• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /****************************************************************************
2  * Copyright 2019-2021,2022 Thomas E. Dickey                                *
3  * Copyright 2017 Free Software Foundation, Inc.                            *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29 /*
30  * clone of view.c, using pads
31  *
32  * $Id: padview.c,v 1.22 2022/12/04 00:40:11 tom Exp $
33  */
34 
35 #include <test.priv.h>
36 #include <widechars.h>
37 #include <popup_msg.h>
38 
39 #include <sys/stat.h>
40 #include <time.h>
41 
42 #if HAVE_NEWPAD
43 
44 static GCC_NORETURN void finish(int sig);
45 
46 #define my_pair 1
47 
48 static WINDOW *global_pad;
49 static int shift = 0;
50 static bool try_color = FALSE;
51 
52 static char *fname;
53 static int num_lines;
54 
55 #if USE_WIDEC_SUPPORT
56 static bool n_option = FALSE;
57 #endif
58 
59 static void
failed(const char * msg)60 failed(const char *msg)
61 {
62     endwin();
63     fprintf(stderr, "%s\n", msg);
64     ExitProgram(EXIT_FAILURE);
65 }
66 
67 static void
finish(int sig)68 finish(int sig)
69 {
70     endwin();
71     if (global_pad != NULL)
72 	delwin(global_pad);
73     ExitProgram(sig != 0 ? EXIT_FAILURE : EXIT_SUCCESS);
74 }
75 
76 static void
show_all(const char * tag,WINDOW * my_pad,int my_row)77 show_all(const char *tag, WINDOW *my_pad, int my_row)
78 {
79     int i;
80     int digits;
81     char temp[BUFSIZ];
82     time_t this_time;
83 
84     for (digits = 1, i = num_lines; i > 0; i /= 10) {
85 	++digits;
86     }
87 
88     wattrset(stdscr, COLOR_PAIR(my_pair));
89     clear();
90 
91     _nc_SPRINTF(temp, _nc_SLIMIT(sizeof(temp))
92 		"view %.*s", (int) strlen(tag), tag);
93     i = (int) strlen(temp);
94     _nc_SPRINTF(temp + i, _nc_SLIMIT(sizeof(temp) - (size_t) i)
95 		" %.*s", (int) sizeof(temp) - i - 2, fname);
96     mvprintw(0, 0, "%.*s", COLS, temp);
97     this_time = time((time_t *) 0);
98     _nc_STRNCPY(temp, ctime(&this_time), (size_t) 30);
99     if ((i = (int) strlen(temp)) != 0) {
100 	temp[--i] = 0;
101 	mvprintw(0, COLS - i - 2, "  %s", temp);
102     }
103 
104     for (i = 1; i < LINES; i++) {
105 	int actual = my_row + i;
106 	if (actual > num_lines) {
107 	    break;
108 	}
109 	mvprintw(i, 0, "%*d:", digits, actual);
110     }
111     wnoutrefresh(stdscr);
112     pnoutrefresh(my_pad, my_row, shift, 1, digits + 1, LINES - 1, COLS - 1);
113     doupdate();
114 }
115 
116 static WINDOW *
read_file(const char * filename)117 read_file(const char *filename)
118 {
119     FILE *fp;
120     int pass;
121     int k;
122     int height, width;
123     size_t j;
124     size_t len;
125     struct stat sb;
126     char *my_blob;
127     char **my_vec = 0;
128     WINDOW *my_pad;
129 
130     if (stat(filename, &sb) != 0
131 	|| (sb.st_mode & S_IFMT) != S_IFREG) {
132 	failed("input is not a file");
133     }
134 
135     if (sb.st_size == 0) {
136 	failed("input is empty");
137     }
138 
139     if ((fp = fopen(filename, "r")) == 0) {
140 	failed("cannot open input-file");
141     }
142 
143     if ((my_blob = malloc((size_t) sb.st_size + 1)) == 0) {
144 	failed("cannot allocate memory for input-file");
145     }
146 
147     len = fread(my_blob, sizeof(char), (size_t) sb.st_size, fp);
148     fclose(fp);
149 
150     if (len > (size_t) sb.st_size)
151 	len = (size_t) sb.st_size;
152     my_blob[len] = '\0';
153 
154     for (pass = 0; pass < 2; ++pass) {
155 	char *base = my_blob;
156 	k = 0;
157 	for (j = 0; j < len; ++j) {
158 	    if (my_blob[j] == '\n') {
159 		if (pass) {
160 		    my_vec[k] = base;
161 		    my_blob[j] = '\0';
162 		}
163 		base = my_blob + j + 1;
164 		++k;
165 	    }
166 	}
167 	if (base != (my_blob + j)) {
168 	    if (pass)
169 		my_vec[k] = base;
170 	    ++k;
171 	}
172 	num_lines = k;
173 	if (pass == 0) {
174 	    if (((my_vec = typeCalloc(char *, (size_t) k + 2)) == 0)) {
175 		failed("cannot allocate line-vector #1");
176 	    }
177 	} else {
178 	    if (my_vec[0] == NULL)
179 		my_vec[0] = my_blob;
180 	}
181     }
182 
183 #if USE_WIDEC_SUPPORT
184     if (!memcmp("\357\273\277", my_blob, 3)) {
185 	char *s = my_blob + 3;
186 	char *d = my_blob;
187 	Trace(("trim BOM"));
188 	do {
189 	} while ((*d++ = *s++) != '\0');
190     }
191 #endif
192 
193     height = num_lines;
194     width = (int) strlen(my_vec[0]);
195     for (k = 1; my_vec[k]; ++k) {
196 	int check = (int) (my_vec[k] - my_vec[k - 1]);
197 	if (width < check)
198 	    width = check;
199     }
200     width = (width + 1) * 5;
201     my_pad = newpad(height, width);
202     if (my_pad == 0)
203 	failed("cannot allocate pad workspace");
204     if (try_color) {
205 	wattrset(my_pad, COLOR_PAIR(my_pair));
206 	wbkgd(my_pad, (chtype) (' ' | COLOR_PAIR(my_pair)));
207     }
208 
209     /*
210      * Use the curses library for rendering, including tab-conversion.
211      */
212     Trace(("slurp the file"));
213     for (k = 0; my_vec[k]; ++k) {
214 	char *s;
215 #if USE_WIDEC_SUPPORT
216 	char *last = my_vec[k] + (int) strlen(my_vec[k]);
217 	wchar_t wch[2];
218 	size_t rc;
219 #ifndef state_unused
220 	mbstate_t state;
221 #endif
222 #endif /* USE_WIDEC_SUPPORT */
223 
224 	wmove(my_pad, k, 0);
225 #if USE_WIDEC_SUPPORT
226 	wch[1] = 0;
227 	reset_mbytes(state);
228 #endif
229 	for (s = my_vec[k]; *s != '\0'; ++s) {
230 #if USE_WIDEC_SUPPORT
231 	    if (!n_option) {
232 		rc = (size_t) check_mbytes(wch[0], s, (size_t) (last - s), state);
233 		if ((long) rc == -1 || (long) rc == -2) {
234 		    break;
235 		}
236 		s += rc - 1;
237 		waddwstr(my_pad, wch);
238 	    } else
239 #endif
240 		waddch(my_pad, *s & 0xff);
241 	}
242     }
243 
244     free(my_vec);
245     free(my_blob);
246 
247     return my_pad;
248 }
249 
250 static void
usage(int ok)251 usage(int ok)
252 {
253     static const char *msg[] =
254     {
255 	"Usage: view [options] file"
256 	,""
257 	,USAGE_COMMON
258 	,"Options:"
259 	," -c       use color if terminal supports it"
260 	," -i       ignore INT, QUIT, TERM signals"
261 #if USE_WIDEC_SUPPORT
262 	," -n       use waddch (bytes) rather then wadd_wch (wide-chars)"
263 #endif
264 	," -s       start in single-step mode, waiting for input"
265 #ifdef TRACE
266 	," -t       trace screen updates"
267 	," -T NUM   specify trace mask"
268 #endif
269     };
270     size_t n;
271     for (n = 0; n < SIZEOF(msg); n++)
272 	fprintf(stderr, "%s\n", msg[n]);
273     ExitProgram(ok ? EXIT_SUCCESS : EXIT_FAILURE);
274 }
275 /* *INDENT-OFF* */
VERSION_COMMON()276 VERSION_COMMON()
277 /* *INDENT-ON* */
278 
279 int
280 main(int argc, char *argv[])
281 {
282     static const char *help[] =
283     {
284 	"Commands:",
285 	"  q,^Q,ESC       - quit this program",
286 	"",
287 	"  p,<Up>         - scroll the viewport up by one row",
288 	"  n,<Down>       - scroll the viewport down by one row",
289 	"  l,<Left>       - scroll the viewport left by one column",
290 	"  r,<Right>      - scroll the viewport right by one column",
291 	"  <,>            - scroll the viewport left/right by 8 columns",
292 	"",
293 	"  h,<Home>       - scroll the viewport to top of file",
294 	"  ^F,<PageDn>    - scroll to the next page",
295 	"  ^B,<PageUp>    - scroll to the previous page",
296 	"  e,<End>        - scroll the viewport to end of file",
297 	"",
298 	"  ^L             - repaint using redrawwin()",
299 	"",
300 	"  0 through 9    - enter digits for count",
301 	"  s              - use entered count for halfdelay() parameter",
302 	"                 - if no entered count, stop nodelay()",
303 	"  <space>        - begin nodelay()",
304 	0
305     };
306 
307     int ch;
308     int i;
309     int my_delay = 0;
310     WINDOW *my_pad;
311     int my_row = 0;
312     int value = 0;
313     bool done = FALSE;
314     bool got_number = FALSE;
315     bool ignore_sigs = FALSE;
316     bool single_step = FALSE;
317     const char *my_label = "Input";
318 
319     setlocale(LC_ALL, "");
320 
321     while ((ch = getopt(argc, argv, OPTS_COMMON "cinstT:")) != -1) {
322 	switch (ch) {
323 	case 'c':
324 	    try_color = TRUE;
325 	    break;
326 	case 'i':
327 	    ignore_sigs = TRUE;
328 	    break;
329 #if USE_WIDEC_SUPPORT
330 	case 'n':
331 	    n_option = TRUE;
332 	    break;
333 #endif
334 	case 's':
335 	    single_step = TRUE;
336 	    break;
337 #ifdef TRACE
338 	case 'T':
339 	    {
340 		char *next = 0;
341 		int tvalue = (int) strtol(optarg, &next, 0);
342 		if (tvalue < 0 || (next != 0 && *next != 0))
343 		    usage(FALSE);
344 		curses_trace((unsigned) tvalue);
345 	    }
346 	    break;
347 	case 't':
348 	    curses_trace(TRACE_CALLS);
349 	    break;
350 #endif
351 	case OPTS_VERSION:
352 	    show_version(argv);
353 	    ExitProgram(EXIT_SUCCESS);
354 	default:
355 	    usage(ch == OPTS_USAGE);
356 	    /* NOTREACHED */
357 	}
358     }
359     if (optind + 1 != argc)
360 	usage(FALSE);
361 
362     InitAndCatch(initscr(), ignore_sigs ? SIG_IGN : finish);
363     keypad(stdscr, TRUE);	/* enable keyboard mapping */
364     (void) nonl();		/* tell curses not to do NL->CR/NL on output */
365     (void) cbreak();		/* take input chars one at a time, no wait for \n */
366     (void) noecho();		/* don't echo input */
367     if (!single_step)
368 	nodelay(stdscr, TRUE);
369     idlok(stdscr, TRUE);	/* allow use of insert/delete line */
370 
371     if (try_color) {
372 	if (has_colors()) {
373 	    start_color();
374 	    init_pair(my_pair, COLOR_WHITE, COLOR_BLUE);
375 	    bkgd((chtype) (' ' | COLOR_PAIR(my_pair)));
376 	} else {
377 	    try_color = FALSE;
378 	}
379     }
380 
381     /*
382      * Do this after starting color, otherwise the pad's background will be
383      * uncolored after the ncurses 6.1.20181208 fixes.
384      */
385     global_pad =
386 	my_pad = read_file(fname = argv[optind]);
387 
388     my_row = 0;
389     while (!done) {
390 	int n, c;
391 
392 	if (!got_number)
393 	    show_all(my_label, my_pad, my_row);
394 
395 	for (;;) {
396 	    c = getch();
397 	    if ((c < 127) && isdigit(c)) {
398 		if (!got_number) {
399 		    MvPrintw(0, 0, "Count: ");
400 		    clrtoeol();
401 		}
402 		addch(UChar(c));
403 		value = 10 * value + (c - '0');
404 		got_number = TRUE;
405 	    } else
406 		break;
407 	}
408 	if (got_number && value) {
409 	    n = value;
410 	} else {
411 	    n = 1;
412 	}
413 
414 	if (c != ERR)
415 	    my_label = keyname(c);
416 	switch (c) {
417 	case KEY_DOWN:
418 	case 'n':
419 	    for (i = 0; i < n; i++)
420 		if (my_row < (num_lines - LINES + 1))
421 		    my_row++;
422 		else
423 		    break;
424 	    break;
425 
426 	case KEY_UP:
427 	case 'p':
428 	    for (i = 0; i < n; i++)
429 		if (my_row > 0)
430 		    my_row--;
431 		else
432 		    break;
433 	    break;
434 
435 	case 'h':
436 	    /* FALLTHRU */
437 	case KEY_HOME:
438 	    my_row = 0;
439 	    break;
440 
441 	case '<':
442 	    if ((shift -= 8) < 0)
443 		shift = 0;
444 	    break;
445 	case '>':
446 	    shift += 8;
447 	    break;
448 
449 	case 'e':
450 	    /* FALLTHRU */
451 	case KEY_END:
452 	    if (num_lines > LINES)
453 		my_row = (num_lines - LINES + 1);
454 	    else
455 		my_row = (num_lines - 2);
456 	    break;
457 
458 	case CTRL('F'):
459 	    /* FALLTHRU */
460 	case KEY_NPAGE:
461 	    for (i = 0; i < n; i++) {
462 		if (my_row < (num_lines - 5))
463 		    my_row += (LINES - 1);
464 		else
465 		    my_row = (num_lines - 2);
466 	    }
467 	    break;
468 
469 	case CTRL('B'):
470 	    /* FALLTHRU */
471 	case KEY_PPAGE:
472 	    for (i = 0; i < n; i++) {
473 		if (my_row >= LINES)
474 		    my_row -= (LINES - 1);
475 		else
476 		    my_row = 0;
477 	    }
478 	    break;
479 
480 	case 'r':
481 	case KEY_RIGHT:
482 	    shift += n;
483 	    break;
484 
485 	case 'l':
486 	case KEY_LEFT:
487 	    shift -= n;
488 	    if (shift < 0) {
489 		shift = 0;
490 		beep();
491 	    }
492 	    break;
493 
494 	case 'q':
495 	case QUIT:
496 	case ESCAPE:
497 	    done = TRUE;
498 	    break;
499 
500 #ifdef KEY_RESIZE
501 	case KEY_RESIZE:	/* ignore this; ncurses will repaint */
502 	    break;
503 #endif
504 	case 's':
505 #if HAVE_HALFDELAY
506 	    if (got_number) {
507 		halfdelay(my_delay = n);
508 	    } else {
509 		nodelay(stdscr, FALSE);
510 		my_delay = -1;
511 	    }
512 #else
513 	    nodelay(stdscr, FALSE);
514 	    my_delay = -1;
515 #endif
516 	    break;
517 	case ' ':
518 	    nodelay(stdscr, TRUE);
519 	    my_delay = 0;
520 	    break;
521 	case CTRL('L'):
522 	    redrawwin(stdscr);
523 	    break;
524 	case ERR:
525 	    if (!my_delay)
526 		napms(50);
527 	    break;
528 	case HELP_KEY_1:
529 	    popup_msg(stdscr, help);
530 	    break;
531 	default:
532 	    beep();
533 	    break;
534 	}
535 	if (c >= KEY_MIN || (c > 0 && !isdigit(c))) {
536 	    got_number = FALSE;
537 	    value = 0;
538 	}
539     }
540 
541     finish(0);			/* we're done */
542 }
543 #else
544 int
main(void)545 main(void)
546 {
547     printf("This program requires the curses pad functions\n");
548     ExitProgram(EXIT_FAILURE);
549 }
550 #endif
551