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