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