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
11 #include "yajl_utils.h"
15 #include <sys/types.h>
25 #include <yajl/yajl_common.h>
26 #include <yajl/yajl_parse.h>
27 #include <yajl/yajl_version.h>
28 #include <yajl/yajl_gen.h>
31 #include <xcb/xcb_keysyms.h>
33 /* Global variables for child_*() */
36 /* stdin- and SIGCHLD-watchers */
40 /* JSON parser for stdin */
43 /* JSON generator for stdout */
46 typedef struct parser_ctx {
47 /* True if one of the parsed blocks was urgent */
50 /* A copy of the last JSON map key. */
53 /* The current block. Will be filled, then copied and put into the list of
55 struct status_block block;
58 parser_ctx parser_context;
60 struct statusline_head statusline_head = TAILQ_HEAD_INITIALIZER(statusline_head);
61 /* Used temporarily while reading a statusline */
62 struct statusline_head statusline_buffer = TAILQ_HEAD_INITIALIZER(statusline_buffer);
67 * Remove all blocks from the given statusline.
68 * If free_resources is set, the fields of each status block will be free'd.
70 static void clear_statusline(struct statusline_head *head, bool free_resources) {
71 struct status_block *first;
72 while (!TAILQ_EMPTY(head)) {
73 first = TAILQ_FIRST(head);
75 I3STRING_FREE(first->full_text);
76 I3STRING_FREE(first->short_text);
79 FREE(first->instance);
80 FREE(first->min_width_str);
81 FREE(first->background);
85 TAILQ_REMOVE(head, first, blocks);
90 static void copy_statusline(struct statusline_head *from, struct statusline_head *to) {
91 struct status_block *current;
92 TAILQ_FOREACH(current, from, blocks) {
93 struct status_block *new_block = smalloc(sizeof(struct status_block));
94 memcpy(new_block, current, sizeof(struct status_block));
95 TAILQ_INSERT_TAIL(to, new_block, blocks);
100 * Replaces the statusline in memory with an error message. Pass a format
101 * string and format parameters as you would in `printf'. The next time
102 * `draw_bars' is called, the error message text will be drawn on the bar in
103 * the space allocated for the statusline.
105 __attribute__((format(printf, 1, 2))) static void set_statusline_error(const char *format, ...) {
106 clear_statusline(&statusline_head, true);
110 va_start(args, format);
111 if (vasprintf(&message, format, args) == -1) {
115 struct status_block *err_block = scalloc(1, sizeof(struct status_block));
116 err_block->full_text = i3string_from_utf8("Error: ");
117 err_block->name = sstrdup("error");
118 err_block->color = sstrdup("#ff0000");
119 err_block->no_separator = true;
121 struct status_block *message_block = scalloc(1, sizeof(struct status_block));
122 message_block->full_text = i3string_from_utf8(message);
123 message_block->name = sstrdup("error_message");
124 message_block->color = sstrdup("#ff0000");
125 message_block->no_separator = true;
127 TAILQ_INSERT_HEAD(&statusline_head, err_block, blocks);
128 TAILQ_INSERT_TAIL(&statusline_head, message_block, blocks);
136 * Stop and free() the stdin- and SIGCHLD-watchers
139 static void cleanup(void) {
140 if (stdin_io != NULL) {
141 ev_io_stop(main_loop, stdin_io);
145 if (child_sig != NULL) {
146 ev_child_stop(main_loop, child_sig);
150 memset(&child, 0, sizeof(i3bar_child));
154 * The start of a new array is the start of a new status line, so we clear all
155 * previous entries from the buffer.
157 static int stdin_start_array(void *context) {
158 // the blocks are still used by statusline_head, so we won't free the
160 clear_statusline(&statusline_buffer, false);
165 * The start of a map is the start of a single block of the status line.
168 static int stdin_start_map(void *context) {
169 parser_ctx *ctx = context;
170 memset(&(ctx->block), '\0', sizeof(struct status_block));
172 /* Default width of the separator block. */
173 if (config.separator_symbol == NULL)
174 ctx->block.sep_block_width = logical_px(9);
176 ctx->block.sep_block_width = logical_px(8) + separator_symbol_width;
181 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
182 parser_ctx *ctx = context;
183 FREE(ctx->last_map_key);
184 sasprintf(&(ctx->last_map_key), "%.*s", len, key);
188 static int stdin_boolean(void *context, int val) {
189 parser_ctx *ctx = context;
190 if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
191 ctx->block.urgent = val;
194 if (strcasecmp(ctx->last_map_key, "separator") == 0) {
195 ctx->block.no_separator = !val;
202 static int stdin_string(void *context, const unsigned char *val, size_t len) {
203 parser_ctx *ctx = context;
204 if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
205 ctx->block.full_text = i3string_from_markup_with_length((const char *)val, len);
208 if (strcasecmp(ctx->last_map_key, "short_text") == 0) {
209 ctx->block.short_text = i3string_from_markup_with_length((const char *)val, len);
212 if (strcasecmp(ctx->last_map_key, "color") == 0) {
213 sasprintf(&(ctx->block.color), "%.*s", len, val);
216 if (strcasecmp(ctx->last_map_key, "background") == 0) {
217 sasprintf(&(ctx->block.background), "%.*s", len, val);
220 if (strcasecmp(ctx->last_map_key, "border") == 0) {
221 sasprintf(&(ctx->block.border), "%.*s", len, val);
224 if (strcasecmp(ctx->last_map_key, "markup") == 0) {
225 ctx->block.pango_markup = (len == strlen("pango") && !strncasecmp((const char *)val, "pango", strlen("pango")));
228 if (strcasecmp(ctx->last_map_key, "align") == 0) {
229 if (len == strlen("center") && !strncmp((const char *)val, "center", strlen("center"))) {
230 ctx->block.align = ALIGN_CENTER;
231 } else if (len == strlen("right") && !strncmp((const char *)val, "right", strlen("right"))) {
232 ctx->block.align = ALIGN_RIGHT;
234 ctx->block.align = ALIGN_LEFT;
238 if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
239 sasprintf(&(ctx->block.min_width_str), "%.*s", len, val);
242 if (strcasecmp(ctx->last_map_key, "name") == 0) {
243 sasprintf(&(ctx->block.name), "%.*s", len, val);
246 if (strcasecmp(ctx->last_map_key, "instance") == 0) {
247 sasprintf(&(ctx->block.instance), "%.*s", len, val);
254 static int stdin_integer(void *context, long long val) {
255 parser_ctx *ctx = context;
256 if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
257 ctx->block.min_width = (uint32_t)val;
260 if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
261 ctx->block.sep_block_width = (uint32_t)val;
269 * When a map is finished, we have an entire status block.
270 * Move it from the parser's context to the statusline buffer.
272 static int stdin_end_map(void *context) {
273 parser_ctx *ctx = context;
274 struct status_block *new_block = smalloc(sizeof(struct status_block));
275 memcpy(new_block, &(ctx->block), sizeof(struct status_block));
276 /* Ensure we have a full_text set, so that when it is missing (or null),
277 * i3bar doesn’t crash and the user gets an annoying message. */
278 if (!new_block->full_text)
279 new_block->full_text = i3string_from_utf8("SPEC VIOLATION: full_text is NULL!");
280 if (new_block->urgent)
281 ctx->has_urgent = true;
283 if (new_block->min_width_str) {
284 i3String *text = i3string_from_utf8(new_block->min_width_str);
285 i3string_set_markup(text, new_block->pango_markup);
286 new_block->min_width = (uint32_t)predict_text_width(text);
290 i3string_set_markup(new_block->full_text, new_block->pango_markup);
292 if (new_block->short_text != NULL)
293 i3string_set_markup(new_block->short_text, new_block->pango_markup);
295 TAILQ_INSERT_TAIL(&statusline_buffer, new_block, blocks);
300 * When an array is finished, we have an entire statusline.
301 * Copy it from the buffer to the actual statusline.
303 static int stdin_end_array(void *context) {
304 DLOG("copying statusline_buffer to statusline_head\n");
305 clear_statusline(&statusline_head, true);
306 copy_statusline(&statusline_buffer, &statusline_head);
308 DLOG("dumping statusline:\n");
309 struct status_block *current;
310 TAILQ_FOREACH(current, &statusline_head, blocks) {
311 DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
312 DLOG("short_text = %s\n", (current->short_text == NULL ? NULL : i3string_as_utf8(current->short_text)));
313 DLOG("color = %s\n", current->color);
315 DLOG("end of dump\n");
320 * Helper function to read stdin
322 * Returns NULL on EOF.
325 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
326 int fd = watcher->fd;
329 int buffer_len = STDIN_CHUNK_SIZE;
330 unsigned char *buffer = smalloc(buffer_len + 1);
333 n = read(fd, buffer + rec, buffer_len - rec);
335 if (errno == EAGAIN) {
339 ELOG("read() failed!: %s\n", strerror(errno));
344 ELOG("stdin: received EOF\n");
346 *ret_buffer_len = -1;
351 if (rec == buffer_len) {
352 buffer_len += STDIN_CHUNK_SIZE;
353 buffer = srealloc(buffer, buffer_len);
356 if (*buffer == '\0') {
360 *ret_buffer_len = rec;
364 static void read_flat_input(char *buffer, int length) {
365 struct status_block *first = TAILQ_FIRST(&statusline_head);
366 /* Clear the old buffer if any. */
367 I3STRING_FREE(first->full_text);
368 /* Remove the trailing newline and terminate the string at the same
370 if (buffer[length - 1] == '\n' || buffer[length - 1] == '\r') {
371 buffer[length - 1] = '\0';
373 buffer[length] = '\0';
376 first->full_text = i3string_from_utf8(buffer);
379 static bool read_json_input(unsigned char *input, int length) {
380 yajl_status status = yajl_parse(parser, input, length);
381 bool has_urgent = false;
382 if (status != yajl_status_ok) {
383 char *message = (char *)yajl_get_error(parser, 0, input, length);
385 /* strip the newline yajl adds to the error message */
386 if (message[strlen(message) - 1] == '\n')
387 message[strlen(message) - 1] = '\0';
389 fprintf(stderr, "[i3bar] Could not parse JSON input (code = %d, message = %s): %.*s\n",
390 status, message, length, input);
392 set_statusline_error("Could not parse JSON (%s)", message);
393 yajl_free_error(parser, (unsigned char *)message);
395 } else if (parser_context.has_urgent) {
402 * Callbalk for stdin. We read a line from stdin and store the result
406 static void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
408 unsigned char *buffer = get_buffer(watcher, &rec);
411 bool has_urgent = false;
412 if (child.version > 0) {
413 has_urgent = read_json_input(buffer, rec);
415 read_flat_input((char *)buffer, rec);
418 draw_bars(has_urgent);
422 * Callbalk for stdin first line. We read the first line to detect
423 * whether this is JSON or plain text
426 static void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
428 unsigned char *buffer = get_buffer(watcher, &rec);
431 DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
432 /* Detect whether this is JSON or plain text. */
433 unsigned int consumed = 0;
434 /* At the moment, we don’t care for the version. This might change
435 * in the future, but for now, we just discard it. */
436 parse_json_header(&child, buffer, rec, &consumed);
437 if (child.version > 0) {
438 /* If hide-on-modifier is set, we start of by sending the
439 * child a SIGSTOP, because the bars aren't mapped at start */
440 if (config.hide_on_modifier) {
443 draw_bars(read_json_input(buffer + consumed, rec - consumed));
445 /* In case of plaintext, we just add a single block and change its
446 * full_text pointer later. */
447 struct status_block *new_block = scalloc(1, sizeof(struct status_block));
448 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
449 read_flat_input((char *)buffer, rec);
452 ev_io_stop(main_loop, stdin_io);
453 ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
454 ev_io_start(main_loop, stdin_io);
458 * We received a SIGCHLD, meaning, that the child process terminated.
459 * We simply free the respective data structures and don't care for input
463 static void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
464 int exit_status = WEXITSTATUS(watcher->rstatus);
466 ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
470 /* this error is most likely caused by a user giving a nonexecutable or
471 * nonexistent file, so we will handle those cases separately. */
472 if (exit_status == 126)
473 set_statusline_error("status_command is not executable (exit %d)", exit_status);
474 else if (exit_status == 127)
475 set_statusline_error("status_command not found or is missing a library dependency (exit %d)", exit_status);
477 set_statusline_error("status_command process exited unexpectedly (exit %d)", exit_status);
483 static void child_write_output(void) {
484 if (child.click_events) {
485 const unsigned char *output;
489 yajl_gen_get_buf(gen, &output, &size);
491 n = writeall(child_stdin, output, size);
493 n = writeall(child_stdin, "\n", 1);
498 child.click_events = false;
500 set_statusline_error("child_write_output failed");
507 * Start a child process with the specified command and reroute stdin.
508 * We actually start a $SHELL to execute the command so we don't have to care
509 * about arguments and such.
511 * If `command' is NULL, such as in the case when no `status_command' is given
512 * in the bar config, no child will be started.
515 void start_child(char *command) {
519 /* Allocate a yajl parser which will be used to parse stdin. */
520 static yajl_callbacks callbacks = {
521 .yajl_boolean = stdin_boolean,
522 .yajl_integer = stdin_integer,
523 .yajl_string = stdin_string,
524 .yajl_start_map = stdin_start_map,
525 .yajl_map_key = stdin_map_key,
526 .yajl_end_map = stdin_end_map,
527 .yajl_start_array = stdin_start_array,
528 .yajl_end_array = stdin_end_array,
530 parser = yajl_alloc(&callbacks, NULL, &parser_context);
532 gen = yajl_gen_alloc(NULL);
534 int pipe_in[2]; /* pipe we read from */
535 int pipe_out[2]; /* pipe we write to */
537 if (pipe(pipe_in) == -1)
538 err(EXIT_FAILURE, "pipe(pipe_in)");
539 if (pipe(pipe_out) == -1)
540 err(EXIT_FAILURE, "pipe(pipe_out)");
545 ELOG("Couldn't fork(): %s\n", strerror(errno));
548 /* Child-process. Reroute streams and start shell */
553 dup2(pipe_in[1], STDOUT_FILENO);
554 dup2(pipe_out[0], STDIN_FILENO);
556 setpgid(child.pid, 0);
557 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char *)NULL);
560 /* Parent-process. Reroute streams */
565 dup2(pipe_in[0], STDIN_FILENO);
566 child_stdin = pipe_out[1];
571 /* We set O_NONBLOCK because blocking is evil in event-driven software */
572 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
574 stdin_io = smalloc(sizeof(ev_io));
575 ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
576 ev_io_start(main_loop, stdin_io);
578 /* We must cleanup, if the child unexpectedly terminates */
579 child_sig = smalloc(sizeof(ev_child));
580 ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
581 ev_child_start(main_loop, child_sig);
583 atexit(kill_child_at_exit);
586 static void child_click_events_initialize(void) {
587 if (!child.click_events_init) {
588 yajl_gen_array_open(gen);
589 child_write_output();
590 child.click_events_init = true;
595 * Generates a click event, if enabled.
598 void send_block_clicked(int button, const char *name, const char *instance, int x, int y, int x_rel, int y_rel, int width, int height, int mods) {
599 if (!child.click_events) {
603 child_click_events_initialize();
605 yajl_gen_map_open(gen);
618 yajl_gen_integer(gen, button);
621 yajl_gen_array_open(gen);
622 if (mods & XCB_MOD_MASK_SHIFT)
624 if (mods & XCB_MOD_MASK_CONTROL)
626 if (mods & XCB_MOD_MASK_1)
628 if (mods & XCB_MOD_MASK_2)
630 if (mods & XCB_MOD_MASK_3)
632 if (mods & XCB_MOD_MASK_4)
634 if (mods & XCB_MOD_MASK_5)
636 yajl_gen_array_close(gen);
639 yajl_gen_integer(gen, x);
642 yajl_gen_integer(gen, y);
645 yajl_gen_integer(gen, x_rel);
648 yajl_gen_integer(gen, y_rel);
651 yajl_gen_integer(gen, width);
654 yajl_gen_integer(gen, height);
656 yajl_gen_map_close(gen);
657 child_write_output();
661 * kill()s the child process (if any). Called when exit()ing.
664 void kill_child_at_exit(void) {
666 if (child.cont_signal > 0 && child.stopped)
667 killpg(child.pid, child.cont_signal);
668 killpg(child.pid, SIGTERM);
673 * kill()s the child process (if existent) and closes and
674 * free()s the stdin- and SIGCHLD-watchers
677 void kill_child(void) {
679 if (child.cont_signal > 0 && child.stopped)
680 killpg(child.pid, child.cont_signal);
681 killpg(child.pid, SIGTERM);
683 waitpid(child.pid, &status, 0);
689 * Sends a SIGSTOP to the child process (if existent)
692 void stop_child(void) {
693 if (child.stop_signal > 0 && !child.stopped) {
694 child.stopped = true;
695 killpg(child.pid, child.stop_signal);
700 * Sends a SIGCONT to the child process (if existent)
703 void cont_child(void) {
704 if (child.cont_signal > 0 && child.stopped) {
705 child.stopped = false;
706 killpg(child.pid, child.cont_signal);
711 * Whether or not the child want click events
714 bool child_want_click_events(void) {
715 return child.click_events;