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