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