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