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