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