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