]> git.sur5r.net Git - i3/i3/blob - src/util.c
Merge pull request #1816 from tcreech/tcreech-for-illumos
[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 a generic cookie for errors and quits with the given message if there
150  * was an error.
151  *
152  */
153 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
154     xcb_generic_error_t *error = xcb_request_check(conn, cookie);
155     if (error != NULL) {
156         fprintf(stderr, "ERROR: %s (X error %d)\n", err_message, error->error_code);
157         xcb_disconnect(conn);
158         exit(-1);
159     }
160 }
161
162 /*
163  * Checks if the given path exists by calling stat().
164  *
165  */
166 bool path_exists(const char *path) {
167     struct stat buf;
168     return (stat(path, &buf) == 0);
169 }
170
171 /*
172  * Goes through the list of arguments (for exec()) and checks if the given argument
173  * is present. If not, it copies the arguments (because we cannot realloc it) and
174  * appends the given argument.
175  *
176  */
177 static char **append_argument(char **original, char *argument) {
178     int num_args;
179     for (num_args = 0; original[num_args] != NULL; num_args++) {
180         DLOG("original argument: \"%s\"\n", original[num_args]);
181         /* If the argument is already present we return the original pointer */
182         if (strcmp(original[num_args], argument) == 0)
183             return original;
184     }
185     /* Copy the original array */
186     char **result = smalloc((num_args + 2) * sizeof(char *));
187     memcpy(result, original, num_args * sizeof(char *));
188     result[num_args] = argument;
189     result[num_args + 1] = NULL;
190
191     return result;
192 }
193
194 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
195 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
196
197 char *store_restart_layout(void) {
198     setlocale(LC_NUMERIC, "C");
199     yajl_gen gen = yajl_gen_alloc(NULL);
200
201     dump_node(gen, croot, true);
202
203     setlocale(LC_NUMERIC, "");
204
205     const unsigned char *payload;
206     size_t length;
207     y(get_buf, &payload, &length);
208
209     /* create a temporary file if one hasn't been specified, or just
210      * resolve the tildes in the specified path */
211     char *filename;
212     if (config.restart_state_path == NULL) {
213         filename = get_process_filename("restart-state");
214         if (!filename)
215             return NULL;
216     } else {
217         filename = resolve_tilde(config.restart_state_path);
218     }
219
220     /* create the directory, it could have been cleaned up before restarting or
221      * may not exist at all in case it was user-specified. */
222     char *filenamecopy = sstrdup(filename);
223     char *base = dirname(filenamecopy);
224     DLOG("Creating \"%s\" for storing the restart layout\n", base);
225     if (mkdirp(base, DEFAULT_DIR_MODE) != 0)
226         ELOG("Could not create \"%s\" for storing the restart layout, layout will be lost.\n", base);
227     free(filenamecopy);
228
229     int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
230     if (fd == -1) {
231         perror("open()");
232         free(filename);
233         return NULL;
234     }
235
236     if (writeall(fd, payload, length) == -1) {
237         ELOG("Could not write restart layout to \"%s\", layout will be lost: %s\n", filename, strerror(errno));
238         free(filename);
239         close(fd);
240         return NULL;
241     }
242
243     close(fd);
244
245     if (length > 0) {
246         DLOG("layout: %.*s\n", (int)length, payload);
247     }
248
249     y(free);
250
251     return filename;
252 }
253
254 /*
255  * Restart i3 in-place
256  * appends -a to argument list to disable autostart
257  *
258  */
259 void i3_restart(bool forget_layout) {
260     char *restart_filename = forget_layout ? NULL : store_restart_layout();
261
262     kill_nagbar(&config_error_nagbar_pid, true);
263     kill_nagbar(&command_error_nagbar_pid, true);
264
265     restore_geometry();
266
267     ipc_shutdown();
268
269     LOG("restarting \"%s\"...\n", start_argv[0]);
270     /* make sure -a is in the argument list or append it */
271     start_argv = append_argument(start_argv, "-a");
272
273     /* replace -r <file> so that the layout is restored */
274     if (restart_filename != NULL) {
275         /* create the new argv */
276         int num_args;
277         for (num_args = 0; start_argv[num_args] != NULL; num_args++)
278             ;
279         char **new_argv = scalloc(num_args + 3, sizeof(char *));
280
281         /* copy the arguments, but skip the ones we'll replace */
282         int write_index = 0;
283         bool skip_next = false;
284         for (int i = 0; i < num_args; ++i) {
285             if (skip_next)
286                 skip_next = false;
287             else if (!strcmp(start_argv[i], "-r") ||
288                      !strcmp(start_argv[i], "--restart"))
289                 skip_next = true;
290             else
291                 new_argv[write_index++] = start_argv[i];
292         }
293
294         /* add the arguments we'll replace */
295         new_argv[write_index++] = "--restart";
296         new_argv[write_index] = restart_filename;
297
298         /* swap the argvs */
299         start_argv = new_argv;
300     }
301
302     execvp(start_argv[0], start_argv);
303     /* not reached */
304 }
305
306 #if defined(__OpenBSD__) || defined(__APPLE__)
307
308 /*
309  * Taken from FreeBSD
310  * Find the first occurrence of the byte string s in byte string l.
311  *
312  */
313 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
314     register char *cur, *last;
315     const char *cl = (const char *)l;
316     const char *cs = (const char *)s;
317
318     /* we need something to compare */
319     if (l_len == 0 || s_len == 0)
320         return NULL;
321
322     /* "s" must be smaller or equal to "l" */
323     if (l_len < s_len)
324         return NULL;
325
326     /* special case where s_len == 1 */
327     if (s_len == 1)
328         return memchr(l, (int)*cs, l_len);
329
330     /* the last position where its possible to find "s" in "l" */
331     last = (char *)cl + l_len - s_len;
332
333     for (cur = (char *)cl; cur <= last; cur++)
334         if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
335             return cur;
336
337     return NULL;
338 }
339
340 #endif
341
342 /*
343  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
344  * it exited (or could not be started, depending on the exit code).
345  *
346  */
347 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
348     ev_child_stop(EV_A_ watcher);
349
350     if (!WIFEXITED(watcher->rstatus)) {
351         ELOG("ERROR: i3-nagbar did not exit normally.\n");
352         return;
353     }
354
355     int exitcode = WEXITSTATUS(watcher->rstatus);
356     DLOG("i3-nagbar process exited with status %d\n", exitcode);
357     if (exitcode == 2) {
358         ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
359     }
360
361     *((pid_t *)watcher->data) = -1;
362 }
363
364 /*
365  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
366  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
367  *
368  */
369 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
370     pid_t *nagbar_pid = (pid_t *)watcher->data;
371     if (*nagbar_pid != -1) {
372         LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, *nagbar_pid);
373         kill(*nagbar_pid, SIGKILL);
374     }
375 }
376
377 /*
378  * Starts an i3-nagbar instance with the given parameters. Takes care of
379  * handling SIGCHLD and killing i3-nagbar when i3 exits.
380  *
381  * The resulting PID will be stored in *nagbar_pid and can be used with
382  * kill_nagbar() to kill the bar later on.
383  *
384  */
385 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
386     if (*nagbar_pid != -1) {
387         DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
388         return;
389     }
390
391     *nagbar_pid = fork();
392     if (*nagbar_pid == -1) {
393         warn("Could not fork()");
394         return;
395     }
396
397     /* child */
398     if (*nagbar_pid == 0)
399         exec_i3_utility("i3-nagbar", argv);
400
401     DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
402
403     /* parent */
404     /* install a child watcher */
405     ev_child *child = smalloc(sizeof(ev_child));
406     ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
407     child->data = nagbar_pid;
408     ev_child_start(main_loop, child);
409
410     /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
411      * still running) */
412     ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
413     ev_cleanup_init(cleanup, nagbar_cleanup);
414     cleanup->data = nagbar_pid;
415     ev_cleanup_start(main_loop, cleanup);
416 }
417
418 /*
419  * Kills the i3-nagbar process, if *nagbar_pid != -1.
420  *
421  * If wait_for_it is set (restarting i3), this function will waitpid(),
422  * otherwise, ev is assumed to handle it (reloading).
423  *
424  */
425 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
426     if (*nagbar_pid == -1)
427         return;
428
429     if (kill(*nagbar_pid, SIGTERM) == -1)
430         warn("kill(configerror_nagbar) failed");
431
432     if (!wait_for_it)
433         return;
434
435     /* When restarting, we don’t enter the ev main loop anymore and after the
436      * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
437      * for us and we would end up with a <defunct> process. Therefore we
438      * waitpid() here. */
439     waitpid(*nagbar_pid, NULL, 0);
440 }