]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/lib_setup.c
ncurses 5.6
[ncurses.git] / ncurses / tinfo / lib_setup.c
1 /****************************************************************************
2  * Copyright (c) 1998-2005,2006 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-2003                                      *
33  ****************************************************************************/
34
35 /*
36  * Terminal setup routines common to termcap and terminfo:
37  *
38  *              use_env(bool)
39  *              setupterm(char *, int, int *)
40  */
41
42 #include <curses.priv.h>
43 #include <tic.h>                /* for MAX_NAME_SIZE */
44 #include <term_entry.h>
45
46 #if SVR4_TERMIO && !defined(_POSIX_SOURCE)
47 #define _POSIX_SOURCE
48 #endif
49
50 #if HAVE_LOCALE_H
51 #include <locale.h>
52 #endif
53
54 #include <term.h>               /* lines, columns, cur_term */
55
56 MODULE_ID("$Id: lib_setup.c,v 1.95 2006/07/28 22:58:13 tom Exp $")
57
58 /****************************************************************************
59  *
60  * Terminal size computation
61  *
62  ****************************************************************************/
63
64 #if HAVE_SIZECHANGE
65 # if !defined(sun) || !TERMIOS
66 #  if HAVE_SYS_IOCTL_H
67 #   include <sys/ioctl.h>
68 #  endif
69 # endif
70 #endif
71
72 #if NEED_PTEM_H
73  /* On SCO, they neglected to define struct winsize in termios.h -- it's only
74   * in termio.h and ptem.h (the former conflicts with other definitions).
75   */
76 # include <sys/stream.h>
77 # include <sys/ptem.h>
78 #endif
79
80 #if HAVE_LANGINFO_CODESET
81 #include <langinfo.h>
82 #endif
83
84 /*
85  * SCO defines TIOCGSIZE and the corresponding struct.  Other systems (SunOS,
86  * Solaris, IRIX) define TIOCGWINSZ and struct winsize.
87  */
88 #ifdef TIOCGSIZE
89 # define IOCTL_WINSIZE TIOCGSIZE
90 # define STRUCT_WINSIZE struct ttysize
91 # define WINSIZE_ROWS(n) (int)n.ts_lines
92 # define WINSIZE_COLS(n) (int)n.ts_cols
93 #else
94 # ifdef TIOCGWINSZ
95 #  define IOCTL_WINSIZE TIOCGWINSZ
96 #  define STRUCT_WINSIZE struct winsize
97 #  define WINSIZE_ROWS(n) (int)n.ws_row
98 #  define WINSIZE_COLS(n) (int)n.ws_col
99 # endif
100 #endif
101
102 NCURSES_EXPORT_VAR(char) ttytype[NAMESIZE] = "";
103 NCURSES_EXPORT_VAR(int) LINES = 0;
104 NCURSES_EXPORT_VAR(int) COLS = 0;
105 NCURSES_EXPORT_VAR(int) TABSIZE = 0;
106
107 static int _use_env = TRUE;
108
109 #if USE_SIGWINCH
110 int
111 _nc_handle_sigwinch(int enable)
112 {
113     static int have_sigwinch = 0;       /* initially no SIGWINCH's */
114     static int can_resizeall = 1;       /* initially enabled */
115     SCREEN *scan;
116     int result;
117
118     switch (enable) {
119     default:
120         /* record a SIGWINCH */
121         have_sigwinch = 1;
122         break;
123     case 0:
124         /* temporarily disable the next block */
125         --can_resizeall;
126         break;
127     case 1:
128         /* temporarily enable the next block */
129         ++can_resizeall;
130         break;
131     }
132
133     /*
134      * If we have a pending SIGWINCH, set the flag in each screen.
135      * But do this only if the block is enabled.
136      */
137     if (can_resizeall-- >= 0) { /* test and disable */
138         if (have_sigwinch) {
139             scan = _nc_screen_chain;
140             while (scan) {
141                 scan->_sig_winch = TRUE;
142                 scan = scan->_next_screen;
143             }
144             have_sigwinch = 0;
145         }
146     }
147     result = can_resizeall + 1; /* reenable (unless disables are nested) */
148     can_resizeall = result;
149
150     return result;
151 }
152
153 #endif
154
155 NCURSES_EXPORT(void)
156 use_env(bool f)
157 {
158     T((T_CALLED("use_env()")));
159     _use_env = f;
160     returnVoid;
161 }
162
163 static void
164 _nc_get_screensize(int *linep, int *colp)
165 /* Obtain lines/columns values from the environment and/or terminfo entry */
166 {
167     /* figure out the size of the screen */
168     T(("screen size: terminfo lines = %d columns = %d", lines, columns));
169
170     _nc_handle_sigwinch(0);
171     if (!_use_env) {
172         *linep = (int) lines;
173         *colp = (int) columns;
174     } else {                    /* usually want to query LINES and COLUMNS from environment */
175         int value;
176
177         *linep = *colp = 0;
178
179         /* first, look for environment variables */
180         if ((value = _nc_getenv_num("LINES")) > 0) {
181             *linep = value;
182         }
183         if ((value = _nc_getenv_num("COLUMNS")) > 0) {
184             *colp = value;
185         }
186         T(("screen size: environment LINES = %d COLUMNS = %d", *linep, *colp));
187
188 #ifdef __EMX__
189         if (*linep <= 0 || *colp <= 0) {
190             int screendata[2];
191             _scrsize(screendata);
192             *colp = screendata[0];
193             *linep = screendata[1];
194             T(("EMX screen size: environment LINES = %d COLUMNS = %d",
195                *linep, *colp));
196         }
197 #endif
198 #if HAVE_SIZECHANGE
199         /* if that didn't work, maybe we can try asking the OS */
200         if (*linep <= 0 || *colp <= 0) {
201             if (isatty(cur_term->Filedes)) {
202                 STRUCT_WINSIZE size;
203
204                 errno = 0;
205                 do {
206                     if (ioctl(cur_term->Filedes, IOCTL_WINSIZE, &size) < 0
207                         && errno != EINTR)
208                         goto failure;
209                 } while
210                     (errno == EINTR);
211
212                 /*
213                  * Solaris lets users override either dimension with an
214                  * environment variable.
215                  */
216                 if (*linep <= 0)
217                     *linep = (SP != 0 && SP->_filtered) ? 1 : WINSIZE_ROWS(size);
218                 if (*colp <= 0)
219                     *colp = WINSIZE_COLS(size);
220             }
221             /* FALLTHRU */
222           failure:;
223         }
224 #endif /* HAVE_SIZECHANGE */
225
226         /* if we can't get dynamic info about the size, use static */
227         if (*linep <= 0) {
228             *linep = (int) lines;
229         }
230         if (*colp <= 0) {
231             *colp = (int) columns;
232         }
233
234         /* the ultimate fallback, assume fixed 24x80 size */
235         if (*linep <= 0) {
236             *linep = 24;
237         }
238         if (*colp <= 0) {
239             *colp = 80;
240         }
241
242         /*
243          * Put the derived values back in the screen-size caps, so
244          * tigetnum() and tgetnum() will do the right thing.
245          */
246         lines = (short) (*linep);
247         columns = (short) (*colp);
248     }
249     _nc_handle_sigwinch(1);
250
251     T(("screen size is %dx%d", *linep, *colp));
252
253     if (VALID_NUMERIC(init_tabs))
254         TABSIZE = (int) init_tabs;
255     else
256         TABSIZE = 8;
257     T(("TABSIZE = %d", TABSIZE));
258 }
259
260 #if USE_SIZECHANGE
261 NCURSES_EXPORT(void)
262 _nc_update_screensize(void)
263 {
264     int old_lines = lines;
265     int new_lines;
266     int old_cols = columns;
267     int new_cols;
268
269     _nc_get_screensize(&new_lines, &new_cols);
270
271     /*
272      * See is_term_resized() and resizeterm().
273      * We're doing it this way because those functions belong to the upper
274      * ncurses library, while this resides in the lower terminfo library.
275      */
276     if (SP != 0
277         && SP->_resize != 0) {
278         if ((new_lines != old_lines) || (new_cols != old_cols))
279             SP->_resize(new_lines, new_cols);
280         SP->_sig_winch = FALSE;
281     }
282 }
283 #endif
284
285 /****************************************************************************
286  *
287  * Terminal setup
288  *
289  ****************************************************************************/
290
291 #define ret_error(code, fmt, arg)       if (errret) {\
292                                             *errret = code;\
293                                             returnCode(ERR);\
294                                         } else {\
295                                             fprintf(stderr, fmt, arg);\
296                                             exit(EXIT_FAILURE);\
297                                         }
298
299 #define ret_error0(code, msg)           if (errret) {\
300                                             *errret = code;\
301                                             returnCode(ERR);\
302                                         } else {\
303                                             fprintf(stderr, msg);\
304                                             exit(EXIT_FAILURE);\
305                                         }
306
307 #if USE_DATABASE || USE_TERMCAP
308 /*
309  * Return 1 if entry found, 0 if not found, -1 if database not accessible,
310  * just like tgetent().
311  */
312 static int
313 grab_entry(const char *const tn, TERMTYPE *const tp)
314 {
315     char filename[PATH_MAX];
316     int status = _nc_read_entry(tn, filename, tp);
317
318     /*
319      * If we have an entry, force all of the cancelled strings to null
320      * pointers so we don't have to test them in the rest of the library.
321      * (The terminfo compiler bypasses this logic, since it must know if
322      * a string is cancelled, for merging entries).
323      */
324     if (status == TGETENT_YES) {
325         unsigned n;
326         for_each_boolean(n, tp) {
327             if (!VALID_BOOLEAN(tp->Booleans[n]))
328                 tp->Booleans[n] = FALSE;
329         }
330         for_each_string(n, tp) {
331             if (tp->Strings[n] == CANCELLED_STRING)
332                 tp->Strings[n] = ABSENT_STRING;
333         }
334     }
335     return (status);
336 }
337 #endif
338
339 /*
340 **      do_prototype()
341 **
342 **      Take the real command character out of the CC environment variable
343 **      and substitute it in for the prototype given in 'command_character'.
344 */
345 static void
346 do_prototype(void)
347 {
348     int i;
349     char CC;
350     char proto;
351     char *tmp;
352
353     tmp = getenv("CC");
354     CC = *tmp;
355     proto = *command_character;
356
357     for_each_string(i, &(cur_term->type)) {
358         for (tmp = cur_term->type.Strings[i]; *tmp; tmp++) {
359             if (*tmp == proto)
360                 *tmp = CC;
361         }
362     }
363 }
364
365 /*
366  * Find the locale which is in effect.
367  */
368 NCURSES_EXPORT(char *)
369 _nc_get_locale(void)
370 {
371     char *env;
372 #if HAVE_LOCALE_H
373     /*
374      * This is preferable to using getenv() since it ensures that we are using
375      * the locale which was actually initialized by the application.
376      */
377     env = setlocale(LC_CTYPE, 0);
378 #else
379     if (((env = getenv("LC_ALL")) != 0 && *env != '\0')
380         || ((env = getenv("LC_CTYPE")) != 0 && *env != '\0')
381         || ((env = getenv("LANG")) != 0 && *env != '\0')) {
382         ;
383     }
384 #endif
385     T(("_nc_get_locale %s", _nc_visbuf(env)));
386     return env;
387 }
388
389 /*
390  * Check if we are running in a UTF-8 locale.
391  */
392 NCURSES_EXPORT(int)
393 _nc_unicode_locale(void)
394 {
395     int result = 0;
396 #if HAVE_LANGINFO_CODESET
397     char *env = nl_langinfo(CODESET);
398     result = !strcmp(env, "UTF-8");
399     T(("_nc_unicode_locale(%s) ->%d", env, result));
400 #else
401     char *env = _nc_get_locale();
402     if (env != 0) {
403         if (strstr(env, ".UTF-8") != 0) {
404             result = 1;
405             T(("_nc_unicode_locale(%s) ->%d", env, result));
406         }
407     }
408 #endif
409     return result;
410 }
411
412 #define CONTROL_N(s) ((s) != 0 && strstr(s, "\016") != 0)
413 #define CONTROL_O(s) ((s) != 0 && strstr(s, "\017") != 0)
414
415 /*
416  * Check for known broken cases where a UTF-8 locale breaks the alternate
417  * character set.
418  */
419 NCURSES_EXPORT(int)
420 _nc_locale_breaks_acs(void)
421 {
422     char *env;
423
424     if ((env = getenv("NCURSES_NO_UTF8_ACS")) != 0) {
425         return atoi(env);
426     } else if ((env = getenv("TERM")) != 0) {
427         if (strstr(env, "linux"))
428             return 1;           /* always broken */
429         if (strstr(env, "screen") != 0
430             && ((env = getenv("TERMCAP")) != 0
431                 && strstr(env, "screen") != 0)
432             && strstr(env, "hhII00") != 0) {
433             if (CONTROL_N(enter_alt_charset_mode) ||
434                 CONTROL_O(enter_alt_charset_mode) ||
435                 CONTROL_N(set_attributes) ||
436                 CONTROL_O(set_attributes))
437                 return 1;
438         }
439     }
440     return 0;
441 }
442
443 /*
444  * This entrypoint is called from tgetent() to allow a special case of reusing
445  * the same TERMINAL data (see comment).
446  */
447 NCURSES_EXPORT(int)
448 _nc_setupterm(NCURSES_CONST char *tname, int Filedes, int *errret, bool reuse)
449 {
450     int status;
451
452     START_TRACE();
453     T((T_CALLED("setupterm(%s,%d,%p)"), _nc_visbuf(tname), Filedes, errret));
454
455     if (tname == 0) {
456         tname = getenv("TERM");
457         if (tname == 0 || *tname == '\0') {
458             ret_error0(TGETENT_ERR, "TERM environment variable not set.\n");
459         }
460     }
461
462     if (strlen(tname) > MAX_NAME_SIZE) {
463         ret_error(TGETENT_ERR,
464                   "TERM environment must be <= %d characters.\n",
465                   MAX_NAME_SIZE);
466     }
467
468     T(("your terminal name is %s", tname));
469
470     /*
471      * Allow output redirection.  This is what SVr3 does.  If stdout is
472      * directed to a file, screen updates go to standard error.
473      */
474     if (Filedes == STDOUT_FILENO && !isatty(Filedes))
475         Filedes = STDERR_FILENO;
476
477     /*
478      * Check if we have already initialized to use this terminal.  If so, we
479      * do not need to re-read the terminfo entry, or obtain TTY settings.
480      *
481      * This is an improvement on SVr4 curses.  If an application mixes curses
482      * and termcap calls, it may call both initscr and tgetent.  This is not
483      * really a good thing to do, but can happen if someone tries using ncurses
484      * with the readline library.  The problem we are fixing is that when
485      * tgetent calls setupterm, the resulting Ottyb struct in cur_term is
486      * zeroed.  A subsequent call to endwin uses the zeroed terminal settings
487      * rather than the ones saved in initscr.  So we check if cur_term appears
488      * to contain terminal settings for the same output file as our current
489      * call - and copy those terminal settings.  (SVr4 curses does not do this,
490      * however applications that are working around the problem will still work
491      * properly with this feature).
492      */
493     if (reuse
494         && cur_term != 0
495         && cur_term->Filedes == Filedes
496         && cur_term->_termname != 0
497         && !strcmp(cur_term->_termname, tname)
498         && _nc_name_match(cur_term->type.term_names, tname, "|")) {
499         T(("reusing existing terminal information and mode-settings"));
500     } else {
501         TERMINAL *term_ptr;
502
503         term_ptr = typeCalloc(TERMINAL, 1);
504
505         if (term_ptr == 0) {
506             ret_error0(TGETENT_ERR,
507                        "Not enough memory to create terminal structure.\n");
508         }
509 #if USE_DATABASE || USE_TERMCAP
510         status = grab_entry(tname, &term_ptr->type);
511 #else
512         status = TGETENT_NO;
513 #endif
514
515         /* try fallback list if entry on disk */
516         if (status != TGETENT_YES) {
517             const TERMTYPE *fallback = _nc_fallback(tname);
518
519             if (fallback) {
520                 term_ptr->type = *fallback;
521                 status = TGETENT_YES;
522             }
523         }
524
525         if (status != TGETENT_YES) {
526             del_curterm(term_ptr);
527             if (status == TGETENT_ERR) {
528                 ret_error0(status, "terminals database is inaccessible\n");
529             } else if (status == TGETENT_NO) {
530                 ret_error(status, "'%s': unknown terminal type.\n", tname);
531             }
532         }
533
534         set_curterm(term_ptr);
535
536         if (command_character && getenv("CC"))
537             do_prototype();
538
539         strncpy(ttytype, cur_term->type.term_names, NAMESIZE - 1);
540         ttytype[NAMESIZE - 1] = '\0';
541
542         cur_term->Filedes = Filedes;
543         cur_term->_termname = strdup(tname);
544
545         /*
546          * If an application calls setupterm() rather than initscr() or
547          * newterm(), we will not have the def_prog_mode() call in
548          * _nc_setupscreen().  Do it now anyway, so we can initialize the
549          * baudrate.
550          */
551         if (isatty(Filedes)) {
552             def_prog_mode();
553             baudrate();
554         }
555     }
556
557     /*
558      * We should always check the screensize, just in case.
559      */
560     _nc_get_screensize(&LINES, &COLS);
561
562     if (errret)
563         *errret = TGETENT_YES;
564
565     T((T_CREATE("screen %s %dx%d"), tname, LINES, COLS));
566
567     if (generic_type) {
568         ret_error(TGETENT_NO, "'%s': I need something more specific.\n", tname);
569     }
570     if (hard_copy) {
571         ret_error(TGETENT_YES, "'%s': I can't handle hardcopy terminals.\n", tname);
572     }
573     returnCode(OK);
574 }
575
576 /*
577  *      setupterm(termname, Filedes, errret)
578  *
579  *      Find and read the appropriate object file for the terminal
580  *      Make cur_term point to the structure.
581  */
582 NCURSES_EXPORT(int)
583 setupterm(NCURSES_CONST char *tname, int Filedes, int *errret)
584 {
585     return _nc_setupterm(tname, Filedes, errret, FALSE);
586 }