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);
63 * Clears all blocks from the statusline structure in memory and frees their
64 * associated resources.
66 static void clear_status_blocks() {
67 struct status_block *first;
68 while (!TAILQ_EMPTY(&statusline_head)) {
69 first = TAILQ_FIRST(&statusline_head);
70 I3STRING_FREE(first->full_text);
71 TAILQ_REMOVE(&statusline_head, first, blocks);
77 * Replaces the statusline in memory with an error message. Pass a format
78 * string and format parameters as you would in `printf'. The next time
79 * `draw_bars' is called, the error message text will be drawn on the bar in
80 * the space allocated for the statusline.
82 __attribute__((format(printf, 1, 2))) static void set_statusline_error(const char *format, ...) {
83 clear_status_blocks();
87 va_start(args, format);
88 vasprintf(&message, format, args);
90 struct status_block *err_block = scalloc(sizeof(struct status_block));
91 err_block->full_text = i3string_from_utf8("Error: ");
92 err_block->name = "error";
93 err_block->color = "red";
94 err_block->no_separator = true;
96 struct status_block *message_block = scalloc(sizeof(struct status_block));
97 message_block->full_text = i3string_from_utf8(message);
98 message_block->name = "error_message";
99 message_block->color = "red";
100 message_block->no_separator = true;
102 TAILQ_INSERT_HEAD(&statusline_head, err_block, blocks);
103 TAILQ_INSERT_TAIL(&statusline_head, message_block, blocks);
110 * Stop and free() the stdin- and sigchild-watchers
114 if (stdin_io != NULL) {
115 ev_io_stop(main_loop, stdin_io);
119 if (child_sig != NULL) {
120 ev_child_stop(main_loop, child_sig);
124 memset(&child, 0, sizeof(i3bar_child));
128 * The start of a new array is the start of a new status line, so we clear all
132 static int stdin_start_array(void *context) {
133 struct status_block *first;
134 while (!TAILQ_EMPTY(&statusline_head)) {
135 first = TAILQ_FIRST(&statusline_head);
136 I3STRING_FREE(first->full_text);
139 FREE(first->instance);
140 TAILQ_REMOVE(&statusline_head, first, blocks);
147 * The start of a map is the start of a single block of the status line.
150 static int stdin_start_map(void *context) {
151 parser_ctx *ctx = context;
152 memset(&(ctx->block), '\0', sizeof(struct status_block));
154 /* Default width of the separator block. */
155 ctx->block.sep_block_width = logical_px(9);
160 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
161 parser_ctx *ctx = context;
162 FREE(ctx->last_map_key);
163 sasprintf(&(ctx->last_map_key), "%.*s", len, key);
167 static int stdin_boolean(void *context, int val) {
168 parser_ctx *ctx = context;
169 if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
170 ctx->block.urgent = val;
172 if (strcasecmp(ctx->last_map_key, "separator") == 0) {
173 ctx->block.no_separator = !val;
178 static int stdin_string(void *context, const unsigned char *val, size_t len) {
179 parser_ctx *ctx = context;
180 if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
181 ctx->block.full_text = i3string_from_utf8_with_length((const char *)val, len);
183 if (strcasecmp(ctx->last_map_key, "color") == 0) {
184 sasprintf(&(ctx->block.color), "%.*s", len, val);
186 if (strcasecmp(ctx->last_map_key, "align") == 0) {
187 if (len == strlen("center") && !strncmp((const char *)val, "center", strlen("center"))) {
188 ctx->block.align = ALIGN_CENTER;
189 } else if (len == strlen("right") && !strncmp((const char *)val, "right", strlen("right"))) {
190 ctx->block.align = ALIGN_RIGHT;
192 ctx->block.align = ALIGN_LEFT;
194 } else if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
195 i3String *text = i3string_from_utf8_with_length((const char *)val, len);
196 ctx->block.min_width = (uint32_t)predict_text_width(text);
199 if (strcasecmp(ctx->last_map_key, "name") == 0) {
200 char *copy = (char *)malloc(len + 1);
201 strncpy(copy, (const char *)val, len);
203 ctx->block.name = copy;
205 if (strcasecmp(ctx->last_map_key, "instance") == 0) {
206 char *copy = (char *)malloc(len + 1);
207 strncpy(copy, (const char *)val, len);
209 ctx->block.instance = copy;
214 static int stdin_integer(void *context, long long val) {
215 parser_ctx *ctx = context;
216 if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
217 ctx->block.min_width = (uint32_t)val;
219 if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
220 ctx->block.sep_block_width = (uint32_t)val;
225 static int stdin_end_map(void *context) {
226 parser_ctx *ctx = context;
227 struct status_block *new_block = smalloc(sizeof(struct status_block));
228 memcpy(new_block, &(ctx->block), sizeof(struct status_block));
229 /* Ensure we have a full_text set, so that when it is missing (or null),
230 * i3bar doesn’t crash and the user gets an annoying message. */
231 if (!new_block->full_text)
232 new_block->full_text = i3string_from_utf8("SPEC VIOLATION: full_text is NULL!");
233 if (new_block->urgent)
234 ctx->has_urgent = true;
235 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
239 static int stdin_end_array(void *context) {
240 DLOG("dumping statusline:\n");
241 struct status_block *current;
242 TAILQ_FOREACH(current, &statusline_head, blocks) {
243 DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
244 DLOG("color = %s\n", current->color);
246 DLOG("end of dump\n");
251 * Helper function to read stdin
253 * Returns NULL on EOF.
256 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
257 int fd = watcher->fd;
260 int buffer_len = STDIN_CHUNK_SIZE;
261 unsigned char *buffer = smalloc(buffer_len + 1);
264 n = read(fd, buffer + rec, buffer_len - rec);
266 if (errno == EAGAIN) {
270 ELOG("read() failed!: %s\n", strerror(errno));
274 ELOG("stdin: received EOF\n");
275 *ret_buffer_len = -1;
280 if (rec == buffer_len) {
281 buffer_len += STDIN_CHUNK_SIZE;
282 buffer = srealloc(buffer, buffer_len);
285 if (*buffer == '\0') {
289 *ret_buffer_len = rec;
293 static void read_flat_input(char *buffer, int length) {
294 struct status_block *first = TAILQ_FIRST(&statusline_head);
295 /* Clear the old buffer if any. */
296 I3STRING_FREE(first->full_text);
297 /* Remove the trailing newline and terminate the string at the same
299 if (buffer[length - 1] == '\n' || buffer[length - 1] == '\r')
300 buffer[length - 1] = '\0';
302 buffer[length] = '\0';
303 first->full_text = i3string_from_utf8(buffer);
306 static bool read_json_input(unsigned char *input, int length) {
307 yajl_status status = yajl_parse(parser, input, length);
308 bool has_urgent = false;
309 if (status != yajl_status_ok) {
310 char *message = (char *)yajl_get_error(parser, 0, input, length);
312 /* strip the newline yajl adds to the error message */
313 if (message[strlen(message) - 1] == '\n')
314 message[strlen(message) - 1] = '\0';
316 fprintf(stderr, "[i3bar] Could not parse JSON input (code = %d, message = %s): %.*s\n",
317 status, message, length, input);
319 set_statusline_error("Could not parse JSON (%s)", message);
320 yajl_free_error(parser, (unsigned char *)message);
322 } else if (parser_context.has_urgent) {
329 * Callbalk for stdin. We read a line from stdin and store the result
333 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
335 unsigned char *buffer = get_buffer(watcher, &rec);
338 bool has_urgent = false;
339 if (child.version > 0) {
340 has_urgent = read_json_input(buffer, rec);
342 read_flat_input((char *)buffer, rec);
345 draw_bars(has_urgent);
349 * Callbalk for stdin first line. We read the first line to detect
350 * whether this is JSON or plain text
353 void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
355 unsigned char *buffer = get_buffer(watcher, &rec);
358 DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
359 /* Detect whether this is JSON or plain text. */
360 unsigned int consumed = 0;
361 /* At the moment, we don’t care for the version. This might change
362 * in the future, but for now, we just discard it. */
363 parse_json_header(&child, buffer, rec, &consumed);
364 if (child.version > 0) {
365 /* If hide-on-modifier is set, we start of by sending the
366 * child a SIGSTOP, because the bars aren't mapped at start */
367 if (config.hide_on_modifier) {
370 draw_bars(read_json_input(buffer + consumed, rec - consumed));
372 /* In case of plaintext, we just add a single block and change its
373 * full_text pointer later. */
374 struct status_block *new_block = scalloc(sizeof(struct status_block));
375 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
376 read_flat_input((char *)buffer, rec);
379 ev_io_stop(main_loop, stdin_io);
380 ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
381 ev_io_start(main_loop, stdin_io);
385 * We received a sigchild, meaning, that the child-process terminated.
386 * We simply free the respective data-structures and don't care for input
390 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
391 int exit_status = WEXITSTATUS(watcher->rstatus);
393 ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
397 /* this error is most likely caused by a user giving a nonexecutable or
398 * nonexistent file, so we will handle those cases separately. */
399 if (exit_status == 126)
400 set_statusline_error("status_command is not executable (exit %d)", exit_status);
401 else if (exit_status == 127)
402 set_statusline_error("status_command not found or is missing a library dependency (exit %d)", exit_status);
404 set_statusline_error("status_command process exited unexpectedly (exit %d)", exit_status);
410 void child_write_output(void) {
411 if (child.click_events) {
412 const unsigned char *output;
415 yajl_gen_get_buf(gen, &output, &size);
416 write(child_stdin, output, size);
417 write(child_stdin, "\n", 1);
423 * Start a child-process with the specified command and reroute stdin.
424 * We actually start a $SHELL to execute the command so we don't have to care
425 * about arguments and such.
427 * If `command' is NULL, such as in the case when no `status_command' is given
428 * in the bar config, no child will be started.
431 void start_child(char *command) {
435 /* Allocate a yajl parser which will be used to parse stdin. */
436 static yajl_callbacks callbacks = {
437 .yajl_boolean = stdin_boolean,
438 .yajl_integer = stdin_integer,
439 .yajl_string = stdin_string,
440 .yajl_start_map = stdin_start_map,
441 .yajl_map_key = stdin_map_key,
442 .yajl_end_map = stdin_end_map,
443 .yajl_start_array = stdin_start_array,
444 .yajl_end_array = stdin_end_array,
446 parser = yajl_alloc(&callbacks, NULL, &parser_context);
448 gen = yajl_gen_alloc(NULL);
450 int pipe_in[2]; /* pipe we read from */
451 int pipe_out[2]; /* pipe we write to */
453 if (pipe(pipe_in) == -1)
454 err(EXIT_FAILURE, "pipe(pipe_in)");
455 if (pipe(pipe_out) == -1)
456 err(EXIT_FAILURE, "pipe(pipe_out)");
461 ELOG("Couldn't fork(): %s\n", strerror(errno));
464 /* Child-process. Reroute streams and start shell */
469 dup2(pipe_in[1], STDOUT_FILENO);
470 dup2(pipe_out[0], STDIN_FILENO);
472 setpgid(child.pid, 0);
473 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char *)NULL);
476 /* Parent-process. Reroute streams */
481 dup2(pipe_in[0], STDIN_FILENO);
482 child_stdin = pipe_out[1];
487 /* We set O_NONBLOCK because blocking is evil in event-driven software */
488 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
490 stdin_io = smalloc(sizeof(ev_io));
491 ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
492 ev_io_start(main_loop, stdin_io);
494 /* We must cleanup, if the child unexpectedly terminates */
495 child_sig = smalloc(sizeof(ev_child));
496 ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
497 ev_child_start(main_loop, child_sig);
499 atexit(kill_child_at_exit);
502 void child_click_events_initialize(void) {
503 if (!child.click_events_init) {
504 yajl_gen_array_open(gen);
505 child_write_output();
506 child.click_events_init = true;
510 void child_click_events_key(const char *key) {
511 yajl_gen_string(gen, (const unsigned char *)key, strlen(key));
515 * Generates a click event, if enabled.
518 void send_block_clicked(int button, const char *name, const char *instance, int x, int y) {
519 if (!child.click_events) {
523 child_click_events_initialize();
525 yajl_gen_map_open(gen);
528 child_click_events_key("name");
529 yajl_gen_string(gen, (const unsigned char *)name, strlen(name));
533 child_click_events_key("instance");
534 yajl_gen_string(gen, (const unsigned char *)instance, strlen(instance));
537 child_click_events_key("button");
538 yajl_gen_integer(gen, button);
540 child_click_events_key("x");
541 yajl_gen_integer(gen, x);
543 child_click_events_key("y");
544 yajl_gen_integer(gen, y);
546 yajl_gen_map_close(gen);
547 child_write_output();
551 * kill()s the child-process (if any). Called when exit()ing.
554 void kill_child_at_exit(void) {
556 if (child.cont_signal > 0 && child.stopped)
557 killpg(child.pid, child.cont_signal);
558 killpg(child.pid, SIGTERM);
563 * kill()s the child-process (if existent) and closes and
564 * free()s the stdin- and sigchild-watchers
567 void kill_child(void) {
569 if (child.cont_signal > 0 && child.stopped)
570 killpg(child.pid, child.cont_signal);
571 killpg(child.pid, SIGTERM);
573 waitpid(child.pid, &status, 0);
579 * Sends a SIGSTOP to the child-process (if existent)
582 void stop_child(void) {
583 if (child.stop_signal > 0 && !child.stopped) {
584 child.stopped = true;
585 killpg(child.pid, child.stop_signal);
590 * Sends a SIGCONT to the child-process (if existent)
593 void cont_child(void) {
594 if (child.cont_signal > 0 && child.stopped) {
595 child.stopped = false;
596 killpg(child.pid, child.cont_signal);
601 * Whether or not the child want click events
604 bool child_want_click_events(void) {
605 return child.click_events;