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