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