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