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