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