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