xref: /netbsd-src/lib/libcurses/setterm.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: setterm.c,v 1.43 2007/10/06 20:14:41 martin 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.43 2007/10/06 20:14:41 martin 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, 10);
164 	if ((p = getenv("COLUMNS")) != NULL)
165 		screen->COLS = (int) strtol(p, NULL, 10);
166 
167 	/*
168 	 * Want cols > 4, otherwise things will fail.
169 	 */
170 	if (screen->COLS <= 4)
171 		return (ERR);
172 
173 	LINES = screen->LINES;
174 	COLS = screen->COLS;
175 
176 #ifdef DEBUG
177 	__CTRACE(__CTRACE_INIT, "setterm: LINES = %d, COLS = %d\n",
178 	    LINES, COLS);
179 #endif
180 	if (!unknown) {
181 		if (zap(screen) == ERR) /* Get terminal description.*/
182 			return ERR;
183 	}
184 
185 	/* If we can't tab, we can't backtab, either. */
186 	if (!screen->GT)
187 		screen->tc_bt = NULL;
188 
189 	/*
190 	 * Test for cursor motion capability.
191 	 *
192 	 */
193 	if (t_goto(NULL, screen->tc_cm, 0, 0, cm_buff, sizeof(cm_buff) - 1) < 0) {
194 		screen->CA = 0;
195 		screen->tc_cm = 0;
196 	} else
197 		screen->CA = 1;
198 
199 	/*
200 	 * set the pad char, only take the first char of the pc capability
201 	 * as this is all we can use.
202 	 */
203 	screen->pad_char = screen->tc_pc ? screen->tc_pc[0] : 0;
204 
205 	/* Get full name of terminal */
206 	if (unknown) {
207 		strcpy(screen->ttytype, "dumb");
208 	} else {
209 		char *tcptr;
210 		size_t limit = 0;
211 		if (t_getterm(screen->cursesi_genbuf, 0, &limit))
212 			return ERR;
213 		if ((tcptr = malloc(limit + 1)) == NULL)
214 			return ERR;
215 		if (t_getterm(screen->cursesi_genbuf, &tcptr, 0) < 0)
216  			return ERR;
217 		__longname(tcptr, screen->ttytype);
218 		free(tcptr);
219 	}
220 
221 	/* If no scrolling commands, no quick change. */
222 	screen->noqch =
223   	    (screen->tc_cs == NULL || screen->tc_ho == NULL ||
224 	    (screen->tc_SF == NULL && screen->tc_sf == NULL) ||
225 	     (screen->tc_SR == NULL && screen->tc_sr == NULL)) &&
226 	    ((screen->tc_AL == NULL && screen->tc_al == NULL) ||
227 	     (screen->tc_DL == NULL && screen->tc_dl == NULL));
228 
229 	/*
230 	 * Precalculate conflict info for color/attribute end commands.
231 	 */
232 #ifndef HAVE_WCHAR
233 	screen->mask_op = __ATTRIBUTES & ~__COLOR;
234 #else
235 	screen->mask_op = WA_ATTRIBUTES & ~__COLOR;
236 #endif /* HAVE_WCHAR */
237 	if (screen->tc_op != NULL) {
238 		if (does_esc_m(screen->tc_op))
239 			screen->mask_op &=
240 			    ~(__STANDOUT | __UNDERSCORE | __TERMATTR);
241 		else {
242 			if (screen->tc_se != NULL &&
243 			    !strcmp(screen->tc_op, screen->tc_se))
244 				screen->mask_op &= ~__STANDOUT;
245 			if (screen->tc_ue != NULL &&
246 			    !strcmp(screen->tc_op, screen->tc_ue))
247 				screen->mask_op &= ~__UNDERSCORE;
248 			if (screen->tc_me != NULL &&
249 			    !strcmp(screen->tc_op, screen->tc_me))
250 				screen->mask_op &= ~__TERMATTR;
251 		}
252 	}
253 	/*
254 	 * Assume that "me" turns off all attributes apart from ACS.
255 	 * It might turn off ACS, so check for that.
256 	 */
257 	if (screen->tc_me != NULL && does_ctrl_o(screen->tc_me))
258 		screen->mask_me = 0;
259 	else
260 		screen->mask_me = __ALTCHARSET;
261 
262 	/* Check what turning off the attributes also turns off */
263 #ifndef HAVE_WCHAR
264 	screen->mask_ue = __ATTRIBUTES & ~__UNDERSCORE;
265 #else
266 	screen->mask_ue = WA_ATTRIBUTES & ~__UNDERSCORE;
267 #endif /* HAVE_WCHAR */
268 	if (screen->tc_ue != NULL) {
269 		if (does_esc_m(screen->tc_ue))
270 			screen->mask_ue &=
271 			    ~(__STANDOUT | __TERMATTR | __COLOR);
272 		else {
273 			if (screen->tc_se != NULL &&
274 			    !strcmp(screen->tc_ue, screen->tc_se))
275 				screen->mask_ue &= ~__STANDOUT;
276 			if (screen->tc_me != NULL &&
277 			    !strcmp(screen->tc_ue, screen->tc_me))
278 				screen->mask_ue &= ~__TERMATTR;
279 			if (screen->tc_op != NULL &&
280 			    !strcmp(screen->tc_ue, screen->tc_op))
281 				screen->mask_ue &= ~__COLOR;
282 		}
283 	}
284 #ifndef HAVE_WCHAR
285 	screen->mask_se = __ATTRIBUTES & ~__STANDOUT;
286 #else
287 	screen->mask_se = WA_ATTRIBUTES & ~__STANDOUT;
288 #endif /* HAVE_WCHAR */
289 	if (screen->tc_se != NULL) {
290 		if (does_esc_m(screen->tc_se))
291 			screen->mask_se &=
292 			    ~(__UNDERSCORE | __TERMATTR | __COLOR);
293 		else {
294 			if (screen->tc_ue != NULL &&
295 			    !strcmp(screen->tc_se, screen->tc_ue))
296 				screen->mask_se &= ~__UNDERSCORE;
297 			if (screen->tc_me != NULL &&
298 			    !strcmp(screen->tc_se, screen->tc_me))
299 				screen->mask_se &= ~__TERMATTR;
300 			if (screen->tc_op != NULL &&
301 			    !strcmp(screen->tc_se, screen->tc_op))
302 				screen->mask_se &= ~__COLOR;
303 		}
304 	}
305 
306 	return (unknown ? ERR : OK);
307 }
308 
309 /*
310  * _cursesi_resetterm --
311  *  Copy the terminal instance data for the given screen to the global
312  *  variables.
313  */
314 void
315 _cursesi_resetterm(SCREEN *screen)
316 {
317 	char ***sp, **scr_sp;
318 	int  **vp, *scr_vp, i;
319 	char **fp, *scr_fp;
320 
321 	LINES = screen->LINES;
322 	COLS = screen->COLS;
323 
324 	  /* reset terminal capabilities */
325 	fp = sflags;
326 	scr_fp = &screen->tc_am;
327 	for (i = 0; i < screen->flag_count; i++)
328 		*(*fp++) = *scr_fp++;
329 
330 	vp = svals;
331 	scr_vp = &screen->tc_pa;
332 	for (i = 0; i < screen->int_count; i++)
333 		*(*vp++) = *scr_vp++;
334 
335 	sp = sstrs;
336 	scr_sp = &screen->tc_AB;
337 	for (i = 0; i < screen->str_count; i++)
338 		*(*sp++) = *scr_sp++;
339 
340 	__GT = screen->GT;
341 	__CA = screen->CA;
342 
343 	PC = screen->pad_char;
344 
345 	__noqch = screen->noqch;
346 	__mask_op = screen->mask_op;
347 	__mask_me = screen->mask_me;
348 	__mask_ue = screen->mask_ue;
349 	__mask_se = screen->mask_se;
350 }
351 
352 /*
353  * zap --
354  *	Gets all the terminal flags from the termcap database.
355  */
356 static int
357 zap(SCREEN *screen)
358 {
359 	const char *nampstr, *namp;
360         char **sp;
361 	int  *vp;
362 	char *fp;
363 	char tmp[3];
364 #ifdef DEBUG
365 	char	*cp;
366 #endif
367 	tmp[2] = '\0';
368 
369 	namp = "ambsccdaeohchlinmimsncnsosulutxbxnxtxsxx";
370 	fp = &screen->tc_am;
371 	screen->flag_count = 0;
372 	do {
373 		*tmp = *namp;
374 		*(tmp + 1) = *(namp + 1);
375 		*fp++ = t_getflag(screen->cursesi_genbuf, tmp);
376 #ifdef DEBUG
377 		__CTRACE(__CTRACE_INIT, "%2.2s = %s\n", namp,
378 		    fp[-1] ? "TRUE" : "FALSE");
379 #endif
380 		namp += 2;
381 		screen->flag_count++;
382 	} while (*namp);
383 	namp = "paCoNC";
384 	vp = &screen->tc_pa;
385 	screen->int_count = 0;
386 	do {
387 		*tmp = *namp;
388 		*(tmp + 1) = *(namp + 1);
389 		*vp++ = t_getnum(screen->cursesi_genbuf, tmp);
390 #ifdef DEBUG
391 		__CTRACE(__CTRACE_INIT, "%2.2s = %d\n", namp, vp[-1]);
392 #endif
393 		namp += 2;
394 		screen->int_count++;
395 	} while (*namp);
396 
397 #ifndef HAVE_WCHAR
398 	nampstr = "ABacaeAFALalasbcblbtcdceclcmcrcsdcDLdldmDOdoeAedeihoIcicimIpipk0k1k2k3k4k5k6k7k8k9kdkekhklkrkskuLEllmambmdmemhmkmmmompmrndnlocoppcrcRISbscseSFSfsfsospSRsrtatetiucueUPupusvbvevivs";
399 #else
400 	nampstr = "ABacaeAFALalasbcblbtcdceclcmcrcsdcDLdldmDOdoeAedeihoIcicimIpipk0k1k2k3k4k5k6k7k8k9kdkekhklkrkskuLEllmambmdmemhmkmmmompmrndnlocoppcrcRISbscseSFSfsfsospSRsrtatetiucueUPupusvbvevivsXhXlXoXrXtXv";
401 #endif /* HAVE_WCHAR */
402 
403 	namp = nampstr;
404 	sp = &screen->tc_AB;
405 	screen->str_count = 0;
406 	do {
407 		*tmp = *namp;
408 		*(tmp + 1) = *(namp + 1);
409 		*sp++ = t_agetstr(screen->cursesi_genbuf, tmp);
410 #ifdef DEBUG
411 		if (sp[-1] == NULL)
412 			__CTRACE(__CTRACE_INIT, "%2.2s = NULL\n", namp);
413 		else {
414 			__CTRACE(__CTRACE_INIT, "%2.2s = \"", namp);
415 			for (cp = sp[-1]; *cp; cp++)
416 				__CTRACE(__CTRACE_INIT, "%s", unctrl(*cp));
417 			__CTRACE(__CTRACE_INIT, "\"\n");
418 		}
419 #endif
420 		namp += 2;
421 		screen->str_count++;
422 	} while (*namp);
423 	if (screen->tc_xs)
424 		screen->tc_so = screen->tc_se = NULL;
425 	else {
426 		if (t_getnum(screen->cursesi_genbuf, "sg") > 0)
427 			screen->tc_so = NULL;
428 		if (t_getnum(screen->cursesi_genbuf, "ug") > 0)
429 			screen->tc_us = NULL;
430 		if (!screen->tc_so && screen->tc_us) {
431 			screen->tc_so = screen->tc_us;
432 			screen->tc_se = screen->tc_ue;
433 		}
434 	}
435 
436 	return OK;
437 }
438 
439 /*
440  * getcap --
441  *	Return a capability from termcap.
442  */
443 char	*
444 getcap(char *name)
445 {
446 	return (t_agetstr(_cursesi_screen->cursesi_genbuf, name));
447 }
448 
449 /*
450  * does_esc_m --
451  * A hack for xterm-like terminals where "\E[m" or "\E[0m" will turn off
452  * other attributes, so we check for this in the capability passed to us.
453  * Note that we can't just do simple string comparison, as the capability
454  * may contain multiple, ';' separated sequence parts.
455  */
456 static int
457 does_esc_m(char *cap)
458 {
459 #define WAITING 0
460 #define PARSING 1
461 #define NUMBER 2
462 #define FOUND 4
463 	char *capptr;
464 	int seq;
465 
466 #ifdef DEBUG
467 	__CTRACE(__CTRACE_INIT, "does_esc_m: Checking %s\n", cap);
468 #endif
469 	/* Is it just "\E[m" or "\E[0m"? */
470 	if (!strcmp(cap, "\x1b[m") || !strcmp(cap, "\x1b[0m"))
471 		return 1;
472 
473 	/* Does it contain a "\E[...m" sequence? */
474 	if (strlen(cap) < 4)
475 		return 0;
476 	capptr = cap;
477 	seq = WAITING;
478 	while (*capptr != 0) {
479 		switch (seq) {
480 		/* Start of sequence */
481 		case WAITING:
482 			if (!strncmp(capptr, "\x1b[", 2)) {
483 				capptr+=2;
484 				if (*capptr == 'm')
485 					return 1;
486 				else {
487 					seq=PARSING;
488 					continue;
489 				}
490 			}
491 			break;
492 		/* Looking for '0' */
493 		case PARSING:
494 			if (*capptr == '0')
495 				seq=FOUND;
496 			else if (*capptr > '0' && *capptr <= '9')
497 				seq=NUMBER;
498 			else if (*capptr != ';')
499 				seq=WAITING;
500 			break;
501 		/* Some other number */
502 		case NUMBER:
503 			if (*capptr == ';')
504 				seq=PARSING;
505 			else if (!(*capptr >= '0' && *capptr <= '9'))
506 				seq=WAITING;
507 			break;
508 		/* Found a '0' */
509 		case FOUND:
510 			if (*capptr == 'm')
511 				return 1;
512 			else if (!((*capptr >= '0' && *capptr <= '9') ||
513 			    *capptr == ';'))
514 				seq=WAITING;
515 			break;
516 		default:
517 			break;
518 		}
519 		capptr++;
520 	}
521 	return 0;
522 }
523 
524 /*
525  * does_ctrl_o --
526  * A hack for vt100/xterm-like terminals where the "me" capability also
527  * unsets acs (i.e. it contains the character '\017').
528  */
529 static int
530 does_ctrl_o(char *cap)
531 {
532 	char *capptr = cap;
533 
534 #ifdef DEBUG
535 	__CTRACE(__CTRACE_INIT, "does_ctrl_o: Looping on %s\n", capptr);
536 #endif
537 	while (*capptr != 0) {
538 		if (*capptr == '\x0f')
539 			return 1;
540 		capptr++;
541 	}
542 	return 0;
543 }
544