i3
util.c
Go to the documentation of this file.
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * util.c: Utility functions, which can be useful everywhere within i3 (see
8  * also libi3).
9  *
10  */
11 #include "all.h"
12 
13 #include <ctype.h>
14 #include <fcntl.h>
15 #include <inttypes.h>
16 #include <libgen.h>
17 #include <locale.h>
18 #include <sys/wait.h>
19 #include <unistd.h>
20 #if defined(__OpenBSD__)
21 #include <sys/cdefs.h>
22 #endif
23 
24 int min(int a, int b) {
25  return (a < b ? a : b);
26 }
27 
28 int max(int a, int b) {
29  return (a > b ? a : b);
30 }
31 
32 bool rect_contains(Rect rect, uint32_t x, uint32_t y) {
33  return (x >= rect.x &&
34  x <= (rect.x + rect.width) &&
35  y >= rect.y &&
36  y <= (rect.y + rect.height));
37 }
38 
40  return (Rect){a.x + b.x,
41  a.y + b.y,
42  a.width + b.width,
43  a.height + b.height};
44 }
45 
47  return (Rect){a.x - b.x,
48  a.y - b.y,
49  a.width - b.width,
50  a.height - b.height};
51 }
52 
54  rect.width = (int32_t)rect.width <= 0 ? 1 : rect.width;
55  rect.height = (int32_t)rect.height <= 0 ? 1 : rect.height;
56  return rect;
57 }
58 
59 bool rect_equals(Rect a, Rect b) {
60  return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height;
61 }
62 
63 /*
64  * Returns true if the name consists of only digits.
65  *
66  */
67 __attribute__((pure)) bool name_is_digits(const char *name) {
68  /* positive integers and zero are interpreted as numbers */
69  for (size_t i = 0; i < strlen(name); i++)
70  if (!isdigit(name[i]))
71  return false;
72 
73  return true;
74 }
75 
76 /*
77  * Set 'out' to the layout_t value for the given layout. The function
78  * returns true on success or false if the passed string is not a valid
79  * layout name.
80  *
81  */
82 bool layout_from_name(const char *layout_str, layout_t *out) {
83  if (strcmp(layout_str, "default") == 0) {
84  *out = L_DEFAULT;
85  return true;
86  } else if (strcasecmp(layout_str, "stacked") == 0 ||
87  strcasecmp(layout_str, "stacking") == 0) {
88  *out = L_STACKED;
89  return true;
90  } else if (strcasecmp(layout_str, "tabbed") == 0) {
91  *out = L_TABBED;
92  return true;
93  } else if (strcasecmp(layout_str, "splitv") == 0) {
94  *out = L_SPLITV;
95  return true;
96  } else if (strcasecmp(layout_str, "splith") == 0) {
97  *out = L_SPLITH;
98  return true;
99  }
100 
101  return false;
102 }
103 
104 /*
105  * Parses the workspace name as a number. Returns -1 if the workspace should be
106  * interpreted as a "named workspace".
107  *
108  */
109 int ws_name_to_number(const char *name) {
110  /* positive integers and zero are interpreted as numbers */
111  char *endptr = NULL;
112  errno = 0;
113  long long parsed_num = strtoll(name, &endptr, 10);
114  if (errno != 0 || parsed_num > INT32_MAX || parsed_num < 0 || endptr == name) {
115  parsed_num = -1;
116  }
117 
118  return parsed_num;
119 }
120 
121 /*
122  * Updates *destination with new_value and returns true if it was changed or false
123  * if it was the same
124  *
125  */
126 bool update_if_necessary(uint32_t *destination, const uint32_t new_value) {
127  uint32_t old_value = *destination;
128 
129  return ((*destination = new_value) != old_value);
130 }
131 
132 /*
133  * exec()s an i3 utility, for example the config file migration script or
134  * i3-nagbar. This function first searches $PATH for the given utility named,
135  * then falls back to the dirname() of the i3 executable path and then falls
136  * back to the dirname() of the target of /proc/self/exe (on linux).
137  *
138  * This function should be called after fork()ing.
139  *
140  * The first argument of the given argv vector will be overwritten with the
141  * executable name, so pass NULL.
142  *
143  * If the utility cannot be found in any of these locations, it exits with
144  * return code 2.
145  *
146  */
147 void exec_i3_utility(char *name, char *argv[]) {
148  /* start the migration script, search PATH first */
149  char *migratepath = name;
150  argv[0] = migratepath;
151  execvp(migratepath, argv);
152 
153  /* if the script is not in path, maybe the user installed to a strange
154  * location and runs the i3 binary with an absolute path. We use
155  * argv[0]’s dirname */
156  char *pathbuf = sstrdup(start_argv[0]);
157  char *dir = dirname(pathbuf);
158  sasprintf(&migratepath, "%s/%s", dir, name);
159  argv[0] = migratepath;
160  execvp(migratepath, argv);
161 
162 #if defined(__linux__)
163  /* on linux, we have one more fall-back: dirname(/proc/self/exe) */
164  char buffer[BUFSIZ];
165  if (readlink("/proc/self/exe", buffer, BUFSIZ) == -1) {
166  warn("could not read /proc/self/exe");
167  _exit(EXIT_FAILURE);
168  }
169  dir = dirname(buffer);
170  sasprintf(&migratepath, "%s/%s", dir, name);
171  argv[0] = migratepath;
172  execvp(migratepath, argv);
173 #endif
174 
175  warn("Could not start %s", name);
176  _exit(2);
177 }
178 
179 /*
180  * Checks if the given path exists by calling stat().
181  *
182  */
183 bool path_exists(const char *path) {
184  struct stat buf;
185  return (stat(path, &buf) == 0);
186 }
187 
188 /*
189  * Goes through the list of arguments (for exec()) and add/replace the given option,
190  * including the option name, its argument, and the option character.
191  */
192 static char **add_argument(char **original, char *opt_char, char *opt_arg, char *opt_name) {
193  int num_args;
194  for (num_args = 0; original[num_args] != NULL; num_args++)
195  ;
196  char **result = scalloc(num_args + 3, sizeof(char *));
197 
198  /* copy the arguments, but skip the ones we'll replace */
199  int write_index = 0;
200  bool skip_next = false;
201  for (int i = 0; i < num_args; ++i) {
202  if (skip_next) {
203  skip_next = false;
204  continue;
205  }
206  if (!strcmp(original[i], opt_char) ||
207  (opt_name && !strcmp(original[i], opt_name))) {
208  if (opt_arg)
209  skip_next = true;
210  continue;
211  }
212  result[write_index++] = original[i];
213  }
214 
215  /* add the arguments we'll replace */
216  result[write_index++] = opt_char;
217  result[write_index] = opt_arg;
218 
219  return result;
220 }
221 
222 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
223 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
224 
225 static char *store_restart_layout(void) {
226  setlocale(LC_NUMERIC, "C");
227  yajl_gen gen = yajl_gen_alloc(NULL);
228 
229  dump_node(gen, croot, true);
230 
231  setlocale(LC_NUMERIC, "");
232 
233  const unsigned char *payload;
234  size_t length;
235  y(get_buf, &payload, &length);
236 
237  /* create a temporary file if one hasn't been specified, or just
238  * resolve the tildes in the specified path */
239  char *filename;
240  if (config.restart_state_path == NULL) {
241  filename = get_process_filename("restart-state");
242  if (!filename)
243  return NULL;
244  } else {
246  }
247 
248  /* create the directory, it could have been cleaned up before restarting or
249  * may not exist at all in case it was user-specified. */
250  char *filenamecopy = sstrdup(filename);
251  char *base = dirname(filenamecopy);
252  DLOG("Creating \"%s\" for storing the restart layout\n", base);
253  if (mkdirp(base, DEFAULT_DIR_MODE) != 0)
254  ELOG("Could not create \"%s\" for storing the restart layout, layout will be lost.\n", base);
255  free(filenamecopy);
256 
257  int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
258  if (fd == -1) {
259  perror("open()");
260  free(filename);
261  return NULL;
262  }
263 
264  if (writeall(fd, payload, length) == -1) {
265  ELOG("Could not write restart layout to \"%s\", layout will be lost: %s\n", filename, strerror(errno));
266  free(filename);
267  close(fd);
268  return NULL;
269  }
270 
271  close(fd);
272 
273  if (length > 0) {
274  DLOG("layout: %.*s\n", (int)length, payload);
275  }
276 
277  y(free);
278 
279  return filename;
280 }
281 
282 /*
283  * Restart i3 in-place
284  * appends -a to argument list to disable autostart
285  *
286  */
287 void i3_restart(bool forget_layout) {
288  char *restart_filename = forget_layout ? NULL : store_restart_layout();
289 
292 
294 
296 
297  LOG("restarting \"%s\"...\n", start_argv[0]);
298  /* make sure -a is in the argument list or add it */
299  start_argv = add_argument(start_argv, "-a", NULL, NULL);
300 
301  /* make debuglog-on persist */
302  if (get_debug_logging()) {
303  start_argv = add_argument(start_argv, "-d", "all", NULL);
304  }
305 
306  /* replace -r <file> so that the layout is restored */
307  if (restart_filename != NULL) {
308  start_argv = add_argument(start_argv, "--restart", restart_filename, "-r");
309  }
310 
311  execvp(start_argv[0], start_argv);
312 
313  /* not reached */
314 }
315 
316 /*
317  * Escapes the given string if a pango font is currently used.
318  * If the string has to be escaped, the input string will be free'd.
319  *
320  */
321 char *pango_escape_markup(char *input) {
322  if (!font_is_pango())
323  return input;
324 
325  char *escaped = g_markup_escape_text(input, -1);
326  FREE(input);
327 
328  return escaped;
329 }
330 
331 /*
332  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
333  * it exited (or could not be started, depending on the exit code).
334  *
335  */
336 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
337  ev_child_stop(EV_A_ watcher);
338 
339  int exitcode = WEXITSTATUS(watcher->rstatus);
340  if (!WIFEXITED(watcher->rstatus)) {
341  ELOG("i3-nagbar (%d) did not exit normally. This is not an error if the config was reloaded while a nagbar was active.\n", watcher->pid);
342  } else if (exitcode != 0) {
343  ELOG("i3-nagbar (%d) process exited with status %d\n", watcher->pid, exitcode);
344  } else {
345  DLOG("i3-nagbar (%d) process exited with status %d\n", watcher->pid, exitcode);
346  }
347 
348  pid_t *nagbar_pid = watcher->data;
349  if (*nagbar_pid == watcher->pid) {
350  /* Only reset if the watched nagbar is the active nagbar */
351  *nagbar_pid = -1;
352  }
353 }
354 
355 /*
356  * Starts an i3-nagbar instance with the given parameters. Takes care of
357  * handling SIGCHLD and killing i3-nagbar when i3 exits.
358  *
359  * The resulting PID will be stored in *nagbar_pid and can be used with
360  * kill_nagbar() to kill the bar later on.
361  *
362  */
363 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
364  if (*nagbar_pid != -1) {
365  DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
366  return;
367  }
368 
369  *nagbar_pid = fork();
370  if (*nagbar_pid == -1) {
371  warn("Could not fork()");
372  return;
373  }
374 
375  /* child */
376  if (*nagbar_pid == 0)
377  exec_i3_utility("i3-nagbar", argv);
378 
379  DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
380 
381  /* parent */
382  /* install a child watcher */
383  ev_child *child = smalloc(sizeof(ev_child));
384  ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
385  child->data = nagbar_pid;
386  ev_child_start(main_loop, child);
387 }
388 
389 /*
390  * Kills the i3-nagbar process, if nagbar_pid != -1.
391  *
392  * If wait_for_it is set (restarting i3), this function will waitpid(),
393  * otherwise, ev is assumed to handle it (reloading).
394  *
395  */
396 void kill_nagbar(pid_t nagbar_pid, bool wait_for_it) {
397  if (nagbar_pid == -1)
398  return;
399 
400  if (kill(nagbar_pid, SIGTERM) == -1)
401  warn("kill(configerror_nagbar) failed");
402 
403  if (!wait_for_it)
404  return;
405 
406  /* When restarting, we don’t enter the ev main loop anymore and after the
407  * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
408  * for us and we would end up with a <defunct> process. Therefore we
409  * waitpid() here. */
410  waitpid(nagbar_pid, NULL, 0);
411 }
412 
413 /*
414  * Converts a string into a long using strtol().
415  * This is a convenience wrapper checking the parsing result. It returns true
416  * if the number could be parsed.
417  */
418 bool parse_long(const char *str, long *out, int base) {
419  char *end = NULL;
420  long result = strtol(str, &end, base);
421  if (result == LONG_MIN || result == LONG_MAX || result < 0 || (end != NULL && *end != '\0')) {
422  *out = result;
423  return false;
424  }
425 
426  *out = result;
427  return true;
428 }
429 
430 /*
431  * Slurp reads path in its entirety into buf, returning the length of the file
432  * or -1 if the file could not be read. buf is set to a buffer of appropriate
433  * size, or NULL if -1 is returned.
434  *
435  */
436 ssize_t slurp(const char *path, char **buf) {
437  FILE *f;
438  if ((f = fopen(path, "r")) == NULL) {
439  ELOG("Cannot open file \"%s\": %s\n", path, strerror(errno));
440  return -1;
441  }
442  struct stat stbuf;
443  if (fstat(fileno(f), &stbuf) != 0) {
444  ELOG("Cannot fstat() \"%s\": %s\n", path, strerror(errno));
445  fclose(f);
446  return -1;
447  }
448  /* Allocate one extra NUL byte to make the buffer usable with C string
449  * functions. yajl doesn’t need this, but this makes slurp safer. */
450  *buf = scalloc(stbuf.st_size + 1, 1);
451  size_t n = fread(*buf, 1, stbuf.st_size, f);
452  fclose(f);
453  if ((ssize_t)n != stbuf.st_size) {
454  ELOG("File \"%s\" could not be read entirely: got %zd, want %" PRIi64 "\n", path, n, (int64_t)stbuf.st_size);
455  FREE(*buf);
456  return -1;
457  }
458  return (ssize_t)n;
459 }
460 
461 /*
462  * Convert a direction to its corresponding orientation.
463  *
464  */
466  return (direction == D_LEFT || direction == D_RIGHT) ? HORIZ : VERT;
467 }
468 
469 /*
470  * Convert a direction to its corresponding position.
471  *
472  */
474  return (direction == D_LEFT || direction == D_UP) ? BEFORE : AFTER;
475 }
476 
477 /*
478  * Convert orientation and position to the corresponding direction.
479  *
480  */
482  if (orientation == HORIZ) {
483  return position == BEFORE ? D_LEFT : D_RIGHT;
484  } else {
485  return position == BEFORE ? D_UP : D_DOWN;
486  }
487 }
pid_t command_error_nagbar_pid
Definition: bindings.c:19
Config config
Definition: config.c:17
pid_t config_error_nagbar_pid
Definition: config_parser.c:48
void ipc_shutdown(shutdown_reason_t reason, int exempt_fd)
Calls shutdown() on each socket and closes it.
Definition: ipc.c:208
void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart)
Definition: ipc.c:354
bool get_debug_logging(void)
Checks if debug logging is active.
Definition: log.c:203
char ** start_argv
Definition: main.c:49
struct ev_loop * main_loop
Definition: main.c:73
void restore_geometry(void)
Restores the geometry of each window by reparenting it to the root window at the position of its fram...
Definition: manage.c:78
struct Con * croot
Definition: tree.c:12
orientation_t orientation_from_direction(direction_t direction)
Convert a direction to its corresponding orientation.
Definition: util.c:465
__attribute__((pure))
Definition: util.c:67
position_t position_from_direction(direction_t direction)
Convert a direction to its corresponding position.
Definition: util.c:473
int ws_name_to_number(const char *name)
Parses the workspace name as a number.
Definition: util.c:109
void exec_i3_utility(char *name, char *argv[])
exec()s an i3 utility, for example the config file migration script or i3-nagbar.
Definition: util.c:147
#define y(x,...)
Definition: util.c:222
bool rect_contains(Rect rect, uint32_t x, uint32_t y)
Definition: util.c:32
char * pango_escape_markup(char *input)
Escapes the given string if a pango font is currently used.
Definition: util.c:321
void start_nagbar(pid_t *nagbar_pid, char *argv[])
Starts an i3-nagbar instance with the given parameters.
Definition: util.c:363
bool update_if_necessary(uint32_t *destination, const uint32_t new_value)
Updates *destination with new_value and returns true if it was changed or false if it was the same.
Definition: util.c:126
void kill_nagbar(pid_t nagbar_pid, bool wait_for_it)
Kills the i3-nagbar process, if nagbar_pid != -1.
Definition: util.c:396
void i3_restart(bool forget_layout)
Restart i3 in-place appends -a to argument list to disable autostart.
Definition: util.c:287
Rect rect_add(Rect a, Rect b)
Definition: util.c:39
bool parse_long(const char *str, long *out, int base)
Converts a string into a long using strtol().
Definition: util.c:418
bool path_exists(const char *path)
Checks if the given path exists by calling stat().
Definition: util.c:183
bool rect_equals(Rect a, Rect b)
Definition: util.c:59
static void nagbar_exited(EV_P_ ev_child *watcher, int revents)
Definition: util.c:336
static char * store_restart_layout(void)
Definition: util.c:225
ssize_t slurp(const char *path, char **buf)
Slurp reads path in its entirety into buf, returning the length of the file or -1 if the file could n...
Definition: util.c:436
int min(int a, int b)
Definition: util.c:24
bool layout_from_name(const char *layout_str, layout_t *out)
Set 'out' to the layout_t value for the given layout.
Definition: util.c:82
direction_t direction_from_orientation_position(orientation_t orientation, position_t position)
Convert orientation and position to the corresponding direction.
Definition: util.c:481
Rect rect_sub(Rect a, Rect b)
Definition: util.c:46
Rect rect_sanitize_dimensions(Rect rect)
Definition: util.c:53
static char ** add_argument(char **original, char *opt_char, char *opt_arg, char *opt_name)
Definition: util.c:192
int max(int a, int b)
Definition: util.c:28
position_t
Definition: data.h:59
@ AFTER
Definition: data.h:60
@ BEFORE
Definition: data.h:59
layout_t
Container layouts.
Definition: data.h:90
@ L_STACKED
Definition: data.h:92
@ L_TABBED
Definition: data.h:93
@ L_SPLITH
Definition: data.h:97
@ L_SPLITV
Definition: data.h:96
@ L_DEFAULT
Definition: data.h:91
orientation_t
Definition: data.h:56
@ VERT
Definition: data.h:58
@ HORIZ
Definition: data.h:57
direction_t
Definition: data.h:52
@ D_RIGHT
Definition: data.h:53
@ D_LEFT
Definition: data.h:52
@ D_UP
Definition: data.h:54
@ D_DOWN
Definition: data.h:55
@ SHUTDOWN_REASON_RESTART
Definition: ipc.h:101
char * sstrdup(const char *str)
Safe-wrapper around strdup which exits if malloc returns NULL (meaning that there is no more memory a...
#define DLOG(fmt,...)
Definition: libi3.h:104
#define DEFAULT_DIR_MODE
Definition: libi3.h:25
#define LOG(fmt,...)
Definition: libi3.h:94
ssize_t writeall(int fd, const void *buf, size_t count)
Wrapper around correct write which returns -1 (meaning that write failed) or count (meaning that all ...
char * get_process_filename(const char *prefix)
Returns the name of a temporary file with the specified prefix.
void * smalloc(size_t size)
Safe-wrapper around malloc which exits if malloc returns NULL (meaning that there is no more memory a...
#define ELOG(fmt,...)
Definition: libi3.h:99
int sasprintf(char **strp, const char *fmt,...)
Safe-wrapper around asprintf which exits if it returns -1 (meaning that there is no more memory avail...
char * resolve_tilde(const char *path)
This function resolves ~ in pathnames.
int mkdirp(const char *path, mode_t mode)
Emulates mkdir -p (creates any missing folders)
void * scalloc(size_t num, size_t size)
Safe-wrapper around calloc which exits if malloc returns NULL (meaning that there is no more memory a...
bool font_is_pango(void)
Returns true if and only if the current font is a pango font.
#define FREE(pointer)
Definition: util.h:47
char * restart_state_path
Definition: configuration.h:96
Stores a rectangle, for example the size of a window, the child window etc.
Definition: data.h:155
uint32_t height
Definition: data.h:159
uint32_t x
Definition: data.h:156
uint32_t y
Definition: data.h:157
uint32_t width
Definition: data.h:158