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