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