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