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