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