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