ee5a9b7c06c959ed1c9638a27caab9abdafd7d77
[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     mutt_endwin (NULL);
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 #ifdef USE_SOCKET
314 void mutt_progress_bar (progress_t* progress, long pos) {
315   char posstr[SHORT_STRING];
316
317   if (!pos) {
318     if (!NetInc)
319       mutt_message (progress->msg);
320     else {
321       mutt_pretty_size (progress->sizestr, sizeof (progress->sizestr),
322                         progress->size);
323       progress->pos = 0;
324     }
325   }
326
327   if (!NetInc)
328     return;
329
330   if (pos > progress->pos + (NetInc << 10)) {
331     progress->pos = pos;
332     pos = pos / (NetInc << 10) * (NetInc << 10);
333     mutt_pretty_size (posstr, sizeof (posstr), pos);
334     mutt_message ("%s %s/%s", progress->msg, posstr, progress->sizestr);
335   }
336 }
337 #endif
338
339 void mutt_curses_message (const char *fmt, ...)
340 {
341   char TmpErrorbuf[STRING];
342   va_list ap;
343
344   va_start (ap, fmt);
345   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
346   va_end (ap);
347
348   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
349                       0, COLS - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
350   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
351
352   if (!option (OPTKEEPQUIET)) {
353     SETCOLOR (MT_COLOR_MESSAGE);
354     mvaddstr (LINES - 1, 0, Errorbuf);
355     clrtoeol ();
356     SETCOLOR (MT_COLOR_NORMAL);
357     mutt_refresh ();
358   }
359
360   unset_option (OPTMSGERR);
361 }
362
363 void mutt_show_error (void)
364 {
365   if (option (OPTKEEPQUIET))
366     return;
367
368   SETCOLOR (option (OPTMSGERR) ? MT_COLOR_ERROR : MT_COLOR_MESSAGE);
369   CLEARLINE (LINES - 1);
370   addstr (Errorbuf);
371   SETCOLOR (MT_COLOR_NORMAL);
372 }
373
374 void mutt_endwin (const char *msg)
375 {
376   if (!option (OPTNOCURSES)) {
377     CLEARLINE (LINES - 1);
378
379     attrset (A_NORMAL);
380     mutt_refresh ();
381     endwin ();
382   }
383
384   if (msg && *msg) {
385     puts (msg);
386     fflush (stdout);
387   }
388 }
389
390 void _mutt_perror (const char *s, const char* filename, int line)
391 {
392   char *p = strerror (errno);
393
394   debug_print (1, ("%s: %s (errno = %d)\n", s, p ? p : "unknown error", errno));
395   mutt_error ("%s: %s (errno = %d) from %s:%i", s, p ? p : _("unknown error"), errno, filename, line);
396 }
397
398 int mutt_any_key_to_continue (const char *s)
399 {
400   struct termios t;
401   struct termios old;
402   int f, ch;
403
404   f = open ("/dev/tty", O_RDONLY);
405   tcgetattr (f, &t);
406   memcpy ((void *) &old, (void *) &t, sizeof (struct termios)); /* save original state */
407   t.c_lflag &= ~(ICANON | ECHO);
408   t.c_cc[VMIN] = 1;
409   t.c_cc[VTIME] = 0;
410   tcsetattr (f, TCSADRAIN, &t);
411   fflush (stdout);
412   if (s)
413     fputs (s, stdout);
414   else
415     fputs (_("Press any key to continue..."), stdout);
416   fflush (stdout);
417   ch = fgetc (stdin);
418   fflush (stdin);
419   tcsetattr (f, TCSADRAIN, &old);
420   close (f);
421   fputs ("\r\n", stdout);
422   mutt_clear_error ();
423   return (ch);
424 }
425
426 int mutt_do_pager (const char *banner,
427                    const char *tempfile, int do_color, pager_t * info)
428 {
429   int rc;
430
431   if (!Pager || str_cmp (Pager, "builtin") == 0)
432     rc = mutt_pager (banner, tempfile, do_color, info);
433   else {
434     char cmd[STRING];
435
436     mutt_endwin (NULL);
437     mutt_expand_file_fmt (cmd, sizeof (cmd), Pager, tempfile);
438     if (mutt_system (cmd) == -1) {
439       mutt_error (_("Error running \"%s\"!"), cmd);
440       rc = -1;
441     }
442     else
443       rc = 0;
444     mutt_unlink (tempfile);
445   }
446
447   return rc;
448 }
449
450 int _mutt_enter_fname (const char *prompt, char *buf, size_t blen,
451                        int *redraw, int buffy, int multiple, char ***files,
452                        int *numfiles)
453 {
454   event_t ch;
455
456   mvaddstr (LINES - 1, 0, (char *) prompt);
457   addstr (_(" ('?' for list): "));
458   if (buf[0])
459     addstr (buf);
460   clrtoeol ();
461   mutt_refresh ();
462
463   ch = mutt_getch ();
464   if (ch.ch == -1) {
465     CLEARLINE (LINES - 1);
466     return (-1);
467   }
468   else if (ch.ch == '?') {
469     mutt_refresh ();
470     buf[0] = 0;
471     _mutt_select_file (buf, blen, M_SEL_FOLDER | (multiple ? M_SEL_MULTI : 0),
472                        files, numfiles);
473     *redraw = REDRAW_FULL;
474   }
475   else {
476     char *pc = mem_malloc (str_len (prompt) + 3);
477
478     sprintf (pc, "%s: ", prompt);       /* __SPRINTF_CHECKED__ */
479     mutt_ungetch (ch.op ? 0 : ch.ch, ch.op ? ch.op : 0);
480     if (_mutt_get_field
481         (pc, buf, blen, (buffy ? M_EFILE : M_FILE) | M_CLEAR, multiple, files,
482          numfiles)
483         != 0)
484       buf[0] = 0;
485     MAYBE_REDRAW (*redraw);
486     mem_free (&pc);
487   }
488
489   return 0;
490 }
491
492 void mutt_ungetch (int ch, int op)
493 {
494   event_t tmp;
495
496   tmp.ch = ch;
497   tmp.op = op;
498
499   if (UngetCount >= UngetBufLen)
500     mem_realloc (&KeyEvent, (UngetBufLen += 128) * sizeof (event_t));
501
502   KeyEvent[UngetCount++] = tmp;
503 }
504
505 void mutt_flushinp (void)
506 {
507   UngetCount = 0;
508   flushinp ();
509 }
510
511 #if (defined(USE_SLANG_CURSES) || defined(HAVE_CURS_SET))
512 /* The argument can take 3 values:
513  * -1: restore the value of the last call
514  *  0: make the cursor invisible
515  *  1: make the cursor visible
516  */
517 void mutt_curs_set (int cursor)
518 {
519   static int SavedCursor = 1;
520
521   if (cursor < 0)
522     cursor = SavedCursor;
523   else
524     SavedCursor = cursor;
525
526   if (curs_set (cursor) == ERR) {
527     if (cursor == 1)            /* cnorm */
528       curs_set (2);             /* cvvis */
529   }
530 }
531 #endif
532
533 int mutt_multi_choice (char *prompt, char *letters)
534 {
535   event_t ch;
536   int choice;
537   char *p;
538
539   mvaddstr (LINES - 1, 0, prompt);
540   clrtoeol ();
541   FOREVER {
542     mutt_refresh ();
543     ch = mutt_getch ();
544     if (ch.ch == -1 || CI_is_return (ch.ch)) {
545       choice = -1;
546       break;
547     }
548     else {
549       p = strchr (letters, ch.ch);
550       if (p) {
551         choice = p - letters + 1;
552         break;
553       }
554       else if (ch.ch <= '9' && ch.ch > '0') {
555         choice = ch.ch - '0';
556         if (choice <= str_len (letters))
557           break;
558       }
559     }
560     BEEP ();
561   }
562   CLEARLINE (LINES - 1);
563   mutt_refresh ();
564   return choice;
565 }
566
567 /*
568  * addwch would be provided by an up-to-date curses library
569  */
570
571 int mutt_addwch (wchar_t wc)
572 {
573   char buf[MB_LEN_MAX * 2];
574   mbstate_t mbstate;
575   size_t n1, n2;
576
577   memset (&mbstate, 0, sizeof (mbstate));
578   if ((n1 = wcrtomb (buf, wc, &mbstate)) == (size_t) (-1) ||
579       (n2 = wcrtomb (buf + n1, 0, &mbstate)) == (size_t) (-1))
580     return -1;                  /* ERR */
581   else
582     return addstr (buf);
583 }
584
585
586 /*
587  * This formats a string, a bit like
588  * snprintf (dest, destlen, "%-*.*s", min_width, max_width, s),
589  * except that the widths refer to the number of character cells
590  * when printed.
591  */
592
593 void mutt_format_string (char *dest, size_t destlen,
594                          int min_width, int max_width,
595                          int right_justify, char m_pad_char,
596                          const char *s, size_t n, int arboreal)
597 {
598   char *p;
599   wchar_t wc;
600   int w;
601   size_t k, k2;
602   char scratch[MB_LEN_MAX];
603   mbstate_t mbstate1, mbstate2;
604
605   memset (&mbstate1, 0, sizeof (mbstate1));
606   memset (&mbstate2, 0, sizeof (mbstate2));
607   --destlen;
608   p = dest;
609   for (; n && (k = mbrtowc (&wc, s, n, &mbstate1)); s += k, n -= k) {
610     if (k == (size_t) (-1) || k == (size_t) (-2)) {
611       k = (k == (size_t) (-1)) ? 1 : n;
612       wc = replacement_char ();
613     }
614     if (arboreal && wc < M_TREE_MAX)
615       w = 1;                    /* hack */
616     else {
617       if (!IsWPrint (wc))
618         wc = '?';
619       w = wcwidth (wc);
620     }
621     if (w >= 0) {
622       if (w > max_width || (k2 = wcrtomb (scratch, wc, &mbstate2)) > destlen)
623         break;
624       min_width -= w;
625       max_width -= w;
626       strncpy (p, scratch, k2);
627       p += k2;
628       destlen -= k2;
629     }
630   }
631   w = (int) destlen < min_width ? destlen : min_width;
632   if (w <= 0)
633     *p = '\0';
634   else if (right_justify) {
635     p[w] = '\0';
636     while (--p >= dest)
637       p[w] = *p;
638     while (--w >= 0)
639       dest[w] = m_pad_char;
640   }
641   else {
642     while (--w >= 0)
643       *p++ = m_pad_char;
644     *p = '\0';
645   }
646 }
647
648 /*
649  * This formats a string rather like
650  *   snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
651  *   snprintf (dest, destlen, fmt, s);
652  * except that the numbers in the conversion specification refer to
653  * the number of character cells when printed.
654  */
655
656 static void mutt_format_s_x (char *dest,
657                              size_t destlen,
658                              const char *prefix, const char *s, int arboreal)
659 {
660   int right_justify = 1;
661   char *p;
662   int min_width;
663   int max_width = INT_MAX;
664
665   if (*prefix == '-')
666     ++prefix, right_justify = 0;
667   min_width = strtol (prefix, &p, 10);
668   if (*p == '.') {
669     prefix = p + 1;
670     max_width = strtol (prefix, &p, 10);
671     if (p <= prefix)
672       max_width = INT_MAX;
673   }
674
675   mutt_format_string (dest, destlen, min_width, max_width,
676                       right_justify, ' ', s, str_len (s), arboreal);
677 }
678
679 void mutt_format_s (char *dest,
680                     size_t destlen, const char *prefix, const char *s)
681 {
682   mutt_format_s_x (dest, destlen, prefix, s, 0);
683 }
684
685 void mutt_format_s_tree (char *dest,
686                          size_t destlen, const char *prefix, const char *s)
687 {
688   mutt_format_s_x (dest, destlen, prefix, s, 1);
689 }
690
691 /*
692  * mutt_paddstr (n, s) is almost equivalent to
693  * mutt_format_string (bigbuf, big, n, n, 0, ' ', s, big, 0), addstr (bigbuf)
694  */
695
696 void mutt_paddstr (int n, const char *s)
697 {
698   wchar_t wc;
699   int w;
700   size_t k;
701   size_t len = str_len (s);
702   mbstate_t mbstate;
703
704   memset (&mbstate, 0, sizeof (mbstate));
705   for (; len && (k = mbrtowc (&wc, s, len, &mbstate)); s += k, len -= k) {
706     if (k == (size_t) (-1) || k == (size_t) (-2)) {
707       k = (k == (size_t) (-1)) ? 1 : len;
708       wc = replacement_char ();
709     }
710     if (!IsWPrint (wc))
711       wc = '?';
712     w = wcwidth (wc);
713     if (w >= 0) {
714       if (w > n)
715         break;
716       addnstr ((char *) s, k);
717       n -= w;
718     }
719   }
720   while (n-- > 0)
721     addch (' ');
722 }
723
724 /*
725  * mutt_strwidth is like str_len except that it returns the width
726  * refering to the number of characters cells.
727  */
728
729 int mutt_strwidth (const char *s)
730 {
731   wchar_t wc;
732   int w;
733   size_t k, n;
734   mbstate_t mbstate;
735
736   if (!s)
737     return 0;
738
739   n = str_len (s);
740
741   memset (&mbstate, 0, sizeof (mbstate));
742   for (w = 0; n && (k = mbrtowc (&wc, s, n, &mbstate)); s += k, n -= k) {
743     if (k == (size_t) (-1) || k == (size_t) (-2)) {
744       k = (k == (size_t) (-1)) ? 1 : n;
745       wc = replacement_char ();
746     }
747     if (!IsWPrint (wc))
748       wc = '?';
749     w += wcwidth (wc);
750   }
751   return w;
752 }