]> git.sur5r.net Git - i3/i3/blob - src/bindings.c
Use safe wrappers wherever possible
[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
13 pid_t command_error_nagbar_pid = -1;
14
15 /*
16  * The name of the default mode.
17  *
18  */
19 const char *DEFAULT_BINDING_MODE = "default";
20
21 /*
22  * Returns the mode specified by `name` or creates a new mode and adds it to
23  * the list of modes.
24  *
25  */
26 static struct Mode *mode_from_name(const char *name) {
27     struct Mode *mode;
28
29     /* Try to find the mode in the list of modes and return it */
30     SLIST_FOREACH(mode, &modes, modes) {
31         if (strcmp(mode->name, name) == 0)
32             return mode;
33     }
34
35     /* If the mode was not found, create a new one */
36     mode = scalloc(1, sizeof(struct Mode));
37     mode->name = sstrdup(name);
38     mode->bindings = scalloc(1, sizeof(struct bindings_head));
39     TAILQ_INIT(mode->bindings);
40     SLIST_INSERT_HEAD(&modes, mode, modes);
41
42     return mode;
43 }
44
45 /*
46  * Adds a binding from config parameters given as strings and returns a
47  * pointer to the binding structure. Returns NULL if the input code could not
48  * be parsed.
49  *
50  */
51 Binding *configure_binding(const char *bindtype, const char *modifiers, const char *input_code,
52                            const char *release, const char *border, const char *whole_window,
53                            const char *command, const char *modename) {
54     Binding *new_binding = scalloc(1, sizeof(Binding));
55     DLOG("bindtype %s, modifiers %s, input code %s, release %s\n", bindtype, modifiers, input_code, release);
56     new_binding->release = (release != NULL ? B_UPON_KEYRELEASE : B_UPON_KEYPRESS);
57     new_binding->border = (border != NULL);
58     new_binding->whole_window = (whole_window != NULL);
59     if (strcmp(bindtype, "bindsym") == 0) {
60         new_binding->input_type = (strncasecmp(input_code, "button", (sizeof("button") - 1)) == 0
61                                        ? B_MOUSE
62                                        : B_KEYBOARD);
63
64         new_binding->symbol = sstrdup(input_code);
65     } else {
66         char *endptr;
67         long keycode = strtol(input_code, &endptr, 10);
68         new_binding->keycode = keycode;
69         new_binding->input_type = B_KEYBOARD;
70         if (keycode == LONG_MAX || keycode == LONG_MIN || keycode < 0 || *endptr != '\0' || endptr == input_code) {
71             ELOG("Could not parse \"%s\" as an input code, ignoring this binding.\n", input_code);
72             FREE(new_binding);
73             return NULL;
74         }
75     }
76     new_binding->mods = modifiers_from_str(modifiers);
77     new_binding->command = sstrdup(command);
78
79     struct Mode *mode = mode_from_name(modename);
80     TAILQ_INSERT_TAIL(mode->bindings, new_binding, bindings);
81
82     return new_binding;
83 }
84
85 static void grab_keycode_for_binding(xcb_connection_t *conn, Binding *bind, uint32_t keycode) {
86     if (bind->input_type != B_KEYBOARD)
87         return;
88
89     DLOG("Grabbing %d with modifiers %d (with mod_mask_lock %d)\n", keycode, bind->mods, bind->mods | XCB_MOD_MASK_LOCK);
90 /* Grab the key in all combinations */
91 #define GRAB_KEY(modifier)                                                                       \
92     do {                                                                                         \
93         xcb_grab_key(conn, 0, root, modifier, keycode, XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC); \
94     } while (0)
95     int mods = bind->mods;
96     if ((bind->mods & BIND_MODE_SWITCH) != 0) {
97         mods &= ~BIND_MODE_SWITCH;
98         if (mods == 0)
99             mods = XCB_MOD_MASK_ANY;
100     }
101     GRAB_KEY(mods);
102     GRAB_KEY(mods | xcb_numlock_mask);
103     GRAB_KEY(mods | XCB_MOD_MASK_LOCK);
104     GRAB_KEY(mods | xcb_numlock_mask | XCB_MOD_MASK_LOCK);
105 }
106
107 /*
108  * Grab the bound keys (tell X to send us keypress events for those keycodes)
109  *
110  */
111 void grab_all_keys(xcb_connection_t *conn, bool bind_mode_switch) {
112     Binding *bind;
113     TAILQ_FOREACH(bind, bindings, bindings) {
114         if (bind->input_type != B_KEYBOARD ||
115             (bind_mode_switch && (bind->mods & BIND_MODE_SWITCH) == 0) ||
116             (!bind_mode_switch && (bind->mods & BIND_MODE_SWITCH) != 0))
117             continue;
118
119         /* The easy case: the user specified a keycode directly. */
120         if (bind->keycode > 0) {
121             grab_keycode_for_binding(conn, bind, bind->keycode);
122             continue;
123         }
124
125         xcb_keycode_t *walk = bind->translated_to;
126         for (uint32_t i = 0; i < bind->number_keycodes; i++)
127             grab_keycode_for_binding(conn, bind, *walk++);
128     }
129 }
130
131 /*
132  * Returns a pointer to the Binding with the specified modifiers and
133  * keycode or NULL if no such binding exists.
134  *
135  */
136 static Binding *get_binding(uint16_t modifiers, bool is_release, uint16_t input_code, input_type_t input_type) {
137     Binding *bind;
138
139     if (!is_release) {
140         /* On a press event, we first reset all B_UPON_KEYRELEASE_IGNORE_MODS
141          * bindings back to B_UPON_KEYRELEASE */
142         TAILQ_FOREACH(bind, bindings, bindings) {
143             if (bind->input_type != input_type)
144                 continue;
145             if (bind->release == B_UPON_KEYRELEASE_IGNORE_MODS)
146                 bind->release = B_UPON_KEYRELEASE;
147         }
148     }
149
150     TAILQ_FOREACH(bind, bindings, bindings) {
151         /* First compare the modifiers (unless this is a
152          * B_UPON_KEYRELEASE_IGNORE_MODS binding and this is a KeyRelease
153          * event) */
154         if (bind->input_type != input_type)
155             continue;
156         if (bind->mods != modifiers &&
157             (bind->release != B_UPON_KEYRELEASE_IGNORE_MODS ||
158              !is_release))
159             continue;
160
161         /* For keyboard bindings where a symbol was specified by the user, we
162          * need to look in the array of translated keycodes for the event’s
163          * keycode */
164         if (input_type == B_KEYBOARD && bind->symbol != NULL) {
165             xcb_keycode_t input_keycode = (xcb_keycode_t)input_code;
166             if (memmem(bind->translated_to,
167                        bind->number_keycodes * sizeof(xcb_keycode_t),
168                        &input_keycode, sizeof(xcb_keycode_t)) == NULL)
169                 continue;
170         } else {
171             /* This case is easier: The user specified a keycode */
172             if (bind->keycode != input_code)
173                 continue;
174         }
175
176         /* If this binding is a release binding, it matches the key which the
177          * user pressed. We therefore mark it as B_UPON_KEYRELEASE_IGNORE_MODS
178          * for later, so that the user can release the modifiers before the
179          * actual key or button and the release event will still be matched. */
180         if (bind->release == B_UPON_KEYRELEASE && !is_release)
181             bind->release = B_UPON_KEYRELEASE_IGNORE_MODS;
182
183         /* Check if the binding is for a press or a release event */
184         if ((bind->release == B_UPON_KEYPRESS && is_release) ||
185             (bind->release >= B_UPON_KEYRELEASE && !is_release))
186             continue;
187
188         break;
189     }
190
191     return (bind == TAILQ_END(bindings) ? NULL : bind);
192 }
193
194 /*
195  * Returns a pointer to the Binding that matches the given xcb button or key
196  * event or NULL if no such binding exists.
197  *
198  */
199 Binding *get_binding_from_xcb_event(xcb_generic_event_t *event) {
200     bool is_release = (event->response_type == XCB_KEY_RELEASE || event->response_type == XCB_BUTTON_RELEASE);
201
202     input_type_t input_type = ((event->response_type == XCB_BUTTON_RELEASE || event->response_type == XCB_BUTTON_PRESS)
203                                    ? B_MOUSE
204                                    : B_KEYBOARD);
205
206     uint16_t event_state = ((xcb_key_press_event_t *)event)->state;
207     uint16_t event_detail = ((xcb_key_press_event_t *)event)->detail;
208
209     /* Remove the numlock bit, all other bits are modifiers we can bind to */
210     uint16_t state_filtered = event_state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
211     DLOG("(removed numlock, state = %d)\n", state_filtered);
212     /* Only use the lower 8 bits of the state (modifier masks) so that mouse
213      * button masks are filtered out */
214     state_filtered &= 0xFF;
215     DLOG("(removed upper 8 bits, state = %d)\n", state_filtered);
216
217     if (xkb_current_group == XCB_XKB_GROUP_2)
218         state_filtered |= BIND_MODE_SWITCH;
219
220     DLOG("(checked mode_switch, state %d)\n", state_filtered);
221
222     /* Find the binding */
223     Binding *bind = get_binding(state_filtered, is_release, event_detail, input_type);
224
225     /* No match? Then the user has Mode_switch enabled but does not have a
226      * specific keybinding. Fall back to the default keybindings (without
227      * Mode_switch). Makes it much more convenient for users of a hybrid
228      * layout (like ru). */
229     if (bind == NULL) {
230         state_filtered &= ~(BIND_MODE_SWITCH);
231         DLOG("no match, new state_filtered = %d\n", state_filtered);
232         if ((bind = get_binding(state_filtered, is_release, event_detail, input_type)) == NULL) {
233             /* This is not a real error since we can have release and
234              * non-release bindings. On a press event for which there is only a
235              * !release-binding, but no release-binding, the corresponding
236              * release event will trigger this. No problem, though. */
237             DLOG("Could not lookup key binding (modifiers %d, keycode %d)\n",
238                  state_filtered, event_detail);
239         }
240     }
241
242     return bind;
243 }
244
245 /*
246  * Translates keysymbols to keycodes for all bindings which use keysyms.
247  *
248  */
249 void translate_keysyms(void) {
250     Binding *bind;
251     xcb_keysym_t keysym;
252     int col;
253     xcb_keycode_t i, min_keycode, max_keycode;
254
255     min_keycode = xcb_get_setup(conn)->min_keycode;
256     max_keycode = xcb_get_setup(conn)->max_keycode;
257
258     TAILQ_FOREACH(bind, bindings, bindings) {
259         if (bind->input_type == B_MOUSE) {
260             char *endptr;
261             long button = strtol(bind->symbol + (sizeof("button") - 1), &endptr, 10);
262             bind->keycode = button;
263
264             if (button == LONG_MAX || button == LONG_MIN || button < 0 || *endptr != '\0' || endptr == bind->symbol)
265                 ELOG("Could not translate string to button: \"%s\"\n", bind->symbol);
266
267             continue;
268         }
269
270         if (bind->keycode > 0)
271             continue;
272
273         /* We need to translate the symbol to a keycode */
274         keysym = xkb_keysym_from_name(bind->symbol, XKB_KEYSYM_NO_FLAGS);
275         if (keysym == XKB_KEY_NoSymbol) {
276             ELOG("Could not translate string to key symbol: \"%s\"\n",
277                  bind->symbol);
278             continue;
279         }
280
281         /* Base column we use for looking up key symbols. We always consider
282          * the base column and the corresponding shift column, so without
283          * mode_switch, we look in 0 and 1, with mode_switch we look in 2 and
284          * 3. */
285         col = (bind->mods & BIND_MODE_SWITCH ? 2 : 0);
286
287         FREE(bind->translated_to);
288         bind->number_keycodes = 0;
289
290         for (i = min_keycode; i && i <= max_keycode; i++) {
291             if ((xcb_key_symbols_get_keysym(keysyms, i, col) != keysym) &&
292                 (xcb_key_symbols_get_keysym(keysyms, i, col + 1) != keysym))
293                 continue;
294             bind->number_keycodes++;
295             bind->translated_to = srealloc(bind->translated_to,
296                                            (sizeof(xcb_keycode_t) *
297                                             bind->number_keycodes));
298             bind->translated_to[bind->number_keycodes - 1] = i;
299         }
300
301         DLOG("Translated symbol \"%s\" to %d keycode (mods %d)\n", bind->symbol,
302              bind->number_keycodes, bind->mods);
303     }
304 }
305
306 /*
307  * Switches the key bindings to the given mode, if the mode exists
308  *
309  */
310 void switch_mode(const char *new_mode) {
311     struct Mode *mode;
312
313     DLOG("Switching to mode %s\n", new_mode);
314
315     SLIST_FOREACH(mode, &modes, modes) {
316         if (strcasecmp(mode->name, new_mode) != 0)
317             continue;
318
319         ungrab_all_keys(conn);
320         bindings = mode->bindings;
321         translate_keysyms();
322         grab_all_keys(conn, false);
323
324         char *event_msg;
325         sasprintf(&event_msg, "{\"change\":\"%s\"}", mode->name);
326
327         ipc_send_event("mode", I3_IPC_EVENT_MODE, event_msg);
328         FREE(event_msg);
329
330         return;
331     }
332
333     ELOG("ERROR: Mode not found\n");
334 }
335
336 /*
337  * Checks for duplicate key bindings (the same keycode or keysym is configured
338  * more than once). If a duplicate binding is found, a message is printed to
339  * stderr and the has_errors variable is set to true, which will start
340  * i3-nagbar.
341  *
342  */
343 void check_for_duplicate_bindings(struct context *context) {
344     Binding *bind, *current;
345     TAILQ_FOREACH(current, bindings, bindings) {
346         TAILQ_FOREACH(bind, bindings, bindings) {
347             /* Abort when we reach the current keybinding, only check the
348              * bindings before */
349             if (bind == current)
350                 break;
351
352             /* Check if the input types are different */
353             if (bind->input_type != current->input_type)
354                 continue;
355
356             /* Check if one is using keysym while the other is using bindsym.
357              * If so, skip. */
358             /* XXX: It should be checked at a later place (when translating the
359              * keysym to keycodes) if there are any duplicates */
360             if ((bind->symbol == NULL && current->symbol != NULL) ||
361                 (bind->symbol != NULL && current->symbol == NULL))
362                 continue;
363
364             /* If bind is NULL, current has to be NULL, too (see above).
365              * If the keycodes differ, it can't be a duplicate. */
366             if (bind->symbol != NULL &&
367                 strcasecmp(bind->symbol, current->symbol) != 0)
368                 continue;
369
370             /* Check if the keycodes or modifiers are different. If so, they
371              * can't be duplicate */
372             if (bind->keycode != current->keycode ||
373                 bind->mods != current->mods ||
374                 bind->release != current->release)
375                 continue;
376
377             context->has_errors = true;
378             if (current->keycode != 0) {
379                 ELOG("Duplicate keybinding in config file:\n  modmask %d with keycode %d, command \"%s\"\n",
380                      current->mods, current->keycode, current->command);
381             } else {
382                 ELOG("Duplicate keybinding in config file:\n  modmask %d with keysym %s, command \"%s\"\n",
383                      current->mods, current->symbol, current->command);
384             }
385         }
386     }
387 }
388
389 /*
390  * Creates a dynamically allocated copy of bind.
391  */
392 static Binding *binding_copy(Binding *bind) {
393     Binding *ret = smalloc(sizeof(Binding));
394     *ret = *bind;
395     if (bind->symbol != NULL)
396         ret->symbol = sstrdup(bind->symbol);
397     if (bind->command != NULL)
398         ret->command = sstrdup(bind->command);
399     if (bind->translated_to != NULL) {
400         ret->translated_to = smalloc(sizeof(xcb_keycode_t) * bind->number_keycodes);
401         memcpy(ret->translated_to, bind->translated_to, sizeof(xcb_keycode_t) * bind->number_keycodes);
402     }
403     return ret;
404 }
405
406 /*
407  * Frees the binding. If bind is null, it simply returns.
408  */
409 void binding_free(Binding *bind) {
410     if (bind == NULL) {
411         return;
412     }
413
414     FREE(bind->symbol);
415     FREE(bind->translated_to);
416     FREE(bind->command);
417     FREE(bind);
418 }
419
420 /*
421  * Runs the given binding and handles parse errors. If con is passed, it will
422  * execute the command binding with that container selected by criteria.
423  * Returns a CommandResult for running the binding's command. Caller should
424  * render tree if needs_tree_render is true. Free with command_result_free().
425  *
426  */
427 CommandResult *run_binding(Binding *bind, Con *con) {
428     char *command;
429
430     /* We need to copy the binding and command since “reload” may be part of
431      * the command, and then the memory that bind points to may not contain the
432      * same data anymore. */
433     if (con == NULL)
434         command = sstrdup(bind->command);
435     else
436         sasprintf(&command, "[con_id=\"%p\"] %s", con, bind->command);
437
438     Binding *bind_cp = binding_copy(bind);
439     CommandResult *result = parse_command(command, NULL);
440     free(command);
441
442     if (result->needs_tree_render)
443         tree_render();
444
445     if (result->parse_error) {
446         char *pageraction;
447         sasprintf(&pageraction, "i3-sensible-pager \"%s\"\n", errorfilename);
448         char *argv[] = {
449             NULL, /* will be replaced by the executable path */
450             "-f",
451             config.font.pattern,
452             "-t",
453             "error",
454             "-m",
455             "The configured command for this shortcut could not be run successfully.",
456             "-b",
457             "show errors",
458             pageraction,
459             NULL};
460         start_nagbar(&command_error_nagbar_pid, argv);
461         free(pageraction);
462     }
463
464     ipc_send_binding_event("run", bind_cp);
465     binding_free(bind_cp);
466
467     return result;
468 }