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 sigchild-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 /* The buffer statusline points to */
58 struct statusline_head statusline_head = TAILQ_HEAD_INITIALIZER(statusline_head);
59 char *statusline_buffer = NULL;
64 * Clears all blocks from the statusline structure in memory and frees their
65 * associated resources.
67 static void clear_status_blocks() {
68 struct status_block *first;
69 while (!TAILQ_EMPTY(&statusline_head)) {
70 first = TAILQ_FIRST(&statusline_head);
71 I3STRING_FREE(first->full_text);
72 TAILQ_REMOVE(&statusline_head, first, blocks);
78 * Replaces the statusline in memory with an error message. Pass a format
79 * string and format parameters as you would in `printf'. The next time
80 * `draw_bars' is called, the error message text will be drawn on the bar in
81 * the space allocated for the statusline.
83 __attribute__ ((format (printf, 1, 2))) static void set_statusline_error(const char *format, ...) {
84 clear_status_blocks();
88 va_start(args, format);
89 vasprintf(&message, format, args);
91 struct status_block *err_block = scalloc(sizeof(struct status_block));
92 err_block->full_text = i3string_from_utf8("Error: ");
93 err_block->name = "error";
94 err_block->color = "red";
95 err_block->no_separator = true;
97 struct status_block *message_block = scalloc(sizeof(struct status_block));
98 message_block->full_text = i3string_from_utf8(message);
99 message_block->name = "error_message";
100 message_block->color = "red";
101 message_block->no_separator = true;
103 TAILQ_INSERT_HEAD(&statusline_head, err_block, blocks);
104 TAILQ_INSERT_TAIL(&statusline_head, message_block, blocks);
111 * Stop and free() the stdin- and sigchild-watchers
115 if (stdin_io != NULL) {
116 ev_io_stop(main_loop, stdin_io);
118 FREE(statusline_buffer);
119 /* statusline pointed to memory within statusline_buffer */
123 if (child_sig != NULL) {
124 ev_child_stop(main_loop, child_sig);
128 memset(&child, 0, sizeof(i3bar_child));
132 * The start of a new array is the start of a new status line, so we clear all
136 static int stdin_start_array(void *context) {
137 struct status_block *first;
138 while (!TAILQ_EMPTY(&statusline_head)) {
139 first = TAILQ_FIRST(&statusline_head);
140 I3STRING_FREE(first->full_text);
143 FREE(first->instance);
144 TAILQ_REMOVE(&statusline_head, first, blocks);
151 * The start of a map is the start of a single block of the status line.
154 static int stdin_start_map(void *context) {
155 parser_ctx *ctx = context;
156 memset(&(ctx->block), '\0', sizeof(struct status_block));
158 /* Default width of the separator block. */
159 ctx->block.sep_block_width = 9;
165 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
167 static int stdin_map_key(void *context, const unsigned char *key, unsigned int len) {
169 parser_ctx *ctx = context;
170 FREE(ctx->last_map_key);
171 sasprintf(&(ctx->last_map_key), "%.*s", len, key);
175 static int stdin_boolean(void *context, int val) {
176 parser_ctx *ctx = context;
177 if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
178 ctx->block.urgent = val;
180 if (strcasecmp(ctx->last_map_key, "separator") == 0) {
181 ctx->block.no_separator = !val;
187 static int stdin_string(void *context, const unsigned char *val, size_t len) {
189 static int stdin_string(void *context, const unsigned char *val, unsigned int len) {
191 parser_ctx *ctx = context;
192 if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
193 ctx->block.full_text = i3string_from_utf8_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("left") && !strncmp((const char*)val, "left", strlen("left"))) {
200 ctx->block.align = ALIGN_LEFT;
201 } else if (len == strlen("right") && !strncmp((const char*)val, "right", strlen("right"))) {
202 ctx->block.align = ALIGN_RIGHT;
204 ctx->block.align = ALIGN_CENTER;
206 } else if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
207 i3String *text = i3string_from_utf8_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;
227 static int stdin_integer(void *context, long long val) {
229 static int stdin_integer(void *context, long val) {
231 parser_ctx *ctx = context;
232 if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
233 ctx->block.min_width = (uint32_t)val;
235 if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
236 ctx->block.sep_block_width = (uint32_t)val;
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 (null)");
249 if (new_block->urgent)
250 ctx->has_urgent = true;
251 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
255 static int stdin_end_array(void *context) {
256 DLOG("dumping statusline:\n");
257 struct status_block *current;
258 TAILQ_FOREACH(current, &statusline_head, blocks) {
259 DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
260 DLOG("color = %s\n", current->color);
262 DLOG("end of dump\n");
267 * Helper function to read stdin
270 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
271 int fd = watcher->fd;
274 int buffer_len = STDIN_CHUNK_SIZE;
275 unsigned char *buffer = smalloc(buffer_len+1);
278 n = read(fd, buffer + rec, buffer_len - rec);
280 if (errno == EAGAIN) {
284 ELOG("read() failed!: %s\n", strerror(errno));
288 /* end of file, kill the watcher */
289 ELOG("stdin: received EOF\n");
291 set_statusline_error("Received EOF from statusline process");
293 *ret_buffer_len = -1;
298 if (rec == buffer_len) {
299 buffer_len += STDIN_CHUNK_SIZE;
300 buffer = srealloc(buffer, buffer_len);
303 if (*buffer == '\0') {
307 *ret_buffer_len = rec;
311 static void read_flat_input(char *buffer, int length) {
312 struct status_block *first = TAILQ_FIRST(&statusline_head);
313 /* Clear the old buffer if any. */
314 I3STRING_FREE(first->full_text);
315 /* Remove the trailing newline and terminate the string at the same
317 if (buffer[length-1] == '\n' || buffer[length-1] == '\r')
318 buffer[length-1] = '\0';
319 else buffer[length] = '\0';
320 first->full_text = i3string_from_utf8(buffer);
323 static bool read_json_input(unsigned char *input, int length) {
324 yajl_status status = yajl_parse(parser, input, length);
325 bool has_urgent = false;
327 if (status != yajl_status_ok) {
329 if (status != yajl_status_ok && status != yajl_status_insufficient_data) {
331 char *message = (char *)yajl_get_error(parser, 0, input, length);
333 /* strip the newline yajl adds to the error message */
334 if (message[strlen(message) - 1] == '\n')
335 message[strlen(message) - 1] = '\0';
337 fprintf(stderr, "[i3bar] Could not parse JSON input (code = %d, message = %s): %.*s\n",
338 status, message, length, input);
340 set_statusline_error("Could not parse JSON (%s)", message);
341 yajl_free_error(parser, (unsigned char*)message);
343 } else if (parser_context.has_urgent) {
350 * Callbalk for stdin. We read a line from stdin and store the result
354 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
356 unsigned char *buffer = get_buffer(watcher, &rec);
359 bool has_urgent = false;
360 if (child.version > 0) {
361 has_urgent = read_json_input(buffer, rec);
363 read_flat_input((char*)buffer, rec);
366 draw_bars(has_urgent);
370 * Callbalk for stdin first line. We read the first line to detect
371 * whether this is JSON or plain text
374 void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
376 unsigned char *buffer = get_buffer(watcher, &rec);
379 DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
380 /* Detect whether this is JSON or plain text. */
381 unsigned int consumed = 0;
382 /* At the moment, we don’t care for the version. This might change
383 * in the future, but for now, we just discard it. */
384 parse_json_header(&child, buffer, rec, &consumed);
385 if (child.version > 0) {
386 /* If hide-on-modifier is set, we start of by sending the
387 * child a SIGSTOP, because the bars aren't mapped at start */
388 if (config.hide_on_modifier) {
391 read_json_input(buffer + consumed, rec - consumed);
393 /* In case of plaintext, we just add a single block and change its
394 * full_text pointer later. */
395 struct status_block *new_block = scalloc(sizeof(struct status_block));
396 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
397 read_flat_input((char*)buffer, rec);
400 ev_io_stop(main_loop, stdin_io);
401 ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
402 ev_io_start(main_loop, stdin_io);
406 * We received a sigchild, meaning, that the child-process terminated.
407 * We simply free the respective data-structures and don't care for input
411 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
412 int exit_status = WEXITSTATUS(watcher->rstatus);
414 ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
418 /* this error is most likely caused by a user giving a nonexecutable or
419 * nonexistent file, so we will handle those cases separately. */
420 if (exit_status == 126)
421 set_statusline_error("status_command is not executable (exit %d)", exit_status);
422 else if (exit_status == 127)
423 set_statusline_error("status_command not found (exit %d)", exit_status);
425 set_statusline_error("status_command process exited unexpectedly (exit %d)", exit_status);
431 void child_write_output(void) {
432 if (child.click_events) {
433 const unsigned char *output;
439 yajl_gen_get_buf(gen, &output, &size);
440 write(child_stdin, output, size);
441 write(child_stdin, "\n", 1);
447 * Start a child-process with the specified command and reroute stdin.
448 * We actually start a $SHELL to execute the command so we don't have to care
449 * about arguments and such.
451 * If `command' is NULL, such as in the case when no `status_command' is given
452 * in the bar config, no child will be started.
455 void start_child(char *command) {
459 /* Allocate a yajl parser which will be used to parse stdin. */
460 yajl_callbacks callbacks = {
461 .yajl_boolean = stdin_boolean,
462 .yajl_integer = stdin_integer,
463 .yajl_string = stdin_string,
464 .yajl_start_map = stdin_start_map,
465 .yajl_map_key = stdin_map_key,
466 .yajl_end_map = stdin_end_map,
467 .yajl_start_array = stdin_start_array,
468 .yajl_end_array = stdin_end_array,
471 yajl_parser_config parse_conf = { 0, 0 };
473 parser = yajl_alloc(&callbacks, &parse_conf, NULL, (void*)&parser_context);
475 gen = yajl_gen_alloc(NULL, NULL);
477 parser = yajl_alloc(&callbacks, NULL, &parser_context);
479 gen = yajl_gen_alloc(NULL);
482 int pipe_in[2]; /* pipe we read from */
483 int pipe_out[2]; /* pipe we write to */
485 if (pipe(pipe_in) == -1)
486 err(EXIT_FAILURE, "pipe(pipe_in)");
487 if (pipe(pipe_out) == -1)
488 err(EXIT_FAILURE, "pipe(pipe_out)");
493 ELOG("Couldn't fork(): %s\n", strerror(errno));
496 /* Child-process. Reroute streams and start shell */
501 dup2(pipe_in[1], STDOUT_FILENO);
502 dup2(pipe_out[0], STDIN_FILENO);
504 setpgid(child.pid, 0);
505 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char*) NULL);
508 /* Parent-process. Reroute streams */
513 dup2(pipe_in[0], STDIN_FILENO);
514 child_stdin = pipe_out[1];
519 /* We set O_NONBLOCK because blocking is evil in event-driven software */
520 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
522 stdin_io = smalloc(sizeof(ev_io));
523 ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
524 ev_io_start(main_loop, stdin_io);
526 /* We must cleanup, if the child unexpectedly terminates */
527 child_sig = smalloc(sizeof(ev_child));
528 ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
529 ev_child_start(main_loop, child_sig);
531 atexit(kill_child_at_exit);
534 void child_click_events_initialize(void) {
535 if (!child.click_events_init) {
536 yajl_gen_array_open(gen);
537 child_write_output();
538 child.click_events_init = true;
542 void child_click_events_key(const char *key) {
543 yajl_gen_string(gen, (const unsigned char *)key, strlen(key));
547 * Generates a click event, if enabled.
550 void send_block_clicked(int button, const char *name, const char *instance, int x, int y) {
551 if (child.click_events) {
552 child_click_events_initialize();
554 yajl_gen_map_open(gen);
557 child_click_events_key("name");
558 yajl_gen_string(gen, (const unsigned char *)name, strlen(name));
562 child_click_events_key("instance");
563 yajl_gen_string(gen, (const unsigned char *)instance, strlen(instance));
566 child_click_events_key("button");
567 yajl_gen_integer(gen, button);
569 child_click_events_key("x");
570 yajl_gen_integer(gen, x);
572 child_click_events_key("y");
573 yajl_gen_integer(gen, y);
575 yajl_gen_map_close(gen);
576 child_write_output();
581 * kill()s the child-process (if any). Called when exit()ing.
584 void kill_child_at_exit(void) {
586 if (child.cont_signal > 0 && child.stopped)
587 killpg(child.pid, child.cont_signal);
588 killpg(child.pid, SIGTERM);
593 * kill()s the child-process (if existent) and closes and
594 * free()s the stdin- and sigchild-watchers
597 void kill_child(void) {
599 if (child.cont_signal > 0 && child.stopped)
600 killpg(child.pid, child.cont_signal);
601 killpg(child.pid, SIGTERM);
603 waitpid(child.pid, &status, 0);
609 * Sends a SIGSTOP to the child-process (if existent)
612 void stop_child(void) {
613 if (child.stop_signal > 0 && !child.stopped) {
614 child.stopped = true;
615 killpg(child.pid, child.stop_signal);
620 * Sends a SIGCONT to the child-process (if existent)
623 void cont_child(void) {
624 if (child.cont_signal > 0 && child.stopped) {
625 child.stopped = false;
626 killpg(child.pid, child.cont_signal);