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