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