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