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