]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/view.c
ncurses 6.2 - patch 20210904
[ncurses.git] / test / view.c
1 /****************************************************************************
2  * Copyright 2019-2020,2021 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.142 2021/06/12 23:16:31 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 GCC_NORETURN void finish(int sig);
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 GCC_NORETURN void
82 failed(const char *msg)
83 {
84     endwin();
85     fprintf(stderr, "%s\n", msg);
86     ExitProgram(EXIT_FAILURE);
87 }
88
89 static int
90 ch_len(NCURSES_CH_T *src)
91 {
92     int result = 0;
93
94 #if USE_WIDEC_SUPPORT
95     for (;;) {
96         int count;
97         TEST_CCHAR(src, count, {
98             int len = wcwidth(test_wch[0]);
99             result += (len > 0) ? len : 1;
100             ++src;
101         }
102         , {
103             break;
104         })
105     }
106 #else
107     while (*src++)
108         result++;
109 #endif
110     return result;
111 }
112
113 static void
114 finish(int sig)
115 {
116     endwin();
117 #if NO_LEAKS
118     if (vec_lines != 0) {
119         int n;
120         for (n = 0; n < num_lines; ++n) {
121             free(vec_lines[n]);
122         }
123         free(vec_lines);
124     }
125 #endif
126     ExitProgram(sig != 0 ? EXIT_FAILURE : EXIT_SUCCESS);
127 }
128
129 static void
130 show_all(const char *tag)
131 {
132     int i;
133     int digits;
134     char temp[BUFSIZ];
135     time_t this_time;
136
137     for (digits = 1, i = num_lines; i > 0; i /= 10) {
138         ++digits;
139     }
140
141     _nc_SPRINTF(temp, _nc_SLIMIT(sizeof(temp))
142                 "view %.*s", (int) strlen(tag), tag);
143     i = (int) strlen(temp);
144     _nc_SPRINTF(temp + i, _nc_SLIMIT(sizeof(temp) - (size_t) i)
145                 " %.*s", (int) sizeof(temp) - i - 2, fname);
146     move(0, 0);
147     printw("%.*s", COLS, temp);
148     clrtoeol();
149     this_time = time((time_t *) 0);
150     _nc_STRNCPY(temp, ctime(&this_time), (size_t) 30);
151     if ((i = (int) strlen(temp)) != 0) {
152         temp[--i] = 0;
153         if (move(0, COLS - i - 2) != ERR)
154             printw("  %s", temp);
155     }
156
157     scrollok(stdscr, FALSE);    /* prevent screen from moving */
158     for (i = 1; i < LINES; i++) {
159         NCURSES_CH_T *s;
160         int len;
161         int actual = (int) (lptr + i - vec_lines);
162
163         if (actual > num_lines) {
164             if (i < LINES - 1) {
165                 int y, x;
166                 getyx(stdscr, y, x);
167                 move(i, 0);
168                 clrtobot();
169                 move(y, x);
170             }
171             break;
172         }
173         move(i, 0);
174         printw("%*d:", digits, actual);
175         clrtoeol();
176         if ((s = lptr[i - 1]) == 0) {
177             continue;
178         }
179         len = ch_len(s);
180         if (len > shift) {
181 #if USE_WIDEC_SUPPORT
182             /*
183              * An index into an array of cchar_t's is not necessarily the same
184              * as the column-offset.  A pad would do this directly.  Here we
185              * must translate (or compute a table of offsets).
186              */
187             {
188                 int j;
189                 int width = 1;
190
191                 for (j = actual = 0; j < shift; ++j) {
192                     int count;
193
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     fclose(fp);
261
262     if (len > (size_t) sb.st_size)
263         len = (size_t) sb.st_size;
264     my_blob[len] = '\0';
265
266     for (pass = 0; pass < 2; ++pass) {
267         char *base = my_blob;
268         k = 0;
269         for (j = 0; j < len; ++j) {
270             if (my_blob[j] == '\n') {
271                 if (pass) {
272                     my_vec[k] = base;
273                     my_blob[j] = '\0';
274                 }
275                 base = my_blob + j + 1;
276                 ++k;
277             }
278         }
279         if (base != (my_blob + j)) {
280             if (pass)
281                 my_vec[k] = base;
282             ++k;
283         }
284         num_lines = k;
285         if (pass == 0) {
286             if (((my_vec = typeCalloc(char *, (size_t) k + 2)) == 0)) {
287                 failed("cannot allocate line-vector #1");
288             }
289         } else {
290             if (my_vec[0] == NULL)
291                 my_vec[0] = my_blob;
292         }
293     }
294
295 #if USE_WIDEC_SUPPORT
296     if (!memcmp("\357\273\277", my_blob, 3)) {
297         char *s = my_blob + 3;
298         char *d = my_blob;
299         Trace(("trim BOM"));
300         do {
301         } while ((*d++ = *s++) != '\0');
302     }
303 #endif
304
305     width = (int) strlen(my_vec[0]);
306     for (k = 1; my_vec[k]; ++k) {
307         int check = (int) (my_vec[k] - my_vec[k - 1]);
308         if (width < check)
309             width = check;
310     }
311     width = (width + 1) * 5;
312     my_win = newwin(2, width, 0, 0);
313     if (my_win == 0) {
314         failed("cannot allocate temporary window");
315     }
316
317     if ((vec_lines = typeCalloc(NCURSES_CH_T *, (size_t) num_lines + 2)) == 0) {
318         failed("cannot allocate line-vector #2");
319     }
320
321     /*
322      * Use the curses library for rendering, including tab-conversion.  This
323      * will not make the resulting array's indices correspond to column for
324      * lines containing double-width cells because the "in_wch" functions will
325      * ignore the skipped cells.  Use pads for that sort of thing.
326      */
327     Trace(("slurp the file"));
328     for (k = 0; my_vec[k]; ++k) {
329         char *s;
330         int y, x;
331 #if USE_WIDEC_SUPPORT
332         char *last = my_vec[k] + (int) strlen(my_vec[k]);
333         wchar_t wch[2];
334         size_t rc;
335 #ifndef state_unused
336         mbstate_t state;
337 #endif
338 #endif /* USE_WIDEC_SUPPORT */
339
340         werase(my_win);
341         wmove(my_win, 0, 0);
342 #if USE_WIDEC_SUPPORT
343         wch[1] = 0;
344         reset_mbytes(state);
345 #endif
346         for (s = my_vec[k]; *s != '\0'; ++s) {
347 #if USE_WIDEC_SUPPORT
348             if (!n_option) {
349                 rc = (size_t) check_mbytes(wch[0], s, (size_t) (last - s), state);
350                 if ((long) rc == -1 || (long) rc == -2) {
351                     break;
352                 }
353                 s += rc - 1;
354                 waddwstr(my_win, wch);
355             } else
356 #endif
357                 waddch(my_win, *s & 0xff);
358         }
359         getyx(my_win, y, x);
360         if (y)
361             x = width - 1;
362         wmove(my_win, 0, 0);
363         /* "x + 1" works with standard curses; some implementations are buggy */
364         if ((vec_lines[k] = typeCalloc(NCURSES_CH_T, x + width + 1)) == 0) {
365             failed("cannot allocate line-vector #3");
366         }
367 #if USE_WIDEC_SUPPORT
368         win_wchnstr(my_win, vec_lines[k], x);
369 #else
370         winchnstr(my_win, vec_lines[k], x);
371 #endif
372     }
373
374     delwin(my_win);
375     free(my_vec);
376     free(my_blob);
377 }
378
379 static GCC_NORETURN void
380 usage(void)
381 {
382     static const char *msg[] =
383     {
384         "Usage: view [options] file"
385         ,""
386         ,"Options:"
387         ," -c       use color if terminal supports it"
388         ," -i       ignore INT, QUIT, TERM signals"
389 #if USE_WIDEC_SUPPORT
390         ," -n       use waddch (bytes) rather then wadd_wch (wide-chars)"
391 #endif
392         ," -s       start in single-step mode, waiting for input"
393 #ifdef TRACE
394         ," -t       trace screen updates"
395         ," -T NUM   specify trace mask"
396 #endif
397     };
398     size_t n;
399     for (n = 0; n < SIZEOF(msg); n++)
400         fprintf(stderr, "%s\n", msg[n]);
401     ExitProgram(EXIT_FAILURE);
402 }
403
404 int
405 main(int argc, char *argv[])
406 {
407     static const char *help[] =
408     {
409         "Commands:",
410         "  q,^Q,ESC       - quit this program",
411         "",
412         "  p,<Up>         - scroll the viewport up by one row",
413         "  n,<Down>       - scroll the viewport down by one row",
414         "  l,<Left>       - scroll the viewport left by one column",
415         "  r,<Right>      - scroll the viewport right by one column",
416         "  <,>            - scroll the viewport left/right by 8 columns",
417         "",
418         "  h,<Home>       - scroll the viewport to top of file",
419         "  ^F,<PageDn>    - scroll to the next page",
420         "  ^B,<PageUp>    - scroll to the previous page",
421         "  e,<End>        - scroll the viewport to end of file",
422         "",
423         "  ^L             - repaint using redrawwin()",
424         "",
425         "  0 through 9    - enter digits for count",
426         "  s              - use entered count for halfdelay() parameter",
427         "                 - if no entered count, stop nodelay()",
428         "  <space>        - begin nodelay()",
429         0
430     };
431
432     int i;
433     int my_delay = 0;
434     NCURSES_CH_T **olptr;
435     int value = 0;
436     bool done = FALSE;
437     bool got_number = FALSE;
438     bool ignore_sigs = FALSE;
439     bool single_step = FALSE;
440     const char *my_label = "Input";
441
442     setlocale(LC_ALL, "");
443
444     while ((i = getopt(argc, argv, "cinstT:")) != -1) {
445         switch (i) {
446         case 'c':
447             try_color = TRUE;
448             break;
449         case 'i':
450             ignore_sigs = TRUE;
451             break;
452 #if USE_WIDEC_SUPPORT
453         case 'n':
454             n_option = TRUE;
455             break;
456 #endif
457         case 's':
458             single_step = TRUE;
459             break;
460 #ifdef TRACE
461         case 'T':
462             {
463                 char *next = 0;
464                 int tvalue = (int) strtol(optarg, &next, 0);
465                 if (tvalue < 0 || (next != 0 && *next != 0))
466                     usage();
467                 curses_trace((unsigned) tvalue);
468             }
469             break;
470         case 't':
471             curses_trace(TRACE_CALLS);
472             break;
473 #endif
474         default:
475             usage();
476         }
477     }
478     if (optind + 1 != argc)
479         usage();
480
481     InitAndCatch(initscr(), ignore_sigs ? SIG_IGN : finish);
482     keypad(stdscr, TRUE);       /* enable keyboard mapping */
483     (void) nonl();              /* tell curses not to do NL->CR/NL on output */
484     (void) cbreak();            /* take input chars one at a time, no wait for \n */
485     (void) noecho();            /* don't echo input */
486     if (!single_step)
487         nodelay(stdscr, TRUE);
488     idlok(stdscr, TRUE);        /* allow use of insert/delete line */
489
490     read_file(fname = argv[optind]);
491
492     if (try_color) {
493         if (has_colors()) {
494             start_color();
495             init_pair(my_pair, COLOR_WHITE, COLOR_BLUE);
496             bkgd((chtype) COLOR_PAIR(my_pair));
497         } else {
498             try_color = FALSE;
499         }
500     }
501
502     lptr = vec_lines;
503     while (!done) {
504         int n, c;
505
506         if (!got_number)
507             show_all(my_label);
508
509         for (;;) {
510             c = getch();
511             if ((c < 127) && isdigit(c)) {
512                 if (!got_number) {
513                     MvPrintw(0, 0, "Count: ");
514                     clrtoeol();
515                 }
516                 addch(UChar(c));
517                 value = 10 * value + (c - '0');
518                 got_number = TRUE;
519             } else
520                 break;
521         }
522         if (got_number && value) {
523             n = value;
524         } else {
525             n = 1;
526         }
527
528         if (c != ERR)
529             my_label = keyname(c);
530         switch (c) {
531         case KEY_DOWN:
532         case 'n':
533             olptr = lptr;
534             for (i = 0; i < n; i++)
535                 if ((lptr - vec_lines) < (num_lines - LINES + 1))
536                     lptr++;
537                 else
538                     break;
539             scrl((int) (lptr - olptr));
540             break;
541
542         case KEY_UP:
543         case 'p':
544             olptr = lptr;
545             for (i = 0; i < n; i++)
546                 if (lptr > vec_lines)
547                     lptr--;
548                 else
549                     break;
550             scrl((int) (lptr - olptr));
551             break;
552
553         case 'h':
554             /* FALLTHRU */
555         case KEY_HOME:
556             lptr = vec_lines;
557             break;
558
559         case '<':
560             if ((shift -= 8) < 0)
561                 shift = 0;
562             break;
563         case '>':
564             shift += 8;
565             break;
566
567         case 'e':
568             /* FALLTHRU */
569         case KEY_END:
570             if (num_lines > LINES)
571                 lptr = (vec_lines + num_lines - LINES + 1);
572             else
573                 lptr = (vec_lines + (num_lines - 2));
574             break;
575
576         case CTRL('F'):
577             /* FALLTHRU */
578         case KEY_NPAGE:
579             for (i = 0; i < n; i++) {
580                 if ((lptr - vec_lines) < (num_lines - 5))
581                     lptr += (LINES - 1);
582                 else
583                     lptr = (vec_lines + num_lines - 2);
584             }
585             break;
586
587         case CTRL('B'):
588             /* FALLTHRU */
589         case KEY_PPAGE:
590             for (i = 0; i < n; i++) {
591                 if ((lptr - vec_lines) >= LINES)
592                     lptr -= (LINES - 1);
593                 else
594                     lptr = vec_lines;
595             }
596             break;
597
598         case 'r':
599         case KEY_RIGHT:
600             shift += n;
601             break;
602
603         case 'l':
604         case KEY_LEFT:
605             shift -= n;
606             if (shift < 0) {
607                 shift = 0;
608                 beep();
609             }
610             break;
611
612         case 'q':
613         case QUIT:
614         case ESCAPE:
615             done = TRUE;
616             break;
617
618 #ifdef KEY_RESIZE
619         case KEY_RESIZE:        /* ignore this; ncurses will repaint */
620             break;
621 #endif
622         case 's':
623 #if HAVE_HALFDELAY
624             if (got_number) {
625                 halfdelay(my_delay = n);
626             } else {
627                 nodelay(stdscr, FALSE);
628                 my_delay = -1;
629             }
630 #else
631             nodelay(stdscr, FALSE);
632             my_delay = -1;
633 #endif
634             break;
635         case ' ':
636             nodelay(stdscr, TRUE);
637             my_delay = 0;
638             break;
639         case CTRL('L'):
640             redrawwin(stdscr);
641             break;
642         case ERR:
643             if (!my_delay)
644                 napms(50);
645             break;
646         case HELP_KEY_1:
647             popup_msg(stdscr, help);
648             break;
649         default:
650             beep();
651             break;
652         }
653         if (c >= KEY_MIN || (c > 0 && !isdigit(c))) {
654             got_number = FALSE;
655             value = 0;
656         }
657     }
658
659     finish(0);                  /* we're done */
660 }