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