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