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