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