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