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