dc42e300abd7b56910d0babfee68f88405cdee53
[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 - 1, 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     nodelay(stdscr, true);
160     gettimeofday(&next, NULL);
161     while (!SigChild) {
162         struct timeval tv = { 0, 1000 * 1000 / 100 };
163         fd_set rfds;
164
165         FD_ZERO(&rfds);
166         FD_SET(0, &rfds);
167         FD_SET(pty, &rfds);
168
169         if (select(pty + 1, &rfds, NULL, NULL, &tv) < 0)
170             break;
171
172         if (FD_ISSET(pty, &rfds)) {
173             madtty_process(rt);
174             dirty = 1;
175         }
176
177         while ((ch = getch()) != ERR) {
178             madtty_keypress(rt, ch); /* pass the keypress for handling */
179             dirty = 1;
180         }
181
182         gettimeofday(&tv, NULL);
183         if (dirty && is_expired(tv, next)) {
184             madtty_draw(rt, main_w, 0, 0);
185             wrefresh(main_w);
186             dirty = 0;
187             next = timeval_add(tv, slice);
188         }
189     }
190     while (waitpid(pid, &res, 0) < 0 && errno == EINTR);
191     nodelay(stdscr, false);
192     close(pty);
193     madtty_destroy(rt);
194 }
195
196 int mutt_yesorno (const char *msg, int def)
197 {
198   event_t ch;
199   const char *yes = _("yes");
200   const char *no = _("no");
201   char *answer_string;
202   ssize_t answer_string_len;
203   char *expr;
204   regex_t reyes;
205   regex_t reno;
206   int reyes_ok;
207   int reno_ok;
208   char answer[2];
209
210   answer[1] = 0;
211
212   reyes_ok = (expr = nl_langinfo (YESEXPR)) && expr[0] == '^' &&
213     !regcomp (&reyes, expr, REG_NOSUB | REG_EXTENDED);
214   reno_ok = (expr = nl_langinfo (NOEXPR)) && expr[0] == '^' &&
215     !regcomp (&reno, expr, REG_NOSUB | REG_EXTENDED);
216
217   CLEARLINE(stdscr, LINES - 1);
218
219   /*
220    * In order to prevent the default answer to the question to wrapped
221    * around the screen in the even the question is wider than the screen,
222    * ensure there is enough room for the answer and truncate the question
223    * to fit.
224    */
225   answer_string = p_new(char, getmaxx(stdscr) + 1);
226   snprintf (answer_string, getmaxx(stdscr) + 1, " ([%s]/%s): ", def == M_YES ? yes : no,
227             def == M_YES ? no : yes);
228   answer_string_len = m_strlen(answer_string);
229   wprintw (stdscr, "%.*s%s", getmaxx(stdscr) - answer_string_len, msg, answer_string);
230   p_delete(&answer_string);
231
232   for (;;) {
233     mutt_refresh ();
234     ch = mutt_getch ();
235     if (CI_is_return (ch.ch))
236       break;
237     if (ch.ch == -1) {
238       def = -1;
239       break;
240     }
241
242     answer[0] = ch.ch;
243     if (reyes_ok ? (regexec (&reyes, answer, 0, 0, 0) == 0) : tolower (ch.ch) == *yes)
244     {
245       def = M_YES;
246       break;
247     }
248     else if (
249               reno_ok ? (regexec (&reno, answer, 0, 0, 0) == 0) :
250               (tolower (ch.ch) == *no)) {
251       def = M_NO;
252       break;
253     } else {
254       BEEP ();
255     }
256   }
257
258   if (reyes_ok)
259     regfree (&reyes);
260   if (reno_ok)
261     regfree (&reno);
262
263   if (def != -1) {
264     waddstr (stdscr, (char *) (def == M_YES ? yes : no));
265     mutt_refresh ();
266   }
267   CLEARLINE(stdscr, LINES - 1);
268   return (def);
269 }
270
271 /* this function is called when the user presses the abort key */
272 void mutt_query_exit (void)
273 {
274   mutt_flushinp ();
275   curs_set (1);
276   if (Timeout)
277     wtimeout (stdscr, -1);               /* restore blocking operation */
278   if (mutt_yesorno (_("Exit Madmutt?"), M_YES) == M_YES) {
279     mutt_endwin (NULL);
280     mutt_exit(1);
281   }
282   mutt_clear_error ();
283   mutt_curs_set (-1);
284   SigInt = 0;
285 }
286
287 void mutt_curses_error (const char *fmt, ...)
288 {
289   char TmpErrorbuf[STRING];
290   va_list ap;
291
292   va_start (ap, fmt);
293   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
294   va_end (ap);
295
296   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
297                       0, getmaxy(stdscr) - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
298   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
299
300   if (!option (OPTKEEPQUIET)) {
301     BEEP ();
302     SETCOLOR(stdscr, MT_COLOR_ERROR);
303     mvwaddstr (stdscr, LINES - 1, 0, Errorbuf);
304     wclrtoeol (stdscr);
305     SETCOLOR(stdscr, MT_COLOR_NORMAL);
306     mutt_refresh ();
307   }
308
309   set_option (OPTMSGERR);
310 }
311
312 void mutt_progress_bar (progress_t* progress, long pos) {
313   char posstr[STRING];
314
315   if (!pos) {
316     if (!NetInc)
317       mutt_message (progress->msg);
318     else {
319       if (progress->size)
320         mutt_pretty_size (progress->sizestr, sizeof (progress->sizestr),
321                           progress->size);
322       progress->pos = 0;
323     }
324   }
325
326   if (!NetInc)
327     return;
328
329   if (pos >= progress->pos + (NetInc << 10)) {
330     progress->pos = pos;
331     pos = pos / (NetInc << 10) * (NetInc << 10);
332     mutt_pretty_size (posstr, sizeof (posstr), pos);
333     if (progress->size)
334       mutt_message ("%s %s/%s", progress->msg, posstr, progress->sizestr);
335     else
336       mutt_message ("%s %s", progress->msg, posstr);
337   }
338 }
339
340 void mutt_curses_message (const char *fmt, ...)
341 {
342   char TmpErrorbuf[STRING];
343   va_list ap;
344
345   va_start (ap, fmt);
346   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
347   va_end (ap);
348
349   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
350                       0, getmaxx(stdscr) - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
351   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
352
353   if (!option (OPTKEEPQUIET)) {
354     SETCOLOR(stdscr, MT_COLOR_MESSAGE);
355     mvwaddstr (stdscr, LINES - 1, 0, Errorbuf);
356     wclrtoeol (stdscr);
357     SETCOLOR(stdscr, MT_COLOR_NORMAL);
358     mutt_refresh ();
359   }
360
361   unset_option (OPTMSGERR);
362 }
363
364 void mutt_show_error (void)
365 {
366   if (option (OPTKEEPQUIET))
367     return;
368
369   SETCOLOR(stdscr, option (OPTMSGERR) ? MT_COLOR_ERROR : MT_COLOR_MESSAGE);
370   CLEARLINE(stdscr, LINES - 1);
371   waddstr (stdscr, Errorbuf);
372   SETCOLOR(stdscr, MT_COLOR_NORMAL);
373 }
374
375 void curses_initialize(void)
376 {
377     initscr();
378     if (start_color() == ERR || !has_colors() || COLORS < 8)
379         mutt_exit(-1);
380     madtty_init_colors();
381     ci_start_color();
382     noecho();
383     raw();
384     keypad(stdscr, true);
385     typeahead(-1);
386     meta(stdscr, true);
387     curs_set(0);
388     ESCDELAY = 50;
389 }
390
391 int mutt_any_key_to_continue (const char *s)
392 {
393   struct termios t;
394   struct termios old;
395   int f, ch;
396
397   f = open ("/dev/tty", O_RDONLY);
398   tcgetattr (f, &t);
399   memcpy ((void *) &old, (void *) &t, sizeof (struct termios)); /* save original state */
400   t.c_lflag &= ~(ICANON | ECHO);
401   t.c_cc[VMIN] = 1;
402   t.c_cc[VTIME] = 0;
403   tcsetattr (f, TCSADRAIN, &t);
404   fflush (stdout);
405   if (s)
406     fputs (s, stdout);
407   else
408     fputs (_("Press any key to continue..."), stdout);
409   fflush (stdout);
410   ch = fgetc (stdin);
411   fflush (stdin);
412   tcsetattr (f, TCSADRAIN, &old);
413   close (f);
414   fputs ("\r\n", stdout);
415   mutt_clear_error ();
416   return (ch);
417 }
418
419 int _mutt_enter_fname (const char *prompt, char *buf, ssize_t blen,
420                        int *redraw, int buffy, int multiple, char ***files,
421                        int *numfiles)
422 {
423   event_t ch;
424
425   mvwaddstr(stdscr, LINES - 1, 0, (char *) prompt);
426   waddstr(stdscr, _(" ('?' for list): "));
427   if (buf[0])
428     waddstr (stdscr, buf);
429   wclrtoeol (stdscr);
430   mutt_refresh ();
431
432   ch = mutt_getch ();
433   if (ch.ch == -1) {
434     CLEARLINE(stdscr, LINES - 1);
435     return (-1);
436   }
437   else if (ch.ch == '?') {
438     mutt_refresh ();
439     buf[0] = 0;
440     mutt_select_file (buf, blen, M_SEL_FOLDER | (multiple ? M_SEL_MULTI : 0),
441                       files, numfiles);
442     *redraw = REDRAW_FULL;
443   }
444   else {
445     char *pc = p_new(char, m_strlen(prompt) + 3);
446
447     sprintf(pc, "%s: ", prompt);
448     mutt_ungetch (ch.op ? 0 : ch.ch, ch.op ? ch.op : 0);
449     if (_mutt_get_field
450         (pc, buf, blen, (buffy ? M_EFILE : M_FILE) | M_CLEAR, multiple, files,
451          numfiles)
452         != 0)
453       buf[0] = 0;
454     MAYBE_REDRAW (*redraw);
455     p_delete(&pc);
456   }
457
458   return 0;
459 }
460
461 void mutt_ungetch (int ch, int op)
462 {
463   event_t tmp;
464
465   tmp.ch = ch;
466   tmp.op = op;
467
468   if (UngetCount >= UngetBufLen)
469     p_realloc(&KeyEvent, UngetBufLen += 128);
470
471   KeyEvent[UngetCount++] = tmp;
472 }
473
474 void mutt_flushinp (void)
475 {
476   UngetCount = 0;
477   flushinp ();
478 }
479
480 /* The argument can take 3 values:
481  * -1: restore the value of the last call
482  *  0: make the cursor invisible
483  *  1: make the cursor visible
484  */
485 void mutt_curs_set (int cursor)
486 {
487   static int SavedCursor = 1;
488
489   if (cursor < 0)
490     cursor = SavedCursor;
491   else
492     SavedCursor = cursor;
493
494   if (curs_set (cursor) == ERR) {
495     if (cursor == 1)            /* cnorm */
496       curs_set (2);             /* cvvis */
497   }
498 }
499
500 int mutt_multi_choice (const char *prompt, const char *letters)
501 {
502   event_t ch;
503   int choice;
504   char *p;
505
506   mvwaddstr (stdscr, LINES - 1, 0, prompt);
507   wclrtoeol (stdscr);
508   for (;;) {
509     mutt_refresh ();
510     ch = mutt_getch ();
511     if (ch.ch == -1 || CI_is_return (ch.ch)) {
512       choice = -1;
513       break;
514     }
515     else {
516       p = strchr (letters, ch.ch);
517       if (p) {
518         choice = p - letters + 1;
519         break;
520       }
521       else if (ch.ch <= '9' && ch.ch > '0') {
522         choice = ch.ch - '0';
523         if (choice <= m_strlen(letters))
524           break;
525       }
526     }
527     BEEP ();
528   }
529   CLEARLINE(stdscr, LINES - 1);
530   mutt_refresh ();
531   return choice;
532 }
533
534 ssize_t mutt_pretty_size(char *s, ssize_t len, ssize_t n)
535 {
536     if (n == 0)
537         return m_strcpy(s, len, "0K");
538
539     if (n < 10189)           /* 0.1K - 9.9K */
540         return snprintf(s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
541
542     if (n < 1023949)         /* 10K - 999K */
543         /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
544         return snprintf(s, len, "%ldK", (n + 51) / 1024);
545
546     if (n < 10433332)        /* 1.0M - 9.9M */
547         return snprintf(s, len, "%3.1fM", n / 1048576.0);
548
549     /* (10433332 + 52428) / 1048576 = 10 */
550     return snprintf (s, len, "%ldM", (n + 52428) / 1048576);
551 }
552
553 /*
554  * This formats a string, a bit like
555  * snprintf (dest, destlen, "%-*.*s", min_width, max_width, s),
556  * except that the widths refer to the number of character cells
557  * when printed.
558  */
559
560 void mutt_format_string (char *dest, ssize_t destlen,
561                          int min_width, int max_width,
562                          int right_justify, char m_pad_char,
563                          const char *s, ssize_t n, int arboreal)
564 {
565   char *p;
566   wchar_t wc;
567   int w;
568   ssize_t k, k2;
569   char scratch[MB_LEN_MAX];
570   mbstate_t mbstate1, mbstate2;
571
572   p_clear(&mbstate1, 1);
573   p_clear(&mbstate2, 1);
574   --destlen;
575   p = dest;
576   for (; n && (k = mbrtowc (&wc, s, n, &mbstate1)); s += k, n -= k) {
577     if (k == -1 || k == -2) {
578       k = (k == -1) ? 1 : n;
579       wc = CharsetReplacement;
580     }
581     if (arboreal && wc < M_TREE_MAX)
582       w = 1;                    /* hack */
583     else {
584       if (!iswprint(wc))
585         wc = '?';
586       w = wcwidth (wc);
587     }
588     if (w >= 0) {
589       if (w > max_width || (k2 = wcrtomb (scratch, wc, &mbstate2)) > destlen)
590         break;
591       min_width -= w;
592       max_width -= w;
593       m_strncpy(p, destlen, scratch, k2);
594       p += k2;
595       destlen -= k2;
596     }
597   }
598   w = destlen < min_width ? destlen : min_width;
599   if (w <= 0)
600     *p = '\0';
601   else if (right_justify) {
602     p[w] = '\0';
603     while (--p >= dest)
604       p[w] = *p;
605     while (--w >= 0)
606       dest[w] = m_pad_char;
607   }
608   else {
609     while (--w >= 0)
610       *p++ = m_pad_char;
611     *p = '\0';
612   }
613 }
614
615 /*
616  * This formats a string rather like
617  *   snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
618  *   snprintf (dest, destlen, fmt, s);
619  * except that the numbers in the conversion specification refer to
620  * the number of character cells when printed.
621  */
622
623 static void mutt_format_s_x (char *dest, ssize_t destlen,
624                              const char *prefix, const char *s, int arboreal)
625 {
626   int right_justify = 1;
627   char *p;
628   int min_width;
629   int max_width = INT_MAX;
630
631   if (*prefix == '-')
632     ++prefix, right_justify = 0;
633   min_width = strtol (prefix, &p, 10);
634   if (*p == '.') {
635     prefix = p + 1;
636     max_width = strtol (prefix, &p, 10);
637     if (p <= prefix)
638       max_width = INT_MAX;
639   }
640
641   mutt_format_string (dest, destlen, min_width, max_width,
642                       right_justify, ' ', s, m_strlen(s), arboreal);
643 }
644
645 void mutt_format_s (char *dest, ssize_t destlen,
646                     const char *prefix, const char *s)
647 {
648   mutt_format_s_x (dest, destlen, prefix, s, 0);
649 }
650
651 void mutt_format_s_tree (char *dest, ssize_t destlen,
652                          const char *prefix, const char *s)
653 {
654   mutt_format_s_x (dest, destlen, prefix, s, 1);
655 }
656
657 /*
658  * mutt_paddstr (n, s) is almost equivalent to
659  * mutt_format_string (bigbuf, big, n, n, 0, ' ', s, big, 0), waddstr (main_w, bigbuf)
660  */
661
662 void mutt_paddstr(WINDOW *win, int n, const char *s)
663 {
664   wchar_t wc;
665   int w;
666   ssize_t k;
667   ssize_t len = m_strlen(s);
668   mbstate_t mbstate;
669
670   p_clear(&mbstate, 1);
671   for (; len && (k = mbrtowc (&wc, s, len, &mbstate)); s += k, len -= k) {
672     if (k == -1 || k == -2) {
673       k = (k == -1) ? 1 : len;
674       wc = CharsetReplacement;
675     }
676     if (!iswprint(wc))
677       wc = '?';
678     w = wcwidth (wc);
679     if (w >= 0) {
680       if (w > n)
681         break;
682       waddnstr(win, (char *) s, k);
683       n -= w;
684     }
685   }
686   while (n-- > 0)
687     waddch(win, ' ');
688 }