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>
21 #include <yajl/yajl_common.h>
22 #include <yajl/yajl_parse.h>
23 #include <yajl/yajl_version.h>
24 #include <yajl/yajl_gen.h>
29 /* Global variables for child_*() */
30 i3bar_child child = { 0 };
32 /* stdin- and sigchild-watchers */
36 /* JSON parser for stdin */
37 yajl_callbacks callbacks;
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 * Stop and free() the stdin- and sigchild-watchers
68 if (stdin_io != NULL) {
69 ev_io_stop(main_loop, stdin_io);
71 FREE(statusline_buffer);
72 /* statusline pointed to memory within statusline_buffer */
76 if (child_sig != NULL) {
77 ev_child_stop(main_loop, child_sig);
81 memset(&child, 0, sizeof(i3bar_child));
85 * The start of a new array is the start of a new status line, so we clear all
89 static int stdin_start_array(void *context) {
90 struct status_block *first;
91 while (!TAILQ_EMPTY(&statusline_head)) {
92 first = TAILQ_FIRST(&statusline_head);
93 I3STRING_FREE(first->full_text);
96 FREE(first->instance);
97 TAILQ_REMOVE(&statusline_head, first, blocks);
104 * The start of a map is the start of a single block of the status line.
107 static int stdin_start_map(void *context) {
108 parser_ctx *ctx = context;
109 memset(&(ctx->block), '\0', sizeof(struct status_block));
111 /* Default width of the separator block. */
112 ctx->block.sep_block_width = 9;
118 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
120 static int stdin_map_key(void *context, const unsigned char *key, unsigned int len) {
122 parser_ctx *ctx = context;
123 FREE(ctx->last_map_key);
124 sasprintf(&(ctx->last_map_key), "%.*s", len, key);
128 static int stdin_boolean(void *context, int val) {
129 parser_ctx *ctx = context;
130 if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
131 ctx->block.urgent = val;
133 if (strcasecmp(ctx->last_map_key, "separator") == 0) {
134 ctx->block.no_separator = !val;
140 static int stdin_string(void *context, const unsigned char *val, size_t len) {
142 static int stdin_string(void *context, const unsigned char *val, unsigned int len) {
144 parser_ctx *ctx = context;
145 if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
146 ctx->block.full_text = i3string_from_utf8_with_length((const char *)val, len);
148 if (strcasecmp(ctx->last_map_key, "color") == 0) {
149 sasprintf(&(ctx->block.color), "%.*s", len, val);
151 if (strcasecmp(ctx->last_map_key, "align") == 0) {
152 if (len == strlen("left") && !strncmp((const char*)val, "left", strlen("left"))) {
153 ctx->block.align = ALIGN_LEFT;
154 } else if (len == strlen("right") && !strncmp((const char*)val, "right", strlen("right"))) {
155 ctx->block.align = ALIGN_RIGHT;
157 ctx->block.align = ALIGN_CENTER;
159 } else if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
160 i3String *text = i3string_from_utf8_with_length((const char *)val, len);
161 ctx->block.min_width = (uint32_t)predict_text_width(text);
164 if (strcasecmp(ctx->last_map_key, "name") == 0) {
165 char *copy = (char*)malloc(len+1);
166 strncpy(copy, (const char *)val, len);
168 ctx->block.name = copy;
170 if (strcasecmp(ctx->last_map_key, "instance") == 0) {
171 char *copy = (char*)malloc(len+1);
172 strncpy(copy, (const char *)val, len);
174 ctx->block.instance = copy;
180 static int stdin_integer(void *context, long long val) {
182 static int stdin_integer(void *context, long val) {
184 parser_ctx *ctx = context;
185 if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
186 ctx->block.min_width = (uint32_t)val;
188 if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
189 ctx->block.sep_block_width = (uint32_t)val;
194 static int stdin_end_map(void *context) {
195 parser_ctx *ctx = context;
196 struct status_block *new_block = smalloc(sizeof(struct status_block));
197 memcpy(new_block, &(ctx->block), sizeof(struct status_block));
198 /* Ensure we have a full_text set, so that when it is missing (or null),
199 * i3bar doesn’t crash and the user gets an annoying message. */
200 if (!new_block->full_text)
201 new_block->full_text = i3string_from_utf8("SPEC VIOLATION (null)");
202 if (new_block->urgent)
203 ctx->has_urgent = true;
204 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
208 static int stdin_end_array(void *context) {
209 DLOG("dumping statusline:\n");
210 struct status_block *current;
211 TAILQ_FOREACH(current, &statusline_head, blocks) {
212 DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
213 DLOG("color = %s\n", current->color);
215 DLOG("end of dump\n");
220 * Helper function to read stdin
223 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
224 int fd = watcher->fd;
227 int buffer_len = STDIN_CHUNK_SIZE;
228 unsigned char *buffer = smalloc(buffer_len+1);
231 n = read(fd, buffer + rec, buffer_len - rec);
233 if (errno == EAGAIN) {
237 ELOG("read() failed!: %s\n", strerror(errno));
241 /* end of file, kill the watcher */
242 ELOG("stdin: received EOF\n");
245 *ret_buffer_len = -1;
250 if (rec == buffer_len) {
251 buffer_len += STDIN_CHUNK_SIZE;
252 buffer = srealloc(buffer, buffer_len);
255 if (*buffer == '\0') {
259 *ret_buffer_len = rec;
263 static void read_flat_input(char *buffer, int length) {
264 struct status_block *first = TAILQ_FIRST(&statusline_head);
265 /* Clear the old buffer if any. */
266 I3STRING_FREE(first->full_text);
267 /* Remove the trailing newline and terminate the string at the same
269 if (buffer[length-1] == '\n' || buffer[length-1] == '\r')
270 buffer[length-1] = '\0';
271 else buffer[length] = '\0';
272 first->full_text = i3string_from_utf8(buffer);
275 static bool read_json_input(unsigned char *input, int length) {
276 yajl_status status = yajl_parse(parser, input, length);
277 bool has_urgent = false;
279 if (status != yajl_status_ok) {
281 if (status != yajl_status_ok && status != yajl_status_insufficient_data) {
283 fprintf(stderr, "[i3bar] Could not parse JSON input (code %d): %.*s\n",
284 status, length, input);
285 } else if (parser_context.has_urgent) {
292 * Callbalk for stdin. We read a line from stdin and store the result
296 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
298 unsigned char *buffer = get_buffer(watcher, &rec);
301 bool has_urgent = false;
302 if (child.version > 0) {
303 has_urgent = read_json_input(buffer, rec);
305 read_flat_input((char*)buffer, rec);
308 draw_bars(has_urgent);
312 * Callbalk for stdin first line. We read the first line to detect
313 * whether this is JSON or plain text
316 void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
318 unsigned char *buffer = get_buffer(watcher, &rec);
321 DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
322 /* Detect whether this is JSON or plain text. */
323 unsigned int consumed = 0;
324 /* At the moment, we don’t care for the version. This might change
325 * in the future, but for now, we just discard it. */
326 parse_json_header(&child, buffer, rec, &consumed);
327 if (child.version > 0) {
328 /* If hide-on-modifier is set, we start of by sending the
329 * child a SIGSTOP, because the bars aren't mapped at start */
330 if (config.hide_on_modifier) {
333 read_json_input(buffer + consumed, rec - consumed);
335 /* In case of plaintext, we just add a single block and change its
336 * full_text pointer later. */
337 struct status_block *new_block = scalloc(sizeof(struct status_block));
338 TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
339 read_flat_input((char*)buffer, rec);
342 ev_io_stop(main_loop, stdin_io);
343 ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
344 ev_io_start(main_loop, stdin_io);
348 * We received a sigchild, meaning, that the child-process terminated.
349 * We simply free the respective data-structures and don't care for input
353 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
354 ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
360 void child_write_output(void) {
361 if (child.click_events) {
362 const unsigned char *output;
368 yajl_gen_get_buf(gen, &output, &size);
369 write(child_stdin, output, size);
370 write(child_stdin, "\n", 1);
376 * Start a child-process with the specified command and reroute stdin.
377 * We actually start a $SHELL to execute the command so we don't have to care
378 * about arguments and such
381 void start_child(char *command) {
382 /* Allocate a yajl parser which will be used to parse stdin. */
383 memset(&callbacks, '\0', sizeof(yajl_callbacks));
384 callbacks.yajl_map_key = stdin_map_key;
385 callbacks.yajl_boolean = stdin_boolean;
386 callbacks.yajl_string = stdin_string;
387 callbacks.yajl_integer = stdin_integer;
388 callbacks.yajl_start_array = stdin_start_array;
389 callbacks.yajl_end_array = stdin_end_array;
390 callbacks.yajl_start_map = stdin_start_map;
391 callbacks.yajl_end_map = stdin_end_map;
393 yajl_parser_config parse_conf = { 0, 0 };
395 parser = yajl_alloc(&callbacks, &parse_conf, NULL, (void*)&parser_context);
397 gen = yajl_gen_alloc(NULL, NULL);
399 parser = yajl_alloc(&callbacks, NULL, &parser_context);
401 gen = yajl_gen_alloc(NULL);
404 if (command != NULL) {
405 int pipe_in[2]; /* pipe we read from */
406 int pipe_out[2]; /* pipe we write to */
408 if (pipe(pipe_in) == -1)
409 err(EXIT_FAILURE, "pipe(pipe_in)");
410 if (pipe(pipe_out) == -1)
411 err(EXIT_FAILURE, "pipe(pipe_out)");
416 ELOG("Couldn't fork(): %s\n", strerror(errno));
419 /* Child-process. Reroute streams and start shell */
424 dup2(pipe_in[1], STDOUT_FILENO);
425 dup2(pipe_out[0], STDIN_FILENO);
427 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char*) NULL);
430 /* Parent-process. Reroute streams */
435 dup2(pipe_in[0], STDIN_FILENO);
436 child_stdin = pipe_out[1];
442 /* We set O_NONBLOCK because blocking is evil in event-driven software */
443 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
445 stdin_io = smalloc(sizeof(ev_io));
446 ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
447 ev_io_start(main_loop, stdin_io);
449 /* We must cleanup, if the child unexpectedly terminates */
450 child_sig = smalloc(sizeof(ev_child));
451 ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
452 ev_child_start(main_loop, child_sig);
454 atexit(kill_child_at_exit);
457 void child_click_events_initialize(void) {
458 if (!child.click_events_init) {
459 yajl_gen_array_open(gen);
460 child_write_output();
461 child.click_events_init = true;
465 void child_click_events_key(const char *key) {
466 yajl_gen_string(gen, (const unsigned char *)key, strlen(key));
470 * Generates a click event, if enabled.
473 void send_block_clicked(int button, const char *name, const char *instance, int x, int y) {
474 if (child.click_events) {
475 child_click_events_initialize();
477 yajl_gen_map_open(gen);
480 child_click_events_key("name");
481 yajl_gen_string(gen, (const unsigned char *)name, strlen(name));
485 child_click_events_key("instance");
486 yajl_gen_string(gen, (const unsigned char *)instance, strlen(instance));
489 child_click_events_key("button");
490 yajl_gen_integer(gen, button);
492 child_click_events_key("x");
493 yajl_gen_integer(gen, x);
495 child_click_events_key("y");
496 yajl_gen_integer(gen, y);
498 yajl_gen_map_close(gen);
499 child_write_output();
504 * kill()s the child-process (if any). Called when exit()ing.
507 void kill_child_at_exit(void) {
509 if (child.cont_signal > 0 && child.stopped)
510 kill(child.pid, child.cont_signal);
511 kill(child.pid, SIGTERM);
516 * kill()s the child-process (if existent) and closes and
517 * free()s the stdin- and sigchild-watchers
520 void kill_child(void) {
522 if (child.cont_signal > 0 && child.stopped)
523 kill(child.pid, child.cont_signal);
524 kill(child.pid, SIGTERM);
526 waitpid(child.pid, &status, 0);
532 * Sends a SIGSTOP to the child-process (if existent)
535 void stop_child(void) {
536 if (child.stop_signal > 0 && !child.stopped) {
537 child.stopped = true;
538 kill(child.pid, child.stop_signal);
543 * Sends a SIGCONT to the child-process (if existent)
546 void cont_child(void) {
547 if (child.cont_signal > 0 && child.stopped) {
548 child.stopped = false;
549 kill(child.pid, child.cont_signal);