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