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