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