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