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