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