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