Back to index

tetex-bin  3.0
lib_setup.c
Go to the documentation of this file.
00001 /****************************************************************************
00002  * Copyright (c) 1998-2003,2004 Free Software Foundation, Inc.              *
00003  *                                                                          *
00004  * Permission is hereby granted, free of charge, to any person obtaining a  *
00005  * copy of this software and associated documentation files (the            *
00006  * "Software"), to deal in the Software without restriction, including      *
00007  * without limitation the rights to use, copy, modify, merge, publish,      *
00008  * distribute, distribute with modifications, sublicense, and/or sell       *
00009  * copies of the Software, and to permit persons to whom the Software is    *
00010  * furnished to do so, subject to the following conditions:                 *
00011  *                                                                          *
00012  * The above copyright notice and this permission notice shall be included  *
00013  * in all copies or substantial portions of the Software.                   *
00014  *                                                                          *
00015  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
00016  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
00017  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
00018  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
00019  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
00020  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
00021  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
00022  *                                                                          *
00023  * Except as contained in this notice, the name(s) of the above copyright   *
00024  * holders shall not be used in advertising or otherwise to promote the     *
00025  * sale, use or other dealings in this Software without prior written       *
00026  * authorization.                                                           *
00027  ****************************************************************************/
00028 
00029 /****************************************************************************
00030  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
00031  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
00032  *     and: Thomas E. Dickey 1996-2003                                      *
00033  ****************************************************************************/
00034 
00035 /*
00036  * Terminal setup routines common to termcap and terminfo:
00037  *
00038  *            use_env(bool)
00039  *            setupterm(char *, int, int *)
00040  */
00041 
00042 #include <curses.priv.h>
00043 #include <tic.h>            /* for MAX_NAME_SIZE */
00044 #include <term_entry.h>
00045 
00046 #if SVR4_TERMIO && !defined(_POSIX_SOURCE)
00047 #define _POSIX_SOURCE
00048 #endif
00049 
00050 #if HAVE_LOCALE_H
00051 #include <locale.h>
00052 #endif
00053 
00054 #include <term.h>           /* lines, columns, cur_term */
00055 
00056 MODULE_ID("$Id: lib_setup.c,v 1.86 2004/10/09 19:16:33 tom Exp $")
00057 
00058 /****************************************************************************
00059  *
00060  * Terminal size computation
00061  *
00062  ****************************************************************************/
00063 
00064 #if HAVE_SIZECHANGE
00065 # if !defined(sun) || !TERMIOS
00066 #  if HAVE_SYS_IOCTL_H
00067 #   include <sys/ioctl.h>
00068 #  endif
00069 # endif
00070 #endif
00071 
00072 #if NEED_PTEM_H
00073  /* On SCO, they neglected to define struct winsize in termios.h -- it's only
00074   * in termio.h and ptem.h (the former conflicts with other definitions).
00075   */
00076 # include <sys/stream.h>
00077 # include <sys/ptem.h>
00078 #endif
00079 
00080 #if HAVE_LANGINFO_CODESET
00081 #include <langinfo.h>
00082 #endif
00083 
00084 /*
00085  * SCO defines TIOCGSIZE and the corresponding struct.  Other systems (SunOS,
00086  * Solaris, IRIX) define TIOCGWINSZ and struct winsize.
00087  */
00088 #ifdef TIOCGSIZE
00089 # define IOCTL_WINSIZE TIOCGSIZE
00090 # define STRUCT_WINSIZE struct ttysize
00091 # define WINSIZE_ROWS(n) (int)n.ts_lines
00092 # define WINSIZE_COLS(n) (int)n.ts_cols
00093 #else
00094 # ifdef TIOCGWINSZ
00095 #  define IOCTL_WINSIZE TIOCGWINSZ
00096 #  define STRUCT_WINSIZE struct winsize
00097 #  define WINSIZE_ROWS(n) (int)n.ws_row
00098 #  define WINSIZE_COLS(n) (int)n.ws_col
00099 # endif
00100 #endif
00101 
00102 NCURSES_EXPORT_VAR(char) ttytype[NAMESIZE] = "";
00103 NCURSES_EXPORT_VAR(int) LINES = 0;
00104 NCURSES_EXPORT_VAR(int) COLS = 0;
00105 NCURSES_EXPORT_VAR(int) TABSIZE = 0;
00106 
00107 static int _use_env = TRUE;
00108 
00109 NCURSES_EXPORT(void)
00110 use_env(bool f)
00111 {
00112     T((T_CALLED("use_env()")));
00113     _use_env = f;
00114     returnVoid;
00115 }
00116 
00117 static void
00118 _nc_get_screensize(int *linep, int *colp)
00119 /* Obtain lines/columns values from the environment and/or terminfo entry */
00120 {
00121     /* figure out the size of the screen */
00122     T(("screen size: terminfo lines = %d columns = %d", lines, columns));
00123 
00124     if (!_use_env) {
00125        *linep = (int) lines;
00126        *colp = (int) columns;
00127     } else {                /* usually want to query LINES and COLUMNS from environment */
00128        int value;
00129 
00130        *linep = *colp = 0;
00131 
00132        /* first, look for environment variables */
00133        if ((value = _nc_getenv_num("LINES")) > 0) {
00134            *linep = value;
00135        }
00136        if ((value = _nc_getenv_num("COLUMNS")) > 0) {
00137            *colp = value;
00138        }
00139        T(("screen size: environment LINES = %d COLUMNS = %d", *linep, *colp));
00140 
00141 #ifdef __EMX__
00142        if (*linep <= 0 || *colp <= 0) {
00143            int screendata[2];
00144            _scrsize(screendata);
00145            *colp = screendata[0];
00146            *linep = screendata[1];
00147            T(("EMX screen size: environment LINES = %d COLUMNS = %d",
00148               *linep, *colp));
00149        }
00150 #endif
00151 #if HAVE_SIZECHANGE
00152        /* if that didn't work, maybe we can try asking the OS */
00153        if (*linep <= 0 || *colp <= 0) {
00154            if (isatty(cur_term->Filedes)) {
00155               STRUCT_WINSIZE size;
00156 
00157               errno = 0;
00158               do {
00159                   if (ioctl(cur_term->Filedes, IOCTL_WINSIZE, &size) < 0
00160                      && errno != EINTR)
00161                      goto failure;
00162               } while
00163                   (errno == EINTR);
00164 
00165               /*
00166                * Solaris lets users override either dimension with an
00167                * environment variable.
00168                */
00169               if (*linep <= 0)
00170                   *linep = WINSIZE_ROWS(size);
00171               if (*colp <= 0)
00172                   *colp = WINSIZE_COLS(size);
00173            }
00174            /* FALLTHRU */
00175          failure:;
00176        }
00177 #endif /* HAVE_SIZECHANGE */
00178 
00179        /* if we can't get dynamic info about the size, use static */
00180        if (*linep <= 0) {
00181            *linep = (int) lines;
00182        }
00183        if (*colp <= 0) {
00184            *colp = (int) columns;
00185        }
00186 
00187        /* the ultimate fallback, assume fixed 24x80 size */
00188        if (*linep <= 0) {
00189            *linep = 24;
00190        }
00191        if (*colp <= 0) {
00192            *colp = 80;
00193        }
00194 
00195        /*
00196         * Put the derived values back in the screen-size caps, so
00197         * tigetnum() and tgetnum() will do the right thing.
00198         */
00199        lines = (short) (*linep);
00200        columns = (short) (*colp);
00201     }
00202 
00203     T(("screen size is %dx%d", *linep, *colp));
00204 
00205     if (VALID_NUMERIC(init_tabs))
00206        TABSIZE = (int) init_tabs;
00207     else
00208        TABSIZE = 8;
00209     T(("TABSIZE = %d", TABSIZE));
00210 }
00211 
00212 #if USE_SIZECHANGE
00213 NCURSES_EXPORT(void)
00214 _nc_update_screensize(void)
00215 {
00216     int old_lines = lines;
00217     int new_lines;
00218     int old_cols = columns;
00219     int new_cols;
00220 
00221     _nc_get_screensize(&new_lines, &new_cols);
00222 
00223     /*
00224      * See is_term_resized() and resizeterm().
00225      * We're doing it this way because those functions belong to the upper
00226      * ncurses library, while this resides in the lower terminfo library.
00227      */
00228     if (SP != 0
00229        && SP->_resize != 0) {
00230        if ((new_lines != old_lines) || (new_cols != old_cols))
00231            SP->_resize(new_lines, new_cols);
00232        SP->_sig_winch = FALSE;
00233     }
00234 }
00235 #endif
00236 
00237 /****************************************************************************
00238  *
00239  * Terminal setup
00240  *
00241  ****************************************************************************/
00242 
00243 #define ret_error(code, fmt, arg)  if (errret) {\
00244                                        *errret = code;\
00245                                        returnCode(ERR);\
00246                                    } else {\
00247                                        fprintf(stderr, fmt, arg);\
00248                                        exit(EXIT_FAILURE);\
00249                                    }
00250 
00251 #define ret_error0(code, msg)             if (errret) {\
00252                                        *errret = code;\
00253                                        returnCode(ERR);\
00254                                    } else {\
00255                                        fprintf(stderr, msg);\
00256                                        exit(EXIT_FAILURE);\
00257                                    }
00258 
00259 #if USE_DATABASE || USE_TERMCAP
00260 static int
00261 grab_entry(const char *const tn, TERMTYPE *const tp)
00262 /* return 1 if entry found, 0 if not found, -1 if database not accessible */
00263 {
00264 #if USE_DATABASE
00265     char filename[PATH_MAX];
00266 #endif
00267     int status;
00268 
00269     /*
00270      * $TERM shouldn't contain pathname delimiters.
00271      */
00272     if (strchr(tn, '/'))
00273        return 0;
00274 
00275 #if USE_DATABASE
00276     if ((status = _nc_read_entry(tn, filename, tp)) != 1) {
00277 
00278 #if !PURE_TERMINFO
00279        /*
00280         * Try falling back on the termcap file.
00281         * Note:  allowing this call links the entire terminfo/termcap
00282         * compiler into the startup code.  It's preferable to build a
00283         * real terminfo database and use that.
00284         */
00285        status = _nc_read_termcap_entry(tn, tp);
00286 #endif /* PURE_TERMINFO */
00287 
00288     }
00289 #else
00290     status = _nc_read_termcap_entry(tn, tp);
00291 #endif
00292 
00293     /*
00294      * If we have an entry, force all of the cancelled strings to null
00295      * pointers so we don't have to test them in the rest of the library.
00296      * (The terminfo compiler bypasses this logic, since it must know if
00297      * a string is cancelled, for merging entries).
00298      */
00299     if (status == 1) {
00300        unsigned n;
00301        for_each_boolean(n, tp) {
00302            if (!VALID_BOOLEAN(tp->Booleans[n]))
00303               tp->Booleans[n] = FALSE;
00304        }
00305        for_each_string(n, tp) {
00306            if (tp->Strings[n] == CANCELLED_STRING)
00307               tp->Strings[n] = ABSENT_STRING;
00308        }
00309     }
00310     return (status);
00311 }
00312 #endif
00313 
00314 /*
00315 **     do_prototype()
00316 **
00317 **     Take the real command character out of the CC environment variable
00318 **     and substitute it in for the prototype given in 'command_character'.
00319 **
00320 */
00321 static void
00322 do_prototype(void)
00323 {
00324     int i;
00325     char CC;
00326     char proto;
00327     char *tmp;
00328 
00329     tmp = getenv("CC");
00330     CC = *tmp;
00331     proto = *command_character;
00332 
00333     for_each_string(i, &(cur_term->type)) {
00334        for (tmp = cur_term->type.Strings[i]; *tmp; tmp++) {
00335            if (*tmp == proto)
00336               *tmp = CC;
00337        }
00338     }
00339 }
00340 
00341 /*
00342  * Find the locale which is in effect.
00343  */
00344 NCURSES_EXPORT(char *)
00345 _nc_get_locale(void)
00346 {
00347     char *env;
00348 #if HAVE_LOCALE_H
00349     /*
00350      * This is preferable to using getenv() since it ensures that we are using
00351      * the locale which was actually initialized by the application.
00352      */
00353     env = setlocale(LC_CTYPE, 0);
00354 #else
00355     if (((env = getenv("LC_ALL")) != 0 && *env != '\0')
00356        || ((env = getenv("LC_CTYPE")) != 0 && *env != '\0')
00357        || ((env = getenv("LANG")) != 0 && *env != '\0')) {
00358        ;
00359     }
00360 #endif
00361     T(("_nc_get_locale %s", _nc_visbuf(env)));
00362     return env;
00363 }
00364 
00365 /*
00366  * Check if we are running in a UTF-8 locale.
00367  */
00368 NCURSES_EXPORT(int)
00369 _nc_unicode_locale(void)
00370 {
00371     int result = 0;
00372 #if HAVE_LANGINFO_CODESET
00373     char *env = nl_langinfo(CODESET);
00374     result = !strcmp(env, "UTF-8");
00375     T(("_nc_unicode_locale(%s) ->%d", env, result));
00376 #else
00377     char *env = _nc_get_locale();
00378     if (env != 0) {
00379        if (strstr(env, ".UTF-8") != 0) {
00380            result = 1;
00381            T(("_nc_unicode_locale(%s) ->%d", env, result));
00382        }
00383     }
00384 #endif
00385     return result;
00386 }
00387 
00388 #define CONTROL_N(s) ((s) != 0 && strstr(s, "\016") != 0)
00389 #define CONTROL_O(s) ((s) != 0 && strstr(s, "\017") != 0)
00390 
00391 /*
00392  * Check for known broken cases where a UTF-8 locale breaks the alternate
00393  * character set.
00394  */
00395 NCURSES_EXPORT(int)
00396 _nc_locale_breaks_acs(void)
00397 {
00398     char *env = getenv("TERM");
00399     if (env != 0) {
00400        if (strstr(env, "linux"))
00401            return 1;        /* always broken */
00402        if (strstr(env, "screen") != 0
00403            && ((env = getenv("TERMCAP")) != 0
00404               && strstr(env, "screen") != 0)
00405            && strstr(env, "hhII00") != 0) {
00406            if (CONTROL_N(enter_alt_charset_mode) ||
00407               CONTROL_O(enter_alt_charset_mode) ||
00408               CONTROL_N(set_attributes) ||
00409               CONTROL_O(set_attributes))
00410               return 1;
00411        }
00412     }
00413     return 0;
00414 }
00415 
00416 /*
00417  *     setupterm(termname, Filedes, errret)
00418  *
00419  *     Find and read the appropriate object file for the terminal
00420  *     Make cur_term point to the structure.
00421  *
00422  */
00423 
00424 NCURSES_EXPORT(int)
00425 setupterm(NCURSES_CONST char *tname, int Filedes, int *errret)
00426 {
00427     int status;
00428 
00429     START_TRACE();
00430     T((T_CALLED("setupterm(%s,%d,%p)"), _nc_visbuf(tname), Filedes, errret));
00431 
00432     if (tname == 0) {
00433        tname = getenv("TERM");
00434        if (tname == 0 || *tname == '\0') {
00435            ret_error0(-1, "TERM environment variable not set.\n");
00436        }
00437     }
00438     if (strlen(tname) > MAX_NAME_SIZE) {
00439        ret_error(-1, "TERM environment must be <= %d characters.\n",
00440                 MAX_NAME_SIZE);
00441     }
00442 
00443     T(("your terminal name is %s", tname));
00444 
00445     /*
00446      * Allow output redirection.  This is what SVr3 does.  If stdout is
00447      * directed to a file, screen updates go to standard error.
00448      */
00449     if (Filedes == STDOUT_FILENO && !isatty(Filedes))
00450        Filedes = STDERR_FILENO;
00451 
00452     /*
00453      * Check if we have already initialized to use this terminal.  If so, we
00454      * do not need to re-read the terminfo entry, or obtain TTY settings.
00455      *
00456      * This is an improvement on SVr4 curses.  If an application mixes curses
00457      * and termcap calls, it may call both initscr and tgetent.  This is not
00458      * really a good thing to do, but can happen if someone tries using ncurses
00459      * with the readline library.  The problem we are fixing is that when
00460      * tgetent calls setupterm, the resulting Ottyb struct in cur_term is
00461      * zeroed.  A subsequent call to endwin uses the zeroed terminal settings
00462      * rather than the ones saved in initscr.  So we check if cur_term appears
00463      * to contain terminal settings for the same output file as our current
00464      * call - and copy those terminal settings.  (SVr4 curses does not do this,
00465      * however applications that are working around the problem will still work
00466      * properly with this feature).
00467      */
00468     if (cur_term != 0
00469        && cur_term->Filedes == Filedes
00470        && cur_term->_termname != 0
00471        && !strcmp(cur_term->_termname, tname)
00472        && _nc_name_match(cur_term->type.term_names, tname, "|")) {
00473        T(("reusing existing terminal information and mode-settings"));
00474     } else {
00475        TERMINAL *term_ptr;
00476 
00477        term_ptr = typeCalloc(TERMINAL, 1);
00478 
00479        if (term_ptr == 0) {
00480            ret_error0(-1,
00481                      "Not enough memory to create terminal structure.\n");
00482        }
00483 #if USE_DATABASE || USE_TERMCAP
00484        status = grab_entry(tname, &term_ptr->type);
00485 #else
00486        status = 0;
00487 #endif
00488 
00489        /* try fallback list if entry on disk */
00490        if (status != 1) {
00491            const TERMTYPE *fallback = _nc_fallback(tname);
00492 
00493            if (fallback) {
00494               term_ptr->type = *fallback;
00495               status = 1;
00496            }
00497        }
00498 
00499        if (status <= 0) {
00500            del_curterm(term_ptr);
00501            if (status == -1) {
00502               ret_error0(-1, "terminals database is inaccessible\n");
00503            } else if (status == 0) {
00504               ret_error(0, "'%s': unknown terminal type.\n", tname);
00505            }
00506        }
00507 
00508        set_curterm(term_ptr);
00509 
00510        if (command_character && getenv("CC"))
00511            do_prototype();
00512 
00513        strncpy(ttytype, cur_term->type.term_names, NAMESIZE - 1);
00514        ttytype[NAMESIZE - 1] = '\0';
00515 
00516        cur_term->Filedes = Filedes;
00517        cur_term->_termname = strdup(tname);
00518 
00519        /*
00520         * If an application calls setupterm() rather than initscr() or
00521         * newterm(), we will not have the def_prog_mode() call in
00522         * _nc_setupscreen().  Do it now anyway, so we can initialize the
00523         * baudrate.
00524         */
00525        if (isatty(Filedes)) {
00526            def_prog_mode();
00527            baudrate();
00528        }
00529     }
00530 
00531     /*
00532      * We should always check the screensize, just in case.
00533      */
00534     _nc_get_screensize(&LINES, &COLS);
00535 
00536     if (errret)
00537        *errret = 1;
00538 
00539     T((T_CREATE("screen %s %dx%d"), tname, LINES, COLS));
00540 
00541     if (generic_type) {
00542        ret_error(0, "'%s': I need something more specific.\n", tname);
00543     }
00544     if (hard_copy) {
00545        ret_error(1, "'%s': I can't handle hardcopy terminals.\n", tname);
00546     }
00547     returnCode(OK);
00548 }