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