]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/view.c
ncurses 6.0 - patch 20171021
[ncurses.git] / test / view.c
1 /****************************************************************************
2  * Copyright (c) 1998-2016,2017 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.129 2017/10/22 00:49:23 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 #undef CTRL                     /* conflict on AIX 5.2 with <sys/ioctl.h> */
65
66 static void finish(int sig) GCC_NORETURN;
67
68 #define my_pair 1
69
70 #undef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72
73 static int shift = 0;
74 static bool try_color = FALSE;
75
76 static char *fname;
77 static NCURSES_CH_T **vec_lines;
78 static NCURSES_CH_T **lptr;
79 static int num_lines;
80
81 #if USE_WIDEC_SUPPORT
82 static bool n_option = FALSE;
83 #endif
84
85 static void usage(void) GCC_NORETURN;
86
87 static void
88 failed(const char *msg)
89 {
90     endwin();
91     fprintf(stderr, "%s\n", msg);
92     ExitProgram(EXIT_FAILURE);
93 }
94
95 static int
96 ch_len(NCURSES_CH_T * src)
97 {
98     int result = 0;
99 #if USE_WIDEC_SUPPORT
100     int count;
101 #endif
102
103 #if USE_WIDEC_SUPPORT
104     for (;;) {
105         TEST_CCHAR(src, count, {
106             int len = wcwidth(test_wch[0]);
107             result += (len > 0) ? len : 1;
108             ++src;
109         }
110         , {
111             break;
112         })
113     }
114 #else
115     while (*src++)
116         result++;
117 #endif
118     return result;
119 }
120
121 static void
122 finish(int sig)
123 {
124     endwin();
125 #if NO_LEAKS
126     if (vec_lines != 0) {
127         int n;
128         for (n = 0; n < num_lines; ++n) {
129             free(vec_lines[n]);
130         }
131         free(vec_lines);
132     }
133 #endif
134     ExitProgram(sig != 0 ? EXIT_FAILURE : EXIT_SUCCESS);
135 }
136
137 static void
138 show_all(const char *tag)
139 {
140     int i;
141     char temp[BUFSIZ];
142     NCURSES_CH_T *s;
143     time_t this_time;
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) - 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("%3d:", 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("", 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         if ((vec_lines[k] = typeCalloc(NCURSES_CH_T, (size_t) x + 1)) == 0)
351             failed("cannot allocate line-vector #3");
352 #if USE_WIDEC_SUPPORT
353         win_wchnstr(my_win, vec_lines[k], x);
354 #else
355         winchnstr(my_win, vec_lines[k], x);
356 #endif
357     }
358
359     delwin(my_win);
360     free(my_vec);
361     free(my_blob);
362 }
363
364 static void
365 usage(void)
366 {
367     static const char *msg[] =
368     {
369         "Usage: view [options] file"
370         ,""
371         ,"Options:"
372         ," -c       use color if terminal supports it"
373         ," -i       ignore INT, QUIT, TERM signals"
374 #if USE_WIDEC_SUPPORT
375         ," -n       use waddch (bytes) rather then wadd_wch (wide-chars)"
376 #endif
377         ," -s       start in single-step mode, waiting for input"
378 #ifdef TRACE
379         ," -t       trace screen updates"
380         ," -T NUM   specify trace mask"
381 #endif
382     };
383     size_t n;
384     for (n = 0; n < SIZEOF(msg); n++)
385         fprintf(stderr, "%s\n", msg[n]);
386     ExitProgram(EXIT_FAILURE);
387 }
388
389 int
390 main(int argc, char *argv[])
391 {
392     static const char *help[] =
393     {
394         "Commands:",
395         "  q,^Q,ESC       - quit this program",
396         "",
397         "  p,<Up>         - scroll the viewport up by one row",
398         "  n,<Down>       - scroll the viewport down by one row",
399         "  l,<Left>       - scroll the viewport left by one column",
400         "  r,<Right>      - scroll the viewport right by one column",
401         "",
402         "  h,<Home>       - scroll the viewport to top of file",
403         "  ^F,<PageDn>    - scroll to the next page",
404         "  ^B,<PageUp>    - scroll to the previous page",
405         "  e,<End>        - scroll the viewport to end of file",
406         "",
407         "  ^L             - repaint using redrawwin()",
408         "",
409         "  0 through 9    - enter digits for count",
410         "  s              - use entered count for halfdelay() parameter",
411         "                 - if no entered count, stop nodelay()",
412         "  <space>        - begin nodelay()",
413         0
414     };
415
416     int i;
417     int my_delay = 0;
418     NCURSES_CH_T **olptr;
419     int value = 0;
420     bool done = FALSE;
421     bool got_number = FALSE;
422     bool ignore_sigs = FALSE;
423     bool single_step = FALSE;
424     const char *my_label = "Input";
425
426     setlocale(LC_ALL, "");
427
428     while ((i = getopt(argc, argv, "cirstT:")) != -1) {
429         switch (i) {
430         case 'c':
431             try_color = TRUE;
432             break;
433         case 'i':
434             ignore_sigs = TRUE;
435             break;
436         case 's':
437             single_step = TRUE;
438             break;
439 #ifdef TRACE
440         case 'T':
441             {
442                 char *next = 0;
443                 int tvalue = (int) strtol(optarg, &next, 0);
444                 if (tvalue < 0 || (next != 0 && *next != 0))
445                     usage();
446                 trace((unsigned) tvalue);
447             }
448             break;
449         case 't':
450             trace(TRACE_CALLS);
451             break;
452 #endif
453         default:
454             usage();
455         }
456     }
457     if (optind + 1 != argc)
458         usage();
459
460     InitAndCatch(initscr(), ignore_sigs ? SIG_IGN : finish);
461     keypad(stdscr, TRUE);       /* enable keyboard mapping */
462     (void) nonl();              /* tell curses not to do NL->CR/NL on output */
463     (void) cbreak();            /* take input chars one at a time, no wait for \n */
464     (void) noecho();            /* don't echo input */
465     if (!single_step)
466         nodelay(stdscr, TRUE);
467     idlok(stdscr, TRUE);        /* allow use of insert/delete line */
468
469     read_file(fname = argv[optind]);
470
471     if (try_color) {
472         if (has_colors()) {
473             start_color();
474             init_pair(my_pair, COLOR_WHITE, COLOR_BLUE);
475             bkgd((chtype) COLOR_PAIR(my_pair));
476         } else {
477             try_color = FALSE;
478         }
479     }
480
481     lptr = vec_lines;
482     while (!done) {
483         int n, c;
484
485         if (!got_number)
486             show_all(my_label);
487
488         for (;;) {
489             c = getch();
490             if ((c < 127) && isdigit(c)) {
491                 if (!got_number) {
492                     MvPrintw(0, 0, "Count: ");
493                     clrtoeol();
494                 }
495                 addch(UChar(c));
496                 value = 10 * value + (c - '0');
497                 got_number = TRUE;
498             } else
499                 break;
500         }
501         if (got_number && value) {
502             n = value;
503         } else {
504             n = 1;
505         }
506
507         if (c != ERR)
508             my_label = keyname(c);
509         switch (c) {
510         case KEY_DOWN:
511         case 'n':
512             olptr = lptr;
513             for (i = 0; i < n; i++)
514                 if ((lptr - vec_lines) < (num_lines - LINES + 1))
515                     lptr++;
516                 else
517                     break;
518             scrl((int) (lptr - olptr));
519             break;
520
521         case KEY_UP:
522         case 'p':
523             olptr = lptr;
524             for (i = 0; i < n; i++)
525                 if (lptr > vec_lines)
526                     lptr--;
527                 else
528                     break;
529             scrl((int) (lptr - olptr));
530             break;
531
532         case '<':
533             shift = 0;
534             /* FALLTHRU */
535         case 'h':
536             /* FALLTHRU */
537         case KEY_HOME:
538             lptr = vec_lines;
539             break;
540
541         case '>':
542             shift = 0;
543             /* FALLTHRU */
544         case 'e':
545             /* FALLTHRU */
546         case KEY_END:
547             if (num_lines > LINES)
548                 lptr = (vec_lines + num_lines - LINES + 1);
549             else
550                 lptr = (vec_lines + (num_lines - 2));
551             break;
552
553         case CTRL('F'):
554             /* FALLTHRU */
555         case KEY_NPAGE:
556             for (i = 0; i < n; i++) {
557                 if ((lptr - vec_lines) < (num_lines - 5))
558                     lptr += (LINES - 1);
559                 else
560                     lptr = (vec_lines + num_lines - 2);
561             }
562             break;
563
564         case CTRL('B'):
565             /* FALLTHRU */
566         case KEY_PPAGE:
567             for (i = 0; i < n; i++) {
568                 if ((lptr - vec_lines) >= LINES)
569                     lptr -= (LINES - 1);
570                 else
571                     lptr = vec_lines;
572             }
573             break;
574
575         case 'r':
576         case KEY_RIGHT:
577             shift += n;
578             break;
579
580         case 'l':
581         case KEY_LEFT:
582             shift -= n;
583             if (shift < 0) {
584                 shift = 0;
585                 beep();
586             }
587             break;
588
589         case 'q':
590         case QUIT:
591         case ESCAPE:
592             done = TRUE;
593             break;
594
595 #ifdef KEY_RESIZE
596         case KEY_RESIZE:        /* ignore this; ncurses will repaint */
597             break;
598 #endif
599         case 's':
600 #if HAVE_HALFDELAY
601             if (got_number) {
602                 halfdelay(my_delay = n);
603             } else {
604                 nodelay(stdscr, FALSE);
605                 my_delay = -1;
606             }
607 #else
608             nodelay(stdscr, FALSE);
609             my_delay = -1;
610 #endif
611             break;
612         case ' ':
613             nodelay(stdscr, TRUE);
614             my_delay = 0;
615             break;
616         case CTRL('L'):
617             redrawwin(stdscr);
618             break;
619         case ERR:
620             if (!my_delay)
621                 napms(50);
622             break;
623         case HELP_KEY_1:
624             popup_msg(stdscr, help);
625             break;
626         default:
627             beep();
628             break;
629         }
630         if (c >= KEY_MIN || (c > 0 && !isdigit(c))) {
631             got_number = FALSE;
632             value = 0;
633         }
634     }
635
636     finish(0);                  /* we're done */
637 }