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