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