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) {
78 } else if (strcasecmp(layout_str, "stacked") == 0 ||
79 strcasecmp(layout_str, "stacking") == 0) {
81 } else if (strcasecmp(layout_str, "tabbed") == 0) {
83 } else if (strcasecmp(layout_str, "splitv") == 0) {
85 } else if (strcasecmp(layout_str, "splith") == 0) {
95 * Parses the workspace name as a number. Returns -1 if the workspace should be
96 * interpreted as a "named workspace".
99 long ws_name_to_number(const char *name) {
100 /* positive integers and zero are interpreted as numbers */
102 long parsed_num = strtol(name, &endptr, 10);
103 if (parsed_num == LONG_MIN ||
104 parsed_num == LONG_MAX ||
114 * Updates *destination with new_value and returns true if it was changed or false
118 bool update_if_necessary(uint32_t *destination, const uint32_t new_value) {
119 uint32_t old_value = *destination;
121 return ((*destination = new_value) != old_value);
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).
130 * This function should be called after fork()ing.
132 * The first argument of the given argv vector will be overwritten with the
133 * executable name, so pass NULL.
135 * If the utility cannot be found in any of these locations, it exits with
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);
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);
154 #if defined(__linux__)
155 /* on linux, we have one more fall-back: dirname(/proc/self/exe) */
157 if (readlink("/proc/self/exe", buffer, BUFSIZ) == -1) {
158 warn("could not read /proc/self/exe");
161 dir = dirname(buffer);
162 sasprintf(&migratepath, "%s/%s", dir, name);
163 argv[0] = migratepath;
164 execvp(migratepath, argv);
167 warn("Could not start %s", name);
172 * Checks if the given path exists by calling stat().
175 bool path_exists(const char *path) {
177 return (stat(path, &buf) == 0);
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.
184 static char **add_argument(char **original, char *opt_char, char *opt_arg, char *opt_name) {
186 for (num_args = 0; original[num_args] != NULL; num_args++)
188 char **result = scalloc(num_args + 3, sizeof(char *));
190 /* copy the arguments, but skip the ones we'll replace */
192 bool skip_next = false;
193 for (int i = 0; i < num_args; ++i) {
198 if (!strcmp(original[i], opt_char) ||
199 (opt_name && !strcmp(original[i], opt_name))) {
204 result[write_index++] = original[i];
207 /* add the arguments we'll replace */
208 result[write_index++] = opt_char;
209 result[write_index] = opt_arg;
214 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
215 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
217 char *store_restart_layout(void) {
218 setlocale(LC_NUMERIC, "C");
219 yajl_gen gen = yajl_gen_alloc(NULL);
221 dump_node(gen, croot, true);
223 setlocale(LC_NUMERIC, "");
225 const unsigned char *payload;
227 y(get_buf, &payload, &length);
229 /* create a temporary file if one hasn't been specified, or just
230 * resolve the tildes in the specified path */
232 if (config.restart_state_path == NULL) {
233 filename = get_process_filename("restart-state");
237 filename = resolve_tilde(config.restart_state_path);
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);
249 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
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));
266 DLOG("layout: %.*s\n", (int)length, payload);
275 * Restart i3 in-place
276 * appends -a to argument list to disable autostart
279 void i3_restart(bool forget_layout) {
280 char *restart_filename = forget_layout ? NULL : store_restart_layout();
282 kill_nagbar(&config_error_nagbar_pid, true);
283 kill_nagbar(&command_error_nagbar_pid, true);
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);
293 /* make debuglog-on persist */
294 if (get_debug_logging()) {
295 start_argv = add_argument(start_argv, "-d", "all", NULL);
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");
303 execvp(start_argv[0], start_argv);
308 #if defined(__OpenBSD__) || defined(__APPLE__)
312 * Find the first occurrence of the byte string s in byte string l.
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;
320 /* we need something to compare */
321 if (l_len == 0 || s_len == 0)
324 /* "s" must be smaller or equal to "l" */
328 /* special case where s_len == 1 */
330 return memchr(l, (int)*cs, l_len);
332 /* the last position where its possible to find "s" in "l" */
333 last = (char *)cl + l_len - s_len;
335 for (cur = (char *)cl; cur <= last; cur++)
336 if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
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.
349 char *pango_escape_markup(char *input) {
350 if (!font_is_pango())
353 char *escaped = g_markup_escape_text(input, -1);
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).
364 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
365 ev_child_stop(EV_A_ watcher);
367 if (!WIFEXITED(watcher->rstatus)) {
368 ELOG("ERROR: i3-nagbar did not exit normally.\n");
372 int exitcode = WEXITSTATUS(watcher->rstatus);
373 DLOG("i3-nagbar process exited with status %d\n", exitcode);
375 ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
378 *((pid_t *)watcher->data) = -1;
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.
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);
395 * Starts an i3-nagbar instance with the given parameters. Takes care of
396 * handling SIGCHLD and killing i3-nagbar when i3 exits.
398 * The resulting PID will be stored in *nagbar_pid and can be used with
399 * kill_nagbar() to kill the bar later on.
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);
408 *nagbar_pid = fork();
409 if (*nagbar_pid == -1) {
410 warn("Could not fork()");
415 if (*nagbar_pid == 0)
416 exec_i3_utility("i3-nagbar", argv);
418 DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
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);
427 /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
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);
436 * Kills the i3-nagbar process, if *nagbar_pid != -1.
438 * If wait_for_it is set (restarting i3), this function will waitpid(),
439 * otherwise, ev is assumed to handle it (reloading).
442 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
443 if (*nagbar_pid == -1)
446 if (kill(*nagbar_pid, SIGTERM) == -1)
447 warn("kill(configerror_nagbar) failed");
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
456 waitpid(*nagbar_pid, NULL, 0);