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>
28 #include <X11/XKBlib.h>
29 #include <X11/extensions/XKB.h>
34 #if defined(__APPLE__)
38 * Returns a pointer to a new string which is a duplicate of the
39 * string, but only copies at most n characters.
42 char *strndup(const char *str, size_t n) {
46 for (len = 0; len < n && str[len]; len++)
49 if ((copy = malloc(len + 1)) == NULL)
51 memcpy(copy, str, len);
58 /* We save the Atoms in an easy to access array, indexed by an enum */
60 #define ATOM_DO(name) name,
61 #include "xcb_atoms.def"
65 xcb_intern_atom_cookie_t atom_cookies[NUM_ATOMS];
66 xcb_atom_t atoms[NUM_ATOMS];
68 /* Variables, that are the same for all functions at all times */
69 xcb_connection_t *xcb_connection;
71 xcb_screen_t *xcb_screen;
72 xcb_window_t xcb_root;
75 /* We need to cache some data to speed up text-width-prediction */
76 xcb_query_font_reply_t *font_info;
78 xcb_charinfo_t *font_table;
80 /* These are only relevant for XKB, which we only need for grabbing modifiers */
85 /* Because the statusline is the same on all outputs, we have
86 * global buffer to render it on */
87 xcb_gcontext_t statusline_ctx;
88 xcb_gcontext_t statusline_clear;
89 xcb_pixmap_t statusline_pm;
90 uint32_t statusline_width;
92 /* Event-Watchers, to interact with the user */
98 /* The parsed colors */
102 uint32_t active_ws_fg;
103 uint32_t active_ws_bg;
104 uint32_t inactive_ws_fg;
105 uint32_t inactive_ws_bg;
106 uint32_t urgent_ws_bg;
107 uint32_t urgent_ws_fg;
108 uint32_t focus_ws_bg;
109 uint32_t focus_ws_fg;
111 struct xcb_colors_t colors;
113 /* We define xcb_request_failed as a macro to include the relevant line-number */
114 #define xcb_request_failed(cookie, err_msg) _xcb_request_failed(cookie, err_msg, __LINE__)
115 int _xcb_request_failed(xcb_void_cookie_t cookie, char *err_msg, int line) {
116 xcb_generic_error_t *err;
117 if ((err = xcb_request_check(xcb_connection, cookie)) != NULL) {
118 fprintf(stderr, "[%s:%d] ERROR: %s. X Error Code: %d\n", __FILE__, line, err_msg, err->error_code);
119 return err->error_code;
125 * Predicts the length of text based on cached data.
126 * The string has to be encoded in ucs2 and glyph_len has to be the length
127 * of the string (in glyphs).
130 uint32_t predict_text_extents(xcb_char2b_t *text, uint32_t length) {
131 /* If we don't have per-character data, return the maximum width */
132 if (font_table == NULL) {
133 return (font_info->max_bounds.character_width * length);
139 for (i = 0; i < length; i++) {
140 xcb_charinfo_t *info;
141 int row = text[i].byte1;
142 int col = text[i].byte2;
144 if (row < font_info->min_byte1 || row > font_info->max_byte1 ||
145 col < font_info->min_char_or_byte2 || col > font_info->max_char_or_byte2) {
149 /* Don't you ask me, how this one works… */
150 info = &font_table[((row - font_info->min_byte1) *
151 (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
152 (col - font_info->min_char_or_byte2)];
154 if (info->character_width != 0 ||
155 (info->right_side_bearing |
156 info->left_side_bearing |
158 info->descent) != 0) {
159 width += info->character_width;
167 * Draws text given in UCS-2-encoding to a given drawable and position
170 void draw_text(xcb_drawable_t drawable, xcb_gcontext_t ctx, int16_t x, int16_t y,
171 xcb_char2b_t *text, uint32_t glyph_count) {
174 int16_t font_ascent = font_info->font_ascent;
176 while (glyph_count > 0) {
177 uint8_t chunk_size = MIN(255, glyph_count);
178 uint32_t chunk_width = predict_text_extents(text + offset, chunk_size);
180 xcb_image_text_16(xcb_connection,
184 pos_x, y + font_ascent,
187 offset += chunk_size;
188 pos_x += chunk_width;
189 glyph_count -= chunk_size;
194 * Converts a colorstring to a colorpixel as expected from xcb_change_gc.
195 * s is assumed to be in the format "rrggbb"
198 uint32_t get_colorpixel(const char *s) {
199 char strings[3][3] = { { s[0], s[1], '\0'} ,
200 { s[2], s[3], '\0'} ,
201 { s[4], s[5], '\0'} };
202 uint8_t r = strtol(strings[0], NULL, 16);
203 uint8_t g = strtol(strings[1], NULL, 16);
204 uint8_t b = strtol(strings[2], NULL, 16);
205 return (r << 16 | g << 8 | b);
209 * Redraws the statusline to the buffer
212 void refresh_statusline() {
215 if (statusline == NULL) {
219 xcb_char2b_t *text = (xcb_char2b_t*) convert_utf8_to_ucs2(statusline, &glyph_count);
220 uint32_t old_statusline_width = statusline_width;
221 statusline_width = predict_text_extents(text, glyph_count);
222 /* If the statusline is bigger than our screen we need to make sure that
223 * the pixmap provides enough space, so re-allocate if the width grew */
224 if (statusline_width > xcb_screen->width_in_pixels &&
225 statusline_width > old_statusline_width)
228 xcb_rectangle_t rect = { 0, 0, xcb_screen->width_in_pixels, font_height };
229 xcb_poly_fill_rectangle(xcb_connection, statusline_pm, statusline_clear, 1, &rect);
230 draw_text(statusline_pm, statusline_ctx, 0, 0, text, glyph_count);
236 * Hides all bars (unmaps them)
240 if (!config.hide_on_modifier) {
245 SLIST_FOREACH(walk, outputs, slist) {
249 xcb_unmap_window(xcb_connection, walk->bar);
255 * Unhides all bars (maps them)
259 if (!config.hide_on_modifier) {
264 xcb_void_cookie_t cookie;
270 SLIST_FOREACH(walk, outputs, slist) {
271 if (walk->bar == XCB_NONE) {
274 mask = XCB_CONFIG_WINDOW_X |
275 XCB_CONFIG_WINDOW_Y |
276 XCB_CONFIG_WINDOW_WIDTH |
277 XCB_CONFIG_WINDOW_HEIGHT |
278 XCB_CONFIG_WINDOW_STACK_MODE;
279 values[0] = walk->rect.x;
280 values[1] = walk->rect.y + walk->rect.h - font_height - 6;
281 values[2] = walk->rect.w;
282 values[3] = font_height + 6;
283 values[4] = XCB_STACK_MODE_ABOVE;
284 DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
285 cookie = xcb_configure_window_checked(xcb_connection,
290 if (xcb_request_failed(cookie, "Could not reconfigure window")) {
293 xcb_map_window(xcb_connection, walk->bar);
298 * Parse the colors into a format that we can use
301 void init_colors(const struct xcb_color_strings_t *new_colors) {
302 #define PARSE_COLOR(name, def) \
304 colors.name = get_colorpixel(new_colors->name ? new_colors->name : def); \
306 PARSE_COLOR(bar_fg, "FFFFFF");
307 PARSE_COLOR(bar_bg, "000000");
308 PARSE_COLOR(active_ws_fg, "FFFFFF");
309 PARSE_COLOR(active_ws_bg, "480000");
310 PARSE_COLOR(inactive_ws_fg, "FFFFFF");
311 PARSE_COLOR(inactive_ws_bg, "240000");
312 PARSE_COLOR(urgent_ws_fg, "FFFFFF");
313 PARSE_COLOR(urgent_ws_bg, "002400");
314 PARSE_COLOR(focus_ws_fg, "FFFFFF");
315 PARSE_COLOR(focus_ws_bg, "480000");
320 * Handle a button-press-event (i.e. a mouse click on one of our bars).
321 * We determine, whether the click occured on a ws-button or if the scroll-
322 * wheel was used and change the workspace appropriately
325 void handle_button(xcb_button_press_event_t *event) {
328 /* Determine, which bar was clicked */
330 xcb_window_t bar = event->event;
331 SLIST_FOREACH(walk, outputs, slist) {
332 if (walk->bar == bar) {
338 DLOG("Unknown Bar klicked!\n");
342 /* TODO: Move this to extern get_ws_for_output() */
343 TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
344 if (cur_ws->visible) {
349 if (cur_ws == NULL) {
350 DLOG("No Workspace active?\n");
354 int32_t x = event->event_x;
356 DLOG("Got Button %d\n", event->detail);
358 switch (event->detail) {
360 /* Left Mousbutton. We determine, which button was clicked
361 * and set cur_ws accordingly */
362 TAILQ_FOREACH(cur_ws, walk->workspaces, tailq) {
364 if (x < cur_ws->name_width + 10) {
367 x -= cur_ws->name_width + 10;
369 if (cur_ws == NULL) {
374 /* Mouse wheel down. We select the next ws */
375 if (cur_ws == TAILQ_FIRST(walk->workspaces)) {
376 cur_ws = TAILQ_LAST(walk->workspaces, ws_head);
378 cur_ws = TAILQ_PREV(cur_ws, ws_head, tailq);
382 /* Mouse wheel up. We select the previos ws */
383 if (cur_ws == TAILQ_LAST(walk->workspaces, ws_head)) {
384 cur_ws = TAILQ_FIRST(walk->workspaces);
386 cur_ws = TAILQ_NEXT(cur_ws, tailq);
391 const size_t len = strlen(cur_ws->name) + strlen("workspace \"\"") + 1;
393 snprintf(buffer, len, "workspace \"%s\"", cur_ws->name);
394 i3_send_msg(I3_IPC_MESSAGE_TYPE_COMMAND, buffer);
398 * Configures the x coordinate of all trayclients. To be called after adding a
399 * new tray client or removing an old one.
402 static void configure_trayclients() {
403 trayclient *trayclient;
405 SLIST_FOREACH(output, outputs, slist) {
410 TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
413 DLOG("Configuring tray window %08x to x=%d\n",
414 trayclient->win, output->rect.w - (clients * (font_height + 2)));
415 uint32_t x = output->rect.w - (clients * (font_height + 2));
416 xcb_configure_window(xcb_connection,
425 * Handles ClientMessages (messages sent from another client directly to us).
427 * At the moment, only the tray window will receive client messages. All
428 * supported client messages currently are _NET_SYSTEM_TRAY_OPCODE.
431 static void handle_client_message(xcb_client_message_event_t* event) {
432 if (event->type == atoms[_NET_SYSTEM_TRAY_OPCODE] &&
433 event->format == 32) {
434 DLOG("_NET_SYSTEM_TRAY_OPCODE received\n");
435 /* event->data.data32[0] is the timestamp */
436 uint32_t op = event->data.data32[1];
439 if (op == SYSTEM_TRAY_REQUEST_DOCK) {
440 xcb_window_t client = event->data.data32[2];
442 /* Listen for PropertyNotify events to get the most recent value of
443 * the XEMBED_MAPPED atom, also listen for UnmapNotify events */
444 mask = XCB_CW_EVENT_MASK;
445 values[0] = XCB_EVENT_MASK_PROPERTY_CHANGE |
446 XCB_EVENT_MASK_STRUCTURE_NOTIFY;
447 xcb_change_window_attributes(xcb_connection,
452 /* Request the _XEMBED_INFO property. The XEMBED specification
453 * (which is referred by the tray specification) says this *has* to
454 * be set, but VLC does not set it… */
457 xcb_get_property_cookie_t xembedc;
458 xembedc = xcb_get_property_unchecked(xcb_connection,
462 XCB_GET_PROPERTY_TYPE_ANY,
466 xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
469 if (xembedr != NULL && xembedr->length != 0) {
470 DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
471 uint32_t *xembed = xcb_get_property_value(xembedr);
472 DLOG("xembed version = %d\n", xembed[0]);
473 DLOG("xembed flags = %d\n", xembed[1]);
474 map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
475 xe_version = xembed[0];
480 ELOG("Window %08x violates the XEMBED protocol, _XEMBED_INFO not set\n", client);
483 DLOG("X window %08x requested docking\n", client);
484 i3_output *walk, *output = NULL;
485 SLIST_FOREACH(walk, outputs, slist) {
488 DLOG("using output %s\n", walk->name);
491 if (output == NULL) {
492 ELOG("No output found\n");
495 xcb_reparent_window(xcb_connection,
498 output->rect.w - font_height - 2,
500 /* We reconfigure the window to use a reasonable size. The systray
501 * specification explicitly says:
502 * Tray icons may be assigned any size by the system tray, and
503 * should do their best to cope with any size effectively
505 mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
506 values[0] = font_height;
507 values[1] = font_height;
508 xcb_configure_window(xcb_connection,
513 /* send the XEMBED_EMBEDDED_NOTIFY message */
514 void *event = calloc(32, 1);
515 xcb_client_message_event_t *ev = event;
516 ev->response_type = XCB_CLIENT_MESSAGE;
518 ev->type = atoms[_XEMBED];
520 ev->data.data32[0] = XCB_CURRENT_TIME;
521 ev->data.data32[1] = atoms[XEMBED_EMBEDDED_NOTIFY];
522 ev->data.data32[2] = output->bar;
523 ev->data.data32[3] = xe_version;
524 xcb_send_event(xcb_connection,
527 XCB_EVENT_MASK_NO_EVENT,
532 DLOG("Mapping dock client\n");
533 xcb_map_window(xcb_connection, client);
535 DLOG("Not mapping dock client yet\n");
537 trayclient *tc = malloc(sizeof(trayclient));
540 tc->xe_version = xe_version;
541 TAILQ_INSERT_TAIL(output->trayclients, tc, tailq);
543 /* Trigger an update to copy the statusline text to the appropriate
545 configure_trayclients();
552 * Handles UnmapNotify events. These events happen when a tray window unmaps
553 * itself. We then update our data structure
556 static void handle_unmap_notify(xcb_unmap_notify_event_t* event) {
557 DLOG("UnmapNotify for window = %08x, event = %08x\n", event->window, event->event);
560 SLIST_FOREACH(walk, outputs, slist) {
563 DLOG("checking output %s\n", walk->name);
564 trayclient *trayclient;
565 TAILQ_FOREACH(trayclient, walk->trayclients, tailq) {
566 if (trayclient->win != event->window)
569 DLOG("Removing tray client with window ID %08x\n", event->window);
570 TAILQ_REMOVE(walk->trayclients, trayclient, tailq);
572 /* Trigger an update, we now have more space for the statusline */
573 configure_trayclients();
581 * Handle PropertyNotify messages. Currently only the _XEMBED_INFO property is
582 * handled, which tells us whether a dock client should be mapped or unmapped.
585 static void handle_property_notify(xcb_property_notify_event_t *event) {
586 DLOG("PropertyNotify\n");
587 if (event->atom == atoms[_XEMBED_INFO] &&
588 event->state == XCB_PROPERTY_NEW_VALUE) {
589 DLOG("xembed_info updated\n");
590 trayclient *trayclient = NULL, *walk;
592 SLIST_FOREACH(o_walk, outputs, slist) {
596 TAILQ_FOREACH(walk, o_walk->trayclients, tailq) {
597 if (walk->win != event->window)
607 ELOG("PropertyNotify received for unknown window %08x\n",
611 xcb_get_property_cookie_t xembedc;
612 xembedc = xcb_get_property_unchecked(xcb_connection,
616 XCB_GET_PROPERTY_TYPE_ANY,
620 xcb_get_property_reply_t *xembedr = xcb_get_property_reply(xcb_connection,
623 if (xembedr == NULL || xembedr->length == 0)
626 DLOG("xembed format = %d, len = %d\n", xembedr->format, xembedr->length);
627 uint32_t *xembed = xcb_get_property_value(xembedr);
628 DLOG("xembed version = %d\n", xembed[0]);
629 DLOG("xembed flags = %d\n", xembed[1]);
630 bool map_it = ((xembed[1] & XEMBED_MAPPED) == XEMBED_MAPPED);
631 DLOG("map-state now %d\n", map_it);
632 if (trayclient->mapped && !map_it) {
633 /* need to unmap the window */
634 xcb_unmap_window(xcb_connection, trayclient->win);
635 trayclient->mapped = map_it;
637 } else if (!trayclient->mapped && map_it) {
638 /* need to map the window */
639 xcb_map_window(xcb_connection, trayclient->win);
640 trayclient->mapped = map_it;
648 * Handle ConfigureRequests by denying them and sending the client a
649 * ConfigureNotify with its actual size.
652 static void handle_configure_request(xcb_configure_request_event_t *event) {
653 DLOG("ConfigureRequest for window = %08x\n", event->window);
655 trayclient *trayclient;
657 SLIST_FOREACH(output, outputs, slist) {
662 TAILQ_FOREACH_REVERSE(trayclient, output->trayclients, tc_head, tailq) {
665 if (trayclient->win != event->window)
668 xcb_rectangle_t rect;
669 rect.x = output->rect.w - (clients * (font_height + 2));
671 rect.width = font_height;
672 rect.height = font_height;
674 DLOG("This is a tray window. x = %d\n", rect.x);
675 fake_configure_notify(xcb_connection, rect, event->window, 0);
680 DLOG("WARNING: Could not find corresponding tray window.\n");
684 * This function is called immediately before the main loop locks. We flush xcb
685 * then (and only then)
688 void xcb_prep_cb(struct ev_loop *loop, ev_prepare *watcher, int revents) {
689 xcb_flush(xcb_connection);
693 * This function is called immediately after the main loop locks, so when one
694 * of the watchers registered an event.
695 * We check whether an X-Event arrived and handle it.
698 void xcb_chk_cb(struct ev_loop *loop, ev_check *watcher, int revents) {
699 xcb_generic_event_t *event;
701 if (xcb_connection_has_error(xcb_connection)) {
702 ELOG("X11 connection was closed unexpectedly - maybe your X server terminated / crashed?\n");
706 while ((event = xcb_poll_for_event(xcb_connection)) == NULL) {
710 switch (event->response_type & ~0x80) {
712 /* Expose-events happen, when the window needs to be redrawn */
715 case XCB_BUTTON_PRESS:
716 /* Button-press-events are mouse-buttons clicked on one of our bars */
717 handle_button((xcb_button_press_event_t*) event);
719 case XCB_CLIENT_MESSAGE:
720 /* Client messages are used for client-to-client communication, for
721 * example system tray widgets talk to us directly via client messages. */
722 handle_client_message((xcb_client_message_event_t*) event);
724 case XCB_UNMAP_NOTIFY:
725 /* UnmapNotifies are received when a tray window unmaps itself */
726 handle_unmap_notify((xcb_unmap_notify_event_t*) event);
728 case XCB_PROPERTY_NOTIFY:
730 handle_property_notify((xcb_property_notify_event_t*) event);
732 case XCB_CONFIGURE_REQUEST:
733 /* ConfigureRequest, sent by a tray child */
734 handle_configure_request((xcb_configure_request_event_t*) event);
741 * Dummy Callback. We only need this, so that the Prepare- and Check-Watchers
745 void xcb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
749 * We need to bind to the modifier per XKB. Sadly, XCB does not implement this
752 void xkb_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
756 DLOG("Got XKB-Event!\n");
758 while (XPending(xkb_dpy)) {
759 XNextEvent(xkb_dpy, (XEvent*)&ev);
761 if (ev.type != xkb_event_base) {
762 ELOG("No Xkb-Event!\n");
766 if (ev.any.xkb_type != XkbStateNotify) {
767 ELOG("No State Notify!\n");
771 unsigned int mods = ev.state.mods;
772 modstate = mods & Mod4Mask;
775 if (modstate != mod_pressed) {
777 DLOG("Mod4 got released!\n");
780 DLOG("Mod4 got pressed!\n");
783 mod_pressed = modstate;
788 * Initialize xcb and use the specified fontname for text-rendering
791 char *init_xcb(char *fontname) {
792 /* FIXME: xcb_connect leaks Memory */
793 xcb_connection = xcb_connect(NULL, &screen);
794 if (xcb_connection_has_error(xcb_connection)) {
795 ELOG("Cannot open display\n");
798 DLOG("Connected to xcb\n");
800 /* We have to request the atoms we need */
801 #define ATOM_DO(name) atom_cookies[name] = xcb_intern_atom(xcb_connection, 0, strlen(#name), #name);
802 #include "xcb_atoms.def"
804 xcb_screen = xcb_setup_roots_iterator(xcb_get_setup(xcb_connection)).data;
805 xcb_root = xcb_screen->root;
807 /* We load and allocate the font */
808 xcb_font = xcb_generate_id(xcb_connection);
809 xcb_void_cookie_t open_font_cookie;
810 open_font_cookie = xcb_open_font_checked(xcb_connection,
815 /* We need to save info about the font, because we need the font's height and
816 * information about the width of characters */
817 xcb_query_font_cookie_t query_font_cookie;
818 query_font_cookie = xcb_query_font(xcb_connection,
821 /* To grab modifiers without blocking other applications from receiving key-events
822 * involving that modifier, we sadly have to use xkb which is not yet fully supported
824 if (config.hide_on_modifier) {
825 int xkb_major, xkb_minor, xkb_errbase, xkb_err;
826 xkb_major = XkbMajorVersion;
827 xkb_minor = XkbMinorVersion;
829 xkb_dpy = XkbOpenDisplay(NULL,
836 if (xkb_dpy == NULL) {
841 if (fcntl(ConnectionNumber(xkb_dpy), F_SETFD, FD_CLOEXEC) == -1) {
842 ELOG("Could not set FD_CLOEXEC on xkbdpy: %s\n", strerror(errno));
847 if (!XkbQueryExtension(xkb_dpy, &i1, &xkb_event_base, &xkb_errbase, &xkb_major, &xkb_minor)) {
848 ELOG("XKB not supported by X-server!\n");
852 if (!XkbSelectEvents(xkb_dpy, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) {
853 ELOG("Could not grab Key!\n");
857 xkb_io = malloc(sizeof(ev_io));
858 ev_io_init(xkb_io, &xkb_io_cb, ConnectionNumber(xkb_dpy), EV_READ);
859 ev_io_start(main_loop, xkb_io);
863 /* We draw the statusline to a seperate pixmap, because it looks the same on all bars and
864 * this way, we can choose to crop it */
865 uint32_t mask = XCB_GC_FOREGROUND;
866 uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
868 statusline_clear = xcb_generate_id(xcb_connection);
869 xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
875 mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
876 vals[0] = colors.bar_fg;
877 statusline_ctx = xcb_generate_id(xcb_connection);
878 xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
884 statusline_pm = xcb_generate_id(xcb_connection);
885 xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
886 xcb_screen->root_depth,
889 xcb_screen->width_in_pixels,
890 xcb_screen->height_in_pixels);
893 /* The various Watchers to communicate with xcb */
894 xcb_io = malloc(sizeof(ev_io));
895 xcb_prep = malloc(sizeof(ev_prepare));
896 xcb_chk = malloc(sizeof(ev_check));
898 ev_io_init(xcb_io, &xcb_io_cb, xcb_get_file_descriptor(xcb_connection), EV_READ);
899 ev_prepare_init(xcb_prep, &xcb_prep_cb);
900 ev_check_init(xcb_chk, &xcb_chk_cb);
902 ev_io_start(main_loop, xcb_io);
903 ev_prepare_start(main_loop, xcb_prep);
904 ev_check_start(main_loop, xcb_chk);
906 /* Now we get the atoms and save them in a nice data structure */
909 xcb_get_property_cookie_t path_cookie;
910 path_cookie = xcb_get_property_unchecked(xcb_connection,
913 atoms[I3_SOCKET_PATH],
914 XCB_GET_PROPERTY_TYPE_ANY,
917 /* We check, if i3 set its socket-path */
918 xcb_get_property_reply_t *path_reply = xcb_get_property_reply(xcb_connection,
923 int len = xcb_get_property_value_length(path_reply);
925 path = strndup(xcb_get_property_value(path_reply), len);
929 /* Now we save the font-infos */
930 font_info = xcb_query_font_reply(xcb_connection,
934 if (xcb_request_failed(open_font_cookie, "Could not open font")) {
938 font_height = font_info->font_ascent + font_info->font_descent;
940 if (xcb_query_font_char_infos_length(font_info) == 0) {
943 font_table = xcb_query_font_char_infos(font_info);
946 DLOG("Calculated Font-height: %d\n", font_height);
948 if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
949 xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
950 xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
958 * Initializes tray support by requesting the appropriate _NET_SYSTEM_TRAY atom
959 * for the X11 display we are running on, then acquiring the selection for this
960 * atom. Afterwards, tray clients will send ClientMessages to our window.
964 /* request the tray manager atom for the X11 display we are running on */
965 char atomname[strlen("_NET_SYSTEM_TRAY_S") + 11];
966 snprintf(atomname, strlen("_NET_SYSTEM_TRAY_S") + 11, "_NET_SYSTEM_TRAY_S%d", screen);
967 xcb_intern_atom_cookie_t tray_cookie;
968 xcb_intern_atom_reply_t *tray_reply;
969 tray_cookie = xcb_intern_atom(xcb_connection, 0, strlen(atomname), atomname);
971 /* tray support: we need a window to own the selection */
972 xcb_window_t selwin = xcb_generate_id(xcb_connection);
973 uint32_t selmask = XCB_CW_OVERRIDE_REDIRECT;
974 uint32_t selval[] = { 1 };
975 xcb_create_window(xcb_connection,
976 xcb_screen->root_depth,
982 XCB_WINDOW_CLASS_INPUT_OUTPUT,
983 xcb_screen->root_visual,
987 uint32_t orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
989 xcb_change_property(xcb_connection,
990 XCB_PROP_MODE_REPLACE,
992 atoms[_NET_SYSTEM_TRAY_ORIENTATION],
998 if (!(tray_reply = xcb_intern_atom_reply(xcb_connection, tray_cookie, NULL))) {
999 ELOG("Could not get atom %s\n", atomname);
1003 xcb_set_selection_owner(xcb_connection,
1008 /* Verify that we have the selection */
1009 xcb_get_selection_owner_cookie_t selcookie;
1010 xcb_get_selection_owner_reply_t *selreply;
1012 selcookie = xcb_get_selection_owner(xcb_connection, tray_reply->atom);
1013 if (!(selreply = xcb_get_selection_owner_reply(xcb_connection, selcookie, NULL))) {
1014 ELOG("Could not get selection owner for %s\n", atomname);
1018 if (selreply->owner != selwin) {
1019 ELOG("Could not set the %s selection. " \
1020 "Maybe another tray is already running?\n", atomname);
1021 /* NOTE that this error is not fatal. We just can’t provide tray
1027 /* Inform clients waiting for a new _NET_SYSTEM_TRAY that we are here */
1028 void *event = calloc(32, 1);
1029 xcb_client_message_event_t *ev = event;
1030 ev->response_type = XCB_CLIENT_MESSAGE;
1031 ev->window = xcb_root;
1032 ev->type = atoms[MANAGER];
1034 ev->data.data32[0] = XCB_CURRENT_TIME;
1035 ev->data.data32[1] = tray_reply->atom;
1036 ev->data.data32[2] = selwin;
1037 xcb_send_event(xcb_connection,
1040 XCB_EVENT_MASK_STRUCTURE_NOTIFY,
1047 * Cleanup the xcb-stuff.
1048 * Called once, before the program terminates.
1053 trayclient *trayclient;
1055 SLIST_FOREACH(o_walk, outputs, slist) {
1056 TAILQ_FOREACH(trayclient, o_walk->trayclients, tailq) {
1057 /* Unmap, then reparent (to root) the tray client windows */
1058 xcb_unmap_window(xcb_connection, trayclient->win);
1059 xcb_reparent_window(xcb_connection,
1065 destroy_window(o_walk);
1066 FREE(o_walk->trayclients);
1067 FREE(o_walk->workspaces);
1070 FREE_SLIST(outputs, i3_output);
1073 xcb_flush(xcb_connection);
1074 xcb_disconnect(xcb_connection);
1076 ev_check_stop(main_loop, xcb_chk);
1077 ev_prepare_stop(main_loop, xcb_prep);
1078 ev_io_stop(main_loop, xcb_io);
1087 * Get the earlier requested atoms and save them in the prepared data structure
1091 xcb_intern_atom_reply_t *reply;
1092 #define ATOM_DO(name) reply = xcb_intern_atom_reply(xcb_connection, atom_cookies[name], NULL); \
1093 if (reply == NULL) { \
1094 ELOG("Could not get atom %s\n", #name); \
1095 exit(EXIT_FAILURE); \
1097 atoms[name] = reply->atom; \
1100 #include "xcb_atoms.def"
1101 DLOG("Got Atoms\n");
1105 * Destroy the bar of the specified output
1108 void destroy_window(i3_output *output) {
1109 if (output == NULL) {
1112 if (output->bar == XCB_NONE) {
1115 xcb_destroy_window(xcb_connection, output->bar);
1116 output->bar = XCB_NONE;
1120 * Reallocate the statusline-buffer
1123 void realloc_sl_buffer() {
1124 DLOG("Re-allocating statusline-buffer, statusline_width = %d, xcb_screen->width_in_pixels = %d\n",
1125 statusline_width, xcb_screen->width_in_pixels);
1126 xcb_free_pixmap(xcb_connection, statusline_pm);
1127 statusline_pm = xcb_generate_id(xcb_connection);
1128 xcb_void_cookie_t sl_pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1129 xcb_screen->root_depth,
1132 MAX(xcb_screen->width_in_pixels, statusline_width),
1133 xcb_screen->height_in_pixels);
1135 uint32_t mask = XCB_GC_FOREGROUND;
1136 uint32_t vals[3] = { colors.bar_bg, colors.bar_bg, xcb_font };
1137 xcb_free_gc(xcb_connection, statusline_clear);
1138 statusline_clear = xcb_generate_id(xcb_connection);
1139 xcb_void_cookie_t clear_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1145 mask |= XCB_GC_BACKGROUND | XCB_GC_FONT;
1146 vals[0] = colors.bar_fg;
1147 statusline_ctx = xcb_generate_id(xcb_connection);
1148 xcb_free_gc(xcb_connection, statusline_ctx);
1149 xcb_void_cookie_t sl_ctx_cookie = xcb_create_gc_checked(xcb_connection,
1155 if (xcb_request_failed(sl_pm_cookie, "Could not allocate statusline-buffer") ||
1156 xcb_request_failed(clear_ctx_cookie, "Could not allocate statusline-buffer-clearcontext") ||
1157 xcb_request_failed(sl_ctx_cookie, "Could not allocate statusline-buffer-context")) {
1164 * Reconfigure all bars and create new bars for recently activated outputs
1167 void reconfig_windows() {
1172 SLIST_FOREACH(walk, outputs, slist) {
1173 if (!walk->active) {
1174 /* If an output is not active, we destroy its bar */
1175 /* FIXME: Maybe we rather want to unmap? */
1176 DLOG("Destroying window for output %s\n", walk->name);
1177 destroy_window(walk);
1180 if (walk->bar == XCB_NONE) {
1181 DLOG("Creating Window for output %s\n", walk->name);
1183 /* TODO: only call init_tray() if the tray is configured for this output */
1186 walk->bar = xcb_generate_id(xcb_connection);
1187 walk->buffer = xcb_generate_id(xcb_connection);
1188 mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;
1189 /* Black background */
1190 values[0] = colors.bar_bg;
1191 /* If hide_on_modifier is set, i3 is not supposed to manage our bar-windows */
1192 values[1] = config.hide_on_modifier;
1193 /* We enable the following EventMask fields:
1194 * EXPOSURE, to get expose events (we have to re-draw then)
1195 * SUBSTRUCTURE_REDIRECT, to get ConfigureRequests when the tray
1196 * child windows use ConfigureWindow
1197 * BUTTON_PRESS, to handle clicks on the workspace buttons
1199 values[2] = XCB_EVENT_MASK_EXPOSURE |
1200 XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;
1201 if (!config.disable_ws) {
1202 values[2] |= XCB_EVENT_MASK_BUTTON_PRESS;
1204 xcb_void_cookie_t win_cookie = xcb_create_window_checked(xcb_connection,
1205 xcb_screen->root_depth,
1208 walk->rect.x, walk->rect.y + walk->rect.h - font_height - 6,
1209 walk->rect.w, font_height + 6,
1211 XCB_WINDOW_CLASS_INPUT_OUTPUT,
1212 xcb_screen->root_visual,
1216 /* The double-buffer we use to render stuff off-screen */
1217 xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1218 xcb_screen->root_depth,
1224 /* Set the WM_CLASS and WM_NAME (we don't need UTF-8) atoms */
1225 xcb_void_cookie_t class_cookie;
1226 class_cookie = xcb_change_property(xcb_connection,
1227 XCB_PROP_MODE_REPLACE,
1232 (strlen("i3bar") + 1) * 2,
1236 if (asprintf(&name, "i3bar for output %s", walk->name) == -1)
1237 err(EXIT_FAILURE, "asprintf()");
1238 xcb_void_cookie_t name_cookie;
1239 name_cookie = xcb_change_property(xcb_connection,
1240 XCB_PROP_MODE_REPLACE,
1249 /* We want dock-windows (for now). When override_redirect is set, i3 is ignoring
1251 xcb_void_cookie_t dock_cookie = xcb_change_property(xcb_connection,
1252 XCB_PROP_MODE_REPLACE,
1254 atoms[_NET_WM_WINDOW_TYPE],
1258 (unsigned char*) &atoms[_NET_WM_WINDOW_TYPE_DOCK]);
1260 /* We need to tell i3, where to reserve space for i3bar */
1261 /* left, right, top, bottom, left_start_y, left_end_y,
1262 * right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x,
1264 /* A local struct to save the strut_partial property */
1270 uint32_t left_start_y;
1271 uint32_t left_end_y;
1272 uint32_t right_start_y;
1273 uint32_t right_end_y;
1274 uint32_t top_start_x;
1276 uint32_t bottom_start_x;
1277 uint32_t bottom_end_x;
1278 } __attribute__((__packed__)) strut_partial = {0,};
1279 switch (config.dockpos) {
1283 strut_partial.top = font_height + 6;
1284 strut_partial.top_start_x = walk->rect.x;
1285 strut_partial.top_end_x = walk->rect.x + walk->rect.w;
1288 strut_partial.bottom = font_height + 6;
1289 strut_partial.bottom_start_x = walk->rect.x;
1290 strut_partial.bottom_end_x = walk->rect.x + walk->rect.w;
1293 xcb_void_cookie_t strut_cookie = xcb_change_property(xcb_connection,
1294 XCB_PROP_MODE_REPLACE,
1296 atoms[_NET_WM_STRUT_PARTIAL],
1302 /* We also want a graphics-context for the bars (it defines the properties
1303 * with which we draw to them) */
1304 walk->bargc = xcb_generate_id(xcb_connection);
1306 values[0] = xcb_font;
1307 xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection,
1313 /* We finally map the bar (display it on screen), unless the modifier-switch is on */
1314 xcb_void_cookie_t map_cookie;
1315 if (!config.hide_on_modifier) {
1316 map_cookie = xcb_map_window_checked(xcb_connection, walk->bar);
1319 if (xcb_request_failed(win_cookie, "Could not create window") ||
1320 xcb_request_failed(pm_cookie, "Could not create pixmap") ||
1321 xcb_request_failed(dock_cookie, "Could not set dock mode") ||
1322 xcb_request_failed(class_cookie, "Could not set WM_CLASS") ||
1323 xcb_request_failed(name_cookie, "Could not set WM_NAME") ||
1324 xcb_request_failed(strut_cookie, "Could not set strut") ||
1325 xcb_request_failed(gc_cookie, "Could not create graphical context") ||
1326 (!config.hide_on_modifier && xcb_request_failed(map_cookie, "Could not map window"))) {
1330 /* We already have a bar, so we just reconfigure it */
1331 mask = XCB_CONFIG_WINDOW_X |
1332 XCB_CONFIG_WINDOW_Y |
1333 XCB_CONFIG_WINDOW_WIDTH |
1334 XCB_CONFIG_WINDOW_HEIGHT |
1335 XCB_CONFIG_WINDOW_STACK_MODE;
1336 values[0] = walk->rect.x;
1337 values[1] = walk->rect.y + walk->rect.h - font_height - 6;
1338 values[2] = walk->rect.w;
1339 values[3] = font_height + 6;
1340 values[4] = XCB_STACK_MODE_ABOVE;
1342 DLOG("Destroying buffer for output %s", walk->name);
1343 xcb_free_pixmap(xcb_connection, walk->buffer);
1345 DLOG("Reconfiguring Window for output %s to %d,%d\n", walk->name, values[0], values[1]);
1346 xcb_void_cookie_t cfg_cookie = xcb_configure_window_checked(xcb_connection,
1351 DLOG("Recreating buffer for output %s", walk->name);
1352 xcb_void_cookie_t pm_cookie = xcb_create_pixmap_checked(xcb_connection,
1353 xcb_screen->root_depth,
1359 if (xcb_request_failed(cfg_cookie, "Could not reconfigure window")) {
1362 if (xcb_request_failed(pm_cookie, "Could not create pixmap")) {
1370 * Render the bars, with buttons and statusline
1374 DLOG("Drawing Bars...\n");
1377 refresh_statusline();
1379 i3_output *outputs_walk;
1380 SLIST_FOREACH(outputs_walk, outputs, slist) {
1381 if (!outputs_walk->active) {
1382 DLOG("Output %s inactive, skipping...\n", outputs_walk->name);
1385 if (outputs_walk->bar == XCB_NONE) {
1386 /* Oh shit, an active output without an own bar. Create it now! */
1389 /* First things first: clear the backbuffer */
1390 uint32_t color = colors.bar_bg;
1391 xcb_change_gc(xcb_connection,
1392 outputs_walk->bargc,
1395 xcb_rectangle_t rect = { 0, 0, outputs_walk->rect.w, font_height + 6 };
1396 xcb_poly_fill_rectangle(xcb_connection,
1397 outputs_walk->buffer,
1398 outputs_walk->bargc,
1402 if (statusline != NULL) {
1403 DLOG("Printing statusline!\n");
1405 /* Luckily we already prepared a seperate pixmap containing the rendered
1406 * statusline, we just have to copy the relevant parts to the relevant
1408 trayclient *trayclient;
1410 TAILQ_FOREACH(trayclient, outputs_walk->trayclients, tailq) {
1411 if (!trayclient->mapped)
1413 /* We assume the tray icons are quadratic (we use the font
1414 * *height* as *width* of the icons) because we configured them
1416 traypx += font_height;
1418 /* Add 2px of padding if there are any tray icons */
1421 xcb_copy_area(xcb_connection,
1423 outputs_walk->buffer,
1424 outputs_walk->bargc,
1425 MAX(0, (int16_t)(statusline_width - outputs_walk->rect.w + 4)), 0,
1426 MAX(0, (int16_t)(outputs_walk->rect.w - statusline_width - traypx - 4)), 3,
1427 MIN(outputs_walk->rect.w - traypx - 4, statusline_width), font_height);
1430 if (config.disable_ws) {
1435 TAILQ_FOREACH(ws_walk, outputs_walk->workspaces, tailq) {
1436 DLOG("Drawing Button for WS %s at x = %d\n", ws_walk->name, i);
1437 uint32_t fg_color = colors.inactive_ws_fg;
1438 uint32_t bg_color = colors.inactive_ws_bg;
1439 if (ws_walk->visible) {
1440 if (!ws_walk->focused) {
1441 fg_color = colors.active_ws_fg;
1442 bg_color = colors.active_ws_bg;
1444 fg_color = colors.focus_ws_fg;
1445 bg_color = colors.focus_ws_bg;
1448 if (ws_walk->urgent) {
1449 DLOG("WS %s is urgent!\n", ws_walk->name);
1450 fg_color = colors.urgent_ws_fg;
1451 bg_color = colors.urgent_ws_bg;
1452 /* The urgent-hint should get noticed, so we unhide the bars shortly */
1455 uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
1456 uint32_t vals[] = { bg_color, bg_color };
1457 xcb_change_gc(xcb_connection,
1458 outputs_walk->bargc,
1461 xcb_rectangle_t rect = { i + 1, 1, ws_walk->name_width + 8, font_height + 4 };
1462 xcb_poly_fill_rectangle(xcb_connection,
1463 outputs_walk->buffer,
1464 outputs_walk->bargc,
1467 xcb_change_gc(xcb_connection,
1468 outputs_walk->bargc,
1471 xcb_image_text_16(xcb_connection,
1472 ws_walk->name_glyphs,
1473 outputs_walk->buffer,
1474 outputs_walk->bargc,
1475 i + 5, font_info->font_ascent + 2,
1476 ws_walk->ucs2_name);
1477 i += 10 + ws_walk->name_width;
1487 * Redraw the bars, i.e. simply copy the buffer to the barwindow
1490 void redraw_bars() {
1491 i3_output *outputs_walk;
1492 SLIST_FOREACH(outputs_walk, outputs, slist) {
1493 if (!outputs_walk->active) {
1496 xcb_copy_area(xcb_connection,
1497 outputs_walk->buffer,
1499 outputs_walk->bargc,
1502 outputs_walk->rect.w,
1503 outputs_walk->rect.h);
1504 xcb_flush(xcb_connection);