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