]> git.sur5r.net Git - i3/i3/blob - i3bar/src/xcb.c
i3bar: Correctly handle removal of tray clients
[i3/i3] / i3bar / src / xcb.c
1 /*
2  * i3bar - an xcb-based status- and ws-bar for i3
3  *
4  * © 2010-2011 Axel Wagner and contributors
5  *
6  * See file LICNSE for license information
7  *
8  * src/xcb.c: Communicating with X
9  *
10  */
11 #include <xcb/xcb.h>
12 #include <xcb/xproto.h>
13 #include <xcb/xcb_atom.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <fcntl.h>
18 #include <string.h>
19 #include <i3/ipc.h>
20 #include <ev.h>
21 #include <errno.h>
22 #include <limits.h>
23
24 #include <X11/Xlib.h>
25 #include <X11/XKBlib.h>
26 #include <X11/extensions/XKB.h>
27
28 #include "common.h"
29
30 #if defined(__APPLE__)
31
32 /*
33  * Taken from FreeBSD
34  * Returns a pointer to a new string which is a duplicate of the
35  * string, but only copies at most n characters.
36  *
37  */
38 char *strndup(const char *str, size_t n) {
39     size_t len;
40     char *copy;
41
42     for (len = 0; len < n && str[len]; len++)
43         continue;
44
45     if ((copy = malloc(len + 1)) == NULL)
46         return (NULL);
47     memcpy(copy, str, len);
48     copy[len] = '\0';
49     return (copy);
50 }
51
52 #endif
53
54 /* We save the Atoms in an easy to access array, indexed by an enum */
55 enum {
56     #define ATOM_DO(name) name,
57     #include "xcb_atoms.def"
58     NUM_ATOMS
59 };
60
61 xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
62 xcb_atom_t               atoms[NUM_ATOMS];
63
64 /* Variables, that are the same for all functions at all times */
65 xcb_connection_t *xcb_connection;
66 xcb_screen_t     *xcb_screen;
67 xcb_window_t     xcb_root;
68 xcb_font_t       xcb_font;
69
70 /* We need to cache some data to speed up text-width-prediction */
71 xcb_query_font_reply_t *font_info;
72 int                    font_height;
73 xcb_charinfo_t         *font_table;
74
75 /* These are only relevant for XKB, which we only need for grabbing modifiers */
76 Display          *xkb_dpy;
77 int              xkb_event_base;
78 int              mod_pressed = 0;
79
80 /* Because the statusline is the same on all outputs, we have
81  * global buffer to render it on */
82 xcb_gcontext_t   statusline_ctx;
83 xcb_gcontext_t   statusline_clear;
84 xcb_pixmap_t     statusline_pm;
85 uint32_t         statusline_width;
86
87 /* Event-Watchers, to interact with the user */
88 ev_prepare *xcb_prep;
89 ev_check   *xcb_chk;
90 ev_io      *xcb_io;
91 ev_io      *xkb_io;
92
93 /* The parsed colors */
94 struct xcb_colors_t {
95     uint32_t bar_fg;
96     uint32_t bar_bg;
97     uint32_t active_ws_fg;
98     uint32_t active_ws_bg;
99     uint32_t inactive_ws_fg;
100     uint32_t inactive_ws_bg;
101     uint32_t urgent_ws_bg;
102     uint32_t urgent_ws_fg;
103     uint32_t focus_ws_bg;
104     uint32_t focus_ws_fg;
105 };
106 struct xcb_colors_t colors;
107
108 /* We define xcb_request_failed as a macro to include the relevant line-number */
109 #define xcb_request_failed(cookie, err_msg) _xcb_request_failed(cookie, err_msg, __LINE__)
110 int _xcb_request_failed(xcb_void_cookie_t cookie, char *err_msg, int line) {
111     xcb_generic_error_t *err;
112     if ((err = xcb_request_check(xcb_connection, cookie)) != NULL) {
113         fprintf(stderr, "[%s:%d] ERROR: %s. X Error Code: %d\n", __FILE__, line, err_msg, err->error_code);
114         return err->error_code;
115     }
116     return 0;
117 }
118
119 /*
120  * Predicts the length of text based on cached data.
121  * The string has to be encoded in ucs2 and glyph_len has to be the length
122  * of the string (in glyphs).
123  *
124  */
125 uint32_t predict_text_extents(xcb_char2b_t *text, uint32_t length) {
126     /* If we don't have per-character data, return the maximum width */
127     if (font_table == NULL) {
128         return (font_info->max_bounds.character_width * length);
129     }
130
131     uint32_t width = 0;
132     uint32_t i;
133
134     for (i = 0; i < length; i++) {
135         xcb_charinfo_t *info;
136         int row = text[i].byte1;
137         int col = text[i].byte2;
138
139         if (row < font_info->min_byte1 || row > font_info->max_byte1 ||
140             col < font_info->min_char_or_byte2 || col > font_info->max_char_or_byte2) {
141             continue;
142         }
143
144         /* Don't you ask me, how this one works… */
145         info = &font_table[((row - font_info->min_byte1) *
146                             (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
147                            (col - font_info->min_char_or_byte2)];
148
149         if (info->character_width != 0 ||
150             (info->right_side_bearing |
151              info->left_side_bearing |
152              info->ascent |
153              info->descent) != 0) {
154             width += info->character_width;
155         }
156     }
157
158     return width;
159 }
160
161 /*
162  * Draws text given in UCS-2-encoding to a given drawable and position
163  *
164  */
165 void draw_text(xcb_drawable_t drawable, xcb_gcontext_t ctx, int16_t x, int16_t y,
166                xcb_char2b_t *text, uint32_t glyph_count) {
167     int offset = 0;
168     int16_t pos_x = x;
169     int16_t font_ascent = font_info->font_ascent;
170
171     while (glyph_count > 0) {
172         uint8_t chunk_size = MIN(255, glyph_count);
173         uint32_t chunk_width = predict_text_extents(text + offset, chunk_size);
174
175         xcb_image_text_16(xcb_connection,
176                           chunk_size,
177                           drawable,
178                           ctx,
179                           pos_x, y + font_ascent,
180                           text + offset);
181
182         offset += chunk_size;
183         pos_x += chunk_width;
184         glyph_count -= chunk_size;
185     }
186 }
187
188 /*
189  * Converts a colorstring to a colorpixel as expected from xcb_change_gc.
190  * s is assumed to be in the format "rrggbb"
191  *
192  */
193 uint32_t get_colorpixel(const char *s) {
194     char strings[3][3] = { { s[0], s[1], '\0'} ,
195                            { s[2], s[3], '\0'} ,
196                            { s[4], s[5], '\0'} };
197     uint8_t r = strtol(strings[0], NULL, 16);
198     uint8_t g = strtol(strings[1], NULL, 16);
199     uint8_t b = strtol(strings[2], NULL, 16);
200     return (r << 16 | g << 8 | b);
201 }
202
203 /*
204  * Redraws the statusline to the buffer
205  *
206  */
207 void refresh_statusline() {
208     int glyph_count;
209
210     if (statusline == NULL) {
211         return;
212     }
213
214     xcb_char2b_t *text = (xcb_char2b_t*) convert_utf8_to_ucs2(statusline, &glyph_count);
215     statusline_width = predict_text_extents(text, glyph_count);
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         values[1] = walk->rect.y + walk->rect.h - font_height - 6;
270         values[2] = walk->rect.w;
271         values[3] = font_height + 6;
272         values[4] = XCB_STACK_MODE_ABOVE;
273         DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
274         cookie = xcb_configure_window_checked(xcb_connection,
275                                               walk->bar,
276                                               mask,
277                                               values);
278
279         if (xcb_request_failed(cookie, "Could not reconfigure window")) {
280             exit(EXIT_FAILURE);
281         }
282         xcb_map_window(xcb_connection, walk->bar);
283     }
284 }
285
286 /*
287  * Parse the colors into a format that we can use
288  *
289  */
290 void init_colors(const struct xcb_color_strings_t *new_colors) {
291 #define PARSE_COLOR(name, def) \
292     do { \
293         colors.name = get_colorpixel(new_colors->name ? new_colors->name : def); \
294     } while  (0)
295     PARSE_COLOR(bar_fg, "FFFFFF");
296     PARSE_COLOR(bar_bg, "000000");
297     PARSE_COLOR(active_ws_fg, "FFFFFF");
298     PARSE_COLOR(active_ws_bg, "480000");
299     PARSE_COLOR(inactive_ws_fg, "FFFFFF");
300     PARSE_COLOR(inactive_ws_bg, "240000");
301     PARSE_COLOR(urgent_ws_fg, "FFFFFF");
302     PARSE_COLOR(urgent_ws_bg, "002400");
303     PARSE_COLOR(focus_ws_fg, "FFFFFF");
304     PARSE_COLOR(focus_ws_bg, "480000");
305 #undef PARSE_COLOR
306 }
307
308 /*
309  * Handle a button-press-event (i.e. a mouse click on one of our bars).
310  * We determine, whether the click occured on a ws-button or if the scroll-
311  * wheel was used and change the workspace appropriately
312  *
313  */
314 void handle_button(xcb_button_press_event_t *event) {
315     i3_ws *cur_ws;
316
317     /* Determine, which bar was clicked */
318     i3_output *walk;
319     xcb_window_t bar = event->event;
320     SLIST_FOREACH(walk, outputs, slist) {
321         if (walk->bar == bar) {
322             break;
323         }
324     }
325
326     if (walk == NULL) {
327         DLOG("Unknown Bar klicked!\n");
328         return;
329     }
330
331     /* TODO: Move this to extern get_ws_for_output() */
332     TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
333         if (cur_ws->visible) {
334             break;
335         }
336     }
337
338     if (cur_ws == NULL) {
339         DLOG("No Workspace active?\n");
340         return;
341     }
342
343     int32_t x = event->event_x;
344
345     DLOG("Got Button %d\n", event->detail);
346
347     switch (event->detail) {
348         case 1:
349             /* Left Mousbutton. We determine, which button was clicked
350              * and set cur_ws accordingly */
351             TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
352                 DLOG("x = %d\n", x);
353                 if (x < cur_ws->name_width + 10) {
354                     break;
355                 }
356                 x -= cur_ws->name_width + 10;
357             }
358             if (cur_ws == NULL) {
359                 return;
360             }
361             break;
362         case 4:
363             /* Mouse wheel down. We select the next ws */
364             if (cur_ws == TAILQ_FIRST(walk->workspaces)) {
365                 cur_ws = TAILQ_LAST(walk->workspaces, ws_head);
366             } else {
367                 cur_ws = TAILQ_PREV(cur_ws, ws_head, tailq);
368             }
369             break;
370         case 5:
371             /* Mouse wheel up. We select the previos ws */
372             if (cur_ws == TAILQ_LAST(walk->workspaces, ws_head)) {
373                 cur_ws = TAILQ_FIRST(walk->workspaces);
374             } else {
375                 cur_ws = TAILQ_NEXT(cur_ws, tailq);
376             }
377             break;
378     }
379
380     const size_t len = strlen(cur_ws->name) + strlen("workspace \"\"") + 1;
381     char buffer[len];
382     snprintf(buffer, len, "workspace \"%s\"", cur_ws->name);
383     i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
384 }
385
386 void handle_client_message(xcb_client_message_event_t* event) {
387     printf("got a client message, yay\n");
388     if (event->type == atoms[_NET_SYSTEM_TRAY_OPCODE] &&
389         event->format == 32) {
390         printf("system tray message\n");
391         /* event->data.data32[0] is the timestamp */
392         uint32_t op = event->data.data32[1];
393 #define SYSTEM_TRAY_REQUEST_DOCK    0
394 #define SYSTEM_TRAY_BEGIN_MESSAGE   1
395 #define SYSTEM_TRAY_CANCEL_MESSAGE  2
396         if (op == SYSTEM_TRAY_REQUEST_DOCK) {
397             printf("docking requested of x window id %d\n", event->data.data32[2]);
398             /* TODO: correctly handle multiple dock clients */
399             xcb_window_t client = event->data.data32[2];
400             i3_output *walk, *output;
401             SLIST_FOREACH(walk, outputs, slist) {
402                 if (!walk->active)
403                     continue;
404                 printf("using output %s\n", walk->name);
405                 output = walk;
406             }
407             xcb_reparent_window(xcb_connection,
408                                 client,
409                                 output->bar,
410                                 output->rect.w - font_height - 2, /* TODO: why -2? */
411                                 2);
412             /* We reconfigure the window to use a reasonable size. The systray
413              * specification explicitly says:
414              *   Tray icons may be assigned any size by the system tray, and
415              *   should do their best to cope with any size effectively
416              */
417             uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
418             uint32_t values[] = { font_height, font_height };
419             xcb_configure_window(xcb_connection,
420                                  client,
421                                  mask,
422                                  values);
423
424             /* Listen for PropertyNotify events to get the most recent value of
425              * the XEMBED_MAPPED atom, also listen for UnmapNotify events */
426             mask = XCB_CW_EVENT_MASK;
427             values[0] = XCB_EVENT_MASK_PROPERTY_CHANGE |
428                     XCB_EVENT_MASK_STRUCTURE_NOTIFY;
429             xcb_change_window_attributes(xcb_connection,
430                                          client,
431                                          mask,
432                                          values);
433             xcb_map_window(xcb_connection, client);
434             trayclient *tc = malloc(sizeof(trayclient));
435             tc->win = client;
436             TAILQ_INSERT_TAIL(output->trayclients, tc, tailq);
437
438             /* Trigger an update to copy the statusline text to the appropriate
439              * position */
440             draw_bars();
441         }
442     }
443 }
444
445 void handle_unmap_notify(xcb_unmap_notify_event_t* event) {
446     DLOG("UnmapNotify for window = %08x, event = %08x\n", event->window, event->event);
447
448     i3_output *walk;
449     SLIST_FOREACH(walk, outputs, slist) {
450         if (!walk->active)
451             continue;
452         DLOG("checking output %s\n", walk->name);
453         trayclient *trayclient;
454         TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
455             if (trayclient->win != event->window)
456                 continue;
457
458             DLOG("Removing tray client with window ID %08x\n", event->window);
459             TAILQ_REMOVE(walk->trayclients, trayclient, tailq);
460
461             /* Trigger an update, we now have more space for the statusline */
462             draw_bars();
463             return;
464         }
465     }
466 }
467
468 /*
469  * This function is called immediately before the main loop locks. We flush xcb
470  * then (and only then)
471  *
472  */
473 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revents) {
474     xcb_flush(xcb_connection);
475 }
476
477 /*
478  * This function is called immediately after the main loop locks, so when one
479  * of the watchers registered an event.
480  * We check whether an X-Event arrived and handle it.
481  *
482  */
483 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
484     xcb_generic_event_t *event;
485     while ((event = xcb_poll_for_event(xcb_connection)) == NULL) {
486         return;
487     }
488
489     switch (event->response_type & ~0x80) {
490         case XCB_EXPOSE:
491             /* Expose-events happen, when the window needs to be redrawn */
492             redraw_bars();
493             break;
494         case XCB_BUTTON_PRESS:
495             /* Button-press-events are mouse-buttons clicked on one of our bars */
496             handle_button((xcb_button_press_event_t*) event);
497             break;
498         case XCB_CLIENT_MESSAGE:
499             /* Client messages are used for client-to-client communication, for
500              * example system tray widgets talk to us directly via client messages. */
501             handle_client_message((xcb_client_message_event_t*) event);
502             break;
503         case XCB_UNMAP_NOTIFY:
504             /* UnmapNotifies are received when a tray window unmaps itself */
505             handle_unmap_notify((xcb_unmap_notify_event_t*) event);
506             break;
507     }
508     FREE(event);
509 }
510
511 /*
512  * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
513  * are triggered
514  *
515  */
516 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
517 }
518
519 /*
520  * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
521  *
522  */
523 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
524     XkbEvent ev;
525     int modstate = 0;
526
527     DLOG("Got XKB-Event!\n");
528
529     while (XPending(xkb_dpy)) {
530         XNextEvent(xkb_dpy, (XEvent*)&ev);
531
532         if (ev.type != xkb_event_base) {
533             ELOG("No Xkb-Event!\n");
534             continue;
535         }
536
537         if (ev.any.xkb_type != XkbStateNotify) {
538             ELOG("No State Notify!\n");
539             continue;
540         }
541
542         unsigned int mods = ev.state.mods;
543         modstate = mods & Mod4Mask;
544     }
545
546     if (modstate != mod_pressed) {
547         if (modstate == 0) {
548             DLOG("Mod4 got released!\n");
549             hide_bars();
550         } else {
551             DLOG("Mod4 got pressed!\n");
552             unhide_bars();
553         }
554         mod_pressed = modstate;
555     }
556 }
557
558 /*
559  * Initialize xcb and use the specified fontname for text-rendering
560  *
561  */
562 char *init_xcb(char *fontname) {
563     /* FIXME: xcb_connect leaks Memory */
564     xcb_connection = xcb_connect(NULL, NULL);
565     if (xcb_connection_has_error(xcb_connection)) {
566         ELOG("Cannot open display\n");
567         exit(EXIT_FAILURE);
568     }
569     DLOG("Connected to xcb\n");
570
571     /* We have to request the atoms we need */
572     #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
573     #include "xcb_atoms.def"
574
575     xcb_screen = xcb_setup_roots_iterator(xcb_get_setup(xcb_connection)).data;
576     xcb_root = xcb_screen->root;
577
578     /* We load and allocate the font */
579     xcb_font = xcb_generate_id(xcb_connection);
580     xcb_void_cookie_t open_font_cookie;
581     open_font_cookie = xcb_open_font_checked(xcb_connection,
582                                              xcb_font,
583                                              strlen(fontname),
584                                              fontname);
585
586     /* We need to save info about the font, because we need the font's height and
587      * information about the width of characters */
588     xcb_query_font_cookie_t query_font_cookie;
589     query_font_cookie = xcb_query_font(xcb_connection,
590                                        xcb_font);
591
592     /* To grab modifiers without blocking other applications from receiving key-events
593      * involving that modifier, we sadly have to use xkb which is not yet fully supported
594      * in xcb */
595     if (config.hide_on_modifier) {
596         int xkb_major, xkb_minor, xkb_errbase, xkb_err;
597         xkb_major = XkbMajorVersion;
598         xkb_minor = XkbMinorVersion;
599
600         xkb_dpy = XkbOpenDisplay(NULL,
601                                  &xkb_event_base,
602                                  &xkb_errbase,
603                                  &xkb_major,
604                                  &xkb_minor,
605                                  &xkb_err);
606
607         if (xkb_dpy == NULL) {
608             ELOG("No XKB!\n");
609             exit(EXIT_FAILURE);
610         }
611
612         if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
613             ELOG("Could not set FD_CLOEXEC on xkbdpy: %s\n", strerror(errno));
614             exit(EXIT_FAILURE);
615         }
616
617         int i1;
618         if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
619             ELOG("XKB not supported by X-server!\n");
620             exit(EXIT_FAILURE);
621         }
622
623         if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
624             ELOG("Could not grab Key!\n");
625             exit(EXIT_FAILURE);
626         }
627
628         xkb_io = malloc(sizeof(ev_io));
629         ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
630         ev_io_start(main_loop, xkb_io);
631         XFlush(xkb_dpy);
632     }
633
634     /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
635      * this way, we can choose to crop it */
636     uint32_t mask = XCB_GC_FOREGROUND;
637     uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
638
639     statusline_clear = xcb_generate_id(xcb_connection);
640     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
641                                                                statusline_clear,
642                                                                xcb_root,
643                                                                mask,
644                                                                vals);
645
646     mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
647     vals[0] = colors.bar_fg;
648     statusline_ctx = xcb_generate_id(xcb_connection);
649     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
650                                                             statusline_ctx,
651                                                             xcb_root,
652                                                             mask,
653                                                             vals);
654
655     statusline_pm = xcb_generate_id(xcb_connection);
656     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
657                                                                xcb_screen->root_depth,
658                                                                statusline_pm,
659                                                                xcb_root,
660                                                                xcb_screen->width_in_pixels,
661                                                                xcb_screen->height_in_pixels);
662
663
664     /* The various Watchers to communicate with xcb */
665     xcb_io = malloc(sizeof(ev_io));
666     xcb_prep = malloc(sizeof(ev_prepare));
667     xcb_chk = malloc(sizeof(ev_check));
668
669     ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
670     ev_prepare_init(xcb_prep, &xcb_prep_cb);
671     ev_check_init(xcb_chk, &xcb_chk_cb);
672
673     ev_io_start(main_loop, xcb_io);
674     ev_prepare_start(main_loop, xcb_prep);
675     ev_check_start(main_loop, xcb_chk);
676
677     /* Now we get the atoms and save them in a nice data structure */
678     get_atoms();
679
680     xcb_get_property_cookie_t path_cookie;
681     path_cookie = xcb_get_property_unchecked(xcb_connection,
682                                    0,
683                                    xcb_root,
684                                    atoms[I3_SOCKET_PATH],
685                                    XCB_GET_PROPERTY_TYPE_ANY,
686                                    0, PATH_MAX);
687
688     /* We check, if i3 set its socket-path */
689     xcb_get_property_reply_t *path_reply = xcb_get_property_reply(xcb_connection,
690                                                                   path_cookie,
691                                                                   NULL);
692     char *path = NULL;
693     if (path_reply) {
694         int len = xcb_get_property_value_length(path_reply);
695         if (len != 0) {
696             path = strndup(xcb_get_property_value(path_reply), len);
697         }
698     }
699
700     /* Now we save the font-infos */
701     font_info = xcb_query_font_reply(xcb_connection,
702                                      query_font_cookie,
703                                      NULL);
704
705     if (xcb_request_failed(open_font_cookie, "Could not open font")) {
706         exit(EXIT_FAILURE);
707     }
708
709     font_height = font_info->font_ascent + font_info->font_descent;
710
711     if (xcb_query_font_char_infos_length(font_info) == 0) {
712         font_table = NULL;
713     } else {
714         font_table = xcb_query_font_char_infos(font_info);
715     }
716
717     DLOG("Calculated Font-height: %d\n", font_height);
718
719     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
720         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
721         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
722         exit(EXIT_FAILURE);
723     }
724
725     return path;
726 }
727
728 void init_tray() {
729 /* tray support: we need a window to own the selection */
730     xcb_void_cookie_t selwin_cookie;
731     xcb_window_t selwin = xcb_generate_id(xcb_connection);
732     uint32_t selmask = XCB_CW_OVERRIDE_REDIRECT;
733     uint32_t selval[] = { 1 };
734     selwin_cookie = xcb_create_window_checked(xcb_connection,
735                                               xcb_screen->root_depth,
736                                               selwin,
737                                               xcb_root,
738                                               -1, -1,
739                                               1, 1,
740                                               1,
741                                               XCB_WINDOW_CLASS_INPUT_OUTPUT,
742                                               xcb_screen->root_visual,
743                                               selmask,
744                                               selval);
745
746 #define _NET_SYSTEM_TRAY_ORIENTATION_HORZ 0
747 #define _NET_SYSTEM_TRAY_ORIENTATION_VERT 1
748     uint32_t orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
749     /* set the atoms */
750     xcb_change_property(xcb_connection,
751                         XCB_PROP_MODE_REPLACE,
752                         selwin,
753                         atoms[_NET_SYSTEM_TRAY_ORIENTATION],
754                         atoms[CARDINAL],
755                         32,
756                         1,
757                         &orientation);
758
759
760     xcb_set_selection_owner(xcb_connection,
761                             selwin,
762                             /* TODO: request this atom separately */
763                             atoms[_NET_SYSTEM_TRAY_S0],
764                             XCB_CURRENT_TIME);
765     /* FIXME: don't use XCB_CURRENT_TIME */
766
767     /* TODO: check if we got the selection */
768     void *event = calloc(32, 1);
769     xcb_client_message_event_t *ev = event;
770     ev->response_type = XCB_CLIENT_MESSAGE;
771     ev->window = xcb_root;
772     ev->type = atoms[MANAGER];
773     ev->format = 32;
774     ev->data.data32[0] = XCB_CURRENT_TIME;
775     ev->data.data32[1] = atoms[_NET_SYSTEM_TRAY_S0];
776     ev->data.data32[2] = selwin;
777     xcb_send_event(xcb_connection,
778                    0,
779                    xcb_root,
780                    XCB_EVENT_MASK_STRUCTURE_NOTIFY,
781                    (char*)ev);
782 }
783
784 /*
785  * Cleanup the xcb-stuff.
786  * Called once, before the program terminates.
787  *
788  */
789 void clean_xcb() {
790     i3_output *o_walk;
791     free_workspaces();
792     SLIST_FOREACH(o_walk, outputs, slist) {
793         destroy_window(o_walk);
794         FREE(o_walk->workspaces);
795         FREE(o_walk->name);
796     }
797     FREE_SLIST(outputs, i3_output);
798     FREE(outputs);
799
800     xcb_disconnect(xcb_connection);
801
802     ev_check_stop(main_loop, xcb_chk);
803     ev_prepare_stop(main_loop, xcb_prep);
804     ev_io_stop(main_loop, xcb_io);
805
806     FREE(xcb_chk);
807     FREE(xcb_prep);
808     FREE(xcb_io);
809     FREE(font_info);
810 }
811
812 /*
813  * Get the earlier requested atoms and save them in the prepared data structure
814  *
815  */
816 void get_atoms() {
817     xcb_intern_atom_reply_t *reply;
818     #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
819         if (reply == NULL) { \
820             ELOG("Could not get atom %s\n", #name); \
821             exit(EXIT_FAILURE); \
822         } \
823         atoms[name] = reply->atom; \
824         free(reply);
825
826     #include "xcb_atoms.def"
827     DLOG("Got Atoms\n");
828 }
829
830 /*
831  * Destroy the bar of the specified output
832  *
833  */
834 void destroy_window(i3_output *output) {
835     if (output == NULL) {
836         return;
837     }
838     if (output->bar == XCB_NONE) {
839         return;
840     }
841     xcb_destroy_window(xcb_connection, output->bar);
842     output->bar = XCB_NONE;
843 }
844
845 /*
846  * Reallocate the statusline-buffer
847  *
848  */
849 void realloc_sl_buffer() {
850     xcb_free_pixmap(xcb_connection, statusline_pm);
851     statusline_pm = xcb_generate_id(xcb_connection);
852     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
853                                                                xcb_screen->root_depth,
854                                                                statusline_pm,
855                                                                xcb_root,
856                                                                xcb_screen->width_in_pixels,
857                                                                xcb_screen->height_in_pixels);
858
859     uint32_t mask = XCB_GC_FOREGROUND;
860     uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
861     xcb_free_gc(xcb_connection, statusline_clear);
862     statusline_clear = xcb_generate_id(xcb_connection);
863     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
864                                                                statusline_clear,
865                                                                xcb_root,
866                                                                mask,
867                                                                vals);
868
869     mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
870     vals[0] = colors.bar_fg;
871     statusline_ctx = xcb_generate_id(xcb_connection);
872     xcb_free_gc(xcb_connection, statusline_ctx);
873     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
874                                                             statusline_ctx,
875                                                             xcb_root,
876                                                             mask,
877                                                             vals);
878
879     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
880         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
881         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
882         exit(EXIT_FAILURE);
883     }
884
885 }
886
887 /*
888  * Reconfigure all bars and create new bars for recently activated outputs
889  *
890  */
891 void reconfig_windows() {
892     uint32_t mask;
893     uint32_t values[5];
894
895     i3_output *walk;
896     SLIST_FOREACH(walk, outputs, slist) {
897         if (!walk->active) {
898             /* If an output is not active, we destroy its bar */
899             /* FIXME: Maybe we rather want to unmap? */
900             DLOG("Destroying window for output %s\n", walk->name);
901             destroy_window(walk);
902             continue;
903         }
904         if (walk->bar == XCB_NONE) {
905             DLOG("Creating Window for output %s\n", walk->name);
906
907             /* TODO: only call init_tray() if the tray is configured for this output */
908             init_tray();
909
910             walk->bar = xcb_generate_id(xcb_connection);
911             walk->buffer = xcb_generate_id(xcb_connection);
912             mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
913             /* Black background */
914             values[0] = colors.bar_bg;
915             /* If hide_on_modifier is set, i3 is not supposed to manage our bar-windows */
916             values[1] = config.hide_on_modifier;
917             /* The events we want to receive */
918             values[2] = XCB_EVENT_MASK_EXPOSURE;
919             if (!config.disable_ws) {
920                 values[2] |= XCB_EVENT_MASK_BUTTON_PRESS;
921             }
922             xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
923                                                                      xcb_screen->root_depth,
924                                                                      walk->bar,
925                                                                      xcb_root,
926                                                                      walk->rect.x, walk->rect.y + walk->rect.h - font_height - 6,
927                                                                      walk->rect.w, font_height + 6,
928                                                                      1,
929                                                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,
930                                                                      xcb_screen->root_visual,
931                                                                      mask,
932                                                                      values);
933
934             /* The double-buffer we use to render stuff off-screen */
935             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
936                                                                     xcb_screen->root_depth,
937                                                                     walk->buffer,
938                                                                     walk->bar,
939                                                                     walk->rect.w,
940                                                                     walk->rect.h);
941
942             /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
943              * this one */
944             xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
945                                                                 XCB_PROP_MODE_REPLACE,
946                                                                 walk->bar,
947                                                                 atoms[_NET_WM_WINDOW_TYPE],
948                                                                 XCB_ATOM_ATOM,
949                                                                 32,
950                                                                 1,
951                                                                 (unsigned char*) &atoms[_NET_WM_WINDOW_TYPE_DOCK]);
952
953             /* We need to tell i3, where to reserve space for i3bar */
954             /* left, right, top, bottom, left_start_y, left_end_y,
955              * right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x,
956              * bottom_end_x */
957             /* A local struct to save the strut_partial property */
958             struct {
959                 uint32_t left;
960                 uint32_t right;
961                 uint32_t top;
962                 uint32_t bottom;
963                 uint32_t left_start_y;
964                 uint32_t left_end_y;
965                 uint32_t right_start_y;
966                 uint32_t right_end_y;
967                 uint32_t top_start_x;
968                 uint32_t top_end_x;
969                 uint32_t bottom_start_x;
970                 uint32_t bottom_end_x;
971             } __attribute__((__packed__)) strut_partial = {0,};
972             switch (config.dockpos) {
973                 case DOCKPOS_NONE:
974                     break;
975                 case DOCKPOS_TOP:
976                     strut_partial.top = font_height + 6;
977                     strut_partial.top_start_x = walk->rect.x;
978                     strut_partial.top_end_x = walk->rect.x + walk->rect.w;
979                     break;
980                 case DOCKPOS_BOT:
981                     strut_partial.bottom = font_height + 6;
982                     strut_partial.bottom_start_x = walk->rect.x;
983                     strut_partial.bottom_end_x = walk->rect.x + walk->rect.w;
984                     break;
985             }
986             xcb_void_cookie_t strut_cookie = xcb_change_property(xcb_connection,
987                                                                  XCB_PROP_MODE_REPLACE,
988                                                                  walk->bar,
989                                                                  atoms[_NET_WM_STRUT_PARTIAL],
990                                                                  XCB_ATOM_CARDINAL,
991                                                                  32,
992                                                                  12,
993                                                                  &strut_partial);
994
995             /* We also want a graphics-context for the bars (it defines the properties
996              * with which we draw to them) */
997             walk->bargc = xcb_generate_id(xcb_connection);
998             mask = XCB_GC_FONT;
999             values[0] = xcb_font;
1000             xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
1001                                                                 walk->bargc,
1002                                                                 walk->bar,
1003                                                                 mask,
1004                                                                 values);
1005
1006             /* We finally map the bar (display it on screen), unless the modifier-switch is on */
1007             xcb_void_cookie_t map_cookie;
1008             if (!config.hide_on_modifier) {
1009                 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
1010             }
1011
1012             if (xcb_request_failed(win_cookie,   "Could not create window") ||
1013                 xcb_request_failed(pm_cookie,    "Could not create pixmap") ||
1014                 xcb_request_failed(dock_cookie,  "Could not set dock mode") ||
1015                 xcb_request_failed(strut_cookie, "Could not set strut")     ||
1016                 xcb_request_failed(gc_cookie,    "Could not create graphical context") ||
1017                 (!config.hide_on_modifier && xcb_request_failed(map_cookie, "Could not map window"))) {
1018                 exit(EXIT_FAILURE);
1019             }
1020         } else {
1021             /* We already have a bar, so we just reconfigure it */
1022             mask = XCB_CONFIG_WINDOW_X |
1023                    XCB_CONFIG_WINDOW_Y |
1024                    XCB_CONFIG_WINDOW_WIDTH |
1025                    XCB_CONFIG_WINDOW_HEIGHT |
1026                    XCB_CONFIG_WINDOW_STACK_MODE;
1027             values[0] = walk->rect.x;
1028             values[1] = walk->rect.y + walk->rect.h - font_height - 6;
1029             values[2] = walk->rect.w;
1030             values[3] = font_height + 6;
1031             values[4] = XCB_STACK_MODE_ABOVE;
1032
1033             DLOG("Destroying buffer for output %s", walk->name);
1034             xcb_free_pixmap(xcb_connection, walk->buffer);
1035
1036             DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
1037             xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
1038                                                                         walk->bar,
1039                                                                         mask,
1040                                                                         values);
1041
1042             DLOG("Recreating buffer for output %s", walk->name);
1043             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1044                                                                     xcb_screen->root_depth,
1045                                                                     walk->buffer,
1046                                                                     walk->bar,
1047                                                                     walk->rect.w,
1048                                                                     walk->rect.h);
1049
1050             if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
1051                 exit(EXIT_FAILURE);
1052             }
1053             if (xcb_request_failed(pm_cookie,  "Could not create pixmap")) {
1054                 exit(EXIT_FAILURE);
1055             }
1056         }
1057     }
1058 }
1059
1060 /*
1061  * Render the bars, with buttons and statusline
1062  *
1063  */
1064 void draw_bars() {
1065     DLOG("Drawing Bars...\n");
1066     int i = 0;
1067
1068     refresh_statusline();
1069
1070     i3_output *outputs_walk;
1071     SLIST_FOREACH(outputs_walk, outputs, slist) {
1072         if (!outputs_walk->active) {
1073             DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
1074             continue;
1075         }
1076         if (outputs_walk->bar == XCB_NONE) {
1077             /* Oh shit, an active output without an own bar. Create it now! */
1078             reconfig_windows();
1079         }
1080         /* First things first: clear the backbuffer */
1081         uint32_t color = colors.bar_bg;
1082         xcb_change_gc(xcb_connection,
1083                       outputs_walk->bargc,
1084                       XCB_GC_FOREGROUND,
1085                       &color);
1086         xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font_height + 6 };
1087         xcb_poly_fill_rectangle(xcb_connection,
1088                                 outputs_walk->buffer,
1089                                 outputs_walk->bargc,
1090                                 1,
1091                                 &rect);
1092
1093         if (statusline != NULL) {
1094             DLOG("Printing statusline!\n");
1095
1096             /* Luckily we already prepared a seperate pixmap containing the rendered
1097              * statusline, we just have to copy the relevant parts to the relevant
1098              * position */
1099             trayclient *trayclient;
1100             int traypx = 0;
1101             TAILQ_FOREACH(trayclient, outputs_walk->trayclients, tailq) {
1102                 /* We assume the tray icons are quadratic (we use the font
1103                  * *height* as *width* of the icons) because we configured them
1104                  * like this. */
1105                 traypx += font_height;
1106             }
1107             /* Add 2px of padding if there are any tray icons */
1108             if (traypx > 0)
1109                 traypx += 2;
1110             xcb_copy_area(xcb_connection,
1111                           statusline_pm,
1112                           outputs_walk->buffer,
1113                           outputs_walk->bargc,
1114                           MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
1115                           MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - traypx - 4)), 3,
1116                           MIN(outputs_walk->rect.w - traypx - 4, statusline_width), font_height);
1117         }
1118
1119         if (config.disable_ws) {
1120             continue;
1121         }
1122
1123         i3_ws *ws_walk;
1124         TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
1125             DLOG("Drawing Button for WS %s at x = %d\n", ws_walk->name, i);
1126             uint32_t fg_color = colors.inactive_ws_fg;
1127             uint32_t bg_color = colors.inactive_ws_bg;
1128             if (ws_walk->visible) {
1129                 if (!ws_walk->focused) {
1130                     fg_color = colors.active_ws_fg;
1131                     bg_color = colors.active_ws_bg;
1132                 } else {
1133                     fg_color = colors.focus_ws_fg;
1134                     bg_color = colors.focus_ws_bg;
1135                 }
1136             }
1137             if (ws_walk->urgent) {
1138                 DLOG("WS %s is urgent!\n", ws_walk->name);
1139                 fg_color = colors.urgent_ws_fg;
1140                 bg_color = colors.urgent_ws_bg;
1141                 /* The urgent-hint should get noticed, so we unhide the bars shortly */
1142                 unhide_bars();
1143             }
1144             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
1145             uint32_t vals[] = { bg_color, bg_color };
1146             xcb_change_gc(xcb_connection,
1147                           outputs_walk->bargc,
1148                           mask,
1149                           vals);
1150             xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font_height + 4 };
1151             xcb_poly_fill_rectangle(xcb_connection,
1152                                     outputs_walk->buffer,
1153                                     outputs_walk->bargc,
1154                                     1,
1155                                     &rect);
1156             xcb_change_gc(xcb_connection,
1157                           outputs_walk->bargc,
1158                           XCB_GC_FOREGROUND,
1159                           &fg_color);
1160             xcb_image_text_16(xcb_connection,
1161                               ws_walk->name_glyphs,
1162                               outputs_walk->buffer,
1163                               outputs_walk->bargc,
1164                               i + 5, font_info->font_ascent + 2,
1165                               ws_walk->ucs2_name);
1166             i += 10 + ws_walk->name_width;
1167         }
1168
1169         i = 0;
1170     }
1171
1172     redraw_bars();
1173 }
1174
1175 /*
1176  * Redraw the bars, i.e. simply copy the buffer to the barwindow
1177  *
1178  */
1179 void redraw_bars() {
1180     i3_output *outputs_walk;
1181     SLIST_FOREACH(outputs_walk, outputs, slist) {
1182         if (!outputs_walk->active) {
1183             continue;
1184         }
1185         xcb_copy_area(xcb_connection,
1186                       outputs_walk->buffer,
1187                       outputs_walk->bar,
1188                       outputs_walk->bargc,
1189                       0, 0,
1190                       0, 0,
1191                       outputs_walk->rect.w,
1192                       outputs_walk->rect.h);
1193         xcb_flush(xcb_connection);
1194     }
1195 }