i3
bindings.c
Go to the documentation of this file.
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 
12 
13 /*
14  * The name of the default mode.
15  *
16  */
17 const char *DEFAULT_BINDING_MODE = "default";
18 
19 /*
20  * Returns the mode specified by `name` or creates a new mode and adds it to
21  * the list of modes.
22  *
23  */
24 static struct Mode *mode_from_name(const char *name) {
25  struct Mode *mode;
26 
27  /* Try to find the mode in the list of modes and return it */
28  SLIST_FOREACH (mode, &modes, modes) {
29  if (strcmp(mode->name, name) == 0)
30  return mode;
31  }
32 
33  /* If the mode was not found, create a new one */
34  mode = scalloc(sizeof(struct Mode));
35  mode->name = sstrdup(name);
36  mode->bindings = scalloc(sizeof(struct bindings_head));
37  TAILQ_INIT(mode->bindings);
38  SLIST_INSERT_HEAD(&modes, mode, modes);
39 
40  return mode;
41 }
42 
43 /*
44  * Adds a binding from config parameters given as strings and returns a
45  * pointer to the binding structure. Returns NULL if the input code could not
46  * be parsed.
47  *
48  */
49 Binding *configure_binding(const char *bindtype, const char *modifiers, const char *input_code,
50  const char *release, const char *command, const char *modename) {
51  Binding *new_binding = scalloc(sizeof(Binding));
52  DLOG("bindtype %s, modifiers %s, input code %s, release %s\n", bindtype, modifiers, input_code, release);
53  new_binding->release = (release != NULL ? B_UPON_KEYRELEASE : B_UPON_KEYPRESS);
54  if (strcmp(bindtype, "bindsym") == 0) {
55  new_binding->input_type = (strncasecmp(input_code, "button", (sizeof("button") - 1)) == 0
56  ? B_MOUSE
57  : B_KEYBOARD);
58 
59  new_binding->symbol = sstrdup(input_code);
60  } else {
61  // TODO: strtol with proper error handling
62  new_binding->keycode = atoi(input_code);
63  new_binding->input_type = B_KEYBOARD;
64  if (new_binding->keycode == 0) {
65  ELOG("Could not parse \"%s\" as an input code, ignoring this binding.\n", input_code);
66  FREE(new_binding);
67  return NULL;
68  }
69  }
70  new_binding->mods = modifiers_from_str(modifiers);
71  new_binding->command = sstrdup(command);
72 
73  struct Mode *mode = mode_from_name(modename);
74  TAILQ_INSERT_TAIL(mode->bindings, new_binding, bindings);
75 
76  return new_binding;
77 }
78 
79 static void grab_keycode_for_binding(xcb_connection_t *conn, Binding *bind, uint32_t keycode) {
80  if (bind->input_type != B_KEYBOARD)
81  return;
82 
83  DLOG("Grabbing %d with modifiers %d (with mod_mask_lock %d)\n", keycode, bind->mods, bind->mods | XCB_MOD_MASK_LOCK);
84 /* Grab the key in all combinations */
85 #define GRAB_KEY(modifier) \
86  do { \
87  xcb_grab_key(conn, 0, root, modifier, keycode, XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC); \
88  } while (0)
89  int mods = bind->mods;
90  if ((bind->mods & BIND_MODE_SWITCH) != 0) {
91  mods &= ~BIND_MODE_SWITCH;
92  if (mods == 0)
93  mods = XCB_MOD_MASK_ANY;
94  }
95  GRAB_KEY(mods);
96  GRAB_KEY(mods | xcb_numlock_mask);
97  GRAB_KEY(mods | XCB_MOD_MASK_LOCK);
98  GRAB_KEY(mods | xcb_numlock_mask | XCB_MOD_MASK_LOCK);
99 }
100 
101 /*
102  * Grab the bound keys (tell X to send us keypress events for those keycodes)
103  *
104  */
105 void grab_all_keys(xcb_connection_t *conn, bool bind_mode_switch) {
106  Binding *bind;
107  TAILQ_FOREACH (bind, bindings, bindings) {
108  if (bind->input_type != B_KEYBOARD ||
109  (bind_mode_switch && (bind->mods & BIND_MODE_SWITCH) == 0) ||
110  (!bind_mode_switch && (bind->mods & BIND_MODE_SWITCH) != 0))
111  continue;
112 
113  /* The easy case: the user specified a keycode directly. */
114  if (bind->keycode > 0) {
115  grab_keycode_for_binding(conn, bind, bind->keycode);
116  continue;
117  }
118 
119  xcb_keycode_t *walk = bind->translated_to;
120  for (uint32_t i = 0; i < bind->number_keycodes; i++)
121  grab_keycode_for_binding(conn, bind, *walk++);
122  }
123 }
124 
125 /*
126  * Returns a pointer to the Binding with the specified modifiers and
127  * keycode or NULL if no such binding exists.
128  *
129  */
130 static Binding *get_binding(uint16_t modifiers, bool is_release, uint16_t input_code, input_type_t input_type) {
131  Binding *bind;
132 
133  if (!is_release) {
134  /* On a press event, we first reset all B_UPON_KEYRELEASE_IGNORE_MODS
135  * bindings back to B_UPON_KEYRELEASE */
136  TAILQ_FOREACH (bind, bindings, bindings) {
137  if (bind->input_type != input_type)
138  continue;
139  if (bind->release == B_UPON_KEYRELEASE_IGNORE_MODS)
140  bind->release = B_UPON_KEYRELEASE;
141  }
142  }
143 
144  TAILQ_FOREACH (bind, bindings, bindings) {
145  /* First compare the modifiers (unless this is a
146  * B_UPON_KEYRELEASE_IGNORE_MODS binding and this is a KeyRelease
147  * event) */
148  if (bind->input_type != input_type)
149  continue;
150  if (bind->mods != modifiers &&
151  (bind->release != B_UPON_KEYRELEASE_IGNORE_MODS ||
152  !is_release))
153  continue;
154 
155  /* For keyboard bindings where a symbol was specified by the user, we
156  * need to look in the array of translated keycodes for the event’s
157  * keycode */
158  if (input_type == B_KEYBOARD && bind->symbol != NULL) {
159  if (memmem(bind->translated_to,
160  bind->number_keycodes * sizeof(xcb_keycode_t),
161  &input_code, sizeof(xcb_keycode_t)) == NULL)
162  continue;
163  } else {
164  /* This case is easier: The user specified a keycode */
165  if (bind->keycode != input_code)
166  continue;
167  }
168 
169  /* If this binding is a release binding, it matches the key which the
170  * user pressed. We therefore mark it as B_UPON_KEYRELEASE_IGNORE_MODS
171  * for later, so that the user can release the modifiers before the
172  * actual key or button and the release event will still be matched. */
173  if (bind->release == B_UPON_KEYRELEASE && !is_release)
174  bind->release = B_UPON_KEYRELEASE_IGNORE_MODS;
175 
176  /* Check if the binding is for a press or a release event */
177  if ((bind->release == B_UPON_KEYPRESS && is_release) ||
178  (bind->release >= B_UPON_KEYRELEASE && !is_release))
179  continue;
180 
181  break;
182  }
183 
184  return (bind == TAILQ_END(bindings) ? NULL : bind);
185 }
186 
187 /*
188  * Returns a pointer to the Binding that matches the given xcb button or key
189  * event or NULL if no such binding exists.
190  *
191  */
192 Binding *get_binding_from_xcb_event(xcb_generic_event_t *event) {
193  bool is_release = (event->response_type == XCB_KEY_RELEASE || event->response_type == XCB_BUTTON_RELEASE);
194 
195  input_type_t input_type = ((event->response_type == XCB_BUTTON_RELEASE || event->response_type == XCB_BUTTON_PRESS)
196  ? B_MOUSE
197  : B_KEYBOARD);
198 
199  uint16_t event_state = ((xcb_key_press_event_t *)event)->state;
200  uint16_t event_detail = ((xcb_key_press_event_t *)event)->detail;
201 
202  /* Remove the numlock bit, all other bits are modifiers we can bind to */
203  uint16_t state_filtered = event_state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
204  DLOG("(removed numlock, state = %d)\n", state_filtered);
205  /* Only use the lower 8 bits of the state (modifier masks) so that mouse
206  * button masks are filtered out */
207  state_filtered &= 0xFF;
208  DLOG("(removed upper 8 bits, state = %d)\n", state_filtered);
209 
210  if (xkb_current_group == XkbGroup2Index)
211  state_filtered |= BIND_MODE_SWITCH;
212 
213  DLOG("(checked mode_switch, state %d)\n", state_filtered);
214 
215  /* Find the binding */
216  Binding *bind = get_binding(state_filtered, is_release, event_detail, input_type);
217 
218  /* No match? Then the user has Mode_switch enabled but does not have a
219  * specific keybinding. Fall back to the default keybindings (without
220  * Mode_switch). Makes it much more convenient for users of a hybrid
221  * layout (like ru). */
222  if (bind == NULL) {
223  state_filtered &= ~(BIND_MODE_SWITCH);
224  DLOG("no match, new state_filtered = %d\n", state_filtered);
225  if ((bind = get_binding(state_filtered, is_release, event_detail, input_type)) == NULL) {
226  /* This is not a real error since we can have release and
227  * non-release bindings. On a press event for which there is only a
228  * !release-binding, but no release-binding, the corresponding
229  * release event will trigger this. No problem, though. */
230  DLOG("Could not lookup key binding (modifiers %d, keycode %d)\n",
231  state_filtered, event_detail);
232  }
233  }
234 
235  return bind;
236 }
237 
238 /*
239  * Translates keysymbols to keycodes for all bindings which use keysyms.
240  *
241  */
242 void translate_keysyms(void) {
243  Binding *bind;
244  xcb_keysym_t keysym;
245  int col;
246  xcb_keycode_t i, min_keycode, max_keycode;
247 
248  min_keycode = xcb_get_setup(conn)->min_keycode;
249  max_keycode = xcb_get_setup(conn)->max_keycode;
250 
251  TAILQ_FOREACH (bind, bindings, bindings) {
252  if (bind->input_type == B_MOUSE) {
253  int button = atoi(bind->symbol + (sizeof("button") - 1));
254  bind->keycode = button;
255 
256  if (button < 1)
257  ELOG("Could not translate string to button: \"%s\"\n", bind->symbol);
258 
259  continue;
260  }
261 
262  if (bind->keycode > 0)
263  continue;
264 
265  /* We need to translate the symbol to a keycode */
266  keysym = XStringToKeysym(bind->symbol);
267  if (keysym == NoSymbol) {
268  ELOG("Could not translate string to key symbol: \"%s\"\n",
269  bind->symbol);
270  continue;
271  }
272 
273  /* Base column we use for looking up key symbols. We always consider
274  * the base column and the corresponding shift column, so without
275  * mode_switch, we look in 0 and 1, with mode_switch we look in 2 and
276  * 3. */
277  col = (bind->mods & BIND_MODE_SWITCH ? 2 : 0);
278 
279  FREE(bind->translated_to);
280  bind->number_keycodes = 0;
281 
282  for (i = min_keycode; i && i <= max_keycode; i++) {
283  if ((xcb_key_symbols_get_keysym(keysyms, i, col) != keysym) &&
284  (xcb_key_symbols_get_keysym(keysyms, i, col + 1) != keysym))
285  continue;
286  bind->number_keycodes++;
287  bind->translated_to = srealloc(bind->translated_to,
288  (sizeof(xcb_keycode_t) *
289  bind->number_keycodes));
290  bind->translated_to[bind->number_keycodes - 1] = i;
291  }
292 
293  DLOG("Translated symbol \"%s\" to %d keycode\n", bind->symbol,
294  bind->number_keycodes);
295  }
296 }
297 
298 /*
299  * Switches the key bindings to the given mode, if the mode exists
300  *
301  */
302 void switch_mode(const char *new_mode) {
303  struct Mode *mode;
304 
305  DLOG("Switching to mode %s\n", new_mode);
306 
307  SLIST_FOREACH (mode, &modes, modes) {
308  if (strcasecmp(mode->name, new_mode) != 0)
309  continue;
310 
312  bindings = mode->bindings;
314  grab_all_keys(conn, false);
315 
316  char *event_msg;
317  sasprintf(&event_msg, "{\"change\":\"%s\"}", mode->name);
318 
319  ipc_send_event("mode", I3_IPC_EVENT_MODE, event_msg);
320  FREE(event_msg);
321 
322  return;
323  }
324 
325  ELOG("ERROR: Mode not found\n");
326 }
327 
328 /*
329  * Checks for duplicate key bindings (the same keycode or keysym is configured
330  * more than once). If a duplicate binding is found, a message is printed to
331  * stderr and the has_errors variable is set to true, which will start
332  * i3-nagbar.
333  *
334  */
336  Binding *bind, *current;
337  TAILQ_FOREACH (current, bindings, bindings) {
338  TAILQ_FOREACH (bind, bindings, bindings) {
339  /* Abort when we reach the current keybinding, only check the
340  * bindings before */
341  if (bind == current)
342  break;
343 
344  /* Check if the input types are different */
345  if (bind->input_type != current->input_type)
346  continue;
347 
348  /* Check if one is using keysym while the other is using bindsym.
349  * If so, skip. */
350  /* XXX: It should be checked at a later place (when translating the
351  * keysym to keycodes) if there are any duplicates */
352  if ((bind->symbol == NULL && current->symbol != NULL) ||
353  (bind->symbol != NULL && current->symbol == NULL))
354  continue;
355 
356  /* If bind is NULL, current has to be NULL, too (see above).
357  * If the keycodes differ, it can't be a duplicate. */
358  if (bind->symbol != NULL &&
359  strcasecmp(bind->symbol, current->symbol) != 0)
360  continue;
361 
362  /* Check if the keycodes or modifiers are different. If so, they
363  * can't be duplicate */
364  if (bind->keycode != current->keycode ||
365  bind->mods != current->mods ||
366  bind->release != current->release)
367  continue;
368 
369  context->has_errors = true;
370  if (current->keycode != 0) {
371  ELOG("Duplicate keybinding in config file:\n modmask %d with keycode %d, command \"%s\"\n",
372  current->mods, current->keycode, current->command);
373  } else {
374  ELOG("Duplicate keybinding in config file:\n modmask %d with keysym %s, command \"%s\"\n",
375  current->mods, current->symbol, current->command);
376  }
377  }
378  }
379 }
380 
381 /*
382  * Runs the given binding and handles parse errors. Returns a CommandResult for
383  * running the binding's command. Caller should render tree if
384  * needs_tree_render is true. Free with command_result_free().
385  *
386  */
388  /* We need to copy the command since “reload” may be part of the command,
389  * and then the memory that bind->command points to may not contain the
390  * same data anymore. */
391  char *command_copy = sstrdup(bind->command);
392  CommandResult *result = parse_command(command_copy, NULL);
393  free(command_copy);
394 
395  if (result->needs_tree_render)
396  tree_render();
397 
398  if (result->parse_error) {
399  char *pageraction;
400  sasprintf(&pageraction, "i3-sensible-pager \"%s\"\n", errorfilename);
401  char *argv[] = {
402  NULL, /* will be replaced by the executable path */
403  "-f",
405  "-t",
406  "error",
407  "-m",
408  "The configured command for this shortcut could not be run successfully.",
409  "-b",
410  "show errors",
411  pageraction,
412  NULL};
414  free(pageraction);
415  }
416 
417  /* TODO: emit event for running a binding */
418 
419  return result;
420 }
char * sstrdup(const char *str)
Safe-wrapper around strdup which exits if malloc returns NULL (meaning that there is no more memory a...
char * name
Definition: config.h:79
#define SLIST_FOREACH(var, head, field)
Definition: queue.h:114
char * symbol
Symbol the user specified in configfile, if any.
Definition: data.h:261
void tree_render(void)
Renders the tree, that is rendering all outputs using render_con() and pushing the changes to X11 usi...
Definition: tree.c:507
void check_for_duplicate_bindings(struct context *context)
Checks for duplicate key bindings (the same keycode or keysym is configured more than once)...
Definition: bindings.c:335
Config config
Definition: config.c:19
xcb_connection_t * conn
Definition: main.c:47
const char * DEFAULT_BINDING_MODE
Definition: bindings.c:17
i3Font font
Definition: config.h:92
CommandResult * run_binding(Binding *bind)
Runs the given binding and handles parse errors.
Definition: bindings.c:387
input_type_t input_type
Definition: data.h:234
void translate_keysyms(void)
Translates keysymbols to keycodes for all bindings which use keysyms.
Definition: bindings.c:242
CommandResult * parse_command(const char *input, yajl_gen gen)
Parses and executes the given command.
#define SLIST_INSERT_HEAD(head, elm, field)
Definition: queue.h:136
static Binding * get_binding(uint16_t modifiers, bool is_release, uint16_t input_code, input_type_t input_type)
Definition: bindings.c:130
static void grab_keycode_for_binding(xcb_connection_t *conn, Binding *bind, uint32_t keycode)
Definition: bindings.c:79
uint32_t modifiers_from_str(const char *str)
A utility function to convert a string of modifiers to the corresponding bit mask.
int xkb_current_group
Definition: main.c:41
static struct Mode * mode_from_name(const char *name)
Definition: bindings.c:24
void grab_all_keys(xcb_connection_t *conn, bool bind_mode_switch)
Grab the bound keys (tell X to send us keypress events for those keycodes)
Definition: bindings.c:105
Holds a keybinding, consisting of a keycode combined with modifiers and the command which is executed...
Definition: data.h:231
void ipc_send_event(const char *event, uint32_t message_type, const char *payload)
Sends the specified event to all IPC clients which are currently connected and subscribed to this kin...
Definition: ipc.c:75
pid_t command_error_nagbar_pid
Definition: bindings.c:11
void switch_mode(const char *new_mode)
Switches the key bindings to the given mode, if the mode exists.
Definition: bindings.c:302
#define DLOG(fmt,...)
Definition: libi3.h:86
struct bindings_head * bindings
Definition: config.h:80
A struct that contains useful information about the result of a command as a whole (e...
char * command
Command, like in command mode.
Definition: data.h:272
int sasprintf(char **strp, const char *fmt,...)
Safe-wrapper around asprintf which exits if it returns -1 (meaning that there is no more memory avail...
The configuration file can contain multiple sets of bindings.
Definition: config.h:78
enum Binding::@10 release
If true, the binding should be executed upon a KeyRelease event, not a KeyPress (the default)...
uint32_t number_keycodes
Definition: data.h:250
char * errorfilename
Definition: log.c:38
bool has_errors
Definition: config.h:33
void start_nagbar(pid_t *nagbar_pid, char *argv[])
Starts an i3-nagbar instance with the given parameters.
Definition: util.c:420
Used during the config file lexing/parsing to keep the state of the lexer in order to provide useful ...
Definition: config.h:32
Definition: data.h:99
input_type_t
Binding input types.
Definition: data.h:97
#define TAILQ_INIT(head)
Definition: queue.h:347
char * pattern
The pattern/name used to load the font.
Definition: libi3.h:50
struct modes_head modes
Definition: config.c:20
Binding * configure_binding(const char *bindtype, const char *modifiers, const char *input_code, const char *release, const char *command, const char *modename)
Adds a binding from config parameters given as strings and returns a pointer to the binding structure...
Definition: bindings.c:49
void ungrab_all_keys(xcb_connection_t *conn)
Ungrabs all keys, to be called before re-grabbing the keys because of a mapping_notify event or a con...
Definition: config.c:28
#define GRAB_KEY(modifier)
#define ELOG(fmt,...)
Definition: libi3.h:81
unsigned int xcb_numlock_mask
Definition: xcb.c:14
void * scalloc(size_t size)
Safe-wrapper around calloc which exits if malloc returns NULL (meaning that there is no more memory a...
struct bindings_head * bindings
Definition: main.c:80
#define TAILQ_END(head)
Definition: queue.h:324
uint32_t keycode
Keycode to bind.
Definition: data.h:253
Binding * get_binding_from_xcb_event(xcb_generic_event_t *event)
Returns a pointer to the Binding that matches the given xcb event or NULL if no such binding exists...
Definition: bindings.c:192
#define TAILQ_INSERT_TAIL(head, elm, field)
Definition: queue.h:362
uint32_t mods
Bitmask consisting of BIND_MOD_1, BIND_MODE_SWITCH, …
Definition: data.h:256
xcb_key_symbols_t * keysyms
Definition: main.c:71
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:334
xcb_keycode_t * translated_to
Only in use if symbol != NULL.
Definition: data.h:268
void * srealloc(void *ptr, size_t size)
Safe-wrapper around realloc which exits if realloc returns NULL (meaning that there is no more memory...
#define FREE(pointer)
Definition: util.h:46