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