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