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