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