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