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