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