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