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