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