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