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