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