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