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