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