]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tput.c
ncurses 6.4 - patch 20240302
[ncurses.git] / progs / tput.c
1 /****************************************************************************
2  * Copyright 2018-2023,2024 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 #include <transform.h>
48 #include <tty_settings.h>
49
50 MODULE_ID("$Id: tput.c,v 1.103 2024/03/02 13:22:26 tom Exp $")
51
52 #define PUTS(s)         fputs(s, stdout)
53
54 const char *_nc_progname = "tput";
55
56 static bool opt_v = FALSE;      /* quiet, do not show warnings */
57 static bool opt_x = FALSE;      /* clear scrollback if possible */
58
59 static bool is_init = FALSE;
60 static bool is_reset = FALSE;
61 static bool is_clear = FALSE;
62
63 static GCC_NORETURN void
64 quit(int status, const char *fmt, ...)
65 {
66     va_list argp;
67
68     va_start(argp, fmt);
69     fprintf(stderr, "%s: ", _nc_progname);
70     vfprintf(stderr, fmt, argp);
71     fprintf(stderr, "\n");
72     va_end(argp);
73     ExitProgram(status);
74 }
75
76 static GCC_NORETURN void
77 usage(const char *optstring)
78 {
79 #define KEEP(s) s "\n"
80     static const char msg[] =
81     {
82         KEEP("")
83         KEEP("Options:")
84         KEEP("  -S <<       read commands from standard input")
85         KEEP("  -T TERM     use this instead of $TERM")
86         KEEP("  -V          print curses-version")
87         KEEP("  -v          verbose, show warnings")
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", _nc_progname);
98     if (optstring != NULL) {
99         const char *s = msg;
100         while (*s != '\0') {
101             fputc(UChar(*s), stderr);
102             if (!strncmp(s, "  -", 3)) {
103                 if (strchr(optstring, s[3]) == NULL)
104                     s = strchr(s, '\n') + 1;
105             } else if (!strncmp(s, "\n\nC", 3))
106                 break;
107             ++s;
108         }
109     } else {
110         fputs(msg, stderr);
111     }
112     ExitProgram(ErrUsage);
113 }
114
115 static char *
116 check_aliases(char *name, bool program)
117 {
118     static char my_init[] = "init";
119     static char my_reset[] = "reset";
120     static char my_clear[] = "clear";
121
122     char *result = name;
123     if ((is_init = same_program(name, program ? PROG_INIT : my_init)))
124         result = my_init;
125     if ((is_reset = same_program(name, program ? PROG_RESET : my_reset)))
126         result = my_reset;
127     if ((is_clear = same_program(name, program ? PROG_CLEAR : my_clear)))
128         result = my_clear;
129     return result;
130 }
131
132 static int
133 exit_code(int token, int value)
134 {
135     int result = 99;
136
137     switch (token) {
138     case BOOLEAN:
139         result = !value;        /* TRUE=0, FALSE=1 */
140         break;
141     case NUMBER:
142         result = 0;             /* always zero */
143         break;
144     case STRING:
145         result = value;         /* 0=normal, 1=missing */
146         break;
147     }
148     return result;
149 }
150
151 /*
152  * Returns nonzero on error.
153  */
154 static int
155 tput_cmd(int fd, TTY * settings, int argc, char **argv, int *used)
156 {
157     NCURSES_CONST char *name;
158     char *s;
159     int status;
160 #if !PURE_TERMINFO
161     bool termcap = FALSE;
162 #endif
163
164     name = check_aliases(argv[0], FALSE);
165     *used = 1;
166     if (is_reset || is_init) {
167         TTY oldmode = *settings;
168
169         int terasechar = -1;    /* new erase character */
170         int intrchar = -1;      /* new interrupt character */
171         int tkillchar = -1;     /* new kill character */
172
173         if (is_reset) {
174             reset_start(stdout, TRUE, FALSE);
175             reset_tty_settings(fd, settings, FALSE);
176         } else {
177             reset_start(stdout, FALSE, TRUE);
178         }
179
180 #if HAVE_SIZECHANGE
181         set_window_size(fd, &lines, &columns);
182 #else
183         (void) fd;
184 #endif
185         set_control_chars(settings, terasechar, intrchar, tkillchar);
186         set_conversions(settings);
187
188         if (send_init_strings(fd, &oldmode)) {
189             reset_flush();
190         }
191
192         update_tty_settings(&oldmode, settings);
193         return 0;
194     }
195
196     if (strcmp(name, "longname") == 0) {
197         PUTS(longname());
198         return 0;
199     }
200 #if !PURE_TERMINFO
201   retry:
202 #endif
203     if (strcmp(name, "clear") == 0) {
204         return (clear_cmd(opt_x) == ERR) ? ErrUsage : 0;
205     } else if ((status = tigetflag(name)) != -1) {
206         return exit_code(BOOLEAN, status);
207     } else if ((status = tigetnum(name)) != CANCELLED_NUMERIC) {
208         (void) printf("%d\n", status);
209         return exit_code(NUMBER, 0);
210     } else if ((s = tigetstr(name)) == CANCELLED_STRING) {
211 #if !PURE_TERMINFO
212         if (!termcap) {
213             const struct name_table_entry *np;
214
215             termcap = TRUE;
216             if ((np = _nc_find_entry(name, _nc_get_hash_table(termcap))) != 0) {
217                 switch (np->nte_type) {
218                 case BOOLEAN:
219                     name = boolnames[np->nte_index];
220                     break;
221
222                 case NUMBER:
223                     name = numnames[np->nte_index];
224                     break;
225
226                 case STRING:
227                     name = strnames[np->nte_index];
228                     break;
229                 }
230                 goto retry;
231             }
232         }
233 #endif
234         quit(ErrCapName, "unknown terminfo capability '%s'", name);
235     } else if (VALID_STRING(s)) {
236         if (argc > 1) {
237             int k;
238             int narg;
239             int analyzed;
240             int provided;
241             int popcount;
242             long numbers[1 + NUM_PARM];
243             char *strings[1 + NUM_PARM];
244             char *p_is_s[NUM_PARM];
245             TParams paramType;
246
247             /* Nasty hack time. The tparm function needs to see numeric
248              * parameters as numbers, not as pointers to their string
249              * representations
250              */
251
252             for (k = 1; (k < argc) && (k <= NUM_PARM); k++) {
253                 char *tmp = 0;
254                 strings[k] = argv[k];
255                 numbers[k] = strtol(argv[k], &tmp, 0);
256                 if (tmp == 0 || *tmp != 0)
257                     numbers[k] = 0;
258             }
259             for (k = argc; k <= NUM_PARM; k++) {
260                 numbers[k] = 0;
261                 strings[k] = 0;
262             }
263
264             paramType = tparm_type(name);
265 #if NCURSES_XNAMES
266             /*
267              * If the capability is an extended one, analyze the string.
268              */
269             if (paramType == Numbers) {
270                 struct name_table_entry const *entry_ptr;
271                 entry_ptr = _nc_find_type_entry(name, STRING, FALSE);
272                 if (entry_ptr == NULL) {
273                     paramType = Other;
274                 }
275             }
276 #endif
277
278             popcount = 0;
279             _nc_reset_tparm(NULL);
280             /*
281              * Count the number of numeric parameters which are provided.
282              */
283             provided = 0;
284             for (narg = 1; narg < argc; ++narg) {
285                 char *ending = NULL;
286                 long check = strtol(argv[narg], &ending, 0);
287                 if (check < 0 || ending == argv[narg] || *ending != '\0')
288                     break;
289                 provided = narg;
290             }
291             switch (paramType) {
292             case Str:
293                 s = TPARM_1(s, strings[1]);
294                 analyzed = 1;
295                 if (provided == 0 && argc >= 1)
296                     provided++;
297                 break;
298             case Str_Str:
299                 s = TPARM_2(s, strings[1], strings[2]);
300                 analyzed = 2;
301                 if (provided == 0 && argc >= 1)
302                     provided++;
303                 if (provided == 1 && argc >= 2)
304                     provided++;
305                 break;
306             case Num_Str:
307                 s = TPARM_2(s, numbers[1], strings[2]);
308                 analyzed = 2;
309                 if (provided == 1 && argc >= 2)
310                     provided++;
311                 break;
312             case Num_Str_Str:
313                 s = TPARM_3(s, numbers[1], strings[2], strings[3]);
314                 analyzed = 3;
315                 if (provided == 1 && argc >= 2)
316                     provided++;
317                 if (provided == 2 && argc >= 3)
318                     provided++;
319                 break;
320             case Numbers:
321                 analyzed = _nc_tparm_analyze(NULL, s, p_is_s, &popcount);
322 #define myParam(n) numbers[n]
323                 s = TIPARM_9(s,
324                              myParam(1),
325                              myParam(2),
326                              myParam(3),
327                              myParam(4),
328                              myParam(5),
329                              myParam(6),
330                              myParam(7),
331                              myParam(8),
332                              myParam(9));
333 #undef myParam
334                 break;
335             case Other:
336                 /* FALLTHRU */
337             default:
338                 analyzed = _nc_tparm_analyze(NULL, s, p_is_s, &popcount);
339 #define myParam(n) (p_is_s[n - 1] != 0 ? ((TPARM_ARG) strings[n]) : numbers[n])
340                 s = TPARM_9(s,
341                             myParam(1),
342                             myParam(2),
343                             myParam(3),
344                             myParam(4),
345                             myParam(5),
346                             myParam(6),
347                             myParam(7),
348                             myParam(8),
349                             myParam(9));
350 #undef myParam
351                 break;
352             }
353             if (analyzed < popcount) {
354                 analyzed = popcount;
355             }
356             if (opt_v && (analyzed != provided)) {
357                 fprintf(stderr, "%s: %s parameters for \"%s\"\n",
358                         _nc_progname,
359                         (analyzed < provided ? "extra" : "missing"),
360                         argv[0]);
361             }
362             *used += provided;
363         }
364
365         /* use putp() in order to perform padding */
366         putp(s);
367         return exit_code(STRING, 0);
368     }
369     return exit_code(STRING, 1);
370 }
371
372 int
373 main(int argc, char **argv)
374 {
375     char *term;
376     int errret;
377     bool cmdline = TRUE;
378     int c;
379     char buf[BUFSIZ];
380     int result = 0;
381     int fd;
382     int used;
383     TTY old_settings;
384     TTY tty_settings;
385     bool is_alias;
386     bool need_tty;
387
388     _nc_progname = check_aliases(_nc_rootname(argv[0]), TRUE);
389     is_alias = (is_clear || is_reset || is_init);
390
391     term = getenv("TERM");
392
393     while ((c = getopt(argc, argv, is_alias ? "T:Vvx" : "ST:Vvx")) != -1) {
394         switch (c) {
395         case 'S':
396             cmdline = FALSE;
397             break;
398         case 'T':
399             use_env(FALSE);
400             use_tioctl(TRUE);
401             term = optarg;
402             break;
403         case 'V':
404             puts(curses_version());
405             ExitProgram(EXIT_SUCCESS);
406         case 'v':               /* verbose */
407             opt_v = TRUE;
408             break;
409         case 'x':               /* do not try to clear scrollback */
410             opt_x = TRUE;
411             break;
412         default:
413             usage(is_alias ? "TVx" : NULL);
414             /* NOTREACHED */
415         }
416     }
417
418     need_tty = ((is_reset || is_init) ||
419                 (optind < argc &&
420                  (!strcmp(argv[optind], "reset") ||
421                   !strcmp(argv[optind], "init"))));
422
423     /*
424      * Modify the argument list to omit the options we processed.
425      */
426     if (is_alias) {
427         if (optind-- < argc) {
428             argc -= optind;
429             argv += optind;
430         }
431         argv[0] = strdup(_nc_progname);
432     } else {
433         argc -= optind;
434         argv += optind;
435     }
436
437     if (term == 0 || *term == '\0')
438         quit(ErrUsage, "No value for $TERM and no -T specified");
439
440     fd = save_tty_settings(&tty_settings, need_tty);
441     old_settings = tty_settings;
442
443     if (setupterm(term, fd, &errret) != OK && errret <= 0)
444         quit(ErrTermType, "unknown terminal \"%s\"", term);
445
446     if (cmdline) {
447         int code = 0;
448         if ((argc <= 0) && !is_alias)
449             usage(NULL);
450         while (argc > 0) {
451             tty_settings = old_settings;
452             code = tput_cmd(fd, &tty_settings, argc, argv, &used);
453             if (code != 0)
454                 break;
455             argc -= used;
456             argv += used;
457         }
458         ExitProgram(code);
459     }
460
461     while (fgets(buf, sizeof(buf), stdin) != 0) {
462         size_t need = strlen(buf);
463         char **argvec = typeCalloc(char *, need + 1);
464         char **argnow;
465         int argnum = 0;
466         char *cp;
467
468         if (argvec == NULL) {
469             quit(ErrSystem(1), strerror(errno));
470         }
471
472         /* split the buffer into tokens */
473         for (cp = buf; *cp; cp++) {
474             if (isspace(UChar(*cp))) {
475                 *cp = '\0';
476             } else if (cp == buf || cp[-1] == '\0') {
477                 argvec[argnum++] = cp;
478                 if (argnum >= (int) need)
479                     break;
480             }
481         }
482
483         argnow = argvec;
484         while (argnum > 0) {
485             int code;
486             tty_settings = old_settings;
487             code = tput_cmd(fd, &tty_settings, argnum, argnow, &used);
488             if (code != 0) {
489                 if (result == 0)
490                     result = ErrSystem(0);      /* will return value >4 */
491                 ++result;
492             }
493             argnum -= used;
494             argnow += used;
495         }
496         free(argvec);
497     }
498
499     ExitProgram(result);
500 }