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