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