Import madtty, use it to deal with colors from now on as it needs to know what is...
[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     start_color();
315     madtty_init_colors();
316     ci_start_color();
317     noecho();
318     raw();
319     keypad(stdscr, true);
320     typeahead(-1);
321     meta(stdscr, true);
322     curs_set(0);
323     ESCDELAY = 50;
324 }
325
326 /*
327  * prompts the user to enter a keystroke, and displays the octal value back
328  * to the user.
329  */
330 void mutt_what_key (void)
331 {
332   int ch;
333
334   mvwprintw(stdscr, LINES - 1, 0, _("Enter keys (^G to abort): "));
335   do {
336     ch = getch();
337     if (ch != ERR && ch != ctrl ('G')) {
338       mutt_message (_("Char = %s, Octal = %o, Decimal = %d"),
339                     km_keyname (ch), ch, ch);
340     }
341   }
342   while (ch != ERR && ch != ctrl ('G'));
343
344   mutt_flushinp ();
345 }
346
347 int mutt_any_key_to_continue (const char *s)
348 {
349   struct termios t;
350   struct termios old;
351   int f, ch;
352
353   f = open ("/dev/tty", O_RDONLY);
354   tcgetattr (f, &t);
355   memcpy ((void *) &old, (void *) &t, sizeof (struct termios)); /* save original state */
356   t.c_lflag &= ~(ICANON | ECHO);
357   t.c_cc[VMIN] = 1;
358   t.c_cc[VTIME] = 0;
359   tcsetattr (f, TCSADRAIN, &t);
360   fflush (stdout);
361   if (s)
362     fputs (s, stdout);
363   else
364     fputs (_("Press any key to continue..."), stdout);
365   fflush (stdout);
366   ch = fgetc (stdin);
367   fflush (stdin);
368   tcsetattr (f, TCSADRAIN, &old);
369   close (f);
370   fputs ("\r\n", stdout);
371   mutt_clear_error ();
372   return (ch);
373 }
374
375 int _mutt_enter_fname (const char *prompt, char *buf, ssize_t blen,
376                        int *redraw, int buffy, int multiple, char ***files,
377                        int *numfiles)
378 {
379   event_t ch;
380
381   mvwaddstr(stdscr, LINES - 1, 0, (char *) prompt);
382   waddstr(stdscr, _(" ('?' for list): "));
383   if (buf[0])
384     waddstr (stdscr, buf);
385   wclrtoeol (stdscr);
386   mutt_refresh ();
387
388   ch = mutt_getch ();
389   if (ch.ch == -1) {
390     CLEARLINE(stdscr, LINES - 1);
391     return (-1);
392   }
393   else if (ch.ch == '?') {
394     mutt_refresh ();
395     buf[0] = 0;
396     mutt_select_file (buf, blen, M_SEL_FOLDER | (multiple ? M_SEL_MULTI : 0),
397                       files, numfiles);
398     *redraw = REDRAW_FULL;
399   }
400   else {
401     char *pc = p_new(char, m_strlen(prompt) + 3);
402
403     sprintf(pc, "%s: ", prompt);
404     mutt_ungetch (ch.op ? 0 : ch.ch, ch.op ? ch.op : 0);
405     if (_mutt_get_field
406         (pc, buf, blen, (buffy ? M_EFILE : M_FILE) | M_CLEAR, multiple, files,
407          numfiles)
408         != 0)
409       buf[0] = 0;
410     MAYBE_REDRAW (*redraw);
411     p_delete(&pc);
412   }
413
414   return 0;
415 }
416
417 void mutt_ungetch (int ch, int op)
418 {
419   event_t tmp;
420
421   tmp.ch = ch;
422   tmp.op = op;
423
424   if (UngetCount >= UngetBufLen)
425     p_realloc(&KeyEvent, UngetBufLen += 128);
426
427   KeyEvent[UngetCount++] = tmp;
428 }
429
430 void mutt_flushinp (void)
431 {
432   UngetCount = 0;
433   flushinp ();
434 }
435
436 /* The argument can take 3 values:
437  * -1: restore the value of the last call
438  *  0: make the cursor invisible
439  *  1: make the cursor visible
440  */
441 void mutt_curs_set (int cursor)
442 {
443   static int SavedCursor = 1;
444
445   if (cursor < 0)
446     cursor = SavedCursor;
447   else
448     SavedCursor = cursor;
449
450   if (curs_set (cursor) == ERR) {
451     if (cursor == 1)            /* cnorm */
452       curs_set (2);             /* cvvis */
453   }
454 }
455
456 int mutt_multi_choice (const char *prompt, const char *letters)
457 {
458   event_t ch;
459   int choice;
460   char *p;
461
462   mvwaddstr (stdscr, LINES - 1, 0, prompt);
463   wclrtoeol (stdscr);
464   for (;;) {
465     mutt_refresh ();
466     ch = mutt_getch ();
467     if (ch.ch == -1 || CI_is_return (ch.ch)) {
468       choice = -1;
469       break;
470     }
471     else {
472       p = strchr (letters, ch.ch);
473       if (p) {
474         choice = p - letters + 1;
475         break;
476       }
477       else if (ch.ch <= '9' && ch.ch > '0') {
478         choice = ch.ch - '0';
479         if (choice <= m_strlen(letters))
480           break;
481       }
482     }
483     BEEP ();
484   }
485   CLEARLINE(stdscr, LINES - 1);
486   mutt_refresh ();
487   return choice;
488 }
489
490 ssize_t mutt_pretty_size(char *s, ssize_t len, ssize_t n)
491 {
492     if (n == 0)
493         return m_strcpy(s, len, "0K");
494
495     if (n < 10189)           /* 0.1K - 9.9K */
496         return snprintf(s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
497
498     if (n < 1023949)         /* 10K - 999K */
499         /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
500         return snprintf(s, len, "%ldK", (n + 51) / 1024);
501
502     if (n < 10433332)        /* 1.0M - 9.9M */
503         return snprintf(s, len, "%3.1fM", n / 1048576.0);
504
505     /* (10433332 + 52428) / 1048576 = 10 */
506     return snprintf (s, len, "%ldM", (n + 52428) / 1048576);
507 }
508
509 /*
510  * This formats a string, a bit like
511  * snprintf (dest, destlen, "%-*.*s", min_width, max_width, s),
512  * except that the widths refer to the number of character cells
513  * when printed.
514  */
515
516 void mutt_format_string (char *dest, ssize_t destlen,
517                          int min_width, int max_width,
518                          int right_justify, char m_pad_char,
519                          const char *s, ssize_t n, int arboreal)
520 {
521   char *p;
522   wchar_t wc;
523   int w;
524   ssize_t k, k2;
525   char scratch[MB_LEN_MAX];
526   mbstate_t mbstate1, mbstate2;
527
528   p_clear(&mbstate1, 1);
529   p_clear(&mbstate2, 1);
530   --destlen;
531   p = dest;
532   for (; n && (k = mbrtowc (&wc, s, n, &mbstate1)); s += k, n -= k) {
533     if (k == -1 || k == -2) {
534       k = (k == -1) ? 1 : n;
535       wc = CharsetReplacement;
536     }
537     if (arboreal && wc < M_TREE_MAX)
538       w = 1;                    /* hack */
539     else {
540       if (!iswprint(wc))
541         wc = '?';
542       w = wcwidth (wc);
543     }
544     if (w >= 0) {
545       if (w > max_width || (k2 = wcrtomb (scratch, wc, &mbstate2)) > destlen)
546         break;
547       min_width -= w;
548       max_width -= w;
549       m_strncpy(p, destlen, scratch, k2);
550       p += k2;
551       destlen -= k2;
552     }
553   }
554   w = destlen < min_width ? destlen : min_width;
555   if (w <= 0)
556     *p = '\0';
557   else if (right_justify) {
558     p[w] = '\0';
559     while (--p >= dest)
560       p[w] = *p;
561     while (--w >= 0)
562       dest[w] = m_pad_char;
563   }
564   else {
565     while (--w >= 0)
566       *p++ = m_pad_char;
567     *p = '\0';
568   }
569 }
570
571 /*
572  * This formats a string rather like
573  *   snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
574  *   snprintf (dest, destlen, fmt, s);
575  * except that the numbers in the conversion specification refer to
576  * the number of character cells when printed.
577  */
578
579 static void mutt_format_s_x (char *dest, ssize_t destlen,
580                              const char *prefix, const char *s, int arboreal)
581 {
582   int right_justify = 1;
583   char *p;
584   int min_width;
585   int max_width = INT_MAX;
586
587   if (*prefix == '-')
588     ++prefix, right_justify = 0;
589   min_width = strtol (prefix, &p, 10);
590   if (*p == '.') {
591     prefix = p + 1;
592     max_width = strtol (prefix, &p, 10);
593     if (p <= prefix)
594       max_width = INT_MAX;
595   }
596
597   mutt_format_string (dest, destlen, min_width, max_width,
598                       right_justify, ' ', s, m_strlen(s), arboreal);
599 }
600
601 void mutt_format_s (char *dest, ssize_t destlen,
602                     const char *prefix, const char *s)
603 {
604   mutt_format_s_x (dest, destlen, prefix, s, 0);
605 }
606
607 void mutt_format_s_tree (char *dest, ssize_t destlen,
608                          const char *prefix, const char *s)
609 {
610   mutt_format_s_x (dest, destlen, prefix, s, 1);
611 }
612
613 /*
614  * mutt_paddstr (n, s) is almost equivalent to
615  * mutt_format_string (bigbuf, big, n, n, 0, ' ', s, big, 0), waddstr (main_w, bigbuf)
616  */
617
618 void mutt_paddstr(WINDOW *win, int n, const char *s)
619 {
620   wchar_t wc;
621   int w;
622   ssize_t k;
623   ssize_t len = m_strlen(s);
624   mbstate_t mbstate;
625
626   p_clear(&mbstate, 1);
627   for (; len && (k = mbrtowc (&wc, s, len, &mbstate)); s += k, len -= k) {
628     if (k == -1 || k == -2) {
629       k = (k == -1) ? 1 : len;
630       wc = CharsetReplacement;
631     }
632     if (!iswprint(wc))
633       wc = '?';
634     w = wcwidth (wc);
635     if (w >= 0) {
636       if (w > n)
637         break;
638       waddnstr(win, (char *) s, k);
639       n -= w;
640     }
641   }
642   while (n-- > 0)
643     waddch(win, ' ');
644 }