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