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