xref: /freebsd/contrib/ncurses/progs/tput.c (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
1 /****************************************************************************
2  * Copyright (c) 1998,1999,2000 Free Software Foundation, Inc.                        *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28 
29 /****************************************************************************
30  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32  ****************************************************************************/
33 
34 /*
35  * tput.c -- shellscript access to terminal capabilities
36  *
37  * by Eric S. Raymond <esr@snark.thyrsus.com>, portions based on code from
38  * Ross Ridge's mytinfo package.
39  */
40 
41 #include <progs.priv.h>
42 
43 #if !PURE_TERMINFO
44 #include <termsort.c>
45 #endif
46 #include <transform.h>
47 
48 MODULE_ID("$Id: tput.c,v 1.26 2001/03/24 21:59:48 tom Exp $")
49 
50 #define PUTS(s)		fputs(s, stdout)
51 #define PUTCHAR(c)	putchar(c)
52 #define FLUSH		fflush(stdout)
53 
54 typedef enum {
55     Numbers = 0
56     ,Num_Str
57     ,Num_Str_Str
58 } TParams;
59 
60 static char *prg_name;
61 static bool is_init = FALSE;
62 static bool is_reset = FALSE;
63 
64 static void
65 quit(int status, const char *fmt,...)
66 {
67     va_list argp;
68 
69     va_start(argp, fmt);
70     vfprintf(stderr, fmt, argp);
71     fprintf(stderr, "\n");
72     va_end(argp);
73     exit(status);
74 }
75 
76 static void
77 usage(void)
78 {
79     fprintf(stderr, "usage: %s [-V] [-S] [-T term] capname\n", prg_name);
80     exit(EXIT_FAILURE);
81 }
82 
83 static void
84 check_aliases(const char *name)
85 {
86     is_init = (strcmp(name, PROG_INIT) == 0);
87     is_reset = (strcmp(name, PROG_RESET) == 0);
88 }
89 
90 /*
91  * Lookup the type of call we should make to tparm().  This ignores the actual
92  * terminfo capability (bad, because it is not extensible), but makes this
93  * code portable to platforms where sizeof(int) != sizeof(char *).
94  *
95  * FIXME: If we want extensibility, analyze the capability string as we do
96  * in tparm() to decide how to parse the varargs list.
97  */
98 static TParams
99 tparm_type(const char *name)
100 {
101 #define TD(code, longname, ti, tc) {code,longname},{code,ti},{code,tc}
102     TParams result = Numbers;
103     /* *INDENT-OFF* */
104     static const struct {
105 	TParams code;
106 	const char *name;
107     } table[] = {
108 	TD(Num_Str,	"pkey_key",	"pfkey",	"pk"),
109 	TD(Num_Str,	"pkey_local",	"pfloc",	"pl"),
110 	TD(Num_Str,	"pkey_xmit",	"pfx",		"px"),
111 	TD(Num_Str,	"plab_norm",	"pln",		"pn"),
112 	TD(Num_Str_Str, "pkey_plab",	"pfxl",		"xl"),
113     };
114     /* *INDENT-ON* */
115 
116     unsigned n;
117     for (n = 0; n < SIZEOF(table); n++) {
118 	if (!strcmp(name, table[n].name)) {
119 	    result = table[n].code;
120 	    break;
121 	}
122     }
123     return result;
124 }
125 
126 static int
127 tput(int argc, char *argv[])
128 {
129     NCURSES_CONST char *name;
130     char *s;
131     int i, j, c;
132     int status;
133     FILE *f;
134 
135     check_aliases(name = argv[0]);
136     if (is_reset || is_init) {
137 	if (init_prog != 0) {
138 	    system(init_prog);
139 	}
140 	FLUSH;
141 
142 	if (is_reset && reset_1string != 0) {
143 	    PUTS(reset_1string);
144 	} else if (init_1string != 0) {
145 	    PUTS(init_1string);
146 	}
147 	FLUSH;
148 
149 	if (is_reset && reset_2string != 0) {
150 	    PUTS(reset_2string);
151 	} else if (init_2string != 0) {
152 	    PUTS(init_2string);
153 	}
154 	FLUSH;
155 
156 	if (set_lr_margin != 0) {
157 	    PUTS(tparm(set_lr_margin, 0, columns - 1));
158 	} else if (set_left_margin_parm != 0
159 		   && set_right_margin_parm != 0) {
160 	    PUTS(tparm(set_left_margin_parm, 0));
161 	    PUTS(tparm(set_right_margin_parm, columns - 1));
162 	} else if (clear_margins != 0
163 		   && set_left_margin != 0
164 		   && set_right_margin != 0) {
165 	    PUTS(clear_margins);
166 	    if (carriage_return != 0) {
167 		PUTS(carriage_return);
168 	    } else {
169 		PUTCHAR('\r');
170 	    }
171 	    PUTS(set_left_margin);
172 	    if (parm_right_cursor) {
173 		PUTS(tparm(parm_right_cursor, columns - 1));
174 	    } else {
175 		for (i = 0; i < columns - 1; i++) {
176 		    PUTCHAR(' ');
177 		}
178 	    }
179 	    PUTS(set_right_margin);
180 	    if (carriage_return != 0) {
181 		PUTS(carriage_return);
182 	    } else {
183 		PUTCHAR('\r');
184 	    }
185 	}
186 	FLUSH;
187 
188 	if (init_tabs != 8) {
189 	    if (clear_all_tabs != 0 && set_tab != 0) {
190 		for (i = 0; i < columns - 1; i += 8) {
191 		    if (parm_right_cursor) {
192 			PUTS(tparm(parm_right_cursor, 8));
193 		    } else {
194 			for (j = 0; j < 8; j++)
195 			    PUTCHAR(' ');
196 		    }
197 		    PUTS(set_tab);
198 		}
199 		FLUSH;
200 	    }
201 	}
202 
203 	if (is_reset && reset_file != 0) {
204 	    f = fopen(reset_file, "r");
205 	    if (f == 0) {
206 		quit(errno, "Can't open reset_file: '%s'", reset_file);
207 	    }
208 	    while ((c = fgetc(f)) != EOF) {
209 		PUTCHAR(c);
210 	    }
211 	    fclose(f);
212 	} else if (init_file != 0) {
213 	    f = fopen(init_file, "r");
214 	    if (f == 0) {
215 		quit(errno, "Can't open init_file: '%s'", init_file);
216 	    }
217 	    while ((c = fgetc(f)) != EOF) {
218 		PUTCHAR(c);
219 	    }
220 	    fclose(f);
221 	}
222 	FLUSH;
223 
224 	if (is_reset && reset_3string != 0) {
225 	    PUTS(reset_3string);
226 	} else if (init_2string != 0) {
227 	    PUTS(init_2string);
228 	}
229 	FLUSH;
230 	return 0;
231     }
232 
233     if (strcmp(name, "longname") == 0) {
234 	PUTS(longname());
235 	return 0;
236     }
237 #if !PURE_TERMINFO
238     {
239 	const struct name_table_entry *np;
240 
241 	if ((np = _nc_find_entry(name, _nc_get_hash_table(1))) != 0)
242 	    switch (np->nte_type) {
243 	    case BOOLEAN:
244 		if (bool_from_termcap[np->nte_index])
245 		    name = boolnames[np->nte_index];
246 		break;
247 
248 	    case NUMBER:
249 		if (num_from_termcap[np->nte_index])
250 		    name = numnames[np->nte_index];
251 		break;
252 
253 	    case STRING:
254 		if (str_from_termcap[np->nte_index])
255 		    name = strnames[np->nte_index];
256 		break;
257 	    }
258     }
259 #endif
260 
261     if ((status = tigetflag(name)) != -1) {
262 	return (status != 0);
263     } else if ((status = tigetnum(name)) != CANCELLED_NUMERIC) {
264 	(void) printf("%d\n", status);
265 	return (0);
266     } else if ((s = tigetstr(name)) == CANCELLED_STRING) {
267 	quit(4, "%s: unknown terminfo capability '%s'", prg_name, name);
268     } else if (s != ABSENT_STRING) {
269 	if (argc > 1) {
270 	    int k;
271 	    int numbers[10];
272 	    char *strings[10];
273 
274 	    /* Nasty hack time. The tparm function needs to see numeric
275 	     * parameters as numbers, not as pointers to their string
276 	     * representations
277 	     */
278 
279 	    for (k = 1; k < argc; k++) {
280 		char *tmp = 0;
281 		strings[k] = argv[k];
282 		numbers[k] = strtol(argv[k], &tmp, 0);
283 		if (tmp == 0 || *tmp != 0)
284 		    numbers[k] = 0;
285 	    }
286 	    for (k = argc; k <= 9; k++) {
287 		numbers[k] = 0;
288 		strings[k] = 0;
289 	    }
290 
291 	    switch (tparm_type(name)) {
292 	    case Num_Str:
293 		s = tparm(s, numbers[1], strings[2]);
294 		break;
295 	    case Num_Str_Str:
296 		s = tparm(s, numbers[1], strings[2], strings[3]);
297 		break;
298 	    default:
299 		s = tparm(s,
300 			  numbers[1], numbers[2], numbers[3],
301 			  numbers[4], numbers[5], numbers[6],
302 			  numbers[7], numbers[8], numbers[9]);
303 		break;
304 	    }
305 	}
306 
307 	/* use putp() in order to perform padding */
308 	putp(s);
309 	return (0);
310     }
311     return (0);
312 }
313 
314 int
315 main(int argc, char **argv)
316 {
317     char *term;
318     int errret;
319     bool cmdline = TRUE;
320     int c;
321     char buf[BUFSIZ];
322     int errors = 0;
323 
324     check_aliases(prg_name = _nc_basename(argv[0]));
325 
326     term = getenv("TERM");
327 
328     while ((c = getopt(argc, argv, "ST:V")) != EOF) {
329 	switch (c) {
330 	case 'S':
331 	    cmdline = FALSE;
332 	    break;
333 	case 'T':
334 	    use_env(FALSE);
335 	    term = optarg;
336 	    break;
337 	case 'V':
338 	    puts(curses_version());
339 	    return EXIT_SUCCESS;
340 	default:
341 	    usage();
342 	    /* NOTREACHED */
343 	}
344     }
345 
346     /*
347      * Modify the argument list to omit the options we processed.
348      */
349     if (is_reset || is_init) {
350 	if (optind-- < argc) {
351 	    argc -= optind;
352 	    argv += optind;
353 	}
354 	argv[0] = prg_name;
355     } else {
356 	argc -= optind;
357 	argv += optind;
358     }
359 
360     if (term == 0 || *term == '\0')
361 	quit(2, "No value for $TERM and no -T specified");
362 
363     if (setupterm(term, STDOUT_FILENO, &errret) != OK && errret <= 0)
364 	quit(3, "unknown terminal \"%s\"", term);
365 
366     if (cmdline) {
367 	if ((argc <= 0) && !is_reset && !is_init)
368 	    usage();
369 	return tput(argc, argv);
370     }
371 
372     while (fgets(buf, sizeof(buf), stdin) != 0) {
373 	char *argvec[16];	/* command, 9 parms, null, & slop */
374 	int argnum = 0;
375 	char *cp;
376 
377 	/* crack the argument list into a dope vector */
378 	for (cp = buf; *cp; cp++) {
379 	    if (isspace(CharOf(*cp)))
380 		*cp = '\0';
381 	    else if (cp == buf || cp[-1] == 0)
382 		argvec[argnum++] = cp;
383 	}
384 	argvec[argnum] = 0;
385 
386 	if (tput(argnum, argvec) != 0)
387 	    errors++;
388     }
389 
390     return errors > 0;
391 }
392