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