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