]> git.sur5r.net Git - i3/i3/blob - i3bar/src/xcb.c
Merge branch 'master' into next
[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 = NULL;
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             if (output == NULL) {
482                 ELOG("No output found\n");
483                 return;
484             }
485             xcb_reparent_window(xcb_connection,
486                                 client,
487                                 output->bar,
488                                 output->rect.w - font_height - 2,
489                                 2);
490             /* We reconfigure the window to use a reasonable size. The systray
491              * specification explicitly says:
492              *   Tray icons may be assigned any size by the system tray, and
493              *   should do their best to cope with any size effectively
494              */
495             mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
496             values[0] = font_height;
497             values[1] = font_height;
498             xcb_configure_window(xcb_connection,
499                                  client,
500                                  mask,
501                                  values);
502
503             /* send the XEMBED_EMBEDDED_NOTIFY message */
504             void *event = calloc(32, 1);
505             xcb_client_message_event_t *ev = event;
506             ev->response_type = XCB_CLIENT_MESSAGE;
507             ev->window = client;
508             ev->type = atoms[_XEMBED];
509             ev->format = 32;
510             ev->data.data32[0] = XCB_CURRENT_TIME;
511             ev->data.data32[1] = atoms[XEMBED_EMBEDDED_NOTIFY];
512             ev->data.data32[2] = output->bar;
513             ev->data.data32[3] = xe_version;
514             xcb_send_event(xcb_connection,
515                            0,
516                            client,
517                            XCB_EVENT_MASK_NO_EVENT,
518                            (char*)ev);
519             free(event);
520
521             if (map_it) {
522                 DLOG("Mapping dock client\n");
523                 xcb_map_window(xcb_connection, client);
524             } else {
525                 DLOG("Not mapping dock client yet\n");
526             }
527             trayclient *tc = malloc(sizeof(trayclient));
528             tc->win = client;
529             tc->mapped = map_it;
530             tc->xe_version = xe_version;
531             TAILQ_INSERT_TAIL(output->trayclients, tc, tailq);
532
533             /* Trigger an update to copy the statusline text to the appropriate
534              * position */
535             configure_trayclients();
536             draw_bars();
537         }
538     }
539 }
540
541 /*
542  * Handles UnmapNotify events. These events happen when a tray window unmaps
543  * itself. We then update our data structure
544  *
545  */
546 static void handle_unmap_notify(xcb_unmap_notify_event_t* event) {
547     DLOG("UnmapNotify for window = %08x, event = %08x\n", event->window, event->event);
548
549     i3_output *walk;
550     SLIST_FOREACH(walk, outputs, slist) {
551         if (!walk->active)
552             continue;
553         DLOG("checking output %s\n", walk->name);
554         trayclient *trayclient;
555         TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
556             if (trayclient->win != event->window)
557                 continue;
558
559             DLOG("Removing tray client with window ID %08x\n", event->window);
560             TAILQ_REMOVE(walk->trayclients, trayclient, tailq);
561
562             /* Trigger an update, we now have more space for the statusline */
563             configure_trayclients();
564             draw_bars();
565             return;
566         }
567     }
568 }
569
570 /*
571  * Handle PropertyNotify messages. Currently only the _XEMBED_INFO property is
572  * handled, which tells us whether a dock client should be mapped or unmapped.
573  *
574  */
575 static void handle_property_notify(xcb_property_notify_event_t *event) {
576     DLOG("PropertyNotify\n");
577     if (event->atom == atoms[_XEMBED_INFO] &&
578         event->state == XCB_PROPERTY_NEW_VALUE) {
579         DLOG("xembed_info updated\n");
580         trayclient *trayclient = NULL, *walk;
581         i3_output *o_walk;
582         SLIST_FOREACH(o_walk, outputs, slist) {
583             if (!o_walk->active)
584                 continue;
585
586             TAILQ_FOREACH(walk, o_walk->trayclients, tailq) {
587                 if (walk->win != event->window)
588                     continue;
589                 trayclient = walk;
590                 break;
591             }
592
593             if (trayclient)
594                 break;
595         }
596         if (!trayclient) {
597             ELOG("PropertyNotify received for unknown window %08x\n",
598                  event->window);
599             return;
600         }
601         xcb_get_property_cookie_t xembedc;
602         xembedc = xcb_get_property_unchecked(xcb_connection,
603                                              0,
604                                              trayclient->win,
605                                              atoms[_XEMBED_INFO],
606                                              XCB_GET_PROPERTY_TYPE_ANY,
607                                              0,
608                                              2 * 32);
609
610         xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
611                                                                    xembedc,
612                                                                    NULL);
613         if (xembedr == NULL || xembedr->length == 0)
614             return;
615
616         DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
617         uint32_t *xembed = xcb_get_property_value(xembedr);
618         DLOG("xembed version = %d\n", xembed[0]);
619         DLOG("xembed flags = %d\n", xembed[1]);
620         bool map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
621         DLOG("map-state now %d\n", map_it);
622         if (trayclient->mapped && !map_it) {
623             /* need to unmap the window */
624             xcb_unmap_window(xcb_connection, trayclient->win);
625             trayclient->mapped = map_it;
626             draw_bars();
627         } else if (!trayclient->mapped && map_it) {
628             /* need to map the window */
629             xcb_map_window(xcb_connection, trayclient->win);
630             trayclient->mapped = map_it;
631             draw_bars();
632         }
633         free(xembedr);
634     }
635 }
636
637 /*
638  * This function is called immediately before the main loop locks. We flush xcb
639  * then (and only then)
640  *
641  */
642 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revents) {
643     xcb_flush(xcb_connection);
644 }
645
646 /*
647  * This function is called immediately after the main loop locks, so when one
648  * of the watchers registered an event.
649  * We check whether an X-Event arrived and handle it.
650  *
651  */
652 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
653     xcb_generic_event_t *event;
654     while ((event = xcb_poll_for_event(xcb_connection)) == NULL) {
655         return;
656     }
657
658     switch (event->response_type & ~0x80) {
659         case XCB_EXPOSE:
660             /* Expose-events happen, when the window needs to be redrawn */
661             redraw_bars();
662             break;
663         case XCB_BUTTON_PRESS:
664             /* Button-press-events are mouse-buttons clicked on one of our bars */
665             handle_button((xcb_button_press_event_t*) event);
666             break;
667         case XCB_CLIENT_MESSAGE:
668             /* Client messages are used for client-to-client communication, for
669              * example system tray widgets talk to us directly via client messages. */
670             handle_client_message((xcb_client_message_event_t*) event);
671             break;
672         case XCB_UNMAP_NOTIFY:
673             /* UnmapNotifies are received when a tray window unmaps itself */
674             handle_unmap_notify((xcb_unmap_notify_event_t*) event);
675             break;
676         case XCB_PROPERTY_NOTIFY:
677             /* PropertyNotify */
678             handle_property_notify((xcb_property_notify_event_t*) event);
679             break;
680     }
681     FREE(event);
682 }
683
684 /*
685  * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
686  * are triggered
687  *
688  */
689 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
690 }
691
692 /*
693  * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
694  *
695  */
696 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
697     XkbEvent ev;
698     int modstate = 0;
699
700     DLOG("Got XKB-Event!\n");
701
702     while (XPending(xkb_dpy)) {
703         XNextEvent(xkb_dpy, (XEvent*)&ev);
704
705         if (ev.type != xkb_event_base) {
706             ELOG("No Xkb-Event!\n");
707             continue;
708         }
709
710         if (ev.any.xkb_type != XkbStateNotify) {
711             ELOG("No State Notify!\n");
712             continue;
713         }
714
715         unsigned int mods = ev.state.mods;
716         modstate = mods & Mod4Mask;
717     }
718
719     if (modstate != mod_pressed) {
720         if (modstate == 0) {
721             DLOG("Mod4 got released!\n");
722             hide_bars();
723         } else {
724             DLOG("Mod4 got pressed!\n");
725             unhide_bars();
726         }
727         mod_pressed = modstate;
728     }
729 }
730
731 /*
732  * Initialize xcb and use the specified fontname for text-rendering
733  *
734  */
735 char *init_xcb(char *fontname) {
736     /* FIXME: xcb_connect leaks Memory */
737     xcb_connection = xcb_connect(NULL, &screen);
738     if (xcb_connection_has_error(xcb_connection)) {
739         ELOG("Cannot open display\n");
740         exit(EXIT_FAILURE);
741     }
742     DLOG("Connected to xcb\n");
743
744     /* We have to request the atoms we need */
745     #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
746     #include "xcb_atoms.def"
747
748     xcb_screen = xcb_setup_roots_iterator(xcb_get_setup(xcb_connection)).data;
749     xcb_root = xcb_screen->root;
750
751     /* We load and allocate the font */
752     xcb_font = xcb_generate_id(xcb_connection);
753     xcb_void_cookie_t open_font_cookie;
754     open_font_cookie = xcb_open_font_checked(xcb_connection,
755                                              xcb_font,
756                                              strlen(fontname),
757                                              fontname);
758
759     /* We need to save info about the font, because we need the font's height and
760      * information about the width of characters */
761     xcb_query_font_cookie_t query_font_cookie;
762     query_font_cookie = xcb_query_font(xcb_connection,
763                                        xcb_font);
764
765     /* To grab modifiers without blocking other applications from receiving key-events
766      * involving that modifier, we sadly have to use xkb which is not yet fully supported
767      * in xcb */
768     if (config.hide_on_modifier) {
769         int xkb_major, xkb_minor, xkb_errbase, xkb_err;
770         xkb_major = XkbMajorVersion;
771         xkb_minor = XkbMinorVersion;
772
773         xkb_dpy = XkbOpenDisplay(NULL,
774                                  &xkb_event_base,
775                                  &xkb_errbase,
776                                  &xkb_major,
777                                  &xkb_minor,
778                                  &xkb_err);
779
780         if (xkb_dpy == NULL) {
781             ELOG("No XKB!\n");
782             exit(EXIT_FAILURE);
783         }
784
785         if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
786             ELOG("Could not set FD_CLOEXEC on xkbdpy: %s\n", strerror(errno));
787             exit(EXIT_FAILURE);
788         }
789
790         int i1;
791         if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
792             ELOG("XKB not supported by X-server!\n");
793             exit(EXIT_FAILURE);
794         }
795
796         if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
797             ELOG("Could not grab Key!\n");
798             exit(EXIT_FAILURE);
799         }
800
801         xkb_io = malloc(sizeof(ev_io));
802         ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
803         ev_io_start(main_loop, xkb_io);
804         XFlush(xkb_dpy);
805     }
806
807     /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
808      * this way, we can choose to crop it */
809     uint32_t mask = XCB_GC_FOREGROUND;
810     uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
811
812     statusline_clear = xcb_generate_id(xcb_connection);
813     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
814                                                                statusline_clear,
815                                                                xcb_root,
816                                                                mask,
817                                                                vals);
818
819     mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
820     vals[0] = colors.bar_fg;
821     statusline_ctx = xcb_generate_id(xcb_connection);
822     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
823                                                             statusline_ctx,
824                                                             xcb_root,
825                                                             mask,
826                                                             vals);
827
828     statusline_pm = xcb_generate_id(xcb_connection);
829     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
830                                                                xcb_screen->root_depth,
831                                                                statusline_pm,
832                                                                xcb_root,
833                                                                xcb_screen->width_in_pixels,
834                                                                xcb_screen->height_in_pixels);
835
836
837     /* The various Watchers to communicate with xcb */
838     xcb_io = malloc(sizeof(ev_io));
839     xcb_prep = malloc(sizeof(ev_prepare));
840     xcb_chk = malloc(sizeof(ev_check));
841
842     ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
843     ev_prepare_init(xcb_prep, &xcb_prep_cb);
844     ev_check_init(xcb_chk, &xcb_chk_cb);
845
846     ev_io_start(main_loop, xcb_io);
847     ev_prepare_start(main_loop, xcb_prep);
848     ev_check_start(main_loop, xcb_chk);
849
850     /* Now we get the atoms and save them in a nice data structure */
851     get_atoms();
852
853     xcb_get_property_cookie_t path_cookie;
854     path_cookie = xcb_get_property_unchecked(xcb_connection,
855                                    0,
856                                    xcb_root,
857                                    atoms[I3_SOCKET_PATH],
858                                    XCB_GET_PROPERTY_TYPE_ANY,
859                                    0, PATH_MAX);
860
861     /* We check, if i3 set its socket-path */
862     xcb_get_property_reply_t *path_reply = xcb_get_property_reply(xcb_connection,
863                                                                   path_cookie,
864                                                                   NULL);
865     char *path = NULL;
866     if (path_reply) {
867         int len = xcb_get_property_value_length(path_reply);
868         if (len != 0) {
869             path = strndup(xcb_get_property_value(path_reply), len);
870         }
871     }
872
873     /* Now we save the font-infos */
874     font_info = xcb_query_font_reply(xcb_connection,
875                                      query_font_cookie,
876                                      NULL);
877
878     if (xcb_request_failed(open_font_cookie, "Could not open font")) {
879         exit(EXIT_FAILURE);
880     }
881
882     font_height = font_info->font_ascent + font_info->font_descent;
883
884     if (xcb_query_font_char_infos_length(font_info) == 0) {
885         font_table = NULL;
886     } else {
887         font_table = xcb_query_font_char_infos(font_info);
888     }
889
890     DLOG("Calculated Font-height: %d\n", font_height);
891
892     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
893         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
894         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
895         exit(EXIT_FAILURE);
896     }
897
898     return path;
899 }
900
901 /*
902  * Initializes tray support by requesting the appropriate _NET_SYSTEM_TRAY atom
903  * for the X11 display we are running on, then acquiring the selection for this
904  * atom. Afterwards, tray clients will send ClientMessages to our window.
905  *
906  */
907 void init_tray() {
908     /* request the tray manager atom for the X11 display we are running on */
909     char atomname[strlen("_NET_SYSTEM_TRAY_S") + 11];
910     snprintf(atomname, strlen("_NET_SYSTEM_TRAY_S") + 11, "_NET_SYSTEM_TRAY_S%d", screen);
911     xcb_intern_atom_cookie_t tray_cookie;
912     xcb_intern_atom_reply_t *tray_reply;
913     tray_cookie = xcb_intern_atom(xcb_connection, 0, strlen(atomname), atomname);
914
915     /* tray support: we need a window to own the selection */
916     xcb_window_t selwin = xcb_generate_id(xcb_connection);
917     uint32_t selmask = XCB_CW_OVERRIDE_REDIRECT;
918     uint32_t selval[] = { 1 };
919     xcb_create_window(xcb_connection,
920                       xcb_screen->root_depth,
921                       selwin,
922                       xcb_root,
923                       -1, -1,
924                       1, 1,
925                       1,
926                       XCB_WINDOW_CLASS_INPUT_OUTPUT,
927                       xcb_screen->root_visual,
928                       selmask,
929                       selval);
930
931     uint32_t orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
932     /* set the atoms */
933     xcb_change_property(xcb_connection,
934                         XCB_PROP_MODE_REPLACE,
935                         selwin,
936                         atoms[_NET_SYSTEM_TRAY_ORIENTATION],
937                         XCB_ATOM_CARDINAL,
938                         32,
939                         1,
940                         &orientation);
941
942     if (!(tray_reply = xcb_intern_atom_reply(xcb_connection, tray_cookie, NULL))) {
943         ELOG("Could not get atom %s\n", atomname);
944         exit(EXIT_FAILURE);
945     }
946
947     xcb_set_selection_owner(xcb_connection,
948                             selwin,
949                             tray_reply->atom,
950                             XCB_CURRENT_TIME);
951
952     /* Verify that we have the selection */
953     xcb_get_selection_owner_cookie_t selcookie;
954     xcb_get_selection_owner_reply_t *selreply;
955
956     selcookie = xcb_get_selection_owner(xcb_connection, tray_reply->atom);
957     if (!(selreply = xcb_get_selection_owner_reply(xcb_connection, selcookie, NULL))) {
958         ELOG("Could not get selection owner for %s\n", atomname);
959         exit(EXIT_FAILURE);
960     }
961
962     if (selreply->owner != selwin) {
963         ELOG("Could not set the %s selection. " \
964              "Maybe another tray is already running?\n", atomname);
965         /* NOTE that this error is not fatal. We just can’t provide tray
966          * functionality */
967         free(selreply);
968         return;
969     }
970
971     /* Inform clients waiting for a new _NET_SYSTEM_TRAY that we are here */
972     void *event = calloc(32, 1);
973     xcb_client_message_event_t *ev = event;
974     ev->response_type = XCB_CLIENT_MESSAGE;
975     ev->window = xcb_root;
976     ev->type = atoms[MANAGER];
977     ev->format = 32;
978     ev->data.data32[0] = XCB_CURRENT_TIME;
979     ev->data.data32[1] = tray_reply->atom;
980     ev->data.data32[2] = selwin;
981     xcb_send_event(xcb_connection,
982                    0,
983                    xcb_root,
984                    XCB_EVENT_MASK_STRUCTURE_NOTIFY,
985                    (char*)ev);
986     free(event);
987     free(tray_reply);
988 }
989
990 /*
991  * Cleanup the xcb-stuff.
992  * Called once, before the program terminates.
993  *
994  */
995 void clean_xcb() {
996     i3_output *o_walk;
997     trayclient *trayclient;
998     free_workspaces();
999     SLIST_FOREACH(o_walk, outputs, slist) {
1000         TAILQ_FOREACH(trayclient, o_walk->trayclients, tailq) {
1001             /* Unmap, then reparent (to root) the tray client windows */
1002             xcb_unmap_window(xcb_connection, trayclient->win);
1003             xcb_reparent_window(xcb_connection,
1004                                 trayclient->win,
1005                                 xcb_root,
1006                                 0,
1007                                 0);
1008         }
1009         destroy_window(o_walk);
1010         FREE(o_walk->trayclients);
1011         FREE(o_walk->workspaces);
1012         FREE(o_walk->name);
1013     }
1014     FREE_SLIST(outputs, i3_output);
1015     FREE(outputs);
1016
1017     xcb_flush(xcb_connection);
1018     xcb_disconnect(xcb_connection);
1019
1020     ev_check_stop(main_loop, xcb_chk);
1021     ev_prepare_stop(main_loop, xcb_prep);
1022     ev_io_stop(main_loop, xcb_io);
1023
1024     FREE(xcb_chk);
1025     FREE(xcb_prep);
1026     FREE(xcb_io);
1027     FREE(font_info);
1028 }
1029
1030 /*
1031  * Get the earlier requested atoms and save them in the prepared data structure
1032  *
1033  */
1034 void get_atoms() {
1035     xcb_intern_atom_reply_t *reply;
1036     #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
1037         if (reply == NULL) { \
1038             ELOG("Could not get atom %s\n", #name); \
1039             exit(EXIT_FAILURE); \
1040         } \
1041         atoms[name] = reply->atom; \
1042         free(reply);
1043
1044     #include "xcb_atoms.def"
1045     DLOG("Got Atoms\n");
1046 }
1047
1048 /*
1049  * Destroy the bar of the specified output
1050  *
1051  */
1052 void destroy_window(i3_output *output) {
1053     if (output == NULL) {
1054         return;
1055     }
1056     if (output->bar == XCB_NONE) {
1057         return;
1058     }
1059     xcb_destroy_window(xcb_connection, output->bar);
1060     output->bar = XCB_NONE;
1061 }
1062
1063 /*
1064  * Reallocate the statusline-buffer
1065  *
1066  */
1067 void realloc_sl_buffer() {
1068     xcb_free_pixmap(xcb_connection, statusline_pm);
1069     statusline_pm = xcb_generate_id(xcb_connection);
1070     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1071                                                                xcb_screen->root_depth,
1072                                                                statusline_pm,
1073                                                                xcb_root,
1074                                                                xcb_screen->width_in_pixels,
1075                                                                xcb_screen->height_in_pixels);
1076
1077     uint32_t mask = XCB_GC_FOREGROUND;
1078     uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
1079     xcb_free_gc(xcb_connection, statusline_clear);
1080     statusline_clear = xcb_generate_id(xcb_connection);
1081     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1082                                                                statusline_clear,
1083                                                                xcb_root,
1084                                                                mask,
1085                                                                vals);
1086
1087     mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
1088     vals[0] = colors.bar_fg;
1089     statusline_ctx = xcb_generate_id(xcb_connection);
1090     xcb_free_gc(xcb_connection, statusline_ctx);
1091     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1092                                                             statusline_ctx,
1093                                                             xcb_root,
1094                                                             mask,
1095                                                             vals);
1096
1097     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
1098         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
1099         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
1100         exit(EXIT_FAILURE);
1101     }
1102
1103 }
1104
1105 /*
1106  * Reconfigure all bars and create new bars for recently activated outputs
1107  *
1108  */
1109 void reconfig_windows() {
1110     uint32_t mask;
1111     uint32_t values[5];
1112
1113     i3_output *walk;
1114     SLIST_FOREACH(walk, outputs, slist) {
1115         if (!walk->active) {
1116             /* If an output is not active, we destroy its bar */
1117             /* FIXME: Maybe we rather want to unmap? */
1118             DLOG("Destroying window for output %s\n", walk->name);
1119             destroy_window(walk);
1120             continue;
1121         }
1122         if (walk->bar == XCB_NONE) {
1123             DLOG("Creating Window for output %s\n", walk->name);
1124
1125             /* TODO: only call init_tray() if the tray is configured for this output */
1126             init_tray();
1127
1128             walk->bar = xcb_generate_id(xcb_connection);
1129             walk->buffer = xcb_generate_id(xcb_connection);
1130             mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
1131             /* Black background */
1132             values[0] = colors.bar_bg;
1133             /* If hide_on_modifier is set, i3 is not supposed to manage our bar-windows */
1134             values[1] = config.hide_on_modifier;
1135             /* The events we want to receive */
1136             values[2] = XCB_EVENT_MASK_EXPOSURE;
1137             if (!config.disable_ws) {
1138                 values[2] |= XCB_EVENT_MASK_BUTTON_PRESS;
1139             }
1140             xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
1141                                                                      xcb_screen->root_depth,
1142                                                                      walk->bar,
1143                                                                      xcb_root,
1144                                                                      walk->rect.x, walk->rect.y + walk->rect.h - font_height - 6,
1145                                                                      walk->rect.w, font_height + 6,
1146                                                                      1,
1147                                                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,
1148                                                                      xcb_screen->root_visual,
1149                                                                      mask,
1150                                                                      values);
1151
1152             /* The double-buffer we use to render stuff off-screen */
1153             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1154                                                                     xcb_screen->root_depth,
1155                                                                     walk->buffer,
1156                                                                     walk->bar,
1157                                                                     walk->rect.w,
1158                                                                     walk->rect.h);
1159
1160             /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
1161              * this one */
1162             xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
1163                                                                 XCB_PROP_MODE_REPLACE,
1164                                                                 walk->bar,
1165                                                                 atoms[_NET_WM_WINDOW_TYPE],
1166                                                                 XCB_ATOM_ATOM,
1167                                                                 32,
1168                                                                 1,
1169                                                                 (unsigned char*) &atoms[_NET_WM_WINDOW_TYPE_DOCK]);
1170
1171             /* We need to tell i3, where to reserve space for i3bar */
1172             /* left, right, top, bottom, left_start_y, left_end_y,
1173              * right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x,
1174              * bottom_end_x */
1175             /* A local struct to save the strut_partial property */
1176             struct {
1177                 uint32_t left;
1178                 uint32_t right;
1179                 uint32_t top;
1180                 uint32_t bottom;
1181                 uint32_t left_start_y;
1182                 uint32_t left_end_y;
1183                 uint32_t right_start_y;
1184                 uint32_t right_end_y;
1185                 uint32_t top_start_x;
1186                 uint32_t top_end_x;
1187                 uint32_t bottom_start_x;
1188                 uint32_t bottom_end_x;
1189             } __attribute__((__packed__)) strut_partial = {0,};
1190             switch (config.dockpos) {
1191                 case DOCKPOS_NONE:
1192                     break;
1193                 case DOCKPOS_TOP:
1194                     strut_partial.top = font_height + 6;
1195                     strut_partial.top_start_x = walk->rect.x;
1196                     strut_partial.top_end_x = walk->rect.x + walk->rect.w;
1197                     break;
1198                 case DOCKPOS_BOT:
1199                     strut_partial.bottom = font_height + 6;
1200                     strut_partial.bottom_start_x = walk->rect.x;
1201                     strut_partial.bottom_end_x = walk->rect.x + walk->rect.w;
1202                     break;
1203             }
1204             xcb_void_cookie_t strut_cookie = xcb_change_property(xcb_connection,
1205                                                                  XCB_PROP_MODE_REPLACE,
1206                                                                  walk->bar,
1207                                                                  atoms[_NET_WM_STRUT_PARTIAL],
1208                                                                  XCB_ATOM_CARDINAL,
1209                                                                  32,
1210                                                                  12,
1211                                                                  &strut_partial);
1212
1213             /* We also want a graphics-context for the bars (it defines the properties
1214              * with which we draw to them) */
1215             walk->bargc = xcb_generate_id(xcb_connection);
1216             mask = XCB_GC_FONT;
1217             values[0] = xcb_font;
1218             xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
1219                                                                 walk->bargc,
1220                                                                 walk->bar,
1221                                                                 mask,
1222                                                                 values);
1223
1224             /* We finally map the bar (display it on screen), unless the modifier-switch is on */
1225             xcb_void_cookie_t map_cookie;
1226             if (!config.hide_on_modifier) {
1227                 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
1228             }
1229
1230             if (xcb_request_failed(win_cookie,   "Could not create window") ||
1231                 xcb_request_failed(pm_cookie,    "Could not create pixmap") ||
1232                 xcb_request_failed(dock_cookie,  "Could not set dock mode") ||
1233                 xcb_request_failed(strut_cookie, "Could not set strut")     ||
1234                 xcb_request_failed(gc_cookie,    "Could not create graphical context") ||
1235                 (!config.hide_on_modifier && xcb_request_failed(map_cookie, "Could not map window"))) {
1236                 exit(EXIT_FAILURE);
1237             }
1238         } else {
1239             /* We already have a bar, so we just reconfigure it */
1240             mask = XCB_CONFIG_WINDOW_X |
1241                    XCB_CONFIG_WINDOW_Y |
1242                    XCB_CONFIG_WINDOW_WIDTH |
1243                    XCB_CONFIG_WINDOW_HEIGHT |
1244                    XCB_CONFIG_WINDOW_STACK_MODE;
1245             values[0] = walk->rect.x;
1246             values[1] = walk->rect.y + walk->rect.h - font_height - 6;
1247             values[2] = walk->rect.w;
1248             values[3] = font_height + 6;
1249             values[4] = XCB_STACK_MODE_ABOVE;
1250
1251             DLOG("Destroying buffer for output %s", walk->name);
1252             xcb_free_pixmap(xcb_connection, walk->buffer);
1253
1254             DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
1255             xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
1256                                                                         walk->bar,
1257                                                                         mask,
1258                                                                         values);
1259
1260             DLOG("Recreating buffer for output %s", walk->name);
1261             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1262                                                                     xcb_screen->root_depth,
1263                                                                     walk->buffer,
1264                                                                     walk->bar,
1265                                                                     walk->rect.w,
1266                                                                     walk->rect.h);
1267
1268             if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
1269                 exit(EXIT_FAILURE);
1270             }
1271             if (xcb_request_failed(pm_cookie,  "Could not create pixmap")) {
1272                 exit(EXIT_FAILURE);
1273             }
1274         }
1275     }
1276 }
1277
1278 /*
1279  * Render the bars, with buttons and statusline
1280  *
1281  */
1282 void draw_bars() {
1283     DLOG("Drawing Bars...\n");
1284     int i = 0;
1285
1286     refresh_statusline();
1287
1288     i3_output *outputs_walk;
1289     SLIST_FOREACH(outputs_walk, outputs, slist) {
1290         if (!outputs_walk->active) {
1291             DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
1292             continue;
1293         }
1294         if (outputs_walk->bar == XCB_NONE) {
1295             /* Oh shit, an active output without an own bar. Create it now! */
1296             reconfig_windows();
1297         }
1298         /* First things first: clear the backbuffer */
1299         uint32_t color = colors.bar_bg;
1300         xcb_change_gc(xcb_connection,
1301                       outputs_walk->bargc,
1302                       XCB_GC_FOREGROUND,
1303                       &color);
1304         xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font_height + 6 };
1305         xcb_poly_fill_rectangle(xcb_connection,
1306                                 outputs_walk->buffer,
1307                                 outputs_walk->bargc,
1308                                 1,
1309                                 &rect);
1310
1311         if (statusline != NULL) {
1312             DLOG("Printing statusline!\n");
1313
1314             /* Luckily we already prepared a seperate pixmap containing the rendered
1315              * statusline, we just have to copy the relevant parts to the relevant
1316              * position */
1317             trayclient *trayclient;
1318             int traypx = 0;
1319             TAILQ_FOREACH(trayclient, outputs_walk->trayclients, tailq) {
1320                 if (!trayclient->mapped)
1321                     continue;
1322                 /* We assume the tray icons are quadratic (we use the font
1323                  * *height* as *width* of the icons) because we configured them
1324                  * like this. */
1325                 traypx += font_height;
1326             }
1327             /* Add 2px of padding if there are any tray icons */
1328             if (traypx > 0)
1329                 traypx += 2;
1330             xcb_copy_area(xcb_connection,
1331                           statusline_pm,
1332                           outputs_walk->buffer,
1333                           outputs_walk->bargc,
1334                           MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
1335                           MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - traypx - 4)), 3,
1336                           MIN(outputs_walk->rect.w - traypx - 4, statusline_width), font_height);
1337         }
1338
1339         if (config.disable_ws) {
1340             continue;
1341         }
1342
1343         i3_ws *ws_walk;
1344         TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
1345             DLOG("Drawing Button for WS %s at x = %d\n", ws_walk->name, i);
1346             uint32_t fg_color = colors.inactive_ws_fg;
1347             uint32_t bg_color = colors.inactive_ws_bg;
1348             if (ws_walk->visible) {
1349                 if (!ws_walk->focused) {
1350                     fg_color = colors.active_ws_fg;
1351                     bg_color = colors.active_ws_bg;
1352                 } else {
1353                     fg_color = colors.focus_ws_fg;
1354                     bg_color = colors.focus_ws_bg;
1355                 }
1356             }
1357             if (ws_walk->urgent) {
1358                 DLOG("WS %s is urgent!\n", ws_walk->name);
1359                 fg_color = colors.urgent_ws_fg;
1360                 bg_color = colors.urgent_ws_bg;
1361                 /* The urgent-hint should get noticed, so we unhide the bars shortly */
1362                 unhide_bars();
1363             }
1364             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
1365             uint32_t vals[] = { bg_color, bg_color };
1366             xcb_change_gc(xcb_connection,
1367                           outputs_walk->bargc,
1368                           mask,
1369                           vals);
1370             xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font_height + 4 };
1371             xcb_poly_fill_rectangle(xcb_connection,
1372                                     outputs_walk->buffer,
1373                                     outputs_walk->bargc,
1374                                     1,
1375                                     &rect);
1376             xcb_change_gc(xcb_connection,
1377                           outputs_walk->bargc,
1378                           XCB_GC_FOREGROUND,
1379                           &fg_color);
1380             xcb_image_text_16(xcb_connection,
1381                               ws_walk->name_glyphs,
1382                               outputs_walk->buffer,
1383                               outputs_walk->bargc,
1384                               i + 5, font_info->font_ascent + 2,
1385                               ws_walk->ucs2_name);
1386             i += 10 + ws_walk->name_width;
1387         }
1388
1389         i = 0;
1390     }
1391
1392     redraw_bars();
1393 }
1394
1395 /*
1396  * Redraw the bars, i.e. simply copy the buffer to the barwindow
1397  *
1398  */
1399 void redraw_bars() {
1400     i3_output *outputs_walk;
1401     SLIST_FOREACH(outputs_walk, outputs, slist) {
1402         if (!outputs_walk->active) {
1403             continue;
1404         }
1405         xcb_copy_area(xcb_connection,
1406                       outputs_walk->buffer,
1407                       outputs_walk->bar,
1408                       outputs_walk->bargc,
1409                       0, 0,
1410                       0, 0,
1411                       outputs_walk->rect.w,
1412                       outputs_walk->rect.h);
1413         xcb_flush(xcb_connection);
1414     }
1415 }