gui: Remove change_theme().
[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         unsigned bytes;
523
524         if (ll < loglevel || !curses_active)
525                 return;
526         switch (ll) {
527                 case LL_DEBUG:
528                 case LL_INFO:
529                 case LL_NOTICE:
530                         color = COLOR_MSG;
531                         break;
532                 default:
533                         color = COLOR_ERRMSG;
534         }
535         va_start(ap, fmt);
536         bytes = xvasprintf(&msg, fmt, ap);
537         va_end(ap);
538         if (bytes > 0 && msg[bytes - 1] == '\n')
539                 msg[bytes - 1] = '\0'; /* cut trailing newline */
540         rb_add_entry(color, msg);
541         wrefresh(bot.win);
542 }
543 __printf_2_3 void (*para_log)(int, const char*, ...) = curses_log;
544
545 static void setup_signal_handling(void)
546 {
547         signal_pipe = para_signal_init();
548         para_install_sighandler(SIGINT);
549         para_install_sighandler(SIGTERM);
550         para_install_sighandler(SIGCHLD);
551         para_install_sighandler(SIGWINCH);
552         para_install_sighandler(SIGUSR1);
553 }
554
555 /* kill every process in the process group and exit */
556 __noreturn static void kill_pg_and_die(int ret)
557 {
558         para_sigaction(SIGTERM, SIG_IGN);
559         kill(0, SIGTERM);
560         exit(ret);
561 }
562
563 static void shutdown_curses(void)
564 {
565         if (!curses_active)
566                 return;
567         def_prog_mode();
568         curses_active = false;
569         endwin();
570 }
571
572 __noreturn static void finish(int ret)
573 {
574         shutdown_curses();
575         kill_pg_and_die(ret);
576 }
577
578 /*
579  * exit curses and print given message to stdout/stderr
580  */
581 __noreturn __printf_2_3 static void msg_n_exit(int ret, const char* fmt, ...)
582 {
583         va_list argp;
584         FILE *outfd = ret? stderr: stdout;
585
586         shutdown_curses();
587         va_start(argp, fmt);
588         vfprintf(outfd, fmt, argp);
589         va_end(argp);
590         kill_pg_and_die(ret);
591 }
592
593 /*
594  * init all windows
595  */
596 static void init_wins(int top_lines)
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                 wresize(top.win, top.lines, top.cols);
626                 mvwin(top.win, top.begy, top.begx);
627
628                 wresize(sb.win, sb.lines, sb.cols);
629                 mvwin(sb.win, sb.begy, sb.begx);
630
631                 wresize(sep.win, sep.lines, sep.cols);
632                 mvwin(sep.win, sep.begy, sep.begx);
633
634                 wresize(bot.win, bot.lines, bot.cols);
635                 mvwin(bot.win, bot.begy, bot.begx);
636
637                 wresize(in.win, in.lines, in.cols);
638                 mvwin(in.win, in.begy, in.begx);
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         whline(sep.win, theme.sep_char, COLS);
667         wclear(top.win);
668         //wclear(bot.win);
669         wnoutrefresh(top.win);
670         wnoutrefresh(bot.win);
671         print_status_bar();
672         wnoutrefresh(sb.win);
673         wnoutrefresh(in.win);
674         wnoutrefresh(sep.win);
675         doupdate();
676 }
677
678 /*
679  * Print stat item #i to curses window
680  */
681 static void print_stat_item(int i)
682 {
683         char *tmp;
684         struct stat_item_data d = theme.data[i];
685         char *c = stat_content[i];
686
687         if (!curses_active || !d.len || !c)
688                 return;
689         tmp = make_message("%s%s%s", d.prefix, c, d.postfix);
690         wmove(top.win, d.y * top.lines / 100, d.x * COLS / 100);
691         wrefresh(top.win);
692         wattron(top.win, COLOR_PAIR(i + 1));
693         align_str(top.win, tmp, d.len * COLS / 100, d.align);
694         free(tmp);
695         wrefresh(top.win);
696 }
697
698 static int update_item(int item_num, char *buf)
699 {
700         char **c = stat_content + item_num;
701
702         free(*c);
703         if (buf && buf[0])
704                 goto dup;
705         switch (item_num) {
706         case SI_ARTIST:
707                 *c = para_strdup("(artist tag not set)");
708                 goto print;
709         case SI_TITLE:
710                 *c = para_strdup("(title tag not set)");
711                 goto print;
712         case SI_YEAR:
713                 *c = para_strdup("????");
714                 goto print;
715         case SI_ALBUM:
716                 *c = para_strdup("(album tag not set)");
717                 goto print;
718         case SI_COMMENT:
719                 *c = para_strdup("(comment tag not set)");
720                 goto print;
721         }
722 dup:
723         *c = para_strdup(buf);
724 print:
725         print_stat_item(item_num);
726         return 1;
727 }
728
729 static int read_stat_pipe(fd_set *rfds)
730 {
731         static char *buf;
732         static int bufsize, loaded;
733         int ret, ret2;
734         size_t sz;
735
736         if (stat_pipe < 0)
737                 return 0;
738         if (loaded >= bufsize) {
739                 if (bufsize > 1000 * 1000) {
740                         loaded = 0;
741                         return 0;
742                 }
743                 bufsize += bufsize + 1000;
744                 buf = para_realloc(buf, bufsize);
745         }
746         assert(loaded < bufsize);
747         ret = read_nonblock(stat_pipe, buf + loaded, bufsize - loaded,
748                 rfds, &sz);
749         loaded += sz;
750         ret2 = for_each_stat_item(buf, loaded, update_item);
751         if (ret < 0 || ret2 < 0) {
752                 loaded = 0;
753                 return ret2 < 0? ret2 : ret;
754         }
755         sz = ret2; /* what is left */
756         if (sz > 0 && sz < loaded)
757                 memmove(buf, buf + loaded - sz, sz);
758         loaded = sz;
759         return 1;
760 }
761
762 static void print_all_items(void)
763 {
764         int i;
765
766         if (!curses_active)
767                 return;
768         FOR_EACH_STATUS_ITEM(i)
769                 print_stat_item(i);
770 }
771
772 static void clear_all_items(void)
773 {
774         int i;
775
776         FOR_EACH_STATUS_ITEM(i) {
777                 free(stat_content[i]);
778                 stat_content[i] = para_strdup("");
779         }
780 }
781
782 static void init_pair_or_die(short pair, short f, short b)
783 {
784         if (init_pair(pair, f, b) == ERR)
785                 msg_n_exit(EXIT_FAILURE, "fatal: init_pair() failed\n");
786 }
787
788 static void init_colors_or_die(void)
789 {
790         int i;
791
792         if (!has_colors())
793                 msg_n_exit(EXIT_FAILURE, "fatal: No color term\n");
794         if (start_color() == ERR)
795                 msg_n_exit(EXIT_FAILURE, "fatal: failed to start colors\n");
796         FOR_EACH_STATUS_ITEM(i)
797                 if (theme.data[i].len)
798                         init_pair_or_die(i + 1, theme.data[i].fg,
799                                 theme.data[i].bg);
800         init_pair_or_die(COLOR_STATUSBAR, theme.sb_fg, theme.sb_bg);
801         init_pair_or_die(COLOR_COMMAND, theme.cmd_fg, theme.cmd_bg);
802         init_pair_or_die(COLOR_OUTPUT, theme.output_fg, theme.output_bg);
803         init_pair_or_die(COLOR_MSG, theme.msg_fg, theme.msg_bg);
804         init_pair_or_die(COLOR_ERRMSG, theme.err_msg_fg, theme.err_msg_bg);
805         init_pair_or_die(COLOR_SEPARATOR, theme.sep_fg, theme.sep_bg);
806         init_pair_or_die(COLOR_TOP, theme.default_fg, theme.default_bg);
807         init_pair_or_die(COLOR_BOT, theme.default_fg, theme.default_bg);
808 }
809
810 /* (Re-)initialize the curses library. */
811 static void init_curses(void)
812 {
813         curses_active = true;
814         if (top.win && refresh() == ERR) /* refresh is really needed */
815                 msg_n_exit(EXIT_FAILURE, "refresh() failed\n");
816         if (LINES < theme.lines_min || COLS < theme.cols_min)
817                 msg_n_exit(EXIT_FAILURE, "Error: Terminal (%dx%d) too small"
818                         " (need at least %dx%d)\n", COLS, LINES,
819                         theme.cols_min, theme.lines_min);
820         curs_set(0); /* make cursor invisible, ignore errors */
821         nonl(); /* do not NL->CR/NL on output, always returns OK */
822         /* don't echo input */
823         if (noecho() == ERR)
824                 msg_n_exit(EXIT_FAILURE, "fatal: noecho() failed\n");
825         /* take input chars one at a time, no wait for \n */
826         if (cbreak() == ERR)
827                 msg_n_exit(EXIT_FAILURE, "fatal: cbreak() failed\n");
828         init_colors_or_die();
829         clear(); /* ignore non-fatal errors */
830         init_wins(theme.top_lines_default);
831         print_all_items();
832         // noecho(); /* don't echo input */
833 }
834
835 static void check_sigchld(void)
836 {
837         int ret;
838         pid_t pid;
839
840 reap_next_child:
841         ret = para_reap_child(&pid);
842         if (ret <= 0)
843                 return;
844         if (pid == cmd_pid)
845                 cmd_pid = 0;
846         goto reap_next_child;
847 }
848
849 /*
850  * This sucker modifies its first argument. *handler and *arg are
851  * pointers to 0-terminated strings (inside line). Crap.
852  */
853 static int split_key_map(char *line, char **handler, char **arg)
854 {
855         if (!(*handler = strchr(line + 1, ':')))
856                 goto err_out;
857         **handler = '\0';
858         (*handler)++;
859         if (!(*arg = strchr(*handler, ':')))
860                 goto err_out;
861         **arg = '\0';
862         (*arg)++;
863         return 1;
864 err_out:
865         return 0;
866 }
867
868 static int check_key_map_args(void)
869 {
870         char *s;
871         int i, ret = -1;
872         char *tmp = NULL, *handler, *arg;
873
874         for (i = 0; i < conf.key_map_given; ++i) {
875                 s = conf.key_map_arg[i];
876                 if (!(*s))
877                         goto out;
878                 free(tmp);
879                 tmp = para_strdup(s);
880                 if (!split_key_map(tmp, &handler, &arg))
881                         goto out;
882                 if (strlen(handler) != 1)
883                         goto out;
884                 if (*handler != 'x'
885                         && *handler != 'd'
886                         && *handler != 'i'
887                         && *handler != 'p')
888                         goto out;
889                 if (*handler != 'i')
890                         continue;
891                 if (find_cmd_byname(arg) < 0)
892                         goto out;
893         }
894         ret = 0;
895 out:
896         free(tmp);
897         return ret;
898 }
899
900 /*
901  * React to various signal-related events
902  */
903 static void handle_signal(int sig)
904 {
905         switch (sig) {
906         case SIGTERM:
907                 msg_n_exit(EXIT_FAILURE,
908                         "only the good die young (caught SIGTERM))\n");
909                 return;
910         case SIGWINCH:
911                 if (curses_active) {
912                         shutdown_curses();
913                         init_curses();
914                         redraw_bot_win();
915                 }
916                 return;
917         case SIGINT:
918                 PARA_WARNING_LOG("caught SIGINT, reset\n");
919                 /* Nothing to do. SIGINT killed our child which gets noticed
920                  * by do_select and resets everything.
921                  */
922                 return;
923         case SIGUSR1:
924                 PARA_NOTICE_LOG("got SIGUSR1, rereading configuration\n");
925                 com_reread_conf();
926                 return;
927         case SIGCHLD:
928                 check_sigchld();
929                 return;
930         }
931 }
932
933 static void status_pre_select(fd_set *rfds, int *max_fileno, struct timeval *tv)
934 {
935         static struct timeval next_exec, atm, diff;
936         int ret, fds[3] = {0, 1, 0};
937         pid_t pid;
938
939         if (stat_pipe >= 0)
940                 goto success;
941         /* Avoid busy loop */
942         gettimeofday(&atm, NULL);
943         if (tv_diff(&next_exec, &atm, &diff) > 0) {
944                 if (tv_diff(&diff, tv, NULL) < 0)
945                         *tv = diff;
946                 return;
947         }
948         next_exec.tv_sec = atm.tv_sec + 2;
949         ret = para_exec_cmdline_pid(&pid, conf.stat_cmd_arg, fds);
950         if (ret < 0)
951                 return;
952         ret = mark_fd_nonblocking(fds[1]);
953         if (ret < 0) {
954                 close(fds[1]);
955                 return;
956         }
957         stat_pipe = fds[1];
958 success:
959         para_fd_set(stat_pipe, rfds, max_fileno);
960 }
961
962 #define COMMAND_BUF_SIZE 32768
963
964 /*
965  * This is the core select loop. Besides the (internal) signal
966  * pipe, the following other fds are checked according to the mode:
967  *
968  * GETCH_MODE: check stdin, return when key is pressed
969  *
970  * COMMAND_MODE: check command fds and stdin. Return when peer has closed both
971  * stdout and stderr or when any key is pressed.
972  *
973  * EXTERNAL_MODE: Check only signal pipe. Used when an external command
974  * is running. During that time curses is disabled.  Returns when
975  * cmd_pid == 0.
976  */
977 static int do_select(int mode)
978 {
979         fd_set rfds;
980         int ret, i, max_fileno;
981         char command_buf[2][COMMAND_BUF_SIZE] = {"", ""};
982         int cbo[2] = {0, 0}; /* command buf offsets */
983         struct timeval tv;
984         unsigned flags[2] = {0, 0}; /* for for_each_line() */
985
986 repeat:
987         tv.tv_sec = conf.timeout_arg  / 1000;
988         tv.tv_usec = (conf.timeout_arg % 1000) * 1000;
989 //      ret = refresh_status();
990         FD_ZERO(&rfds);
991         max_fileno = 0;
992         status_pre_select(&rfds, &max_fileno, &tv);
993         /* signal pipe */
994         para_fd_set(signal_pipe, &rfds, &max_fileno);
995         /* command pipe only for COMMAND_MODE */
996         if (mode == COMMAND_MODE) {
997                 if (command_fds[0] >= 0)
998                         para_fd_set(command_fds[0], &rfds, &max_fileno);
999                 if (command_fds[1] >= 0)
1000                         para_fd_set(command_fds[1], &rfds, &max_fileno);
1001         }
1002         if (mode == GETCH_MODE || mode == COMMAND_MODE)
1003                 para_fd_set(STDIN_FILENO, &rfds, &max_fileno);
1004         ret = para_select(max_fileno + 1, &rfds, NULL, &tv);
1005         if (ret <= 0)
1006                 goto check_return; /* skip fd checks */
1007         /* signals */
1008         ret = para_next_signal(&rfds);
1009         if (ret > 0)
1010                 handle_signal(ret);
1011         /* read command pipe if ready */
1012         if (mode == COMMAND_MODE) {
1013                 for (i = 0; i < 2; i++) {
1014                         size_t sz;
1015                         if (command_fds[i] < 0)
1016                                 continue;
1017                         ret = read_nonblock(command_fds[i],
1018                                 command_buf[i] + cbo[i],
1019                                 COMMAND_BUF_SIZE - 1 - cbo[i], &rfds, &sz);
1020                         cbo[i] += sz;
1021                         sz = cbo[i];
1022                         cbo[i] = for_each_line(flags[i], command_buf[i], cbo[i],
1023                                 add_output_line, &i);
1024                         if (sz != cbo[i]) { /* at least one line found */
1025                                 wrefresh(bot.win);
1026                                 flags[i] = 0;
1027                         }
1028                         if (ret < 0) {
1029                                 PARA_NOTICE_LOG("closing command fd %d: %s\n",
1030                                         i, para_strerror(-ret));
1031                                 close(command_fds[i]);
1032                                 command_fds[i] = -1;
1033                                 flags[i] = 0;
1034                                 cbo[i] = 0;
1035                                 if (command_fds[!i] < 0) /* both fds closed */
1036                                         return 0;
1037                         }
1038                         if (cbo[i] == COMMAND_BUF_SIZE - 1) {
1039                                 PARA_NOTICE_LOG("discarding overlong line\n");
1040                                 cbo[i] = 0;
1041                                 flags[i] = FELF_DISCARD_FIRST;
1042                         }
1043                 }
1044         }
1045         ret = read_stat_pipe(&rfds);
1046         if (ret < 0) {
1047                 PARA_NOTICE_LOG("closing stat pipe: %s\n", para_strerror(-ret));
1048                 close(stat_pipe);
1049                 stat_pipe = -1;
1050                 clear_all_items();
1051                 free(stat_content[SI_BASENAME]);
1052                 stat_content[SI_BASENAME] =
1053                         para_strdup("stat command terminated!?");
1054                 print_all_items();
1055         }
1056 check_return:
1057         switch (mode) {
1058         case COMMAND_MODE:
1059                 ret = wgetch(top.win);
1060                 if (ret != ERR && ret != KEY_RESIZE) {
1061                         if (cmd_pid)
1062                                 kill(cmd_pid, SIGTERM);
1063                         return -1;
1064                 }
1065                 break;
1066         case GETCH_MODE:
1067                 ret = wgetch(top.win);
1068                 if (ret != ERR && ret != KEY_RESIZE)
1069                         return ret;
1070                 break;
1071         case EXTERNAL_MODE:
1072                 if (cmd_pid == 0)
1073                         return 0;
1074         }
1075         goto repeat;
1076 }
1077
1078 /* read from command pipe and print data to bot window */
1079 static void exec_and_display_cmd(const char *cmd)
1080 {
1081         int ret, fds[3] = {0, 1, 1};
1082
1083         outputf(COLOR_COMMAND, "%s", cmd);
1084         ret = para_exec_cmdline_pid(&cmd_pid, cmd, fds);
1085         if (ret < 0)
1086                 return;
1087         ret = mark_fd_nonblocking(fds[1]);
1088         if (ret < 0)
1089                 goto fail;
1090         ret = mark_fd_nonblocking(fds[2]);
1091         if (ret < 0)
1092                 goto fail;
1093         command_fds[0] = fds[1];
1094         command_fds[1] = fds[2];
1095         if (do_select(COMMAND_MODE) >= 0)
1096                 PARA_INFO_LOG("command complete\n");
1097         else
1098                 PARA_NOTICE_LOG("command aborted\n");
1099         print_in_bar(COLOR_MSG, " ");
1100         return;
1101 fail:
1102         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1103         close(command_fds[0]);
1104         close(command_fds[1]);
1105 }
1106
1107 static void para_cmd(char *cmd)
1108 {
1109         char *c;
1110
1111         print_in_bar(COLOR_MSG, "executing client command, hit any key to abort\n");
1112         c = make_message(BINDIR "/para_client -- %s", cmd);
1113         exec_and_display_cmd(c);
1114         free(c);
1115 }
1116
1117 static void display_cmd(char *cmd)
1118 {
1119         print_in_bar(COLOR_MSG, "executing display command, hit any key to abort");
1120         exec_and_display_cmd(cmd);
1121 }
1122
1123 /*
1124  * shutdown curses and stat pipe before executing external commands
1125  */
1126 static void external_cmd(char *cmd)
1127 {
1128         int fds[3] = {-1, -1, -1};
1129
1130         if (cmd_pid)
1131                 return;
1132         shutdown_curses();
1133         if (para_exec_cmdline_pid(&cmd_pid, cmd, fds) < 0)
1134                 return;
1135         do_select(EXTERNAL_MODE);
1136         init_curses();
1137 }
1138
1139 static void print_scroll_msg(void)
1140 {
1141         unsigned lines_total, filled = ringbuffer_filled(bot_win_rb);
1142         int first_rbe = first_visible_rbe(&lines_total);
1143
1144         print_in_bar(COLOR_MSG, "scrolled view: %d-%d/%d\n", filled - first_rbe,
1145                 filled - scroll_position, ringbuffer_filled(bot_win_rb));
1146 }
1147
1148 static void com_scroll_top(void)
1149 {
1150         int i = RINGBUFFER_SIZE - 1;
1151         unsigned lines = 0;
1152
1153         while (i > 0 && !ringbuffer_get(bot_win_rb, i))
1154                 i--;
1155         /* i is oldest entry */
1156         for (; lines < bot.lines && i >= 0; i--) {
1157                 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
1158                 if (!rbe)
1159                         break;
1160                 lines += NUM_LINES(rbe->len);
1161         }
1162         i++;
1163         if (lines > 0 && scroll_position != i) {
1164                 scroll_position = i;
1165                 redraw_bot_win();
1166                 print_scroll_msg();
1167                 return;
1168         }
1169         print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1170 }
1171
1172 static void com_cancel_scrolling(void)
1173 {
1174
1175         if (scroll_position == 0) {
1176                 print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1177                 return;
1178         }
1179         scroll_position = 0;
1180         redraw_bot_win();
1181 }
1182
1183 static void com_page_down(void)
1184 {
1185         unsigned lines = 0;
1186         int i = scroll_position;
1187
1188         while (lines < bot.lines && --i > 0) {
1189                 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
1190                 if (!rbe)
1191                         break;
1192                 lines += NUM_LINES(rbe->len);
1193         }
1194         if (lines) {
1195                 scroll_position = i;
1196                 redraw_bot_win();
1197                 print_scroll_msg();
1198                 return;
1199         }
1200         print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1201 }
1202
1203 static void com_page_up(void)
1204 {
1205         unsigned lines;
1206         int fvr = first_visible_rbe(&lines);
1207
1208         if (fvr < 0 || fvr + 1 >= ringbuffer_filled(bot_win_rb)) {
1209                 print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1210                 return;
1211         }
1212         scroll_position = fvr + 1;
1213         for (; scroll_position > 0; scroll_position--) {
1214                 first_visible_rbe(&lines);
1215                 if (lines == bot.lines)
1216                         break;
1217         }
1218         redraw_bot_win();
1219         print_scroll_msg();
1220 }
1221
1222 static void com_scroll_down(void)
1223 {
1224         struct rb_entry *rbe;
1225         int rbe_lines;
1226
1227         if (!scroll_position) {
1228                 print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1229                 return;
1230         }
1231         scroll_position--;
1232         rbe = ringbuffer_get(bot_win_rb, scroll_position);
1233         rbe_lines = NUM_LINES(rbe->len);
1234         wscrl(bot.win, rbe_lines);
1235         wmove(bot.win, bot.lines - rbe_lines, 0);
1236         wattron(bot.win, COLOR_PAIR(rbe->color));
1237         waddstr(bot.win, rbe->msg);
1238         wrefresh(bot.win);
1239         print_scroll_msg();
1240 }
1241
1242 static void com_scroll_up(void)
1243 {
1244         struct rb_entry *rbe = NULL;
1245         unsigned lines;
1246         int i, first_rbe, num_scroll;
1247
1248         /* the entry that is going to vanish */
1249         rbe = ringbuffer_get(bot_win_rb, scroll_position);
1250         if (!rbe)
1251                 goto err_out;
1252         num_scroll = NUM_LINES(rbe->len);
1253         first_rbe = first_visible_rbe(&lines);
1254         if (first_rbe < 0 || (first_rbe == ringbuffer_filled(bot_win_rb) - 1))
1255                 goto err_out;
1256         scroll_position++;
1257         wscrl(bot.win, -num_scroll);
1258         i = draw_top_rbe(&lines);
1259         if (i < 0)
1260                 goto err_out;
1261         while (i > 0 && lines < num_scroll) {
1262                 int rbe_lines;
1263                 rbe = ringbuffer_get(bot_win_rb, --i);
1264                 if (!rbe)
1265                         break;
1266                 rbe_lines = NUM_LINES(rbe->len);
1267                 lines += rbe_lines;
1268 //              fprintf(stderr, "msg: %s\n", rbe->msg);
1269                 wattron(bot.win, COLOR_PAIR(rbe->color));
1270                 waddstr(bot.win, "\n");
1271                 waddstr(bot.win, rbe->msg);
1272                 if (!i)
1273                         break;
1274                 i--;
1275         }
1276         wrefresh(bot.win);
1277         print_scroll_msg();
1278         return;
1279 err_out:
1280         print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1281 }
1282
1283 static void com_ll_decr(void)
1284 {
1285         if (loglevel <= LL_DEBUG) {
1286                 print_in_bar(COLOR_ERRMSG,
1287                         "loglevel already at maximal verbosity\n");
1288                 return;
1289         }
1290         loglevel--;
1291         print_in_bar(COLOR_MSG, "loglevel set to %d\n", loglevel);
1292 }
1293
1294 static void com_ll_incr(void)
1295 {
1296         if (loglevel >= LL_EMERG) {
1297                 print_in_bar(COLOR_ERRMSG,
1298                         "loglevel already at minimal verbosity\n");
1299                 return;
1300         }
1301         loglevel++;
1302         print_in_bar(COLOR_MSG, "loglevel set to %d\n", loglevel);
1303 }
1304
1305 /*
1306  * reread configuration, terminate on errors
1307  */
1308 static void com_reread_conf(void)
1309 {
1310         char *cf = configfile_exists();
1311         struct gui_cmdline_parser_params params = {
1312                 .override = 1,
1313                 .initialize = 1,
1314                 .check_required = 0,
1315                 .check_ambiguity = 0,
1316                 .print_errors = 0,
1317         };
1318
1319         if (!cf) {
1320                 PARA_WARNING_LOG("there is no configuration to read\n");
1321                 return;
1322         }
1323         PARA_INFO_LOG("rereading command line options and config file\n");
1324         gui_cmdline_parser_ext(_argc, _argv, &conf, &params);
1325         /*
1326          * Despite .print_errors is set to 0, gengetopt will print to stderr
1327          * anyway, and exit on errors. So we have to shutdown curses first.
1328          */
1329         shutdown_curses();
1330         gui_cmdline_parser_config_file(cf, &conf, &params);
1331         init_curses();
1332         PARA_NOTICE_LOG("config file reloaded\n");
1333         if (check_key_map_args() < 0)
1334                 finish(EXIT_FAILURE);
1335 }
1336
1337 static void com_help(void)
1338 {
1339         int i;
1340
1341         for (i = 0; i < conf.key_map_given; ++i) {
1342                 char *handler, *arg, *tmp = para_strdup(conf.key_map_arg[i]);
1343                 const char *handler_text = "???", *desc = NULL;
1344
1345                 if (!split_key_map(tmp, &handler, &arg)) {
1346                         free(tmp);
1347                         return;
1348                 }
1349                 switch (*handler) {
1350                         case 'i':
1351                                 handler_text = "internal";
1352                                 desc = command_list[find_cmd_byname(arg)].description;
1353                                 break;
1354                         case 'x': handler_text = "external"; break;
1355                         case 'd': handler_text = "display "; break;
1356                         case 'p': handler_text = "para    "; break;
1357                 }
1358                 outputf(COLOR_MSG, "%s\t%s\t%s%s\t%s", tmp, handler_text, arg,
1359                         strlen(arg) < 8? "\t" : "",
1360                         desc? desc : "");
1361                 free(tmp);
1362         }
1363         for (i = 0; command_list[i].handler; i++) {
1364                 struct gui_command gc = command_list[i];
1365
1366                 outputf(COLOR_MSG, "%s\tinternal\t%s\t%s%s", gc.key, gc.name,
1367                         strlen(gc.name) < 8? "\t" : "",
1368                         gc.description);
1369         }
1370         print_in_bar(COLOR_MSG, "try \"para_gui -h\" or \"para_client help\" "
1371                 "for more info");
1372 }
1373
1374 static void com_shrink_top_win(void)
1375 {
1376         if (top.lines <= theme.top_lines_min) {
1377                 PARA_WARNING_LOG("can not decrease top window\n");
1378                 return;
1379         }
1380         init_wins(top.lines - 1);
1381         wclear(top.win);
1382         print_all_items();
1383         print_in_bar(COLOR_MSG, "%s", "decreased top window");
1384 }
1385
1386 static void com_enlarge_top_win(void)
1387 {
1388         if (bot.lines < 3) {
1389                 PARA_WARNING_LOG("can not increase top window\n");
1390                 return;
1391         }
1392         init_wins(top.lines + 1);
1393         wclear(top.win);
1394         print_all_items();
1395         print_in_bar(COLOR_MSG, "increased top window");
1396 }
1397
1398 static void com_version(void)
1399 {
1400         print_in_bar(COLOR_MSG, "%s", version_single_line("gui"));
1401 }
1402
1403 __noreturn static void com_quit(void)
1404 {
1405         finish(0);
1406 }
1407
1408 static void com_refresh(void)
1409 {
1410         shutdown_curses();
1411         init_curses();
1412 }
1413
1414 static void com_next_theme(void)
1415 {
1416         theme_next(&theme);
1417         com_refresh();
1418 }
1419
1420 static void com_prev_theme(void)
1421 {
1422         theme_prev(&theme);
1423         com_refresh();
1424 }
1425
1426 static void handle_command(int c)
1427 {
1428         int i;
1429
1430         /* first check user-defined key bindings */
1431         for (i = 0; i < conf.key_map_given; ++i) {
1432                 char *tmp, *handler, *arg;
1433
1434                 tmp = para_strdup(conf.key_map_arg[i]);
1435                 if (!split_key_map(tmp, &handler, &arg)) {
1436                         free(tmp);
1437                         return;
1438                 }
1439                 if (strcmp(tmp, km_keyname(c))) {
1440                         free(tmp);
1441                         continue;
1442                 }
1443                 if (*handler == 'd')
1444                         display_cmd(arg);
1445                 else if (*handler == 'x')
1446                         external_cmd(arg);
1447                 else if (*handler == 'p')
1448                         para_cmd(arg);
1449                 else if (*handler == 'i') {
1450                         int num = find_cmd_byname(arg);
1451                         if (num >= 0)
1452                                 command_list[num].handler();
1453                 }
1454                 free(tmp);
1455                 return;
1456         }
1457         /* not found, check internal key bindings */
1458         for (i = 0; command_list[i].handler; i++) {
1459                 if (!strcmp(km_keyname(c), command_list[i].key)) {
1460                         command_list[i].handler();
1461                         return;
1462                 }
1463         }
1464         print_in_bar(COLOR_ERRMSG, "key '%s' is not bound, press ? for help",
1465                 km_keyname(c));
1466 }
1467
1468 __noreturn static void print_help_and_die(void)
1469 {
1470         struct ggo_help h = DEFINE_GGO_HELP(gui);
1471         bool d = conf.detailed_help_given;
1472
1473         ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
1474         exit(0);
1475 }
1476
1477 int main(int argc, char *argv[])
1478 {
1479         int ret;
1480         char *cf;
1481
1482         _argc = argc;
1483         _argv = argv;
1484
1485         gui_cmdline_parser(argc, argv, &conf); /* exits on errors */
1486         loglevel = get_loglevel_by_name(conf.loglevel_arg);
1487         version_handle_flag("gui", conf.version_given);
1488         if (conf.help_given || conf.detailed_help_given)
1489                 print_help_and_die();
1490         cf = configfile_exists();
1491         if (!cf && conf.config_file_given) {
1492                 fprintf(stderr, "can not read config file %s\n",
1493                         conf.config_file_arg);
1494                 exit(EXIT_FAILURE);
1495         }
1496         if (cf) {
1497                 struct gui_cmdline_parser_params params = {
1498                         .override = 0,
1499                         .initialize = 0,
1500                         .check_required = 0,
1501                         .check_ambiguity = 0,
1502                         .print_errors = 1,
1503                 };
1504                 gui_cmdline_parser_config_file(cf, &conf, &params);
1505                 loglevel = get_loglevel_by_name(conf.loglevel_arg);
1506         }
1507         if (check_key_map_args() < 0) {
1508                 fprintf(stderr, "invalid key map\n");
1509                 exit(EXIT_FAILURE);
1510         }
1511         theme_init(conf.theme_arg, &theme);
1512         setup_signal_handling();
1513         bot_win_rb = ringbuffer_new(RINGBUFFER_SIZE);
1514         setlocale(LC_CTYPE, "");
1515         initscr(); /* needed only once, always successful */
1516         init_curses();
1517         for (;;) {
1518                 print_status_bar();
1519                 ret = do_select(GETCH_MODE);
1520                 if (!ret)
1521                         continue;
1522                 print_in_bar(COLOR_MSG, " ");
1523                 handle_command(ret);
1524         }
1525 }