]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/lib_setup.c
ncurses 6.4 - patch 20231104
[ncurses.git] / ncurses / tinfo / lib_setup.c
1 /****************************************************************************
2  * Copyright 2018-2022,2023 Thomas E. Dickey                                *
3  * Copyright 1998-2016,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29
30 /****************************************************************************
31  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
32  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
33  *     and: Thomas E. Dickey                        1996-on                 *
34  *     and: Juergen Pfeifer                         2009                    *
35  ****************************************************************************/
36
37 /*
38  * Terminal setup routines common to termcap and terminfo:
39  *
40  *              use_env(bool)
41  *              use_tioctl(bool)
42  *              setupterm(char *, int, int *)
43  */
44
45 #include <curses.priv.h>
46 #include <tic.h>                /* for MAX_NAME_SIZE */
47
48 #if HAVE_LOCALE_H
49 #include <locale.h>
50 #endif
51
52 MODULE_ID("$Id: lib_setup.c,v 1.230 2023/11/04 21:02:27 tom Exp $")
53
54 /****************************************************************************
55  *
56  * Terminal size computation
57  *
58  ****************************************************************************/
59
60 #if HAVE_SIZECHANGE
61 # if !defined(sun) || !TERMIOS
62 #  if HAVE_SYS_IOCTL_H
63 #   include <sys/ioctl.h>
64 #  endif
65 # endif
66 #endif
67
68 #if NEED_PTEM_H
69  /* On SCO, they neglected to define struct winsize in termios.h -- it is only
70   * in termio.h and ptem.h (the former conflicts with other definitions).
71   */
72 # include <sys/stream.h>
73 # include <sys/ptem.h>
74 #endif
75
76 #if HAVE_LANGINFO_CODESET
77 #include <langinfo.h>
78 #endif
79
80 /*
81  * SCO defines TIOCGSIZE and the corresponding struct.  Other systems (SunOS,
82  * Solaris, IRIX) define TIOCGWINSZ and struct winsize.
83  */
84 #ifdef TIOCGSIZE
85 # define IOCTL_WINSIZE TIOCGSIZE
86 # define STRUCT_WINSIZE struct ttysize
87 # define WINSIZE_ROWS(n) (int)n.ts_lines
88 # define WINSIZE_COLS(n) (int)n.ts_cols
89 #else
90 # ifdef TIOCGWINSZ
91 #  define IOCTL_WINSIZE TIOCGWINSZ
92 #  define STRUCT_WINSIZE struct winsize
93 #  define WINSIZE_ROWS(n) (int)n.ws_row
94 #  define WINSIZE_COLS(n) (int)n.ws_col
95 # endif
96 #endif
97
98 /*
99  * Reduce explicit use of "cur_term" global variable.
100  */
101 #undef CUR
102 #define CUR TerminalType(termp).
103
104 /*
105  * Wrap global variables in this module.
106  */
107 #if USE_REENTRANT
108
109 NCURSES_EXPORT(char *)
110 NCURSES_PUBLIC_VAR(ttytype) (void)
111 {
112     static char empty[] = "";
113     char *result = empty;
114
115 #if NCURSES_SP_FUNCS
116     if (CURRENT_SCREEN) {
117         TERMINAL *termp = TerminalOf(CURRENT_SCREEN);
118         if (termp != 0) {
119             result = TerminalType(termp).term_names;
120         }
121     }
122 #else
123     if (cur_term != 0) {
124         result = TerminalType(cur_term).term_names;
125     }
126 #endif
127     return result;
128 }
129
130 NCURSES_EXPORT(int *)
131 _nc_ptr_Lines(SCREEN *sp)
132 {
133     return ptrLines(sp);
134 }
135
136 NCURSES_EXPORT(int)
137 NCURSES_PUBLIC_VAR(LINES) (void)
138 {
139     return *_nc_ptr_Lines(CURRENT_SCREEN);
140 }
141
142 NCURSES_EXPORT(int *)
143 _nc_ptr_Cols(SCREEN *sp)
144 {
145     return ptrCols(sp);
146 }
147
148 NCURSES_EXPORT(int)
149 NCURSES_PUBLIC_VAR(COLS) (void)
150 {
151     return *_nc_ptr_Cols(CURRENT_SCREEN);
152 }
153
154 NCURSES_EXPORT(int *)
155 _nc_ptr_Tabsize(SCREEN *sp)
156 {
157     return ptrTabsize(sp);
158 }
159
160 NCURSES_EXPORT(int)
161 NCURSES_PUBLIC_VAR(TABSIZE) (void)
162 {
163     return *_nc_ptr_Tabsize(CURRENT_SCREEN);
164 }
165 #else
166 NCURSES_EXPORT_VAR(char) ttytype[NAMESIZE] = "";
167 NCURSES_EXPORT_VAR(int) LINES = 0;
168 NCURSES_EXPORT_VAR(int) COLS = 0;
169 NCURSES_EXPORT_VAR(int) TABSIZE = 8;
170 #endif
171
172 #if NCURSES_EXT_FUNCS
173 NCURSES_EXPORT(int)
174 NCURSES_SP_NAME(set_tabsize) (NCURSES_SP_DCLx int value)
175 {
176     int code = OK;
177     if (value <= 0) {
178         code = ERR;
179     } else {
180 #if USE_REENTRANT
181         if (SP_PARM) {
182             SP_PARM->_TABSIZE = value;
183         } else {
184             code = ERR;
185         }
186 #else
187         (void) SP_PARM;
188         TABSIZE = value;
189 #endif
190     }
191     return code;
192 }
193
194 #if NCURSES_SP_FUNCS
195 NCURSES_EXPORT(int)
196 set_tabsize(int value)
197 {
198     return NCURSES_SP_NAME(set_tabsize) (CURRENT_SCREEN, value);
199 }
200 #endif
201 #endif /* NCURSES_EXT_FUNCS */
202
203 #if USE_SIGWINCH
204 /*
205  * If we have a pending SIGWINCH, set the flag in each screen.
206  */
207 NCURSES_EXPORT(int)
208 _nc_handle_sigwinch(SCREEN *sp)
209 {
210     SCREEN *scan;
211
212     if (_nc_globals.have_sigwinch) {
213         _nc_globals.have_sigwinch = 0;
214
215         for (each_screen(scan)) {
216             scan->_sig_winch = TRUE;
217         }
218     }
219
220     return (sp ? sp->_sig_winch : 0);
221 }
222
223 #endif
224
225 NCURSES_EXPORT(void)
226 NCURSES_SP_NAME(use_env) (NCURSES_SP_DCLx bool f)
227 {
228     START_TRACE();
229     T((T_CALLED("use_env(%p,%d)"), (void *) SP_PARM, (int) f));
230 #if NCURSES_SP_FUNCS
231     if (IsPreScreen(SP_PARM)) {
232         SP_PARM->_use_env = f;
233     }
234 #else
235     _nc_prescreen.use_env = f;
236 #endif
237     returnVoid;
238 }
239
240 NCURSES_EXPORT(void)
241 NCURSES_SP_NAME(use_tioctl) (NCURSES_SP_DCLx bool f)
242 {
243     START_TRACE();
244     T((T_CALLED("use_tioctl(%p,%d)"), (void *) SP_PARM, (int) f));
245 #if NCURSES_SP_FUNCS
246     if (IsPreScreen(SP_PARM)) {
247         SP_PARM->use_tioctl = f;
248     }
249 #else
250     _nc_prescreen.use_tioctl = f;
251 #endif
252     returnVoid;
253 }
254
255 #if NCURSES_SP_FUNCS
256 NCURSES_EXPORT(void)
257 use_env(bool f)
258 {
259     START_TRACE();
260     T((T_CALLED("use_env(%d)"), (int) f));
261     _nc_prescreen.use_env = f;
262     returnVoid;
263 }
264
265 NCURSES_EXPORT(void)
266 use_tioctl(bool f)
267 {
268     START_TRACE();
269     T((T_CALLED("use_tioctl(%d)"), (int) f));
270     _nc_prescreen.use_tioctl = f;
271     returnVoid;
272 }
273 #endif
274
275 #if !(defined(USE_TERM_DRIVER) || defined(EXP_WIN32_DRIVER))
276 static void
277 _nc_default_screensize(TERMINAL *termp, int *linep, int *colp)
278 {
279     /* if we can't get dynamic info about the size, use static */
280     if (*linep <= 0) {
281         *linep = (int) lines;
282     }
283     if (*colp <= 0) {
284         *colp = (int) columns;
285     }
286
287     /* the ultimate fallback, assume fixed 24x80 size */
288     if (*linep <= 0) {
289         *linep = 24;
290     }
291     if (*colp <= 0) {
292         *colp = 80;
293     }
294 }
295
296 #if defined(USE_CHECK_SIZE) && defined(user6) && defined(user7)
297 static const char *
298 skip_csi(const char *value)
299 {
300     if (UChar(*value) == CSI_CHR) {
301         ++value;
302     } else if (*value == ESC_CHR && value[1] == L_BLOCK) {
303         value += 2;
304     }
305     return value;
306 }
307
308 static bool
309 is_expected(const char *value, const char *expected)
310 {
311     bool result = FALSE;
312     if (VALID_STRING(value)) {
313         const char *skipped = skip_csi(value);
314         if (skipped != value) {
315             if (!strcmp(skipped, expected))
316                 result = TRUE;
317         }
318     }
319     return result;
320 }
321
322 static bool
323 get_position(TERMINAL *termp, int fd, int *row, int *col)
324 {
325     bool result = FALSE;
326     size_t need = strlen(user7);
327     int have;
328
329     have = (int) write(fd, user7, need);
330
331     if (have == (int) need) {
332         int y, x;
333         char buf[20];
334         char *s;
335         char ignore;
336
337         s = memset(buf, '\0', sizeof(buf));
338         do {
339             size_t ask = (sizeof(buf) - 1 - (size_t) (s - buf));
340             int got = (int) read(fd, s, ask);
341             if (got == 0)
342                 break;
343             s += got;
344             *s = '\0';
345         } while (strchr(buf, 'R') == NULL && (size_t) (s + 1 - buf) < sizeof(buf));
346         T(("response %s", _nc_visbuf(buf)));
347         if (sscanf(skip_csi(buf), "%d;%d%c", &y, &x, &ignore) != 2
348             || (ignore != 'R' && ignore != ';')) {
349             *row = y;
350             *col = x;
351             result = TRUE;
352         }
353     }
354     T(("get_position %d,%d", *row, *col));
355     return result;
356 }
357
358 static bool
359 set_position(TERMINAL *termp, int fd, int row, int col)
360 {
361     bool result = FALSE;
362     char *actual = TIPARM_2(cursor_address, row, col);
363     T(("set_position %d,%d", row, col));
364     if (actual != NULL) {
365         size_t want = strlen(actual);
366         int have = (int) write(fd, actual, want);       /* FIXME - padding */
367         result = ((int) want == have);
368     }
369     return result;
370 }
371
372 /*
373  * This is a little more complicated than one might expect, because we do this
374  * before setting up the terminal modes, etc.
375  */
376 static void
377 _nc_check_screensize(TERMINAL *termp, int *linep, int *colp)
378 {
379     int fd = fileno(stderr);
380     TTY saved;
381
382     if (NC_ISATTY(fd)
383         && VALID_STRING(cursor_address)
384         && is_expected(user7, "6n")
385         && is_expected(user6, "%i%d;%dR")
386         && GET_TTY(fd, &saved) == OK) {
387         int current_y, current_x;
388         int updated_y, updated_x;
389         TTY alter = saved;
390
391         alter.c_lflag &= (unsigned) ~(ECHO | ICANON | ISIG | IEXTEN);
392         alter.c_iflag &= (unsigned) ~(IXON | BRKINT | PARMRK);
393         alter.c_cc[VMIN] = 0;
394         alter.c_cc[VTIME] = 1;
395         SET_TTY(fd, &alter);
396
397         if (get_position(termp, fd, &current_y, &current_x)
398             && set_position(termp, fd, 9999, 9999)
399             && get_position(termp, fd, &updated_y, &updated_x)) {
400             *linep = updated_y;
401             *colp = updated_x;
402             set_position(termp, fd, current_y, current_x);
403         }
404         /* restore tty modes */
405         SET_TTY(fd, &saved);
406     }
407
408     _nc_default_screensize(termp, linep, colp);
409 }
410 #else /* !USE_CHECK_SIZE */
411 #define _nc_check_screensize(termp, linep, colp)        /* nothing */
412 #endif
413 #endif /* !(defined(USE_TERM_DRIVER) || defined(EXP_WIN32_DRIVER)) */
414
415 NCURSES_EXPORT(void)
416 _nc_get_screensize(SCREEN *sp,
417 #ifdef USE_TERM_DRIVER
418                    TERMINAL *termp,
419 #endif
420                    int *linep, int *colp)
421 /* Obtain lines/columns values from the environment and/or terminfo entry */
422 {
423 #ifdef USE_TERM_DRIVER
424     TERMINAL_CONTROL_BLOCK *TCB;
425     int my_tabsize;
426
427     assert(termp != 0 && linep != 0 && colp != 0);
428     TCB = (TERMINAL_CONTROL_BLOCK *) termp;
429
430     my_tabsize = TCB->info.tabsize;
431     TCB->drv->td_size(TCB, linep, colp);
432
433 #if USE_REENTRANT
434     if (sp != 0) {
435         sp->_TABSIZE = my_tabsize;
436     }
437 #else
438     (void) sp;
439     TABSIZE = my_tabsize;
440 #endif
441     T(("TABSIZE = %d", my_tabsize));
442 #else /* !USE_TERM_DRIVER */
443     TERMINAL *termp = cur_term;
444     int my_tabsize;
445     bool useEnv = _nc_prescreen.use_env;
446     bool useTioctl = _nc_prescreen.use_tioctl;
447
448 #ifdef EXP_WIN32_DRIVER
449     /* If we are here, then Windows console is used in terminfo mode.
450        We need to figure out the size using the console API
451      */
452     _nc_console_size(linep, colp);
453     T(("screen size: winconsole lines = %d columns = %d", *linep, *colp));
454 #else
455     /* figure out the size of the screen */
456     T(("screen size: terminfo lines = %d columns = %d", lines, columns));
457
458     *linep = (int) lines;
459     *colp = (int) columns;
460 #endif
461
462 #if NCURSES_SP_FUNCS
463     if (sp) {
464         useEnv = sp->_use_env;
465         useTioctl = sp->use_tioctl;
466     }
467 #endif
468
469     if (useEnv || useTioctl) {
470 #ifdef __EMX__
471         {
472             int screendata[2];
473             _scrsize(screendata);
474             *colp = screendata[0];
475             *linep = ((sp != 0 && sp->_filtered)
476                       ? 1
477                       : screendata[1]);
478             T(("EMX screen size: environment LINES = %d COLUMNS = %d",
479                *linep, *colp));
480         }
481 #endif
482 #if HAVE_SIZECHANGE
483         /* try asking the OS */
484         if (NC_ISATTY(cur_term->Filedes)) {
485             STRUCT_WINSIZE size;
486
487             errno = 0;
488             do {
489                 if (ioctl(cur_term->Filedes, IOCTL_WINSIZE, &size) >= 0) {
490                     *linep = ((sp != 0 && sp->_filtered)
491                               ? 1
492                               : WINSIZE_ROWS(size));
493                     *colp = WINSIZE_COLS(size);
494                     T(("SYS screen size: environment LINES = %d COLUMNS = %d",
495                        *linep, *colp));
496                     break;
497                 }
498             } while
499                 (errno == EINTR);
500         }
501 #endif /* HAVE_SIZECHANGE */
502
503         if (useEnv) {
504             int value;
505
506             if (useTioctl) {
507                 /*
508                  * If environment variables are used, update them.
509                  */
510                 if ((sp == 0 || !sp->_filtered) && _nc_getenv_num("LINES") > 0) {
511                     _nc_setenv_num("LINES", *linep);
512                 }
513                 if (_nc_getenv_num("COLUMNS") > 0) {
514                     _nc_setenv_num("COLUMNS", *colp);
515                 }
516             }
517
518             /*
519              * Finally, look for environment variables.
520              *
521              * Solaris lets users override either dimension with an environment
522              * variable.
523              */
524             if ((value = _nc_getenv_num("LINES")) > 0) {
525                 *linep = value;
526                 T(("screen size: environment LINES = %d", *linep));
527             }
528             if ((value = _nc_getenv_num("COLUMNS")) > 0) {
529                 *colp = value;
530                 T(("screen size: environment COLUMNS = %d", *colp));
531             }
532
533             _nc_default_screensize(termp, linep, colp);
534         } else {
535             _nc_check_screensize(termp, linep, colp);
536         }
537
538         /*
539          * Put the derived values back in the screen-size caps, so
540          * tigetnum() and tgetnum() will do the right thing.
541          */
542         lines = (NCURSES_INT2) (*linep);
543         columns = (NCURSES_INT2) (*colp);
544 #if NCURSES_EXT_NUMBERS
545 #define OldNumber(termp,name) \
546         (termp)->type.Numbers[(&name - (termp)->type2.Numbers)]
547         OldNumber(termp, lines) = (short) (*linep);
548         OldNumber(termp, columns) = (short) (*colp);
549 #endif
550     } else {
551         _nc_check_screensize(termp, linep, colp);
552     }
553
554     T(("screen size is %dx%d", *linep, *colp));
555
556     if (VALID_NUMERIC(init_tabs))
557         my_tabsize = (int) init_tabs;
558     else
559         my_tabsize = 8;
560
561 #if USE_REENTRANT
562     if (sp != 0)
563         sp->_TABSIZE = my_tabsize;
564 #else
565     TABSIZE = my_tabsize;
566 #endif
567     T(("TABSIZE = %d", TABSIZE));
568 #endif /* USE_TERM_DRIVER */
569 }
570
571 #if USE_SIZECHANGE
572 NCURSES_EXPORT(void)
573 _nc_update_screensize(SCREEN *sp)
574 {
575     int new_lines;
576     int new_cols;
577
578 #ifdef USE_TERM_DRIVER
579     int old_lines;
580     int old_cols;
581
582     assert(sp != 0);
583
584     CallDriver_2(sp, td_getsize, &old_lines, &old_cols);
585
586 #else
587     TERMINAL *termp = cur_term;
588     int old_lines = lines;
589     int old_cols = columns;
590 #endif
591
592     if (sp != 0) {
593         TINFO_GET_SIZE(sp, sp->_term, &new_lines, &new_cols);
594         /*
595          * See is_term_resized() and resizeterm().
596          * We're doing it this way because those functions belong to the upper
597          * ncurses library, while this resides in the lower terminfo library.
598          */
599         if (sp->_resize != 0) {
600             if ((new_lines != old_lines) || (new_cols != old_cols)) {
601                 sp->_resize(NCURSES_SP_ARGx new_lines, new_cols);
602             } else if (sp->_sig_winch && (sp->_ungetch != 0)) {
603                 sp->_ungetch(SP_PARM, KEY_RESIZE);      /* so application can know this */
604             }
605             sp->_sig_winch = FALSE;
606         }
607     }
608 }
609 #endif /* USE_SIZECHANGE */
610
611 /****************************************************************************
612  *
613  * Terminal setup
614  *
615  ****************************************************************************/
616
617 #if NCURSES_USE_DATABASE || NCURSES_USE_TERMCAP
618 /*
619  * Return 1 if entry found, 0 if not found, -1 if database not accessible,
620  * just like tgetent().
621  */
622 int
623 _nc_setup_tinfo(const char *const tn, TERMTYPE2 *const tp)
624 {
625     char filename[PATH_MAX];
626     int status = _nc_read_entry2(tn, filename, tp);
627
628     /*
629      * If we have an entry, force all of the cancelled strings to null
630      * pointers so we don't have to test them in the rest of the library.
631      * (The terminfo compiler bypasses this logic, since it must know if
632      * a string is cancelled, for merging entries).
633      */
634     if (status == TGETENT_YES) {
635         unsigned n;
636         T(("_nc_setup_tinfo - resetting invalid booleans/strings"));
637         for_each_boolean(n, tp) {
638             if (!VALID_BOOLEAN(tp->Booleans[n]))
639                 tp->Booleans[n] = FALSE;
640         }
641         for_each_string(n, tp) {
642             if (tp->Strings[n] == CANCELLED_STRING)
643                 tp->Strings[n] = ABSENT_STRING;
644         }
645     }
646     return (status);
647 }
648 #endif
649
650 /*
651  * Take the real command character out of the CC environment variable
652  * and substitute it in for the prototype given in 'command_character'.
653  */
654 void
655 _nc_tinfo_cmdch(TERMINAL *termp, int proto)
656 {
657     char *tmp;
658
659     /*
660      * Only use the character if the string is a single character,
661      * since it is fairly common for developers to set the C compiler
662      * name as an environment variable - using the same symbol.
663      */
664     if ((tmp = getenv("CC")) != 0 && strlen(tmp) == 1) {
665         unsigned i;
666         char CC = *tmp;
667
668         for_each_string(i, &(termp->type)) {
669             tmp = termp->type.Strings[i];
670             if (VALID_STRING(tmp)) {
671                 for (; *tmp; ++tmp) {
672                     if (UChar(*tmp) == proto)
673                         *tmp = CC;
674                 }
675             }
676         }
677     }
678 }
679
680 /*
681  * Find the locale which is in effect.
682  */
683 NCURSES_EXPORT(char *)
684 _nc_get_locale(void)
685 {
686     char *env;
687 #if HAVE_LOCALE_H
688     /*
689      * This is preferable to using getenv() since it ensures that we are using
690      * the locale which was actually initialized by the application.
691      */
692     env = setlocale(LC_CTYPE, 0);
693 #else
694     if (((env = getenv("LANG")) != 0 && *env != '\0')
695         || ((env = getenv("LC_CTYPE")) != 0 && *env != '\0')
696         || ((env = getenv("LC_ALL")) != 0 && *env != '\0')) {
697         ;
698     }
699 #endif
700     T(("_nc_get_locale %s", _nc_visbuf(env)));
701     return env;
702 }
703
704 /*
705  * Check if we are running in a UTF-8 locale.
706  */
707 NCURSES_EXPORT(int)
708 _nc_unicode_locale(void)
709 {
710     int result = 0;
711 #if defined(_NC_WINDOWS) && USE_WIDEC_SUPPORT
712     result = 1;
713 #elif HAVE_LANGINFO_CODESET
714     char *env = nl_langinfo(CODESET);
715     result = !strcmp(env, "UTF-8");
716     T(("_nc_unicode_locale(%s) ->%d", env, result));
717 #else
718     char *env = _nc_get_locale();
719     if (env != 0) {
720         if (strstr(env, ".UTF-8") != 0) {
721             result = 1;
722             T(("_nc_unicode_locale(%s) ->%d", env, result));
723         }
724     }
725 #endif
726     return result;
727 }
728
729 #define CONTROL_N(s) ((s) != 0 && strstr(s, "\016") != 0)
730 #define CONTROL_O(s) ((s) != 0 && strstr(s, "\017") != 0)
731
732 /*
733  * Check for known broken cases where a UTF-8 locale breaks the alternate
734  * character set.
735  */
736 NCURSES_EXPORT(int)
737 _nc_locale_breaks_acs(TERMINAL *termp)
738 {
739     const char *env_name = "NCURSES_NO_UTF8_ACS";
740     const char *env;
741     int value;
742     int result = 0;
743
744     T((T_CALLED("_nc_locale_breaks_acs:%d"), result));
745     if (getenv(env_name) != 0) {
746         result = _nc_getenv_num(env_name);
747     } else if ((value = tigetnum("U8")) >= 0) {
748         result = value;         /* use extension feature */
749     } else if ((env = getenv("TERM")) != 0) {
750         if (strstr(env, "linux")) {
751             result = 1;         /* always broken */
752         } else if (strstr(env, "screen") != 0
753                    && ((env = getenv("TERMCAP")) != 0
754                        && strstr(env, "screen") != 0)
755                    && strstr(env, "hhII00") != 0) {
756             if (CONTROL_N(enter_alt_charset_mode) ||
757                 CONTROL_O(enter_alt_charset_mode) ||
758                 CONTROL_N(set_attributes) ||
759                 CONTROL_O(set_attributes)) {
760                 result = 1;
761             }
762         }
763     }
764     returnCode(result);
765 }
766
767 NCURSES_EXPORT(int)
768 TINFO_SETUP_TERM(TERMINAL **tp,
769                  const char *tname,
770                  int Filedes,
771                  int *errret,
772                  int reuse)
773 {
774 #ifdef USE_TERM_DRIVER
775     TERMINAL_CONTROL_BLOCK *TCB = 0;
776 #endif
777     TERMINAL *termp;
778     SCREEN *sp = 0;
779     char *myname;
780     int code = ERR;
781
782     START_TRACE();
783
784 #ifdef USE_TERM_DRIVER
785     T((T_CALLED("_nc_setupterm_ex(%p,%s,%d,%p)"),
786        (void *) tp, _nc_visbuf(tname), Filedes, (void *) errret));
787
788     if (tp == 0) {
789         ret_error0(TGETENT_ERR,
790                    "Invalid parameter, internal error.\n");
791     } else
792         termp = *tp;
793 #else
794     termp = cur_term;
795     T((T_CALLED("setupterm(%s,%d,%p)"), _nc_visbuf(tname), Filedes, (void *) errret));
796 #endif
797
798     if (tname == 0) {
799         tname = getenv("TERM");
800 #if defined(EXP_WIN32_DRIVER)
801         if (!VALID_TERM_ENV(tname, NO_TERMINAL)) {
802             T(("Failure with TERM=%s", NonNull(tname)));
803             ret_error0(TGETENT_ERR, "TERM environment variable not set.\n");
804         }
805 #elif defined(USE_TERM_DRIVER)
806         if (!NonEmpty(tname))
807             tname = "unknown";
808 #else
809         if (!NonEmpty(tname)) {
810             T(("Failure with TERM=%s", NonNull(tname)));
811             ret_error0(TGETENT_ERR, "TERM environment variable not set.\n");
812         }
813 #endif
814     }
815     myname = strdup(tname);
816     if (myname == NULL || strlen(myname) > MAX_NAME_SIZE) {
817         ret_error(TGETENT_ERR,
818                   "TERM environment must be 1..%d characters.\n",
819                   MAX_NAME_SIZE,
820                   free(myname));
821     }
822
823     T(("your terminal name is %s", myname));
824
825     /*
826      * Allow output redirection.  This is what SVr3 does.  If stdout is
827      * directed to a file, screen updates go to standard error.
828      */
829     if (Filedes == STDOUT_FILENO && !NC_ISATTY(Filedes))
830         Filedes = STDERR_FILENO;
831 #if defined(EXP_WIN32_DRIVER)
832     if (Filedes != STDERR_FILENO && NC_ISATTY(Filedes))
833         _setmode(Filedes, _O_BINARY);
834 #endif
835
836     /*
837      * Check if we have already initialized to use this terminal.  If so, we
838      * do not need to re-read the terminfo entry, or obtain TTY settings.
839      *
840      * This is an improvement on SVr4 curses.  If an application mixes curses
841      * and termcap calls, it may call both initscr and tgetent.  This is not
842      * really a good thing to do, but can happen if someone tries using ncurses
843      * with the readline library.  The problem we are fixing is that when
844      * tgetent calls setupterm, the resulting Ottyb struct in cur_term is
845      * zeroed.  A subsequent call to endwin uses the zeroed terminal settings
846      * rather than the ones saved in initscr.  So we check if cur_term appears
847      * to contain terminal settings for the same output file as our current
848      * call - and copy those terminal settings.  (SVr4 curses does not do this,
849      * however applications that are working around the problem will still work
850      * properly with this feature).
851      */
852     if (reuse
853         && (termp != 0)
854         && termp->Filedes == Filedes
855         && termp->_termname != 0
856         && !strcmp(termp->_termname, myname)
857         && _nc_name_match(TerminalType(termp).term_names, myname, "|")) {
858         T(("reusing existing terminal information and mode-settings"));
859         code = OK;
860 #ifdef USE_TERM_DRIVER
861         TCB = (TERMINAL_CONTROL_BLOCK *) termp;
862 #endif
863     } else {
864 #ifdef USE_TERM_DRIVER
865         TERMINAL_CONTROL_BLOCK *my_tcb;
866         termp = 0;
867         if ((my_tcb = typeCalloc(TERMINAL_CONTROL_BLOCK, 1)) != 0)
868             termp = &(my_tcb->term);
869 #else
870         int status;
871
872         termp = typeCalloc(TERMINAL, 1);
873 #endif
874         if (termp == 0) {
875             ret_error1(TGETENT_ERR,
876                        "Not enough memory to create terminal structure.\n",
877                        myname, free(myname));
878         }
879         ++_nc_globals.terminal_count;
880 #if HAVE_SYSCONF
881         {
882             long limit;
883 #ifdef LINE_MAX
884             limit = LINE_MAX;
885 #else
886             limit = _nc_globals.getstr_limit;
887 #endif
888 #ifdef _SC_LINE_MAX
889             if (limit < sysconf(_SC_LINE_MAX))
890                 limit = sysconf(_SC_LINE_MAX);
891 #endif
892             if (_nc_globals.getstr_limit < (int) limit)
893                 _nc_globals.getstr_limit = (int) limit;
894         }
895 #endif /* HAVE_SYSCONF */
896         T(("using %d for getstr limit", _nc_globals.getstr_limit));
897
898 #ifdef USE_TERM_DRIVER
899         INIT_TERM_DRIVER();
900         /*
901          * _nc_get_driver() will call td_CanHandle() for each driver, and win_driver
902          * needs file descriptor to do the test, so set it before calling.
903          */
904         termp->Filedes = (short) Filedes;
905         TCB = (TERMINAL_CONTROL_BLOCK *) termp;
906         code = _nc_globals.term_driver(TCB, myname, errret);
907         if (code == OK) {
908             termp->_termname = strdup(myname);
909         } else {
910             ret_error1(errret ? *errret : TGETENT_ERR,
911                        "Could not find any driver to handle terminal.\n",
912                        myname, free(myname));
913         }
914 #else
915 #if NCURSES_USE_DATABASE || NCURSES_USE_TERMCAP
916         status = _nc_setup_tinfo(myname, &TerminalType(termp));
917         T(("_nc_setup_tinfo returns %d", status));
918 #else
919         T(("no database available"));
920         status = TGETENT_NO;
921 #endif
922
923         /* try fallback list if entry on disk */
924         if (status != TGETENT_YES) {
925             const TERMTYPE2 *fallback = _nc_fallback2(myname);
926
927             if (fallback) {
928                 T(("found fallback entry"));
929                 _nc_copy_termtype2(&(TerminalType(termp)), fallback);
930                 status = TGETENT_YES;
931             }
932         }
933
934         if (status != TGETENT_YES) {
935             del_curterm(termp);
936             if (status == TGETENT_ERR) {
937                 free(myname);
938                 ret_error0(status, "terminals database is inaccessible\n");
939             } else if (status == TGETENT_NO) {
940                 ret_error1(status, "unknown terminal type.\n",
941                            myname, free(myname));
942             } else {
943                 free(myname);
944                 ret_error0(status, "unexpected return-code\n");
945             }
946         }
947 #if NCURSES_EXT_NUMBERS
948         _nc_export_termtype2(&termp->type, &TerminalType(termp));
949 #endif
950 #if !USE_REENTRANT
951         save_ttytype(termp);
952 #endif
953
954         termp->Filedes = (short) Filedes;
955         termp->_termname = strdup(myname);
956
957         set_curterm(termp);
958
959         if (VALID_STRING(command_character))
960             _nc_tinfo_cmdch(termp, UChar(*command_character));
961
962         /*
963          * If an application calls setupterm() rather than initscr() or
964          * newterm(), we will not have the def_prog_mode() call in
965          * _nc_setupscreen().  Do it now anyway, so we can initialize the
966          * baudrate.  Also get the shell-mode so that erasechar() works.
967          */
968         if (NC_ISATTY(Filedes)) {
969             NCURSES_SP_NAME(def_shell_mode) (NCURSES_SP_ARG);
970             NCURSES_SP_NAME(def_prog_mode) (NCURSES_SP_ARG);
971             NCURSES_SP_NAME(baudrate) (NCURSES_SP_ARG);
972         }
973         code = OK;
974 #endif
975     }
976
977 #ifdef USE_TERM_DRIVER
978     *tp = termp;
979     NCURSES_SP_NAME(set_curterm) (sp, termp);
980     TCB->drv->td_init(TCB);
981 #else
982     sp = SP;
983 #endif
984
985     /*
986      * We should always check the screensize, just in case.
987      */
988     TINFO_GET_SIZE(sp, termp, ptrLines(sp), ptrCols(sp));
989
990     if (errret)
991         *errret = TGETENT_YES;
992
993 #ifndef USE_TERM_DRIVER
994     if (generic_type) {
995         /*
996          * BSD 4.3's termcap contains mis-typed "gn" for wy99.  Do a sanity
997          * check before giving up.
998          */
999         if ((VALID_STRING(cursor_address)
1000              || (VALID_STRING(cursor_down) && VALID_STRING(cursor_home)))
1001             && VALID_STRING(clear_screen)) {
1002             ret_error1(TGETENT_YES, "terminal is not really generic.\n",
1003                        myname, free(myname));
1004         } else {
1005             del_curterm(termp);
1006             ret_error1(TGETENT_NO, "I need something more specific.\n",
1007                        myname, free(myname));
1008         }
1009     } else if (hard_copy) {
1010         ret_error1(TGETENT_YES, "I can't handle hardcopy terminals.\n",
1011                    myname, free(myname));
1012     }
1013 #endif
1014     free(myname);
1015     returnCode(code);
1016 }
1017
1018 #ifdef USE_PTHREADS
1019 /*
1020  * Returns a non-null pointer unless a new screen should be allocated because
1021  * no match was found in the pre-screen cache.
1022  */
1023 NCURSES_EXPORT(SCREEN *)
1024 _nc_find_prescr(void)
1025 {
1026     SCREEN *result = 0;
1027     PRESCREEN_LIST *p;
1028     pthread_t id = GetThreadID();
1029     for (p = _nc_prescreen.allocated; p != 0; p = p->next) {
1030         if (p->id == id) {
1031             result = p->sp;
1032             break;
1033         }
1034     }
1035     return result;
1036 }
1037
1038 /*
1039  * Tells ncurses to forget that this thread was associated with the pre-screen
1040  * cache.  It does not modify the pre-screen cache itself, since that is used
1041  * for creating new screens.
1042  */
1043 NCURSES_EXPORT(void)
1044 _nc_forget_prescr(void)
1045 {
1046     PRESCREEN_LIST *p, *q;
1047     pthread_t id = GetThreadID();
1048     _nc_lock_global(screen);
1049     for (p = _nc_prescreen.allocated, q = 0; p != 0; q = p, p = p->next) {
1050         if (p->id == id) {
1051             if (q) {
1052                 q->next = p->next;
1053             } else {
1054                 _nc_prescreen.allocated = p->next;
1055             }
1056             free(p);
1057             break;
1058         }
1059     }
1060     _nc_unlock_global(screen);
1061 }
1062 #endif /* USE_PTHREADS */
1063
1064 #if NCURSES_SP_FUNCS
1065 /*
1066  * In case of handling multiple screens, we need to have a screen before
1067  * initialization in _nc_setupscreen takes place.  This is to extend the
1068  * substitute for some of the stuff in _nc_prescreen, especially for slk and
1069  * ripoff handling which should be done per screen.
1070  */
1071 NCURSES_EXPORT(SCREEN *)
1072 new_prescr(void)
1073 {
1074     SCREEN *sp;
1075
1076     START_TRACE();
1077     T((T_CALLED("new_prescr()")));
1078
1079     _nc_lock_global(screen);
1080     if ((sp = _nc_find_prescr()) == 0) {
1081         sp = _nc_alloc_screen_sp();
1082         T(("_nc_alloc_screen_sp %p", (void *) sp));
1083         if (sp != 0) {
1084 #ifdef USE_PTHREADS
1085             PRESCREEN_LIST *p = typeCalloc(PRESCREEN_LIST, 1);
1086             if (p != 0) {
1087                 p->id = GetThreadID();
1088                 p->sp = sp;
1089                 p->next = _nc_prescreen.allocated;
1090                 _nc_prescreen.allocated = p;
1091             }
1092 #else
1093             _nc_prescreen.allocated = sp;
1094 #endif
1095             sp->rsp = sp->rippedoff;
1096             sp->_filtered = _nc_prescreen.filter_mode;
1097             sp->_use_env = _nc_prescreen.use_env;
1098 #if NCURSES_NO_PADDING
1099             sp->_no_padding = _nc_prescreen._no_padding;
1100 #endif
1101             sp->slk_format = 0;
1102             sp->_slk = 0;
1103             sp->_prescreen = TRUE;
1104             SP_PRE_INIT(sp);
1105 #if USE_REENTRANT
1106             sp->_TABSIZE = _nc_prescreen._TABSIZE;
1107             sp->_ESCDELAY = _nc_prescreen._ESCDELAY;
1108 #endif
1109         }
1110     } else {
1111         T(("_nc_alloc_screen_sp %p (reuse)", (void *) sp));
1112     }
1113     _nc_unlock_global(screen);
1114     returnSP(sp);
1115 }
1116 #endif
1117
1118 #ifdef USE_TERM_DRIVER
1119 /*
1120  * This entrypoint is called from tgetent() to allow a special case of reusing
1121  * the same TERMINAL data (see comment).
1122  */
1123 NCURSES_EXPORT(int)
1124 _nc_setupterm(const char *tname,
1125               int Filedes,
1126               int *errret,
1127               int reuse)
1128 {
1129     int rc = ERR;
1130     TERMINAL *termp = 0;
1131
1132     _nc_init_pthreads();
1133     _nc_lock_global(prescreen);
1134     START_TRACE();
1135     if (TINFO_SETUP_TERM(&termp, tname, Filedes, errret, reuse) == OK) {
1136         _nc_forget_prescr();
1137         if (NCURSES_SP_NAME(set_curterm) (CURRENT_SCREEN_PRE, termp) != 0) {
1138             rc = OK;
1139         }
1140     }
1141     _nc_unlock_global(prescreen);
1142
1143     return rc;
1144 }
1145 #endif
1146
1147 /*
1148  *      setupterm(termname, Filedes, errret)
1149  *
1150  *      Find and read the appropriate object file for the terminal
1151  *      Make cur_term point to the structure.
1152  */
1153 NCURSES_EXPORT(int)
1154 setupterm(const char *tname, int Filedes, int *errret)
1155 {
1156     START_TRACE();
1157     return _nc_setupterm(tname, Filedes, errret, FALSE);
1158 }