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