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