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