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