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