]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/picsmap.c
ncurses 6.2 - patch 20210417
[ncurses.git] / test / picsmap.c
1 /****************************************************************************
2  * Copyright 2018-2020,2021 Thomas E. Dickey                                *
3  * Copyright 2017,2018 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  * $Id: picsmap.c,v 1.137 2021/03/27 22:52:16 tom Exp $
31  *
32  * Author: Thomas E. Dickey
33  *
34  * A little more interesting than "dots", read a simple image into memory and
35  * measure the time taken to paint it normally vs randomly.
36  *
37  * TODO improve use of rgb-names using tsearch.
38  *
39  * TODO add option to dump picture in non-optimized mode, e.g., like tput.
40  * TODO write cells/second to stderr (or log)
41  * TODO write picture left-to-right/top-to-bottom
42  * TODO write picture randomly
43  * TODO add one-shot option vs repeat-count before exiting
44  * TODO add option "-xc" for init_color vs init_extended_color
45  * TODO add option "-xa" for init_pair vs alloc_pair
46  * TODO use pad to allow pictures larger than screen
47  * TODO add option to just use convert (which can scale) vs builtin xbm/xpm.
48  * TODO add scr_dump and scr_restore calls
49  * TODO add option for assume_default_colors
50  */
51 #include <test.priv.h>
52
53 #include <sys/types.h>
54 #include <sys/stat.h>
55
56 #if HAVE_STDINT_H
57 #include <stdint.h>
58 #define my_intptr_t     intptr_t
59 #else
60 #define my_intptr_t     long
61 #endif
62
63 #if HAVE_TSEARCH
64 #include <search.h>
65 #endif
66
67 #undef CUR                      /* use only the curses interface */
68
69 #define  L_BLOCK '['
70 #define  R_BLOCK ']'
71
72 #define  L_CURLY '{'
73 #define  R_CURLY '}'
74
75 #define MaxSCALE        1000    /* input curses ranges 0..1000 */
76 #define MaxRGB          255     /* output color ranges 0..255 */
77 #define okCOLOR(n)      ((n) >= 0 && (n) < COLORS)
78 #define okSCALE(n)      ((n) >= 0 && (n) <= MaxSCALE)
79 #define Scaled256(n)    (NCURSES_COLOR_T) (int)(((double)(n) * MaxSCALE) / 255)
80 #define ScaledColor(n)  (NCURSES_COLOR_T) (int)(((double)(n) * MaxSCALE) / scale)
81
82 #ifndef RGB_PATH
83 #define RGB_PATH "/etc/X11/rgb.txt"
84 #endif
85
86 #include <picsmap.h>
87
88 typedef struct {
89     size_t file;
90     size_t name;
91     size_t list;
92     size_t data;
93     size_t head;
94     size_t pair;
95     size_t cell;
96 } HOW_MUCH;
97
98 #undef MAX
99 #define MAX(a,b) ((a)>(b)?(a):(b))
100
101 /*
102  * tfind will return null on failure, so we map subscripts starting at one.
103  */
104 #define P2I(n) (((int)(my_intptr_t)(n)) - 1)
105 #define I2P(n) (void *)(my_intptr_t)((n) + 1)
106
107 #define pause_curses() if (in_curses) stop_curses()
108
109 #define debugmsg if (debugging) logmsg
110 #define debugmsg2 if (debugging) logmsg2
111
112 static GCC_NORETURN void cleanup(int);
113 static void giveup(const char *fmt, ...) GCC_PRINTFLIKE(1, 2);
114 static void logmsg(const char *fmt, ...) GCC_PRINTFLIKE(1, 2);
115 static void logmsg2(const char *fmt, ...) GCC_PRINTFLIKE(1, 2);
116 static void warning(const char *fmt, ...) GCC_PRINTFLIKE(1, 2);
117 static int gather_c_values(int);
118
119 static FILE *logfp = 0;
120 static double aspect_ratio = 0.6;
121 static bool in_curses = FALSE;
122 static bool debugging = FALSE;
123 static bool quiet = FALSE;
124 static int slow_time = -1;
125 static RGB_NAME *rgb_table;
126 static RGB_DATA *all_colors;
127 static HOW_MUCH how_much;
128
129 static int reading_last;
130 static int reading_size;
131 static FG_NODE *reading_ncols;
132
133 #if HAVE_TSEARCH
134 static void *reading_ntree;
135 #endif
136
137 #if HAVE_ALLOC_PAIR && USE_EXTENDED_COLOR
138 #define USE_EXTENDED_COLORS 1
139 static bool use_extended_pairs = FALSE;
140 static bool use_extended_colors = FALSE;
141 #else
142 #define USE_EXTENDED_COLORS 0
143 #endif
144
145 static void
146 logmsg(const char *fmt, ...)
147 {
148     if (logfp != 0) {
149         va_list ap;
150         va_start(ap, fmt);
151         vfprintf(logfp, fmt, ap);
152         va_end(ap);
153         fputc('\n', logfp);
154         fflush(logfp);
155     }
156 }
157
158 static void
159 logmsg2(const char *fmt, ...)
160 {
161     if (logfp != 0) {
162         va_list ap;
163         va_start(ap, fmt);
164         vfprintf(logfp, fmt, ap);
165         va_end(ap);
166         fflush(logfp);
167     }
168 }
169
170 static void
171 close_log(void)
172 {
173     if (logfp != 0) {
174         logmsg("Allocations:");
175         logmsg("%8ld file", (long) how_much.file);
176         logmsg("%8ld name", (long) how_much.name);
177         logmsg("%8ld list", (long) how_much.list);
178         logmsg("%8ld data", (long) how_much.data);
179         logmsg("%8ld head", (long) how_much.head);
180         logmsg("%8ld pair", (long) how_much.pair);
181         logmsg("%8ld cell", (long) how_much.cell);
182         logmsg("%8ld window", LINES * COLS * (long) sizeof(NCURSES_CH_T));
183         fclose(logfp);
184         logfp = 0;
185     }
186 }
187
188 static void
189 cleanup(int code)
190 {
191     pause_curses();
192     close_log();
193     ExitProgram(code);
194     /* NOTREACHED */
195 }
196
197 static void
198 failed(const char *msg)
199 {
200     int save = errno;
201     perror(msg);
202     logmsg("failed with %s", strerror(save));
203     cleanup(EXIT_FAILURE);
204 }
205
206 static void
207 warning(const char *fmt, ...)
208 {
209     if (logfp != 0) {
210         va_list ap;
211         va_start(ap, fmt);
212         vfprintf(logfp, fmt, ap);
213         va_end(ap);
214         fputc('\n', logfp);
215         fflush(logfp);
216     } else {
217         va_list ap;
218         va_start(ap, fmt);
219         vfprintf(stderr, fmt, ap);
220         va_end(ap);
221         fputc('\n', stderr);
222         cleanup(EXIT_FAILURE);
223     }
224 }
225
226 static void
227 free_data(char **data)
228 {
229     if (data != 0) {
230         free(data[0]);
231         free(data);
232     }
233 }
234
235 static PICS_HEAD *
236 free_pics_head(PICS_HEAD * pics)
237 {
238     if (pics != 0) {
239         free(pics->fgcol);
240         free(pics->cells);
241         free(pics->name);
242         free(pics);
243         pics = 0;
244     }
245     return pics;
246 }
247
248 static void
249 begin_c_values(int size)
250 {
251     reading_last = 0;
252     reading_size = size;
253     reading_ncols = typeCalloc(FG_NODE, size + 1);
254     how_much.pair += (sizeof(FG_NODE) * (size_t) size);
255     /* black is always the first slot, to work around P2I/I2P logic */
256     gather_c_values(0);
257 }
258
259 #if HAVE_TSEARCH
260 static int
261 compare_c_values(const void *p, const void *q)
262 {
263     const int a = P2I(p);
264     const int b = P2I(q);
265     return (reading_ncols[a].fgcol - reading_ncols[b].fgcol);
266 }
267
268 #ifdef DEBUG_TSEARCH
269 static void
270 check_c_values(int ln)
271 {
272     static int oops = 5;
273     FG_NODE **ft;
274     int n;
275     for (n = 0; n < reading_last; ++n) {
276         ft = tfind(I2P(n), &reading_ntree, compare_c_values);
277         if (ft != 0) {
278             int q = P2I(*ft);
279             if (reading_ncols[q].fgcol != reading_ncols[n].fgcol) {
280                 logmsg("@%d, %d:%d (%d) %d %d fgcol %06X %06X", ln, n,
281                        reading_last - 1,
282                        reading_size,
283                        q, n,
284                        reading_ncols[n].fgcol,
285                        reading_ncols[q].fgcol);
286             }
287         } else {
288             logmsg("@%d, %d:%d (%d) ? %d null %06X", ln, n,
289                    reading_last - 1,
290                    reading_size,
291                    n,
292                    reading_ncols[n].fgcol);
293             if (oops-- <= 0)
294                 return;
295         }
296     }
297 }
298 #else
299 #define check_c_values(n)       /* nothing */
300 #endif
301 #endif
302
303 static int
304 gather_c_values(int fg)
305 {
306     int found = -1;
307 #if HAVE_TSEARCH
308     FG_NODE **ft;
309     int next = reading_last;
310
311     reading_ncols[next].fgcol = fg;
312     reading_ncols[next].count = 0;
313
314     check_c_values(__LINE__);
315     if ((ft = tfind(I2P(next), &reading_ntree, compare_c_values)) != 0) {
316         found = P2I(*ft);
317     } else {
318         if (reading_last + 2 >= reading_size) {
319             int more = ((MAX(reading_last, reading_size) + 2) * 3) / 2;
320             int last = reading_last + 1;
321             FG_NODE *p = typeRealloc(FG_NODE, more, reading_ncols);
322             if (p == 0)
323                 goto done;
324
325             reading_size = more;
326             reading_ncols = p;
327             memset(reading_ncols + last, 0,
328                    sizeof(FG_NODE) * (size_t) (more - last));
329             check_c_values(__LINE__);
330         }
331         ++reading_last;
332         how_much.pair += sizeof(FG_NODE);
333         if ((ft = tsearch(I2P(next), &reading_ntree, compare_c_values)) != 0) {
334             found = P2I(*ft);
335             if (found != next)
336                 logmsg("OOPS expected slot %d, got %d", next, found);
337             debugmsg("allocated color #%d as #%06X", next, fg);
338             check_c_values(__LINE__);
339         }
340     }
341 #else
342     int n;
343
344     for (n = 0; n < reading_last; ++n) {
345         if (reading_ncols[n].fgcol == fg) {
346             found = n;
347             break;
348         }
349     }
350     if (found < 0) {
351         if (reading_last + 2 >= reading_size) {
352             int more = ((reading_last + 2) * 3) / 2;
353             FG_NODE *p = typeRealloc(FG_NODE, more, reading_ncols);
354             if (p == 0)
355                 goto done;
356
357             how_much.pair -= (sizeof(FG_NODE) * (size_t) reading_size);
358             how_much.pair += (sizeof(FG_NODE) * (size_t) more);
359             reading_size = more;
360             reading_ncols = p;
361             memset(reading_ncols + reading_last, 0,
362                    sizeof(FG_NODE) * (size_t) (more - reading_last));
363         }
364         reading_ncols[reading_last].fgcol = fg;
365         found = reading_last++;
366     }
367 #endif
368   done:
369     return found;
370 }
371
372 static void
373 finish_c_values(PICS_HEAD * head)
374 {
375     head->colors = reading_last;
376     head->fgcol = reading_ncols;
377
378     reading_last = 0;
379     reading_size = 0;
380     reading_ncols = 0;
381 }
382
383 static void
384 dispose_c_values(void)
385 {
386 #if HAVE_TSEARCH
387     if (reading_ntree != 0) {
388         int n;
389         for (n = 0; n < reading_last; ++n) {
390             tdelete(I2P(n), &reading_ntree, compare_c_values);
391         }
392         reading_ntree = 0;
393     }
394 #endif
395     if (reading_ncols != 0) {
396         free(reading_ncols);
397         reading_ncols = 0;
398     }
399     reading_last = 0;
400     reading_size = 0;
401 }
402
403 static int
404 is_file(const char *filename, struct stat *sb)
405 {
406     int result = 0;
407     if (stat(filename, sb) == 0
408         && (sb->st_mode & S_IFMT) == S_IFREG
409         && sb->st_size != 0) {
410         result = 1;
411     }
412     debugmsg("is_file(%s) %d", filename, result);
413     return result;
414 }
415
416 /*
417  * Simplify reading xbm/xpm files by first making an array of lines.  Blank
418  * lines are filtered out.
419  */
420 static char **
421 read_file(const char *filename)
422 {
423     char **result = 0;
424     struct stat sb;
425
426     if (!quiet) {
427         pause_curses();
428         printf("** %s\n", filename);
429     }
430
431     if (is_file(filename, &sb)) {
432         size_t size = (size_t) sb.st_size;
433         char *blob = typeCalloc(char, size + 1);
434         bool binary = FALSE;
435         unsigned k = 0;
436
437         result = typeCalloc(char *, size + 1);
438         how_much.file += ((size + 1) * 2);
439
440         if (blob != 0 && result != 0) {
441             FILE *fp = fopen(filename, "r");
442             if (fp != 0) {
443                 logmsg("opened %s", filename);
444
445                 if (fread(blob, sizeof(char), size, fp) == size) {
446                     bool had_line = TRUE;
447                     unsigned j;
448
449                     for (j = 0; (size_t) j < size; ++j) {
450                         if (blob[j] == '\0' ||
451                             (UChar(blob[j]) < 32 &&
452                              !isspace(UChar(blob[j]))) ||
453                             (UChar(blob[j]) >= 128 && UChar(blob[j]) < 160)) {
454                             binary = TRUE;
455                         }
456                         if (blob[j] == '\n') {
457                             blob[j] = '\0';
458                             if (k && !binary) {
459                                 debugmsg2("[%5d] %s\n", k, result[k - 1]);
460                             }
461                             had_line = TRUE;
462                         } else if (had_line) {
463                             had_line = FALSE;
464                             result[k++] = blob + j;
465                         }
466                     }
467                     result[k] = 0;
468                     if (k && !binary) {
469                         debugmsg2("[%5d] %s\n", k, result[k - 1]);
470                     }
471                 }
472                 fclose(fp);
473             } else {
474                 logmsg("cannot open %s", filename);
475             }
476         }
477         if (k == 0) {
478             debugmsg("...file is empty");
479             free(blob);
480             free(result);
481             result = 0;
482         } else if (binary) {
483             debugmsg("...file is non-text");
484         }
485     }
486     return result;
487 }
488
489 static void
490 usage(void)
491 {
492     static const char *msg[] =
493     {
494         "Usage: picsmap [options] [imagefile [...]]"
495         ,"Read/display one or more xbm/xpm files (possibly use \"convert\")"
496         ,""
497         ,"Options:"
498         ,"  -a ratio     aspect-ratio correction for ImageMagick"
499 #if HAVE_USE_DEFAULT_COLORS
500         ,"  -d           invoke use_default_colors"
501 #endif
502         ,"  -L           add debugging information to logfile"
503         ,"  -l logfile   write informational messages to logfile"
504         ,"  -p palette   color-palette file (default \"$TERM.dat\")"
505         ,"  -q           less verbose"
506         ,"  -r rgb-path  xpm uses X rgb color-names (default \"" RGB_PATH "\")"
507         ,"  -s SECS      pause for SECS seconds after display vs getch"
508 #if USE_EXTENDED_COLORS
509         ,"  -x [pc]      use extension (p=extended-pairs, c=extended-colors)"
510         ,"               Either/both extension may be given"
511 #endif
512     };
513     size_t n;
514
515     pause_curses();
516
517     fflush(stdout);
518     for (n = 0; n < SIZEOF(msg); n++)
519         fprintf(stderr, "%s\n", msg[n]);
520     cleanup(EXIT_FAILURE);
521 }
522
523 static void
524 giveup(const char *fmt, ...)
525 {
526     va_list ap;
527
528     pause_curses();
529     fflush(stdout);
530
531     va_start(ap, fmt);
532     vfprintf(stderr, fmt, ap);
533     fputc('\n', stderr);
534     va_end(ap);
535
536     if (logfp) {
537         va_start(ap, fmt);
538         vfprintf(logfp, fmt, ap);
539         fputc('\n', logfp);
540         va_end(ap);
541         fflush(logfp);
542     }
543
544     usage();
545 }
546
547 /*
548  * Palette files are named for $TERM values.  However, there are fewer palette
549  * files than $TERM's.  Although there are known problems (some cannot even get
550  * black and white correct), for the purpose of comparison, pretending that
551  * those map into "xterm" is useful.
552  */
553 static char **
554 read_palette(const char *filename)
555 {
556     static const char *data_dir = DATA_DIR;
557     char **result = 0;
558     size_t last = strlen(filename);
559     size_t need = (strlen(data_dir) + 20 + last);
560     char *full_name = malloc(need);
561     char *s;
562     struct stat sb;
563
564     if (full_name != 0) {
565         int tries;
566         for (tries = 0; tries < 8; ++tries) {
567
568             *(s = full_name) = '\0';
569             if (tries & 1) {
570                 if (strchr(filename, '/') == 0) {
571                     _nc_SPRINTF(full_name, _nc_SLIMIT(need) "%s/", data_dir);
572                 } else {
573                     continue;
574                 }
575             }
576             s += strlen(s);
577             if (((size_t) (s - full_name) + last + 1) >= need)
578                 continue;
579
580             _nc_STRCAT(full_name, filename, need);
581             if (tries & 4) {
582                 char *t = s;
583                 char *tc;
584                 int num;
585                 char chr;
586                 int found = 0;
587                 while (*t != '\0') {
588                     if (*t == '-') {
589                         if (sscanf(t, "-%d%c", &num, &chr) == 2 &&
590                             chr == 'c' &&
591                             (tc = strchr(t, chr)) != 0 &&
592                             !(strncmp) (tc, "color", 5)) {
593                             found = 1;
594                         }
595                         break;
596                     }
597                     ++t;
598                 }
599                 if (found && (t != s)
600                     && (strncmp) (s, "xterm", (size_t) (t - s))) {
601                     _nc_SPRINTF(s, _nc_SLIMIT(need - (size_t) (s - full_name))
602                                 "xterm%s", filename + (t - s));
603                 } else {
604                     continue;
605                 }
606             }
607             s += strlen(s);
608
609             if (tries & 2) {
610                 int len = (int) strlen(filename);
611                 if (len <= 4 || strcmp(filename + len - 4, ".dat")) {
612                     _nc_STRCAT(full_name, ".dat", need);
613                 } else {
614                     continue;
615                 }
616             }
617             if (is_file(full_name, &sb))
618                 goto ok;
619         }
620         goto failed;
621       ok:
622         result = read_file(full_name);
623       failed:
624         free(full_name);
625     }
626     return result;
627 }
628
629 static void
630 init_palette(const char *palette_file)
631 {
632     if (palette_file != 0) {
633         char **data = read_palette(palette_file);
634
635         all_colors = typeMalloc(RGB_DATA, (unsigned) COLORS);
636         how_much.data += (sizeof(RGB_DATA) * (unsigned) COLORS);
637
638 #if HAVE_COLOR_CONTENT
639         {
640             int cp;
641             for (cp = 0; cp < COLORS; ++cp) {
642                 color_content((short) cp,
643                               &all_colors[cp].red,
644                               &all_colors[cp].green,
645                               &all_colors[cp].blue);
646             }
647         }
648 #else
649         memset(all_colors, 0, sizeof(RGB_DATA) * (size_t) COLORS);
650 #endif
651         if (data != 0) {
652             int n;
653             int red, green, blue;
654             int scale = MaxSCALE;
655             int c;
656             for (n = 0; data[n] != 0; ++n) {
657                 if (sscanf(data[n], "scale:%d", &c) == 1) {
658                     scale = c;
659                 } else if (sscanf(data[n], "%d:%d %d %d",
660                                   &c,
661                                   &red,
662                                   &green,
663                                   &blue) == 4
664                            && okCOLOR(c)
665                            && okSCALE(red)
666                            && okSCALE(green)
667                            && okSCALE(blue)) {
668                     /* *INDENT-EQLS* */
669                     all_colors[c].red   = ScaledColor(red);
670                     all_colors[c].green = ScaledColor(green);
671                     all_colors[c].blue  = ScaledColor(blue);
672                 }
673             }
674         }
675         free_data(data);
676         /* *INDENT-EQLS* */
677     } else if (COLORS > 1) {
678         int power2 = 1;
679         int shift = 0;
680
681         while (power2 < COLORS) {
682             ++shift;
683             power2 <<= 1;
684         }
685
686         if ((power2 != COLORS) || ((shift % 3) != 0)) {
687             if (all_colors == 0) {
688                 init_palette(getenv("TERM"));
689                 if (all_colors == 0) {
690                     giveup("With %d colors, you need a palette-file", COLORS);
691                 }
692             }
693         }
694     }
695 }
696
697 /*
698  * Map the 24-bit RGB value to a color index if using a palette, otherwise to a
699  * direct color value.
700  */
701 static int
702 map_color(int value)
703 {
704     int result = value;
705
706     if (result < 0) {
707         result = -1;
708     } else {
709         /* *INDENT-EQLS* */
710         int red   = (value & 0xff0000) >> 16;
711         int green = (value & 0x00ff00) >> 8;
712         int blue  = (value & 0x0000ff) >> 0;
713
714         if (all_colors != 0) {
715 #define Diff2(n,m) ((m) - all_colors[n].m) * ((m) - all_colors[n].m)
716 #define Diff2S(n) Diff2(n,red) + Diff2(n,green) + Diff2(n,blue)
717             int d2 = Diff2S(0);
718             int n;
719
720             /* *INDENT-EQLS* */
721             red   = Scaled256(red);
722             green = Scaled256(green);
723             blue  = Scaled256(blue);
724
725             for (result = 0, n = 1; n < COLORS; ++n) {
726                 int d = Diff2(n, red) + Diff2(n, green) + Diff2(n, blue);
727                 if (d < d2) {
728                     d2 = d;
729                     result = n;
730                 }
731             }
732         } else {                /* direct color */
733             int power2 = 1;
734             int shifts = 8;
735
736             while (power2 < COLORS) {
737                 power2 <<= 3;
738                 shifts--;
739             }
740
741             if (shifts > 0) {
742                 /* TODO: round up */
743                 red >>= shifts;
744                 green >>= shifts;
745                 blue >>= shifts;
746                 result = ((red << (2 * (8 - shifts)))
747                           + (green << (8 - shifts))
748                           + blue);
749             }
750         }
751     }
752     return result;
753 }
754
755 static int
756 bytes_of(int value)
757 {
758     if (value & 7) {
759         value |= 7;
760         value++;
761     }
762     return value;
763 }
764
765 static int match_c(const char *, const char *, ...) GCC_SCANFLIKE(2,3);
766
767 static char *
768 skip_s(char *s)
769 {
770     while (isspace(UChar(*s)))
771         s++;
772     return s;
773 }
774
775 static const char *
776 skip_cs(const char *s)
777 {
778     while (isspace(UChar(*s)))
779         s++;
780     return s;
781 }
782
783 static char *
784 skip_word(char *s)
785 {
786     s = skip_s(s);
787     while (isgraph(UChar(*s)))
788         s++;
789     return s;
790 }
791
792 static int
793 match_c(const char *source, const char *pattern, ...)
794 {
795     int limit = (int) strlen(source);
796     const char *last_s = source + limit;
797     va_list ap;
798     int ch;
799     int *ip;
800     char *cp;
801     long lv;
802
803     va_start(ap, pattern);
804
805     limit = -1;
806     while (*pattern != '\0') {
807         ch = UChar(*pattern++);
808         /* blank in the pattern matches zero-or-more blanks in source */
809         if (isspace(ch)) {
810             source = skip_cs(source);
811             continue;
812         }
813         /* %c, %d, %s are like sscanf except for special treatment of blanks */
814         if (ch == '%' && *pattern != '\0' && strchr("cdnsx", *pattern)) {
815             bool found = FALSE;
816             ch = *pattern++;
817             switch (ch) {
818             case 'c':
819                 cp = va_arg(ap, char *);
820                 do {
821                     *cp++ = *source++;
822                 } while (--limit > 0);
823                 break;
824             case 'd':
825             case 'x':
826                 limit = -1;
827                 ip = va_arg(ap, int *);
828                 lv = strtol(source, &cp, ch == 'd' ? 10 : 16);
829                 if (cp != 0 && cp != source) {
830                     *ip = (int) lv;
831                     source = cp;
832                 } else {
833                     goto finish;
834                 }
835                 break;
836             case 'n':
837                 /* not really sscanf... */
838                 limit = *va_arg(ap, int *);
839                 break;
840             case 's':
841                 limit = -1;
842                 cp = va_arg(ap, char *);
843                 while (*source != '\0') {
844                     ch = UChar(*source);
845                     if (isspace(ch)) {
846                         break;
847                     } else if (found && (ch == *skip_cs(pattern))) {
848                         break;
849                     } else {
850                         *cp++ = *source++;
851                         found = TRUE;
852                     }
853                 }
854                 *cp = '\0';
855                 break;
856             }
857             continue;
858         }
859         /* other characters are matched literally */
860         if (*source++ != ch) {
861             break;
862         }
863     }
864   finish:
865
866     va_end(ap);
867     if (source > last_s)
868         source = last_s;
869     return (*source || *pattern) ? 0 : 1;
870 }
871
872 static int
873 match_colors(const char *source, int cpp, char *arg1, char *arg2, char *arg3)
874 {
875     int result = 0;
876
877     /* most files use a quasi-fixed format */
878     if (match_c(source, " \"%n%c %s %s \" , ", &cpp, arg1, arg2, arg3)) {
879         arg1[cpp] = '\0';
880         result = 1;
881     } else {
882         const char *s = skip_cs(source);
883         size_t have = strlen(source);
884
885         if (*s++ == '"' && have > ((size_t) cpp + 2)) {
886             memcpy(arg1, s, (size_t) cpp);
887             s += cpp;
888             while (*s++ == '\t') {
889                 char *t;
890                 for (t = arg2; (*s != '\0') && strchr("\t\"", *s) == 0;) {
891                     if (*s == ' ') {
892                         s = skip_cs(s);
893                         break;
894                     }
895                     *t++ = *s++;
896                     *t = '\0';
897                 }
898                 for (t = arg3; (*s != '\0') && strchr("\t\"", *s) == 0;) {
899                     *t++ = *s++;
900                     *t = '\0';
901                 }
902                 if (!strcmp(arg2, "c")) {
903                     result = 1;
904                     break;
905                 }
906             }
907         }
908     }
909     return result;
910 }
911
912 static RGB_NAME *
913 parse_rgb(char **data)
914 {
915     char buf[BUFSIZ];
916     int n;
917     unsigned long r, g, b;
918     char *s, *t;
919     size_t item = 0;
920     size_t need;
921     RGB_NAME *result = 0;
922
923     for (need = 0; data[need] != 0; ++need) ;
924
925     result = typeCalloc(RGB_NAME, need + 2);
926     how_much.name += (sizeof(RGB_NAME) * (need + 2));
927
928     for (n = 0; data[n] != 0; ++n) {
929         if (strlen(t = data[n]) >= sizeof(buf) - 1)
930             continue;
931         if (*(s = skip_s(t)) == '!')
932             continue;
933
934         r = strtoul(s, &t, 10);
935         s = skip_s(t);
936         g = strtoul(s, &t, 10);
937         s = skip_s(t);
938         b = strtoul(s, &t, 10);
939         s = skip_s(t);
940
941         result[item].name = s;
942         t = s + strlen(s);
943         while (t-- != s && isspace(UChar(*t))) {
944             *t = '\0';
945         }
946         result[item].value = (int) ((r & 0xff) << 16 |
947                                     (g & 0xff) << 8 |
948                                     (b & 0xff));
949         ++item;
950     }
951
952     result[item].name = "none";
953     result[item].value = -1;
954
955     return result;
956 }
957
958 #define LOWERCASE(c) ((isalpha(UChar(c)) && isupper(UChar(c))) ? tolower(UChar(c)) : (c))
959
960 static int
961 CaselessCmp(const char *a, const char *b)
962 {                               /* strcasecmp isn't portable */
963     while (*a && *b) {
964         int cmp = LOWERCASE(*a) - LOWERCASE(*b);
965         if (cmp != 0)
966             break;
967         a++, b++;
968     }
969     return LOWERCASE(*a) - LOWERCASE(*b);
970 }
971
972 static RGB_NAME *
973 lookup_rgb(const char *name)
974 {
975     RGB_NAME *result = 0;
976     if (rgb_table != 0) {
977         int n;
978         for (n = 0; rgb_table[n].name != 0; ++n) {
979             if (!CaselessCmp(name, rgb_table[n].name)) {
980                 result = &rgb_table[n];
981                 break;
982             }
983         }
984     }
985     return result;
986 }
987
988 static PICS_HEAD *
989 parse_xbm(char **data)
990 {
991     int n;
992     int state = 0;
993     char buf[BUFSIZ];
994     int num;
995     char ch;
996     char *s;
997     char *t;
998     PICS_HEAD *result;
999     size_t which = 0;
1000     size_t cells = 0;
1001
1002     debugmsg("called parse_xbm");
1003
1004     result = typeCalloc(PICS_HEAD, 1);
1005     how_much.head += sizeof(PICS_HEAD);
1006
1007     begin_c_values(2);
1008     gather_c_values(0);
1009     gather_c_values(0xffffff);
1010
1011     for (n = 0; data[n] != 0; ++n) {
1012         if (strlen(s = data[n]) >= sizeof(buf) - 1)
1013             continue;
1014         switch (state) {
1015         case 0:
1016         case 1:
1017         case 2:
1018             if (sscanf(s, "#define %1024s %d%c", buf, &num, &ch) >= 2) {
1019                 if ((t = strstr(buf, "_width")) != 0) {
1020                     state |= 1;
1021                     result->wide = (short) bytes_of(num);
1022                 } else if ((t = strstr(buf, "_height")) != 0) {
1023                     state |= 2;
1024                     result->high = (short) num;
1025                 } else {
1026                     break;
1027                 }
1028                 *t = '\0';
1029                 if (result->name) {
1030                     if (strcmp(result->name, buf)) {
1031                         goto finish;
1032                     }
1033                 } else {
1034                     result->name = strdup(buf);
1035                 }
1036             }
1037             break;
1038         case 3:
1039             if (sscanf(s, "static char %1024[^_ ]_bits[]%c", buf, &ch) >= 1) {
1040                 if (strcmp(result->name, buf)) {
1041                     goto finish;
1042                 }
1043                 state = 4;
1044                 cells = (size_t) (result->wide * result->high);
1045
1046                 result->cells = typeCalloc(PICS_CELL, cells);
1047                 how_much.cell += (sizeof(PICS_CELL) * cells);
1048
1049                 if ((s = strchr(s, L_CURLY)) == 0)
1050                     break;
1051                 ++s;
1052             } else {
1053                 break;
1054             }
1055         case 4:
1056             while (*s != '\0') {
1057                 while (isspace(UChar(*s))) {
1058                     ++s;
1059                 }
1060                 if (isdigit(UChar(*s))) {
1061                     long value = strtol(s, &t, 0);
1062                     int b;
1063                     if (t != s || value > MaxRGB || value < 0) {
1064                         s = t;
1065                     } else {
1066                         state = -1;
1067                         goto finish;
1068                     }
1069                     for (b = 0; b < 8; ++b) {
1070                         if (((1L << b) & value) != 0) {
1071                             result->cells[which].ch = '*';
1072                             result->cells[which].fg = 1;
1073                             reading_ncols[1].count++;
1074                         } else {
1075                             result->cells[which].ch = ' ';
1076                             result->cells[which].fg = 0;
1077                             reading_ncols[0].count++;
1078                         }
1079                         if (++which > cells) {
1080                             state = -1;
1081                             goto finish;
1082                         }
1083                     }
1084                 }
1085                 if (*s == R_CURLY) {
1086                     state = 5;
1087                     goto finish;
1088                 } else if (*s == ',') {
1089                     ++s;
1090                 }
1091             }
1092             break;
1093         default:
1094             break;
1095         }
1096     }
1097   finish:
1098     if (state < 4) {
1099         debugmsg("...state was only %d", state);
1100         if (result) {
1101             result = free_pics_head(result);
1102         }
1103     } else {
1104         finish_c_values(result);
1105     }
1106     return result;
1107 }
1108
1109 static PICS_HEAD *
1110 parse_xpm(char **data)
1111 {
1112     int state = 0;
1113     PICS_HEAD *result;
1114     RGB_NAME *by_name;
1115     int n;
1116     int cells = 0;
1117     int cpp = 1;                /* chars per pixel */
1118     int num[6];
1119     int found;
1120     int which = 0;
1121     int num_colors = 0;
1122     char ch;
1123     const char *cs;
1124     char *s;
1125     char buf[BUFSIZ];
1126     char arg1[BUFSIZ];
1127     char arg2[BUFSIZ];
1128     char arg3[BUFSIZ];
1129     char **list = 0;
1130
1131     debugmsg("called parse_xpm");
1132
1133     result = typeCalloc(PICS_HEAD, 1);
1134     how_much.head += sizeof(PICS_HEAD);
1135
1136     for (n = 0; data[n] != 0; ++n) {
1137         if (strlen(s = data[n]) >= sizeof(buf) - 1)
1138             continue;
1139         switch (state) {
1140         case 0:
1141             if (match_c(s, " /* XPM */ ")) {
1142                 state = 1;
1143             }
1144             break;
1145         case 1:
1146             if (match_c(s, " static char * %s [] = %c ", arg1, &ch) &&
1147                 ch == L_CURLY) {
1148                 result->name = strdup(arg1);
1149                 state = 2;
1150             }
1151             break;
1152         case 2:
1153             if (match_c(s, " \" %d %d %d %d \" , ",
1154                         num + 0, num + 1, num + 2, num + 3) ||
1155                 match_c(s, " \" %d %d %d %d %d %d \" , ",
1156                         num + 0, num + 1, num + 2, num + 3, num + 4, num + 5)) {
1157                 result->wide = (short) num[0];
1158                 result->high = (short) num[1];
1159                 result->colors = num[2];
1160
1161                 begin_c_values(num[2]);
1162
1163                 cells = (result->wide * result->high);
1164
1165                 result->cells = typeCalloc(PICS_CELL, cells);
1166                 how_much.cell += sizeof(PICS_CELL) * (size_t) cells;
1167
1168                 list = typeCalloc(char *, result->colors + 1);
1169                 how_much.list += sizeof(char *) * (size_t) (result->colors + 1);
1170
1171                 cpp = num[3];
1172                 state = 3;
1173             }
1174             break;
1175         case 3:
1176             if (!match_colors(s, cpp, arg1, arg2, arg3)) {
1177                 break;
1178             }
1179             num_colors++;
1180             free(list[reading_last]);
1181             list[reading_last] = strdup(arg1);
1182             if ((by_name = lookup_rgb(arg3)) != 0) {
1183                 found = gather_c_values(by_name->value);
1184             } else if (*arg3 == '#') {
1185                 char *rgb = arg3 + 1;
1186                 unsigned long value = strtoul(rgb, &s, 16);
1187                 switch ((int) strlen(rgb)) {
1188                 case 6:
1189                     break;
1190                 case 12:
1191                     value = (((value >> 24) & 0xff0000L)
1192                              | ((value >> 16) & 0xff00L)
1193                              | ((value >> 8) & 0xffL));
1194                     break;
1195                 default:
1196                     warning("unexpected rgb value %s", rgb);
1197                     break;
1198                 }
1199                 found = gather_c_values((int) value);
1200             } else {
1201                 found = gather_c_values(0);     /* actually an error */
1202             }
1203             debugmsg("  [%d:%d] %06X", num_colors, result->colors,
1204                      reading_ncols[(found >= 0) ? found : 0].fgcol);
1205             if (num_colors >= result->colors) {
1206                 finish_c_values(result);
1207                 state = 4;
1208                 if (list[0] == 0)
1209                     list[0] = strdup("\033");
1210             }
1211             break;
1212         case 4:
1213             if (*(cs = skip_cs(s)) == '"') {
1214                 ++cs;
1215                 while (*cs != '\0' && *cs != '"') {
1216                     int c;
1217
1218                     /* FIXME - factor out */
1219                     for (c = 0; c < result->colors; ++c) {
1220                         if (list[c] == 0) {
1221                             /* should not happen... */
1222                             continue;
1223                         }
1224                         if (!(strncmp) (cs, list[c], (size_t) cpp)) {
1225                             result->cells[which].ch = list[c][0];
1226                             result->cells[which].fg = c;
1227                             result->fgcol[c].count++;
1228                             break;
1229                         }
1230                     }
1231
1232                     if (result->cells[which].ch == 0) {
1233                         result->cells[which].ch = '?';
1234                         result->cells[which].fg = 0;
1235                     }
1236
1237                     if (++which >= cells) {
1238                         state = 5;
1239                         break;
1240                     }
1241                     for (c = cpp; c > 0; --c, ++cs) {
1242                         if (*cs == '\0')
1243                             break;
1244                     }
1245                 }
1246             }
1247             break;
1248         }
1249     }
1250
1251     if (result && list) {
1252         for (n = 0; n < result->colors; ++n)
1253             free(list[n]);
1254         free(list);
1255     }
1256
1257     if (state < 5) {
1258         debugmsg("...state was only %d", state);
1259         result = free_pics_head(result);
1260     }
1261
1262     if (result) {
1263         debugmsg("...allocated %d colors", result->colors);
1264     }
1265
1266     return result;
1267 }
1268
1269 /*
1270  * The obscurely-named "convert" is provided by ImageMagick
1271  */
1272 static PICS_HEAD *
1273 parse_img(const char *filename)
1274 {
1275     size_t need = strlen(filename) + 256;
1276     char *cmd = malloc(need);
1277     FILE *pp;
1278     char buffer[BUFSIZ];
1279     char dummy[BUFSIZ];
1280     bool okay = TRUE;
1281     PICS_HEAD *result;
1282     int pic_x = 0;
1283     int pic_y = 0;
1284     int width = in_curses ? COLS : 80;
1285
1286     _nc_SPRINTF(cmd, _nc_SLIMIT(need) "identify \"%s\"", filename);
1287     if (quiet)
1288         _nc_STRCAT(cmd, " 2>/dev/null", need);
1289
1290     logmsg("...opening pipe to %s", cmd);
1291
1292     result = typeCalloc(PICS_HEAD, 1);
1293     how_much.head += sizeof(PICS_HEAD);
1294
1295     if ((pp = popen(cmd, "r")) != 0) {
1296         if (fgets(buffer, sizeof(buffer), pp) != 0) {
1297             size_t n = strlen(filename);
1298             debugmsg2("...read %s", buffer);
1299             if (strlen(buffer) > n &&
1300                 !(strncmp) (buffer, filename, n) &&
1301                 isspace(UChar(buffer[n])) &&
1302                 sscanf(skip_word(buffer + n), " %dx%d ", &pic_x, &pic_y) == 2) {
1303                 /* distort image to make it show normally on terminal */
1304                 pic_x = (int) ((double) pic_x / aspect_ratio);
1305             } else {
1306                 pic_x = pic_y = 0;
1307             }
1308         }
1309         pclose(pp);
1310     }
1311     if (pic_x <= 0 || pic_y <= 0)
1312         goto finish;
1313
1314     _nc_SPRINTF(cmd, _nc_SLIMIT(need)
1315                 "convert " "-resize %dx%d\\! " "-thumbnail %dx \"%s\" "
1316                 "-define txt:compliance=SVG txt:-",
1317                 pic_x, pic_y, width, filename);
1318     if (quiet)
1319         _nc_STRCAT(cmd, " 2>/dev/null", need);
1320
1321     logmsg("...opening pipe to %s", cmd);
1322     if ((pp = popen(cmd, "r")) != 0) {
1323         int count = 0;
1324         int col = 0;
1325         int row = 0;
1326         int len = 0;
1327         while (fgets(buffer, sizeof(buffer), pp) != 0) {
1328             debugmsg2("[%5d] %s", count + 1, buffer);
1329             if (strlen(buffer) > 160) {         /* 80 columns would be enough */
1330                 okay = FALSE;
1331                 break;
1332             }
1333             if (count++ == 0) {
1334                 if (match_c(buffer,
1335                             "# ImageMagick pixel enumeration: %d,%d,%d,%s ",
1336                             &col, &row, &len, dummy)) {
1337                     result->name = strdup(filename);
1338                     result->wide = (short) col;
1339                     result->high = (short) row;
1340
1341                     begin_c_values(256);
1342
1343                     result->cells = typeCalloc(PICS_CELL, (size_t) (col * row));
1344                     how_much.cell += (sizeof(PICS_CELL) * (size_t) (col * row));
1345                 } else {
1346                     okay = FALSE;
1347                     break;
1348                 }
1349             } else {
1350                 /* subsequent lines begin "col,row: (r,g,b,a) #RGB" */
1351                 int r, g, b, nocolor;
1352                 unsigned check;
1353                 char *t;
1354                 char *s = t = strchr(buffer, '#');
1355
1356                 if (s != 0) {
1357                     /* after the "#RGB", there are differences - just ignore */
1358                     while (*s != '\0' && !isspace(UChar(*s)))
1359                         ++s;
1360                     *++s = '\0';
1361                 }
1362                 if (match_c(buffer,
1363                             "%d,%d: (%d,%d,%d,%d) #%x ",
1364                             &col, &row,
1365                             &r, &g, &b, &nocolor,
1366                             &check)) {
1367                     int which, c;
1368
1369                     if ((s - t) > 8)    /* 6 hex digits vs 8 */
1370                         check /= 256;
1371                     if (r > MaxRGB ||
1372                         g > MaxRGB ||
1373                         b > MaxRGB ||
1374                         check != (unsigned) ((r << 16) | (g << 8) | b)) {
1375                         okay = FALSE;
1376                         break;
1377                     }
1378                     c = gather_c_values((int) check);
1379                     which = col + (row * result->wide);
1380                     result->cells[which].ch = ((in_curses ||
1381                                                 check == 0xffffff)
1382                                                ? ' '
1383                                                : '#');
1384                     if (c >= 0 && c < reading_last) {
1385                         result->cells[which].fg = c;
1386                         reading_ncols[c].count++;
1387                     } else {
1388                         result->cells[which].fg = -1;
1389                     }
1390                 } else {
1391                     okay = FALSE;
1392                     break;
1393                 }
1394             }
1395         }
1396         finish_c_values(result);
1397         pclose(pp);
1398         if (okay) {
1399             /* FIXME - is this trimming needed? */
1400             for (len = result->colors; len > 3; len--) {
1401                 if (result->fgcol[len - 1].fgcol == 0) {
1402                     result->colors = len - 1;
1403                 } else {
1404                     break;
1405                 }
1406             }
1407         }
1408     }
1409   finish:
1410     free(cmd);
1411
1412     if (!okay) {
1413         result = free_pics_head(result);
1414     }
1415
1416     return result;
1417 }
1418
1419 static PICS_HEAD *
1420 read_picture(const char *filename, char **data)
1421 {
1422     PICS_HEAD *pics;
1423     if ((pics = parse_xbm(data)) == 0) {
1424         dispose_c_values();
1425         if ((pics = parse_xpm(data)) == 0) {
1426             dispose_c_values();
1427             if ((pics = parse_img(filename)) == 0) {
1428                 dispose_c_values();
1429                 free_data(data);
1430                 warning("unexpected file-format for \"%s\"", filename);
1431             } else if (pics->high == 0 || pics->wide == 0) {
1432                 dispose_c_values();
1433                 free_data(data);
1434                 pics = free_pics_head(pics);
1435                 warning("no picture found in \"%s\"", filename);
1436             }
1437         }
1438     }
1439     return pics;
1440 }
1441
1442 #define fg_color(pics,n) (pics->fgcol[n].fgcol)
1443
1444 static void
1445 dump_picture(PICS_HEAD * pics)
1446 {
1447     int y, x;
1448
1449     printf("Name %s\n", pics->name);
1450     printf("Size %dx%d\n", pics->high, pics->wide);
1451     printf("Color\n");
1452     for (y = 0; y < pics->colors; ++y) {
1453         if (fg_color(pics, y) < 0) {
1454             printf(" %3d: %d\n", y, fg_color(pics, y));
1455         } else {
1456             printf(" %3d: #%06x\n", y, fg_color(pics, y));
1457         }
1458     }
1459     for (y = 0; y < pics->high; ++y) {
1460         for (x = 0; x < pics->wide; ++x) {
1461             putchar(pics->cells[y * pics->wide + x].ch);
1462         }
1463         putchar('\n');
1464     }
1465 }
1466
1467 #ifndef USE_DISPLAY_DRIVER
1468 static void
1469 init_display(const char *palette_path, int opt_d)
1470 {
1471     (void) opt_d;
1472     if (isatty(fileno(stdout))) {
1473         in_curses = TRUE;
1474         initscr();
1475         cbreak();
1476         noecho();
1477         curs_set(0);
1478         if (has_colors()) {
1479             start_color();
1480 #if HAVE_USE_DEFAULT_COLORS
1481             if (opt_d)
1482                 use_default_colors();
1483 #endif
1484             init_palette(palette_path);
1485         }
1486         scrollok(stdscr, FALSE);
1487         stop_curses();
1488     }
1489 }
1490
1491 static void
1492 show_picture(PICS_HEAD * pics)
1493 {
1494     int y, x;
1495     int n;
1496
1497     debugmsg("called show_picture");
1498     logmsg("...using %dx%d screen", LINES, COLS);
1499 #if HAVE_RESET_COLOR_PAIRS
1500     reset_color_pairs();
1501 #elif HAVE_CURSCR
1502     wclear(curscr);
1503     clear();
1504 #endif
1505     if (has_colors()) {
1506         logmsg("...using %d colors", pics->colors);
1507         for (n = 0; n < pics->colors; ++n) {
1508             int my_pair = (n + 1);
1509             int my_color = map_color(fg_color(pics, n));
1510 #if USE_EXTENDED_COLORS
1511             if (use_extended_pairs) {
1512                 init_extended_pair(my_pair, my_color, my_color);
1513             } else
1514 #endif
1515             {
1516                 my_pair &= 0x7fff;
1517                 my_color &= 0x7fff;
1518                 init_pair((short) my_pair, (short) my_color, (short) my_color);
1519             }
1520         }
1521         attrset(COLOR_PAIR(1));
1522         erase();
1523     }
1524     for (y = 0; y < pics->high; ++y) {
1525         if (y >= LINES)
1526             break;
1527         move(y, 0);
1528
1529         for (x = 0; x < pics->wide; ++x) {
1530             int my_pair;
1531
1532             if (x >= COLS)
1533                 break;
1534             n = (y * pics->wide + x);
1535             my_pair = pics->cells[n].fg + 1;
1536 #if USE_EXTENDED_COLORS
1537             if (use_extended_pairs) {
1538                 cchar_t temp;
1539                 wchar_t wch[2];
1540                 wch[0] = (wchar_t) pics->cells[n].ch;
1541                 wch[1] = 0;
1542                 setcchar(&temp, wch, A_NORMAL, (short) my_pair, &my_pair);
1543                 add_wch(&temp);
1544             } else
1545 #endif
1546             {
1547                 attrset(COLOR_PAIR(my_pair));
1548                 addch((chtype) pics->cells[n].ch);
1549             }
1550         }
1551     }
1552     if (slow_time >= 0) {
1553         refresh();
1554         if (slow_time > 0) {
1555 #ifdef NCURSES_VERSION
1556             napms(1000 * slow_time);
1557 #else
1558             sleep((unsigned) slow_time);
1559 #endif
1560         }
1561     } else {
1562         wmove(stdscr, 0, 0);
1563         getch();
1564     }
1565     if (!quiet)
1566         endwin();
1567 }
1568 #endif
1569
1570 static int
1571 compare_fg_counts(const void *a, const void *b)
1572 {
1573     const FG_NODE *p = (const FG_NODE *) a;
1574     const FG_NODE *q = (const FG_NODE *) b;
1575     return (q->count - p->count);
1576 }
1577
1578 static void
1579 report_colors(PICS_HEAD * pics)
1580 {
1581     int accum;
1582     double level;
1583     int j;
1584     int shift;
1585     int total;
1586     char buffer[256];
1587
1588     if (logfp == 0)
1589         return;
1590
1591     qsort(pics->fgcol, (size_t) pics->colors, sizeof(FG_NODE), compare_fg_counts);
1592     /*
1593      * For debugging, show a (short) list of the colors used.
1594      */
1595     if (debugging && (pics->colors < 1000)) {
1596         int digits = 0;
1597         int high;
1598         int wide = 4;
1599         for (j = pics->colors; j != 0; j /= 10) {
1600             ++digits;
1601             if (j < 10)
1602                 ++digits;
1603         }
1604         if (digits > 8)
1605             digits = 8;
1606         logmsg("These colors were used:");
1607         high = (pics->colors + wide - 1) / wide;
1608         for (j = 0; j < high && j < pics->colors; ++j) {
1609             int k;
1610             char *s = buffer;
1611             *s = '\0';
1612             for (k = 0; k < wide; ++k) {
1613                 int n = j + (k * high);
1614                 size_t want = (sizeof(buffer) - (size_t) (s - buffer));
1615                 if (want < 100 || want >= sizeof(buffer))
1616                     break;
1617                 if (n >= pics->colors)
1618                     break;
1619                 if (k) {
1620                     *s++ = ' ';
1621                     if (digits < 8) {
1622                         _nc_SPRINTF(s, _nc_SLIMIT(want) "%*s", 8 - digits,
1623                                     " ");
1624                         s += strlen(s);
1625                     }
1626                 }
1627                 if (pics->fgcol[n].fgcol >= 0) {
1628                     _nc_SPRINTF(s, _nc_SLIMIT(want) "%3d #%06X %*d", n,
1629                                 pics->fgcol[n].fgcol,
1630                                 digits, pics->fgcol[n].count);
1631                 } else {
1632                     _nc_SPRINTF(s, _nc_SLIMIT(want) "%3d (empty) %*d", n,
1633                                 digits, pics->fgcol[n].count);
1634                 }
1635                 s += strlen(s);
1636                 if ((s - buffer) > 100)
1637                     break;
1638             }
1639             logmsg("%s", buffer);
1640         }
1641     }
1642
1643     /*
1644      * Given the list of colors sorted by the number of times they are used,
1645      * log a short report showing the number of colors for 90%, 99%, 99.9%,
1646      * etc.
1647      */
1648     logmsg("Number of colors versus number of cells");
1649     total = pics->high * pics->wide;
1650     accum = 0;
1651     level = 0.1;
1652     shift = 1;
1653     for (j = 0; j < pics->colors; ++j) {
1654         accum += pics->fgcol[j].count;
1655         if (accum >= (total * (1.0 - level))) {
1656             int after = (shift > 2) ? shift - 2 : 0;
1657             logmsg("%8d colors (%.1f%%) in %d cells (%.*f%%)",
1658                    j + 1,
1659                    (100.0 * (j + 1)) / pics->colors,
1660                    accum,
1661                    after, (100.0 * accum) / total);
1662             if (accum >= total)
1663                 break;
1664             level /= 10.0;
1665             shift++;
1666         }
1667     }
1668 }
1669
1670 int
1671 main(int argc, char *argv[])
1672 {
1673     int n;
1674     int opt_d = FALSE;
1675     char ignore_ch;
1676     const char *palette_path = 0;
1677     const char *rgb_path = RGB_PATH;
1678
1679     while ((n = getopt(argc, argv, "a:dLl:p:qr:s:x:")) != -1) {
1680         switch (n) {
1681         case 'a':
1682             if (sscanf(optarg, "%lf%c", &aspect_ratio, &ignore_ch) != 1
1683                 || aspect_ratio < 0.1
1684                 || aspect_ratio > 10.) {
1685                 fprintf(stderr, "Expected a number in [0.1 to 10.]: %s\n", optarg);
1686                 usage();
1687             }
1688             break;
1689 #if HAVE_USE_DEFAULT_COLORS
1690         case 'd':
1691             opt_d = TRUE;
1692             break;
1693 #endif
1694         case 'L':
1695             debugging = TRUE;
1696             break;
1697         case 'l':
1698             if ((logfp = fopen(optarg, "a")) == 0)
1699                 failed(optarg);
1700             break;
1701         case 'p':
1702             palette_path = optarg;
1703             break;
1704         case 'q':
1705             quiet = TRUE;
1706             break;
1707         case 'r':
1708             rgb_path = optarg;
1709             break;
1710         case 's':
1711             slow_time = atoi(optarg);
1712             break;
1713 #if USE_EXTENDED_COLORS
1714         case 'x':
1715             {
1716                 char *s = optarg;
1717                 while (*s) {
1718                     switch (*s++) {
1719                     case 'p':
1720                         use_extended_pairs = TRUE;
1721                         break;
1722                     case 'c':
1723                         use_extended_colors = TRUE;
1724                         break;
1725                     default:
1726                         usage();
1727                         break;
1728                     }
1729                 }
1730             }
1731             break;
1732 #endif
1733         default:
1734             usage();
1735             break;
1736         }
1737     }
1738
1739     if (optind < argc) {
1740         char **rgb_data = read_file(rgb_path);
1741
1742         if (rgb_data)
1743             rgb_table = parse_rgb(rgb_data);
1744
1745         init_display(palette_path, opt_d);
1746         if (optind >= argc)
1747             giveup("expected at least one image filename");
1748
1749         for (n = optind; n < argc; ++n) {
1750             PICS_HEAD *pics;
1751             char **data = read_file(argv[n]);
1752
1753             if (data == 0) {
1754                 warning("cannot read \"%s\"", argv[n]);
1755                 continue;
1756             }
1757             if ((pics = read_picture(argv[n], data)) != 0) {
1758                 if (in_curses) {
1759                     show_picture(pics);
1760                 } else {
1761                     dump_picture(pics);
1762                 }
1763                 report_colors(pics);
1764                 dispose_c_values();
1765                 free_data(data);
1766                 free_pics_head(pics);
1767             }
1768         }
1769         free_data(rgb_data);
1770         free(rgb_table);
1771         free(all_colors);
1772     } else {
1773         usage();
1774     }
1775
1776     cleanup(EXIT_SUCCESS);
1777 }