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