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