]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/view.c
ncurses 6.2 - patch 20201010
[ncurses.git] / test / view.c
1 /****************************************************************************
2  * Copyright 2019,2020 Thomas E. Dickey                                     *
3  * Copyright 1998-2016,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29 /*
30  * view.c -- a silly little viewer program
31  *
32  * written by Eric S. Raymond <esr@snark.thyrsus.com> December 1994
33  * to test the scrolling code in ncurses.
34  *
35  * modified by Thomas Dickey <dickey@clark.net> July 1995 to demonstrate
36  * the use of 'resizeterm()', and May 2000 to illustrate wide-character
37  * handling.  This program intentionally does not use pads, to allow testing
38  * with less-capable implementations of curses.
39  *
40  * Takes a filename argument.  It's a simple file-viewer with various
41  * scroll-up and scroll-down commands.
42  *
43  * n    -- scroll one line forward
44  * p    -- scroll one line back
45  *
46  * Either command accepts a numeric prefix interpreted as a repeat count.
47  * Thus, typing `5n' should scroll forward 5 lines in the file.
48  *
49  * The way you can tell this is working OK is that, in the trace file,
50  * there should be one scroll operation plus a small number of line
51  * updates, as opposed to a whole-page update.  This means the physical
52  * scroll operation worked, and the refresh() code only had to do a
53  * partial repaint.
54  *
55  * $Id: view.c,v 1.138 2020/02/02 23:34:34 tom Exp $
56  */
57
58 #include <test.priv.h>
59 #include <widechars.h>
60 #include <popup_msg.h>
61
62 #include <sys/stat.h>
63 #include <time.h>
64
65 static void finish(int sig) GCC_NORETURN;
66
67 #define my_pair 1
68
69 static int shift = 0;
70 static bool try_color = FALSE;
71
72 static char *fname;
73 static NCURSES_CH_T **vec_lines;
74 static NCURSES_CH_T **lptr;
75 static int num_lines;
76
77 #if USE_WIDEC_SUPPORT
78 static bool n_option = FALSE;
79 #endif
80
81 static void usage(void) GCC_NORETURN;
82
83 static void
84 failed(const char *msg)
85 {
86     endwin();
87     fprintf(stderr, "%s\n", msg);
88     ExitProgram(EXIT_FAILURE);
89 }
90
91 static int
92 ch_len(NCURSES_CH_T *src)
93 {
94     int result = 0;
95 #if USE_WIDEC_SUPPORT
96     int count;
97 #endif
98
99 #if USE_WIDEC_SUPPORT
100     for (;;) {
101         TEST_CCHAR(src, count, {
102             int len = wcwidth(test_wch[0]);
103             result += (len > 0) ? len : 1;
104             ++src;
105         }
106         , {
107             break;
108         })
109     }
110 #else
111     while (*src++)
112         result++;
113 #endif
114     return result;
115 }
116
117 static void
118 finish(int sig)
119 {
120     endwin();
121 #if NO_LEAKS
122     if (vec_lines != 0) {
123         int n;
124         for (n = 0; n < num_lines; ++n) {
125             free(vec_lines[n]);
126         }
127         free(vec_lines);
128     }
129 #endif
130     ExitProgram(sig != 0 ? EXIT_FAILURE : EXIT_SUCCESS);
131 }
132
133 static void
134 show_all(const char *tag)
135 {
136     int i;
137     int digits;
138     char temp[BUFSIZ];
139     NCURSES_CH_T *s;
140     time_t this_time;
141
142     for (digits = 1, i = num_lines; i > 0; i /= 10) {
143         ++digits;
144     }
145
146     _nc_SPRINTF(temp, _nc_SLIMIT(sizeof(temp))
147                 "view %.*s", (int) strlen(tag), tag);
148     i = (int) strlen(temp);
149     _nc_SPRINTF(temp + i, _nc_SLIMIT(sizeof(temp) - (size_t) i)
150                 " %.*s", (int) sizeof(temp) - i - 2, fname);
151     move(0, 0);
152     printw("%.*s", COLS, temp);
153     clrtoeol();
154     this_time = time((time_t *) 0);
155     _nc_STRNCPY(temp, ctime(&this_time), (size_t) 30);
156     if ((i = (int) strlen(temp)) != 0) {
157         temp[--i] = 0;
158         if (move(0, COLS - i - 2) != ERR)
159             printw("  %s", temp);
160     }
161
162     scrollok(stdscr, FALSE);    /* prevent screen from moving */
163     for (i = 1; i < LINES; i++) {
164         int len;
165         int actual = (int) (lptr + i - vec_lines);
166         if (actual > num_lines) {
167             if (i < LINES - 1) {
168                 int y, x;
169                 getyx(stdscr, y, x);
170                 move(i, 0);
171                 clrtobot();
172                 move(y, x);
173             }
174             break;
175         }
176         move(i, 0);
177         printw("%*d:", digits, actual);
178         clrtoeol();
179         if ((s = lptr[i - 1]) == 0) {
180             continue;
181         }
182         len = ch_len(s);
183         if (len > shift) {
184 #if USE_WIDEC_SUPPORT
185             /*
186              * An index into an array of cchar_t's is not necessarily the same
187              * as the column-offset.  A pad would do this directly.  Here we
188              * must translate (or compute a table of offsets).
189              */
190             {
191                 int j;
192                 int width = 1, count;
193                 for (j = actual = 0; j < shift; ++j) {
194                     TEST_CCHAR(s + j, count, {
195                         width = wcwidth(test_wch[0]);
196                     }
197                     , {
198                         width = 1;
199                     });
200                     actual += width;
201                     if (actual > shift) {
202                         break;
203                     } else if (actual == shift) {
204                         ++j;
205                         break;
206                     }
207                 }
208                 if (actual < len) {
209                     if (actual > shift)
210                         addch('<');
211                     add_wchstr(s + j + (actual > shift));
212                 }
213             }
214 #else
215             addchstr(s + shift);
216 #endif
217         }
218 #if defined(NCURSES_VERSION) || defined(HAVE_WCHGAT)
219         if (try_color)
220             wchgat(stdscr, -1, WA_NORMAL, my_pair, NULL);
221 #endif
222     }
223     setscrreg(1, LINES - 1);
224     scrollok(stdscr, TRUE);
225     refresh();
226 }
227
228 static void
229 read_file(const char *filename)
230 {
231     FILE *fp;
232     int pass;
233     int k;
234     int width;
235     size_t j;
236     size_t len;
237     struct stat sb;
238     char *my_blob;
239     char **my_vec = 0;
240     WINDOW *my_win;
241
242     if (stat(filename, &sb) != 0
243         || (sb.st_mode & S_IFMT) != S_IFREG) {
244         failed("input is not a file");
245     }
246
247     if (sb.st_size == 0) {
248         failed("input is empty");
249     }
250
251     if ((fp = fopen(filename, "r")) == 0) {
252         failed("cannot open input-file");
253     }
254
255     if ((my_blob = malloc((size_t) sb.st_size + 1)) == 0) {
256         failed("cannot allocate memory for input-file");
257     }
258
259     len = fread(my_blob, sizeof(char), (size_t) sb.st_size, fp);
260     my_blob[sb.st_size] = '\0';
261     fclose(fp);
262
263     for (pass = 0; pass < 2; ++pass) {
264         char *base = my_blob;
265         k = 0;
266         for (j = 0; j < len; ++j) {
267             if (my_blob[j] == '\n') {
268                 if (pass) {
269                     my_vec[k] = base;
270                     my_blob[j] = '\0';
271                 }
272                 base = my_blob + j + 1;
273                 ++k;
274             }
275         }
276         num_lines = k;
277         if (base != (my_blob + j))
278             ++num_lines;
279         if (!pass &&
280             ((my_vec = typeCalloc(char *, (size_t) k + 2)) == 0)) {
281             failed("cannot allocate line-vector #1");
282         }
283     }
284
285 #if USE_WIDEC_SUPPORT
286     if (!memcmp("\357\273\277", my_blob, 3)) {
287         char *s = my_blob + 3;
288         char *d = my_blob;
289         Trace(("trim BOM"));
290         do {
291         } while ((*d++ = *s++) != '\0');
292     }
293 #endif
294
295     width = (int) strlen(my_vec[0]);
296     for (k = 1; my_vec[k]; ++k) {
297         int check = (int) (my_vec[k] - my_vec[k - 1]);
298         if (width < check)
299             width = check;
300     }
301     width = (width + 1) * 5;
302     my_win = newwin(2, width, 0, 0);
303     if (my_win == 0) {
304         failed("cannot allocate temporary window");
305     }
306
307     if ((vec_lines = typeCalloc(NCURSES_CH_T *, (size_t) num_lines + 2)) == 0) {
308         failed("cannot allocate line-vector #2");
309     }
310
311     /*
312      * Use the curses library for rendering, including tab-conversion.  This
313      * will not make the resulting array's indices correspond to column for
314      * lines containing double-width cells because the "in_wch" functions will
315      * ignore the skipped cells.  Use pads for that sort of thing.
316      */
317     Trace(("slurp the file"));
318     for (k = 0; my_vec[k]; ++k) {
319         char *s;
320         int y, x;
321 #if USE_WIDEC_SUPPORT
322         char *last = my_vec[k] + (int) strlen(my_vec[k]);
323         wchar_t wch[2];
324         size_t rc;
325 #ifndef state_unused
326         mbstate_t state;
327 #endif
328 #endif /* USE_WIDEC_SUPPORT */
329
330         werase(my_win);
331         wmove(my_win, 0, 0);
332 #if USE_WIDEC_SUPPORT
333         wch[1] = 0;
334         reset_mbytes(state);
335 #endif
336         for (s = my_vec[k]; *s != '\0'; ++s) {
337 #if USE_WIDEC_SUPPORT
338             if (!n_option) {
339                 rc = (size_t) check_mbytes(wch[0], s, (size_t) (last - s), state);
340                 if ((long) rc == -1 || (long) rc == -2) {
341                     break;
342                 }
343                 s += rc - 1;
344                 waddwstr(my_win, wch);
345             } else
346 #endif
347                 waddch(my_win, *s & 0xff);
348         }
349         getyx(my_win, y, x);
350         if (y)
351             x = width - 1;
352         wmove(my_win, 0, 0);
353         /* "x + 1" works with standard curses; some implementations are buggy */
354         if ((vec_lines[k] = typeCalloc(NCURSES_CH_T, x + width + 1)) == 0) {
355             failed("cannot allocate line-vector #3");
356         }
357 #if USE_WIDEC_SUPPORT
358         win_wchnstr(my_win, vec_lines[k], x);
359 #else
360         winchnstr(my_win, vec_lines[k], x);
361 #endif
362     }
363
364     delwin(my_win);
365     free(my_vec);
366     free(my_blob);
367 }
368
369 static void
370 usage(void)
371 {
372     static const char *msg[] =
373     {
374         "Usage: view [options] file"
375         ,""
376         ,"Options:"
377         ," -c       use color if terminal supports it"
378         ," -i       ignore INT, QUIT, TERM signals"
379 #if USE_WIDEC_SUPPORT
380         ," -n       use waddch (bytes) rather then wadd_wch (wide-chars)"
381 #endif
382         ," -s       start in single-step mode, waiting for input"
383 #ifdef TRACE
384         ," -t       trace screen updates"
385         ," -T NUM   specify trace mask"
386 #endif
387     };
388     size_t n;
389     for (n = 0; n < SIZEOF(msg); n++)
390         fprintf(stderr, "%s\n", msg[n]);
391     ExitProgram(EXIT_FAILURE);
392 }
393
394 int
395 main(int argc, char *argv[])
396 {
397     static const char *help[] =
398     {
399         "Commands:",
400         "  q,^Q,ESC       - quit this program",
401         "",
402         "  p,<Up>         - scroll the viewport up by one row",
403         "  n,<Down>       - scroll the viewport down by one row",
404         "  l,<Left>       - scroll the viewport left by one column",
405         "  r,<Right>      - scroll the viewport right by one column",
406         "  <,>            - scroll the viewport left/right by 8 columns",
407         "",
408         "  h,<Home>       - scroll the viewport to top of file",
409         "  ^F,<PageDn>    - scroll to the next page",
410         "  ^B,<PageUp>    - scroll to the previous page",
411         "  e,<End>        - scroll the viewport to end of file",
412         "",
413         "  ^L             - repaint using redrawwin()",
414         "",
415         "  0 through 9    - enter digits for count",
416         "  s              - use entered count for halfdelay() parameter",
417         "                 - if no entered count, stop nodelay()",
418         "  <space>        - begin nodelay()",
419         0
420     };
421
422     int i;
423     int my_delay = 0;
424     NCURSES_CH_T **olptr;
425     int value = 0;
426     bool done = FALSE;
427     bool got_number = FALSE;
428     bool ignore_sigs = FALSE;
429     bool single_step = FALSE;
430     const char *my_label = "Input";
431
432     setlocale(LC_ALL, "");
433
434     while ((i = getopt(argc, argv, "cinstT:")) != -1) {
435         switch (i) {
436         case 'c':
437             try_color = TRUE;
438             break;
439         case 'i':
440             ignore_sigs = TRUE;
441             break;
442 #if USE_WIDEC_SUPPORT
443         case 'n':
444             n_option = TRUE;
445             break;
446 #endif
447         case 's':
448             single_step = TRUE;
449             break;
450 #ifdef TRACE
451         case 'T':
452             {
453                 char *next = 0;
454                 int tvalue = (int) strtol(optarg, &next, 0);
455                 if (tvalue < 0 || (next != 0 && *next != 0))
456                     usage();
457                 curses_trace((unsigned) tvalue);
458             }
459             break;
460         case 't':
461             curses_trace(TRACE_CALLS);
462             break;
463 #endif
464         default:
465             usage();
466         }
467     }
468     if (optind + 1 != argc)
469         usage();
470
471     InitAndCatch(initscr(), ignore_sigs ? SIG_IGN : finish);
472     keypad(stdscr, TRUE);       /* enable keyboard mapping */
473     (void) nonl();              /* tell curses not to do NL->CR/NL on output */
474     (void) cbreak();            /* take input chars one at a time, no wait for \n */
475     (void) noecho();            /* don't echo input */
476     if (!single_step)
477         nodelay(stdscr, TRUE);
478     idlok(stdscr, TRUE);        /* allow use of insert/delete line */
479
480     read_file(fname = argv[optind]);
481
482     if (try_color) {
483         if (has_colors()) {
484             start_color();
485             init_pair(my_pair, COLOR_WHITE, COLOR_BLUE);
486             bkgd((chtype) COLOR_PAIR(my_pair));
487         } else {
488             try_color = FALSE;
489         }
490     }
491
492     lptr = vec_lines;
493     while (!done) {
494         int n, c;
495
496         if (!got_number)
497             show_all(my_label);
498
499         for (;;) {
500             c = getch();
501             if ((c < 127) && isdigit(c)) {
502                 if (!got_number) {
503                     MvPrintw(0, 0, "Count: ");
504                     clrtoeol();
505                 }
506                 addch(UChar(c));
507                 value = 10 * value + (c - '0');
508                 got_number = TRUE;
509             } else
510                 break;
511         }
512         if (got_number && value) {
513             n = value;
514         } else {
515             n = 1;
516         }
517
518         if (c != ERR)
519             my_label = keyname(c);
520         switch (c) {
521         case KEY_DOWN:
522         case 'n':
523             olptr = lptr;
524             for (i = 0; i < n; i++)
525                 if ((lptr - vec_lines) < (num_lines - LINES + 1))
526                     lptr++;
527                 else
528                     break;
529             scrl((int) (lptr - olptr));
530             break;
531
532         case KEY_UP:
533         case 'p':
534             olptr = lptr;
535             for (i = 0; i < n; i++)
536                 if (lptr > vec_lines)
537                     lptr--;
538                 else
539                     break;
540             scrl((int) (lptr - olptr));
541             break;
542
543         case 'h':
544             /* FALLTHRU */
545         case KEY_HOME:
546             lptr = vec_lines;
547             break;
548
549         case '<':
550             if ((shift -= 8) < 0)
551                 shift = 0;
552             break;
553         case '>':
554             shift += 8;
555             break;
556
557         case 'e':
558             /* FALLTHRU */
559         case KEY_END:
560             if (num_lines > LINES)
561                 lptr = (vec_lines + num_lines - LINES + 1);
562             else
563                 lptr = (vec_lines + (num_lines - 2));
564             break;
565
566         case CTRL('F'):
567             /* FALLTHRU */
568         case KEY_NPAGE:
569             for (i = 0; i < n; i++) {
570                 if ((lptr - vec_lines) < (num_lines - 5))
571                     lptr += (LINES - 1);
572                 else
573                     lptr = (vec_lines + num_lines - 2);
574             }
575             break;
576
577         case CTRL('B'):
578             /* FALLTHRU */
579         case KEY_PPAGE:
580             for (i = 0; i < n; i++) {
581                 if ((lptr - vec_lines) >= LINES)
582                     lptr -= (LINES - 1);
583                 else
584                     lptr = vec_lines;
585             }
586             break;
587
588         case 'r':
589         case KEY_RIGHT:
590             shift += n;
591             break;
592
593         case 'l':
594         case KEY_LEFT:
595             shift -= n;
596             if (shift < 0) {
597                 shift = 0;
598                 beep();
599             }
600             break;
601
602         case 'q':
603         case QUIT:
604         case ESCAPE:
605             done = TRUE;
606             break;
607
608 #ifdef KEY_RESIZE
609         case KEY_RESIZE:        /* ignore this; ncurses will repaint */
610             break;
611 #endif
612         case 's':
613 #if HAVE_HALFDELAY
614             if (got_number) {
615                 halfdelay(my_delay = n);
616             } else {
617                 nodelay(stdscr, FALSE);
618                 my_delay = -1;
619             }
620 #else
621             nodelay(stdscr, FALSE);
622             my_delay = -1;
623 #endif
624             break;
625         case ' ':
626             nodelay(stdscr, TRUE);
627             my_delay = 0;
628             break;
629         case CTRL('L'):
630             redrawwin(stdscr);
631             break;
632         case ERR:
633             if (!my_delay)
634                 napms(50);
635             break;
636         case HELP_KEY_1:
637             popup_msg(stdscr, help);
638             break;
639         default:
640             beep();
641             break;
642         }
643         if (c >= KEY_MIN || (c > 0 && !isdigit(c))) {
644             got_number = FALSE;
645             value = 0;
646         }
647     }
648
649     finish(0);                  /* we're done */
650 }