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