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