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>
22 #include <X11/XKBlib.h>
23 #include <X11/extensions/XKB.h>
27 /* We save the Atoms in an easy to access array, indexed by an enum */
31 #define ATOM_DO(name) name,
32 #include "xcb_atoms.def"
35 xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
36 xcb_atom_t atoms[NUM_ATOMS];
38 /* Variables, that are the same for all functions at all times */
39 xcb_connection_t *xcb_connection;
40 xcb_screen_t *xcb_screen;
41 xcb_window_t xcb_root;
44 /* We need to cache some data to speed up text-width-prediction */
45 xcb_query_font_reply_t *font_info;
47 xcb_charinfo_t *font_table;
49 /* These are only relevant for XKB, which we only need for grabbing modifiers */
54 /* Because the statusline is the same on all outputs, we have
55 * global buffer to render it on */
56 xcb_gcontext_t statusline_ctx;
57 xcb_pixmap_t statusline_pm;
58 uint32_t statusline_width;
60 /* Event-Watchers, to interact with the user */
66 /* The parsed colors */
70 uint32_t active_ws_fg;
71 uint32_t active_ws_bg;
72 uint32_t inactive_ws_fg;
73 uint32_t inactive_ws_bg;
74 uint32_t urgent_ws_bg;
75 uint32_t urgent_ws_fg;
77 struct xcb_colors_t colors;
79 /* We define xcb_request_failed as a macro to include the relevant line-number */
80 #define xcb_request_failed(cookie, err_msg) _xcb_request_failed(cookie, err_msg, __LINE__)
81 int _xcb_request_failed(xcb_void_cookie_t cookie, char *err_msg, int line) {
82 xcb_generic_error_t *err;
83 if ((err = xcb_request_check(xcb_connection, cookie)) != NULL) {
84 ELOG("%s. X Error Code: %d\n", err_msg, err->error_code);
85 return err->error_code;
91 * Predicts the length of text based on cached data.
92 * The string has to be encoded in ucs2 and glyph_len has to be the length
93 * of the string (in glyphs).
96 uint32_t predict_text_extents(xcb_char2b_t *text, uint32_t length) {
97 /* If we don't have per-character data, return the maximum width */
98 if (font_table == NULL) {
99 return (font_info->max_bounds.character_width * length);
105 for (i = 0; i < length; i++) {
106 xcb_charinfo_t *info;
107 int row = text[i].byte1;
108 int col = text[i].byte2;
110 if (row < font_info->min_byte1 || row > font_info->max_byte1 ||
111 col < font_info->min_char_or_byte2 || col > font_info->max_char_or_byte2) {
115 /* Don't you ask me, how this one works… */
116 info = &font_table[((row - font_info->min_byte1) *
117 (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
118 (col - font_info->min_char_or_byte2)];
120 if (info->character_width != 0 ||
121 (info->right_side_bearing |
122 info->left_side_bearing |
124 info->descent) != 0) {
125 width += info->character_width;
133 * Draws text given in UCS-2-encoding to a given drawable and position
136 void draw_text(xcb_drawable_t drawable, xcb_gcontext_t ctx, int16_t x, int16_t y,
137 xcb_char2b_t *text, uint32_t glyph_count) {
140 int16_t font_ascent = font_info->font_ascent;
142 while (glyph_count > 0) {
143 uint8_t chunk_size = MIN(255, glyph_count);
144 uint32_t chunk_width = predict_text_extents(text + offset, chunk_size);
146 xcb_image_text_16(xcb_connection,
150 pos_x, y + font_ascent,
153 offset += chunk_size;
154 pos_x += chunk_width;
155 glyph_count -= chunk_size;
160 * Converts a colorstring to a colorpixel as expected from xcb_change_gc.
161 * s is assumed to be in the format "rrggbb"
164 uint32_t get_colorpixel(const char *s) {
165 char strings[3][3] = { { s[0], s[1], '\0'} ,
166 { s[2], s[3], '\0'} ,
167 { s[4], s[5], '\0'} };
168 uint8_t r = strtol(strings[0], NULL, 16);
169 uint8_t g = strtol(strings[1], NULL, 16);
170 uint8_t b = strtol(strings[2], NULL, 16);
171 return (r << 16 | g << 8 | b);
175 * Redraws the statusline to the buffer
178 void refresh_statusline() {
181 if (statusline == NULL) {
185 xcb_char2b_t *text = (xcb_char2b_t*) convert_utf8_to_ucs2(statusline, &glyph_count);
186 statusline_width = predict_text_extents(text, glyph_count);
188 xcb_free_pixmap(xcb_connection, statusline_pm);
189 statusline_pm = xcb_generate_id(xcb_connection);
190 xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
191 xcb_screen->root_depth,
197 draw_text(statusline_pm, statusline_ctx, 0, 0, text, glyph_count);
199 if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer")) {
205 * Hides all bars (unmaps them)
209 if (!config.hide_on_modifier) {
214 SLIST_FOREACH(walk, outputs, slist) {
215 xcb_unmap_window(xcb_connection, walk->bar);
221 * Unhides all bars (maps them)
225 if (!config.hide_on_modifier) {
230 xcb_void_cookie_t cookie;
236 SLIST_FOREACH(walk, outputs, slist) {
237 if (walk->bar == XCB_NONE) {
240 mask = XCB_CONFIG_WINDOW_X |
241 XCB_CONFIG_WINDOW_Y |
242 XCB_CONFIG_WINDOW_WIDTH |
243 XCB_CONFIG_WINDOW_HEIGHT |
244 XCB_CONFIG_WINDOW_STACK_MODE;
245 values[0] = walk->rect.x;
246 values[1] = walk->rect.y + walk->rect.h - font_height - 6;
247 values[2] = walk->rect.w;
248 values[3] = font_height + 6;
249 values[4] = XCB_STACK_MODE_ABOVE;
250 DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
251 cookie = xcb_configure_window_checked(xcb_connection,
256 if (xcb_request_failed(cookie, "Could not reconfigure window")) {
259 xcb_map_window(xcb_connection, walk->bar);
264 * Parse the colors into a format that we can use
267 void init_colors(const struct xcb_color_strings_t *new_colors) {
268 #define PARSE_COLOR(name, def) \
270 colors.name = get_colorpixel(new_colors->name ? new_colors->name : def); \
272 PARSE_COLOR(bar_fg, "FFFFFF");
273 PARSE_COLOR(bar_bg, "000000");
274 PARSE_COLOR(active_ws_fg, "FFFFFF");
275 PARSE_COLOR(active_ws_bg, "480000");
276 PARSE_COLOR(inactive_ws_fg, "FFFFFF");
277 PARSE_COLOR(inactive_ws_bg, "240000");
278 PARSE_COLOR(urgent_ws_fg, "FFFFFF");
279 PARSE_COLOR(urgent_ws_bg, "002400");
284 * Handle a button-press-event (i.c. a mouse click on one of our bars).
285 * We determine, wether the click occured on a ws-button or if the scroll-
286 * wheel was used and change the workspace appropriately
289 void handle_button(xcb_button_press_event_t *event) {
292 /* Determine, which bar was clicked */
294 xcb_window_t bar = event->event;
295 SLIST_FOREACH(walk, outputs, slist) {
296 if (walk->bar == bar) {
302 DLOG("Unknown Bar klicked!\n");
306 /* TODO: Move this to extern get_ws_for_output() */
307 TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
308 if (cur_ws->visible) {
313 if (cur_ws == NULL) {
314 DLOG("No Workspace active?\n");
318 int32_t x = event->event_x;
320 DLOG("Got Button %d\n", event->detail);
322 switch (event->detail) {
324 /* Left Mousbutton. We determine, which button was clicked
325 * and set cur_ws accordingly */
326 TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
328 if (x < cur_ws->name_width + 10) {
331 x -= cur_ws->name_width + 10;
333 if (cur_ws == NULL) {
338 /* Mouse wheel down. We select the next ws */
339 if (cur_ws == TAILQ_FIRST(walk->workspaces)) {
340 cur_ws = TAILQ_LAST(walk->workspaces, ws_head);
342 cur_ws = TAILQ_PREV(cur_ws, ws_head, tailq);
346 /* Mouse wheel up. We select the previos ws */
347 if (cur_ws == TAILQ_LAST(walk->workspaces, ws_head)) {
348 cur_ws = TAILQ_FIRST(walk->workspaces);
350 cur_ws = TAILQ_NEXT(cur_ws, tailq);
356 snprintf(buffer, 50, "%d", cur_ws->num);
357 i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
361 * This function is called immediately bevor the main loop locks. We flush xcb
362 * then (and only then)
365 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revenst) {
366 xcb_flush(xcb_connection);
370 * This function is called immediately after the main loop locks, so when one
371 * of the watchers registered an event.
372 * We check wether an X-Event arrived and handle it.
375 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
376 xcb_generic_event_t *event;
377 while ((event = xcb_poll_for_event(xcb_connection)) == NULL) {
381 switch (event->response_type & ~0x80) {
383 /* Expose-events happen, when the window needs to be redrawn */
386 case XCB_BUTTON_PRESS:
387 /* Button-press-events are mouse-buttons clicked on one of our bars */
388 handle_button((xcb_button_press_event_t*) event);
395 * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
399 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
403 * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
406 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
410 DLOG("Got XKB-Event!\n");
412 while (XPending(xkb_dpy)) {
413 XNextEvent(xkb_dpy, (XEvent*)&ev);
415 if (ev.type != xkb_event_base) {
416 ELOG("No Xkb-Event!\n");
420 if (ev.any.xkb_type != XkbStateNotify) {
421 ELOG("No State Notify!\n");
425 unsigned int mods = ev.state.mods;
426 modstate = mods & Mod4Mask;
429 if (modstate != mod_pressed) {
431 DLOG("Mod4 got released!\n");
434 DLOG("Mod4 got pressed!\n");
437 mod_pressed = modstate;
442 * Initialize xcb and use the specified fontname for text-rendering
445 void init_xcb(char *fontname) {
446 /* FIXME: xcb_connect leaks Memory */
447 xcb_connection = xcb_connect(NULL, NULL);
448 if (xcb_connection_has_error(xcb_connection)) {
449 ELOG("Cannot open display\n");
452 DLOG("Connected to xcb\n");
454 /* We have to request the atoms we need */
455 #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
456 #include "xcb_atoms.def"
458 xcb_screen = xcb_setup_roots_iterator(xcb_get_setup(xcb_connection)).data;
459 xcb_root = xcb_screen->root;
461 /* We load and allocate the font */
462 xcb_font = xcb_generate_id(xcb_connection);
463 xcb_void_cookie_t open_font_cookie;
464 open_font_cookie = xcb_open_font_checked(xcb_connection,
469 /* We need to save info about the font, because we need the fonts height and
470 * information about the width of characters */
471 xcb_query_font_cookie_t query_font_cookie;
472 query_font_cookie = xcb_query_font(xcb_connection,
475 /* To grab modifiers without blocking other applications from receiving key-events
476 * involving that modifier, we sadly have to use xkb which is not yet fully supported
478 if (config.hide_on_modifier) {
479 int xkb_major, xkb_minor, xkb_errbase, xkb_err;
480 xkb_major = XkbMajorVersion;
481 xkb_minor = XkbMinorVersion;
483 xkb_dpy = XkbOpenDisplay(":0",
490 if (xkb_dpy == NULL) {
495 if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
496 ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
501 if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
502 ELOG("XKB not supported by X-server!\n");
506 if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
507 ELOG("Could not grab Key!\n");
511 xkb_io = malloc(sizeof(ev_io));
512 ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
513 ev_io_start(main_loop, xkb_io);
517 /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
518 * this way, we can choose to crop it */
519 statusline_ctx = xcb_generate_id(xcb_connection);
520 uint32_t mask = XCB_GC_FOREGROUND |
523 uint32_t vals[3] = { colors.bar_fg, colors.bar_bg, xcb_font };
525 xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
531 /* We only generate an id for the pixmap, because the width of it is dependent on the
533 statusline_pm = xcb_generate_id(xcb_connection);
535 /* The varios Watchers to communicate with xcb */
536 xcb_io = malloc(sizeof(ev_io));
537 xcb_prep = malloc(sizeof(ev_prepare));
538 xcb_chk = malloc(sizeof(ev_check));
540 ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
541 ev_prepare_init(xcb_prep, &xcb_prep_cb);
542 ev_check_init(xcb_chk, &xcb_chk_cb);
544 ev_io_start(main_loop, xcb_io);
545 ev_prepare_start(main_loop, xcb_prep);
546 ev_check_start(main_loop, xcb_chk);
548 /* Now we get the atoms and save them in a nice data-structure */
551 /* Now we save the font-infos */
552 font_info = xcb_query_font_reply(xcb_connection,
555 font_height = font_info->font_ascent + font_info->font_descent;
557 if (xcb_request_failed(open_font_cookie, "Could not open font")) {
561 if (xcb_query_font_char_infos_length(font_info) == 0) {
564 font_table = xcb_query_font_char_infos(font_info);
567 DLOG("Calculated Font-height: %d\n", font_height);
569 if (xcb_request_failed(sl_ctx_cookie, "Could not create context for statusline")) {
575 * Cleanup the xcb-stuff.
576 * Called once, before the program terminates.
581 SLIST_FOREACH(walk, outputs, slist) {
582 destroy_window(walk);
584 FREE_SLIST(outputs, i3_output);
586 xcb_disconnect(xcb_connection);
588 ev_check_stop(main_loop, xcb_chk);
589 ev_prepare_stop(main_loop, xcb_prep);
590 ev_io_stop(main_loop, xcb_io);
599 * Get the earlier requested atoms and save them in the prepared data-structure
603 xcb_intern_atom_reply_t *reply;
604 #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
605 if (reply == NULL) { \
606 ELOG("Could not get atom %s\n", #name); \
607 exit(EXIT_FAILURE); \
609 atoms[name] = reply->atom; \
612 #include "xcb_atoms.def"
617 * Destroy the bar of the specified output
620 void destroy_window(i3_output *output) {
621 if (output == NULL) {
624 if (output->bar == XCB_NONE) {
627 xcb_destroy_window(xcb_connection, output->bar);
628 output->bar = XCB_NONE;
632 * Reconfigure all bars and create new for newly activated outputs
635 void reconfig_windows() {
639 xcb_generic_error_t *err;
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;
730 DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
731 xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
735 if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
743 * Render the bars, with buttons and statusline
747 DLOG("Drawing Bars...\n");
750 refresh_statusline();
752 i3_output *outputs_walk;
753 SLIST_FOREACH(outputs_walk, outputs, slist) {
754 if (!outputs_walk->active) {
755 DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
758 if (outputs_walk->bar == XCB_NONE) {
759 /* Oh shit, an active output without an own bar. Create it now! */
762 /* First things first: clear the backbuffer */
763 uint32_t color = colors.bar_bg;
764 xcb_change_gc(xcb_connection,
768 xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font_height + 6 };
769 xcb_poly_fill_rectangle(xcb_connection,
770 outputs_walk->buffer,
775 if (statusline != NULL) {
776 DLOG("Printing statusline!\n");
778 /* Luckily we already prepared a seperate pixmap containing the rendered
779 * statusline, we just have to copy the relevant parts to the relevant
781 xcb_copy_area(xcb_connection,
783 outputs_walk->buffer,
785 MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
786 MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - 4)), 3,
787 MIN(outputs_walk->rect.w - 4, statusline_width), font_height);
791 TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
792 DLOG("Drawing Button for WS %s at x = %d\n", ws_walk->name, i);
793 uint32_t fg_color = colors.inactive_ws_fg;
794 uint32_t bg_color = colors.inactive_ws_bg;
795 if (ws_walk->visible) {
796 fg_color = colors.active_ws_fg;
797 bg_color = colors.active_ws_bg;
799 if (ws_walk->urgent) {
800 DLOG("WS %s is urgent!\n", ws_walk->name);
801 fg_color = colors.urgent_ws_fg;
802 bg_color = colors.urgent_ws_bg;
803 /* The urgent-hint should get noticed, so we unhide the bars shortly */
806 xcb_change_gc(xcb_connection,
810 xcb_change_gc(xcb_connection,
814 xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font_height + 4 };
815 xcb_poly_fill_rectangle(xcb_connection,
816 outputs_walk->buffer,
820 xcb_change_gc(xcb_connection,
824 xcb_image_text_16(xcb_connection,
825 ws_walk->name_glyphs,
826 outputs_walk->buffer,
828 i + 5, font_info->font_ascent + 2,
830 i += 10 + ws_walk->name_width;
840 * Redraw the bars, i.e. simply copy the buffer to the barwindow
844 i3_output *outputs_walk;
845 SLIST_FOREACH(outputs_walk, outputs, slist) {
846 xcb_copy_area(xcb_connection,
847 outputs_walk->buffer,
852 outputs_walk->rect.w,
853 outputs_walk->rect.h);
854 xcb_flush(xcb_connection);