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