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