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