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