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,
52 * Returns true if the name consists of only digits.
55 __attribute__ ((pure)) bool name_is_digits(const char *name) {
56 /* positive integers and zero are interpreted as numbers */
57 for (int i = 0; i < strlen(name); i++)
58 if (!isdigit(name[i]))
65 * Parses the workspace name as a number. Returns -1 if the workspace should be
66 * interpreted as a "named workspace".
69 long ws_name_to_number(const char *name) {
70 /* positive integers and zero are interpreted as numbers */
72 long parsed_num = strtol(name, &endptr, 10);
73 if (parsed_num == LONG_MIN ||
74 parsed_num == LONG_MAX ||
84 * Updates *destination with new_value and returns true if it was changed or false
88 bool update_if_necessary(uint32_t *destination, const uint32_t new_value) {
89 uint32_t old_value = *destination;
91 return ((*destination = new_value) != old_value);
95 * exec()s an i3 utility, for example the config file migration script or
96 * i3-nagbar. This function first searches $PATH for the given utility named,
97 * then falls back to the dirname() of the i3 executable path and then falls
98 * back to the dirname() of the target of /proc/self/exe (on linux).
100 * This function should be called after fork()ing.
102 * The first argument of the given argv vector will be overwritten with the
103 * executable name, so pass NULL.
105 * If the utility cannot be found in any of these locations, it exits with
109 void exec_i3_utility(char *name, char *argv[]) {
110 /* start the migration script, search PATH first */
111 char *migratepath = name;
112 argv[0] = migratepath;
113 execvp(migratepath, argv);
115 /* if the script is not in path, maybe the user installed to a strange
116 * location and runs the i3 binary with an absolute path. We use
117 * argv[0]’s dirname */
118 char *pathbuf = strdup(start_argv[0]);
119 char *dir = dirname(pathbuf);
120 sasprintf(&migratepath, "%s/%s", dir, name);
121 argv[0] = migratepath;
122 execvp(migratepath, argv);
124 #if defined(__linux__)
125 /* on linux, we have one more fall-back: dirname(/proc/self/exe) */
127 if (readlink("/proc/self/exe", buffer, BUFSIZ) == -1) {
128 warn("could not read /proc/self/exe");
131 dir = dirname(buffer);
132 sasprintf(&migratepath, "%s/%s", dir, name);
133 argv[0] = migratepath;
134 execvp(migratepath, argv);
137 warn("Could not start %s", name);
142 * Checks a generic cookie for errors and quits with the given message if there
146 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
147 xcb_generic_error_t *error = xcb_request_check(conn, cookie);
149 fprintf(stderr, "ERROR: %s (X error %d)\n", err_message , error->error_code);
150 xcb_disconnect(conn);
156 * This function resolves ~ in pathnames.
157 * It may resolve wildcards in the first part of the path, but if no match
158 * or multiple matches are found, it just returns a copy of path as given.
161 char *resolve_tilde(const char *path) {
162 static glob_t globbuf;
163 char *head, *tail, *result;
165 tail = strchr(path, '/');
166 head = strndup(path, tail ? (size_t)(tail - path) : strlen(path));
168 int res = glob(head, GLOB_TILDE, NULL, &globbuf);
170 /* no match, or many wildcard matches are bad */
171 if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
172 result = sstrdup(path);
174 die("glob() failed");
176 head = globbuf.gl_pathv[0];
177 result = scalloc(strlen(head) + (tail ? strlen(tail) : 0) + 1);
178 strncpy(result, head, strlen(head));
180 strncat(result, tail, strlen(tail));
188 * Checks if the given path exists by calling stat().
191 bool path_exists(const char *path) {
193 return (stat(path, &buf) == 0);
197 * Goes through the list of arguments (for exec()) and checks if the given argument
198 * is present. If not, it copies the arguments (because we cannot realloc it) and
199 * appends the given argument.
202 static char **append_argument(char **original, char *argument) {
204 for (num_args = 0; original[num_args] != NULL; num_args++) {
205 DLOG("original argument: \"%s\"\n", original[num_args]);
206 /* If the argument is already present we return the original pointer */
207 if (strcmp(original[num_args], argument) == 0)
210 /* Copy the original array */
211 char **result = smalloc((num_args+2) * sizeof(char*));
212 memcpy(result, original, num_args * sizeof(char*));
213 result[num_args] = argument;
214 result[num_args+1] = NULL;
219 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
220 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
222 char *store_restart_layout(void) {
223 setlocale(LC_NUMERIC, "C");
224 yajl_gen gen = yajl_gen_alloc(NULL);
226 dump_node(gen, croot, true);
228 setlocale(LC_NUMERIC, "");
230 const unsigned char *payload;
232 y(get_buf, &payload, &length);
234 /* create a temporary file if one hasn't been specified, or just
235 * resolve the tildes in the specified path */
237 if (config.restart_state_path == NULL) {
238 filename = get_process_filename("restart-state");
242 filename = resolve_tilde(config.restart_state_path);
245 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
253 while (written < length) {
254 int n = write(fd, payload + written, length - written);
255 /* TODO: correct error-handling */
263 printf("write == 0?\n");
269 DLOG("written: %zd of %zd\n", written, length);
274 printf("layout: %.*s\n", (int)length, payload);
283 * Restart i3 in-place
284 * appends -a to argument list to disable autostart
287 void i3_restart(bool forget_layout) {
288 char *restart_filename = forget_layout ? NULL : store_restart_layout();
290 kill_nagbar(&config_error_nagbar_pid, true);
291 kill_nagbar(&command_error_nagbar_pid, true);
297 LOG("restarting \"%s\"...\n", start_argv[0]);
298 /* make sure -a is in the argument list or append it */
299 start_argv = append_argument(start_argv, "-a");
301 /* replace -r <file> so that the layout is restored */
302 if (restart_filename != NULL) {
303 /* create the new argv */
305 for (num_args = 0; start_argv[num_args] != NULL; num_args++);
306 char **new_argv = scalloc((num_args + 3) * sizeof(char*));
308 /* copy the arguments, but skip the ones we'll replace */
310 bool skip_next = false;
311 for (int i = 0; i < num_args; ++i) {
314 else if (!strcmp(start_argv[i], "-r") ||
315 !strcmp(start_argv[i], "--restart"))
318 new_argv[write_index++] = start_argv[i];
321 /* add the arguments we'll replace */
322 new_argv[write_index++] = "--restart";
323 new_argv[write_index] = restart_filename;
326 start_argv = new_argv;
329 execvp(start_argv[0], start_argv);
333 #if defined(__OpenBSD__) || defined(__APPLE__)
337 * Find the first occurrence of the byte string s in byte string l.
340 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
341 register char *cur, *last;
342 const char *cl = (const char *)l;
343 const char *cs = (const char *)s;
345 /* we need something to compare */
346 if (l_len == 0 || s_len == 0)
349 /* "s" must be smaller or equal to "l" */
353 /* special case where s_len == 1 */
355 return memchr(l, (int)*cs, l_len);
357 /* the last position where its possible to find "s" in "l" */
358 last = (char *)cl + l_len - s_len;
360 for (cur = (char *)cl; cur <= last; cur++)
361 if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
370 * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
371 * it exited (or could not be started, depending on the exit code).
374 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
375 ev_child_stop(EV_A_ watcher);
377 if (!WIFEXITED(watcher->rstatus)) {
378 ELOG("ERROR: i3-nagbar did not exit normally.\n");
382 int exitcode = WEXITSTATUS(watcher->rstatus);
383 DLOG("i3-nagbar process exited with status %d\n", exitcode);
385 ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
388 *((pid_t*)watcher->data) = -1;
392 * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
393 * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
396 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
397 pid_t *nagbar_pid = (pid_t*)watcher->data;
398 if (*nagbar_pid != -1) {
399 LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, *nagbar_pid);
400 kill(*nagbar_pid, SIGKILL);
405 * Starts an i3-nagbar instance with the given parameters. Takes care of
406 * handling SIGCHLD and killing i3-nagbar when i3 exits.
408 * The resulting PID will be stored in *nagbar_pid and can be used with
409 * kill_nagbar() to kill the bar later on.
412 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
413 if (*nagbar_pid != -1) {
414 DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
418 *nagbar_pid = fork();
419 if (*nagbar_pid == -1) {
420 warn("Could not fork()");
425 if (*nagbar_pid == 0)
426 exec_i3_utility("i3-nagbar", argv);
428 DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
431 /* install a child watcher */
432 ev_child *child = smalloc(sizeof(ev_child));
433 ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
434 child->data = nagbar_pid;
435 ev_child_start(main_loop, child);
437 /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
439 ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
440 ev_cleanup_init(cleanup, nagbar_cleanup);
441 cleanup->data = nagbar_pid;
442 ev_cleanup_start(main_loop, cleanup);
446 * Kills the i3-nagbar process, if *nagbar_pid != -1.
448 * If wait_for_it is set (restarting i3), this function will waitpid(),
449 * otherwise, ev is assumed to handle it (reloading).
452 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
453 if (*nagbar_pid == -1)
456 if (kill(*nagbar_pid, SIGTERM) == -1)
457 warn("kill(configerror_nagbar) failed");
462 /* When restarting, we don’t enter the ev main loop anymore and after the
463 * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
464 * for us and we would end up with a <defunct> process. Therefore we
466 waitpid(*nagbar_pid, NULL, 0);