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