]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/lib_setup.c
7231ac671532f6981d664142d4be7e920c8d7bba
[ncurses.git] / ncurses / tinfo / lib_setup.c
1 /****************************************************************************
2  * Copyright 2018-2023,2024 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.235 2024/04/13 20:35:14 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 cc;
336         const char *skipped;
337         int scanned;
338
339         s = memset(buf, '\0', sizeof(buf));
340         do {
341             size_t ask = (sizeof(buf) - 1 - (size_t) (s - buf));
342             int got = (int) read(fd, s, ask);
343             if (got == 0)
344                 break;
345             s += got;
346             *s = '\0';
347         } while (strchr(buf, 'R') == NULL && (size_t) (s + 1 - buf) < sizeof(buf));
348         T(("CPR response %s", _nc_visbuf(buf)));
349         skipped = skip_csi(buf);
350         cc = '\0';
351         if (skipped != buf
352             && *skipped != '\0'
353             && (scanned = sscanf(skip_csi(buf), "%d;%d%c", &y, &x, &cc)) == 3
354             && (cc == 'R')) {
355             *row = y;
356             *col = x;
357             result = TRUE;
358         }
359     }
360     T(("get_position %s %d,%d", result ? "OK" : "ERR", *row, *col));
361     return result;
362 }
363
364 static bool
365 set_position(NCURSES_SP_DCLx TERMINAL *termp, int row, int col)
366 {
367     bool result = FALSE;
368     char *actual = TIPARM_2(cursor_address, row, col);
369     T((T_CALLED("set_position %d,%d)"), row, col));
370     if (NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "set_position", actual) == OK)
371         result = TRUE;
372     NCURSES_SP_NAME(_nc_flush) (NCURSES_SP_ARG);
373     returnBool(result);
374 }
375
376 /*
377  * This is a little more complicated than one might expect, because we do this
378  * before setting up the terminal modes, etc., and cannot use the timeout or
379  * buffering functions.
380  *
381  * We check if the terminal description has the ECMA-48 CPR (cursor position
382  * report) in u7 and the response in u6.  The two variations of is_expected()
383  * cover the termcap style and terminfo style, and are equivalent as far as we
384  * are concerned.  For analyzing the response, we wait (a short time) for 'R'
385  * to be echoed, and then check if we received two integers in the response.
386  *
387  * In principle, this could run on "any" ECMA-48 terminal, but in practice,
388  * there is a scenario using GNU screen where it uses ncurses with a partially
389  * configured pseudo-terminal, and the CPR response goes to the wrong place.
390  * So we do a simple check to exclude pseudo-terminals.
391  */
392 static void
393 _nc_check_screensize(NCURSES_SP_DCLx TERMINAL *termp, int *linep, int *colp)
394 {
395     int fd = termp->Filedes;
396     TTY saved;
397     const char *name;
398
399     if (IsRealTty(fd, name)
400         && VALID_STRING(cursor_address)
401         && is_expected(user7, "6n")
402         && (is_expected(user6, "%i%d;%dR") ||
403             is_expected(user6, "%i%p1%d;%p2%dR"))
404         && GET_TTY(fd, &saved) == OK) {
405         int current_y = -1, current_x = -1;
406         int updated_y = -1, updated_x = -1;
407         TTY alter = saved;
408
409 #if NCURSES_SP_FUNCS
410         if (sp == NULL) {
411             sp = new_prescr();
412             sp->_term = termp;
413             NCURSES_SP_NAME(baudrate) (NCURSES_SP_ARG);
414         }
415 #endif
416
417         T(("checking screensize of %s", name));
418         alter.c_lflag &= (unsigned) ~(ECHO | ICANON | ISIG | IEXTEN);
419         alter.c_iflag &= (unsigned) ~(IXON | BRKINT | PARMRK);
420         alter.c_cc[VMIN] = 0;
421         alter.c_cc[VTIME] = 1;
422         SET_TTY(fd, &alter);
423
424         if (get_position(termp, fd, &current_y, &current_x)
425             && set_position(NCURSES_SP_ARGx termp, 9999, 9999)
426             && get_position(termp, fd, &updated_y, &updated_x)) {
427             *linep = updated_y;
428             *colp = updated_x;
429             set_position(NCURSES_SP_ARGx termp, current_y, current_x);
430         }
431         /* restore tty modes */
432         SET_TTY(fd, &saved);
433     }
434
435     _nc_default_screensize(termp, linep, colp);
436 }
437 #else /* !USE_CHECK_SIZE */
438 #define _nc_check_screensize(sp, termp, linep, colp)    /* nothing */
439 #endif
440 #endif /* !(defined(USE_TERM_DRIVER) || defined(EXP_WIN32_DRIVER)) */
441
442 NCURSES_EXPORT(void)
443 _nc_get_screensize(SCREEN *sp,
444 #ifdef USE_TERM_DRIVER
445                    TERMINAL *termp,
446 #endif
447                    int *linep, int *colp)
448 /* Obtain lines/columns values from the environment and/or terminfo entry */
449 {
450 #ifdef USE_TERM_DRIVER
451     TERMINAL_CONTROL_BLOCK *TCB;
452     int my_tabsize;
453
454     assert(termp != 0 && linep != 0 && colp != 0);
455     TCB = (TERMINAL_CONTROL_BLOCK *) termp;
456
457     my_tabsize = TCB->info.tabsize;
458     TCB->drv->td_size(TCB, linep, colp);
459
460 #if USE_REENTRANT
461     if (sp != 0) {
462         sp->_TABSIZE = my_tabsize;
463     }
464 #else
465     (void) sp;
466     TABSIZE = my_tabsize;
467 #endif
468     T(("TABSIZE = %d", my_tabsize));
469 #else /* !USE_TERM_DRIVER */
470     TERMINAL *termp = cur_term;
471     int my_tabsize;
472     bool useEnv = _nc_prescreen.use_env;
473     bool useTioctl = _nc_prescreen.use_tioctl;
474
475     T((T_CALLED("_nc_get_screensize (%p)"), sp));
476 #ifdef EXP_WIN32_DRIVER
477     /* If we are here, then Windows console is used in terminfo mode.
478        We need to figure out the size using the console API
479      */
480     _nc_console_size(linep, colp);
481     T(("screen size: winconsole lines = %d columns = %d", *linep, *colp));
482 #else
483     /* figure out the size of the screen */
484     T(("screen size: terminfo lines = %d columns = %d", lines, columns));
485
486     *linep = (int) lines;
487     *colp = (int) columns;
488 #endif
489
490 #if NCURSES_SP_FUNCS
491     if (sp) {
492         useEnv = sp->_use_env;
493         useTioctl = sp->use_tioctl;
494     }
495 #endif
496
497     T(("useEnv:%d useTioctl:%d", useEnv, useTioctl));
498     if (useEnv || useTioctl) {
499 #ifdef __EMX__
500         {
501             int screendata[2];
502             _scrsize(screendata);
503             *colp = screendata[0];
504             *linep = ((sp != 0 && sp->_filtered)
505                       ? 1
506                       : screendata[1]);
507             T(("EMX screen size: environment LINES = %d COLUMNS = %d",
508                *linep, *colp));
509         }
510 #endif
511 #if HAVE_SIZECHANGE
512         /* try asking the OS */
513         if (!NC_ISATTY(cur_term->Filedes)) {
514             STRUCT_WINSIZE size;
515
516             errno = 0;
517             do {
518                 if (ioctl(cur_term->Filedes, IOCTL_WINSIZE, &size) >= 0) {
519                     *linep = ((sp != 0 && sp->_filtered)
520                               ? 1
521                               : WINSIZE_ROWS(size));
522                     *colp = WINSIZE_COLS(size);
523                     T(("SYS screen size: environment LINES = %d COLUMNS = %d",
524                        *linep, *colp));
525                     break;
526                 }
527             } while
528                 (errno == EINTR);
529         }
530 #endif /* HAVE_SIZECHANGE */
531
532         if (useEnv) {
533             int value;
534
535             if (useTioctl) {
536                 /*
537                  * If environment variables are used, update them.
538                  */
539                 if ((sp == 0 || !sp->_filtered) && _nc_getenv_num("LINES") > 0) {
540                     _nc_setenv_num("LINES", *linep);
541                 }
542                 if (_nc_getenv_num("COLUMNS") > 0) {
543                     _nc_setenv_num("COLUMNS", *colp);
544                 }
545             }
546
547             /*
548              * Finally, look for environment variables.
549              *
550              * Solaris lets users override either dimension with an environment
551              * variable.
552              */
553             if ((value = _nc_getenv_num("LINES")) > 0) {
554                 *linep = value;
555                 T(("screen size: environment LINES = %d", *linep));
556             }
557             if ((value = _nc_getenv_num("COLUMNS")) > 0) {
558                 *colp = value;
559                 T(("screen size: environment COLUMNS = %d", *colp));
560             }
561
562             _nc_default_screensize(termp, linep, colp);
563         } else {
564             _nc_check_screensize(NCURSES_SP_ARGx termp, linep, colp);
565         }
566
567         /*
568          * Put the derived values back in the screen-size caps, so
569          * tigetnum() and tgetnum() will do the right thing.
570          */
571         lines = (NCURSES_INT2) (*linep);
572         columns = (NCURSES_INT2) (*colp);
573 #if NCURSES_EXT_NUMBERS
574 #define OldNumber(termp,name) \
575         (termp)->type.Numbers[(&name - (termp)->type2.Numbers)]
576         OldNumber(termp, lines) = (short) (*linep);
577         OldNumber(termp, columns) = (short) (*colp);
578 #endif
579     } else {
580         _nc_check_screensize(NCURSES_SP_ARGx termp, linep, colp);
581     }
582
583     T(("screen size is %dx%d", *linep, *colp));
584
585     if (VALID_NUMERIC(init_tabs))
586         my_tabsize = (int) init_tabs;
587     else
588         my_tabsize = 8;
589
590 #if USE_REENTRANT
591     if (sp != 0)
592         sp->_TABSIZE = my_tabsize;
593 #else
594     TABSIZE = my_tabsize;
595 #endif
596     T(("TABSIZE = %d", TABSIZE));
597     returnVoid;
598 #endif /* USE_TERM_DRIVER */
599 }
600
601 #if USE_SIZECHANGE
602 NCURSES_EXPORT(void)
603 _nc_update_screensize(SCREEN *sp)
604 {
605     int new_lines;
606     int new_cols;
607
608 #ifdef USE_TERM_DRIVER
609     int old_lines;
610     int old_cols;
611
612     assert(sp != 0);
613
614     CallDriver_2(sp, td_getsize, &old_lines, &old_cols);
615
616 #else
617     TERMINAL *termp = cur_term;
618     int old_lines = lines;
619     int old_cols = columns;
620 #endif
621
622     if (sp != 0) {
623         TINFO_GET_SIZE(sp, sp->_term, &new_lines, &new_cols);
624         /*
625          * See is_term_resized() and resizeterm().
626          * We're doing it this way because those functions belong to the upper
627          * ncurses library, while this resides in the lower terminfo library.
628          */
629         if (sp->_resize != 0) {
630             if ((new_lines != old_lines) || (new_cols != old_cols)) {
631                 sp->_resize(NCURSES_SP_ARGx new_lines, new_cols);
632             } else if (sp->_sig_winch && (sp->_ungetch != 0)) {
633                 sp->_ungetch(SP_PARM, KEY_RESIZE);      /* so application can know this */
634             }
635             sp->_sig_winch = FALSE;
636         }
637     }
638 }
639 #endif /* USE_SIZECHANGE */
640
641 /****************************************************************************
642  *
643  * Terminal setup
644  *
645  ****************************************************************************/
646
647 #if NCURSES_USE_DATABASE || NCURSES_USE_TERMCAP
648 /*
649  * Return 1 if entry found, 0 if not found, -1 if database not accessible,
650  * just like tgetent().
651  */
652 int
653 _nc_setup_tinfo(const char *const tn, TERMTYPE2 *const tp)
654 {
655     char filename[PATH_MAX];
656     int status = _nc_read_entry2(tn, filename, tp);
657
658     /*
659      * If we have an entry, force all of the cancelled strings to null
660      * pointers so we don't have to test them in the rest of the library.
661      * (The terminfo compiler bypasses this logic, since it must know if
662      * a string is cancelled, for merging entries).
663      */
664     if (status == TGETENT_YES) {
665         unsigned n;
666         T(("_nc_setup_tinfo - resetting invalid booleans/strings"));
667         for_each_boolean(n, tp) {
668             if (!VALID_BOOLEAN(tp->Booleans[n]))
669                 tp->Booleans[n] = FALSE;
670         }
671         for_each_string(n, tp) {
672             if (tp->Strings[n] == CANCELLED_STRING)
673                 tp->Strings[n] = ABSENT_STRING;
674         }
675     }
676     return (status);
677 }
678 #endif
679
680 /*
681  * Take the real command character out of the CC environment variable
682  * and substitute it in for the prototype given in 'command_character'.
683  */
684 void
685 _nc_tinfo_cmdch(TERMINAL *termp, int proto)
686 {
687     char *tmp;
688
689     /*
690      * Only use the character if the string is a single character,
691      * since it is fairly common for developers to set the C compiler
692      * name as an environment variable - using the same symbol.
693      */
694     if ((tmp = getenv("CC")) != 0 && strlen(tmp) == 1) {
695         unsigned i;
696         char CC = *tmp;
697
698         for_each_string(i, &(termp->type)) {
699             tmp = termp->type.Strings[i];
700             if (VALID_STRING(tmp)) {
701                 for (; *tmp; ++tmp) {
702                     if (UChar(*tmp) == proto)
703                         *tmp = CC;
704                 }
705             }
706         }
707     }
708 }
709
710 /*
711  * Find the locale which is in effect.
712  */
713 NCURSES_EXPORT(char *)
714 _nc_get_locale(void)
715 {
716     char *env;
717 #if HAVE_LOCALE_H
718     /*
719      * This is preferable to using getenv() since it ensures that we are using
720      * the locale which was actually initialized by the application.
721      */
722     env = setlocale(LC_CTYPE, 0);
723 #else
724     if (((env = getenv("LANG")) != 0 && *env != '\0')
725         || ((env = getenv("LC_CTYPE")) != 0 && *env != '\0')
726         || ((env = getenv("LC_ALL")) != 0 && *env != '\0')) {
727         ;
728     }
729 #endif
730     T(("_nc_get_locale %s", _nc_visbuf(env)));
731     return env;
732 }
733
734 /*
735  * Check if we are running in a UTF-8 locale.
736  */
737 NCURSES_EXPORT(int)
738 _nc_unicode_locale(void)
739 {
740     static bool initialized = FALSE;
741     static int result = 0;
742
743     if (!initialized) {
744 #if defined(_NC_WINDOWS) && USE_WIDEC_SUPPORT
745         result = 1;
746 #elif HAVE_LANGINFO_CODESET
747         char *env = nl_langinfo(CODESET);
748         result = !strcmp(env, "UTF-8");
749         T(("_nc_unicode_locale(%s) ->%d", env, result));
750 #else
751         char *env = _nc_get_locale();
752         if (env != 0) {
753             if (strstr(env, ".UTF-8") != 0) {
754                 result = 1;
755                 T(("_nc_unicode_locale(%s) ->%d", env, result));
756             }
757         }
758 #endif
759         initialized = TRUE;
760     }
761     return result;
762 }
763
764 #define CONTROL_N(s) ((s) != 0 && strstr(s, "\016") != 0)
765 #define CONTROL_O(s) ((s) != 0 && strstr(s, "\017") != 0)
766
767 /*
768  * Check for known broken cases where a UTF-8 locale breaks the alternate
769  * character set.
770  */
771 NCURSES_EXPORT(int)
772 _nc_locale_breaks_acs(TERMINAL *termp)
773 {
774     const char *env_name = "NCURSES_NO_UTF8_ACS";
775     const char *env;
776     int value;
777     int result = 0;
778
779     T((T_CALLED("_nc_locale_breaks_acs:%d"), result));
780     if (getenv(env_name) != 0) {
781         result = _nc_getenv_num(env_name);
782     } else if ((value = tigetnum("U8")) >= 0) {
783         result = value;         /* use extension feature */
784     } else if ((env = getenv("TERM")) != 0) {
785         if (strstr(env, "linux")) {
786             result = 1;         /* always broken */
787         } else if (strstr(env, "screen") != 0
788                    && ((env = getenv("TERMCAP")) != 0
789                        && strstr(env, "screen") != 0)
790                    && strstr(env, "hhII00") != 0) {
791             if (CONTROL_N(enter_alt_charset_mode) ||
792                 CONTROL_O(enter_alt_charset_mode) ||
793                 CONTROL_N(set_attributes) ||
794                 CONTROL_O(set_attributes)) {
795                 result = 1;
796             }
797         }
798     }
799     returnCode(result);
800 }
801
802 NCURSES_EXPORT(int)
803 TINFO_SETUP_TERM(TERMINAL **tp,
804                  const char *tname,
805                  int Filedes,
806                  int *errret,
807                  int reuse)
808 {
809 #ifdef USE_TERM_DRIVER
810     TERMINAL_CONTROL_BLOCK *TCB = 0;
811 #endif
812     TERMINAL *termp;
813     SCREEN *sp = 0;
814     char *myname;
815     int code = ERR;
816
817     START_TRACE();
818
819 #ifdef USE_TERM_DRIVER
820     T((T_CALLED("_nc_setupterm_ex(%p,%s,%d,%p)"),
821        (void *) tp, _nc_visbuf(tname), Filedes, (void *) errret));
822
823     if (tp == 0) {
824         ret_error0(TGETENT_ERR,
825                    "Invalid parameter, internal error.\n");
826     } else
827         termp = *tp;
828 #else
829     termp = cur_term;
830     T((T_CALLED("setupterm(%s,%d,%p)"), _nc_visbuf(tname), Filedes, (void *) errret));
831 #endif
832
833     if (tname == 0) {
834         tname = getenv("TERM");
835 #if defined(EXP_WIN32_DRIVER)
836         if (!VALID_TERM_ENV(tname, NO_TERMINAL)) {
837             T(("Failure with TERM=%s", NonNull(tname)));
838             ret_error0(TGETENT_ERR, "TERM environment variable not set.\n");
839         }
840 #elif defined(USE_TERM_DRIVER)
841         if (!NonEmpty(tname))
842             tname = "unknown";
843 #else
844         if (!NonEmpty(tname)) {
845             T(("Failure with TERM=%s", NonNull(tname)));
846             ret_error0(TGETENT_ERR, "TERM environment variable not set.\n");
847         }
848 #endif
849     }
850     myname = strdup(tname);
851     if (myname == NULL || strlen(myname) > MAX_NAME_SIZE) {
852         ret_error(TGETENT_ERR,
853                   "TERM environment must be 1..%d characters.\n",
854                   MAX_NAME_SIZE,
855                   free(myname));
856     }
857
858     T(("your terminal name is %s", myname));
859
860     /*
861      * Allow output redirection.  This is what SVr3 does.  If stdout is
862      * directed to a file, screen updates go to standard error.
863      */
864     if (Filedes == STDOUT_FILENO && !NC_ISATTY(Filedes))
865         Filedes = STDERR_FILENO;
866 #if defined(EXP_WIN32_DRIVER)
867     if (Filedes != STDERR_FILENO && NC_ISATTY(Filedes))
868         _setmode(Filedes, _O_BINARY);
869 #endif
870
871     /*
872      * Check if we have already initialized to use this terminal.  If so, we
873      * do not need to re-read the terminfo entry, or obtain TTY settings.
874      *
875      * This is an improvement on SVr4 curses.  If an application mixes curses
876      * and termcap calls, it may call both initscr and tgetent.  This is not
877      * really a good thing to do, but can happen if someone tries using ncurses
878      * with the readline library.  The problem we are fixing is that when
879      * tgetent calls setupterm, the resulting Ottyb struct in cur_term is
880      * zeroed.  A subsequent call to endwin uses the zeroed terminal settings
881      * rather than the ones saved in initscr.  So we check if cur_term appears
882      * to contain terminal settings for the same output file as our current
883      * call - and copy those terminal settings.  (SVr4 curses does not do this,
884      * however applications that are working around the problem will still work
885      * properly with this feature).
886      */
887     if (reuse
888         && (termp != 0)
889         && termp->Filedes == Filedes
890         && termp->_termname != 0
891         && !strcmp(termp->_termname, myname)
892         && _nc_name_match(TerminalType(termp).term_names, myname, "|")) {
893         T(("reusing existing terminal information and mode-settings"));
894         code = OK;
895 #ifdef USE_TERM_DRIVER
896         TCB = (TERMINAL_CONTROL_BLOCK *) termp;
897 #endif
898     } else {
899 #ifdef USE_TERM_DRIVER
900         TERMINAL_CONTROL_BLOCK *my_tcb;
901         termp = 0;
902         if ((my_tcb = typeCalloc(TERMINAL_CONTROL_BLOCK, 1)) != 0)
903             termp = &(my_tcb->term);
904 #else
905         int status;
906
907         termp = typeCalloc(TERMINAL, 1);
908 #endif
909         if (termp == 0) {
910             ret_error1(TGETENT_ERR,
911                        "Not enough memory to create terminal structure.\n",
912                        myname, free(myname));
913         }
914         ++_nc_globals.terminal_count;
915 #if HAVE_SYSCONF
916         {
917             long limit;
918 #ifdef LINE_MAX
919             limit = LINE_MAX;
920 #else
921             limit = _nc_globals.getstr_limit;
922 #endif
923 #ifdef _SC_LINE_MAX
924             if (limit < sysconf(_SC_LINE_MAX))
925                 limit = sysconf(_SC_LINE_MAX);
926 #endif
927             if (_nc_globals.getstr_limit < (int) limit)
928                 _nc_globals.getstr_limit = (int) limit;
929         }
930 #endif /* HAVE_SYSCONF */
931         T(("using %d for getstr limit", _nc_globals.getstr_limit));
932
933 #ifdef USE_TERM_DRIVER
934         INIT_TERM_DRIVER();
935         /*
936          * _nc_get_driver() will call td_CanHandle() for each driver, and win_driver
937          * needs file descriptor to do the test, so set it before calling.
938          */
939         termp->Filedes = (short) Filedes;
940         TCB = (TERMINAL_CONTROL_BLOCK *) termp;
941         code = _nc_globals.term_driver(TCB, myname, errret);
942         if (code == OK) {
943             termp->_termname = strdup(myname);
944         } else {
945             ret_error1(errret ? *errret : TGETENT_ERR,
946                        "Could not find any driver to handle terminal.\n",
947                        myname, free(myname));
948         }
949 #else
950 #if NCURSES_USE_DATABASE || NCURSES_USE_TERMCAP
951         status = _nc_setup_tinfo(myname, &TerminalType(termp));
952         T(("_nc_setup_tinfo returns %d", status));
953 #else
954         T(("no database available"));
955         status = TGETENT_NO;
956 #endif
957
958         /* try fallback list if entry on disk */
959         if (status != TGETENT_YES) {
960             const TERMTYPE2 *fallback = _nc_fallback2(myname);
961
962             if (fallback) {
963                 T(("found fallback entry"));
964                 _nc_copy_termtype2(&(TerminalType(termp)), fallback);
965                 status = TGETENT_YES;
966             }
967         }
968
969         if (status != TGETENT_YES) {
970             del_curterm(termp);
971             if (status == TGETENT_ERR) {
972                 free(myname);
973                 ret_error0(status, "terminals database is inaccessible\n");
974             } else if (status == TGETENT_NO) {
975                 ret_error1(status, "unknown terminal type.\n",
976                            myname, free(myname));
977             } else {
978                 free(myname);
979                 ret_error0(status, "unexpected return-code\n");
980             }
981         }
982 #if NCURSES_EXT_NUMBERS
983         _nc_export_termtype2(&termp->type, &TerminalType(termp));
984 #endif
985 #if !USE_REENTRANT
986         save_ttytype(termp);
987 #endif
988
989         termp->Filedes = (short) Filedes;
990         termp->_termname = strdup(myname);
991
992         set_curterm(termp);
993
994         if (VALID_STRING(command_character))
995             _nc_tinfo_cmdch(termp, UChar(*command_character));
996
997         /*
998          * If an application calls setupterm() rather than initscr() or
999          * newterm(), we will not have the def_prog_mode() call in
1000          * _nc_setupscreen().  Do it now anyway, so we can initialize the
1001          * baudrate.  Also get the shell-mode so that erasechar() works.
1002          */
1003         if (NC_ISATTY(Filedes)) {
1004             NCURSES_SP_NAME(def_shell_mode) (NCURSES_SP_ARG);
1005             NCURSES_SP_NAME(def_prog_mode) (NCURSES_SP_ARG);
1006             NCURSES_SP_NAME(baudrate) (NCURSES_SP_ARG);
1007         }
1008         code = OK;
1009 #endif
1010     }
1011
1012 #ifdef USE_TERM_DRIVER
1013     *tp = termp;
1014     NCURSES_SP_NAME(set_curterm) (sp, termp);
1015     TCB->drv->td_init(TCB);
1016 #else
1017     sp = SP;
1018 #endif
1019
1020     /*
1021      * We should always check the screensize, just in case.
1022      */
1023     TINFO_GET_SIZE(sp, termp, ptrLines(sp), ptrCols(sp));
1024
1025     if (errret)
1026         *errret = TGETENT_YES;
1027
1028 #ifndef USE_TERM_DRIVER
1029     if (generic_type) {
1030         /*
1031          * BSD 4.3's termcap contains mis-typed "gn" for wy99.  Do a sanity
1032          * check before giving up.
1033          */
1034         if ((VALID_STRING(cursor_address)
1035              || (VALID_STRING(cursor_down) && VALID_STRING(cursor_home)))
1036             && VALID_STRING(clear_screen)) {
1037             ret_error1(TGETENT_YES, "terminal is not really generic.\n",
1038                        myname, free(myname));
1039         } else {
1040             del_curterm(termp);
1041             ret_error1(TGETENT_NO, "I need something more specific.\n",
1042                        myname, free(myname));
1043         }
1044     } else if (hard_copy) {
1045         ret_error1(TGETENT_YES, "I can't handle hardcopy terminals.\n",
1046                    myname, free(myname));
1047     }
1048 #endif
1049     free(myname);
1050     returnCode(code);
1051 }
1052
1053 #ifdef USE_PTHREADS
1054 /*
1055  * Returns a non-null pointer unless a new screen should be allocated because
1056  * no match was found in the pre-screen cache.
1057  */
1058 NCURSES_EXPORT(SCREEN *)
1059 _nc_find_prescr(void)
1060 {
1061     SCREEN *result = 0;
1062     PRESCREEN_LIST *p;
1063     pthread_t id = GetThreadID();
1064     for (p = _nc_prescreen.allocated; p != 0; p = p->next) {
1065         if (p->id == id) {
1066             result = p->sp;
1067             break;
1068         }
1069     }
1070     return result;
1071 }
1072
1073 /*
1074  * Tells ncurses to forget that this thread was associated with the pre-screen
1075  * cache.  It does not modify the pre-screen cache itself, since that is used
1076  * for creating new screens.
1077  */
1078 NCURSES_EXPORT(void)
1079 _nc_forget_prescr(void)
1080 {
1081     PRESCREEN_LIST *p, *q;
1082     pthread_t id = GetThreadID();
1083     _nc_lock_global(screen);
1084     for (p = _nc_prescreen.allocated, q = 0; p != 0; q = p, p = p->next) {
1085         if (p->id == id) {
1086             if (q) {
1087                 q->next = p->next;
1088             } else {
1089                 _nc_prescreen.allocated = p->next;
1090             }
1091             free(p);
1092             break;
1093         }
1094     }
1095     _nc_unlock_global(screen);
1096 }
1097 #endif /* USE_PTHREADS */
1098
1099 #if NCURSES_SP_FUNCS
1100 /*
1101  * In case of handling multiple screens, we need to have a screen before
1102  * initialization in _nc_setupscreen takes place.  This is to extend the
1103  * substitute for some of the stuff in _nc_prescreen, especially for slk and
1104  * ripoff handling which should be done per screen.
1105  */
1106 NCURSES_EXPORT(SCREEN *)
1107 new_prescr(void)
1108 {
1109     SCREEN *sp;
1110
1111     START_TRACE();
1112     T((T_CALLED("new_prescr()")));
1113
1114     _nc_lock_global(screen);
1115     if ((sp = _nc_find_prescr()) == 0) {
1116         sp = _nc_alloc_screen_sp();
1117         T(("_nc_alloc_screen_sp %p", (void *) sp));
1118         if (sp != 0) {
1119 #ifdef USE_PTHREADS
1120             PRESCREEN_LIST *p = typeCalloc(PRESCREEN_LIST, 1);
1121             if (p != 0) {
1122                 p->id = GetThreadID();
1123                 p->sp = sp;
1124                 p->next = _nc_prescreen.allocated;
1125                 _nc_prescreen.allocated = p;
1126             }
1127 #else
1128             _nc_prescreen.allocated = sp;
1129 #endif
1130             sp->rsp = sp->rippedoff;
1131             sp->_filtered = _nc_prescreen.filter_mode;
1132             sp->_use_env = _nc_prescreen.use_env;
1133 #if NCURSES_NO_PADDING
1134             sp->_no_padding = _nc_prescreen._no_padding;
1135 #endif
1136             sp->slk_format = 0;
1137             sp->_slk = 0;
1138             sp->_prescreen = TRUE;
1139             SP_PRE_INIT(sp);
1140 #if USE_REENTRANT
1141             sp->_TABSIZE = _nc_prescreen._TABSIZE;
1142             sp->_ESCDELAY = _nc_prescreen._ESCDELAY;
1143 #endif
1144         }
1145     } else {
1146         T(("_nc_alloc_screen_sp %p (reuse)", (void *) sp));
1147     }
1148     _nc_unlock_global(screen);
1149     returnSP(sp);
1150 }
1151 #endif
1152
1153 #ifdef USE_TERM_DRIVER
1154 /*
1155  * This entrypoint is called from tgetent() to allow a special case of reusing
1156  * the same TERMINAL data (see comment).
1157  */
1158 NCURSES_EXPORT(int)
1159 _nc_setupterm(const char *tname,
1160               int Filedes,
1161               int *errret,
1162               int reuse)
1163 {
1164     int rc = ERR;
1165     TERMINAL *termp = 0;
1166
1167     _nc_init_pthreads();
1168     _nc_lock_global(prescreen);
1169     START_TRACE();
1170     if (TINFO_SETUP_TERM(&termp, tname, Filedes, errret, reuse) == OK) {
1171         _nc_forget_prescr();
1172         if (NCURSES_SP_NAME(set_curterm) (CURRENT_SCREEN_PRE, termp) != 0) {
1173             rc = OK;
1174         }
1175     }
1176     _nc_unlock_global(prescreen);
1177
1178     return rc;
1179 }
1180 #endif
1181
1182 /*
1183  *      setupterm(termname, Filedes, errret)
1184  *
1185  *      Find and read the appropriate object file for the terminal
1186  *      Make cur_term point to the structure.
1187  */
1188 NCURSES_EXPORT(int)
1189 setupterm(const char *tname, int Filedes, int *errret)
1190 {
1191     START_TRACE();
1192     return _nc_setupterm(tname, Filedes, errret, FALSE);
1193 }