de14e59c034e59bb27c57d933102b83d2bf22632
[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 #if HAVE_CONFIG_H
15 # include "config.h"
16 #endif
17
18 #include <wchar.h>
19 #include <wctype.h>
20 #include <termios.h>
21 #include <sys/types.h>
22 #include <fcntl.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <ctype.h>
28
29 #ifdef HAVE_LANGINFO_YESEXPR
30 #include <langinfo.h>
31 #endif
32
33 #include <lib-lib/lib-lib.h>
34
35 #include <lib-sys/unix.h>
36 #include <lib-sys/mutt_signal.h>
37
38 #include "curses.h"
39 #include "menu.h"
40 #include "enter.h"
41
42 #include "mutt.h"
43 #include "pager.h"
44 #include "charset.h"
45
46 /* not possible to unget more than one char under some curses libs, and it
47  * is impossible to unget function keys in SLang, so roll our own input
48  * buffering routines.
49  */
50 ssize_t UngetCount = 0;
51 static ssize_t UngetBufLen = 0;
52 static event_t *KeyEvent;
53
54 void mutt_refresh (void)
55 {
56   /* don't refresh when we are waiting for a child. */
57   if (option (OPTKEEPQUIET))
58     return;
59
60   /* don't refresh in the middle of macros unless necessary */
61   if (UngetCount && !option (OPTFORCEREFRESH))
62     return;
63
64   /* else */
65   refresh ();
66 }
67
68 /* Make sure that the next refresh does a full refresh.  This could be
69    optmized by not doing it at all if DISPLAY is set as this might
70    indicate that a GUI based pinentry was used.  Having an option to
71    customize this is of course the Mutt way.  */
72 void mutt_need_hard_redraw (void)
73 {
74   if (!getenv ("DISPLAY")) {
75     keypad (stdscr, TRUE);
76     clearok (stdscr, TRUE);
77     set_option (OPTNEEDREDRAW);
78   }
79 }
80
81 event_t mutt_getch (void)
82 {
83   int ch;
84   event_t err = { -1, OP_NULL }, ret;
85
86   if (!option (OPTUNBUFFEREDINPUT) && UngetCount)
87     return (KeyEvent[--UngetCount]);
88
89   SigInt = 0;
90
91   mutt_allow_interrupt (1);
92   ch = getch ();
93   mutt_allow_interrupt (0);
94
95   if (SigInt)
96     mutt_query_exit ();
97
98   if (ch == ERR)
99     return err;
100
101   if ((ch & 0x80) && option (OPTMETAKEY)) {
102     /* send ALT-x as ESC-x */
103     ch &= ~0x80;
104     mutt_ungetch (ch, 0);
105     ret.ch = '\033';
106     ret.op = 0;
107     return ret;
108   }
109
110   ret.ch = ch;
111   ret.op = 0;
112   return (ch == ctrl ('G') ? err : ret);
113 }
114
115 int _mutt_get_field ( const char *field, char *buf, ssize_t buflen,
116                      int complete, int multiple, char ***files, int *numfiles)
117 {
118   int ret;
119   int x, y;
120
121   ENTER_STATE *es = mutt_new_enter_state ();
122
123   do {
124     CLEARLINE (LINES - 1);
125     addstr (field);
126     mutt_refresh ();
127     getyx (stdscr, y, x);
128     ret =
129       _mutt_enter_string (buf, buflen, y, x, complete, multiple, files,
130                           numfiles, es);
131   }
132   while (ret == 1);
133   CLEARLINE (LINES - 1);
134   mutt_free_enter_state (&es);
135
136   return (ret);
137 }
138
139 int mutt_get_field_unbuffered (char *msg, char *buf, ssize_t buflen, int flags)
140 {
141   int rc;
142
143   set_option (OPTUNBUFFEREDINPUT);
144   rc = mutt_get_field (msg, buf, buflen, flags);
145   unset_option (OPTUNBUFFEREDINPUT);
146
147   return (rc);
148 }
149
150 void mutt_clear_error (void)
151 {
152   Errorbuf[0] = 0;
153   if (!option (OPTNOCURSES))
154     CLEARLINE (LINES - 1);
155 }
156
157 void mutt_edit_file (const char *editor, const char *data)
158 {
159   char cmd[LONG_STRING];
160
161   mutt_endwin (NULL);
162   mutt_expand_file_fmt (cmd, sizeof (cmd), editor, data);
163   if (mutt_system (cmd) == -1)
164     mutt_error (_("Error running \"%s\"!"), cmd);
165   keypad (stdscr, TRUE);
166   clearok (stdscr, TRUE);
167 }
168
169 int mutt_yesorno (const char *msg, int def)
170 {
171   event_t ch;
172   char *yes = _("yes");
173   char *no = _("no");
174   char *answer_string;
175   ssize_t answer_string_len;
176
177 #ifdef HAVE_LANGINFO_YESEXPR
178   char *expr;
179   regex_t reyes;
180   regex_t reno;
181   int reyes_ok;
182   int reno_ok;
183   char answer[2];
184
185   answer[1] = 0;
186
187   reyes_ok = (expr = nl_langinfo (YESEXPR)) && expr[0] == '^' &&
188     !regcomp (&reyes, expr, REG_NOSUB | REG_EXTENDED);
189   reno_ok = (expr = nl_langinfo (NOEXPR)) && expr[0] == '^' &&
190     !regcomp (&reno, expr, REG_NOSUB | REG_EXTENDED);
191 #endif
192
193   CLEARLINE (LINES - 1);
194
195   /*
196    * In order to prevent the default answer to the question to wrapped
197    * around the screen in the even the question is wider than the screen,
198    * ensure there is enough room for the answer and truncate the question
199    * to fit.
200    */
201   answer_string = p_new(char, COLS + 1);
202   snprintf (answer_string, COLS + 1, " ([%s]/%s): ", def == M_YES ? yes : no,
203             def == M_YES ? no : yes);
204   answer_string_len = m_strlen(answer_string);
205   printw ("%.*s%s", COLS - answer_string_len, msg, answer_string);
206   p_delete(&answer_string);
207
208   for (;;) {
209     mutt_refresh ();
210     ch = mutt_getch ();
211     if (CI_is_return (ch.ch))
212       break;
213     if (ch.ch == -1) {
214       def = -1;
215       break;
216     }
217
218 #ifdef HAVE_LANGINFO_YESEXPR
219     answer[0] = ch.ch;
220     if (reyes_ok ? (regexec (&reyes, answer, 0, 0, 0) == 0) : tolower (ch.ch) == *yes)
221 #else
222     if (tolower (ch.ch) == *yes)
223 #endif
224     {
225       def = M_YES;
226       break;
227     }
228     else if (
229 #ifdef HAVE_LANGINFO_YESEXPR
230               reno_ok ? (regexec (&reno, answer, 0, 0, 0) == 0) :
231 #endif
232               (tolower (ch.ch) == *no)) {
233       def = M_NO;
234       break;
235     } else {
236       BEEP ();
237     }
238   }
239
240 #ifdef HAVE_LANGINFO_YESEXPR
241   if (reyes_ok)
242     regfree (&reyes);
243   if (reno_ok)
244     regfree (&reno);
245 #endif
246
247   if (def != -1) {
248     addstr ((char *) (def == M_YES ? yes : no));
249     mutt_refresh ();
250   }
251   return (def);
252 }
253
254 /* this function is called when the user presses the abort key */
255 void mutt_query_exit (void)
256 {
257   mutt_flushinp ();
258   curs_set (1);
259   if (Timeout)
260     timeout (-1);               /* restore blocking operation */
261   if (mutt_yesorno (_("Exit Madmutt?"), M_YES) == M_YES) {
262     mutt_endwin (NULL);
263     exit (1);
264   }
265   mutt_clear_error ();
266   mutt_curs_set (-1);
267   SigInt = 0;
268 }
269
270 void mutt_curses_error (const char *fmt, ...)
271 {
272   char TmpErrorbuf[STRING];
273   va_list ap;
274
275   va_start (ap, fmt);
276   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
277   va_end (ap);
278
279   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
280                       0, COLS - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
281   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
282
283   if (!option (OPTKEEPQUIET)) {
284     BEEP ();
285     SETCOLOR (MT_COLOR_ERROR);
286     mvaddstr (LINES - 1, 0, Errorbuf);
287     clrtoeol ();
288     SETCOLOR (MT_COLOR_NORMAL);
289     mutt_refresh ();
290   }
291
292   set_option (OPTMSGERR);
293 }
294
295 void mutt_progress_bar (progress_t* progress, long pos) {
296   char posstr[SHORT_STRING];
297
298   if (!pos) {
299     if (!NetInc)
300       mutt_message (progress->msg);
301     else {
302       if (progress->size)
303         mutt_pretty_size (progress->sizestr, sizeof (progress->sizestr),
304                           progress->size);
305       progress->pos = 0;
306     }
307   }
308
309   if (!NetInc)
310     return;
311
312   if (pos >= progress->pos + (NetInc << 10)) {
313     progress->pos = pos;
314     pos = pos / (NetInc << 10) * (NetInc << 10);
315     mutt_pretty_size (posstr, sizeof (posstr), pos);
316     if (progress->size)
317       mutt_message ("%s %s/%s", progress->msg, posstr, progress->sizestr);
318     else
319       mutt_message ("%s %s", progress->msg, posstr);
320   }
321 }
322
323 void mutt_curses_message (const char *fmt, ...)
324 {
325   char TmpErrorbuf[STRING];
326   va_list ap;
327
328   va_start (ap, fmt);
329   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
330   va_end (ap);
331
332   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
333                       0, COLS - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
334   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
335
336   if (!option (OPTKEEPQUIET)) {
337     SETCOLOR (MT_COLOR_MESSAGE);
338     mvaddstr (LINES - 1, 0, Errorbuf);
339     clrtoeol ();
340     SETCOLOR (MT_COLOR_NORMAL);
341     mutt_refresh ();
342   }
343
344   unset_option (OPTMSGERR);
345 }
346
347 void mutt_show_error (void)
348 {
349   if (option (OPTKEEPQUIET))
350     return;
351
352   SETCOLOR (option (OPTMSGERR) ? MT_COLOR_ERROR : MT_COLOR_MESSAGE);
353   CLEARLINE (LINES - 1);
354   addstr (Errorbuf);
355   SETCOLOR (MT_COLOR_NORMAL);
356 }
357
358 void mutt_endwin (const char *msg)
359 {
360   if (!option (OPTNOCURSES)) {
361     CLEARLINE (LINES - 1);
362
363     attrset (A_NORMAL);
364     mutt_refresh ();
365     endwin ();
366   }
367
368   if (msg && *msg) {
369     puts (msg);
370     fflush (stdout);
371   }
372 }
373
374 void _mutt_perror (const char *s, const char* filename, int line)
375 {
376   char *p = strerror (errno);
377   mutt_error ("%s: %s (errno = %d) from %s:%i", s, p ? p : _("unknown error"), errno, filename, line);
378 }
379
380 int mutt_any_key_to_continue (const char *s)
381 {
382   struct termios t;
383   struct termios old;
384   int f, ch;
385
386   f = open ("/dev/tty", O_RDONLY);
387   tcgetattr (f, &t);
388   memcpy ((void *) &old, (void *) &t, sizeof (struct termios)); /* save original state */
389   t.c_lflag &= ~(ICANON | ECHO);
390   t.c_cc[VMIN] = 1;
391   t.c_cc[VTIME] = 0;
392   tcsetattr (f, TCSADRAIN, &t);
393   fflush (stdout);
394   if (s)
395     fputs (s, stdout);
396   else
397     fputs (_("Press any key to continue..."), stdout);
398   fflush (stdout);
399   ch = fgetc (stdin);
400   fflush (stdin);
401   tcsetattr (f, TCSADRAIN, &old);
402   close (f);
403   fputs ("\r\n", stdout);
404   mutt_clear_error ();
405   return (ch);
406 }
407
408 int mutt_do_pager (const char *banner,
409                    const char *tempfile, int do_color, pager_t * info)
410 {
411   int rc;
412
413   if (!Pager || m_strcmp(Pager, "builtin") == 0)
414     rc = mutt_pager (banner, tempfile, do_color, info);
415   else {
416     char cmd[STRING];
417
418     mutt_endwin (NULL);
419     mutt_expand_file_fmt (cmd, sizeof (cmd), Pager, tempfile);
420     if (mutt_system (cmd) == -1) {
421       mutt_error (_("Error running \"%s\"!"), cmd);
422       rc = -1;
423     }
424     else
425       rc = 0;
426     mutt_unlink (tempfile);
427   }
428
429   return rc;
430 }
431
432 int _mutt_enter_fname (const char *prompt, char *buf, ssize_t blen,
433                        int *redraw, int buffy, int multiple, char ***files,
434                        int *numfiles)
435 {
436   event_t ch;
437
438   mvaddstr (LINES - 1, 0, (char *) prompt);
439   addstr (_(" ('?' for list): "));
440   if (buf[0])
441     addstr (buf);
442   clrtoeol ();
443   mutt_refresh ();
444
445   ch = mutt_getch ();
446   if (ch.ch == -1) {
447     CLEARLINE (LINES - 1);
448     return (-1);
449   }
450   else if (ch.ch == '?') {
451     mutt_refresh ();
452     buf[0] = 0;
453     _mutt_select_file (buf, blen, M_SEL_FOLDER | (multiple ? M_SEL_MULTI : 0),
454                        files, numfiles);
455     *redraw = REDRAW_FULL;
456   }
457   else {
458     char *pc = p_new(char, m_strlen(prompt) + 3);
459
460     sprintf (pc, "%s: ", prompt);       /* __SPRINTF_CHECKED__ */
461     mutt_ungetch (ch.op ? 0 : ch.ch, ch.op ? ch.op : 0);
462     if (_mutt_get_field
463         (pc, buf, blen, (buffy ? M_EFILE : M_FILE) | M_CLEAR, multiple, files,
464          numfiles)
465         != 0)
466       buf[0] = 0;
467     MAYBE_REDRAW (*redraw);
468     p_delete(&pc);
469   }
470
471   return 0;
472 }
473
474 void mutt_ungetch (int ch, int op)
475 {
476   event_t tmp;
477
478   tmp.ch = ch;
479   tmp.op = op;
480
481   if (UngetCount >= UngetBufLen)
482     p_realloc(&KeyEvent, UngetBufLen += 128);
483
484   KeyEvent[UngetCount++] = tmp;
485 }
486
487 void mutt_flushinp (void)
488 {
489   UngetCount = 0;
490   flushinp ();
491 }
492
493 #if (defined(USE_SLANG_CURSES) || defined(HAVE_CURS_SET))
494 /* The argument can take 3 values:
495  * -1: restore the value of the last call
496  *  0: make the cursor invisible
497  *  1: make the cursor visible
498  */
499 void mutt_curs_set (int cursor)
500 {
501   static int SavedCursor = 1;
502
503   if (cursor < 0)
504     cursor = SavedCursor;
505   else
506     SavedCursor = cursor;
507
508   if (curs_set (cursor) == ERR) {
509     if (cursor == 1)            /* cnorm */
510       curs_set (2);             /* cvvis */
511   }
512 }
513 #endif
514
515 int mutt_multi_choice (char *prompt, char *letters)
516 {
517   event_t ch;
518   int choice;
519   char *p;
520
521   mvaddstr (LINES - 1, 0, prompt);
522   clrtoeol ();
523   for (;;) {
524     mutt_refresh ();
525     ch = mutt_getch ();
526     if (ch.ch == -1 || CI_is_return (ch.ch)) {
527       choice = -1;
528       break;
529     }
530     else {
531       p = strchr (letters, ch.ch);
532       if (p) {
533         choice = p - letters + 1;
534         break;
535       }
536       else if (ch.ch <= '9' && ch.ch > '0') {
537         choice = ch.ch - '0';
538         if (choice <= m_strlen(letters))
539           break;
540       }
541     }
542     BEEP ();
543   }
544   CLEARLINE (LINES - 1);
545   mutt_refresh ();
546   return choice;
547 }
548
549 /*
550  * addwch would be provided by an up-to-date curses library
551  */
552
553 int mutt_addwch (wchar_t wc)
554 {
555   char buf[MB_LEN_MAX * 2];
556   mbstate_t mbstate;
557   ssize_t n1, n2;
558
559   p_clear(&mbstate, 1);
560   if ((n1 = wcrtomb(buf, wc, &mbstate)) == -1 ||
561       (n2 = wcrtomb(buf + n1, 0, &mbstate)) == -1)
562     return -1;                  /* ERR */
563   else
564     return addstr (buf);
565 }
566
567
568 /*
569  * This formats a string, a bit like
570  * snprintf (dest, destlen, "%-*.*s", min_width, max_width, s),
571  * except that the widths refer to the number of character cells
572  * when printed.
573  */
574
575 void mutt_format_string (char *dest, ssize_t destlen,
576                          int min_width, int max_width,
577                          int right_justify, char m_pad_char,
578                          const char *s, ssize_t n, int arboreal)
579 {
580   char *p;
581   wchar_t wc;
582   int w;
583   ssize_t k, k2;
584   char scratch[MB_LEN_MAX];
585   mbstate_t mbstate1, mbstate2;
586
587   p_clear(&mbstate1, 1);
588   p_clear(&mbstate2, 1);
589   --destlen;
590   p = dest;
591   for (; n && (k = mbrtowc (&wc, s, n, &mbstate1)); s += k, n -= k) {
592     if (k == -1 || k == -2) {
593       k = (k == -1) ? 1 : n;
594       wc = CharsetReplacement;
595     }
596     if (arboreal && wc < M_TREE_MAX)
597       w = 1;                    /* hack */
598     else {
599       if (!iswprint(wc))
600         wc = '?';
601       w = wcwidth (wc);
602     }
603     if (w >= 0) {
604       if (w > max_width || (k2 = wcrtomb (scratch, wc, &mbstate2)) > destlen)
605         break;
606       min_width -= w;
607       max_width -= w;
608       strncpy (p, scratch, k2);
609       p += k2;
610       destlen -= k2;
611     }
612   }
613   w = destlen < min_width ? destlen : min_width;
614   if (w <= 0)
615     *p = '\0';
616   else if (right_justify) {
617     p[w] = '\0';
618     while (--p >= dest)
619       p[w] = *p;
620     while (--w >= 0)
621       dest[w] = m_pad_char;
622   }
623   else {
624     while (--w >= 0)
625       *p++ = m_pad_char;
626     *p = '\0';
627   }
628 }
629
630 /*
631  * This formats a string rather like
632  *   snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
633  *   snprintf (dest, destlen, fmt, s);
634  * except that the numbers in the conversion specification refer to
635  * the number of character cells when printed.
636  */
637
638 static void mutt_format_s_x (char *dest, ssize_t destlen,
639                              const char *prefix, const char *s, int arboreal)
640 {
641   int right_justify = 1;
642   char *p;
643   int min_width;
644   int max_width = INT_MAX;
645
646   if (*prefix == '-')
647     ++prefix, right_justify = 0;
648   min_width = strtol (prefix, &p, 10);
649   if (*p == '.') {
650     prefix = p + 1;
651     max_width = strtol (prefix, &p, 10);
652     if (p <= prefix)
653       max_width = INT_MAX;
654   }
655
656   mutt_format_string (dest, destlen, min_width, max_width,
657                       right_justify, ' ', s, m_strlen(s), arboreal);
658 }
659
660 void mutt_format_s (char *dest, ssize_t destlen,
661                     const char *prefix, const char *s)
662 {
663   mutt_format_s_x (dest, destlen, prefix, s, 0);
664 }
665
666 void mutt_format_s_tree (char *dest, ssize_t destlen,
667                          const char *prefix, const char *s)
668 {
669   mutt_format_s_x (dest, destlen, prefix, s, 1);
670 }
671
672 /*
673  * mutt_paddstr (n, s) is almost equivalent to
674  * mutt_format_string (bigbuf, big, n, n, 0, ' ', s, big, 0), addstr (bigbuf)
675  */
676
677 void mutt_paddstr (int n, const char *s)
678 {
679   wchar_t wc;
680   int w;
681   ssize_t k;
682   ssize_t len = m_strlen(s);
683   mbstate_t mbstate;
684
685   p_clear(&mbstate, 1);
686   for (; len && (k = mbrtowc (&wc, s, len, &mbstate)); s += k, len -= k) {
687     if (k == -1 || k == -2) {
688       k = (k == -1) ? 1 : len;
689       wc = CharsetReplacement;
690     }
691     if (!iswprint(wc))
692       wc = '?';
693     w = wcwidth (wc);
694     if (w >= 0) {
695       if (w > n)
696         break;
697       addnstr ((char *) s, k);
698       n -= w;
699     }
700   }
701   while (n-- > 0)
702     addch (' ');
703 }
704
705 /*
706  * mutt_strwidth is like m_strlenexcept that it returns the width
707  * refering to the number of characters cells.
708  */
709
710 int mutt_strwidth (const char *s)
711 {
712   wchar_t wc;
713   int w;
714   ssize_t k, n;
715   mbstate_t mbstate;
716
717   if (!s)
718     return 0;
719
720   n = m_strlen(s);
721
722   p_clear(&mbstate, 1);
723   for (w = 0; n && (k = mbrtowc (&wc, s, n, &mbstate)); s += k, n -= k) {
724     if (k == -1 || k == -2) {
725       k = (k == -1) ? 1 : n;
726       wc = CharsetReplacement;
727     }
728     if (!iswprint(wc))
729       wc = '?';
730     w += wcwidth (wc);
731   }
732   return w;
733 }