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