]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tput.c
3295d18e6819574fa79477d6d15a0401e707afe6
[ncurses.git] / progs / tput.c
1 /****************************************************************************
2  * Copyright (c) 1998-2016,2017 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  *     and: Thomas E. Dickey                        1996-on                 *
33  ****************************************************************************/
34
35 /*
36  * tput.c -- shellscript access to terminal capabilities
37  *
38  * by Eric S. Raymond <esr@snark.thyrsus.com>, portions based on code from
39  * Ross Ridge's mytinfo package.
40  */
41
42 #include <tparm_type.h>
43 #include <clear_cmd.h>
44 #include <reset_cmd.h>
45
46 #if !PURE_TERMINFO
47 #include <dump_entry.h>
48 #include <termsort.c>
49 #endif
50 #include <transform.h>
51 #include <tty_settings.h>
52
53 MODULE_ID("$Id: tput.c,v 1.72 2017/09/02 21:03:26 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 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 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(EXIT_FAILURE);
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 static int
139 tput_cmd(int fd, TTY * saved_settings, bool opt_x, int argc, char *argv[])
140 {
141     NCURSES_CONST char *name;
142     char *s;
143     int status;
144 #if !PURE_TERMINFO
145     bool termcap = FALSE;
146 #endif
147
148     name = check_aliases(argv[0], FALSE);
149     if (is_reset || is_init) {
150         TTY oldmode;
151
152         int terasechar = -1;    /* new erase character */
153         int intrchar = -1;      /* new interrupt character */
154         int tkillchar = -1;     /* new kill character */
155
156         if (is_reset) {
157             reset_start(stdout, TRUE, FALSE);
158             reset_tty_settings(fd, saved_settings);
159         } else {
160             reset_start(stdout, FALSE, TRUE);
161         }
162
163 #if HAVE_SIZECHANGE
164         set_window_size(fd, &lines, &columns);
165 #else
166         (void) fd;
167 #endif
168         set_control_chars(saved_settings, terasechar, intrchar, tkillchar);
169         set_conversions(saved_settings);
170         if (send_init_strings(fd, &oldmode)) {
171             reset_flush();
172         }
173
174         update_tty_settings(&oldmode, saved_settings);
175         return 0;
176     }
177
178     if (strcmp(name, "longname") == 0) {
179         PUTS(longname());
180         return 0;
181     }
182 #if !PURE_TERMINFO
183   retry:
184 #endif
185     if (strcmp(name, "clear") == 0) {
186         return clear_cmd(opt_x);
187     } else if ((status = tigetflag(name)) != -1) {
188         return exit_code(BOOLEAN, status);
189     } else if ((status = tigetnum(name)) != CANCELLED_NUMERIC) {
190         (void) printf("%d\n", status);
191         return exit_code(NUMBER, 0);
192     } else if ((s = tigetstr(name)) == CANCELLED_STRING) {
193 #if !PURE_TERMINFO
194         if (!termcap) {
195             const struct name_table_entry *np;
196
197             termcap = TRUE;
198             if ((np = _nc_find_entry(name, _nc_get_hash_table(termcap))) != 0) {
199                 switch (np->nte_type) {
200                 case BOOLEAN:
201                     name = boolnames[np->nte_index];
202                     break;
203
204                 case NUMBER:
205                     name = numnames[np->nte_index];
206                     break;
207
208                 case STRING:
209                     name = strnames[np->nte_index];
210                     break;
211                 }
212                 goto retry;
213             }
214         }
215 #endif
216         quit(4, "unknown terminfo capability '%s'", name);
217     } else if (VALID_STRING(s)) {
218         if (argc > 1) {
219             int k;
220             int ignored;
221             long numbers[1 + NUM_PARM];
222             char *strings[1 + NUM_PARM];
223             char *p_is_s[NUM_PARM];
224
225             /* Nasty hack time. The tparm function needs to see numeric
226              * parameters as numbers, not as pointers to their string
227              * representations
228              */
229
230             for (k = 1; k < argc; k++) {
231                 char *tmp = 0;
232                 strings[k] = argv[k];
233                 numbers[k] = strtol(argv[k], &tmp, 0);
234                 if (tmp == 0 || *tmp != 0)
235                     numbers[k] = 0;
236             }
237             for (k = argc; k <= NUM_PARM; k++) {
238                 numbers[k] = 0;
239                 strings[k] = 0;
240             }
241
242             switch (tparm_type(name)) {
243             case Num_Str:
244                 s = TPARM_2(s, numbers[1], strings[2]);
245                 break;
246             case Num_Str_Str:
247                 s = TPARM_3(s, numbers[1], strings[2], strings[3]);
248                 break;
249             case Numbers:
250             default:
251                 (void) _nc_tparm_analyze(s, p_is_s, &ignored);
252 #define myParam(n) (p_is_s[n - 1] != 0 ? ((TPARM_ARG) strings[n]) : numbers[n])
253                 s = TPARM_9(s,
254                             myParam(1),
255                             myParam(2),
256                             myParam(3),
257                             myParam(4),
258                             myParam(5),
259                             myParam(6),
260                             myParam(7),
261                             myParam(8),
262                             myParam(9));
263                 break;
264             }
265         }
266
267         /* use putp() in order to perform padding */
268         putp(s);
269         return exit_code(STRING, 0);
270     }
271     return exit_code(STRING, 1);
272 }
273
274 int
275 main(int argc, char **argv)
276 {
277     char *term;
278     int errret;
279     bool cmdline = TRUE;
280     int c;
281     char buf[BUFSIZ];
282     int result = 0;
283     int fd;
284     TTY tty_settings;
285     bool opt_x = FALSE;         /* clear scrollback if possible */
286
287     prg_name = check_aliases(_nc_rootname(argv[0]), TRUE);
288
289     term = getenv("TERM");
290
291     while ((c = getopt(argc, argv, "ST:V")) != -1) {
292         switch (c) {
293         case 'S':
294             cmdline = FALSE;
295             break;
296         case 'T':
297             use_env(FALSE);
298             term = optarg;
299             break;
300         case 'V':
301             puts(curses_version());
302             ExitProgram(EXIT_SUCCESS);
303         case 'x':               /* do not try to clear scrollback */
304             opt_x = TRUE;
305             break;
306         default:
307             usage();
308             /* NOTREACHED */
309         }
310     }
311
312     /*
313      * Modify the argument list to omit the options we processed.
314      */
315     if (is_clear || is_reset || is_init) {
316         if (optind-- < argc) {
317             argc -= optind;
318             argv += optind;
319         }
320         argv[0] = prg_name;
321     } else {
322         argc -= optind;
323         argv += optind;
324     }
325
326     if (term == 0 || *term == '\0')
327         quit(2, "No value for $TERM and no -T specified");
328
329     fd = save_tty_settings(&tty_settings);
330
331     if (setupterm(term, fd, &errret) != OK && errret <= 0)
332         quit(3, "unknown terminal \"%s\"", term);
333
334     if (cmdline) {
335         if ((argc <= 0) && !(is_clear || is_reset || is_init))
336             usage();
337         ExitProgram(tput_cmd(fd, &tty_settings, opt_x, argc, argv));
338     }
339
340     while (fgets(buf, sizeof(buf), stdin) != 0) {
341         char *argvec[16];       /* command, 9 parms, null, & slop */
342         int argnum = 0;
343         char *cp;
344
345         /* crack the argument list into a dope vector */
346         for (cp = buf; *cp; cp++) {
347             if (isspace(UChar(*cp))) {
348                 *cp = '\0';
349             } else if (cp == buf || cp[-1] == 0) {
350                 argvec[argnum++] = cp;
351                 if (argnum >= (int) SIZEOF(argvec) - 1)
352                     break;
353             }
354         }
355         argvec[argnum] = 0;
356
357         if (argnum != 0
358             && tput_cmd(fd, &tty_settings, opt_x, argnum, argvec) != 0) {
359             if (result == 0)
360                 result = 4;     /* will return value >4 */
361             ++result;
362         }
363     }
364
365     ExitProgram(result);
366 }