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