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