2 * vim:ts=4:sw=4:expandtab
4 * i3bar - an xcb-based status- and ws-bar for i3
5 * © 2010-2012 Axel Wagner and contributors (see also: LICENSE)
7 * child.c: Getting Input for the statusline
12 #include <sys/types.h>
22 #include <yajl/yajl_common.h>
23 #include <yajl/yajl_parse.h>
24 #include <yajl/yajl_version.h>
25 #include <yajl/yajl_gen.h>
30 /* Global variables for child_*() */
33 /* stdin- and SIGCHLD-watchers */
37 /* JSON parser for stdin */
40 /* JSON generator for stdout */
43 typedef struct parser_ctx {
44 /* True if one of the parsed blocks was urgent */
47 /* A copy of the last JSON map key. */
50 /* The current block. Will be filled, then copied and put into the list of
52 struct status_block block;
55 parser_ctx parser_context;
57 struct statusline_head statusline_head = TAILQ_HEAD_INITIALIZER(statusline_head);
58 /* Used temporarily while reading a statusline */
59 struct statusline_head statusline_buffer = TAILQ_HEAD_INITIALIZER(statusline_buffer);
64 * Remove all blocks from the given statusline.
65 * If free_resources is set, the fields of each status block will be free'd.
67 static void clear_statusline(struct statusline_head *head, bool free_resources) {
68 struct status_block *first;
69 while (!TAILQ_EMPTY(head)) {
70 first = TAILQ_FIRST(head);
72 I3STRING_FREE(first->full_text);
73 I3STRING_FREE(first->short_text);
76 FREE(first->instance);
79 TAILQ_REMOVE(head, first, blocks);
84 static void copy_statusline(struct statusline_head *from, struct statusline_head *to) {
85 struct status_block *current;
86 TAILQ_FOREACH(current, from, blocks) {
87 struct status_block *new_block = smalloc(sizeof(struct status_block));
88 memcpy(new_block, current, sizeof(struct status_block));
89 TAILQ_INSERT_TAIL(to, new_block, blocks);
94 * Replaces the statusline in memory with an error message. Pass a format
95 * string and format parameters as you would in `printf'. The next time
96 * `draw_bars' is called, the error message text will be drawn on the bar in
97 * the space allocated for the statusline.
99 __attribute__((format(printf, 1, 2))) static void set_statusline_error(const char *format, ...) {
100 clear_statusline(&statusline_head, true);
104 va_start(args, format);
105 vasprintf(&message, format, args);
107 struct status_block *err_block = scalloc(sizeof(struct status_block));
108 err_block->full_text = i3string_from_utf8("Error: ");
109 err_block->name = "error";
110 err_block->color = "red";
111 err_block->no_separator = true;
113 struct status_block *message_block = scalloc(sizeof(struct status_block));
114 message_block->full_text = i3string_from_utf8(message);
115 message_block->name = "error_message";
116 message_block->color = "red";
117 message_block->no_separator = true;
119 TAILQ_INSERT_HEAD(&statusline_head, err_block, blocks);
120 TAILQ_INSERT_TAIL(&statusline_head, message_block, blocks);
127 * Stop and free() the stdin- and SIGCHLD-watchers
131 if (stdin_io != NULL) {
132 ev_io_stop(main_loop, stdin_io);
136 if (child_sig != NULL) {
137 ev_child_stop(main_loop, child_sig);
141 memset(&child, 0, sizeof(i3bar_child));
145 * The start of a new array is the start of a new status line, so we clear all
146 * previous entries from the buffer.
148 static int stdin_start_array(void *context) {
149 // the blocks are still used by statusline_head, so we won't free the
151 clear_statusline(&statusline_buffer, false);
156 * The start of a map is the start of a single block of the status line.
159 static int stdin_start_map(void *context) {
160 parser_ctx *ctx = context;
161 memset(&(ctx->block), '\0', sizeof(struct status_block));
163 /* Default width of the separator block. */
164 ctx->block.sep_block_width = logical_px(9);
169 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
170 parser_ctx *ctx = context;
171 FREE(ctx->last_map_key);
172 sasprintf(&(ctx->last_map_key), "%.*s", len, key);
176 static int stdin_boolean(void *context, int val) {
177 parser_ctx *ctx = context;
178 if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
179 ctx->block.urgent = val;
181 if (strcasecmp(ctx->last_map_key, "separator") == 0) {
182 ctx->block.no_separator = !val;
187 static int stdin_string(void *context, const unsigned char *val, size_t len) {
188 parser_ctx *ctx = context;
189 if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
190 ctx->block.full_text = i3string_from_markup_with_length((const char *)val, len);
192 if (strcasecmp(ctx->last_map_key, "short_text") == 0) {
193 ctx->block.short_text = i3string_from_markup_with_length((const char *)val, len);
195 if (strcasecmp(ctx->last_map_key, "color") == 0) {
196 sasprintf(&(ctx->block.color), "%.*s", len, val);
198 if (strcasecmp(ctx->last_map_key, "align") == 0) {
199 if (len == strlen("center") && !strncmp((const char *)val, "center", strlen("center"))) {
200 ctx->block.align = ALIGN_CENTER;
201 } else if (len == strlen("right") && !strncmp((const char *)val, "right", strlen("right"))) {
202 ctx->block.align = ALIGN_RIGHT;
204 ctx->block.align = ALIGN_LEFT;
206 } else if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
207 i3String *text = i3string_from_markup_with_length((const char *)val, len);
208 ctx->block.min_width = (uint32_t)predict_text_width(text);
211 if (strcasecmp(ctx->last_map_key, "name") == 0) {
212 char *copy = (char *)malloc(len + 1);
213 strncpy(copy, (const char *)val, len);
215 ctx->block.name = copy;
217 if (strcasecmp(ctx->last_map_key, "instance") == 0) {
218 char *copy = (char *)malloc(len + 1);
219 strncpy(copy, (const char *)val, len);
221 ctx->block.instance = copy;
226 static int stdin_integer(void *context, long long val) {
227 parser_ctx *ctx = context;
228 if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
229 ctx->block.min_width = (uint32_t)val;
231 if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
232 ctx->block.sep_block_width = (uint32_t)val;
238 * When a map is finished, we have an entire status block.
239 * Move it from the parser's context to the statusline buffer.
241 static int stdin_end_map(void *context) {
242 parser_ctx *ctx = context;
243 struct status_block *new_block = smalloc(sizeof(struct status_block));
244 memcpy(new_block, &(ctx->block), sizeof(struct status_block));
245 /* Ensure we have a full_text set, so that when it is missing (or null),
246 * i3bar doesn’t crash and the user gets an annoying message. */
247 if (!new_block->full_text)
248 new_block->full_text = i3string_from_utf8("SPEC VIOLATION: full_text is NULL!");
249 if (new_block->urgent)
250 ctx->has_urgent = true;
251 TAILQ_INSERT_TAIL(&statusline_buffer, new_block, blocks);
256 * When an array is finished, we have an entire statusline.
257 * Copy it from the buffer to the actual statusline.
259 static int stdin_end_array(void *context) {
260 DLOG("copying statusline_buffer to statusline_head\n");
261 clear_statusline(&statusline_head, true);
262 copy_statusline(&statusline_buffer, &statusline_head);
264 DLOG("dumping statusline:\n");
265 struct status_block *current;
266 TAILQ_FOREACH(current, &statusline_head, blocks) {
267 DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
268 DLOG("short_text = %s\n", i3string_as_utf8(current->short_text));
269 DLOG("color = %s\n", current->color);
271 DLOG("end of dump\n");
276 * Helper function to read stdin
278 * Returns NULL on EOF.
281 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
282 int fd = watcher->fd;
285 int buffer_len = STDIN_CHUNK_SIZE;
286 unsigned char *buffer = smalloc(buffer_len + 1);
289 n = read(fd, buffer + rec, buffer_len - rec);
291 if (errno == EAGAIN) {
295 ELOG("read() failed!: %s\n", strerror(errno));
299 ELOG("stdin: received EOF\n");
300 *ret_buffer_len = -1;
305 if (rec == buffer_len) {
306 buffer_len += STDIN_CHUNK_SIZE;
307 buffer = srealloc(buffer, buffer_len);
310 if (*buffer == '\0') {
314 *ret_buffer_len = rec;
318 static void read_flat_input(char *buffer, int length) {
319 struct status_block *first = TAILQ_FIRST(&statusline_head);
320 /* Clear the old buffer if any. */
321 I3STRING_FREE(first->full_text);
322 /* Remove the trailing newline and terminate the string at the same
324 if (buffer[length - 1] == '\n' || buffer[length - 1] == '\r')
325 buffer[length - 1] = '\0';
327 buffer[length] = '\0';
328 first->full_text = i3string_from_markup(buffer);
331 static bool read_json_input(unsigned char *input, int length) {
332 yajl_status status = yajl_parse(parser, input, length);
333 bool has_urgent = false;
334 if (status != yajl_status_ok) {
335 char *message = (char *)yajl_get_error(parser, 0, input, length);
337 /* strip the newline yajl adds to the error message */
338 if (message[strlen(message) - 1] == '\n')
339 message[strlen(message) - 1] = '\0';
341 fprintf(stderr, "[i3bar] Could not parse JSON input (code = %d, message = %s): %.*s\n",
342 status, message, length, input);
344 set_statusline_error("Could not parse JSON (%s)", message);
345 yajl_free_error(parser, (unsigned char *)message);
347 } else if (parser_context.has_urgent) {
354 * Callbalk for stdin. We read a line from stdin and store the result
358 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
360 unsigned char *buffer = get_buffer(watcher, &rec);
363 bool has_urgent = false;
364 if (child.version > 0) {
365 has_urgent = read_json_input(buffer, rec);
367 read_flat_input((char *)buffer, rec);
370 draw_bars(has_urgent);
374 * Callbalk for stdin first line. We read the first line to detect
375 * whether this is JSON or plain text
378 void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
380 unsigned char *buffer = get_buffer(watcher, &rec);
383 DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
384 /* Detect whether this is JSON or plain text. */
385 unsigned int consumed = 0;
386 /* At the moment, we don’t care for the version. This might change
387 * in the future, but for now, we just discard it. */
388 parse_json_header(&child, buffer, rec, &consumed);
389 if (child.version > 0) {
390 /* If hide-on-modifier is set, we start of by sending the
391 * child a SIGSTOP, because the bars aren't mapped at start */
392 if (config.hide_on_modifier) {
395 draw_bars(read_json_input(buffer + consumed, rec - consumed));
397 /* In case of plaintext, we just add a single block and change its
398 * full_text pointer later. */
399 struct status_block *new_block = scalloc(sizeof(struct status_block));
400 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
401 read_flat_input((char *)buffer, rec);
404 ev_io_stop(main_loop, stdin_io);
405 ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
406 ev_io_start(main_loop, stdin_io);
410 * We received a SIGCHLD, meaning, that the child process terminated.
411 * We simply free the respective data structures and don't care for input
415 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
416 int exit_status = WEXITSTATUS(watcher->rstatus);
418 ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
422 /* this error is most likely caused by a user giving a nonexecutable or
423 * nonexistent file, so we will handle those cases separately. */
424 if (exit_status == 126)
425 set_statusline_error("status_command is not executable (exit %d)", exit_status);
426 else if (exit_status == 127)
427 set_statusline_error("status_command not found or is missing a library dependency (exit %d)", exit_status);
429 set_statusline_error("status_command process exited unexpectedly (exit %d)", exit_status);
435 void child_write_output(void) {
436 if (child.click_events) {
437 const unsigned char *output;
440 yajl_gen_get_buf(gen, &output, &size);
441 write(child_stdin, output, size);
442 write(child_stdin, "\n", 1);
448 * Start a child process with the specified command and reroute stdin.
449 * We actually start a $SHELL to execute the command so we don't have to care
450 * about arguments and such.
452 * If `command' is NULL, such as in the case when no `status_command' is given
453 * in the bar config, no child will be started.
456 void start_child(char *command) {
460 /* Allocate a yajl parser which will be used to parse stdin. */
461 static yajl_callbacks callbacks = {
462 .yajl_boolean = stdin_boolean,
463 .yajl_integer = stdin_integer,
464 .yajl_string = stdin_string,
465 .yajl_start_map = stdin_start_map,
466 .yajl_map_key = stdin_map_key,
467 .yajl_end_map = stdin_end_map,
468 .yajl_start_array = stdin_start_array,
469 .yajl_end_array = stdin_end_array,
471 parser = yajl_alloc(&callbacks, NULL, &parser_context);
473 gen = yajl_gen_alloc(NULL);
475 int pipe_in[2]; /* pipe we read from */
476 int pipe_out[2]; /* pipe we write to */
478 if (pipe(pipe_in) == -1)
479 err(EXIT_FAILURE, "pipe(pipe_in)");
480 if (pipe(pipe_out) == -1)
481 err(EXIT_FAILURE, "pipe(pipe_out)");
486 ELOG("Couldn't fork(): %s\n", strerror(errno));
489 /* Child-process. Reroute streams and start shell */
494 dup2(pipe_in[1], STDOUT_FILENO);
495 dup2(pipe_out[0], STDIN_FILENO);
497 setpgid(child.pid, 0);
498 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char *)NULL);
501 /* Parent-process. Reroute streams */
506 dup2(pipe_in[0], STDIN_FILENO);
507 child_stdin = pipe_out[1];
512 /* We set O_NONBLOCK because blocking is evil in event-driven software */
513 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
515 stdin_io = smalloc(sizeof(ev_io));
516 ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
517 ev_io_start(main_loop, stdin_io);
519 /* We must cleanup, if the child unexpectedly terminates */
520 child_sig = smalloc(sizeof(ev_child));
521 ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
522 ev_child_start(main_loop, child_sig);
524 atexit(kill_child_at_exit);
527 void child_click_events_initialize(void) {
528 if (!child.click_events_init) {
529 yajl_gen_array_open(gen);
530 child_write_output();
531 child.click_events_init = true;
535 void child_click_events_key(const char *key) {
536 yajl_gen_string(gen, (const unsigned char *)key, strlen(key));
540 * Generates a click event, if enabled.
543 void send_block_clicked(int button, const char *name, const char *instance, int x, int y) {
544 if (!child.click_events) {
548 child_click_events_initialize();
550 yajl_gen_map_open(gen);
553 child_click_events_key("name");
554 yajl_gen_string(gen, (const unsigned char *)name, strlen(name));
558 child_click_events_key("instance");
559 yajl_gen_string(gen, (const unsigned char *)instance, strlen(instance));
562 child_click_events_key("button");
563 yajl_gen_integer(gen, button);
565 child_click_events_key("x");
566 yajl_gen_integer(gen, x);
568 child_click_events_key("y");
569 yajl_gen_integer(gen, y);
571 yajl_gen_map_close(gen);
572 child_write_output();
576 * kill()s the child process (if any). Called when exit()ing.
579 void kill_child_at_exit(void) {
581 if (child.cont_signal > 0 && child.stopped)
582 killpg(child.pid, child.cont_signal);
583 killpg(child.pid, SIGTERM);
588 * kill()s the child process (if existent) and closes and
589 * free()s the stdin- and SIGCHLD-watchers
592 void kill_child(void) {
594 if (child.cont_signal > 0 && child.stopped)
595 killpg(child.pid, child.cont_signal);
596 killpg(child.pid, SIGTERM);
598 waitpid(child.pid, &status, 0);
604 * Sends a SIGSTOP to the child process (if existent)
607 void stop_child(void) {
608 if (child.stop_signal > 0 && !child.stopped) {
609 child.stopped = true;
610 killpg(child.pid, child.stop_signal);
615 * Sends a SIGCONT to the child process (if existent)
618 void cont_child(void) {
619 if (child.cont_signal > 0 && child.stopped) {
620 child.stopped = false;
621 killpg(child.pid, child.cont_signal);
626 * Whether or not the child want click events
629 bool child_want_click_events(void) {
630 return child.click_events;