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