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