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