]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/view.c
2772a2773dde3a74645ff8b72ae3e31def214974
[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.136 2019/01/27 00:52:06 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     if ((vec_lines = typeCalloc(NCURSES_CH_T *, (size_t) num_lines + 2)) == 0)
306         failed("cannot allocate line-vector #2");
307
308     /*
309      * Use the curses library for rendering, including tab-conversion.  This
310      * will not make the resulting array's indices correspond to column for
311      * lines containing double-width cells because the "in_wch" functions will
312      * ignore the skipped cells.  Use pads for that sort of thing.
313      */
314     Trace(("slurp the file"));
315     for (k = 0; my_vec[k]; ++k) {
316         char *s;
317         int y, x;
318 #if USE_WIDEC_SUPPORT
319         char *last = my_vec[k] + (int) strlen(my_vec[k]);
320         wchar_t wch[2];
321         size_t rc;
322 #ifndef state_unused
323         mbstate_t state;
324 #endif
325 #endif /* USE_WIDEC_SUPPORT */
326
327         werase(my_win);
328         wmove(my_win, 0, 0);
329 #if USE_WIDEC_SUPPORT
330         wch[1] = 0;
331         reset_mbytes(state);
332 #endif
333         for (s = my_vec[k]; *s != '\0'; ++s) {
334 #if USE_WIDEC_SUPPORT
335             if (!n_option) {
336                 rc = (size_t) check_mbytes(wch[0], s, (size_t) (last - s), state);
337                 if ((long) rc == -1 || (long) rc == -2) {
338                     break;
339                 }
340                 s += rc - 1;
341                 waddwstr(my_win, wch);
342             } else
343 #endif
344                 waddch(my_win, *s & 0xff);
345         }
346         getyx(my_win, y, x);
347         if (y)
348             x = width - 1;
349         wmove(my_win, 0, 0);
350         /* "x + 1" works with standard curses; some implementations are buggy */
351         if ((vec_lines[k] = typeCalloc(NCURSES_CH_T, x + width + 1)) == 0)
352             failed("cannot allocate line-vector #3");
353 #if USE_WIDEC_SUPPORT
354         win_wchnstr(my_win, vec_lines[k], x);
355 #else
356         winchnstr(my_win, vec_lines[k], x);
357 #endif
358     }
359
360     delwin(my_win);
361     free(my_vec);
362     free(my_blob);
363 }
364
365 static void
366 usage(void)
367 {
368     static const char *msg[] =
369     {
370         "Usage: view [options] file"
371         ,""
372         ,"Options:"
373         ," -c       use color if terminal supports it"
374         ," -i       ignore INT, QUIT, TERM signals"
375 #if USE_WIDEC_SUPPORT
376         ," -n       use waddch (bytes) rather then wadd_wch (wide-chars)"
377 #endif
378         ," -s       start in single-step mode, waiting for input"
379 #ifdef TRACE
380         ," -t       trace screen updates"
381         ," -T NUM   specify trace mask"
382 #endif
383     };
384     size_t n;
385     for (n = 0; n < SIZEOF(msg); n++)
386         fprintf(stderr, "%s\n", msg[n]);
387     ExitProgram(EXIT_FAILURE);
388 }
389
390 int
391 main(int argc, char *argv[])
392 {
393     static const char *help[] =
394     {
395         "Commands:",
396         "  q,^Q,ESC       - quit this program",
397         "",
398         "  p,<Up>         - scroll the viewport up by one row",
399         "  n,<Down>       - scroll the viewport down by one row",
400         "  l,<Left>       - scroll the viewport left by one column",
401         "  r,<Right>      - scroll the viewport right by one column",
402         "  <,>            - scroll the viewport left/right by 8 columns",
403         "",
404         "  h,<Home>       - scroll the viewport to top of file",
405         "  ^F,<PageDn>    - scroll to the next page",
406         "  ^B,<PageUp>    - scroll to the previous page",
407         "  e,<End>        - scroll the viewport to end of file",
408         "",
409         "  ^L             - repaint using redrawwin()",
410         "",
411         "  0 through 9    - enter digits for count",
412         "  s              - use entered count for halfdelay() parameter",
413         "                 - if no entered count, stop nodelay()",
414         "  <space>        - begin nodelay()",
415         0
416     };
417
418     int i;
419     int my_delay = 0;
420     NCURSES_CH_T **olptr;
421     int value = 0;
422     bool done = FALSE;
423     bool got_number = FALSE;
424     bool ignore_sigs = FALSE;
425     bool single_step = FALSE;
426     const char *my_label = "Input";
427
428     setlocale(LC_ALL, "");
429
430     while ((i = getopt(argc, argv, "cinstT:")) != -1) {
431         switch (i) {
432         case 'c':
433             try_color = TRUE;
434             break;
435         case 'i':
436             ignore_sigs = TRUE;
437             break;
438 #if USE_WIDEC_SUPPORT
439         case 'n':
440             n_option = TRUE;
441             break;
442 #endif
443         case 's':
444             single_step = TRUE;
445             break;
446 #ifdef TRACE
447         case 'T':
448             {
449                 char *next = 0;
450                 int tvalue = (int) strtol(optarg, &next, 0);
451                 if (tvalue < 0 || (next != 0 && *next != 0))
452                     usage();
453                 trace((unsigned) tvalue);
454             }
455             break;
456         case 't':
457             trace(TRACE_CALLS);
458             break;
459 #endif
460         default:
461             usage();
462         }
463     }
464     if (optind + 1 != argc)
465         usage();
466
467     InitAndCatch(initscr(), ignore_sigs ? SIG_IGN : finish);
468     keypad(stdscr, TRUE);       /* enable keyboard mapping */
469     (void) nonl();              /* tell curses not to do NL->CR/NL on output */
470     (void) cbreak();            /* take input chars one at a time, no wait for \n */
471     (void) noecho();            /* don't echo input */
472     if (!single_step)
473         nodelay(stdscr, TRUE);
474     idlok(stdscr, TRUE);        /* allow use of insert/delete line */
475
476     read_file(fname = argv[optind]);
477
478     if (try_color) {
479         if (has_colors()) {
480             start_color();
481             init_pair(my_pair, COLOR_WHITE, COLOR_BLUE);
482             bkgd((chtype) COLOR_PAIR(my_pair));
483         } else {
484             try_color = FALSE;
485         }
486     }
487
488     lptr = vec_lines;
489     while (!done) {
490         int n, c;
491
492         if (!got_number)
493             show_all(my_label);
494
495         for (;;) {
496             c = getch();
497             if ((c < 127) && isdigit(c)) {
498                 if (!got_number) {
499                     MvPrintw(0, 0, "Count: ");
500                     clrtoeol();
501                 }
502                 addch(UChar(c));
503                 value = 10 * value + (c - '0');
504                 got_number = TRUE;
505             } else
506                 break;
507         }
508         if (got_number && value) {
509             n = value;
510         } else {
511             n = 1;
512         }
513
514         if (c != ERR)
515             my_label = keyname(c);
516         switch (c) {
517         case KEY_DOWN:
518         case 'n':
519             olptr = lptr;
520             for (i = 0; i < n; i++)
521                 if ((lptr - vec_lines) < (num_lines - LINES + 1))
522                     lptr++;
523                 else
524                     break;
525             scrl((int) (lptr - olptr));
526             break;
527
528         case KEY_UP:
529         case 'p':
530             olptr = lptr;
531             for (i = 0; i < n; i++)
532                 if (lptr > vec_lines)
533                     lptr--;
534                 else
535                     break;
536             scrl((int) (lptr - olptr));
537             break;
538
539         case 'h':
540             /* FALLTHRU */
541         case KEY_HOME:
542             lptr = vec_lines;
543             break;
544
545         case '<':
546             if ((shift -= 8) < 0)
547                 shift = 0;
548             break;
549         case '>':
550             shift += 8;
551             break;
552
553         case 'e':
554             /* FALLTHRU */
555         case KEY_END:
556             if (num_lines > LINES)
557                 lptr = (vec_lines + num_lines - LINES + 1);
558             else
559                 lptr = (vec_lines + (num_lines - 2));
560             break;
561
562         case CTRL('F'):
563             /* FALLTHRU */
564         case KEY_NPAGE:
565             for (i = 0; i < n; i++) {
566                 if ((lptr - vec_lines) < (num_lines - 5))
567                     lptr += (LINES - 1);
568                 else
569                     lptr = (vec_lines + num_lines - 2);
570             }
571             break;
572
573         case CTRL('B'):
574             /* FALLTHRU */
575         case KEY_PPAGE:
576             for (i = 0; i < n; i++) {
577                 if ((lptr - vec_lines) >= LINES)
578                     lptr -= (LINES - 1);
579                 else
580                     lptr = vec_lines;
581             }
582             break;
583
584         case 'r':
585         case KEY_RIGHT:
586             shift += n;
587             break;
588
589         case 'l':
590         case KEY_LEFT:
591             shift -= n;
592             if (shift < 0) {
593                 shift = 0;
594                 beep();
595             }
596             break;
597
598         case 'q':
599         case QUIT:
600         case ESCAPE:
601             done = TRUE;
602             break;
603
604 #ifdef KEY_RESIZE
605         case KEY_RESIZE:        /* ignore this; ncurses will repaint */
606             break;
607 #endif
608         case 's':
609 #if HAVE_HALFDELAY
610             if (got_number) {
611                 halfdelay(my_delay = n);
612             } else {
613                 nodelay(stdscr, FALSE);
614                 my_delay = -1;
615             }
616 #else
617             nodelay(stdscr, FALSE);
618             my_delay = -1;
619 #endif
620             break;
621         case ' ':
622             nodelay(stdscr, TRUE);
623             my_delay = 0;
624             break;
625         case CTRL('L'):
626             redrawwin(stdscr);
627             break;
628         case ERR:
629             if (!my_delay)
630                 napms(50);
631             break;
632         case HELP_KEY_1:
633             popup_msg(stdscr, help);
634             break;
635         default:
636             beep();
637             break;
638         }
639         if (c >= KEY_MIN || (c > 0 && !isdigit(c))) {
640             got_number = FALSE;
641             value = 0;
642         }
643     }
644
645     finish(0);                  /* we're done */
646 }