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