]> git.sur5r.net Git - i3/i3/blob - i3bar/src/child.c
bb5ceaff0ee2cc1592e1edf157becdcdd4e7fdc9
[i3/i3] / i3bar / src / child.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3bar - an xcb-based status- and ws-bar for i3
5  * © 2010 Axel Wagner and contributors (see also: LICENSE)
6  *
7  * child.c: Getting input for the statusline
8  *
9  */
10 #include "common.h"
11
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <sys/types.h>
15 #include <sys/wait.h>
16 #include <signal.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <fcntl.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <err.h>
23 #include <ev.h>
24 #include <yajl/yajl_common.h>
25 #include <yajl/yajl_parse.h>
26 #include <yajl/yajl_version.h>
27 #include <yajl/yajl_gen.h>
28 #include <paths.h>
29
30 /* Global variables for child_*() */
31 i3bar_child child;
32
33 /* stdin- and SIGCHLD-watchers */
34 ev_io *stdin_io;
35 ev_child *child_sig;
36
37 /* JSON parser for stdin */
38 yajl_handle parser;
39
40 /* JSON generator for stdout */
41 yajl_gen gen;
42
43 typedef struct parser_ctx {
44     /* True if one of the parsed blocks was urgent */
45     bool has_urgent;
46
47     /* A copy of the last JSON map key. */
48     char *last_map_key;
49
50     /* The current block. Will be filled, then copied and put into the list of
51      * blocks. */
52     struct status_block block;
53 } parser_ctx;
54
55 parser_ctx parser_context;
56
57 struct statusline_head statusline_head = TAILQ_HEAD_INITIALIZER(statusline_head);
58 /* Used temporarily while reading a statusline */
59 struct statusline_head statusline_buffer = TAILQ_HEAD_INITIALIZER(statusline_buffer);
60
61 int child_stdin;
62
63 /*
64  * Remove all blocks from the given statusline.
65  * If free_resources is set, the fields of each status block will be free'd.
66  */
67 static void clear_statusline(struct statusline_head *head, bool free_resources) {
68     struct status_block *first;
69     while (!TAILQ_EMPTY(head)) {
70         first = TAILQ_FIRST(head);
71         if (free_resources) {
72             I3STRING_FREE(first->full_text);
73             I3STRING_FREE(first->short_text);
74             FREE(first->color);
75             FREE(first->name);
76             FREE(first->instance);
77             FREE(first->min_width_str);
78             FREE(first->background);
79             FREE(first->border);
80         }
81
82         TAILQ_REMOVE(head, first, blocks);
83         free(first);
84     }
85 }
86
87 static void copy_statusline(struct statusline_head *from, struct statusline_head *to) {
88     struct status_block *current;
89     TAILQ_FOREACH(current, from, blocks) {
90         struct status_block *new_block = smalloc(sizeof(struct status_block));
91         memcpy(new_block, current, sizeof(struct status_block));
92         TAILQ_INSERT_TAIL(to, new_block, blocks);
93     }
94 }
95
96 /*
97  * Replaces the statusline in memory with an error message. Pass a format
98  * string and format parameters as you would in `printf'. The next time
99  * `draw_bars' is called, the error message text will be drawn on the bar in
100  * the space allocated for the statusline.
101  */
102 __attribute__((format(printf, 1, 2))) static void set_statusline_error(const char *format, ...) {
103     clear_statusline(&statusline_head, true);
104
105     char *message;
106     va_list args;
107     va_start(args, format);
108     if (vasprintf(&message, format, args) == -1) {
109         goto finish;
110     }
111
112     struct status_block *err_block = scalloc(1, sizeof(struct status_block));
113     err_block->full_text = i3string_from_utf8("Error: ");
114     err_block->name = sstrdup("error");
115     err_block->color = sstrdup("#ff0000");
116     err_block->no_separator = true;
117
118     struct status_block *message_block = scalloc(1, sizeof(struct status_block));
119     message_block->full_text = i3string_from_utf8(message);
120     message_block->name = sstrdup("error_message");
121     message_block->color = sstrdup("#ff0000");
122     message_block->no_separator = true;
123
124     TAILQ_INSERT_HEAD(&statusline_head, err_block, blocks);
125     TAILQ_INSERT_TAIL(&statusline_head, message_block, blocks);
126
127 finish:
128     FREE(message);
129     va_end(args);
130 }
131
132 /*
133  * Stop and free() the stdin- and SIGCHLD-watchers
134  *
135  */
136 static void cleanup(void) {
137     if (stdin_io != NULL) {
138         ev_io_stop(main_loop, stdin_io);
139         FREE(stdin_io);
140     }
141
142     if (child_sig != NULL) {
143         ev_child_stop(main_loop, child_sig);
144         FREE(child_sig);
145     }
146
147     memset(&child, 0, sizeof(i3bar_child));
148 }
149
150 /*
151  * The start of a new array is the start of a new status line, so we clear all
152  * previous entries from the buffer.
153  */
154 static int stdin_start_array(void *context) {
155     // the blocks are still used by statusline_head, so we won't free the
156     // resources here.
157     clear_statusline(&statusline_buffer, false);
158     return 1;
159 }
160
161 /*
162  * The start of a map is the start of a single block of the status line.
163  *
164  */
165 static int stdin_start_map(void *context) {
166     parser_ctx *ctx = context;
167     memset(&(ctx->block), '\0', sizeof(struct status_block));
168
169     /* Default width of the separator block. */
170     if (config.separator_symbol == NULL)
171         ctx->block.sep_block_width = logical_px(9);
172     else
173         ctx->block.sep_block_width = logical_px(8) + separator_symbol_width;
174
175     return 1;
176 }
177
178 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
179     parser_ctx *ctx = context;
180     FREE(ctx->last_map_key);
181     sasprintf(&(ctx->last_map_key), "%.*s", len, key);
182     return 1;
183 }
184
185 static int stdin_boolean(void *context, int val) {
186     parser_ctx *ctx = context;
187     if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
188         ctx->block.urgent = val;
189         return 1;
190     }
191     if (strcasecmp(ctx->last_map_key, "separator") == 0) {
192         ctx->block.no_separator = !val;
193         return 1;
194     }
195
196     return 1;
197 }
198
199 static int stdin_string(void *context, const unsigned char *val, size_t len) {
200     parser_ctx *ctx = context;
201     if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
202         ctx->block.full_text = i3string_from_markup_with_length((const char *)val, len);
203         return 1;
204     }
205     if (strcasecmp(ctx->last_map_key, "short_text") == 0) {
206         ctx->block.short_text = i3string_from_markup_with_length((const char *)val, len);
207         return 1;
208     }
209     if (strcasecmp(ctx->last_map_key, "color") == 0) {
210         sasprintf(&(ctx->block.color), "%.*s", len, val);
211         return 1;
212     }
213     if (strcasecmp(ctx->last_map_key, "background") == 0) {
214         sasprintf(&(ctx->block.background), "%.*s", len, val);
215         return 1;
216     }
217     if (strcasecmp(ctx->last_map_key, "border") == 0) {
218         sasprintf(&(ctx->block.border), "%.*s", len, val);
219         return 1;
220     }
221     if (strcasecmp(ctx->last_map_key, "markup") == 0) {
222         ctx->block.pango_markup = (len == strlen("pango") && !strncasecmp((const char *)val, "pango", strlen("pango")));
223         return 1;
224     }
225     if (strcasecmp(ctx->last_map_key, "align") == 0) {
226         if (len == strlen("center") && !strncmp((const char *)val, "center", strlen("center"))) {
227             ctx->block.align = ALIGN_CENTER;
228         } else if (len == strlen("right") && !strncmp((const char *)val, "right", strlen("right"))) {
229             ctx->block.align = ALIGN_RIGHT;
230         } else {
231             ctx->block.align = ALIGN_LEFT;
232         }
233         return 1;
234     }
235     if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
236         sasprintf(&(ctx->block.min_width_str), "%.*s", len, val);
237         return 1;
238     }
239     if (strcasecmp(ctx->last_map_key, "name") == 0) {
240         sasprintf(&(ctx->block.name), "%.*s", len, val);
241         return 1;
242     }
243     if (strcasecmp(ctx->last_map_key, "instance") == 0) {
244         sasprintf(&(ctx->block.instance), "%.*s", len, val);
245         return 1;
246     }
247
248     return 1;
249 }
250
251 static int stdin_integer(void *context, long long val) {
252     parser_ctx *ctx = context;
253     if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
254         ctx->block.min_width = (uint32_t)val;
255         return 1;
256     }
257     if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
258         ctx->block.sep_block_width = (uint32_t)val;
259         return 1;
260     }
261
262     return 1;
263 }
264
265 /*
266  * When a map is finished, we have an entire status block.
267  * Move it from the parser's context to the statusline buffer.
268  */
269 static int stdin_end_map(void *context) {
270     parser_ctx *ctx = context;
271     struct status_block *new_block = smalloc(sizeof(struct status_block));
272     memcpy(new_block, &(ctx->block), sizeof(struct status_block));
273     /* Ensure we have a full_text set, so that when it is missing (or null),
274      * i3bar doesn’t crash and the user gets an annoying message. */
275     if (!new_block->full_text)
276         new_block->full_text = i3string_from_utf8("SPEC VIOLATION: full_text is NULL!");
277     if (new_block->urgent)
278         ctx->has_urgent = true;
279
280     if (new_block->min_width_str) {
281         i3String *text = i3string_from_utf8(new_block->min_width_str);
282         i3string_set_markup(text, new_block->pango_markup);
283         new_block->min_width = (uint32_t)predict_text_width(text);
284         i3string_free(text);
285     }
286
287     i3string_set_markup(new_block->full_text, new_block->pango_markup);
288
289     if (new_block->short_text != NULL)
290         i3string_set_markup(new_block->short_text, new_block->pango_markup);
291
292     TAILQ_INSERT_TAIL(&statusline_buffer, new_block, blocks);
293     return 1;
294 }
295
296 /*
297  * When an array is finished, we have an entire statusline.
298  * Copy it from the buffer to the actual statusline.
299  */
300 static int stdin_end_array(void *context) {
301     DLOG("copying statusline_buffer to statusline_head\n");
302     clear_statusline(&statusline_head, true);
303     copy_statusline(&statusline_buffer, &statusline_head);
304
305     DLOG("dumping statusline:\n");
306     struct status_block *current;
307     TAILQ_FOREACH(current, &statusline_head, blocks) {
308         DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
309         DLOG("short_text = %s\n", (current->short_text == NULL ? NULL : i3string_as_utf8(current->short_text)));
310         DLOG("color = %s\n", current->color);
311     }
312     DLOG("end of dump\n");
313     return 1;
314 }
315
316 /*
317  * Helper function to read stdin
318  *
319  * Returns NULL on EOF.
320  *
321  */
322 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
323     int fd = watcher->fd;
324     int n = 0;
325     int rec = 0;
326     int buffer_len = STDIN_CHUNK_SIZE;
327     unsigned char *buffer = smalloc(buffer_len + 1);
328     buffer[0] = '\0';
329     while (1) {
330         n = read(fd, buffer + rec, buffer_len - rec);
331         if (n == -1) {
332             if (errno == EAGAIN) {
333                 /* finish up */
334                 break;
335             }
336             ELOG("read() failed!: %s\n", strerror(errno));
337             FREE(buffer);
338             exit(EXIT_FAILURE);
339         }
340         if (n == 0) {
341             ELOG("stdin: received EOF\n");
342             FREE(buffer);
343             *ret_buffer_len = -1;
344             return NULL;
345         }
346         rec += n;
347
348         if (rec == buffer_len) {
349             buffer_len += STDIN_CHUNK_SIZE;
350             buffer = srealloc(buffer, buffer_len);
351         }
352     }
353     if (*buffer == '\0') {
354         FREE(buffer);
355         rec = -1;
356     }
357     *ret_buffer_len = rec;
358     return buffer;
359 }
360
361 static void read_flat_input(char *buffer, int length) {
362     struct status_block *first = TAILQ_FIRST(&statusline_head);
363     /* Clear the old buffer if any. */
364     I3STRING_FREE(first->full_text);
365     /* Remove the trailing newline and terminate the string at the same
366      * time. */
367     if (buffer[length - 1] == '\n' || buffer[length - 1] == '\r') {
368         buffer[length - 1] = '\0';
369     } else {
370         buffer[length] = '\0';
371     }
372
373     first->full_text = i3string_from_utf8(buffer);
374 }
375
376 static bool read_json_input(unsigned char *input, int length) {
377     yajl_status status = yajl_parse(parser, input, length);
378     bool has_urgent = false;
379     if (status != yajl_status_ok) {
380         char *message = (char *)yajl_get_error(parser, 0, input, length);
381
382         /* strip the newline yajl adds to the error message */
383         if (message[strlen(message) - 1] == '\n')
384             message[strlen(message) - 1] = '\0';
385
386         fprintf(stderr, "[i3bar] Could not parse JSON input (code = %d, message = %s): %.*s\n",
387                 status, message, length, input);
388
389         set_statusline_error("Could not parse JSON (%s)", message);
390         yajl_free_error(parser, (unsigned char *)message);
391         draw_bars(false);
392     } else if (parser_context.has_urgent) {
393         has_urgent = true;
394     }
395     return has_urgent;
396 }
397
398 /*
399  * Callbalk for stdin. We read a line from stdin and store the result
400  * in statusline
401  *
402  */
403 static void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
404     int rec;
405     unsigned char *buffer = get_buffer(watcher, &rec);
406     if (buffer == NULL)
407         return;
408     bool has_urgent = false;
409     if (child.version > 0) {
410         has_urgent = read_json_input(buffer, rec);
411     } else {
412         read_flat_input((char *)buffer, rec);
413     }
414     free(buffer);
415     draw_bars(has_urgent);
416 }
417
418 /*
419  * Callbalk for stdin first line. We read the first line to detect
420  * whether this is JSON or plain text
421  *
422  */
423 static void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
424     int rec;
425     unsigned char *buffer = get_buffer(watcher, &rec);
426     if (buffer == NULL)
427         return;
428     DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
429     /* Detect whether this is JSON or plain text. */
430     unsigned int consumed = 0;
431     /* At the moment, we don’t care for the version. This might change
432      * in the future, but for now, we just discard it. */
433     parse_json_header(&child, buffer, rec, &consumed);
434     if (child.version > 0) {
435         /* If hide-on-modifier is set, we start of by sending the
436          * child a SIGSTOP, because the bars aren't mapped at start */
437         if (config.hide_on_modifier) {
438             stop_child();
439         }
440         draw_bars(read_json_input(buffer + consumed, rec - consumed));
441     } else {
442         /* In case of plaintext, we just add a single block and change its
443          * full_text pointer later. */
444         struct status_block *new_block = scalloc(1, sizeof(struct status_block));
445         TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
446         read_flat_input((char *)buffer, rec);
447     }
448     free(buffer);
449     ev_io_stop(main_loop, stdin_io);
450     ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
451     ev_io_start(main_loop, stdin_io);
452 }
453
454 /*
455  * We received a SIGCHLD, meaning, that the child process terminated.
456  * We simply free the respective data structures and don't care for input
457  * anymore
458  *
459  */
460 static void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
461     int exit_status = WEXITSTATUS(watcher->rstatus);
462
463     ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
464          child.pid,
465          exit_status);
466
467     /* this error is most likely caused by a user giving a nonexecutable or
468      * nonexistent file, so we will handle those cases separately. */
469     if (exit_status == 126)
470         set_statusline_error("status_command is not executable (exit %d)", exit_status);
471     else if (exit_status == 127)
472         set_statusline_error("status_command not found or is missing a library dependency (exit %d)", exit_status);
473     else
474         set_statusline_error("status_command process exited unexpectedly (exit %d)", exit_status);
475
476     cleanup();
477     draw_bars(false);
478 }
479
480 static void child_write_output(void) {
481     if (child.click_events) {
482         const unsigned char *output;
483         size_t size;
484         ssize_t n;
485
486         yajl_gen_get_buf(gen, &output, &size);
487
488         n = writeall(child_stdin, output, size);
489         if (n != -1)
490             n = writeall(child_stdin, "\n", 1);
491
492         yajl_gen_clear(gen);
493
494         if (n == -1) {
495             child.click_events = false;
496             kill_child();
497             set_statusline_error("child_write_output failed");
498             draw_bars(false);
499         }
500     }
501 }
502
503 /*
504  * Start a child process with the specified command and reroute stdin.
505  * We actually start a $SHELL to execute the command so we don't have to care
506  * about arguments and such.
507  *
508  * If `command' is NULL, such as in the case when no `status_command' is given
509  * in the bar config, no child will be started.
510  *
511  */
512 void start_child(char *command) {
513     if (command == NULL)
514         return;
515
516     /* Allocate a yajl parser which will be used to parse stdin. */
517     static yajl_callbacks callbacks = {
518         .yajl_boolean = stdin_boolean,
519         .yajl_integer = stdin_integer,
520         .yajl_string = stdin_string,
521         .yajl_start_map = stdin_start_map,
522         .yajl_map_key = stdin_map_key,
523         .yajl_end_map = stdin_end_map,
524         .yajl_start_array = stdin_start_array,
525         .yajl_end_array = stdin_end_array,
526     };
527     parser = yajl_alloc(&callbacks, NULL, &parser_context);
528
529     gen = yajl_gen_alloc(NULL);
530
531     int pipe_in[2];  /* pipe we read from */
532     int pipe_out[2]; /* pipe we write to */
533
534     if (pipe(pipe_in) == -1)
535         err(EXIT_FAILURE, "pipe(pipe_in)");
536     if (pipe(pipe_out) == -1)
537         err(EXIT_FAILURE, "pipe(pipe_out)");
538
539     child.pid = fork();
540     switch (child.pid) {
541         case -1:
542             ELOG("Couldn't fork(): %s\n", strerror(errno));
543             exit(EXIT_FAILURE);
544         case 0:
545             /* Child-process. Reroute streams and start shell */
546
547             close(pipe_in[0]);
548             close(pipe_out[1]);
549
550             dup2(pipe_in[1], STDOUT_FILENO);
551             dup2(pipe_out[0], STDIN_FILENO);
552
553             setpgid(child.pid, 0);
554             execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command, (char *)NULL);
555             return;
556         default:
557             /* Parent-process. Reroute streams */
558
559             close(pipe_in[1]);
560             close(pipe_out[0]);
561
562             dup2(pipe_in[0], STDIN_FILENO);
563             child_stdin = pipe_out[1];
564
565             break;
566     }
567
568     /* We set O_NONBLOCK because blocking is evil in event-driven software */
569     fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
570
571     stdin_io = smalloc(sizeof(ev_io));
572     ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
573     ev_io_start(main_loop, stdin_io);
574
575     /* We must cleanup, if the child unexpectedly terminates */
576     child_sig = smalloc(sizeof(ev_child));
577     ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
578     ev_child_start(main_loop, child_sig);
579
580     atexit(kill_child_at_exit);
581 }
582
583 static void child_click_events_initialize(void) {
584     if (!child.click_events_init) {
585         yajl_gen_array_open(gen);
586         child_write_output();
587         child.click_events_init = true;
588     }
589 }
590
591 static void child_click_events_key(const char *key) {
592     yajl_gen_string(gen, (const unsigned char *)key, strlen(key));
593 }
594
595 /*
596  * Generates a click event, if enabled.
597  *
598  */
599 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) {
600     if (!child.click_events) {
601         return;
602     }
603
604     child_click_events_initialize();
605
606     yajl_gen_map_open(gen);
607
608     if (name) {
609         child_click_events_key("name");
610         yajl_gen_string(gen, (const unsigned char *)name, strlen(name));
611     }
612
613     if (instance) {
614         child_click_events_key("instance");
615         yajl_gen_string(gen, (const unsigned char *)instance, strlen(instance));
616     }
617
618     child_click_events_key("button");
619     yajl_gen_integer(gen, button);
620
621     child_click_events_key("x");
622     yajl_gen_integer(gen, x);
623
624     child_click_events_key("y");
625     yajl_gen_integer(gen, y);
626
627     child_click_events_key("relative_x");
628     yajl_gen_integer(gen, x_rel);
629
630     child_click_events_key("relative_y");
631     yajl_gen_integer(gen, y_rel);
632
633     child_click_events_key("width");
634     yajl_gen_integer(gen, width);
635
636     child_click_events_key("height");
637     yajl_gen_integer(gen, height);
638
639     yajl_gen_map_close(gen);
640     child_write_output();
641 }
642
643 /*
644  * kill()s the child process (if any). Called when exit()ing.
645  *
646  */
647 void kill_child_at_exit(void) {
648     if (child.pid > 0) {
649         if (child.cont_signal > 0 && child.stopped)
650             killpg(child.pid, child.cont_signal);
651         killpg(child.pid, SIGTERM);
652     }
653 }
654
655 /*
656  * kill()s the child process (if existent) and closes and
657  * free()s the stdin- and SIGCHLD-watchers
658  *
659  */
660 void kill_child(void) {
661     if (child.pid > 0) {
662         if (child.cont_signal > 0 && child.stopped)
663             killpg(child.pid, child.cont_signal);
664         killpg(child.pid, SIGTERM);
665         int status;
666         waitpid(child.pid, &status, 0);
667         cleanup();
668     }
669 }
670
671 /*
672  * Sends a SIGSTOP to the child process (if existent)
673  *
674  */
675 void stop_child(void) {
676     if (child.stop_signal > 0 && !child.stopped) {
677         child.stopped = true;
678         killpg(child.pid, child.stop_signal);
679     }
680 }
681
682 /*
683  * Sends a SIGCONT to the child process (if existent)
684  *
685  */
686 void cont_child(void) {
687     if (child.cont_signal > 0 && child.stopped) {
688         child.stopped = false;
689         killpg(child.pid, child.cont_signal);
690     }
691 }
692
693 /*
694  * Whether or not the child want click events
695  *
696  */
697 bool child_want_click_events(void) {
698     return child.click_events;
699 }