2 * Copyright (C) 1998 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file gui.c Curses-based interface for paraslash. */
11 #include <sys/types.h>
16 #include "gui.cmdline.h"
20 #include "ringbuffer.h"
29 /** Array of error strings. */
32 static char *stat_content[NUM_STAT_ITEMS];
34 static struct gui_window {
37 } top, bot, sb, in, sep;
39 /** How many lines of output to remember. */
40 #define RINGBUFFER_SIZE 512
47 static struct ringbuffer *bot_win_rb;
49 static unsigned scroll_position;
51 static pid_t exec_pid;
53 static int exec_fds[2] = {-1, -1};
54 static struct gui_args_info conf;
57 /** Type of the process currently being executed. */
59 EXEC_IDLE, /**< No process running. */
60 EXEC_DCMD, /**< para or display process running. */
61 EXEC_XCMD, /**< External process running. */
65 * Codes for various colors.
67 * Each status item has its own color pair. The ones defined here start at a
68 * higher number so that they do not overlap with these.
71 COLOR_STATUSBAR = NUM_STAT_ITEMS + 1,
84 const char *description;
85 void (*handler)(void);
88 static struct gui_theme theme;
90 #define GUI_COMMANDS \
91 GUI_COMMAND(help, "?", "print help") \
92 GUI_COMMAND(enlarge_top_win, "+", "enlarge the top window") \
93 GUI_COMMAND(shrink_top_win, "-", "shrink the top window") \
94 GUI_COMMAND(reread_conf, "r", "reread configuration file") \
95 GUI_COMMAND(quit, "q", "exit para_gui") \
96 GUI_COMMAND(refresh, "^L", "redraw the screen") \
97 GUI_COMMAND(next_theme, ".", "switch to next theme") \
98 GUI_COMMAND(prev_theme, ",", "switch to previous theme") \
99 GUI_COMMAND(ll_incr, ">", "increase loglevel (decreases verbosity)") \
100 GUI_COMMAND(ll_decr, "<", "decrease loglevel (increases verbosity)") \
101 GUI_COMMAND(version, "V", "show the para_gui version") \
102 GUI_COMMAND(scroll_up, "<up>", "scroll up one line") \
103 GUI_COMMAND(scroll_down, "<down>", "scroll_down") \
104 GUI_COMMAND(page_up, "<ppage>", "scroll up one page") \
105 GUI_COMMAND(page_down, "<npage>", "scroll down one page") \
106 GUI_COMMAND(scroll_top, "<home>", "scroll to top of buffer") \
107 GUI_COMMAND(cancel_scroll, "<end>", "deactivate scroll mode") \
109 /* declare command handlers */
110 #define GUI_COMMAND(_c, _k, _d) \
111 static void com_ ## _c(void);
116 /* define command array */
117 #define GUI_COMMAND(_c, _k, _d) \
122 .handler = com_ ## _c \
125 static struct gui_command command_list[] = {GUI_COMMANDS {.name = NULL}};
136 struct timeval next_exec;
140 /** Stdout/stderr of the executing process is read in chunks of this size. */
141 #define COMMAND_BUF_SIZE 32768
145 char command_buf[2][COMMAND_BUF_SIZE]; /* stdout/stderr of command */
146 int cbo[2]; /* command buf offsets */
147 unsigned flags[2]; /* passed to for_each_line() */
150 static int find_cmd_byname(const char *name)
154 for (i = 0; command_list[i].handler; i++)
155 if (!strcmp(command_list[i].name, name))
161 * Even though ncurses provides getmaxx and getmaxy, these functions/macros are
162 * not described in the XSI Curses standard.
164 static int get_num_lines(struct gui_window *w)
167 __a_unused int cols; /* avoid "set but not used" warnings */
169 getmaxyx(w->win, lines, cols);
173 static int get_num_cols(struct gui_window *w)
175 __a_unused int lines; /* avoid "set but not used" warnings */
178 getmaxyx(w->win, lines, cols);
182 /** Number of lines of the window are occupied by an output line. */
183 #define NUM_LINES(len) (1 + (len) / get_num_cols(&bot))
185 /* isendwin() returns false before initscr() was called */
186 static bool curses_active(void)
188 return top.win && !isendwin();
191 /* taken from mutt */
192 static char *km_keyname(int c)
197 sprintf(buf, "<up>");
201 sprintf(buf, "<down>");
205 sprintf(buf, "<left>");
208 if (c == KEY_RIGHT) {
209 sprintf(buf, "<right>");
212 if (c == KEY_NPAGE) {
213 sprintf(buf, "<npage>");
216 if (c == KEY_PPAGE) {
217 sprintf(buf, "<ppage>");
221 sprintf(buf, "<home>");
225 sprintf(buf, "<end>");
228 if (c < 256 && c > -128 && iscntrl((unsigned char) c)) {
233 buf[1] = (c + '@') & 0x7f;
236 snprintf(buf, sizeof(buf), "\\%d%d%d", c >> 6,
237 (c >> 3) & 7, c & 7);
238 } else if (c >= KEY_F0 && c < KEY_F(256))
239 sprintf(buf, "<F%d>", c - KEY_F0);
241 snprintf(buf, sizeof(buf), "%c", (unsigned char) c);
243 snprintf(buf, sizeof(buf), "\\x%hx", (unsigned short) c);
247 /* Print given number of spaces to curses window. */
248 static void add_spaces(WINDOW* win, unsigned int num)
250 const char space[] = " ";
251 const unsigned sz = sizeof(space) - 1; /* number of spaces */
259 waddstr(win, space + sz - num);
264 * print aligned string to curses window. This function always prints
267 static int align_str(WINDOW* win, const char *str, unsigned int len,
270 int ret, num; /* of spaces */
272 char *sstr; /* sanitized string */
276 ret = sanitize_str(str, len, &sstr, &width);
278 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
280 sstr = para_strdup(NULL);
282 assert(width <= len);
286 add_spaces(win, num);
287 } else if (align == RIGHT) {
288 add_spaces(win, num);
291 add_spaces(win, num / 2);
293 add_spaces(win, num - num / 2);
299 static void refresh_window(struct gui_window *gw)
301 gw->needs_update = true;
304 static bool window_update_needed(void)
306 return top.needs_update || bot.needs_update || sb.needs_update ||
307 in.needs_update || sep.needs_update;
310 __printf_2_3 static void print_in_bar(int color, const char *fmt,...)
315 if (!curses_active())
317 wattron(in.win, COLOR_PAIR(color));
319 xvasprintf(&msg, fmt, ap);
322 align_str(in.win, msg, get_num_cols(&in), LEFT);
327 static void print_status_bar(void)
331 tmp = para_strdup("para_gui " PACKAGE_VERSION " (hit ? for help)");
333 align_str(sb.win, tmp, get_num_cols(&sb), CENTER);
338 * get the number of the oldest rbe that is (partially) visible. On return,
339 * lines contains the sum of the number of lines of all visible entries. If the
340 * first one is only partially visible, lines is greater than bot.lines.
342 static int first_visible_rbe(unsigned *lines)
344 int i, bot_lines = get_num_lines(&bot);
347 for (i = scroll_position; i < RINGBUFFER_SIZE; i++) {
348 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
352 rbe_lines = NUM_LINES(rbe->len);
353 if (rbe_lines > bot_lines)
356 if (*lines >= bot_lines)
359 return RINGBUFFER_SIZE - 1;
363 returns number of first visible rbe, *lines is the number of lines drawn.
365 static int draw_top_rbe(unsigned *lines)
367 int bot_cols, bot_lines, ret, fvr = first_visible_rbe(lines);
368 struct rb_entry *rbe;
369 size_t bytes_to_skip, cells_to_skip, width;
373 wmove(bot.win, 0, 0);
374 rbe = ringbuffer_get(bot_win_rb, fvr);
377 getmaxyx(bot.win, bot_lines, bot_cols);
378 if (*lines > bot_lines) {
379 /* rbe is partially visible multi-line */
380 cells_to_skip = (*lines - bot_lines) * bot_cols;
381 ret = skip_cells(rbe->msg, cells_to_skip, &bytes_to_skip);
384 ret = strwidth(rbe->msg + bytes_to_skip, &width);
391 wattron(bot.win, COLOR_PAIR(rbe->color));
392 waddstr(bot.win, rbe->msg + bytes_to_skip);
393 *lines = NUM_LINES(width);
397 static void redraw_bot_win(void)
400 int i, bot_lines = get_num_lines(&bot);
402 wmove(bot.win, 0, 0);
404 i = draw_top_rbe(&lines);
407 while (i > 0 && lines < bot_lines) {
408 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, --i);
411 waddstr(bot.win, "\n");
414 lines += NUM_LINES(rbe->len);
415 wattron(bot.win, COLOR_PAIR(rbe->color));
416 waddstr(bot.win, "\n");
417 waddstr(bot.win, rbe->msg);
420 refresh_window(&bot);
423 static void rb_add_entry(int color, char *msg)
425 struct rb_entry *old, *new;
429 if (strwidth(msg, &len) < 0)
431 new = para_malloc(sizeof(struct rb_entry));
435 old = ringbuffer_add(bot_win_rb, new);
440 if (scroll_position) {
441 /* discard current scrolling, like xterm does */
446 wattron(bot.win, COLOR_PAIR(color));
447 getyx(bot.win, y, x);
449 waddstr(bot.win, "\n");
450 waddstr(bot.win, msg);
454 * print formated output to bot win and refresh
456 __printf_2_3 static void outputf(int color, const char* fmt,...)
461 if (!curses_active())
464 xvasprintf(&msg, fmt, ap);
466 rb_add_entry(color, msg);
467 refresh_window(&bot);
470 static int add_output_line(char *line, void *data)
472 int color = *(int *)data? COLOR_ERRMSG : COLOR_OUTPUT;
474 if (!curses_active())
476 rb_add_entry(color, para_strdup(line));
480 static __printf_2_3 void curses_log(int ll, const char *fmt,...)
487 if (curses_active()) {
488 int color = ll <= LL_NOTICE? COLOR_MSG : COLOR_ERRMSG;
490 unsigned bytes = xvasprintf(&msg, fmt, ap);
491 if (bytes > 0 && msg[bytes - 1] == '\n')
492 msg[bytes - 1] = '\0'; /* cut trailing newline */
493 rb_add_entry(color, msg);
494 refresh_window(&bot);
495 } else if (exec_pid <= 0) /* no external command running */
496 vfprintf(stderr, fmt, ap);
499 /** The log function of para_gui, always set to curses_log(). */
500 __printf_2_3 void (*para_log)(int, const char*, ...) = curses_log;
502 /* Call endwin() to reset the terminal into non-visual mode. */
503 static void shutdown_curses(void)
506 * If para_gui received a terminating signal in external mode, the
507 * terminal can be in an unusable state at this point because the child
508 * process might not have caught the signal. In this case endwin() has
509 * already been called and must not be called again. So we first return
510 * to program mode, then call endwin().
512 if (!curses_active())
517 /* disable curses, print a message, kill running processes and exit */
518 __noreturn __printf_2_3 static void die(int exit_code, const char* fmt, ...)
522 /* Kill every process in our process group. */
523 para_sigaction(SIGTERM, SIG_IGN);
525 /* Wait up to two seconds for child processes to die. */
527 while (waitpid(0, NULL, 0) >= 0)
530 /* mousemask() exists only in ncurses */
531 #ifdef NCURSES_MOUSE_VERSION
532 mousemask(~(mmask_t)0, NULL); /* Avoid bad terminal state with xterm. */
536 vfprintf(stderr, fmt, argp);
542 * Print stat item #i to curses window
544 static void print_stat_item(int i)
547 struct stat_item_data d = theme.data[i];
548 char *c = stat_content[i];
549 int top_lines = get_num_lines(&top);
551 if (!curses_active() || !d.len || !c)
553 tmp = make_message("%s%s%s", d.prefix, c, d.postfix);
554 wmove(top.win, d.y * top_lines / 100, d.x * COLS / 100);
555 wattron(top.win, COLOR_PAIR(i + 1));
556 align_str(top.win, tmp, d.len * COLS / 100, d.align);
558 refresh_window(&top);
561 static int update_item(int item_num, char *buf)
563 char **c = stat_content + item_num;
570 *c = para_strdup("(artist tag not set)");
573 *c = para_strdup("(title tag not set)");
576 *c = para_strdup("????");
579 *c = para_strdup("(album tag not set)");
582 *c = para_strdup("(comment tag not set)");
586 *c = para_strdup(buf);
588 print_stat_item(item_num);
592 static void print_all_items(void)
596 if (!curses_active())
598 FOR_EACH_STATUS_ITEM(i)
602 static void clear_all_items(void)
606 FOR_EACH_STATUS_ITEM(i) {
607 free(stat_content[i]);
608 stat_content[i] = para_strdup("");
612 static void status_pre_select(struct sched *s, void *context)
614 struct status_task *st = context;
617 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
618 if (task_get_notification(st->task) < 0)
619 return sched_min_delay(s);
621 sched_request_barrier_or_min_delay(&st->next_exec, s);
624 static int status_post_select(struct sched *s, void *context)
626 struct status_task *st = context;
630 ret = task_get_notification(st->task);
631 if (ret == -E_GUI_SIGCHLD && st->pid > 0) {
633 if (waitpid(st->pid, &exit_status, WNOHANG) == st->pid) {
635 PARA_ERROR_LOG("stat command exit status: %d",
640 int fds[3] = {0, 1, 0};
643 /* Avoid busy loop */
644 if (tv_diff(&st->next_exec, now, NULL) > 0)
646 st->next_exec.tv_sec = now->tv_sec + 2;
647 ret = para_exec_cmdline_pid(&st->pid, conf.stat_cmd_arg, fds);
650 ret = mark_fd_nonblocking(fds[1]);
659 if (st->loaded >= st->bufsize) {
660 if (st->bufsize > 1000 * 1000) {
664 st->bufsize += st->bufsize + 1000;
665 st->buf = para_realloc(st->buf, st->bufsize);
667 assert(st->loaded < st->bufsize);
668 ret = read_nonblock(st->fd, st->buf + st->loaded,
669 st->bufsize - st->loaded, &s->rfds, &sz);
671 ret2 = for_each_stat_item(st->buf, st->loaded, update_item);
672 if (ret < 0 || ret2 < 0) {
674 PARA_NOTICE_LOG("closing stat pipe: %s\n",
675 para_strerror(ret < 0? -ret : -ret2));
679 free(stat_content[SI_BASENAME]);
680 stat_content[SI_BASENAME] =
681 para_strdup("stat command terminated!?");
685 sz = ret2; /* what is left */
686 if (sz > 0 && sz < st->loaded)
687 memmove(st->buf, st->buf + st->loaded - sz, sz);
695 static void init_wins(int top_lines)
697 int top_y = 0, bot_y = top_lines + 1, sb_y = LINES - 2,
698 in_y = LINES - 1, sep_y = top_lines;
699 int bot_lines = LINES - top_lines - 3, sb_lines = 1, in_lines = 1,
702 assume_default_colors(theme.dflt.fg, theme.dflt.bg);
704 wresize(top.win, top_lines, COLS);
705 mvwin(top.win, top_y, 0);
707 wresize(sb.win, sb_lines, COLS);
708 mvwin(sb.win, sb_y, 0);
710 wresize(sep.win, sep_lines, COLS);
711 mvwin(sep.win, sep_y, 0);
713 wresize(bot.win, bot_lines, COLS);
714 mvwin(bot.win, bot_y, 0);
716 wresize(in.win, in_lines, COLS);
717 mvwin(in.win, in_y, 0);
719 sep.win = newwin(sep_lines, COLS, sep_y, 0);
720 top.win = newwin(top_lines, COLS, top_y, 0);
721 bot.win = newwin(bot_lines, COLS, bot_y, 0);
722 sb.win = newwin(sb_lines, COLS, sb_y, 0);
723 in.win = newwin(in_lines, COLS, in_y, 0);
724 if (!top.win || !bot.win || !sb.win || !in.win || !sep.win)
725 die(EXIT_FAILURE, "Error: Cannot create curses windows\n");
729 scrollok(bot.win, 1);
730 wattron(sb.win, COLOR_PAIR(COLOR_STATUSBAR));
731 wattron(sep.win, COLOR_PAIR(COLOR_SEPARATOR));
732 wattron(bot.win, COLOR_PAIR(COLOR_BOT));
733 wattron(top.win, COLOR_PAIR(COLOR_TOP));
744 wmove(sep.win, 0, 0);
745 whline(sep.win, theme.sep_char, COLS);
749 wnoutrefresh(top.win);
750 wnoutrefresh(bot.win);
752 wnoutrefresh(sb.win);
753 wnoutrefresh(in.win);
754 wnoutrefresh(sep.win);
758 static void init_pair_or_die(short pair, short f, short b)
760 if (init_pair(pair, f, b) == ERR)
761 die(EXIT_FAILURE, "fatal: init_pair() failed\n");
764 static void init_colors_or_die(void)
769 die(EXIT_FAILURE, "fatal: No color term\n");
770 if (start_color() == ERR)
771 die(EXIT_FAILURE, "fatal: failed to start colors\n");
772 FOR_EACH_STATUS_ITEM(i)
773 if (theme.data[i].len)
774 init_pair_or_die(i + 1, theme.data[i].color.fg,
775 theme.data[i].color.bg);
776 init_pair_or_die(COLOR_STATUSBAR, theme.sb.fg, theme.sb.bg);
777 init_pair_or_die(COLOR_COMMAND, theme.cmd.fg, theme.cmd.bg);
778 init_pair_or_die(COLOR_OUTPUT, theme.output.fg, theme.output.bg);
779 init_pair_or_die(COLOR_MSG, theme.msg.fg, theme.msg.bg);
780 init_pair_or_die(COLOR_ERRMSG, theme.err_msg.fg, theme.err_msg.bg);
781 init_pair_or_die(COLOR_SEPARATOR, theme.sep.fg, theme.sep.bg);
782 init_pair_or_die(COLOR_TOP, theme.dflt.fg, theme.dflt.bg);
783 init_pair_or_die(COLOR_BOT, theme.dflt.fg, theme.dflt.bg);
786 /* (Re-)initialize the curses library. */
787 static void init_curses(void)
791 if (refresh() == ERR) /* refresh is really needed */
792 die(EXIT_FAILURE, "refresh() failed\n");
793 if (LINES < theme.lines_min || COLS < theme.cols_min)
794 die(EXIT_FAILURE, "Terminal (%dx%d) too small"
795 " (need at least %dx%d)\n", COLS, LINES,
796 theme.cols_min, theme.lines_min);
797 curs_set(0); /* make cursor invisible, ignore errors */
798 nonl(); /* do not NL->CR/NL on output, always returns OK */
799 /* don't echo input */
801 die(EXIT_FAILURE, "fatal: noecho() failed\n");
802 /* take input chars one at a time, no wait for \n */
804 die(EXIT_FAILURE, "fatal: cbreak() failed\n");
805 init_colors_or_die();
806 clear(); /* ignore non-fatal errors */
807 init_wins(theme.top_lines_default);
808 // noecho(); /* don't echo input */
812 * This sucker modifies its first argument. *handler and *arg are
813 * pointers to 0-terminated strings (inside line). Crap.
815 static int split_key_map(char *line, char **handler, char **arg)
817 if (!(*handler = strchr(line + 1, ':')))
821 if (!(*arg = strchr(*handler, ':')))
830 static void check_key_map_args_or_die(void)
835 for (i = 0; i < conf.key_map_given; ++i) {
839 tmp = para_strdup(conf.key_map_arg[i]);
840 if (!split_key_map(tmp, &handler, &arg))
842 if (strlen(handler) != 1)
844 if (*handler != 'x' && *handler != 'd' && *handler != 'i'
849 if (find_cmd_byname(arg) < 0)
852 if (i != conf.key_map_given)
853 die(EXIT_FAILURE, "invalid key map: %s\n", conf.key_map_arg[i]);
857 static void parse_config_file_or_die(bool override)
861 struct gui_cmdline_parser_params params = {
862 .override = override,
864 .check_required = !override,
865 .check_ambiguity = 0,
869 if (conf.config_file_given)
870 config_file = para_strdup(conf.config_file_arg);
872 char *home = para_homedir();
873 config_file = make_message("%s/.paraslash/gui.conf", home);
876 if (!file_exists(config_file)) {
877 if (!conf.config_file_given)
880 PARA_EMERG_LOG("config file %s does not exist\n",
887 * When the gengetopt config file parser is called more than once, any
888 * key map arguments found in the config file are _appended_ to the old
889 * values, even though we turn on ->override. We want the new arguments
890 * to replace the old ones, so we must empty the key_map_arg array
891 * first. Unfortunately, this also clears any key map arguments given
892 * at the command line.
896 for (i = 0; i < conf.key_map_given; i++) {
897 free(conf.key_map_arg[i]);
898 conf.key_map_arg[i] = NULL;
900 conf.key_map_given = 0;
903 gui_cmdline_parser_config_file(config_file, &conf, ¶ms);
904 loglevel = get_loglevel_by_name(conf.loglevel_arg);
905 check_key_map_args_or_die();
911 theme_init(conf.theme_arg, &theme);
914 /* reread configuration, terminate on errors */
915 static void reread_conf(void)
918 * gengetopt might print to stderr and exit on errors. So we have to
919 * shutdown curses first.
922 parse_config_file_or_die(true /* override */);
924 print_in_bar(COLOR_MSG, "config file reloaded\n");
928 * React to various signal-related events
930 static int signal_post_select(struct sched *s, __a_unused void *context)
932 int ret = para_next_signal(&s->rfds);
938 die(EXIT_FAILURE, "only the good die young (caught SIGTERM)\n");
942 PARA_NOTICE_LOG("got SIGUSR1, rereading configuration\n");
946 task_notify_all(s, E_GUI_SIGCHLD);
952 static enum exec_status exec_status(void)
954 if (exec_fds[0] >= 0 || exec_fds[1] >= 0)
961 static void exec_pre_select(struct sched *s, void *context)
963 struct exec_task *et = context;
964 if (exec_fds[0] >= 0)
965 para_fd_set(exec_fds[0], &s->rfds, &s->max_fileno);
966 if (exec_fds[1] >= 0)
967 para_fd_set(exec_fds[1], &s->rfds, &s->max_fileno);
968 if (task_get_notification(et->task) < 0)
972 static int exec_post_select(struct sched *s, void *context)
974 struct exec_task *ct = context;
977 ret = task_get_notification(ct->task);
978 if (ret == -E_GUI_SIGCHLD && exec_pid > 0) {
980 if (waitpid(exec_pid, &exit_status, WNOHANG) == exec_pid) {
983 PARA_INFO_LOG("command exit status: %d", exit_status);
984 print_in_bar(COLOR_MSG, " ");
987 for (i = 0; i < 2; i++) {
991 ret = read_nonblock(exec_fds[i],
992 ct->command_buf[i] + ct->cbo[i],
993 COMMAND_BUF_SIZE - 1 - ct->cbo[i], &s->rfds, &sz);
996 ct->cbo[i] = for_each_line(ct->flags[i], ct->command_buf[i],
997 ct->cbo[i], add_output_line, &i);
998 if (sz != ct->cbo[i]) { /* at least one line found */
999 refresh_window(&bot);
1002 if (ret < 0 || exec_pid == 0) {
1004 PARA_NOTICE_LOG("closing command fd %d: %s",
1005 i, para_strerror(-ret));
1010 if (exec_fds[!i] < 0) /* both fds closed */
1013 if (ct->cbo[i] == COMMAND_BUF_SIZE - 1) {
1014 PARA_NOTICE_LOG("discarding overlong line");
1016 ct->flags[i] = FELF_DISCARD_FIRST;
1022 static void input_pre_select(struct sched *s, __a_unused void *context)
1024 if (exec_status() != EXEC_XCMD)
1025 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1026 if (window_update_needed())
1030 /* read from command pipe and print data to bot window */
1031 static void exec_and_display(const char *file_and_args)
1033 int ret, fds[3] = {0, 1, 1};
1035 outputf(COLOR_COMMAND, "%s", file_and_args);
1036 ret = para_exec_cmdline_pid(&exec_pid, file_and_args, fds);
1039 ret = mark_fd_nonblocking(fds[1]);
1042 ret = mark_fd_nonblocking(fds[2]);
1045 exec_fds[0] = fds[1];
1046 exec_fds[1] = fds[2];
1047 print_in_bar(COLOR_MSG, "hit any key to abort\n");
1050 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1055 static void exec_para(const char *args)
1057 char *file_and_args;
1059 file_and_args = make_message(BINDIR "/para_client -- %s", args);
1060 exec_and_display(file_and_args);
1061 free(file_and_args);
1065 * shutdown curses and stat pipe before executing external commands
1067 static void exec_external(char *file_and_args)
1069 int fds[3] = {-1, -1, -1};
1074 para_exec_cmdline_pid(&exec_pid, file_and_args, fds);
1077 static void handle_command(int c)
1081 /* first check user-defined key bindings */
1082 for (i = 0; i < conf.key_map_given; ++i) {
1083 char *tmp, *handler, *arg;
1085 tmp = para_strdup(conf.key_map_arg[i]);
1086 if (!split_key_map(tmp, &handler, &arg)) {
1090 if (strcmp(tmp, km_keyname(c))) {
1094 if (*handler == 'd')
1095 exec_and_display(arg);
1096 else if (*handler == 'x')
1098 else if (*handler == 'p')
1100 else if (*handler == 'i') {
1101 int num = find_cmd_byname(arg);
1103 command_list[num].handler();
1108 /* not found, check internal key bindings */
1109 for (i = 0; command_list[i].handler; i++) {
1110 if (!strcmp(km_keyname(c), command_list[i].key)) {
1111 command_list[i].handler();
1115 print_in_bar(COLOR_ERRMSG, "key '%s' is not bound, press ? for help",
1119 static int input_post_select(__a_unused struct sched *s, __a_unused void *context)
1122 enum exec_status exs = exec_status();
1124 if (exs == EXEC_XCMD)
1126 if (window_update_needed()) {
1127 if (top.needs_update)
1128 assert(wnoutrefresh(top.win) == OK);
1129 if (bot.needs_update)
1130 assert(wnoutrefresh(bot.win) == OK);
1131 if (sep.needs_update)
1132 assert(wnoutrefresh(sep.win) == OK);
1133 if (sb.needs_update)
1134 assert(wnoutrefresh(sb.win) == OK);
1135 if (in.needs_update)
1136 assert(wnoutrefresh(in.win) == OK);
1138 top.needs_update = bot.needs_update = sb.needs_update =
1139 in.needs_update = sep.needs_update = false;
1141 ret = wgetch(top.win);
1144 if (ret == KEY_RESIZE) {
1145 if (curses_active()) {
1152 if (exs == EXEC_IDLE)
1153 handle_command(ret);
1154 else if (exec_pid > 0)
1155 kill(exec_pid, SIGTERM);
1159 static void print_scroll_msg(void)
1161 unsigned lines_total, filled = ringbuffer_filled(bot_win_rb);
1162 int first_rbe = first_visible_rbe(&lines_total);
1164 print_in_bar(COLOR_MSG, "scrolled view: %u-%u/%u\n", filled - first_rbe,
1165 filled - scroll_position, ringbuffer_filled(bot_win_rb));
1168 static void com_scroll_top(void)
1170 int i = RINGBUFFER_SIZE - 1, bot_lines = get_num_lines(&bot);
1173 while (i > 0 && !ringbuffer_get(bot_win_rb, i))
1175 /* i is oldest entry */
1176 for (; lines < bot_lines && i >= 0; i--) {
1177 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
1180 lines += NUM_LINES(rbe->len);
1183 if (lines > 0 && scroll_position != i) {
1184 scroll_position = i;
1189 print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1192 static void com_cancel_scroll(void)
1195 if (scroll_position == 0) {
1196 print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1199 scroll_position = 0;
1203 static void com_page_down(void)
1206 int i = scroll_position, bot_lines = get_num_lines(&bot);
1208 while (lines < bot_lines && --i > 0) {
1209 struct rb_entry *rbe = ringbuffer_get(bot_win_rb, i);
1212 lines += NUM_LINES(rbe->len);
1215 scroll_position = i;
1220 print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1223 static void com_page_up(void)
1226 int fvr = first_visible_rbe(&lines), bot_lines = get_num_lines(&bot);
1228 if (fvr < 0 || fvr + 1 >= ringbuffer_filled(bot_win_rb)) {
1229 print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1232 scroll_position = fvr + 1;
1233 for (; scroll_position > 0; scroll_position--) {
1234 first_visible_rbe(&lines);
1235 if (lines == bot_lines)
1242 static void com_scroll_down(void)
1244 struct rb_entry *rbe;
1245 int rbe_lines, bot_lines = get_num_lines(&bot);
1247 if (!scroll_position) {
1248 print_in_bar(COLOR_ERRMSG, "bottom of buffer is shown\n");
1252 rbe = ringbuffer_get(bot_win_rb, scroll_position);
1253 rbe_lines = NUM_LINES(rbe->len);
1254 wscrl(bot.win, rbe_lines);
1255 wmove(bot.win, bot_lines - rbe_lines, 0);
1256 wattron(bot.win, COLOR_PAIR(rbe->color));
1257 waddstr(bot.win, rbe->msg);
1258 refresh_window(&bot);
1262 static void com_scroll_up(void)
1264 struct rb_entry *rbe = NULL;
1266 int i, first_rbe, num_scroll;
1268 /* the entry that is going to vanish */
1269 rbe = ringbuffer_get(bot_win_rb, scroll_position);
1272 num_scroll = NUM_LINES(rbe->len);
1273 first_rbe = first_visible_rbe(&lines);
1274 if (first_rbe < 0 || (first_rbe == ringbuffer_filled(bot_win_rb) - 1))
1277 wscrl(bot.win, -num_scroll);
1278 i = draw_top_rbe(&lines);
1281 while (i > 0 && lines < num_scroll) {
1283 rbe = ringbuffer_get(bot_win_rb, --i);
1286 rbe_lines = NUM_LINES(rbe->len);
1288 wattron(bot.win, COLOR_PAIR(rbe->color));
1289 waddstr(bot.win, "\n");
1290 waddstr(bot.win, rbe->msg);
1295 refresh_window(&bot);
1299 print_in_bar(COLOR_ERRMSG, "top of buffer is shown\n");
1302 static void com_ll_decr(void)
1304 if (loglevel <= LL_DEBUG) {
1305 print_in_bar(COLOR_ERRMSG,
1306 "loglevel already at maximal verbosity\n");
1310 print_in_bar(COLOR_MSG, "loglevel set to %d\n", loglevel);
1313 static void com_ll_incr(void)
1315 if (loglevel >= LL_EMERG) {
1316 print_in_bar(COLOR_ERRMSG,
1317 "loglevel already at minimal verbosity\n");
1321 print_in_bar(COLOR_MSG, "loglevel set to %d\n", loglevel);
1324 static void com_reread_conf(void)
1329 static void com_help(void)
1333 for (i = 0; i < conf.key_map_given; ++i) {
1334 char *handler, *arg, *tmp = para_strdup(conf.key_map_arg[i]);
1335 const char *handler_text = "???", *desc = NULL;
1337 if (!split_key_map(tmp, &handler, &arg)) {
1343 handler_text = "internal";
1344 desc = command_list[find_cmd_byname(arg)].description;
1346 case 'x': handler_text = "external"; break;
1347 case 'd': handler_text = "display "; break;
1348 case 'p': handler_text = "para "; break;
1350 outputf(COLOR_MSG, "%s\t%s\t%s%s\t%s", tmp, handler_text, arg,
1351 strlen(arg) < 8? "\t" : "",
1355 for (i = 0; command_list[i].handler; i++) {
1356 struct gui_command gc = command_list[i];
1358 outputf(COLOR_MSG, "%s\tinternal\t%s\t%s%s", gc.key, gc.name,
1359 strlen(gc.name) < 8? "\t" : "",
1362 print_in_bar(COLOR_MSG, "try \"para_gui -h\" or \"para_client help\" "
1366 static void com_shrink_top_win(void)
1368 int top_lines = get_num_lines(&top);
1370 if (top_lines <= theme.top_lines_min) {
1371 PARA_WARNING_LOG("can not decrease top window\n");
1374 init_wins(top_lines - 1);
1375 print_in_bar(COLOR_MSG, "%s", "decreased top window");
1378 static void com_enlarge_top_win(void)
1380 int top_lines = get_num_lines(&top), bot_lines = get_num_lines(&bot);
1382 if (bot_lines < 3) {
1383 PARA_WARNING_LOG("can not increase top window\n");
1386 init_wins(top_lines + 1);
1387 print_in_bar(COLOR_MSG, "increased top window");
1390 static void com_version(void)
1392 print_in_bar(COLOR_MSG, "%s", version_single_line("gui"));
1395 __noreturn static void com_quit(void)
1397 die(EXIT_SUCCESS, "%s", "");
1400 static void com_refresh(void)
1406 static void com_next_theme(void)
1412 static void com_prev_theme(void)
1418 __noreturn static void print_help_and_die(void)
1420 struct ggo_help h = DEFINE_GGO_HELP(gui);
1421 bool d = conf.detailed_help_given;
1423 ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
1427 static int setup_tasks_and_schedule(void)
1430 struct exec_task exec_task = {.task = NULL};
1431 struct status_task status_task = {.fd = -1};
1432 struct input_task input_task = {.task = NULL};
1433 struct signal_task *signal_task;
1434 struct sched sched = {
1435 .default_timeout = {
1436 .tv_sec = conf.timeout_arg / 1000,
1437 .tv_usec = (conf.timeout_arg % 1000) * 1000,
1441 exec_task.task = task_register(&(struct task_info) {
1443 .pre_select = exec_pre_select,
1444 .post_select = exec_post_select,
1445 .context = &exec_task,
1448 status_task.task = task_register(&(struct task_info) {
1450 .pre_select = status_pre_select,
1451 .post_select = status_post_select,
1452 .context = &status_task,
1455 input_task.task = task_register(&(struct task_info) {
1457 .pre_select = input_pre_select,
1458 .post_select = input_post_select,
1459 .context = &input_task,
1462 signal_task = signal_init_or_die();
1463 para_install_sighandler(SIGINT);
1464 para_install_sighandler(SIGTERM);
1465 para_install_sighandler(SIGCHLD);
1466 para_install_sighandler(SIGUSR1);
1467 signal_task->task = task_register(&(struct task_info) {
1469 .pre_select = signal_pre_select,
1470 .post_select = signal_post_select,
1471 .context = signal_task,
1473 ret = schedule(&sched);
1474 sched_shutdown(&sched);
1475 signal_shutdown(signal_task);
1480 * The main function of para_gui.
1482 * \param argc Usual argument count.
1483 * \param argv Usual argument vector.
1485 * After initialization para_gui registers the following tasks to the paraslash
1486 * scheduler: status, exec, signal, input.
1488 * The status task executes the para_audioc stat command to obtain the status
1489 * of para_server and para_audiod, and displays this information in the top
1490 * window of para_gui.
1492 * The exec task is responsible for printing the output of the currently
1493 * running executable to the bottom window.
1495 * The signal task performs various actions according to signals received. For
1496 * example, it reloads the configuration file on SIGUSR1, and it shuts down the
1497 * curses system on SIGTERM to restore the terminal settings before exit.
1499 * The input task reads single key strokes from stdin. For each key pressed, it
1500 * executes the command handler associated with this key.
1502 * \return \p EXIT_SUCCESS or \p EXIT_FAILURE.
1504 int main(int argc, char *argv[])
1506 gui_cmdline_parser(argc, argv, &conf); /* exits on errors */
1507 loglevel = get_loglevel_by_name(conf.loglevel_arg);
1508 version_handle_flag("gui", conf.version_given);
1509 if (conf.help_given || conf.detailed_help_given)
1510 print_help_and_die();
1511 parse_config_file_or_die(false /* override */);
1512 bot_win_rb = ringbuffer_new(RINGBUFFER_SIZE);
1513 setlocale(LC_CTYPE, "");
1514 initscr(); /* needed only once, always successful */
1516 return setup_tasks_and_schedule() < 0? EXIT_FAILURE : EXIT_SUCCESS;