2 #define I3__FILE__ "util.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
9 * util.c: Utility functions, which can be useful everywhere within i3 (see
17 #if defined(__OpenBSD__)
18 #include <sys/cdefs.h>
22 #include <yajl/yajl_version.h>
26 #define SN_API_NOT_YET_FROZEN 1
27 #include <libsn/sn-launcher.h>
29 int min(int a, int b) {
30 return (a < b ? a : b);
33 int max(int a, int b) {
34 return (a > b ? a : b);
37 bool rect_contains(Rect rect, uint32_t x, uint32_t y) {
38 return (x >= rect.x &&
39 x <= (rect.x + rect.width) &&
41 y <= (rect.y + rect.height));
44 Rect rect_add(Rect a, Rect b) {
45 return (Rect){a.x + b.x,
51 Rect rect_sub(Rect a, Rect b) {
52 return (Rect){a.x - b.x,
59 * Returns true if the name consists of only digits.
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]))
72 * Parses the workspace name as a number. Returns -1 if the workspace should be
73 * interpreted as a "named workspace".
76 long ws_name_to_number(const char *name) {
77 /* positive integers and zero are interpreted as numbers */
79 long parsed_num = strtol(name, &endptr, 10);
80 if (parsed_num == LONG_MIN ||
81 parsed_num == LONG_MAX ||
91 * Updates *destination with new_value and returns true if it was changed or false
95 bool update_if_necessary(uint32_t *destination, const uint32_t new_value) {
96 uint32_t old_value = *destination;
98 return ((*destination = new_value) != old_value);
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).
107 * This function should be called after fork()ing.
109 * The first argument of the given argv vector will be overwritten with the
110 * executable name, so pass NULL.
112 * If the utility cannot be found in any of these locations, it exits with
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);
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 = strdup(start_argv[0]);
126 char *dir = dirname(pathbuf);
127 sasprintf(&migratepath, "%s/%s", dir, name);
128 argv[0] = migratepath;
129 execvp(migratepath, argv);
131 #if defined(__linux__)
132 /* on linux, we have one more fall-back: dirname(/proc/self/exe) */
134 if (readlink("/proc/self/exe", buffer, BUFSIZ) == -1) {
135 warn("could not read /proc/self/exe");
138 dir = dirname(buffer);
139 sasprintf(&migratepath, "%s/%s", dir, name);
140 argv[0] = migratepath;
141 execvp(migratepath, argv);
144 warn("Could not start %s", name);
149 * Checks a generic cookie for errors and quits with the given message if there
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);
156 fprintf(stderr, "ERROR: %s (X error %d)\n", err_message, error->error_code);
157 xcb_disconnect(conn);
163 * This function resolves ~ in pathnames.
164 * It may resolve wildcards in the first part of the path, but if no match
165 * or multiple matches are found, it just returns a copy of path as given.
168 char *resolve_tilde(const char *path) {
169 static glob_t globbuf;
170 char *head, *tail, *result;
172 tail = strchr(path, '/');
173 head = strndup(path, tail ? (size_t)(tail - path) : strlen(path));
175 int res = glob(head, GLOB_TILDE, NULL, &globbuf);
177 /* no match, or many wildcard matches are bad */
178 if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
179 result = sstrdup(path);
181 die("glob() failed");
183 head = globbuf.gl_pathv[0];
184 result = scalloc(strlen(head) + (tail ? strlen(tail) : 0) + 1);
185 strncpy(result, head, strlen(head));
187 strncat(result, tail, strlen(tail));
195 * Checks if the given path exists by calling stat().
198 bool path_exists(const char *path) {
200 return (stat(path, &buf) == 0);
204 * Goes through the list of arguments (for exec()) and checks if the given argument
205 * is present. If not, it copies the arguments (because we cannot realloc it) and
206 * appends the given argument.
209 static char **append_argument(char **original, char *argument) {
211 for (num_args = 0; original[num_args] != NULL; num_args++) {
212 DLOG("original argument: \"%s\"\n", original[num_args]);
213 /* If the argument is already present we return the original pointer */
214 if (strcmp(original[num_args], argument) == 0)
217 /* Copy the original array */
218 char **result = smalloc((num_args + 2) * sizeof(char *));
219 memcpy(result, original, num_args * sizeof(char *));
220 result[num_args] = argument;
221 result[num_args + 1] = NULL;
226 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
227 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
229 char *store_restart_layout(void) {
230 setlocale(LC_NUMERIC, "C");
231 yajl_gen gen = yajl_gen_alloc(NULL);
233 dump_node(gen, croot, true);
235 setlocale(LC_NUMERIC, "");
237 const unsigned char *payload;
239 y(get_buf, &payload, &length);
241 /* create a temporary file if one hasn't been specified, or just
242 * resolve the tildes in the specified path */
244 if (config.restart_state_path == NULL) {
245 filename = get_process_filename("restart-state");
249 filename = resolve_tilde(config.restart_state_path);
252 /* create the directory, it could have been cleaned up before restarting or
253 * may not exist at all in case it was user-specified. */
254 char *filenamecopy = sstrdup(filename);
255 char *base = dirname(filenamecopy);
256 DLOG("Creating \"%s\" for storing the restart layout\n", base);
258 ELOG("Could not create \"%s\" for storing the restart layout, layout will be lost.\n", base);
261 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
268 if (writeall(fd, payload, length) == -1) {
269 ELOG("Could not write restart layout to \"%s\", layout will be lost: %s\n", filename, strerror(errno));
278 DLOG("layout: %.*s\n", (int)length, payload);
287 * Restart i3 in-place
288 * appends -a to argument list to disable autostart
291 void i3_restart(bool forget_layout) {
292 char *restart_filename = forget_layout ? NULL : store_restart_layout();
294 kill_nagbar(&config_error_nagbar_pid, true);
295 kill_nagbar(&command_error_nagbar_pid, true);
301 LOG("restarting \"%s\"...\n", start_argv[0]);
302 /* make sure -a is in the argument list or append it */
303 start_argv = append_argument(start_argv, "-a");
305 /* replace -r <file> so that the layout is restored */
306 if (restart_filename != NULL) {
307 /* create the new argv */
309 for (num_args = 0; start_argv[num_args] != NULL; num_args++)
311 char **new_argv = scalloc((num_args + 3) * sizeof(char *));
313 /* copy the arguments, but skip the ones we'll replace */
315 bool skip_next = false;
316 for (int i = 0; i < num_args; ++i) {
319 else if (!strcmp(start_argv[i], "-r") ||
320 !strcmp(start_argv[i], "--restart"))
323 new_argv[write_index++] = start_argv[i];
326 /* add the arguments we'll replace */
327 new_argv[write_index++] = "--restart";
328 new_argv[write_index] = restart_filename;
331 start_argv = new_argv;
334 execvp(start_argv[0], start_argv);
338 #if defined(__OpenBSD__) || defined(__APPLE__)
342 * Find the first occurrence of the byte string s in byte string l.
345 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
346 register char *cur, *last;
347 const char *cl = (const char *)l;
348 const char *cs = (const char *)s;
350 /* we need something to compare */
351 if (l_len == 0 || s_len == 0)
354 /* "s" must be smaller or equal to "l" */
358 /* special case where s_len == 1 */
360 return memchr(l, (int)*cs, l_len);
362 /* the last position where its possible to find "s" in "l" */
363 last = (char *)cl + l_len - s_len;
365 for (cur = (char *)cl; cur <= last; cur++)
366 if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
375 * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
376 * it exited (or could not be started, depending on the exit code).
379 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
380 ev_child_stop(EV_A_ watcher);
382 if (!WIFEXITED(watcher->rstatus)) {
383 ELOG("ERROR: i3-nagbar did not exit normally.\n");
387 int exitcode = WEXITSTATUS(watcher->rstatus);
388 DLOG("i3-nagbar process exited with status %d\n", exitcode);
390 ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
393 *((pid_t *)watcher->data) = -1;
397 * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
398 * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
401 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
402 pid_t *nagbar_pid = (pid_t *)watcher->data;
403 if (*nagbar_pid != -1) {
404 LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, *nagbar_pid);
405 kill(*nagbar_pid, SIGKILL);
410 * Starts an i3-nagbar instance with the given parameters. Takes care of
411 * handling SIGCHLD and killing i3-nagbar when i3 exits.
413 * The resulting PID will be stored in *nagbar_pid and can be used with
414 * kill_nagbar() to kill the bar later on.
417 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
418 if (*nagbar_pid != -1) {
419 DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
423 *nagbar_pid = fork();
424 if (*nagbar_pid == -1) {
425 warn("Could not fork()");
430 if (*nagbar_pid == 0)
431 exec_i3_utility("i3-nagbar", argv);
433 DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
436 /* install a child watcher */
437 ev_child *child = smalloc(sizeof(ev_child));
438 ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
439 child->data = nagbar_pid;
440 ev_child_start(main_loop, child);
442 /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
444 ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
445 ev_cleanup_init(cleanup, nagbar_cleanup);
446 cleanup->data = nagbar_pid;
447 ev_cleanup_start(main_loop, cleanup);
451 * Kills the i3-nagbar process, if *nagbar_pid != -1.
453 * If wait_for_it is set (restarting i3), this function will waitpid(),
454 * otherwise, ev is assumed to handle it (reloading).
457 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
458 if (*nagbar_pid == -1)
461 if (kill(*nagbar_pid, SIGTERM) == -1)
462 warn("kill(configerror_nagbar) failed");
467 /* When restarting, we don’t enter the ev main loop anymore and after the
468 * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
469 * for us and we would end up with a <defunct> process. Therefore we
471 waitpid(*nagbar_pid, NULL, 0);