2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
7 * util.c: Utility functions, which can be useful everywhere within i3 (see
15 #if defined(__OpenBSD__)
16 #include <sys/cdefs.h>
20 #include <yajl/yajl_version.h>
24 #define SN_API_NOT_YET_FROZEN 1
25 #include <libsn/sn-launcher.h>
27 int min(int a, int b) {
28 return (a < b ? a : b);
31 int max(int a, int b) {
32 return (a > b ? a : b);
35 bool rect_contains(Rect rect, uint32_t x, uint32_t y) {
36 return (x >= rect.x &&
37 x <= (rect.x + rect.width) &&
39 y <= (rect.y + rect.height));
42 Rect rect_add(Rect a, Rect b) {
43 return (Rect){a.x + b.x,
49 Rect rect_sub(Rect a, Rect b) {
50 return (Rect){a.x - b.x,
57 * Returns true if the name consists of only digits.
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]))
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
75 bool layout_from_name(const char *layout_str, layout_t *out) {
76 if (strcmp(layout_str, "default") == 0) {
79 } else if (strcasecmp(layout_str, "stacked") == 0 ||
80 strcasecmp(layout_str, "stacking") == 0) {
83 } else if (strcasecmp(layout_str, "tabbed") == 0) {
86 } else if (strcasecmp(layout_str, "splitv") == 0) {
89 } else if (strcasecmp(layout_str, "splith") == 0) {
98 * Parses the workspace name as a number. Returns -1 if the workspace should be
99 * interpreted as a "named workspace".
102 long ws_name_to_number(const char *name) {
103 /* positive integers and zero are interpreted as numbers */
105 long parsed_num = strtol(name, &endptr, 10);
106 if (parsed_num == LONG_MIN ||
107 parsed_num == LONG_MAX ||
117 * Updates *destination with new_value and returns true if it was changed or false
121 bool update_if_necessary(uint32_t *destination, const uint32_t new_value) {
122 uint32_t old_value = *destination;
124 return ((*destination = new_value) != old_value);
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).
133 * This function should be called after fork()ing.
135 * The first argument of the given argv vector will be overwritten with the
136 * executable name, so pass NULL.
138 * If the utility cannot be found in any of these locations, it exits with
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);
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);
157 #if defined(__linux__)
158 /* on linux, we have one more fall-back: dirname(/proc/self/exe) */
160 if (readlink("/proc/self/exe", buffer, BUFSIZ) == -1) {
161 warn("could not read /proc/self/exe");
164 dir = dirname(buffer);
165 sasprintf(&migratepath, "%s/%s", dir, name);
166 argv[0] = migratepath;
167 execvp(migratepath, argv);
170 warn("Could not start %s", name);
175 * Checks if the given path exists by calling stat().
178 bool path_exists(const char *path) {
180 return (stat(path, &buf) == 0);
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.
187 static char **add_argument(char **original, char *opt_char, char *opt_arg, char *opt_name) {
189 for (num_args = 0; original[num_args] != NULL; num_args++)
191 char **result = scalloc(num_args + 3, sizeof(char *));
193 /* copy the arguments, but skip the ones we'll replace */
195 bool skip_next = false;
196 for (int i = 0; i < num_args; ++i) {
201 if (!strcmp(original[i], opt_char) ||
202 (opt_name && !strcmp(original[i], opt_name))) {
207 result[write_index++] = original[i];
210 /* add the arguments we'll replace */
211 result[write_index++] = opt_char;
212 result[write_index] = opt_arg;
217 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
218 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
220 static char *store_restart_layout(void) {
221 setlocale(LC_NUMERIC, "C");
222 yajl_gen gen = yajl_gen_alloc(NULL);
224 dump_node(gen, croot, true);
226 setlocale(LC_NUMERIC, "");
228 const unsigned char *payload;
230 y(get_buf, &payload, &length);
232 /* create a temporary file if one hasn't been specified, or just
233 * resolve the tildes in the specified path */
235 if (config.restart_state_path == NULL) {
236 filename = get_process_filename("restart-state");
240 filename = resolve_tilde(config.restart_state_path);
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);
252 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
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));
269 DLOG("layout: %.*s\n", (int)length, payload);
278 * Restart i3 in-place
279 * appends -a to argument list to disable autostart
282 void i3_restart(bool forget_layout) {
283 char *restart_filename = forget_layout ? NULL : store_restart_layout();
285 kill_nagbar(&config_error_nagbar_pid, true);
286 kill_nagbar(&command_error_nagbar_pid, true);
290 ipc_shutdown(SHUTDOWN_REASON_RESTART);
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);
296 /* make debuglog-on persist */
297 if (get_debug_logging()) {
298 start_argv = add_argument(start_argv, "-d", "all", NULL);
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");
306 execvp(start_argv[0], start_argv);
311 #if defined(__OpenBSD__) || defined(__APPLE__)
315 * Find the first occurrence of the byte string s in byte string l.
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;
323 /* we need something to compare */
324 if (l_len == 0 || s_len == 0)
327 /* "s" must be smaller or equal to "l" */
331 /* special case where s_len == 1 */
333 return memchr(l, (int)*cs, l_len);
335 /* the last position where its possible to find "s" in "l" */
336 last = (char *)cl + l_len - s_len;
338 for (cur = (char *)cl; cur <= last; cur++)
339 if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
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.
352 char *pango_escape_markup(char *input) {
353 if (!font_is_pango())
356 char *escaped = g_markup_escape_text(input, -1);
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).
367 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
368 ev_child_stop(EV_A_ watcher);
370 if (!WIFEXITED(watcher->rstatus)) {
371 ELOG("ERROR: i3-nagbar did not exit normally.\n");
375 int exitcode = WEXITSTATUS(watcher->rstatus);
376 DLOG("i3-nagbar process exited with status %d\n", exitcode);
378 ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
381 *((pid_t *)watcher->data) = -1;
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.
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);
398 * Starts an i3-nagbar instance with the given parameters. Takes care of
399 * handling SIGCHLD and killing i3-nagbar when i3 exits.
401 * The resulting PID will be stored in *nagbar_pid and can be used with
402 * kill_nagbar() to kill the bar later on.
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);
411 *nagbar_pid = fork();
412 if (*nagbar_pid == -1) {
413 warn("Could not fork()");
418 if (*nagbar_pid == 0)
419 exec_i3_utility("i3-nagbar", argv);
421 DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
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);
430 /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
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);
439 * Kills the i3-nagbar process, if *nagbar_pid != -1.
441 * If wait_for_it is set (restarting i3), this function will waitpid(),
442 * otherwise, ev is assumed to handle it (reloading).
445 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
446 if (*nagbar_pid == -1)
449 if (kill(*nagbar_pid, SIGTERM) == -1)
450 warn("kill(configerror_nagbar) failed");
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
459 waitpid(*nagbar_pid, NULL, 0);
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.
467 bool parse_long(const char *str, long *out, int base) {
469 long result = strtol(str, &end, base);
470 if (result == LONG_MIN || result == LONG_MAX || result < 0 || (end != NULL && *end != '\0')) {
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.
485 ssize_t slurp(const char *path, char **buf) {
487 if ((f = fopen(path, "r")) == NULL) {
488 ELOG("Cannot open file \"%s\": %s\n", path, strerror(errno));
492 if (fstat(fileno(f), &stbuf) != 0) {
493 ELOG("Cannot fstat() \"%s\": %s\n", path, strerror(errno));
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);
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);
511 * Convert a direction to its corresponding orientation.
514 orientation_t orientation_from_direction(direction_t direction) {
515 return (direction == D_LEFT || direction == D_RIGHT) ? HORIZ : VERT;