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