xref: /netbsd-src/lib/libcurses/setterm.c (revision 0d34d14bb949d7e0fe657c29532de778397cd58d)
1 /*	$NetBSD: setterm.c,v 1.45 2009/07/22 16:57:15 roy Exp $	*/
2 
3 /*
4  * Copyright (c) 1981, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)setterm.c	8.8 (Berkeley) 10/25/94";
36 #else
37 __RCSID("$NetBSD: setterm.c,v 1.45 2009/07/22 16:57:15 roy Exp $");
38 #endif
39 #endif /* not lint */
40 
41 #include <sys/ioctl.h>		/* TIOCGWINSZ on old systems. */
42 
43 #include <stdlib.h>
44 #include <string.h>
45 #include <termios.h>
46 #include <unistd.h>
47 
48 #include "curses.h"
49 #include "curses_private.h"
50 
51 static int zap(SCREEN *screen);
52 
53 static int does_esc_m(char *cap);
54 static int does_ctrl_o(char *cap);
55 
56 static char	*sflags[] = {
57 /*	      am        bs        cc        da        eo */
58 	 &__tc_am, &__tc_bs, &__tc_cc, &__tc_da, &__tc_eo,
59 /*	      hc        hl        in        mi        ms */
60 	&__tc_hc, &__tc_hl, &__tc_in, &__tc_mi, &__tc_ms,
61 /*	      nc        ns        os        ul        ut */
62 	&__tc_nc, &__tc_ns, &__tc_os, &__tc_ul, &__tc_ut,
63 /*	      xb        xn        xt        xs        xx */
64 	&__tc_xb, &__tc_xn, &__tc_xt, &__tc_xs, &__tc_xx
65 };
66 
67 static int	*svals[] = {
68 /*	      pa        Co        NC */
69 	&__tc_pa, &__tc_Co, &__tc_NC
70 };
71 
72 static char	*_PC,
73 	**sstrs[] = {
74 	/*	      AB        ac        ae        AF        AL */
75 		&__tc_AB, &__tc_ac, &__tc_ae, &__tc_AF, &__tc_AL,
76 	/*	      al        as        bc        bl        bt */
77 		&__tc_al, &__tc_as, &__tc_bc, &__tc_bl, &__tc_bt,
78 	/*	      cd        ce        cl        cm        cr */
79 		&__tc_cd, &__tc_ce, &__tc_cl, &__tc_cm, &__tc_cr,
80 	/*	      cs        dc        DL        dl        dm */
81 		&__tc_cs, &__tc_dc, &__tc_DL, &__tc_dl, &__tc_dm,
82 	/*	      DO        do        eA        ed        ei */
83 		&__tc_DO, &__tc_do, &__tc_eA, &__tc_ed, &__tc_ei,
84 	/*	      ho        Ic        ic        im        Ip */
85 		&__tc_ho, &__tc_Ic, &__tc_ic, &__tc_im, &__tc_Ip,
86 	/*	      ip        k0        k1        k2        k3 */
87 		&__tc_ip, &__tc_k0, &__tc_k1, &__tc_k2, &__tc_k3,
88 	/*	      k4        k5        k6        k7        k8 */
89 		&__tc_k4, &__tc_k5, &__tc_k6, &__tc_k7, &__tc_k8,
90 	/*	      k9        kd        ke        kh        kl */
91 		&__tc_k9, &__tc_kd, &__tc_ke, &__tc_kh, &__tc_kl,
92 	/*	      kr        ks        ku        LE        ll */
93 		&__tc_kr, &__tc_ks, &__tc_ku, &__tc_LE, &__tc_ll,
94 	/*	      ma        mb        md        me        mh */
95 		&__tc_ma, &__tc_mb, &__tc_md, &__tc_me, &__tc_mh,
96 	/*	      mk        mm        mo        mp        mr */
97 		&__tc_mk, &__tc_mm, &__tc_mo, &__tc_mp, &__tc_mr,
98 	/*	      nd        nl        oc        op    pc     */
99 		&__tc_nd, &__tc_nl, &__tc_oc, &__tc_op, &_PC,
100 	/*	      rc        RI        sc        Sb        se */
101 		&__tc_rc, &__tc_RI, &__tc_Sb, &__tc_sc, &__tc_se,
102 	/*	      SF        Sf        sf        so        sp */
103 		&__tc_SF, &__tc_Sf, &__tc_sf, &__tc_so, &__tc_sp,
104 	/*	      SR        sr        ta        te        ti */
105 		&__tc_SR, &__tc_sr, &__tc_ta, &__tc_te, &__tc_ti,
106 	/*	      uc        ue        UP        up        us */
107 		&__tc_uc, &__tc_ue, &__tc_UP, &__tc_up, &__tc_us,
108 #ifndef HAVE_WCHAR
109 	/*	      vb        ve        vi        vs           */
110 		&__tc_vb, &__tc_ve, &__tc_vi, &__tc_vs
111 #else
112 	/*	      vb        ve        vi        vs        Xh */
113 		&__tc_vb, &__tc_ve, &__tc_vi, &__tc_vs, &__tc_Xh,
114 	/*	      Xl        Xo        Xr        Xt        Xv */
115 		&__tc_Xl, &__tc_Xo, &__tc_Xr, &__tc_Xt, &__tc_Xv
116 #endif /* HAVE_WCHAR */
117 	};
118 
119 attr_t	 __mask_op, __mask_me, __mask_ue, __mask_se;
120 
121 int
122 setterm(char *type)
123 {
124 	return _cursesi_setterm(type, _cursesi_screen);
125 }
126 
127 int
128 _cursesi_setterm(char *type, SCREEN *screen)
129 {
130 	int unknown;
131 	struct winsize win;
132 	char *p;
133 	char cm_buff[64];
134 
135 	if (type[0] == '\0')
136 		type = "xx";
137 	unknown = 0;
138 	if (t_getent(&screen->cursesi_genbuf, type) != 1) {
139 		unknown++;
140 	}
141 #ifdef DEBUG
142 	__CTRACE(__CTRACE_INIT, "setterm: tty = %s\n", type);
143 #endif
144 
145 	/* Try TIOCGWINSZ, and, if it fails, the termcap entry. */
146 	if (ioctl(fileno(screen->outfd), TIOCGWINSZ, &win) != -1 &&
147 	    win.ws_row != 0 && win.ws_col != 0) {
148 		screen->LINES = win.ws_row;
149 		screen->COLS = win.ws_col;
150 	}  else {
151 		if (unknown) {
152 			screen->LINES = -1;
153 			screen->COLS = -1;
154 		} else {
155 			screen->LINES = t_getnum(screen->cursesi_genbuf, "li");
156 			screen->COLS = t_getnum(screen->cursesi_genbuf, "co");
157 		}
158 
159 	}
160 
161 	/* POSIX 1003.2 requires that the environment override. */
162 	if ((p = getenv("LINES")) != NULL)
163 		screen->LINES = (int) strtol(p, NULL, 0);
164 	if ((p = getenv("COLUMNS")) != NULL)
165 		screen->COLS = (int) strtol(p, NULL, 0);
166 	if ((p = getenv("ESCDELAY")) != NULL)
167 		ESCDELAY = (int) strtol(p, NULL, 0);
168 
169 
170 	/*
171 	 * Want cols > 4, otherwise things will fail.
172 	 */
173 	if (screen->COLS <= 4)
174 		return (ERR);
175 
176 	LINES = screen->LINES;
177 	COLS = screen->COLS;
178 
179 #ifdef DEBUG
180 	__CTRACE(__CTRACE_INIT, "setterm: LINES = %d, COLS = %d\n",
181 	    LINES, COLS);
182 #endif
183 	if (!unknown) {
184 		if (zap(screen) == ERR) /* Get terminal description.*/
185 			return ERR;
186 	}
187 
188 	/* If we can't tab, we can't backtab, either. */
189 	if (!screen->GT)
190 		screen->tc_bt = NULL;
191 
192 	/*
193 	 * Test for cursor motion capability.
194 	 *
195 	 */
196 	if (t_goto(NULL, screen->tc_cm, 0, 0, cm_buff, sizeof(cm_buff) - 1) < 0) {
197 		screen->CA = 0;
198 		screen->tc_cm = 0;
199 	} else
200 		screen->CA = 1;
201 
202 	/*
203 	 * set the pad char, only take the first char of the pc capability
204 	 * as this is all we can use.
205 	 */
206 	screen->padchar = screen->tc_pc ? screen->tc_pc[0] : 0;
207 
208 	/* Get full name of terminal */
209 	if (unknown) {
210 		strcpy(screen->ttytype, "dumb");
211 	} else {
212 		char *tcptr;
213 		size_t limit = 0;
214 		if (t_getterm(screen->cursesi_genbuf, 0, &limit))
215 			return ERR;
216 		if ((tcptr = malloc(limit + 1)) == NULL)
217 			return ERR;
218 		if (t_getterm(screen->cursesi_genbuf, &tcptr, 0) < 0)
219  			return ERR;
220 		__longname(tcptr, screen->ttytype);
221 		free(tcptr);
222 	}
223 
224 	/* If no scrolling commands, no quick change. */
225 	screen->noqch =
226   	    (screen->tc_cs == NULL || screen->tc_ho == NULL ||
227 	    (screen->tc_SF == NULL && screen->tc_sf == NULL) ||
228 	     (screen->tc_SR == NULL && screen->tc_sr == NULL)) &&
229 	    ((screen->tc_AL == NULL && screen->tc_al == NULL) ||
230 	     (screen->tc_DL == NULL && screen->tc_dl == NULL));
231 
232 	/*
233 	 * Precalculate conflict info for color/attribute end commands.
234 	 */
235 #ifndef HAVE_WCHAR
236 	screen->mask_op = __ATTRIBUTES & ~__COLOR;
237 #else
238 	screen->mask_op = WA_ATTRIBUTES & ~__COLOR;
239 #endif /* HAVE_WCHAR */
240 	if (screen->tc_op != NULL) {
241 		if (does_esc_m(screen->tc_op))
242 			screen->mask_op &=
243 			    ~(__STANDOUT | __UNDERSCORE | __TERMATTR);
244 		else {
245 			if (screen->tc_se != NULL &&
246 			    !strcmp(screen->tc_op, screen->tc_se))
247 				screen->mask_op &= ~__STANDOUT;
248 			if (screen->tc_ue != NULL &&
249 			    !strcmp(screen->tc_op, screen->tc_ue))
250 				screen->mask_op &= ~__UNDERSCORE;
251 			if (screen->tc_me != NULL &&
252 			    !strcmp(screen->tc_op, screen->tc_me))
253 				screen->mask_op &= ~__TERMATTR;
254 		}
255 	}
256 	/*
257 	 * Assume that "me" turns off all attributes apart from ACS.
258 	 * It might turn off ACS, so check for that.
259 	 */
260 	if (screen->tc_me != NULL && does_ctrl_o(screen->tc_me))
261 		screen->mask_me = 0;
262 	else
263 		screen->mask_me = __ALTCHARSET;
264 
265 	/* Check what turning off the attributes also turns off */
266 #ifndef HAVE_WCHAR
267 	screen->mask_ue = __ATTRIBUTES & ~__UNDERSCORE;
268 #else
269 	screen->mask_ue = WA_ATTRIBUTES & ~__UNDERSCORE;
270 #endif /* HAVE_WCHAR */
271 	if (screen->tc_ue != NULL) {
272 		if (does_esc_m(screen->tc_ue))
273 			screen->mask_ue &=
274 			    ~(__STANDOUT | __TERMATTR | __COLOR);
275 		else {
276 			if (screen->tc_se != NULL &&
277 			    !strcmp(screen->tc_ue, screen->tc_se))
278 				screen->mask_ue &= ~__STANDOUT;
279 			if (screen->tc_me != NULL &&
280 			    !strcmp(screen->tc_ue, screen->tc_me))
281 				screen->mask_ue &= ~__TERMATTR;
282 			if (screen->tc_op != NULL &&
283 			    !strcmp(screen->tc_ue, screen->tc_op))
284 				screen->mask_ue &= ~__COLOR;
285 		}
286 	}
287 #ifndef HAVE_WCHAR
288 	screen->mask_se = __ATTRIBUTES & ~__STANDOUT;
289 #else
290 	screen->mask_se = WA_ATTRIBUTES & ~__STANDOUT;
291 #endif /* HAVE_WCHAR */
292 	if (screen->tc_se != NULL) {
293 		if (does_esc_m(screen->tc_se))
294 			screen->mask_se &=
295 			    ~(__UNDERSCORE | __TERMATTR | __COLOR);
296 		else {
297 			if (screen->tc_ue != NULL &&
298 			    !strcmp(screen->tc_se, screen->tc_ue))
299 				screen->mask_se &= ~__UNDERSCORE;
300 			if (screen->tc_me != NULL &&
301 			    !strcmp(screen->tc_se, screen->tc_me))
302 				screen->mask_se &= ~__TERMATTR;
303 			if (screen->tc_op != NULL &&
304 			    !strcmp(screen->tc_se, screen->tc_op))
305 				screen->mask_se &= ~__COLOR;
306 		}
307 	}
308 
309 	return (unknown ? ERR : OK);
310 }
311 
312 /*
313  * _cursesi_resetterm --
314  *  Copy the terminal instance data for the given screen to the global
315  *  variables.
316  */
317 void
318 _cursesi_resetterm(SCREEN *screen)
319 {
320 	char ***sp, **scr_sp;
321 	int  **vp, *scr_vp, i;
322 	char **fp, *scr_fp;
323 
324 	LINES = screen->LINES;
325 	COLS = screen->COLS;
326 
327 	  /* reset terminal capabilities */
328 	fp = sflags;
329 	scr_fp = &screen->tc_am;
330 	for (i = 0; i < screen->flag_count; i++)
331 		*(*fp++) = *scr_fp++;
332 
333 	vp = svals;
334 	scr_vp = &screen->tc_pa;
335 	for (i = 0; i < screen->int_count; i++)
336 		*(*vp++) = *scr_vp++;
337 
338 	sp = sstrs;
339 	scr_sp = &screen->tc_AB;
340 	for (i = 0; i < screen->str_count; i++)
341 		*(*sp++) = *scr_sp++;
342 
343 	__GT = screen->GT;
344 	__CA = screen->CA;
345 
346 	PC = screen->padchar;
347 
348 	__noqch = screen->noqch;
349 	__mask_op = screen->mask_op;
350 	__mask_me = screen->mask_me;
351 	__mask_ue = screen->mask_ue;
352 	__mask_se = screen->mask_se;
353 }
354 
355 /*
356  * zap --
357  *	Gets all the terminal flags from the termcap database.
358  */
359 static int
360 zap(SCREEN *screen)
361 {
362 	const char *nampstr, *namp;
363         char **sp;
364 	int  *vp;
365 	char *fp;
366 	char tmp[3];
367 #ifdef DEBUG
368 	char	*cp;
369 #endif
370 	tmp[2] = '\0';
371 
372 	namp = "ambsccdaeohchlinmimsncnsosulutxbxnxtxsxx";
373 	fp = &screen->tc_am;
374 	screen->flag_count = 0;
375 	do {
376 		*tmp = *namp;
377 		*(tmp + 1) = *(namp + 1);
378 		*fp++ = t_getflag(screen->cursesi_genbuf, tmp);
379 #ifdef DEBUG
380 		__CTRACE(__CTRACE_INIT, "%2.2s = %s\n", namp,
381 		    fp[-1] ? "TRUE" : "FALSE");
382 #endif
383 		namp += 2;
384 		screen->flag_count++;
385 	} while (*namp);
386 	namp = "paCoNC";
387 	vp = &screen->tc_pa;
388 	screen->int_count = 0;
389 	do {
390 		*tmp = *namp;
391 		*(tmp + 1) = *(namp + 1);
392 		*vp++ = t_getnum(screen->cursesi_genbuf, tmp);
393 #ifdef DEBUG
394 		__CTRACE(__CTRACE_INIT, "%2.2s = %d\n", namp, vp[-1]);
395 #endif
396 		namp += 2;
397 		screen->int_count++;
398 	} while (*namp);
399 
400 #ifndef HAVE_WCHAR
401 	nampstr = "ABacaeAFALalasbcblbtcdceclcmcrcsdcDLdldmDOdoeAedeihoIcicimIpipk0k1k2k3k4k5k6k7k8k9kdkekhklkrkskuLEllmambmdmemhmkmmmompmrndnlocoppcrcRISbscseSFSfsfsospSRsrtatetiucueUPupusvbvevivs";
402 #else
403 	nampstr = "ABacaeAFALalasbcblbtcdceclcmcrcsdcDLdldmDOdoeAedeihoIcicimIpipk0k1k2k3k4k5k6k7k8k9kdkekhklkrkskuLEllmambmdmemhmkmmmompmrndnlocoppcrcRISbscseSFSfsfsospSRsrtatetiucueUPupusvbvevivsXhXlXoXrXtXv";
404 #endif /* HAVE_WCHAR */
405 
406 	namp = nampstr;
407 	sp = &screen->tc_AB;
408 	screen->str_count = 0;
409 	do {
410 		*tmp = *namp;
411 		*(tmp + 1) = *(namp + 1);
412 		*sp++ = t_agetstr(screen->cursesi_genbuf, tmp);
413 #ifdef DEBUG
414 		if (sp[-1] == NULL)
415 			__CTRACE(__CTRACE_INIT, "%2.2s = NULL\n", namp);
416 		else {
417 			__CTRACE(__CTRACE_INIT, "%2.2s = \"", namp);
418 			for (cp = sp[-1]; *cp; cp++)
419 				__CTRACE(__CTRACE_INIT, "%s", unctrl(*cp));
420 			__CTRACE(__CTRACE_INIT, "\"\n");
421 		}
422 #endif
423 		namp += 2;
424 		screen->str_count++;
425 	} while (*namp);
426 	if (screen->tc_xs)
427 		screen->tc_so = screen->tc_se = NULL;
428 	else {
429 		if (t_getnum(screen->cursesi_genbuf, "sg") > 0)
430 			screen->tc_so = NULL;
431 		if (t_getnum(screen->cursesi_genbuf, "ug") > 0)
432 			screen->tc_us = NULL;
433 		if (!screen->tc_so && screen->tc_us) {
434 			screen->tc_so = screen->tc_us;
435 			screen->tc_se = screen->tc_ue;
436 		}
437 	}
438 
439 	return OK;
440 }
441 
442 /*
443  * getcap --
444  *	Return a capability from termcap.
445  */
446 char	*
447 getcap(char *name)
448 {
449 	return (t_agetstr(_cursesi_screen->cursesi_genbuf, name));
450 }
451 
452 /*
453  * does_esc_m --
454  * A hack for xterm-like terminals where "\E[m" or "\E[0m" will turn off
455  * other attributes, so we check for this in the capability passed to us.
456  * Note that we can't just do simple string comparison, as the capability
457  * may contain multiple, ';' separated sequence parts.
458  */
459 static int
460 does_esc_m(char *cap)
461 {
462 #define WAITING 0
463 #define PARSING 1
464 #define NUMBER 2
465 #define FOUND 4
466 	char *capptr;
467 	int seq;
468 
469 #ifdef DEBUG
470 	__CTRACE(__CTRACE_INIT, "does_esc_m: Checking %s\n", cap);
471 #endif
472 	/* Is it just "\E[m" or "\E[0m"? */
473 	if (!strcmp(cap, "\x1b[m") || !strcmp(cap, "\x1b[0m"))
474 		return 1;
475 
476 	/* Does it contain a "\E[...m" sequence? */
477 	if (strlen(cap) < 4)
478 		return 0;
479 	capptr = cap;
480 	seq = WAITING;
481 	while (*capptr != 0) {
482 		switch (seq) {
483 		/* Start of sequence */
484 		case WAITING:
485 			if (!strncmp(capptr, "\x1b[", 2)) {
486 				capptr+=2;
487 				if (*capptr == 'm')
488 					return 1;
489 				else {
490 					seq=PARSING;
491 					continue;
492 				}
493 			}
494 			break;
495 		/* Looking for '0' */
496 		case PARSING:
497 			if (*capptr == '0')
498 				seq=FOUND;
499 			else if (*capptr > '0' && *capptr <= '9')
500 				seq=NUMBER;
501 			else if (*capptr != ';')
502 				seq=WAITING;
503 			break;
504 		/* Some other number */
505 		case NUMBER:
506 			if (*capptr == ';')
507 				seq=PARSING;
508 			else if (!(*capptr >= '0' && *capptr <= '9'))
509 				seq=WAITING;
510 			break;
511 		/* Found a '0' */
512 		case FOUND:
513 			if (*capptr == 'm')
514 				return 1;
515 			else if (!((*capptr >= '0' && *capptr <= '9') ||
516 			    *capptr == ';'))
517 				seq=WAITING;
518 			break;
519 		default:
520 			break;
521 		}
522 		capptr++;
523 	}
524 	return 0;
525 }
526 
527 /*
528  * does_ctrl_o --
529  * A hack for vt100/xterm-like terminals where the "me" capability also
530  * unsets acs (i.e. it contains the character '\017').
531  */
532 static int
533 does_ctrl_o(char *cap)
534 {
535 	char *capptr = cap;
536 
537 #ifdef DEBUG
538 	__CTRACE(__CTRACE_INIT, "does_ctrl_o: Looping on %s\n", capptr);
539 #endif
540 	while (*capptr != 0) {
541 		if (*capptr == '\x0f')
542 			return 1;
543 		capptr++;
544 	}
545 	return 0;
546 }
547