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