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