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