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