]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tput.c
94539251382b55800f81c4f107bc8aa2ee7658c2
[ncurses.git] / progs / tput.c
1 /****************************************************************************
2  * Copyright 2018-2020,2021 Thomas E. Dickey                                *
3  * Copyright 1998-2016,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29
30 /****************************************************************************
31  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
32  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
33  *     and: Thomas E. Dickey                        1996-on                 *
34  ****************************************************************************/
35
36 /*
37  * tput.c -- shellscript access to terminal capabilities
38  *
39  * by Eric S. Raymond <esr@snark.thyrsus.com>, portions based on code from
40  * Ross Ridge's mytinfo package.
41  */
42
43 #include <tparm_type.h>
44 #include <clear_cmd.h>
45 #include <reset_cmd.h>
46
47 #if !PURE_TERMINFO
48 #include <termsort.c>
49 #endif
50 #include <transform.h>
51 #include <tty_settings.h>
52
53 MODULE_ID("$Id: tput.c,v 1.88 2021/04/17 15:34:16 tom Exp $")
54
55 #define PUTS(s)         fputs(s, stdout)
56
57 const char *_nc_progname = "tput";
58
59 static char *prg_name;
60 static bool is_init = FALSE;
61 static bool is_reset = FALSE;
62 static bool is_clear = FALSE;
63
64 static GCC_NORETURN void
65 quit(int status, const char *fmt, ...)
66 {
67     va_list argp;
68
69     va_start(argp, fmt);
70     fprintf(stderr, "%s: ", prg_name);
71     vfprintf(stderr, fmt, argp);
72     fprintf(stderr, "\n");
73     va_end(argp);
74     ExitProgram(status);
75 }
76
77 static GCC_NORETURN void
78 usage(void)
79 {
80 #define KEEP(s) s "\n"
81     static const char msg[] =
82     {
83         KEEP("")
84         KEEP("Options:")
85         KEEP("  -S <<       read commands from standard input")
86         KEEP("  -T TERM     use this instead of $TERM")
87         KEEP("  -V          print curses-version")
88         KEEP("  -x          do not try to clear scrollback")
89         KEEP("")
90         KEEP("Commands:")
91         KEEP("  clear       clear the screen")
92         KEEP("  init        initialize the terminal")
93         KEEP("  reset       reinitialize the terminal")
94         KEEP("  capname     unlike clear/init/reset, print value for capability \"capname\"")
95     };
96 #undef KEEP
97     (void) fprintf(stderr, "Usage: %s [options] [command]\n", prg_name);
98     fputs(msg, stderr);
99     ExitProgram(ErrUsage);
100 }
101
102 static char *
103 check_aliases(char *name, bool program)
104 {
105     static char my_init[] = "init";
106     static char my_reset[] = "reset";
107     static char my_clear[] = "clear";
108
109     char *result = name;
110     if ((is_init = same_program(name, program ? PROG_INIT : my_init)))
111         result = my_init;
112     if ((is_reset = same_program(name, program ? PROG_RESET : my_reset)))
113         result = my_reset;
114     if ((is_clear = same_program(name, program ? PROG_CLEAR : my_clear)))
115         result = my_clear;
116     return result;
117 }
118
119 static int
120 exit_code(int token, int value)
121 {
122     int result = 99;
123
124     switch (token) {
125     case BOOLEAN:
126         result = !value;        /* TRUE=0, FALSE=1 */
127         break;
128     case NUMBER:
129         result = 0;             /* always zero */
130         break;
131     case STRING:
132         result = value;         /* 0=normal, 1=missing */
133         break;
134     }
135     return result;
136 }
137
138 /*
139  * Returns nonzero on error.
140  */
141 static int
142 tput_cmd(int fd, TTY * saved_settings, bool opt_x, int argc, char *argv[])
143 {
144     NCURSES_CONST char *name;
145     char *s;
146     int status;
147 #if !PURE_TERMINFO
148     bool termcap = FALSE;
149 #endif
150
151     name = check_aliases(argv[0], FALSE);
152     if (is_reset || is_init) {
153         TTY oldmode;
154
155         int terasechar = -1;    /* new erase character */
156         int intrchar = -1;      /* new interrupt character */
157         int tkillchar = -1;     /* new kill character */
158
159         if (is_reset) {
160             reset_start(stdout, TRUE, FALSE);
161             reset_tty_settings(fd, saved_settings);
162         } else {
163             reset_start(stdout, FALSE, TRUE);
164         }
165
166 #if HAVE_SIZECHANGE
167         set_window_size(fd, &lines, &columns);
168 #else
169         (void) fd;
170 #endif
171         set_control_chars(saved_settings, terasechar, intrchar, tkillchar);
172         set_conversions(saved_settings);
173         if (send_init_strings(fd, &oldmode)) {
174             reset_flush();
175         }
176
177         update_tty_settings(&oldmode, saved_settings);
178         return 0;
179     }
180
181     if (strcmp(name, "longname") == 0) {
182         PUTS(longname());
183         return 0;
184     }
185 #if !PURE_TERMINFO
186   retry:
187 #endif
188     if (strcmp(name, "clear") == 0) {
189         return (clear_cmd(opt_x) == ERR) ? ErrUsage : 0;
190     } else if ((status = tigetflag(name)) != -1) {
191         return exit_code(BOOLEAN, status);
192     } else if ((status = tigetnum(name)) != CANCELLED_NUMERIC) {
193         (void) printf("%d\n", status);
194         return exit_code(NUMBER, 0);
195     } else if ((s = tigetstr(name)) == CANCELLED_STRING) {
196 #if !PURE_TERMINFO
197         if (!termcap) {
198             const struct name_table_entry *np;
199
200             termcap = TRUE;
201             if ((np = _nc_find_entry(name, _nc_get_hash_table(termcap))) != 0) {
202                 switch (np->nte_type) {
203                 case BOOLEAN:
204                     name = boolnames[np->nte_index];
205                     break;
206
207                 case NUMBER:
208                     name = numnames[np->nte_index];
209                     break;
210
211                 case STRING:
212                     name = strnames[np->nte_index];
213                     break;
214                 }
215                 goto retry;
216             }
217         }
218 #endif
219         quit(ErrCapName, "unknown terminfo capability '%s'", name);
220     } else if (VALID_STRING(s)) {
221         if (argc > 1) {
222             int k;
223             int ignored;
224             long numbers[1 + NUM_PARM];
225             char *strings[1 + NUM_PARM];
226             char *p_is_s[NUM_PARM];
227             TParams paramType;
228
229             /* Nasty hack time. The tparm function needs to see numeric
230              * parameters as numbers, not as pointers to their string
231              * representations
232              */
233
234             for (k = 1; (k < argc) && (k <= NUM_PARM); k++) {
235                 char *tmp = 0;
236                 strings[k] = argv[k];
237                 numbers[k] = strtol(argv[k], &tmp, 0);
238                 if (tmp == 0 || *tmp != 0)
239                     numbers[k] = 0;
240             }
241             for (k = argc; k <= NUM_PARM; k++) {
242                 numbers[k] = 0;
243                 strings[k] = 0;
244             }
245
246             paramType = tparm_type(name);
247 #if NCURSES_XNAMES
248             /*
249              * If the capability is an extended one, analyze the string.
250              */
251             if (paramType == Numbers) {
252                 struct name_table_entry const *entry_ptr;
253                 entry_ptr = _nc_find_type_entry(name, STRING, FALSE);
254                 if (entry_ptr == NULL) {
255                     paramType = Other;
256                 }
257             }
258 #endif
259
260             switch (paramType) {
261             case Num_Str:
262                 s = TPARM_2(s, numbers[1], strings[2]);
263                 break;
264             case Num_Str_Str:
265                 s = TPARM_3(s, numbers[1], strings[2], strings[3]);
266                 break;
267             case Numbers:
268 #define myParam(n) numbers[n]
269                 s = TIPARM_9(s,
270                              myParam(1),
271                              myParam(2),
272                              myParam(3),
273                              myParam(4),
274                              myParam(5),
275                              myParam(6),
276                              myParam(7),
277                              myParam(8),
278                              myParam(9));
279 #undef myParam
280                 break;
281             case Other:
282                 /* FALLTHRU */
283             default:
284                 (void) _nc_tparm_analyze(s, p_is_s, &ignored);
285 #define myParam(n) (p_is_s[n - 1] != 0 ? ((TPARM_ARG) strings[n]) : numbers[n])
286                 s = TPARM_9(s,
287                             myParam(1),
288                             myParam(2),
289                             myParam(3),
290                             myParam(4),
291                             myParam(5),
292                             myParam(6),
293                             myParam(7),
294                             myParam(8),
295                             myParam(9));
296 #undef myParam
297                 break;
298             }
299         }
300
301         /* use putp() in order to perform padding */
302         putp(s);
303         return exit_code(STRING, 0);
304     }
305     return exit_code(STRING, 1);
306 }
307
308 int
309 main(int argc, char **argv)
310 {
311     char *term;
312     int errret;
313     bool cmdline = TRUE;
314     int c;
315     char buf[BUFSIZ];
316     int result = 0;
317     int fd;
318     TTY tty_settings;
319     bool opt_x = FALSE;         /* clear scrollback if possible */
320     bool is_alias;
321     bool need_tty;
322
323     prg_name = check_aliases(_nc_rootname(argv[0]), TRUE);
324
325     term = getenv("TERM");
326
327     while ((c = getopt(argc, argv, "ST:Vx")) != -1) {
328         switch (c) {
329         case 'S':
330             cmdline = FALSE;
331             break;
332         case 'T':
333             use_env(FALSE);
334             use_tioctl(TRUE);
335             term = optarg;
336             break;
337         case 'V':
338             puts(curses_version());
339             ExitProgram(EXIT_SUCCESS);
340         case 'x':               /* do not try to clear scrollback */
341             opt_x = TRUE;
342             break;
343         default:
344             usage();
345             /* NOTREACHED */
346         }
347     }
348
349     is_alias = (is_clear || is_reset || is_init);
350     need_tty = ((is_reset || is_init) ||
351                 (optind < argc &&
352                  (!strcmp(argv[optind], "reset") ||
353                   !strcmp(argv[optind], "init"))));
354
355     /*
356      * Modify the argument list to omit the options we processed.
357      */
358     if (is_alias) {
359         if (optind-- < argc) {
360             argc -= optind;
361             argv += optind;
362         }
363         argv[0] = prg_name;
364     } else {
365         argc -= optind;
366         argv += optind;
367     }
368
369     if (term == 0 || *term == '\0')
370         quit(ErrUsage, "No value for $TERM and no -T specified");
371
372     fd = save_tty_settings(&tty_settings, need_tty);
373
374     if (setupterm(term, fd, &errret) != OK && errret <= 0)
375         quit(ErrTermType, "unknown terminal \"%s\"", term);
376
377     if (cmdline) {
378         if ((argc <= 0) && !is_alias)
379             usage();
380         ExitProgram(tput_cmd(fd, &tty_settings, opt_x, argc, argv));
381     }
382
383     while (fgets(buf, sizeof(buf), stdin) != 0) {
384         char *argvec[16];       /* command, 9 parms, null, & slop */
385         int argnum = 0;
386         char *cp;
387
388         /* crack the argument list into a dope vector */
389         for (cp = buf; *cp; cp++) {
390             if (isspace(UChar(*cp))) {
391                 *cp = '\0';
392             } else if (cp == buf || cp[-1] == 0) {
393                 argvec[argnum++] = cp;
394                 if (argnum >= (int) SIZEOF(argvec) - 1)
395                     break;
396             }
397         }
398         argvec[argnum] = 0;
399
400         if (argnum != 0
401             && tput_cmd(fd, &tty_settings, opt_x, argnum, argvec) != 0) {
402             if (result == 0)
403                 result = ErrSystem(0);  /* will return value >4 */
404             ++result;
405         }
406     }
407
408     ExitProgram(result);
409 }