move more files.
[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 <lib-ui/curses.h>
24 #include <lib-ui/enter.h>
25
26 #include "mutt.h"
27 #include "mutt_menu.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 #ifdef KEY_RESIZE
94   /* ncurses 4.2 sends this when the screen is resized */
95   ch = KEY_RESIZE;
96   while (ch == KEY_RESIZE)
97 #endif /* KEY_RESIZE */
98     ch = getch ();
99   mutt_allow_interrupt (0);
100
101   if (SigInt)
102     mutt_query_exit ();
103
104   if (ch == ERR)
105     return err;
106
107   if ((ch & 0x80) && option (OPTMETAKEY)) {
108     /* send ALT-x as ESC-x */
109     ch &= ~0x80;
110     mutt_ungetch (ch, 0);
111     ret.ch = '\033';
112     ret.op = 0;
113     return ret;
114   }
115
116   ret.ch = ch;
117   ret.op = 0;
118   return (ch == ctrl ('G') ? err : ret);
119 }
120
121 int _mutt_get_field ( const char *field, char *buf, size_t buflen,
122                      int complete, int multiple, char ***files, int *numfiles)
123 {
124   int ret;
125   int x, y;
126
127   ENTER_STATE *es = mutt_new_enter_state ();
128
129   do {
130     CLEARLINE (LINES - 1);
131     addstr (field);
132     mutt_refresh ();
133     getyx (stdscr, y, x);
134     ret =
135       _mutt_enter_string (buf, buflen, y, x, complete, multiple, files,
136                           numfiles, es);
137   }
138   while (ret == 1);
139   CLEARLINE (LINES - 1);
140   mutt_free_enter_state (&es);
141
142   return (ret);
143 }
144
145 int mutt_get_field_unbuffered (char *msg, char *buf, size_t buflen, int flags)
146 {
147   int rc;
148
149   set_option (OPTUNBUFFEREDINPUT);
150   rc = mutt_get_field (msg, buf, buflen, flags);
151   unset_option (OPTUNBUFFEREDINPUT);
152
153   return (rc);
154 }
155
156 void mutt_clear_error (void)
157 {
158   Errorbuf[0] = 0;
159   if (!option (OPTNOCURSES))
160     CLEARLINE (LINES - 1);
161 }
162
163 void mutt_edit_file (const char *editor, const char *data)
164 {
165   char cmd[LONG_STRING];
166
167   mutt_endwin (NULL);
168   mutt_expand_file_fmt (cmd, sizeof (cmd), editor, data);
169   if (mutt_system (cmd) == -1)
170     mutt_error (_("Error running \"%s\"!"), cmd);
171   keypad (stdscr, TRUE);
172   clearok (stdscr, TRUE);
173 }
174
175 int mutt_yesorno (const char *msg, int def)
176 {
177   event_t ch;
178   char *yes = _("yes");
179   char *no = _("no");
180   char *answer_string;
181   size_t answer_string_len;
182
183 #ifdef HAVE_LANGINFO_YESEXPR
184   char *expr;
185   regex_t reyes;
186   regex_t reno;
187   int reyes_ok;
188   int reno_ok;
189   char answer[2];
190
191   answer[1] = 0;
192
193   reyes_ok = (expr = nl_langinfo (YESEXPR)) && expr[0] == '^' &&
194     !regcomp (&reyes, expr, REG_NOSUB | REG_EXTENDED);
195   reno_ok = (expr = nl_langinfo (NOEXPR)) && expr[0] == '^' &&
196     !regcomp (&reno, expr, REG_NOSUB | REG_EXTENDED);
197 #endif
198
199   CLEARLINE (LINES - 1);
200
201   /*
202    * In order to prevent the default answer to the question to wrapped
203    * around the screen in the even the question is wider than the screen,
204    * ensure there is enough room for the answer and truncate the question
205    * to fit.
206    */
207   answer_string = p_new(char, COLS + 1);
208   snprintf (answer_string, COLS + 1, " ([%s]/%s): ", def == M_YES ? yes : no,
209             def == M_YES ? no : yes);
210   answer_string_len = m_strlen(answer_string);
211   printw ("%.*s%s", COLS - answer_string_len, msg, answer_string);
212   p_delete(&answer_string);
213
214   for (;;) {
215     mutt_refresh ();
216     ch = mutt_getch ();
217     if (CI_is_return (ch.ch))
218       break;
219     if (ch.ch == -1) {
220       def = -1;
221       break;
222     }
223
224 #ifdef HAVE_LANGINFO_YESEXPR
225     answer[0] = ch.ch;
226     if (reyes_ok ? (regexec (&reyes, answer, 0, 0, 0) == 0) :
227 #else
228     if (
229 #endif
230          (tolower (ch.ch) == *yes)) {
231       def = M_YES;
232       break;
233     }
234     else if (
235 #ifdef HAVE_LANGINFO_YESEXPR
236               reno_ok ? (regexec (&reno, answer, 0, 0, 0) == 0) :
237 #endif
238               (tolower (ch.ch) == *no)) {
239       def = M_NO;
240       break;
241     }
242     else {
243       BEEP ();
244     }
245   }
246
247 #ifdef HAVE_LANGINFO_YESEXPR
248   if (reyes_ok)
249     regfree (&reyes);
250   if (reno_ok)
251     regfree (&reno);
252 #endif
253
254   if (def != -1) {
255     addstr ((char *) (def == M_YES ? yes : no));
256     mutt_refresh ();
257   }
258   return (def);
259 }
260
261 /* this function is called when the user presses the abort key */
262 void mutt_query_exit (void)
263 {
264   mutt_flushinp ();
265   curs_set (1);
266   if (Timeout)
267     timeout (-1);               /* restore blocking operation */
268   if (mutt_yesorno (_("Exit Madmutt?"), M_YES) == M_YES) {
269     mutt_endwin (NULL);
270     exit (1);
271   }
272   mutt_clear_error ();
273   mutt_curs_set (-1);
274   SigInt = 0;
275 }
276
277 void mutt_curses_error (const char *fmt, ...)
278 {
279   char TmpErrorbuf[STRING];
280   va_list ap;
281
282   va_start (ap, fmt);
283   vsnprintf (Errorbuf, sizeof (Errorbuf), fmt, ap);
284   va_end (ap);
285
286   debug_print (1, ("%s\n", Errorbuf));
287   mutt_format_string (TmpErrorbuf, sizeof (TmpErrorbuf),
288                       0, COLS - 2, 0, 0, Errorbuf, sizeof (Errorbuf), 0);
289   snprintf (Errorbuf, sizeof (Errorbuf), "%s", TmpErrorbuf);    /* overkill */
290
291   if (!option (OPTKEEPQUIET)) {
292     BEEP ();
293     SETCOLOR (MT_COLOR_ERROR);
294     mvaddstr (LINES - 1, 0, Errorbuf);
295     clrtoeol ();
296     SETCOLOR (MT_COLOR_NORMAL);
297     mutt_refresh ();
298   }
299
300   set_option (OPTMSGERR);
301 }
302
303 void mutt_progress_bar (progress_t* progress, long pos) {
304   char posstr[SHORT_STRING];
305
306   if (!pos) {
307     if (!NetInc)
308       mutt_message (progress->msg);
309     else {
310       if (progress->size)
311         mutt_pretty_size (progress->sizestr, sizeof (progress->sizestr),
312                           progress->size);
313       progress->pos = 0;
314     }
315   }
316
317   if (!NetInc)
318     return;
319
320   if (pos >= progress->pos + (NetInc << 10)) {
321     progress->pos = pos;
322     pos = pos / (NetInc << 10) * (NetInc << 10);
323     mutt_pretty_size (posstr, sizeof (posstr), pos);
324     if (progress->size)
325       mutt_message ("%s %s/%s", progress->msg, posstr, progress->sizestr);
326     else
327       mutt_message ("%s %s", progress->msg, posstr);
328   }
329 }
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 || m_strcmp(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, m_strlen(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   for (;;) {
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 <= m_strlen(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   p_clear(&mbstate, 1);
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, ssize_t destlen,
586                          int min_width, int max_width,
587                          int right_justify, char m_pad_char,
588                          const char *s, ssize_t n, int arboreal)
589 {
590   char *p;
591   wchar_t wc;
592   int w;
593   ssize_t k, k2;
594   char scratch[MB_LEN_MAX];
595   mbstate_t mbstate1, mbstate2;
596
597   p_clear(&mbstate1, 1);
598   p_clear(&mbstate2, 1);
599   --destlen;
600   p = dest;
601   for (; n && (k = mbrtowc (&wc, s, n, &mbstate1)); s += k, n -= k) {
602     if (k == -1 || k == -2) {
603       k = (k == -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 = 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, m_strlen(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 = m_strlen(s);
694   mbstate_t mbstate;
695
696   p_clear(&mbstate, 1);
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 m_strlenexcept 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 = m_strlen(s);
732
733   p_clear(&mbstate, 1);
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 }