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