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