Move more things about stdscr in lib-ui.
[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     wrefresh (stdscr);
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 = wgetch (stdscr);
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     waddstr (stdscr, 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   wprintw (stdscr, "%.*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     waddstr (stdscr, (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     wtimeout (stdscr, -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     mvwaddstr (stdscr, LINES - 1, 0, Errorbuf);
249     wclrtoeol (stdscr);
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     mvwaddstr (stdscr, LINES - 1, 0, Errorbuf);
301     wclrtoeol (stdscr);
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   waddstr (stdscr, Errorbuf);
317   SETCOLOR (MT_COLOR_NORMAL);
318 }
319
320 void curses_initialize(void)
321 {
322     ci_start_color();
323     keypad(stdscr, TRUE);
324     cbreak();
325     noecho();
326     typeahead (-1);               /* simulate smooth scrolling */
327     meta(stdscr, TRUE);
328 }
329
330 void curses_install(void)
331 {
332     SETCOLOR(MT_COLOR_NORMAL);
333     wclear(stdscr);
334     mutt_error   = mutt_curses_error;
335     mutt_message = mutt_curses_message;
336 }
337
338 void mutt_endwin (const char *msg)
339 {
340   if (!option (OPTNOCURSES)) {
341     CLEARLINE (LINES - 1);
342
343     wattrset (stdscr, A_NORMAL);
344     mutt_refresh ();
345     endwin ();
346   }
347
348   if (msg && *msg) {
349     puts (msg);
350     fflush (stdout);
351   }
352 }
353
354 void _mutt_perror (const char *s, const char* filename, int line)
355 {
356   char *p = strerror (errno);
357   mutt_error ("%s: %s (errno = %d) from %s:%i", s, p ? p : _("unknown error"), errno, filename, line);
358 }
359
360 /*
361  * prompts the user to enter a keystroke, and displays the octal value back
362  * to the user.
363  */
364 void mutt_what_key (void)
365 {
366   int ch;
367
368   mvwprintw (stdscr, LINES - 1, 0, _("Enter keys (^G to abort): "));
369   do {
370     ch = wgetch (stdscr);
371     if (ch != ERR && ch != ctrl ('G')) {
372       mutt_message (_("Char = %s, Octal = %o, Decimal = %d"),
373                     km_keyname (ch), ch, ch);
374     }
375   }
376   while (ch != ERR && ch != ctrl ('G'));
377
378   mutt_flushinp ();
379 }
380
381 int mutt_any_key_to_continue (const char *s)
382 {
383   struct termios t;
384   struct termios old;
385   int f, ch;
386
387   f = open ("/dev/tty", O_RDONLY);
388   tcgetattr (f, &t);
389   memcpy ((void *) &old, (void *) &t, sizeof (struct termios)); /* save original state */
390   t.c_lflag &= ~(ICANON | ECHO);
391   t.c_cc[VMIN] = 1;
392   t.c_cc[VTIME] = 0;
393   tcsetattr (f, TCSADRAIN, &t);
394   fflush (stdout);
395   if (s)
396     fputs (s, stdout);
397   else
398     fputs (_("Press any key to continue..."), stdout);
399   fflush (stdout);
400   ch = fgetc (stdin);
401   fflush (stdin);
402   tcsetattr (f, TCSADRAIN, &old);
403   close (f);
404   fputs ("\r\n", stdout);
405   mutt_clear_error ();
406   return (ch);
407 }
408
409 int _mutt_enter_fname (const char *prompt, char *buf, ssize_t blen,
410                        int *redraw, int buffy, int multiple, char ***files,
411                        int *numfiles)
412 {
413   event_t ch;
414
415   mvwaddstr (stdscr, LINES - 1, 0, (char *) prompt);
416   waddstr (stdscr, _(" ('?' for list): "));
417   if (buf[0])
418     waddstr (stdscr, buf);
419   wclrtoeol (stdscr);
420   mutt_refresh ();
421
422   ch = mutt_getch ();
423   if (ch.ch == -1) {
424     CLEARLINE (LINES - 1);
425     return (-1);
426   }
427   else if (ch.ch == '?') {
428     mutt_refresh ();
429     buf[0] = 0;
430     mutt_select_file (buf, blen, M_SEL_FOLDER | (multiple ? M_SEL_MULTI : 0),
431                       files, numfiles);
432     *redraw = REDRAW_FULL;
433   }
434   else {
435     char *pc = p_new(char, m_strlen(prompt) + 3);
436
437     sprintf(pc, "%s: ", prompt);
438     mutt_ungetch (ch.op ? 0 : ch.ch, ch.op ? ch.op : 0);
439     if (_mutt_get_field
440         (pc, buf, blen, (buffy ? M_EFILE : M_FILE) | M_CLEAR, multiple, files,
441          numfiles)
442         != 0)
443       buf[0] = 0;
444     MAYBE_REDRAW (*redraw);
445     p_delete(&pc);
446   }
447
448   return 0;
449 }
450
451 void mutt_ungetch (int ch, int op)
452 {
453   event_t tmp;
454
455   tmp.ch = ch;
456   tmp.op = op;
457
458   if (UngetCount >= UngetBufLen)
459     p_realloc(&KeyEvent, UngetBufLen += 128);
460
461   KeyEvent[UngetCount++] = tmp;
462 }
463
464 void mutt_flushinp (void)
465 {
466   UngetCount = 0;
467   flushinp ();
468 }
469
470 /* The argument can take 3 values:
471  * -1: restore the value of the last call
472  *  0: make the cursor invisible
473  *  1: make the cursor visible
474  */
475 void mutt_curs_set (int cursor)
476 {
477   static int SavedCursor = 1;
478
479   if (cursor < 0)
480     cursor = SavedCursor;
481   else
482     SavedCursor = cursor;
483
484   if (curs_set (cursor) == ERR) {
485     if (cursor == 1)            /* cnorm */
486       curs_set (2);             /* cvvis */
487   }
488 }
489
490 int mutt_multi_choice (const char *prompt, const char *letters)
491 {
492   event_t ch;
493   int choice;
494   char *p;
495
496   mvwaddstr (stdscr, LINES - 1, 0, prompt);
497   wclrtoeol (stdscr);
498   for (;;) {
499     mutt_refresh ();
500     ch = mutt_getch ();
501     if (ch.ch == -1 || CI_is_return (ch.ch)) {
502       choice = -1;
503       break;
504     }
505     else {
506       p = strchr (letters, ch.ch);
507       if (p) {
508         choice = p - letters + 1;
509         break;
510       }
511       else if (ch.ch <= '9' && ch.ch > '0') {
512         choice = ch.ch - '0';
513         if (choice <= m_strlen(letters))
514           break;
515       }
516     }
517     BEEP ();
518   }
519   CLEARLINE (LINES - 1);
520   mutt_refresh ();
521   return choice;
522 }
523
524 /*
525  * addwch would be provided by an up-to-date curses library
526  */
527
528 int mutt_addwch (wchar_t wc)
529 {
530   char buf[MB_LEN_MAX * 2];
531   mbstate_t mbstate;
532   ssize_t n1, n2;
533
534   p_clear(&mbstate, 1);
535   if ((n1 = wcrtomb(buf, wc, &mbstate)) == -1 ||
536       (n2 = wcrtomb(buf + n1, 0, &mbstate)) == -1)
537     return -1;                  /* ERR */
538   else
539     return waddstr (stdscr, buf);
540 }
541
542 ssize_t mutt_pretty_size(char *s, ssize_t len, ssize_t n)
543 {
544     if (n == 0)
545         return m_strcpy(s, len, "0K");
546
547     if (n < 10189)           /* 0.1K - 9.9K */
548         return snprintf(s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
549
550     if (n < 1023949)         /* 10K - 999K */
551         /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
552         return snprintf(s, len, "%ldK", (n + 51) / 1024);
553
554     if (n < 10433332)        /* 1.0M - 9.9M */
555         return snprintf(s, len, "%3.1fM", n / 1048576.0);
556
557     /* (10433332 + 52428) / 1048576 = 10 */
558     return snprintf (s, len, "%ldM", (n + 52428) / 1048576);
559 }
560
561 /*
562  * This formats a string, a bit like
563  * snprintf (dest, destlen, "%-*.*s", min_width, max_width, s),
564  * except that the widths refer to the number of character cells
565  * when printed.
566  */
567
568 void mutt_format_string (char *dest, ssize_t destlen,
569                          int min_width, int max_width,
570                          int right_justify, char m_pad_char,
571                          const char *s, ssize_t n, int arboreal)
572 {
573   char *p;
574   wchar_t wc;
575   int w;
576   ssize_t k, k2;
577   char scratch[MB_LEN_MAX];
578   mbstate_t mbstate1, mbstate2;
579
580   p_clear(&mbstate1, 1);
581   p_clear(&mbstate2, 1);
582   --destlen;
583   p = dest;
584   for (; n && (k = mbrtowc (&wc, s, n, &mbstate1)); s += k, n -= k) {
585     if (k == -1 || k == -2) {
586       k = (k == -1) ? 1 : n;
587       wc = CharsetReplacement;
588     }
589     if (arboreal && wc < M_TREE_MAX)
590       w = 1;                    /* hack */
591     else {
592       if (!iswprint(wc))
593         wc = '?';
594       w = wcwidth (wc);
595     }
596     if (w >= 0) {
597       if (w > max_width || (k2 = wcrtomb (scratch, wc, &mbstate2)) > destlen)
598         break;
599       min_width -= w;
600       max_width -= w;
601       m_strncpy(p, destlen, scratch, k2);
602       p += k2;
603       destlen -= k2;
604     }
605   }
606   w = destlen < min_width ? destlen : min_width;
607   if (w <= 0)
608     *p = '\0';
609   else if (right_justify) {
610     p[w] = '\0';
611     while (--p >= dest)
612       p[w] = *p;
613     while (--w >= 0)
614       dest[w] = m_pad_char;
615   }
616   else {
617     while (--w >= 0)
618       *p++ = m_pad_char;
619     *p = '\0';
620   }
621 }
622
623 /*
624  * This formats a string rather like
625  *   snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
626  *   snprintf (dest, destlen, fmt, s);
627  * except that the numbers in the conversion specification refer to
628  * the number of character cells when printed.
629  */
630
631 static void mutt_format_s_x (char *dest, ssize_t destlen,
632                              const char *prefix, const char *s, int arboreal)
633 {
634   int right_justify = 1;
635   char *p;
636   int min_width;
637   int max_width = INT_MAX;
638
639   if (*prefix == '-')
640     ++prefix, right_justify = 0;
641   min_width = strtol (prefix, &p, 10);
642   if (*p == '.') {
643     prefix = p + 1;
644     max_width = strtol (prefix, &p, 10);
645     if (p <= prefix)
646       max_width = INT_MAX;
647   }
648
649   mutt_format_string (dest, destlen, min_width, max_width,
650                       right_justify, ' ', s, m_strlen(s), arboreal);
651 }
652
653 void mutt_format_s (char *dest, ssize_t destlen,
654                     const char *prefix, const char *s)
655 {
656   mutt_format_s_x (dest, destlen, prefix, s, 0);
657 }
658
659 void mutt_format_s_tree (char *dest, ssize_t destlen,
660                          const char *prefix, const char *s)
661 {
662   mutt_format_s_x (dest, destlen, prefix, s, 1);
663 }
664
665 /*
666  * mutt_paddstr (n, s) is almost equivalent to
667  * mutt_format_string (bigbuf, big, n, n, 0, ' ', s, big, 0), waddstr (stdscr, bigbuf)
668  */
669
670 void mutt_paddstr (int n, const char *s)
671 {
672   wchar_t wc;
673   int w;
674   ssize_t k;
675   ssize_t len = m_strlen(s);
676   mbstate_t mbstate;
677
678   p_clear(&mbstate, 1);
679   for (; len && (k = mbrtowc (&wc, s, len, &mbstate)); s += k, len -= k) {
680     if (k == -1 || k == -2) {
681       k = (k == -1) ? 1 : len;
682       wc = CharsetReplacement;
683     }
684     if (!iswprint(wc))
685       wc = '?';
686     w = wcwidth (wc);
687     if (w >= 0) {
688       if (w > n)
689         break;
690       waddnstr (stdscr, (char *) s, k);
691       n -= w;
692     }
693   }
694   while (n-- > 0)
695     waddch (stdscr, ' ');
696 }
697
698 /* this routine should be called after receiving SIGWINCH */
699 void mutt_resize_screen (void)
700 {
701   char *cp;
702   int fd;
703   struct winsize w;
704
705   int rows, cols;
706
707   rows = -1;
708   cols = -1;
709   if ((fd = open ("/dev/tty", O_RDONLY)) != -1) {
710     if (ioctl (fd, TIOCGWINSZ, &w) != -1) {
711       rows = w.ws_row;
712       cols = w.ws_col;
713     }
714     close (fd);
715   }
716   if (rows <= 0) {
717     if ((cp = getenv ("LINES")) != NULL) {
718       rows = atoi (cp);
719     }
720     else
721       rows = 24;
722   }
723   if (cols <= 0) {
724     if ((cp = getenv ("COLUMNS")) != NULL)
725       cols = atoi (cp);
726     else
727       cols = 80;
728   }
729   resizeterm (rows, cols);
730 }