]> git.tuebingen.mpg.de Git - paraslash.git/blob - gui.c
gui: Use lsu_merge_config_file_options().
[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 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 SIGINT:
905                 return 1;
906         case SIGUSR1:
907                 PARA_NOTICE_LOG("got SIGUSR1, rereading configuration\n");
908                 reread_conf();
909                 return 1;
910         case SIGCHLD:
911                 task_notify_all(s, E_GUI_SIGCHLD);
912                 return 1;
913         }
914         return 1;
915 }
916
917 static enum exec_status exec_status(void)
918 {
919         if (exec_fds[0] >= 0 || exec_fds[1] >= 0)
920                 return EXEC_DCMD;
921         if (exec_pid > 0)
922                 return EXEC_XCMD;
923         return EXEC_IDLE;
924 }
925
926 static void exec_pre_select(struct sched *s, void *context)
927 {
928         struct exec_task *et = context;
929         if (exec_fds[0] >= 0)
930                 para_fd_set(exec_fds[0], &s->rfds, &s->max_fileno);
931         if (exec_fds[1] >= 0)
932                 para_fd_set(exec_fds[1], &s->rfds, &s->max_fileno);
933         if (task_get_notification(et->task) < 0)
934                 sched_min_delay(s);
935 }
936
937 static int exec_post_select(struct sched *s, void *context)
938 {
939         struct exec_task *ct = context;
940         int i, ret;
941
942         ret = task_get_notification(ct->task);
943         if (ret == -E_GUI_SIGCHLD && exec_pid > 0) {
944                 int exit_status;
945                 if (waitpid(exec_pid, &exit_status, WNOHANG) == exec_pid) {
946                         exec_pid = 0;
947                         init_curses();
948                         PARA_INFO_LOG("command exit status: %d", exit_status);
949                         print_in_bar(COLOR_MSG, " ");
950                 }
951         }
952         for (i = 0; i < 2; i++) {
953                 size_t sz;
954                 if (exec_fds[i] < 0)
955                         continue;
956                 ret = read_nonblock(exec_fds[i],
957                         ct->command_buf[i] + ct->cbo[i],
958                         COMMAND_BUF_SIZE - 1 - ct->cbo[i], &s->rfds, &sz);
959                 ct->cbo[i] += sz;
960                 sz = ct->cbo[i];
961                 ct->cbo[i] = for_each_line(ct->flags[i], ct->command_buf[i],
962                         ct->cbo[i], add_output_line, &i);
963                 if (sz != ct->cbo[i]) { /* at least one line found */
964                         refresh_window(&bot);
965                         ct->flags[i] = 0;
966                 }
967                 if (ret < 0 || exec_pid == 0) {
968                         if (ret < 0)
969                                 PARA_NOTICE_LOG("closing command fd %d: %s",
970                                         i, para_strerror(-ret));
971                         close(exec_fds[i]);
972                         exec_fds[i] = -1;
973                         ct->flags[i] = 0;
974                         ct->cbo[i] = 0;
975                         if (exec_fds[!i] < 0) /* both fds closed */
976                                 return 1;
977                 }
978                 if (ct->cbo[i] == COMMAND_BUF_SIZE - 1) {
979                         PARA_NOTICE_LOG("discarding overlong line");
980                         ct->cbo[i] = 0;
981                         ct->flags[i] = FELF_DISCARD_FIRST;
982                 }
983         }
984         return 0;
985 }
986
987 static void input_pre_select(struct sched *s, __a_unused void *context)
988 {
989         if (exec_status() != EXEC_XCMD)
990                 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
991         if (window_update_needed())
992                 sched_min_delay(s);
993 }
994
995 /* Read from command pipe and print data to bot window. */
996 static void exec_and_display(const char *file_and_args)
997 {
998         int ret, fds[3] = {0, 1, 1};
999
1000         outputf(COLOR_COMMAND, "%s", file_and_args);
1001         ret = para_exec_cmdline_pid(&exec_pid, file_and_args, fds);
1002         if (ret < 0)
1003                 return;
1004         ret = mark_fd_nonblocking(fds[1]);
1005         if (ret < 0)
1006                 goto fail;
1007         ret = mark_fd_nonblocking(fds[2]);
1008         if (ret < 0)
1009                 goto fail;
1010         exec_fds[0] = fds[1];
1011         exec_fds[1] = fds[2];
1012         print_in_bar(COLOR_MSG, "hit any key to abort\n");
1013         return;
1014 fail:
1015         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1016         close(exec_fds[0]);
1017         close(exec_fds[1]);
1018 }
1019
1020 static void exec_para(const char *args)
1021 {
1022         char *file_and_args;
1023
1024         file_and_args = make_message(BINDIR "/para_client -- %s", args);
1025         exec_and_display(file_and_args);
1026         free(file_and_args);
1027 }
1028
1029 /* Shutdown curses and stat pipe before executing external commands. */
1030 static void exec_external(char *file_and_args)
1031 {
1032         int fds[3] = {-1, -1, -1};
1033
1034         if (exec_pid)
1035                 return;
1036         shutdown_curses();
1037         para_exec_cmdline_pid(&exec_pid, file_and_args, fds);
1038 }
1039
1040 static void handle_command(int c)
1041 {
1042         int i;
1043         const struct lls_opt_result *lor = OPT_RESULT(KEY_MAP);
1044
1045         /* first check user-defined key bindings */
1046         FOR_EACH_KEY_MAP(i) {
1047                 char *tmp, *handler, *arg;
1048
1049                 tmp = para_strdup(lls_string_val(i, lor));
1050                 if (!split_key_map(tmp, &handler, &arg)) {
1051                         free(tmp);
1052                         return;
1053                 }
1054                 if (strcmp(tmp, km_keyname(c))) {
1055                         free(tmp);
1056                         continue;
1057                 }
1058                 if (*handler == 'd')
1059                         exec_and_display(arg);
1060                 else if (*handler == 'x')
1061                         exec_external(arg);
1062                 else if (*handler == 'p')
1063                         exec_para(arg);
1064                 else if (*handler == 'i') {
1065                         int num = find_cmd_byname(arg);
1066                         if (num >= 0)
1067                                 command_list[num].handler();
1068                 }
1069                 free(tmp);
1070                 return;
1071         }
1072         /* not found, check internal key bindings */
1073         for (i = 0; command_list[i].handler; i++) {
1074                 if (!strcmp(km_keyname(c), command_list[i].key)) {
1075                         command_list[i].handler();
1076                         return;
1077                 }
1078         }
1079         print_in_bar(COLOR_ERRMSG, "key '%s' is not bound, press ? for help",
1080                 km_keyname(c));
1081 }
1082
1083 static int input_post_select(__a_unused struct sched *s,
1084                 __a_unused void *context)
1085 {
1086         int ret;
1087         enum exec_status exs = exec_status();
1088
1089         if (exs == EXEC_XCMD)
1090                 return 0;
1091         if (window_update_needed()) {
1092                 if (top.needs_update)
1093                         assert(wnoutrefresh(top.win) == OK);
1094                 if (bot.needs_update)
1095                         assert(wnoutrefresh(bot.win) == OK);
1096                 if (sep.needs_update)
1097                         assert(wnoutrefresh(sep.win) == OK);
1098                 if (sb.needs_update)
1099                         assert(wnoutrefresh(sb.win) == OK);
1100                 if (in.needs_update)
1101                         assert(wnoutrefresh(in.win) == OK);
1102                 doupdate();
1103                 top.needs_update = bot.needs_update = sb.needs_update =
1104                         in.needs_update = sep.needs_update = false;
1105         }
1106         ret = wgetch(top.win);
1107         if (ret == ERR)
1108                 return 0;
1109         if (ret == KEY_RESIZE) {
1110                 if (curses_active()) {
1111                         shutdown_curses();
1112                         init_curses();
1113                         redraw_bot_win();
1114                 }
1115                 return 0;
1116         }
1117         if (exs == EXEC_IDLE)
1118                 handle_command(ret);
1119         else if (exec_pid > 0)
1120                 kill(exec_pid, SIGTERM);
1121         return 0;
1122 }
1123
1124 static void print_scroll_msg(void)
1125 {
1126         unsigned lines_total, filled = ringbuffer_filled(bot_win_rb);
1127         int first_rbe = first_visible_rbe(&lines_total);
1128
1129         print_in_bar(COLOR_MSG, "scrolled view: %u-%u/%u\n", filled - first_rbe,
1130                 filled - scroll_position, ringbuffer_filled(bot_win_rb));
1131 }
1132
1133 static void com_scroll_top(void)
1134 {
1135         int i = RINGBUFFER_SIZE - 1, bot_lines = get_num_lines(&bot);
1136         unsigned lines = 0;
1137
1138         while (i > 0 && !ringbuffer_get(bot_win_rb, i))
1139                 i--;
1140         /* i is oldest entry */
1141         for (; lines < bot_lines && i >= 0; i--) {
1142                 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
1143                 if (!rbe)
1144                         break;
1145                 lines += NUM_LINES(rbe->len);
1146         }
1147         i++;
1148         if (lines > 0 && scroll_position != i) {
1149                 scroll_position = i;
1150                 redraw_bot_win();
1151                 print_scroll_msg();
1152                 return;
1153         }
1154         print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1155 }
1156
1157 static void com_cancel_scroll(void)
1158 {
1159
1160         if (scroll_position == 0) {
1161                 print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1162                 return;
1163         }
1164         scroll_position = 0;
1165         redraw_bot_win();
1166 }
1167
1168 static void com_page_down(void)
1169 {
1170         unsigned lines = 0;
1171         int i = scroll_position, bot_lines = get_num_lines(&bot);
1172
1173         while (lines < bot_lines && --i > 0) {
1174                 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
1175                 if (!rbe)
1176                         break;
1177                 lines += NUM_LINES(rbe->len);
1178         }
1179         if (lines) {
1180                 scroll_position = i;
1181                 redraw_bot_win();
1182                 print_scroll_msg();
1183                 return;
1184         }
1185         print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1186 }
1187
1188 static void com_page_up(void)
1189 {
1190         unsigned lines;
1191         int fvr = first_visible_rbe(&lines), bot_lines = get_num_lines(&bot);
1192
1193         if (fvr < 0 || fvr + 1 >= ringbuffer_filled(bot_win_rb)) {
1194                 print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1195                 return;
1196         }
1197         scroll_position = fvr + 1;
1198         for (; scroll_position > 0; scroll_position--) {
1199                 first_visible_rbe(&lines);
1200                 if (lines == bot_lines)
1201                         break;
1202         }
1203         redraw_bot_win();
1204         print_scroll_msg();
1205 }
1206
1207 static void com_scroll_down(void)
1208 {
1209         struct rb_entry *rbe;
1210         int rbe_lines, bot_lines = get_num_lines(&bot);
1211
1212         if (!scroll_position) {
1213                 print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1214                 return;
1215         }
1216         scroll_position--;
1217         rbe = ringbuffer_get(bot_win_rb, scroll_position);
1218         rbe_lines = NUM_LINES(rbe->len);
1219         wscrl(bot.win, rbe_lines);
1220         wmove(bot.win, bot_lines - rbe_lines, 0);
1221         wattron(bot.win, COLOR_PAIR(rbe->color));
1222         waddstr(bot.win, rbe->msg);
1223         refresh_window(&bot);
1224         print_scroll_msg();
1225 }
1226
1227 static void com_scroll_up(void)
1228 {
1229         struct rb_entry *rbe = NULL;
1230         unsigned lines;
1231         int i, first_rbe, num_scroll;
1232
1233         /* the entry that is going to vanish */
1234         rbe = ringbuffer_get(bot_win_rb, scroll_position);
1235         if (!rbe)
1236                 goto err_out;
1237         num_scroll = NUM_LINES(rbe->len);
1238         first_rbe = first_visible_rbe(&lines);
1239         if (first_rbe < 0 || (first_rbe == ringbuffer_filled(bot_win_rb) - 1))
1240                 goto err_out;
1241         scroll_position++;
1242         wscrl(bot.win, -num_scroll);
1243         i = draw_top_rbe(&lines);
1244         if (i < 0)
1245                 goto err_out;
1246         while (i > 0 && lines < num_scroll) {
1247                 int rbe_lines;
1248                 rbe = ringbuffer_get(bot_win_rb, --i);
1249                 if (!rbe)
1250                         break;
1251                 rbe_lines = NUM_LINES(rbe->len);
1252                 lines += rbe_lines;
1253                 wattron(bot.win, COLOR_PAIR(rbe->color));
1254                 waddstr(bot.win, "\n");
1255                 waddstr(bot.win, rbe->msg);
1256                 if (!i)
1257                         break;
1258                 i--;
1259         }
1260         refresh_window(&bot);
1261         print_scroll_msg();
1262         return;
1263 err_out:
1264         print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1265 }
1266
1267 static void com_ll_decr(void)
1268 {
1269         if (loglevel <= LL_DEBUG) {
1270                 print_in_bar(COLOR_ERRMSG,
1271                         "loglevel already at maximal verbosity\n");
1272                 return;
1273         }
1274         loglevel--;
1275         print_in_bar(COLOR_MSG, "loglevel set to %d\n", loglevel);
1276 }
1277
1278 static void com_ll_incr(void)
1279 {
1280         if (loglevel >= LL_EMERG) {
1281                 print_in_bar(COLOR_ERRMSG,
1282                         "loglevel already at minimal verbosity\n");
1283                 return;
1284         }
1285         loglevel++;
1286         print_in_bar(COLOR_MSG, "loglevel set to %d\n", loglevel);
1287 }
1288
1289 static void com_reread_conf(void)
1290 {
1291         reread_conf();
1292 }
1293
1294 static void com_help(void)
1295 {
1296         int i;
1297         const struct lls_opt_result *lor = OPT_RESULT(KEY_MAP);
1298
1299         FOR_EACH_KEY_MAP(i) {
1300                 char *handler, *arg, *tmp = para_strdup(lls_string_val(i, lor));
1301                 const char *handler_text = "???", *desc = NULL;
1302
1303                 if (!split_key_map(tmp, &handler, &arg)) {
1304                         free(tmp);
1305                         return;
1306                 }
1307                 switch (*handler) {
1308                         case 'i':
1309                                 handler_text = "internal";
1310                                 desc = command_list[find_cmd_byname(arg)].description;
1311                                 break;
1312                         case 'x': handler_text = "external"; break;
1313                         case 'd': handler_text = "display "; break;
1314                         case 'p': handler_text = "para    "; break;
1315                 }
1316                 outputf(COLOR_MSG, "%s\t%s\t%s%s\t%s", tmp, handler_text, arg,
1317                         strlen(arg) < 8? "\t" : "",
1318                         desc? desc : "");
1319                 free(tmp);
1320         }
1321         for (i = 0; command_list[i].handler; i++) {
1322                 struct gui_command gc = command_list[i];
1323
1324                 outputf(COLOR_MSG, "%s\tinternal\t%s\t%s%s", gc.key, gc.name,
1325                         strlen(gc.name) < 8? "\t" : "",
1326                         gc.description);
1327         }
1328         print_in_bar(COLOR_MSG, "try \"para_gui -h\" or \"para_client help\" "
1329                 "for more info");
1330 }
1331
1332 static void com_shrink_top_win(void)
1333 {
1334         int top_lines = get_num_lines(&top);
1335
1336         if (top_lines <= theme.top_lines_min) {
1337                 PARA_WARNING_LOG("can not decrease top window\n");
1338                 return;
1339         }
1340         init_wins(top_lines - 1);
1341         print_in_bar(COLOR_MSG, "%s", "decreased top window");
1342 }
1343
1344 static void com_enlarge_top_win(void)
1345 {
1346         int top_lines = get_num_lines(&top), bot_lines = get_num_lines(&bot);
1347
1348         if (bot_lines < 3) {
1349                 PARA_WARNING_LOG("can not increase top window\n");
1350                 return;
1351         }
1352         init_wins(top_lines + 1);
1353         print_in_bar(COLOR_MSG, "increased top window");
1354 }
1355
1356 static void com_version(void)
1357 {
1358         print_in_bar(COLOR_MSG, "%s", version_single_line("gui"));
1359 }
1360
1361 __noreturn static void com_quit(void)
1362 {
1363         die(EXIT_SUCCESS, "%s", "");
1364 }
1365
1366 static void com_refresh(void)
1367 {
1368         shutdown_curses();
1369         init_curses();
1370 }
1371
1372 static void com_next_theme(void)
1373 {
1374         theme_next(&theme);
1375         com_refresh();
1376 }
1377
1378 static void com_prev_theme(void)
1379 {
1380         theme_prev(&theme);
1381         com_refresh();
1382 }
1383
1384 static int setup_tasks_and_schedule(void)
1385 {
1386         int ret;
1387         struct exec_task exec_task = {.task = NULL};
1388         struct status_task status_task = {.fd = -1};
1389         struct input_task input_task = {.task = NULL};
1390         struct signal_task *signal_task;
1391         struct sched sched = {.default_timeout = {.tv_sec = 1}};
1392
1393         exec_task.task = task_register(&(struct task_info) {
1394                 .name = "exec",
1395                 .pre_select = exec_pre_select,
1396                 .post_select = exec_post_select,
1397                 .context = &exec_task,
1398         }, &sched);
1399
1400         status_task.task = task_register(&(struct task_info) {
1401                 .name = "status",
1402                 .pre_select = status_pre_select,
1403                 .post_select = status_post_select,
1404                 .context = &status_task,
1405         }, &sched);
1406
1407         input_task.task = task_register(&(struct task_info) {
1408                 .name = "input",
1409                 .pre_select = input_pre_select,
1410                 .post_select = input_post_select,
1411                 .context = &input_task,
1412         }, &sched);
1413
1414         signal_task = signal_init_or_die();
1415         para_install_sighandler(SIGINT);
1416         para_install_sighandler(SIGTERM);
1417         para_install_sighandler(SIGCHLD);
1418         para_install_sighandler(SIGUSR1);
1419         signal_task->task = task_register(&(struct task_info) {
1420                 .name = "signal",
1421                 .pre_select = signal_pre_select,
1422                 .post_select = signal_post_select,
1423                 .context = signal_task,
1424         }, &sched);
1425         ret = schedule(&sched);
1426         sched_shutdown(&sched);
1427         signal_shutdown(signal_task);
1428         return ret;
1429 }
1430
1431 static void handle_help_flags(void)
1432 {
1433         char *help;
1434
1435         if (OPT_GIVEN(DETAILED_HELP))
1436                 help = lls_long_help(CMD_PTR);
1437         else if (OPT_GIVEN(HELP))
1438                 help = lls_short_help(CMD_PTR);
1439         else
1440                 return;
1441         printf("%s\n", help);
1442         free(help);
1443         exit(EXIT_SUCCESS);
1444 }
1445
1446 /**
1447  * The main function of para_gui.
1448  *
1449  * \param argc Usual argument count.
1450  * \param argv Usual argument vector.
1451  *
1452  * After initialization para_gui registers the following tasks to the paraslash
1453  * scheduler: status, exec, signal, input.
1454  *
1455  * The status task executes the para_audioc stat command to obtain the status
1456  * of para_server and para_audiod, and displays this information in the top
1457  * window of para_gui.
1458  *
1459  * The exec task is responsible for printing the output of the currently
1460  * running executable to the bottom window.
1461  *
1462  * The signal task performs various actions according to signals received. For
1463  * example, it reloads the configuration file on SIGUSR1, and it shuts down the
1464  * curses system on SIGTERM to restore the terminal settings before exit.
1465  *
1466  * The input task reads single key strokes from stdin. For each key pressed, it
1467  * executes the command handler associated with this key.
1468  *
1469  * \return \p EXIT_SUCCESS or \p EXIT_FAILURE.
1470  */
1471 int main(int argc, char *argv[])
1472 {
1473         int ret;
1474         char *errctx;
1475
1476         ret = lls(lls_parse(argc, argv, CMD_PTR, &cmdline_lpr, &errctx));
1477         if (ret < 0)
1478                 goto out;
1479         lpr = cmdline_lpr;
1480         loglevel = OPT_UINT32_VAL(LOGLEVEL);
1481         version_handle_flag("gui", OPT_GIVEN(VERSION));
1482         handle_help_flags();
1483         parse_config_file_or_die(false);
1484         bot_win_rb = ringbuffer_new(RINGBUFFER_SIZE);
1485         setlocale(LC_CTYPE, "");
1486         initscr(); /* needed only once, always successful */
1487         init_curses();
1488         ret = setup_tasks_and_schedule();
1489 out:
1490         lls_free_parse_result(lpr, CMD_PTR);
1491         if (lpr != cmdline_lpr)
1492                 lls_free_parse_result(cmdline_lpr, CMD_PTR);
1493         if (ret < 0) {
1494                 if (errctx)
1495                         PARA_ERROR_LOG("%s\n", errctx);
1496                 free(errctx);
1497                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1498         }
1499         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1500 }