]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/view.c
ncurses 6.0 - patch 20170826
[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.
37  *
38  * Takes a filename argument.  It's a simple file-viewer with various
39  * scroll-up and scroll-down commands.
40  *
41  * n    -- scroll one line forward
42  * p    -- scroll one line back
43  *
44  * Either command accepts a numeric prefix interpreted as a repeat count.
45  * Thus, typing `5n' should scroll forward 5 lines in the file.
46  *
47  * The way you can tell this is working OK is that, in the trace file,
48  * there should be one scroll operation plus a small number of line
49  * updates, as opposed to a whole-page update.  This means the physical
50  * scroll operation worked, and the refresh() code only had to do a
51  * partial repaint.
52  *
53  * $Id: view.c,v 1.101 2017/04/15 20:14:01 tom Exp $
54  */
55
56 #include <test.priv.h>
57 #include <widechars.h>
58 #include <popup_msg.h>
59
60 #include <time.h>
61
62 #undef CTRL                     /* conflict on AIX 5.2 with <sys/ioctl.h> */
63
64 #if HAVE_TERMIOS_H
65 # include <termios.h>
66 #else
67 #if !defined(__MINGW32__)
68 # include <sgtty.h>
69 #endif
70 #endif
71
72 #if !defined(sun) || !HAVE_TERMIOS_H
73 # if HAVE_SYS_IOCTL_H
74 #  include <sys/ioctl.h>
75 # endif
76 #endif
77
78 #define my_pair 1
79
80 /* This is needed to compile 'struct winsize' */
81 #if NEED_PTEM_H
82 #include <sys/stream.h>
83 #include <sys/ptem.h>
84 #endif
85
86 #undef CTRL
87 #define CTRL(x) ((x) & 0x1f)
88
89 static void finish(int sig) GCC_NORETURN;
90 static void show_all(const char *tag);
91
92 #if defined(SIGWINCH) && defined(TIOCGWINSZ) && HAVE_RESIZE_TERM
93 #define CAN_RESIZE 1
94 #else
95 #define CAN_RESIZE 0
96 #endif
97
98 #if CAN_RESIZE
99 static void adjust(int sig);
100 static int interrupted;
101 static bool waiting = FALSE;
102 #endif
103
104 static int shift = 0;
105 static bool try_color = FALSE;
106
107 static char *fname;
108 static NCURSES_CH_T **vec_lines;
109 static NCURSES_CH_T **lptr;
110 static int num_lines;
111
112 static void usage(void) GCC_NORETURN;
113
114 static void
115 usage(void)
116 {
117     static const char *msg[] =
118     {
119         "Usage: view [options] file"
120         ,""
121         ,"Options:"
122         ," -c       use color if terminal supports it"
123         ," -i       ignore INT, QUIT, TERM signals"
124         ," -n NUM   specify maximum number of lines (default 1000)"
125 #if defined(KEY_RESIZE)
126         ," -r       use old-style sigwinch handler rather than KEY_RESIZE"
127 #endif
128         ," -s       start in single-step mode, waiting for input"
129 #ifdef TRACE
130         ," -t       trace screen updates"
131         ," -T NUM   specify trace mask"
132 #endif
133     };
134     size_t n;
135     for (n = 0; n < SIZEOF(msg); n++)
136         fprintf(stderr, "%s\n", msg[n]);
137     ExitProgram(EXIT_FAILURE);
138 }
139
140 static int
141 ch_len(NCURSES_CH_T * src)
142 {
143     int result = 0;
144 #if USE_WIDEC_SUPPORT
145     int count;
146 #endif
147
148 #if USE_WIDEC_SUPPORT
149     for (;;) {
150         TEST_CCHAR(src, count, {
151             ++result;
152             ++src;
153         }
154         , {
155             break;
156         })
157     }
158 #else
159     while (*src++)
160         result++;
161 #endif
162     return result;
163 }
164
165 /*
166  * Allocate a string into an array of chtype's.  If UTF-8 mode is
167  * active, translate the string accordingly.
168  */
169 static NCURSES_CH_T *
170 ch_dup(char *src)
171 {
172     unsigned len = (unsigned) strlen(src);
173     NCURSES_CH_T *dst = typeMalloc(NCURSES_CH_T, len + 1);
174     size_t j, k;
175 #if USE_WIDEC_SUPPORT
176     wchar_t wstr[CCHARW_MAX + 1];
177     wchar_t wch;
178     int l = 0;
179     size_t rc;
180     int width;
181 #ifndef state_unused
182     mbstate_t state;
183 #endif
184 #endif /* USE_WIDEC_SUPPORT */
185
186 #if USE_WIDEC_SUPPORT
187     reset_mbytes(state);
188 #endif
189     for (j = k = 0; j < len; j++) {
190 #if USE_WIDEC_SUPPORT
191         rc = (size_t) check_mbytes(wch, src + j, len - j, state);
192         if (rc == (size_t) -1 || rc == (size_t) -2) {
193             break;
194         }
195         j += rc - 1;
196         width = wcwidth(wch);
197         if (width == 0) {
198             if (l == 0) {
199                 wstr[l++] = L' ';
200             }
201         } else if ((l > 0) || (l == CCHARW_MAX)) {
202             wstr[l] = L'\0';
203             l = 0;
204             if (setcchar(dst + k, wstr, 0, 0, NULL) != OK) {
205                 break;
206             }
207             ++k;
208         }
209         wstr[l++] = wch;
210 #else
211         dst[k++] = (chtype) UChar(src[j]);
212 #endif
213     }
214 #if USE_WIDEC_SUPPORT
215     if (l > 0) {
216         wstr[l] = L'\0';
217         if (setcchar(dst + k, wstr, 0, 0, NULL) == OK)
218             ++k;
219     }
220     wstr[0] = L'\0';
221     setcchar(dst + k, wstr, 0, 0, NULL);
222 #else
223     dst[k] = 0;
224 #endif
225     return dst;
226 }
227
228 int
229 main(int argc, char *argv[])
230 {
231     static const char *help[] =
232     {
233         "Commands:",
234         "  q,^Q,ESC       - quit this program",
235         "",
236         "  p,<Up>         - scroll the viewport up by one row",
237         "  n,<Down>       - scroll the viewport down by one row",
238         "  l,<Left>       - scroll the viewport left by one column",
239         "  r,<Right>      - scroll the viewport right by one column",
240         "",
241         "  h,<Home>       - scroll the viewport to top of file",
242         "  e,<End>        - scroll the viewport to end of file",
243         "",
244         "  ^L             - repaint using redrawwin()",
245         "",
246         "  0 through 9    - enter digits for count",
247         "  s              - use entered count for halfdelay() parameter",
248         "                 - if no entered count, stop nodelay()",
249         "  <space>        - begin nodelay()",
250         0
251     };
252
253     int MAXLINES = 1000;
254     FILE *fp;
255     char buf[BUFSIZ];
256     int i;
257     int my_delay = 0;
258     NCURSES_CH_T **olptr;
259     int value = 0;
260     bool done = FALSE;
261     bool got_number = FALSE;
262     bool single_step = FALSE;
263 #if CAN_RESIZE
264     bool nonposix_resize = FALSE;
265 #endif
266     const char *my_label = "Input";
267
268     setlocale(LC_ALL, "");
269
270 #ifndef NCURSES_VERSION
271     /*
272      * We know ncurses will catch SIGINT if we don't establish our own handler.
273      * Other versions of curses may/may not catch it.
274      */
275     (void) signal(SIGINT, finish);      /* arrange interrupts to terminate */
276 #endif
277
278     while ((i = getopt(argc, argv, "cin:rstT:")) != -1) {
279         switch (i) {
280         case 'c':
281             try_color = TRUE;
282             break;
283         case 'i':
284             CATCHALL(SIG_IGN);
285             break;
286         case 'n':
287             if ((MAXLINES = atoi(optarg)) < 1 ||
288                 (MAXLINES + 2) <= 1)
289                 usage();
290             break;
291 #if CAN_RESIZE
292         case 'r':
293             nonposix_resize = TRUE;
294             break;
295 #endif
296         case 's':
297             single_step = TRUE;
298             break;
299 #ifdef TRACE
300         case 'T':
301             {
302                 char *next = 0;
303                 int tvalue = (int) strtol(optarg, &next, 0);
304                 if (tvalue < 0 || (next != 0 && *next != 0))
305                     usage();
306                 trace((unsigned) tvalue);
307             }
308             break;
309         case 't':
310             trace(TRACE_CALLS);
311             break;
312 #endif
313         default:
314             usage();
315         }
316     }
317     if (optind + 1 != argc)
318         usage();
319
320     if ((vec_lines = typeCalloc(NCURSES_CH_T *, (size_t) MAXLINES + 2)) == 0)
321         usage();
322
323     assert(vec_lines != 0);
324
325     fname = argv[optind];
326     if ((fp = fopen(fname, "r")) == 0) {
327         perror(fname);
328         ExitProgram(EXIT_FAILURE);
329     }
330 #if CAN_RESIZE
331     if (nonposix_resize)
332         (void) signal(SIGWINCH, adjust);        /* arrange interrupts to resize */
333 #endif
334
335     Trace(("slurp the file"));
336     for (lptr = &vec_lines[0]; (lptr - vec_lines) < MAXLINES; lptr++) {
337         char temp[BUFSIZ], *s, *d;
338         int col;
339
340         if (fgets(buf, sizeof(buf), fp) == 0)
341             break;
342
343 #if USE_WIDEC_SUPPORT
344         if (lptr == vec_lines) {
345             if (!memcmp("", buf, 3)) {
346                 Trace(("trim BOM"));
347                 s = buf + 3;
348                 d = buf;
349                 do {
350                 } while ((*d++ = *s++) != '\0');
351             }
352         }
353 #endif
354
355         /* convert tabs and nonprinting chars so that shift will work properly */
356         for (s = buf, d = temp, col = 0; (*d = *s) != '\0'; s++) {
357             if (*d == '\r') {
358                 if (s[1] == '\n') {
359                     continue;
360                 } else {
361                     break;
362                 }
363             }
364             if (*d == '\n') {
365                 *d = '\0';
366                 break;
367             } else if (*d == '\t') {
368                 col = (col | 7) + 1;
369                 while ((d - temp) != col)
370                     *d++ = ' ';
371             } else
372 #if USE_WIDEC_SUPPORT
373                 col++, d++;
374 #else
375             if (isprint(UChar(*d))) {
376                 col++;
377                 d++;
378             } else {
379                 _nc_SPRINTF(d, _nc_SLIMIT(sizeof(temp) - (d - buf))
380                             "\\%03o", UChar(*s));
381                 d += strlen(d);
382                 col = (int) (d - temp);
383             }
384 #endif
385         }
386         *lptr = ch_dup(temp);
387     }
388     (void) fclose(fp);
389     num_lines = (int) (lptr - vec_lines);
390
391     (void) initscr();           /* initialize the curses library */
392     keypad(stdscr, TRUE);       /* enable keyboard mapping */
393     (void) nonl();              /* tell curses not to do NL->CR/NL on output */
394     (void) cbreak();            /* take input chars one at a time, no wait for \n */
395     (void) noecho();            /* don't echo input */
396     if (!single_step)
397         nodelay(stdscr, TRUE);
398     idlok(stdscr, TRUE);        /* allow use of insert/delete line */
399
400     if (try_color) {
401         if (has_colors()) {
402             start_color();
403             init_pair(my_pair, COLOR_WHITE, COLOR_BLUE);
404             bkgd((chtype) COLOR_PAIR(my_pair));
405         } else {
406             try_color = FALSE;
407         }
408     }
409
410     lptr = vec_lines;
411     while (!done) {
412         int n, c;
413
414         if (!got_number)
415             show_all(my_label);
416
417         for (;;) {
418 #if CAN_RESIZE
419             if (interrupted) {
420                 adjust(0);
421                 my_label = "interrupt";
422             }
423             waiting = TRUE;
424             c = getch();
425             waiting = FALSE;
426 #else
427             c = getch();
428 #endif
429             if ((c < 127) && isdigit(c)) {
430                 if (!got_number) {
431                     MvPrintw(0, 0, "Count: ");
432                     clrtoeol();
433                 }
434                 addch(UChar(c));
435                 value = 10 * value + (c - '0');
436                 got_number = TRUE;
437             } else
438                 break;
439         }
440         if (got_number && value) {
441             n = value;
442         } else {
443             n = 1;
444         }
445
446         if (c != ERR)
447             my_label = keyname(c);
448         switch (c) {
449         case KEY_DOWN:
450         case 'n':
451             olptr = lptr;
452             for (i = 0; i < n; i++)
453                 if ((lptr - vec_lines) < (num_lines - LINES + 1))
454                     lptr++;
455                 else
456                     break;
457             scrl((int) (lptr - olptr));
458             break;
459
460         case KEY_UP:
461         case 'p':
462             olptr = lptr;
463             for (i = 0; i < n; i++)
464                 if (lptr > vec_lines)
465                     lptr--;
466                 else
467                     break;
468             scrl((int) (lptr - olptr));
469             break;
470
471         case 'h':
472         case KEY_HOME:
473             lptr = vec_lines;
474             break;
475
476         case 'e':
477         case KEY_END:
478             if (num_lines > LINES)
479                 lptr = vec_lines + num_lines - LINES + 1;
480             else
481                 lptr = vec_lines;
482             break;
483
484         case 'r':
485         case KEY_RIGHT:
486             shift += n;
487             break;
488
489         case 'l':
490         case KEY_LEFT:
491             shift -= n;
492             if (shift < 0) {
493                 shift = 0;
494                 beep();
495             }
496             break;
497
498         case 'q':
499         case QUIT:
500         case ESCAPE:
501             done = TRUE;
502             break;
503
504 #ifdef KEY_RESIZE
505         case KEY_RESIZE:        /* ignore this; ncurses will repaint */
506             break;
507 #endif
508         case 's':
509             if (got_number) {
510                 halfdelay(my_delay = n);
511             } else {
512                 nodelay(stdscr, FALSE);
513                 my_delay = -1;
514             }
515             break;
516         case ' ':
517             nodelay(stdscr, TRUE);
518             my_delay = 0;
519             break;
520         case CTRL('L'):
521             redrawwin(stdscr);
522             break;
523         case ERR:
524             if (!my_delay)
525                 napms(50);
526             break;
527         case HELP_KEY_1:
528             popup_msg(stdscr, help);
529             break;
530         default:
531             beep();
532             break;
533         }
534         if (c >= KEY_MIN || (c > 0 && !isdigit(c))) {
535             got_number = FALSE;
536             value = 0;
537         }
538     }
539
540     finish(0);                  /* we're done */
541 }
542
543 static void
544 finish(int sig)
545 {
546     endwin();
547 #if NO_LEAKS
548     if (vec_lines != 0) {
549         int n;
550         for (n = 0; n < num_lines; ++n) {
551             free(vec_lines[n]);
552         }
553         free(vec_lines);
554     }
555 #endif
556     ExitProgram(sig != 0 ? EXIT_FAILURE : EXIT_SUCCESS);
557 }
558
559 #if CAN_RESIZE
560 /*
561  * This uses functions that are "unsafe", but it seems to work on SunOS. 
562  * Usually: the "unsafe" refers to the functions that POSIX lists which may be
563  * called from a signal handler.  Those do not include buffered I/O, which is
564  * used for instance in wrefresh().  To be really portable, you should use the
565  * KEY_RESIZE return (which relies on ncurses' sigwinch handler).
566  *
567  * The 'wrefresh(curscr)' is needed to force the refresh to start from the top
568  * of the screen -- some xterms mangle the bitmap while resizing.
569  */
570 static void
571 adjust(int sig)
572 {
573     if (waiting || sig == 0) {
574         struct winsize size;
575
576         if (ioctl(fileno(stdout), TIOCGWINSZ, &size) == 0) {
577             resize_term(size.ws_row, size.ws_col);
578             wrefresh(curscr);
579             show_all(sig ? "SIGWINCH" : "interrupt");
580         }
581         interrupted = FALSE;
582     } else {
583         interrupted = TRUE;
584     }
585     (void) signal(SIGWINCH, adjust);    /* some systems need this */
586 }
587 #endif /* CAN_RESIZE */
588
589 static void
590 show_all(const char *tag)
591 {
592     int i;
593     char temp[BUFSIZ];
594     NCURSES_CH_T *s;
595     time_t this_time;
596
597 #if CAN_RESIZE
598     _nc_SPRINTF(temp, _nc_SLIMIT(sizeof(temp))
599                 "%.20s (%3dx%3d) col %d ", tag, LINES, COLS, shift);
600     i = (int) strlen(temp);
601     if ((i + 7) < (int) sizeof(temp)) {
602         _nc_SPRINTF(temp + i, _nc_SLIMIT(sizeof(temp) - (size_t) i)
603                     "view %.*s",
604                     (int) (sizeof(temp) - 7 - (size_t) i),
605                     fname);
606     }
607 #else
608     (void) tag;
609     _nc_SPRINTF(temp, _nc_SLIMIT(sizeof(temp))
610                 "view %.*s", (int) sizeof(temp) - 7, fname);
611 #endif
612     move(0, 0);
613     printw("%.*s", COLS, temp);
614     clrtoeol();
615     this_time = time((time_t *) 0);
616     _nc_STRNCPY(temp, ctime(&this_time), (size_t) 30);
617     if ((i = (int) strlen(temp)) != 0) {
618         temp[--i] = 0;
619         if (move(0, COLS - i - 2) != ERR)
620             printw("  %s", temp);
621     }
622
623     scrollok(stdscr, FALSE);    /* prevent screen from moving */
624     for (i = 1; i < LINES; i++) {
625         move(i, 0);
626         printw("%3ld:", (long) (lptr + i - vec_lines));
627         clrtoeol();
628         if ((s = lptr[i - 1]) != 0) {
629             int len = ch_len(s);
630             if (len > shift) {
631 #if USE_WIDEC_SUPPORT
632                 add_wchstr(s + shift);
633 #else
634                 addchstr(s + shift);
635 #endif
636             }
637 #if defined(NCURSES_VERSION) || defined(HAVE_WCHGAT)
638             if (try_color)
639                 wchgat(stdscr, -1, A_NORMAL, my_pair, NULL);
640 #endif
641         }
642     }
643     setscrreg(1, LINES - 1);
644     scrollok(stdscr, TRUE);
645     refresh();
646 }