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