150276Speter/****************************************************************************
2262685Sdelphij * Copyright (c) 1998-2007,2008 Free Software Foundation, Inc.              *
350276Speter *                                                                          *
450276Speter * Permission is hereby granted, free of charge, to any person obtaining a  *
550276Speter * copy of this software and associated documentation files (the            *
650276Speter * "Software"), to deal in the Software without restriction, including      *
750276Speter * without limitation the rights to use, copy, modify, merge, publish,      *
850276Speter * distribute, distribute with modifications, sublicense, and/or sell       *
950276Speter * copies of the Software, and to permit persons to whom the Software is    *
1050276Speter * furnished to do so, subject to the following conditions:                 *
1150276Speter *                                                                          *
1250276Speter * The above copyright notice and this permission notice shall be included  *
1350276Speter * in all copies or substantial portions of the Software.                   *
1450276Speter *                                                                          *
1550276Speter * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
1650276Speter * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
1750276Speter * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
1850276Speter * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
1950276Speter * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
2050276Speter * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
2150276Speter * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
2250276Speter *                                                                          *
2350276Speter * Except as contained in this notice, the name(s) of the above copyright   *
2450276Speter * holders shall not be used in advertising or otherwise to promote the     *
2550276Speter * sale, use or other dealings in this Software without prior written       *
2650276Speter * authorization.                                                           *
2750276Speter ****************************************************************************/
2850276Speter
2950276Speter/****************************************************************************
30166124Srafan *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
3150276Speter *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
3250276Speter *     and: Thomas E. Dickey                        1996-on                 *
3350276Speter ****************************************************************************/
34166124Srafan
35174993Srafan/*
36166124Srafan * Terminal setup routines common to termcap and terminfo:
3766963Speter *
3850276Speter *		use_env(bool)
39262685Sdelphij *		setupterm(char *, int, int *)
4050276Speter */
41262685Sdelphij
42262685Sdelphij#include <curses.priv.h>
43262685Sdelphij#include <tic.h>		/* for MAX_NAME_SIZE */
44262685Sdelphij#include <term_entry.h>
45262685Sdelphij
46262685Sdelphij#if SVR4_TERMIO && !defined(_POSIX_SOURCE)
47262685Sdelphij#define _POSIX_SOURCE
48262685Sdelphij#endif
4997049Speter
5097049Speter#if HAVE_LOCALE_H
5176726Speter#include <locale.h>
5297049Speter#endif
5397049Speter
5497049Speter#include <term.h>		/* lines, columns, cur_term */
55174993Srafan
5697049SpeterMODULE_ID("$Id: lib_setup.c,v 1.111 2008/08/03 22:42:33 tom Exp $")
5797049Speter
5897049Speter/****************************************************************************
5997049Speter *
6097049Speter * Terminal size computation
61174993Srafan *
6297049Speter ****************************************************************************/
63262685Sdelphij
6497049Speter#if HAVE_SIZECHANGE
6597049Speter# if !defined(sun) || !TERMIOS
6697049Speter#  if HAVE_SYS_IOCTL_H
6797049Speter#   include <sys/ioctl.h>
6897049Speter#  endif
6997049Speter# endif
7097049Speter#endif
7197049Speter
7297049Speter#if NEED_PTEM_H
7397049Speter /* On SCO, they neglected to define struct winsize in termios.h -- it's only
7497049Speter  * in termio.h and ptem.h (the former conflicts with other definitions).
7597049Speter  */
76166124Srafan# include <sys/stream.h>
77166124Srafan# include <sys/ptem.h>
78166124Srafan#endif
79166124Srafan
80166124Srafan#if HAVE_LANGINFO_CODESET
8150276Speter#include <langinfo.h>
82166124Srafan#endif
83166124Srafan
84166124Srafan/*
85166124Srafan * SCO defines TIOCGSIZE and the corresponding struct.  Other systems (SunOS,
86166124Srafan * Solaris, IRIX) define TIOCGWINSZ and struct winsize.
87166124Srafan */
88166124Srafan#ifdef TIOCGSIZE
89166124Srafan# define IOCTL_WINSIZE TIOCGSIZE
90166124Srafan# define STRUCT_WINSIZE struct ttysize
91166124Srafan# define WINSIZE_ROWS(n) (int)n.ts_lines
92166124Srafan# define WINSIZE_COLS(n) (int)n.ts_cols
93166124Srafan#else
94166124Srafan# ifdef TIOCGWINSZ
95166124Srafan#  define IOCTL_WINSIZE TIOCGWINSZ
96166124Srafan#  define STRUCT_WINSIZE struct winsize
97166124Srafan#  define WINSIZE_ROWS(n) (int)n.ws_row
9866963Speter#  define WINSIZE_COLS(n) (int)n.ws_col
99166124Srafan# endif
100166124Srafan#endif
10166963Speter
102166124Srafan/*
103166124Srafan * Reduce explicit use of "cur_term" global variable.
10466963Speter */
105166124Srafan#undef CUR
106262629Sdelphij#define CUR termp->type.
10766963Speter
10866963Speter/*
109166124Srafan * Wrap global variables in this module.
110166124Srafan */
111166124Srafan#if USE_REENTRANT
112166124SrafanNCURSES_EXPORT(char *)
113166124SrafanNCURSES_PUBLIC_VAR(ttytype) (void)
114166124Srafan{
11576726Speter    static char empty[] = "";
11666963Speter    return cur_term ? cur_term->type.term_names : empty;
11766963Speter}
118262685SdelphijNCURSES_EXPORT(int *)
119262685Sdelphij_nc_ptr_Lines(void)
120262685Sdelphij{
121262685Sdelphij    return ptrLines();
122262685Sdelphij}
12366963SpeterNCURSES_EXPORT(int)
12466963SpeterNCURSES_PUBLIC_VAR(LINES) (void)
12566963Speter{
12666963Speter    return *_nc_ptr_Lines();
127262685Sdelphij}
12866963SpeterNCURSES_EXPORT(int *)
129262685Sdelphij_nc_ptr_Cols(void)
130262685Sdelphij{
13166963Speter    return ptrCols();
13266963Speter}
13366963SpeterNCURSES_EXPORT(int)
13466963SpeterNCURSES_PUBLIC_VAR(COLS) (void)
135262685Sdelphij{
13666963Speter    return *_nc_ptr_Cols();
137262685Sdelphij}
138262685SdelphijNCURSES_EXPORT(int)
139262685SdelphijNCURSES_PUBLIC_VAR(TABSIZE) (void)
14050276Speter{
141262685Sdelphij    return SP ? SP->_TABSIZE : 8;
142262685Sdelphij}
14366963Speter#else
144262685SdelphijNCURSES_EXPORT_VAR(char) ttytype[NAMESIZE] = "";
14550276SpeterNCURSES_EXPORT_VAR(int) LINES = 0;
14666963SpeterNCURSES_EXPORT_VAR(int) COLS = 0;
147166124SrafanNCURSES_EXPORT_VAR(int) TABSIZE = 0;
148166124Srafan#endif
149166124Srafan
150166124Srafan#if NCURSES_EXT_FUNCS
151166124SrafanNCURSES_EXPORT(int)
152166124Srafanset_tabsize(int value)
153166124Srafan{
154262685Sdelphij    int code = OK;
155166124Srafan#if USE_REENTRANT
156166124Srafan    if (SP) {
157166124Srafan	SP->_TABSIZE = value;
158166124Srafan    } else {
159166124Srafan	code = ERR;
160166124Srafan    }
161166124Srafan#else
162166124Srafan    TABSIZE = value;
163166124Srafan#endif
164166124Srafan    return code;
165166124Srafan}
166166124Srafan#endif
167262685Sdelphij
168166124Srafan#if USE_SIGWINCH
169166124Srafan/*
170166124Srafan * If we have a pending SIGWINCH, set the flag in each screen.
171166124Srafan */
172166124SrafanNCURSES_EXPORT(int)
17366963Speter_nc_handle_sigwinch(SCREEN *sp)
17466963Speter{
17566963Speter    SCREEN *scan;
17666963Speter
17766963Speter    if (_nc_globals.have_sigwinch) {
17876726Speter	_nc_globals.have_sigwinch = 0;
17966963Speter
18066963Speter	for (each_screen(scan)) {
18166963Speter	    scan->_sig_winch = TRUE;
18266963Speter	}
18366963Speter    }
18466963Speter
18566963Speter    return (sp ? sp->_sig_winch : 0);
18676726Speter}
18766963Speter
18866963Speter#endif
189262685Sdelphij
190262685SdelphijNCURSES_EXPORT(void)
19166963Speteruse_env(bool f)
19266963Speter{
193    T((T_CALLED("use_env()")));
194    _nc_prescreen.use_env = f;
195    returnVoid;
196}
197
198NCURSES_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
304NCURSES_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 */
356static int
357grab_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*/
389static void
390do_prototype(TERMINAL * termp)
391{
392    unsigned i;
393    char CC;
394    char proto;
395    char *tmp;
396
397    if ((tmp = getenv("CC")) != 0) {
398	if ((CC = *tmp) != 0) {
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
411/*
412 * Find the locale which is in effect.
413 */
414NCURSES_EXPORT(char *)
415_nc_get_locale(void)
416{
417    char *env;
418#if HAVE_LOCALE_H
419    /*
420     * This is preferable to using getenv() since it ensures that we are using
421     * the locale which was actually initialized by the application.
422     */
423    env = setlocale(LC_CTYPE, 0);
424#else
425    if (((env = getenv("LC_ALL")) != 0 && *env != '\0')
426	|| ((env = getenv("LC_CTYPE")) != 0 && *env != '\0')
427	|| ((env = getenv("LANG")) != 0 && *env != '\0')) {
428	;
429    }
430#endif
431    T(("_nc_get_locale %s", _nc_visbuf(env)));
432    return env;
433}
434
435/*
436 * Check if we are running in a UTF-8 locale.
437 */
438NCURSES_EXPORT(int)
439_nc_unicode_locale(void)
440{
441    int result = 0;
442#if HAVE_LANGINFO_CODESET
443    char *env = nl_langinfo(CODESET);
444    result = !strcmp(env, "UTF-8");
445    T(("_nc_unicode_locale(%s) ->%d", env, result));
446#else
447    char *env = _nc_get_locale();
448    if (env != 0) {
449	if (strstr(env, ".UTF-8") != 0) {
450	    result = 1;
451	    T(("_nc_unicode_locale(%s) ->%d", env, result));
452	}
453    }
454#endif
455    return result;
456}
457
458#define CONTROL_N(s) ((s) != 0 && strstr(s, "\016") != 0)
459#define CONTROL_O(s) ((s) != 0 && strstr(s, "\017") != 0)
460
461/*
462 * Check for known broken cases where a UTF-8 locale breaks the alternate
463 * character set.
464 */
465NCURSES_EXPORT(int)
466_nc_locale_breaks_acs(TERMINAL * termp)
467{
468    char *env;
469
470    if ((env = getenv("NCURSES_NO_UTF8_ACS")) != 0) {
471	return atoi(env);
472    } else if ((env = getenv("TERM")) != 0) {
473	if (strstr(env, "linux"))
474	    return 1;		/* always broken */
475	if (strstr(env, "screen") != 0
476	    && ((env = getenv("TERMCAP")) != 0
477		&& strstr(env, "screen") != 0)
478	    && strstr(env, "hhII00") != 0) {
479	    if (CONTROL_N(enter_alt_charset_mode) ||
480		CONTROL_O(enter_alt_charset_mode) ||
481		CONTROL_N(set_attributes) ||
482		CONTROL_O(set_attributes))
483		return 1;
484	}
485    }
486    return 0;
487}
488
489/*
490 * This entrypoint is called from tgetent() to allow a special case of reusing
491 * the same TERMINAL data (see comment).
492 */
493NCURSES_EXPORT(int)
494_nc_setupterm(NCURSES_CONST char *tname, int Filedes, int *errret, bool reuse)
495{
496    TERMINAL *termp;
497    int status;
498
499    START_TRACE();
500    T((T_CALLED("setupterm(%s,%d,%p)"), _nc_visbuf(tname), Filedes, errret));
501
502    if (tname == 0) {
503	tname = getenv("TERM");
504	if (tname == 0 || *tname == '\0') {
505	    ret_error0(TGETENT_ERR, "TERM environment variable not set.\n");
506	}
507    }
508
509    if (strlen(tname) > MAX_NAME_SIZE) {
510	ret_error(TGETENT_ERR,
511		  "TERM environment must be <= %d characters.\n",
512		  MAX_NAME_SIZE);
513    }
514
515    T(("your terminal name is %s", tname));
516
517    /*
518     * Allow output redirection.  This is what SVr3 does.  If stdout is
519     * directed to a file, screen updates go to standard error.
520     */
521    if (Filedes == STDOUT_FILENO && !isatty(Filedes))
522	Filedes = STDERR_FILENO;
523
524    /*
525     * Check if we have already initialized to use this terminal.  If so, we
526     * do not need to re-read the terminfo entry, or obtain TTY settings.
527     *
528     * This is an improvement on SVr4 curses.  If an application mixes curses
529     * and termcap calls, it may call both initscr and tgetent.  This is not
530     * really a good thing to do, but can happen if someone tries using ncurses
531     * with the readline library.  The problem we are fixing is that when
532     * tgetent calls setupterm, the resulting Ottyb struct in cur_term is
533     * zeroed.  A subsequent call to endwin uses the zeroed terminal settings
534     * rather than the ones saved in initscr.  So we check if cur_term appears
535     * to contain terminal settings for the same output file as our current
536     * call - and copy those terminal settings.  (SVr4 curses does not do this,
537     * however applications that are working around the problem will still work
538     * properly with this feature).
539     */
540    if (reuse
541	&& (termp = cur_term) != 0
542	&& termp->Filedes == Filedes
543	&& termp->_termname != 0
544	&& !strcmp(termp->_termname, tname)
545	&& _nc_name_match(termp->type.term_names, tname, "|")) {
546	T(("reusing existing terminal information and mode-settings"));
547    } else {
548
549	termp = typeCalloc(TERMINAL, 1);
550
551	if (termp == 0) {
552	    ret_error0(TGETENT_ERR,
553		       "Not enough memory to create terminal structure.\n");
554	}
555#if USE_DATABASE || USE_TERMCAP
556	status = grab_entry(tname, &termp->type);
557#else
558	status = TGETENT_NO;
559#endif
560
561	/* try fallback list if entry on disk */
562	if (status != TGETENT_YES) {
563	    const TERMTYPE *fallback = _nc_fallback(tname);
564
565	    if (fallback) {
566		termp->type = *fallback;
567		status = TGETENT_YES;
568	    }
569	}
570
571	if (status != TGETENT_YES) {
572	    del_curterm(termp);
573	    if (status == TGETENT_ERR) {
574		ret_error0(status, "terminals database is inaccessible\n");
575	    } else if (status == TGETENT_NO) {
576		ret_error(status, "'%s': unknown terminal type.\n", tname);
577	    }
578	}
579#if !USE_REENTRANT
580	strncpy(ttytype, termp->type.term_names, NAMESIZE - 1);
581	ttytype[NAMESIZE - 1] = '\0';
582#endif
583
584	termp->Filedes = Filedes;
585	termp->_termname = strdup(tname);
586
587	set_curterm(termp);
588
589	if (command_character && getenv("CC"))
590	    do_prototype(termp);
591
592	/*
593	 * If an application calls setupterm() rather than initscr() or
594	 * newterm(), we will not have the def_prog_mode() call in
595	 * _nc_setupscreen().  Do it now anyway, so we can initialize the
596	 * baudrate.
597	 */
598	if (isatty(Filedes)) {
599	    def_prog_mode();
600	    baudrate();
601	}
602    }
603
604    /*
605     * We should always check the screensize, just in case.
606     */
607    _nc_get_screensize(SP, ptrLines(), ptrCols());
608
609    if (errret)
610	*errret = TGETENT_YES;
611
612    if (generic_type) {
613	ret_error(TGETENT_NO, "'%s': I need something more specific.\n", tname);
614    }
615    if (hard_copy) {
616	ret_error(TGETENT_YES, "'%s': I can't handle hardcopy terminals.\n", tname);
617    }
618    returnCode(OK);
619}
620
621/*
622 *	setupterm(termname, Filedes, errret)
623 *
624 *	Find and read the appropriate object file for the terminal
625 *	Make cur_term point to the structure.
626 */
627NCURSES_EXPORT(int)
628setupterm(NCURSES_CONST char *tname, int Filedes, int *errret)
629{
630    return _nc_setupterm(tname, Filedes, errret, FALSE);
631}
632