i3
key_press.c
Go to the documentation of this file.
1 #undef I3__FILE__
2 #define I3__FILE__ "key_press.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * key_press.c: key press handler
10  *
11  */
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <sys/wait.h>
15 #include <fcntl.h>
16 #include "all.h"
17 
19 static bool parse_error_key;
20 static bool command_failed;
21 
22 /* XXX: I don’t want to touch too much of the nagbar code at once, but we
23  * should refactor this with src/cfgparse.y into a clean generic nagbar
24  * interface. It might come in handy in other situations within i3, too. */
25 static char *pager_script_path;
26 static pid_t nagbar_pid = -1;
27 
28 /*
29  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
30  * it exited (or could not be started, depending on the exit code).
31  *
32  */
33 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
34  ev_child_stop(EV_A_ watcher);
35 
36  if (unlink(pager_script_path) != 0)
37  warn("Could not delete temporary i3-nagbar script %s", pager_script_path);
38 
39  if (!WIFEXITED(watcher->rstatus)) {
40  fprintf(stderr, "ERROR: i3-nagbar did not exit normally.\n");
41  return;
42  }
43 
44  int exitcode = WEXITSTATUS(watcher->rstatus);
45  printf("i3-nagbar process exited with status %d\n", exitcode);
46  if (exitcode == 2) {
47  fprintf(stderr, "ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
48  }
49 
50  nagbar_pid = -1;
51 }
52 
53 /* We need ev >= 4 for the following code. Since it is not *that* important (it
54  * only makes sure that there are no i3-nagbar instances left behind) we still
55  * support old systems with libev 3. */
56 #if EV_VERSION_MAJOR >= 4
57 /*
58  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
59  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
60  *
61  */
62 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
63  if (nagbar_pid != -1) {
64  LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, nagbar_pid);
65  kill(nagbar_pid, SIGKILL);
66  }
67 }
68 #endif
69 
70 /*
71  * Writes the given command as a shell script to path.
72  * Returns true unless something went wrong.
73  *
74  */
75 static bool write_nagbar_script(const char *path, const char *command) {
76  int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR);
77  if (fd == -1) {
78  warn("Could not create temporary script to store the nagbar command");
79  return false;
80  }
81  write(fd, "#!/bin/sh\n", strlen("#!/bin/sh\n"));
82  write(fd, command, strlen(command));
83  close(fd);
84  return true;
85 }
86 
87 /*
88  * Starts an i3-nagbar process which alerts the user that his configuration
89  * file contains one or more errors. Also offers two buttons: One to launch an
90  * $EDITOR on the config file and another one to launch a $PAGER on the error
91  * logfile.
92  *
93  */
94 static void start_commanderror_nagbar(void) {
95  if (nagbar_pid != -1) {
96  DLOG("i3-nagbar for command error already running, not starting again.\n");
97  return;
98  }
99 
100  DLOG("Starting i3-nagbar due to command error\n");
101 
102  /* We need to create a custom script containing our actual command
103  * since not every terminal emulator which is contained in
104  * i3-sensible-terminal supports -e with multiple arguments (and not
105  * all of them support -e with one quoted argument either).
106  *
107  * NB: The paths need to be unique, that is, don’t assume users close
108  * their nagbars at any point in time (and they still need to work).
109  * */
110  pager_script_path = get_process_filename("nagbar-cfgerror-pager");
111 
112  nagbar_pid = fork();
113  if (nagbar_pid == -1) {
114  warn("Could not fork()");
115  return;
116  }
117 
118  /* child */
119  if (nagbar_pid == 0) {
120  char *pager_command;
121  sasprintf(&pager_command, "i3-sensible-pager \"%s\"\n", errorfilename);
122  if (!write_nagbar_script(pager_script_path, pager_command))
123  return;
124 
125  char *pageraction;
126  sasprintf(&pageraction, "i3-sensible-terminal -e \"%s\"", pager_script_path);
127  char *argv[] = {
128  NULL, /* will be replaced by the executable path */
129  "-t",
130  "error",
131  "-m",
132  "The configured command for this shortcut could not be run successfully.",
133  "-b",
134  "show errors",
135  pageraction,
136  NULL
137  };
138  exec_i3_utility("i3-nagbar", argv);
139  }
140 
141  /* parent */
142  /* install a child watcher */
143  ev_child *child = smalloc(sizeof(ev_child));
144  ev_child_init(child, &nagbar_exited, nagbar_pid, 0);
145  ev_child_start(main_loop, child);
146 
147 /* We need ev >= 4 for the following code. Since it is not *that* important (it
148  * only makes sure that there are no i3-nagbar instances left behind) we still
149  * support old systems with libev 3. */
150 #if EV_VERSION_MAJOR >= 4
151  /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
152  * still running) */
153  ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
154  ev_cleanup_init(cleanup, nagbar_cleanup);
155  ev_cleanup_start(main_loop, cleanup);
156 #endif
157 }
158 
159 /*
160  * Kills the commanderror i3-nagbar process, if any.
161  *
162  * Called when reloading/restarting, since the user probably fixed his wrong
163  * keybindings.
164  *
165  * If wait_for_it is set (restarting), this function will waitpid(), otherwise,
166  * ev is assumed to handle it (reloading).
167  *
168  */
169 void kill_commanderror_nagbar(bool wait_for_it) {
170  if (nagbar_pid == -1)
171  return;
172 
173  if (kill(nagbar_pid, SIGTERM) == -1)
174  warn("kill(configerror_nagbar) failed");
175 
176  if (!wait_for_it)
177  return;
178 
179  /* When restarting, we don’t enter the ev main loop anymore and after the
180  * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
181  * for us and we would end up with a <defunct> process. Therefore we
182  * waitpid() here. */
183  waitpid(nagbar_pid, NULL, 0);
184 }
185 
186 static int json_boolean(void *ctx, int boolval) {
187  DLOG("Got bool: %d, parse_error_key %d, nesting_level %d\n", boolval, parse_error_key, current_nesting_level);
188 
189  if (parse_error_key && current_nesting_level == 1 && boolval)
190  command_failed = true;
191 
192  return 1;
193 }
194 
195 #if YAJL_MAJOR >= 2
196 static int json_map_key(void *ctx, const unsigned char *stringval, size_t stringlen) {
197 #else
198 static int json_map_key(void *ctx, const unsigned char *stringval, unsigned int stringlen) {
199 #endif
200  parse_error_key = (stringlen >= strlen("parse_error") &&
201  strncmp((const char*)stringval, "parse_error", strlen("parse_error")) == 0);
202  return 1;
203 }
204 
205 static int json_start_map(void *ctx) {
207  return 1;
208 }
209 
210 static int json_end_map(void *ctx) {
212  return 1;
213 }
214 
215 static yajl_callbacks command_error_callbacks = {
216  NULL,
217  &json_boolean,
218  NULL,
219  NULL,
220  NULL,
221  NULL,
223  &json_map_key,
224  &json_end_map,
225  NULL,
226  NULL
227 };
228 
229 /*
230  * There was a KeyPress or KeyRelease (both events have the same fields). We
231  * compare this key code with our bindings table and pass the bound action to
232  * parse_command().
233  *
234  */
235 void handle_key_press(xcb_key_press_event_t *event) {
236  bool key_release = (event->response_type == XCB_KEY_RELEASE);
237 
238  last_timestamp = event->time;
239 
240  DLOG("%s %d, state raw = %d\n", (key_release ? "KeyRelease" : "KeyPress"), event->detail, event->state);
241 
242  /* Remove the numlock bit, all other bits are modifiers we can bind to */
243  uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
244  DLOG("(removed numlock, state = %d)\n", state_filtered);
245  /* Only use the lower 8 bits of the state (modifier masks) so that mouse
246  * button masks are filtered out */
247  state_filtered &= 0xFF;
248  DLOG("(removed upper 8 bits, state = %d)\n", state_filtered);
249 
250  if (xkb_current_group == XkbGroup2Index)
251  state_filtered |= BIND_MODE_SWITCH;
252 
253  DLOG("(checked mode_switch, state %d)\n", state_filtered);
254 
255  /* Find the binding */
256  Binding *bind = get_binding(state_filtered, key_release, event->detail);
257 
258  /* No match? Then the user has Mode_switch enabled but does not have a
259  * specific keybinding. Fall back to the default keybindings (without
260  * Mode_switch). Makes it much more convenient for users of a hybrid
261  * layout (like us, ru). */
262  if (bind == NULL) {
263  state_filtered &= ~(BIND_MODE_SWITCH);
264  DLOG("no match, new state_filtered = %d\n", state_filtered);
265  if ((bind = get_binding(state_filtered, key_release, event->detail)) == NULL) {
266  /* This is not a real error since we can have release and
267  * non-release keybindings. On a KeyPress event for which there is
268  * only a !release-binding, but no release-binding, the
269  * corresponding KeyRelease event will trigger this. No problem,
270  * though. */
271  DLOG("Could not lookup key binding (modifiers %d, keycode %d)\n",
272  state_filtered, event->detail);
273  return;
274  }
275  }
276 
277  char *command_copy = sstrdup(bind->command);
278  struct CommandResult *command_output = parse_command(command_copy);
279  free(command_copy);
280 
281  if (command_output->needs_tree_render)
282  tree_render();
283 
284  /* We parse the JSON reply to figure out whether there was an error
285  * ("success" being false in on of the returned dictionaries). */
286  const unsigned char *reply;
287 #if YAJL_MAJOR >= 2
288  size_t length;
289  yajl_handle handle = yajl_alloc(&command_error_callbacks, NULL, NULL);
290 #else
291  unsigned int length;
292  yajl_parser_config parse_conf = { 0, 0 };
293 
294  yajl_handle handle = yajl_alloc(&command_error_callbacks, &parse_conf, NULL, NULL);
295 #endif
296  yajl_gen_get_buf(command_output->json_gen, &reply, &length);
297 
299  parse_error_key = false;
300  command_failed = false;
301  yajl_status state = yajl_parse(handle, reply, length);
302  if (state != yajl_status_ok) {
303  ELOG("Could not parse my own reply. That's weird. reply is %.*s\n", (int)length, reply);
304  } else {
305  if (command_failed)
307  }
308 
309  yajl_free(handle);
310 
311  yajl_gen_free(command_output->json_gen);
312 }