]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/ditto.c
06b635536dfefecd40a5811b6d35ca5702cc0632
[ncurses.git] / test / ditto.c
1 /****************************************************************************
2  * Copyright 2018-2021,2022 Thomas E. Dickey                                *
3  * Copyright 1998-2016,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 /*
31  * Author: Thomas E. Dickey (1998-on)
32  *
33  * $Id: ditto.c,v 1.55 2022/12/04 00:40:55 tom Exp $
34  *
35  * The program illustrates how to set up multiple screens from a single
36  * program.
37  *
38  * If openpty() is supported, the command line parameters are titles for
39  * the windows showing each screen's data.
40  *
41  * If openpty() is not supported, you must invoke the program by specifying
42  * another terminal on the same machine by specifying its device, e.g.,
43  *      ditto /dev/ttyp1
44  */
45 #include <test.priv.h>
46 #include <sys/stat.h>
47
48 #if HAVE_DELSCREEN
49
50 #ifdef USE_PTHREADS
51 #include <pthread.h>
52 #endif
53
54 #ifdef USE_XTERM_PTY
55 #include USE_OPENPTY_HEADER
56 #endif
57
58 #define MAX_FIFO 256
59
60 #define THIS_FIFO(n) ((n) % MAX_FIFO)
61 #define NEXT_FIFO(n) THIS_FIFO((n) + 1)
62
63 typedef struct {
64     unsigned long sequence;
65     int head;
66     int tail;
67     int data[MAX_FIFO];
68 } FIFO;
69
70 typedef struct {
71     unsigned long sequence;
72 } PEEK;
73
74 /*
75  * Data "owned" for a single screen.  Each screen is divided into windows that
76  * show the text read from each terminal.  Input from a given screen will also
77  * be read into one window per screen.
78  */
79 typedef struct {
80     FILE *input;
81     FILE *output;
82     SCREEN *screen;             /* this screen - curses internal data */
83     int which1;                 /* this screen's index in DITTO[] array */
84     int length;                 /* length of windows[] and peeks[] */
85     char **titles;              /* per-window titles */
86     WINDOW **parents;           /* display boxes around each screen's data */
87     WINDOW **windows;           /* display data from each screen */
88     PEEK *peeks;                /* indices for each screen's fifo */
89     FIFO fifo;                  /* fifo for this screen */
90 #ifdef USE_PTHREADS
91     pthread_t thread;
92 #endif
93 } DITTO;
94
95 /*
96  * Structure used to pass multiple parameters via the use_screen()
97  * single-parameter interface.
98  */
99 typedef struct {
100     int source;                 /* which screen did character come from */
101     int target;                 /* which screen is character going to */
102     DITTO *ditto;               /* data for all screens */
103 } DDATA;
104
105 static void
106 failed(const char *s)
107 {
108     perror(s);
109     ExitProgram(EXIT_FAILURE);
110 }
111
112 /* Add to the head of the fifo, checking for overflow. */
113 static void
114 put_fifo(FIFO * fifo, int value)
115 {
116     int next = NEXT_FIFO(fifo->head);
117     if (next == fifo->tail)
118         fifo->tail = NEXT_FIFO(fifo->tail);
119     fifo->data[next] = value;
120     fifo->head = next;
121     fifo->sequence += 1;
122 }
123
124 /* Get data from the tail (oldest part) of the fifo, returning -1 if no data.
125  * Since each screen can peek into the fifo, we do not update the tail index,
126  * but modify the peek-index.
127  *
128  * FIXME - test/workaround for case where fifo gets more than a buffer
129  * ahead of peek.
130  */
131 static int
132 peek_fifo(FIFO * fifo, PEEK * peek)
133 {
134     int result = -1;
135     if (peek->sequence < fifo->sequence) {
136         result = fifo->data[THIS_FIFO(peek->sequence)];
137         peek->sequence += 1;
138     }
139     return result;
140 }
141
142 static FILE *
143 open_tty(char *path)
144 {
145     FILE *fp;
146 #ifdef USE_XTERM_PTY
147     int amaster;
148     int aslave;
149     char slave_name[1024];
150     char s_option[sizeof(slave_name) + 80];
151     const char *xterm_prog = 0;
152
153     if ((xterm_prog = getenv("XTERM_PROG")) == 0)
154         xterm_prog = "xterm";
155
156     if (openpty(&amaster, &aslave, slave_name, 0, 0) != 0
157         || strlen(slave_name) > sizeof(slave_name) - 1)
158         failed("openpty");
159     if (strrchr(slave_name, '/') == 0) {
160         errno = EISDIR;
161         failed(slave_name);
162     }
163     _nc_SPRINTF(s_option, _nc_SLIMIT(sizeof(s_option))
164                 "-S%s/%d", slave_name, aslave);
165     if (fork()) {
166         execlp(xterm_prog, xterm_prog, s_option, "-title", path, (char *) 0);
167         _exit(0);
168     }
169     fp = fdopen(amaster, "r+");
170     if (fp == 0)
171         failed(path);
172 #else
173     struct stat sb;
174
175     if (stat(path, &sb) == -1)
176         failed(path);
177     if ((sb.st_mode & S_IFMT) != S_IFCHR) {
178         errno = ENOTTY;
179         failed(path);
180     }
181     fp = fopen(path, "r+");
182     if (fp == 0)
183         failed(path);
184     printf("opened %s\n", path);
185 #endif
186     assert(fp != 0);
187     return fp;
188 }
189
190 static int
191 init_screen(
192 #if HAVE_USE_WINDOW
193                SCREEN *sp GCC_UNUSED,
194 #endif
195                void *arg)
196 {
197     DITTO *target = (DITTO *) arg;
198     int high, wide;
199     int k;
200
201     cbreak();
202     noecho();
203     scrollok(stdscr, TRUE);
204     box(stdscr, 0, 0);
205
206     target->parents = typeCalloc(WINDOW *, (size_t) target->length);
207     target->windows = typeCalloc(WINDOW *, (size_t) target->length);
208     target->peeks = typeCalloc(PEEK, (size_t) target->length);
209
210     high = (LINES - 2) / target->length;
211     wide = (COLS - 2);
212     for (k = 0; k < target->length; ++k) {
213         WINDOW *outer = newwin(high, wide, 1 + (high * k), 1);
214         WINDOW *inner = derwin(outer, high - 2, wide - 2, 1, 1);
215
216         box(outer, 0, 0);
217         MvWAddStr(outer, 0, 2, target->titles[k]);
218         wnoutrefresh(outer);
219
220         scrollok(inner, TRUE);
221         keypad(inner, TRUE);
222 #ifndef USE_PTHREADS
223         nodelay(inner, TRUE);
224 #endif
225
226         target->parents[k] = outer;
227         target->windows[k] = inner;
228     }
229     doupdate();
230     return TRUE;
231 }
232
233 static void
234 open_screen(DITTO * target, char **source, int length, int which1)
235 {
236     if (which1 != 0) {
237         target->input =
238             target->output = open_tty(source[which1]);
239     } else {
240         target->input = stdin;
241         target->output = stdout;
242     }
243
244     target->which1 = which1;
245     target->titles = source;
246     target->length = length;
247     target->fifo.head = -1;
248     target->screen = newterm((char *) 0,        /* assume $TERM is the same */
249                              target->output,
250                              target->input);
251
252     if (target->screen == 0)
253         failed("newterm");
254
255     (void) USING_SCREEN(target->screen, init_screen, target);
256 }
257
258 static int
259 close_screen(
260 #if HAVE_USE_WINDOW
261                 SCREEN *sp GCC_UNUSED,
262 #endif
263                 void *arg GCC_UNUSED)
264 {
265 #if HAVE_USE_WINDOW
266     (void) sp;
267 #endif
268     (void) arg;
269     return endwin();
270 }
271
272 /*
273  * Read data from the 'source' screen.
274  */
275 static int
276 read_screen(
277 #if HAVE_USE_WINDOW
278                SCREEN *sp GCC_UNUSED,
279 #endif
280                void *arg)
281 {
282     DDATA *data = (DDATA *) arg;
283     DITTO *ditto = &(data->ditto[data->source]);
284     WINDOW *win = ditto->windows[data->source];
285     int ch = wgetch(win);
286
287     if (ch > 0 && ch < 256)
288         put_fifo(&(ditto->fifo), ch);
289     else
290         ch = ERR;
291
292     return ch;
293 }
294
295 /*
296  * Write all of the data that's in fifos for the 'target' screen.
297  */
298 static int
299 write_screen(
300 #if HAVE_USE_WINDOW
301                 SCREEN *sp GCC_UNUSED,
302 #endif
303                 void *arg GCC_UNUSED)
304 {
305     DDATA *data = (DDATA *) arg;
306     DITTO *ditto = &(data->ditto[data->target]);
307     bool changed = FALSE;
308     int which;
309
310     for (which = 0; which < ditto->length; ++which) {
311         WINDOW *win = ditto->windows[which];
312         FIFO *fifo = &(data->ditto[which].fifo);
313         PEEK *peek = &(ditto->peeks[which]);
314         int ch;
315
316         while ((ch = peek_fifo(fifo, peek)) > 0) {
317             changed = TRUE;
318
319             waddch(win, (chtype) ch);
320             wnoutrefresh(win);
321         }
322     }
323
324     if (changed)
325         doupdate();
326     return OK;
327 }
328
329 static void
330 show_ditto(DITTO * data, int count, DDATA * ddata)
331 {
332     int n;
333
334     (void) data;
335     for (n = 0; n < count; n++) {
336         ddata->target = n;
337         USING_SCREEN(data[n].screen, write_screen, (void *) ddata);
338     }
339 }
340
341 #ifdef USE_PTHREADS
342 static void *
343 handle_screen(void *arg)
344 {
345     DDATA ddata;
346
347     memset(&ddata, 0, sizeof(ddata));
348     ddata.ditto = (DITTO *) arg;
349     ddata.source = ddata.ditto->which1;
350     ddata.ditto -= ddata.source;        /* -> base of array */
351
352     for (;;) {
353         int ch = read_screen(ddata.ditto->screen, &ddata);
354         if (ch == CTRL('D')) {
355             int later = (ddata.source ? ddata.source : -1);
356             int j;
357
358             for (j = ddata.ditto->length - 1; j > 0; --j) {
359                 if (j != later) {
360                     pthread_cancel(ddata.ditto[j].thread);
361                 }
362             }
363             if (later > 0) {
364                 pthread_cancel(ddata.ditto[later].thread);
365             }
366             break;
367         }
368         show_ditto(ddata.ditto, ddata.ditto->length, &ddata);
369     }
370     return NULL;
371 }
372 #endif
373
374 static void
375 usage(int ok)
376 {
377     static const char *msg[] =
378     {
379         "Usage: ditto [terminal [terminal2 ...]]"
380         ,""
381         ,USAGE_COMMON
382     };
383     size_t n;
384
385     for (n = 0; n < SIZEOF(msg); n++)
386         fprintf(stderr, "%s\n", msg[n]);
387
388     ExitProgram(ok ? EXIT_SUCCESS : EXIT_FAILURE);
389 /* *INDENT-OFF* */}
390 VERSION_COMMON()
391 /* *INDENT-ON* */
392
393     int
394       main(int argc, char *argv[]) {
395         int j;
396         int ch;
397         DITTO *data;
398 #ifndef USE_PTHREADS
399         int count;
400 #endif
401
402         while ((ch = getopt(argc, argv, OPTS_COMMON)) != -1) {
403             switch (ch) {
404             case OPTS_VERSION:
405                 show_version(argv);
406                 ExitProgram(EXIT_SUCCESS);
407                 default:
408                 usage(ch == OPTS_USAGE);
409                 /* NOTREACHED */
410             }
411         } if (optind < argc)
412               usage(FALSE);
413
414         if ((data = typeCalloc(DITTO, (size_t) argc)) == 0)
415             failed("calloc data");
416
417         assert(data != 0);
418
419         for (j = 0; j < argc; j++) {
420             open_screen(&data[j], argv, argc, j);
421         }
422
423 #ifdef USE_PTHREADS
424         /*
425          * For multi-threaded operation, set up a reader for each of the screens.
426          * That uses blocking I/O rather than polling for input, so no calls to
427          * napms() are needed.
428          */
429         for (j = 0; j < argc; j++) {
430             (void) pthread_create(&(data[j].thread), NULL, handle_screen,
431                                   &data[j]);
432         }
433         pthread_join(data[1].thread, NULL);
434 #else
435         /*
436          * Loop, reading characters from any of the inputs and writing to all
437          * of the screens.
438          */
439         for (count = 0;; ++count) {
440             DDATA ddata;
441             int which = (count % argc);
442
443             napms(20);
444
445             ddata.source = which;
446             ddata.ditto = data;
447
448             ch = USING_SCREEN(data[which].screen, read_screen, &ddata);
449             if (ch == CTRL('D')) {
450                 break;
451             } else if (ch != ERR) {
452                 show_ditto(data, argc, &ddata);
453             }
454         }
455 #endif
456
457         /*
458          * Cleanup and exit
459          */
460         for (j = argc - 1; j >= 0; j--) {
461             USING_SCREEN(data[j].screen, close_screen, 0);
462             fprintf(data[j].output, "**Closed\r\n");
463
464             /*
465              * Closing before a delscreen() helps ncurses determine that there
466              * is no valid output buffer, and can remove the setbuf() data.
467              */
468             fflush(data[j].output);
469             fclose(data[j].output);
470             delscreen(data[j].screen);
471         }
472         ExitProgram(EXIT_SUCCESS);
473     }
474 #else
475 int
476 main(void)
477 {
478     printf("This program requires the curses delscreen function\n");
479     ExitProgram(EXIT_FAILURE);
480 }
481 #endif