2 * vim:ts=4:sw=4:expandtab
4 * i3bar - an xcb-based status- and ws-bar for i3
6 * © 2010-2011 Axel Wagner and contributors
8 * See file LICNSE for license information
10 * src/xcb.c: Communicating with X
14 #include <xcb/xproto.h>
15 #include <xcb/xcb_atom.h>
18 #include "xcb_compat.h"
33 #include <X11/XKBlib.h>
34 #include <X11/extensions/XKB.h>
39 #if defined(__APPLE__)
43 * Returns a pointer to a new string which is a duplicate of the
44 * string, but only copies at most n characters.
47 char *strndup(const char *str, size_t n) {
51 for (len = 0; len < n && str[len]; len++)
54 copy = smalloc(len + 1);
55 memcpy(copy, str, len);
62 /* We save the Atoms in an easy to access array, indexed by an enum */
64 #define ATOM_DO(name) name,
65 #include "xcb_atoms.def"
69 xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
70 xcb_atom_t atoms[NUM_ATOMS];
72 /* Variables, that are the same for all functions at all times */
73 xcb_connection_t *xcb_connection;
75 xcb_screen_t *xcb_screen;
76 xcb_window_t xcb_root;
79 /* We need to cache some data to speed up text-width-prediction */
80 xcb_query_font_reply_t *font_info;
82 xcb_charinfo_t *font_table;
84 /* These are only relevant for XKB, which we only need for grabbing modifiers */
89 /* Because the statusline is the same on all outputs, we have
90 * global buffer to render it on */
91 xcb_gcontext_t statusline_ctx;
92 xcb_gcontext_t statusline_clear;
93 xcb_pixmap_t statusline_pm;
94 uint32_t statusline_width;
96 /* Event-Watchers, to interact with the user */
102 /* The parsed colors */
103 struct xcb_colors_t {
106 uint32_t active_ws_fg;
107 uint32_t active_ws_bg;
108 uint32_t inactive_ws_fg;
109 uint32_t inactive_ws_bg;
110 uint32_t urgent_ws_bg;
111 uint32_t urgent_ws_fg;
112 uint32_t focus_ws_bg;
113 uint32_t focus_ws_fg;
115 struct xcb_colors_t colors;
117 /* We define xcb_request_failed as a macro to include the relevant line-number */
118 #define xcb_request_failed(cookie, err_msg) _xcb_request_failed(cookie, err_msg, __LINE__)
119 int _xcb_request_failed(xcb_void_cookie_t cookie, char *err_msg, int line) {
120 xcb_generic_error_t *err;
121 if ((err = xcb_request_check(xcb_connection, cookie)) != NULL) {
122 fprintf(stderr, "[%s:%d] ERROR: %s. X Error Code: %d\n", __FILE__, line, err_msg, err->error_code);
123 return err->error_code;
129 * Predicts the length of text based on cached data.
130 * The string has to be encoded in ucs2 and glyph_len has to be the length
131 * of the string (in glyphs).
134 uint32_t predict_text_extents(xcb_char2b_t *text, uint32_t length) {
135 /* If we don't have per-character data, return the maximum width */
136 if (font_table == NULL) {
137 return (font_info->max_bounds.character_width * length);
143 for (i = 0; i < length; i++) {
144 xcb_charinfo_t *info;
145 int row = text[i].byte1;
146 int col = text[i].byte2;
148 if (row < font_info->min_byte1 || row > font_info->max_byte1 ||
149 col < font_info->min_char_or_byte2 || col > font_info->max_char_or_byte2) {
153 /* Don't you ask me, how this one works… */
154 info = &font_table[((row - font_info->min_byte1) *
155 (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
156 (col - font_info->min_char_or_byte2)];
158 if (info->character_width != 0 ||
159 (info->right_side_bearing |
160 info->left_side_bearing |
162 info->descent) != 0) {
163 width += info->character_width;
171 * Draws text given in UCS-2-encoding to a given drawable and position
174 void draw_text(xcb_drawable_t drawable, xcb_gcontext_t ctx, int16_t x, int16_t y,
175 xcb_char2b_t *text, uint32_t glyph_count) {
178 int16_t font_ascent = font_info->font_ascent;
180 while (glyph_count > 0) {
181 uint8_t chunk_size = MIN(255, glyph_count);
182 uint32_t chunk_width = predict_text_extents(text + offset, chunk_size);
184 xcb_image_text_16(xcb_connection,
188 pos_x, y + font_ascent,
191 offset += chunk_size;
192 pos_x += chunk_width;
193 glyph_count -= chunk_size;
198 * Converts a colorstring to a colorpixel as expected from xcb_change_gc.
199 * s is assumed to be in the format "rrggbb"
202 uint32_t get_colorpixel(const char *s) {
203 char strings[3][3] = { { s[0], s[1], '\0'} ,
204 { s[2], s[3], '\0'} ,
205 { s[4], s[5], '\0'} };
206 uint8_t r = strtol(strings[0], NULL, 16);
207 uint8_t g = strtol(strings[1], NULL, 16);
208 uint8_t b = strtol(strings[2], NULL, 16);
209 return (r << 16 | g << 8 | b);
213 * Redraws the statusline to the buffer
216 void refresh_statusline() {
219 if (statusline == NULL) {
223 xcb_char2b_t *text = (xcb_char2b_t*) convert_utf8_to_ucs2(statusline, &glyph_count);
224 uint32_t old_statusline_width = statusline_width;
225 statusline_width = predict_text_extents(text, glyph_count);
226 /* If the statusline is bigger than our screen we need to make sure that
227 * the pixmap provides enough space, so re-allocate if the width grew */
228 if (statusline_width > xcb_screen->width_in_pixels &&
229 statusline_width > old_statusline_width)
232 xcb_rectangle_t rect = { 0, 0, xcb_screen->width_in_pixels, font_height };
233 xcb_poly_fill_rectangle(xcb_connection, statusline_pm, statusline_clear, 1, &rect);
234 draw_text(statusline_pm, statusline_ctx, 0, 0, text, glyph_count);
240 * Hides all bars (unmaps them)
244 if (!config.hide_on_modifier) {
249 SLIST_FOREACH(walk, outputs, slist) {
253 xcb_unmap_window(xcb_connection, walk->bar);
259 * Unhides all bars (maps them)
263 if (!config.hide_on_modifier) {
268 xcb_void_cookie_t cookie;
274 SLIST_FOREACH(walk, outputs, slist) {
275 if (walk->bar == XCB_NONE) {
278 mask = XCB_CONFIG_WINDOW_X |
279 XCB_CONFIG_WINDOW_Y |
280 XCB_CONFIG_WINDOW_WIDTH |
281 XCB_CONFIG_WINDOW_HEIGHT |
282 XCB_CONFIG_WINDOW_STACK_MODE;
283 values[0] = walk->rect.x;
284 if (config.position == POS_TOP)
285 values[1] = walk->rect.y;
286 else values[1] = walk->rect.y + walk->rect.h - font_height - 6;
287 values[2] = walk->rect.w;
288 values[3] = font_height + 6;
289 values[4] = XCB_STACK_MODE_ABOVE;
290 DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
291 cookie = xcb_configure_window_checked(xcb_connection,
296 if (xcb_request_failed(cookie, "Could not reconfigure window")) {
299 xcb_map_window(xcb_connection, walk->bar);
304 * Parse the colors into a format that we can use
307 void init_colors(const struct xcb_color_strings_t *new_colors) {
308 #define PARSE_COLOR(name, def) \
310 colors.name = get_colorpixel(new_colors->name ? new_colors->name : def); \
312 PARSE_COLOR(bar_fg, "FFFFFF");
313 PARSE_COLOR(bar_bg, "000000");
314 PARSE_COLOR(active_ws_fg, "FFFFFF");
315 PARSE_COLOR(active_ws_bg, "480000");
316 PARSE_COLOR(inactive_ws_fg, "FFFFFF");
317 PARSE_COLOR(inactive_ws_bg, "240000");
318 PARSE_COLOR(urgent_ws_fg, "FFFFFF");
319 PARSE_COLOR(urgent_ws_bg, "002400");
320 PARSE_COLOR(focus_ws_fg, "FFFFFF");
321 PARSE_COLOR(focus_ws_bg, "480000");
326 * Handle a button-press-event (i.e. a mouse click on one of our bars).
327 * We determine, whether the click occured on a ws-button or if the scroll-
328 * wheel was used and change the workspace appropriately
331 void handle_button(xcb_button_press_event_t *event) {
334 /* Determine, which bar was clicked */
336 xcb_window_t bar = event->event;
337 SLIST_FOREACH(walk, outputs, slist) {
338 if (walk->bar == bar) {
344 DLOG("Unknown Bar klicked!\n");
348 /* TODO: Move this to extern get_ws_for_output() */
349 TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
350 if (cur_ws->visible) {
355 if (cur_ws == NULL) {
356 DLOG("No Workspace active?\n");
360 int32_t x = event->event_x;
362 DLOG("Got Button %d\n", event->detail);
364 switch (event->detail) {
366 /* Left Mousbutton. We determine, which button was clicked
367 * and set cur_ws accordingly */
368 TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
370 if (x < cur_ws->name_width + 10) {
373 x -= cur_ws->name_width + 10;
375 if (cur_ws == NULL) {
380 /* Mouse wheel down. We select the next ws */
381 if (cur_ws == TAILQ_FIRST(walk->workspaces)) {
382 cur_ws = TAILQ_LAST(walk->workspaces, ws_head);
384 cur_ws = TAILQ_PREV(cur_ws, ws_head, tailq);
388 /* Mouse wheel up. We select the previos ws */
389 if (cur_ws == TAILQ_LAST(walk->workspaces, ws_head)) {
390 cur_ws = TAILQ_FIRST(walk->workspaces);
392 cur_ws = TAILQ_NEXT(cur_ws, tailq);
397 const size_t len = strlen(cur_ws->name) + strlen("workspace \"\"") + 1;
399 snprintf(buffer, len, "workspace \"%s\"", cur_ws->name);
400 i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
404 * Configures the x coordinate of all trayclients. To be called after adding a
405 * new tray client or removing an old one.
408 static void configure_trayclients() {
409 trayclient *trayclient;
411 SLIST_FOREACH(output, outputs, slist) {
416 TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
419 DLOG("Configuring tray window %08x to x=%d\n",
420 trayclient->win, output->rect.w - (clients * (font_height + 2)));
421 uint32_t x = output->rect.w - (clients * (font_height + 2));
422 xcb_configure_window(xcb_connection,
431 * Handles ClientMessages (messages sent from another client directly to us).
433 * At the moment, only the tray window will receive client messages. All
434 * supported client messages currently are _NET_SYSTEM_TRAY_OPCODE.
437 static void handle_client_message(xcb_client_message_event_t* event) {
438 if (event->type == atoms[_NET_SYSTEM_TRAY_OPCODE] &&
439 event->format == 32) {
440 DLOG("_NET_SYSTEM_TRAY_OPCODE received\n");
441 /* event->data.data32[0] is the timestamp */
442 uint32_t op = event->data.data32[1];
445 if (op == SYSTEM_TRAY_REQUEST_DOCK) {
446 xcb_window_t client = event->data.data32[2];
448 /* Listen for PropertyNotify events to get the most recent value of
449 * the XEMBED_MAPPED atom, also listen for UnmapNotify events */
450 mask = XCB_CW_EVENT_MASK;
451 values[0] = XCB_EVENT_MASK_PROPERTY_CHANGE |
452 XCB_EVENT_MASK_STRUCTURE_NOTIFY;
453 xcb_change_window_attributes(xcb_connection,
458 /* Request the _XEMBED_INFO property. The XEMBED specification
459 * (which is referred by the tray specification) says this *has* to
460 * be set, but VLC does not set it… */
463 xcb_get_property_cookie_t xembedc;
464 xembedc = xcb_get_property_unchecked(xcb_connection,
468 XCB_GET_PROPERTY_TYPE_ANY,
472 xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
475 if (xembedr != NULL && xembedr->length != 0) {
476 DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
477 uint32_t *xembed = xcb_get_property_value(xembedr);
478 DLOG("xembed version = %d\n", xembed[0]);
479 DLOG("xembed flags = %d\n", xembed[1]);
480 map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
481 xe_version = xembed[0];
486 ELOG("Window %08x violates the XEMBED protocol, _XEMBED_INFO not set\n", client);
489 DLOG("X window %08x requested docking\n", client);
490 i3_output *walk, *output = NULL;
491 SLIST_FOREACH(walk, outputs, slist) {
494 if (config.tray_output &&
495 strcasecmp(walk->name, config.tray_output) != 0)
497 DLOG("using output %s\n", walk->name);
500 if (output == NULL) {
501 ELOG("No output found\n");
504 xcb_reparent_window(xcb_connection,
507 output->rect.w - font_height - 2,
509 /* We reconfigure the window to use a reasonable size. The systray
510 * specification explicitly says:
511 * Tray icons may be assigned any size by the system tray, and
512 * should do their best to cope with any size effectively
514 mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
515 values[0] = font_height;
516 values[1] = font_height;
517 xcb_configure_window(xcb_connection,
522 /* send the XEMBED_EMBEDDED_NOTIFY message */
523 void *event = scalloc(32);
524 xcb_client_message_event_t *ev = event;
525 ev->response_type = XCB_CLIENT_MESSAGE;
527 ev->type = atoms[_XEMBED];
529 ev->data.data32[0] = XCB_CURRENT_TIME;
530 ev->data.data32[1] = atoms[XEMBED_EMBEDDED_NOTIFY];
531 ev->data.data32[2] = output->bar;
532 ev->data.data32[3] = xe_version;
533 xcb_send_event(xcb_connection,
536 XCB_EVENT_MASK_NO_EVENT,
541 DLOG("Mapping dock client\n");
542 xcb_map_window(xcb_connection, client);
544 DLOG("Not mapping dock client yet\n");
546 trayclient *tc = smalloc(sizeof(trayclient));
549 tc->xe_version = xe_version;
550 TAILQ_INSERT_TAIL(output->trayclients, tc, tailq);
552 /* Trigger an update to copy the statusline text to the appropriate
554 configure_trayclients();
561 * Handles UnmapNotify events. These events happen when a tray window unmaps
562 * itself. We then update our data structure
565 static void handle_unmap_notify(xcb_unmap_notify_event_t* event) {
566 DLOG("UnmapNotify for window = %08x, event = %08x\n", event->window, event->event);
569 SLIST_FOREACH(walk, outputs, slist) {
572 DLOG("checking output %s\n", walk->name);
573 trayclient *trayclient;
574 TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
575 if (trayclient->win != event->window)
578 DLOG("Removing tray client with window ID %08x\n", event->window);
579 TAILQ_REMOVE(walk->trayclients, trayclient, tailq);
581 /* Trigger an update, we now have more space for the statusline */
582 configure_trayclients();
590 * Handle PropertyNotify messages. Currently only the _XEMBED_INFO property is
591 * handled, which tells us whether a dock client should be mapped or unmapped.
594 static void handle_property_notify(xcb_property_notify_event_t *event) {
595 DLOG("PropertyNotify\n");
596 if (event->atom == atoms[_XEMBED_INFO] &&
597 event->state == XCB_PROPERTY_NEW_VALUE) {
598 DLOG("xembed_info updated\n");
599 trayclient *trayclient = NULL, *walk;
601 SLIST_FOREACH(o_walk, outputs, slist) {
605 TAILQ_FOREACH(walk, o_walk->trayclients, tailq) {
606 if (walk->win != event->window)
616 ELOG("PropertyNotify received for unknown window %08x\n",
620 xcb_get_property_cookie_t xembedc;
621 xembedc = xcb_get_property_unchecked(xcb_connection,
625 XCB_GET_PROPERTY_TYPE_ANY,
629 xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
632 if (xembedr == NULL || xembedr->length == 0)
635 DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
636 uint32_t *xembed = xcb_get_property_value(xembedr);
637 DLOG("xembed version = %d\n", xembed[0]);
638 DLOG("xembed flags = %d\n", xembed[1]);
639 bool map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
640 DLOG("map-state now %d\n", map_it);
641 if (trayclient->mapped && !map_it) {
642 /* need to unmap the window */
643 xcb_unmap_window(xcb_connection, trayclient->win);
644 trayclient->mapped = map_it;
646 } else if (!trayclient->mapped && map_it) {
647 /* need to map the window */
648 xcb_map_window(xcb_connection, trayclient->win);
649 trayclient->mapped = map_it;
657 * Handle ConfigureRequests by denying them and sending the client a
658 * ConfigureNotify with its actual size.
661 static void handle_configure_request(xcb_configure_request_event_t *event) {
662 DLOG("ConfigureRequest for window = %08x\n", event->window);
664 trayclient *trayclient;
666 SLIST_FOREACH(output, outputs, slist) {
671 TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
674 if (trayclient->win != event->window)
677 xcb_rectangle_t rect;
678 rect.x = output->rect.w - (clients * (font_height + 2));
680 rect.width = font_height;
681 rect.height = font_height;
683 DLOG("This is a tray window. x = %d\n", rect.x);
684 fake_configure_notify(xcb_connection, rect, event->window, 0);
689 DLOG("WARNING: Could not find corresponding tray window.\n");
693 * This function is called immediately before the main loop locks. We flush xcb
694 * then (and only then)
697 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revents) {
698 xcb_flush(xcb_connection);
702 * This function is called immediately after the main loop locks, so when one
703 * of the watchers registered an event.
704 * We check whether an X-Event arrived and handle it.
707 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
708 xcb_generic_event_t *event;
710 if (xcb_connection_has_error(xcb_connection)) {
711 ELOG("X11 connection was closed unexpectedly - maybe your X server terminated / crashed?\n");
715 while ((event = xcb_poll_for_event(xcb_connection)) == NULL) {
719 switch (event->response_type & ~0x80) {
721 /* Expose-events happen, when the window needs to be redrawn */
724 case XCB_BUTTON_PRESS:
725 /* Button-press-events are mouse-buttons clicked on one of our bars */
726 handle_button((xcb_button_press_event_t*) event);
728 case XCB_CLIENT_MESSAGE:
729 /* Client messages are used for client-to-client communication, for
730 * example system tray widgets talk to us directly via client messages. */
731 handle_client_message((xcb_client_message_event_t*) event);
733 case XCB_UNMAP_NOTIFY:
734 /* UnmapNotifies are received when a tray window unmaps itself */
735 handle_unmap_notify((xcb_unmap_notify_event_t*) event);
737 case XCB_PROPERTY_NOTIFY:
739 handle_property_notify((xcb_property_notify_event_t*) event);
741 case XCB_CONFIGURE_REQUEST:
742 /* ConfigureRequest, sent by a tray child */
743 handle_configure_request((xcb_configure_request_event_t*) event);
750 * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
754 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
758 * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
761 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
765 DLOG("Got XKB-Event!\n");
767 while (XPending(xkb_dpy)) {
768 XNextEvent(xkb_dpy, (XEvent*)&ev);
770 if (ev.type != xkb_event_base) {
771 ELOG("No Xkb-Event!\n");
775 if (ev.any.xkb_type != XkbStateNotify) {
776 ELOG("No State Notify!\n");
780 unsigned int mods = ev.state.mods;
781 modstate = mods & Mod4Mask;
784 if (modstate != mod_pressed) {
786 DLOG("Mod4 got released!\n");
789 DLOG("Mod4 got pressed!\n");
792 mod_pressed = modstate;
797 * Early initialization of the connection to X11: Everything which does not
798 * depend on 'config'.
801 char *init_xcb_early() {
802 /* FIXME: xcb_connect leaks Memory */
803 xcb_connection = xcb_connect(NULL, &screen);
804 if (xcb_connection_has_error(xcb_connection)) {
805 ELOG("Cannot open display\n");
808 DLOG("Connected to xcb\n");
810 /* We have to request the atoms we need */
811 #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
812 #include "xcb_atoms.def"
814 xcb_screen = xcb_setup_roots_iterator(xcb_get_setup(xcb_connection)).data;
815 xcb_root = xcb_screen->root;
817 /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
818 * this way, we can choose to crop it */
819 uint32_t mask = XCB_GC_FOREGROUND;
820 uint32_t vals[] = { colors.bar_bg, colors.bar_bg };
822 statusline_clear = xcb_generate_id(xcb_connection);
823 xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
829 mask |= XCB_GC_BACKGROUND;
830 vals[0] = colors.bar_fg;
831 statusline_ctx = xcb_generate_id(xcb_connection);
832 xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
838 statusline_pm = xcb_generate_id(xcb_connection);
839 xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
840 xcb_screen->root_depth,
843 xcb_screen->width_in_pixels,
844 xcb_screen->height_in_pixels);
847 /* The various Watchers to communicate with xcb */
848 xcb_io = smalloc(sizeof(ev_io));
849 xcb_prep = smalloc(sizeof(ev_prepare));
850 xcb_chk = smalloc(sizeof(ev_check));
852 ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
853 ev_prepare_init(xcb_prep, &xcb_prep_cb);
854 ev_check_init(xcb_chk, &xcb_chk_cb);
856 ev_io_start(main_loop, xcb_io);
857 ev_prepare_start(main_loop, xcb_prep);
858 ev_check_start(main_loop, xcb_chk);
860 /* Now we get the atoms and save them in a nice data structure */
863 xcb_get_property_cookie_t path_cookie;
864 path_cookie = xcb_get_property_unchecked(xcb_connection,
867 atoms[I3_SOCKET_PATH],
868 XCB_GET_PROPERTY_TYPE_ANY,
871 /* We check, if i3 set its socket-path */
872 xcb_get_property_reply_t *path_reply = xcb_get_property_reply(xcb_connection,
877 int len = xcb_get_property_value_length(path_reply);
879 path = strndup(xcb_get_property_value(path_reply), len);
884 if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
885 xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
886 xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
894 * Initialization which depends on 'config' being usable. Called after the
895 * configuration has arrived.
898 void init_xcb_late(char *fontname) {
899 if (fontname == NULL) {
900 /* This is a very restrictive default. More sensefull would be something like
901 * "-misc-*-*-*-*--*-*-*-*-*-*-*-*". But since that produces very ugly results
902 * on my machine, let's stick with this until we have a configfile */
903 fontname = "-misc-fixed-medium-r-semicondensed--12-110-75-75-c-60-iso10646-1";
906 /* We load and allocate the font */
907 xcb_font = xcb_generate_id(xcb_connection);
908 xcb_void_cookie_t open_font_cookie;
909 open_font_cookie = xcb_open_font_checked(xcb_connection,
914 /* We need to save info about the font, because we need the font's height and
915 * information about the width of characters */
916 xcb_query_font_cookie_t query_font_cookie;
917 query_font_cookie = xcb_query_font(xcb_connection,
920 xcb_change_gc(xcb_connection,
923 (uint32_t[]){ xcb_font });
925 xcb_flush(xcb_connection);
927 /* To grab modifiers without blocking other applications from receiving key-events
928 * involving that modifier, we sadly have to use xkb which is not yet fully supported
930 if (config.hide_on_modifier) {
931 int xkb_major, xkb_minor, xkb_errbase, xkb_err;
932 xkb_major = XkbMajorVersion;
933 xkb_minor = XkbMinorVersion;
935 xkb_dpy = XkbOpenDisplay(NULL,
942 if (xkb_dpy == NULL) {
947 if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
948 ELOG("Could not set FD_CLOEXEC on xkbdpy: %s\n", strerror(errno));
953 if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
954 ELOG("XKB not supported by X-server!\n");
958 if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
959 ELOG("Could not grab Key!\n");
963 xkb_io = smalloc(sizeof(ev_io));
964 ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
965 ev_io_start(main_loop, xkb_io);
969 /* Now we save the font-infos */
970 font_info = xcb_query_font_reply(xcb_connection,
974 if (xcb_request_failed(open_font_cookie, "Could not open font")) {
978 font_height = font_info->font_ascent + font_info->font_descent;
980 if (xcb_query_font_char_infos_length(font_info) == 0) {
983 font_table = xcb_query_font_char_infos(font_info);
986 DLOG("Calculated Font-height: %d\n", font_height);
990 * Initializes tray support by requesting the appropriate _NET_SYSTEM_TRAY atom
991 * for the X11 display we are running on, then acquiring the selection for this
992 * atom. Afterwards, tray clients will send ClientMessages to our window.
996 DLOG("Initializing system tray functionality\n");
997 /* request the tray manager atom for the X11 display we are running on */
998 char atomname[strlen("_NET_SYSTEM_TRAY_S") + 11];
999 snprintf(atomname, strlen("_NET_SYSTEM_TRAY_S") + 11, "_NET_SYSTEM_TRAY_S%d", screen);
1000 xcb_intern_atom_cookie_t tray_cookie;
1001 xcb_intern_atom_reply_t *tray_reply;
1002 tray_cookie = xcb_intern_atom(xcb_connection, 0, strlen(atomname), atomname);
1004 /* tray support: we need a window to own the selection */
1005 xcb_window_t selwin = xcb_generate_id(xcb_connection);
1006 uint32_t selmask = XCB_CW_OVERRIDE_REDIRECT;
1007 uint32_t selval[] = { 1 };
1008 xcb_create_window(xcb_connection,
1009 xcb_screen->root_depth,
1015 XCB_WINDOW_CLASS_INPUT_OUTPUT,
1016 xcb_screen->root_visual,
1020 uint32_t orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
1022 xcb_change_property(xcb_connection,
1023 XCB_PROP_MODE_REPLACE,
1025 atoms[_NET_SYSTEM_TRAY_ORIENTATION],
1031 if (!(tray_reply = xcb_intern_atom_reply(xcb_connection, tray_cookie, NULL))) {
1032 ELOG("Could not get atom %s\n", atomname);
1036 xcb_set_selection_owner(xcb_connection,
1041 /* Verify that we have the selection */
1042 xcb_get_selection_owner_cookie_t selcookie;
1043 xcb_get_selection_owner_reply_t *selreply;
1045 selcookie = xcb_get_selection_owner(xcb_connection, tray_reply->atom);
1046 if (!(selreply = xcb_get_selection_owner_reply(xcb_connection, selcookie, NULL))) {
1047 ELOG("Could not get selection owner for %s\n", atomname);
1051 if (selreply->owner != selwin) {
1052 ELOG("Could not set the %s selection. " \
1053 "Maybe another tray is already running?\n", atomname);
1054 /* NOTE that this error is not fatal. We just can’t provide tray
1060 /* Inform clients waiting for a new _NET_SYSTEM_TRAY that we are here */
1061 void *event = scalloc(32);
1062 xcb_client_message_event_t *ev = event;
1063 ev->response_type = XCB_CLIENT_MESSAGE;
1064 ev->window = xcb_root;
1065 ev->type = atoms[MANAGER];
1067 ev->data.data32[0] = XCB_CURRENT_TIME;
1068 ev->data.data32[1] = tray_reply->atom;
1069 ev->data.data32[2] = selwin;
1070 xcb_send_event(xcb_connection,
1073 XCB_EVENT_MASK_STRUCTURE_NOTIFY,
1080 * Cleanup the xcb-stuff.
1081 * Called once, before the program terminates.
1086 trayclient *trayclient;
1088 SLIST_FOREACH(o_walk, outputs, slist) {
1089 TAILQ_FOREACH(trayclient, o_walk->trayclients, tailq) {
1090 /* Unmap, then reparent (to root) the tray client windows */
1091 xcb_unmap_window(xcb_connection, trayclient->win);
1092 xcb_reparent_window(xcb_connection,
1098 destroy_window(o_walk);
1099 FREE(o_walk->trayclients);
1100 FREE(o_walk->workspaces);
1103 FREE_SLIST(outputs, i3_output);
1106 xcb_flush(xcb_connection);
1107 xcb_disconnect(xcb_connection);
1109 ev_check_stop(main_loop, xcb_chk);
1110 ev_prepare_stop(main_loop, xcb_prep);
1111 ev_io_stop(main_loop, xcb_io);
1120 * Get the earlier requested atoms and save them in the prepared data structure
1124 xcb_intern_atom_reply_t *reply;
1125 #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
1126 if (reply == NULL) { \
1127 ELOG("Could not get atom %s\n", #name); \
1128 exit(EXIT_FAILURE); \
1130 atoms[name] = reply->atom; \
1133 #include "xcb_atoms.def"
1134 DLOG("Got Atoms\n");
1138 * Destroy the bar of the specified output
1141 void destroy_window(i3_output *output) {
1142 if (output == NULL) {
1145 if (output->bar == XCB_NONE) {
1148 xcb_destroy_window(xcb_connection, output->bar);
1149 output->bar = XCB_NONE;
1153 * Reallocate the statusline-buffer
1156 void realloc_sl_buffer() {
1157 DLOG("Re-allocating statusline-buffer, statusline_width = %d, xcb_screen->width_in_pixels = %d\n",
1158 statusline_width, xcb_screen->width_in_pixels);
1159 xcb_free_pixmap(xcb_connection, statusline_pm);
1160 statusline_pm = xcb_generate_id(xcb_connection);
1161 xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1162 xcb_screen->root_depth,
1165 MAX(xcb_screen->width_in_pixels, statusline_width),
1166 xcb_screen->height_in_pixels);
1168 uint32_t mask = XCB_GC_FOREGROUND;
1169 uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
1170 xcb_free_gc(xcb_connection, statusline_clear);
1171 statusline_clear = xcb_generate_id(xcb_connection);
1172 xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1178 mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
1179 vals[0] = colors.bar_fg;
1180 statusline_ctx = xcb_generate_id(xcb_connection);
1181 xcb_free_gc(xcb_connection, statusline_ctx);
1182 xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1188 if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
1189 xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
1190 xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
1197 * Reconfigure all bars and create new bars for recently activated outputs
1200 void reconfig_windows() {
1203 static bool tray_configured = false;
1206 SLIST_FOREACH(walk, outputs, slist) {
1207 if (!walk->active) {
1208 /* If an output is not active, we destroy its bar */
1209 /* FIXME: Maybe we rather want to unmap? */
1210 DLOG("Destroying window for output %s\n", walk->name);
1211 destroy_window(walk);
1214 if (walk->bar == XCB_NONE) {
1215 DLOG("Creating Window for output %s\n", walk->name);
1217 walk->bar = xcb_generate_id(xcb_connection);
1218 walk->buffer = xcb_generate_id(xcb_connection);
1219 mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
1220 /* Black background */
1221 values[0] = colors.bar_bg;
1222 /* If hide_on_modifier is set, i3 is not supposed to manage our bar-windows */
1223 values[1] = config.hide_on_modifier;
1224 /* We enable the following EventMask fields:
1225 * EXPOSURE, to get expose events (we have to re-draw then)
1226 * SUBSTRUCTURE_REDIRECT, to get ConfigureRequests when the tray
1227 * child windows use ConfigureWindow
1228 * BUTTON_PRESS, to handle clicks on the workspace buttons
1230 values[2] = XCB_EVENT_MASK_EXPOSURE |
1231 XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;
1232 if (!config.disable_ws) {
1233 values[2] |= XCB_EVENT_MASK_BUTTON_PRESS;
1235 xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
1236 xcb_screen->root_depth,
1239 walk->rect.x, walk->rect.y + walk->rect.h - font_height - 6,
1240 walk->rect.w, font_height + 6,
1242 XCB_WINDOW_CLASS_INPUT_OUTPUT,
1243 xcb_screen->root_visual,
1247 /* The double-buffer we use to render stuff off-screen */
1248 xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1249 xcb_screen->root_depth,
1255 /* Set the WM_CLASS and WM_NAME (we don't need UTF-8) atoms */
1256 xcb_void_cookie_t class_cookie;
1257 class_cookie = xcb_change_property(xcb_connection,
1258 XCB_PROP_MODE_REPLACE,
1263 (strlen("i3bar") + 1) * 2,
1267 if (asprintf(&name, "i3bar for output %s", walk->name) == -1)
1268 err(EXIT_FAILURE, "asprintf()");
1269 xcb_void_cookie_t name_cookie;
1270 name_cookie = xcb_change_property(xcb_connection,
1271 XCB_PROP_MODE_REPLACE,
1280 /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
1282 xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
1283 XCB_PROP_MODE_REPLACE,
1285 atoms[_NET_WM_WINDOW_TYPE],
1289 (unsigned char*) &atoms[_NET_WM_WINDOW_TYPE_DOCK]);
1291 /* We need to tell i3, where to reserve space for i3bar */
1292 /* left, right, top, bottom, left_start_y, left_end_y,
1293 * right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x,
1295 /* A local struct to save the strut_partial property */
1301 uint32_t left_start_y;
1302 uint32_t left_end_y;
1303 uint32_t right_start_y;
1304 uint32_t right_end_y;
1305 uint32_t top_start_x;
1307 uint32_t bottom_start_x;
1308 uint32_t bottom_end_x;
1309 } __attribute__((__packed__)) strut_partial = {0,};
1310 switch (config.position) {
1314 strut_partial.top = font_height + 6;
1315 strut_partial.top_start_x = walk->rect.x;
1316 strut_partial.top_end_x = walk->rect.x + walk->rect.w;
1319 strut_partial.bottom = font_height + 6;
1320 strut_partial.bottom_start_x = walk->rect.x;
1321 strut_partial.bottom_end_x = walk->rect.x + walk->rect.w;
1324 xcb_void_cookie_t strut_cookie = xcb_change_property(xcb_connection,
1325 XCB_PROP_MODE_REPLACE,
1327 atoms[_NET_WM_STRUT_PARTIAL],
1333 /* We also want a graphics-context for the bars (it defines the properties
1334 * with which we draw to them) */
1335 walk->bargc = xcb_generate_id(xcb_connection);
1337 values[0] = xcb_font;
1338 xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
1344 /* We finally map the bar (display it on screen), unless the modifier-switch is on */
1345 xcb_void_cookie_t map_cookie;
1346 if (!config.hide_on_modifier) {
1347 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
1350 if (xcb_request_failed(win_cookie, "Could not create window") ||
1351 xcb_request_failed(pm_cookie, "Could not create pixmap") ||
1352 xcb_request_failed(dock_cookie, "Could not set dock mode") ||
1353 xcb_request_failed(class_cookie, "Could not set WM_CLASS") ||
1354 xcb_request_failed(name_cookie, "Could not set WM_NAME") ||
1355 xcb_request_failed(strut_cookie, "Could not set strut") ||
1356 xcb_request_failed(gc_cookie, "Could not create graphical context") ||
1357 (!config.hide_on_modifier && xcb_request_failed(map_cookie, "Could not map window"))) {
1361 if (!tray_configured &&
1362 strcasecmp("none", config.tray_output) != 0) {
1364 tray_configured = true;
1367 /* We already have a bar, so we just reconfigure it */
1368 mask = XCB_CONFIG_WINDOW_X |
1369 XCB_CONFIG_WINDOW_Y |
1370 XCB_CONFIG_WINDOW_WIDTH |
1371 XCB_CONFIG_WINDOW_HEIGHT |
1372 XCB_CONFIG_WINDOW_STACK_MODE;
1373 values[0] = walk->rect.x;
1374 values[1] = walk->rect.y + walk->rect.h - font_height - 6;
1375 values[2] = walk->rect.w;
1376 values[3] = font_height + 6;
1377 values[4] = XCB_STACK_MODE_ABOVE;
1379 DLOG("Destroying buffer for output %s", walk->name);
1380 xcb_free_pixmap(xcb_connection, walk->buffer);
1382 DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
1383 xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
1388 DLOG("Recreating buffer for output %s", walk->name);
1389 xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1390 xcb_screen->root_depth,
1396 if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
1399 if (xcb_request_failed(pm_cookie, "Could not create pixmap")) {
1407 * Render the bars, with buttons and statusline
1411 DLOG("Drawing Bars...\n");
1414 refresh_statusline();
1416 i3_output *outputs_walk;
1417 SLIST_FOREACH(outputs_walk, outputs, slist) {
1418 if (!outputs_walk->active) {
1419 DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
1422 if (outputs_walk->bar == XCB_NONE) {
1423 /* Oh shit, an active output without an own bar. Create it now! */
1426 /* First things first: clear the backbuffer */
1427 uint32_t color = colors.bar_bg;
1428 xcb_change_gc(xcb_connection,
1429 outputs_walk->bargc,
1432 xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font_height + 6 };
1433 xcb_poly_fill_rectangle(xcb_connection,
1434 outputs_walk->buffer,
1435 outputs_walk->bargc,
1439 if (statusline != NULL) {
1440 DLOG("Printing statusline!\n");
1442 /* Luckily we already prepared a seperate pixmap containing the rendered
1443 * statusline, we just have to copy the relevant parts to the relevant
1445 trayclient *trayclient;
1447 TAILQ_FOREACH(trayclient, outputs_walk->trayclients, tailq) {
1448 if (!trayclient->mapped)
1450 /* We assume the tray icons are quadratic (we use the font
1451 * *height* as *width* of the icons) because we configured them
1453 traypx += font_height + 2;
1455 /* Add 2px of padding if there are any tray icons */
1458 xcb_copy_area(xcb_connection,
1460 outputs_walk->buffer,
1461 outputs_walk->bargc,
1462 MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
1463 MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - traypx - 4)), 3,
1464 MIN(outputs_walk->rect.w - traypx - 4, statusline_width), font_height);
1467 if (config.disable_ws) {
1472 TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
1473 DLOG("Drawing Button for WS %s at x = %d\n", ws_walk->name, i);
1474 uint32_t fg_color = colors.inactive_ws_fg;
1475 uint32_t bg_color = colors.inactive_ws_bg;
1476 if (ws_walk->visible) {
1477 if (!ws_walk->focused) {
1478 fg_color = colors.active_ws_fg;
1479 bg_color = colors.active_ws_bg;
1481 fg_color = colors.focus_ws_fg;
1482 bg_color = colors.focus_ws_bg;
1485 if (ws_walk->urgent) {
1486 DLOG("WS %s is urgent!\n", ws_walk->name);
1487 fg_color = colors.urgent_ws_fg;
1488 bg_color = colors.urgent_ws_bg;
1489 /* The urgent-hint should get noticed, so we unhide the bars shortly */
1492 uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
1493 uint32_t vals[] = { bg_color, bg_color };
1494 xcb_change_gc(xcb_connection,
1495 outputs_walk->bargc,
1498 xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font_height + 4 };
1499 xcb_poly_fill_rectangle(xcb_connection,
1500 outputs_walk->buffer,
1501 outputs_walk->bargc,
1504 xcb_change_gc(xcb_connection,
1505 outputs_walk->bargc,
1508 xcb_image_text_16(xcb_connection,
1509 ws_walk->name_glyphs,
1510 outputs_walk->buffer,
1511 outputs_walk->bargc,
1512 i + 5, font_info->font_ascent + 2,
1513 ws_walk->ucs2_name);
1514 i += 10 + ws_walk->name_width;
1524 * Redraw the bars, i.e. simply copy the buffer to the barwindow
1527 void redraw_bars() {
1528 i3_output *outputs_walk;
1529 SLIST_FOREACH(outputs_walk, outputs, slist) {
1530 if (!outputs_walk->active) {
1533 xcb_copy_area(xcb_connection,
1534 outputs_walk->buffer,
1536 outputs_walk->bargc,
1539 outputs_walk->rect.w,
1540 outputs_walk->rect.h);
1541 xcb_flush(xcb_connection);