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