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