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