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