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