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