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