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