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