Merge branch 'vendor/NCURSES'
[dragonfly.git] / contrib / ncurses / progs / tic.c
1 /****************************************************************************
2  * Copyright (c) 1998-2002,2003 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  *      tic.c --- Main program for terminfo compiler
37  *                      by Eric S. Raymond
38  *
39  */
40
41 #include <progs.priv.h>
42 #include <sys/stat.h>
43
44 #include <dump_entry.h>
45 #include <term_entry.h>
46 #include <transform.h>
47
48 MODULE_ID("$Id: tic.c,v 1.109 2003/12/06 17:36:57 tom Exp $")
49
50 const char *_nc_progname = "tic";
51
52 static FILE *log_fp;
53 static FILE *tmp_fp;
54 static bool showsummary = FALSE;
55 static const char *to_remove;
56 static int tparm_errs;
57
58 static void (*save_check_termtype) (TERMTYPE *);
59 static void check_termtype(TERMTYPE * tt);
60
61 static const char usage_string[] = "[-V] [-v[n]] [-e names] [-o dir] [-R name] [-CILNTcfrswx1] source-file\n";
62
63 static void
64 cleanup(void)
65 {
66     if (tmp_fp != 0)
67         fclose(tmp_fp);
68     if (to_remove != 0) {
69 #if HAVE_REMOVE
70         remove(to_remove);
71 #else
72         unlink(to_remove);
73 #endif
74     }
75 }
76
77 static void
78 failed(const char *msg)
79 {
80     perror(msg);
81     cleanup();
82     ExitProgram(EXIT_FAILURE);
83 }
84
85 static void
86 usage(void)
87 {
88     static const char *const tbl[] =
89     {
90         "Options:",
91         "  -1         format translation output one capability per line",
92 #if NCURSES_XNAMES
93         "  -a         retain commented-out capabilities (sets -x also)",
94 #endif
95         "  -C         translate entries to termcap source form",
96         "  -c         check only, validate input without compiling or translating",
97         "  -e<names>  translate/compile only entries named by comma-separated list",
98         "  -f         format complex strings for readability",
99         "  -G         format %{number} to %'char'",
100         "  -g         format %'char' to %{number}",
101         "  -I         translate entries to terminfo source form",
102         "  -L         translate entries to full terminfo source form",
103         "  -N         disable smart defaults for source translation",
104         "  -o<dir>    set output directory for compiled entry writes",
105         "  -R<name>   restrict translation to given terminfo/termcap version",
106         "  -r         force resolution of all use entries in source translation",
107         "  -s         print summary statistics",
108         "  -T         remove size-restrictions on compiled description",
109 #if NCURSES_XNAMES
110         "  -t         suppress commented-out capabilities",
111 #endif
112         "  -V         print version",
113         "  -v[n]      set verbosity level",
114         "  -w[n]      set format width for translation output",
115 #if NCURSES_XNAMES
116         "  -x         treat unknown capabilities as user-defined",
117 #endif
118         "",
119         "Parameters:",
120         "  <file>     file to translate or compile"
121     };
122     size_t j;
123
124     fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
125     for (j = 0; j < SIZEOF(tbl); j++) {
126         fputs(tbl[j], stderr);
127         putc('\n', stderr);
128     }
129     ExitProgram(EXIT_FAILURE);
130 }
131
132 #define L_BRACE '{'
133 #define R_BRACE '}'
134 #define S_QUOTE '\'';
135
136 static void
137 write_it(ENTRY * ep)
138 {
139     unsigned n;
140     int ch;
141     char *s, *d, *t;
142     char result[MAX_ENTRY_SIZE];
143
144     /*
145      * Look for strings that contain %{number}, convert them to %'char',
146      * which is shorter and runs a little faster.
147      */
148     for (n = 0; n < STRCOUNT; n++) {
149         s = ep->tterm.Strings[n];
150         if (VALID_STRING(s)
151             && strchr(s, L_BRACE) != 0) {
152             d = result;
153             t = s;
154             while ((ch = *t++) != 0) {
155                 *d++ = ch;
156                 if (ch == '\\') {
157                     *d++ = *t++;
158                 } else if ((ch == '%')
159                            && (*t == L_BRACE)) {
160                     char *v = 0;
161                     long value = strtol(t + 1, &v, 0);
162                     if (v != 0
163                         && *v == R_BRACE
164                         && value > 0
165                         && value != '\\'        /* FIXME */
166                         && value < 127
167                         && isprint((int) value)) {
168                         *d++ = S_QUOTE;
169                         *d++ = (int) value;
170                         *d++ = S_QUOTE;
171                         t = (v + 1);
172                     }
173                 }
174             }
175             *d = 0;
176             if (strlen(result) < strlen(s))
177                 strcpy(s, result);
178         }
179     }
180
181     _nc_set_type(_nc_first_name(ep->tterm.term_names));
182     _nc_curr_line = ep->startline;
183     _nc_write_entry(&ep->tterm);
184 }
185
186 static bool
187 immedhook(ENTRY * ep GCC_UNUSED)
188 /* write out entries with no use capabilities immediately to save storage */
189 {
190 #if !HAVE_BIG_CORE
191     /*
192      * This is strictly a core-economy kluge.  The really clean way to handle
193      * compilation is to slurp the whole file into core and then do all the
194      * name-collision checks and entry writes in one swell foop.  But the
195      * terminfo master file is large enough that some core-poor systems swap
196      * like crazy when you compile it this way...there have been reports of
197      * this process taking *three hours*, rather than the twenty seconds or
198      * less typical on my development box.
199      *
200      * So.  This hook *immediately* writes out the referenced entry if it
201      * has no use capabilities.  The compiler main loop refrains from
202      * adding the entry to the in-core list when this hook fires.  If some
203      * other entry later needs to reference an entry that got written
204      * immediately, that's OK; the resolution code will fetch it off disk
205      * when it can't find it in core.
206      *
207      * Name collisions will still be detected, just not as cleanly.  The
208      * write_entry() code complains before overwriting an entry that
209      * postdates the time of tic's first call to write_entry().  Thus
210      * it will complain about overwriting entries newly made during the
211      * tic run, but not about overwriting ones that predate it.
212      *
213      * The reason this is a hook, and not in line with the rest of the
214      * compiler code, is that the support for termcap fallback cannot assume
215      * it has anywhere to spool out these entries!
216      *
217      * The _nc_set_type() call here requires a compensating one in
218      * _nc_parse_entry().
219      *
220      * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
221      * make tic a bit faster (because the resolution code won't have to do
222      * disk I/O nearly as often).
223      */
224     if (ep->nuses == 0) {
225         int oldline = _nc_curr_line;
226
227         write_it(ep);
228         _nc_curr_line = oldline;
229         free(ep->tterm.str_table);
230         return (TRUE);
231     }
232 #endif /* HAVE_BIG_CORE */
233     return (FALSE);
234 }
235
236 static void
237 put_translate(int c)
238 /* emit a comment char, translating terminfo names to termcap names */
239 {
240     static bool in_name = FALSE;
241     static size_t have, used;
242     static char *namebuf, *suffix;
243
244     if (in_name) {
245         if (used + 1 >= have) {
246             have += 132;
247             namebuf = typeRealloc(char, have, namebuf);
248             suffix = typeRealloc(char, have, suffix);
249         }
250         if (c == '\n' || c == '@') {
251             namebuf[used++] = '\0';
252             (void) putchar('<');
253             (void) fputs(namebuf, stdout);
254             putchar(c);
255             in_name = FALSE;
256         } else if (c != '>') {
257             namebuf[used++] = c;
258         } else {                /* ah! candidate name! */
259             char *up;
260             NCURSES_CONST char *tp;
261
262             namebuf[used++] = '\0';
263             in_name = FALSE;
264
265             suffix[0] = '\0';
266             if ((up = strchr(namebuf, '#')) != 0
267                 || (up = strchr(namebuf, '=')) != 0
268                 || ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
269                 (void) strcpy(suffix, up);
270                 *up = '\0';
271             }
272
273             if ((tp = nametrans(namebuf)) != 0) {
274                 (void) putchar(':');
275                 (void) fputs(tp, stdout);
276                 (void) fputs(suffix, stdout);
277                 (void) putchar(':');
278             } else {
279                 /* couldn't find a translation, just dump the name */
280                 (void) putchar('<');
281                 (void) fputs(namebuf, stdout);
282                 (void) fputs(suffix, stdout);
283                 (void) putchar('>');
284             }
285         }
286     } else {
287         used = 0;
288         if (c == '<') {
289             in_name = TRUE;
290         } else {
291             putchar(c);
292         }
293     }
294 }
295
296 /* Returns a string, stripped of leading/trailing whitespace */
297 static char *
298 stripped(char *src)
299 {
300     while (isspace(UChar(*src)))
301         src++;
302     if (*src != '\0') {
303         char *dst = strcpy((char *) malloc(strlen(src) + 1), src);
304         size_t len = strlen(dst);
305         while (--len != 0 && isspace(UChar(dst[len])))
306             dst[len] = '\0';
307         return dst;
308     }
309     return 0;
310 }
311
312 static FILE *
313 open_input(const char *filename)
314 {
315     FILE *fp = fopen(filename, "r");
316     struct stat sb;
317
318     if (fp == 0) {
319         fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
320         ExitProgram(EXIT_FAILURE);
321     }
322     if (fstat(fileno(fp), &sb) < 0
323         || (sb.st_mode & S_IFMT) != S_IFREG) {
324         fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
325         ExitProgram(EXIT_FAILURE);
326     }
327     return fp;
328 }
329
330 /* Parse the "-e" option-value into a list of names */
331 static const char **
332 make_namelist(char *src)
333 {
334     const char **dst = 0;
335
336     char *s, *base;
337     unsigned pass, n, nn;
338     char buffer[BUFSIZ];
339
340     if (src == 0) {
341         /* EMPTY */ ;
342     } else if (strchr(src, '/') != 0) {         /* a filename */
343         FILE *fp = open_input(src);
344
345         for (pass = 1; pass <= 2; pass++) {
346             nn = 0;
347             while (fgets(buffer, sizeof(buffer), fp) != 0) {
348                 if ((s = stripped(buffer)) != 0) {
349                     if (dst != 0)
350                         dst[nn] = s;
351                     nn++;
352                 }
353             }
354             if (pass == 1) {
355                 dst = typeCalloc(const char *, nn + 1);
356                 rewind(fp);
357             }
358         }
359         fclose(fp);
360     } else {                    /* literal list of names */
361         for (pass = 1; pass <= 2; pass++) {
362             for (n = nn = 0, base = src;; n++) {
363                 int mark = src[n];
364                 if (mark == ',' || mark == '\0') {
365                     if (pass == 1) {
366                         nn++;
367                     } else {
368                         src[n] = '\0';
369                         if ((s = stripped(base)) != 0)
370                             dst[nn++] = s;
371                         base = &src[n + 1];
372                     }
373                 }
374                 if (mark == '\0')
375                     break;
376             }
377             if (pass == 1)
378                 dst = typeCalloc(const char *, nn + 1);
379         }
380     }
381     if (showsummary) {
382         fprintf(log_fp, "Entries that will be compiled:\n");
383         for (n = 0; dst[n] != 0; n++)
384             fprintf(log_fp, "%d:%s\n", n + 1, dst[n]);
385     }
386     return dst;
387 }
388
389 static bool
390 matches(const char **needle, const char *haystack)
391 /* does entry in needle list match |-separated field in haystack? */
392 {
393     bool code = FALSE;
394     size_t n;
395
396     if (needle != 0) {
397         for (n = 0; needle[n] != 0; n++) {
398             if (_nc_name_match(haystack, needle[n], "|")) {
399                 code = TRUE;
400                 break;
401             }
402         }
403     } else
404         code = TRUE;
405     return (code);
406 }
407
408 static FILE *
409 open_tempfile(char *name)
410 {
411     FILE *result = 0;
412 #if HAVE_MKSTEMP
413     int fd = mkstemp(name);
414     if (fd >= 0)
415         result = fdopen(fd, "w");
416 #else
417     if (tmpnam(name) != 0)
418         result = fopen(name, "w");
419 #endif
420     return result;
421 }
422
423 int
424 main(int argc, char *argv[])
425 {
426     char my_tmpname[PATH_MAX];
427     int v_opt = -1, debug_level;
428     int smart_defaults = TRUE;
429     char *termcap;
430     ENTRY *qp;
431
432     int this_opt, last_opt = '?';
433
434     int outform = F_TERMINFO;   /* output format */
435     int sortmode = S_TERMINFO;  /* sort_mode */
436
437     int width = 60;
438     bool formatted = FALSE;     /* reformat complex strings? */
439     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
440     bool infodump = FALSE;      /* running as captoinfo? */
441     bool capdump = FALSE;       /* running as infotocap? */
442     bool forceresolve = FALSE;  /* force resolution */
443     bool limited = TRUE;
444     char *tversion = (char *) NULL;
445     const char *source_file = "terminfo";
446     const char **namelst = 0;
447     char *outdir = (char *) NULL;
448     bool check_only = FALSE;
449     bool suppress_untranslatable = FALSE;
450
451     log_fp = stderr;
452
453     _nc_progname = _nc_rootname(argv[0]);
454
455     if ((infodump = (strcmp(_nc_progname, PROG_CAPTOINFO) == 0)) != FALSE) {
456         outform = F_TERMINFO;
457         sortmode = S_TERMINFO;
458     }
459     if ((capdump = (strcmp(_nc_progname, PROG_INFOTOCAP) == 0)) != FALSE) {
460         outform = F_TERMCAP;
461         sortmode = S_TERMCAP;
462     }
463 #if NCURSES_XNAMES
464     use_extended_names(FALSE);
465 #endif
466
467     /*
468      * Processing arguments is a little complicated, since someone made a
469      * design decision to allow the numeric values for -w, -v options to
470      * be optional.
471      */
472     while ((this_opt = getopt(argc, argv,
473                               "0123456789CILNR:TVace:fGgo:rstvwx")) != EOF) {
474         if (isdigit(this_opt)) {
475             switch (last_opt) {
476             case 'v':
477                 v_opt = (v_opt * 10) + (this_opt - '0');
478                 break;
479             case 'w':
480                 width = (width * 10) + (this_opt - '0');
481                 break;
482             default:
483                 if (this_opt != '1')
484                     usage();
485                 last_opt = this_opt;
486                 width = 0;
487             }
488             continue;
489         }
490         switch (this_opt) {
491         case 'C':
492             capdump = TRUE;
493             outform = F_TERMCAP;
494             sortmode = S_TERMCAP;
495             break;
496         case 'I':
497             infodump = TRUE;
498             outform = F_TERMINFO;
499             sortmode = S_TERMINFO;
500             break;
501         case 'L':
502             infodump = TRUE;
503             outform = F_VARIABLE;
504             sortmode = S_VARIABLE;
505             break;
506         case 'N':
507             smart_defaults = FALSE;
508             break;
509         case 'R':
510             tversion = optarg;
511             break;
512         case 'T':
513             limited = FALSE;
514             break;
515         case 'V':
516             puts(curses_version());
517             return EXIT_SUCCESS;
518         case 'c':
519             check_only = TRUE;
520             break;
521         case 'e':
522             namelst = make_namelist(optarg);
523             break;
524         case 'f':
525             formatted = TRUE;
526             break;
527         case 'G':
528             numbers = 1;
529             break;
530         case 'g':
531             numbers = -1;
532             break;
533         case 'o':
534             outdir = optarg;
535             break;
536         case 'r':
537             forceresolve = TRUE;
538             break;
539         case 's':
540             showsummary = TRUE;
541             break;
542         case 'v':
543             v_opt = 0;
544             break;
545         case 'w':
546             width = 0;
547             break;
548 #if NCURSES_XNAMES
549         case 't':
550             _nc_disable_period = FALSE;
551             suppress_untranslatable = TRUE;
552             break;
553         case 'a':
554             _nc_disable_period = TRUE;
555             /* FALLTHRU */
556         case 'x':
557             use_extended_names(TRUE);
558             break;
559 #endif
560         default:
561             usage();
562         }
563         last_opt = this_opt;
564     }
565
566     debug_level = (v_opt > 0) ? v_opt : (v_opt == 0);
567     set_trace_level(debug_level);
568
569     if (_nc_tracing) {
570         save_check_termtype = _nc_check_termtype;
571         _nc_check_termtype = check_termtype;
572     }
573 #if !HAVE_BIG_CORE
574     /*
575      * Aaargh! immedhook seriously hoses us!
576      *
577      * One problem with immedhook is it means we can't do -e.  Problem
578      * is that we can't guarantee that for each terminal listed, all the
579      * terminals it depends on will have been kept in core for reference
580      * resolution -- in fact it's certain the primitive types at the end
581      * of reference chains *won't* be in core unless they were explicitly
582      * in the select list themselves.
583      */
584     if (namelst && (!infodump && !capdump)) {
585         (void) fprintf(stderr,
586                        "Sorry, -e can't be used without -I or -C\n");
587         cleanup();
588         return EXIT_FAILURE;
589     }
590 #endif /* HAVE_BIG_CORE */
591
592     if (optind < argc) {
593         source_file = argv[optind++];
594         if (optind < argc) {
595             fprintf(stderr,
596                     "%s: Too many file names.  Usage:\n\t%s %s",
597                     _nc_progname,
598                     _nc_progname,
599                     usage_string);
600             return EXIT_FAILURE;
601         }
602     } else {
603         if (infodump == TRUE) {
604             /* captoinfo's no-argument case */
605             source_file = "/etc/termcap";
606             if ((termcap = getenv("TERMCAP")) != 0
607                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
608                 if (access(termcap, F_OK) == 0) {
609                     /* file exists */
610                     source_file = termcap;
611                 } else if ((tmp_fp = open_tempfile(strcpy(my_tmpname,
612                                                           "/tmp/XXXXXX")))
613                            != 0) {
614                     source_file = my_tmpname;
615                     fprintf(tmp_fp, "%s\n", termcap);
616                     fclose(tmp_fp);
617                     tmp_fp = open_input(source_file);
618                     to_remove = source_file;
619                 } else {
620                     failed("tmpnam");
621                 }
622             }
623         } else {
624             /* tic */
625             fprintf(stderr,
626                     "%s: File name needed.  Usage:\n\t%s %s",
627                     _nc_progname,
628                     _nc_progname,
629                     usage_string);
630             cleanup();
631             return EXIT_FAILURE;
632         }
633     }
634
635     if (tmp_fp == 0)
636         tmp_fp = open_input(source_file);
637
638     if (infodump)
639         dump_init(tversion,
640                   smart_defaults
641                   ? outform
642                   : F_LITERAL,
643                   sortmode, width, debug_level, formatted);
644     else if (capdump)
645         dump_init(tversion,
646                   outform,
647                   sortmode, width, debug_level, FALSE);
648
649     /* parse entries out of the source file */
650     _nc_set_source(source_file);
651 #if !HAVE_BIG_CORE
652     if (!(check_only || infodump || capdump))
653         _nc_set_writedir(outdir);
654 #endif /* HAVE_BIG_CORE */
655     _nc_read_entry_source(tmp_fp, (char *) NULL,
656                           !smart_defaults, FALSE,
657                           (check_only || infodump || capdump) ? NULLHOOK : immedhook);
658
659     /* do use resolution */
660     if (check_only || (!infodump && !capdump) || forceresolve) {
661         if (!_nc_resolve_uses(TRUE) && !check_only) {
662             cleanup();
663             return EXIT_FAILURE;
664         }
665     }
666
667     /* length check */
668     if (check_only && (capdump || infodump)) {
669         for_entry_list(qp) {
670             if (matches(namelst, qp->tterm.term_names)) {
671                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
672
673                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
674                     (void) fprintf(stderr,
675                                    "warning: resolved %s entry is %d bytes long\n",
676                                    _nc_first_name(qp->tterm.term_names),
677                                    len);
678             }
679         }
680     }
681
682     /* write or dump all entries */
683     if (!check_only) {
684         if (!infodump && !capdump) {
685             _nc_set_writedir(outdir);
686             for_entry_list(qp) {
687                 if (matches(namelst, qp->tterm.term_names))
688                     write_it(qp);
689             }
690         } else {
691             /* this is in case infotocap() generates warnings */
692             _nc_curr_col = _nc_curr_line = -1;
693
694             for_entry_list(qp) {
695                 if (matches(namelst, qp->tterm.term_names)) {
696                     int j = qp->cend - qp->cstart;
697                     int len = 0;
698
699                     /* this is in case infotocap() generates warnings */
700                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
701
702                     (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
703                     while (j--) {
704                         if (infodump)
705                             (void) putchar(fgetc(tmp_fp));
706                         else
707                             put_translate(fgetc(tmp_fp));
708                     }
709
710                     len = dump_entry(&qp->tterm, suppress_untranslatable,
711                                      limited, 0, numbers, NULL);
712                     for (j = 0; j < qp->nuses; j++)
713                         len += dump_uses(qp->uses[j].name, !capdump);
714                     (void) putchar('\n');
715                     if (debug_level != 0 && !limited)
716                         printf("# length=%d\n", len);
717                 }
718             }
719             if (!namelst && _nc_tail) {
720                 int c, oldc = '\0';
721                 bool in_comment = FALSE;
722                 bool trailing_comment = FALSE;
723
724                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
725                 while ((c = fgetc(tmp_fp)) != EOF) {
726                     if (oldc == '\n') {
727                         if (c == '#') {
728                             trailing_comment = TRUE;
729                             in_comment = TRUE;
730                         } else {
731                             in_comment = FALSE;
732                         }
733                     }
734                     if (trailing_comment
735                         && (in_comment || (oldc == '\n' && c == '\n')))
736                         putchar(c);
737                     oldc = c;
738                 }
739             }
740         }
741     }
742
743     /* Show the directory into which entries were written, and the total
744      * number of entries
745      */
746     if (showsummary
747         && (!(check_only || infodump || capdump))) {
748         int total = _nc_tic_written();
749         if (total != 0)
750             fprintf(log_fp, "%d entries written to %s\n",
751                     total,
752                     _nc_tic_dir((char *) 0));
753         else
754             fprintf(log_fp, "No entries written\n");
755     }
756     cleanup();
757     return (EXIT_SUCCESS);
758 }
759
760 /*
761  * This bit of legerdemain turns all the terminfo variable names into
762  * references to locations in the arrays Booleans, Numbers, and Strings ---
763  * precisely what's needed (see comp_parse.c).
764  */
765
766 TERMINAL *cur_term;             /* tweak to avoid linking lib_cur_term.c */
767
768 #undef CUR
769 #define CUR tp->
770
771 /*
772  * Check if the alternate character-set capabilities are consistent.
773  */
774 static void
775 check_acs(TERMTYPE * tp)
776 {
777     if (VALID_STRING(acs_chars)) {
778         const char *boxes = "lmkjtuvwqxn";
779         char mapped[256];
780         char missing[256];
781         const char *p;
782         char *q;
783
784         memset(mapped, 0, sizeof(mapped));
785         for (p = acs_chars; *p != '\0'; p += 2) {
786             if (p[1] == '\0') {
787                 _nc_warning("acsc has odd number of characters");
788                 break;
789             }
790             mapped[UChar(p[0])] = p[1];
791         }
792         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
793             _nc_warning("acsc refers to 'I', which is probably an error");
794         }
795         for (p = boxes, q = missing; *p != '\0'; ++p) {
796             if (!mapped[UChar(p[0])]) {
797                 *q++ = p[0];
798             }
799             *q = '\0';
800         }
801         if (*missing != '\0' && strcmp(missing, boxes)) {
802             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
803         }
804     }
805 }
806
807 /*
808  * Check if the color capabilities are consistent
809  */
810 static void
811 check_colors(TERMTYPE * tp)
812 {
813     if ((max_colors > 0) != (max_pairs > 0)
814         || ((max_colors > max_pairs) && (initialize_pair == 0)))
815         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
816                     max_colors, max_pairs);
817
818     PAIRED(set_foreground, set_background);
819     PAIRED(set_a_foreground, set_a_background);
820     PAIRED(set_color_pair, initialize_pair);
821
822     if (VALID_STRING(set_foreground)
823         && VALID_STRING(set_a_foreground)
824         && !strcmp(set_foreground, set_a_foreground))
825         _nc_warning("expected setf/setaf to be different");
826
827     if (VALID_STRING(set_background)
828         && VALID_STRING(set_a_background)
829         && !strcmp(set_background, set_a_background))
830         _nc_warning("expected setb/setab to be different");
831
832     /* see: has_colors() */
833     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
834         && (((set_foreground != NULL)
835              && (set_background != NULL))
836             || ((set_a_foreground != NULL)
837                 && (set_a_background != NULL))
838             || set_color_pair)) {
839         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
840             _nc_warning("expected either op/oc string for resetting colors");
841     }
842 }
843
844 static int
845 keypad_final(const char *string)
846 {
847     int result = '\0';
848
849     if (VALID_STRING(string)
850         && *string++ == '\033'
851         && *string++ == 'O'
852         && strlen(string) == 1) {
853         result = *string;
854     }
855
856     return result;
857 }
858
859 static int
860 keypad_index(const char *string)
861 {
862     char *test;
863     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
864     int ch;
865     int result = -1;
866
867     if ((ch = keypad_final(string)) != '\0') {
868         test = strchr(list, ch);
869         if (test != 0)
870             result = (test - list);
871     }
872     return result;
873 }
874
875 /*
876  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
877  * is mapped inconsistently.
878  */
879 static void
880 check_keypad(TERMTYPE * tp)
881 {
882     char show[80];
883
884     if (VALID_STRING(key_a1) &&
885         VALID_STRING(key_a3) &&
886         VALID_STRING(key_b2) &&
887         VALID_STRING(key_c1) &&
888         VALID_STRING(key_c3)) {
889         char final[6];
890         int list[5];
891         int increase = 0;
892         int j, k, kk;
893         int last;
894         int test;
895
896         final[0] = keypad_final(key_a1);
897         final[1] = keypad_final(key_a3);
898         final[2] = keypad_final(key_b2);
899         final[3] = keypad_final(key_c1);
900         final[4] = keypad_final(key_c3);
901         final[5] = '\0';
902
903         /* special case: legacy coding using 1,2,3,0,. on the bottom */
904         if (!strcmp(final, "qsrpn"))
905             return;
906
907         list[0] = keypad_index(key_a1);
908         list[1] = keypad_index(key_a3);
909         list[2] = keypad_index(key_b2);
910         list[3] = keypad_index(key_c1);
911         list[4] = keypad_index(key_c3);
912
913         /* check that they're all vt100 keys */
914         for (j = 0; j < 5; ++j) {
915             if (list[j] < 0) {
916                 return;
917             }
918         }
919
920         /* check if they're all in increasing order */
921         for (j = 1; j < 5; ++j) {
922             if (list[j] > list[j - 1]) {
923                 ++increase;
924             }
925         }
926         if (increase != 4) {
927             show[0] = '\0';
928
929             for (j = 0, last = -1; j < 5; ++j) {
930                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
931                     if (list[k] > last &&
932                         list[k] < test) {
933                         test = list[k];
934                         kk = k;
935                     }
936                 }
937                 last = test;
938                 switch (kk) {
939                 case 0:
940                     strcat(show, " ka1");
941                     break;
942                 case 1:
943                     strcat(show, " ka3");
944                     break;
945                 case 2:
946                     strcat(show, " kb2");
947                     break;
948                 case 3:
949                     strcat(show, " kc1");
950                     break;
951                 case 4:
952                     strcat(show, " kc3");
953                     break;
954                 }
955             }
956
957             _nc_warning("vt100 keypad order inconsistent: %s", show);
958         }
959
960     } else if (VALID_STRING(key_a1) ||
961                VALID_STRING(key_a3) ||
962                VALID_STRING(key_b2) ||
963                VALID_STRING(key_c1) ||
964                VALID_STRING(key_c3)) {
965         show[0] = '\0';
966         if (keypad_index(key_a1) >= 0)
967             strcat(show, " ka1");
968         if (keypad_index(key_a3) >= 0)
969             strcat(show, " ka3");
970         if (keypad_index(key_b2) >= 0)
971             strcat(show, " kb2");
972         if (keypad_index(key_c1) >= 0)
973             strcat(show, " kc1");
974         if (keypad_index(key_c3) >= 0)
975             strcat(show, " kc3");
976         if (*show != '\0')
977             _nc_warning("vt100 keypad map incomplete:%s", show);
978     }
979 }
980
981 /*
982  * Returns the expected number of parameters for the given capability.
983  */
984 static int
985 expected_params(const char *name)
986 {
987     /* *INDENT-OFF* */
988     static const struct {
989         const char *name;
990         int count;
991     } table[] = {
992         { "S0",                 1 },    /* 'screen' extension */
993         { "birep",              2 },
994         { "chr",                1 },
995         { "colornm",            1 },
996         { "cpi",                1 },
997         { "csnm",               1 },
998         { "csr",                2 },
999         { "cub",                1 },
1000         { "cud",                1 },
1001         { "cuf",                1 },
1002         { "cup",                2 },
1003         { "cuu",                1 },
1004         { "cvr",                1 },
1005         { "cwin",               5 },
1006         { "dch",                1 },
1007         { "defc",               3 },
1008         { "dial",               1 },
1009         { "dispc",              1 },
1010         { "dl",                 1 },
1011         { "ech",                1 },
1012         { "getm",               1 },
1013         { "hpa",                1 },
1014         { "ich",                1 },
1015         { "il",                 1 },
1016         { "indn",               1 },
1017         { "initc",              4 },
1018         { "initp",              7 },
1019         { "lpi",                1 },
1020         { "mc5p",               1 },
1021         { "mrcup",              2 },
1022         { "mvpa",               1 },
1023         { "pfkey",              2 },
1024         { "pfloc",              2 },
1025         { "pfx",                2 },
1026         { "pfxl",               3 },
1027         { "pln",                2 },
1028         { "qdial",              1 },
1029         { "rcsd",               1 },
1030         { "rep",                2 },
1031         { "rin",                1 },
1032         { "sclk",               3 },
1033         { "scp",                1 },
1034         { "scs",                1 },
1035         { "scsd",               2 },
1036         { "setab",              1 },
1037         { "setaf",              1 },
1038         { "setb",               1 },
1039         { "setcolor",           1 },
1040         { "setf",               1 },
1041         { "sgr",                9 },
1042         { "sgr1",               6 },
1043         { "slength",            1 },
1044         { "slines",             1 },
1045         { "smgbp",              1 },    /* 2 if smgtp is not given */
1046         { "smglp",              1 },
1047         { "smglr",              2 },
1048         { "smgrp",              1 },
1049         { "smgtb",              2 },
1050         { "smgtp",              1 },
1051         { "tsl",                1 },
1052         { "u6",                 -1 },
1053         { "vpa",                1 },
1054         { "wind",               4 },
1055         { "wingo",              1 },
1056     };
1057     /* *INDENT-ON* */
1058
1059     unsigned n;
1060     int result = 0;             /* function-keys, etc., use none */
1061
1062     for (n = 0; n < SIZEOF(table); n++) {
1063         if (!strcmp(name, table[n].name)) {
1064             result = table[n].count;
1065             break;
1066         }
1067     }
1068
1069     return result;
1070 }
1071
1072 /*
1073  * Make a quick sanity check for the parameters which are used in the given
1074  * strings.  If there are no "%p" tokens, then there should be no other "%"
1075  * markers.
1076  */
1077 static void
1078 check_params(TERMTYPE * tp, const char *name, char *value)
1079 {
1080     int expected = expected_params(name);
1081     int actual = 0;
1082     int n;
1083     bool params[10];
1084     char *s = value;
1085
1086 #ifdef set_top_margin_parm
1087     if (!strcmp(name, "smgbp")
1088         && set_top_margin_parm == 0)
1089         expected = 2;
1090 #endif
1091
1092     for (n = 0; n < 10; n++)
1093         params[n] = FALSE;
1094
1095     while (*s != 0) {
1096         if (*s == '%') {
1097             if (*++s == '\0') {
1098                 _nc_warning("expected character after %% in %s", name);
1099                 break;
1100             } else if (*s == 'p') {
1101                 if (*++s == '\0' || !isdigit((int) *s)) {
1102                     _nc_warning("expected digit after %%p in %s", name);
1103                     return;
1104                 } else {
1105                     n = (*s - '0');
1106                     if (n > actual)
1107                         actual = n;
1108                     params[n] = TRUE;
1109                 }
1110             }
1111         }
1112         s++;
1113     }
1114
1115     if (params[0]) {
1116         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1117     }
1118     if (value == set_attributes || expected < 0) {
1119         ;
1120     } else if (expected != actual) {
1121         _nc_warning("%s uses %d parameters, expected %d", name,
1122                     actual, expected);
1123         for (n = 1; n < actual; n++) {
1124             if (!params[n])
1125                 _nc_warning("%s omits parameter %d", name, n);
1126         }
1127     }
1128 }
1129
1130 static char *
1131 skip_delay(char *s)
1132 {
1133     while (*s == '/' || isdigit(UChar(*s)))
1134         ++s;
1135     return s;
1136 }
1137
1138 /*
1139  * An sgr string may contain several settings other than the one we're
1140  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
1141  * "whatever" is contained in the sgr string, that is close enough for our
1142  * sanity check.
1143  */
1144 static bool
1145 similar_sgr(int num, char *a, char *b)
1146 {
1147     static const char *names[] =
1148     {
1149         "none"
1150         ,"standout"
1151         ,"underline"
1152         ,"reverse"
1153         ,"blink"
1154         ,"dim"
1155         ,"bold"
1156         ,"invis"
1157         ,"protect"
1158         ,"altcharset"
1159     };
1160     char *base_a = a;
1161     char *base_b = b;
1162     int delaying = 0;
1163
1164     while (*b != 0) {
1165         while (*a != *b) {
1166             if (*a == 0) {
1167                 if (b[0] == '$'
1168                     && b[1] == '<') {
1169                     _nc_warning("Did not find delay %s", _nc_visbuf(b));
1170                 } else {
1171                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
1172                                 names[num], _nc_visbuf2(1, base_a),
1173                                 _nc_visbuf2(2, base_b),
1174                                 _nc_visbuf2(3, b));
1175                 }
1176                 return FALSE;
1177             } else if (delaying) {
1178                 a = skip_delay(a);
1179                 b = skip_delay(b);
1180             } else {
1181                 a++;
1182             }
1183         }
1184         switch (*a) {
1185         case '$':
1186             if (delaying == 0)
1187                 delaying = 1;
1188             break;
1189         case '<':
1190             if (delaying == 1)
1191                 delaying = 2;
1192             break;
1193         default:
1194             delaying = 0;
1195             break;
1196         }
1197         a++;
1198         b++;
1199     }
1200     return TRUE;
1201 }
1202
1203 static void
1204 check_sgr(TERMTYPE * tp, char *zero, int num, char *cap, const char *name)
1205 {
1206     char *test = tparm(set_attributes,
1207                        num == 1,
1208                        num == 2,
1209                        num == 3,
1210                        num == 4,
1211                        num == 5,
1212                        num == 6,
1213                        num == 7,
1214                        num == 8,
1215                        num == 9);
1216     tparm_errs += _nc_tparm_err;
1217     if (test != 0) {
1218         if (PRESENT(cap)) {
1219             if (!similar_sgr(num, test, cap)) {
1220                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
1221                             name, num,
1222                             name, _nc_visbuf2(1, cap),
1223                             num, _nc_visbuf2(2, test));
1224             }
1225         } else if (strcmp(test, zero)) {
1226             _nc_warning("sgr(%d) present, but not %s", num, name);
1227         }
1228     } else if (PRESENT(cap)) {
1229         _nc_warning("sgr(%d) missing, but %s present", num, name);
1230     }
1231 }
1232
1233 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
1234
1235 /* other sanity-checks (things that we don't want in the normal
1236  * logic that reads a terminfo entry)
1237  */
1238 static void
1239 check_termtype(TERMTYPE * tp)
1240 {
1241     bool conflict = FALSE;
1242     unsigned j, k;
1243     char fkeys[STRCOUNT];
1244
1245     /*
1246      * A terminal entry may contain more than one keycode assigned to
1247      * a given string (e.g., KEY_END and KEY_LL).  But curses will only
1248      * return one (the last one assigned).
1249      */
1250     memset(fkeys, 0, sizeof(fkeys));
1251     for (j = 0; _nc_tinfo_fkeys[j].code; j++) {
1252         char *a = tp->Strings[_nc_tinfo_fkeys[j].offset];
1253         bool first = TRUE;
1254         if (!VALID_STRING(a))
1255             continue;
1256         for (k = j + 1; _nc_tinfo_fkeys[k].code; k++) {
1257             char *b = tp->Strings[_nc_tinfo_fkeys[k].offset];
1258             if (!VALID_STRING(b)
1259                 || fkeys[k])
1260                 continue;
1261             if (!strcmp(a, b)) {
1262                 fkeys[j] = 1;
1263                 fkeys[k] = 1;
1264                 if (first) {
1265                     if (!conflict) {
1266                         _nc_warning("Conflicting key definitions (using the last)");
1267                         conflict = TRUE;
1268                     }
1269                     fprintf(stderr, "... %s is the same as %s",
1270                             keyname(_nc_tinfo_fkeys[j].code),
1271                             keyname(_nc_tinfo_fkeys[k].code));
1272                     first = FALSE;
1273                 } else {
1274                     fprintf(stderr, ", %s",
1275                             keyname(_nc_tinfo_fkeys[k].code));
1276                 }
1277             }
1278         }
1279         if (!first)
1280             fprintf(stderr, "\n");
1281     }
1282
1283     for (j = 0; j < NUM_STRINGS(tp); j++) {
1284         char *a = tp->Strings[j];
1285         if (VALID_STRING(a))
1286             check_params(tp, ExtStrname(tp, j, strnames), a);
1287     }
1288
1289     check_acs(tp);
1290     check_colors(tp);
1291     check_keypad(tp);
1292
1293     /*
1294      * These may be mismatched because the terminal description relies on
1295      * restoring the cursor visibility by resetting it.
1296      */
1297     ANDMISSING(cursor_invisible, cursor_normal);
1298     ANDMISSING(cursor_visible, cursor_normal);
1299
1300     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
1301         && !strcmp(cursor_visible, cursor_normal))
1302         _nc_warning("cursor_visible is same as cursor_normal");
1303
1304     /*
1305      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
1306      * given, because the cursor position after the scrolling operation is
1307      * performed is undefined.
1308      */
1309     ANDMISSING(change_scroll_region, save_cursor);
1310     ANDMISSING(change_scroll_region, restore_cursor);
1311
1312     tparm_errs = 0;
1313     if (PRESENT(set_attributes)) {
1314         char *zero = tparm(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1315
1316         zero = strdup(zero);
1317         CHECK_SGR(1, enter_standout_mode);
1318         CHECK_SGR(2, enter_underline_mode);
1319         CHECK_SGR(3, enter_reverse_mode);
1320         CHECK_SGR(4, enter_blink_mode);
1321         CHECK_SGR(5, enter_dim_mode);
1322         CHECK_SGR(6, enter_bold_mode);
1323         CHECK_SGR(7, enter_secure_mode);
1324         CHECK_SGR(8, enter_protected_mode);
1325         CHECK_SGR(9, enter_alt_charset_mode);
1326         free(zero);
1327         if (tparm_errs)
1328             _nc_warning("stack error in sgr string");
1329     }
1330
1331     /*
1332      * Some standard applications (e.g., vi) and some non-curses
1333      * applications (e.g., jove) get confused if we have both ich1 and
1334      * smir/rmir.  Let's be nice and warn about that, too, even though
1335      * ncurses handles it.
1336      */
1337     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
1338         && PRESENT(parm_ich)) {
1339         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
1340     }
1341
1342     /*
1343      * Finally, do the non-verbose checks
1344      */
1345     if (save_check_termtype != 0)
1346         save_check_termtype(tp);
1347 }