2 * vim:ts=4:sw=4:expandtab
4 * i3bar - an xcb-based status- and ws-bar for i3
5 * © 2010 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);
77 FREE(first->min_width_str);
80 TAILQ_REMOVE(head, first, blocks);
85 static void copy_statusline(struct statusline_head *from, struct statusline_head *to) {
86 struct status_block *current;
87 TAILQ_FOREACH(current, from, blocks) {
88 struct status_block *new_block = smalloc(sizeof(struct status_block));
89 memcpy(new_block, current, sizeof(struct status_block));
90 TAILQ_INSERT_TAIL(to, new_block, blocks);
95 * Replaces the statusline in memory with an error message. Pass a format
96 * string and format parameters as you would in `printf'. The next time
97 * `draw_bars' is called, the error message text will be drawn on the bar in
98 * the space allocated for the statusline.
100 __attribute__((format(printf, 1, 2))) static void set_statusline_error(const char *format, ...) {
101 clear_statusline(&statusline_head, true);
105 va_start(args, format);
106 (void)vasprintf(&message, format, args);
108 struct status_block *err_block = scalloc(sizeof(struct status_block));
109 err_block->full_text = i3string_from_utf8("Error: ");
110 err_block->name = "error";
111 err_block->color = "red";
112 err_block->no_separator = true;
114 struct status_block *message_block = scalloc(sizeof(struct status_block));
115 message_block->full_text = i3string_from_utf8(message);
116 message_block->name = "error_message";
117 message_block->color = "red";
118 message_block->no_separator = true;
120 TAILQ_INSERT_HEAD(&statusline_head, err_block, blocks);
121 TAILQ_INSERT_TAIL(&statusline_head, message_block, blocks);
128 * Stop and free() the stdin- and SIGCHLD-watchers
132 if (stdin_io != NULL) {
133 ev_io_stop(main_loop, stdin_io);
137 if (child_sig != NULL) {
138 ev_child_stop(main_loop, child_sig);
142 memset(&child, 0, sizeof(i3bar_child));
146 * The start of a new array is the start of a new status line, so we clear all
147 * previous entries from the buffer.
149 static int stdin_start_array(void *context) {
150 // the blocks are still used by statusline_head, so we won't free the
152 clear_statusline(&statusline_buffer, false);
157 * The start of a map is the start of a single block of the status line.
160 static int stdin_start_map(void *context) {
161 parser_ctx *ctx = context;
162 memset(&(ctx->block), '\0', sizeof(struct status_block));
164 /* Default width of the separator block. */
165 if (config.separator_symbol == NULL)
166 ctx->block.sep_block_width = logical_px(9);
168 ctx->block.sep_block_width = logical_px(8) + separator_symbol_width;
173 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
174 parser_ctx *ctx = context;
175 FREE(ctx->last_map_key);
176 sasprintf(&(ctx->last_map_key), "%.*s", len, key);
180 static int stdin_boolean(void *context, int val) {
181 parser_ctx *ctx = context;
182 if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
183 ctx->block.urgent = val;
186 if (strcasecmp(ctx->last_map_key, "separator") == 0) {
187 ctx->block.no_separator = !val;
194 static int stdin_string(void *context, const unsigned char *val, size_t len) {
195 parser_ctx *ctx = context;
196 if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
197 ctx->block.full_text = i3string_from_markup_with_length((const char *)val, len);
200 if (strcasecmp(ctx->last_map_key, "short_text") == 0) {
201 ctx->block.short_text = i3string_from_markup_with_length((const char *)val, len);
204 if (strcasecmp(ctx->last_map_key, "color") == 0) {
205 sasprintf(&(ctx->block.color), "%.*s", len, val);
208 if (strcasecmp(ctx->last_map_key, "markup") == 0) {
209 ctx->block.is_markup = (len == strlen("pango") && !strncasecmp((const char *)val, "pango", strlen("pango")));
212 if (strcasecmp(ctx->last_map_key, "align") == 0) {
213 if (len == strlen("center") && !strncmp((const char *)val, "center", strlen("center"))) {
214 ctx->block.align = ALIGN_CENTER;
215 } else if (len == strlen("right") && !strncmp((const char *)val, "right", strlen("right"))) {
216 ctx->block.align = ALIGN_RIGHT;
218 ctx->block.align = ALIGN_LEFT;
222 if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
223 char *copy = (char *)malloc(len + 1);
224 strncpy(copy, (const char *)val, len);
226 ctx->block.min_width_str = copy;
229 if (strcasecmp(ctx->last_map_key, "name") == 0) {
230 char *copy = (char *)malloc(len + 1);
231 strncpy(copy, (const char *)val, len);
233 ctx->block.name = copy;
236 if (strcasecmp(ctx->last_map_key, "instance") == 0) {
237 char *copy = (char *)malloc(len + 1);
238 strncpy(copy, (const char *)val, len);
240 ctx->block.instance = copy;
247 static int stdin_integer(void *context, long long val) {
248 parser_ctx *ctx = context;
249 if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
250 ctx->block.min_width = (uint32_t)val;
253 if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
254 ctx->block.sep_block_width = (uint32_t)val;
262 * When a map is finished, we have an entire status block.
263 * Move it from the parser's context to the statusline buffer.
265 static int stdin_end_map(void *context) {
266 parser_ctx *ctx = context;
267 struct status_block *new_block = smalloc(sizeof(struct status_block));
268 memcpy(new_block, &(ctx->block), sizeof(struct status_block));
269 /* Ensure we have a full_text set, so that when it is missing (or null),
270 * i3bar doesn’t crash and the user gets an annoying message. */
271 if (!new_block->full_text)
272 new_block->full_text = i3string_from_utf8("SPEC VIOLATION: full_text is NULL!");
273 if (new_block->urgent)
274 ctx->has_urgent = true;
276 if (new_block->min_width_str) {
277 i3String *text = i3string_from_utf8(new_block->min_width_str);
278 i3string_set_markup(text, new_block->is_markup);
279 new_block->min_width = (uint32_t)predict_text_width(text);
283 i3string_set_markup(new_block->full_text, new_block->is_markup);
285 if (new_block->short_text != NULL)
286 i3string_set_markup(new_block->short_text, new_block->is_markup);
288 TAILQ_INSERT_TAIL(&statusline_buffer, new_block, blocks);
293 * When an array is finished, we have an entire statusline.
294 * Copy it from the buffer to the actual statusline.
296 static int stdin_end_array(void *context) {
297 DLOG("copying statusline_buffer to statusline_head\n");
298 clear_statusline(&statusline_head, true);
299 copy_statusline(&statusline_buffer, &statusline_head);
301 DLOG("dumping statusline:\n");
302 struct status_block *current;
303 TAILQ_FOREACH(current, &statusline_head, blocks) {
304 DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
305 DLOG("short_text = %s\n", (current->short_text == NULL ? NULL : i3string_as_utf8(current->short_text)));
306 DLOG("color = %s\n", current->color);
308 DLOG("end of dump\n");
313 * Helper function to read stdin
315 * Returns NULL on EOF.
318 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
319 int fd = watcher->fd;
322 int buffer_len = STDIN_CHUNK_SIZE;
323 unsigned char *buffer = smalloc(buffer_len + 1);
326 n = read(fd, buffer + rec, buffer_len - rec);
328 if (errno == EAGAIN) {
332 ELOG("read() failed!: %s\n", strerror(errno));
336 ELOG("stdin: received EOF\n");
337 *ret_buffer_len = -1;
342 if (rec == buffer_len) {
343 buffer_len += STDIN_CHUNK_SIZE;
344 buffer = srealloc(buffer, buffer_len);
347 if (*buffer == '\0') {
351 *ret_buffer_len = rec;
355 static void read_flat_input(char *buffer, int length) {
356 struct status_block *first = TAILQ_FIRST(&statusline_head);
357 /* Clear the old buffer if any. */
358 I3STRING_FREE(first->full_text);
359 /* Remove the trailing newline and terminate the string at the same
361 if (buffer[length - 1] == '\n' || buffer[length - 1] == '\r')
362 buffer[length - 1] = '\0';
364 buffer[length] = '\0';
365 first->full_text = i3string_from_markup(buffer);
368 static bool read_json_input(unsigned char *input, int length) {
369 yajl_status status = yajl_parse(parser, input, length);
370 bool has_urgent = false;
371 if (status != yajl_status_ok) {
372 char *message = (char *)yajl_get_error(parser, 0, input, length);
374 /* strip the newline yajl adds to the error message */
375 if (message[strlen(message) - 1] == '\n')
376 message[strlen(message) - 1] = '\0';
378 fprintf(stderr, "[i3bar] Could not parse JSON input (code = %d, message = %s): %.*s\n",
379 status, message, length, input);
381 set_statusline_error("Could not parse JSON (%s)", message);
382 yajl_free_error(parser, (unsigned char *)message);
384 } else if (parser_context.has_urgent) {
391 * Callbalk for stdin. We read a line from stdin and store the result
395 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
397 unsigned char *buffer = get_buffer(watcher, &rec);
400 bool has_urgent = false;
401 if (child.version > 0) {
402 has_urgent = read_json_input(buffer, rec);
404 read_flat_input((char *)buffer, rec);
407 draw_bars(has_urgent);
411 * Callbalk for stdin first line. We read the first line to detect
412 * whether this is JSON or plain text
415 void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
417 unsigned char *buffer = get_buffer(watcher, &rec);
420 DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
421 /* Detect whether this is JSON or plain text. */
422 unsigned int consumed = 0;
423 /* At the moment, we don’t care for the version. This might change
424 * in the future, but for now, we just discard it. */
425 parse_json_header(&child, buffer, rec, &consumed);
426 if (child.version > 0) {
427 /* If hide-on-modifier is set, we start of by sending the
428 * child a SIGSTOP, because the bars aren't mapped at start */
429 if (config.hide_on_modifier) {
432 draw_bars(read_json_input(buffer + consumed, rec - consumed));
434 /* In case of plaintext, we just add a single block and change its
435 * full_text pointer later. */
436 struct status_block *new_block = scalloc(sizeof(struct status_block));
437 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
438 read_flat_input((char *)buffer, rec);
441 ev_io_stop(main_loop, stdin_io);
442 ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
443 ev_io_start(main_loop, stdin_io);
447 * We received a SIGCHLD, meaning, that the child process terminated.
448 * We simply free the respective data structures and don't care for input
452 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
453 int exit_status = WEXITSTATUS(watcher->rstatus);
455 ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
459 /* this error is most likely caused by a user giving a nonexecutable or
460 * nonexistent file, so we will handle those cases separately. */
461 if (exit_status == 126)
462 set_statusline_error("status_command is not executable (exit %d)", exit_status);
463 else if (exit_status == 127)
464 set_statusline_error("status_command not found or is missing a library dependency (exit %d)", exit_status);
466 set_statusline_error("status_command process exited unexpectedly (exit %d)", exit_status);
472 void child_write_output(void) {
473 if (child.click_events) {
474 const unsigned char *output;
478 yajl_gen_get_buf(gen, &output, &size);
480 n = writeall(child_stdin, output, size);
482 n = writeall(child_stdin, "\n", 1);
487 child.click_events = false;
489 set_statusline_error("child_write_output failed");
496 * Start a child process with the specified command and reroute stdin.
497 * We actually start a $SHELL to execute the command so we don't have to care
498 * about arguments and such.
500 * If `command' is NULL, such as in the case when no `status_command' is given
501 * in the bar config, no child will be started.
504 void start_child(char *command) {
508 /* Allocate a yajl parser which will be used to parse stdin. */
509 static yajl_callbacks callbacks = {
510 .yajl_boolean = stdin_boolean,
511 .yajl_integer = stdin_integer,
512 .yajl_string = stdin_string,
513 .yajl_start_map = stdin_start_map,
514 .yajl_map_key = stdin_map_key,
515 .yajl_end_map = stdin_end_map,
516 .yajl_start_array = stdin_start_array,
517 .yajl_end_array = stdin_end_array,
519 parser = yajl_alloc(&callbacks, NULL, &parser_context);
521 gen = yajl_gen_alloc(NULL);
523 int pipe_in[2]; /* pipe we read from */
524 int pipe_out[2]; /* pipe we write to */
526 if (pipe(pipe_in) == -1)
527 err(EXIT_FAILURE, "pipe(pipe_in)");
528 if (pipe(pipe_out) == -1)
529 err(EXIT_FAILURE, "pipe(pipe_out)");
534 ELOG("Couldn't fork(): %s\n", strerror(errno));
537 /* Child-process. Reroute streams and start shell */
542 dup2(pipe_in[1], STDOUT_FILENO);
543 dup2(pipe_out[0], STDIN_FILENO);
545 setpgid(child.pid, 0);
546 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char *)NULL);
549 /* Parent-process. Reroute streams */
554 dup2(pipe_in[0], STDIN_FILENO);
555 child_stdin = pipe_out[1];
560 /* We set O_NONBLOCK because blocking is evil in event-driven software */
561 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
563 stdin_io = smalloc(sizeof(ev_io));
564 ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
565 ev_io_start(main_loop, stdin_io);
567 /* We must cleanup, if the child unexpectedly terminates */
568 child_sig = smalloc(sizeof(ev_child));
569 ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
570 ev_child_start(main_loop, child_sig);
572 atexit(kill_child_at_exit);
575 void child_click_events_initialize(void) {
576 if (!child.click_events_init) {
577 yajl_gen_array_open(gen);
578 child_write_output();
579 child.click_events_init = true;
583 void child_click_events_key(const char *key) {
584 yajl_gen_string(gen, (const unsigned char *)key, strlen(key));
588 * Generates a click event, if enabled.
591 void send_block_clicked(int button, const char *name, const char *instance, int x, int y) {
592 if (!child.click_events) {
596 child_click_events_initialize();
598 yajl_gen_map_open(gen);
601 child_click_events_key("name");
602 yajl_gen_string(gen, (const unsigned char *)name, strlen(name));
606 child_click_events_key("instance");
607 yajl_gen_string(gen, (const unsigned char *)instance, strlen(instance));
610 child_click_events_key("button");
611 yajl_gen_integer(gen, button);
613 child_click_events_key("x");
614 yajl_gen_integer(gen, x);
616 child_click_events_key("y");
617 yajl_gen_integer(gen, y);
619 yajl_gen_map_close(gen);
620 child_write_output();
624 * kill()s the child process (if any). Called when exit()ing.
627 void kill_child_at_exit(void) {
629 if (child.cont_signal > 0 && child.stopped)
630 killpg(child.pid, child.cont_signal);
631 killpg(child.pid, SIGTERM);
636 * kill()s the child process (if existent) and closes and
637 * free()s the stdin- and SIGCHLD-watchers
640 void kill_child(void) {
642 if (child.cont_signal > 0 && child.stopped)
643 killpg(child.pid, child.cont_signal);
644 killpg(child.pid, SIGTERM);
646 waitpid(child.pid, &status, 0);
652 * Sends a SIGSTOP to the child process (if existent)
655 void stop_child(void) {
656 if (child.stop_signal > 0 && !child.stopped) {
657 child.stopped = true;
658 killpg(child.pid, child.stop_signal);
663 * Sends a SIGCONT to the child process (if existent)
666 void cont_child(void) {
667 if (child.cont_signal > 0 && child.stopped) {
668 child.stopped = false;
669 killpg(child.pid, child.cont_signal);
674 * Whether or not the child want click events
677 bool child_want_click_events(void) {
678 return child.click_events;