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