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