]> git.sur5r.net Git - i3/i3/blob - i3bar/src/xcb.c
Merge pull request #1999 from hwangcc23/fix-workspace-next
[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         int type = (event->response_type & ~0x80);
991
992         if (type == xkb_base && xkb_base > -1) {
993             DLOG("received an xkb event\n");
994
995             xcb_xkb_state_notify_event_t *state = (xcb_xkb_state_notify_event_t *)event;
996             if (state->xkbType == XCB_XKB_STATE_NOTIFY) {
997                 int modstate = state->mods & config.modifier;
998
999 #define DLOGMOD(modmask, status)                        \
1000     do {                                                \
1001         switch (modmask) {                              \
1002             case ShiftMask:                             \
1003                 DLOG("ShiftMask got " #status "!\n");   \
1004                 break;                                  \
1005             case ControlMask:                           \
1006                 DLOG("ControlMask got " #status "!\n"); \
1007                 break;                                  \
1008             case Mod1Mask:                              \
1009                 DLOG("Mod1Mask got " #status "!\n");    \
1010                 break;                                  \
1011             case Mod2Mask:                              \
1012                 DLOG("Mod2Mask got " #status "!\n");    \
1013                 break;                                  \
1014             case Mod3Mask:                              \
1015                 DLOG("Mod3Mask got " #status "!\n");    \
1016                 break;                                  \
1017             case Mod4Mask:                              \
1018                 DLOG("Mod4Mask got " #status "!\n");    \
1019                 break;                                  \
1020             case Mod5Mask:                              \
1021                 DLOG("Mod5Mask got " #status "!\n");    \
1022                 break;                                  \
1023         }                                               \
1024     } while (0)
1025
1026                 if (modstate != mod_pressed) {
1027                     if (modstate == 0) {
1028                         DLOGMOD(config.modifier, released);
1029                         if (!activated_mode)
1030                             hide_bars();
1031                     } else {
1032                         DLOGMOD(config.modifier, pressed);
1033                         activated_mode = false;
1034                         unhide_bars();
1035                     }
1036                     mod_pressed = modstate;
1037                 }
1038 #undef DLOGMOD
1039             }
1040
1041             free(event);
1042             continue;
1043         }
1044
1045         switch (type) {
1046             case XCB_VISIBILITY_NOTIFY:
1047                 /* Visibility change: a bar is [un]obscured by other window */
1048                 handle_visibility_notify((xcb_visibility_notify_event_t *)event);
1049                 break;
1050             case XCB_EXPOSE:
1051                 /* Expose-events happen, when the window needs to be redrawn */
1052                 redraw_bars();
1053                 break;
1054             case XCB_BUTTON_PRESS:
1055                 /* Button press events are mouse buttons clicked on one of our bars */
1056                 handle_button((xcb_button_press_event_t *)event);
1057                 break;
1058             case XCB_CLIENT_MESSAGE:
1059                 /* Client messages are used for client-to-client communication, for
1060                  * example system tray widgets talk to us directly via client messages. */
1061                 handle_client_message((xcb_client_message_event_t *)event);
1062                 break;
1063             case XCB_DESTROY_NOTIFY:
1064                 /* DestroyNotify signifies the end of the XEmbed protocol */
1065                 handle_destroy_notify((xcb_destroy_notify_event_t *)event);
1066                 break;
1067             case XCB_UNMAP_NOTIFY:
1068                 /* UnmapNotify is received when a tray client hides its window. */
1069                 handle_unmap_notify((xcb_unmap_notify_event_t *)event);
1070                 break;
1071             case XCB_MAP_NOTIFY:
1072                 handle_map_notify((xcb_map_notify_event_t *)event);
1073                 break;
1074             case XCB_PROPERTY_NOTIFY:
1075                 /* PropertyNotify */
1076                 handle_property_notify((xcb_property_notify_event_t *)event);
1077                 break;
1078             case XCB_CONFIGURE_REQUEST:
1079                 /* ConfigureRequest, sent by a tray child */
1080                 handle_configure_request((xcb_configure_request_event_t *)event);
1081                 break;
1082         }
1083         free(event);
1084     }
1085 }
1086
1087 /*
1088  * Dummy callback. We only need this, so that the prepare and check watchers
1089  * are triggered
1090  *
1091  */
1092 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
1093 }
1094
1095 /*
1096  * Early initialization of the connection to X11: Everything which does not
1097  * depend on 'config'.
1098  *
1099  */
1100 char *init_xcb_early() {
1101     /* FIXME: xcb_connect leaks memory */
1102     xcb_connection = xcb_connect(NULL, &screen);
1103     if (xcb_connection_has_error(xcb_connection)) {
1104         ELOG("Cannot open display\n");
1105         exit(EXIT_FAILURE);
1106     }
1107     conn = xcb_connection;
1108     DLOG("Connected to xcb\n");
1109
1110 /* We have to request the atoms we need */
1111 #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
1112 #include "xcb_atoms.def"
1113
1114     root_screen = xcb_aux_get_screen(xcb_connection, screen);
1115     xcb_root = root_screen->root;
1116
1117     depth = root_screen->root_depth;
1118     colormap = root_screen->default_colormap;
1119     visual_type = get_visualtype(root_screen);
1120
1121     /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
1122      * this way, we can choose to crop it */
1123     xcb_pixmap_t statusline_id = xcb_generate_id(xcb_connection);
1124     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1125                                                                depth,
1126                                                                statusline_id,
1127                                                                xcb_root,
1128                                                                root_screen->width_in_pixels,
1129                                                                root_screen->height_in_pixels);
1130     draw_util_surface_init(&statusline_surface, statusline_id, root_screen->width_in_pixels, root_screen->height_in_pixels);
1131
1132     /* The various watchers to communicate with xcb */
1133     xcb_io = smalloc(sizeof(ev_io));
1134     xcb_prep = smalloc(sizeof(ev_prepare));
1135     xcb_chk = smalloc(sizeof(ev_check));
1136
1137     ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
1138     ev_prepare_init(xcb_prep, &xcb_prep_cb);
1139     ev_check_init(xcb_chk, &xcb_chk_cb);
1140
1141     ev_io_start(main_loop, xcb_io);
1142     ev_prepare_start(main_loop, xcb_prep);
1143     ev_check_start(main_loop, xcb_chk);
1144
1145     /* Now we get the atoms and save them in a nice data structure */
1146     get_atoms();
1147
1148     char *path = root_atom_contents("I3_SOCKET_PATH", xcb_connection, screen);
1149
1150     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline buffer"))
1151         exit(EXIT_FAILURE);
1152
1153     return path;
1154 }
1155
1156 /*
1157  * Register for xkb keyevents. To grab modifiers without blocking other applications from receiving key events
1158  * involving that modifier, we sadly have to use xkb which is not yet fully supported
1159  * in xcb.
1160  *
1161  */
1162 void register_xkb_keyevents() {
1163     const xcb_query_extension_reply_t *extreply;
1164     extreply = xcb_get_extension_data(conn, &xcb_xkb_id);
1165     if (!extreply->present) {
1166         ELOG("xkb is not present on this server\n");
1167         exit(EXIT_FAILURE);
1168     }
1169     DLOG("initializing xcb-xkb\n");
1170     xcb_xkb_use_extension(conn, XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION);
1171     xcb_xkb_select_events(conn,
1172                           XCB_XKB_ID_USE_CORE_KBD,
1173                           XCB_XKB_EVENT_TYPE_STATE_NOTIFY,
1174                           0,
1175                           XCB_XKB_EVENT_TYPE_STATE_NOTIFY,
1176                           0xff,
1177                           0xff,
1178                           NULL);
1179     xkb_base = extreply->first_event;
1180 }
1181
1182 /*
1183  * Deregister from xkb keyevents.
1184  *
1185  */
1186 void deregister_xkb_keyevents() {
1187     xcb_xkb_select_events(conn,
1188                           XCB_XKB_ID_USE_CORE_KBD,
1189                           0,
1190                           0,
1191                           0,
1192                           0xff,
1193                           0xff,
1194                           NULL);
1195 }
1196
1197 /*
1198  * Initialization which depends on 'config' being usable. Called after the
1199  * configuration has arrived.
1200  *
1201  */
1202 void init_xcb_late(char *fontname) {
1203     if (fontname == NULL)
1204         fontname = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
1205
1206     /* Load the font */
1207     font = load_font(fontname, true);
1208     set_font(&font);
1209     DLOG("Calculated font height: %d\n", font.height);
1210     bar_height = font.height + 2 * logical_px(ws_voff_px);
1211     icon_size = bar_height - 2 * logical_px(config.tray_padding);
1212
1213     if (config.separator_symbol)
1214         separator_symbol_width = predict_text_width(config.separator_symbol);
1215
1216     xcb_flush(xcb_connection);
1217
1218     if (config.hide_on_modifier == M_HIDE)
1219         register_xkb_keyevents();
1220 }
1221
1222 /*
1223  * Inform clients waiting for a new _NET_SYSTEM_TRAY that we took the
1224  * selection.
1225  *
1226  */
1227 static void send_tray_clientmessage(void) {
1228     uint8_t buffer[32] = {0};
1229     xcb_client_message_event_t *ev = (xcb_client_message_event_t *)buffer;
1230
1231     ev->response_type = XCB_CLIENT_MESSAGE;
1232     ev->window = xcb_root;
1233     ev->type = atoms[MANAGER];
1234     ev->format = 32;
1235     ev->data.data32[0] = XCB_CURRENT_TIME;
1236     ev->data.data32[1] = tray_reply->atom;
1237     ev->data.data32[2] = selwin;
1238
1239     xcb_send_event(xcb_connection,
1240                    0,
1241                    xcb_root,
1242                    0xFFFFFF,
1243                    (char *)buffer);
1244 }
1245
1246 /*
1247  * Initializes tray support by requesting the appropriate _NET_SYSTEM_TRAY atom
1248  * for the X11 display we are running on, then acquiring the selection for this
1249  * atom. Afterwards, tray clients will send ClientMessages to our window.
1250  *
1251  */
1252 void init_tray(void) {
1253     DLOG("Initializing system tray functionality\n");
1254     /* request the tray manager atom for the X11 display we are running on */
1255     char atomname[strlen("_NET_SYSTEM_TRAY_S") + 11];
1256     snprintf(atomname, strlen("_NET_SYSTEM_TRAY_S") + 11, "_NET_SYSTEM_TRAY_S%d", screen);
1257     xcb_intern_atom_cookie_t tray_cookie;
1258     if (tray_reply == NULL)
1259         tray_cookie = xcb_intern_atom(xcb_connection, 0, strlen(atomname), atomname);
1260
1261     /* tray support: we need a window to own the selection */
1262     selwin = xcb_generate_id(xcb_connection);
1263     uint32_t selmask = XCB_CW_BACK_PIXEL | XCB_CW_BORDER_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_COLORMAP;
1264     uint32_t selval[] = {root_screen->black_pixel, root_screen->black_pixel, 1, colormap};
1265     xcb_create_window(xcb_connection,
1266                       depth,
1267                       selwin,
1268                       xcb_root,
1269                       -1, -1,
1270                       1, 1,
1271                       0,
1272                       XCB_WINDOW_CLASS_INPUT_OUTPUT,
1273                       visual_type->visual_id,
1274                       selmask,
1275                       selval);
1276
1277     uint32_t orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
1278     /* set the atoms */
1279     xcb_change_property(xcb_connection,
1280                         XCB_PROP_MODE_REPLACE,
1281                         selwin,
1282                         atoms[_NET_SYSTEM_TRAY_ORIENTATION],
1283                         XCB_ATOM_CARDINAL,
1284                         32,
1285                         1,
1286                         &orientation);
1287     xcb_change_property(xcb_connection,
1288                         XCB_PROP_MODE_REPLACE,
1289                         selwin,
1290                         atoms[_NET_SYSTEM_TRAY_VISUAL],
1291                         XCB_ATOM_VISUALID,
1292                         32,
1293                         1,
1294                         &visual_type->visual_id);
1295
1296     init_tray_colors();
1297
1298     if (tray_reply == NULL) {
1299         if (!(tray_reply = xcb_intern_atom_reply(xcb_connection, tray_cookie, NULL))) {
1300             ELOG("Could not get atom %s\n", atomname);
1301             exit(EXIT_FAILURE);
1302         }
1303     }
1304
1305     xcb_set_selection_owner(xcb_connection,
1306                             selwin,
1307                             tray_reply->atom,
1308                             XCB_CURRENT_TIME);
1309
1310     /* Verify that we have the selection */
1311     xcb_get_selection_owner_cookie_t selcookie;
1312     xcb_get_selection_owner_reply_t *selreply;
1313
1314     selcookie = xcb_get_selection_owner(xcb_connection, tray_reply->atom);
1315     if (!(selreply = xcb_get_selection_owner_reply(xcb_connection, selcookie, NULL))) {
1316         ELOG("Could not get selection owner for %s\n", atomname);
1317         exit(EXIT_FAILURE);
1318     }
1319
1320     if (selreply->owner != selwin) {
1321         ELOG("Could not set the %s selection. "
1322              "Maybe another tray is already running?\n",
1323              atomname);
1324         /* NOTE that this error is not fatal. We just can’t provide tray
1325          * functionality */
1326         free(selreply);
1327         return;
1328     }
1329
1330     send_tray_clientmessage();
1331 }
1332
1333 /*
1334  * We need to set the _NET_SYSTEM_TRAY_COLORS atom on the tray selection window
1335  * to make GTK+ 3 applets with symbolic icons visible. If the colors are unset,
1336  * they assume a light background.
1337  * See also https://bugzilla.gnome.org/show_bug.cgi?id=679591
1338  *
1339  */
1340 void init_tray_colors(void) {
1341     /* Convert colors.bar_fg (#rrggbb) to 16-bit RGB */
1342     const char *bar_fg = (config.colors.bar_fg ? config.colors.bar_fg : "#FFFFFF");
1343
1344     DLOG("Setting bar_fg = %s as _NET_SYSTEM_TRAY_COLORS\n", bar_fg);
1345
1346     char strgroups[3][3] = {{bar_fg[1], bar_fg[2], '\0'},
1347                             {bar_fg[3], bar_fg[4], '\0'},
1348                             {bar_fg[5], bar_fg[6], '\0'}};
1349     const uint8_t r = strtol(strgroups[0], NULL, 16);
1350     const uint8_t g = strtol(strgroups[1], NULL, 16);
1351     const uint8_t b = strtol(strgroups[2], NULL, 16);
1352
1353     const uint16_t r16 = ((uint16_t)r << 8) | r;
1354     const uint16_t g16 = ((uint16_t)g << 8) | g;
1355     const uint16_t b16 = ((uint16_t)b << 8) | b;
1356
1357     const uint32_t tray_colors[12] = {
1358         r16, g16, b16, /* foreground color */
1359         r16, g16, b16, /* error color */
1360         r16, g16, b16, /* warning color */
1361         r16, g16, b16, /* success color */
1362     };
1363
1364     xcb_change_property(xcb_connection,
1365                         XCB_PROP_MODE_REPLACE,
1366                         selwin,
1367                         atoms[_NET_SYSTEM_TRAY_COLORS],
1368                         XCB_ATOM_CARDINAL,
1369                         32,
1370                         12,
1371                         tray_colors);
1372 }
1373
1374 /*
1375  * Cleanup the xcb stuff.
1376  * Called once, before the program terminates.
1377  *
1378  */
1379 void clean_xcb(void) {
1380     i3_output *o_walk;
1381     free_workspaces();
1382     SLIST_FOREACH(o_walk, outputs, slist) {
1383         destroy_window(o_walk);
1384         FREE(o_walk->trayclients);
1385         FREE(o_walk->workspaces);
1386         FREE(o_walk->name);
1387     }
1388     FREE_SLIST(outputs, i3_output);
1389     FREE(outputs);
1390
1391     xcb_flush(xcb_connection);
1392     xcb_aux_sync(xcb_connection);
1393     xcb_disconnect(xcb_connection);
1394
1395     ev_check_stop(main_loop, xcb_chk);
1396     ev_prepare_stop(main_loop, xcb_prep);
1397     ev_io_stop(main_loop, xcb_io);
1398
1399     FREE(xcb_chk);
1400     FREE(xcb_prep);
1401     FREE(xcb_io);
1402 }
1403
1404 /*
1405  * Get the earlier requested atoms and save them in the prepared data structure
1406  *
1407  */
1408 void get_atoms(void) {
1409     xcb_intern_atom_reply_t *reply;
1410 #define ATOM_DO(name)                                                        \
1411     reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
1412     if (reply == NULL) {                                                     \
1413         ELOG("Could not get atom %s\n", #name);                              \
1414         exit(EXIT_FAILURE);                                                  \
1415     }                                                                        \
1416     atoms[name] = reply->atom;                                               \
1417     free(reply);
1418
1419 #include "xcb_atoms.def"
1420     DLOG("Got atoms\n");
1421 }
1422
1423 /*
1424  * Reparents all tray clients of the specified output to the root window. This
1425  * is either used when shutting down, when an output appears (xrandr --output
1426  * VGA1 --off) or when the primary output changes.
1427  *
1428  * Applications using the tray will start the protocol from the beginning again
1429  * afterwards.
1430  *
1431  */
1432 void kick_tray_clients(i3_output *output) {
1433     if (TAILQ_EMPTY(output->trayclients))
1434         return;
1435
1436     trayclient *trayclient;
1437     while (!TAILQ_EMPTY(output->trayclients)) {
1438         trayclient = TAILQ_FIRST(output->trayclients);
1439         /* Unmap, then reparent (to root) the tray client windows */
1440         xcb_unmap_window(xcb_connection, trayclient->win);
1441         xcb_reparent_window(xcb_connection,
1442                             trayclient->win,
1443                             xcb_root,
1444                             0,
1445                             0);
1446
1447         /* We remove the trayclient right here. We might receive an UnmapNotify
1448          * event afterwards, but better safe than sorry. */
1449         TAILQ_REMOVE(output->trayclients, trayclient, tailq);
1450     }
1451
1452     /* Fake a DestroyNotify so that Qt re-adds tray icons.
1453      * We cannot actually destroy the window because then Qt will not restore
1454      * its event mask on the new window. */
1455     uint8_t buffer[32] = {0};
1456     xcb_destroy_notify_event_t *event = (xcb_destroy_notify_event_t *)buffer;
1457
1458     event->response_type = XCB_DESTROY_NOTIFY;
1459     event->event = selwin;
1460     event->window = selwin;
1461
1462     xcb_send_event(conn, false, selwin, XCB_EVENT_MASK_STRUCTURE_NOTIFY, (char *)event);
1463
1464     send_tray_clientmessage();
1465 }
1466
1467 /*
1468  * Destroy the bar of the specified output
1469  *
1470  */
1471 void destroy_window(i3_output *output) {
1472     if (output == NULL) {
1473         return;
1474     }
1475     if (output->bar.id == XCB_NONE) {
1476         return;
1477     }
1478
1479     kick_tray_clients(output);
1480     xcb_destroy_window(xcb_connection, output->bar.id);
1481     output->bar.id = XCB_NONE;
1482 }
1483
1484 /*
1485  * Reallocate the statusline buffer
1486  *
1487  */
1488 void realloc_sl_buffer(void) {
1489     DLOG("Re-allocating statusline buffer, statusline_width = %d, root_screen->width_in_pixels = %d\n",
1490          statusline_width, root_screen->width_in_pixels);
1491     xcb_free_pixmap(xcb_connection, statusline_surface.id);
1492     draw_util_surface_free(&statusline_surface);
1493
1494     xcb_pixmap_t statusline_id = xcb_generate_id(xcb_connection);
1495     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1496                                                                depth,
1497                                                                statusline_id,
1498                                                                xcb_root,
1499                                                                MAX(root_screen->width_in_pixels, statusline_width),
1500                                                                bar_height);
1501     draw_util_surface_init(&statusline_surface, statusline_id, root_screen->width_in_pixels, root_screen->height_in_pixels);
1502
1503     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline buffer"))
1504         exit(EXIT_FAILURE);
1505 }
1506
1507 /* Strut partial tells i3 where to reserve space for i3bar. This is determined
1508  * by the `position` bar config directive. */
1509 xcb_void_cookie_t config_strut_partial(i3_output *output) {
1510     /* A local struct to save the strut_partial property */
1511     struct {
1512         uint32_t left;
1513         uint32_t right;
1514         uint32_t top;
1515         uint32_t bottom;
1516         uint32_t left_start_y;
1517         uint32_t left_end_y;
1518         uint32_t right_start_y;
1519         uint32_t right_end_y;
1520         uint32_t top_start_x;
1521         uint32_t top_end_x;
1522         uint32_t bottom_start_x;
1523         uint32_t bottom_end_x;
1524     } __attribute__((__packed__)) strut_partial;
1525     memset(&strut_partial, 0, sizeof(strut_partial));
1526
1527     switch (config.position) {
1528         case POS_NONE:
1529             break;
1530         case POS_TOP:
1531             strut_partial.top = bar_height;
1532             strut_partial.top_start_x = output->rect.x;
1533             strut_partial.top_end_x = output->rect.x + output->rect.w;
1534             break;
1535         case POS_BOT:
1536             strut_partial.bottom = bar_height;
1537             strut_partial.bottom_start_x = output->rect.x;
1538             strut_partial.bottom_end_x = output->rect.x + output->rect.w;
1539             break;
1540     }
1541     return xcb_change_property(xcb_connection,
1542                                XCB_PROP_MODE_REPLACE,
1543                                output->bar.id,
1544                                atoms[_NET_WM_STRUT_PARTIAL],
1545                                XCB_ATOM_CARDINAL,
1546                                32,
1547                                12,
1548                                &strut_partial);
1549 }
1550
1551 /*
1552  * Reconfigure all bars and create new bars for recently activated outputs
1553  *
1554  */
1555 void reconfig_windows(bool redraw_bars) {
1556     uint32_t mask;
1557     uint32_t values[5];
1558     static bool tray_configured = false;
1559
1560     i3_output *walk;
1561     SLIST_FOREACH(walk, outputs, slist) {
1562         if (!walk->active) {
1563             /* If an output is not active, we destroy its bar */
1564             /* FIXME: Maybe we rather want to unmap? */
1565             DLOG("Destroying window for output %s\n", walk->name);
1566             destroy_window(walk);
1567             continue;
1568         }
1569         if (walk->bar.id == XCB_NONE) {
1570             DLOG("Creating window for output %s\n", walk->name);
1571
1572             xcb_window_t bar_id = xcb_generate_id(xcb_connection);
1573             xcb_pixmap_t buffer_id = xcb_generate_id(xcb_connection);
1574             mask = XCB_CW_BACK_PIXEL | XCB_CW_BORDER_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK | XCB_CW_COLORMAP;
1575
1576             values[0] = colors.bar_bg.colorpixel;
1577             values[1] = root_screen->black_pixel;
1578             /* If hide_on_modifier is set to hide or invisible mode, i3 is not supposed to manage our bar windows */
1579             values[2] = (config.hide_on_modifier == M_DOCK ? 0 : 1);
1580             /* We enable the following EventMask fields:
1581              * EXPOSURE, to get expose events (we have to re-draw then)
1582              * SUBSTRUCTURE_REDIRECT, to get ConfigureRequests when the tray
1583              *                        child windows use ConfigureWindow
1584              * BUTTON_PRESS, to handle clicks on the workspace buttons
1585              * */
1586             values[3] = XCB_EVENT_MASK_EXPOSURE |
1587                         XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
1588                         XCB_EVENT_MASK_BUTTON_PRESS;
1589             if (config.hide_on_modifier == M_DOCK) {
1590                 /* If the bar is normally visible, catch visibility change events to suspend
1591                  * the status process when the bar is obscured by full-screened windows.  */
1592                 values[3] |= XCB_EVENT_MASK_VISIBILITY_CHANGE;
1593                 walk->visible = true;
1594             }
1595             values[4] = colormap;
1596
1597             xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
1598                                                                      depth,
1599                                                                      bar_id,
1600                                                                      xcb_root,
1601                                                                      walk->rect.x, walk->rect.y + walk->rect.h - bar_height,
1602                                                                      walk->rect.w, bar_height,
1603                                                                      0,
1604                                                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,
1605                                                                      visual_type->visual_id,
1606                                                                      mask,
1607                                                                      values);
1608
1609             /* The double-buffer we use to render stuff off-screen */
1610             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1611                                                                     depth,
1612                                                                     buffer_id,
1613                                                                     bar_id,
1614                                                                     walk->rect.w,
1615                                                                     bar_height);
1616
1617             /* Set the WM_CLASS and WM_NAME (we don't need UTF-8) atoms */
1618             xcb_void_cookie_t class_cookie;
1619             class_cookie = xcb_change_property(xcb_connection,
1620                                                XCB_PROP_MODE_REPLACE,
1621                                                bar_id,
1622                                                XCB_ATOM_WM_CLASS,
1623                                                XCB_ATOM_STRING,
1624                                                8,
1625                                                (strlen("i3bar") + 1) * 2,
1626                                                "i3bar\0i3bar\0");
1627
1628             char *name;
1629             sasprintf(&name, "i3bar for output %s", walk->name);
1630             xcb_void_cookie_t name_cookie;
1631             name_cookie = xcb_change_property(xcb_connection,
1632                                               XCB_PROP_MODE_REPLACE,
1633                                               bar_id,
1634                                               XCB_ATOM_WM_NAME,
1635                                               XCB_ATOM_STRING,
1636                                               8,
1637                                               strlen(name),
1638                                               name);
1639             free(name);
1640
1641             /* We want dock windows (for now). When override_redirect is set, i3 is ignoring
1642              * this one */
1643             xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
1644                                                                 XCB_PROP_MODE_REPLACE,
1645                                                                 bar_id,
1646                                                                 atoms[_NET_WM_WINDOW_TYPE],
1647                                                                 XCB_ATOM_ATOM,
1648                                                                 32,
1649                                                                 1,
1650                                                                 (unsigned char *)&atoms[_NET_WM_WINDOW_TYPE_DOCK]);
1651
1652             draw_util_surface_init(&walk->bar, bar_id, walk->rect.w, bar_height);
1653             draw_util_surface_init(&walk->buffer, buffer_id, walk->rect.w, bar_height);
1654
1655             xcb_void_cookie_t strut_cookie = config_strut_partial(walk);
1656
1657             /* We finally map the bar (display it on screen), unless the modifier-switch is on */
1658             xcb_void_cookie_t map_cookie;
1659             if (config.hide_on_modifier == M_DOCK) {
1660                 map_cookie = xcb_map_window_checked(xcb_connection, bar_id);
1661             }
1662
1663             if (xcb_request_failed(win_cookie, "Could not create window") ||
1664                 xcb_request_failed(pm_cookie, "Could not create pixmap") ||
1665                 xcb_request_failed(dock_cookie, "Could not set dock mode") ||
1666                 xcb_request_failed(class_cookie, "Could not set WM_CLASS") ||
1667                 xcb_request_failed(name_cookie, "Could not set WM_NAME") ||
1668                 xcb_request_failed(strut_cookie, "Could not set strut") ||
1669                 ((config.hide_on_modifier == M_DOCK) && xcb_request_failed(map_cookie, "Could not map window"))) {
1670                 exit(EXIT_FAILURE);
1671             }
1672
1673             const char *tray_output = (config.tray_output ? config.tray_output : SLIST_FIRST(outputs)->name);
1674             if (!tray_configured && strcasecmp(tray_output, "none") != 0) {
1675                 /* Configuration sanity check: ensure this i3bar instance handles the output on
1676                  * which the tray should appear (e.g. don’t initialize a tray if tray_output ==
1677                  * VGA-1 but output == [HDMI-1]).
1678                  */
1679                 i3_output *output;
1680                 SLIST_FOREACH(output, outputs, slist) {
1681                     if (strcasecmp(output->name, tray_output) == 0 ||
1682                         (strcasecmp(tray_output, "primary") == 0 && output->primary)) {
1683                         init_tray();
1684                         break;
1685                     }
1686                 }
1687                 tray_configured = true;
1688             }
1689         } else {
1690             /* We already have a bar, so we just reconfigure it */
1691             mask = XCB_CONFIG_WINDOW_X |
1692                    XCB_CONFIG_WINDOW_Y |
1693                    XCB_CONFIG_WINDOW_WIDTH |
1694                    XCB_CONFIG_WINDOW_HEIGHT |
1695                    XCB_CONFIG_WINDOW_STACK_MODE;
1696             values[0] = walk->rect.x;
1697             if (config.position == POS_TOP)
1698                 values[1] = walk->rect.y;
1699             else
1700                 values[1] = walk->rect.y + walk->rect.h - bar_height;
1701             values[2] = walk->rect.w;
1702             values[3] = bar_height;
1703             values[4] = XCB_STACK_MODE_ABOVE;
1704
1705             DLOG("Reconfiguring strut partial property for output %s\n", walk->name);
1706             xcb_void_cookie_t strut_cookie = config_strut_partial(walk);
1707
1708             DLOG("Destroying buffer for output %s\n", walk->name);
1709             xcb_free_pixmap(xcb_connection, walk->buffer.id);
1710
1711             DLOG("Reconfiguring window for output %s to %d,%d\n", walk->name, values[0], values[1]);
1712             xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
1713                                                                         walk->bar.id,
1714                                                                         mask,
1715                                                                         values);
1716
1717             mask = XCB_CW_OVERRIDE_REDIRECT;
1718             values[0] = (config.hide_on_modifier == M_DOCK ? 0 : 1);
1719             DLOG("Changing window attribute override_redirect for output %s to %d\n", walk->name, values[0]);
1720             xcb_void_cookie_t chg_cookie = xcb_change_window_attributes(xcb_connection,
1721                                                                         walk->bar.id,
1722                                                                         mask,
1723                                                                         values);
1724
1725             DLOG("Recreating buffer for output %s\n", walk->name);
1726             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1727                                                                     depth,
1728                                                                     walk->buffer.id,
1729                                                                     walk->bar.id,
1730                                                                     walk->rect.w,
1731                                                                     bar_height);
1732
1733             draw_util_surface_free(&(walk->bar));
1734             draw_util_surface_free(&(walk->buffer));
1735             draw_util_surface_init(&(walk->bar), walk->bar.id, walk->rect.w, bar_height);
1736             draw_util_surface_init(&(walk->buffer), walk->buffer.id, walk->rect.w, bar_height);
1737
1738             xcb_void_cookie_t map_cookie, umap_cookie;
1739             if (redraw_bars) {
1740                 /* Unmap the window, and draw it again when in dock mode */
1741                 umap_cookie = xcb_unmap_window_checked(xcb_connection, walk->bar.id);
1742                 if (config.hide_on_modifier == M_DOCK) {
1743                     cont_child();
1744                     map_cookie = xcb_map_window_checked(xcb_connection, walk->bar.id);
1745                 } else {
1746                     stop_child();
1747                 }
1748
1749                 if (config.hide_on_modifier == M_HIDE) {
1750                     /* Switching to hide mode, register for keyevents */
1751                     register_xkb_keyevents();
1752                 } else {
1753                     /* Switching to dock/invisible mode, deregister from keyevents */
1754                     deregister_xkb_keyevents();
1755                 }
1756             }
1757
1758             if (xcb_request_failed(cfg_cookie, "Could not reconfigure window") ||
1759                 xcb_request_failed(chg_cookie, "Could not change window") ||
1760                 xcb_request_failed(pm_cookie, "Could not create pixmap") ||
1761                 xcb_request_failed(strut_cookie, "Could not set strut") ||
1762                 (redraw_bars && (xcb_request_failed(umap_cookie, "Could not unmap window") ||
1763                                  (config.hide_on_modifier == M_DOCK && xcb_request_failed(map_cookie, "Could not map window"))))) {
1764                 exit(EXIT_FAILURE);
1765             }
1766         }
1767     }
1768 }
1769
1770 /*
1771  * Render the bars, with buttons and statusline
1772  *
1773  */
1774 void draw_bars(bool unhide) {
1775     DLOG("Drawing bars...\n");
1776     int workspace_width = 0;
1777     /* Is the currently-rendered statusline using short_text items? */
1778     bool rendered_statusline_is_short = false;
1779
1780     refresh_statusline(false);
1781
1782     i3_output *outputs_walk;
1783     SLIST_FOREACH(outputs_walk, outputs, slist) {
1784         if (!outputs_walk->active) {
1785             DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
1786             continue;
1787         }
1788         if (outputs_walk->bar.id == XCB_NONE) {
1789             /* Oh shit, an active output without an own bar. Create it now! */
1790             reconfig_windows(false);
1791         }
1792
1793         /* First things first: clear the backbuffer */
1794         draw_util_clear_surface(&(outputs_walk->buffer), colors.bar_bg);
1795
1796         if (!config.disable_ws) {
1797             i3_ws *ws_walk;
1798             TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
1799                 DLOG("Drawing button for WS %s at x = %d, len = %d\n",
1800                      i3string_as_utf8(ws_walk->name), workspace_width, ws_walk->name_width);
1801                 color_t fg_color = colors.inactive_ws_fg;
1802                 color_t bg_color = colors.inactive_ws_bg;
1803                 color_t border_color = colors.inactive_ws_border;
1804                 if (ws_walk->visible) {
1805                     if (!ws_walk->focused) {
1806                         fg_color = colors.active_ws_fg;
1807                         bg_color = colors.active_ws_bg;
1808                         border_color = colors.active_ws_border;
1809                     } else {
1810                         fg_color = colors.focus_ws_fg;
1811                         bg_color = colors.focus_ws_bg;
1812                         border_color = colors.focus_ws_border;
1813                     }
1814                 }
1815                 if (ws_walk->urgent) {
1816                     DLOG("WS %s is urgent!\n", i3string_as_utf8(ws_walk->name));
1817                     fg_color = colors.urgent_ws_fg;
1818                     bg_color = colors.urgent_ws_bg;
1819                     border_color = colors.urgent_ws_border;
1820                     unhide = true;
1821                 }
1822
1823                 /* Draw the border of the button. */
1824                 draw_util_rectangle(&(outputs_walk->buffer), border_color,
1825                                     workspace_width,
1826                                     logical_px(1),
1827                                     ws_walk->name_width + 2 * logical_px(ws_hoff_px) + 2 * logical_px(1),
1828                                     font.height + 2 * logical_px(ws_voff_px) - 2 * logical_px(1));
1829
1830                 /* Draw the inside of the button. */
1831                 draw_util_rectangle(&(outputs_walk->buffer), bg_color,
1832                                     workspace_width + logical_px(1),
1833                                     2 * logical_px(1),
1834                                     ws_walk->name_width + 2 * logical_px(ws_hoff_px),
1835                                     font.height + 2 * logical_px(ws_voff_px) - 4 * logical_px(1));
1836
1837                 draw_util_text(ws_walk->name, &(outputs_walk->buffer), fg_color, bg_color,
1838                                workspace_width + logical_px(ws_hoff_px) + logical_px(1),
1839                                logical_px(ws_voff_px),
1840                                ws_walk->name_width);
1841
1842                 workspace_width += 2 * logical_px(ws_hoff_px) + 2 * logical_px(1) + ws_walk->name_width;
1843                 if (TAILQ_NEXT(ws_walk, tailq) != NULL)
1844                     workspace_width += logical_px(ws_spacing_px);
1845             }
1846         }
1847
1848         if (binding.name && !config.disable_binding_mode_indicator) {
1849             workspace_width += logical_px(ws_spacing_px);
1850
1851             color_t fg_color = colors.binding_mode_fg;
1852             color_t bg_color = colors.binding_mode_bg;
1853
1854             draw_util_rectangle(&(outputs_walk->buffer), colors.binding_mode_border,
1855                                 workspace_width,
1856                                 logical_px(1),
1857                                 binding.width + 2 * logical_px(ws_hoff_px) + 2 * logical_px(1),
1858                                 font.height + 2 * logical_px(ws_voff_px) - 2 * logical_px(1));
1859
1860             draw_util_rectangle(&(outputs_walk->buffer), bg_color,
1861                                 workspace_width + logical_px(1),
1862                                 2 * logical_px(1),
1863                                 binding.width + 2 * logical_px(ws_hoff_px),
1864                                 font.height + 2 * logical_px(ws_voff_px) - 4 * logical_px(1));
1865
1866             draw_util_text(binding.name, &(outputs_walk->buffer), fg_color, bg_color,
1867                            workspace_width + logical_px(ws_hoff_px) + logical_px(1),
1868                            logical_px(ws_voff_px),
1869                            binding.width);
1870
1871             unhide = true;
1872             workspace_width += 2 * logical_px(ws_hoff_px) + 2 * logical_px(1) + binding.width;
1873         }
1874
1875         if (!TAILQ_EMPTY(&statusline_head)) {
1876             DLOG("Printing statusline!\n");
1877
1878             int tray_width = get_tray_width(outputs_walk->trayclients);
1879             uint32_t max_statusline_width = outputs_walk->rect.w - workspace_width - tray_width - 2 * logical_px(sb_hoff_px);
1880
1881             /* If the statusline is too long, try to use short texts. */
1882             if (statusline_width > max_statusline_width) {
1883                 /* If the currently rendered statusline is long, render a short status line */
1884                 refresh_statusline(true);
1885                 rendered_statusline_is_short = true;
1886             } else if (rendered_statusline_is_short) {
1887                 /* If the currently rendered statusline is short, render a long status line */
1888                 refresh_statusline(false);
1889                 rendered_statusline_is_short = false;
1890             }
1891
1892             /* Luckily we already prepared a seperate pixmap containing the rendered
1893              * statusline, we just have to copy the relevant parts to the relevant
1894              * position */
1895             int visible_statusline_width = MIN(statusline_width, max_statusline_width);
1896             int x_src = (int16_t)(statusline_width - visible_statusline_width);
1897             int x_dest = (int16_t)(outputs_walk->rect.w - tray_width - logical_px(sb_hoff_px) - visible_statusline_width);
1898
1899             draw_util_copy_surface(&statusline_surface, &(outputs_walk->buffer), x_src, 0,
1900                                    x_dest, 0, (int16_t)visible_statusline_width, (int16_t)bar_height);
1901         }
1902
1903         workspace_width = 0;
1904     }
1905
1906     /* Assure the bar is hidden/unhidden according to the specified hidden_state and mode */
1907     if (mod_pressed ||
1908         config.hidden_state == S_SHOW ||
1909         unhide) {
1910         unhide_bars();
1911     } else if (config.hide_on_modifier == M_HIDE) {
1912         hide_bars();
1913     }
1914
1915     redraw_bars();
1916 }
1917
1918 /*
1919  * Redraw the bars, i.e. simply copy the buffer to the barwindow
1920  *
1921  */
1922 void redraw_bars(void) {
1923     i3_output *outputs_walk;
1924     SLIST_FOREACH(outputs_walk, outputs, slist) {
1925         if (!outputs_walk->active) {
1926             continue;
1927         }
1928
1929         draw_util_copy_surface(&(outputs_walk->buffer), &(outputs_walk->bar), 0, 0,
1930                                0, 0, outputs_walk->rect.w, outputs_walk->rect.h);
1931         xcb_flush(xcb_connection);
1932     }
1933 }
1934
1935 /*
1936  * Set the current binding mode
1937  *
1938  */
1939 void set_current_mode(struct mode *current) {
1940     I3STRING_FREE(binding.name);
1941     binding = *current;
1942     activated_mode = binding.name != NULL;
1943     return;
1944 }