]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/ditto.c
ncurses 6.0 - patch 20171230
[ncurses.git] / test / ditto.c
1 /****************************************************************************
2  * Copyright (c) 1998-2016,2017 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 /*
30  * Author: Thomas E. Dickey (1998-on)
31  *
32  * $Id: ditto.c,v 1.47 2017/10/18 23:04:42 tom Exp $
33  *
34  * The program illustrates how to set up multiple screens from a single
35  * program.
36  *
37  * If openpty() is supported, the command line parameters are titles for
38  * the windows showing each screen's data.
39  *
40  * If openpty() is not supported, you must invoke the program by specifying
41  * another terminal on the same machine by specifying its device, e.g.,
42  *      ditto /dev/ttyp1
43  */
44 #include <test.priv.h>
45 #include <sys/stat.h>
46
47 #if HAVE_DELSCREEN
48
49 #ifdef USE_PTHREADS
50 #include <pthread.h>
51 #endif
52
53 #ifdef USE_XTERM_PTY
54 #include USE_OPENPTY_HEADER
55 #endif
56
57 #define MAX_FIFO 256
58
59 #define THIS_FIFO(n) ((n) % MAX_FIFO)
60 #define NEXT_FIFO(n) THIS_FIFO((n) + 1)
61
62 typedef struct {
63     unsigned long sequence;
64     int head;
65     int tail;
66     int data[MAX_FIFO];
67 } FIFO;
68
69 typedef struct {
70     unsigned long sequence;
71 } PEEK;
72
73 /*
74  * Data "owned" for a single screen.  Each screen is divided into windows that
75  * show the text read from each terminal.  Input from a given screen will also
76  * be read into one window per screen.
77  */
78 typedef struct {
79     FILE *input;
80     FILE *output;
81     SCREEN *screen;             /* this screen - curses internal data */
82     int which1;                 /* this screen's index in DITTO[] array */
83     int length;                 /* length of windows[] and peeks[] */
84     char **titles;              /* per-window titles */
85     WINDOW **parents;           /* display boxes around each screen's data */
86     WINDOW **windows;           /* display data from each screen */
87     PEEK *peeks;                /* indices for each screen's fifo */
88     FIFO fifo;                  /* fifo for this screen */
89 #ifdef USE_PTHREADS
90     pthread_t thread;
91 #endif
92 } DITTO;
93
94 /*
95  * Structure used to pass multiple parameters via the use_screen()
96  * single-parameter interface.
97  */
98 typedef struct {
99     int source;                 /* which screen did character come from */
100     int target;                 /* which screen is character going to */
101     DITTO *ditto;               /* data for all screens */
102 } DDATA;
103
104 static void failed(const char *) GCC_NORETURN;
105 static void usage(void) GCC_NORETURN;
106
107 static void
108 failed(const char *s)
109 {
110     perror(s);
111     ExitProgram(EXIT_FAILURE);
112 }
113
114 static void
115 usage(void)
116 {
117     fprintf(stderr, "Usage: ditto [terminal1 ...]\n");
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) < 0)
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 void
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 }
240
241 static void
242 open_screen(DITTO * target, char **source, int length, int which1)
243 {
244     if (which1 != 0) {
245         target->input =
246             target->output = open_tty(source[which1]);
247     } else {
248         target->input = stdin;
249         target->output = stdout;
250     }
251
252     target->which1 = which1;
253     target->titles = source;
254     target->length = length;
255     target->fifo.head = -1;
256     target->screen = newterm((char *) 0,        /* assume $TERM is the same */
257                              target->output,
258                              target->input);
259
260     if (target->screen == 0)
261         failed("newterm");
262
263     (void) USING_SCREEN(target->screen, init_screen, target);
264 }
265
266 static int
267 close_screen(
268 #if HAVE_USE_WINDOW
269                 SCREEN *sp GCC_UNUSED,
270 #endif
271                 void *arg GCC_UNUSED)
272 {
273 #if HAVE_USE_WINDOW
274     (void) sp;
275 #endif
276     (void) arg;
277     return endwin();
278 }
279
280 /*
281  * Read data from the 'source' screen.
282  */
283 static int
284 read_screen(
285 #if HAVE_USE_WINDOW
286                SCREEN *sp GCC_UNUSED,
287 #endif
288                void *arg)
289 {
290     DDATA *data = (DDATA *) arg;
291     DITTO *ditto = &(data->ditto[data->source]);
292     WINDOW *win = ditto->windows[data->source];
293     int ch = wgetch(win);
294
295     if (ch > 0 && ch < 256)
296         put_fifo(&(ditto->fifo), ch);
297     else
298         ch = ERR;
299
300     return ch;
301 }
302
303 /*
304  * Write all of the data that's in fifos for the 'target' screen.
305  */
306 static int
307 write_screen(
308 #if HAVE_USE_WINDOW
309                 SCREEN *sp GCC_UNUSED,
310 #endif
311                 void *arg GCC_UNUSED)
312 {
313     DDATA *data = (DDATA *) arg;
314     DITTO *ditto = &(data->ditto[data->target]);
315     bool changed = FALSE;
316     int which;
317
318     for (which = 0; which < ditto->length; ++which) {
319         WINDOW *win = ditto->windows[which];
320         FIFO *fifo = &(data->ditto[which].fifo);
321         PEEK *peek = &(ditto->peeks[which]);
322         int ch;
323
324         while ((ch = peek_fifo(fifo, peek)) > 0) {
325             changed = TRUE;
326
327             waddch(win, (chtype) ch);
328             wnoutrefresh(win);
329         }
330     }
331
332     if (changed)
333         doupdate();
334     return OK;
335 }
336
337 static void
338 show_ditto(DITTO * data, int count, DDATA * ddata)
339 {
340     int n;
341
342     (void) data;
343     for (n = 0; n < count; n++) {
344         ddata->target = n;
345         USING_SCREEN(data[n].screen, write_screen, (void *) ddata);
346     }
347 }
348
349 #ifdef USE_PTHREADS
350 static void *
351 handle_screen(void *arg)
352 {
353     DDATA ddata;
354     int ch;
355
356     memset(&ddata, 0, sizeof(ddata));
357     ddata.ditto = (DITTO *) arg;
358     ddata.source = ddata.ditto->which1;
359     ddata.ditto -= ddata.source;        /* -> base of array */
360
361     for (;;) {
362         ch = read_screen(ddata.ditto->screen, &ddata);
363         if (ch == CTRL('D')) {
364             int later = (ddata.source ? ddata.source : -1);
365             int j;
366
367             for (j = ddata.ditto->length - 1; j > 0; --j) {
368                 if (j != later) {
369                     pthread_cancel(ddata.ditto[j].thread);
370                 }
371             }
372             if (later > 0) {
373                 pthread_cancel(ddata.ditto[later].thread);
374             }
375             break;
376         }
377         show_ditto(ddata.ditto, ddata.ditto->length, &ddata);
378     }
379     return NULL;
380 }
381 #endif
382
383 int
384 main(int argc, char *argv[])
385 {
386     int j;
387     DITTO *data;
388 #ifndef USE_PTHREADS
389     int count;
390 #endif
391
392     if (argc <= 1)
393         usage();
394
395     if ((data = typeCalloc(DITTO, (size_t) argc)) == 0)
396         failed("calloc data");
397
398     assert(data != 0);
399
400     for (j = 0; j < argc; j++) {
401         open_screen(&data[j], argv, argc, j);
402     }
403
404 #ifdef USE_PTHREADS
405     /*
406      * For multi-threaded operation, set up a reader for each of the screens.
407      * That uses blocking I/O rather than polling for input, so no calls to
408      * napms() are needed.
409      */
410     for (j = 0; j < argc; j++) {
411         (void) pthread_create(&(data[j].thread), NULL, handle_screen, &data[j]);
412     }
413     pthread_join(data[1].thread, NULL);
414 #else
415     /*
416      * Loop, reading characters from any of the inputs and writing to all
417      * of the screens.
418      */
419     for (count = 0;; ++count) {
420         DDATA ddata;
421         int ch;
422         int which = (count % argc);
423
424         napms(20);
425
426         ddata.source = which;
427         ddata.ditto = data;
428
429         ch = USING_SCREEN(data[which].screen, read_screen, &ddata);
430         if (ch == CTRL('D')) {
431             break;
432         } else if (ch != ERR) {
433             show_ditto(data, argc, &ddata);
434         }
435     }
436 #endif
437
438     /*
439      * Cleanup and exit
440      */
441     for (j = argc - 1; j >= 0; j--) {
442         USING_SCREEN(data[j].screen, close_screen, 0);
443         fprintf(data[j].output, "**Closed\r\n");
444
445         /*
446          * Closing before a delscreen() helps ncurses determine that there
447          * is no valid output buffer, and can remove the setbuf() data.
448          */
449         fflush(data[j].output);
450         fclose(data[j].output);
451         delscreen(data[j].screen);
452     }
453     ExitProgram(EXIT_SUCCESS);
454 }
455 #else
456 int
457 main(void)
458 {
459     printf("This program requires the curses delscreen function\n");
460     ExitProgram(EXIT_FAILURE);
461 }
462 #endif