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