]> git.sur5r.net Git - i3/i3/blob - i3bar/src/child.c
Merge branch 'master' into next
[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-2012 Axel Wagner and contributors (see also: LICENSE)
6  *
7  * child.c: Getting Input for the statusline
8  *
9  */
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <signal.h>
15 #include <stdio.h>
16 #include <fcntl.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <err.h>
20 #include <ev.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>
25
26 #include "common.h"
27
28 /* Global variables for child_*() */
29 i3bar_child child = { 0 };
30
31 /* stdin- and sigchild-watchers */
32 ev_io    *stdin_io;
33 ev_child *child_sig;
34
35 /* JSON parser for stdin */
36 yajl_callbacks callbacks;
37 yajl_handle parser;
38
39 /* JSON generator for stdout */
40 yajl_gen gen;
41
42 typedef struct parser_ctx {
43     /* True if one of the parsed blocks was urgent */
44     bool has_urgent;
45
46     /* A copy of the last JSON map key. */
47     char *last_map_key;
48
49     /* The current block. Will be filled, then copied and put into the list of
50      * blocks. */
51     struct status_block block;
52 } parser_ctx;
53
54 parser_ctx parser_context;
55
56 /* The buffer statusline points to */
57 struct statusline_head statusline_head = TAILQ_HEAD_INITIALIZER(statusline_head);
58 char *statusline_buffer = NULL;
59
60 int child_stdin;
61
62 /*
63  * Stop and free() the stdin- and sigchild-watchers
64  *
65  */
66 void cleanup(void) {
67     if (stdin_io != NULL) {
68         ev_io_stop(main_loop, stdin_io);
69         FREE(stdin_io);
70         FREE(statusline_buffer);
71         /* statusline pointed to memory within statusline_buffer */
72         statusline = NULL;
73     }
74
75     if (child_sig != NULL) {
76         ev_child_stop(main_loop, child_sig);
77         FREE(child_sig);
78     }
79
80     memset(&child, 0, sizeof(i3bar_child));
81 }
82
83 /*
84  * The start of a new array is the start of a new status line, so we clear all
85  * previous entries.
86  *
87  */
88 static int stdin_start_array(void *context) {
89     struct status_block *first;
90     while (!TAILQ_EMPTY(&statusline_head)) {
91         first = TAILQ_FIRST(&statusline_head);
92         I3STRING_FREE(first->full_text);
93         FREE(first->color);
94         FREE(first->name);
95         FREE(first->instance);
96         TAILQ_REMOVE(&statusline_head, first, blocks);
97         free(first);
98     }
99     return 1;
100 }
101
102 /*
103  * The start of a map is the start of a single block of the status line.
104  *
105  */
106 static int stdin_start_map(void *context) {
107     parser_ctx *ctx = context;
108     memset(&(ctx->block), '\0', sizeof(struct status_block));
109
110     /* Default width of the separator block. */
111     ctx->block.sep_block_width = 9;
112
113     return 1;
114 }
115
116 #if YAJL_MAJOR >= 2
117 static int stdin_map_key(void *context, const unsigned char *key, size_t len) {
118 #else
119 static int stdin_map_key(void *context, const unsigned char *key, unsigned int len) {
120 #endif
121     parser_ctx *ctx = context;
122     FREE(ctx->last_map_key);
123     sasprintf(&(ctx->last_map_key), "%.*s", len, key);
124     return 1;
125 }
126
127 static int stdin_boolean(void *context, int val) {
128     parser_ctx *ctx = context;
129     if (strcasecmp(ctx->last_map_key, "urgent") == 0) {
130         ctx->block.urgent = val;
131     }
132     if (strcasecmp(ctx->last_map_key, "separator") == 0) {
133         ctx->block.no_separator = !val;
134     }
135     return 1;
136 }
137
138 #if YAJL_MAJOR >= 2
139 static int stdin_string(void *context, const unsigned char *val, size_t len) {
140 #else
141 static int stdin_string(void *context, const unsigned char *val, unsigned int len) {
142 #endif
143     parser_ctx *ctx = context;
144     if (strcasecmp(ctx->last_map_key, "full_text") == 0) {
145         ctx->block.full_text = i3string_from_utf8_with_length((const char *)val, len);
146     }
147     if (strcasecmp(ctx->last_map_key, "color") == 0) {
148         sasprintf(&(ctx->block.color), "%.*s", len, val);
149     }
150     if (strcasecmp(ctx->last_map_key, "align") == 0) {
151         if (len == strlen("left") && !strncmp((const char*)val, "left", strlen("left"))) {
152             ctx->block.align = ALIGN_LEFT;
153         } else if (len == strlen("right") && !strncmp((const char*)val, "right", strlen("right"))) {
154             ctx->block.align = ALIGN_RIGHT;
155         } else {
156             ctx->block.align = ALIGN_CENTER;
157         }
158     } else if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
159         i3String *text = i3string_from_utf8_with_length((const char *)val, len);
160         ctx->block.min_width = (uint32_t)predict_text_width(text);
161         i3string_free(text);
162     }
163     if (strcasecmp(ctx->last_map_key, "name") == 0) {
164         char *copy = (char*)malloc(len+1);
165         strncpy(copy, (const char *)val, len);
166         copy[len] = 0;
167         ctx->block.name = copy;
168     }
169     if (strcasecmp(ctx->last_map_key, "instance") == 0) {
170         char *copy = (char*)malloc(len+1);
171         strncpy(copy, (const char *)val, len);
172         copy[len] = 0;
173         ctx->block.instance = copy;
174     }
175     return 1;
176 }
177
178 #if YAJL_MAJOR >= 2
179 static int stdin_integer(void *context, long long val) {
180 #else
181 static int stdin_integer(void *context, long val) {
182 #endif
183     parser_ctx *ctx = context;
184     if (strcasecmp(ctx->last_map_key, "min_width") == 0) {
185         ctx->block.min_width = (uint32_t)val;
186     }
187     if (strcasecmp(ctx->last_map_key, "separator_block_width") == 0) {
188         ctx->block.sep_block_width = (uint32_t)val;
189     }
190     return 1;
191 }
192
193 static int stdin_end_map(void *context) {
194     parser_ctx *ctx = context;
195     struct status_block *new_block = smalloc(sizeof(struct status_block));
196     memcpy(new_block, &(ctx->block), sizeof(struct status_block));
197     /* Ensure we have a full_text set, so that when it is missing (or null),
198      * i3bar doesn’t crash and the user gets an annoying message. */
199     if (!new_block->full_text)
200         new_block->full_text = i3string_from_utf8("SPEC VIOLATION (null)");
201     if (new_block->urgent)
202         ctx->has_urgent = true;
203     TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
204     return 1;
205 }
206
207 static int stdin_end_array(void *context) {
208     DLOG("dumping statusline:\n");
209     struct status_block *current;
210     TAILQ_FOREACH(current, &statusline_head, blocks) {
211         DLOG("full_text = %s\n", i3string_as_utf8(current->full_text));
212         DLOG("color = %s\n", current->color);
213     }
214     DLOG("end of dump\n");
215     return 1;
216 }
217
218 /*
219  * Helper function to read stdin
220  *
221  */
222 static unsigned char *get_buffer(ev_io *watcher, int *ret_buffer_len) {
223     int fd = watcher->fd;
224     int n = 0;
225     int rec = 0;
226     int buffer_len = STDIN_CHUNK_SIZE;
227     unsigned char *buffer = smalloc(buffer_len+1);
228     buffer[0] = '\0';
229     while(1) {
230         n = read(fd, buffer + rec, buffer_len - rec);
231         if (n == -1) {
232             if (errno == EAGAIN) {
233                 /* finish up */
234                 break;
235             }
236             ELOG("read() failed!: %s\n", strerror(errno));
237             exit(EXIT_FAILURE);
238         }
239         if (n == 0) {
240             /* end of file, kill the watcher */
241             ELOG("stdin: received EOF\n");
242             cleanup();
243             draw_bars(false);
244             *ret_buffer_len = -1;
245             return NULL;
246         }
247         rec += n;
248
249         if (rec == buffer_len) {
250             buffer_len += STDIN_CHUNK_SIZE;
251             buffer = srealloc(buffer, buffer_len);
252         }
253     }
254     if (*buffer == '\0') {
255         FREE(buffer);
256         rec = -1;
257     }
258     *ret_buffer_len = rec;
259     return buffer;
260 }
261
262 static void read_flat_input(char *buffer, int length) {
263     struct status_block *first = TAILQ_FIRST(&statusline_head);
264     /* Clear the old buffer if any. */
265     I3STRING_FREE(first->full_text);
266     /* Remove the trailing newline and terminate the string at the same
267      * time. */
268     if (buffer[length-1] == '\n' || buffer[length-1] == '\r')
269         buffer[length-1] = '\0';
270     else buffer[length] = '\0';
271     first->full_text = i3string_from_utf8(buffer);
272 }
273
274 static bool read_json_input(unsigned char *input, int length) {
275     yajl_status status = yajl_parse(parser, input, length);
276     bool has_urgent = false;
277 #if YAJL_MAJOR >= 2
278     if (status != yajl_status_ok) {
279 #else
280     if (status != yajl_status_ok && status != yajl_status_insufficient_data) {
281 #endif
282         fprintf(stderr, "[i3bar] Could not parse JSON input (code %d): %.*s\n",
283                 status, length, input);
284     } else if (parser_context.has_urgent) {
285         has_urgent = true;
286     }
287     return has_urgent;
288 }
289
290 /*
291  * Callbalk for stdin. We read a line from stdin and store the result
292  * in statusline
293  *
294  */
295 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
296     int rec;
297     unsigned char *buffer = get_buffer(watcher, &rec);
298     if (buffer == NULL)
299         return;
300     bool has_urgent = false;
301     if (child.version > 0) {
302         has_urgent = read_json_input(buffer, rec);
303     } else {
304         read_flat_input((char*)buffer, rec);
305     }
306     free(buffer);
307     draw_bars(has_urgent);
308 }
309
310 /*
311  * Callbalk for stdin first line. We read the first line to detect
312  * whether this is JSON or plain text
313  *
314  */
315 void stdin_io_first_line_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
316     int rec;
317     unsigned char *buffer = get_buffer(watcher, &rec);
318     if (buffer == NULL)
319         return;
320     DLOG("Detecting input type based on buffer *%.*s*\n", rec, buffer);
321     /* Detect whether this is JSON or plain text. */
322     unsigned int consumed = 0;
323     /* At the moment, we don’t care for the version. This might change
324      * in the future, but for now, we just discard it. */
325     parse_json_header(&child, buffer, rec, &consumed);
326     if (child.version > 0) {
327         /* If hide-on-modifier is set, we start of by sending the
328          * child a SIGSTOP, because the bars aren't mapped at start */
329         if (config.hide_on_modifier) {
330             stop_child();
331         }
332         read_json_input(buffer + consumed, rec - consumed);
333     } else {
334         /* In case of plaintext, we just add a single block and change its
335          * full_text pointer later. */
336         struct status_block *new_block = scalloc(sizeof(struct status_block));
337         TAILQ_INSERT_TAIL(&statusline_head, new_block, blocks);
338         read_flat_input((char*)buffer, rec);
339     }
340     free(buffer);
341     ev_io_stop(main_loop, stdin_io);
342     ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
343     ev_io_start(main_loop, stdin_io);
344 }
345
346 /*
347  * We received a sigchild, meaning, that the child-process terminated.
348  * We simply free the respective data-structures and don't care for input
349  * anymore
350  *
351  */
352 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
353     ELOG("Child (pid: %d) unexpectedly exited with status %d\n",
354            child.pid,
355            watcher->rstatus);
356     cleanup();
357 }
358
359 void child_write_output(void) {
360     if (child.click_events) {
361         const unsigned char *output;
362 #if YAJL_MAJOR < 2
363         unsigned int size;
364 #else
365         size_t size;
366 #endif
367         yajl_gen_get_buf(gen, &output, &size);
368         write(child_stdin, output, size);
369         write(child_stdin, "\n", 1);
370         yajl_gen_clear(gen);
371     }
372 }
373
374 /*
375  * Start a child-process with the specified command and reroute stdin.
376  * We actually start a $SHELL to execute the command so we don't have to care
377  * about arguments and such
378  *
379  */
380 void start_child(char *command) {
381     /* Allocate a yajl parser which will be used to parse stdin. */
382     memset(&callbacks, '\0', sizeof(yajl_callbacks));
383     callbacks.yajl_map_key = stdin_map_key;
384     callbacks.yajl_boolean = stdin_boolean;
385     callbacks.yajl_string = stdin_string;
386     callbacks.yajl_integer = stdin_integer;
387     callbacks.yajl_start_array = stdin_start_array;
388     callbacks.yajl_end_array = stdin_end_array;
389     callbacks.yajl_start_map = stdin_start_map;
390     callbacks.yajl_end_map = stdin_end_map;
391 #if YAJL_MAJOR < 2
392     yajl_parser_config parse_conf = { 0, 0 };
393
394     parser = yajl_alloc(&callbacks, &parse_conf, NULL, (void*)&parser_context);
395
396     gen = yajl_gen_alloc(NULL, NULL);
397 #else
398     parser = yajl_alloc(&callbacks, NULL, &parser_context);
399
400     gen = yajl_gen_alloc(NULL);
401 #endif
402
403     if (command != NULL) {
404         int pipe_in[2]; /* pipe we read from */
405         int pipe_out[2]; /* pipe we write to */
406
407         if (pipe(pipe_in) == -1)
408             err(EXIT_FAILURE, "pipe(pipe_in)");
409         if (pipe(pipe_out) == -1)
410             err(EXIT_FAILURE, "pipe(pipe_out)");
411
412         child.pid = fork();
413         switch (child.pid) {
414             case -1:
415                 ELOG("Couldn't fork(): %s\n", strerror(errno));
416                 exit(EXIT_FAILURE);
417             case 0:
418                 /* Child-process. Reroute streams and start shell */
419
420                 close(pipe_in[0]);
421                 close(pipe_out[1]);
422
423                 dup2(pipe_in[1], STDOUT_FILENO);
424                 dup2(pipe_out[0], STDIN_FILENO);
425
426                 static const char *shell = NULL;
427
428                 if ((shell = getenv("SHELL")) == NULL)
429                     shell = "/bin/sh";
430
431                 execl(shell, shell, "-c", command, (char*) NULL);
432                 return;
433             default:
434                 /* Parent-process. Reroute streams */
435
436                 close(pipe_in[1]);
437                 close(pipe_out[0]);
438
439                 dup2(pipe_in[0], STDIN_FILENO);
440                 child_stdin = pipe_out[1];
441
442                 break;
443         }
444     }
445
446     /* We set O_NONBLOCK because blocking is evil in event-driven software */
447     fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
448
449     stdin_io = smalloc(sizeof(ev_io));
450     ev_io_init(stdin_io, &stdin_io_first_line_cb, STDIN_FILENO, EV_READ);
451     ev_io_start(main_loop, stdin_io);
452
453     /* We must cleanup, if the child unexpectedly terminates */
454     child_sig = smalloc(sizeof(ev_child));
455     ev_child_init(child_sig, &child_sig_cb, child.pid, 0);
456     ev_child_start(main_loop, child_sig);
457
458     atexit(kill_child_at_exit);
459 }
460
461 void child_click_events_initialize(void) {
462     if (!child.click_events_init) {
463         yajl_gen_array_open(gen);
464         child_write_output();
465         child.click_events_init = true;
466     }
467 }
468
469 void child_click_events_key(const char *key) {
470     yajl_gen_string(gen, (const unsigned char *)key, strlen(key));
471 }
472
473 /*
474  * Generates a click event, if enabled.
475  *
476  */
477 void send_block_clicked(int button, const char *name, const char *instance, int x, int y) {
478     if (child.click_events) {
479         child_click_events_initialize();
480
481         yajl_gen_map_open(gen);
482
483         if (name) {
484             child_click_events_key("name");
485             yajl_gen_string(gen, (const unsigned char *)name, strlen(name));
486         }
487
488         if (instance) {
489             child_click_events_key("instance");
490             yajl_gen_string(gen, (const unsigned char *)instance, strlen(instance));
491         }
492
493         child_click_events_key("button");
494         yajl_gen_integer(gen, button);
495
496         child_click_events_key("x");
497         yajl_gen_integer(gen, x);
498
499         child_click_events_key("y");
500         yajl_gen_integer(gen, y);
501
502         yajl_gen_map_close(gen);
503         child_write_output();
504     }
505 }
506
507 /*
508  * kill()s the child-process (if any). Called when exit()ing.
509  *
510  */
511 void kill_child_at_exit(void) {
512     if (child.pid > 0) {
513         if (child.cont_signal > 0 && child.stopped)
514             kill(child.pid, child.cont_signal);
515         kill(child.pid, SIGTERM);
516     }
517 }
518
519 /*
520  * kill()s the child-process (if existent) and closes and
521  * free()s the stdin- and sigchild-watchers
522  *
523  */
524 void kill_child(void) {
525     if (child.pid > 0) {
526         if (child.cont_signal > 0 && child.stopped)
527             kill(child.pid, child.cont_signal);
528         kill(child.pid, SIGTERM);
529         int status;
530         waitpid(child.pid, &status, 0);
531         cleanup();
532     }
533 }
534
535 /*
536  * Sends a SIGSTOP to the child-process (if existent)
537  *
538  */
539 void stop_child(void) {
540     if (child.stop_signal > 0 && !child.stopped) {
541         child.stopped = true;
542         kill(child.pid, child.stop_signal);
543     }
544 }
545
546 /*
547  * Sends a SIGCONT to the child-process (if existent)
548  *
549  */
550 void cont_child(void) {
551     if (child.cont_signal > 0 && child.stopped) {
552         child.stopped = false;
553         kill(child.pid, child.cont_signal);
554     }
555 }