7562ad89ac292c15c73427336e10a0a927746d31
[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_enter_fname (const char *prompt, char *buf, ssize_t blen,
394                        int *redraw, int buffy, int multiple, char ***files,
395                        int *numfiles)
396 {
397   event_t ch;
398
399   mvaddstr (LINES - 1, 0, (char *) prompt);
400   addstr (_(" ('?' for list): "));
401   if (buf[0])
402     addstr (buf);
403   clrtoeol ();
404   mutt_refresh ();
405
406   ch = mutt_getch ();
407   if (ch.ch == -1) {
408     CLEARLINE (LINES - 1);
409     return (-1);
410   }
411   else if (ch.ch == '?') {
412     mutt_refresh ();
413     buf[0] = 0;
414     _mutt_select_file (buf, blen, M_SEL_FOLDER | (multiple ? M_SEL_MULTI : 0),
415                        files, numfiles);
416     *redraw = REDRAW_FULL;
417   }
418   else {
419     char *pc = p_new(char, m_strlen(prompt) + 3);
420
421     sprintf(pc, "%s: ", prompt);
422     mutt_ungetch (ch.op ? 0 : ch.ch, ch.op ? ch.op : 0);
423     if (_mutt_get_field
424         (pc, buf, blen, (buffy ? M_EFILE : M_FILE) | M_CLEAR, multiple, files,
425          numfiles)
426         != 0)
427       buf[0] = 0;
428     MAYBE_REDRAW (*redraw);
429     p_delete(&pc);
430   }
431
432   return 0;
433 }
434
435 void mutt_ungetch (int ch, int op)
436 {
437   event_t tmp;
438
439   tmp.ch = ch;
440   tmp.op = op;
441
442   if (UngetCount >= UngetBufLen)
443     p_realloc(&KeyEvent, UngetBufLen += 128);
444
445   KeyEvent[UngetCount++] = tmp;
446 }
447
448 void mutt_flushinp (void)
449 {
450   UngetCount = 0;
451   flushinp ();
452 }
453
454 #if (defined(USE_SLANG_CURSES) || defined(HAVE_CURS_SET))
455 /* The argument can take 3 values:
456  * -1: restore the value of the last call
457  *  0: make the cursor invisible
458  *  1: make the cursor visible
459  */
460 void mutt_curs_set (int cursor)
461 {
462   static int SavedCursor = 1;
463
464   if (cursor < 0)
465     cursor = SavedCursor;
466   else
467     SavedCursor = cursor;
468
469   if (curs_set (cursor) == ERR) {
470     if (cursor == 1)            /* cnorm */
471       curs_set (2);             /* cvvis */
472   }
473 }
474 #endif
475
476 int mutt_multi_choice (char *prompt, char *letters)
477 {
478   event_t ch;
479   int choice;
480   char *p;
481
482   mvaddstr (LINES - 1, 0, prompt);
483   clrtoeol ();
484   for (;;) {
485     mutt_refresh ();
486     ch = mutt_getch ();
487     if (ch.ch == -1 || CI_is_return (ch.ch)) {
488       choice = -1;
489       break;
490     }
491     else {
492       p = strchr (letters, ch.ch);
493       if (p) {
494         choice = p - letters + 1;
495         break;
496       }
497       else if (ch.ch <= '9' && ch.ch > '0') {
498         choice = ch.ch - '0';
499         if (choice <= m_strlen(letters))
500           break;
501       }
502     }
503     BEEP ();
504   }
505   CLEARLINE (LINES - 1);
506   mutt_refresh ();
507   return choice;
508 }
509
510 /*
511  * addwch would be provided by an up-to-date curses library
512  */
513
514 int mutt_addwch (wchar_t wc)
515 {
516   char buf[MB_LEN_MAX * 2];
517   mbstate_t mbstate;
518   ssize_t n1, n2;
519
520   p_clear(&mbstate, 1);
521   if ((n1 = wcrtomb(buf, wc, &mbstate)) == -1 ||
522       (n2 = wcrtomb(buf + n1, 0, &mbstate)) == -1)
523     return -1;                  /* ERR */
524   else
525     return addstr (buf);
526 }
527
528 ssize_t mutt_pretty_size(char *s, ssize_t len, ssize_t n)
529 {
530     if (n == 0)
531         return m_strcpy(s, len, "0K");
532
533     if (n < 10189)           /* 0.1K - 9.9K */
534         return snprintf(s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
535
536     if (n < 1023949)         /* 10K - 999K */
537         /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
538         return snprintf(s, len, "%ldK", (n + 51) / 1024);
539
540     if (n < 10433332)        /* 1.0M - 9.9M */
541         return snprintf(s, len, "%3.1fM", n / 1048576.0);
542
543     /* (10433332 + 52428) / 1048576 = 10 */
544     return snprintf (s, len, "%ldM", (n + 52428) / 1048576);
545 }
546
547 /*
548  * This formats a string, a bit like
549  * snprintf (dest, destlen, "%-*.*s", min_width, max_width, s),
550  * except that the widths refer to the number of character cells
551  * when printed.
552  */
553
554 void mutt_format_string (char *dest, ssize_t destlen,
555                          int min_width, int max_width,
556                          int right_justify, char m_pad_char,
557                          const char *s, ssize_t n, int arboreal)
558 {
559   char *p;
560   wchar_t wc;
561   int w;
562   ssize_t k, k2;
563   char scratch[MB_LEN_MAX];
564   mbstate_t mbstate1, mbstate2;
565
566   p_clear(&mbstate1, 1);
567   p_clear(&mbstate2, 1);
568   --destlen;
569   p = dest;
570   for (; n && (k = mbrtowc (&wc, s, n, &mbstate1)); s += k, n -= k) {
571     if (k == -1 || k == -2) {
572       k = (k == -1) ? 1 : n;
573       wc = CharsetReplacement;
574     }
575     if (arboreal && wc < M_TREE_MAX)
576       w = 1;                    /* hack */
577     else {
578       if (!iswprint(wc))
579         wc = '?';
580       w = wcwidth (wc);
581     }
582     if (w >= 0) {
583       if (w > max_width || (k2 = wcrtomb (scratch, wc, &mbstate2)) > destlen)
584         break;
585       min_width -= w;
586       max_width -= w;
587       m_strncpy(p, destlen, scratch, k2);
588       p += k2;
589       destlen -= k2;
590     }
591   }
592   w = destlen < min_width ? destlen : min_width;
593   if (w <= 0)
594     *p = '\0';
595   else if (right_justify) {
596     p[w] = '\0';
597     while (--p >= dest)
598       p[w] = *p;
599     while (--w >= 0)
600       dest[w] = m_pad_char;
601   }
602   else {
603     while (--w >= 0)
604       *p++ = m_pad_char;
605     *p = '\0';
606   }
607 }
608
609 /*
610  * This formats a string rather like
611  *   snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
612  *   snprintf (dest, destlen, fmt, s);
613  * except that the numbers in the conversion specification refer to
614  * the number of character cells when printed.
615  */
616
617 static void mutt_format_s_x (char *dest, ssize_t destlen,
618                              const char *prefix, const char *s, int arboreal)
619 {
620   int right_justify = 1;
621   char *p;
622   int min_width;
623   int max_width = INT_MAX;
624
625   if (*prefix == '-')
626     ++prefix, right_justify = 0;
627   min_width = strtol (prefix, &p, 10);
628   if (*p == '.') {
629     prefix = p + 1;
630     max_width = strtol (prefix, &p, 10);
631     if (p <= prefix)
632       max_width = INT_MAX;
633   }
634
635   mutt_format_string (dest, destlen, min_width, max_width,
636                       right_justify, ' ', s, m_strlen(s), arboreal);
637 }
638
639 void mutt_format_s (char *dest, ssize_t destlen,
640                     const char *prefix, const char *s)
641 {
642   mutt_format_s_x (dest, destlen, prefix, s, 0);
643 }
644
645 void mutt_format_s_tree (char *dest, ssize_t destlen,
646                          const char *prefix, const char *s)
647 {
648   mutt_format_s_x (dest, destlen, prefix, s, 1);
649 }
650
651 /*
652  * mutt_paddstr (n, s) is almost equivalent to
653  * mutt_format_string (bigbuf, big, n, n, 0, ' ', s, big, 0), addstr (bigbuf)
654  */
655
656 void mutt_paddstr (int n, const char *s)
657 {
658   wchar_t wc;
659   int w;
660   ssize_t k;
661   ssize_t len = m_strlen(s);
662   mbstate_t mbstate;
663
664   p_clear(&mbstate, 1);
665   for (; len && (k = mbrtowc (&wc, s, len, &mbstate)); s += k, len -= k) {
666     if (k == -1 || k == -2) {
667       k = (k == -1) ? 1 : len;
668       wc = CharsetReplacement;
669     }
670     if (!iswprint(wc))
671       wc = '?';
672     w = wcwidth (wc);
673     if (w >= 0) {
674       if (w > n)
675         break;
676       addnstr ((char *) s, k);
677       n -= w;
678     }
679   }
680   while (n-- > 0)
681     addch (' ');
682 }
683