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