2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
7 * i3-config-wizard: Program to convert configs using keycodes to configs using
11 #if defined(__FreeBSD__)
12 #include <sys/param.h>
15 /* For systems without getline, fall back to fgetln */
16 #if defined(__APPLE__) || (defined(__FreeBSD__) && __FreeBSD_version < 800000)
18 #elif defined(__FreeBSD__)
19 /* Defining this macro before including stdio.h is necessary in order to have
20 * a prototype for getline in FreeBSD. */
25 #include <sys/types.h>
42 #include <xcb/xcb_aux.h>
43 #include <xcb/xcb_event.h>
44 #include <xcb/xcb_keysyms.h>
47 #include <X11/keysym.h>
48 #include <X11/XKBlib.h>
50 /* We need SYSCONFDIR for the path to the keycode config template, so raise an
51 * error if it’s not defined for whatever reason */
53 #error "SYSCONFDIR not defined"
56 #define FREE(pointer) do { \
57 if (pointer != NULL) { \
67 enum { STEP_WELCOME, STEP_GENERATE } current_step = STEP_WELCOME;
68 enum { MOD_Mod1, MOD_Mod4 } modifier = MOD_Mod4;
70 static char *config_path;
71 static uint32_t xcb_numlock_mask;
72 xcb_connection_t *conn;
73 static xcb_key_symbols_t *keysyms;
74 xcb_screen_t *root_screen;
75 static xcb_get_modifier_mapping_reply_t *modmap_reply;
77 static i3Font bold_font;
78 static char *socket_path;
79 static xcb_window_t win;
80 static xcb_pixmap_t pixmap;
81 static xcb_gcontext_t pixmap_gc;
82 static xcb_key_symbols_t *symbols;
88 #include "GENERATED_config_enums.h"
90 typedef struct token {
93 /* This might be __CALL */
94 cmdp_state next_state;
96 uint16_t call_identifier;
100 typedef struct tokenptr {
106 #include "GENERATED_config_tokens.h"
108 static cmdp_state state;
109 /* A list which contains the states that lead to the current state, e.g.
110 * INITIAL, WORKSPACE_LAYOUT.
111 * When jumping back to INITIAL, statelist_idx will simply be set to 1
112 * (likewise for other states, e.g. MODE or BAR).
113 * This list is used to process the nearest error token. */
114 static cmdp_state statelist[10] = { INITIAL };
115 /* NB: statelist_idx points to where the next entry will be inserted */
116 static int statelist_idx = 1;
119 /* Just a pointer, not dynamically allocated. */
120 const char *identifier;
131 /* 10 entries should be enough for everybody. */
132 static struct stack_entry stack[10];
135 * Pushes a string (identified by 'identifier') on the stack. We simply use a
136 * single array, since the number of entries we have to store is very small.
139 static void push_string(const char *identifier, const char *str) {
140 for (int c = 0; c < 10; c++) {
141 if (stack[c].identifier != NULL &&
142 strcmp(stack[c].identifier, identifier) != 0)
144 if (stack[c].identifier == NULL) {
145 /* Found a free slot, let’s store it here. */
146 stack[c].identifier = identifier;
147 stack[c].val.str = sstrdup(str);
148 stack[c].type = STACK_STR;
150 /* Append the value. */
151 char *prev = stack[c].val.str;
152 sasprintf(&(stack[c].val.str), "%s,%s", prev, str);
158 /* When we arrive here, the stack is full. This should not happen and
159 * means there’s either a bug in this parser or the specification
160 * contains a command with more than 10 identified tokens. */
161 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
162 "in the code, or a new command which contains more than "
163 "10 identified tokens.\n");
167 static void push_long(const char *identifier, long num) {
168 for (int c = 0; c < 10; c++) {
169 if (stack[c].identifier != NULL)
171 /* Found a free slot, let’s store it here. */
172 stack[c].identifier = identifier;
173 stack[c].val.num = num;
174 stack[c].type = STACK_LONG;
178 /* When we arrive here, the stack is full. This should not happen and
179 * means there’s either a bug in this parser or the specification
180 * contains a command with more than 10 identified tokens. */
181 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
182 "in the code, or a new command which contains more than "
183 "10 identified tokens.\n");
188 static const char *get_string(const char *identifier) {
189 for (int c = 0; c < 10; c++) {
190 if (stack[c].identifier == NULL)
192 if (strcmp(identifier, stack[c].identifier) == 0)
193 return stack[c].val.str;
199 static void clear_stack(void) {
200 for (int c = 0; c < 10; c++) {
201 if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
202 free(stack[c].val.str);
203 stack[c].identifier = NULL;
204 stack[c].val.str = NULL;
205 stack[c].val.num = 0;
210 * Returns true if sym is bound to any key except for 'except_keycode' on the
211 * first four layers (normal, shift, mode_switch, mode_switch + shift).
214 static bool keysym_used_on_other_key(KeySym sym, xcb_keycode_t except_keycode) {
216 min_keycode = xcb_get_setup(conn)->min_keycode,
217 max_keycode = xcb_get_setup(conn)->max_keycode;
219 for (i = min_keycode; i && i <= max_keycode; i++) {
220 if (i == except_keycode)
222 for (int level = 0; level < 4; level++) {
223 if (xcb_key_symbols_get_keysym(keysyms, i, level) != sym)
232 static char *next_state(const cmdp_token *token) {
233 cmdp_state _next_state = token->next_state;
235 if (token->next_state == __CALL) {
236 const char *modifiers = get_string("modifiers");
237 int keycode = atoi(get_string("key"));
239 if (modifiers != NULL &&
240 strstr(modifiers, "Shift") != NULL) {
241 /* When shift is included, we really need to use the second-level
242 * symbol (upper-case). The lower-case symbol could be on a
243 * different key than the upper-case one (unlikely for letters, but
244 * more likely for special characters). */
247 /* Try to use the keysym on the first level (lower-case). In case
248 * this doesn’t make it ambiguous (think of a keyboard layout
249 * having '1' on two different keys, but '!' only on keycode 10),
250 * we’ll stick with the keysym of the first level.
252 * This reduces a lot of confusion for users who switch keyboard
253 * layouts from qwerty to qwertz or other slight variations of
254 * qwerty (yes, that happens quite often). */
255 KeySym sym = XkbKeycodeToKeysym(dpy, keycode, 0, 0);
256 if (!keysym_used_on_other_key(sym, keycode))
259 KeySym sym = XkbKeycodeToKeysym(dpy, keycode, 0, level);
260 char *str = XKeysymToString(sym);
261 const char *release = get_string("release");
263 char *modrep = (modifiers == NULL ? sstrdup("") : sstrdup(modifiers));
265 while ((comma = strchr(modrep, ',')) != NULL) {
268 sasprintf(&res, "bindsym %s%s%s %s%s\n", (modifiers == NULL ? "" : modrep), (modifiers == NULL ? "" : "+"), str, (release == NULL ? "" : release), get_string("command"));
275 /* See if we are jumping back to a state in which we were in previously
276 * (statelist contains INITIAL) and just move statelist_idx accordingly. */
277 for (int i = 0; i < statelist_idx; i++) {
278 if (statelist[i] != _next_state)
284 /* Otherwise, the state is new and we add it to the list */
285 statelist[statelist_idx++] = _next_state;
290 static char *rewrite_binding(const char *input) {
294 const char *walk = input;
295 const size_t len = strlen(input);
297 const cmdp_token *token;
300 /* The "<=" operator is intentional: We also handle the terminating 0-byte
301 * explicitly by looking for an 'end' token. */
302 while ((walk - input) <= len) {
303 /* Skip whitespace before every token, newlines are relevant since they
304 * separate configuration directives. */
305 while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
308 //printf("remaining input: %s\n", walk);
310 cmdp_token_ptr *ptr = &(tokens[state]);
311 for (c = 0; c < ptr->n; c++) {
312 token = &(ptr->array[c]);
315 if (token->name[0] == '\'') {
316 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
317 if (token->identifier != NULL)
318 push_string(token->identifier, token->name + 1);
319 walk += strlen(token->name) - 1;
320 if ((result = next_state(token)) != NULL)
327 if (strcmp(token->name, "number") == 0) {
328 /* Handle numbers. We only accept decimal numbers for now. */
331 long int num = strtol(walk, &end, 10);
332 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
333 (errno != 0 && num == 0))
336 /* No valid numbers found */
340 if (token->identifier != NULL)
341 push_long(token->identifier, num);
343 /* Set walk to the first non-number character */
345 if ((result = next_state(token)) != NULL)
350 if (strcmp(token->name, "string") == 0 ||
351 strcmp(token->name, "word") == 0) {
352 const char *beginning = walk;
353 /* Handle quoted strings (or words). */
357 while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
360 if (token->name[0] == 's') {
361 while (*walk != '\0' && *walk != '\r' && *walk != '\n')
364 /* For a word, the delimiters are white space (' ' or
365 * '\t'), closing square bracket (]), comma (,) and
367 while (*walk != ' ' && *walk != '\t' &&
368 *walk != ']' && *walk != ',' &&
369 *walk != ';' && *walk != '\r' &&
370 *walk != '\n' && *walk != '\0')
374 if (walk != beginning) {
375 char *str = scalloc(walk-beginning + 1);
376 /* We copy manually to handle escaping of characters. */
378 for (inpos = 0, outpos = 0;
379 inpos < (walk-beginning);
381 /* We only handle escaped double quotes to not break
382 * backwards compatibility with people using \w in
383 * regular expressions etc. */
384 if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
386 str[outpos] = beginning[inpos];
388 if (token->identifier)
389 push_string(token->identifier, str);
391 /* If we are at the end of a quoted string, skip the ending
395 if ((result = next_state(token)) != NULL)
401 if (strcmp(token->name, "end") == 0) {
402 //printf("checking for end: *%s*\n", walk);
403 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
404 if ((result = next_state(token)) != NULL)
406 /* To make sure we start with an appropriate matching
407 * datastructure for commands which do *not* specify any
408 * criteria, we re-initialize the criteria system after
410 // TODO: make this testable
423 * Having verboselog() and errorlog() is necessary when using libi3.
426 void verboselog(char *fmt, ...) {
430 vfprintf(stdout, fmt, args);
434 void errorlog(char *fmt, ...) {
438 vfprintf(stderr, fmt, args);
443 * This function resolves ~ in pathnames.
444 * It may resolve wildcards in the first part of the path, but if no match
445 * or multiple matches are found, it just returns a copy of path as given.
448 static char *resolve_tilde(const char *path) {
449 static glob_t globbuf;
450 char *head, *tail, *result;
452 tail = strchr(path, '/');
453 head = strndup(path, tail ? tail - path : strlen(path));
455 int res = glob(head, GLOB_TILDE, NULL, &globbuf);
457 /* no match, or many wildcard matches are bad */
458 if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
459 result = strdup(path);
461 err(1, "glob() failed");
463 head = globbuf.gl_pathv[0];
464 result = calloc(1, strlen(head) + (tail ? strlen(tail) : 0) + 1);
465 strncpy(result, head, strlen(head));
467 strncat(result, tail, strlen(tail));
475 * Handles expose events, that is, draws the window contents.
478 static int handle_expose() {
479 /* re-draw the background */
480 xcb_rectangle_t border = {0, 0, 300, (15 * font.height) + 8};
481 xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#000000") });
482 xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
486 #define txt(x, row, text) \
487 draw_text_ascii(text, pixmap, pixmap_gc,\
488 x, (row - 1) * font.height + 4, 300 - x * 2)
490 if (current_step == STEP_WELCOME) {
491 /* restore font color */
492 set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
494 txt(10, 2, "You have not configured i3 yet.");
495 txt(10, 3, "Do you want me to generate ~/.i3/config?");
496 txt(85, 5, "Yes, generate ~/.i3/config");
497 txt(85, 7, "No, I will use the defaults");
500 set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
501 txt(25, 5, "<Enter>");
504 set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
508 if (current_step == STEP_GENERATE) {
509 set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
511 txt(10, 2, "Please choose either:");
512 txt(85, 4, "Win as default modifier");
513 txt(85, 5, "Alt as default modifier");
514 txt(10, 7, "Afterwards, press");
515 txt(85, 9, "to write ~/.i3/config");
516 txt(85, 10, "to abort");
518 /* the not-selected modifier */
519 if (modifier == MOD_Mod4)
521 else txt(31, 4, "<Win>");
523 /* the selected modifier */
524 set_font(&bold_font);
525 set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
526 if (modifier == MOD_Mod4)
527 txt(10, 4, "-> <Win>");
528 else txt(10, 5, "-> <Alt>");
532 set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
533 txt(25, 9, "<Enter>");
536 set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
537 txt(31, 10, "<ESC>");
540 /* Copy the contents of the pixmap to the real window */
541 xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, /* */ 500, 500);
547 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
548 printf("Keypress %d, state raw = %d\n", event->detail, event->state);
550 /* Remove the numlock bit, all other bits are modifiers we can bind to */
551 uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
552 /* Only use the lower 8 bits of the state (modifier masks) so that mouse
553 * button masks are filtered out */
554 state_filtered &= 0xFF;
556 xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, state_filtered);
558 printf("sym = %c (%d)\n", sym, sym);
560 if (sym == XK_Return || sym == XK_KP_Enter) {
561 if (current_step == STEP_WELCOME) {
562 current_step = STEP_GENERATE;
563 /* Set window title */
564 xcb_change_property(conn,
565 XCB_PROP_MODE_REPLACE,
570 strlen("i3: generate config"),
571 "i3: generate config");
577 /* cancel any time */
578 if (sym == XK_Escape)
581 /* Check if this is Mod1 or Mod4. The modmap contains Shift, Lock, Control,
582 * Mod1, Mod2, Mod3, Mod4, Mod5 (in that order) */
583 xcb_keycode_t *modmap = xcb_get_modifier_mapping_keycodes(modmap_reply);
586 for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
587 xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
588 if (code == XCB_NONE)
590 printf("Modifier keycode for Mod1: 0x%02x\n", code);
591 if (code == event->detail) {
593 printf("This is Mod1!\n");
599 for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
600 xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
601 if (code == XCB_NONE)
603 printf("Modifier keycode for Mod4: 0x%02x\n", code);
604 if (code == event->detail) {
606 printf("This is Mod4!\n");
615 * Handle button presses to make clicking on "<win>" and "<alt>" work
618 static void handle_button_press(xcb_button_press_event_t* event) {
619 if (current_step != STEP_GENERATE)
622 if (event->event_x >= 32 && event->event_x <= 68 &&
623 event->event_y >= 45 && event->event_y <= 54) {
628 if (event->event_x >= 32 && event->event_x <= 68 &&
629 event->event_y >= 56 && event->event_y <= 70) {
638 * Creates the config file and tells i3 to reload.
641 static void finish() {
642 printf("creating \"%s\"...\n", config_path);
644 if (!(dpy = XOpenDisplay(NULL)))
645 errx(1, "Could not connect to X11");
647 FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r");
648 if (kc_config == NULL)
649 err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes");
651 FILE *ks_config = fopen(config_path, "w");
652 if (ks_config == NULL)
653 err(1, "Could not open output config file \"%s\"", config_path);
661 bool head_of_file = true;
663 /* write a header about auto-generation to the output file */
664 fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config);
665 fputs("# It will not be overwritten, so edit it as you like.\n", ks_config);
666 fputs("#\n", ks_config);
667 fputs("# Should you change your keyboard layout somewhen, delete\n", ks_config);
668 fputs("# this file and re-run i3-config-wizard(1).\n", ks_config);
669 fputs("#\n", ks_config);
673 while ((buf = fgetln(kc_config, &len)) != NULL) {
674 /* fgetln does not return null-terminated strings */
676 sasprintf(&line, "%.*s", len, buf);
679 while ((read = getline(&line, &linecap, kc_config)) != -1) {
682 /* skip the warning block at the beginning of the input file */
684 strncmp("# WARNING", line, strlen("# WARNING")) == 0)
687 head_of_file = false;
689 /* Skip leading whitespace */
691 while (isspace(*walk) && walk < (line + len)) {
692 /* Pre-output the skipped whitespaces to keep proper indentation */
693 fputc(*walk, ks_config);
697 /* Set the modifier the user chose */
698 if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) {
699 if (modifier == MOD_Mod1)
700 fputs("set $mod Mod1\n", ks_config);
701 else fputs("set $mod Mod4\n", ks_config);
705 /* Check for 'bindcode'. If it’s not a bindcode line, we
706 * just copy it to the output file */
707 if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) {
708 fputs(walk, ks_config);
711 char *result = rewrite_binding(walk);
712 fputs(result, ks_config);
716 /* sync to do our best in order to have the file really stored on disk */
718 fsync(fileno(ks_config));
727 /* tell i3 to reload the config file */
728 int sockfd = ipc_connect(socket_path);
729 ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t*)"reload");
735 int main(int argc, char *argv[]) {
736 config_path = resolve_tilde("~/.i3/config");
737 socket_path = getenv("I3SOCK");
738 char *pattern = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
739 char *patternbold = "-misc-fixed-bold-r-normal--13-120-75-75-C-70-iso10646-1";
740 int o, option_index = 0;
742 static struct option long_options[] = {
743 {"socket", required_argument, 0, 's'},
744 {"version", no_argument, 0, 'v'},
745 {"limit", required_argument, 0, 'l'},
746 {"prompt", required_argument, 0, 'P'},
747 {"prefix", required_argument, 0, 'p'},
748 {"font", required_argument, 0, 'f'},
749 {"help", no_argument, 0, 'h'},
753 char *options_string = "s:vh";
755 while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
759 socket_path = strdup(optarg);
762 printf("i3-config-wizard " I3_VERSION "\n");
765 printf("i3-config-wizard " I3_VERSION "\n");
766 printf("i3-config-wizard [-s <socket>] [-v]\n");
771 /* Check if the destination config file does not exist but the path is
772 * writable. If not, exit now, this program is not useful in that case. */
774 if (stat(config_path, &stbuf) == 0) {
775 printf("The config file \"%s\" already exists. Exiting.\n", config_path);
779 /* Create ~/.i3 if it does not yet exist */
780 char *config_dir = resolve_tilde("~/.i3");
781 if (stat(config_dir, &stbuf) != 0)
782 if (mkdir(config_dir, 0755) == -1)
783 err(1, "mkdir(%s) failed", config_dir);
787 if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) {
788 printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno));
794 if (socket_path == NULL)
795 socket_path = root_atom_contents("I3_SOCKET_PATH");
797 if (socket_path == NULL)
798 socket_path = "/tmp/i3-ipc.sock";
801 if ((conn = xcb_connect(NULL, &screens)) == NULL ||
802 xcb_connection_has_error(conn))
803 errx(1, "Cannot open display\n");
805 keysyms = xcb_key_symbols_alloc(conn);
806 xcb_get_modifier_mapping_cookie_t modmap_cookie;
807 modmap_cookie = xcb_get_modifier_mapping(conn);
808 symbols = xcb_key_symbols_alloc(conn);
810 /* Place requests for the atoms we need as soon as possible */
811 #define xmacro(atom) \
812 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
813 #include "atoms.xmacro"
816 root_screen = xcb_aux_get_screen(conn, screens);
817 root = root_screen->root;
819 if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL)))
820 errx(EXIT_FAILURE, "Could not get modifier mapping\n");
822 xcb_numlock_mask = get_mod_mask_for(XCB_NUM_LOCK, symbols, modmap_reply);
824 font = load_font(pattern, true);
825 bold_font = load_font(patternbold, true);
827 /* Open an input window */
828 win = xcb_generate_id(conn);
831 XCB_COPY_FROM_PARENT,
832 win, /* the window id */
833 root, /* parent == root */
834 490, 297, 300, 205, /* dimensions */
835 0, /* X11 border = 0, we draw our own */
836 XCB_WINDOW_CLASS_INPUT_OUTPUT,
837 XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
838 XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
840 0, /* back pixel: black */
841 XCB_EVENT_MASK_EXPOSURE |
842 XCB_EVENT_MASK_BUTTON_PRESS
845 /* Map the window (make it visible) */
846 xcb_map_window(conn, win);
848 /* Setup NetWM atoms */
849 #define xmacro(name) \
851 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
853 errx(EXIT_FAILURE, "Could not get atom " # name "\n"); \
855 A_ ## name = reply->atom; \
858 #include "atoms.xmacro"
862 xcb_change_property(conn,
863 XCB_PROP_MODE_REPLACE,
865 A__NET_WM_WINDOW_TYPE,
869 (unsigned char*) &A__NET_WM_WINDOW_TYPE_DIALOG);
871 /* Set window title */
872 xcb_change_property(conn,
873 XCB_PROP_MODE_REPLACE,
878 strlen("i3: first configuration"),
879 "i3: first configuration");
882 pixmap = xcb_generate_id(conn);
883 pixmap_gc = xcb_generate_id(conn);
884 xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, 500);
885 xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
887 /* Grab the keyboard to get all input */
890 /* Try (repeatedly, if necessary) to grab the keyboard. We might not
891 * get the keyboard at the first attempt because of the keybinding
892 * still being active when started via a wm’s keybinding. */
893 xcb_grab_keyboard_cookie_t cookie;
894 xcb_grab_keyboard_reply_t *reply = NULL;
897 while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
898 cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
899 reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
903 if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
904 fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
910 xcb_generic_event_t *event;
911 while ((event = xcb_wait_for_event(conn)) != NULL) {
912 if (event->response_type == 0) {
913 fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
917 /* Strip off the highest bit (set if the event is generated) */
918 int type = (event->response_type & 0x7F);
922 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
925 /* TODO: handle mappingnotify */
927 case XCB_BUTTON_PRESS:
928 handle_button_press((xcb_button_press_event_t*)event);