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