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