]> git.tuebingen.mpg.de Git - paraslash.git/blob - gui.c
gui.c: Constify local variables of add_spaces().
[paraslash.git] / gui.c
1 /*
2  * Copyright (C) 1998 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file gui.c Curses-based interface for paraslash. */
8
9 #include <regex.h>
10 #include <signal.h>
11 #include <sys/types.h>
12 #include <curses.h>
13 #include <locale.h>
14 #include <sys/time.h>
15
16 #include "gui.cmdline.h"
17 #include "para.h"
18 #include "gui.h"
19 #include "string.h"
20 #include "ringbuffer.h"
21 #include "fd.h"
22 #include "error.h"
23 #include "list.h"
24 #include "sched.h"
25 #include "signal.h"
26 #include "ggo.h"
27 #include "version.h"
28
29 /** define the array of error lists needed by para_gui */
30 INIT_GUI_ERRLISTS;
31 static char *stat_content[NUM_STAT_ITEMS];
32
33 static struct gui_window {
34         WINDOW *win;
35         bool needs_update;
36 } top, bot, sb, in, sep;
37
38 /** How many lines of output to remember. */
39 #define RINGBUFFER_SIZE 512
40
41 struct rb_entry {
42         char *msg;
43         size_t len;
44         int color;
45 };
46 static struct ringbuffer *bot_win_rb;
47
48 static unsigned scroll_position;
49
50 static pid_t exec_pid;
51
52 static int exec_fds[2] = {-1, -1};
53 static struct gui_args_info conf;
54 static int loglevel;
55
56 /** Type of the process currently being executed. */
57 enum exec_status {
58         EXEC_IDLE, /**< No process running. */
59         EXEC_DCMD, /**< para or display process running. */
60         EXEC_XCMD, /**< External process running. */
61 };
62
63 /**
64  * Codes for various colors.
65  *
66  * Each status item has its own color pair. The ones defined here start at a
67  * higher number so that they do not overlap with these.
68  */
69 enum gui_color_pair {
70         COLOR_STATUSBAR = NUM_STAT_ITEMS + 1,
71         COLOR_COMMAND,
72         COLOR_OUTPUT,
73         COLOR_MSG,
74         COLOR_ERRMSG,
75         COLOR_SEPARATOR,
76         COLOR_TOP,
77         COLOR_BOT,
78 };
79
80 struct gui_command {
81         const char *key;
82         const char *name;
83         const char *description;
84         void (*handler)(void);
85 };
86
87 static struct gui_theme theme;
88
89 #define GUI_COMMANDS \
90         GUI_COMMAND(help, "?", "print help") \
91         GUI_COMMAND(enlarge_top_win, "+", "enlarge the top window") \
92         GUI_COMMAND(shrink_top_win, "-", "shrink the top window") \
93         GUI_COMMAND(reread_conf, "r", "reread configuration file") \
94         GUI_COMMAND(quit, "q", "exit para_gui") \
95         GUI_COMMAND(refresh, "^L", "redraw the screen") \
96         GUI_COMMAND(next_theme, ".", "switch to next theme") \
97         GUI_COMMAND(prev_theme, ",", "switch to previous theme") \
98         GUI_COMMAND(ll_incr, ">", "increase loglevel (decreases verbosity)") \
99         GUI_COMMAND(ll_decr, "<", "decrease loglevel (increases verbosity)") \
100         GUI_COMMAND(version, "V", "show the para_gui version") \
101         GUI_COMMAND(scroll_up, "<up>", "scroll up one line") \
102         GUI_COMMAND(scroll_down, "<down>", "scroll_down") \
103         GUI_COMMAND(page_up, "<ppage>", "scroll up one page") \
104         GUI_COMMAND(page_down, "<npage>", "scroll down one page") \
105         GUI_COMMAND(scroll_top, "<home>", "scroll to top of buffer") \
106         GUI_COMMAND(cancel_scroll, "<end>", "deactivate scroll mode") \
107
108 /* declare command handlers */
109 #define GUI_COMMAND(_c, _k, _d) \
110         static void com_ ## _c(void);
111 GUI_COMMANDS
112
113 #undef GUI_COMMAND
114
115 /* define command array */
116 #define GUI_COMMAND(_c, _k, _d) \
117         { \
118                 .key = _k, \
119                 .name = #_c, \
120                 .description = _d, \
121                 .handler = com_ ## _c \
122         },
123
124 static struct gui_command command_list[] = {GUI_COMMANDS {.name = NULL}};
125
126 struct input_task {
127         struct task *task;
128 };
129
130 struct status_task {
131         struct task *task;
132         pid_t pid;
133         char *buf;
134         int bufsize, loaded;
135         struct timeval next_exec;
136         int fd;
137 };
138
139 /** Stdout/stderr of the executing process is read in chunks of this size. */
140 #define COMMAND_BUF_SIZE 32768
141
142 struct exec_task {
143         struct task *task;
144         char command_buf[2][COMMAND_BUF_SIZE]; /* stdout/stderr of command */
145         int cbo[2]; /* command buf offsets */
146         unsigned flags[2]; /* passed to for_each_line() */
147 };
148
149 static int find_cmd_byname(char *name)
150 {
151         int i;
152
153         for (i = 0; command_list[i].handler; i++)
154                 if (!strcmp(command_list[i].name, name))
155                         return i;
156         return -1;
157 }
158
159 /*
160  * Even though ncurses provides getmaxx and getmaxy, these functions/macros are
161  * not described in the XSI Curses standard.
162  */
163 static int get_num_lines(struct gui_window *w)
164 {
165         int lines;
166         __a_unused int cols; /* avoid "set but not used" warnings */
167
168         getmaxyx(w->win, lines, cols);
169         return lines;
170 }
171
172 static int get_num_cols(struct gui_window *w)
173 {
174         __a_unused int lines; /* avoid "set but not used" warnings */
175         int cols;
176
177         getmaxyx(w->win, lines, cols);
178         return cols;
179 }
180
181 /** Number of lines of the window are occupied by an output line. */
182 #define NUM_LINES(len) (1 + (len) / get_num_cols(&bot))
183
184 /* isendwin() returns false before initscr() was called */
185 static bool curses_active(void)
186 {
187         return top.win && !isendwin();
188 }
189
190 /* taken from mutt */
191 static char *km_keyname(int c)
192 {
193         static char buf[10];
194
195         if (c == KEY_UP) {
196                 sprintf(buf, "<up>");
197                 return buf;
198         }
199         if (c == KEY_DOWN) {
200                 sprintf(buf, "<down>");
201                 return buf;
202         }
203         if (c == KEY_LEFT) {
204                 sprintf(buf, "<left>");
205                 return buf;
206         }
207         if (c == KEY_RIGHT) {
208                 sprintf(buf, "<right>");
209                 return buf;
210         }
211         if (c == KEY_NPAGE) {
212                 sprintf(buf, "<npage>");
213                 return buf;
214         }
215         if (c == KEY_PPAGE) {
216                 sprintf(buf, "<ppage>");
217                 return buf;
218         }
219         if (c == KEY_HOME) {
220                 sprintf(buf, "<home>");
221                 return buf;
222         }
223         if (c == KEY_END) {
224                 sprintf(buf, "<end>");
225                 return buf;
226         }
227         if (c < 256 && c > -128 && iscntrl((unsigned char) c)) {
228                 if (c < 0)
229                         c += 256;
230                 if (c < 128) {
231                         buf[0] = '^';
232                         buf[1] = (c + '@') & 0x7f;
233                         buf[2] = 0;
234                 } else
235                         snprintf(buf, sizeof(buf), "\\%d%d%d", c >> 6,
236                                 (c >> 3) & 7, c & 7);
237         } else if (c >= KEY_F0 && c < KEY_F(256))
238                 sprintf(buf, "<F%d>", c - KEY_F0);
239         else if (isprint(c))
240                 snprintf(buf, sizeof(buf), "%c", (unsigned char) c);
241         else
242                 snprintf(buf, sizeof(buf), "\\x%hx", (unsigned short) c);
243         return buf;
244 }
245
246 /* Print given number of spaces to curses window. */
247 static void add_spaces(WINDOW* win, unsigned int num)
248 {
249         const char space[] = "                                ";
250         const unsigned sz = sizeof(space) - 1; /* number of spaces */
251
252         while (num >= sz)  {
253                 waddstr(win, space);
254                 num -= sz;
255         }
256         if (num > 0) {
257                 assert(num < sz);
258                 waddstr(win, space + sz - num);
259         }
260 }
261
262 /*
263  * print aligned string to curses window. This function always prints
264  * exactly len chars.
265  */
266 static int align_str(WINDOW* win, const char *str, unsigned int len,
267                 unsigned int align)
268 {
269         int ret, num; /* of spaces */
270         size_t width;
271         char *sstr; /* sanitized string */
272
273         if (!win || !str)
274                 return 0;
275         ret = sanitize_str(str, len, &sstr, &width);
276         if (ret < 0) {
277                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
278                 width = 0;
279                 sstr = para_strdup(NULL);
280         }
281         assert(width <= len);
282         num = len - width;
283         if (align == LEFT) {
284                 waddstr(win, sstr);
285                 add_spaces(win, num);
286         } else if (align == RIGHT) {
287                 add_spaces(win, num);
288                 waddstr(win, sstr);
289         } else {
290                 add_spaces(win, num / 2);
291                 waddstr(win, sstr);
292                 add_spaces(win, num - num / 2);
293         }
294         free(sstr);
295         return 1;
296 }
297
298 static void refresh_window(struct gui_window *gw)
299 {
300         gw->needs_update = true;
301 }
302
303 static bool window_update_needed(void)
304 {
305         return top.needs_update || bot.needs_update || sb.needs_update ||
306                 in.needs_update || sep.needs_update;
307 }
308
309 __printf_2_3 static void print_in_bar(int color, const char *fmt,...)
310 {
311         char *msg;
312         va_list ap;
313
314         if (!curses_active())
315                 return;
316         wattron(in.win, COLOR_PAIR(color));
317         va_start(ap, fmt);
318         xvasprintf(&msg, fmt, ap);
319         va_end(ap);
320         wmove(in.win, 0, 0);
321         align_str(in.win, msg, get_num_cols(&in), LEFT);
322         free(msg);
323         refresh_window(&in);
324 }
325
326 static void print_status_bar(void)
327 {
328         char *tmp;
329
330         tmp = para_strdup("para_gui " PACKAGE_VERSION " (hit ? for help)");
331         wmove(sb.win, 0, 0);
332         align_str(sb.win, tmp, get_num_cols(&sb), CENTER);
333         free(tmp);
334 }
335
336 /*
337  * get the number of the oldest rbe that is (partially) visible. On return,
338  * lines contains the sum of the number of lines of all visible entries. If the
339  * first one is only partially visible, lines is greater than bot.lines.
340  */
341 static int first_visible_rbe(unsigned *lines)
342 {
343         int i, bot_lines = get_num_lines(&bot);
344
345         *lines = 0;
346         for (i = scroll_position; i < RINGBUFFER_SIZE; i++) {
347                 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
348                 int rbe_lines;
349                 if (!rbe)
350                         return i - 1;
351                 rbe_lines = NUM_LINES(rbe->len);
352                 if (rbe_lines > bot_lines)
353                         return -1;
354                 *lines += rbe_lines;
355                 if (*lines >= bot_lines)
356                         return i;
357         }
358         return RINGBUFFER_SIZE - 1;
359 }
360
361 /*
362 returns number of first visible rbe, *lines is the number of lines drawn.
363  */
364 static int draw_top_rbe(unsigned *lines)
365 {
366         int bot_cols, bot_lines, ret, fvr = first_visible_rbe(lines);
367         struct rb_entry *rbe;
368         size_t bytes_to_skip, cells_to_skip, width;
369
370         if (fvr < 0)
371                 return -1;
372         wmove(bot.win, 0, 0);
373         rbe = ringbuffer_get(bot_win_rb, fvr);
374         if (!rbe)
375                 return -1;
376         getmaxyx(bot.win, bot_lines, bot_cols);
377         if (*lines > bot_lines) {
378                 /* rbe is partially visible multi-line */
379                 cells_to_skip = (*lines - bot_lines) * bot_cols;
380                 ret = skip_cells(rbe->msg, cells_to_skip, &bytes_to_skip);
381                 if (ret < 0)
382                         return ret;
383                 ret = strwidth(rbe->msg + bytes_to_skip, &width);
384                 if (ret < 0)
385                         return ret;
386         } else {
387                 bytes_to_skip = 0;
388                 width = rbe->len;
389         }
390         wattron(bot.win, COLOR_PAIR(rbe->color));
391         waddstr(bot.win, rbe->msg + bytes_to_skip);
392         *lines = NUM_LINES(width);
393         return fvr;
394 }
395
396 static void redraw_bot_win(void)
397 {
398         unsigned lines;
399         int i, bot_lines = get_num_lines(&bot);
400
401         wmove(bot.win, 0, 0);
402         wclear(bot.win);
403         i = draw_top_rbe(&lines);
404         if (i <= 0)
405                 goto out;
406         while (i > 0 && lines < bot_lines) {
407                 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, --i);
408                 if (!rbe) {
409                         lines++;
410                         waddstr(bot.win, "\n");
411                         continue;
412                 }
413                 lines += NUM_LINES(rbe->len);
414                 wattron(bot.win, COLOR_PAIR(rbe->color));
415                 waddstr(bot.win, "\n");
416                 waddstr(bot.win, rbe->msg);
417         }
418 out:
419         refresh_window(&bot);
420 }
421
422 static void rb_add_entry(int color, char *msg)
423 {
424         struct rb_entry *old, *new;
425         int x, y;
426         size_t len;
427
428         if (strwidth(msg, &len) < 0)
429                 return;
430         new = para_malloc(sizeof(struct rb_entry));
431         new->color = color;
432         new->len = len;
433         new->msg = msg;
434         old = ringbuffer_add(bot_win_rb, new);
435         if (old) {
436                 free(old->msg);
437                 free(old);
438         }
439         if (scroll_position) {
440                 /* discard current scrolling, like xterm does */
441                 scroll_position = 0;
442                 redraw_bot_win();
443                 return;
444         }
445         wattron(bot.win, COLOR_PAIR(color));
446         getyx(bot.win, y, x);
447         if (y || x)
448                 waddstr(bot.win, "\n");
449         waddstr(bot.win, msg);
450 }
451
452 /*
453  * print formated output to bot win and refresh
454  */
455 __printf_2_3 static void outputf(int color, const char* fmt,...)
456 {
457         char *msg;
458         va_list ap;
459
460         if (!curses_active())
461                 return;
462         va_start(ap, fmt);
463         xvasprintf(&msg, fmt, ap);
464         va_end(ap);
465         rb_add_entry(color, msg);
466         refresh_window(&bot);
467 }
468
469 static int add_output_line(char *line, void *data)
470 {
471         int color = *(int *)data? COLOR_ERRMSG : COLOR_OUTPUT;
472
473         if (!curses_active())
474                 return 1;
475         rb_add_entry(color, para_strdup(line));
476         return 1;
477 }
478
479 static __printf_2_3 void curses_log(int ll, const char *fmt,...)
480 {
481         va_list ap;
482
483         if (ll < loglevel)
484                 return;
485         va_start(ap, fmt);
486         if (curses_active()) {
487                 int color = ll <= LL_NOTICE? COLOR_MSG : COLOR_ERRMSG;
488                 char *msg;
489                 unsigned bytes = xvasprintf(&msg, fmt, ap);
490                 if (bytes > 0 && msg[bytes - 1] == '\n')
491                         msg[bytes - 1] = '\0'; /* cut trailing newline */
492                 rb_add_entry(color, msg);
493                 refresh_window(&bot);
494         } else if (exec_pid <= 0) /* no external command running */
495                 vfprintf(stderr, fmt, ap);
496         va_end(ap);
497 }
498 /** The log function of para_gui, always set to curses_log(). */
499 __printf_2_3 void (*para_log)(int, const char*, ...) = curses_log;
500
501 static void shutdown_curses(void)
502 {
503         def_prog_mode();
504         endwin();
505 }
506
507 /* disable curses, print a message, kill running processes and exit */
508 __noreturn __printf_2_3 static void die(int exit_code, const char* fmt, ...)
509 {
510         va_list argp;
511
512         shutdown_curses();
513         va_start(argp, fmt);
514         vfprintf(stderr, fmt, argp);
515         va_end(argp);
516         /* kill every process in the process group and exit */
517         para_sigaction(SIGTERM, SIG_IGN);
518         kill(0, SIGTERM);
519         exit(exit_code);
520 }
521
522 /*
523  * Print stat item #i to curses window
524  */
525 static void print_stat_item(int i)
526 {
527         char *tmp;
528         struct stat_item_data d = theme.data[i];
529         char *c = stat_content[i];
530         int top_lines = get_num_lines(&top);
531
532         if (!curses_active() || !d.len || !c)
533                 return;
534         tmp = make_message("%s%s%s", d.prefix, c, d.postfix);
535         wmove(top.win, d.y * top_lines / 100, d.x * COLS / 100);
536         wattron(top.win, COLOR_PAIR(i + 1));
537         align_str(top.win, tmp, d.len * COLS / 100, d.align);
538         free(tmp);
539         refresh_window(&top);
540 }
541
542 static int update_item(int item_num, char *buf)
543 {
544         char **c = stat_content + item_num;
545
546         free(*c);
547         if (buf && buf[0])
548                 goto dup;
549         switch (item_num) {
550         case SI_ARTIST:
551                 *c = para_strdup("(artist tag not set)");
552                 goto print;
553         case SI_TITLE:
554                 *c = para_strdup("(title tag not set)");
555                 goto print;
556         case SI_YEAR:
557                 *c = para_strdup("????");
558                 goto print;
559         case SI_ALBUM:
560                 *c = para_strdup("(album tag not set)");
561                 goto print;
562         case SI_COMMENT:
563                 *c = para_strdup("(comment tag not set)");
564                 goto print;
565         }
566 dup:
567         *c = para_strdup(buf);
568 print:
569         print_stat_item(item_num);
570         return 1;
571 }
572
573 static void print_all_items(void)
574 {
575         int i;
576
577         if (!curses_active())
578                 return;
579         FOR_EACH_STATUS_ITEM(i)
580                 print_stat_item(i);
581 }
582
583 static void clear_all_items(void)
584 {
585         int i;
586
587         FOR_EACH_STATUS_ITEM(i) {
588                 free(stat_content[i]);
589                 stat_content[i] = para_strdup("");
590         }
591 }
592
593 static void status_pre_select(struct sched *s, void *context)
594 {
595         struct status_task *st = context;
596
597         if (st->fd >= 0)
598                 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
599         if (task_get_notification(st->task) < 0)
600                 return sched_min_delay(s);
601         if (st->fd < 0)
602                 sched_request_barrier_or_min_delay(&st->next_exec, s);
603 }
604
605 static int status_post_select(struct sched *s, void *context)
606 {
607         struct status_task *st = context;
608         size_t sz;
609         int ret, ret2;
610
611         ret = task_get_notification(st->task);
612         if (ret == -E_GUI_SIGCHLD && st->pid > 0) {
613                 int exit_status;
614                 if (waitpid(st->pid, &exit_status, WNOHANG) == st->pid) {
615                         st->pid = 0;
616                         PARA_ERROR_LOG("stat command exit status: %d",
617                                 exit_status);
618                 }
619         }
620         if (st->fd < 0) {
621                 int fds[3] = {0, 1, 0};
622                 if (st->pid > 0)
623                         return 0;
624                 /* Avoid busy loop */
625                 if (tv_diff(&st->next_exec, now, NULL) > 0)
626                         return 0;
627                 st->next_exec.tv_sec = now->tv_sec + 2;
628                 ret = para_exec_cmdline_pid(&st->pid, conf.stat_cmd_arg, fds);
629                 if (ret < 0)
630                         return 0;
631                 ret = mark_fd_nonblocking(fds[1]);
632                 if (ret < 0) {
633                         close(fds[1]);
634                         return 0;
635                 }
636                 st->fd = fds[1];
637                 return 0;
638         }
639
640         if (st->loaded >= st->bufsize) {
641                 if (st->bufsize > 1000 * 1000) {
642                         st->loaded = 0;
643                         return 0;
644                 }
645                 st->bufsize += st->bufsize + 1000;
646                 st->buf = para_realloc(st->buf, st->bufsize);
647         }
648         assert(st->loaded < st->bufsize);
649         ret = read_nonblock(st->fd, st->buf + st->loaded,
650                 st->bufsize - st->loaded, &s->rfds, &sz);
651         st->loaded += sz;
652         ret2 = for_each_stat_item(st->buf, st->loaded, update_item);
653         if (ret < 0 || ret2 < 0) {
654                 st->loaded = 0;
655                 PARA_NOTICE_LOG("closing stat pipe: %s\n",
656                         para_strerror(ret < 0? -ret : -ret2));
657                 close(st->fd);
658                 st->fd = -1;
659                 clear_all_items();
660                 free(stat_content[SI_BASENAME]);
661                 stat_content[SI_BASENAME] =
662                         para_strdup("stat command terminated!?");
663                 print_all_items();
664                 return 0;
665         }
666         sz = ret2; /* what is left */
667         if (sz > 0 && sz < st->loaded)
668                 memmove(st->buf, st->buf + st->loaded - sz, sz);
669         st->loaded = sz;
670         return 0;
671 }
672
673 /*
674  * init all windows
675  */
676 static void init_wins(int top_lines)
677 {
678         int top_y = 0, bot_y = top_lines + 1, sb_y = LINES - 2,
679                 in_y = LINES - 1, sep_y = top_lines;
680         int bot_lines = LINES - top_lines - 3, sb_lines = 1, in_lines = 1,
681                 sep_lines = 1;
682
683         assume_default_colors(theme.dflt.fg, theme.dflt.bg);
684         if (top.win) {
685                 wresize(top.win, top_lines, COLS);
686                 mvwin(top.win, top_y, 0);
687
688                 wresize(sb.win, sb_lines, COLS);
689                 mvwin(sb.win, sb_y, 0);
690
691                 wresize(sep.win, sep_lines, COLS);
692                 mvwin(sep.win, sep_y, 0);
693
694                 wresize(bot.win, bot_lines, COLS);
695                 mvwin(bot.win, bot_y, 0);
696
697                 wresize(in.win, in_lines, COLS);
698                 mvwin(in.win, in_y, 0);
699         } else {
700                 sep.win = newwin(sep_lines, COLS, sep_y, 0);
701                 top.win = newwin(top_lines, COLS, top_y, 0);
702                 bot.win = newwin(bot_lines, COLS, bot_y, 0);
703                 sb.win = newwin(sb_lines, COLS, sb_y, 0);
704                 in.win = newwin(in_lines, COLS, in_y, 0);
705                 if (!top.win || !bot.win || !sb.win || !in.win || !sep.win)
706                         die(EXIT_FAILURE, "Error: Cannot create curses windows\n");
707                 wclear(bot.win);
708                 wclear(sb.win);
709                 wclear(in.win);
710                 scrollok(bot.win, 1);
711                 wattron(sb.win, COLOR_PAIR(COLOR_STATUSBAR));
712                 wattron(sep.win, COLOR_PAIR(COLOR_SEPARATOR));
713                 wattron(bot.win, COLOR_PAIR(COLOR_BOT));
714                 wattron(top.win, COLOR_PAIR(COLOR_TOP));
715                 nodelay(top.win, 1);
716                 nodelay(bot.win, 1);
717                 nodelay(sb.win, 1);
718                 nodelay(in.win, 0);
719
720                 keypad(top.win, 1);
721                 keypad(bot.win, 1);
722                 keypad(sb.win, 1);
723                 keypad(in.win, 1);
724         }
725         wmove(sep.win, 0, 0);
726         whline(sep.win, theme.sep_char, COLS);
727         wclear(top.win);
728         print_all_items();
729         //wclear(bot.win);
730         wnoutrefresh(top.win);
731         wnoutrefresh(bot.win);
732         print_status_bar();
733         wnoutrefresh(sb.win);
734         wnoutrefresh(in.win);
735         wnoutrefresh(sep.win);
736         doupdate();
737 }
738
739 static void init_pair_or_die(short pair, short f, short b)
740 {
741         if (init_pair(pair, f, b) == ERR)
742                 die(EXIT_FAILURE, "fatal: init_pair() failed\n");
743 }
744
745 static void init_colors_or_die(void)
746 {
747         int i;
748
749         if (!has_colors())
750                 die(EXIT_FAILURE, "fatal: No color term\n");
751         if (start_color() == ERR)
752                 die(EXIT_FAILURE, "fatal: failed to start colors\n");
753         FOR_EACH_STATUS_ITEM(i)
754                 if (theme.data[i].len)
755                         init_pair_or_die(i + 1, theme.data[i].color.fg,
756                                 theme.data[i].color.bg);
757         init_pair_or_die(COLOR_STATUSBAR, theme.sb.fg, theme.sb.bg);
758         init_pair_or_die(COLOR_COMMAND, theme.cmd.fg, theme.cmd.bg);
759         init_pair_or_die(COLOR_OUTPUT, theme.output.fg, theme.output.bg);
760         init_pair_or_die(COLOR_MSG, theme.msg.fg, theme.msg.bg);
761         init_pair_or_die(COLOR_ERRMSG, theme.err_msg.fg, theme.err_msg.bg);
762         init_pair_or_die(COLOR_SEPARATOR, theme.sep.fg, theme.sep.bg);
763         init_pair_or_die(COLOR_TOP, theme.dflt.fg, theme.dflt.bg);
764         init_pair_or_die(COLOR_BOT, theme.dflt.fg, theme.dflt.bg);
765 }
766
767 /* (Re-)initialize the curses library. */
768 static void init_curses(void)
769 {
770         if (curses_active())
771                 return;
772         if (refresh() == ERR) /* refresh is really needed */
773                 die(EXIT_FAILURE, "refresh() failed\n");
774         if (LINES < theme.lines_min || COLS < theme.cols_min)
775                 die(EXIT_FAILURE, "Terminal (%dx%d) too small"
776                         " (need at least %dx%d)\n", COLS, LINES,
777                         theme.cols_min, theme.lines_min);
778         curs_set(0); /* make cursor invisible, ignore errors */
779         nonl(); /* do not NL->CR/NL on output, always returns OK */
780         /* don't echo input */
781         if (noecho() == ERR)
782                 die(EXIT_FAILURE, "fatal: noecho() failed\n");
783         /* take input chars one at a time, no wait for \n */
784         if (cbreak() == ERR)
785                 die(EXIT_FAILURE, "fatal: cbreak() failed\n");
786         init_colors_or_die();
787         clear(); /* ignore non-fatal errors */
788         init_wins(theme.top_lines_default);
789         // noecho(); /* don't echo input */
790 }
791
792 /*
793  * This sucker modifies its first argument. *handler and *arg are
794  * pointers to 0-terminated strings (inside line). Crap.
795  */
796 static int split_key_map(char *line, char **handler, char **arg)
797 {
798         if (!(*handler = strchr(line + 1, ':')))
799                 goto err_out;
800         **handler = '\0';
801         (*handler)++;
802         if (!(*arg = strchr(*handler, ':')))
803                 goto err_out;
804         **arg = '\0';
805         (*arg)++;
806         return 1;
807 err_out:
808         return 0;
809 }
810
811 static void check_key_map_args_or_die(void)
812 {
813         int i;
814         char *tmp = NULL;
815
816         for (i = 0; i < conf.key_map_given; ++i) {
817                 char *handler, *arg;
818
819                 free(tmp);
820                 tmp = para_strdup(conf.key_map_arg[i]);
821                 if (!split_key_map(tmp, &handler, &arg))
822                         break;
823                 if (strlen(handler) != 1)
824                         break;
825                 if (*handler != 'x' && *handler != 'd' && *handler != 'i'
826                                 && *handler != 'p')
827                         break;
828                 if (*handler != 'i')
829                         continue;
830                 if (find_cmd_byname(arg) < 0)
831                         break;
832         }
833         if (i != conf.key_map_given)
834                 die(EXIT_FAILURE, "invalid key map: %s\n", conf.key_map_arg[i]);
835         free(tmp);
836 }
837
838 static void parse_config_file_or_die(bool override)
839 {
840         bool err;
841         char *config_file;
842         struct gui_cmdline_parser_params params = {
843                 .override = override,
844                 .initialize = 0,
845                 .check_required = !override,
846                 .check_ambiguity = 0,
847                 .print_errors = 1,
848         };
849
850         if (conf.config_file_given)
851                 config_file = para_strdup(conf.config_file_arg);
852         else {
853                 char *home = para_homedir();
854                 config_file = make_message("%s/.paraslash/gui.conf", home);
855                 free(home);
856         }
857         if (!file_exists(config_file)) {
858                 if (!conf.config_file_given)
859                         err = false;
860                 else {
861                         PARA_EMERG_LOG("config file %s does not exist\n",
862                                 config_file);
863                         err = true;
864                 }
865                 goto out;
866         }
867         /*
868          * When the gengetopt config file parser is called more than once, any
869          * key map arguments found in the config file are _appended_ to the old
870          * values, even though we turn on ->override. We want the new arguments
871          * to replace the old ones, so we must empty the key_map_arg array
872          * first. Unfortunately, this also clears any key map arguments given
873          * at the command line.
874          */
875         if (override) {
876                 int i;
877                 for (i = 0; i < conf.key_map_given; i++) {
878                         free(conf.key_map_arg[i]);
879                         conf.key_map_arg[i] = NULL;
880                 }
881                 conf.key_map_given = 0;
882         }
883
884         gui_cmdline_parser_config_file(config_file, &conf, &params);
885         loglevel = get_loglevel_by_name(conf.loglevel_arg);
886         check_key_map_args_or_die();
887         err = false;
888 out:
889         free(config_file);
890         if (err)
891                 exit(EXIT_FAILURE);
892         theme_init(conf.theme_arg, &theme);
893 }
894
895 /* reread configuration, terminate on errors */
896 static void reread_conf(void)
897 {
898         /*
899          * gengetopt might print to stderr and exit on errors. So we have to
900          * shutdown curses first.
901          */
902         shutdown_curses();
903         parse_config_file_or_die(true /* override */);
904         init_curses();
905         print_in_bar(COLOR_MSG, "config file reloaded\n");
906 }
907
908 /*
909  * React to various signal-related events
910  */
911 static int signal_post_select(struct sched *s, __a_unused void *context)
912 {
913         int ret = para_next_signal(&s->rfds);
914
915         if (ret <= 0)
916                 return 0;
917         switch (ret) {
918         case SIGTERM:
919                 die(EXIT_FAILURE, "only the good die young (caught SIGTERM)\n");
920                 return 1;
921         case SIGINT:
922                 PARA_WARNING_LOG("caught SIGINT, reset\n");
923                 /* Nothing to do. SIGINT killed our child which gets noticed
924                  * by do_select and resets everything.
925                  */
926                 return 1;
927         case SIGUSR1:
928                 PARA_NOTICE_LOG("got SIGUSR1, rereading configuration\n");
929                 reread_conf();
930                 return 1;
931         case SIGCHLD:
932                 task_notify_all(s, E_GUI_SIGCHLD);
933                 return 1;
934         }
935         return 1;
936 }
937
938 static enum exec_status exec_status(void)
939 {
940         if (exec_fds[0] >= 0 || exec_fds[1] >= 0)
941                 return EXEC_DCMD;
942         if (exec_pid > 0)
943                 return EXEC_XCMD;
944         return EXEC_IDLE;
945 }
946
947 static void exec_pre_select(struct sched *s, void *context)
948 {
949         struct exec_task *et = context;
950         if (exec_fds[0] >= 0)
951                 para_fd_set(exec_fds[0], &s->rfds, &s->max_fileno);
952         if (exec_fds[1] >= 0)
953                 para_fd_set(exec_fds[1], &s->rfds, &s->max_fileno);
954         if (task_get_notification(et->task) < 0)
955                 sched_min_delay(s);
956 }
957
958 static int exec_post_select(struct sched *s, void *context)
959 {
960         struct exec_task *ct = context;
961         int i, ret;
962
963         ret = task_get_notification(ct->task);
964         if (ret == -E_GUI_SIGCHLD && exec_pid > 0) {
965                 int exit_status;
966                 if (waitpid(exec_pid, &exit_status, WNOHANG) == exec_pid) {
967                         exec_pid = 0;
968                         init_curses();
969                         PARA_INFO_LOG("command exit status: %d", exit_status);
970                         print_in_bar(COLOR_MSG, " ");
971                 }
972         }
973         for (i = 0; i < 2; i++) {
974                 size_t sz;
975                 if (exec_fds[i] < 0)
976                         continue;
977                 ret = read_nonblock(exec_fds[i],
978                         ct->command_buf[i] + ct->cbo[i],
979                         COMMAND_BUF_SIZE - 1 - ct->cbo[i], &s->rfds, &sz);
980                 ct->cbo[i] += sz;
981                 sz = ct->cbo[i];
982                 ct->cbo[i] = for_each_line(ct->flags[i], ct->command_buf[i],
983                         ct->cbo[i], add_output_line, &i);
984                 if (sz != ct->cbo[i]) { /* at least one line found */
985                         refresh_window(&bot);
986                         ct->flags[i] = 0;
987                 }
988                 if (ret < 0 || exec_pid == 0) {
989                         if (ret < 0)
990                                 PARA_NOTICE_LOG("closing command fd %d: %s",
991                                         i, para_strerror(-ret));
992                         close(exec_fds[i]);
993                         exec_fds[i] = -1;
994                         ct->flags[i] = 0;
995                         ct->cbo[i] = 0;
996                         if (exec_fds[!i] < 0) /* both fds closed */
997                                 return 1;
998                 }
999                 if (ct->cbo[i] == COMMAND_BUF_SIZE - 1) {
1000                         PARA_NOTICE_LOG("discarding overlong line");
1001                         ct->cbo[i] = 0;
1002                         ct->flags[i] = FELF_DISCARD_FIRST;
1003                 }
1004         }
1005         return 0;
1006 }
1007
1008 static void input_pre_select(struct sched *s, __a_unused void *context)
1009 {
1010         if (exec_status() != EXEC_XCMD)
1011                 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1012         if (window_update_needed())
1013                 sched_min_delay(s);
1014 }
1015
1016 /* read from command pipe and print data to bot window */
1017 static void exec_and_display(const char *file_and_args)
1018 {
1019         int ret, fds[3] = {0, 1, 1};
1020
1021         outputf(COLOR_COMMAND, "%s", file_and_args);
1022         ret = para_exec_cmdline_pid(&exec_pid, file_and_args, fds);
1023         if (ret < 0)
1024                 return;
1025         ret = mark_fd_nonblocking(fds[1]);
1026         if (ret < 0)
1027                 goto fail;
1028         ret = mark_fd_nonblocking(fds[2]);
1029         if (ret < 0)
1030                 goto fail;
1031         exec_fds[0] = fds[1];
1032         exec_fds[1] = fds[2];
1033         print_in_bar(COLOR_MSG, "hit any key to abort\n");
1034         return;
1035 fail:
1036         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1037         close(exec_fds[0]);
1038         close(exec_fds[1]);
1039 }
1040
1041 static void exec_para(const char *args)
1042 {
1043         char *file_and_args;
1044
1045         file_and_args = make_message(BINDIR "/para_client -- %s", args);
1046         exec_and_display(file_and_args);
1047         free(file_and_args);
1048 }
1049
1050 /*
1051  * shutdown curses and stat pipe before executing external commands
1052  */
1053 static void exec_external(char *file_and_args)
1054 {
1055         int fds[3] = {-1, -1, -1};
1056
1057         if (exec_pid)
1058                 return;
1059         shutdown_curses();
1060         para_exec_cmdline_pid(&exec_pid, file_and_args, fds);
1061 }
1062
1063 static void handle_command(int c)
1064 {
1065         int i;
1066
1067         /* first check user-defined key bindings */
1068         for (i = 0; i < conf.key_map_given; ++i) {
1069                 char *tmp, *handler, *arg;
1070
1071                 tmp = para_strdup(conf.key_map_arg[i]);
1072                 if (!split_key_map(tmp, &handler, &arg)) {
1073                         free(tmp);
1074                         return;
1075                 }
1076                 if (strcmp(tmp, km_keyname(c))) {
1077                         free(tmp);
1078                         continue;
1079                 }
1080                 if (*handler == 'd')
1081                         exec_and_display(arg);
1082                 else if (*handler == 'x')
1083                         exec_external(arg);
1084                 else if (*handler == 'p')
1085                         exec_para(arg);
1086                 else if (*handler == 'i') {
1087                         int num = find_cmd_byname(arg);
1088                         if (num >= 0)
1089                                 command_list[num].handler();
1090                 }
1091                 free(tmp);
1092                 return;
1093         }
1094         /* not found, check internal key bindings */
1095         for (i = 0; command_list[i].handler; i++) {
1096                 if (!strcmp(km_keyname(c), command_list[i].key)) {
1097                         command_list[i].handler();
1098                         return;
1099                 }
1100         }
1101         print_in_bar(COLOR_ERRMSG, "key '%s' is not bound, press ? for help",
1102                 km_keyname(c));
1103 }
1104
1105 static int input_post_select(__a_unused struct sched *s, __a_unused void *context)
1106 {
1107         int ret;
1108         enum exec_status exs = exec_status();
1109
1110         if (exs == EXEC_XCMD)
1111                 return 0;
1112         if (window_update_needed()) {
1113                 if (top.needs_update)
1114                         assert(wnoutrefresh(top.win) == OK);
1115                 if (bot.needs_update)
1116                         assert(wnoutrefresh(bot.win) == OK);
1117                 if (sep.needs_update)
1118                         assert(wnoutrefresh(sep.win) == OK);
1119                 if (sb.needs_update)
1120                         assert(wnoutrefresh(sb.win) == OK);
1121                 if (in.needs_update)
1122                         assert(wnoutrefresh(in.win) == OK);
1123                 doupdate();
1124                 top.needs_update = bot.needs_update = sb.needs_update =
1125                         in.needs_update = sep.needs_update = false;
1126         }
1127         ret = wgetch(top.win);
1128         if (ret == ERR)
1129                 return 0;
1130         if (ret == KEY_RESIZE) {
1131                 if (curses_active()) {
1132                         shutdown_curses();
1133                         init_curses();
1134                         redraw_bot_win();
1135                 }
1136                 return 0;
1137         }
1138         if (exs == EXEC_IDLE)
1139                 handle_command(ret);
1140         else if (exec_pid > 0)
1141                 kill(exec_pid, SIGTERM);
1142         return 0;
1143 }
1144
1145 static void print_scroll_msg(void)
1146 {
1147         unsigned lines_total, filled = ringbuffer_filled(bot_win_rb);
1148         int first_rbe = first_visible_rbe(&lines_total);
1149
1150         print_in_bar(COLOR_MSG, "scrolled view: %d-%d/%d\n", filled - first_rbe,
1151                 filled - scroll_position, ringbuffer_filled(bot_win_rb));
1152 }
1153
1154 static void com_scroll_top(void)
1155 {
1156         int i = RINGBUFFER_SIZE - 1, bot_lines = get_num_lines(&bot);
1157         unsigned lines = 0;
1158
1159         while (i > 0 && !ringbuffer_get(bot_win_rb, i))
1160                 i--;
1161         /* i is oldest entry */
1162         for (; lines < bot_lines && i >= 0; i--) {
1163                 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
1164                 if (!rbe)
1165                         break;
1166                 lines += NUM_LINES(rbe->len);
1167         }
1168         i++;
1169         if (lines > 0 && scroll_position != i) {
1170                 scroll_position = i;
1171                 redraw_bot_win();
1172                 print_scroll_msg();
1173                 return;
1174         }
1175         print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1176 }
1177
1178 static void com_cancel_scroll(void)
1179 {
1180
1181         if (scroll_position == 0) {
1182                 print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1183                 return;
1184         }
1185         scroll_position = 0;
1186         redraw_bot_win();
1187 }
1188
1189 static void com_page_down(void)
1190 {
1191         unsigned lines = 0;
1192         int i = scroll_position, bot_lines = get_num_lines(&bot);
1193
1194         while (lines < bot_lines && --i > 0) {
1195                 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
1196                 if (!rbe)
1197                         break;
1198                 lines += NUM_LINES(rbe->len);
1199         }
1200         if (lines) {
1201                 scroll_position = i;
1202                 redraw_bot_win();
1203                 print_scroll_msg();
1204                 return;
1205         }
1206         print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1207 }
1208
1209 static void com_page_up(void)
1210 {
1211         unsigned lines;
1212         int fvr = first_visible_rbe(&lines), bot_lines = get_num_lines(&bot);
1213
1214         if (fvr < 0 || fvr + 1 >= ringbuffer_filled(bot_win_rb)) {
1215                 print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1216                 return;
1217         }
1218         scroll_position = fvr + 1;
1219         for (; scroll_position > 0; scroll_position--) {
1220                 first_visible_rbe(&lines);
1221                 if (lines == bot_lines)
1222                         break;
1223         }
1224         redraw_bot_win();
1225         print_scroll_msg();
1226 }
1227
1228 static void com_scroll_down(void)
1229 {
1230         struct rb_entry *rbe;
1231         int rbe_lines, bot_lines = get_num_lines(&bot);
1232
1233         if (!scroll_position) {
1234                 print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1235                 return;
1236         }
1237         scroll_position--;
1238         rbe = ringbuffer_get(bot_win_rb, scroll_position);
1239         rbe_lines = NUM_LINES(rbe->len);
1240         wscrl(bot.win, rbe_lines);
1241         wmove(bot.win, bot_lines - rbe_lines, 0);
1242         wattron(bot.win, COLOR_PAIR(rbe->color));
1243         waddstr(bot.win, rbe->msg);
1244         refresh_window(&bot);
1245         print_scroll_msg();
1246 }
1247
1248 static void com_scroll_up(void)
1249 {
1250         struct rb_entry *rbe = NULL;
1251         unsigned lines;
1252         int i, first_rbe, num_scroll;
1253
1254         /* the entry that is going to vanish */
1255         rbe = ringbuffer_get(bot_win_rb, scroll_position);
1256         if (!rbe)
1257                 goto err_out;
1258         num_scroll = NUM_LINES(rbe->len);
1259         first_rbe = first_visible_rbe(&lines);
1260         if (first_rbe < 0 || (first_rbe == ringbuffer_filled(bot_win_rb) - 1))
1261                 goto err_out;
1262         scroll_position++;
1263         wscrl(bot.win, -num_scroll);
1264         i = draw_top_rbe(&lines);
1265         if (i < 0)
1266                 goto err_out;
1267         while (i > 0 && lines < num_scroll) {
1268                 int rbe_lines;
1269                 rbe = ringbuffer_get(bot_win_rb, --i);
1270                 if (!rbe)
1271                         break;
1272                 rbe_lines = NUM_LINES(rbe->len);
1273                 lines += rbe_lines;
1274                 wattron(bot.win, COLOR_PAIR(rbe->color));
1275                 waddstr(bot.win, "\n");
1276                 waddstr(bot.win, rbe->msg);
1277                 if (!i)
1278                         break;
1279                 i--;
1280         }
1281         refresh_window(&bot);
1282         print_scroll_msg();
1283         return;
1284 err_out:
1285         print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1286 }
1287
1288 static void com_ll_decr(void)
1289 {
1290         if (loglevel <= LL_DEBUG) {
1291                 print_in_bar(COLOR_ERRMSG,
1292                         "loglevel already at maximal verbosity\n");
1293                 return;
1294         }
1295         loglevel--;
1296         print_in_bar(COLOR_MSG, "loglevel set to %d\n", loglevel);
1297 }
1298
1299 static void com_ll_incr(void)
1300 {
1301         if (loglevel >= LL_EMERG) {
1302                 print_in_bar(COLOR_ERRMSG,
1303                         "loglevel already at minimal verbosity\n");
1304                 return;
1305         }
1306         loglevel++;
1307         print_in_bar(COLOR_MSG, "loglevel set to %d\n", loglevel);
1308 }
1309
1310 static void com_reread_conf(void)
1311 {
1312         reread_conf();
1313 }
1314
1315 static void com_help(void)
1316 {
1317         int i;
1318
1319         for (i = 0; i < conf.key_map_given; ++i) {
1320                 char *handler, *arg, *tmp = para_strdup(conf.key_map_arg[i]);
1321                 const char *handler_text = "???", *desc = NULL;
1322
1323                 if (!split_key_map(tmp, &handler, &arg)) {
1324                         free(tmp);
1325                         return;
1326                 }
1327                 switch (*handler) {
1328                         case 'i':
1329                                 handler_text = "internal";
1330                                 desc = command_list[find_cmd_byname(arg)].description;
1331                                 break;
1332                         case 'x': handler_text = "external"; break;
1333                         case 'd': handler_text = "display "; break;
1334                         case 'p': handler_text = "para    "; break;
1335                 }
1336                 outputf(COLOR_MSG, "%s\t%s\t%s%s\t%s", tmp, handler_text, arg,
1337                         strlen(arg) < 8? "\t" : "",
1338                         desc? desc : "");
1339                 free(tmp);
1340         }
1341         for (i = 0; command_list[i].handler; i++) {
1342                 struct gui_command gc = command_list[i];
1343
1344                 outputf(COLOR_MSG, "%s\tinternal\t%s\t%s%s", gc.key, gc.name,
1345                         strlen(gc.name) < 8? "\t" : "",
1346                         gc.description);
1347         }
1348         print_in_bar(COLOR_MSG, "try \"para_gui -h\" or \"para_client help\" "
1349                 "for more info");
1350 }
1351
1352 static void com_shrink_top_win(void)
1353 {
1354         int top_lines = get_num_lines(&top);
1355
1356         if (top_lines <= theme.top_lines_min) {
1357                 PARA_WARNING_LOG("can not decrease top window\n");
1358                 return;
1359         }
1360         init_wins(top_lines - 1);
1361         print_in_bar(COLOR_MSG, "%s", "decreased top window");
1362 }
1363
1364 static void com_enlarge_top_win(void)
1365 {
1366         int top_lines = get_num_lines(&top), bot_lines = get_num_lines(&bot);
1367
1368         if (bot_lines < 3) {
1369                 PARA_WARNING_LOG("can not increase top window\n");
1370                 return;
1371         }
1372         init_wins(top_lines + 1);
1373         print_in_bar(COLOR_MSG, "increased top window");
1374 }
1375
1376 static void com_version(void)
1377 {
1378         print_in_bar(COLOR_MSG, "%s", version_single_line("gui"));
1379 }
1380
1381 __noreturn static void com_quit(void)
1382 {
1383         die(EXIT_SUCCESS, "%s", "");
1384 }
1385
1386 static void com_refresh(void)
1387 {
1388         shutdown_curses();
1389         init_curses();
1390 }
1391
1392 static void com_next_theme(void)
1393 {
1394         theme_next(&theme);
1395         com_refresh();
1396 }
1397
1398 static void com_prev_theme(void)
1399 {
1400         theme_prev(&theme);
1401         com_refresh();
1402 }
1403
1404 __noreturn static void print_help_and_die(void)
1405 {
1406         struct ggo_help h = DEFINE_GGO_HELP(gui);
1407         bool d = conf.detailed_help_given;
1408
1409         ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
1410         exit(0);
1411 }
1412
1413 static int setup_tasks_and_schedule(void)
1414 {
1415         int ret;
1416         struct exec_task exec_task = {.task = NULL};
1417         struct status_task status_task = {.fd = -1};
1418         struct input_task input_task = {.task = NULL};
1419         struct signal_task *signal_task;
1420         struct sched sched = {
1421                 .default_timeout = {
1422                         .tv_sec = conf.timeout_arg  / 1000,
1423                         .tv_usec = (conf.timeout_arg % 1000) * 1000,
1424                 },
1425         };
1426
1427         exec_task.task = task_register(&(struct task_info) {
1428                 .name = "exec",
1429                 .pre_select = exec_pre_select,
1430                 .post_select = exec_post_select,
1431                 .context = &exec_task,
1432         }, &sched);
1433
1434         status_task.task = task_register(&(struct task_info) {
1435                 .name = "status",
1436                 .pre_select = status_pre_select,
1437                 .post_select = status_post_select,
1438                 .context = &status_task,
1439         }, &sched);
1440
1441         input_task.task = task_register(&(struct task_info) {
1442                 .name = "input",
1443                 .pre_select = input_pre_select,
1444                 .post_select = input_post_select,
1445                 .context = &input_task,
1446         }, &sched);
1447
1448         signal_task = signal_init_or_die();
1449         para_install_sighandler(SIGINT);
1450         para_install_sighandler(SIGTERM);
1451         para_install_sighandler(SIGCHLD);
1452         para_install_sighandler(SIGUSR1);
1453         signal_task->task = task_register(&(struct task_info) {
1454                 .name = "signal",
1455                 .pre_select = signal_pre_select,
1456                 .post_select = signal_post_select,
1457                 .context = signal_task,
1458         }, &sched);
1459         ret = schedule(&sched);
1460         sched_shutdown(&sched);
1461         signal_shutdown(signal_task);
1462         return ret;
1463 }
1464
1465 /**
1466  * The main function of para_gui.
1467  *
1468  * \param argc Usual argument count.
1469  * \param argv Usual argument vector.
1470  *
1471  * After initialization para_gui registers the following tasks to the paraslash
1472  * scheduler: status, exec, signal, input.
1473  *
1474  * The status task executes the para_audioc stat command to obtain the status
1475  * of para_server and para_audiod, and displays this information in the top
1476  * window of para_gui.
1477  *
1478  * The exec task is responsible for printing the output of the currently
1479  * running executable to the bottom window.
1480  *
1481  * The signal task performs suitable actions according to any signals received.
1482  * For example it refreshes all windows on terminal size changes and resets the
1483  * terminal on \p SIGTERM.
1484  *
1485  * The input task reads single key strokes from stdin. For each key pressed, it
1486  * executes the command handler associated with this key.
1487  *
1488  * \return \p EXIT_SUCCESS or \p EXIT_FAILURE.
1489  */
1490 int main(int argc, char *argv[])
1491 {
1492         gui_cmdline_parser(argc, argv, &conf); /* exits on errors */
1493         loglevel = get_loglevel_by_name(conf.loglevel_arg);
1494         version_handle_flag("gui", conf.version_given);
1495         if (conf.help_given || conf.detailed_help_given)
1496                 print_help_and_die();
1497         parse_config_file_or_die(false /* override */);
1498         bot_win_rb = ringbuffer_new(RINGBUFFER_SIZE);
1499         setlocale(LC_CTYPE, "");
1500         initscr(); /* needed only once, always successful */
1501         init_curses();
1502         return setup_tasks_and_schedule() < 0? EXIT_FAILURE : EXIT_SUCCESS;
1503 }