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