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