many simplifications, copyright statements.
[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 <wctype.h>
20 #include <termios.h>
21 #include <sys/types.h>
22 #include <fcntl.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <ctype.h>
28
29 #ifdef HAVE_LANGINFO_YESEXPR
30 #include <langinfo.h>
31 #endif
32
33 #include <lib-lib/mem.h>
34 #include <lib-lib/str.h>
35 #include <lib-lib/macros.h>
36 #include <lib-lib/file.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 "charset.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 ssize_t UngetCount = 0;
54 static ssize_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, ssize_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, ssize_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   ssize_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) : tolower (ch.ch) == *yes)
224 #else
225     if (tolower (ch.ch) == *yes)
226 #endif
227     {
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     } else {
239       BEEP ();
240     }
241   }
242
243 #ifdef HAVE_LANGINFO_YESEXPR
244   if (reyes_ok)
245     regfree (&reyes);
246   if (reno_ok)
247     regfree (&reno);
248 #endif
249
250   if (def != -1) {
251     addstr ((char *) (def == M_YES ? yes : no));
252     mutt_refresh ();
253   }
254   return (def);
255 }
256
257 /* this function is called when the user presses the abort key */
258 void mutt_query_exit (void)
259 {
260   mutt_flushinp ();
261   curs_set (1);
262   if (Timeout)
263     timeout (-1);               /* restore blocking operation */
264   if (mutt_yesorno (_("Exit Madmutt?"), M_YES) == M_YES) {
265     mutt_endwin (NULL);
266     exit (1);
267   }
268   mutt_clear_error ();
269   mutt_curs_set (-1);
270   SigInt = 0;
271 }
272
273 void mutt_curses_error (const char *fmt, ...)
274 {
275   char TmpErrorbuf[STRING];
276   va_list ap;
277
278   va_start (ap, fmt);
279   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
280   va_end (ap);
281
282   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
283                       0, COLS - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
284   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
285
286   if (!option (OPTKEEPQUIET)) {
287     BEEP ();
288     SETCOLOR (MT_COLOR_ERROR);
289     mvaddstr (LINES - 1, 0, Errorbuf);
290     clrtoeol ();
291     SETCOLOR (MT_COLOR_NORMAL);
292     mutt_refresh ();
293   }
294
295   set_option (OPTMSGERR);
296 }
297
298 void mutt_progress_bar (progress_t* progress, long pos) {
299   char posstr[SHORT_STRING];
300
301   if (!pos) {
302     if (!NetInc)
303       mutt_message (progress->msg);
304     else {
305       if (progress->size)
306         mutt_pretty_size (progress->sizestr, sizeof (progress->sizestr),
307                           progress->size);
308       progress->pos = 0;
309     }
310   }
311
312   if (!NetInc)
313     return;
314
315   if (pos >= progress->pos + (NetInc << 10)) {
316     progress->pos = pos;
317     pos = pos / (NetInc << 10) * (NetInc << 10);
318     mutt_pretty_size (posstr, sizeof (posstr), pos);
319     if (progress->size)
320       mutt_message ("%s %s/%s", progress->msg, posstr, progress->sizestr);
321     else
322       mutt_message ("%s %s", progress->msg, posstr);
323   }
324 }
325
326 void mutt_curses_message (const char *fmt, ...)
327 {
328   char TmpErrorbuf[STRING];
329   va_list ap;
330
331   va_start (ap, fmt);
332   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
333   va_end (ap);
334
335   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
336                       0, COLS - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
337   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
338
339   if (!option (OPTKEEPQUIET)) {
340     SETCOLOR (MT_COLOR_MESSAGE);
341     mvaddstr (LINES - 1, 0, Errorbuf);
342     clrtoeol ();
343     SETCOLOR (MT_COLOR_NORMAL);
344     mutt_refresh ();
345   }
346
347   unset_option (OPTMSGERR);
348 }
349
350 void mutt_show_error (void)
351 {
352   if (option (OPTKEEPQUIET))
353     return;
354
355   SETCOLOR (option (OPTMSGERR) ? MT_COLOR_ERROR : MT_COLOR_MESSAGE);
356   CLEARLINE (LINES - 1);
357   addstr (Errorbuf);
358   SETCOLOR (MT_COLOR_NORMAL);
359 }
360
361 void mutt_endwin (const char *msg)
362 {
363   if (!option (OPTNOCURSES)) {
364     CLEARLINE (LINES - 1);
365
366     attrset (A_NORMAL);
367     mutt_refresh ();
368     endwin ();
369   }
370
371   if (msg && *msg) {
372     puts (msg);
373     fflush (stdout);
374   }
375 }
376
377 void _mutt_perror (const char *s, const char* filename, int line)
378 {
379   char *p = strerror (errno);
380   mutt_error ("%s: %s (errno = %d) from %s:%i", s, p ? p : _("unknown error"), errno, filename, line);
381 }
382
383 int mutt_any_key_to_continue (const char *s)
384 {
385   struct termios t;
386   struct termios old;
387   int f, ch;
388
389   f = open ("/dev/tty", O_RDONLY);
390   tcgetattr (f, &t);
391   memcpy ((void *) &old, (void *) &t, sizeof (struct termios)); /* save original state */
392   t.c_lflag &= ~(ICANON | ECHO);
393   t.c_cc[VMIN] = 1;
394   t.c_cc[VTIME] = 0;
395   tcsetattr (f, TCSADRAIN, &t);
396   fflush (stdout);
397   if (s)
398     fputs (s, stdout);
399   else
400     fputs (_("Press any key to continue..."), stdout);
401   fflush (stdout);
402   ch = fgetc (stdin);
403   fflush (stdin);
404   tcsetattr (f, TCSADRAIN, &old);
405   close (f);
406   fputs ("\r\n", stdout);
407   mutt_clear_error ();
408   return (ch);
409 }
410
411 int mutt_do_pager (const char *banner,
412                    const char *tempfile, int do_color, pager_t * info)
413 {
414   int rc;
415
416   if (!Pager || m_strcmp(Pager, "builtin") == 0)
417     rc = mutt_pager (banner, tempfile, do_color, info);
418   else {
419     char cmd[STRING];
420
421     mutt_endwin (NULL);
422     mutt_expand_file_fmt (cmd, sizeof (cmd), Pager, tempfile);
423     if (mutt_system (cmd) == -1) {
424       mutt_error (_("Error running \"%s\"!"), cmd);
425       rc = -1;
426     }
427     else
428       rc = 0;
429     mutt_unlink (tempfile);
430   }
431
432   return rc;
433 }
434
435 int _mutt_enter_fname (const char *prompt, char *buf, ssize_t blen,
436                        int *redraw, int buffy, int multiple, char ***files,
437                        int *numfiles)
438 {
439   event_t ch;
440
441   mvaddstr (LINES - 1, 0, (char *) prompt);
442   addstr (_(" ('?' for list): "));
443   if (buf[0])
444     addstr (buf);
445   clrtoeol ();
446   mutt_refresh ();
447
448   ch = mutt_getch ();
449   if (ch.ch == -1) {
450     CLEARLINE (LINES - 1);
451     return (-1);
452   }
453   else if (ch.ch == '?') {
454     mutt_refresh ();
455     buf[0] = 0;
456     _mutt_select_file (buf, blen, M_SEL_FOLDER | (multiple ? M_SEL_MULTI : 0),
457                        files, numfiles);
458     *redraw = REDRAW_FULL;
459   }
460   else {
461     char *pc = p_new(char, m_strlen(prompt) + 3);
462
463     sprintf (pc, "%s: ", prompt);       /* __SPRINTF_CHECKED__ */
464     mutt_ungetch (ch.op ? 0 : ch.ch, ch.op ? ch.op : 0);
465     if (_mutt_get_field
466         (pc, buf, blen, (buffy ? M_EFILE : M_FILE) | M_CLEAR, multiple, files,
467          numfiles)
468         != 0)
469       buf[0] = 0;
470     MAYBE_REDRAW (*redraw);
471     p_delete(&pc);
472   }
473
474   return 0;
475 }
476
477 void mutt_ungetch (int ch, int op)
478 {
479   event_t tmp;
480
481   tmp.ch = ch;
482   tmp.op = op;
483
484   if (UngetCount >= UngetBufLen)
485     p_realloc(&KeyEvent, UngetBufLen += 128);
486
487   KeyEvent[UngetCount++] = tmp;
488 }
489
490 void mutt_flushinp (void)
491 {
492   UngetCount = 0;
493   flushinp ();
494 }
495
496 #if (defined(USE_SLANG_CURSES) || defined(HAVE_CURS_SET))
497 /* The argument can take 3 values:
498  * -1: restore the value of the last call
499  *  0: make the cursor invisible
500  *  1: make the cursor visible
501  */
502 void mutt_curs_set (int cursor)
503 {
504   static int SavedCursor = 1;
505
506   if (cursor < 0)
507     cursor = SavedCursor;
508   else
509     SavedCursor = cursor;
510
511   if (curs_set (cursor) == ERR) {
512     if (cursor == 1)            /* cnorm */
513       curs_set (2);             /* cvvis */
514   }
515 }
516 #endif
517
518 int mutt_multi_choice (char *prompt, char *letters)
519 {
520   event_t ch;
521   int choice;
522   char *p;
523
524   mvaddstr (LINES - 1, 0, prompt);
525   clrtoeol ();
526   for (;;) {
527     mutt_refresh ();
528     ch = mutt_getch ();
529     if (ch.ch == -1 || CI_is_return (ch.ch)) {
530       choice = -1;
531       break;
532     }
533     else {
534       p = strchr (letters, ch.ch);
535       if (p) {
536         choice = p - letters + 1;
537         break;
538       }
539       else if (ch.ch <= '9' && ch.ch > '0') {
540         choice = ch.ch - '0';
541         if (choice <= m_strlen(letters))
542           break;
543       }
544     }
545     BEEP ();
546   }
547   CLEARLINE (LINES - 1);
548   mutt_refresh ();
549   return choice;
550 }
551
552 /*
553  * addwch would be provided by an up-to-date curses library
554  */
555
556 int mutt_addwch (wchar_t wc)
557 {
558   char buf[MB_LEN_MAX * 2];
559   mbstate_t mbstate;
560   ssize_t n1, n2;
561
562   p_clear(&mbstate, 1);
563   if ((n1 = wcrtomb(buf, wc, &mbstate)) == -1 ||
564       (n2 = wcrtomb(buf + n1, 0, &mbstate)) == -1)
565     return -1;                  /* ERR */
566   else
567     return addstr (buf);
568 }
569
570
571 /*
572  * This formats a string, a bit like
573  * snprintf (dest, destlen, "%-*.*s", min_width, max_width, s),
574  * except that the widths refer to the number of character cells
575  * when printed.
576  */
577
578 void mutt_format_string (char *dest, ssize_t destlen,
579                          int min_width, int max_width,
580                          int right_justify, char m_pad_char,
581                          const char *s, ssize_t n, int arboreal)
582 {
583   char *p;
584   wchar_t wc;
585   int w;
586   ssize_t k, k2;
587   char scratch[MB_LEN_MAX];
588   mbstate_t mbstate1, mbstate2;
589
590   p_clear(&mbstate1, 1);
591   p_clear(&mbstate2, 1);
592   --destlen;
593   p = dest;
594   for (; n && (k = mbrtowc (&wc, s, n, &mbstate1)); s += k, n -= k) {
595     if (k == -1 || k == -2) {
596       k = (k == -1) ? 1 : n;
597       wc = CharsetReplacement;
598     }
599     if (arboreal && wc < M_TREE_MAX)
600       w = 1;                    /* hack */
601     else {
602       if (!IsWPrint (wc))
603         wc = '?';
604       w = wcwidth (wc);
605     }
606     if (w >= 0) {
607       if (w > max_width || (k2 = wcrtomb (scratch, wc, &mbstate2)) > destlen)
608         break;
609       min_width -= w;
610       max_width -= w;
611       strncpy (p, scratch, k2);
612       p += k2;
613       destlen -= k2;
614     }
615   }
616   w = destlen < min_width ? destlen : min_width;
617   if (w <= 0)
618     *p = '\0';
619   else if (right_justify) {
620     p[w] = '\0';
621     while (--p >= dest)
622       p[w] = *p;
623     while (--w >= 0)
624       dest[w] = m_pad_char;
625   }
626   else {
627     while (--w >= 0)
628       *p++ = m_pad_char;
629     *p = '\0';
630   }
631 }
632
633 /*
634  * This formats a string rather like
635  *   snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
636  *   snprintf (dest, destlen, fmt, s);
637  * except that the numbers in the conversion specification refer to
638  * the number of character cells when printed.
639  */
640
641 static void mutt_format_s_x (char *dest, ssize_t destlen,
642                              const char *prefix, const char *s, int arboreal)
643 {
644   int right_justify = 1;
645   char *p;
646   int min_width;
647   int max_width = INT_MAX;
648
649   if (*prefix == '-')
650     ++prefix, right_justify = 0;
651   min_width = strtol (prefix, &p, 10);
652   if (*p == '.') {
653     prefix = p + 1;
654     max_width = strtol (prefix, &p, 10);
655     if (p <= prefix)
656       max_width = INT_MAX;
657   }
658
659   mutt_format_string (dest, destlen, min_width, max_width,
660                       right_justify, ' ', s, m_strlen(s), arboreal);
661 }
662
663 void mutt_format_s (char *dest, ssize_t destlen,
664                     const char *prefix, const char *s)
665 {
666   mutt_format_s_x (dest, destlen, prefix, s, 0);
667 }
668
669 void mutt_format_s_tree (char *dest, ssize_t destlen,
670                          const char *prefix, const char *s)
671 {
672   mutt_format_s_x (dest, destlen, prefix, s, 1);
673 }
674
675 /*
676  * mutt_paddstr (n, s) is almost equivalent to
677  * mutt_format_string (bigbuf, big, n, n, 0, ' ', s, big, 0), addstr (bigbuf)
678  */
679
680 void mutt_paddstr (int n, const char *s)
681 {
682   wchar_t wc;
683   int w;
684   ssize_t k;
685   ssize_t len = m_strlen(s);
686   mbstate_t mbstate;
687
688   p_clear(&mbstate, 1);
689   for (; len && (k = mbrtowc (&wc, s, len, &mbstate)); s += k, len -= k) {
690     if (k == -1 || k == -2) {
691       k = (k == -1) ? 1 : len;
692       wc = CharsetReplacement;
693     }
694     if (!IsWPrint (wc))
695       wc = '?';
696     w = wcwidth (wc);
697     if (w >= 0) {
698       if (w > n)
699         break;
700       addnstr ((char *) s, k);
701       n -= w;
702     }
703   }
704   while (n-- > 0)
705     addch (' ');
706 }
707
708 /*
709  * mutt_strwidth is like m_strlenexcept that it returns the width
710  * refering to the number of characters cells.
711  */
712
713 int mutt_strwidth (const char *s)
714 {
715   wchar_t wc;
716   int w;
717   ssize_t k, n;
718   mbstate_t mbstate;
719
720   if (!s)
721     return 0;
722
723   n = m_strlen(s);
724
725   p_clear(&mbstate, 1);
726   for (w = 0; n && (k = mbrtowc (&wc, s, n, &mbstate)); s += k, n -= k) {
727     if (k == -1 || k == -2) {
728       k = (k == -1) ? 1 : n;
729       wc = CharsetReplacement;
730     }
731     if (!IsWPrint (wc))
732       wc = '?';
733     w += wcwidth (wc);
734   }
735   return w;
736 }