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