]> git.sur5r.net Git - i3/i3/blob - src/util.c
15796d887cb95edfd2595718835ed9aad72c4c9d
[i3/i3] / src / util.c
1 #undef I3__FILE__
2 #define I3__FILE__ "util.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * util.c: Utility functions, which can be useful everywhere within i3 (see
10  *         also libi3).
11  *
12  */
13 #include "all.h"
14
15 #include <sys/wait.h>
16 #include <stdarg.h>
17 #if defined(__OpenBSD__)
18 #include <sys/cdefs.h>
19 #endif
20 #include <fcntl.h>
21 #include <pwd.h>
22 #include <yajl/yajl_version.h>
23 #include <libgen.h>
24 #include <ctype.h>
25
26 #define SN_API_NOT_YET_FROZEN 1
27 #include <libsn/sn-launcher.h>
28
29 int min(int a, int b) {
30     return (a < b ? a : b);
31 }
32
33 int max(int a, int b) {
34     return (a > b ? a : b);
35 }
36
37 bool rect_contains(Rect rect, uint32_t x, uint32_t y) {
38     return (x >= rect.x &&
39             x <= (rect.x + rect.width) &&
40             y >= rect.y &&
41             y <= (rect.y + rect.height));
42 }
43
44 Rect rect_add(Rect a, Rect b) {
45     return (Rect){a.x + b.x,
46                   a.y + b.y,
47                   a.width + b.width,
48                   a.height + b.height};
49 }
50
51 Rect rect_sub(Rect a, Rect b) {
52     return (Rect){a.x - b.x,
53                   a.y - b.y,
54                   a.width - b.width,
55                   a.height - b.height};
56 }
57
58 /*
59  * Returns true if the name consists of only digits.
60  *
61  */
62 __attribute__((pure)) bool name_is_digits(const char *name) {
63     /* positive integers and zero are interpreted as numbers */
64     for (size_t i = 0; i < strlen(name); i++)
65         if (!isdigit(name[i]))
66             return false;
67
68     return true;
69 }
70
71 /*
72  * Parses the workspace name as a number. Returns -1 if the workspace should be
73  * interpreted as a "named workspace".
74  *
75  */
76 long ws_name_to_number(const char *name) {
77     /* positive integers and zero are interpreted as numbers */
78     char *endptr = NULL;
79     long parsed_num = strtol(name, &endptr, 10);
80     if (parsed_num == LONG_MIN ||
81         parsed_num == LONG_MAX ||
82         parsed_num < 0 ||
83         endptr == name) {
84         parsed_num = -1;
85     }
86
87     return parsed_num;
88 }
89
90 /*
91  * Updates *destination with new_value and returns true if it was changed or false
92  * if it was the same
93  *
94  */
95 bool update_if_necessary(uint32_t *destination, const uint32_t new_value) {
96     uint32_t old_value = *destination;
97
98     return ((*destination = new_value) != old_value);
99 }
100
101 /*
102  * exec()s an i3 utility, for example the config file migration script or
103  * i3-nagbar. This function first searches $PATH for the given utility named,
104  * then falls back to the dirname() of the i3 executable path and then falls
105  * back to the dirname() of the target of /proc/self/exe (on linux).
106  *
107  * This function should be called after fork()ing.
108  *
109  * The first argument of the given argv vector will be overwritten with the
110  * executable name, so pass NULL.
111  *
112  * If the utility cannot be found in any of these locations, it exits with
113  * return code 2.
114  *
115  */
116 void exec_i3_utility(char *name, char *argv[]) {
117     /* start the migration script, search PATH first */
118     char *migratepath = name;
119     argv[0] = migratepath;
120     execvp(migratepath, argv);
121
122     /* if the script is not in path, maybe the user installed to a strange
123      * location and runs the i3 binary with an absolute path. We use
124      * argv[0]’s dirname */
125     char *pathbuf = sstrdup(start_argv[0]);
126     char *dir = dirname(pathbuf);
127     sasprintf(&migratepath, "%s/%s", dir, name);
128     argv[0] = migratepath;
129     execvp(migratepath, argv);
130
131 #if defined(__linux__)
132     /* on linux, we have one more fall-back: dirname(/proc/self/exe) */
133     char buffer[BUFSIZ];
134     if (readlink("/proc/self/exe", buffer, BUFSIZ) == -1) {
135         warn("could not read /proc/self/exe");
136         _exit(1);
137     }
138     dir = dirname(buffer);
139     sasprintf(&migratepath, "%s/%s", dir, name);
140     argv[0] = migratepath;
141     execvp(migratepath, argv);
142 #endif
143
144     warn("Could not start %s", name);
145     _exit(2);
146 }
147
148 /*
149  * Checks if the given path exists by calling stat().
150  *
151  */
152 bool path_exists(const char *path) {
153     struct stat buf;
154     return (stat(path, &buf) == 0);
155 }
156
157 /*
158  * Goes through the list of arguments (for exec()) and add/replace the given option,
159  * including the option name, its argument, and the option character.
160  */
161 static char **add_argument(char **original, char *opt_char, char *opt_arg, char *opt_name) {
162     int num_args;
163     for (num_args = 0; original[num_args] != NULL; num_args++)
164         ;
165     char **result = scalloc(num_args + 3, sizeof(char *));
166
167     /* copy the arguments, but skip the ones we'll replace */
168     int write_index = 0;
169     bool skip_next = false;
170     for (int i = 0; i < num_args; ++i) {
171         if (skip_next) {
172             skip_next = false;
173             continue;
174         }
175         if (!strcmp(original[i], opt_char) ||
176             (opt_name && !strcmp(original[i], opt_name))) {
177             if (opt_arg)
178                 skip_next = true;
179             continue;
180         }
181         result[write_index++] = original[i];
182     }
183
184     /* add the arguments we'll replace */
185     result[write_index++] = opt_char;
186     result[write_index] = opt_arg;
187
188     return result;
189 }
190
191 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
192 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
193
194 char *store_restart_layout(void) {
195     setlocale(LC_NUMERIC, "C");
196     yajl_gen gen = yajl_gen_alloc(NULL);
197
198     dump_node(gen, croot, true);
199
200     setlocale(LC_NUMERIC, "");
201
202     const unsigned char *payload;
203     size_t length;
204     y(get_buf, &payload, &length);
205
206     /* create a temporary file if one hasn't been specified, or just
207      * resolve the tildes in the specified path */
208     char *filename;
209     if (config.restart_state_path == NULL) {
210         filename = get_process_filename("restart-state");
211         if (!filename)
212             return NULL;
213     } else {
214         filename = resolve_tilde(config.restart_state_path);
215     }
216
217     /* create the directory, it could have been cleaned up before restarting or
218      * may not exist at all in case it was user-specified. */
219     char *filenamecopy = sstrdup(filename);
220     char *base = dirname(filenamecopy);
221     DLOG("Creating \"%s\" for storing the restart layout\n", base);
222     if (mkdirp(base, DEFAULT_DIR_MODE) != 0)
223         ELOG("Could not create \"%s\" for storing the restart layout, layout will be lost.\n", base);
224     free(filenamecopy);
225
226     int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
227     if (fd == -1) {
228         perror("open()");
229         free(filename);
230         return NULL;
231     }
232
233     if (writeall(fd, payload, length) == -1) {
234         ELOG("Could not write restart layout to \"%s\", layout will be lost: %s\n", filename, strerror(errno));
235         free(filename);
236         close(fd);
237         return NULL;
238     }
239
240     close(fd);
241
242     if (length > 0) {
243         DLOG("layout: %.*s\n", (int)length, payload);
244     }
245
246     y(free);
247
248     return filename;
249 }
250
251 /*
252  * Restart i3 in-place
253  * appends -a to argument list to disable autostart
254  *
255  */
256 void i3_restart(bool forget_layout) {
257     char *restart_filename = forget_layout ? NULL : store_restart_layout();
258
259     kill_nagbar(&config_error_nagbar_pid, true);
260     kill_nagbar(&command_error_nagbar_pid, true);
261
262     restore_geometry();
263
264     ipc_shutdown();
265
266     LOG("restarting \"%s\"...\n", start_argv[0]);
267     /* make sure -a is in the argument list or add it */
268     start_argv = add_argument(start_argv, "-a", NULL, NULL);
269
270     /* make debuglog-on persist */
271     if (get_debug_logging()) {
272         start_argv = add_argument(start_argv, "-d", "all", NULL);
273     }
274
275     /* replace -r <file> so that the layout is restored */
276     if (restart_filename != NULL) {
277         start_argv = add_argument(start_argv, "--restart", restart_filename, "-r");
278     }
279
280     execvp(start_argv[0], start_argv);
281
282     /* not reached */
283 }
284
285 #if defined(__OpenBSD__) || defined(__APPLE__)
286
287 /*
288  * Taken from FreeBSD
289  * Find the first occurrence of the byte string s in byte string l.
290  *
291  */
292 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
293     register char *cur, *last;
294     const char *cl = (const char *)l;
295     const char *cs = (const char *)s;
296
297     /* we need something to compare */
298     if (l_len == 0 || s_len == 0)
299         return NULL;
300
301     /* "s" must be smaller or equal to "l" */
302     if (l_len < s_len)
303         return NULL;
304
305     /* special case where s_len == 1 */
306     if (s_len == 1)
307         return memchr(l, (int)*cs, l_len);
308
309     /* the last position where its possible to find "s" in "l" */
310     last = (char *)cl + l_len - s_len;
311
312     for (cur = (char *)cl; cur <= last; cur++)
313         if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
314             return cur;
315
316     return NULL;
317 }
318
319 #endif
320
321 /*
322  * Escapes the given string if a pango font is currently used.
323  * If the string has to be escaped, the input string will be free'd.
324  *
325  */
326 char *pango_escape_markup(char *input) {
327     if (!font_is_pango())
328         return input;
329
330     char *escaped = g_markup_escape_text(input, -1);
331     FREE(input);
332
333     return escaped;
334 }
335
336 /*
337  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
338  * it exited (or could not be started, depending on the exit code).
339  *
340  */
341 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
342     ev_child_stop(EV_A_ watcher);
343
344     if (!WIFEXITED(watcher->rstatus)) {
345         ELOG("ERROR: i3-nagbar did not exit normally.\n");
346         return;
347     }
348
349     int exitcode = WEXITSTATUS(watcher->rstatus);
350     DLOG("i3-nagbar process exited with status %d\n", exitcode);
351     if (exitcode == 2) {
352         ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
353     }
354
355     *((pid_t *)watcher->data) = -1;
356 }
357
358 /*
359  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
360  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
361  *
362  */
363 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
364     pid_t *nagbar_pid = (pid_t *)watcher->data;
365     if (*nagbar_pid != -1) {
366         LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, *nagbar_pid);
367         kill(*nagbar_pid, SIGKILL);
368     }
369 }
370
371 /*
372  * Starts an i3-nagbar instance with the given parameters. Takes care of
373  * handling SIGCHLD and killing i3-nagbar when i3 exits.
374  *
375  * The resulting PID will be stored in *nagbar_pid and can be used with
376  * kill_nagbar() to kill the bar later on.
377  *
378  */
379 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
380     if (*nagbar_pid != -1) {
381         DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
382         return;
383     }
384
385     *nagbar_pid = fork();
386     if (*nagbar_pid == -1) {
387         warn("Could not fork()");
388         return;
389     }
390
391     /* child */
392     if (*nagbar_pid == 0)
393         exec_i3_utility("i3-nagbar", argv);
394
395     DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
396
397     /* parent */
398     /* install a child watcher */
399     ev_child *child = smalloc(sizeof(ev_child));
400     ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
401     child->data = nagbar_pid;
402     ev_child_start(main_loop, child);
403
404     /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
405      * still running) */
406     ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
407     ev_cleanup_init(cleanup, nagbar_cleanup);
408     cleanup->data = nagbar_pid;
409     ev_cleanup_start(main_loop, cleanup);
410 }
411
412 /*
413  * Kills the i3-nagbar process, if *nagbar_pid != -1.
414  *
415  * If wait_for_it is set (restarting i3), this function will waitpid(),
416  * otherwise, ev is assumed to handle it (reloading).
417  *
418  */
419 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
420     if (*nagbar_pid == -1)
421         return;
422
423     if (kill(*nagbar_pid, SIGTERM) == -1)
424         warn("kill(configerror_nagbar) failed");
425
426     if (!wait_for_it)
427         return;
428
429     /* When restarting, we don’t enter the ev main loop anymore and after the
430      * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
431      * for us and we would end up with a <defunct> process. Therefore we
432      * waitpid() here. */
433     waitpid(*nagbar_pid, NULL, 0);
434 }