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