]> git.sur5r.net Git - i3/i3/blob - i3bar/src/xcb.c
Merge branch 'userguide-mark'
[i3/i3] / i3bar / src / xcb.c
1 /*
2  * i3bar - an xcb-based status- and ws-bar for i3
3  *
4  * © 2010-2011 Axel Wagner and contributors
5  *
6  * See file LICNSE for license information
7  *
8  * src/xcb.c: Communicating with X
9  *
10  */
11 #include <xcb/xcb.h>
12 #include <xcb/xproto.h>
13 #include <xcb/xcb_atom.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <fcntl.h>
18 #include <string.h>
19 #include <i3/ipc.h>
20 #include <ev.h>
21 #include <errno.h>
22 #include <limits.h>
23
24 #include <X11/Xlib.h>
25 #include <X11/XKBlib.h>
26 #include <X11/extensions/XKB.h>
27
28 #include "common.h"
29
30 #if defined(__APPLE__)
31
32 /*
33  * Taken from FreeBSD
34  * Returns a pointer to a new string which is a duplicate of the
35  * string, but only copies at most n characters.
36  *
37  */
38 char *strndup(const char *str, size_t n) {
39     size_t len;
40     char *copy;
41
42     for (len = 0; len < n && str[len]; len++)
43         continue;
44
45     if ((copy = malloc(len + 1)) == NULL)
46         return (NULL);
47     memcpy(copy, str, len);
48     copy[len] = '\0';
49     return (copy);
50 }
51
52 #endif
53
54 /* We save the Atoms in an easy to access array, indexed by an enum */
55 enum {
56     #define ATOM_DO(name) name,
57     #include "xcb_atoms.def"
58     NUM_ATOMS
59 };
60
61 xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
62 xcb_atom_t               atoms[NUM_ATOMS];
63
64 /* Variables, that are the same for all functions at all times */
65 xcb_connection_t *xcb_connection;
66 xcb_screen_t     *xcb_screen;
67 xcb_window_t     xcb_root;
68 xcb_font_t       xcb_font;
69
70 /* We need to cache some data to speed up text-width-prediction */
71 xcb_query_font_reply_t *font_info;
72 int                    font_height;
73 xcb_charinfo_t         *font_table;
74
75 /* These are only relevant for XKB, which we only need for grabbing modifiers */
76 Display          *xkb_dpy;
77 int              xkb_event_base;
78 int              mod_pressed = 0;
79
80 /* Because the statusline is the same on all outputs, we have
81  * global buffer to render it on */
82 xcb_gcontext_t   statusline_ctx;
83 xcb_gcontext_t   statusline_clear;
84 xcb_pixmap_t     statusline_pm;
85 uint32_t         statusline_width;
86
87 /* Event-Watchers, to interact with the user */
88 ev_prepare *xcb_prep;
89 ev_check   *xcb_chk;
90 ev_io      *xcb_io;
91 ev_io      *xkb_io;
92
93 /* The parsed colors */
94 struct xcb_colors_t {
95     uint32_t bar_fg;
96     uint32_t bar_bg;
97     uint32_t active_ws_fg;
98     uint32_t active_ws_bg;
99     uint32_t inactive_ws_fg;
100     uint32_t inactive_ws_bg;
101     uint32_t urgent_ws_bg;
102     uint32_t urgent_ws_fg;
103     uint32_t focus_ws_bg;
104     uint32_t focus_ws_fg;
105 };
106 struct xcb_colors_t colors;
107
108 /* We define xcb_request_failed as a macro to include the relevant line-number */
109 #define xcb_request_failed(cookie, err_msg) _xcb_request_failed(cookie, err_msg, __LINE__)
110 int _xcb_request_failed(xcb_void_cookie_t cookie, char *err_msg, int line) {
111     xcb_generic_error_t *err;
112     if ((err = xcb_request_check(xcb_connection, cookie)) != NULL) {
113         fprintf(stderr, "[%s:%d] ERROR: %s. X Error Code: %d\n", __FILE__, line, err_msg, err->error_code);
114         return err->error_code;
115     }
116     return 0;
117 }
118
119 /*
120  * Predicts the length of text based on cached data.
121  * The string has to be encoded in ucs2 and glyph_len has to be the length
122  * of the string (in glyphs).
123  *
124  */
125 uint32_t predict_text_extents(xcb_char2b_t *text, uint32_t length) {
126     /* If we don't have per-character data, return the maximum width */
127     if (font_table == NULL) {
128         return (font_info->max_bounds.character_width * length);
129     }
130
131     uint32_t width = 0;
132     uint32_t i;
133
134     for (i = 0; i < length; i++) {
135         xcb_charinfo_t *info;
136         int row = text[i].byte1;
137         int col = text[i].byte2;
138
139         if (row < font_info->min_byte1 || row > font_info->max_byte1 ||
140             col < font_info->min_char_or_byte2 || col > font_info->max_char_or_byte2) {
141             continue;
142         }
143
144         /* Don't you ask me, how this one works… */
145         info = &font_table[((row - font_info->min_byte1) *
146                             (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
147                            (col - font_info->min_char_or_byte2)];
148
149         if (info->character_width != 0 ||
150             (info->right_side_bearing |
151              info->left_side_bearing |
152              info->ascent |
153              info->descent) != 0) {
154             width += info->character_width;
155         }
156     }
157
158     return width;
159 }
160
161 /*
162  * Draws text given in UCS-2-encoding to a given drawable and position
163  *
164  */
165 void draw_text(xcb_drawable_t drawable, xcb_gcontext_t ctx, int16_t x, int16_t y,
166                xcb_char2b_t *text, uint32_t glyph_count) {
167     int offset = 0;
168     int16_t pos_x = x;
169     int16_t font_ascent = font_info->font_ascent;
170
171     while (glyph_count > 0) {
172         uint8_t chunk_size = MIN(255, glyph_count);
173         uint32_t chunk_width = predict_text_extents(text + offset, chunk_size);
174
175         xcb_image_text_16(xcb_connection,
176                           chunk_size,
177                           drawable,
178                           ctx,
179                           pos_x, y + font_ascent,
180                           text + offset);
181
182         offset += chunk_size;
183         pos_x += chunk_width;
184         glyph_count -= chunk_size;
185     }
186 }
187
188 /*
189  * Converts a colorstring to a colorpixel as expected from xcb_change_gc.
190  * s is assumed to be in the format "rrggbb"
191  *
192  */
193 uint32_t get_colorpixel(const char *s) {
194     char strings[3][3] = { { s[0], s[1], '\0'} ,
195                            { s[2], s[3], '\0'} ,
196                            { s[4], s[5], '\0'} };
197     uint8_t r = strtol(strings[0], NULL, 16);
198     uint8_t g = strtol(strings[1], NULL, 16);
199     uint8_t b = strtol(strings[2], NULL, 16);
200     return (r << 16 | g << 8 | b);
201 }
202
203 /*
204  * Redraws the statusline to the buffer
205  *
206  */
207 void refresh_statusline() {
208     int glyph_count;
209
210     if (statusline == NULL) {
211         return;
212     }
213
214     xcb_char2b_t *text = (xcb_char2b_t*) convert_utf8_to_ucs2(statusline, &glyph_count);
215     uint32_t old_statusline_width = statusline_width;
216     statusline_width = predict_text_extents(text, glyph_count);
217     /* If the statusline is bigger than our screen we need to make sure that
218      * the pixmap provides enough space, so re-allocate if the width grew */
219     if (statusline_width > xcb_screen->width_in_pixels &&
220         statusline_width > old_statusline_width)
221         realloc_sl_buffer();
222
223     xcb_rectangle_t rect = { 0, 0, xcb_screen->width_in_pixels, font_height };
224     xcb_poly_fill_rectangle(xcb_connection, statusline_pm, statusline_clear, 1, &rect);
225     draw_text(statusline_pm, statusline_ctx, 0, 0, text, glyph_count);
226
227     FREE(text);
228 }
229
230 /*
231  * Hides all bars (unmaps them)
232  *
233  */
234 void hide_bars() {
235     if (!config.hide_on_modifier) {
236         return;
237     }
238
239     i3_output *walk;
240     SLIST_FOREACH(walk, outputs, slist) {
241         if (!walk->active) {
242             continue;
243         }
244         xcb_unmap_window(xcb_connection, walk->bar);
245     }
246     stop_child();
247 }
248
249 /*
250  * Unhides all bars (maps them)
251  *
252  */
253 void unhide_bars() {
254     if (!config.hide_on_modifier) {
255         return;
256     }
257
258     i3_output           *walk;
259     xcb_void_cookie_t   cookie;
260     uint32_t            mask;
261     uint32_t            values[5];
262
263     cont_child();
264
265     SLIST_FOREACH(walk, outputs, slist) {
266         if (walk->bar == XCB_NONE) {
267             continue;
268         }
269         mask = XCB_CONFIG_WINDOW_X |
270                XCB_CONFIG_WINDOW_Y |
271                XCB_CONFIG_WINDOW_WIDTH |
272                XCB_CONFIG_WINDOW_HEIGHT |
273                XCB_CONFIG_WINDOW_STACK_MODE;
274         values[0] = walk->rect.x;
275         values[1] = walk->rect.y + walk->rect.h - font_height - 6;
276         values[2] = walk->rect.w;
277         values[3] = font_height + 6;
278         values[4] = XCB_STACK_MODE_ABOVE;
279         DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
280         cookie = xcb_configure_window_checked(xcb_connection,
281                                               walk->bar,
282                                               mask,
283                                               values);
284
285         if (xcb_request_failed(cookie, "Could not reconfigure window")) {
286             exit(EXIT_FAILURE);
287         }
288         xcb_map_window(xcb_connection, walk->bar);
289     }
290 }
291
292 /*
293  * Parse the colors into a format that we can use
294  *
295  */
296 void init_colors(const struct xcb_color_strings_t *new_colors) {
297 #define PARSE_COLOR(name, def) \
298     do { \
299         colors.name = get_colorpixel(new_colors->name ? new_colors->name : def); \
300     } while  (0)
301     PARSE_COLOR(bar_fg, "FFFFFF");
302     PARSE_COLOR(bar_bg, "000000");
303     PARSE_COLOR(active_ws_fg, "FFFFFF");
304     PARSE_COLOR(active_ws_bg, "480000");
305     PARSE_COLOR(inactive_ws_fg, "FFFFFF");
306     PARSE_COLOR(inactive_ws_bg, "240000");
307     PARSE_COLOR(urgent_ws_fg, "FFFFFF");
308     PARSE_COLOR(urgent_ws_bg, "002400");
309     PARSE_COLOR(focus_ws_fg, "FFFFFF");
310     PARSE_COLOR(focus_ws_bg, "480000");
311 #undef PARSE_COLOR
312 }
313
314 /*
315  * Handle a button-press-event (i.e. a mouse click on one of our bars).
316  * We determine, whether the click occured on a ws-button or if the scroll-
317  * wheel was used and change the workspace appropriately
318  *
319  */
320 void handle_button(xcb_button_press_event_t *event) {
321     i3_ws *cur_ws;
322
323     /* Determine, which bar was clicked */
324     i3_output *walk;
325     xcb_window_t bar = event->event;
326     SLIST_FOREACH(walk, outputs, slist) {
327         if (walk->bar == bar) {
328             break;
329         }
330     }
331
332     if (walk == NULL) {
333         DLOG("Unknown Bar klicked!\n");
334         return;
335     }
336
337     /* TODO: Move this to extern get_ws_for_output() */
338     TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
339         if (cur_ws->visible) {
340             break;
341         }
342     }
343
344     if (cur_ws == NULL) {
345         DLOG("No Workspace active?\n");
346         return;
347     }
348
349     int32_t x = event->event_x;
350
351     DLOG("Got Button %d\n", event->detail);
352
353     switch (event->detail) {
354         case 1:
355             /* Left Mousbutton. We determine, which button was clicked
356              * and set cur_ws accordingly */
357             TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
358                 DLOG("x = %d\n", x);
359                 if (x < cur_ws->name_width + 10) {
360                     break;
361                 }
362                 x -= cur_ws->name_width + 10;
363             }
364             if (cur_ws == NULL) {
365                 return;
366             }
367             break;
368         case 4:
369             /* Mouse wheel down. We select the next ws */
370             if (cur_ws == TAILQ_FIRST(walk->workspaces)) {
371                 cur_ws = TAILQ_LAST(walk->workspaces, ws_head);
372             } else {
373                 cur_ws = TAILQ_PREV(cur_ws, ws_head, tailq);
374             }
375             break;
376         case 5:
377             /* Mouse wheel up. We select the previos ws */
378             if (cur_ws == TAILQ_LAST(walk->workspaces, ws_head)) {
379                 cur_ws = TAILQ_FIRST(walk->workspaces);
380             } else {
381                 cur_ws = TAILQ_NEXT(cur_ws, tailq);
382             }
383             break;
384     }
385
386     const size_t len = strlen(cur_ws->name) + strlen("workspace \"\"") + 1;
387     char buffer[len];
388     snprintf(buffer, len, "workspace \"%s\"", cur_ws->name);
389     i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
390 }
391
392 /*
393  * This function is called immediately before the main loop locks. We flush xcb
394  * then (and only then)
395  *
396  */
397 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revents) {
398     xcb_flush(xcb_connection);
399 }
400
401 /*
402  * This function is called immediately after the main loop locks, so when one
403  * of the watchers registered an event.
404  * We check whether an X-Event arrived and handle it.
405  *
406  */
407 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
408     xcb_generic_event_t *event;
409
410     if (xcb_connection_has_error(xcb_connection)) {
411         ELOG("X11 connection was closed unexpectedly - maybe your X server terminated / crashed?\n");
412         exit(1);
413     }
414
415     while ((event = xcb_poll_for_event(xcb_connection)) == NULL) {
416         return;
417     }
418
419     switch (event->response_type & ~0x80) {
420         case XCB_EXPOSE:
421             /* Expose-events happen, when the window needs to be redrawn */
422             redraw_bars();
423             break;
424         case XCB_BUTTON_PRESS:
425             /* Button-press-events are mouse-buttons clicked on one of our bars */
426             handle_button((xcb_button_press_event_t*) event);
427             break;
428     }
429     FREE(event);
430 }
431
432 /*
433  * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
434  * are triggered
435  *
436  */
437 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
438 }
439
440 /*
441  * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
442  *
443  */
444 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
445     XkbEvent ev;
446     int modstate = 0;
447
448     DLOG("Got XKB-Event!\n");
449
450     while (XPending(xkb_dpy)) {
451         XNextEvent(xkb_dpy, (XEvent*)&ev);
452
453         if (ev.type != xkb_event_base) {
454             ELOG("No Xkb-Event!\n");
455             continue;
456         }
457
458         if (ev.any.xkb_type != XkbStateNotify) {
459             ELOG("No State Notify!\n");
460             continue;
461         }
462
463         unsigned int mods = ev.state.mods;
464         modstate = mods & Mod4Mask;
465     }
466
467     if (modstate != mod_pressed) {
468         if (modstate == 0) {
469             DLOG("Mod4 got released!\n");
470             hide_bars();
471         } else {
472             DLOG("Mod4 got pressed!\n");
473             unhide_bars();
474         }
475         mod_pressed = modstate;
476     }
477 }
478
479 /*
480  * Initialize xcb and use the specified fontname for text-rendering
481  *
482  */
483 char *init_xcb(char *fontname) {
484     /* FIXME: xcb_connect leaks Memory */
485     xcb_connection = xcb_connect(NULL, NULL);
486     if (xcb_connection_has_error(xcb_connection)) {
487         ELOG("Cannot open display\n");
488         exit(EXIT_FAILURE);
489     }
490     DLOG("Connected to xcb\n");
491
492     /* We have to request the atoms we need */
493     #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
494     #include "xcb_atoms.def"
495
496     xcb_screen = xcb_setup_roots_iterator(xcb_get_setup(xcb_connection)).data;
497     xcb_root = xcb_screen->root;
498
499     /* We load and allocate the font */
500     xcb_font = xcb_generate_id(xcb_connection);
501     xcb_void_cookie_t open_font_cookie;
502     open_font_cookie = xcb_open_font_checked(xcb_connection,
503                                              xcb_font,
504                                              strlen(fontname),
505                                              fontname);
506
507     /* We need to save info about the font, because we need the font's height and
508      * information about the width of characters */
509     xcb_query_font_cookie_t query_font_cookie;
510     query_font_cookie = xcb_query_font(xcb_connection,
511                                        xcb_font);
512
513     /* To grab modifiers without blocking other applications from receiving key-events
514      * involving that modifier, we sadly have to use xkb which is not yet fully supported
515      * in xcb */
516     if (config.hide_on_modifier) {
517         int xkb_major, xkb_minor, xkb_errbase, xkb_err;
518         xkb_major = XkbMajorVersion;
519         xkb_minor = XkbMinorVersion;
520
521         xkb_dpy = XkbOpenDisplay(NULL,
522                                  &xkb_event_base,
523                                  &xkb_errbase,
524                                  &xkb_major,
525                                  &xkb_minor,
526                                  &xkb_err);
527
528         if (xkb_dpy == NULL) {
529             ELOG("No XKB!\n");
530             exit(EXIT_FAILURE);
531         }
532
533         if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
534             ELOG("Could not set FD_CLOEXEC on xkbdpy: %s\n", strerror(errno));
535             exit(EXIT_FAILURE);
536         }
537
538         int i1;
539         if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
540             ELOG("XKB not supported by X-server!\n");
541             exit(EXIT_FAILURE);
542         }
543
544         if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
545             ELOG("Could not grab Key!\n");
546             exit(EXIT_FAILURE);
547         }
548
549         xkb_io = malloc(sizeof(ev_io));
550         ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
551         ev_io_start(main_loop, xkb_io);
552         XFlush(xkb_dpy);
553     }
554
555     /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
556      * this way, we can choose to crop it */
557     uint32_t mask = XCB_GC_FOREGROUND;
558     uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
559
560     statusline_clear = xcb_generate_id(xcb_connection);
561     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
562                                                                statusline_clear,
563                                                                xcb_root,
564                                                                mask,
565                                                                vals);
566
567     mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
568     vals[0] = colors.bar_fg;
569     statusline_ctx = xcb_generate_id(xcb_connection);
570     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
571                                                             statusline_ctx,
572                                                             xcb_root,
573                                                             mask,
574                                                             vals);
575
576     statusline_pm = xcb_generate_id(xcb_connection);
577     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
578                                                                xcb_screen->root_depth,
579                                                                statusline_pm,
580                                                                xcb_root,
581                                                                xcb_screen->width_in_pixels,
582                                                                xcb_screen->height_in_pixels);
583
584
585     /* The various Watchers to communicate with xcb */
586     xcb_io = malloc(sizeof(ev_io));
587     xcb_prep = malloc(sizeof(ev_prepare));
588     xcb_chk = malloc(sizeof(ev_check));
589
590     ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
591     ev_prepare_init(xcb_prep, &xcb_prep_cb);
592     ev_check_init(xcb_chk, &xcb_chk_cb);
593
594     ev_io_start(main_loop, xcb_io);
595     ev_prepare_start(main_loop, xcb_prep);
596     ev_check_start(main_loop, xcb_chk);
597
598     /* Now we get the atoms and save them in a nice data structure */
599     get_atoms();
600
601     xcb_get_property_cookie_t path_cookie;
602     path_cookie = xcb_get_property_unchecked(xcb_connection,
603                                    0,
604                                    xcb_root,
605                                    atoms[I3_SOCKET_PATH],
606                                    XCB_GET_PROPERTY_TYPE_ANY,
607                                    0, PATH_MAX);
608
609     /* We check, if i3 set its socket-path */
610     xcb_get_property_reply_t *path_reply = xcb_get_property_reply(xcb_connection,
611                                                                   path_cookie,
612                                                                   NULL);
613     char *path = NULL;
614     if (path_reply) {
615         int len = xcb_get_property_value_length(path_reply);
616         if (len != 0) {
617             path = strndup(xcb_get_property_value(path_reply), len);
618         }
619     }
620
621     /* Now we save the font-infos */
622     font_info = xcb_query_font_reply(xcb_connection,
623                                      query_font_cookie,
624                                      NULL);
625
626     if (xcb_request_failed(open_font_cookie, "Could not open font")) {
627         exit(EXIT_FAILURE);
628     }
629
630     font_height = font_info->font_ascent + font_info->font_descent;
631
632     if (xcb_query_font_char_infos_length(font_info) == 0) {
633         font_table = NULL;
634     } else {
635         font_table = xcb_query_font_char_infos(font_info);
636     }
637
638     DLOG("Calculated Font-height: %d\n", font_height);
639
640     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
641         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
642         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
643         exit(EXIT_FAILURE);
644     }
645
646     return path;
647 }
648
649 /*
650  * Cleanup the xcb-stuff.
651  * Called once, before the program terminates.
652  *
653  */
654 void clean_xcb() {
655     i3_output *o_walk;
656     free_workspaces();
657     SLIST_FOREACH(o_walk, outputs, slist) {
658         destroy_window(o_walk);
659         FREE(o_walk->workspaces);
660         FREE(o_walk->name);
661     }
662     FREE_SLIST(outputs, i3_output);
663     FREE(outputs);
664
665     xcb_disconnect(xcb_connection);
666
667     ev_check_stop(main_loop, xcb_chk);
668     ev_prepare_stop(main_loop, xcb_prep);
669     ev_io_stop(main_loop, xcb_io);
670
671     FREE(xcb_chk);
672     FREE(xcb_prep);
673     FREE(xcb_io);
674     FREE(font_info);
675 }
676
677 /*
678  * Get the earlier requested atoms and save them in the prepared data structure
679  *
680  */
681 void get_atoms() {
682     xcb_intern_atom_reply_t *reply;
683     #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
684         if (reply == NULL) { \
685             ELOG("Could not get atom %s\n", #name); \
686             exit(EXIT_FAILURE); \
687         } \
688         atoms[name] = reply->atom; \
689         free(reply);
690
691     #include "xcb_atoms.def"
692     DLOG("Got Atoms\n");
693 }
694
695 /*
696  * Destroy the bar of the specified output
697  *
698  */
699 void destroy_window(i3_output *output) {
700     if (output == NULL) {
701         return;
702     }
703     if (output->bar == XCB_NONE) {
704         return;
705     }
706     xcb_destroy_window(xcb_connection, output->bar);
707     output->bar = XCB_NONE;
708 }
709
710 /*
711  * Reallocate the statusline-buffer
712  *
713  */
714 void realloc_sl_buffer() {
715     DLOG("Re-allocating statusline-buffer, statusline_width = %d, xcb_screen->width_in_pixels = %d\n",
716          statusline_width, xcb_screen->width_in_pixels);
717     xcb_free_pixmap(xcb_connection, statusline_pm);
718     statusline_pm = xcb_generate_id(xcb_connection);
719     xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
720                                                                xcb_screen->root_depth,
721                                                                statusline_pm,
722                                                                xcb_root,
723                                                                MAX(xcb_screen->width_in_pixels, statusline_width),
724                                                                xcb_screen->height_in_pixels);
725
726     uint32_t mask = XCB_GC_FOREGROUND;
727     uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
728     xcb_free_gc(xcb_connection, statusline_clear);
729     statusline_clear = xcb_generate_id(xcb_connection);
730     xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
731                                                                statusline_clear,
732                                                                xcb_root,
733                                                                mask,
734                                                                vals);
735
736     mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
737     vals[0] = colors.bar_fg;
738     statusline_ctx = xcb_generate_id(xcb_connection);
739     xcb_free_gc(xcb_connection, statusline_ctx);
740     xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
741                                                             statusline_ctx,
742                                                             xcb_root,
743                                                             mask,
744                                                             vals);
745
746     if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
747         xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
748         xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
749         exit(EXIT_FAILURE);
750     }
751
752 }
753
754 /*
755  * Reconfigure all bars and create new bars for recently activated outputs
756  *
757  */
758 void reconfig_windows() {
759     uint32_t mask;
760     uint32_t values[5];
761
762     i3_output *walk;
763     SLIST_FOREACH(walk, outputs, slist) {
764         if (!walk->active) {
765             /* If an output is not active, we destroy its bar */
766             /* FIXME: Maybe we rather want to unmap? */
767             DLOG("Destroying window for output %s\n", walk->name);
768             destroy_window(walk);
769             continue;
770         }
771         if (walk->bar == XCB_NONE) {
772             DLOG("Creating Window for output %s\n", walk->name);
773
774             walk->bar = xcb_generate_id(xcb_connection);
775             walk->buffer = xcb_generate_id(xcb_connection);
776             mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
777             /* Black background */
778             values[0] = colors.bar_bg;
779             /* If hide_on_modifier is set, i3 is not supposed to manage our bar-windows */
780             values[1] = config.hide_on_modifier;
781             /* The events we want to receive */
782             values[2] = XCB_EVENT_MASK_EXPOSURE;
783             if (!config.disable_ws) {
784                 values[2] |= XCB_EVENT_MASK_BUTTON_PRESS;
785             }
786             xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
787                                                                      xcb_screen->root_depth,
788                                                                      walk->bar,
789                                                                      xcb_root,
790                                                                      walk->rect.x, walk->rect.y + walk->rect.h - font_height - 6,
791                                                                      walk->rect.w, font_height + 6,
792                                                                      1,
793                                                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,
794                                                                      xcb_screen->root_visual,
795                                                                      mask,
796                                                                      values);
797
798             /* The double-buffer we use to render stuff off-screen */
799             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
800                                                                     xcb_screen->root_depth,
801                                                                     walk->buffer,
802                                                                     walk->bar,
803                                                                     walk->rect.w,
804                                                                     walk->rect.h);
805
806             /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
807              * this one */
808             xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
809                                                                 XCB_PROP_MODE_REPLACE,
810                                                                 walk->bar,
811                                                                 atoms[_NET_WM_WINDOW_TYPE],
812                                                                 XCB_ATOM_ATOM,
813                                                                 32,
814                                                                 1,
815                                                                 (unsigned char*) &atoms[_NET_WM_WINDOW_TYPE_DOCK]);
816
817             /* We need to tell i3, where to reserve space for i3bar */
818             /* left, right, top, bottom, left_start_y, left_end_y,
819              * right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x,
820              * bottom_end_x */
821             /* A local struct to save the strut_partial property */
822             struct {
823                 uint32_t left;
824                 uint32_t right;
825                 uint32_t top;
826                 uint32_t bottom;
827                 uint32_t left_start_y;
828                 uint32_t left_end_y;
829                 uint32_t right_start_y;
830                 uint32_t right_end_y;
831                 uint32_t top_start_x;
832                 uint32_t top_end_x;
833                 uint32_t bottom_start_x;
834                 uint32_t bottom_end_x;
835             } __attribute__((__packed__)) strut_partial = {0,};
836             switch (config.dockpos) {
837                 case DOCKPOS_NONE:
838                     break;
839                 case DOCKPOS_TOP:
840                     strut_partial.top = font_height + 6;
841                     strut_partial.top_start_x = walk->rect.x;
842                     strut_partial.top_end_x = walk->rect.x + walk->rect.w;
843                     break;
844                 case DOCKPOS_BOT:
845                     strut_partial.bottom = font_height + 6;
846                     strut_partial.bottom_start_x = walk->rect.x;
847                     strut_partial.bottom_end_x = walk->rect.x + walk->rect.w;
848                     break;
849             }
850             xcb_void_cookie_t strut_cookie = xcb_change_property(xcb_connection,
851                                                                  XCB_PROP_MODE_REPLACE,
852                                                                  walk->bar,
853                                                                  atoms[_NET_WM_STRUT_PARTIAL],
854                                                                  XCB_ATOM_CARDINAL,
855                                                                  32,
856                                                                  12,
857                                                                  &strut_partial);
858
859             /* We also want a graphics-context for the bars (it defines the properties
860              * with which we draw to them) */
861             walk->bargc = xcb_generate_id(xcb_connection);
862             mask = XCB_GC_FONT;
863             values[0] = xcb_font;
864             xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
865                                                                 walk->bargc,
866                                                                 walk->bar,
867                                                                 mask,
868                                                                 values);
869
870             /* We finally map the bar (display it on screen), unless the modifier-switch is on */
871             xcb_void_cookie_t map_cookie;
872             if (!config.hide_on_modifier) {
873                 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
874             }
875
876             if (xcb_request_failed(win_cookie,   "Could not create window") ||
877                 xcb_request_failed(pm_cookie,    "Could not create pixmap") ||
878                 xcb_request_failed(dock_cookie,  "Could not set dock mode") ||
879                 xcb_request_failed(strut_cookie, "Could not set strut")     ||
880                 xcb_request_failed(gc_cookie,    "Could not create graphical context") ||
881                 (!config.hide_on_modifier && xcb_request_failed(map_cookie, "Could not map window"))) {
882                 exit(EXIT_FAILURE);
883             }
884         } else {
885             /* We already have a bar, so we just reconfigure it */
886             mask = XCB_CONFIG_WINDOW_X |
887                    XCB_CONFIG_WINDOW_Y |
888                    XCB_CONFIG_WINDOW_WIDTH |
889                    XCB_CONFIG_WINDOW_HEIGHT |
890                    XCB_CONFIG_WINDOW_STACK_MODE;
891             values[0] = walk->rect.x;
892             values[1] = walk->rect.y + walk->rect.h - font_height - 6;
893             values[2] = walk->rect.w;
894             values[3] = font_height + 6;
895             values[4] = XCB_STACK_MODE_ABOVE;
896
897             DLOG("Destroying buffer for output %s", walk->name);
898             xcb_free_pixmap(xcb_connection, walk->buffer);
899
900             DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
901             xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
902                                                                         walk->bar,
903                                                                         mask,
904                                                                         values);
905
906             DLOG("Recreating buffer for output %s", walk->name);
907             xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
908                                                                     xcb_screen->root_depth,
909                                                                     walk->buffer,
910                                                                     walk->bar,
911                                                                     walk->rect.w,
912                                                                     walk->rect.h);
913
914             if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
915                 exit(EXIT_FAILURE);
916             }
917             if (xcb_request_failed(pm_cookie,  "Could not create pixmap")) {
918                 exit(EXIT_FAILURE);
919             }
920         }
921     }
922 }
923
924 /*
925  * Render the bars, with buttons and statusline
926  *
927  */
928 void draw_bars() {
929     DLOG("Drawing Bars...\n");
930     int i = 0;
931
932     refresh_statusline();
933
934     i3_output *outputs_walk;
935     SLIST_FOREACH(outputs_walk, outputs, slist) {
936         if (!outputs_walk->active) {
937             DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
938             continue;
939         }
940         if (outputs_walk->bar == XCB_NONE) {
941             /* Oh shit, an active output without an own bar. Create it now! */
942             reconfig_windows();
943         }
944         /* First things first: clear the backbuffer */
945         uint32_t color = colors.bar_bg;
946         xcb_change_gc(xcb_connection,
947                       outputs_walk->bargc,
948                       XCB_GC_FOREGROUND,
949                       &color);
950         xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font_height + 6 };
951         xcb_poly_fill_rectangle(xcb_connection,
952                                 outputs_walk->buffer,
953                                 outputs_walk->bargc,
954                                 1,
955                                 &rect);
956
957         if (statusline != NULL) {
958             DLOG("Printing statusline!\n");
959
960             /* Luckily we already prepared a seperate pixmap containing the rendered
961              * statusline, we just have to copy the relevant parts to the relevant
962              * position */
963             xcb_copy_area(xcb_connection,
964                           statusline_pm,
965                           outputs_walk->buffer,
966                           outputs_walk->bargc,
967                           MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
968                           MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - 4)), 3,
969                           MIN(outputs_walk->rect.w - 4, statusline_width), font_height);
970         }
971
972         if (config.disable_ws) {
973             continue;
974         }
975
976         i3_ws *ws_walk;
977         TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
978             DLOG("Drawing Button for WS %s at x = %d\n", ws_walk->name, i);
979             uint32_t fg_color = colors.inactive_ws_fg;
980             uint32_t bg_color = colors.inactive_ws_bg;
981             if (ws_walk->visible) {
982                 if (!ws_walk->focused) {
983                     fg_color = colors.active_ws_fg;
984                     bg_color = colors.active_ws_bg;
985                 } else {
986                     fg_color = colors.focus_ws_fg;
987                     bg_color = colors.focus_ws_bg;
988                 }
989             }
990             if (ws_walk->urgent) {
991                 DLOG("WS %s is urgent!\n", ws_walk->name);
992                 fg_color = colors.urgent_ws_fg;
993                 bg_color = colors.urgent_ws_bg;
994                 /* The urgent-hint should get noticed, so we unhide the bars shortly */
995                 unhide_bars();
996             }
997             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
998             uint32_t vals[] = { bg_color, bg_color };
999             xcb_change_gc(xcb_connection,
1000                           outputs_walk->bargc,
1001                           mask,
1002                           vals);
1003             xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font_height + 4 };
1004             xcb_poly_fill_rectangle(xcb_connection,
1005                                     outputs_walk->buffer,
1006                                     outputs_walk->bargc,
1007                                     1,
1008                                     &rect);
1009             xcb_change_gc(xcb_connection,
1010                           outputs_walk->bargc,
1011                           XCB_GC_FOREGROUND,
1012                           &fg_color);
1013             xcb_image_text_16(xcb_connection,
1014                               ws_walk->name_glyphs,
1015                               outputs_walk->buffer,
1016                               outputs_walk->bargc,
1017                               i + 5, font_info->font_ascent + 2,
1018                               ws_walk->ucs2_name);
1019             i += 10 + ws_walk->name_width;
1020         }
1021
1022         i = 0;
1023     }
1024
1025     redraw_bars();
1026 }
1027
1028 /*
1029  * Redraw the bars, i.e. simply copy the buffer to the barwindow
1030  *
1031  */
1032 void redraw_bars() {
1033     i3_output *outputs_walk;
1034     SLIST_FOREACH(outputs_walk, outputs, slist) {
1035         if (!outputs_walk->active) {
1036             continue;
1037         }
1038         xcb_copy_area(xcb_connection,
1039                       outputs_walk->buffer,
1040                       outputs_walk->bar,
1041                       outputs_walk->bargc,
1042                       0, 0,
1043                       0, 0,
1044                       outputs_walk->rect.w,
1045                       outputs_walk->rect.h);
1046         xcb_flush(xcb_connection);
1047     }
1048 }