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