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