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