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