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