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