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