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