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