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