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