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