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