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