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