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