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