]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/tinfo_driver.c
ncurses 5.7 - patch 20100306
[ncurses.git] / ncurses / tinfo / tinfo_driver.c
1 /****************************************************************************
2  * Copyright (c) 2008-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: Juergen Pfeifer                                                 *
31  *                                                                          *
32  ****************************************************************************/
33
34 #include <curses.priv.h>
35 #define CUR ((TERMINAL*)TCB)->type.
36 #include <tic.h>
37
38 #if HAVE_NANOSLEEP
39 #include <time.h>
40 #if HAVE_SYS_TIME_H
41 #include <sys/time.h>           /* needed for MacOS X DP3 */
42 #endif
43 #endif
44
45 #if HAVE_SIZECHANGE
46 # if !defined(sun) || !TERMIOS
47 #  if HAVE_SYS_IOCTL_H
48 #   include <sys/ioctl.h>
49 #  endif
50 # endif
51 #endif
52
53 MODULE_ID("$Id: tinfo_driver.c,v 1.7 2010/01/16 16:56:16 tom Exp $")
54
55 /*
56  * SCO defines TIOCGSIZE and the corresponding struct.  Other systems (SunOS,
57  * Solaris, IRIX) define TIOCGWINSZ and struct winsize.
58  */
59 #ifdef TIOCGSIZE
60 # define IOCTL_WINSIZE TIOCGSIZE
61 # define STRUCT_WINSIZE struct ttysize
62 # define WINSIZE_ROWS(n) (int)n.ts_lines
63 # define WINSIZE_COLS(n) (int)n.ts_cols
64 #else
65 # ifdef TIOCGWINSZ
66 #  define IOCTL_WINSIZE TIOCGWINSZ
67 #  define STRUCT_WINSIZE struct winsize
68 #  define WINSIZE_ROWS(n) (int)n.ws_row
69 #  define WINSIZE_COLS(n) (int)n.ws_col
70 # endif
71 #endif
72
73 /*
74  * These should be screen structure members.  They need to be globals for
75  * historical reasons.  So we assign them in start_color() and also in
76  * set_term()'s screen-switching logic.
77  */
78 #if USE_REENTRANT
79 NCURSES_EXPORT(int)
80 NCURSES_PUBLIC_VAR(COLOR_PAIRS) (void)
81 {
82     return CURRENT_SCREEN ? CURRENT_SCREEN->_pair_count : -1;
83 }
84 NCURSES_EXPORT(int)
85 NCURSES_PUBLIC_VAR(COLORS) (void)
86 {
87     return CURRENT_SCREEN ? CURRENT_SCREEN->_color_count : -1;
88 }
89 #else
90 NCURSES_EXPORT_VAR(int) COLOR_PAIRS = 0;
91 NCURSES_EXPORT_VAR(int) COLORS = 0;
92 #endif
93
94 #define TCBMAGIC NCDRV_MAGIC(NCDRV_TINFO)
95 #define AssertTCB() assert(TCB!=0 && TCB->magic==TCBMAGIC)
96 #define SetSP() assert(TCB->csp!=0); sp = TCB->csp
97
98 /*
99  * This routine needs to do all the work to make curscr look
100  * like newscr.
101  */
102 static int
103 drv_doupdate(TERMINAL_CONTROL_BLOCK * TCB)
104 {
105     AssertTCB();
106     return TINFO_DOUPDATE(TCB->csp);
107 }
108
109 #define ret_error(code, fmt, arg)       if (errret) {\
110                                             *errret = code;\
111                                             return(FALSE); \
112                                         } else {\
113                                             fprintf(stderr, fmt, arg);\
114                                             exit(EXIT_FAILURE);\
115                                         }
116
117 #define ret_error0(code, msg)           if (errret) {\
118                                             *errret = code;\
119                                             return(FALSE);\
120                                         } else {\
121                                             fprintf(stderr, msg);\
122                                             exit(EXIT_FAILURE);\
123                                         }
124
125 #if USE_DATABASE || USE_TERMCAP
126 /*
127  * Return 1 if entry found, 0 if not found, -1 if database not accessible,
128  * just like tgetent().
129  */
130 static int
131 grab_entry(const char *const tn, TERMTYPE *const tp)
132 {
133     char filename[PATH_MAX];
134     int status = _nc_read_entry(tn, filename, tp);
135
136     /*
137      * If we have an entry, force all of the cancelled strings to null
138      * pointers so we don't have to test them in the rest of the library.
139      * (The terminfo compiler bypasses this logic, since it must know if
140      * a string is cancelled, for merging entries).
141      */
142     if (status == TGETENT_YES) {
143         unsigned n;
144         for_each_boolean(n, tp) {
145             if (!VALID_BOOLEAN(tp->Booleans[n]))
146                 tp->Booleans[n] = FALSE;
147         }
148         for_each_string(n, tp) {
149             if (tp->Strings[n] == CANCELLED_STRING)
150                 tp->Strings[n] = ABSENT_STRING;
151         }
152     }
153     return (status);
154 }
155 #endif
156
157 static bool
158 drv_CanHandle(TERMINAL_CONTROL_BLOCK * TCB, const char *tname, int *errret)
159 {
160     bool result = FALSE;
161     int status;
162     TERMINAL *termp;
163     SCREEN *sp;
164
165     assert(TCB != 0 && tname != 0);
166     termp = (TERMINAL *) TCB;
167     sp = TCB->csp;
168     TCB->magic = TCBMAGIC;
169
170 #if (USE_DATABASE || USE_TERMCAP)
171     status = grab_entry(tname, &termp->type);
172 #else
173     status = TGETENT_NO;
174 #endif
175
176     /* try fallback list if entry on disk */
177     if (status != TGETENT_YES) {
178         const TERMTYPE *fallback = _nc_fallback(tname);
179
180         if (fallback) {
181             termp->type = *fallback;
182             status = TGETENT_YES;
183         }
184     }
185
186     if (status != TGETENT_YES) {
187         NCURSES_SP_NAME(del_curterm) (NCURSES_SP_ARGx termp);
188         if (status == TGETENT_ERR) {
189             ret_error0(status, "terminals database is inaccessible\n");
190         } else if (status == TGETENT_NO) {
191             ret_error(status, "'%s': unknown terminal type.\n", tname);
192         }
193     }
194     result = TRUE;
195 #if !USE_REENTRANT
196     strncpy(ttytype, termp->type.term_names, NAMESIZE - 1);
197     ttytype[NAMESIZE - 1] = '\0';
198 #endif
199
200     if (command_character)
201         _nc_tinfo_cmdch(termp, *command_character);
202
203     if (generic_type) {
204         ret_error(TGETENT_NO, "'%s': I need something more specific.\n", tname);
205     }
206     if (hard_copy) {
207         ret_error(TGETENT_YES, "'%s': I can't handle hardcopy terminals.\n", tname);
208     }
209
210     return result;
211 }
212
213 static int
214 drv_dobeepflash(TERMINAL_CONTROL_BLOCK * TCB, bool beepFlag)
215 {
216     SCREEN *sp;
217     int res = ERR;
218
219     AssertTCB();
220     SetSP();
221
222     /* FIXME: should make sure that we are not in altchar mode */
223     if (beepFlag) {
224         if (bell) {
225             res = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "bell", bell);
226             NCURSES_SP_NAME(_nc_flush) (sp);
227         } else if (flash_screen) {
228             res = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
229                                              "flash_screen",
230                                              flash_screen);
231             NCURSES_SP_NAME(_nc_flush) (sp);
232         }
233     } else {
234         if (flash_screen) {
235             res = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
236                                              "flash_screen",
237                                              flash_screen);
238             NCURSES_SP_NAME(_nc_flush) (sp);
239         } else if (bell) {
240             res = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "bell", bell);
241             NCURSES_SP_NAME(_nc_flush) (sp);
242         }
243     }
244     return res;
245 }
246
247 /*
248  * SVr4 curses is known to interchange color codes (1,4) and (3,6), possibly
249  * to maintain compatibility with a pre-ANSI scheme.  The same scheme is
250  * also used in the FreeBSD syscons.
251  */
252 static int
253 toggled_colors(int c)
254 {
255     if (c < 16) {
256         static const int table[] =
257         {0, 4, 2, 6, 1, 5, 3, 7,
258          8, 12, 10, 14, 9, 13, 11, 15};
259         c = table[c];
260     }
261     return c;
262 }
263
264 static int
265 drv_print(TERMINAL_CONTROL_BLOCK * TCB, char *data, int len)
266 {
267     SCREEN *sp;
268
269     AssertTCB();
270     SetSP();
271 #if NCURSES_EXT_FUNCS
272     return NCURSES_SP_NAME(mcprint) (TCB->csp, data, len);
273 #else
274     return ERR;
275 #endif
276 }
277
278 static int
279 drv_defaultcolors(TERMINAL_CONTROL_BLOCK * TCB, int fg, int bg)
280 {
281     SCREEN *sp;
282     int code = ERR;
283
284     AssertTCB();
285     SetSP();
286
287     if (sp != 0 && orig_pair && orig_colors && (initialize_pair != 0)) {
288 #if NCURSES_EXT_FUNCS
289         sp->_default_color = isDefaultColor(fg) || isDefaultColor(bg);
290         sp->_has_sgr_39_49 = (NCURSES_SP_NAME(tigetflag) (NCURSES_SP_ARGx
291                                                           "AX")
292                               == TRUE);
293         sp->_default_fg = isDefaultColor(fg) ? COLOR_DEFAULT : (fg & C_MASK);
294         sp->_default_bg = isDefaultColor(bg) ? COLOR_DEFAULT : (bg & C_MASK);
295         if (sp->_color_pairs != 0) {
296             bool save = sp->_default_color;
297             sp->_default_color = TRUE;
298             NCURSES_SP_NAME(init_pair) (NCURSES_SP_ARGx
299                                         0,
300                                         (short)fg,
301                                         (short)bg);
302             sp->_default_color = save;
303         }
304 #endif
305         code = OK;
306     }
307     return (code);
308 }
309
310 static void
311 drv_setcolor(TERMINAL_CONTROL_BLOCK * TCB,
312              bool fore,
313              int color,
314              NCURSES_SP_OUTC outc)
315 {
316     SCREEN *sp;
317
318     AssertTCB();
319     SetSP();
320
321     if (fore) {
322         if (set_a_foreground) {
323             TPUTS_TRACE("set_a_foreground");
324             NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
325                                     TPARM_1(set_a_foreground, color), 1, outc);
326         } else {
327             TPUTS_TRACE("set_foreground");
328             NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
329                                     TPARM_1(set_foreground,
330                                             toggled_colors(color)), 1, outc);
331         }
332     } else {
333         if (set_a_background) {
334             TPUTS_TRACE("set_a_background");
335             NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
336                                     TPARM_1(set_a_background, color), 1, outc);
337         } else {
338             TPUTS_TRACE("set_background");
339             NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
340                                     TPARM_1(set_background,
341                                             toggled_colors(color)), 1, outc);
342         }
343     }
344 }
345
346 static bool
347 drv_rescol(TERMINAL_CONTROL_BLOCK * TCB)
348 {
349     bool result = FALSE;
350     SCREEN *sp;
351
352     AssertTCB();
353     SetSP();
354
355     if (orig_pair != 0) {
356         NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "orig_pair", orig_pair);
357         result = TRUE;
358     }
359     return result;
360 }
361
362 static bool
363 drv_rescolors(TERMINAL_CONTROL_BLOCK * TCB)
364 {
365     int result = FALSE;
366     SCREEN *sp;
367
368     AssertTCB();
369     SetSP();
370
371     if (orig_colors != 0) {
372         NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "orig_colors", orig_colors);
373         result = TRUE;
374     }
375     return result;
376 }
377
378 static int
379 drv_size(TERMINAL_CONTROL_BLOCK * TCB, int *linep, int *colp)
380 {
381     SCREEN *sp;
382     bool useEnv = TRUE;
383
384     AssertTCB();
385     sp = TCB->csp;              /* can be null here */
386
387     if (sp) {
388         useEnv = sp->_use_env;
389     } else
390         useEnv = _nc_prescreen.use_env;
391
392     /* figure out the size of the screen */
393     T(("screen size: terminfo lines = %d columns = %d", lines, columns));
394
395     if (!useEnv) {
396         *linep = (int) lines;
397         *colp = (int) columns;
398     } else {                    /* usually want to query LINES and COLUMNS from environment */
399         int value;
400
401         *linep = *colp = 0;
402
403         /* first, look for environment variables */
404         if ((value = _nc_getenv_num("LINES")) > 0) {
405             *linep = value;
406         }
407         if ((value = _nc_getenv_num("COLUMNS")) > 0) {
408             *colp = value;
409         }
410         T(("screen size: environment LINES = %d COLUMNS = %d", *linep, *colp));
411
412 #ifdef __EMX__
413         if (*linep <= 0 || *colp <= 0) {
414             int screendata[2];
415             _scrsize(screendata);
416             *colp = screendata[0];
417             *linep = screendata[1];
418             T(("EMX screen size: environment LINES = %d COLUMNS = %d",
419                *linep, *colp));
420         }
421 #endif
422 #if HAVE_SIZECHANGE
423         /* if that didn't work, maybe we can try asking the OS */
424         if (*linep <= 0 || *colp <= 0) {
425             TERMINAL *termp = (TERMINAL *) TCB;
426             if (isatty(termp->Filedes)) {
427                 STRUCT_WINSIZE size;
428
429                 errno = 0;
430                 do {
431                     if (ioctl(termp->Filedes, IOCTL_WINSIZE, &size) < 0
432                         && errno != EINTR)
433                         goto failure;
434                 } while
435                     (errno == EINTR);
436
437                 /*
438                  * Solaris lets users override either dimension with an
439                  * environment variable.
440                  */
441                 if (*linep <= 0)
442                     *linep = (sp != 0 && sp->_filtered) ? 1 : WINSIZE_ROWS(size);
443                 if (*colp <= 0)
444                     *colp = WINSIZE_COLS(size);
445             }
446             /* FALLTHRU */
447           failure:;
448         }
449 #endif /* HAVE_SIZECHANGE */
450
451         /* if we can't get dynamic info about the size, use static */
452         if (*linep <= 0) {
453             *linep = (int) lines;
454         }
455         if (*colp <= 0) {
456             *colp = (int) columns;
457         }
458
459         /* the ultimate fallback, assume fixed 24x80 size */
460         if (*linep <= 0) {
461             *linep = 24;
462         }
463         if (*colp <= 0) {
464             *colp = 80;
465         }
466
467         /*
468          * Put the derived values back in the screen-size caps, so
469          * tigetnum() and tgetnum() will do the right thing.
470          */
471         lines = (short) (*linep);
472         columns = (short) (*colp);
473     }
474
475     T(("screen size is %dx%d", *linep, *colp));
476     return OK;
477 }
478
479 static int
480 drv_getsize(TERMINAL_CONTROL_BLOCK * TCB, int *l, int *c)
481 {
482     AssertTCB();
483     assert(l != 0 && c != 0);
484     *l = lines;
485     *c = columns;
486     return OK;
487 }
488
489 static int
490 drv_setsize(TERMINAL_CONTROL_BLOCK * TCB, int l, int c)
491 {
492     AssertTCB();
493     lines = (short) l;
494     columns = (short) c;
495     return OK;
496 }
497
498 static int
499 drv_sgmode(TERMINAL_CONTROL_BLOCK * TCB, bool setFlag, TTY * buf)
500 {
501     SCREEN *sp = TCB->csp;
502     TERMINAL *_term = (TERMINAL *) TCB;
503     int result = OK;
504
505     AssertTCB();
506     if (setFlag) {
507         for (;;) {
508             if (SET_TTY(_term->Filedes, buf) != 0) {
509                 if (errno == EINTR)
510                     continue;
511                 if (errno == ENOTTY) {
512                     if (sp)
513                         sp->_notty = TRUE;
514                 }
515                 result = ERR;
516             }
517             break;
518         }
519     } else {
520         for (;;) {
521             if (GET_TTY(_term->Filedes, buf) != 0) {
522                 if (errno == EINTR)
523                     continue;
524                 result = ERR;
525             }
526             break;
527         }
528     }
529     return result;
530 }
531
532 static int
533 drv_mode(TERMINAL_CONTROL_BLOCK * TCB, bool progFlag, bool defFlag)
534 {
535     SCREEN *sp;
536     TERMINAL *_term = (TERMINAL *) TCB;
537     int code = ERR;
538
539     AssertTCB();
540     sp = TCB->csp;
541
542     if (progFlag)               /* prog mode */
543     {
544         if (defFlag) {
545             /* def_prog_mode */
546             /*
547              * Turn off the XTABS bit in the tty structure if it was on.
548              */
549             if ((drv_sgmode(TCB, FALSE, &(_term->Nttyb)) == OK)) {
550 #ifdef TERMIOS
551                 _term->Nttyb.c_oflag &= ~OFLAGS_TABS;
552 #else
553                 _term->Nttyb.sg_flags &= ~XTABS;
554 #endif
555                 code = OK;
556             }
557         } else {
558             /* reset_prog_mode */
559             if (drv_sgmode(TCB, TRUE, &(_term->Nttyb)) == OK) {
560                 if (sp) {
561                     if (sp->_keypad_on)
562                         _nc_keypad(sp, TRUE);
563                     NC_BUFFERED(sp, TRUE);
564                 }
565                 code = OK;
566             }
567         }
568     } else {                    /* shell mode */
569         if (defFlag) {
570             /* def_shell_mode */
571             /*
572              * If XTABS was on, remove the tab and backtab capabilities.
573              */
574             if (drv_sgmode(TCB, FALSE, &(_term->Ottyb)) == OK) {
575 #ifdef TERMIOS
576                 if (_term->Ottyb.c_oflag & OFLAGS_TABS)
577                     tab = back_tab = NULL;
578 #else
579                 if (_term->Ottyb.sg_flags & XTABS)
580                     tab = back_tab = NULL;
581 #endif
582                 code = OK;
583             }
584         } else {
585             /* reset_shell_mode */
586             if (sp) {
587                 _nc_keypad(sp, FALSE);
588                 NCURSES_SP_NAME(_nc_flush) (sp);
589                 NC_BUFFERED(sp, FALSE);
590             }
591             code = drv_sgmode(TCB, TRUE, &(_term->Ottyb));
592         }
593     }
594     return (code);
595 }
596
597 static void
598 drv_wrap(SCREEN *sp)
599 {
600     if (sp) {
601         sp->_mouse_wrap(sp);
602         NCURSES_SP_NAME(_nc_screen_wrap) (sp);
603         NCURSES_SP_NAME(_nc_mvcur_wrap) (sp);   /* wrap up cursor addressing */
604     }
605 }
606
607 static void
608 drv_release(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED)
609 {
610 }
611
612 #  define SGR0_TEST(mode) (mode != 0) && (exit_attribute_mode == 0 || strcmp(mode, exit_attribute_mode))
613
614 static void
615 drv_screen_init(SCREEN *sp)
616 {
617     TERMINAL_CONTROL_BLOCK *TCB = TCBOf(sp);
618
619     AssertTCB();
620
621     /*
622      * Check for mismatched graphic-rendition capabilities.  Most SVr4
623      * terminfo trees contain entries that have rmul or rmso equated to
624      * sgr0 (Solaris curses copes with those entries).  We do this only
625      * for curses, since many termcap applications assume that
626      * smso/rmso and smul/rmul are paired, and will not function
627      * properly if we remove rmso or rmul.  Curses applications
628      * shouldn't be looking at this detail.
629      */
630     sp->_use_rmso = SGR0_TEST(exit_standout_mode);
631     sp->_use_rmul = SGR0_TEST(exit_underline_mode);
632
633     /*
634      * Check whether we can optimize scrolling under dumb terminals in
635      * case we do not have any of these capabilities, scrolling
636      * optimization will be useless.
637      */
638     sp->_scrolling = ((scroll_forward && scroll_reverse) ||
639                       ((parm_rindex ||
640                         parm_insert_line ||
641                         insert_line) &&
642                        (parm_index ||
643                         parm_delete_line ||
644                         delete_line)));
645
646     NCURSES_SP_NAME(baudrate) (sp);
647
648     NCURSES_SP_NAME(_nc_mvcur_init) (sp);
649     /* initialize terminal to a sane state */
650     NCURSES_SP_NAME(_nc_screen_init) (sp);
651 }
652
653 static void
654 drv_init(TERMINAL_CONTROL_BLOCK * TCB)
655 {
656     SCREEN *sp;
657     TERMINAL *trm;
658
659     AssertTCB();
660
661     trm = (TERMINAL *) TCB;
662     sp = TCB->csp;
663
664     TCB->info.initcolor = initialize_color;
665     TCB->info.canchange = can_change;
666     TCB->info.hascolor = ((VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
667                            && (((set_foreground != NULL)
668                                 && (set_background != NULL))
669                                || ((set_a_foreground != NULL)
670                                    && (set_a_background != NULL))
671                                || set_color_pair)) ? TRUE : FALSE);
672
673     TCB->info.caninit = !(exit_ca_mode && non_rev_rmcup);
674
675     TCB->info.maxpairs = VALID_NUMERIC(max_pairs) ? max_pairs : 0;
676     TCB->info.maxcolors = VALID_NUMERIC(max_colors) ? max_colors : 0;
677     TCB->info.numlabels = VALID_NUMERIC(num_labels) ? num_labels : 0;
678     TCB->info.labelwidth = VALID_NUMERIC(label_width) ? label_width : 0;
679     TCB->info.labelheight = VALID_NUMERIC(label_height) ? label_height : 0;
680     TCB->info.nocolorvideo = VALID_NUMERIC(no_color_video) ? no_color_video
681         : 0;
682     TCB->info.tabsize = VALID_NUMERIC(init_tabs) ? (int) init_tabs : 8;
683
684     TCB->info.defaultPalette = hue_lightness_saturation ? _nc_hls_palette : _nc_cga_palette;
685
686     /*
687      * If an application calls setupterm() rather than initscr() or
688      * newterm(), we will not have the def_prog_mode() call in
689      * _nc_setupscreen().  Do it now anyway, so we can initialize the
690      * baudrate.
691      */
692     if (isatty(trm->Filedes)) {
693         TCB->drv->mode(TCB, TRUE, TRUE);
694     }
695 }
696
697 #define MAX_PALETTE     8
698 #define InPalette(n)    ((n) >= 0 && (n) < MAX_PALETTE)
699
700 static void
701 drv_initpair(TERMINAL_CONTROL_BLOCK * TCB, short pair, short f, short b)
702 {
703     SCREEN *sp;
704
705     AssertTCB();
706     SetSP();
707
708     if ((initialize_pair != NULL) && InPalette(f) && InPalette(b)) {
709         const color_t *tp = InfoOf(sp).defaultPalette;
710
711         TR(TRACE_ATTRS,
712            ("initializing pair: pair = %d, fg=(%d,%d,%d), bg=(%d,%d,%d)",
713             pair,
714             tp[f].red, tp[f].green, tp[f].blue,
715             tp[b].red, tp[b].green, tp[b].blue));
716
717         NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
718                                    "initialize_pair",
719                                    TPARM_7(initialize_pair,
720                                            pair,
721                                            tp[f].red, tp[f].green, tp[f].blue,
722                                            tp[b].red, tp[b].green, tp[b].blue));
723     }
724 }
725
726 static int
727 default_fg(SCREEN *sp)
728 {
729 #if NCURSES_EXT_FUNCS
730     return (sp != 0) ? sp->_default_fg : COLOR_WHITE;
731 #else
732     return COLOR_WHITE;
733 #endif
734 }
735
736 static int
737 default_bg(SCREEN *sp)
738 {
739 #if NCURSES_EXT_FUNCS
740     return sp != 0 ? sp->_default_bg : COLOR_BLACK;
741 #else
742     return COLOR_BLACK;
743 #endif
744 }
745
746 static void
747 drv_initcolor(TERMINAL_CONTROL_BLOCK * TCB,
748               short color, short r, short g, short b)
749 {
750     SCREEN *sp = TCB->csp;
751
752     AssertTCB();
753     if (initialize_color != NULL) {
754         NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
755                                    "initialize_color",
756                                    TPARM_4(initialize_color, color, r, g, b));
757     }
758 }
759
760 static void
761 drv_do_color(TERMINAL_CONTROL_BLOCK * TCB,
762              short old_pair,
763              short pair,
764              bool reverse,
765              NCURSES_SP_OUTC outc)
766 {
767     SCREEN *sp = TCB->csp;
768     NCURSES_COLOR_T fg = COLOR_DEFAULT;
769     NCURSES_COLOR_T bg = COLOR_DEFAULT;
770     NCURSES_COLOR_T old_fg, old_bg;
771
772     AssertTCB();
773     if (sp == 0)
774         return;
775
776     if (pair < 0 || pair >= COLOR_PAIRS) {
777         return;
778     } else if (pair != 0) {
779         if (set_color_pair) {
780             TPUTS_TRACE("set_color_pair");
781             NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
782                                     TPARM_1(set_color_pair, pair), 1, outc);
783             return;
784         } else if (sp != 0) {
785             NCURSES_SP_NAME(pair_content) (NCURSES_SP_ARGx
786                                            (short) pair,
787                                            &fg,
788                                            &bg);
789         }
790     }
791
792     if (old_pair >= 0
793         && sp != 0
794         && NCURSES_SP_NAME(pair_content) (NCURSES_SP_ARGx
795                                           old_pair,
796                                           &old_fg,
797                                           &old_bg) !=ERR) {
798         if ((isDefaultColor(fg) && !isDefaultColor(old_fg))
799             || (isDefaultColor(bg) && !isDefaultColor(old_bg))) {
800 #if NCURSES_EXT_FUNCS
801             /*
802              * A minor optimization - but extension.  If "AX" is specified in
803              * the terminal description, treat it as screen's indicator of ECMA
804              * SGR 39 and SGR 49, and assume the two sequences are independent.
805              */
806             if (sp->_has_sgr_39_49
807                 && isDefaultColor(old_bg)
808                 && !isDefaultColor(old_fg)) {
809                 NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx "\033[39m", 1, outc);
810             } else if (sp->_has_sgr_39_49
811                        && isDefaultColor(old_fg)
812                        && !isDefaultColor(old_bg)) {
813                 NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx "\033[49m", 1, outc);
814             } else
815 #endif
816                 drv_rescol(TCB);
817         }
818     } else {
819         drv_rescol(TCB);
820         if (old_pair < 0)
821             return;
822     }
823
824 #if NCURSES_EXT_FUNCS
825     if (isDefaultColor(fg))
826         fg = (NCURSES_COLOR_T) default_fg(sp);
827     if (isDefaultColor(bg))
828         bg = (NCURSES_COLOR_T) default_bg(sp);
829 #endif
830
831     if (reverse) {
832         NCURSES_COLOR_T xx = fg;
833         fg = bg;
834         bg = xx;
835     }
836
837     TR(TRACE_ATTRS, ("setting colors: pair = %d, fg = %d, bg = %d", pair,
838                      fg, bg));
839
840     if (!isDefaultColor(fg)) {
841         drv_setcolor(TCB, TRUE, fg, outc);
842     }
843     if (!isDefaultColor(bg)) {
844         drv_setcolor(TCB, FALSE, bg, outc);
845     }
846 }
847
848 #define xterm_kmous "\033[M"
849 static void
850 init_xterm_mouse(SCREEN *sp)
851 {
852     sp->_mouse_type = M_XTERM;
853     sp->_mouse_xtermcap = NCURSES_SP_NAME(tigetstr) (NCURSES_SP_ARGx "XM");
854     if (!VALID_STRING(sp->_mouse_xtermcap))
855         sp->_mouse_xtermcap = "\033[?1000%?%p1%{1}%=%th%el%;";
856 }
857
858 static void
859 drv_initmouse(TERMINAL_CONTROL_BLOCK * TCB)
860 {
861     SCREEN *sp;
862
863     AssertTCB();
864     SetSP();
865
866     /* we know how to recognize mouse events under "xterm" */
867     if (sp != 0) {
868         if (key_mouse != 0) {
869             if (!strcmp(key_mouse, xterm_kmous)
870                 || strstr(TerminalOf(sp)->type.term_names, "xterm") != 0) {
871                 init_xterm_mouse(sp);
872             }
873         } else if (strstr(TerminalOf(sp)->type.term_names, "xterm") != 0) {
874             if (_nc_add_to_try(&(sp->_keytry), xterm_kmous, KEY_MOUSE) == OK)
875                 init_xterm_mouse(sp);
876         }
877     }
878 }
879
880 static int
881 drv_mvcur(TERMINAL_CONTROL_BLOCK * TCB, int yold, int xold, int ynew, int xnew)
882 {
883     SCREEN *sp = TCB->csp;
884     AssertTCB();
885     return TINFO_MVCUR(sp, yold, xold, ynew, xnew);
886 }
887
888 static void
889 drv_hwlabel(TERMINAL_CONTROL_BLOCK * TCB, int labnum, char *text)
890 {
891     SCREEN *sp = TCB->csp;
892
893     AssertTCB();
894     if (labnum > 0 && labnum <= num_labels) {
895         NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
896                                    "plab_norm",
897                                    TPARM_2(plab_norm, labnum, text));
898     }
899 }
900
901 static void
902 drv_hwlabelOnOff(TERMINAL_CONTROL_BLOCK * TCB, bool OnFlag)
903 {
904     SCREEN *sp = TCB->csp;
905
906     AssertTCB();
907     if (OnFlag) {
908         NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "label_on", label_on);
909     } else {
910         NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "label_off", label_off);
911     }
912 }
913
914 static chtype
915 drv_conattr(TERMINAL_CONTROL_BLOCK * TCB)
916 {
917     SCREEN *sp = TCB->csp;
918     chtype attrs = A_NORMAL;
919
920     AssertTCB();
921     if (enter_alt_charset_mode)
922         attrs |= A_ALTCHARSET;
923
924     if (enter_blink_mode)
925         attrs |= A_BLINK;
926
927     if (enter_bold_mode)
928         attrs |= A_BOLD;
929
930     if (enter_dim_mode)
931         attrs |= A_DIM;
932
933     if (enter_reverse_mode)
934         attrs |= A_REVERSE;
935
936     if (enter_standout_mode)
937         attrs |= A_STANDOUT;
938
939     if (enter_protected_mode)
940         attrs |= A_PROTECT;
941
942     if (enter_secure_mode)
943         attrs |= A_INVIS;
944
945     if (enter_underline_mode)
946         attrs |= A_UNDERLINE;
947
948     if (sp && sp->_coloron)
949         attrs |= A_COLOR;
950
951     return (attrs);
952 }
953
954 static void
955 drv_setfilter(TERMINAL_CONTROL_BLOCK * TCB)
956 {
957     AssertTCB();
958
959     clear_screen = 0;
960     cursor_down = parm_down_cursor = 0;
961     cursor_address = 0;
962     cursor_up = parm_up_cursor = 0;
963     row_address = 0;
964     cursor_home = carriage_return;
965 }
966
967 static void
968 drv_initacs(TERMINAL_CONTROL_BLOCK * TCB, chtype *real_map, chtype *fake_map)
969 {
970     SCREEN *sp = TCB->csp;
971
972     AssertTCB();
973     assert(sp != 0);
974     if (ena_acs != NULL) {
975         NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "ena_acs", ena_acs);
976     }
977 #if NCURSES_EXT_FUNCS
978     /*
979      * Linux console "supports" the "PC ROM" character set by the coincidence
980      * that smpch/rmpch and smacs/rmacs have the same values.  ncurses has
981      * no codepage support (see SCO Merge for an example).  Outside of the
982      * values defined in acsc, there are no definitions for the "PC ROM"
983      * character set (assumed by some applications to be codepage 437), but we
984      * allow those applications to use those codepoints.
985      *
986      * test/blue.c uses this feature.
987      */
988 #define PCH_KLUDGE(a,b) (a != 0 && b != 0 && !strcmp(a,b))
989     if (PCH_KLUDGE(enter_pc_charset_mode, enter_alt_charset_mode) &&
990         PCH_KLUDGE(exit_pc_charset_mode, exit_alt_charset_mode)) {
991         size_t i;
992         for (i = 1; i < ACS_LEN; ++i) {
993             if (real_map[i] == 0) {
994                 real_map[i] = i;
995                 if (real_map != fake_map) {
996                     if (sp != 0)
997                         sp->_screen_acs_map[i] = TRUE;
998                 }
999             }
1000         }
1001     }
1002 #endif
1003
1004     if (acs_chars != NULL) {
1005         size_t i = 0;
1006         size_t length = strlen(acs_chars);
1007
1008         while (i + 1 < length) {
1009             if (acs_chars[i] != 0 && UChar(acs_chars[i]) < ACS_LEN) {
1010                 real_map[UChar(acs_chars[i])] = UChar(acs_chars[i + 1]) | A_ALTCHARSET;
1011                 if (sp != 0)
1012                     sp->_screen_acs_map[UChar(acs_chars[i])] = TRUE;
1013             }
1014             i += 2;
1015         }
1016     }
1017 #ifdef TRACE
1018     /* Show the equivalent mapping, noting if it does not match the
1019      * given attribute, whether by re-ordering or duplication.
1020      */
1021     if (USE_TRACEF(TRACE_CALLS)) {
1022         size_t n, m;
1023         char show[ACS_LEN * 2 + 1];
1024         for (n = 1, m = 0; n < ACS_LEN; n++) {
1025             if (real_map[n] != 0) {
1026                 show[m++] = (char) n;
1027                 show[m++] = (char) ChCharOf(real_map[n]);
1028             }
1029         }
1030         show[m] = 0;
1031         if (acs_chars == NULL || strcmp(acs_chars, show))
1032             _tracef("%s acs_chars %s",
1033                     (acs_chars == NULL) ? "NULL" : "READ",
1034                     _nc_visbuf(acs_chars));
1035         _tracef("%s acs_chars %s",
1036                 (acs_chars == NULL)
1037                 ? "NULL"
1038                 : (strcmp(acs_chars, show)
1039                    ? "DIFF"
1040                    : "SAME"),
1041                 _nc_visbuf(show));
1042
1043         _nc_unlock_global(tracef);
1044     }
1045 #endif /* TRACE */
1046 }
1047
1048 #define ENSURE_TINFO(sp) (TCBOf(sp)->drv->isTerminfo)
1049
1050 NCURSES_EXPORT(void)
1051 _nc_cookie_init(SCREEN *sp)
1052 {
1053     bool support_cookies = USE_XMC_SUPPORT;
1054     TERMINAL_CONTROL_BLOCK *TCB = (TERMINAL_CONTROL_BLOCK *) (sp->_term);
1055
1056     if (sp == 0 || !ENSURE_TINFO(sp))
1057         return;
1058
1059 #if USE_XMC_SUPPORT
1060     /*
1061      * If we have no magic-cookie support compiled-in, or if it is suppressed
1062      * in the environment, reset the support-flag.
1063      */
1064     if (magic_cookie_glitch >= 0) {
1065         if (getenv("NCURSES_NO_MAGIC_COOKIE") != 0) {
1066             support_cookies = FALSE;
1067         }
1068     }
1069 #endif
1070
1071     if (!support_cookies && magic_cookie_glitch >= 0) {
1072         T(("will disable attributes to work w/o magic cookies"));
1073     }
1074
1075     if (magic_cookie_glitch > 0) {      /* tvi, wyse */
1076
1077         sp->_xmc_triggers = sp->_ok_attributes & (
1078                                                      A_STANDOUT |
1079                                                      A_UNDERLINE |
1080                                                      A_REVERSE |
1081                                                      A_BLINK |
1082                                                      A_DIM |
1083                                                      A_BOLD |
1084                                                      A_INVIS |
1085                                                      A_PROTECT
1086             );
1087 #if 0
1088         /*
1089          * We "should" treat colors as an attribute.  The wyse350 (and its
1090          * clones) appear to be the only ones that have both colors and magic
1091          * cookies.
1092          */
1093         if (has_colors()) {
1094             sp->_xmc_triggers |= A_COLOR;
1095         }
1096 #endif
1097         sp->_xmc_suppress = sp->_xmc_triggers & (chtype) ~(A_BOLD);
1098
1099         T(("magic cookie attributes %s", _traceattr(sp->_xmc_suppress)));
1100         /*
1101          * Supporting line-drawing may be possible.  But make the regular
1102          * video attributes work first.
1103          */
1104         acs_chars = ABSENT_STRING;
1105         ena_acs = ABSENT_STRING;
1106         enter_alt_charset_mode = ABSENT_STRING;
1107         exit_alt_charset_mode = ABSENT_STRING;
1108 #if USE_XMC_SUPPORT
1109         /*
1110          * To keep the cookie support simple, suppress all of the optimization
1111          * hooks except for clear_screen and the cursor addressing.
1112          */
1113         if (support_cookies) {
1114             clr_eol = ABSENT_STRING;
1115             clr_eos = ABSENT_STRING;
1116             set_attributes = ABSENT_STRING;
1117         }
1118 #endif
1119     } else if (magic_cookie_glitch == 0) {      /* hpterm */
1120     }
1121
1122     /*
1123      * If magic cookies are not supported, cancel the strings that set
1124      * video attributes.
1125      */
1126     if (!support_cookies && magic_cookie_glitch >= 0) {
1127         magic_cookie_glitch = ABSENT_NUMERIC;
1128         set_attributes = ABSENT_STRING;
1129         enter_blink_mode = ABSENT_STRING;
1130         enter_bold_mode = ABSENT_STRING;
1131         enter_dim_mode = ABSENT_STRING;
1132         enter_reverse_mode = ABSENT_STRING;
1133         enter_standout_mode = ABSENT_STRING;
1134         enter_underline_mode = ABSENT_STRING;
1135     }
1136
1137     /* initialize normal acs before wide, since we use mapping in the latter */
1138 #if !USE_WIDEC_SUPPORT
1139     if (_nc_unicode_locale() && _nc_locale_breaks_acs(sp->_term)) {
1140         acs_chars = NULL;
1141         ena_acs = NULL;
1142         enter_alt_charset_mode = NULL;
1143         exit_alt_charset_mode = NULL;
1144         set_attributes = NULL;
1145     }
1146 #endif
1147 }
1148
1149 static int
1150 drv_twait(TERMINAL_CONTROL_BLOCK * TCB,
1151           int mode,
1152           int milliseconds,
1153           int *timeleft
1154           EVENTLIST_2nd(_nc_eventlist * evl))
1155 {
1156     SCREEN *sp;
1157
1158     AssertTCB();
1159     SetSP();
1160
1161     return _nc_timed_wait(sp, mode, milliseconds, timeleft EVENTLIST_2nd(evl));
1162 }
1163
1164 static int
1165 drv_read(TERMINAL_CONTROL_BLOCK * TCB, int *buf)
1166 {
1167     SCREEN *sp;
1168     unsigned char c2 = 0;
1169     int n;
1170
1171     AssertTCB();
1172     assert(buf);
1173     SetSP();
1174
1175     n = read(sp->_ifd, &c2, 1);
1176     *buf = (int) c2;
1177     return n;
1178 }
1179
1180 static int
1181 drv_nap(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED, int ms)
1182 {
1183 #if HAVE_NANOSLEEP
1184     {
1185         struct timespec request, remaining;
1186         request.tv_sec = ms / 1000;
1187         request.tv_nsec = (ms % 1000) * 1000000;
1188         while (nanosleep(&request, &remaining) == -1
1189                && errno == EINTR) {
1190             request = remaining;
1191         }
1192     }
1193 #else
1194     _nc_timed_wait(0, 0, ms, (int *) 0 EVENTLIST_2nd(0));
1195 #endif
1196     return OK;
1197 }
1198
1199 static int
1200 __nc_putp(SCREEN *sp, const char *name GCC_UNUSED, const char *value)
1201 {
1202     int rc = ERR;
1203
1204     if (value) {
1205         rc = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx name, value);
1206     }
1207     return rc;
1208 }
1209
1210 static int
1211 __nc_putp_flush(SCREEN *sp, const char *name, const char *value)
1212 {
1213     int rc = __nc_putp(sp, name, value);
1214     if (rc != ERR) {
1215         NCURSES_SP_NAME(_nc_flush) (sp);
1216     }
1217     return rc;
1218 }
1219
1220 static int
1221 drv_kpad(TERMINAL_CONTROL_BLOCK * TCB, bool flag)
1222 {
1223     int ret = ERR;
1224     SCREEN *sp;
1225
1226     AssertTCB();
1227
1228     sp = TCB->csp;
1229
1230     if (sp) {
1231         if (flag) {
1232             (void) __nc_putp_flush(sp, "keypad_xmit", keypad_xmit);
1233         } else if (!flag && keypad_local) {
1234             (void) __nc_putp_flush(sp, "keypad_local", keypad_local);
1235         }
1236         if (flag && !sp->_tried) {
1237             _nc_init_keytry(sp);
1238             sp->_tried = TRUE;
1239         }
1240         ret = OK;
1241     }
1242
1243     return ret;
1244 }
1245
1246 static int
1247 drv_keyok(TERMINAL_CONTROL_BLOCK * TCB, int c, bool flag)
1248 {
1249     SCREEN *sp;
1250     int code = ERR;
1251     int count = 0;
1252     char *s;
1253
1254     AssertTCB();
1255     SetSP();
1256
1257     if (c >= 0) {
1258         unsigned ch = (unsigned) c;
1259         if (flag) {
1260             while ((s = _nc_expand_try(sp->_key_ok, ch, &count, 0)) != 0
1261                    && _nc_remove_key(&(sp->_key_ok), ch)) {
1262                 code = _nc_add_to_try(&(sp->_keytry), s, ch);
1263                 free(s);
1264                 count = 0;
1265                 if (code != OK)
1266                     break;
1267             }
1268         } else {
1269             while ((s = _nc_expand_try(sp->_keytry, ch, &count, 0)) != 0
1270                    && _nc_remove_key(&(sp->_keytry), ch)) {
1271                 code = _nc_add_to_try(&(sp->_key_ok), s, ch);
1272                 free(s);
1273                 count = 0;
1274                 if (code != OK)
1275                     break;
1276             }
1277         }
1278     }
1279     return (code);
1280 }
1281
1282 static bool
1283 drv_kyExist(TERMINAL_CONTROL_BLOCK * TCB, int key)
1284 {
1285     bool res = FALSE;
1286
1287     AssertTCB();
1288     if (TCB->csp)
1289         res = TINFO_HAS_KEY(TCB->csp, key) == 0 ? FALSE : TRUE;
1290
1291     return res;
1292 }
1293
1294 NCURSES_EXPORT_VAR (TERM_DRIVER) _nc_TINFO_DRIVER = {
1295     TRUE,
1296         drv_CanHandle,          /* CanHandle */
1297         drv_init,               /* init */
1298         drv_release,            /* release */
1299         drv_size,               /* size */
1300         drv_sgmode,             /* sgmode */
1301         drv_conattr,            /* conattr */
1302         drv_mvcur,              /* hwcur */
1303         drv_mode,               /* mode */
1304         drv_rescol,             /* rescol */
1305         drv_rescolors,          /* rescolors */
1306         drv_setcolor,           /* color */
1307         drv_dobeepflash,        /* doBeepOrFlash */
1308         drv_initpair,           /* initpair */
1309         drv_initcolor,          /* initcolor */
1310         drv_do_color,           /* docolor */
1311         drv_initmouse,          /* initmouse */
1312         drv_setfilter,          /* setfilter */
1313         drv_hwlabel,            /* hwlabel */
1314         drv_hwlabelOnOff,       /* hwlabelOnOff */
1315         drv_doupdate,           /* update */
1316         drv_defaultcolors,      /* defaultcolors */
1317         drv_print,              /* print */
1318         drv_getsize,            /* getsize */
1319         drv_setsize,            /* setsize */
1320         drv_initacs,            /* initacs */
1321         drv_screen_init,        /* scinit */
1322         drv_wrap,               /* scexit */
1323         drv_twait,              /* twait  */
1324         drv_read,               /* read */
1325         drv_nap,                /* nap */
1326         drv_kpad,               /* kpad */
1327         drv_keyok,              /* kyOk */
1328         drv_kyExist             /* kyExist */
1329 };