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