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