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