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  * Goes through the list of arguments (for exec()) and add/replace the given option,
181  * including the option name, its argument, and the option character.
182  */
183 static char **add_argument(char **original, char *opt_char, char *opt_arg, char *opt_name) {
184  int num_args;
185  for (num_args = 0; original[num_args] != NULL; num_args++)
186  ;
187  char **result = scalloc(num_args + 3, sizeof(char *));
188 
189  /* copy the arguments, but skip the ones we'll replace */
190  int write_index = 0;
191  bool skip_next = false;
192  for (int i = 0; i < num_args; ++i) {
193  if (skip_next) {
194  skip_next = false;
195  continue;
196  }
197  if (!strcmp(original[i], opt_char) ||
198  (opt_name && !strcmp(original[i], opt_name))) {
199  if (opt_arg)
200  skip_next = true;
201  continue;
202  }
203  result[write_index++] = original[i];
204  }
205 
206  /* add the arguments we'll replace */
207  result[write_index++] = opt_char;
208  result[write_index] = opt_arg;
209 
210  return result;
211 }
212 
213 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
214 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
215 
216 static char *store_restart_layout(void) {
217  setlocale(LC_NUMERIC, "C");
218  yajl_gen gen = yajl_gen_alloc(NULL);
219 
220  dump_node(gen, croot, true);
221 
222  setlocale(LC_NUMERIC, "");
223 
224  const unsigned char *payload;
225  size_t length;
226  y(get_buf, &payload, &length);
227 
228  /* create a temporary file if one hasn't been specified, or just
229  * resolve the tildes in the specified path */
230  char *filename;
231  if (config.restart_state_path == NULL) {
232  filename = get_process_filename("restart-state");
233  if (!filename)
234  return NULL;
235  } else {
237  }
238 
239  /* create the directory, it could have been cleaned up before restarting or
240  * may not exist at all in case it was user-specified. */
241  char *filenamecopy = sstrdup(filename);
242  char *base = dirname(filenamecopy);
243  DLOG("Creating \"%s\" for storing the restart layout\n", base);
244  if (mkdirp(base, DEFAULT_DIR_MODE) != 0)
245  ELOG("Could not create \"%s\" for storing the restart layout, layout will be lost.\n", base);
246  free(filenamecopy);
247 
248  int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
249  if (fd == -1) {
250  perror("open()");
251  free(filename);
252  return NULL;
253  }
254 
255  if (writeall(fd, payload, length) == -1) {
256  ELOG("Could not write restart layout to \"%s\", layout will be lost: %s\n", filename, strerror(errno));
257  free(filename);
258  close(fd);
259  return NULL;
260  }
261 
262  close(fd);
263 
264  if (length > 0) {
265  DLOG("layout: %.*s\n", (int)length, payload);
266  }
267 
268  y(free);
269 
270  return filename;
271 }
272 
273 /*
274  * Restart i3 in-place
275  * appends -a to argument list to disable autostart
276  *
277  */
278 void i3_restart(bool forget_layout) {
279  char *restart_filename = forget_layout ? NULL : store_restart_layout();
280 
283 
285 
287 
288  LOG("restarting \"%s\"...\n", start_argv[0]);
289  /* make sure -a is in the argument list or add it */
290  start_argv = add_argument(start_argv, "-a", NULL, NULL);
291 
292  /* make debuglog-on persist */
293  if (get_debug_logging()) {
294  start_argv = add_argument(start_argv, "-d", "all", NULL);
295  }
296 
297  /* replace -r <file> so that the layout is restored */
298  if (restart_filename != NULL) {
299  start_argv = add_argument(start_argv, "--restart", restart_filename, "-r");
300  }
301 
302  execvp(start_argv[0], start_argv);
303 
304  /* not reached */
305 }
306 
307 /*
308  * Escapes the given string if a pango font is currently used.
309  * If the string has to be escaped, the input string will be free'd.
310  *
311  */
312 char *pango_escape_markup(char *input) {
313  if (!font_is_pango())
314  return input;
315 
316  char *escaped = g_markup_escape_text(input, -1);
317  FREE(input);
318 
319  return escaped;
320 }
321 
322 /*
323  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
324  * it exited (or could not be started, depending on the exit code).
325  *
326  */
327 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
328  ev_child_stop(EV_A_ watcher);
329 
330  int exitcode = WEXITSTATUS(watcher->rstatus);
331  if (!WIFEXITED(watcher->rstatus)) {
332  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);
333  } else if (exitcode != 0) {
334  ELOG("i3-nagbar (%d) process exited with status %d\n", watcher->pid, exitcode);
335  } else {
336  DLOG("i3-nagbar (%d) process exited with status %d\n", watcher->pid, exitcode);
337  }
338 
339  pid_t *nagbar_pid = watcher->data;
340  if (*nagbar_pid == watcher->pid) {
341  /* Only reset if the watched nagbar is the active nagbar */
342  *nagbar_pid = -1;
343  }
344 }
345 
346 /*
347  * Starts an i3-nagbar instance with the given parameters. Takes care of
348  * handling SIGCHLD and killing i3-nagbar when i3 exits.
349  *
350  * The resulting PID will be stored in *nagbar_pid and can be used with
351  * kill_nagbar() to kill the bar later on.
352  *
353  */
354 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
355  if (*nagbar_pid != -1) {
356  DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
357  return;
358  }
359 
360  *nagbar_pid = fork();
361  if (*nagbar_pid == -1) {
362  warn("Could not fork()");
363  return;
364  }
365 
366  /* child */
367  if (*nagbar_pid == 0)
368  exec_i3_utility("i3-nagbar", argv);
369 
370  DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
371 
372  /* parent */
373  /* install a child watcher */
374  ev_child *child = smalloc(sizeof(ev_child));
375  ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
376  child->data = nagbar_pid;
377  ev_child_start(main_loop, child);
378 }
379 
380 /*
381  * Kills the i3-nagbar process, if nagbar_pid != -1.
382  *
383  * If wait_for_it is set (restarting i3), this function will waitpid(),
384  * otherwise, ev is assumed to handle it (reloading).
385  *
386  */
387 void kill_nagbar(pid_t nagbar_pid, bool wait_for_it) {
388  if (nagbar_pid == -1)
389  return;
390 
391  if (kill(nagbar_pid, SIGTERM) == -1)
392  warn("kill(configerror_nagbar) failed");
393 
394  if (!wait_for_it)
395  return;
396 
397  /* When restarting, we don’t enter the ev main loop anymore and after the
398  * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
399  * for us and we would end up with a <defunct> process. Therefore we
400  * waitpid() here. */
401  waitpid(nagbar_pid, NULL, 0);
402 }
403 
404 /*
405  * Converts a string into a long using strtol().
406  * This is a convenience wrapper checking the parsing result. It returns true
407  * if the number could be parsed.
408  */
409 bool parse_long(const char *str, long *out, int base) {
410  char *end = NULL;
411  long result = strtol(str, &end, base);
412  if (result == LONG_MIN || result == LONG_MAX || result < 0 || (end != NULL && *end != '\0')) {
413  *out = result;
414  return false;
415  }
416 
417  *out = result;
418  return true;
419 }
420 
421 /*
422  * Slurp reads path in its entirety into buf, returning the length of the file
423  * or -1 if the file could not be read. buf is set to a buffer of appropriate
424  * size, or NULL if -1 is returned.
425  *
426  */
427 ssize_t slurp(const char *path, char **buf) {
428  FILE *f;
429  if ((f = fopen(path, "r")) == NULL) {
430  ELOG("Cannot open file \"%s\": %s\n", path, strerror(errno));
431  return -1;
432  }
433  struct stat stbuf;
434  if (fstat(fileno(f), &stbuf) != 0) {
435  ELOG("Cannot fstat() \"%s\": %s\n", path, strerror(errno));
436  fclose(f);
437  return -1;
438  }
439  /* Allocate one extra NUL byte to make the buffer usable with C string
440  * functions. yajl doesn’t need this, but this makes slurp safer. */
441  *buf = scalloc(stbuf.st_size + 1, 1);
442  size_t n = fread(*buf, 1, stbuf.st_size, f);
443  fclose(f);
444  if ((ssize_t)n != stbuf.st_size) {
445  ELOG("File \"%s\" could not be read entirely: got %zd, want %" PRIi64 "\n", path, n, (int64_t)stbuf.st_size);
446  FREE(*buf);
447  return -1;
448  }
449  return (ssize_t)n;
450 }
451 
452 /*
453  * Convert a direction to its corresponding orientation.
454  *
455  */
457  return (direction == D_LEFT || direction == D_RIGHT) ? HORIZ : VERT;
458 }
459 
460 /*
461  * Convert a direction to its corresponding position.
462  *
463  */
465  return (direction == D_LEFT || direction == D_UP) ? BEFORE : AFTER;
466 }
467 
468 /*
469  * Convert orientation and position to the corresponding direction.
470  *
471  */
473  if (orientation == HORIZ) {
474  return position == BEFORE ? D_LEFT : D_RIGHT;
475  } else {
476  return position == BEFORE ? D_UP : D_DOWN;
477  }
478 }
pid_t command_error_nagbar_pid
Definition: bindings.c:19
Config config
Definition: config.c:19
pid_t config_error_nagbar_pid
Definition: config_parser.c:45
void ipc_shutdown(shutdown_reason_t reason, int exempt_fd)
Calls shutdown() on each socket and closes it.
Definition: ipc.c:192
void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart)
Definition: ipc.c:338
bool get_debug_logging(void)
Checks if debug logging is active.
Definition: log.c:208
char ** start_argv
Definition: main.c:52
struct ev_loop * main_loop
Definition: main.c:79
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:456
__attribute__((pure))
Definition: util.c:67
position_t position_from_direction(direction_t direction)
Convert a direction to its corresponding position.
Definition: util.c:464
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:213
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:312
void start_nagbar(pid_t *nagbar_pid, char *argv[])
Starts an i3-nagbar instance with the given parameters.
Definition: util.c:354
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:387
void i3_restart(bool forget_layout)
Restart i3 in-place appends -a to argument list to disable autostart.
Definition: util.c:278
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:409
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:327
static char * store_restart_layout(void)
Definition: util.c:216
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:427
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:472
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:183
int max(int a, int b)
Definition: util.c:28
position_t
Definition: data.h:60
@ AFTER
Definition: data.h:61
@ BEFORE
Definition: data.h:60
layout_t
Container layouts.
Definition: data.h:91
@ L_STACKED
Definition: data.h:93
@ L_TABBED
Definition: data.h:94
@ L_SPLITH
Definition: data.h:98
@ L_SPLITV
Definition: data.h:97
@ L_DEFAULT
Definition: data.h:92
orientation_t
Definition: data.h:57
@ VERT
Definition: data.h:59
@ HORIZ
Definition: data.h:58
direction_t
Definition: data.h:53
@ D_RIGHT
Definition: data.h:54
@ D_LEFT
Definition: data.h:53
@ D_UP
Definition: data.h:55
@ D_DOWN
Definition: data.h:56
@ SHUTDOWN_REASON_RESTART
Definition: ipc.h:94
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:105
#define DEFAULT_DIR_MODE
Definition: libi3.h:26
#define LOG(fmt,...)
Definition: libi3.h:95
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:100
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
Stores a rectangle, for example the size of a window, the child window etc.
Definition: data.h:156
uint32_t height
Definition: data.h:160
uint32_t x
Definition: data.h:157
uint32_t y
Definition: data.h:158
uint32_t width
Definition: data.h:159