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 = logical_px(9);
164 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
165 parser_ctx *ctx = context;
166 FREE(ctx->last_map_key);
167 sasprintf(&(ctx->last_map_key), "%.*s", len, key);
171 static int stdin_boolean(void *context, int val) {
172 parser_ctx *ctx = context;
173 if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
174 ctx->block.urgent = val;
176 if (strcasecmp(ctx->last_map_key, "separator") == 0) {
177 ctx->block.no_separator = !val;
182 static int stdin_string(void *context, const unsigned char *val, size_t len) {
183 parser_ctx *ctx = context;
184 if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
185 ctx->block.full_text = i3string_from_utf8_with_length((const char *)val, len);
187 if (strcasecmp(ctx->last_map_key, "color") == 0) {
188 sasprintf(&(ctx->block.color), "%.*s", len, val);
190 if (strcasecmp(ctx->last_map_key, "align") == 0) {
191 if (len == strlen("center") && !strncmp((const char *)val, "center", strlen("center"))) {
192 ctx->block.align = ALIGN_CENTER;
193 } else if (len == strlen("right") && !strncmp((const char *)val, "right", strlen("right"))) {
194 ctx->block.align = ALIGN_RIGHT;
196 ctx->block.align = ALIGN_LEFT;
198 } else if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
199 i3String *text = i3string_from_utf8_with_length((const char *)val, len);
200 ctx->block.min_width = (uint32_t)predict_text_width(text);
203 if (strcasecmp(ctx->last_map_key, "name") == 0) {
204 char *copy = (char *)malloc(len + 1);
205 strncpy(copy, (const char *)val, len);
207 ctx->block.name = copy;
209 if (strcasecmp(ctx->last_map_key, "instance") == 0) {
210 char *copy = (char *)malloc(len + 1);
211 strncpy(copy, (const char *)val, len);
213 ctx->block.instance = copy;
218 static int stdin_integer(void *context, long long val) {
219 parser_ctx *ctx = context;
220 if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
221 ctx->block.min_width = (uint32_t)val;
223 if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
224 ctx->block.sep_block_width = (uint32_t)val;
229 static int stdin_end_map(void *context) {
230 parser_ctx *ctx = context;
231 struct status_block *new_block = smalloc(sizeof(struct status_block));
232 memcpy(new_block, &(ctx->block), sizeof(struct status_block));
233 /* Ensure we have a full_text set, so that when it is missing (or null),
234 * i3bar doesn’t crash and the user gets an annoying message. */
235 if (!new_block->full_text)
236 new_block->full_text = i3string_from_utf8("SPEC VIOLATION: full_text is NULL!");
237 if (new_block->urgent)
238 ctx->has_urgent = true;
239 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
243 static int stdin_end_array(void *context) {
244 DLOG("dumping statusline:\n");
245 struct status_block *current;
246 TAILQ_FOREACH(current, &statusline_head, blocks) {
247 DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
248 DLOG("color = %s\n", current->color);
250 DLOG("end of dump\n");
255 * Helper function to read stdin
257 * Returns NULL on EOF.
260 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
261 int fd = watcher->fd;
264 int buffer_len = STDIN_CHUNK_SIZE;
265 unsigned char *buffer = smalloc(buffer_len + 1);
268 n = read(fd, buffer + rec, buffer_len - rec);
270 if (errno == EAGAIN) {
274 ELOG("read() failed!: %s\n", strerror(errno));
278 ELOG("stdin: received EOF\n");
279 *ret_buffer_len = -1;
284 if (rec == buffer_len) {
285 buffer_len += STDIN_CHUNK_SIZE;
286 buffer = srealloc(buffer, buffer_len);
289 if (*buffer == '\0') {
293 *ret_buffer_len = rec;
297 static void read_flat_input(char *buffer, int length) {
298 struct status_block *first = TAILQ_FIRST(&statusline_head);
299 /* Clear the old buffer if any. */
300 I3STRING_FREE(first->full_text);
301 /* Remove the trailing newline and terminate the string at the same
303 if (buffer[length - 1] == '\n' || buffer[length - 1] == '\r')
304 buffer[length - 1] = '\0';
306 buffer[length] = '\0';
307 first->full_text = i3string_from_utf8(buffer);
310 static bool read_json_input(unsigned char *input, int length) {
311 yajl_status status = yajl_parse(parser, input, length);
312 bool has_urgent = false;
313 if (status != yajl_status_ok) {
314 char *message = (char *)yajl_get_error(parser, 0, input, length);
316 /* strip the newline yajl adds to the error message */
317 if (message[strlen(message) - 1] == '\n')
318 message[strlen(message) - 1] = '\0';
320 fprintf(stderr, "[i3bar] Could not parse JSON input (code = %d, message = %s): %.*s\n",
321 status, message, length, input);
323 set_statusline_error("Could not parse JSON (%s)", message);
324 yajl_free_error(parser, (unsigned char *)message);
326 } else if (parser_context.has_urgent) {
333 * Callbalk for stdin. We read a line from stdin and store the result
337 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
339 unsigned char *buffer = get_buffer(watcher, &rec);
342 bool has_urgent = false;
343 if (child.version > 0) {
344 has_urgent = read_json_input(buffer, rec);
346 read_flat_input((char *)buffer, rec);
349 draw_bars(has_urgent);
353 * Callbalk for stdin first line. We read the first line to detect
354 * whether this is JSON or plain text
357 void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
359 unsigned char *buffer = get_buffer(watcher, &rec);
362 DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
363 /* Detect whether this is JSON or plain text. */
364 unsigned int consumed = 0;
365 /* At the moment, we don’t care for the version. This might change
366 * in the future, but for now, we just discard it. */
367 parse_json_header(&child, buffer, rec, &consumed);
368 if (child.version > 0) {
369 /* If hide-on-modifier is set, we start of by sending the
370 * child a SIGSTOP, because the bars aren't mapped at start */
371 if (config.hide_on_modifier) {
374 draw_bars(read_json_input(buffer + consumed, rec - consumed));
376 /* In case of plaintext, we just add a single block and change its
377 * full_text pointer later. */
378 struct status_block *new_block = scalloc(sizeof(struct status_block));
379 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
380 read_flat_input((char *)buffer, rec);
383 ev_io_stop(main_loop, stdin_io);
384 ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
385 ev_io_start(main_loop, stdin_io);
389 * We received a sigchild, meaning, that the child-process terminated.
390 * We simply free the respective data-structures and don't care for input
394 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
395 int exit_status = WEXITSTATUS(watcher->rstatus);
397 ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
401 /* this error is most likely caused by a user giving a nonexecutable or
402 * nonexistent file, so we will handle those cases separately. */
403 if (exit_status == 126)
404 set_statusline_error("status_command is not executable (exit %d)", exit_status);
405 else if (exit_status == 127)
406 set_statusline_error("status_command not found or is missing a library dependency (exit %d)", exit_status);
408 set_statusline_error("status_command process exited unexpectedly (exit %d)", exit_status);
414 void child_write_output(void) {
415 if (child.click_events) {
416 const unsigned char *output;
419 yajl_gen_get_buf(gen, &output, &size);
420 write(child_stdin, output, size);
421 write(child_stdin, "\n", 1);
427 * Start a child-process with the specified command and reroute stdin.
428 * We actually start a $SHELL to execute the command so we don't have to care
429 * about arguments and such.
431 * If `command' is NULL, such as in the case when no `status_command' is given
432 * in the bar config, no child will be started.
435 void start_child(char *command) {
439 /* Allocate a yajl parser which will be used to parse stdin. */
440 static yajl_callbacks callbacks = {
441 .yajl_boolean = stdin_boolean,
442 .yajl_integer = stdin_integer,
443 .yajl_string = stdin_string,
444 .yajl_start_map = stdin_start_map,
445 .yajl_map_key = stdin_map_key,
446 .yajl_end_map = stdin_end_map,
447 .yajl_start_array = stdin_start_array,
448 .yajl_end_array = stdin_end_array,
450 parser = yajl_alloc(&callbacks, NULL, &parser_context);
452 gen = yajl_gen_alloc(NULL);
454 int pipe_in[2]; /* pipe we read from */
455 int pipe_out[2]; /* pipe we write to */
457 if (pipe(pipe_in) == -1)
458 err(EXIT_FAILURE, "pipe(pipe_in)");
459 if (pipe(pipe_out) == -1)
460 err(EXIT_FAILURE, "pipe(pipe_out)");
465 ELOG("Couldn't fork(): %s\n", strerror(errno));
468 /* Child-process. Reroute streams and start shell */
473 dup2(pipe_in[1], STDOUT_FILENO);
474 dup2(pipe_out[0], STDIN_FILENO);
476 setpgid(child.pid, 0);
477 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char *)NULL);
480 /* Parent-process. Reroute streams */
485 dup2(pipe_in[0], STDIN_FILENO);
486 child_stdin = pipe_out[1];
491 /* We set O_NONBLOCK because blocking is evil in event-driven software */
492 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
494 stdin_io = smalloc(sizeof(ev_io));
495 ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
496 ev_io_start(main_loop, stdin_io);
498 /* We must cleanup, if the child unexpectedly terminates */
499 child_sig = smalloc(sizeof(ev_child));
500 ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
501 ev_child_start(main_loop, child_sig);
503 atexit(kill_child_at_exit);
506 void child_click_events_initialize(void) {
507 if (!child.click_events_init) {
508 yajl_gen_array_open(gen);
509 child_write_output();
510 child.click_events_init = true;
514 void child_click_events_key(const char *key) {
515 yajl_gen_string(gen, (const unsigned char *)key, strlen(key));
519 * Generates a click event, if enabled.
522 void send_block_clicked(int button, const char *name, const char *instance, int x, int y) {
523 if (child.click_events) {
524 child_click_events_initialize();
526 yajl_gen_map_open(gen);
529 child_click_events_key("name");
530 yajl_gen_string(gen, (const unsigned char *)name, strlen(name));
534 child_click_events_key("instance");
535 yajl_gen_string(gen, (const unsigned char *)instance, strlen(instance));
538 child_click_events_key("button");
539 yajl_gen_integer(gen, button);
541 child_click_events_key("x");
542 yajl_gen_integer(gen, x);
544 child_click_events_key("y");
545 yajl_gen_integer(gen, y);
547 yajl_gen_map_close(gen);
548 child_write_output();
553 * kill()s the child-process (if any). Called when exit()ing.
556 void kill_child_at_exit(void) {
558 if (child.cont_signal > 0 && child.stopped)
559 killpg(child.pid, child.cont_signal);
560 killpg(child.pid, SIGTERM);
565 * kill()s the child-process (if existent) and closes and
566 * free()s the stdin- and sigchild-watchers
569 void kill_child(void) {
571 if (child.cont_signal > 0 && child.stopped)
572 killpg(child.pid, child.cont_signal);
573 killpg(child.pid, SIGTERM);
575 waitpid(child.pid, &status, 0);
581 * Sends a SIGSTOP to the child-process (if existent)
584 void stop_child(void) {
585 if (child.stop_signal > 0 && !child.stopped) {
586 child.stopped = true;
587 killpg(child.pid, child.stop_signal);
592 * Sends a SIGCONT to the child-process (if existent)
595 void cont_child(void) {
596 if (child.cont_signal > 0 && child.stopped) {
597 child.stopped = false;
598 killpg(child.pid, child.cont_signal);
603 * Whether or not the child want click events
606 bool child_want_click_events(void) {
607 return child.click_events;