2 * i3bar - an xcb-based status- and ws-bar for i3
4 * © 2010 Axel Wagner and contributors
6 * See file LICNSE for license information
8 * src/xcb.c: Communicating with X
12 #include <xcb/xproto.h>
23 #include <X11/XKBlib.h>
24 #include <X11/extensions/XKB.h>
28 /* We save the Atoms in an easy to access array, indexed by an enum */
32 #define ATOM_DO(name) name,
33 #include "xcb_atoms.def"
36 xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
37 xcb_atom_t atoms[NUM_ATOMS];
39 /* Variables, that are the same for all functions at all times */
40 xcb_connection_t *xcb_connection;
41 xcb_screen_t *xcb_screen;
42 xcb_window_t xcb_root;
45 /* We need to cache some data to speed up text-width-prediction */
46 xcb_query_font_reply_t *font_info;
48 xcb_charinfo_t *font_table;
50 /* These are only relevant for XKB, which we only need for grabbing modifiers */
55 /* Because the statusline is the same on all outputs, we have
56 * global buffer to render it on */
57 xcb_gcontext_t statusline_ctx;
58 xcb_pixmap_t statusline_pm;
59 uint32_t statusline_width;
61 /* Event-Watchers, to interact with the user */
67 /* The parsed colors */
71 uint32_t active_ws_fg;
72 uint32_t active_ws_bg;
73 uint32_t inactive_ws_fg;
74 uint32_t inactive_ws_bg;
75 uint32_t urgent_ws_bg;
76 uint32_t urgent_ws_fg;
78 struct xcb_colors_t colors;
80 /* We define xcb_request_failed as a macro to include the relevant line-number */
81 #define xcb_request_failed(cookie, err_msg) _xcb_request_failed(cookie, err_msg, __LINE__)
82 int _xcb_request_failed(xcb_void_cookie_t cookie, char *err_msg, int line) {
83 xcb_generic_error_t *err;
84 if ((err = xcb_request_check(xcb_connection, cookie)) != NULL) {
85 ELOG("%s. X Error Code: %d\n", err_msg, err->error_code);
86 return err->error_code;
92 * Predicts the length of text based on cached data.
93 * The string has to be encoded in ucs2 and glyph_len has to be the length
94 * of the string (in glyphs).
97 uint32_t predict_text_extents(xcb_char2b_t *text, uint32_t length) {
98 /* If we don't have per-character data, return the maximum width */
99 if (font_table == NULL) {
100 return (font_info->max_bounds.character_width * length);
106 for (i = 0; i < length; i++) {
107 xcb_charinfo_t *info;
108 int row = text[i].byte1;
109 int col = text[i].byte2;
111 if (row < font_info->min_byte1 || row > font_info->max_byte1 ||
112 col < font_info->min_char_or_byte2 || col > font_info->max_char_or_byte2) {
116 /* Don't you ask me, how this one works… */
117 info = &font_table[((row - font_info->min_byte1) *
118 (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
119 (col - font_info->min_char_or_byte2)];
121 if (info->character_width != 0 ||
122 (info->right_side_bearing |
123 info->left_side_bearing |
125 info->descent) != 0) {
126 width += info->character_width;
134 * Draws text given in UCS-2-encoding to a given drawable and position
137 void draw_text(xcb_drawable_t drawable, xcb_gcontext_t ctx, int16_t x, int16_t y,
138 xcb_char2b_t *text, uint32_t glyph_count) {
141 int16_t font_ascent = font_info->font_ascent;
143 while (glyph_count > 0) {
144 uint8_t chunk_size = MIN(255, glyph_count);
145 uint32_t chunk_width = predict_text_extents(text + offset, chunk_size);
147 xcb_image_text_16(xcb_connection,
151 pos_x, y + font_ascent,
154 offset += chunk_size;
155 pos_x += chunk_width;
156 glyph_count -= chunk_size;
161 * Converts a colorstring to a colorpixel as expected from xcb_change_gc.
162 * s is assumed to be in the format "rrggbb"
165 uint32_t get_colorpixel(const char *s) {
166 char strings[3][3] = { { s[0], s[1], '\0'} ,
167 { s[2], s[3], '\0'} ,
168 { s[4], s[5], '\0'} };
169 uint8_t r = strtol(strings[0], NULL, 16);
170 uint8_t g = strtol(strings[1], NULL, 16);
171 uint8_t b = strtol(strings[2], NULL, 16);
172 return (r << 16 | g << 8 | b);
176 * Redraws the statusline to the buffer
179 void refresh_statusline() {
182 if (statusline == NULL) {
186 xcb_char2b_t *text = (xcb_char2b_t*) convert_utf8_to_ucs2(statusline, &glyph_count);
187 statusline_width = predict_text_extents(text, glyph_count);
189 xcb_free_pixmap(xcb_connection, statusline_pm);
190 statusline_pm = xcb_generate_id(xcb_connection);
191 xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
192 xcb_screen->root_depth,
198 draw_text(statusline_pm, statusline_ctx, 0, 0, text, glyph_count);
200 if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer")) {
206 * Hides all bars (unmaps them)
210 if (!config.hide_on_modifier) {
215 SLIST_FOREACH(walk, outputs, slist) {
216 xcb_unmap_window(xcb_connection, walk->bar);
222 * Unhides all bars (maps them)
226 if (!config.hide_on_modifier) {
231 xcb_void_cookie_t cookie;
237 SLIST_FOREACH(walk, outputs, slist) {
238 if (walk->bar == XCB_NONE) {
241 mask = XCB_CONFIG_WINDOW_X |
242 XCB_CONFIG_WINDOW_Y |
243 XCB_CONFIG_WINDOW_WIDTH |
244 XCB_CONFIG_WINDOW_HEIGHT |
245 XCB_CONFIG_WINDOW_STACK_MODE;
246 values[0] = walk->rect.x;
247 values[1] = walk->rect.y + walk->rect.h - font_height - 6;
248 values[2] = walk->rect.w;
249 values[3] = font_height + 6;
250 values[4] = XCB_STACK_MODE_ABOVE;
251 DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
252 cookie = xcb_configure_window_checked(xcb_connection,
257 if (xcb_request_failed(cookie, "Could not reconfigure window")) {
260 xcb_map_window(xcb_connection, walk->bar);
265 * Parse the colors into a format that we can use
268 void init_colors(const struct xcb_color_strings_t *new_colors) {
269 #define PARSE_COLOR(name, def) \
271 colors.name = get_colorpixel(new_colors->name ? new_colors->name : def); \
273 PARSE_COLOR(bar_fg, "FFFFFF");
274 PARSE_COLOR(bar_bg, "000000");
275 PARSE_COLOR(active_ws_fg, "FFFFFF");
276 PARSE_COLOR(active_ws_bg, "480000");
277 PARSE_COLOR(inactive_ws_fg, "FFFFFF");
278 PARSE_COLOR(inactive_ws_bg, "240000");
279 PARSE_COLOR(urgent_ws_fg, "FFFFFF");
280 PARSE_COLOR(urgent_ws_bg, "002400");
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
290 void handle_button(xcb_button_press_event_t *event) {
293 /* Determine, which bar was clicked */
295 xcb_window_t bar = event->event;
296 SLIST_FOREACH(walk, outputs, slist) {
297 if (walk->bar == bar) {
303 DLOG("Unknown Bar klicked!\n");
307 /* TODO: Move this to extern get_ws_for_output() */
308 TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
309 if (cur_ws->visible) {
314 if (cur_ws == NULL) {
315 DLOG("No Workspace active?\n");
319 int32_t x = event->event_x;
321 DLOG("Got Button %d\n", event->detail);
323 switch (event->detail) {
325 /* Left Mousbutton. We determine, which button was clicked
326 * and set cur_ws accordingly */
327 TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
329 if (x < cur_ws->name_width + 10) {
332 x -= cur_ws->name_width + 10;
334 if (cur_ws == NULL) {
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);
343 cur_ws = TAILQ_PREV(cur_ws, ws_head, tailq);
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);
351 cur_ws = TAILQ_NEXT(cur_ws, tailq);
357 snprintf(buffer, 50, "%d", cur_ws->num);
358 i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
362 * This function is called immediately bevor the main loop locks. We flush xcb
363 * then (and only then)
366 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revenst) {
367 xcb_flush(xcb_connection);
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.
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) {
382 switch (event->response_type & ~0x80) {
384 /* Expose-events happen, when the window needs to be redrawn */
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);
396 * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
400 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
404 * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
407 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
411 DLOG("Got XKB-Event!\n");
413 while (XPending(xkb_dpy)) {
414 XNextEvent(xkb_dpy, (XEvent*)&ev);
416 if (ev.type != xkb_event_base) {
417 ELOG("No Xkb-Event!\n");
421 if (ev.any.xkb_type != XkbStateNotify) {
422 ELOG("No State Notify!\n");
426 unsigned int mods = ev.state.mods;
427 modstate = mods & Mod4Mask;
430 if (modstate != mod_pressed) {
432 DLOG("Mod4 got released!\n");
435 DLOG("Mod4 got pressed!\n");
438 mod_pressed = modstate;
443 * Initialize xcb and use the specified fontname for text-rendering
446 void 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");
453 DLOG("Connected to xcb\n");
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"
459 xcb_screen = xcb_setup_roots_iterator(xcb_get_setup(xcb_connection)).data;
460 xcb_root = xcb_screen->root;
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,
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,
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
479 if (config.hide_on_modifier) {
480 int xkb_major, xkb_minor, xkb_errbase, xkb_err;
481 xkb_major = XkbMajorVersion;
482 xkb_minor = XkbMinorVersion;
484 xkb_dpy = XkbOpenDisplay(":0",
491 if (xkb_dpy == NULL) {
496 if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
497 ELOG("Could not set FD_CLOEXEC on xkbdpy: %s\n", strerror(errno));
502 if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
503 ELOG("XKB not supported by X-server!\n");
507 if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
508 ELOG("Could not grab Key!\n");
512 xkb_io = malloc(sizeof(ev_io));
513 ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
514 ev_io_start(main_loop, xkb_io);
518 /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
519 * this way, we can choose to crop it */
520 statusline_ctx = xcb_generate_id(xcb_connection);
521 uint32_t mask = XCB_GC_FOREGROUND |
524 uint32_t vals[3] = { colors.bar_fg, colors.bar_bg, xcb_font };
526 xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
532 /* We only generate an id for the pixmap, because the width of it is dependent on the
534 statusline_pm = xcb_generate_id(xcb_connection);
536 /* The varios Watchers to communicate with xcb */
537 xcb_io = malloc(sizeof(ev_io));
538 xcb_prep = malloc(sizeof(ev_prepare));
539 xcb_chk = malloc(sizeof(ev_check));
541 ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
542 ev_prepare_init(xcb_prep, &xcb_prep_cb);
543 ev_check_init(xcb_chk, &xcb_chk_cb);
545 ev_io_start(main_loop, xcb_io);
546 ev_prepare_start(main_loop, xcb_prep);
547 ev_check_start(main_loop, xcb_chk);
549 /* Now we get the atoms and save them in a nice data-structure */
552 /* Now we save the font-infos */
553 font_info = xcb_query_font_reply(xcb_connection,
557 if (xcb_request_failed(open_font_cookie, "Could not open font")) {
561 font_height = font_info->font_ascent + font_info->font_descent;
563 if (xcb_query_font_char_infos_length(font_info) == 0) {
566 font_table = xcb_query_font_char_infos(font_info);
569 DLOG("Calculated Font-height: %d\n", font_height);
571 if (xcb_request_failed(sl_ctx_cookie, "Could not create context for statusline")) {
577 * Cleanup the xcb-stuff.
578 * Called once, before the program terminates.
583 SLIST_FOREACH(walk, outputs, slist) {
584 destroy_window(walk);
586 FREE_SLIST(outputs, i3_output);
588 xcb_disconnect(xcb_connection);
590 ev_check_stop(main_loop, xcb_chk);
591 ev_prepare_stop(main_loop, xcb_prep);
592 ev_io_stop(main_loop, xcb_io);
601 * Get the earlier requested atoms and save them in the prepared data-structure
605 xcb_intern_atom_reply_t *reply;
606 #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
607 if (reply == NULL) { \
608 ELOG("Could not get atom %s\n", #name); \
609 exit(EXIT_FAILURE); \
611 atoms[name] = reply->atom; \
614 #include "xcb_atoms.def"
619 * Destroy the bar of the specified output
622 void destroy_window(i3_output *output) {
623 if (output == NULL) {
626 if (output->bar == XCB_NONE) {
629 xcb_destroy_window(xcb_connection, output->bar);
630 output->bar = XCB_NONE;
634 * Reconfigure all bars and create new for newly activated outputs
637 void reconfig_windows() {
642 SLIST_FOREACH(walk, outputs, slist) {
644 /* If an output is not active, we destroy it's bar */
645 /* FIXME: Maybe we rather want to unmap? */
646 DLOG("Destroying window for output %s\n", walk->name);
647 destroy_window(walk);
650 if (walk->bar == XCB_NONE) {
651 DLOG("Creating Window for output %s\n", walk->name);
653 walk->bar = xcb_generate_id(xcb_connection);
654 walk->buffer = xcb_generate_id(xcb_connection);
655 mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
656 /* Black background */
657 values[0] = colors.bar_bg;
658 /* If hide_on_modifier is set, i3 is not supposed to manage our bar-windows */
659 values[1] = config.hide_on_modifier;
660 /* The events we want to receive */
661 values[2] = XCB_EVENT_MASK_EXPOSURE |
662 XCB_EVENT_MASK_BUTTON_PRESS;
663 xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
664 xcb_screen->root_depth,
667 walk->rect.x, walk->rect.y + walk->rect.h - font_height - 6,
668 walk->rect.w, font_height + 6,
670 XCB_WINDOW_CLASS_INPUT_OUTPUT,
671 xcb_screen->root_visual,
675 /* The double-buffer we use to render stuff off-screen */
676 xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
677 xcb_screen->root_depth,
683 /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
685 xcb_void_cookie_t prop_cookie = xcb_change_property(xcb_connection,
686 XCB_PROP_MODE_REPLACE,
688 atoms[_NET_WM_WINDOW_TYPE],
692 (unsigned char*) &atoms[_NET_WM_WINDOW_TYPE_DOCK]);
694 /* We also want a graphics-context for the bars (it defines the properties
695 * with which we draw to them) */
696 walk->bargc = xcb_generate_id(xcb_connection);
698 values[0] = xcb_font;
699 xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
705 /* We finally map the bar (display it on screen), unless the modifier-switch is on */
706 xcb_void_cookie_t map_cookie;
707 if (!config.hide_on_modifier) {
708 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
711 if (xcb_request_failed(win_cookie, "Could not create window") ||
712 xcb_request_failed(pm_cookie, "Could not create pixmap") ||
713 xcb_request_failed(prop_cookie, "Could not set dock mode") ||
714 xcb_request_failed(gc_cookie, "Could not create graphical context") ||
715 (!config.hide_on_modifier && xcb_request_failed(map_cookie, "Could not map window"))) {
719 /* We already have a bar, so we just reconfigure it */
720 mask = XCB_CONFIG_WINDOW_X |
721 XCB_CONFIG_WINDOW_Y |
722 XCB_CONFIG_WINDOW_WIDTH |
723 XCB_CONFIG_WINDOW_HEIGHT |
724 XCB_CONFIG_WINDOW_STACK_MODE;
725 values[0] = walk->rect.x;
726 values[1] = walk->rect.y + walk->rect.h - font_height - 6;
727 values[2] = walk->rect.w;
728 values[3] = font_height + 6;
729 values[4] = XCB_STACK_MODE_ABOVE;
731 DLOG("Destroying buffer for output %s", walk->name);
732 xcb_free_pixmap(xcb_connection, walk->buffer);
734 DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
735 xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
740 DLOG("Recreating buffer for output %s", walk->name);
741 xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
742 xcb_screen->root_depth,
748 if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
751 if (xcb_request_failed(pm_cookie, "Could not create pixmap")) {
759 * Render the bars, with buttons and statusline
763 DLOG("Drawing Bars...\n");
766 refresh_statusline();
768 i3_output *outputs_walk;
769 SLIST_FOREACH(outputs_walk, outputs, slist) {
770 if (!outputs_walk->active) {
771 DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
774 if (outputs_walk->bar == XCB_NONE) {
775 /* Oh shit, an active output without an own bar. Create it now! */
778 /* First things first: clear the backbuffer */
779 uint32_t color = colors.bar_bg;
780 xcb_change_gc(xcb_connection,
784 xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font_height + 6 };
785 xcb_poly_fill_rectangle(xcb_connection,
786 outputs_walk->buffer,
791 if (statusline != NULL) {
792 DLOG("Printing statusline!\n");
794 /* Luckily we already prepared a seperate pixmap containing the rendered
795 * statusline, we just have to copy the relevant parts to the relevant
797 xcb_copy_area(xcb_connection,
799 outputs_walk->buffer,
801 MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
802 MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - 4)), 3,
803 MIN(outputs_walk->rect.w - 4, statusline_width), font_height);
807 TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
808 DLOG("Drawing Button for WS %s at x = %d\n", ws_walk->name, i);
809 uint32_t fg_color = colors.inactive_ws_fg;
810 uint32_t bg_color = colors.inactive_ws_bg;
811 if (ws_walk->visible) {
812 fg_color = colors.active_ws_fg;
813 bg_color = colors.active_ws_bg;
815 if (ws_walk->urgent) {
816 DLOG("WS %s is urgent!\n", ws_walk->name);
817 fg_color = colors.urgent_ws_fg;
818 bg_color = colors.urgent_ws_bg;
819 /* The urgent-hint should get noticed, so we unhide the bars shortly */
822 xcb_change_gc(xcb_connection,
826 xcb_change_gc(xcb_connection,
830 xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font_height + 4 };
831 xcb_poly_fill_rectangle(xcb_connection,
832 outputs_walk->buffer,
836 xcb_change_gc(xcb_connection,
840 xcb_image_text_16(xcb_connection,
841 ws_walk->name_glyphs,
842 outputs_walk->buffer,
844 i + 5, font_info->font_ascent + 2,
846 i += 10 + ws_walk->name_width;
856 * Redraw the bars, i.e. simply copy the buffer to the barwindow
860 i3_output *outputs_walk;
861 SLIST_FOREACH(outputs_walk, outputs, slist) {
862 xcb_copy_area(xcb_connection,
863 outputs_walk->buffer,
868 outputs_walk->rect.w,
869 outputs_walk->rect.h);
870 xcb_flush(xcb_connection);