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