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