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