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