]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/ditto.c
ncurses 5.7 - patch 20110115
[ncurses.git] / test / ditto.c
1 /****************************************************************************
2  * Copyright (c) 1998-2009,2010 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.40 2010/11/14 01:06:47 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
155     if (openpty(&amaster, &aslave, slave_name, 0, 0) != 0
156         || strlen(slave_name) > sizeof(slave_name) - 1)
157         failed("openpty");
158     if (strrchr(slave_name, '/') == 0) {
159         errno = EISDIR;
160         failed(slave_name);
161     }
162     sprintf(s_option, "-S%s/%d", slave_name, aslave);
163     if (fork()) {
164         execlp("xterm", "xterm", s_option, "-title", path, (char *) 0);
165         _exit(0);
166     }
167     fp = fdopen(amaster, "r+");
168     if (fp == 0)
169         failed(path);
170 #else
171     struct stat sb;
172
173     if (stat(path, &sb) < 0)
174         failed(path);
175     if ((sb.st_mode & S_IFMT) != S_IFCHR) {
176         errno = ENOTTY;
177         failed(path);
178     }
179     fp = fopen(path, "r+");
180     if (fp == 0)
181         failed(path);
182     printf("opened %s\n", path);
183 #endif
184     assert(fp != 0);
185     return fp;
186 }
187
188 static void
189 init_screen(
190 #if HAVE_USE_WINDOW
191                SCREEN *sp GCC_UNUSED,
192 #endif
193                void *arg)
194 {
195     DITTO *target = (DITTO *) arg;
196     int high, wide;
197     int k;
198
199     cbreak();
200     noecho();
201     scrollok(stdscr, TRUE);
202     box(stdscr, 0, 0);
203
204     target->windows = typeCalloc(WINDOW *, (size_t) target->length);
205     target->peeks = typeCalloc(PEEK, (size_t) target->length);
206
207     high = (LINES - 2) / target->length;
208     wide = (COLS - 2);
209     for (k = 0; k < target->length; ++k) {
210         WINDOW *outer = newwin(high, wide, 1 + (high * k), 1);
211         WINDOW *inner = derwin(outer, high - 2, wide - 2, 1, 1);
212
213         box(outer, 0, 0);
214         MvWAddStr(outer, 0, 2, target->titles[k]);
215         wnoutrefresh(outer);
216
217         scrollok(inner, TRUE);
218         keypad(inner, TRUE);
219 #ifndef USE_PTHREADS
220         nodelay(inner, TRUE);
221 #endif
222
223         target->windows[k] = inner;
224     }
225     doupdate();
226 }
227
228 static void
229 open_screen(DITTO * target, char **source, int length, int which1)
230 {
231     if (which1 != 0) {
232         target->input =
233             target->output = open_tty(source[which1]);
234     } else {
235         target->input = stdin;
236         target->output = stdout;
237     }
238
239     target->which1 = which1;
240     target->titles = source;
241     target->length = length;
242     target->fifo.head = -1;
243     target->screen = newterm((char *) 0,        /* assume $TERM is the same */
244                              target->output,
245                              target->input);
246
247     if (target->screen == 0)
248         failed("newterm");
249
250     (void) USING_SCREEN(target->screen, init_screen, target);
251 }
252
253 static int
254 close_screen(
255 #if HAVE_USE_WINDOW
256                 SCREEN *sp GCC_UNUSED,
257 #endif
258                 void *arg GCC_UNUSED)
259 {
260 #if HAVE_USE_WINDOW
261     (void) sp;
262 #endif
263     (void) arg;
264     return endwin();
265 }
266
267 /*
268  * Read data from the 'source' screen.
269  */
270 static int
271 read_screen(
272 #if HAVE_USE_WINDOW
273                SCREEN *sp GCC_UNUSED,
274 #endif
275                void *arg)
276 {
277     DDATA *data = (DDATA *) arg;
278     DITTO *ditto = &(data->ditto[data->source]);
279     WINDOW *win = ditto->windows[data->source];
280     int ch = wgetch(win);
281
282     if (ch > 0 && ch < 256)
283         put_fifo(&(ditto->fifo), ch);
284     else
285         ch = ERR;
286
287     return ch;
288 }
289
290 /*
291  * Write all of the data that's in fifos for the 'target' screen.
292  */
293 static int
294 write_screen(
295 #if HAVE_USE_WINDOW
296                 SCREEN *sp GCC_UNUSED,
297 #endif
298                 void *arg GCC_UNUSED)
299 {
300     DDATA *data = (DDATA *) arg;
301     DITTO *ditto = &(data->ditto[data->target]);
302     bool changed = FALSE;
303     int which;
304
305     for (which = 0; which < ditto->length; ++which) {
306         WINDOW *win = ditto->windows[which];
307         FIFO *fifo = &(data->ditto[which].fifo);
308         PEEK *peek = &(ditto->peeks[which]);
309         int ch;
310
311         while ((ch = peek_fifo(fifo, peek)) > 0) {
312             changed = TRUE;
313
314             waddch(win, (chtype) ch);
315             wnoutrefresh(win);
316         }
317     }
318
319     if (changed)
320         doupdate();
321     return OK;
322 }
323
324 static void
325 show_ditto(DITTO * data, int count, DDATA * ddata)
326 {
327     int n;
328
329     (void) data;
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     assert(data != 0);
386
387     for (j = 0; j < argc; j++) {
388         open_screen(&data[j], argv, argc, j);
389     }
390
391 #ifdef USE_PTHREADS
392     /*
393      * For multi-threaded operation, set up a reader for each of the screens.
394      * That uses blocking I/O rather than polling for input, so no calls to
395      * napms() are needed.
396      */
397     for (j = 0; j < argc; j++) {
398         (void) pthread_create(&(data[j].thread), NULL, handle_screen, &data[j]);
399     }
400     pthread_join(data[1].thread, NULL);
401 #else
402     /*
403      * Loop, reading characters from any of the inputs and writing to all
404      * of the screens.
405      */
406     for (count = 0;; ++count) {
407         DDATA ddata;
408         int ch;
409         int which = (count % argc);
410
411         napms(20);
412
413         ddata.source = which;
414         ddata.ditto = data;
415
416         ch = USING_SCREEN(data[which].screen, read_screen, &ddata);
417         if (ch == CTRL('D')) {
418             break;
419         } else if (ch != ERR) {
420             show_ditto(data, argc, &ddata);
421         }
422     }
423 #endif
424
425     /*
426      * Cleanup and exit
427      */
428     for (j = argc - 1; j >= 0; j--) {
429         USING_SCREEN(data[j].screen, close_screen, 0);
430         fprintf(data[j].output, "**Closed\r\n");
431
432         /*
433          * Closing before a delscreen() helps ncurses determine that there
434          * is no valid output buffer, and can remove the setbuf() data.
435          */
436         fflush(data[j].output);
437         fclose(data[j].output);
438         delscreen(data[j].screen);
439     }
440     ExitProgram(EXIT_SUCCESS);
441 }