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