]> git.sur5r.net Git - i3/i3/blob - src/bindings.c
Add i3test::XTEST, add 2 test cases for key bindings
[i3/i3] / src / bindings.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * bindings.c: Functions for configuring, finding and, running bindings.
8  */
9 #include "all.h"
10
11 #include <xkbcommon/xkbcommon.h>
12 #include <xkbcommon/xkbcommon-x11.h>
13
14 static struct xkb_context *xkb_context;
15 static struct xkb_keymap *xkb_keymap;
16
17 pid_t command_error_nagbar_pid = -1;
18
19 /*
20  * The name of the default mode.
21  *
22  */
23 const char *DEFAULT_BINDING_MODE = "default";
24
25 /*
26  * Returns the mode specified by `name` or creates a new mode and adds it to
27  * the list of modes.
28  *
29  */
30 static struct Mode *mode_from_name(const char *name, bool pango_markup) {
31     struct Mode *mode;
32
33     /* Try to find the mode in the list of modes and return it */
34     SLIST_FOREACH(mode, &modes, modes) {
35         if (strcmp(mode->name, name) == 0)
36             return mode;
37     }
38
39     /* If the mode was not found, create a new one */
40     mode = scalloc(1, sizeof(struct Mode));
41     mode->name = sstrdup(name);
42     mode->pango_markup = pango_markup;
43     mode->bindings = scalloc(1, sizeof(struct bindings_head));
44     TAILQ_INIT(mode->bindings);
45     SLIST_INSERT_HEAD(&modes, mode, modes);
46
47     return mode;
48 }
49
50 /*
51  * Adds a binding from config parameters given as strings and returns a
52  * pointer to the binding structure. Returns NULL if the input code could not
53  * be parsed.
54  *
55  */
56 Binding *configure_binding(const char *bindtype, const char *modifiers, const char *input_code,
57                            const char *release, const char *border, const char *whole_window,
58                            const char *command, const char *modename, bool pango_markup) {
59     Binding *new_binding = scalloc(1, sizeof(Binding));
60     DLOG("bindtype %s, modifiers %s, input code %s, release %s\n", bindtype, modifiers, input_code, release);
61     new_binding->release = (release != NULL ? B_UPON_KEYRELEASE : B_UPON_KEYPRESS);
62     new_binding->border = (border != NULL);
63     new_binding->whole_window = (whole_window != NULL);
64     if (strcmp(bindtype, "bindsym") == 0) {
65         new_binding->input_type = (strncasecmp(input_code, "button", (sizeof("button") - 1)) == 0
66                                        ? B_MOUSE
67                                        : B_KEYBOARD);
68
69         new_binding->symbol = sstrdup(input_code);
70     } else {
71         char *endptr;
72         long keycode = strtol(input_code, &endptr, 10);
73         new_binding->keycode = keycode;
74         new_binding->input_type = B_KEYBOARD;
75         if (keycode == LONG_MAX || keycode == LONG_MIN || keycode < 0 || *endptr != '\0' || endptr == input_code) {
76             ELOG("Could not parse \"%s\" as an input code, ignoring this binding.\n", input_code);
77             FREE(new_binding);
78             return NULL;
79         }
80     }
81     new_binding->command = sstrdup(command);
82     new_binding->event_state_mask = event_state_from_str(modifiers);
83     int group_bits_set = 0;
84     if ((new_binding->event_state_mask >> 16) & I3_XKB_GROUP_MASK_1)
85         group_bits_set++;
86     if ((new_binding->event_state_mask >> 16) & I3_XKB_GROUP_MASK_2)
87         group_bits_set++;
88     if ((new_binding->event_state_mask >> 16) & I3_XKB_GROUP_MASK_3)
89         group_bits_set++;
90     if ((new_binding->event_state_mask >> 16) & I3_XKB_GROUP_MASK_4)
91         group_bits_set++;
92     if (group_bits_set > 1)
93         ELOG("Keybinding has more than one Group specified, but your X server is always in precisely one group. The keybinding can never trigger.\n");
94
95     struct Mode *mode = mode_from_name(modename, pango_markup);
96     TAILQ_INSERT_TAIL(mode->bindings, new_binding, bindings);
97
98     return new_binding;
99 }
100
101 static void grab_keycode_for_binding(xcb_connection_t *conn, Binding *bind, uint32_t keycode) {
102     if (bind->input_type != B_KEYBOARD)
103         return;
104
105 /* Grab the key in all combinations */
106 #define GRAB_KEY(modifier)                                                                       \
107     do {                                                                                         \
108         xcb_grab_key(conn, 0, root, modifier, keycode, XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC); \
109     } while (0)
110     int mods = bind->event_state_mask;
111     if (((mods >> 16) & I3_XKB_GROUP_MASK_1) && xkb_current_group != XCB_XKB_GROUP_1)
112         return;
113     if (((mods >> 16) & I3_XKB_GROUP_MASK_2) && xkb_current_group != XCB_XKB_GROUP_2)
114         return;
115     if (((mods >> 16) & I3_XKB_GROUP_MASK_3) && xkb_current_group != XCB_XKB_GROUP_3)
116         return;
117     if (((mods >> 16) & I3_XKB_GROUP_MASK_4) && xkb_current_group != XCB_XKB_GROUP_4)
118         return;
119     mods &= 0xFFFF;
120     DLOG("Grabbing keycode %d with event state mask 0x%x (mods 0x%x)\n",
121          keycode, bind->event_state_mask, mods);
122     GRAB_KEY(mods);
123     GRAB_KEY(mods | xcb_numlock_mask);
124     GRAB_KEY(mods | XCB_MOD_MASK_LOCK);
125     GRAB_KEY(mods | xcb_numlock_mask | XCB_MOD_MASK_LOCK);
126 }
127
128 /*
129  * Grab the bound keys (tell X to send us keypress events for those keycodes)
130  *
131  */
132 void grab_all_keys(xcb_connection_t *conn) {
133     Binding *bind;
134     TAILQ_FOREACH(bind, bindings, bindings) {
135         if (bind->input_type != B_KEYBOARD)
136             continue;
137
138         /* The easy case: the user specified a keycode directly. */
139         if (bind->keycode > 0) {
140             grab_keycode_for_binding(conn, bind, bind->keycode);
141             continue;
142         }
143
144         for (uint32_t i = 0; i < bind->number_keycodes; i++)
145             grab_keycode_for_binding(conn, bind, bind->translated_to[i]);
146     }
147 }
148
149 /*
150  * Returns a pointer to the Binding with the specified modifiers and
151  * keycode or NULL if no such binding exists.
152  *
153  */
154 static Binding *get_binding(i3_event_state_mask_t state_filtered, bool is_release, uint16_t input_code, input_type_t input_type) {
155     Binding *bind;
156
157     if (!is_release) {
158         /* On a press event, we first reset all B_UPON_KEYRELEASE_IGNORE_MODS
159          * bindings back to B_UPON_KEYRELEASE */
160         TAILQ_FOREACH(bind, bindings, bindings) {
161             if (bind->input_type != input_type)
162                 continue;
163             if (bind->release == B_UPON_KEYRELEASE_IGNORE_MODS)
164                 bind->release = B_UPON_KEYRELEASE;
165         }
166     }
167
168     const uint32_t xkb_group_state = (state_filtered & 0xFFFF0000);
169     const uint32_t modifiers_state = (state_filtered & 0x0000FFFF);
170     TAILQ_FOREACH(bind, bindings, bindings) {
171         const uint32_t xkb_group_mask = (bind->event_state_mask & 0xFFFF0000);
172         /* modifiers_mask is a special case: a value of 0 does not mean “match all”,
173          * but rather “match exactly when no modifiers are present”. */
174         const uint32_t modifiers_mask = (bind->event_state_mask & 0x0000FFFF);
175         const bool groups_match = ((xkb_group_state & xkb_group_mask) == xkb_group_mask);
176         bool mods_match;
177         if (modifiers_mask == 0) {
178             /* Verify no modifiers are pressed. A bitwise AND would lead to
179              * false positives, see issue #2002. */
180             mods_match = (modifiers_state == 0);
181         } else {
182             mods_match = ((modifiers_state & modifiers_mask) == modifiers_mask);
183         }
184         const bool state_matches = (groups_match && mods_match);
185
186         DLOG("binding groups_match = %s, mods_match = %s, state_matches = %s\n",
187              (groups_match ? "yes" : "no"),
188              (mods_match ? "yes" : "no"),
189              (state_matches ? "yes" : "no"));
190         /* First compare the state_filtered (unless this is a
191          * B_UPON_KEYRELEASE_IGNORE_MODS binding and this is a KeyRelease
192          * event) */
193         if (bind->input_type != input_type)
194             continue;
195         if (!state_matches &&
196             (bind->release != B_UPON_KEYRELEASE_IGNORE_MODS ||
197              !is_release))
198             continue;
199
200         /* For keyboard bindings where a symbol was specified by the user, we
201          * need to look in the array of translated keycodes for the event’s
202          * keycode */
203         if (input_type == B_KEYBOARD && bind->symbol != NULL) {
204             xcb_keycode_t input_keycode = (xcb_keycode_t)input_code;
205             if (memmem(bind->translated_to,
206                        bind->number_keycodes * sizeof(xcb_keycode_t),
207                        &input_keycode, sizeof(xcb_keycode_t)) == NULL)
208                 continue;
209         } else {
210             /* This case is easier: The user specified a keycode */
211             if (bind->keycode != input_code)
212                 continue;
213         }
214
215         /* If this binding is a release binding, it matches the key which the
216          * user pressed. We therefore mark it as B_UPON_KEYRELEASE_IGNORE_MODS
217          * for later, so that the user can release the modifiers before the
218          * actual key or button and the release event will still be matched. */
219         if (bind->release == B_UPON_KEYRELEASE && !is_release)
220             bind->release = B_UPON_KEYRELEASE_IGNORE_MODS;
221
222         /* Check if the binding is for a press or a release event */
223         if ((bind->release == B_UPON_KEYPRESS && is_release) ||
224             (bind->release >= B_UPON_KEYRELEASE && !is_release))
225             continue;
226
227         break;
228     }
229
230     return (bind == TAILQ_END(bindings) ? NULL : bind);
231 }
232
233 /*
234  * Returns a pointer to the Binding that matches the given xcb button or key
235  * event or NULL if no such binding exists.
236  *
237  */
238 Binding *get_binding_from_xcb_event(xcb_generic_event_t *event) {
239     const bool is_release = (event->response_type == XCB_KEY_RELEASE ||
240                              event->response_type == XCB_BUTTON_RELEASE);
241
242     const input_type_t input_type = ((event->response_type == XCB_BUTTON_RELEASE ||
243                                       event->response_type == XCB_BUTTON_PRESS)
244                                          ? B_MOUSE
245                                          : B_KEYBOARD);
246
247     const uint16_t event_state = ((xcb_key_press_event_t *)event)->state;
248     const uint16_t event_detail = ((xcb_key_press_event_t *)event)->detail;
249
250     /* Remove the numlock bit */
251     i3_event_state_mask_t state_filtered = event_state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
252     DLOG("(removed numlock, state = 0x%x)\n", state_filtered);
253     /* Transform the keyboard_group from bit 13 and bit 14 into an
254      * i3_xkb_group_mask_t, so that get_binding() can just bitwise AND the
255      * configured bindings against |state_filtered|.
256      *
257      * These bits are only set because we set the XKB client flags
258      * XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE and
259      * XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED. See also doc/kbproto
260      * section 2.2.2:
261      * http://www.x.org/releases/X11R7.7/doc/kbproto/xkbproto.html#Computing_A_State_Field_from_an_XKB_State */
262     switch ((event_state & 0x6000) >> 13) {
263         case XCB_XKB_GROUP_1:
264             state_filtered |= (I3_XKB_GROUP_MASK_1 << 16);
265             break;
266         case XCB_XKB_GROUP_2:
267             state_filtered |= (I3_XKB_GROUP_MASK_2 << 16);
268             break;
269         case XCB_XKB_GROUP_3:
270             state_filtered |= (I3_XKB_GROUP_MASK_3 << 16);
271             break;
272         case XCB_XKB_GROUP_4:
273             state_filtered |= (I3_XKB_GROUP_MASK_4 << 16);
274             break;
275     }
276     state_filtered &= ~0x6000;
277     DLOG("(transformed keyboard group, state = 0x%x)\n", state_filtered);
278     return get_binding(state_filtered, is_release, event_detail, input_type);
279 }
280
281 struct resolve {
282     /* The binding which we are resolving. */
283     Binding *bind;
284
285     /* |bind|’s keysym (translated to xkb_keysym_t), e.g. XKB_KEY_R. */
286     xkb_keysym_t keysym;
287
288     /* The xkb state built from the user-provided modifiers and group. */
289     struct xkb_state *xkb_state;
290
291     /* Like |xkb_state|, just without the shift modifier, if shift was specified. */
292     struct xkb_state *xkb_state_no_shift;
293 };
294
295 /*
296  * add_keycode_if_matches is called for each keycode in the keymap and will add
297  * the keycode to |data->bind| if the keycode can result in the keysym
298  * |data->resolving|.
299  *
300  */
301 static void add_keycode_if_matches(struct xkb_keymap *keymap, xkb_keycode_t key, void *data) {
302     const struct resolve *resolving = data;
303     xkb_keysym_t sym = xkb_state_key_get_one_sym(resolving->xkb_state, key);
304     if (sym != resolving->keysym) {
305         /* Check if Shift was specified, and try resolving the symbol without
306          * shift, so that “bindsym $mod+Shift+a nop” actually works. */
307         const xkb_layout_index_t layout = xkb_state_key_get_layout(resolving->xkb_state, key);
308         if (layout == XKB_LAYOUT_INVALID)
309             return;
310         if (xkb_state_key_get_level(resolving->xkb_state, key, layout) > 1)
311             return;
312         sym = xkb_state_key_get_one_sym(resolving->xkb_state_no_shift, key);
313         if (sym != resolving->keysym)
314             return;
315     }
316     Binding *bind = resolving->bind;
317     bind->number_keycodes++;
318     bind->translated_to = srealloc(bind->translated_to,
319                                    (sizeof(xcb_keycode_t) *
320                                     bind->number_keycodes));
321     bind->translated_to[bind->number_keycodes - 1] = key;
322 }
323
324 /*
325  * Translates keysymbols to keycodes for all bindings which use keysyms.
326  *
327  */
328 void translate_keysyms(void) {
329     struct xkb_state *dummy_state = xkb_state_new(xkb_keymap);
330     if (dummy_state == NULL) {
331         ELOG("Could not create XKB state, cannot translate keysyms.\n");
332         return;
333     }
334
335     struct xkb_state *dummy_state_no_shift = xkb_state_new(xkb_keymap);
336     if (dummy_state_no_shift == NULL) {
337         ELOG("Could not create XKB state, cannot translate keysyms.\n");
338         return;
339     }
340
341     bool has_errors = false;
342     Binding *bind;
343     TAILQ_FOREACH(bind, bindings, bindings) {
344         if (bind->input_type == B_MOUSE) {
345             char *endptr;
346             long button = strtol(bind->symbol + (sizeof("button") - 1), &endptr, 10);
347             bind->keycode = button;
348
349             if (button == LONG_MAX || button == LONG_MIN || button < 0 || *endptr != '\0' || endptr == bind->symbol)
350                 ELOG("Could not translate string to button: \"%s\"\n", bind->symbol);
351
352             continue;
353         }
354
355         if (bind->keycode > 0)
356             continue;
357
358         /* We need to translate the symbol to a keycode */
359         const xkb_keysym_t keysym = xkb_keysym_from_name(bind->symbol, XKB_KEYSYM_NO_FLAGS);
360         if (keysym == XKB_KEY_NoSymbol) {
361             ELOG("Could not translate string to key symbol: \"%s\"\n",
362                  bind->symbol);
363             continue;
364         }
365
366         xkb_layout_index_t group = XCB_XKB_GROUP_1;
367         if ((bind->event_state_mask >> 16) & I3_XKB_GROUP_MASK_2)
368             group = XCB_XKB_GROUP_2;
369         else if ((bind->event_state_mask >> 16) & I3_XKB_GROUP_MASK_3)
370             group = XCB_XKB_GROUP_3;
371         else if ((bind->event_state_mask >> 16) & I3_XKB_GROUP_MASK_4)
372             group = XCB_XKB_GROUP_4;
373
374         DLOG("group = %d, event_state_mask = %d, &2 = %s, &3 = %s, &4 = %s\n", group,
375              bind->event_state_mask,
376              (bind->event_state_mask & I3_XKB_GROUP_MASK_2) ? "yes" : "no",
377              (bind->event_state_mask & I3_XKB_GROUP_MASK_3) ? "yes" : "no",
378              (bind->event_state_mask & I3_XKB_GROUP_MASK_4) ? "yes" : "no");
379         (void)xkb_state_update_mask(
380             dummy_state,
381             (bind->event_state_mask & 0x1FFF) /* xkb_mod_mask_t base_mods, */,
382             0 /* xkb_mod_mask_t latched_mods, */,
383             0 /* xkb_mod_mask_t locked_mods, */,
384             0 /* xkb_layout_index_t base_group, */,
385             0 /* xkb_layout_index_t latched_group, */,
386             group /* xkb_layout_index_t locked_group, */);
387
388         (void)xkb_state_update_mask(
389             dummy_state_no_shift,
390             (bind->event_state_mask & 0x1FFF) ^ XCB_KEY_BUT_MASK_SHIFT /* xkb_mod_mask_t base_mods, */,
391             0 /* xkb_mod_mask_t latched_mods, */,
392             0 /* xkb_mod_mask_t locked_mods, */,
393             0 /* xkb_layout_index_t base_group, */,
394             0 /* xkb_layout_index_t latched_group, */,
395             group /* xkb_layout_index_t locked_group, */);
396
397         struct resolve resolving = {
398             .bind = bind,
399             .keysym = keysym,
400             .xkb_state = dummy_state,
401             .xkb_state_no_shift = dummy_state_no_shift,
402         };
403         FREE(bind->translated_to);
404         bind->number_keycodes = 0;
405         xkb_keymap_key_for_each(xkb_keymap, add_keycode_if_matches, &resolving);
406         char *keycodes = sstrdup("");
407         for (uint32_t n = 0; n < bind->number_keycodes; n++) {
408             char *tmp;
409             sasprintf(&tmp, "%s %d", keycodes, bind->translated_to[n]);
410             free(keycodes);
411             keycodes = tmp;
412
413             /* check for duplicate bindings */
414             Binding *check;
415             TAILQ_FOREACH(check, bindings, bindings) {
416                 if (check == bind)
417                     continue;
418                 if (check->symbol != NULL)
419                     continue;
420                 if (check->keycode != bind->translated_to[n] ||
421                     check->event_state_mask != bind->event_state_mask ||
422                     check->release != bind->release)
423                     continue;
424                 has_errors = true;
425                 ELOG("Duplicate keybinding in config file:\n  keysym = %s, keycode = %d, state_mask = 0x%x\n", bind->symbol, check->keycode, bind->event_state_mask);
426             }
427         }
428         DLOG("state=0x%x, cfg=\"%s\", sym=0x%x → keycodes%s (%d)\n",
429              bind->event_state_mask, bind->symbol, keysym, keycodes, bind->number_keycodes);
430         free(keycodes);
431     }
432
433     xkb_state_unref(dummy_state);
434     xkb_state_unref(dummy_state_no_shift);
435
436     if (has_errors) {
437         start_config_error_nagbar(current_configpath, true);
438     }
439 }
440
441 /*
442  * Switches the key bindings to the given mode, if the mode exists
443  *
444  */
445 void switch_mode(const char *new_mode) {
446     struct Mode *mode;
447
448     DLOG("Switching to mode %s\n", new_mode);
449
450     SLIST_FOREACH(mode, &modes, modes) {
451         if (strcasecmp(mode->name, new_mode) != 0)
452             continue;
453
454         ungrab_all_keys(conn);
455         bindings = mode->bindings;
456         translate_keysyms();
457         grab_all_keys(conn);
458
459         char *event_msg;
460         sasprintf(&event_msg, "{\"change\":\"%s\", \"pango_markup\":%s}",
461                   mode->name, (mode->pango_markup ? "true" : "false"));
462
463         ipc_send_event("mode", I3_IPC_EVENT_MODE, event_msg);
464         FREE(event_msg);
465
466         return;
467     }
468
469     ELOG("ERROR: Mode not found\n");
470 }
471
472 static int reorder_binding_cmp(const void *a, const void *b) {
473     Binding *first = *((Binding **)a);
474     Binding *second = *((Binding **)b);
475     if (first->event_state_mask < second->event_state_mask) {
476         return 1;
477     } else if (first->event_state_mask == second->event_state_mask) {
478         return 0;
479     } else {
480         return -1;
481     }
482 }
483
484 static void reorder_bindings_of_mode(struct Mode *mode) {
485     /* Copy the bindings into an array, so that we can use qsort(3). */
486     int n = 0;
487     Binding *current;
488     TAILQ_FOREACH(current, mode->bindings, bindings) {
489         n++;
490     }
491     Binding **tmp = scalloc(n, sizeof(Binding *));
492     n = 0;
493     TAILQ_FOREACH(current, mode->bindings, bindings) {
494         tmp[n++] = current;
495     }
496
497     qsort(tmp, n, sizeof(Binding *), reorder_binding_cmp);
498
499     struct bindings_head *reordered = scalloc(1, sizeof(struct bindings_head));
500     TAILQ_INIT(reordered);
501     for (int i = 0; i < n; i++) {
502         current = tmp[i];
503         TAILQ_REMOVE(mode->bindings, current, bindings);
504         TAILQ_INSERT_TAIL(reordered, current, bindings);
505     }
506     free(tmp);
507     assert(TAILQ_EMPTY(mode->bindings));
508     /* Free the old bindings_head, which is now empty. */
509     free(mode->bindings);
510     mode->bindings = reordered;
511 }
512
513 /*
514  * Reorders bindings by event_state_mask descendingly so that get_binding()
515  * correctly matches more specific bindings before more generic bindings. Take
516  * the following binding configuration as an example:
517  *
518  *   bindsym n nop lower-case n pressed
519  *   bindsym Shift+n nop upper-case n pressed
520  *
521  * Without reordering, the first binding’s event_state_mask of 0x0 would match
522  * the actual event_stat_mask of 0x1 and hence trigger instead of the second
523  * keybinding.
524  *
525  */
526 void reorder_bindings(void) {
527     struct Mode *mode;
528     SLIST_FOREACH(mode, &modes, modes) {
529         const bool current_mode = (mode->bindings == bindings);
530         reorder_bindings_of_mode(mode);
531         if (current_mode)
532             bindings = mode->bindings;
533     }
534 }
535
536 /*
537  * Checks for duplicate key bindings (the same keycode or keysym is configured
538  * more than once). If a duplicate binding is found, a message is printed to
539  * stderr and the has_errors variable is set to true, which will start
540  * i3-nagbar.
541  *
542  */
543 void check_for_duplicate_bindings(struct context *context) {
544     Binding *bind, *current;
545     TAILQ_FOREACH(current, bindings, bindings) {
546         TAILQ_FOREACH(bind, bindings, bindings) {
547             /* Abort when we reach the current keybinding, only check the
548              * bindings before */
549             if (bind == current)
550                 break;
551
552             /* Check if the input types are different */
553             if (bind->input_type != current->input_type)
554                 continue;
555
556             /* Check if one is using keysym while the other is using bindsym.
557              * If so, skip. */
558             if ((bind->symbol == NULL && current->symbol != NULL) ||
559                 (bind->symbol != NULL && current->symbol == NULL))
560                 continue;
561
562             /* If bind is NULL, current has to be NULL, too (see above).
563              * If the keycodes differ, it can't be a duplicate. */
564             if (bind->symbol != NULL &&
565                 strcasecmp(bind->symbol, current->symbol) != 0)
566                 continue;
567
568             /* Check if the keycodes or modifiers are different. If so, they
569              * can't be duplicate */
570             if (bind->keycode != current->keycode ||
571                 bind->event_state_mask != current->event_state_mask ||
572                 bind->release != current->release)
573                 continue;
574
575             context->has_errors = true;
576             if (current->keycode != 0) {
577                 ELOG("Duplicate keybinding in config file:\n  state mask 0x%x with keycode %d, command \"%s\"\n",
578                      current->event_state_mask, current->keycode, current->command);
579             } else {
580                 ELOG("Duplicate keybinding in config file:\n  state mask 0x%x with keysym %s, command \"%s\"\n",
581                      current->event_state_mask, current->symbol, current->command);
582             }
583         }
584     }
585 }
586
587 /*
588  * Creates a dynamically allocated copy of bind.
589  */
590 static Binding *binding_copy(Binding *bind) {
591     Binding *ret = smalloc(sizeof(Binding));
592     *ret = *bind;
593     if (bind->symbol != NULL)
594         ret->symbol = sstrdup(bind->symbol);
595     if (bind->command != NULL)
596         ret->command = sstrdup(bind->command);
597     if (bind->translated_to != NULL) {
598         ret->translated_to = smalloc(sizeof(xcb_keycode_t) * bind->number_keycodes);
599         memcpy(ret->translated_to, bind->translated_to, sizeof(xcb_keycode_t) * bind->number_keycodes);
600     }
601     return ret;
602 }
603
604 /*
605  * Frees the binding. If bind is null, it simply returns.
606  */
607 void binding_free(Binding *bind) {
608     if (bind == NULL) {
609         return;
610     }
611
612     FREE(bind->symbol);
613     FREE(bind->translated_to);
614     FREE(bind->command);
615     FREE(bind);
616 }
617
618 /*
619  * Runs the given binding and handles parse errors. If con is passed, it will
620  * execute the command binding with that container selected by criteria.
621  * Returns a CommandResult for running the binding's command. Caller should
622  * render tree if needs_tree_render is true. Free with command_result_free().
623  *
624  */
625 CommandResult *run_binding(Binding *bind, Con *con) {
626     char *command;
627
628     /* We need to copy the binding and command since “reload” may be part of
629      * the command, and then the memory that bind points to may not contain the
630      * same data anymore. */
631     if (con == NULL)
632         command = sstrdup(bind->command);
633     else
634         sasprintf(&command, "[con_id=\"%p\"] %s", con, bind->command);
635
636     Binding *bind_cp = binding_copy(bind);
637     CommandResult *result = parse_command(command, NULL);
638     free(command);
639
640     if (result->needs_tree_render)
641         tree_render();
642
643     if (result->parse_error) {
644         char *pageraction;
645         sasprintf(&pageraction, "i3-sensible-pager \"%s\"\n", errorfilename);
646         char *argv[] = {
647             NULL, /* will be replaced by the executable path */
648             "-f",
649             config.font.pattern,
650             "-t",
651             "error",
652             "-m",
653             "The configured command for this shortcut could not be run successfully.",
654             "-b",
655             "show errors",
656             pageraction,
657             NULL};
658         start_nagbar(&command_error_nagbar_pid, argv);
659         free(pageraction);
660     }
661
662     ipc_send_binding_event("run", bind_cp);
663     binding_free(bind_cp);
664
665     return result;
666 }
667
668 static int fill_rmlvo_from_root(struct xkb_rule_names *xkb_names) {
669     xcb_intern_atom_reply_t *atom_reply;
670     size_t content_max_words = 256;
671
672     xcb_window_t root = root_screen->root;
673
674     atom_reply = xcb_intern_atom_reply(
675         conn, xcb_intern_atom(conn, 0, strlen("_XKB_RULES_NAMES"), "_XKB_RULES_NAMES"), NULL);
676     if (atom_reply == NULL)
677         return -1;
678
679     xcb_get_property_cookie_t prop_cookie;
680     xcb_get_property_reply_t *prop_reply;
681     prop_cookie = xcb_get_property_unchecked(conn, false, root, atom_reply->atom,
682                                              XCB_GET_PROPERTY_TYPE_ANY, 0, content_max_words);
683     prop_reply = xcb_get_property_reply(conn, prop_cookie, NULL);
684     if (prop_reply == NULL) {
685         free(atom_reply);
686         return -1;
687     }
688     if (xcb_get_property_value_length(prop_reply) > 0 && prop_reply->bytes_after > 0) {
689         /* We received an incomplete value. Ask again but with a properly
690          * adjusted size. */
691         content_max_words += ceil(prop_reply->bytes_after / 4.0);
692         /* Repeat the request, with adjusted size */
693         free(prop_reply);
694         prop_cookie = xcb_get_property_unchecked(conn, false, root, atom_reply->atom,
695                                                  XCB_GET_PROPERTY_TYPE_ANY, 0, content_max_words);
696         prop_reply = xcb_get_property_reply(conn, prop_cookie, NULL);
697         if (prop_reply == NULL) {
698             free(atom_reply);
699             return -1;
700         }
701     }
702     if (xcb_get_property_value_length(prop_reply) == 0) {
703         free(atom_reply);
704         free(prop_reply);
705         return -1;
706     }
707
708     const char *walk = (const char *)xcb_get_property_value(prop_reply);
709     int remaining = xcb_get_property_value_length(prop_reply);
710     for (int i = 0; i < 5 && remaining > 0; i++) {
711         const int len = strnlen(walk, remaining);
712         remaining -= len;
713         switch (i) {
714             case 0:
715                 sasprintf((char **)&(xkb_names->rules), "%.*s", len, walk);
716                 break;
717             case 1:
718                 sasprintf((char **)&(xkb_names->model), "%.*s", len, walk);
719                 break;
720             case 2:
721                 sasprintf((char **)&(xkb_names->layout), "%.*s", len, walk);
722                 break;
723             case 3:
724                 sasprintf((char **)&(xkb_names->variant), "%.*s", len, walk);
725                 break;
726             case 4:
727                 sasprintf((char **)&(xkb_names->options), "%.*s", len, walk);
728                 break;
729         }
730         DLOG("component %d of _XKB_RULES_NAMES is \"%.*s\"\n", i, len, walk);
731         walk += (len + 1);
732     }
733
734     free(atom_reply);
735     free(prop_reply);
736     return 0;
737 }
738
739 /*
740  * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
741  *
742  */
743 bool load_keymap(void) {
744     if (xkb_context == NULL) {
745         if ((xkb_context = xkb_context_new(0)) == NULL) {
746             ELOG("Could not create xkbcommon context\n");
747             return false;
748         }
749     }
750
751     struct xkb_keymap *new_keymap = NULL;
752     int32_t device_id;
753     if (xkb_supported && (device_id = xkb_x11_get_core_keyboard_device_id(conn)) > -1) {
754         if ((new_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL) {
755             ELOG("xkb_x11_keymap_new_from_device failed\n");
756             return false;
757         }
758     } else {
759         /* Likely there is no XKB support on this server, possibly because it
760          * is a VNC server. */
761         LOG("No XKB / core keyboard device? Assembling keymap from local RMLVO.\n");
762         struct xkb_rule_names names = {
763             .rules = NULL,
764             .model = NULL,
765             .layout = NULL,
766             .variant = NULL,
767             .options = NULL};
768         if (fill_rmlvo_from_root(&names) == -1) {
769             ELOG("Could not get _XKB_RULES_NAMES atom from root window, falling back to defaults.\n");
770             if ((new_keymap = xkb_keymap_new_from_names(xkb_context, &names, 0)) == NULL) {
771                 ELOG("xkb_keymap_new_from_names(NULL) failed\n");
772                 return false;
773             }
774         }
775         new_keymap = xkb_keymap_new_from_names(xkb_context, &names, 0);
776         free((char *)names.rules);
777         free((char *)names.model);
778         free((char *)names.layout);
779         free((char *)names.variant);
780         free((char *)names.options);
781         if (new_keymap == NULL) {
782             ELOG("xkb_keymap_new_from_names(RMLVO) failed\n");
783             return false;
784         }
785     }
786     xkb_keymap_unref(xkb_keymap);
787     xkb_keymap = new_keymap;
788
789     return true;
790 }