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