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