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