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