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