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