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