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