]> git.sur5r.net Git - i3/i3/blob - i3bar/src/xcb.c
Fix i3bar when using multiple displays (Thanks brimstone)
[i3/i3] / i3bar / src / xcb.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3bar - an xcb-based status- and ws-bar for i3
5  * © 2010-2011 Axel Wagner and contributors (see also: LICENSE)
6  *
7  * xcb.c: Communicating with X
8  *
9  */
10 #include <xcb/xcb.h>
11 #include <xcb/xproto.h>
12 #include <xcb/xcb_atom.h>
13 #include <xcb/xcb_aux.h>
14
15 #ifdef XCB_COMPAT
16 #include "xcb_compat.h"
17 #endif
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <string.h>
24 #include <i3/ipc.h>
25 #include <ev.h>
26 #include <errno.h>
27 #include <limits.h>
28 #include <err.h>
29
30 #include <X11/Xlib.h>
31 #include <X11/XKBlib.h>
32 #include <X11/extensions/XKB.h>
33
34 #include "common.h"
35 #include "libi3.h"
36
37 /* We save the Atoms in an easy to access array, indexed by an enum */
38 enum {
39     #define ATOM_DO(name) name,
40     #include "xcb_atoms.def"
41     NUM_ATOMS
42 };
43
44 xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
45 xcb_atom_t               atoms[NUM_ATOMS];
46
47 /* Variables, that are the same for all functions at all times */
48 xcb_connection_t *xcb_connection;
49 int              screen;
50 xcb_screen_t     *xcb_screen;
51 xcb_window_t     xcb_root;
52 xcb_font_t       xcb_font;
53
54 /* We need to cache some data to speed up text-width-prediction */
55 xcb_query_font_reply_t *font_info;
56 int                    font_height;
57 xcb_charinfo_t         *font_table;
58
59 /* These are only relevant for XKB, which we only need for grabbing modifiers */
60 Display          *xkb_dpy;
61 int              xkb_event_base;
62 int              mod_pressed = 0;
63
64 /* Because the statusline is the same on all outputs, we have
65  * global buffer to render it on */
66 xcb_gcontext_t   statusline_ctx;
67 xcb_gcontext_t   statusline_clear;
68 xcb_pixmap_t     statusline_pm;
69 uint32_t         statusline_width;
70
71 /* Event-Watchers, to interact with the user */
72 ev_prepare *xcb_prep;
73 ev_check   *xcb_chk;
74 ev_io      *xcb_io;
75 ev_io      *xkb_io;
76
77 /* The parsed colors */
78 struct xcb_colors_t {
79     uint32_t bar_fg;
80     uint32_t bar_bg;
81     uint32_t active_ws_fg;
82     uint32_t active_ws_bg;
83     uint32_t inactive_ws_fg;
84     uint32_t inactive_ws_bg;
85     uint32_t urgent_ws_bg;
86     uint32_t urgent_ws_fg;
87     uint32_t focus_ws_bg;
88     uint32_t focus_ws_fg;
89 };
90 struct xcb_colors_t colors;
91
92 /* We define xcb_request_failed as a macro to include the relevant line-number */
93 #define xcb_request_failed(cookie, err_msg) _xcb_request_failed(cookie, err_msg, __LINE__)
94 int _xcb_request_failed(xcb_void_cookie_t cookie, char *err_msg, int line) {
95     xcb_generic_error_t *err;
96     if ((err = xcb_request_check(xcb_connection, cookie)) != NULL) {
97         fprintf(stderr, "[%s:%d] ERROR: %s. X Error Code: %d\n", __FILE__, line, err_msg, err->error_code);
98         return err->error_code;
99     }
100     return 0;
101 }
102
103 /*
104  * Predicts the length of text based on cached data.
105  * The string has to be encoded in ucs2 and glyph_len has to be the length
106  * of the string (in glyphs).
107  *
108  */
109 uint32_t predict_text_extents(xcb_char2b_t *text, uint32_t length) {
110     /* If we don't have per-character data, return the maximum width */
111     if (font_table == NULL) {
112         return (font_info->max_bounds.character_width * length);
113     }
114
115     uint32_t width = 0;
116     uint32_t i;
117
118     for (i = 0; i < length; i++) {
119         xcb_charinfo_t *info;
120         int row = text[i].byte1;
121         int col = text[i].byte2;
122
123         if (row < font_info->min_byte1 || row > font_info->max_byte1 ||
124             col < font_info->min_char_or_byte2 || col > font_info->max_char_or_byte2) {
125             continue;
126         }
127
128         /* Don't you ask me, how this one works… */
129         info = &font_table[((row - font_info->min_byte1) *
130                             (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
131                            (col - font_info->min_char_or_byte2)];
132
133         if (info->character_width != 0 ||
134             (info->right_side_bearing |
135              info->left_side_bearing |
136              info->ascent |
137              info->descent) != 0) {
138             width += info->character_width;
139         }
140     }
141
142     return width;
143 }
144
145 /*
146  * Draws text given in UCS-2-encoding to a given drawable and position
147  *
148  */
149 void draw_text(xcb_drawable_t drawable, xcb_gcontext_t ctx, int16_t x, int16_t y,
150                xcb_char2b_t *text, uint32_t glyph_count) {
151     int offset = 0;
152     int16_t pos_x = x;
153     int16_t font_ascent = font_info->font_ascent;
154
155     while (glyph_count > 0) {
156         uint8_t chunk_size = MIN(255, glyph_count);
157         uint32_t chunk_width = predict_text_extents(text + offset, chunk_size);
158
159         xcb_image_text_16(xcb_connection,
160                           chunk_size,
161                           drawable,
162                           ctx,
163                           pos_x, y + font_ascent,
164                           text + offset);
165
166         offset += chunk_size;
167         pos_x += chunk_width;
168         glyph_count -= chunk_size;
169     }
170 }
171
172 /*
173  * Redraws the statusline to the buffer
174  *
175  */
176 void refresh_statusline() {
177     int glyph_count;
178
179     if (statusline == NULL) {
180         return;
181     }
182
183     xcb_char2b_t *text = (xcb_char2b_t*) convert_utf8_to_ucs2(statusline, &glyph_count);
184     uint32_t old_statusline_width = statusline_width;
185     statusline_width = predict_text_extents(text, glyph_count);
186     /* If the statusline is bigger than our screen we need to make sure that
187      * the pixmap provides enough space, so re-allocate if the width grew */
188     if (statusline_width > xcb_screen->width_in_pixels &&
189         statusline_width > old_statusline_width)
190         realloc_sl_buffer();
191
192     xcb_rectangle_t rect = { 0, 0, xcb_screen->width_in_pixels, font_height };
193     xcb_poly_fill_rectangle(xcb_connection, statusline_pm, statusline_clear, 1, &rect);
194     draw_text(statusline_pm, statusline_ctx, 0, 0, text, glyph_count);
195
196     FREE(text);
197 }
198
199 /*
200  * Hides all bars (unmaps them)
201  *
202  */
203 void hide_bars() {
204     if (!config.hide_on_modifier) {
205         return;
206     }
207
208     i3_output *walk;
209     SLIST_FOREACH(walk, outputs, slist) {
210         if (!walk->active) {
211             continue;
212         }
213         xcb_unmap_window(xcb_connection, walk->bar);
214     }
215     stop_child();
216 }
217
218 /*
219  * Unhides all bars (maps them)
220  *
221  */
222 void unhide_bars() {
223     if (!config.hide_on_modifier) {
224         return;
225     }
226
227     i3_output           *walk;
228     xcb_void_cookie_t   cookie;
229     uint32_t            mask;
230     uint32_t            values[5];
231
232     cont_child();
233
234     SLIST_FOREACH(walk, outputs, slist) {
235         if (walk->bar == XCB_NONE) {
236             continue;
237         }
238         mask = XCB_CONFIG_WINDOW_X |
239                XCB_CONFIG_WINDOW_Y |
240                XCB_CONFIG_WINDOW_WIDTH |
241                XCB_CONFIG_WINDOW_HEIGHT |
242                XCB_CONFIG_WINDOW_STACK_MODE;
243         values[0] = walk->rect.x;
244         if (config.position == POS_TOP)
245             values[1] = walk->rect.y;
246         else values[1] = walk->rect.y + walk->rect.h - font_height - 6;
247         values[2] = walk->rect.w;
248         values[3] = font_height + 6;
249         values[4] = XCB_STACK_MODE_ABOVE;
250         DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
251         cookie = xcb_configure_window_checked(xcb_connection,
252                                               walk->bar,
253                                               mask,
254                                               values);
255
256         if (xcb_request_failed(cookie, "Could not reconfigure window")) {
257             exit(EXIT_FAILURE);
258         }
259         xcb_map_window(xcb_connection, walk->bar);
260     }
261 }
262
263 /*
264  * Parse the colors into a format that we can use
265  *
266  */
267 void init_colors(const struct xcb_color_strings_t *new_colors) {
268 #define PARSE_COLOR(name, def) \
269     do { \
270         colors.name = get_colorpixel(new_colors->name ? new_colors->name : def); \
271     } while  (0)
272     PARSE_COLOR(bar_fg, "#FFFFFF");
273     PARSE_COLOR(bar_bg, "#000000");
274     PARSE_COLOR(active_ws_fg, "#FFFFFF");
275     PARSE_COLOR(active_ws_bg, "#333333");
276     PARSE_COLOR(inactive_ws_fg, "#888888");
277     PARSE_COLOR(inactive_ws_bg, "#222222");
278     PARSE_COLOR(urgent_ws_fg, "#FFFFFF");
279     PARSE_COLOR(urgent_ws_bg, "#900000");
280     PARSE_COLOR(focus_ws_fg, "#FFFFFF");
281     PARSE_COLOR(focus_ws_bg, "#285577");
282 #undef PARSE_COLOR
283 }
284
285 /*
286  * Handle a button-press-event (i.e. a mouse click on one of our bars).
287  * We determine, whether the click occured on a ws-button or if the scroll-
288  * wheel was used and change the workspace appropriately
289  *
290  */
291 void handle_button(xcb_button_press_event_t *event) {
292     i3_ws *cur_ws;
293
294     /* Determine, which bar was clicked */
295     i3_output *walk;
296     xcb_window_t bar = event->event;
297     SLIST_FOREACH(walk, outputs, slist) {
298         if (walk->bar == bar) {
299             break;
300         }
301     }
302
303     if (walk == NULL) {
304         DLOG("Unknown Bar klicked!\n");
305         return;
306     }
307
308     /* TODO: Move this to extern get_ws_for_output() */
309     TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
310         if (cur_ws->visible) {
311             break;
312         }
313     }
314
315     if (cur_ws == NULL) {
316         DLOG("No Workspace active?\n");
317         return;
318     }
319
320     int32_t x = event->event_x;
321
322     DLOG("Got Button %d\n", event->detail);
323
324     switch (event->detail) {
325         case 1:
326             /* Left Mousbutton. We determine, which button was clicked
327              * and set cur_ws accordingly */
328             TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
329                 DLOG("x = %d\n", x);
330                 if (x < cur_ws->name_width + 10) {
331                     break;
332                 }
333                 x -= cur_ws->name_width + 10;
334             }
335             if (cur_ws == NULL) {
336                 return;
337             }
338             break;
339         case 4:
340             /* Mouse wheel down. We select the next ws */
341             if (cur_ws == TAILQ_FIRST(walk->workspaces)) {
342                 cur_ws = TAILQ_LAST(walk->workspaces, ws_head);
343             } else {
344                 cur_ws = TAILQ_PREV(cur_ws, ws_head, tailq);
345             }
346             break;
347         case 5:
348             /* Mouse wheel up. We select the previos ws */
349             if (cur_ws == TAILQ_LAST(walk->workspaces, ws_head)) {
350                 cur_ws = TAILQ_FIRST(walk->workspaces);
351             } else {
352                 cur_ws = TAILQ_NEXT(cur_ws, tailq);
353             }
354             break;
355     }
356
357     const size_t len = strlen(cur_ws->name) + strlen("workspace \"\"") + 1;
358     char buffer[len];
359     snprintf(buffer, len, "workspace \"%s\"", cur_ws->name);
360     i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
361 }
362
363 /*
364  * Configures the x coordinate of all trayclients. To be called after adding a
365  * new tray client or removing an old one.
366  *
367  */
368 static void configure_trayclients() {
369     trayclient *trayclient;
370     i3_output *output;
371     SLIST_FOREACH(output, outputs, slist) {
372         if (!output->active)
373             continue;
374
375         int clients = 0;
376         TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
377             if (!trayclient->mapped)
378                 continue;
379             clients++;
380
381             DLOG("Configuring tray window %08x to x=%d\n",
382                  trayclient->win, output->rect.w - (clients * (font_height + 2)));
383             uint32_t x = output->rect.w - (clients * (font_height + 2));
384             xcb_configure_window(xcb_connection,
385                                  trayclient->win,
386                                  XCB_CONFIG_WINDOW_X,
387                                  &x);
388         }
389     }
390 }
391
392 /*
393  * Handles ClientMessages (messages sent from another client directly to us).
394  *
395  * At the moment, only the tray window will receive client messages. All
396  * supported client messages currently are _NET_SYSTEM_TRAY_OPCODE.
397  *
398  */
399 static void handle_client_message(xcb_client_message_event_t* event) {
400     if (event->type == atoms[_NET_SYSTEM_TRAY_OPCODE] &&
401         event->format == 32) {
402         DLOG("_NET_SYSTEM_TRAY_OPCODE received\n");
403         /* event->data.data32[0] is the timestamp */
404         uint32_t op = event->data.data32[1];
405         uint32_t mask;
406         uint32_t values[2];
407         if (op == SYSTEM_TRAY_REQUEST_DOCK) {
408             xcb_window_t client = event->data.data32[2];
409
410             /* Listen for PropertyNotify events to get the most recent value of
411              * the XEMBED_MAPPED atom, also listen for UnmapNotify events */
412             mask = XCB_CW_EVENT_MASK;
413             values[0] = XCB_EVENT_MASK_PROPERTY_CHANGE |
414                         XCB_EVENT_MASK_STRUCTURE_NOTIFY;
415             xcb_change_window_attributes(xcb_connection,
416                                          client,
417                                          mask,
418                                          values);
419
420             /* Request the _XEMBED_INFO property. The XEMBED specification
421              * (which is referred by the tray specification) says this *has* to
422              * be set, but VLC does not set it… */
423             bool map_it = true;
424             int xe_version = 1;
425             xcb_get_property_cookie_t xembedc;
426             xembedc = xcb_get_property_unchecked(xcb_connection,
427                                                  0,
428                                                  client,
429                                                  atoms[_XEMBED_INFO],
430                                                  XCB_GET_PROPERTY_TYPE_ANY,
431                                                  0,
432                                                  2 * 32);
433
434             xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
435                                                                        xembedc,
436                                                                        NULL);
437             if (xembedr != NULL && xembedr->length != 0) {
438                 DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
439                 uint32_t *xembed = xcb_get_property_value(xembedr);
440                 DLOG("xembed version = %d\n", xembed[0]);
441                 DLOG("xembed flags = %d\n", xembed[1]);
442                 map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
443                 xe_version = xembed[0];
444                 if (xe_version > 1)
445                     xe_version = 1;
446                 free(xembedr);
447             } else {
448                 ELOG("Window %08x violates the XEMBED protocol, _XEMBED_INFO not set\n", client);
449             }
450
451             DLOG("X window %08x requested docking\n", client);
452             i3_output *walk, *output = NULL;
453             SLIST_FOREACH(walk, outputs, slist) {
454                 if (!walk->active)
455                     continue;
456                 if (config.tray_output &&
457                     strcasecmp(walk->name, config.tray_output) != 0)
458                     continue;
459                 DLOG("using output %s\n", walk->name);
460                 output = walk;
461             }
462             if (output == NULL) {
463                 ELOG("No output found\n");
464                 return;
465             }
466             xcb_reparent_window(xcb_connection,
467                                 client,
468                                 output->bar,
469                                 output->rect.w - font_height - 2,
470                                 2);
471             /* We reconfigure the window to use a reasonable size. The systray
472              * specification explicitly says:
473              *   Tray icons may be assigned any size by the system tray, and
474              *   should do their best to cope with any size effectively
475              */
476             mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
477             values[0] = font_height;
478             values[1] = font_height;
479             xcb_configure_window(xcb_connection,
480                                  client,
481                                  mask,
482                                  values);
483
484             /* send the XEMBED_EMBEDDED_NOTIFY message */
485             void *event = scalloc(32);
486             xcb_client_message_event_t *ev = event;
487             ev->response_type = XCB_CLIENT_MESSAGE;
488             ev->window = client;
489             ev->type = atoms[_XEMBED];
490             ev->format = 32;
491             ev->data.data32[0] = XCB_CURRENT_TIME;
492             ev->data.data32[1] = atoms[XEMBED_EMBEDDED_NOTIFY];
493             ev->data.data32[2] = output->bar;
494             ev->data.data32[3] = xe_version;
495             xcb_send_event(xcb_connection,
496                            0,
497                            client,
498                            XCB_EVENT_MASK_NO_EVENT,
499                            (char*)ev);
500             free(event);
501
502             /* Put the client inside the save set. Upon termination (whether
503              * killed or normal exit does not matter) of i3bar, these clients
504              * will be correctly reparented to their most closest living
505              * ancestor. Without this, tray icons might die when i3bar
506              * exits/crashes. */
507             xcb_change_save_set(xcb_connection, XCB_SET_MODE_INSERT, client);
508
509             if (map_it) {
510                 DLOG("Mapping dock client\n");
511                 xcb_map_window(xcb_connection, client);
512             } else {
513                 DLOG("Not mapping dock client yet\n");
514             }
515             trayclient *tc = smalloc(sizeof(trayclient));
516             tc->win = client;
517             tc->mapped = map_it;
518             tc->xe_version = xe_version;
519             TAILQ_INSERT_TAIL(output->trayclients, tc, tailq);
520
521             /* Trigger an update to copy the statusline text to the appropriate
522              * position */
523             configure_trayclients();
524             draw_bars();
525         }
526     }
527 }
528
529 /*
530  * Handles UnmapNotify events. These events happen when a tray window unmaps
531  * itself. We then update our data structure
532  *
533  */
534 static void handle_unmap_notify(xcb_unmap_notify_event_t* event) {
535     DLOG("UnmapNotify for window = %08x, event = %08x\n", event->window, event->event);
536
537     i3_output *walk;
538     SLIST_FOREACH(walk, outputs, slist) {
539         if (!walk->active)
540             continue;
541         DLOG("checking output %s\n", walk->name);
542         trayclient *trayclient;
543         TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
544             if (trayclient->win != event->window)
545                 continue;
546
547             DLOG("Removing tray client with window ID %08x\n", event->window);
548             TAILQ_REMOVE(walk->trayclients, trayclient, tailq);
549
550             /* Trigger an update, we now have more space for the statusline */
551             configure_trayclients();
552             draw_bars();
553             return;
554         }
555     }
556 }
557
558 /*
559  * Handle PropertyNotify messages. Currently only the _XEMBED_INFO property is
560  * handled, which tells us whether a dock client should be mapped or unmapped.
561  *
562  */
563 static void handle_property_notify(xcb_property_notify_event_t *event) {
564     DLOG("PropertyNotify\n");
565     if (event->atom == atoms[_XEMBED_INFO] &&
566         event->state == XCB_PROPERTY_NEW_VALUE) {
567         DLOG("xembed_info updated\n");
568         trayclient *trayclient = NULL, *walk;
569         i3_output *o_walk;
570         SLIST_FOREACH(o_walk, outputs, slist) {
571             if (!o_walk->active)
572                 continue;
573
574             TAILQ_FOREACH(walk, o_walk->trayclients, tailq) {
575                 if (walk->win != event->window)
576                     continue;
577                 trayclient = walk;
578                 break;
579             }
580
581             if (trayclient)
582                 break;
583         }
584         if (!trayclient) {
585             ELOG("PropertyNotify received for unknown window %08x\n",
586                  event->window);
587             return;
588         }
589         xcb_get_property_cookie_t xembedc;
590         xembedc = xcb_get_property_unchecked(xcb_connection,
591                                              0,
592                                              trayclient->win,
593                                              atoms[_XEMBED_INFO],
594                                              XCB_GET_PROPERTY_TYPE_ANY,
595                                              0,
596                                              2 * 32);
597
598         xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
599                                                                    xembedc,
600                                                                    NULL);
601         if (xembedr == NULL || xembedr->length == 0) {
602             DLOG("xembed_info unset\n");
603             return;
604         }
605
606         DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
607         uint32_t *xembed = xcb_get_property_value(xembedr);
608         DLOG("xembed version = %d\n", xembed[0]);
609         DLOG("xembed flags = %d\n", xembed[1]);
610         bool map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
611         DLOG("map-state now %d\n", map_it);
612         if (trayclient->mapped && !map_it) {
613             /* need to unmap the window */
614             xcb_unmap_window(xcb_connection, trayclient->win);
615             trayclient->mapped = map_it;
616             configure_trayclients();
617             draw_bars();
618         } else if (!trayclient->mapped && map_it) {
619             /* need to map the window */
620             xcb_map_window(xcb_connection, trayclient->win);
621             trayclient->mapped = map_it;
622             configure_trayclients();
623             draw_bars();
624         }
625         free(xembedr);
626     }
627 }
628
629 /*
630  * Handle ConfigureRequests by denying them and sending the client a
631  * ConfigureNotify with its actual size.
632  *
633  */
634 static void handle_configure_request(xcb_configure_request_event_t *event) {
635     DLOG("ConfigureRequest for window = %08x\n", event->window);
636
637     trayclient *trayclient;
638     i3_output *output;
639     SLIST_FOREACH(output, outputs, slist) {
640         if (!output->active)
641             continue;
642
643         int clients = 0;
644         TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
645             if (!trayclient->mapped)
646                 continue;
647             clients++;
648
649             if (trayclient->win != event->window)
650                 continue;
651
652             xcb_rectangle_t rect;
653             rect.x = output->rect.w - (clients * (font_height + 2));
654             rect.y = 2;
655             rect.width = font_height;
656             rect.height = font_height;
657
658             DLOG("This is a tray window. x = %d\n", rect.x);
659             fake_configure_notify(xcb_connection, rect, event->window, 0);
660             return;
661         }
662     }
663
664     DLOG("WARNING: Could not find corresponding tray window.\n");
665 }
666
667 /*
668  * This function is called immediately before the main loop locks. We flush xcb
669  * then (and only then)
670  *
671  */
672 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revents) {
673     xcb_flush(xcb_connection);
674 }
675
676 /*
677  * This function is called immediately after the main loop locks, so when one
678  * of the watchers registered an event.
679  * We check whether an X-Event arrived and handle it.
680  *
681  */
682 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
683     xcb_generic_event_t *event;
684
685     if (xcb_connection_has_error(xcb_connection)) {
686         ELOG("X11 connection was closed unexpectedly - maybe your X server terminated / crashed?\n");
687         exit(1);
688     }
689
690     while ((event = xcb_poll_for_event(xcb_connection)) != NULL) {
691         switch (event->response_type & ~0x80) {
692             case XCB_EXPOSE:
693                 /* Expose-events happen, when the window needs to be redrawn */
694                 redraw_bars();
695                 break;
696             case XCB_BUTTON_PRESS:
697                 /* Button-press-events are mouse-buttons clicked on one of our bars */
698                 handle_button((xcb_button_press_event_t*) event);
699                 break;
700             case XCB_CLIENT_MESSAGE:
701                 /* Client messages are used for client-to-client communication, for
702                  * example system tray widgets talk to us directly via client messages. */
703                 handle_client_message((xcb_client_message_event_t*) event);
704                 break;
705             case XCB_UNMAP_NOTIFY:
706             case XCB_DESTROY_NOTIFY:
707                 /* UnmapNotifies are received when a tray window unmaps itself */
708                 handle_unmap_notify((xcb_unmap_notify_event_t*) event);
709                 break;
710             case XCB_PROPERTY_NOTIFY:
711                 /* PropertyNotify */
712                 handle_property_notify((xcb_property_notify_event_t*) event);
713                 break;
714             case XCB_CONFIGURE_REQUEST:
715                 /* ConfigureRequest, sent by a tray child */
716                 handle_configure_request((xcb_configure_request_event_t*) event);
717                 break;
718         }
719         free(event);
720     }
721 }
722
723 /*
724  * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
725  * are triggered
726  *
727  */
728 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
729 }
730
731 /*
732  * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
733  *
734  */
735 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
736     XkbEvent ev;
737     int modstate = 0;
738
739     DLOG("Got XKB-Event!\n");
740
741     while (XPending(xkb_dpy)) {
742         XNextEvent(xkb_dpy, (XEvent*)&ev);
743
744         if (ev.type != xkb_event_base) {
745             ELOG("No Xkb-Event!\n");
746             continue;
747         }
748
749         if (ev.any.xkb_type != XkbStateNotify) {
750             ELOG("No State Notify!\n");
751             continue;
752         }
753
754         unsigned int mods = ev.state.mods;
755         modstate = mods & Mod4Mask;
756     }
757
758     if (modstate != mod_pressed) {
759         if (modstate == 0) {
760             DLOG("Mod4 got released!\n");
761             hide_bars();
762         } else {
763             DLOG("Mod4 got pressed!\n");
764             unhide_bars();
765         }
766         mod_pressed = modstate;
767     }
768 }
769
770 /*
771  * Early initialization of the connection to X11: Everything which does not
772  * depend on 'config'.
773  *
774  */
775 char *init_xcb_early() {
776     /* FIXME: xcb_connect leaks Memory */
777     xcb_connection = xcb_connect(NULL, &screen);
778     if (xcb_connection_has_error(xcb_connection)) {
779         ELOG("Cannot open display\n");
780         exit(EXIT_FAILURE);
781     }
782     DLOG("Connected to xcb\n");
783
784     /* We have to request the atoms we need */
785     #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
786     #include "xcb_atoms.def"
787
788     xcb_screen = xcb_aux_get_screen(xcb_connection, screen);
789     xcb_root = xcb_screen->root;
790
791     /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
792      * this way, we can choose to crop it */
793     uint32_t mask = XCB_GC_FOREGROUND;
794     uint32_t vals[] = { colors.bar_bg, colors.bar_bg };
795
796     statusline_clear = xcb_generate_id(xcb_connection);
797     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
798                                                                statusline_clear,
799                                                                xcb_root,
800                                                                mask,
801                                                                vals);
802
803     mask |= XCB_GC_BACKGROUND;
804     vals[0] = colors.bar_fg;
805     statusline_ctx = xcb_generate_id(xcb_connection);
806     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
807                                                             statusline_ctx,
808                                                             xcb_root,
809                                                             mask,
810                                                             vals);
811
812     statusline_pm = xcb_generate_id(xcb_connection);
813     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
814                                                                xcb_screen->root_depth,
815                                                                statusline_pm,
816                                                                xcb_root,
817                                                                xcb_screen->width_in_pixels,
818                                                                xcb_screen->height_in_pixels);
819
820
821     /* The various Watchers to communicate with xcb */
822     xcb_io = smalloc(sizeof(ev_io));
823     xcb_prep = smalloc(sizeof(ev_prepare));
824     xcb_chk = smalloc(sizeof(ev_check));
825
826     ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
827     ev_prepare_init(xcb_prep, &xcb_prep_cb);
828     ev_check_init(xcb_chk, &xcb_chk_cb);
829
830     ev_io_start(main_loop, xcb_io);
831     ev_prepare_start(main_loop, xcb_prep);
832     ev_check_start(main_loop, xcb_chk);
833
834     /* Now we get the atoms and save them in a nice data structure */
835     get_atoms();
836
837     xcb_get_property_cookie_t path_cookie;
838     path_cookie = xcb_get_property_unchecked(xcb_connection,
839                                    0,
840                                    xcb_root,
841                                    atoms[I3_SOCKET_PATH],
842                                    XCB_GET_PROPERTY_TYPE_ANY,
843                                    0, PATH_MAX);
844
845     /* We check, if i3 set its socket-path */
846     xcb_get_property_reply_t *path_reply = xcb_get_property_reply(xcb_connection,
847                                                                   path_cookie,
848                                                                   NULL);
849     char *path = NULL;
850     if (path_reply) {
851         int len = xcb_get_property_value_length(path_reply);
852         if (len != 0) {
853             path = strndup(xcb_get_property_value(path_reply), len);
854         }
855     }
856
857
858     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
859         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
860         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
861         exit(EXIT_FAILURE);
862     }
863
864     return path;
865 }
866
867 /*
868  * Initialization which depends on 'config' being usable. Called after the
869  * configuration has arrived.
870  *
871  */
872 void init_xcb_late(char *fontname) {
873     if (fontname == NULL) {
874         /* XXX: font fallback to 'misc' like i3 does it would be good. */
875         fontname = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
876     }
877
878     /* We load and allocate the font */
879     xcb_font = xcb_generate_id(xcb_connection);
880     xcb_void_cookie_t open_font_cookie;
881     open_font_cookie = xcb_open_font_checked(xcb_connection,
882                                              xcb_font,
883                                              strlen(fontname),
884                                              fontname);
885
886     /* We need to save info about the font, because we need the font's height and
887      * information about the width of characters */
888     xcb_query_font_cookie_t query_font_cookie;
889     query_font_cookie = xcb_query_font(xcb_connection,
890                                        xcb_font);
891
892     xcb_change_gc(xcb_connection,
893                   statusline_ctx,
894                   XCB_GC_FONT,
895                   (uint32_t[]){ xcb_font });
896
897     xcb_flush(xcb_connection);
898
899     /* To grab modifiers without blocking other applications from receiving key-events
900      * involving that modifier, we sadly have to use xkb which is not yet fully supported
901      * in xcb */
902     if (config.hide_on_modifier) {
903         int xkb_major, xkb_minor, xkb_errbase, xkb_err;
904         xkb_major = XkbMajorVersion;
905         xkb_minor = XkbMinorVersion;
906
907         xkb_dpy = XkbOpenDisplay(NULL,
908                                  &xkb_event_base,
909                                  &xkb_errbase,
910                                  &xkb_major,
911                                  &xkb_minor,
912                                  &xkb_err);
913
914         if (xkb_dpy == NULL) {
915             ELOG("No XKB!\n");
916             exit(EXIT_FAILURE);
917         }
918
919         if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
920             ELOG("Could not set FD_CLOEXEC on xkbdpy: %s\n", strerror(errno));
921             exit(EXIT_FAILURE);
922         }
923
924         int i1;
925         if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
926             ELOG("XKB not supported by X-server!\n");
927             exit(EXIT_FAILURE);
928         }
929
930         if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
931             ELOG("Could not grab Key!\n");
932             exit(EXIT_FAILURE);
933         }
934
935         xkb_io = smalloc(sizeof(ev_io));
936         ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
937         ev_io_start(main_loop, xkb_io);
938         XFlush(xkb_dpy);
939     }
940
941     /* Now we save the font-infos */
942     font_info = xcb_query_font_reply(xcb_connection,
943                                      query_font_cookie,
944                                      NULL);
945
946     if (xcb_request_failed(open_font_cookie, "Could not open font")) {
947         exit(EXIT_FAILURE);
948     }
949
950     font_height = font_info->font_ascent + font_info->font_descent;
951
952     if (xcb_query_font_char_infos_length(font_info) == 0) {
953         font_table = NULL;
954     } else {
955         font_table = xcb_query_font_char_infos(font_info);
956     }
957
958     DLOG("Calculated Font-height: %d\n", font_height);
959 }
960
961 /*
962  * Initializes tray support by requesting the appropriate _NET_SYSTEM_TRAY atom
963  * for the X11 display we are running on, then acquiring the selection for this
964  * atom. Afterwards, tray clients will send ClientMessages to our window.
965  *
966  */
967 void init_tray() {
968     DLOG("Initializing system tray functionality\n");
969     /* request the tray manager atom for the X11 display we are running on */
970     char atomname[strlen("_NET_SYSTEM_TRAY_S") + 11];
971     snprintf(atomname, strlen("_NET_SYSTEM_TRAY_S") + 11, "_NET_SYSTEM_TRAY_S%d", screen);
972     xcb_intern_atom_cookie_t tray_cookie;
973     xcb_intern_atom_reply_t *tray_reply;
974     tray_cookie = xcb_intern_atom(xcb_connection, 0, strlen(atomname), atomname);
975
976     /* tray support: we need a window to own the selection */
977     xcb_window_t selwin = xcb_generate_id(xcb_connection);
978     uint32_t selmask = XCB_CW_OVERRIDE_REDIRECT;
979     uint32_t selval[] = { 1 };
980     xcb_create_window(xcb_connection,
981                       xcb_screen->root_depth,
982                       selwin,
983                       xcb_root,
984                       -1, -1,
985                       1, 1,
986                       1,
987                       XCB_WINDOW_CLASS_INPUT_OUTPUT,
988                       xcb_screen->root_visual,
989                       selmask,
990                       selval);
991
992     uint32_t orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
993     /* set the atoms */
994     xcb_change_property(xcb_connection,
995                         XCB_PROP_MODE_REPLACE,
996                         selwin,
997                         atoms[_NET_SYSTEM_TRAY_ORIENTATION],
998                         XCB_ATOM_CARDINAL,
999                         32,
1000                         1,
1001                         &orientation);
1002
1003     if (!(tray_reply = xcb_intern_atom_reply(xcb_connection, tray_cookie, NULL))) {
1004         ELOG("Could not get atom %s\n", atomname);
1005         exit(EXIT_FAILURE);
1006     }
1007
1008     xcb_set_selection_owner(xcb_connection,
1009                             selwin,
1010                             tray_reply->atom,
1011                             XCB_CURRENT_TIME);
1012
1013     /* Verify that we have the selection */
1014     xcb_get_selection_owner_cookie_t selcookie;
1015     xcb_get_selection_owner_reply_t *selreply;
1016
1017     selcookie = xcb_get_selection_owner(xcb_connection, tray_reply->atom);
1018     if (!(selreply = xcb_get_selection_owner_reply(xcb_connection, selcookie, NULL))) {
1019         ELOG("Could not get selection owner for %s\n", atomname);
1020         exit(EXIT_FAILURE);
1021     }
1022
1023     if (selreply->owner != selwin) {
1024         ELOG("Could not set the %s selection. " \
1025              "Maybe another tray is already running?\n", atomname);
1026         /* NOTE that this error is not fatal. We just can’t provide tray
1027          * functionality */
1028         free(selreply);
1029         return;
1030     }
1031
1032     /* Inform clients waiting for a new _NET_SYSTEM_TRAY that we are here */
1033     void *event = scalloc(32);
1034     xcb_client_message_event_t *ev = event;
1035     ev->response_type = XCB_CLIENT_MESSAGE;
1036     ev->window = xcb_root;
1037     ev->type = atoms[MANAGER];
1038     ev->format = 32;
1039     ev->data.data32[0] = XCB_CURRENT_TIME;
1040     ev->data.data32[1] = tray_reply->atom;
1041     ev->data.data32[2] = selwin;
1042     xcb_send_event(xcb_connection,
1043                    0,
1044                    xcb_root,
1045                    XCB_EVENT_MASK_STRUCTURE_NOTIFY,
1046                    (char*)ev);
1047     free(event);
1048     free(tray_reply);
1049 }
1050
1051 /*
1052  * Cleanup the xcb-stuff.
1053  * Called once, before the program terminates.
1054  *
1055  */
1056 void clean_xcb() {
1057     i3_output *o_walk;
1058     trayclient *trayclient;
1059     free_workspaces();
1060     SLIST_FOREACH(o_walk, outputs, slist) {
1061         TAILQ_FOREACH(trayclient, o_walk->trayclients, tailq) {
1062             /* Unmap, then reparent (to root) the tray client windows */
1063             xcb_unmap_window(xcb_connection, trayclient->win);
1064             xcb_reparent_window(xcb_connection,
1065                                 trayclient->win,
1066                                 xcb_root,
1067                                 0,
1068                                 0);
1069         }
1070         destroy_window(o_walk);
1071         FREE(o_walk->trayclients);
1072         FREE(o_walk->workspaces);
1073         FREE(o_walk->name);
1074     }
1075     FREE_SLIST(outputs, i3_output);
1076     FREE(outputs);
1077
1078     xcb_flush(xcb_connection);
1079     xcb_disconnect(xcb_connection);
1080
1081     ev_check_stop(main_loop, xcb_chk);
1082     ev_prepare_stop(main_loop, xcb_prep);
1083     ev_io_stop(main_loop, xcb_io);
1084
1085     FREE(xcb_chk);
1086     FREE(xcb_prep);
1087     FREE(xcb_io);
1088     FREE(font_info);
1089 }
1090
1091 /*
1092  * Get the earlier requested atoms and save them in the prepared data structure
1093  *
1094  */
1095 void get_atoms() {
1096     xcb_intern_atom_reply_t *reply;
1097     #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
1098         if (reply == NULL) { \
1099             ELOG("Could not get atom %s\n", #name); \
1100             exit(EXIT_FAILURE); \
1101         } \
1102         atoms[name] = reply->atom; \
1103         free(reply);
1104
1105     #include "xcb_atoms.def"
1106     DLOG("Got Atoms\n");
1107 }
1108
1109 /*
1110  * Destroy the bar of the specified output
1111  *
1112  */
1113 void destroy_window(i3_output *output) {
1114     if (output == NULL) {
1115         return;
1116     }
1117     if (output->bar == XCB_NONE) {
1118         return;
1119     }
1120     xcb_destroy_window(xcb_connection, output->bar);
1121     output->bar = XCB_NONE;
1122 }
1123
1124 /*
1125  * Reallocate the statusline-buffer
1126  *
1127  */
1128 void realloc_sl_buffer() {
1129     DLOG("Re-allocating statusline-buffer, statusline_width = %d, xcb_screen->width_in_pixels = %d\n",
1130          statusline_width, xcb_screen->width_in_pixels);
1131     xcb_free_pixmap(xcb_connection, statusline_pm);
1132     statusline_pm = xcb_generate_id(xcb_connection);
1133     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1134                                                                xcb_screen->root_depth,
1135                                                                statusline_pm,
1136                                                                xcb_root,
1137                                                                MAX(xcb_screen->width_in_pixels, statusline_width),
1138                                                                xcb_screen->height_in_pixels);
1139
1140     uint32_t mask = XCB_GC_FOREGROUND;
1141     uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
1142     xcb_free_gc(xcb_connection, statusline_clear);
1143     statusline_clear = xcb_generate_id(xcb_connection);
1144     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1145                                                                statusline_clear,
1146                                                                xcb_root,
1147                                                                mask,
1148                                                                vals);
1149
1150     mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
1151     vals[0] = colors.bar_fg;
1152     statusline_ctx = xcb_generate_id(xcb_connection);
1153     xcb_free_gc(xcb_connection, statusline_ctx);
1154     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1155                                                             statusline_ctx,
1156                                                             xcb_root,
1157                                                             mask,
1158                                                             vals);
1159
1160     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
1161         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
1162         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
1163         exit(EXIT_FAILURE);
1164     }
1165
1166 }
1167
1168 /*
1169  * Reconfigure all bars and create new bars for recently activated outputs
1170  *
1171  */
1172 void reconfig_windows() {
1173     uint32_t mask;
1174     uint32_t values[5];
1175     static bool tray_configured = false;
1176
1177     i3_output *walk;
1178     SLIST_FOREACH(walk, outputs, slist) {
1179         if (!walk->active) {
1180             /* If an output is not active, we destroy its bar */
1181             /* FIXME: Maybe we rather want to unmap? */
1182             DLOG("Destroying window for output %s\n", walk->name);
1183             destroy_window(walk);
1184             continue;
1185         }
1186         if (walk->bar == XCB_NONE) {
1187             DLOG("Creating Window for output %s\n", walk->name);
1188
1189             walk->bar = xcb_generate_id(xcb_connection);
1190             walk->buffer = xcb_generate_id(xcb_connection);
1191             mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
1192             /* Black background */
1193             values[0] = colors.bar_bg;
1194             /* If hide_on_modifier is set, i3 is not supposed to manage our bar-windows */
1195             values[1] = config.hide_on_modifier;
1196             /* We enable the following EventMask fields:
1197              * EXPOSURE, to get expose events (we have to re-draw then)
1198              * SUBSTRUCTURE_REDIRECT, to get ConfigureRequests when the tray
1199              *                        child windows use ConfigureWindow
1200              * BUTTON_PRESS, to handle clicks on the workspace buttons
1201              * */
1202             values[2] = XCB_EVENT_MASK_EXPOSURE |
1203                         XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;
1204             if (!config.disable_ws) {
1205                 values[2] |= XCB_EVENT_MASK_BUTTON_PRESS;
1206             }
1207             xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
1208                                                                      xcb_screen->root_depth,
1209                                                                      walk->bar,
1210                                                                      xcb_root,
1211                                                                      walk->rect.x, walk->rect.y + walk->rect.h - font_height - 6,
1212                                                                      walk->rect.w, font_height + 6,
1213                                                                      1,
1214                                                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,
1215                                                                      xcb_screen->root_visual,
1216                                                                      mask,
1217                                                                      values);
1218
1219             /* The double-buffer we use to render stuff off-screen */
1220             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1221                                                                     xcb_screen->root_depth,
1222                                                                     walk->buffer,
1223                                                                     walk->bar,
1224                                                                     walk->rect.w,
1225                                                                     walk->rect.h);
1226
1227             /* Set the WM_CLASS and WM_NAME (we don't need UTF-8) atoms */
1228             xcb_void_cookie_t class_cookie;
1229             class_cookie = xcb_change_property(xcb_connection,
1230                                                XCB_PROP_MODE_REPLACE,
1231                                                walk->bar,
1232                                                XCB_ATOM_WM_CLASS,
1233                                                XCB_ATOM_STRING,
1234                                                8,
1235                                                (strlen("i3bar") + 1) * 2,
1236                                                "i3bar\0i3bar\0");
1237
1238             char *name;
1239             if (asprintf(&name, "i3bar for output %s", walk->name) == -1)
1240                 err(EXIT_FAILURE, "asprintf()");
1241             xcb_void_cookie_t name_cookie;
1242             name_cookie = xcb_change_property(xcb_connection,
1243                                               XCB_PROP_MODE_REPLACE,
1244                                               walk->bar,
1245                                               XCB_ATOM_WM_NAME,
1246                                               XCB_ATOM_STRING,
1247                                               8,
1248                                               strlen(name),
1249                                               name);
1250             free(name);
1251
1252             /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
1253              * this one */
1254             xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
1255                                                                 XCB_PROP_MODE_REPLACE,
1256                                                                 walk->bar,
1257                                                                 atoms[_NET_WM_WINDOW_TYPE],
1258                                                                 XCB_ATOM_ATOM,
1259                                                                 32,
1260                                                                 1,
1261                                                                 (unsigned char*) &atoms[_NET_WM_WINDOW_TYPE_DOCK]);
1262
1263             /* We need to tell i3, where to reserve space for i3bar */
1264             /* left, right, top, bottom, left_start_y, left_end_y,
1265              * right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x,
1266              * bottom_end_x */
1267             /* A local struct to save the strut_partial property */
1268             struct {
1269                 uint32_t left;
1270                 uint32_t right;
1271                 uint32_t top;
1272                 uint32_t bottom;
1273                 uint32_t left_start_y;
1274                 uint32_t left_end_y;
1275                 uint32_t right_start_y;
1276                 uint32_t right_end_y;
1277                 uint32_t top_start_x;
1278                 uint32_t top_end_x;
1279                 uint32_t bottom_start_x;
1280                 uint32_t bottom_end_x;
1281             } __attribute__((__packed__)) strut_partial = {0,};
1282             switch (config.position) {
1283                 case POS_NONE:
1284                     break;
1285                 case POS_TOP:
1286                     strut_partial.top = font_height + 6;
1287                     strut_partial.top_start_x = walk->rect.x;
1288                     strut_partial.top_end_x = walk->rect.x + walk->rect.w;
1289                     break;
1290                 case POS_BOT:
1291                     strut_partial.bottom = font_height + 6;
1292                     strut_partial.bottom_start_x = walk->rect.x;
1293                     strut_partial.bottom_end_x = walk->rect.x + walk->rect.w;
1294                     break;
1295             }
1296             xcb_void_cookie_t strut_cookie = xcb_change_property(xcb_connection,
1297                                                                  XCB_PROP_MODE_REPLACE,
1298                                                                  walk->bar,
1299                                                                  atoms[_NET_WM_STRUT_PARTIAL],
1300                                                                  XCB_ATOM_CARDINAL,
1301                                                                  32,
1302                                                                  12,
1303                                                                  &strut_partial);
1304
1305             /* We also want a graphics-context for the bars (it defines the properties
1306              * with which we draw to them) */
1307             walk->bargc = xcb_generate_id(xcb_connection);
1308             mask = XCB_GC_FONT;
1309             values[0] = xcb_font;
1310             xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
1311                                                                 walk->bargc,
1312                                                                 walk->bar,
1313                                                                 mask,
1314                                                                 values);
1315
1316             /* We finally map the bar (display it on screen), unless the modifier-switch is on */
1317             xcb_void_cookie_t map_cookie;
1318             if (!config.hide_on_modifier) {
1319                 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
1320             }
1321
1322             if (xcb_request_failed(win_cookie,   "Could not create window") ||
1323                 xcb_request_failed(pm_cookie,    "Could not create pixmap") ||
1324                 xcb_request_failed(dock_cookie,  "Could not set dock mode") ||
1325                 xcb_request_failed(class_cookie, "Could not set WM_CLASS")  ||
1326                 xcb_request_failed(name_cookie,  "Could not set WM_NAME")   ||
1327                 xcb_request_failed(strut_cookie, "Could not set strut")     ||
1328                 xcb_request_failed(gc_cookie,    "Could not create graphical context") ||
1329                 (!config.hide_on_modifier && xcb_request_failed(map_cookie, "Could not map window"))) {
1330                 exit(EXIT_FAILURE);
1331             }
1332
1333             if (!tray_configured &&
1334                 (!config.tray_output ||
1335                  strcasecmp("none", config.tray_output) != 0)) {
1336                 init_tray();
1337                 tray_configured = true;
1338             }
1339         } else {
1340             /* We already have a bar, so we just reconfigure it */
1341             mask = XCB_CONFIG_WINDOW_X |
1342                    XCB_CONFIG_WINDOW_Y |
1343                    XCB_CONFIG_WINDOW_WIDTH |
1344                    XCB_CONFIG_WINDOW_HEIGHT |
1345                    XCB_CONFIG_WINDOW_STACK_MODE;
1346             values[0] = walk->rect.x;
1347             values[1] = walk->rect.y + walk->rect.h - font_height - 6;
1348             values[2] = walk->rect.w;
1349             values[3] = font_height + 6;
1350             values[4] = XCB_STACK_MODE_ABOVE;
1351
1352             DLOG("Destroying buffer for output %s", walk->name);
1353             xcb_free_pixmap(xcb_connection, walk->buffer);
1354
1355             DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
1356             xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
1357                                                                         walk->bar,
1358                                                                         mask,
1359                                                                         values);
1360
1361             DLOG("Recreating buffer for output %s", walk->name);
1362             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1363                                                                     xcb_screen->root_depth,
1364                                                                     walk->buffer,
1365                                                                     walk->bar,
1366                                                                     walk->rect.w,
1367                                                                     walk->rect.h);
1368
1369             if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
1370                 exit(EXIT_FAILURE);
1371             }
1372             if (xcb_request_failed(pm_cookie,  "Could not create pixmap")) {
1373                 exit(EXIT_FAILURE);
1374             }
1375         }
1376     }
1377 }
1378
1379 /*
1380  * Render the bars, with buttons and statusline
1381  *
1382  */
1383 void draw_bars() {
1384     DLOG("Drawing Bars...\n");
1385     int i = 0;
1386
1387     refresh_statusline();
1388
1389     i3_output *outputs_walk;
1390     SLIST_FOREACH(outputs_walk, outputs, slist) {
1391         if (!outputs_walk->active) {
1392             DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
1393             continue;
1394         }
1395         if (outputs_walk->bar == XCB_NONE) {
1396             /* Oh shit, an active output without an own bar. Create it now! */
1397             reconfig_windows();
1398         }
1399         /* First things first: clear the backbuffer */
1400         uint32_t color = colors.bar_bg;
1401         xcb_change_gc(xcb_connection,
1402                       outputs_walk->bargc,
1403                       XCB_GC_FOREGROUND,
1404                       &color);
1405         xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font_height + 6 };
1406         xcb_poly_fill_rectangle(xcb_connection,
1407                                 outputs_walk->buffer,
1408                                 outputs_walk->bargc,
1409                                 1,
1410                                 &rect);
1411
1412         if (statusline != NULL) {
1413             DLOG("Printing statusline!\n");
1414
1415             /* Luckily we already prepared a seperate pixmap containing the rendered
1416              * statusline, we just have to copy the relevant parts to the relevant
1417              * position */
1418             trayclient *trayclient;
1419             int traypx = 0;
1420             TAILQ_FOREACH(trayclient, outputs_walk->trayclients, tailq) {
1421                 if (!trayclient->mapped)
1422                     continue;
1423                 /* We assume the tray icons are quadratic (we use the font
1424                  * *height* as *width* of the icons) because we configured them
1425                  * like this. */
1426                 traypx += font_height + 2;
1427             }
1428             /* Add 2px of padding if there are any tray icons */
1429             if (traypx > 0)
1430                 traypx += 2;
1431             xcb_copy_area(xcb_connection,
1432                           statusline_pm,
1433                           outputs_walk->buffer,
1434                           outputs_walk->bargc,
1435                           MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
1436                           MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - traypx - 4)), 3,
1437                           MIN(outputs_walk->rect.w - traypx - 4, statusline_width), font_height);
1438         }
1439
1440         if (config.disable_ws) {
1441             continue;
1442         }
1443
1444         i3_ws *ws_walk;
1445         TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
1446             DLOG("Drawing Button for WS %s at x = %d\n", ws_walk->name, i);
1447             uint32_t fg_color = colors.inactive_ws_fg;
1448             uint32_t bg_color = colors.inactive_ws_bg;
1449             if (ws_walk->visible) {
1450                 if (!ws_walk->focused) {
1451                     fg_color = colors.active_ws_fg;
1452                     bg_color = colors.active_ws_bg;
1453                 } else {
1454                     fg_color = colors.focus_ws_fg;
1455                     bg_color = colors.focus_ws_bg;
1456                 }
1457             }
1458             if (ws_walk->urgent) {
1459                 DLOG("WS %s is urgent!\n", ws_walk->name);
1460                 fg_color = colors.urgent_ws_fg;
1461                 bg_color = colors.urgent_ws_bg;
1462                 /* The urgent-hint should get noticed, so we unhide the bars shortly */
1463                 unhide_bars();
1464             }
1465             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
1466             uint32_t vals[] = { bg_color, bg_color };
1467             xcb_change_gc(xcb_connection,
1468                           outputs_walk->bargc,
1469                           mask,
1470                           vals);
1471             xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font_height + 4 };
1472             xcb_poly_fill_rectangle(xcb_connection,
1473                                     outputs_walk->buffer,
1474                                     outputs_walk->bargc,
1475                                     1,
1476                                     &rect);
1477             xcb_change_gc(xcb_connection,
1478                           outputs_walk->bargc,
1479                           XCB_GC_FOREGROUND,
1480                           &fg_color);
1481             xcb_image_text_16(xcb_connection,
1482                               ws_walk->name_glyphs,
1483                               outputs_walk->buffer,
1484                               outputs_walk->bargc,
1485                               i + 5, font_info->font_ascent + 2,
1486                               ws_walk->ucs2_name);
1487             i += 10 + ws_walk->name_width;
1488         }
1489
1490         i = 0;
1491     }
1492
1493     redraw_bars();
1494 }
1495
1496 /*
1497  * Redraw the bars, i.e. simply copy the buffer to the barwindow
1498  *
1499  */
1500 void redraw_bars() {
1501     i3_output *outputs_walk;
1502     SLIST_FOREACH(outputs_walk, outputs, slist) {
1503         if (!outputs_walk->active) {
1504             continue;
1505         }
1506         xcb_copy_area(xcb_connection,
1507                       outputs_walk->buffer,
1508                       outputs_walk->bar,
1509                       outputs_walk->bargc,
1510                       0, 0,
1511                       0, 0,
1512                       outputs_walk->rect.w,
1513                       outputs_walk->rect.h);
1514         xcb_flush(xcb_connection);
1515     }
1516 }