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