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