]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/savescreen.c
610b86d041bd1dd07730b7d63fd03099c80ecdbb
[ncurses.git] / test / savescreen.c
1 /****************************************************************************
2  * Copyright (c) 2007-2017,2018 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  * $Id: savescreen.c,v 1.52 2018/02/03 23:18:50 tom Exp $
30  *
31  * Demonstrate save/restore functions from the curses library.
32  * Thomas Dickey - 2007/7/14
33  */
34
35 #include <test.priv.h>
36 #include <popup_msg.h>
37 #include <parse_rgb.h>
38
39 #if HAVE_SCR_DUMP
40
41 #include <sys/types.h>
42 #include <sys/stat.h>
43
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
46 # include <time.h>
47 #else
48 # if HAVE_SYS_TIME_H
49 #  include <sys/time.h>
50 # else
51 #  include <time.h>
52 # endif
53 #endif
54
55 #if defined(__hpux)
56 #define MyMarker 'X'
57 #else
58 #define MyMarker ACS_DIAMOND
59 #endif
60
61 #define MAX_ANSI 8
62
63 static bool use_init = FALSE;
64 static bool keep_dumps = FALSE;
65
66 #if USE_WIDEC_SUPPORT
67 /* In HPUX curses, cchar_t is opaque; other implementations are not */
68 static wchar_t
69 BaseChar(cchar_t data)
70 {
71     wchar_t my_wchar[CCHARW_MAX];
72     attr_t my_attr;
73     short my_pair;
74     getcchar(&data, my_wchar, &my_attr, &my_pair, NULL);
75     return my_wchar[0];
76 }
77 #endif
78
79 static int
80 fexists(const char *name)
81 {
82     struct stat sb;
83     return (stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFREG);
84 }
85
86 static void
87 setup_next(void)
88 {
89     curs_set(1);
90     reset_shell_mode();
91 }
92
93 static void
94 cleanup(char *files[])
95 {
96     int n;
97
98     if (!keep_dumps) {
99         for (n = 0; files[n] != 0; ++n) {
100             unlink(files[n]);
101         }
102     }
103 }
104
105 static int
106 load_screen(char *filename)
107 {
108     int result;
109
110     if (use_init) {
111         if ((result = scr_init(filename)) != ERR)
112             result = scr_restore(filename);
113     } else {
114         result = scr_set(filename);
115     }
116     return result;
117 }
118
119 /*
120  * scr_restore() or scr_set() operates on curscr.  If we read a character using
121  * getch() that will refresh stdscr, wiping out the result.  To avoid that,
122  * copy the data back from curscr to stdscr.
123  */
124 static void
125 after_load(void)
126 {
127     overwrite(curscr, stdscr);
128     doupdate();
129 }
130
131 static void
132 show_what(int color, int which, int last)
133 {
134     int y, x, n;
135     time_t now;
136     char *mytime;
137
138     getyx(stdscr, y, x);
139
140     move(0, 0);
141     printw("Color %d.  Saved %d of %d (? for help)", color, which, last + 1);
142
143     now = time((time_t *) 0);
144     mytime = ctime(&now);
145     for (n = (int) strlen(mytime) - 1; n >= 0; --n) {
146         if (isspace(UChar(mytime[n]))) {
147             mytime[n] = '\0';
148         } else {
149             break;
150         }
151     }
152     mvprintw(0, (COLS - n - 2), " %s", mytime);
153
154     move(y, x);
155
156     refresh();
157 }
158
159 static int
160 get_command(int color, int which, int last)
161 {
162     int ch;
163
164     timeout(50);
165
166     do {
167         show_what(color, which, last);
168         ch = getch();
169     } while (ch == ERR);
170
171     return ch;
172 }
173
174 static int
175 dump_screen(char **files, int color, int which, int last, bool use_colors)
176 {
177 #if USE_WIDEC_SUPPORT
178     cchar_t mycc;
179     int myxx;
180 #endif
181     char *filename = files[which];
182     bool dumped = FALSE;
183
184     if (filename != 0) {
185         dumped = TRUE;
186         show_what(color, ++which, last);
187         if (scr_dump(filename) == ERR) {
188             endwin();
189             printf("Cannot write screen-dump %s\n", filename);
190             cleanup(files);
191             ExitProgram(EXIT_SUCCESS);
192         }
193         if (use_colors) {
194             int cx, cy;
195             int pair = 1 + (which % MAX_ANSI);
196             /*
197              * Change the background color, to make it more obvious.  But that
198              * changes the existing text-color.  Copy the old values from the
199              * currently displayed screen.
200              */
201             bkgd((chtype) COLOR_PAIR(pair));
202             for (cy = 1; cy < LINES; ++cy) {
203                 for (cx = 0; cx < COLS; ++cx) {
204                     wmove(curscr, cy, cx);
205                     wmove(stdscr, cy, cx);
206 #if USE_WIDEC_SUPPORT
207                     if (win_wch(curscr, &mycc) != ERR) {
208                         myxx = wcwidth(BaseChar(mycc));
209                         if (myxx > 0) {
210                             wadd_wchnstr(stdscr, &mycc, 1);
211                             cx += (myxx - 1);
212                         }
213                     }
214 #else
215                     waddch(stdscr, winch(curscr));
216 #endif
217                 }
218             }
219         }
220     }
221     return dumped;
222 }
223
224 static void
225 editor_help(void)
226 {
227     static const char *msgs[] =
228     {
229         "You are now in the screen-editor, which allows you to make some",
230         "lines on the screen, as well as save copies of the screen to a",
231         "temporary file",
232         "",
233         "Keys:",
234         "   q           quit",
235         "   n           run the screen-loader to show the saved screens",
236         "   <space>     dump a screen",
237         "",
238         "   a           toggle between '#' and graphic symbol for drawing",
239         "   c           change color drawn by line to next in palette",
240         "   h,j,k,l or arrows to move around the screen, drawing",
241         0
242     };
243     popup_msg(stdscr, msgs);
244 }
245
246 static void
247 replay_help(void)
248 {
249     static const char *msgs[] =
250     {
251         "You are now in the screen-loader, which allows you to view",
252         "the dumped/restored screens.",
253         "",
254         "Keys:",
255         "   q           quit",
256         "   <space>     load the next screen",
257         "   <backspace> load the previous screen",
258         0
259     };
260     popup_msg(stdscr, msgs);
261 }
262
263 static void
264 usage(void)
265 {
266     static const char *msg[] =
267     {
268         "Usage: savescreen [-r] files",
269         "",
270         "Options:",
271         " -f file  fill/initialize screen using text from this file",
272         " -i       use scr_init/scr_restore rather than scr_set",
273         " -k       keep the restored dump-files rather than removing them",
274         " -r       replay the screen-dump files"
275     };
276     unsigned n;
277     for (n = 0; n < SIZEOF(msg); ++n) {
278         fprintf(stderr, "%s\n", msg[n]);
279     }
280     ExitProgram(EXIT_FAILURE);
281 }
282
283 int
284 main(int argc, char *argv[])
285 {
286     int ch;
287     int which = 0;
288     int last;
289     bool use_colors = FALSE;
290     bool replaying = FALSE;
291     bool done = FALSE;
292     char **files;
293     char *fill_by = 0;
294 #if USE_WIDEC_SUPPORT
295     int r, g, b;
296     int cube = 0;
297     int cube0 = 16;
298     int cube1;
299     cchar_t mycc;
300     static const wchar_t mywc[2] =
301     {L'#', 0};
302     bool using_rgb = FALSE;
303 #endif
304
305     setlocale(LC_ALL, "");
306
307     while ((ch = getopt(argc, argv, "f:ikr")) != -1) {
308         switch (ch) {
309         case 'f':
310             fill_by = optarg;
311             break;
312         case 'i':
313             use_init = TRUE;
314             break;
315         case 'k':
316             keep_dumps = TRUE;
317             break;
318         case 'r':
319             replaying = TRUE;
320             break;
321         default:
322             usage();
323             break;
324         }
325     }
326
327     files = argv + optind;
328     last = argc - optind - 1;
329
330     if (replaying) {
331         while (last >= 0 && !fexists(files[last]))
332             --last;
333     }
334
335     initscr();
336     cbreak();
337     noecho();
338     keypad(stdscr, TRUE);
339     curs_set(0);
340
341     if (has_colors() && (start_color() == OK) && COLORS >= MAX_ANSI) {
342         static const struct {
343             int fg, bg;
344         } table[MAX_ANSI] = {
345 #define DATA(fg,bg) { COLOR_##fg, COLOR_##bg }
346             DATA(RED, WHITE),
347                 DATA(GREEN, WHITE),
348                 DATA(YELLOW, BLACK),
349                 DATA(BLUE, WHITE),
350                 DATA(MAGENTA, WHITE),
351                 DATA(MAGENTA, BLACK),
352                 DATA(CYAN, WHITE),
353                 DATA(CYAN, BLACK),
354 #undef DATA
355         };
356         int n;
357         int pair = 1;
358
359         use_colors = TRUE;
360         /*
361          * Discounting color-pair 0 (no color), make the next 8 color pairs
362          * useful for leaving a visually distinct trail of characters on the
363          * screen.
364          */
365         for (n = 0; n < MAX_ANSI; ++n) {
366             init_pair((short) pair++, (short) table[n].fg, (short) table[n].bg);
367         }
368         /*
369          * After that, use color pairs for constructing a test-pattern, e.g.,
370          * imitating xterm's scripts.
371          */
372         if (fill_by == 0) {
373             if (COLORS <= 256) {
374                 for (n = 0; n < COLORS; ++n)
375                     init_pair((short) (n + MAX_ANSI), (short) n, (short) n);
376             }
377 #if HAVE_TIGETSTR && USE_WIDEC_SUPPORT
378             else {
379                 int r_max, g_max, b_max;
380
381                 if (parse_rgb(&r_max, &g_max, &b_max) > 0) {
382                     int rows = LINES - 1;
383                     int cols = COLS - 1;
384                     int b_delta = (b_max / rows);
385                     int r_delta = (r_max / cols);
386                     int g_delta = (g_max / cols);
387                     int row = 0;
388
389                     b = 0;
390                     using_rgb = TRUE;
391                     while (row++ < rows) {
392                         int col = 0;
393                         r = 0;
394                         g = g_max;
395                         while (col++ < cols) {
396                             int color = (((r * (g_max + 1)) + g) * (b_max + 1)
397                                          + b + MAX_ANSI);
398 #if HAVE_INIT_EXTENDED_COLOR
399                             init_extended_pair(pair, color, color);
400 #else
401                             init_pair(pair, color, color);
402 #endif
403                             pair++;
404                             r += r_delta;
405                             g -= g_delta;
406                         }
407                         b += b_delta;
408                     }
409                 }
410             }
411 #endif
412         }
413         if ((fill_by == 0) && !replaying) {
414             /*
415              * Originally (before wide-characters) ncurses supported 16 colors.
416              */
417             if (COLORS >= 16 && COLORS <= 256) {
418                 mvprintw(2, 0, "System colors:\n");
419                 for (n = 0; n < 16; ++n) {
420                     pair = n + MAX_ANSI;
421                     addch((chtype) (' ' | COLOR_PAIR(pair)));
422                     addch((chtype) (' ' | COLOR_PAIR(pair)));
423                     if (((n + 1) % 8) == 0)
424                         addch('\n');
425                 }
426             }
427             /*
428              * Even with ncurses, you need wide-character support to have more
429              * than 16 colors.
430              */
431 #if USE_WIDEC_SUPPORT
432             if (COLORS == 88) {
433                 cube = 4;
434             } else if (COLORS == 256) {
435                 cube = 6;
436             }
437             if (cube != 0) {
438                 cube0 = 16;
439                 cube1 = cube0 + (cube * cube * cube);
440
441                 addch('\n');
442                 printw("Color cube, %dx%dx%d:\n", cube, cube, cube);
443                 for (g = 0; g < cube; g++) {
444                     for (r = 0; r < cube; r++) {
445                         for (b = 0; b < cube; b++) {
446                             pair = MAX_ANSI
447                                 + 16
448                                 + (r * cube * cube) + (g * cube) + b;
449                             setcchar(&mycc, mywc, 0, (short) pair, NULL);
450                             add_wch(&mycc);
451                             add_wch(&mycc);
452                         }
453                         addch(' ');
454                     }
455                     addch('\n');
456                 }
457                 addch('\n');
458                 printw("Grayscale ramp:\n");
459                 for (n = cube1; n < COLORS; ++n) {
460                     pair = n + MAX_ANSI;
461                     setcchar(&mycc, mywc, 0, (short) pair, NULL);
462                     add_wch(&mycc);
463                     add_wch(&mycc);
464                 }
465             } else if ((COLORS > 256) && using_rgb) {
466                 int rows = LINES - 1;
467                 int cols = COLS - 1;
468                 int row = 0;
469
470                 b = 0;
471                 pair = MAX_ANSI;
472                 while (row++ < rows) {
473                     int col = 0;
474                     while (col++ < cols) {
475                         setcchar(&mycc, mywc, 0, (short) pair, &pair);
476                         add_wch(&mycc);
477                         ++pair;
478                     }
479                     addch('\n');
480                 }
481                 addch('\n');
482             }
483 #endif
484         }
485     }
486
487     if (fill_by != 0) {
488         FILE *fp = fopen(fill_by, "r");
489         if (fp != 0) {
490             bool filled = FALSE;
491             move(1, 0);
492             while ((ch = fgetc(fp)) != EOF) {
493                 if (addch(UChar(ch)) == ERR) {
494                     filled = TRUE;
495                     break;
496                 }
497             }
498             fclose(fp);
499             if (!filled) {
500                 while (addch(' ') != ERR) {
501                     ;
502                 }
503             }
504             move(0, 0);
505         } else {
506             exit_curses();
507             fprintf(stderr, "Cannot open \"%s\"\n", fill_by);
508             ExitProgram(EXIT_FAILURE);
509         }
510     }
511
512     if (replaying) {
513
514         /*
515          * Use the last file as the initial/current screen.
516          */
517         if (last < 0) {
518             exit_curses();
519             printf("No screen-dumps given\n");
520             ExitProgram(EXIT_FAILURE);
521         }
522
523         which = last;
524         if (load_screen(files[which]) == ERR) {
525             exit_curses();
526             printf("Cannot load screen-dump %s\n", files[which]);
527             ExitProgram(EXIT_FAILURE);
528         }
529         after_load();
530
531         while (!done && (ch = getch()) != ERR) {
532             switch (ch) {
533             case 'n':
534                 /*
535                  * If we got a "next" here, skip to the final screen before
536                  * moving to the next process.
537                  */
538                 setup_next();
539                 which = last;
540                 done = TRUE;
541                 break;
542             case 'q':
543                 cleanup(files);
544                 done = TRUE;
545                 break;
546             case KEY_BACKSPACE:
547             case '\b':
548                 if (--which < 0)
549                     which = last;
550                 break;
551             case ' ':
552                 if (++which > last)
553                     which = 0;
554                 break;
555             case HELP_KEY_1:
556                 replay_help();
557                 break;
558             default:
559                 beep();
560                 continue;
561             }
562
563             if (ch == 'q') {
564                 ;
565             } else if (scr_restore(files[which]) == ERR) {
566                 endwin();
567                 printf("Cannot load screen-dump %s\n", files[which]);
568                 cleanup(files);
569                 ExitProgram(EXIT_FAILURE);
570             } else {
571                 wrefresh(curscr);
572             }
573         }
574         endwin();
575     } else {
576         int y = 0;
577         int x = 0;
578         int color = 0;
579         int altchars = 0;
580         bool dirty = use_colors || (fill_by != 0);
581
582         while (!done) {
583             switch (get_command(color, which, last)) {
584             case 'n':
585                 if (dirty && files[which]) {
586                     dump_screen(files, color, which, last, use_colors);
587                 }
588                 setup_next();
589                 done = TRUE;
590                 break;
591             case 'q':
592                 cleanup(files);
593                 done = TRUE;
594                 break;
595             case ' ':
596                 if (dump_screen(files, color, which, last, use_colors)) {
597                     which = (which + 1) % MAX_ANSI;
598                     dirty = FALSE;
599                 } else {
600                     setup_next();
601                     done = TRUE;
602                 }
603                 break;
604             case KEY_LEFT:
605             case 'h':
606                 if (--x < 0)
607                     x = COLS - 1;
608                 break;
609             case KEY_DOWN:
610             case 'j':
611                 if (++y >= LINES)
612                     y = 1;
613                 break;
614             case KEY_UP:
615             case 'k':
616                 if (--y < 1)
617                     y = LINES - 1;
618                 break;
619             case KEY_RIGHT:
620             case 'l':
621                 if (++x >= COLS)
622                     x = 0;
623                 break;
624             case 'a':
625                 altchars = !altchars;
626                 break;
627             case 'c':
628                 if (use_colors) {
629                     color = (color + 1) % MAX_ANSI;
630                 }
631                 break;
632             case HELP_KEY_1:
633                 editor_help();
634                 break;
635             default:
636                 beep();
637                 continue;
638             }
639             if (!done) {
640                 chtype attr = A_REVERSE;
641                 chtype ch2 = (altchars ? MyMarker : '#');
642                 if (use_colors) {
643                     attr |= (chtype) COLOR_PAIR(color);
644                 }
645                 move(y, x);
646                 AddCh(ch2 | attr);
647                 move(y, x);
648                 dirty = TRUE;
649             }
650         }
651         endwin();
652     }
653     ExitProgram(EXIT_SUCCESS);
654 }
655
656 #else
657 int
658 main(int argc GCC_UNUSED, char *argv[]GCC_UNUSED)
659 {
660     printf("This program requires the screen-dump functions\n");
661     ExitProgram(EXIT_FAILURE);
662 }
663 #endif