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