]> git.sur5r.net Git - i3/i3/blob - i3bar/src/xcb.c
Merge branch 'master' into next
[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     const size_t len = strlen(cur_ws->name) + strlen("workspace \"\"") + 1;
298     char buffer[len];
299     snprintf(buffer, len, "workspace \"%s\"", cur_ws->name);
300     i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
301 }
302
303 /*
304  * Configures the x coordinate of all trayclients. To be called after adding a
305  * new tray client or removing an old one.
306  *
307  */
308 static void configure_trayclients() {
309     trayclient *trayclient;
310     i3_output *output;
311     SLIST_FOREACH(output, outputs, slist) {
312         if (!output->active)
313             continue;
314
315         int clients = 0;
316         TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
317             if (!trayclient->mapped)
318                 continue;
319             clients++;
320
321             DLOG("Configuring tray window %08x to x=%d\n",
322                  trayclient->win, output->rect.w - (clients * (font.height + 2)));
323             uint32_t x = output->rect.w - (clients * (font.height + 2));
324             xcb_configure_window(xcb_connection,
325                                  trayclient->win,
326                                  XCB_CONFIG_WINDOW_X,
327                                  &x);
328         }
329     }
330 }
331
332 /*
333  * Handles ClientMessages (messages sent from another client directly to us).
334  *
335  * At the moment, only the tray window will receive client messages. All
336  * supported client messages currently are _NET_SYSTEM_TRAY_OPCODE.
337  *
338  */
339 static void handle_client_message(xcb_client_message_event_t* event) {
340     if (event->type == atoms[_NET_SYSTEM_TRAY_OPCODE] &&
341         event->format == 32) {
342         DLOG("_NET_SYSTEM_TRAY_OPCODE received\n");
343         /* event->data.data32[0] is the timestamp */
344         uint32_t op = event->data.data32[1];
345         uint32_t mask;
346         uint32_t values[2];
347         if (op == SYSTEM_TRAY_REQUEST_DOCK) {
348             xcb_window_t client = event->data.data32[2];
349
350             /* Listen for PropertyNotify events to get the most recent value of
351              * the XEMBED_MAPPED atom, also listen for UnmapNotify events */
352             mask = XCB_CW_EVENT_MASK;
353             values[0] = XCB_EVENT_MASK_PROPERTY_CHANGE |
354                         XCB_EVENT_MASK_STRUCTURE_NOTIFY;
355             xcb_change_window_attributes(xcb_connection,
356                                          client,
357                                          mask,
358                                          values);
359
360             /* Request the _XEMBED_INFO property. The XEMBED specification
361              * (which is referred by the tray specification) says this *has* to
362              * be set, but VLC does not set it… */
363             bool map_it = true;
364             int xe_version = 1;
365             xcb_get_property_cookie_t xembedc;
366             xcb_generic_error_t *error;
367             xembedc = xcb_get_property(xcb_connection,
368                                        0,
369                                        client,
370                                        atoms[_XEMBED_INFO],
371                                        XCB_GET_PROPERTY_TYPE_ANY,
372                                        0,
373                                        2 * 32);
374
375             xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
376                                                                        xembedc,
377                                                                        &error);
378             if (error != NULL) {
379                 ELOG("Error getting _XEMBED_INFO property: error_code %d\n",
380                      error->error_code);
381                 free(error);
382                 return;
383             }
384             if (xembedr != NULL && xembedr->length != 0) {
385                 DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
386                 uint32_t *xembed = xcb_get_property_value(xembedr);
387                 DLOG("xembed version = %d\n", xembed[0]);
388                 DLOG("xembed flags = %d\n", xembed[1]);
389                 map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
390                 xe_version = xembed[0];
391                 if (xe_version > 1)
392                     xe_version = 1;
393                 free(xembedr);
394             } else {
395                 ELOG("Window %08x violates the XEMBED protocol, _XEMBED_INFO not set\n", client);
396             }
397
398             DLOG("X window %08x requested docking\n", client);
399             i3_output *walk, *output = NULL;
400             SLIST_FOREACH(walk, outputs, slist) {
401                 if (!walk->active)
402                     continue;
403                 if (config.tray_output &&
404                     strcasecmp(walk->name, config.tray_output) != 0)
405                     continue;
406                 DLOG("using output %s\n", walk->name);
407                 output = walk;
408             }
409             if (output == NULL) {
410                 ELOG("No output found\n");
411                 return;
412             }
413             xcb_reparent_window(xcb_connection,
414                                 client,
415                                 output->bar,
416                                 output->rect.w - font.height - 2,
417                                 2);
418             /* We reconfigure the window to use a reasonable size. The systray
419              * specification explicitly says:
420              *   Tray icons may be assigned any size by the system tray, and
421              *   should do their best to cope with any size effectively
422              */
423             mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
424             values[0] = font.height;
425             values[1] = font.height;
426             xcb_configure_window(xcb_connection,
427                                  client,
428                                  mask,
429                                  values);
430
431             /* send the XEMBED_EMBEDDED_NOTIFY message */
432             void *event = scalloc(32);
433             xcb_client_message_event_t *ev = event;
434             ev->response_type = XCB_CLIENT_MESSAGE;
435             ev->window = client;
436             ev->type = atoms[_XEMBED];
437             ev->format = 32;
438             ev->data.data32[0] = XCB_CURRENT_TIME;
439             ev->data.data32[1] = atoms[XEMBED_EMBEDDED_NOTIFY];
440             ev->data.data32[2] = output->bar;
441             ev->data.data32[3] = xe_version;
442             xcb_send_event(xcb_connection,
443                            0,
444                            client,
445                            XCB_EVENT_MASK_NO_EVENT,
446                            (char*)ev);
447             free(event);
448
449             /* Put the client inside the save set. Upon termination (whether
450              * killed or normal exit does not matter) of i3bar, these clients
451              * will be correctly reparented to their most closest living
452              * ancestor. Without this, tray icons might die when i3bar
453              * exits/crashes. */
454             xcb_change_save_set(xcb_connection, XCB_SET_MODE_INSERT, client);
455
456             if (map_it) {
457                 DLOG("Mapping dock client\n");
458                 xcb_map_window(xcb_connection, client);
459             } else {
460                 DLOG("Not mapping dock client yet\n");
461             }
462             trayclient *tc = smalloc(sizeof(trayclient));
463             tc->win = client;
464             tc->mapped = map_it;
465             tc->xe_version = xe_version;
466             TAILQ_INSERT_TAIL(output->trayclients, tc, tailq);
467
468             /* Trigger an update to copy the statusline text to the appropriate
469              * position */
470             configure_trayclients();
471             draw_bars();
472         }
473     }
474 }
475
476 /*
477  * Handles UnmapNotify events. These events happen when a tray window unmaps
478  * itself. We then update our data structure
479  *
480  */
481 static void handle_unmap_notify(xcb_unmap_notify_event_t* event) {
482     DLOG("UnmapNotify for window = %08x, event = %08x\n", event->window, event->event);
483
484     i3_output *walk;
485     SLIST_FOREACH(walk, outputs, slist) {
486         if (!walk->active)
487             continue;
488         DLOG("checking output %s\n", walk->name);
489         trayclient *trayclient;
490         TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
491             if (trayclient->win != event->window)
492                 continue;
493
494             DLOG("Removing tray client with window ID %08x\n", event->window);
495             TAILQ_REMOVE(walk->trayclients, trayclient, tailq);
496
497             /* Trigger an update, we now have more space for the statusline */
498             configure_trayclients();
499             draw_bars();
500             return;
501         }
502     }
503 }
504
505 /*
506  * Handle PropertyNotify messages. Currently only the _XEMBED_INFO property is
507  * handled, which tells us whether a dock client should be mapped or unmapped.
508  *
509  */
510 static void handle_property_notify(xcb_property_notify_event_t *event) {
511     DLOG("PropertyNotify\n");
512     if (event->atom == atoms[_XEMBED_INFO] &&
513         event->state == XCB_PROPERTY_NEW_VALUE) {
514         DLOG("xembed_info updated\n");
515         trayclient *trayclient = NULL, *walk;
516         i3_output *o_walk;
517         SLIST_FOREACH(o_walk, outputs, slist) {
518             if (!o_walk->active)
519                 continue;
520
521             TAILQ_FOREACH(walk, o_walk->trayclients, tailq) {
522                 if (walk->win != event->window)
523                     continue;
524                 trayclient = walk;
525                 break;
526             }
527
528             if (trayclient)
529                 break;
530         }
531         if (!trayclient) {
532             ELOG("PropertyNotify received for unknown window %08x\n",
533                  event->window);
534             return;
535         }
536         xcb_get_property_cookie_t xembedc;
537         xembedc = xcb_get_property_unchecked(xcb_connection,
538                                              0,
539                                              trayclient->win,
540                                              atoms[_XEMBED_INFO],
541                                              XCB_GET_PROPERTY_TYPE_ANY,
542                                              0,
543                                              2 * 32);
544
545         xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
546                                                                    xembedc,
547                                                                    NULL);
548         if (xembedr == NULL || xembedr->length == 0) {
549             DLOG("xembed_info unset\n");
550             return;
551         }
552
553         DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
554         uint32_t *xembed = xcb_get_property_value(xembedr);
555         DLOG("xembed version = %d\n", xembed[0]);
556         DLOG("xembed flags = %d\n", xembed[1]);
557         bool map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
558         DLOG("map-state now %d\n", map_it);
559         if (trayclient->mapped && !map_it) {
560             /* need to unmap the window */
561             xcb_unmap_window(xcb_connection, trayclient->win);
562             trayclient->mapped = map_it;
563             configure_trayclients();
564             draw_bars();
565         } else if (!trayclient->mapped && map_it) {
566             /* need to map the window */
567             xcb_map_window(xcb_connection, trayclient->win);
568             trayclient->mapped = map_it;
569             configure_trayclients();
570             draw_bars();
571         }
572         free(xembedr);
573     }
574 }
575
576 /*
577  * Handle ConfigureRequests by denying them and sending the client a
578  * ConfigureNotify with its actual size.
579  *
580  */
581 static void handle_configure_request(xcb_configure_request_event_t *event) {
582     DLOG("ConfigureRequest for window = %08x\n", event->window);
583
584     trayclient *trayclient;
585     i3_output *output;
586     SLIST_FOREACH(output, outputs, slist) {
587         if (!output->active)
588             continue;
589
590         int clients = 0;
591         TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
592             if (!trayclient->mapped)
593                 continue;
594             clients++;
595
596             if (trayclient->win != event->window)
597                 continue;
598
599             xcb_rectangle_t rect;
600             rect.x = output->rect.w - (clients * (font.height + 2));
601             rect.y = 2;
602             rect.width = font.height;
603             rect.height = font.height;
604
605             DLOG("This is a tray window. x = %d\n", rect.x);
606             fake_configure_notify(xcb_connection, rect, event->window, 0);
607             return;
608         }
609     }
610
611     DLOG("WARNING: Could not find corresponding tray window.\n");
612 }
613
614 /*
615  * This function is called immediately before the main loop locks. We flush xcb
616  * then (and only then)
617  *
618  */
619 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revents) {
620     xcb_flush(xcb_connection);
621 }
622
623 /*
624  * This function is called immediately after the main loop locks, so when one
625  * of the watchers registered an event.
626  * We check whether an X-Event arrived and handle it.
627  *
628  */
629 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
630     xcb_generic_event_t *event;
631
632     if (xcb_connection_has_error(xcb_connection)) {
633         ELOG("X11 connection was closed unexpectedly - maybe your X server terminated / crashed?\n");
634         exit(1);
635     }
636
637     while ((event = xcb_poll_for_event(xcb_connection)) != NULL) {
638         switch (event->response_type & ~0x80) {
639             case XCB_EXPOSE:
640                 /* Expose-events happen, when the window needs to be redrawn */
641                 redraw_bars();
642                 break;
643             case XCB_BUTTON_PRESS:
644                 /* Button-press-events are mouse-buttons clicked on one of our bars */
645                 handle_button((xcb_button_press_event_t*) event);
646                 break;
647             case XCB_CLIENT_MESSAGE:
648                 /* Client messages are used for client-to-client communication, for
649                  * example system tray widgets talk to us directly via client messages. */
650                 handle_client_message((xcb_client_message_event_t*) event);
651                 break;
652             case XCB_UNMAP_NOTIFY:
653             case XCB_DESTROY_NOTIFY:
654                 /* UnmapNotifies are received when a tray window unmaps itself */
655                 handle_unmap_notify((xcb_unmap_notify_event_t*) event);
656                 break;
657             case XCB_PROPERTY_NOTIFY:
658                 /* PropertyNotify */
659                 handle_property_notify((xcb_property_notify_event_t*) event);
660                 break;
661             case XCB_CONFIGURE_REQUEST:
662                 /* ConfigureRequest, sent by a tray child */
663                 handle_configure_request((xcb_configure_request_event_t*) event);
664                 break;
665         }
666         free(event);
667     }
668 }
669
670 /*
671  * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
672  * are triggered
673  *
674  */
675 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
676 }
677
678 /*
679  * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
680  *
681  */
682 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
683     XkbEvent ev;
684     int modstate = 0;
685
686     DLOG("Got XKB-Event!\n");
687
688     while (XPending(xkb_dpy)) {
689         XNextEvent(xkb_dpy, (XEvent*)&ev);
690
691         if (ev.type != xkb_event_base) {
692             ELOG("No Xkb-Event!\n");
693             continue;
694         }
695
696         if (ev.any.xkb_type != XkbStateNotify) {
697             ELOG("No State Notify!\n");
698             continue;
699         }
700
701         unsigned int mods = ev.state.mods;
702         modstate = mods & config.modifier;
703     }
704
705 #define DLOGMOD(modmask, status, barfunc) \
706     do { \
707         switch (modmask) { \
708             case ShiftMask: \
709                 DLOG("ShiftMask got " #status "!\n"); \
710                 break; \
711             case ControlMask: \
712                 DLOG("ControlMask got " #status "!\n"); \
713                 break; \
714             case Mod1Mask: \
715                 DLOG("Mod1Mask got " #status "!\n"); \
716                 break; \
717             case Mod2Mask: \
718                 DLOG("Mod2Mask got " #status "!\n"); \
719                 break; \
720             case Mod3Mask: \
721                 DLOG("Mod3Mask got " #status "!\n"); \
722                 break; \
723             case Mod4Mask: \
724                 DLOG("Mod4Mask got " #status "!\n"); \
725                 break; \
726             case Mod5Mask: \
727                 DLOG("Mod5Mask got " #status "!\n"); \
728                 break; \
729         } \
730         barfunc(); \
731     } while (0)
732
733     if (modstate != mod_pressed) {
734         if (modstate == 0) {
735             DLOGMOD(config.modifier, released, hide_bars);
736         } else {
737             DLOGMOD(config.modifier, pressed, unhide_bars);
738         }
739         mod_pressed = modstate;
740     }
741
742 #undef DLOGMOD
743 }
744
745 /*
746  * Early initialization of the connection to X11: Everything which does not
747  * depend on 'config'.
748  *
749  */
750 char *init_xcb_early() {
751     /* FIXME: xcb_connect leaks Memory */
752     xcb_connection = xcb_connect(NULL, &screen);
753     if (xcb_connection_has_error(xcb_connection)) {
754         ELOG("Cannot open display\n");
755         exit(EXIT_FAILURE);
756     }
757     conn = xcb_connection;
758     DLOG("Connected to xcb\n");
759
760     /* We have to request the atoms we need */
761     #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
762     #include "xcb_atoms.def"
763
764     xcb_screen = xcb_setup_roots_iterator(xcb_get_setup(xcb_connection)).data;
765     xcb_root = xcb_screen->root;
766
767     /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
768      * this way, we can choose to crop it */
769     uint32_t mask = XCB_GC_FOREGROUND;
770     uint32_t vals[] = { colors.bar_bg, colors.bar_bg };
771
772     statusline_clear = xcb_generate_id(xcb_connection);
773     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
774                                                                statusline_clear,
775                                                                xcb_root,
776                                                                mask,
777                                                                vals);
778
779     statusline_ctx = xcb_generate_id(xcb_connection);
780     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
781                                                             statusline_ctx,
782                                                             xcb_root,
783                                                             0,
784                                                             NULL);
785
786     statusline_pm = xcb_generate_id(xcb_connection);
787     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
788                                                                xcb_screen->root_depth,
789                                                                statusline_pm,
790                                                                xcb_root,
791                                                                xcb_screen->width_in_pixels,
792                                                                xcb_screen->height_in_pixels);
793
794
795     /* The various Watchers to communicate with xcb */
796     xcb_io = smalloc(sizeof(ev_io));
797     xcb_prep = smalloc(sizeof(ev_prepare));
798     xcb_chk = smalloc(sizeof(ev_check));
799
800     ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
801     ev_prepare_init(xcb_prep, &xcb_prep_cb);
802     ev_check_init(xcb_chk, &xcb_chk_cb);
803
804     ev_io_start(main_loop, xcb_io);
805     ev_prepare_start(main_loop, xcb_prep);
806     ev_check_start(main_loop, xcb_chk);
807
808     /* Now we get the atoms and save them in a nice data structure */
809     get_atoms();
810
811     xcb_get_property_cookie_t path_cookie;
812     path_cookie = xcb_get_property_unchecked(xcb_connection,
813                                    0,
814                                    xcb_root,
815                                    atoms[I3_SOCKET_PATH],
816                                    XCB_GET_PROPERTY_TYPE_ANY,
817                                    0, PATH_MAX);
818
819     /* We check, if i3 set its socket-path */
820     xcb_get_property_reply_t *path_reply = xcb_get_property_reply(xcb_connection,
821                                                                   path_cookie,
822                                                                   NULL);
823     char *path = NULL;
824     if (path_reply) {
825         int len = xcb_get_property_value_length(path_reply);
826         if (len != 0) {
827             path = strndup(xcb_get_property_value(path_reply), len);
828         }
829     }
830
831
832     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
833         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
834         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
835         exit(EXIT_FAILURE);
836     }
837
838     return path;
839 }
840
841 /*
842  * Initialization which depends on 'config' being usable. Called after the
843  * configuration has arrived.
844  *
845  */
846 void init_xcb_late(char *fontname) {
847     if (fontname == NULL)
848         fontname = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
849
850     /* Load the font */
851     font = load_font(fontname, true);
852     set_font(&font);
853     DLOG("Calculated Font-height: %d\n", font.height);
854
855     xcb_flush(xcb_connection);
856
857     /* To grab modifiers without blocking other applications from receiving key-events
858      * involving that modifier, we sadly have to use xkb which is not yet fully supported
859      * in xcb */
860     if (config.hide_on_modifier) {
861         int xkb_major, xkb_minor, xkb_errbase, xkb_err;
862         xkb_major = XkbMajorVersion;
863         xkb_minor = XkbMinorVersion;
864
865         xkb_dpy = XkbOpenDisplay(NULL,
866                                  &xkb_event_base,
867                                  &xkb_errbase,
868                                  &xkb_major,
869                                  &xkb_minor,
870                                  &xkb_err);
871
872         if (xkb_dpy == NULL) {
873             ELOG("No XKB!\n");
874             exit(EXIT_FAILURE);
875         }
876
877         if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
878             ELOG("Could not set FD_CLOEXEC on xkbdpy: %s\n", strerror(errno));
879             exit(EXIT_FAILURE);
880         }
881
882         int i1;
883         if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
884             ELOG("XKB not supported by X-server!\n");
885             exit(EXIT_FAILURE);
886         }
887
888         if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
889             ELOG("Could not grab Key!\n");
890             exit(EXIT_FAILURE);
891         }
892
893         xkb_io = smalloc(sizeof(ev_io));
894         ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
895         ev_io_start(main_loop, xkb_io);
896         XFlush(xkb_dpy);
897     }
898 }
899
900 /*
901  * Initializes tray support by requesting the appropriate _NET_SYSTEM_TRAY atom
902  * for the X11 display we are running on, then acquiring the selection for this
903  * atom. Afterwards, tray clients will send ClientMessages to our window.
904  *
905  */
906 void init_tray() {
907     DLOG("Initializing system tray functionality\n");
908     /* request the tray manager atom for the X11 display we are running on */
909     char atomname[strlen("_NET_SYSTEM_TRAY_S") + 11];
910     snprintf(atomname, strlen("_NET_SYSTEM_TRAY_S") + 11, "_NET_SYSTEM_TRAY_S%d", screen);
911     xcb_intern_atom_cookie_t tray_cookie;
912     xcb_intern_atom_reply_t *tray_reply;
913     tray_cookie = xcb_intern_atom(xcb_connection, 0, strlen(atomname), atomname);
914
915     /* tray support: we need a window to own the selection */
916     xcb_window_t selwin = xcb_generate_id(xcb_connection);
917     uint32_t selmask = XCB_CW_OVERRIDE_REDIRECT;
918     uint32_t selval[] = { 1 };
919     xcb_create_window(xcb_connection,
920                       xcb_screen->root_depth,
921                       selwin,
922                       xcb_root,
923                       -1, -1,
924                       1, 1,
925                       1,
926                       XCB_WINDOW_CLASS_INPUT_OUTPUT,
927                       xcb_screen->root_visual,
928                       selmask,
929                       selval);
930
931     uint32_t orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
932     /* set the atoms */
933     xcb_change_property(xcb_connection,
934                         XCB_PROP_MODE_REPLACE,
935                         selwin,
936                         atoms[_NET_SYSTEM_TRAY_ORIENTATION],
937                         XCB_ATOM_CARDINAL,
938                         32,
939                         1,
940                         &orientation);
941
942     if (!(tray_reply = xcb_intern_atom_reply(xcb_connection, tray_cookie, NULL))) {
943         ELOG("Could not get atom %s\n", atomname);
944         exit(EXIT_FAILURE);
945     }
946
947     xcb_set_selection_owner(xcb_connection,
948                             selwin,
949                             tray_reply->atom,
950                             XCB_CURRENT_TIME);
951
952     /* Verify that we have the selection */
953     xcb_get_selection_owner_cookie_t selcookie;
954     xcb_get_selection_owner_reply_t *selreply;
955
956     selcookie = xcb_get_selection_owner(xcb_connection, tray_reply->atom);
957     if (!(selreply = xcb_get_selection_owner_reply(xcb_connection, selcookie, NULL))) {
958         ELOG("Could not get selection owner for %s\n", atomname);
959         exit(EXIT_FAILURE);
960     }
961
962     if (selreply->owner != selwin) {
963         ELOG("Could not set the %s selection. " \
964              "Maybe another tray is already running?\n", atomname);
965         /* NOTE that this error is not fatal. We just can’t provide tray
966          * functionality */
967         free(selreply);
968         return;
969     }
970
971     /* Inform clients waiting for a new _NET_SYSTEM_TRAY that we are here */
972     void *event = scalloc(32);
973     xcb_client_message_event_t *ev = event;
974     ev->response_type = XCB_CLIENT_MESSAGE;
975     ev->window = xcb_root;
976     ev->type = atoms[MANAGER];
977     ev->format = 32;
978     ev->data.data32[0] = XCB_CURRENT_TIME;
979     ev->data.data32[1] = tray_reply->atom;
980     ev->data.data32[2] = selwin;
981     xcb_send_event(xcb_connection,
982                    0,
983                    xcb_root,
984                    XCB_EVENT_MASK_STRUCTURE_NOTIFY,
985                    (char*)ev);
986     free(event);
987     free(tray_reply);
988 }
989
990 /*
991  * Cleanup the xcb-stuff.
992  * Called once, before the program terminates.
993  *
994  */
995 void clean_xcb() {
996     i3_output *o_walk;
997     trayclient *trayclient;
998     free_workspaces();
999     SLIST_FOREACH(o_walk, outputs, slist) {
1000         TAILQ_FOREACH(trayclient, o_walk->trayclients, tailq) {
1001             /* Unmap, then reparent (to root) the tray client windows */
1002             xcb_unmap_window(xcb_connection, trayclient->win);
1003             xcb_reparent_window(xcb_connection,
1004                                 trayclient->win,
1005                                 xcb_root,
1006                                 0,
1007                                 0);
1008         }
1009         destroy_window(o_walk);
1010         FREE(o_walk->trayclients);
1011         FREE(o_walk->workspaces);
1012         FREE(o_walk->name);
1013     }
1014     FREE_SLIST(outputs, i3_output);
1015     FREE(outputs);
1016
1017     xcb_flush(xcb_connection);
1018     xcb_disconnect(xcb_connection);
1019
1020     ev_check_stop(main_loop, xcb_chk);
1021     ev_prepare_stop(main_loop, xcb_prep);
1022     ev_io_stop(main_loop, xcb_io);
1023
1024     FREE(xcb_chk);
1025     FREE(xcb_prep);
1026     FREE(xcb_io);
1027 }
1028
1029 /*
1030  * Get the earlier requested atoms and save them in the prepared data structure
1031  *
1032  */
1033 void get_atoms() {
1034     xcb_intern_atom_reply_t *reply;
1035     #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
1036         if (reply == NULL) { \
1037             ELOG("Could not get atom %s\n", #name); \
1038             exit(EXIT_FAILURE); \
1039         } \
1040         atoms[name] = reply->atom; \
1041         free(reply);
1042
1043     #include "xcb_atoms.def"
1044     DLOG("Got Atoms\n");
1045 }
1046
1047 /*
1048  * Destroy the bar of the specified output
1049  *
1050  */
1051 void destroy_window(i3_output *output) {
1052     if (output == NULL) {
1053         return;
1054     }
1055     if (output->bar == XCB_NONE) {
1056         return;
1057     }
1058     xcb_destroy_window(xcb_connection, output->bar);
1059     output->bar = XCB_NONE;
1060 }
1061
1062 /*
1063  * Reallocate the statusline-buffer
1064  *
1065  */
1066 void realloc_sl_buffer() {
1067     DLOG("Re-allocating statusline-buffer, statusline_width = %d, xcb_screen->width_in_pixels = %d\n",
1068          statusline_width, xcb_screen->width_in_pixels);
1069     xcb_free_pixmap(xcb_connection, statusline_pm);
1070     statusline_pm = xcb_generate_id(xcb_connection);
1071     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1072                                                                xcb_screen->root_depth,
1073                                                                statusline_pm,
1074                                                                xcb_root,
1075                                                                MAX(xcb_screen->width_in_pixels, statusline_width),
1076                                                                xcb_screen->height_in_pixels);
1077
1078     uint32_t mask = XCB_GC_FOREGROUND;
1079     uint32_t vals[2] = { colors.bar_bg, colors.bar_bg };
1080     xcb_free_gc(xcb_connection, statusline_clear);
1081     statusline_clear = xcb_generate_id(xcb_connection);
1082     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1083                                                                statusline_clear,
1084                                                                xcb_root,
1085                                                                mask,
1086                                                                vals);
1087
1088     mask |= XCB_GC_BACKGROUND;
1089     vals[0] = colors.bar_fg;
1090     statusline_ctx = xcb_generate_id(xcb_connection);
1091     xcb_free_gc(xcb_connection, statusline_ctx);
1092     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1093                                                             statusline_ctx,
1094                                                             xcb_root,
1095                                                             mask,
1096                                                             vals);
1097
1098     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
1099         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
1100         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
1101         exit(EXIT_FAILURE);
1102     }
1103
1104 }
1105
1106 /*
1107  * Reconfigure all bars and create new bars for recently activated outputs
1108  *
1109  */
1110 void reconfig_windows() {
1111     uint32_t mask;
1112     uint32_t values[5];
1113     static bool tray_configured = false;
1114
1115     i3_output *walk;
1116     SLIST_FOREACH(walk, outputs, slist) {
1117         if (!walk->active) {
1118             /* If an output is not active, we destroy its bar */
1119             /* FIXME: Maybe we rather want to unmap? */
1120             DLOG("Destroying window for output %s\n", walk->name);
1121             destroy_window(walk);
1122             continue;
1123         }
1124         if (walk->bar == XCB_NONE) {
1125             DLOG("Creating Window for output %s\n", walk->name);
1126
1127             walk->bar = xcb_generate_id(xcb_connection);
1128             walk->buffer = xcb_generate_id(xcb_connection);
1129             mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
1130             /* Black background */
1131             values[0] = colors.bar_bg;
1132             /* If hide_on_modifier is set, i3 is not supposed to manage our bar-windows */
1133             values[1] = config.hide_on_modifier;
1134             /* We enable the following EventMask fields:
1135              * EXPOSURE, to get expose events (we have to re-draw then)
1136              * SUBSTRUCTURE_REDIRECT, to get ConfigureRequests when the tray
1137              *                        child windows use ConfigureWindow
1138              * BUTTON_PRESS, to handle clicks on the workspace buttons
1139              * */
1140             values[2] = XCB_EVENT_MASK_EXPOSURE |
1141                         XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;
1142             if (!config.disable_ws) {
1143                 values[2] |= XCB_EVENT_MASK_BUTTON_PRESS;
1144             }
1145             xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
1146                                                                      xcb_screen->root_depth,
1147                                                                      walk->bar,
1148                                                                      xcb_root,
1149                                                                      walk->rect.x, walk->rect.y + walk->rect.h - font.height - 6,
1150                                                                      walk->rect.w, font.height + 6,
1151                                                                      1,
1152                                                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,
1153                                                                      xcb_screen->root_visual,
1154                                                                      mask,
1155                                                                      values);
1156
1157             /* The double-buffer we use to render stuff off-screen */
1158             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1159                                                                     xcb_screen->root_depth,
1160                                                                     walk->buffer,
1161                                                                     walk->bar,
1162                                                                     walk->rect.w,
1163                                                                     walk->rect.h);
1164
1165             /* Set the WM_CLASS and WM_NAME (we don't need UTF-8) atoms */
1166             xcb_void_cookie_t class_cookie;
1167             class_cookie = xcb_change_property(xcb_connection,
1168                                                XCB_PROP_MODE_REPLACE,
1169                                                walk->bar,
1170                                                XCB_ATOM_WM_CLASS,
1171                                                XCB_ATOM_STRING,
1172                                                8,
1173                                                (strlen("i3bar") + 1) * 2,
1174                                                "i3bar\0i3bar\0");
1175
1176             char *name;
1177             if (asprintf(&name, "i3bar for output %s", walk->name) == -1)
1178                 err(EXIT_FAILURE, "asprintf()");
1179             xcb_void_cookie_t name_cookie;
1180             name_cookie = xcb_change_property(xcb_connection,
1181                                               XCB_PROP_MODE_REPLACE,
1182                                               walk->bar,
1183                                               XCB_ATOM_WM_NAME,
1184                                               XCB_ATOM_STRING,
1185                                               8,
1186                                               strlen(name),
1187                                               name);
1188             free(name);
1189
1190             /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
1191              * this one */
1192             xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
1193                                                                 XCB_PROP_MODE_REPLACE,
1194                                                                 walk->bar,
1195                                                                 atoms[_NET_WM_WINDOW_TYPE],
1196                                                                 XCB_ATOM_ATOM,
1197                                                                 32,
1198                                                                 1,
1199                                                                 (unsigned char*) &atoms[_NET_WM_WINDOW_TYPE_DOCK]);
1200
1201             /* We need to tell i3, where to reserve space for i3bar */
1202             /* left, right, top, bottom, left_start_y, left_end_y,
1203              * right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x,
1204              * bottom_end_x */
1205             /* A local struct to save the strut_partial property */
1206             struct {
1207                 uint32_t left;
1208                 uint32_t right;
1209                 uint32_t top;
1210                 uint32_t bottom;
1211                 uint32_t left_start_y;
1212                 uint32_t left_end_y;
1213                 uint32_t right_start_y;
1214                 uint32_t right_end_y;
1215                 uint32_t top_start_x;
1216                 uint32_t top_end_x;
1217                 uint32_t bottom_start_x;
1218                 uint32_t bottom_end_x;
1219             } __attribute__((__packed__)) strut_partial = {0,};
1220             switch (config.position) {
1221                 case POS_NONE:
1222                     break;
1223                 case POS_TOP:
1224                     strut_partial.top = font.height + 6;
1225                     strut_partial.top_start_x = walk->rect.x;
1226                     strut_partial.top_end_x = walk->rect.x + walk->rect.w;
1227                     break;
1228                 case POS_BOT:
1229                     strut_partial.bottom = font.height + 6;
1230                     strut_partial.bottom_start_x = walk->rect.x;
1231                     strut_partial.bottom_end_x = walk->rect.x + walk->rect.w;
1232                     break;
1233             }
1234             xcb_void_cookie_t strut_cookie = xcb_change_property(xcb_connection,
1235                                                                  XCB_PROP_MODE_REPLACE,
1236                                                                  walk->bar,
1237                                                                  atoms[_NET_WM_STRUT_PARTIAL],
1238                                                                  XCB_ATOM_CARDINAL,
1239                                                                  32,
1240                                                                  12,
1241                                                                  &strut_partial);
1242
1243             /* We also want a graphics-context for the bars (it defines the properties
1244              * with which we draw to them) */
1245             walk->bargc = xcb_generate_id(xcb_connection);
1246             xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
1247                                                                 walk->bargc,
1248                                                                 walk->bar,
1249                                                                 0,
1250                                                                 NULL);
1251
1252             /* We finally map the bar (display it on screen), unless the modifier-switch is on */
1253             xcb_void_cookie_t map_cookie;
1254             if (!config.hide_on_modifier) {
1255                 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
1256             }
1257
1258             if (xcb_request_failed(win_cookie,   "Could not create window") ||
1259                 xcb_request_failed(pm_cookie,    "Could not create pixmap") ||
1260                 xcb_request_failed(dock_cookie,  "Could not set dock mode") ||
1261                 xcb_request_failed(class_cookie, "Could not set WM_CLASS")  ||
1262                 xcb_request_failed(name_cookie,  "Could not set WM_NAME")   ||
1263                 xcb_request_failed(strut_cookie, "Could not set strut")     ||
1264                 xcb_request_failed(gc_cookie,    "Could not create graphical context") ||
1265                 (!config.hide_on_modifier && xcb_request_failed(map_cookie, "Could not map window"))) {
1266                 exit(EXIT_FAILURE);
1267             }
1268
1269             if (!tray_configured &&
1270                 (!config.tray_output ||
1271                  strcasecmp("none", config.tray_output) != 0)) {
1272                 init_tray();
1273                 tray_configured = true;
1274             }
1275         } else {
1276             /* We already have a bar, so we just reconfigure it */
1277             mask = XCB_CONFIG_WINDOW_X |
1278                    XCB_CONFIG_WINDOW_Y |
1279                    XCB_CONFIG_WINDOW_WIDTH |
1280                    XCB_CONFIG_WINDOW_HEIGHT |
1281                    XCB_CONFIG_WINDOW_STACK_MODE;
1282             values[0] = walk->rect.x;
1283             values[1] = walk->rect.y + walk->rect.h - font.height - 6;
1284             values[2] = walk->rect.w;
1285             values[3] = font.height + 6;
1286             values[4] = XCB_STACK_MODE_ABOVE;
1287
1288             DLOG("Destroying buffer for output %s", walk->name);
1289             xcb_free_pixmap(xcb_connection, walk->buffer);
1290
1291             DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
1292             xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
1293                                                                         walk->bar,
1294                                                                         mask,
1295                                                                         values);
1296
1297             DLOG("Recreating buffer for output %s", walk->name);
1298             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1299                                                                     xcb_screen->root_depth,
1300                                                                     walk->buffer,
1301                                                                     walk->bar,
1302                                                                     walk->rect.w,
1303                                                                     walk->rect.h);
1304
1305             if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
1306                 exit(EXIT_FAILURE);
1307             }
1308             if (xcb_request_failed(pm_cookie,  "Could not create pixmap")) {
1309                 exit(EXIT_FAILURE);
1310             }
1311         }
1312     }
1313 }
1314
1315 /*
1316  * Render the bars, with buttons and statusline
1317  *
1318  */
1319 void draw_bars() {
1320     DLOG("Drawing Bars...\n");
1321     int i = 0;
1322
1323     refresh_statusline();
1324
1325     i3_output *outputs_walk;
1326     SLIST_FOREACH(outputs_walk, outputs, slist) {
1327         if (!outputs_walk->active) {
1328             DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
1329             continue;
1330         }
1331         if (outputs_walk->bar == XCB_NONE) {
1332             /* Oh shit, an active output without an own bar. Create it now! */
1333             reconfig_windows();
1334         }
1335         /* First things first: clear the backbuffer */
1336         uint32_t color = colors.bar_bg;
1337         xcb_change_gc(xcb_connection,
1338                       outputs_walk->bargc,
1339                       XCB_GC_FOREGROUND,
1340                       &color);
1341         xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font.height + 6 };
1342         xcb_poly_fill_rectangle(xcb_connection,
1343                                 outputs_walk->buffer,
1344                                 outputs_walk->bargc,
1345                                 1,
1346                                 &rect);
1347
1348         if (statusline != NULL) {
1349             DLOG("Printing statusline!\n");
1350
1351             /* Luckily we already prepared a seperate pixmap containing the rendered
1352              * statusline, we just have to copy the relevant parts to the relevant
1353              * position */
1354             trayclient *trayclient;
1355             int traypx = 0;
1356             TAILQ_FOREACH(trayclient, outputs_walk->trayclients, tailq) {
1357                 if (!trayclient->mapped)
1358                     continue;
1359                 /* We assume the tray icons are quadratic (we use the font
1360                  * *height* as *width* of the icons) because we configured them
1361                  * like this. */
1362                 traypx += font.height + 2;
1363             }
1364             /* Add 2px of padding if there are any tray icons */
1365             if (traypx > 0)
1366                 traypx += 2;
1367             xcb_copy_area(xcb_connection,
1368                           statusline_pm,
1369                           outputs_walk->buffer,
1370                           outputs_walk->bargc,
1371                           MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
1372                           MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - traypx - 4)), 3,
1373                           MIN(outputs_walk->rect.w - traypx - 4, statusline_width), font.height);
1374         }
1375
1376         if (config.disable_ws) {
1377             continue;
1378         }
1379
1380         i3_ws *ws_walk;
1381         TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
1382             DLOG("Drawing Button for WS %s at x = %d, len = %d\n", ws_walk->name, i, ws_walk->name_width);
1383             uint32_t fg_color = colors.inactive_ws_fg;
1384             uint32_t bg_color = colors.inactive_ws_bg;
1385             uint32_t border_color = colors.inactive_ws_border;
1386             if (ws_walk->visible) {
1387                 if (!ws_walk->focused) {
1388                     fg_color = colors.active_ws_fg;
1389                     bg_color = colors.active_ws_bg;
1390                     border_color = colors.active_ws_border;
1391                 } else {
1392                     fg_color = colors.focus_ws_fg;
1393                     bg_color = colors.focus_ws_bg;
1394                     border_color = colors.focus_ws_border;
1395                 }
1396             }
1397             if (ws_walk->urgent) {
1398                 DLOG("WS %s is urgent!\n", ws_walk->name);
1399                 fg_color = colors.urgent_ws_fg;
1400                 bg_color = colors.urgent_ws_bg;
1401                 border_color = colors.urgent_ws_border;
1402                 /* The urgent-hint should get noticed, so we unhide the bars shortly */
1403                 unhide_bars();
1404             }
1405             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
1406             uint32_t vals_border[] = { border_color, border_color };
1407             xcb_change_gc(xcb_connection,
1408                           outputs_walk->bargc,
1409                           mask,
1410                           vals_border);
1411             xcb_rectangle_t rect_border = { i, 0, ws_walk->name_width + 10, font.height + 4 };
1412             xcb_poly_fill_rectangle(xcb_connection,
1413                                     outputs_walk->buffer,
1414                                     outputs_walk->bargc,
1415                                     1,
1416                                     &rect_border);
1417             uint32_t vals[] = { bg_color, bg_color };
1418             xcb_change_gc(xcb_connection,
1419                           outputs_walk->bargc,
1420                           mask,
1421                           vals);
1422             xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font.height + 2 };
1423             xcb_poly_fill_rectangle(xcb_connection,
1424                                     outputs_walk->buffer,
1425                                     outputs_walk->bargc,
1426                                     1,
1427                                     &rect);
1428             set_font_colors(outputs_walk->bargc, fg_color, bg_color);
1429             draw_text((char*)ws_walk->ucs2_name, ws_walk->name_glyphs, true,
1430                     outputs_walk->buffer, outputs_walk->bargc, i + 5, 2, ws_walk->name_width);
1431             i += 10 + ws_walk->name_width + 1;
1432         }
1433
1434         i = 0;
1435     }
1436
1437     redraw_bars();
1438 }
1439
1440 /*
1441  * Redraw the bars, i.e. simply copy the buffer to the barwindow
1442  *
1443  */
1444 void redraw_bars() {
1445     i3_output *outputs_walk;
1446     SLIST_FOREACH(outputs_walk, outputs, slist) {
1447         if (!outputs_walk->active) {
1448             continue;
1449         }
1450         xcb_copy_area(xcb_connection,
1451                       outputs_walk->buffer,
1452                       outputs_walk->bar,
1453                       outputs_walk->bargc,
1454                       0, 0,
1455                       0, 0,
1456                       outputs_walk->rect.w,
1457                       outputs_walk->rect.h);
1458         xcb_flush(xcb_connection);
1459     }
1460 }