]> git.sur5r.net Git - i3/i3/blob - i3bar/src/xcb.c
i3bar: introduce get_tray_width() function to reduce duplication
[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-2012 Axel Wagner and contributors (see also: LICENSE)
6  *
7  * xcb.c: Communicating with X
8  *
9  */
10 #include <xcb/xcb.h>
11 #include <xcb/xkb.h>
12 #include <xcb/xproto.h>
13 #include <xcb/xcb_aux.h>
14
15 #ifdef XCB_COMPAT
16 #include "xcb_compat.h"
17 #endif
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <string.h>
24 #include <i3/ipc.h>
25 #include <ev.h>
26 #include <errno.h>
27 #include <limits.h>
28 #include <err.h>
29
30 #include <X11/Xlib.h>
31 #include <X11/XKBlib.h>
32 #include <X11/extensions/XKB.h>
33
34 #include "common.h"
35 #include "libi3.h"
36
37 /* We save the Atoms in an easy to access array, indexed by an enum */
38 enum {
39 #define ATOM_DO(name) name,
40 #include "xcb_atoms.def"
41     NUM_ATOMS
42 };
43
44 xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
45 xcb_atom_t atoms[NUM_ATOMS];
46
47 /* Variables, that are the same for all functions at all times */
48 xcb_connection_t *xcb_connection;
49 int screen;
50 xcb_screen_t *root_screen;
51 xcb_window_t xcb_root;
52
53 /* selection window for tray support */
54 static xcb_window_t selwin = XCB_NONE;
55 static xcb_intern_atom_reply_t *tray_reply = NULL;
56
57 /* This is needed for integration with libi3 */
58 xcb_connection_t *conn;
59
60 /* The font we'll use */
61 static i3Font font;
62
63 /* Overall height of the bar (based on font size) */
64 int bar_height;
65
66 /* These are only relevant for XKB, which we only need for grabbing modifiers */
67 int xkb_base;
68 int mod_pressed = 0;
69
70 /* Because the statusline is the same on all outputs, we have
71  * global buffer to render it on */
72 xcb_gcontext_t statusline_ctx;
73 xcb_gcontext_t statusline_clear;
74 xcb_pixmap_t statusline_pm;
75 uint32_t statusline_width;
76
77 /* Event-Watchers, to interact with the user */
78 ev_prepare *xcb_prep;
79 ev_check *xcb_chk;
80 ev_io *xcb_io;
81 ev_io *xkb_io;
82
83 /* The name of current binding mode */
84 static mode binding;
85
86 /* Indicates whether a new binding mode was recently activated */
87 bool activated_mode = false;
88
89 /* The parsed colors */
90 struct xcb_colors_t {
91     uint32_t bar_fg;
92     uint32_t bar_bg;
93     uint32_t sep_fg;
94     uint32_t active_ws_fg;
95     uint32_t active_ws_bg;
96     uint32_t active_ws_border;
97     uint32_t inactive_ws_fg;
98     uint32_t inactive_ws_bg;
99     uint32_t inactive_ws_border;
100     uint32_t urgent_ws_bg;
101     uint32_t urgent_ws_fg;
102     uint32_t urgent_ws_border;
103     uint32_t focus_ws_bg;
104     uint32_t focus_ws_fg;
105     uint32_t focus_ws_border;
106 };
107 struct xcb_colors_t colors;
108
109 const static int ws_hoff_px = 4,    /* Horizontal offset between a workspace label and button borders */
110                  ws_voff_px = 3,    /* Vertical offset between a workspace label and button borders */
111                  ws_spacing_px = 1, /* Offset between two workspace buttons */
112                  sb_hoff_px = 4,    /* Offset between the statusline and 1) workspace buttons on the left
113                                      *                                   2) the tray or screen edge on the right */
114                  tray_loff_px = 2,  /* Additional offset between the tray and the statusline, if the tray is not empty */
115                  sep_voff_px = 4;   /* Vertical offset between the bar and a separator */
116
117 /* We define xcb_request_failed as a macro to include the relevant line-number */
118 #define xcb_request_failed(cookie, err_msg) _xcb_request_failed(cookie, err_msg, __LINE__)
119 int _xcb_request_failed(xcb_void_cookie_t cookie, char *err_msg, int line) {
120     xcb_generic_error_t *err;
121     if ((err = xcb_request_check(xcb_connection, cookie)) != NULL) {
122         fprintf(stderr, "[%s:%d] ERROR: %s. X Error Code: %d\n", __FILE__, line, err_msg, err->error_code);
123         return err->error_code;
124     }
125     return 0;
126 }
127
128 uint32_t get_sep_offset(struct status_block *block) {
129     if (!block->no_separator && block->sep_block_width > 0)
130         return block->sep_block_width / 2 + block->sep_block_width % 2;
131     return 0;
132 }
133
134 int get_tray_width(struct tc_head* trayclients) {
135     trayclient *trayclient;
136     int tray_width = 0;
137     TAILQ_FOREACH_REVERSE(trayclient, trayclients, tc_head, tailq) {
138         if (!trayclient->mapped)
139             continue;
140         tray_width += font.height + logical_px(2);
141     }
142     if (tray_width > 0)
143         tray_width += logical_px(tray_loff_px);
144     return tray_width;
145 }
146
147 /*
148  * Redraws the statusline to the buffer
149  *
150  */
151 void refresh_statusline(void) {
152     struct status_block *block;
153
154     uint32_t old_statusline_width = statusline_width;
155     statusline_width = 0;
156
157     /* Predict the text width of all blocks (in pixels). */
158     TAILQ_FOREACH(block, &statusline_head, blocks) {
159         if (i3string_get_num_bytes(block->full_text) == 0)
160             continue;
161
162         block->width = predict_text_width(block->full_text);
163
164         /* Compute offset and append for text aligment in min_width. */
165         if (block->min_width <= block->width) {
166             block->x_offset = 0;
167             block->x_append = 0;
168         } else {
169             uint32_t padding_width = block->min_width - block->width;
170             switch (block->align) {
171                 case ALIGN_LEFT:
172                     block->x_append = padding_width;
173                     break;
174                 case ALIGN_RIGHT:
175                     block->x_offset = padding_width;
176                     break;
177                 case ALIGN_CENTER:
178                     block->x_offset = padding_width / 2;
179                     block->x_append = padding_width / 2 + padding_width % 2;
180                     break;
181             }
182         }
183
184         /* If this is not the last block, add some pixels for a separator. */
185         if (TAILQ_NEXT(block, blocks) != NULL)
186             statusline_width += block->sep_block_width;
187
188         statusline_width += block->width + block->x_offset + block->x_append;
189     }
190
191     /* If the statusline is bigger than our screen we need to make sure that
192      * the pixmap provides enough space, so re-allocate if the width grew */
193     if (statusline_width > root_screen->width_in_pixels &&
194         statusline_width > old_statusline_width)
195         realloc_sl_buffer();
196
197     /* Clear the statusline pixmap. */
198     xcb_rectangle_t rect = {0, 0, MAX(root_screen->width_in_pixels, statusline_width), bar_height};
199     xcb_poly_fill_rectangle(xcb_connection, statusline_pm, statusline_clear, 1, &rect);
200
201     /* Draw the text of each block. */
202     uint32_t x = 0;
203     TAILQ_FOREACH(block, &statusline_head, blocks) {
204         if (i3string_get_num_bytes(block->full_text) == 0)
205             continue;
206         uint32_t fg_color;
207
208         /* If this block is urgent, draw it with the defined color and border. */
209         if (block->urgent) {
210             fg_color = colors.urgent_ws_fg;
211
212             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
213
214             /* Draw the background */
215             uint32_t bg_color = colors.urgent_ws_bg;
216             uint32_t bg_values[] = {bg_color, bg_color};
217             xcb_change_gc(xcb_connection, statusline_ctx, mask, bg_values);
218
219             /* The urgent background “overshoots” by 2 px so that the text that
220              * is printed onto it will not be look so cut off. */
221             xcb_rectangle_t bg_rect = {x - logical_px(2), logical_px(1), block->width + logical_px(4), bar_height - logical_px(2)};
222             xcb_poly_fill_rectangle(xcb_connection, statusline_pm, statusline_ctx, 1, &bg_rect);
223         } else {
224             fg_color = (block->color ? get_colorpixel(block->color) : colors.bar_fg);
225         }
226
227         set_font_colors(statusline_ctx, fg_color, colors.bar_bg);
228         draw_text(block->full_text, statusline_pm, statusline_ctx, x + block->x_offset, logical_px(ws_voff_px), block->width);
229         x += block->width + block->sep_block_width + block->x_offset + block->x_append;
230
231         uint32_t sep_offset = get_sep_offset(block);
232         if (TAILQ_NEXT(block, blocks) != NULL && sep_offset > 0) {
233             /* This is not the last block, draw a separator. */
234             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND | XCB_GC_LINE_WIDTH;
235             uint32_t values[] = {colors.sep_fg, colors.bar_bg, logical_px(1)};
236             xcb_change_gc(xcb_connection, statusline_ctx, mask, values);
237             xcb_poly_line(xcb_connection, XCB_COORD_MODE_ORIGIN, statusline_pm,
238                           statusline_ctx, 2,
239                           (xcb_point_t[]){{x - sep_offset, logical_px(sep_voff_px)},
240                                           {x - sep_offset, bar_height - logical_px(sep_voff_px)}});
241         }
242     }
243 }
244
245 /*
246  * Hides all bars (unmaps them)
247  *
248  */
249 void hide_bars(void) {
250     if ((config.hide_on_modifier == M_DOCK) || (config.hidden_state == S_SHOW && config.hide_on_modifier == M_HIDE)) {
251         return;
252     }
253
254     i3_output *walk;
255     SLIST_FOREACH(walk, outputs, slist) {
256         if (!walk->active) {
257             continue;
258         }
259         xcb_unmap_window(xcb_connection, walk->bar);
260     }
261     stop_child();
262 }
263
264 /*
265  * Unhides all bars (maps them)
266  *
267  */
268 void unhide_bars(void) {
269     if (config.hide_on_modifier != M_HIDE) {
270         return;
271     }
272
273     i3_output *walk;
274     xcb_void_cookie_t cookie;
275     uint32_t mask;
276     uint32_t values[5];
277
278     cont_child();
279
280     SLIST_FOREACH(walk, outputs, slist) {
281         if (walk->bar == XCB_NONE) {
282             continue;
283         }
284         mask = XCB_CONFIG_WINDOW_X |
285                XCB_CONFIG_WINDOW_Y |
286                XCB_CONFIG_WINDOW_WIDTH |
287                XCB_CONFIG_WINDOW_HEIGHT |
288                XCB_CONFIG_WINDOW_STACK_MODE;
289         values[0] = walk->rect.x;
290         if (config.position == POS_TOP)
291             values[1] = walk->rect.y;
292         else
293             values[1] = walk->rect.y + walk->rect.h - bar_height;
294         values[2] = walk->rect.w;
295         values[3] = bar_height;
296         values[4] = XCB_STACK_MODE_ABOVE;
297         DLOG("Reconfiguring window for output %s to %d,%d\n", walk->name, values[0], values[1]);
298         cookie = xcb_configure_window_checked(xcb_connection,
299                                               walk->bar,
300                                               mask,
301                                               values);
302
303         if (xcb_request_failed(cookie, "Could not reconfigure window")) {
304             exit(EXIT_FAILURE);
305         }
306         xcb_map_window(xcb_connection, walk->bar);
307     }
308 }
309
310 /*
311  * Parse the colors into a format that we can use
312  *
313  */
314 void init_colors(const struct xcb_color_strings_t *new_colors) {
315 #define PARSE_COLOR(name, def)                                                   \
316     do {                                                                         \
317         colors.name = get_colorpixel(new_colors->name ? new_colors->name : def); \
318     } while (0)
319     PARSE_COLOR(bar_fg, "#FFFFFF");
320     PARSE_COLOR(bar_bg, "#000000");
321     PARSE_COLOR(sep_fg, "#666666");
322     PARSE_COLOR(active_ws_fg, "#FFFFFF");
323     PARSE_COLOR(active_ws_bg, "#333333");
324     PARSE_COLOR(active_ws_border, "#333333");
325     PARSE_COLOR(inactive_ws_fg, "#888888");
326     PARSE_COLOR(inactive_ws_bg, "#222222");
327     PARSE_COLOR(inactive_ws_border, "#333333");
328     PARSE_COLOR(urgent_ws_fg, "#FFFFFF");
329     PARSE_COLOR(urgent_ws_bg, "#900000");
330     PARSE_COLOR(urgent_ws_border, "#2f343a");
331     PARSE_COLOR(focus_ws_fg, "#FFFFFF");
332     PARSE_COLOR(focus_ws_bg, "#285577");
333     PARSE_COLOR(focus_ws_border, "#4c7899");
334 #undef PARSE_COLOR
335
336     init_tray_colors();
337     xcb_flush(xcb_connection);
338 }
339
340 /*
341  * Handle a button-press-event (i.e. a mouse click on one of our bars).
342  * We determine, whether the click occured on a ws-button or if the scroll-
343  * wheel was used and change the workspace appropriately
344  *
345  */
346 void handle_button(xcb_button_press_event_t *event) {
347     /* Determine, which bar was clicked */
348     i3_output *walk;
349     xcb_window_t bar = event->event;
350     SLIST_FOREACH(walk, outputs, slist) {
351         if (walk->bar == bar) {
352             break;
353         }
354     }
355
356     if (walk == NULL) {
357         DLOG("Unknown bar clicked!\n");
358         return;
359     }
360
361     int32_t x = event->event_x >= 0 ? event->event_x : 0;
362     int32_t original_x = x;
363
364     DLOG("Got button %d\n", event->detail);
365
366     int workspace_width = 0;
367     i3_ws *cur_ws = NULL, *clicked_ws = NULL, *ws_walk;
368
369     TAILQ_FOREACH(ws_walk, walk->workspaces, tailq) {
370         int w = 2*logical_px(ws_hoff_px) + 2*logical_px(1) + ws_walk->name_width;
371         if (x >= workspace_width && x <= workspace_width + w)
372             clicked_ws = ws_walk;
373         if (ws_walk->visible)
374             cur_ws = ws_walk;
375         workspace_width += w;
376         if (TAILQ_NEXT(ws_walk, tailq) != NULL)
377             workspace_width += logical_px(ws_spacing_px);
378     }
379
380     if (x > workspace_width && child_want_click_events()) {
381         /* If the child asked for click events,
382          * check if a status block has been clicked. */
383         int tray_width = get_tray_width(walk->trayclients);
384         int block_x = 0, last_block_x;
385         int offset = walk->rect.w - statusline_width - tray_width - logical_px(sb_hoff_px);
386
387         x = original_x - offset;
388         if (x >= 0) {
389             struct status_block *block;
390             int sep_offset_remainder = 0;
391
392             TAILQ_FOREACH(block, &statusline_head, blocks) {
393                 if (i3string_get_num_bytes(block->full_text) == 0)
394                     continue;
395
396                 last_block_x = block_x;
397                 block_x += block->width + block->x_offset + block->x_append + get_sep_offset(block) + sep_offset_remainder;
398
399                 if (x <= block_x && x >= last_block_x) {
400                     send_block_clicked(event->detail, block->name, block->instance, event->root_x, event->root_y);
401                     return;
402                 }
403
404                 sep_offset_remainder = block->sep_block_width - get_sep_offset(block);
405             }
406         }
407         x = original_x;
408     }
409
410     if (cur_ws == NULL) {
411         DLOG("No workspace active?\n");
412         return;
413     }
414
415     switch (event->detail) {
416         case 4:
417             /* Mouse wheel up. We select the previous ws, if any.
418              * If there is no more workspace, don’t even send the workspace
419              * command, otherwise (with workspace auto_back_and_forth) we’d end
420              * up on the wrong workspace. */
421
422             /* If `wheel_up_cmd [COMMAND]` was specified, it should override
423              * the default behavior */
424             if (config.wheel_up_cmd) {
425                 i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, config.wheel_up_cmd);
426                 return;
427             }
428
429             if (cur_ws == TAILQ_FIRST(walk->workspaces))
430                 return;
431
432             cur_ws = TAILQ_PREV(cur_ws, ws_head, tailq);
433             break;
434         case 5:
435             /* Mouse wheel down. We select the next ws, if any.
436              * If there is no more workspace, don’t even send the workspace
437              * command, otherwise (with workspace auto_back_and_forth) we’d end
438              * up on the wrong workspace. */
439
440             /* if `wheel_down_cmd [COMMAND]` was specified, it should override
441              * the default behavior */
442             if (config.wheel_down_cmd) {
443                 i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, config.wheel_down_cmd);
444                 return;
445             }
446
447             if (cur_ws == TAILQ_LAST(walk->workspaces, ws_head))
448                 return;
449
450             cur_ws = TAILQ_NEXT(cur_ws, tailq);
451             break;
452         case 1:
453             cur_ws = clicked_ws;
454
455             /* if no workspace was clicked, focus our currently visible
456              * workspace if it is not already focused */
457             if (cur_ws == NULL) {
458                 TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
459                     if (cur_ws->visible && !cur_ws->focused)
460                         break;
461                 }
462             }
463
464             /* if there is nothing to focus, we are done */
465             if (cur_ws == NULL)
466                 return;
467
468             break;
469         default:
470             return;
471     }
472
473     /* To properly handle workspace names with double quotes in them, we need
474      * to escape the double quotes. Unfortunately, that’s rather ugly in C: We
475      * first count the number of double quotes, then we allocate a large enough
476      * buffer, then we copy character by character. */
477     int num_quotes = 0;
478     size_t namelen = 0;
479     const char *utf8_name = cur_ws->canonical_name;
480     for (const char *walk = utf8_name; *walk != '\0'; walk++) {
481         if (*walk == '"')
482             num_quotes++;
483         /* While we’re looping through the name anyway, we can save one
484          * strlen(). */
485         namelen++;
486     }
487
488     const size_t len = namelen + strlen("workspace \"\"") + 1;
489     char *buffer = scalloc(len + num_quotes);
490     strncpy(buffer, "workspace \"", strlen("workspace \""));
491     size_t inpos, outpos;
492     for (inpos = 0, outpos = strlen("workspace \"");
493          inpos < namelen;
494          inpos++, outpos++) {
495         if (utf8_name[inpos] == '"') {
496             buffer[outpos] = '\\';
497             outpos++;
498         }
499         buffer[outpos] = utf8_name[inpos];
500     }
501     buffer[outpos] = '"';
502     i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
503     free(buffer);
504 }
505
506 /*
507  * Handle visibility notifications: when none of the bars are visible, e.g.
508  * if windows are in full-screen on each output, suspend the child process.
509  *
510  */
511 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
512     bool visible = (event->state != XCB_VISIBILITY_FULLY_OBSCURED);
513     int num_visible = 0;
514     i3_output *output;
515
516     SLIST_FOREACH(output, outputs, slist) {
517         if (!output->active) {
518             continue;
519         }
520         if (output->bar == event->window) {
521             if (output->visible == visible) {
522                 return;
523             }
524             output->visible = visible;
525         }
526         num_visible += output->visible;
527     }
528
529     if (num_visible == 0) {
530         stop_child();
531     } else if (num_visible == visible) {
532         /* Wake the child only when transitioning from 0 to 1 visible bar.
533          * We cannot transition from 0 to 2 or more visible bars at once since
534          * visibility events are delivered to each window separately */
535         cont_child();
536     }
537 }
538
539 /*
540  * Adjusts the size of the tray window and alignment of the tray clients by
541  * configuring their respective x coordinates. To be called when mapping or
542  * unmapping a tray client window.
543  *
544  */
545 static void configure_trayclients(void) {
546     trayclient *trayclient;
547     i3_output *output;
548     SLIST_FOREACH(output, outputs, slist) {
549         if (!output->active)
550             continue;
551
552         int clients = 0;
553         TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
554             if (!trayclient->mapped)
555                 continue;
556             clients++;
557
558             DLOG("Configuring tray window %08x to x=%d\n",
559                  trayclient->win, output->rect.w - (clients * (font.height + logical_px(2))));
560             uint32_t x = output->rect.w - (clients * (font.height + logical_px(2)));
561             xcb_configure_window(xcb_connection,
562                                  trayclient->win,
563                                  XCB_CONFIG_WINDOW_X,
564                                  &x);
565         }
566     }
567 }
568
569 /*
570  * Handles ClientMessages (messages sent from another client directly to us).
571  *
572  * At the moment, only the tray window will receive client messages. All
573  * supported client messages currently are _NET_SYSTEM_TRAY_OPCODE.
574  *
575  */
576 static void handle_client_message(xcb_client_message_event_t *event) {
577     if (event->type == atoms[_NET_SYSTEM_TRAY_OPCODE] &&
578         event->format == 32) {
579         DLOG("_NET_SYSTEM_TRAY_OPCODE received\n");
580         /* event->data.data32[0] is the timestamp */
581         uint32_t op = event->data.data32[1];
582         uint32_t mask;
583         uint32_t values[2];
584         if (op == SYSTEM_TRAY_REQUEST_DOCK) {
585             xcb_window_t client = event->data.data32[2];
586
587             /* Listen for PropertyNotify events to get the most recent value of
588              * the XEMBED_MAPPED atom, also listen for UnmapNotify events */
589             mask = XCB_CW_EVENT_MASK;
590             values[0] = XCB_EVENT_MASK_PROPERTY_CHANGE |
591                         XCB_EVENT_MASK_STRUCTURE_NOTIFY;
592             xcb_change_window_attributes(xcb_connection,
593                                          client,
594                                          mask,
595                                          values);
596
597             /* Request the _XEMBED_INFO property. The XEMBED specification
598              * (which is referred by the tray specification) says this *has* to
599              * be set, but VLC does not set it… */
600             bool map_it = true;
601             int xe_version = 1;
602             xcb_get_property_cookie_t xembedc;
603             xcb_generic_error_t *error;
604             xembedc = xcb_get_property(xcb_connection,
605                                        0,
606                                        client,
607                                        atoms[_XEMBED_INFO],
608                                        XCB_GET_PROPERTY_TYPE_ANY,
609                                        0,
610                                        2 * 32);
611
612             xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
613                                                                        xembedc,
614                                                                        &error);
615             if (error != NULL) {
616                 ELOG("Error getting _XEMBED_INFO property: error_code %d\n",
617                      error->error_code);
618                 free(error);
619                 return;
620             }
621             if (xembedr != NULL && xembedr->length != 0) {
622                 DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
623                 uint32_t *xembed = xcb_get_property_value(xembedr);
624                 DLOG("xembed version = %d\n", xembed[0]);
625                 DLOG("xembed flags = %d\n", xembed[1]);
626                 map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
627                 xe_version = xembed[0];
628                 if (xe_version > 1)
629                     xe_version = 1;
630                 free(xembedr);
631             } else {
632                 ELOG("Window %08x violates the XEMBED protocol, _XEMBED_INFO not set\n", client);
633             }
634
635             DLOG("X window %08x requested docking\n", client);
636             i3_output *walk, *output = NULL;
637             SLIST_FOREACH(walk, outputs, slist) {
638                 if (!walk->active)
639                     continue;
640                 if (config.tray_output) {
641                     if ((strcasecmp(walk->name, config.tray_output) != 0) &&
642                         (!walk->primary || strcasecmp("primary", config.tray_output) != 0))
643                         continue;
644                 }
645
646                 DLOG("using output %s\n", walk->name);
647                 output = walk;
648                 break;
649             }
650             /* In case of tray_output == primary and there is no primary output
651              * configured, we fall back to the first available output. */
652             if (output == NULL &&
653                 config.tray_output &&
654                 strcasecmp("primary", config.tray_output) == 0) {
655                 SLIST_FOREACH(walk, outputs, slist) {
656                     if (!walk->active)
657                         continue;
658                     DLOG("Falling back to output %s because no primary output is configured\n", walk->name);
659                     output = walk;
660                     break;
661                 }
662             }
663             if (output == NULL) {
664                 ELOG("No output found\n");
665                 return;
666             }
667             xcb_reparent_window(xcb_connection,
668                                 client,
669                                 output->bar,
670                                 output->rect.w - font.height - 2,
671                                 2);
672             /* We reconfigure the window to use a reasonable size. The systray
673              * specification explicitly says:
674              *   Tray icons may be assigned any size by the system tray, and
675              *   should do their best to cope with any size effectively
676              */
677             mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
678             values[0] = font.height;
679             values[1] = font.height;
680             xcb_configure_window(xcb_connection,
681                                  client,
682                                  mask,
683                                  values);
684
685             /* send the XEMBED_EMBEDDED_NOTIFY message */
686             void *event = scalloc(32);
687             xcb_client_message_event_t *ev = event;
688             ev->response_type = XCB_CLIENT_MESSAGE;
689             ev->window = client;
690             ev->type = atoms[_XEMBED];
691             ev->format = 32;
692             ev->data.data32[0] = XCB_CURRENT_TIME;
693             ev->data.data32[1] = atoms[XEMBED_EMBEDDED_NOTIFY];
694             ev->data.data32[2] = output->bar;
695             ev->data.data32[3] = xe_version;
696             xcb_send_event(xcb_connection,
697                            0,
698                            client,
699                            XCB_EVENT_MASK_NO_EVENT,
700                            (char *)ev);
701             free(event);
702
703             /* Put the client inside the save set. Upon termination (whether
704              * killed or normal exit does not matter) of i3bar, these clients
705              * will be correctly reparented to their most closest living
706              * ancestor. Without this, tray icons might die when i3bar
707              * exits/crashes. */
708             xcb_change_save_set(xcb_connection, XCB_SET_MODE_INSERT, client);
709
710             trayclient *tc = smalloc(sizeof(trayclient));
711             tc->win = client;
712             tc->xe_version = xe_version;
713             tc->mapped = false;
714             TAILQ_INSERT_TAIL(output->trayclients, tc, tailq);
715
716             if (map_it) {
717                 DLOG("Mapping dock client\n");
718                 xcb_map_window(xcb_connection, client);
719             } else {
720                 DLOG("Not mapping dock client yet\n");
721             }
722             /* Trigger an update to copy the statusline text to the appropriate
723              * position */
724             configure_trayclients();
725             draw_bars(false);
726         }
727     }
728 }
729
730 /*
731  * Handles DestroyNotify events by removing the tray client from the data
732  * structure. According to the XEmbed protocol, this is one way for a tray
733  * client to finish the protocol. After this event is received, there is no
734  * further interaction with the tray client.
735  *
736  * See: http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
737  *
738  */
739 static void handle_destroy_notify(xcb_destroy_notify_event_t *event) {
740     DLOG("DestroyNotify for window = %08x, event = %08x\n", event->window, event->event);
741
742     i3_output *walk;
743     SLIST_FOREACH(walk, outputs, slist) {
744         if (!walk->active)
745             continue;
746         DLOG("checking output %s\n", walk->name);
747         trayclient *trayclient;
748         TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
749             if (trayclient->win != event->window)
750                 continue;
751
752             DLOG("Removing tray client with window ID %08x\n", event->window);
753             TAILQ_REMOVE(walk->trayclients, trayclient, tailq);
754
755             /* Trigger an update, we now have more space for the statusline */
756             configure_trayclients();
757             draw_bars(false);
758             return;
759         }
760     }
761 }
762
763 /*
764  * Handles MapNotify events. These events happen when a tray client shows its
765  * window. We respond by realigning the tray clients.
766  *
767  */
768 static void handle_map_notify(xcb_map_notify_event_t *event) {
769     DLOG("MapNotify for window = %08x, event = %08x\n", event->window, event->event);
770
771     i3_output *walk;
772     SLIST_FOREACH(walk, outputs, slist) {
773         if (!walk->active)
774             continue;
775         DLOG("checking output %s\n", walk->name);
776         trayclient *trayclient;
777         TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
778             if (trayclient->win != event->window)
779                 continue;
780
781             DLOG("Tray client mapped (window ID %08x). Adjusting tray.\n", event->window);
782             trayclient->mapped = true;
783
784             /* Trigger an update, we now have more space for the statusline */
785             configure_trayclients();
786             draw_bars(false);
787             return;
788         }
789     }
790 }
791 /*
792  * Handles UnmapNotify events. These events happen when a tray client hides its
793  * window. We respond by realigning the tray clients.
794  *
795  */
796 static void handle_unmap_notify(xcb_unmap_notify_event_t *event) {
797     DLOG("UnmapNotify for window = %08x, event = %08x\n", event->window, event->event);
798
799     i3_output *walk;
800     SLIST_FOREACH(walk, outputs, slist) {
801         if (!walk->active)
802             continue;
803         DLOG("checking output %s\n", walk->name);
804         trayclient *trayclient;
805         TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
806             if (trayclient->win != event->window)
807                 continue;
808
809             DLOG("Tray client unmapped (window ID %08x). Adjusting tray.\n", event->window);
810             trayclient->mapped = false;
811
812             /* Trigger an update, we now have more space for the statusline */
813             configure_trayclients();
814             draw_bars(false);
815             return;
816         }
817     }
818 }
819
820 /*
821  * Handle PropertyNotify messages. Currently only the _XEMBED_INFO property is
822  * handled, which tells us whether a dock client should be mapped or unmapped.
823  *
824  */
825 static void handle_property_notify(xcb_property_notify_event_t *event) {
826     DLOG("PropertyNotify\n");
827     if (event->atom == atoms[_XEMBED_INFO] &&
828         event->state == XCB_PROPERTY_NEW_VALUE) {
829         DLOG("xembed_info updated\n");
830         trayclient *trayclient = NULL, *walk;
831         i3_output *o_walk;
832         SLIST_FOREACH(o_walk, outputs, slist) {
833             if (!o_walk->active)
834                 continue;
835
836             TAILQ_FOREACH(walk, o_walk->trayclients, tailq) {
837                 if (walk->win != event->window)
838                     continue;
839                 trayclient = walk;
840                 break;
841             }
842
843             if (trayclient)
844                 break;
845         }
846         if (!trayclient) {
847             ELOG("PropertyNotify received for unknown window %08x\n",
848                  event->window);
849             return;
850         }
851         xcb_get_property_cookie_t xembedc;
852         xembedc = xcb_get_property_unchecked(xcb_connection,
853                                              0,
854                                              trayclient->win,
855                                              atoms[_XEMBED_INFO],
856                                              XCB_GET_PROPERTY_TYPE_ANY,
857                                              0,
858                                              2 * 32);
859
860         xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
861                                                                    xembedc,
862                                                                    NULL);
863         if (xembedr == NULL || xembedr->length == 0) {
864             DLOG("xembed_info unset\n");
865             return;
866         }
867
868         DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
869         uint32_t *xembed = xcb_get_property_value(xembedr);
870         DLOG("xembed version = %d\n", xembed[0]);
871         DLOG("xembed flags = %d\n", xembed[1]);
872         bool map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
873         DLOG("map-state now %d\n", map_it);
874         if (trayclient->mapped && !map_it) {
875             /* need to unmap the window */
876             xcb_unmap_window(xcb_connection, trayclient->win);
877         } else if (!trayclient->mapped && map_it) {
878             /* need to map the window */
879             xcb_map_window(xcb_connection, trayclient->win);
880         }
881         free(xembedr);
882     }
883 }
884
885 /*
886  * Handle ConfigureRequests by denying them and sending the client a
887  * ConfigureNotify with its actual size.
888  *
889  */
890 static void handle_configure_request(xcb_configure_request_event_t *event) {
891     DLOG("ConfigureRequest for window = %08x\n", event->window);
892
893     trayclient *trayclient;
894     i3_output *output;
895     SLIST_FOREACH(output, outputs, slist) {
896         if (!output->active)
897             continue;
898
899         int clients = 0;
900         TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
901             if (!trayclient->mapped)
902                 continue;
903             clients++;
904
905             if (trayclient->win != event->window)
906                 continue;
907
908             xcb_rectangle_t rect;
909             rect.x = output->rect.w - (clients * (font.height + 2));
910             rect.y = 2;
911             rect.width = font.height;
912             rect.height = font.height;
913
914             DLOG("This is a tray window. x = %d\n", rect.x);
915             fake_configure_notify(xcb_connection, rect, event->window, 0);
916             return;
917         }
918     }
919
920     DLOG("WARNING: Could not find corresponding tray window.\n");
921 }
922
923 /*
924  * This function is called immediately before the main loop locks. We flush xcb
925  * then (and only then)
926  *
927  */
928 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revents) {
929     xcb_flush(xcb_connection);
930 }
931
932 /*
933  * This function is called immediately after the main loop locks, so when one
934  * of the watchers registered an event.
935  * We check whether an X-Event arrived and handle it.
936  *
937  */
938 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
939     xcb_generic_event_t *event;
940
941     if (xcb_connection_has_error(xcb_connection)) {
942         ELOG("X11 connection was closed unexpectedly - maybe your X server terminated / crashed?\n");
943         exit(1);
944     }
945
946     while ((event = xcb_poll_for_event(xcb_connection)) != NULL) {
947         int type = (event->response_type & ~0x80);
948
949         if (type == xkb_base && xkb_base > -1) {
950             DLOG("received an xkb event\n");
951
952             xcb_xkb_state_notify_event_t *state = (xcb_xkb_state_notify_event_t *)event;
953             if (state->xkbType == XCB_XKB_STATE_NOTIFY) {
954                 int modstate = state->mods & config.modifier;
955
956 #define DLOGMOD(modmask, status)                        \
957     do {                                                \
958         switch (modmask) {                              \
959             case ShiftMask:                             \
960                 DLOG("ShiftMask got " #status "!\n");   \
961                 break;                                  \
962             case ControlMask:                           \
963                 DLOG("ControlMask got " #status "!\n"); \
964                 break;                                  \
965             case Mod1Mask:                              \
966                 DLOG("Mod1Mask got " #status "!\n");    \
967                 break;                                  \
968             case Mod2Mask:                              \
969                 DLOG("Mod2Mask got " #status "!\n");    \
970                 break;                                  \
971             case Mod3Mask:                              \
972                 DLOG("Mod3Mask got " #status "!\n");    \
973                 break;                                  \
974             case Mod4Mask:                              \
975                 DLOG("Mod4Mask got " #status "!\n");    \
976                 break;                                  \
977             case Mod5Mask:                              \
978                 DLOG("Mod5Mask got " #status "!\n");    \
979                 break;                                  \
980         }                                               \
981     } while (0)
982
983                 if (modstate != mod_pressed) {
984                     if (modstate == 0) {
985                         DLOGMOD(config.modifier, released);
986                         if (!activated_mode)
987                             hide_bars();
988                     } else {
989                         DLOGMOD(config.modifier, pressed);
990                         activated_mode = false;
991                         unhide_bars();
992                     }
993                     mod_pressed = modstate;
994                 }
995 #undef DLOGMOD
996             }
997
998             free(event);
999             continue;
1000         }
1001
1002         switch (type) {
1003             case XCB_VISIBILITY_NOTIFY:
1004                 /* Visibility change: a bar is [un]obscured by other window */
1005                 handle_visibility_notify((xcb_visibility_notify_event_t *)event);
1006                 break;
1007             case XCB_EXPOSE:
1008                 /* Expose-events happen, when the window needs to be redrawn */
1009                 redraw_bars();
1010                 break;
1011             case XCB_BUTTON_PRESS:
1012                 /* Button-press-events are mouse-buttons clicked on one of our bars */
1013                 handle_button((xcb_button_press_event_t *)event);
1014                 break;
1015             case XCB_CLIENT_MESSAGE:
1016                 /* Client messages are used for client-to-client communication, for
1017                  * example system tray widgets talk to us directly via client messages. */
1018                 handle_client_message((xcb_client_message_event_t *)event);
1019                 break;
1020             case XCB_DESTROY_NOTIFY:
1021                 /* DestroyNotify signifies the end of the XEmbed protocol */
1022                 handle_destroy_notify((xcb_destroy_notify_event_t *)event);
1023                 break;
1024             case XCB_UNMAP_NOTIFY:
1025                 /* UnmapNotify is received when a tray client hides its window. */
1026                 handle_unmap_notify((xcb_unmap_notify_event_t *)event);
1027                 break;
1028             case XCB_MAP_NOTIFY:
1029                 handle_map_notify((xcb_map_notify_event_t *)event);
1030                 break;
1031             case XCB_PROPERTY_NOTIFY:
1032                 /* PropertyNotify */
1033                 handle_property_notify((xcb_property_notify_event_t *)event);
1034                 break;
1035             case XCB_CONFIGURE_REQUEST:
1036                 /* ConfigureRequest, sent by a tray child */
1037                 handle_configure_request((xcb_configure_request_event_t *)event);
1038                 break;
1039         }
1040         free(event);
1041     }
1042 }
1043
1044 /*
1045  * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
1046  * are triggered
1047  *
1048  */
1049 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
1050 }
1051
1052 /*
1053  * Early initialization of the connection to X11: Everything which does not
1054  * depend on 'config'.
1055  *
1056  */
1057 char *init_xcb_early() {
1058     /* FIXME: xcb_connect leaks Memory */
1059     xcb_connection = xcb_connect(NULL, &screen);
1060     if (xcb_connection_has_error(xcb_connection)) {
1061         ELOG("Cannot open display\n");
1062         exit(EXIT_FAILURE);
1063     }
1064     conn = xcb_connection;
1065     DLOG("Connected to xcb\n");
1066
1067 /* We have to request the atoms we need */
1068 #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
1069 #include "xcb_atoms.def"
1070
1071     root_screen = xcb_aux_get_screen(xcb_connection, screen);
1072     xcb_root = root_screen->root;
1073
1074     /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
1075      * this way, we can choose to crop it */
1076     uint32_t mask = XCB_GC_FOREGROUND;
1077     uint32_t vals[] = {colors.bar_bg, colors.bar_bg};
1078
1079     statusline_clear = xcb_generate_id(xcb_connection);
1080     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1081                                                                statusline_clear,
1082                                                                xcb_root,
1083                                                                mask,
1084                                                                vals);
1085
1086     statusline_ctx = xcb_generate_id(xcb_connection);
1087     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1088                                                             statusline_ctx,
1089                                                             xcb_root,
1090                                                             0,
1091                                                             NULL);
1092
1093     statusline_pm = xcb_generate_id(xcb_connection);
1094     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1095                                                                root_screen->root_depth,
1096                                                                statusline_pm,
1097                                                                xcb_root,
1098                                                                root_screen->width_in_pixels,
1099                                                                root_screen->height_in_pixels);
1100
1101     /* The various Watchers to communicate with xcb */
1102     xcb_io = smalloc(sizeof(ev_io));
1103     xcb_prep = smalloc(sizeof(ev_prepare));
1104     xcb_chk = smalloc(sizeof(ev_check));
1105
1106     ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
1107     ev_prepare_init(xcb_prep, &xcb_prep_cb);
1108     ev_check_init(xcb_chk, &xcb_chk_cb);
1109
1110     ev_io_start(main_loop, xcb_io);
1111     ev_prepare_start(main_loop, xcb_prep);
1112     ev_check_start(main_loop, xcb_chk);
1113
1114     /* Now we get the atoms and save them in a nice data structure */
1115     get_atoms();
1116
1117     char *path = root_atom_contents("I3_SOCKET_PATH", xcb_connection, screen);
1118
1119     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
1120         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
1121         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
1122         exit(EXIT_FAILURE);
1123     }
1124
1125     return path;
1126 }
1127
1128 /*
1129  * Register for xkb keyevents. To grab modifiers without blocking other applications from receiving key-events
1130  * involving that modifier, we sadly have to use xkb which is not yet fully supported
1131  * in xcb.
1132  *
1133  */
1134 void register_xkb_keyevents() {
1135     const xcb_query_extension_reply_t *extreply;
1136     extreply = xcb_get_extension_data(conn, &xcb_xkb_id);
1137     if (!extreply->present) {
1138         ELOG("xkb is not present on this server\n");
1139         exit(EXIT_FAILURE);
1140     }
1141     DLOG("initializing xcb-xkb\n");
1142     xcb_xkb_use_extension(conn, XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION);
1143     xcb_xkb_select_events(conn,
1144                           XCB_XKB_ID_USE_CORE_KBD,
1145                           XCB_XKB_EVENT_TYPE_STATE_NOTIFY,
1146                           0,
1147                           XCB_XKB_EVENT_TYPE_STATE_NOTIFY,
1148                           0xff,
1149                           0xff,
1150                           NULL);
1151     xkb_base = extreply->first_event;
1152 }
1153
1154 /*
1155  * Deregister from xkb keyevents.
1156  *
1157  */
1158 void deregister_xkb_keyevents() {
1159     xcb_xkb_select_events(conn,
1160                           XCB_XKB_ID_USE_CORE_KBD,
1161                           0,
1162                           0,
1163                           0,
1164                           0xff,
1165                           0xff,
1166                           NULL);
1167 }
1168
1169 /*
1170  * Initialization which depends on 'config' being usable. Called after the
1171  * configuration has arrived.
1172  *
1173  */
1174 void init_xcb_late(char *fontname) {
1175     if (fontname == NULL)
1176         fontname = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
1177
1178     /* Load the font */
1179     font = load_font(fontname, true);
1180     set_font(&font);
1181     DLOG("Calculated font height: %d\n", font.height);
1182     bar_height = font.height + 2*logical_px(ws_voff_px);
1183
1184     xcb_flush(xcb_connection);
1185
1186     if (config.hide_on_modifier == M_HIDE)
1187         register_xkb_keyevents();
1188 }
1189
1190 /*
1191  * Inform clients waiting for a new _NET_SYSTEM_TRAY that we took the
1192  * selection.
1193  *
1194  */
1195 static void send_tray_clientmessage(void) {
1196     uint8_t buffer[32] = {0};
1197     xcb_client_message_event_t *ev = (xcb_client_message_event_t *)buffer;
1198
1199     ev->response_type = XCB_CLIENT_MESSAGE;
1200     ev->window = xcb_root;
1201     ev->type = atoms[MANAGER];
1202     ev->format = 32;
1203     ev->data.data32[0] = XCB_CURRENT_TIME;
1204     ev->data.data32[1] = tray_reply->atom;
1205     ev->data.data32[2] = selwin;
1206
1207     xcb_send_event(xcb_connection,
1208                    0,
1209                    xcb_root,
1210                    0xFFFFFF,
1211                    (char *)buffer);
1212 }
1213
1214 /*
1215  * Initializes tray support by requesting the appropriate _NET_SYSTEM_TRAY atom
1216  * for the X11 display we are running on, then acquiring the selection for this
1217  * atom. Afterwards, tray clients will send ClientMessages to our window.
1218  *
1219  */
1220 void init_tray(void) {
1221     DLOG("Initializing system tray functionality\n");
1222     /* request the tray manager atom for the X11 display we are running on */
1223     char atomname[strlen("_NET_SYSTEM_TRAY_S") + 11];
1224     snprintf(atomname, strlen("_NET_SYSTEM_TRAY_S") + 11, "_NET_SYSTEM_TRAY_S%d", screen);
1225     xcb_intern_atom_cookie_t tray_cookie;
1226     if (tray_reply == NULL)
1227         tray_cookie = xcb_intern_atom(xcb_connection, 0, strlen(atomname), atomname);
1228
1229     /* tray support: we need a window to own the selection */
1230     selwin = xcb_generate_id(xcb_connection);
1231     uint32_t selmask = XCB_CW_OVERRIDE_REDIRECT;
1232     uint32_t selval[] = {1};
1233     xcb_create_window(xcb_connection,
1234                       root_screen->root_depth,
1235                       selwin,
1236                       xcb_root,
1237                       -1, -1,
1238                       1, 1,
1239                       0,
1240                       XCB_WINDOW_CLASS_INPUT_OUTPUT,
1241                       root_screen->root_visual,
1242                       selmask,
1243                       selval);
1244
1245     uint32_t orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
1246     /* set the atoms */
1247     xcb_change_property(xcb_connection,
1248                         XCB_PROP_MODE_REPLACE,
1249                         selwin,
1250                         atoms[_NET_SYSTEM_TRAY_ORIENTATION],
1251                         XCB_ATOM_CARDINAL,
1252                         32,
1253                         1,
1254                         &orientation);
1255
1256     init_tray_colors();
1257
1258     if (tray_reply == NULL) {
1259         if (!(tray_reply = xcb_intern_atom_reply(xcb_connection, tray_cookie, NULL))) {
1260             ELOG("Could not get atom %s\n", atomname);
1261             exit(EXIT_FAILURE);
1262         }
1263     }
1264
1265     xcb_set_selection_owner(xcb_connection,
1266                             selwin,
1267                             tray_reply->atom,
1268                             XCB_CURRENT_TIME);
1269
1270     /* Verify that we have the selection */
1271     xcb_get_selection_owner_cookie_t selcookie;
1272     xcb_get_selection_owner_reply_t *selreply;
1273
1274     selcookie = xcb_get_selection_owner(xcb_connection, tray_reply->atom);
1275     if (!(selreply = xcb_get_selection_owner_reply(xcb_connection, selcookie, NULL))) {
1276         ELOG("Could not get selection owner for %s\n", atomname);
1277         exit(EXIT_FAILURE);
1278     }
1279
1280     if (selreply->owner != selwin) {
1281         ELOG("Could not set the %s selection. "
1282              "Maybe another tray is already running?\n",
1283              atomname);
1284         /* NOTE that this error is not fatal. We just can’t provide tray
1285          * functionality */
1286         free(selreply);
1287         return;
1288     }
1289
1290     send_tray_clientmessage();
1291 }
1292
1293 /*
1294  * We need to set the _NET_SYSTEM_TRAY_COLORS atom on the tray selection window
1295  * to make GTK+ 3 applets with Symbolic Icons visible. If the colors are unset,
1296  * they assume a light background.
1297  * See also https://bugzilla.gnome.org/show_bug.cgi?id=679591
1298  *
1299  */
1300 void init_tray_colors(void) {
1301     /* Convert colors.bar_fg (#rrggbb) to 16-bit RGB */
1302     const char *bar_fg = (config.colors.bar_fg ? config.colors.bar_fg : "#FFFFFF");
1303
1304     DLOG("Setting bar_fg = %s as _NET_SYSTEM_TRAY_COLORS\n", bar_fg);
1305
1306     char strgroups[3][3] = {{bar_fg[1], bar_fg[2], '\0'},
1307                             {bar_fg[3], bar_fg[4], '\0'},
1308                             {bar_fg[5], bar_fg[6], '\0'}};
1309     const uint8_t r = strtol(strgroups[0], NULL, 16);
1310     const uint8_t g = strtol(strgroups[1], NULL, 16);
1311     const uint8_t b = strtol(strgroups[2], NULL, 16);
1312
1313     const uint16_t r16 = ((uint16_t)r << 8) | r;
1314     const uint16_t g16 = ((uint16_t)g << 8) | g;
1315     const uint16_t b16 = ((uint16_t)b << 8) | b;
1316
1317     const uint32_t tray_colors[12] = {
1318         r16, g16, b16, /* foreground color */
1319         r16, g16, b16, /* error color */
1320         r16, g16, b16, /* warning color */
1321         r16, g16, b16, /* success color */
1322     };
1323
1324     xcb_change_property(xcb_connection,
1325                         XCB_PROP_MODE_REPLACE,
1326                         selwin,
1327                         atoms[_NET_SYSTEM_TRAY_COLORS],
1328                         XCB_ATOM_CARDINAL,
1329                         32,
1330                         12,
1331                         tray_colors);
1332 }
1333
1334 /*
1335  * Cleanup the xcb-stuff.
1336  * Called once, before the program terminates.
1337  *
1338  */
1339 void clean_xcb(void) {
1340     i3_output *o_walk;
1341     free_workspaces();
1342     SLIST_FOREACH(o_walk, outputs, slist) {
1343         destroy_window(o_walk);
1344         FREE(o_walk->trayclients);
1345         FREE(o_walk->workspaces);
1346         FREE(o_walk->name);
1347     }
1348     FREE_SLIST(outputs, i3_output);
1349     FREE(outputs);
1350
1351     xcb_flush(xcb_connection);
1352     xcb_aux_sync(xcb_connection);
1353     xcb_disconnect(xcb_connection);
1354
1355     ev_check_stop(main_loop, xcb_chk);
1356     ev_prepare_stop(main_loop, xcb_prep);
1357     ev_io_stop(main_loop, xcb_io);
1358
1359     FREE(xcb_chk);
1360     FREE(xcb_prep);
1361     FREE(xcb_io);
1362 }
1363
1364 /*
1365  * Get the earlier requested atoms and save them in the prepared data structure
1366  *
1367  */
1368 void get_atoms(void) {
1369     xcb_intern_atom_reply_t *reply;
1370 #define ATOM_DO(name)                                                        \
1371     reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
1372     if (reply == NULL) {                                                     \
1373         ELOG("Could not get atom %s\n", #name);                              \
1374         exit(EXIT_FAILURE);                                                  \
1375     }                                                                        \
1376     atoms[name] = reply->atom;                                               \
1377     free(reply);
1378
1379 #include "xcb_atoms.def"
1380     DLOG("Got atoms\n");
1381 }
1382
1383 /*
1384  * Reparents all tray clients of the specified output to the root window. This
1385  * is either used when shutting down, when an output appears (xrandr --output
1386  * VGA1 --off) or when the primary output changes.
1387  *
1388  * Applications using the tray will start the protocol from the beginning again
1389  * afterwards.
1390  *
1391  */
1392 void kick_tray_clients(i3_output *output) {
1393     if (TAILQ_EMPTY(output->trayclients))
1394         return;
1395
1396     trayclient *trayclient;
1397     while (!TAILQ_EMPTY(output->trayclients)) {
1398         trayclient = TAILQ_FIRST(output->trayclients);
1399         /* Unmap, then reparent (to root) the tray client windows */
1400         xcb_unmap_window(xcb_connection, trayclient->win);
1401         xcb_reparent_window(xcb_connection,
1402                             trayclient->win,
1403                             xcb_root,
1404                             0,
1405                             0);
1406
1407         /* We remove the trayclient right here. We might receive an UnmapNotify
1408          * event afterwards, but better safe than sorry. */
1409         TAILQ_REMOVE(output->trayclients, trayclient, tailq);
1410     }
1411
1412     /* Fake a DestroyNotify so that Qt re-adds tray icons.
1413      * We cannot actually destroy the window because then Qt will not restore
1414      * its event mask on the new window. */
1415     uint8_t buffer[32] = {0};
1416     xcb_destroy_notify_event_t *event = (xcb_destroy_notify_event_t *)buffer;
1417
1418     event->response_type = XCB_DESTROY_NOTIFY;
1419     event->event = selwin;
1420     event->window = selwin;
1421
1422     xcb_send_event(conn, false, selwin, XCB_EVENT_MASK_STRUCTURE_NOTIFY, (char *)event);
1423
1424     send_tray_clientmessage();
1425 }
1426
1427 /*
1428  * Destroy the bar of the specified output
1429  *
1430  */
1431 void destroy_window(i3_output *output) {
1432     if (output == NULL) {
1433         return;
1434     }
1435     if (output->bar == XCB_NONE) {
1436         return;
1437     }
1438
1439     kick_tray_clients(output);
1440     xcb_destroy_window(xcb_connection, output->bar);
1441     output->bar = XCB_NONE;
1442 }
1443
1444 /*
1445  * Reallocate the statusline-buffer
1446  *
1447  */
1448 void realloc_sl_buffer(void) {
1449     DLOG("Re-allocating statusline-buffer, statusline_width = %d, root_screen->width_in_pixels = %d\n",
1450          statusline_width, root_screen->width_in_pixels);
1451     xcb_free_pixmap(xcb_connection, statusline_pm);
1452     statusline_pm = xcb_generate_id(xcb_connection);
1453     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1454                                                                root_screen->root_depth,
1455                                                                statusline_pm,
1456                                                                xcb_root,
1457                                                                MAX(root_screen->width_in_pixels, statusline_width),
1458                                                                bar_height);
1459
1460     uint32_t mask = XCB_GC_FOREGROUND;
1461     uint32_t vals[2] = {colors.bar_bg, colors.bar_bg};
1462     xcb_free_gc(xcb_connection, statusline_clear);
1463     statusline_clear = xcb_generate_id(xcb_connection);
1464     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1465                                                                statusline_clear,
1466                                                                xcb_root,
1467                                                                mask,
1468                                                                vals);
1469
1470     mask |= XCB_GC_BACKGROUND;
1471     vals[0] = colors.bar_fg;
1472     xcb_free_gc(xcb_connection, statusline_ctx);
1473     statusline_ctx = xcb_generate_id(xcb_connection);
1474     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1475                                                             statusline_ctx,
1476                                                             xcb_root,
1477                                                             mask,
1478                                                             vals);
1479
1480     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
1481         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
1482         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
1483         exit(EXIT_FAILURE);
1484     }
1485 }
1486
1487 /*
1488  * Reconfigure all bars and create new bars for recently activated outputs
1489  *
1490  */
1491 void reconfig_windows(bool redraw_bars) {
1492     uint32_t mask;
1493     uint32_t values[5];
1494     static bool tray_configured = false;
1495
1496     i3_output *walk;
1497     SLIST_FOREACH(walk, outputs, slist) {
1498         if (!walk->active) {
1499             /* If an output is not active, we destroy its bar */
1500             /* FIXME: Maybe we rather want to unmap? */
1501             DLOG("Destroying window for output %s\n", walk->name);
1502             destroy_window(walk);
1503             continue;
1504         }
1505         if (walk->bar == XCB_NONE) {
1506             DLOG("Creating window for output %s\n", walk->name);
1507
1508             walk->bar = xcb_generate_id(xcb_connection);
1509             walk->buffer = xcb_generate_id(xcb_connection);
1510             mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
1511             /* Black background */
1512             values[0] = colors.bar_bg;
1513             /* If hide_on_modifier is set to hide or invisible mode, i3 is not supposed to manage our bar-windows */
1514             values[1] = (config.hide_on_modifier == M_DOCK ? 0 : 1);
1515             /* We enable the following EventMask fields:
1516              * EXPOSURE, to get expose events (we have to re-draw then)
1517              * SUBSTRUCTURE_REDIRECT, to get ConfigureRequests when the tray
1518              *                        child windows use ConfigureWindow
1519              * BUTTON_PRESS, to handle clicks on the workspace buttons
1520              * */
1521             values[2] = XCB_EVENT_MASK_EXPOSURE |
1522                         XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
1523                         XCB_EVENT_MASK_BUTTON_PRESS;
1524             if (config.hide_on_modifier == M_DOCK) {
1525                 /* If the bar is normally visible, catch visibility change events to suspend
1526                  * the status process when the bar is obscured by full-screened windows.  */
1527                 values[2] |= XCB_EVENT_MASK_VISIBILITY_CHANGE;
1528                 walk->visible = true;
1529             }
1530             xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
1531                                                                      root_screen->root_depth,
1532                                                                      walk->bar,
1533                                                                      xcb_root,
1534                                                                      walk->rect.x, walk->rect.y + walk->rect.h - bar_height,
1535                                                                      walk->rect.w, bar_height,
1536                                                                      0,
1537                                                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,
1538                                                                      root_screen->root_visual,
1539                                                                      mask,
1540                                                                      values);
1541
1542             /* The double-buffer we use to render stuff off-screen */
1543             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1544                                                                     root_screen->root_depth,
1545                                                                     walk->buffer,
1546                                                                     walk->bar,
1547                                                                     walk->rect.w,
1548                                                                     bar_height);
1549
1550             /* Set the WM_CLASS and WM_NAME (we don't need UTF-8) atoms */
1551             xcb_void_cookie_t class_cookie;
1552             class_cookie = xcb_change_property(xcb_connection,
1553                                                XCB_PROP_MODE_REPLACE,
1554                                                walk->bar,
1555                                                XCB_ATOM_WM_CLASS,
1556                                                XCB_ATOM_STRING,
1557                                                8,
1558                                                (strlen("i3bar") + 1) * 2,
1559                                                "i3bar\0i3bar\0");
1560
1561             char *name;
1562             if (asprintf(&name, "i3bar for output %s", walk->name) == -1)
1563                 err(EXIT_FAILURE, "asprintf()");
1564             xcb_void_cookie_t name_cookie;
1565             name_cookie = xcb_change_property(xcb_connection,
1566                                               XCB_PROP_MODE_REPLACE,
1567                                               walk->bar,
1568                                               XCB_ATOM_WM_NAME,
1569                                               XCB_ATOM_STRING,
1570                                               8,
1571                                               strlen(name),
1572                                               name);
1573             free(name);
1574
1575             /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
1576              * this one */
1577             xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
1578                                                                 XCB_PROP_MODE_REPLACE,
1579                                                                 walk->bar,
1580                                                                 atoms[_NET_WM_WINDOW_TYPE],
1581                                                                 XCB_ATOM_ATOM,
1582                                                                 32,
1583                                                                 1,
1584                                                                 (unsigned char *)&atoms[_NET_WM_WINDOW_TYPE_DOCK]);
1585
1586             /* We need to tell i3, where to reserve space for i3bar */
1587             /* left, right, top, bottom, left_start_y, left_end_y,
1588              * right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x,
1589              * bottom_end_x */
1590             /* A local struct to save the strut_partial property */
1591             struct {
1592                 uint32_t left;
1593                 uint32_t right;
1594                 uint32_t top;
1595                 uint32_t bottom;
1596                 uint32_t left_start_y;
1597                 uint32_t left_end_y;
1598                 uint32_t right_start_y;
1599                 uint32_t right_end_y;
1600                 uint32_t top_start_x;
1601                 uint32_t top_end_x;
1602                 uint32_t bottom_start_x;
1603                 uint32_t bottom_end_x;
1604             } __attribute__((__packed__)) strut_partial;
1605             memset(&strut_partial, 0, sizeof(strut_partial));
1606
1607             switch (config.position) {
1608                 case POS_NONE:
1609                     break;
1610                 case POS_TOP:
1611                     strut_partial.top = bar_height;
1612                     strut_partial.top_start_x = walk->rect.x;
1613                     strut_partial.top_end_x = walk->rect.x + walk->rect.w;
1614                     break;
1615                 case POS_BOT:
1616                     strut_partial.bottom = bar_height;
1617                     strut_partial.bottom_start_x = walk->rect.x;
1618                     strut_partial.bottom_end_x = walk->rect.x + walk->rect.w;
1619                     break;
1620             }
1621             xcb_void_cookie_t strut_cookie = xcb_change_property(xcb_connection,
1622                                                                  XCB_PROP_MODE_REPLACE,
1623                                                                  walk->bar,
1624                                                                  atoms[_NET_WM_STRUT_PARTIAL],
1625                                                                  XCB_ATOM_CARDINAL,
1626                                                                  32,
1627                                                                  12,
1628                                                                  &strut_partial);
1629
1630             /* We also want a graphics-context for the bars (it defines the properties
1631              * with which we draw to them) */
1632             walk->bargc = xcb_generate_id(xcb_connection);
1633             xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
1634                                                                 walk->bargc,
1635                                                                 walk->bar,
1636                                                                 0,
1637                                                                 NULL);
1638
1639             /* We finally map the bar (display it on screen), unless the modifier-switch is on */
1640             xcb_void_cookie_t map_cookie;
1641             if (config.hide_on_modifier == M_DOCK) {
1642                 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
1643             }
1644
1645             if (xcb_request_failed(win_cookie, "Could not create window") ||
1646                 xcb_request_failed(pm_cookie, "Could not create pixmap") ||
1647                 xcb_request_failed(dock_cookie, "Could not set dock mode") ||
1648                 xcb_request_failed(class_cookie, "Could not set WM_CLASS") ||
1649                 xcb_request_failed(name_cookie, "Could not set WM_NAME") ||
1650                 xcb_request_failed(strut_cookie, "Could not set strut") ||
1651                 xcb_request_failed(gc_cookie, "Could not create graphical context") ||
1652                 ((config.hide_on_modifier == M_DOCK) && xcb_request_failed(map_cookie, "Could not map window"))) {
1653                 exit(EXIT_FAILURE);
1654             }
1655
1656             const char *tray_output = (config.tray_output ? config.tray_output : SLIST_FIRST(outputs)->name);
1657             if (!tray_configured && strcasecmp(tray_output, "none") != 0) {
1658                 /* Configuration sanity check: ensure this i3bar instance handles the output on
1659                  * which the tray should appear (e.g. don’t initialize a tray if tray_output ==
1660                  * VGA-1 but output == [HDMI-1]).
1661                  */
1662                 i3_output *output;
1663                 SLIST_FOREACH(output, outputs, slist) {
1664                     if (strcasecmp(output->name, tray_output) == 0 ||
1665                         (strcasecmp(tray_output, "primary") == 0 && output->primary)) {
1666                         init_tray();
1667                         break;
1668                     }
1669                 }
1670                 tray_configured = true;
1671             }
1672         } else {
1673             /* We already have a bar, so we just reconfigure it */
1674             mask = XCB_CONFIG_WINDOW_X |
1675                    XCB_CONFIG_WINDOW_Y |
1676                    XCB_CONFIG_WINDOW_WIDTH |
1677                    XCB_CONFIG_WINDOW_HEIGHT |
1678                    XCB_CONFIG_WINDOW_STACK_MODE;
1679             values[0] = walk->rect.x;
1680             values[1] = walk->rect.y + walk->rect.h - bar_height;
1681             values[2] = walk->rect.w;
1682             values[3] = bar_height;
1683             values[4] = XCB_STACK_MODE_ABOVE;
1684
1685             DLOG("Destroying buffer for output %s\n", walk->name);
1686             xcb_free_pixmap(xcb_connection, walk->buffer);
1687
1688             DLOG("Reconfiguring window for output %s to %d,%d\n", walk->name, values[0], values[1]);
1689             xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
1690                                                                         walk->bar,
1691                                                                         mask,
1692                                                                         values);
1693
1694             mask = XCB_CW_OVERRIDE_REDIRECT;
1695             values[0] = (config.hide_on_modifier == M_DOCK ? 0 : 1);
1696             DLOG("Changing window attribute override_redirect for output %s to %d\n", walk->name, values[0]);
1697             xcb_void_cookie_t chg_cookie = xcb_change_window_attributes(xcb_connection,
1698                                                                         walk->bar,
1699                                                                         mask,
1700                                                                         values);
1701
1702             DLOG("Recreating buffer for output %s\n", walk->name);
1703             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1704                                                                     root_screen->root_depth,
1705                                                                     walk->buffer,
1706                                                                     walk->bar,
1707                                                                     walk->rect.w,
1708                                                                     bar_height);
1709
1710             xcb_void_cookie_t map_cookie, umap_cookie;
1711             if (redraw_bars) {
1712                 /* Unmap the window, and draw it again when in dock mode */
1713                 umap_cookie = xcb_unmap_window_checked(xcb_connection, walk->bar);
1714                 if (config.hide_on_modifier == M_DOCK) {
1715                     cont_child();
1716                     map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
1717                 } else {
1718                     stop_child();
1719                 }
1720
1721                 if (config.hide_on_modifier == M_HIDE) {
1722                     /* Switching to hide mode, register for keyevents */
1723                     register_xkb_keyevents();
1724                 } else {
1725                     /* Switching to dock/invisible mode, deregister from keyevents */
1726                     deregister_xkb_keyevents();
1727                 }
1728             }
1729
1730             if (xcb_request_failed(cfg_cookie, "Could not reconfigure window") ||
1731                 xcb_request_failed(chg_cookie, "Could not change window") ||
1732                 xcb_request_failed(pm_cookie, "Could not create pixmap") ||
1733                 (redraw_bars && (xcb_request_failed(umap_cookie, "Could not unmap window") ||
1734                                  (config.hide_on_modifier == M_DOCK && xcb_request_failed(map_cookie, "Could not map window"))))) {
1735                 exit(EXIT_FAILURE);
1736             }
1737         }
1738     }
1739 }
1740
1741 /*
1742  * Render the bars, with buttons and statusline
1743  *
1744  */
1745 void draw_bars(bool unhide) {
1746     DLOG("Drawing bars...\n");
1747     int workspace_width = 0;
1748
1749     refresh_statusline();
1750
1751     i3_output *outputs_walk;
1752     SLIST_FOREACH(outputs_walk, outputs, slist) {
1753         if (!outputs_walk->active) {
1754             DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
1755             continue;
1756         }
1757         if (outputs_walk->bar == XCB_NONE) {
1758             /* Oh shit, an active output without an own bar. Create it now! */
1759             reconfig_windows(false);
1760         }
1761         /* First things first: clear the backbuffer */
1762         uint32_t color = colors.bar_bg;
1763         xcb_change_gc(xcb_connection,
1764                       outputs_walk->bargc,
1765                       XCB_GC_FOREGROUND,
1766                       &color);
1767         xcb_rectangle_t rect = {0, 0, outputs_walk->rect.w, bar_height};
1768         xcb_poly_fill_rectangle(xcb_connection,
1769                                 outputs_walk->buffer,
1770                                 outputs_walk->bargc,
1771                                 1,
1772                                 &rect);
1773
1774         if (!config.disable_ws) {
1775             i3_ws *ws_walk;
1776             TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
1777                 DLOG("Drawing button for WS %s at x = %d, len = %d\n",
1778                      i3string_as_utf8(ws_walk->name), workspace_width, ws_walk->name_width);
1779                 uint32_t fg_color = colors.inactive_ws_fg;
1780                 uint32_t bg_color = colors.inactive_ws_bg;
1781                 uint32_t border_color = colors.inactive_ws_border;
1782                 if (ws_walk->visible) {
1783                     if (!ws_walk->focused) {
1784                         fg_color = colors.active_ws_fg;
1785                         bg_color = colors.active_ws_bg;
1786                         border_color = colors.active_ws_border;
1787                     } else {
1788                         fg_color = colors.focus_ws_fg;
1789                         bg_color = colors.focus_ws_bg;
1790                         border_color = colors.focus_ws_border;
1791                     }
1792                 }
1793                 if (ws_walk->urgent) {
1794                     DLOG("WS %s is urgent!\n", i3string_as_utf8(ws_walk->name));
1795                     fg_color = colors.urgent_ws_fg;
1796                     bg_color = colors.urgent_ws_bg;
1797                     border_color = colors.urgent_ws_border;
1798                     unhide = true;
1799                 }
1800                 uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
1801                 uint32_t vals_border[] = {border_color, border_color};
1802                 xcb_change_gc(xcb_connection,
1803                               outputs_walk->bargc,
1804                               mask,
1805                               vals_border);
1806                 xcb_rectangle_t rect_border = {workspace_width,
1807                                                logical_px(1),
1808                                                ws_walk->name_width + 2*logical_px(ws_hoff_px) + 2*logical_px(1),
1809                                                font.height + 2*logical_px(ws_voff_px) - 2*logical_px(1)};
1810                 xcb_poly_fill_rectangle(xcb_connection,
1811                                         outputs_walk->buffer,
1812                                         outputs_walk->bargc,
1813                                         1,
1814                                         &rect_border);
1815                 uint32_t vals[] = {bg_color, bg_color};
1816                 xcb_change_gc(xcb_connection,
1817                               outputs_walk->bargc,
1818                               mask,
1819                               vals);
1820                 xcb_rectangle_t rect = {workspace_width + logical_px(1),
1821                                         2 * logical_px(1),
1822                                         ws_walk->name_width + 2*logical_px(ws_hoff_px),
1823                                         font.height + 2*logical_px(ws_voff_px) - 4*logical_px(1)};
1824                 xcb_poly_fill_rectangle(xcb_connection,
1825                                         outputs_walk->buffer,
1826                                         outputs_walk->bargc,
1827                                         1,
1828                                         &rect);
1829                 set_font_colors(outputs_walk->bargc, fg_color, bg_color);
1830                 draw_text(ws_walk->name, outputs_walk->buffer, outputs_walk->bargc,
1831                           workspace_width + logical_px(ws_hoff_px) + logical_px(1),
1832                           logical_px(ws_voff_px),
1833                           ws_walk->name_width);
1834
1835                 workspace_width += 2*logical_px(ws_hoff_px) + 2*logical_px(1) + ws_walk->name_width;
1836                 if (TAILQ_NEXT(ws_walk, tailq) != NULL)
1837                     workspace_width += logical_px(ws_spacing_px);
1838             }
1839         }
1840
1841         if (binding.name && !config.disable_binding_mode_indicator) {
1842             workspace_width += logical_px(ws_spacing_px);
1843
1844             uint32_t fg_color = colors.urgent_ws_fg;
1845             uint32_t bg_color = colors.urgent_ws_bg;
1846             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
1847
1848             uint32_t vals_border[] = {colors.urgent_ws_border, colors.urgent_ws_border};
1849             xcb_change_gc(xcb_connection,
1850                           outputs_walk->bargc,
1851                           mask,
1852                           vals_border);
1853             xcb_rectangle_t rect_border = {workspace_width,
1854                                            logical_px(1),
1855                                            binding.width + 2*logical_px(ws_hoff_px) + 2*logical_px(1),
1856                                            font.height + 2*logical_px(ws_voff_px) - 2*logical_px(1)};
1857             xcb_poly_fill_rectangle(xcb_connection,
1858                                     outputs_walk->buffer,
1859                                     outputs_walk->bargc,
1860                                     1,
1861                                     &rect_border);
1862
1863             uint32_t vals[] = {bg_color, bg_color};
1864             xcb_change_gc(xcb_connection,
1865                           outputs_walk->bargc,
1866                           mask,
1867                           vals);
1868             xcb_rectangle_t rect = {workspace_width + logical_px(1),
1869                                     2*logical_px(1),
1870                                     binding.width + 2*logical_px(ws_hoff_px),
1871                                     font.height + 2*logical_px(ws_voff_px) - 4*logical_px(1)};
1872             xcb_poly_fill_rectangle(xcb_connection,
1873                                     outputs_walk->buffer,
1874                                     outputs_walk->bargc,
1875                                     1,
1876                                     &rect);
1877
1878             set_font_colors(outputs_walk->bargc, fg_color, bg_color);
1879             draw_text(binding.name,
1880                       outputs_walk->buffer,
1881                       outputs_walk->bargc,
1882                       workspace_width + logical_px(ws_hoff_px) + logical_px(1),
1883                       logical_px(ws_voff_px),
1884                       binding.width);
1885
1886             unhide = true;
1887             workspace_width += 2*logical_px(ws_hoff_px) + 2*logical_px(1) + binding.width;
1888         }
1889
1890         if (!TAILQ_EMPTY(&statusline_head)) {
1891             DLOG("Printing statusline!\n");
1892
1893             /* Luckily we already prepared a seperate pixmap containing the rendered
1894              * statusline, we just have to copy the relevant parts to the relevant
1895              * position */
1896             int tray_width = get_tray_width(outputs_walk->trayclients);
1897
1898             int visible_statusline_width = MIN(statusline_width,
1899                                                outputs_walk->rect.w - workspace_width - tray_width - 2*logical_px(sb_hoff_px));
1900
1901             xcb_copy_area(xcb_connection,
1902                           statusline_pm,
1903                           outputs_walk->buffer,
1904                           outputs_walk->bargc,
1905                           (int16_t)(statusline_width - visible_statusline_width), 0,
1906                           (int16_t)(outputs_walk->rect.w - tray_width - logical_px(sb_hoff_px) - visible_statusline_width), 0,
1907                           (int16_t)visible_statusline_width, (int16_t)bar_height);
1908         }
1909
1910         workspace_width = 0;
1911     }
1912
1913     /* Assure the bar is hidden/unhidden according to the specified hidden_state and mode */
1914     if (mod_pressed ||
1915         config.hidden_state == S_SHOW ||
1916         unhide) {
1917         unhide_bars();
1918     } else if (config.hide_on_modifier == M_HIDE) {
1919         hide_bars();
1920     }
1921
1922     redraw_bars();
1923 }
1924
1925 /*
1926  * Redraw the bars, i.e. simply copy the buffer to the barwindow
1927  *
1928  */
1929 void redraw_bars(void) {
1930     i3_output *outputs_walk;
1931     SLIST_FOREACH(outputs_walk, outputs, slist) {
1932         if (!outputs_walk->active) {
1933             continue;
1934         }
1935         xcb_copy_area(xcb_connection,
1936                       outputs_walk->buffer,
1937                       outputs_walk->bar,
1938                       outputs_walk->bargc,
1939                       0, 0,
1940                       0, 0,
1941                       outputs_walk->rect.w,
1942                       outputs_walk->rect.h);
1943         xcb_flush(xcb_connection);
1944     }
1945 }
1946
1947 /*
1948  * Set the current binding mode
1949  *
1950  */
1951 void set_current_mode(struct mode *current) {
1952     I3STRING_FREE(binding.name);
1953     binding = *current;
1954     activated_mode = binding.name != NULL;
1955     return;
1956 }