Event better: have an ACS_HLINE to erase status line.
[apps/madmutt.git] / lib-ui / curs_lib.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 2004 g10 Code GmbH
5  *
6  * Parts were written/modified by:
7  * Nico Golde <nico@ngolde.de>
8  *
9  * This file is part of mutt-ng, see http://www.muttng.org/.
10  * It's licensed under the GNU General Public License,
11  * please see the file GPL in the top level source directory.
12  */
13
14 #include <lib-ui/lib-ui.h>
15
16 #include <langinfo.h>
17 #include <termios.h>
18
19 #include <lib-lua/lib-lua.h>
20 #include <lib-sys/unix.h>
21 #include <lib-sys/mutt_signal.h>
22
23 #include "menu.h"
24 #include "enter.h"
25
26 #include "mutt.h"
27 #include "pager.h"
28 #include "charset.h"
29 #include "madtty.h"
30
31 /* not possible to unget more than one char under some curses libs, and it
32  * is impossible to unget function keys in SLang, so roll our own input
33  * buffering routines.
34  */
35 ssize_t UngetCount = 0;
36 static ssize_t UngetBufLen = 0;
37 static event_t *KeyEvent;
38
39 event_t mutt_getch (void)
40 {
41   int ch;
42   event_t err = { -1, OP_NULL }, ret;
43
44   if (!option (OPTUNBUFFEREDINPUT) && UngetCount)
45     return (KeyEvent[--UngetCount]);
46
47   SigInt = 0;
48
49   mutt_allow_interrupt (1);
50   ch = getch();
51   mutt_allow_interrupt (0);
52
53   if (SigInt)
54     mutt_query_exit ();
55
56   if (ch == ERR)
57     return err;
58
59   ret.ch = ch;
60   ret.op = 0;
61   return (ch == ctrl ('G') ? err : ret);
62 }
63
64 #ifndef waddnwstr
65 int waddwch(WINDOW *win, wchar_t wc)
66 {
67     char buf[MB_LEN_MAX * 2];
68     mbstate_t mbstate;
69     ssize_t n1, n2;
70
71     p_clear(&mbstate, 1);
72     if ((n1 = wcrtomb(buf, wc, &mbstate)) == -1
73     ||  (n2 = wcrtomb(buf + n1, 0, &mbstate)) == -1)
74         return -1;                  /* ERR */
75     return waddstr(win, buf);
76 }
77 #endif
78
79
80 int _mutt_get_field ( const char *field, char *buf, ssize_t buflen,
81                      int complete, int multiple, char ***files, int *numfiles)
82 {
83   int ret;
84   int x, y;
85
86   ENTER_STATE *es = mutt_new_enter_state ();
87
88   do {
89     CLEARLINE(stdscr, LINES - 1);
90     waddstr (stdscr, field);
91     mutt_refresh ();
92     getyx (stdscr, y, x);
93     ret = _mutt_enter_string(buf, buflen, y, x, complete, multiple, files,
94                              numfiles, es);
95   } while (ret == 1);
96   CLEARLINE(stdscr, LINES - 1);
97   mutt_free_enter_state (&es);
98
99   return (ret);
100 }
101
102 int mutt_get_field_unbuffered (char *msg, char *buf, ssize_t buflen, int flags)
103 {
104   int rc;
105
106   set_option (OPTUNBUFFEREDINPUT);
107   rc = mutt_get_field (msg, buf, buflen, flags);
108   unset_option (OPTUNBUFFEREDINPUT);
109
110   return (rc);
111 }
112
113 void mutt_clear_error (void)
114 {
115   Errorbuf[0] = 0;
116   if (!option (OPTNOCURSES))
117     CLEARLINE(stdscr, LINES - 1);
118 }
119
120 static struct timeval const slice = { 0, 1000 * 1000 / 100 };
121 static struct timeval timeval_add(struct timeval a, struct timeval b)
122 {
123     int usec = a.tv_usec + b.tv_usec;
124     a.tv_sec += b.tv_sec;
125     while (usec > 1000 * 1000) {
126         a.tv_sec += 1;
127         usec -= 1000 * 1000;
128     }
129     a.tv_usec = usec;
130     return a;
131 }
132
133 static int is_expired(struct timeval now, struct timeval expiry)
134 {
135     return now.tv_sec > expiry.tv_sec
136         || (now.tv_sec == expiry.tv_sec && now.tv_usec > expiry.tv_usec);
137 }
138
139 void mutt_edit_file(const char *data)
140 {
141     char cmd[STRING];
142     const char *args[] = { "/bin/sh", "-c", cmd, NULL };
143     int dirty = 0, ch, res, mh, mw, pty, pid;
144     struct timeval next;
145     madtty_t *rt;
146
147     m_quotefile_fmt(cmd, sizeof(cmd), mod_core.editor, data);
148     getmaxyx(main_w, mh, mw);
149     SigChild = 0;
150
151     rt = madtty_create(mh - 2, mw);
152     pid = madtty_forkpty(rt, args[0], args, &pty);
153     if (pid < 0) {
154         madtty_destroy(rt);
155         mutt_error(_("unable to start editor"));
156         return;
157     }
158
159     SETCOLOR(main_w, MT_COLOR_SIDEBAR);
160     mvwhline(main_w, 0, 0, ACS_HLINE, mw);
161
162     nodelay(stdscr, true);
163     gettimeofday(&next, NULL);
164     while (!SigChild) {
165         struct timeval tv = { 0, 1000 * 1000 / 100 };
166         fd_set rfds;
167
168         FD_ZERO(&rfds);
169         FD_SET(0, &rfds);
170         FD_SET(pty, &rfds);
171
172         if (select(pty + 1, &rfds, NULL, NULL, &tv) < 0)
173             break;
174
175         if (FD_ISSET(pty, &rfds)) {
176             madtty_process(rt);
177             dirty = 1;
178         }
179
180         while ((ch = getch()) != ERR) {
181             madtty_keypress(rt, ch); /* pass the keypress for handling */
182             dirty = 1;
183         }
184
185         gettimeofday(&tv, NULL);
186         if (dirty && is_expired(tv, next)) {
187             madtty_draw(rt, main_w, 1, 0);
188             wrefresh(main_w);
189             dirty = 0;
190             next = timeval_add(tv, slice);
191         }
192     }
193     while (waitpid(pid, &res, 0) < 0 && errno == EINTR);
194     nodelay(stdscr, false);
195     close(pty);
196     madtty_destroy(rt);
197 }
198
199 int mutt_yesorno (const char *msg, int def)
200 {
201   event_t ch;
202   const char *yes = _("yes");
203   const char *no = _("no");
204   char *answer_string;
205   ssize_t answer_string_len;
206   char *expr;
207   regex_t reyes;
208   regex_t reno;
209   int reyes_ok;
210   int reno_ok;
211   char answer[2];
212
213   answer[1] = 0;
214
215   reyes_ok = (expr = nl_langinfo (YESEXPR)) && expr[0] == '^' &&
216     !regcomp (&reyes, expr, REG_NOSUB | REG_EXTENDED);
217   reno_ok = (expr = nl_langinfo (NOEXPR)) && expr[0] == '^' &&
218     !regcomp (&reno, expr, REG_NOSUB | REG_EXTENDED);
219
220   CLEARLINE(stdscr, LINES - 1);
221
222   /*
223    * In order to prevent the default answer to the question to wrapped
224    * around the screen in the even the question is wider than the screen,
225    * ensure there is enough room for the answer and truncate the question
226    * to fit.
227    */
228   answer_string = p_new(char, getmaxx(stdscr) + 1);
229   snprintf (answer_string, getmaxx(stdscr) + 1, " ([%s]/%s): ", def == M_YES ? yes : no,
230             def == M_YES ? no : yes);
231   answer_string_len = m_strlen(answer_string);
232   wprintw (stdscr, "%.*s%s", getmaxx(stdscr) - answer_string_len, msg, answer_string);
233   p_delete(&answer_string);
234
235   for (;;) {
236     mutt_refresh ();
237     ch = mutt_getch ();
238     if (CI_is_return (ch.ch))
239       break;
240     if (ch.ch == -1) {
241       def = -1;
242       break;
243     }
244
245     answer[0] = ch.ch;
246     if (reyes_ok ? (regexec (&reyes, answer, 0, 0, 0) == 0) : tolower (ch.ch) == *yes)
247     {
248       def = M_YES;
249       break;
250     }
251     else if (
252               reno_ok ? (regexec (&reno, answer, 0, 0, 0) == 0) :
253               (tolower (ch.ch) == *no)) {
254       def = M_NO;
255       break;
256     } else {
257       BEEP ();
258     }
259   }
260
261   if (reyes_ok)
262     regfree (&reyes);
263   if (reno_ok)
264     regfree (&reno);
265
266   if (def != -1) {
267     waddstr (stdscr, (char *) (def == M_YES ? yes : no));
268     mutt_refresh ();
269   }
270   CLEARLINE(stdscr, LINES - 1);
271   return (def);
272 }
273
274 /* this function is called when the user presses the abort key */
275 void mutt_query_exit (void)
276 {
277   mutt_flushinp ();
278   curs_set (1);
279   if (Timeout)
280     wtimeout (stdscr, -1);               /* restore blocking operation */
281   if (mutt_yesorno (_("Exit Madmutt?"), M_YES) == M_YES) {
282     mutt_endwin (NULL);
283     mutt_exit(1);
284   }
285   mutt_clear_error ();
286   mutt_curs_set (-1);
287   SigInt = 0;
288 }
289
290 void mutt_curses_error (const char *fmt, ...)
291 {
292   char TmpErrorbuf[STRING];
293   va_list ap;
294
295   va_start (ap, fmt);
296   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
297   va_end (ap);
298
299   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
300                       0, getmaxy(stdscr) - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
301   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
302
303   if (!option (OPTKEEPQUIET)) {
304     BEEP ();
305     SETCOLOR(stdscr, MT_COLOR_ERROR);
306     mvwaddstr (stdscr, LINES - 1, 0, Errorbuf);
307     wclrtoeol (stdscr);
308     SETCOLOR(stdscr, MT_COLOR_NORMAL);
309     mutt_refresh ();
310   }
311
312   set_option (OPTMSGERR);
313 }
314
315 void mutt_progress_bar (progress_t* progress, long pos) {
316   char posstr[STRING];
317
318   if (!pos) {
319     if (!NetInc)
320       mutt_message (progress->msg);
321     else {
322       if (progress->size)
323         mutt_pretty_size (progress->sizestr, sizeof (progress->sizestr),
324                           progress->size);
325       progress->pos = 0;
326     }
327   }
328
329   if (!NetInc)
330     return;
331
332   if (pos >= progress->pos + (NetInc << 10)) {
333     progress->pos = pos;
334     pos = pos / (NetInc << 10) * (NetInc << 10);
335     mutt_pretty_size (posstr, sizeof (posstr), pos);
336     if (progress->size)
337       mutt_message ("%s %s/%s", progress->msg, posstr, progress->sizestr);
338     else
339       mutt_message ("%s %s", progress->msg, posstr);
340   }
341 }
342
343 void mutt_curses_message (const char *fmt, ...)
344 {
345   char TmpErrorbuf[STRING];
346   va_list ap;
347
348   va_start (ap, fmt);
349   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
350   va_end (ap);
351
352   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
353                       0, getmaxx(stdscr) - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
354   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
355
356   if (!option (OPTKEEPQUIET)) {
357     SETCOLOR(stdscr, MT_COLOR_MESSAGE);
358     mvwaddstr (stdscr, LINES - 1, 0, Errorbuf);
359     wclrtoeol (stdscr);
360     SETCOLOR(stdscr, MT_COLOR_NORMAL);
361     mutt_refresh ();
362   }
363
364   unset_option (OPTMSGERR);
365 }
366
367 void mutt_show_error (void)
368 {
369   if (option (OPTKEEPQUIET))
370     return;
371
372   SETCOLOR(stdscr, option (OPTMSGERR) ? MT_COLOR_ERROR : MT_COLOR_MESSAGE);
373   CLEARLINE(stdscr, LINES - 1);
374   waddstr (stdscr, Errorbuf);
375   SETCOLOR(stdscr, MT_COLOR_NORMAL);
376 }
377
378 void curses_initialize(void)
379 {
380     initscr();
381     if (start_color() == ERR || !has_colors() || COLORS < 8)
382         mutt_exit(-1);
383     madtty_init_colors();
384     ci_start_color();
385     noecho();
386     raw();
387     keypad(stdscr, true);
388     typeahead(-1);
389     meta(stdscr, true);
390     curs_set(0);
391     ESCDELAY = 50;
392 }
393
394 int mutt_any_key_to_continue (const char *s)
395 {
396   struct termios t;
397   struct termios old;
398   int f, ch;
399
400   f = open ("/dev/tty", O_RDONLY);
401   tcgetattr (f, &t);
402   memcpy ((void *) &old, (void *) &t, sizeof (struct termios)); /* save original state */
403   t.c_lflag &= ~(ICANON | ECHO);
404   t.c_cc[VMIN] = 1;
405   t.c_cc[VTIME] = 0;
406   tcsetattr (f, TCSADRAIN, &t);
407   fflush (stdout);
408   if (s)
409     fputs (s, stdout);
410   else
411     fputs (_("Press any key to continue..."), stdout);
412   fflush (stdout);
413   ch = fgetc (stdin);
414   fflush (stdin);
415   tcsetattr (f, TCSADRAIN, &old);
416   close (f);
417   fputs ("\r\n", stdout);
418   mutt_clear_error ();
419   return (ch);
420 }
421
422 int _mutt_enter_fname (const char *prompt, char *buf, ssize_t blen,
423                        int *redraw, int buffy, int multiple, char ***files,
424                        int *numfiles)
425 {
426   event_t ch;
427
428   mvwaddstr(stdscr, LINES - 1, 0, (char *) prompt);
429   waddstr(stdscr, _(" ('?' for list): "));
430   if (buf[0])
431     waddstr (stdscr, buf);
432   wclrtoeol (stdscr);
433   mutt_refresh ();
434
435   ch = mutt_getch ();
436   if (ch.ch == -1) {
437     CLEARLINE(stdscr, LINES - 1);
438     return (-1);
439   }
440   else if (ch.ch == '?') {
441     mutt_refresh ();
442     buf[0] = 0;
443     mutt_select_file (buf, blen, M_SEL_FOLDER | (multiple ? M_SEL_MULTI : 0),
444                       files, numfiles);
445     *redraw = REDRAW_FULL;
446   }
447   else {
448     char *pc = p_new(char, m_strlen(prompt) + 3);
449
450     sprintf(pc, "%s: ", prompt);
451     mutt_ungetch (ch.op ? 0 : ch.ch, ch.op ? ch.op : 0);
452     if (_mutt_get_field
453         (pc, buf, blen, (buffy ? M_EFILE : M_FILE) | M_CLEAR, multiple, files,
454          numfiles)
455         != 0)
456       buf[0] = 0;
457     MAYBE_REDRAW (*redraw);
458     p_delete(&pc);
459   }
460
461   return 0;
462 }
463
464 void mutt_ungetch (int ch, int op)
465 {
466   event_t tmp;
467
468   tmp.ch = ch;
469   tmp.op = op;
470
471   if (UngetCount >= UngetBufLen)
472     p_realloc(&KeyEvent, UngetBufLen += 128);
473
474   KeyEvent[UngetCount++] = tmp;
475 }
476
477 void mutt_flushinp (void)
478 {
479   UngetCount = 0;
480   flushinp ();
481 }
482
483 /* The argument can take 3 values:
484  * -1: restore the value of the last call
485  *  0: make the cursor invisible
486  *  1: make the cursor visible
487  */
488 void mutt_curs_set (int cursor)
489 {
490   static int SavedCursor = 1;
491
492   if (cursor < 0)
493     cursor = SavedCursor;
494   else
495     SavedCursor = cursor;
496
497   if (curs_set (cursor) == ERR) {
498     if (cursor == 1)            /* cnorm */
499       curs_set (2);             /* cvvis */
500   }
501 }
502
503 int mutt_multi_choice (const char *prompt, const char *letters)
504 {
505   event_t ch;
506   int choice;
507   char *p;
508
509   mvwaddstr (stdscr, LINES - 1, 0, prompt);
510   wclrtoeol (stdscr);
511   for (;;) {
512     mutt_refresh ();
513     ch = mutt_getch ();
514     if (ch.ch == -1 || CI_is_return (ch.ch)) {
515       choice = -1;
516       break;
517     }
518     else {
519       p = strchr (letters, ch.ch);
520       if (p) {
521         choice = p - letters + 1;
522         break;
523       }
524       else if (ch.ch <= '9' && ch.ch > '0') {
525         choice = ch.ch - '0';
526         if (choice <= m_strlen(letters))
527           break;
528       }
529     }
530     BEEP ();
531   }
532   CLEARLINE(stdscr, LINES - 1);
533   mutt_refresh ();
534   return choice;
535 }
536
537 ssize_t mutt_pretty_size(char *s, ssize_t len, ssize_t n)
538 {
539     if (n == 0)
540         return m_strcpy(s, len, "0K");
541
542     if (n < 10189)           /* 0.1K - 9.9K */
543         return snprintf(s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
544
545     if (n < 1023949)         /* 10K - 999K */
546         /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
547         return snprintf(s, len, "%ldK", (n + 51) / 1024);
548
549     if (n < 10433332)        /* 1.0M - 9.9M */
550         return snprintf(s, len, "%3.1fM", n / 1048576.0);
551
552     /* (10433332 + 52428) / 1048576 = 10 */
553     return snprintf (s, len, "%ldM", (n + 52428) / 1048576);
554 }
555
556 /*
557  * This formats a string, a bit like
558  * snprintf (dest, destlen, "%-*.*s", min_width, max_width, s),
559  * except that the widths refer to the number of character cells
560  * when printed.
561  */
562
563 void mutt_format_string (char *dest, ssize_t destlen,
564                          int min_width, int max_width,
565                          int right_justify, char m_pad_char,
566                          const char *s, ssize_t n, int arboreal)
567 {
568   char *p;
569   wchar_t wc;
570   int w;
571   ssize_t k, k2;
572   char scratch[MB_LEN_MAX];
573   mbstate_t mbstate1, mbstate2;
574
575   p_clear(&mbstate1, 1);
576   p_clear(&mbstate2, 1);
577   --destlen;
578   p = dest;
579   for (; n && (k = mbrtowc (&wc, s, n, &mbstate1)); s += k, n -= k) {
580     if (k == -1 || k == -2) {
581       k = (k == -1) ? 1 : n;
582       wc = CharsetReplacement;
583     }
584     if (arboreal && wc < M_TREE_MAX)
585       w = 1;                    /* hack */
586     else {
587       if (!iswprint(wc))
588         wc = '?';
589       w = wcwidth (wc);
590     }
591     if (w >= 0) {
592       if (w > max_width || (k2 = wcrtomb (scratch, wc, &mbstate2)) > destlen)
593         break;
594       min_width -= w;
595       max_width -= w;
596       m_strncpy(p, destlen, scratch, k2);
597       p += k2;
598       destlen -= k2;
599     }
600   }
601   w = destlen < min_width ? destlen : min_width;
602   if (w <= 0)
603     *p = '\0';
604   else if (right_justify) {
605     p[w] = '\0';
606     while (--p >= dest)
607       p[w] = *p;
608     while (--w >= 0)
609       dest[w] = m_pad_char;
610   }
611   else {
612     while (--w >= 0)
613       *p++ = m_pad_char;
614     *p = '\0';
615   }
616 }
617
618 /*
619  * This formats a string rather like
620  *   snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
621  *   snprintf (dest, destlen, fmt, s);
622  * except that the numbers in the conversion specification refer to
623  * the number of character cells when printed.
624  */
625
626 static void mutt_format_s_x (char *dest, ssize_t destlen,
627                              const char *prefix, const char *s, int arboreal)
628 {
629   int right_justify = 1;
630   char *p;
631   int min_width;
632   int max_width = INT_MAX;
633
634   if (*prefix == '-')
635     ++prefix, right_justify = 0;
636   min_width = strtol (prefix, &p, 10);
637   if (*p == '.') {
638     prefix = p + 1;
639     max_width = strtol (prefix, &p, 10);
640     if (p <= prefix)
641       max_width = INT_MAX;
642   }
643
644   mutt_format_string (dest, destlen, min_width, max_width,
645                       right_justify, ' ', s, m_strlen(s), arboreal);
646 }
647
648 void mutt_format_s (char *dest, ssize_t destlen,
649                     const char *prefix, const char *s)
650 {
651   mutt_format_s_x (dest, destlen, prefix, s, 0);
652 }
653
654 void mutt_format_s_tree (char *dest, ssize_t destlen,
655                          const char *prefix, const char *s)
656 {
657   mutt_format_s_x (dest, destlen, prefix, s, 1);
658 }
659
660 /*
661  * mutt_paddstr (n, s) is almost equivalent to
662  * mutt_format_string (bigbuf, big, n, n, 0, ' ', s, big, 0), waddstr (main_w, bigbuf)
663  */
664
665 void mutt_paddstr(WINDOW *win, int n, const char *s)
666 {
667   wchar_t wc;
668   int w;
669   ssize_t k;
670   ssize_t len = m_strlen(s);
671   mbstate_t mbstate;
672
673   p_clear(&mbstate, 1);
674   for (; len && (k = mbrtowc (&wc, s, len, &mbstate)); s += k, len -= k) {
675     if (k == -1 || k == -2) {
676       k = (k == -1) ? 1 : len;
677       wc = CharsetReplacement;
678     }
679     if (!iswprint(wc))
680       wc = '?';
681     w = wcwidth (wc);
682     if (w >= 0) {
683       if (w > n)
684         break;
685       waddnstr(win, (char *) s, k);
686       n -= w;
687     }
688   }
689   while (n-- > 0)
690     waddch(win, ' ');
691 }