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