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