2 #define I3__FILE__ "util.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009 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 = sstrdup(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 * Checks if the given path exists by calling stat().
166 bool path_exists(const char *path) {
168 return (stat(path, &buf) == 0);
172 * Goes through the list of arguments (for exec()) and add/replace the given option,
173 * including the option name, its argument, and the option character.
175 static char **add_argument(char **original, char *opt_char, char *opt_arg, char *opt_name) {
177 for (num_args = 0; original[num_args] != NULL; num_args++)
179 char **result = scalloc(num_args + 3, sizeof(char *));
181 /* copy the arguments, but skip the ones we'll replace */
183 bool skip_next = false;
184 for (int i = 0; i < num_args; ++i) {
189 if (!strcmp(original[i], opt_char) ||
190 (opt_name && !strcmp(original[i], opt_name))) {
195 result[write_index++] = original[i];
198 /* add the arguments we'll replace */
199 result[write_index++] = opt_char;
200 result[write_index] = opt_arg;
205 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
206 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
208 char *store_restart_layout(void) {
209 setlocale(LC_NUMERIC, "C");
210 yajl_gen gen = yajl_gen_alloc(NULL);
212 dump_node(gen, croot, true);
214 setlocale(LC_NUMERIC, "");
216 const unsigned char *payload;
218 y(get_buf, &payload, &length);
220 /* create a temporary file if one hasn't been specified, or just
221 * resolve the tildes in the specified path */
223 if (config.restart_state_path == NULL) {
224 filename = get_process_filename("restart-state");
228 filename = resolve_tilde(config.restart_state_path);
231 /* create the directory, it could have been cleaned up before restarting or
232 * may not exist at all in case it was user-specified. */
233 char *filenamecopy = sstrdup(filename);
234 char *base = dirname(filenamecopy);
235 DLOG("Creating \"%s\" for storing the restart layout\n", base);
236 if (mkdirp(base, DEFAULT_DIR_MODE) != 0)
237 ELOG("Could not create \"%s\" for storing the restart layout, layout will be lost.\n", base);
240 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
247 if (writeall(fd, payload, length) == -1) {
248 ELOG("Could not write restart layout to \"%s\", layout will be lost: %s\n", filename, strerror(errno));
257 DLOG("layout: %.*s\n", (int)length, payload);
266 * Restart i3 in-place
267 * appends -a to argument list to disable autostart
270 void i3_restart(bool forget_layout) {
271 char *restart_filename = forget_layout ? NULL : store_restart_layout();
273 kill_nagbar(&config_error_nagbar_pid, true);
274 kill_nagbar(&command_error_nagbar_pid, true);
280 LOG("restarting \"%s\"...\n", start_argv[0]);
281 /* make sure -a is in the argument list or add it */
282 start_argv = add_argument(start_argv, "-a", NULL, NULL);
284 /* make debuglog-on persist */
285 if (get_debug_logging()) {
286 start_argv = add_argument(start_argv, "-d", "all", NULL);
289 /* replace -r <file> so that the layout is restored */
290 if (restart_filename != NULL) {
291 start_argv = add_argument(start_argv, "--restart", restart_filename, "-r");
294 execvp(start_argv[0], start_argv);
299 #if defined(__OpenBSD__) || defined(__APPLE__)
303 * Find the first occurrence of the byte string s in byte string l.
306 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
307 register char *cur, *last;
308 const char *cl = (const char *)l;
309 const char *cs = (const char *)s;
311 /* we need something to compare */
312 if (l_len == 0 || s_len == 0)
315 /* "s" must be smaller or equal to "l" */
319 /* special case where s_len == 1 */
321 return memchr(l, (int)*cs, l_len);
323 /* the last position where its possible to find "s" in "l" */
324 last = (char *)cl + l_len - s_len;
326 for (cur = (char *)cl; cur <= last; cur++)
327 if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
336 * Escapes the given string if a pango font is currently used.
337 * If the string has to be escaped, the input string will be free'd.
340 char *pango_escape_markup(char *input) {
341 if (!font_is_pango())
344 char *escaped = g_markup_escape_text(input, -1);
351 * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
352 * it exited (or could not be started, depending on the exit code).
355 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
356 ev_child_stop(EV_A_ watcher);
358 if (!WIFEXITED(watcher->rstatus)) {
359 ELOG("ERROR: i3-nagbar did not exit normally.\n");
363 int exitcode = WEXITSTATUS(watcher->rstatus);
364 DLOG("i3-nagbar process exited with status %d\n", exitcode);
366 ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
369 *((pid_t *)watcher->data) = -1;
373 * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
374 * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
377 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
378 pid_t *nagbar_pid = (pid_t *)watcher->data;
379 if (*nagbar_pid != -1) {
380 LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, *nagbar_pid);
381 kill(*nagbar_pid, SIGKILL);
386 * Starts an i3-nagbar instance with the given parameters. Takes care of
387 * handling SIGCHLD and killing i3-nagbar when i3 exits.
389 * The resulting PID will be stored in *nagbar_pid and can be used with
390 * kill_nagbar() to kill the bar later on.
393 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
394 if (*nagbar_pid != -1) {
395 DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
399 *nagbar_pid = fork();
400 if (*nagbar_pid == -1) {
401 warn("Could not fork()");
406 if (*nagbar_pid == 0)
407 exec_i3_utility("i3-nagbar", argv);
409 DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
412 /* install a child watcher */
413 ev_child *child = smalloc(sizeof(ev_child));
414 ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
415 child->data = nagbar_pid;
416 ev_child_start(main_loop, child);
418 /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
420 ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
421 ev_cleanup_init(cleanup, nagbar_cleanup);
422 cleanup->data = nagbar_pid;
423 ev_cleanup_start(main_loop, cleanup);
427 * Kills the i3-nagbar process, if *nagbar_pid != -1.
429 * If wait_for_it is set (restarting i3), this function will waitpid(),
430 * otherwise, ev is assumed to handle it (reloading).
433 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
434 if (*nagbar_pid == -1)
437 if (kill(*nagbar_pid, SIGTERM) == -1)
438 warn("kill(configerror_nagbar) failed");
443 /* When restarting, we don’t enter the ev main loop anymore and after the
444 * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
445 * for us and we would end up with a <defunct> process. Therefore we
447 waitpid(*nagbar_pid, NULL, 0);