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