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