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