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