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