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