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