gui: Kill struct gui_window->beg{xy}.
[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 bool curses_active;
53 static pid_t cmd_pid;
54
55 static int command_fds[2] = {-1, -1};
56 static int stat_pipe = -1;
57 static struct gui_args_info conf;
58
59 enum {GETCH_MODE, COMMAND_MODE, EXTERNAL_MODE};
60
61
62 /**
63 * Codes for various colors.
64 *
65 * Each status item has its own color pair. The ones defined here start at a
66 * higher number so that they do not overlap with these.
67 */
68 enum gui_color_pair {
69 COLOR_STATUSBAR = NUM_STAT_ITEMS + 1,
70 COLOR_COMMAND,
71 COLOR_OUTPUT,
72 COLOR_MSG,
73 COLOR_ERRMSG,
74 COLOR_SEPARATOR,
75 COLOR_TOP,
76 COLOR_BOT,
77 };
78
79 struct gui_command {
80 const char *key;
81 const char *name;
82 const char *description;
83 void (*handler)(void);
84 };
85
86 static struct gui_theme theme;
87
88 static int _argc;
89 static char **_argv;
90
91 static void com_help(void);
92 static void com_reread_conf(void);
93 static void com_enlarge_top_win(void);
94 static void com_shrink_top_win(void);
95 static void com_version(void);
96 __noreturn static void com_quit(void);
97 static void com_refresh(void);
98 static void com_ll_incr(void);
99 static void com_ll_decr(void);
100 static void com_prev_theme(void);
101 static void com_next_theme(void);
102 static void com_scroll_up(void);
103 static void com_scroll_down(void);
104 static void com_page_up(void);
105 static void com_page_down(void);
106 static void com_cancel_scrolling(void);
107 static void com_scroll_top(void);
108
109 static struct gui_command command_list[] = {
110 {
111 .key = "?",
112 .name = "help",
113 .description = "print help",
114 .handler = com_help
115 }, {
116 .key = "+",
117 .name = "enlarge_win",
118 .description = "enlarge the top window",
119 .handler = com_enlarge_top_win
120 }, {
121 .key = "-",
122 .name = "shrink_win",
123 .description = "shrink the top window",
124 .handler = com_shrink_top_win
125 }, {
126 .key = "r",
127 .name = "reread_conf",
128 .description = "reread configuration file",
129 .handler = com_reread_conf
130 }, {
131 .key = "q",
132 .name = "quit",
133 .description = "exit para_gui",
134 .handler = com_quit
135 }, {
136 .key = "^L",
137 .name = "refresh",
138 .description = "redraw the screen",
139 .handler = com_refresh
140 }, {
141 .key = ".",
142 .name = "next_theme",
143 .description = "switch to next theme",
144 .handler = com_next_theme
145 }, {
146 .key = ",",
147 .name = "prev_theme",
148 .description = "switch to previous stream",
149 .handler = com_prev_theme
150 }, {
151 .key = ">",
152 .name = "ll_incr",
153 .description = "increase loglevel (decreases verbosity)",
154 .handler = com_ll_incr
155 }, {
156 .key = "<",
157 .name = "ll_decr",
158 .description = "decrease loglevel (increases verbosity)",
159 .handler = com_ll_decr
160 }, {
161 .key = "V",
162 .name = "version",
163 .description = "show the para_gui version",
164 .handler = com_version
165 }, {
166 .key = "<up>",
167 .name = "scroll_up",
168 .description = "scroll up one line",
169 .handler = com_scroll_up
170 }, {
171 .key = "<down>",
172 .name = "scroll_down",
173 .description = "scroll down one line",
174 .handler = com_scroll_down
175 }, {
176 .key = "<ppage>",
177 .name = "page_up",
178 .description = "scroll up one page",
179 .handler = com_page_up
180 }, {
181 .key = "<npage>",
182 .name = "page_down",
183 .description = "scroll down one page",
184 .handler = com_page_down
185 }, {
186 .key = "<home>",
187 .name = "scroll_top",
188 .description = "scroll to top of buffer",
189 .handler = com_scroll_top
190 }, {
191 .key = "<end>",
192 .name = "cancel_scroll",
193 .description = "deactivate scroll mode",
194 .handler = com_cancel_scrolling
195 }, {
196 .handler = NULL
197 }
198 };
199
200 static int find_cmd_byname(char *name)
201 {
202 int i;
203
204 for (i = 0; command_list[i].handler; i++)
205 if (!strcmp(command_list[i].name, name))
206 return i;
207 return -1;
208 }
209
210 /* taken from mutt */
211 static char *km_keyname(int c)
212 {
213 static char buf[10];
214
215 if (c == KEY_UP) {
216 sprintf(buf, "<up>");
217 return buf;
218 }
219 if (c == KEY_DOWN) {
220 sprintf(buf, "<down>");
221 return buf;
222 }
223 if (c == KEY_LEFT) {
224 sprintf(buf, "<left>");
225 return buf;
226 }
227 if (c == KEY_RIGHT) {
228 sprintf(buf, "<right>");
229 return buf;
230 }
231 if (c == KEY_NPAGE) {
232 sprintf(buf, "<npage>");
233 return buf;
234 }
235 if (c == KEY_PPAGE) {
236 sprintf(buf, "<ppage>");
237 return buf;
238 }
239 if (c == KEY_HOME) {
240 sprintf(buf, "<home>");
241 return buf;
242 }
243 if (c == KEY_END) {
244 sprintf(buf, "<end>");
245 return buf;
246 }
247 if (c < 256 && c > -128 && iscntrl((unsigned char) c)) {
248 if (c < 0)
249 c += 256;
250 if (c < 128) {
251 buf[0] = '^';
252 buf[1] = (c + '@') & 0x7f;
253 buf[2] = 0;
254 } else
255 snprintf(buf, sizeof(buf), "\\%d%d%d", c >> 6,
256 (c >> 3) & 7, c & 7);
257 } else if (c >= KEY_F0 && c < KEY_F(256))
258 sprintf(buf, "<F%d>", c - KEY_F0);
259 else if (isprint(c))
260 snprintf(buf, sizeof(buf), "%c", (unsigned char) c);
261 else
262 snprintf(buf, sizeof(buf), "\\x%hx", (unsigned short) c);
263 return buf;
264 }
265
266 static char *configfile_exists(void)
267 {
268 static char *config_file;
269 char *tmp;
270
271 if (!conf.config_file_given) {
272 if (!config_file) {
273 char *home = para_homedir();
274 config_file = make_message("%s/.paraslash/gui.conf",
275 home);
276 free(home);
277 }
278 tmp = config_file;
279 } else
280 tmp = conf.config_file_arg;
281 return file_exists(tmp)? tmp: NULL;
282 }
283
284 /* Print given number of spaces to curses window. */
285 static void add_spaces(WINDOW* win, unsigned int num)
286 {
287 char space[] = " ";
288 unsigned sz = sizeof(space) - 1; /* number of spaces */
289
290 while (num >= sz) {
291 waddstr(win, space);
292 num -= sz;
293 }
294 if (num > 0) {
295 assert(num < sz);
296 space[num] = '\0';
297 waddstr(win, space);
298 }
299 }
300
301 /*
302 * print aligned string to curses window. This function always prints
303 * exactly len chars.
304 */
305 static int align_str(WINDOW* win, char *str, unsigned int len,
306 unsigned int align)
307 {
308 int ret, i, num; /* of spaces */
309 size_t width;
310
311 if (!win || !str)
312 return 0;
313 ret = strwidth(str, &width);
314 if (ret < 0) {
315 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
316 width = 0;
317 str[0] = '\0';
318 }
319 num = len - width;
320 if (num < 0) {
321 str[len] = '\0';
322 num = 0;
323 }
324 /* replace control characters by spaces */
325 for (i = 0; i < len && str[i]; i++) {
326 if (str[i] == '\n' || str[i] == '\r' || str[i] == '\f')
327 str[i] = ' ';
328 }
329 if (align == LEFT) {
330 waddstr(win, str);
331 add_spaces(win, num);
332 } else if (align == RIGHT) {
333 add_spaces(win, num);
334 waddstr(win, str);
335 } else {
336 add_spaces(win, num / 2);
337 waddstr(win, str[0]? str: "");
338 add_spaces(win, num - num / 2);
339 }
340 return 1;
341 }
342
343 __printf_2_3 static void print_in_bar(int color, const char *fmt,...)
344 {
345 char *msg;
346 va_list ap;
347
348 if (!curses_active)
349 return;
350 wattron(in.win, COLOR_PAIR(color));
351 va_start(ap, fmt);
352 xvasprintf(&msg, fmt, ap);
353 va_end(ap);
354 wmove(in.win, 0, 0);
355 align_str(in.win, msg, in.cols, LEFT);
356 free(msg);
357 wrefresh(in.win);
358 }
359
360 static void print_status_bar(void)
361 {
362 char *tmp;
363
364 tmp = para_strdup("para_gui " PACKAGE_VERSION " (hit ? for help)");
365 wmove(sb.win, 0, 0);
366 align_str(sb.win, tmp, sb.cols, CENTER);
367 free(tmp);
368 }
369
370 /*
371 * get the number of the oldest rbe that is (partially) visible. On return,
372 * lines contains the sum of the number of lines of all visible entries. If the
373 * first one is only partially visible, lines is greater than bot.lines.
374 */
375 static int first_visible_rbe(unsigned *lines)
376 {
377 int i;
378 *lines = 0;
379 for (i = scroll_position; i < RINGBUFFER_SIZE; i++) {
380 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
381 int rbe_lines;
382 if (!rbe)
383 return i - 1;
384 // fprintf(stderr, "found: %s\n", rbe->msg);
385 rbe_lines = NUM_LINES(rbe->len);
386 if (rbe_lines > bot.lines)
387 return -1;
388 *lines += rbe_lines;
389 if (*lines >= bot.lines)
390 return i;
391 }
392 return RINGBUFFER_SIZE - 1;
393 }
394
395 /*
396 returns number of first visible rbe, *lines is the number of lines drawn.
397 */
398 static int draw_top_rbe(unsigned *lines)
399 {
400 int ret, fvr = first_visible_rbe(lines);
401 struct rb_entry *rbe;
402 size_t bytes_to_skip, cells_to_skip, width;
403
404 if (fvr < 0)
405 return -1;
406 wmove(bot.win, 0, 0);
407 rbe = ringbuffer_get(bot_win_rb, fvr);
408 if (!rbe)
409 return -1;
410 if (*lines > bot.lines) {
411 /* rbe is partially visible multi-line */
412 cells_to_skip = (*lines - bot.lines) * bot.cols;
413 ret = skip_cells(rbe->msg, cells_to_skip, &bytes_to_skip);
414 if (ret < 0)
415 return ret;
416 ret = strwidth(rbe->msg + bytes_to_skip, &width);
417 if (ret < 0)
418 return ret;
419 } else {
420 bytes_to_skip = 0;
421 width = rbe->len;
422 }
423 wattron(bot.win, COLOR_PAIR(rbe->color));
424 waddstr(bot.win, rbe->msg + bytes_to_skip);
425 *lines = NUM_LINES(width);
426 return fvr;
427 }
428
429 static void redraw_bot_win(void)
430 {
431 unsigned lines;
432 int i;
433
434 wmove(bot.win, 0, 0);
435 wclear(bot.win);
436 i = draw_top_rbe(&lines);
437 if (i <= 0)
438 goto out;
439 while (i > 0 && lines < bot.lines) {
440 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, --i);
441 if (!rbe) {
442 lines++;
443 waddstr(bot.win, "\n");
444 continue;
445 }
446 lines += NUM_LINES(rbe->len);
447 wattron(bot.win, COLOR_PAIR(rbe->color));
448 waddstr(bot.win, "\n");
449 waddstr(bot.win, rbe->msg);
450 }
451 out:
452 wrefresh(bot.win);
453 }
454
455 static void rb_add_entry(int color, char *msg)
456 {
457 struct rb_entry *old, *new;
458 int x, y;
459 size_t len;
460
461 if (strwidth(msg, &len) < 0)
462 return;
463 new = para_malloc(sizeof(struct rb_entry));
464 new->color = color;
465 new->len = len;
466 new->msg = msg;
467 old = ringbuffer_add(bot_win_rb, new);
468 // fprintf(stderr, "added: %s\n", new->msg);
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 int color;
518 char *msg;
519 va_list ap;
520 unsigned bytes;
521
522 if (ll < loglevel || !curses_active)
523 return;
524 switch (ll) {
525 case LL_DEBUG:
526 case LL_INFO:
527 case LL_NOTICE:
528 color = COLOR_MSG;
529 break;
530 default:
531 color = COLOR_ERRMSG;
532 }
533 va_start(ap, fmt);
534 bytes = xvasprintf(&msg, fmt, ap);
535 va_end(ap);
536 if (bytes > 0 && msg[bytes - 1] == '\n')
537 msg[bytes - 1] = '\0'; /* cut trailing newline */
538 rb_add_entry(color, msg);
539 wrefresh(bot.win);
540 }
541 __printf_2_3 void (*para_log)(int, const char*, ...) = curses_log;
542
543 static void setup_signal_handling(void)
544 {
545 signal_pipe = para_signal_init();
546 para_install_sighandler(SIGINT);
547 para_install_sighandler(SIGTERM);
548 para_install_sighandler(SIGCHLD);
549 para_install_sighandler(SIGWINCH);
550 para_install_sighandler(SIGUSR1);
551 }
552
553 /* kill every process in the process group and exit */
554 __noreturn static void kill_pg_and_die(int ret)
555 {
556 para_sigaction(SIGTERM, SIG_IGN);
557 kill(0, SIGTERM);
558 exit(ret);
559 }
560
561 static void shutdown_curses(void)
562 {
563 if (!curses_active)
564 return;
565 def_prog_mode();
566 curses_active = false;
567 endwin();
568 }
569
570 __noreturn static void finish(int ret)
571 {
572 shutdown_curses();
573 kill_pg_and_die(ret);
574 }
575
576 /*
577 * exit curses and print given message to stdout/stderr
578 */
579 __noreturn __printf_2_3 static void msg_n_exit(int ret, const char* fmt, ...)
580 {
581 va_list argp;
582 FILE *outfd = ret? stderr: stdout;
583
584 shutdown_curses();
585 va_start(argp, fmt);
586 vfprintf(outfd, fmt, argp);
587 va_end(argp);
588 kill_pg_and_die(ret);
589 }
590
591 /*
592 * init all windows
593 */
594 static void init_wins(int top_lines)
595 {
596 int top_y = 0, bot_y = top_lines + 1, sb_y = LINES - 2,
597 in_y = LINES - 1, sep_y = top_lines;
598
599 top.lines = top_lines;
600 bot.lines = LINES - top.lines - 3;
601 sb.lines = in.lines = sep.lines = 1;
602
603 top.cols = bot.cols = sb.cols = in.cols = sep.cols = COLS;
604
605 assume_default_colors(theme.default_fg, theme.default_bg);
606 if (top.win) {
607 wresize(top.win, top.lines, top.cols);
608 mvwin(top.win, top_y, 0);
609
610 wresize(sb.win, sb.lines, sb.cols);
611 mvwin(sb.win, sb_y, 0);
612
613 wresize(sep.win, sep.lines, sep.cols);
614 mvwin(sep.win, sep_y, 0);
615
616 wresize(bot.win, bot.lines, bot.cols);
617 mvwin(bot.win, bot_y, 0);
618
619 wresize(in.win, in.lines, in.cols);
620 mvwin(in.win, in_y, 0);
621 } else {
622 sep.win = newwin(sep.lines, sep.cols, sep_y, 0);
623 top.win = newwin(top.lines, top.cols, top_y, 0);
624 bot.win = newwin(bot.lines, bot.cols, bot_y, 0);
625 sb.win = newwin(sb.lines, sb.cols, sb_y, 0);
626 in.win = newwin(in.lines, in.cols, in_y, 0);
627 if (!top.win || !bot.win || !sb.win || !in.win || !sep.win)
628 msg_n_exit(1, "Error: Cannot create curses windows\n");
629 wclear(bot.win);
630 wclear(sb.win);
631 wclear(in.win);
632 scrollok(bot.win, 1);
633 wattron(sb.win, COLOR_PAIR(COLOR_STATUSBAR));
634 wattron(sep.win, COLOR_PAIR(COLOR_SEPARATOR));
635 wattron(bot.win, COLOR_PAIR(COLOR_BOT));
636 wattron(top.win, COLOR_PAIR(COLOR_TOP));
637 nodelay(top.win, 1);
638 nodelay(bot.win, 1);
639 nodelay(sb.win, 1);
640 nodelay(in.win, 0);
641
642 keypad(top.win, 1);
643 keypad(bot.win, 1);
644 keypad(sb.win, 1);
645 keypad(in.win, 1);
646 }
647 wmove(sep.win, 0, 0);
648 whline(sep.win, theme.sep_char, COLS);
649 wclear(top.win);
650 //wclear(bot.win);
651 wnoutrefresh(top.win);
652 wnoutrefresh(bot.win);
653 print_status_bar();
654 wnoutrefresh(sb.win);
655 wnoutrefresh(in.win);
656 wnoutrefresh(sep.win);
657 doupdate();
658 }
659
660 /*
661 * Print stat item #i to curses window
662 */
663 static void print_stat_item(int i)
664 {
665 char *tmp;
666 struct stat_item_data d = theme.data[i];
667 char *c = stat_content[i];
668
669 if (!curses_active || !d.len || !c)
670 return;
671 tmp = make_message("%s%s%s", d.prefix, c, d.postfix);
672 wmove(top.win, d.y * top.lines / 100, d.x * COLS / 100);
673 wrefresh(top.win);
674 wattron(top.win, COLOR_PAIR(i + 1));
675 align_str(top.win, tmp, d.len * COLS / 100, d.align);
676 free(tmp);
677 wrefresh(top.win);
678 }
679
680 static int update_item(int item_num, char *buf)
681 {
682 char **c = stat_content + item_num;
683
684 free(*c);
685 if (buf && buf[0])
686 goto dup;
687 switch (item_num) {
688 case SI_ARTIST:
689 *c = para_strdup("(artist tag not set)");
690 goto print;
691 case SI_TITLE:
692 *c = para_strdup("(title tag not set)");
693 goto print;
694 case SI_YEAR:
695 *c = para_strdup("????");
696 goto print;
697 case SI_ALBUM:
698 *c = para_strdup("(album tag not set)");
699 goto print;
700 case SI_COMMENT:
701 *c = para_strdup("(comment tag not set)");
702 goto print;
703 }
704 dup:
705 *c = para_strdup(buf);
706 print:
707 print_stat_item(item_num);
708 return 1;
709 }
710
711 static int read_stat_pipe(fd_set *rfds)
712 {
713 static char *buf;
714 static int bufsize, loaded;
715 int ret, ret2;
716 size_t sz;
717
718 if (stat_pipe < 0)
719 return 0;
720 if (loaded >= bufsize) {
721 if (bufsize > 1000 * 1000) {
722 loaded = 0;
723 return 0;
724 }
725 bufsize += bufsize + 1000;
726 buf = para_realloc(buf, bufsize);
727 }
728 assert(loaded < bufsize);
729 ret = read_nonblock(stat_pipe, buf + loaded, bufsize - loaded,
730 rfds, &sz);
731 loaded += sz;
732 ret2 = for_each_stat_item(buf, loaded, update_item);
733 if (ret < 0 || ret2 < 0) {
734 loaded = 0;
735 return ret2 < 0? ret2 : ret;
736 }
737 sz = ret2; /* what is left */
738 if (sz > 0 && sz < loaded)
739 memmove(buf, buf + loaded - sz, sz);
740 loaded = sz;
741 return 1;
742 }
743
744 static void print_all_items(void)
745 {
746 int i;
747
748 if (!curses_active)
749 return;
750 FOR_EACH_STATUS_ITEM(i)
751 print_stat_item(i);
752 }
753
754 static void clear_all_items(void)
755 {
756 int i;
757
758 FOR_EACH_STATUS_ITEM(i) {
759 free(stat_content[i]);
760 stat_content[i] = para_strdup("");
761 }
762 }
763
764 static void init_pair_or_die(short pair, short f, short b)
765 {
766 if (init_pair(pair, f, b) == ERR)
767 msg_n_exit(EXIT_FAILURE, "fatal: init_pair() failed\n");
768 }
769
770 static void init_colors_or_die(void)
771 {
772 int i;
773
774 if (!has_colors())
775 msg_n_exit(EXIT_FAILURE, "fatal: No color term\n");
776 if (start_color() == ERR)
777 msg_n_exit(EXIT_FAILURE, "fatal: failed to start colors\n");
778 FOR_EACH_STATUS_ITEM(i)
779 if (theme.data[i].len)
780 init_pair_or_die(i + 1, theme.data[i].fg,
781 theme.data[i].bg);
782 init_pair_or_die(COLOR_STATUSBAR, theme.sb_fg, theme.sb_bg);
783 init_pair_or_die(COLOR_COMMAND, theme.cmd_fg, theme.cmd_bg);
784 init_pair_or_die(COLOR_OUTPUT, theme.output_fg, theme.output_bg);
785 init_pair_or_die(COLOR_MSG, theme.msg_fg, theme.msg_bg);
786 init_pair_or_die(COLOR_ERRMSG, theme.err_msg_fg, theme.err_msg_bg);
787 init_pair_or_die(COLOR_SEPARATOR, theme.sep_fg, theme.sep_bg);
788 init_pair_or_die(COLOR_TOP, theme.default_fg, theme.default_bg);
789 init_pair_or_die(COLOR_BOT, theme.default_fg, theme.default_bg);
790 }
791
792 /* (Re-)initialize the curses library. */
793 static void init_curses(void)
794 {
795 curses_active = true;
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 gui_cmdline_parser_ext(_argc, _argv, &conf, &params);
1307 /*
1308 * Despite .print_errors is set to 0, gengetopt will print to stderr
1309 * anyway, and exit on errors. So we have to shutdown curses first.
1310 */
1311 shutdown_curses();
1312 gui_cmdline_parser_config_file(cf, &conf, &params);
1313 init_curses();
1314 PARA_NOTICE_LOG("config file reloaded\n");
1315 if (check_key_map_args() < 0)
1316 finish(EXIT_FAILURE);
1317 }
1318
1319 static void com_help(void)
1320 {
1321 int i;
1322
1323 for (i = 0; i < conf.key_map_given; ++i) {
1324 char *handler, *arg, *tmp = para_strdup(conf.key_map_arg[i]);
1325 const char *handler_text = "???", *desc = NULL;
1326
1327 if (!split_key_map(tmp, &handler, &arg)) {
1328 free(tmp);
1329 return;
1330 }
1331 switch (*handler) {
1332 case 'i':
1333 handler_text = "internal";
1334 desc = command_list[find_cmd_byname(arg)].description;
1335 break;
1336 case 'x': handler_text = "external"; break;
1337 case 'd': handler_text = "display "; break;
1338 case 'p': handler_text = "para "; break;
1339 }
1340 outputf(COLOR_MSG, "%s\t%s\t%s%s\t%s", tmp, handler_text, arg,
1341 strlen(arg) < 8? "\t" : "",
1342 desc? desc : "");
1343 free(tmp);
1344 }
1345 for (i = 0; command_list[i].handler; i++) {
1346 struct gui_command gc = command_list[i];
1347
1348 outputf(COLOR_MSG, "%s\tinternal\t%s\t%s%s", gc.key, gc.name,
1349 strlen(gc.name) < 8? "\t" : "",
1350 gc.description);
1351 }
1352 print_in_bar(COLOR_MSG, "try \"para_gui -h\" or \"para_client help\" "
1353 "for more info");
1354 }
1355
1356 static void com_shrink_top_win(void)
1357 {
1358 if (top.lines <= theme.top_lines_min) {
1359 PARA_WARNING_LOG("can not decrease top window\n");
1360 return;
1361 }
1362 init_wins(top.lines - 1);
1363 wclear(top.win);
1364 print_all_items();
1365 print_in_bar(COLOR_MSG, "%s", "decreased top window");
1366 }
1367
1368 static void com_enlarge_top_win(void)
1369 {
1370 if (bot.lines < 3) {
1371 PARA_WARNING_LOG("can not increase top window\n");
1372 return;
1373 }
1374 init_wins(top.lines + 1);
1375 wclear(top.win);
1376 print_all_items();
1377 print_in_bar(COLOR_MSG, "increased top window");
1378 }
1379
1380 static void com_version(void)
1381 {
1382 print_in_bar(COLOR_MSG, "%s", version_single_line("gui"));
1383 }
1384
1385 __noreturn static void com_quit(void)
1386 {
1387 finish(0);
1388 }
1389
1390 static void com_refresh(void)
1391 {
1392 shutdown_curses();
1393 init_curses();
1394 }
1395
1396 static void com_next_theme(void)
1397 {
1398 theme_next(&theme);
1399 com_refresh();
1400 }
1401
1402 static void com_prev_theme(void)
1403 {
1404 theme_prev(&theme);
1405 com_refresh();
1406 }
1407
1408 static void handle_command(int c)
1409 {
1410 int i;
1411
1412 /* first check user-defined key bindings */
1413 for (i = 0; i < conf.key_map_given; ++i) {
1414 char *tmp, *handler, *arg;
1415
1416 tmp = para_strdup(conf.key_map_arg[i]);
1417 if (!split_key_map(tmp, &handler, &arg)) {
1418 free(tmp);
1419 return;
1420 }
1421 if (strcmp(tmp, km_keyname(c))) {
1422 free(tmp);
1423 continue;
1424 }
1425 if (*handler == 'd')
1426 display_cmd(arg);
1427 else if (*handler == 'x')
1428 external_cmd(arg);
1429 else if (*handler == 'p')
1430 para_cmd(arg);
1431 else if (*handler == 'i') {
1432 int num = find_cmd_byname(arg);
1433 if (num >= 0)
1434 command_list[num].handler();
1435 }
1436 free(tmp);
1437 return;
1438 }
1439 /* not found, check internal key bindings */
1440 for (i = 0; command_list[i].handler; i++) {
1441 if (!strcmp(km_keyname(c), command_list[i].key)) {
1442 command_list[i].handler();
1443 return;
1444 }
1445 }
1446 print_in_bar(COLOR_ERRMSG, "key '%s' is not bound, press ? for help",
1447 km_keyname(c));
1448 }
1449
1450 __noreturn static void print_help_and_die(void)
1451 {
1452 struct ggo_help h = DEFINE_GGO_HELP(gui);
1453 bool d = conf.detailed_help_given;
1454
1455 ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
1456 exit(0);
1457 }
1458
1459 int main(int argc, char *argv[])
1460 {
1461 int ret;
1462 char *cf;
1463
1464 _argc = argc;
1465 _argv = argv;
1466
1467 gui_cmdline_parser(argc, argv, &conf); /* exits on errors */
1468 loglevel = get_loglevel_by_name(conf.loglevel_arg);
1469 version_handle_flag("gui", conf.version_given);
1470 if (conf.help_given || conf.detailed_help_given)
1471 print_help_and_die();
1472 cf = configfile_exists();
1473 if (!cf && conf.config_file_given) {
1474 fprintf(stderr, "can not read config file %s\n",
1475 conf.config_file_arg);
1476 exit(EXIT_FAILURE);
1477 }
1478 if (cf) {
1479 struct gui_cmdline_parser_params params = {
1480 .override = 0,
1481 .initialize = 0,
1482 .check_required = 0,
1483 .check_ambiguity = 0,
1484 .print_errors = 1,
1485 };
1486 gui_cmdline_parser_config_file(cf, &conf, &params);
1487 loglevel = get_loglevel_by_name(conf.loglevel_arg);
1488 }
1489 if (check_key_map_args() < 0) {
1490 fprintf(stderr, "invalid key map\n");
1491 exit(EXIT_FAILURE);
1492 }
1493 theme_init(conf.theme_arg, &theme);
1494 setup_signal_handling();
1495 bot_win_rb = ringbuffer_new(RINGBUFFER_SIZE);
1496 setlocale(LC_CTYPE, "");
1497 initscr(); /* needed only once, always successful */
1498 init_curses();
1499 for (;;) {
1500 print_status_bar();
1501 ret = do_select(GETCH_MODE);
1502 if (!ret)
1503 continue;
1504 print_in_bar(COLOR_MSG, " ");
1505 handle_command(ret);
1506 }
1507 }