]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/picsmap.c
ncurses 6.4 - patch 20240420
[ncurses.git] / test / picsmap.c
1 /****************************************************************************
2  * Copyright 2018-2021,2022 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.145 2022/04/16 18:21:05 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
608             if (tries & 2) {
609                 int len = (int) strlen(filename);
610                 if (len <= 4 || strcmp(filename + len - 4, ".dat")) {
611                     _nc_STRCAT(full_name, ".dat", need);
612                 } else {
613                     continue;
614                 }
615             }
616             if (is_file(full_name, &sb))
617                 goto ok;
618         }
619         goto failed;
620       ok:
621         result = read_file(full_name);
622       failed:
623         free(full_name);
624     }
625     return result;
626 }
627
628 static void
629 init_palette(const char *palette_file)
630 {
631     if (palette_file != 0) {
632         char **data = read_palette(palette_file);
633
634         all_colors = typeMalloc(RGB_DATA, (unsigned) COLORS);
635         how_much.data += (sizeof(RGB_DATA) * (unsigned) COLORS);
636
637 #if HAVE_COLOR_CONTENT
638         {
639             int cp;
640             for (cp = 0; cp < COLORS; ++cp) {
641                 color_content((short) cp,
642                               &all_colors[cp].red,
643                               &all_colors[cp].green,
644                               &all_colors[cp].blue);
645             }
646         }
647 #else
648         memset(all_colors, 0, sizeof(RGB_DATA) * (size_t) COLORS);
649 #endif
650         if (data != 0) {
651             int n;
652             int red, green, blue;
653             int scale = MaxSCALE;
654             int c;
655             for (n = 0; data[n] != 0; ++n) {
656                 if (sscanf(data[n], "scale:%d", &c) == 1) {
657                     scale = c;
658                 } else if (sscanf(data[n], "%d:%d %d %d",
659                                   &c,
660                                   &red,
661                                   &green,
662                                   &blue) == 4
663                            && okCOLOR(c)
664                            && okSCALE(red)
665                            && okSCALE(green)
666                            && okSCALE(blue)) {
667                     /* *INDENT-EQLS* */
668                     all_colors[c].red   = ScaledColor(red);
669                     all_colors[c].green = ScaledColor(green);
670                     all_colors[c].blue  = ScaledColor(blue);
671                 }
672             }
673         }
674         free_data(data);
675         /* *INDENT-EQLS* */
676     } else if (COLORS > 1) {
677         int power2 = 1;
678         int shift = 0;
679
680         while (power2 < COLORS) {
681             ++shift;
682             power2 <<= 1;
683         }
684
685         if ((power2 != COLORS) || ((shift % 3) != 0)) {
686             if (all_colors == 0) {
687                 init_palette(getenv("TERM"));
688                 if (all_colors == 0) {
689                     giveup("With %d colors, you need a palette-file", COLORS);
690                 }
691             }
692         }
693     }
694 }
695
696 /*
697  * Map the 24-bit RGB value to a color index if using a palette, otherwise to a
698  * direct color value.
699  */
700 static int
701 map_color(int value)
702 {
703     int result = value;
704
705     if (result < 0) {
706         result = -1;
707     } else {
708         /* *INDENT-EQLS* */
709         int red   = (value & 0xff0000) >> 16;
710         int green = (value & 0x00ff00) >> 8;
711         int blue  = (value & 0x0000ff) >> 0;
712
713         if (all_colors != 0) {
714 #define Diff2(n,m) ((m) - all_colors[n].m) * ((m) - all_colors[n].m)
715 #define Diff2S(n) Diff2(n,red) + Diff2(n,green) + Diff2(n,blue)
716             int d2 = Diff2S(0);
717             int n;
718
719             /* *INDENT-EQLS* */
720             red   = Scaled256(red);
721             green = Scaled256(green);
722             blue  = Scaled256(blue);
723
724             for (result = 0, n = 1; n < COLORS; ++n) {
725                 int d = Diff2(n, red) + Diff2(n, green) + Diff2(n, blue);
726                 if (d < d2) {
727                     d2 = d;
728                     result = n;
729                 }
730             }
731         } else {                /* direct color */
732             int power2 = 1;
733             int shifts = 8;
734
735             while (power2 < COLORS) {
736                 power2 <<= 3;
737                 shifts--;
738             }
739
740             if (shifts > 0) {
741                 /* TODO: round up */
742                 red >>= shifts;
743                 green >>= shifts;
744                 blue >>= shifts;
745                 result = ((red << (2 * (8 - shifts)))
746                           + (green << (8 - shifts))
747                           + blue);
748             }
749         }
750     }
751     return result;
752 }
753
754 static int
755 bytes_of(int value)
756 {
757     if (value & 7) {
758         value |= 7;
759         value++;
760     }
761     return value;
762 }
763
764 static int match_c(const char *, const char *, ...) GCC_SCANFLIKE(2,3);
765
766 static char *
767 skip_s(char *s)
768 {
769     while (isspace(UChar(*s)))
770         s++;
771     return s;
772 }
773
774 static const char *
775 skip_cs(const char *s)
776 {
777     while (isspace(UChar(*s)))
778         s++;
779     return s;
780 }
781
782 static char *
783 skip_word(char *s)
784 {
785     s = skip_s(s);
786     while (isgraph(UChar(*s)))
787         s++;
788     return s;
789 }
790
791 static int
792 match_c(const char *source, const char *pattern, ...)
793 {
794     int limit = (int) strlen(source);
795     const char *last_s = source + limit;
796     va_list ap;
797     int ch;
798     int *ip;
799     char *cp;
800     float *fp;
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("%cdnfsx", *pattern)) {
815             bool found = FALSE;
816             ch = *pattern++;
817             switch (ch) {
818             case '%':
819                 source++;
820                 break;
821             case 'c':
822                 cp = va_arg(ap, char *);
823                 do {
824                     *cp++ = *source++;
825                 } while (--limit > 0);
826                 break;
827             case 'd':
828             case 'x':
829                 limit = -1;
830                 ip = va_arg(ap, int *);
831                 lv = strtol(source, &cp, ch == 'd' ? 10 : 16);
832                 if (cp != 0 && cp != source) {
833                     *ip = (int) lv;
834                     source = cp;
835                 } else {
836                     goto finish;
837                 }
838                 break;
839             case 'f':
840                 /* floating point for pixels... */
841                 fp = va_arg(ap, float *);
842                 lv = strtol(source, &cp, 10);
843                 if (cp == 0 || cp == source)
844                     goto finish;
845                 *fp = (float) lv;
846                 source = cp;
847                 if (*source == '.') {
848                     lv = strtol(++source, &cp, 10);
849                     if (cp == 0 || cp == source)
850                         goto finish;
851                     {
852                         float scale = 1.0f;
853                         int digits = (int) (cp - source);
854                         while (digits-- > 0) {
855                             scale *= 10.0f;
856                         }
857                         *fp += (float) lv / scale;
858                     }
859                     source = cp;
860                 }
861                 break;
862             case 'n':
863                 /* not really sscanf... */
864                 limit = *va_arg(ap, int *);
865                 break;
866             case 's':
867                 limit = -1;
868                 cp = va_arg(ap, char *);
869                 while (*source != '\0') {
870                     ch = UChar(*source);
871                     if (isspace(ch)) {
872                         break;
873                     } else if (found && (ch == *skip_cs(pattern))) {
874                         break;
875                     } else {
876                         *cp++ = *source++;
877                         found = TRUE;
878                     }
879                 }
880                 *cp = '\0';
881                 break;
882             }
883             continue;
884         }
885         /* other characters are matched literally */
886         if (*source++ != ch) {
887             break;
888         }
889     }
890   finish:
891
892     va_end(ap);
893     if (source > last_s)
894         source = last_s;
895     return (*source || *pattern) ? 0 : 1;
896 }
897
898 static int
899 match_colors(const char *source, int cpp, char *arg1, char *arg2, char *arg3)
900 {
901     int result = 0;
902
903     /* most files use a quasi-fixed format */
904     if (match_c(source, " \"%n%c %s %s \" , ", &cpp, arg1, arg2, arg3)) {
905         arg1[cpp] = '\0';
906         result = 1;
907     } else {
908         const char *s = skip_cs(source);
909         size_t have = strlen(source);
910
911         if (*s++ == '"' && have > ((size_t) cpp + 2)) {
912             memcpy(arg1, s, (size_t) cpp);
913             s += cpp;
914             while (*s++ == '\t') {
915                 char *t;
916                 for (t = arg2; (*s != '\0') && strchr("\t\"", *s) == 0;) {
917                     if (*s == ' ') {
918                         s = skip_cs(s);
919                         break;
920                     }
921                     *t++ = *s++;
922                     *t = '\0';
923                 }
924                 for (t = arg3; (*s != '\0') && strchr("\t\"", *s) == 0;) {
925                     *t++ = *s++;
926                     *t = '\0';
927                 }
928                 if (!strcmp(arg2, "c")) {
929                     result = 1;
930                     break;
931                 }
932             }
933         }
934     }
935     return result;
936 }
937
938 static RGB_NAME *
939 parse_rgb(char **data)
940 {
941     char buf[BUFSIZ];
942     int n;
943     unsigned long r, g, b;
944     char *s, *t;
945     size_t item = 0;
946     size_t need;
947     RGB_NAME *result = 0;
948
949     for (need = 0; data[need] != 0; ++need) ;
950
951     result = typeCalloc(RGB_NAME, need + 2);
952     how_much.name += (sizeof(RGB_NAME) * (need + 2));
953
954     for (n = 0; data[n] != 0; ++n) {
955         if (strlen(t = data[n]) >= sizeof(buf) - 1)
956             continue;
957         if (*(s = skip_s(t)) == '!')
958             continue;
959
960         r = strtoul(s, &t, 10);
961         s = skip_s(t);
962         g = strtoul(s, &t, 10);
963         s = skip_s(t);
964         b = strtoul(s, &t, 10);
965         s = skip_s(t);
966
967         result[item].name = s;
968         t = s + strlen(s);
969         while (t-- != s && isspace(UChar(*t))) {
970             *t = '\0';
971         }
972         result[item].value = (int) ((r & 0xff) << 16 |
973                                     (g & 0xff) << 8 |
974                                     (b & 0xff));
975         ++item;
976     }
977
978     result[item].name = "none";
979     result[item].value = -1;
980
981     return result;
982 }
983
984 #define LOWERCASE(c) ((isalpha(UChar(c)) && isupper(UChar(c))) ? tolower(UChar(c)) : (c))
985
986 static int
987 CaselessCmp(const char *a, const char *b)
988 {                               /* strcasecmp isn't portable */
989     while (*a && *b) {
990         int cmp = LOWERCASE(*a) - LOWERCASE(*b);
991         if (cmp != 0)
992             break;
993         a++, b++;
994     }
995     return LOWERCASE(*a) - LOWERCASE(*b);
996 }
997
998 static RGB_NAME *
999 lookup_rgb(const char *name)
1000 {
1001     RGB_NAME *result = 0;
1002     if (rgb_table != 0) {
1003         int n;
1004         for (n = 0; rgb_table[n].name != 0; ++n) {
1005             if (!CaselessCmp(name, rgb_table[n].name)) {
1006                 result = &rgb_table[n];
1007                 break;
1008             }
1009         }
1010     }
1011     return result;
1012 }
1013
1014 static PICS_HEAD *
1015 parse_xbm(char **data)
1016 {
1017     int n;
1018     int state = 0;
1019     char buf[2048];
1020     int num;
1021     char ch;
1022     char *s;
1023     char *t;
1024     PICS_HEAD *result;
1025     size_t which = 0;
1026     size_t cells = 0;
1027
1028     debugmsg("called parse_xbm");
1029
1030     result = typeCalloc(PICS_HEAD, 1);
1031     how_much.head += sizeof(PICS_HEAD);
1032
1033     begin_c_values(2);
1034     gather_c_values(0);
1035     gather_c_values(0xffffff);
1036
1037     for (n = 0; data[n] != 0; ++n) {
1038         if (strlen(s = data[n]) >= sizeof(buf) - 1)
1039             continue;
1040         switch (state) {
1041         case 0:
1042         case 1:
1043         case 2:
1044             if (sscanf(s, "#define %1024s %d%c", buf, &num, &ch) >= 2) {
1045                 if ((t = strstr(buf, "_width")) != 0) {
1046                     state |= 1;
1047                     result->wide = (short) bytes_of(num);
1048                 } else if ((t = strstr(buf, "_height")) != 0) {
1049                     state |= 2;
1050                     result->high = (short) num;
1051                 } else {
1052                     break;
1053                 }
1054                 *t = '\0';
1055                 if (result->name) {
1056                     if (strcmp(result->name, buf)) {
1057                         goto finish;
1058                     }
1059                 } else {
1060                     result->name = strdup(buf);
1061                 }
1062             }
1063             break;
1064         case 3:
1065             if (sscanf(s, "static char %1024[^_ ]_bits[]%c", buf, &ch) >= 1) {
1066                 if (strcmp(result->name, buf)) {
1067                     goto finish;
1068                 }
1069                 state = 4;
1070                 cells = (size_t) (result->wide * result->high);
1071
1072                 result->cells = typeCalloc(PICS_CELL, cells);
1073                 how_much.cell += (sizeof(PICS_CELL) * cells);
1074
1075                 if ((s = strchr(s, L_CURLY)) == 0)
1076                     break;
1077                 ++s;
1078             } else {
1079                 break;
1080             }
1081         case 4:
1082             while (*s != '\0') {
1083                 while (isspace(UChar(*s))) {
1084                     ++s;
1085                 }
1086                 if (isdigit(UChar(*s))) {
1087                     long value = strtol(s, &t, 0);
1088                     int b;
1089                     if (t != s || value > MaxRGB || value < 0) {
1090                         s = t;
1091                     } else {
1092                         state = -1;
1093                         goto finish;
1094                     }
1095                     for (b = 0; b < 8; ++b) {
1096                         if (((1L << b) & value) != 0) {
1097                             result->cells[which].ch = '*';
1098                             result->cells[which].fg = 1;
1099                             reading_ncols[1].count++;
1100                         } else {
1101                             result->cells[which].ch = ' ';
1102                             result->cells[which].fg = 0;
1103                             reading_ncols[0].count++;
1104                         }
1105                         if (++which > cells) {
1106                             state = -1;
1107                             goto finish;
1108                         }
1109                     }
1110                 }
1111                 if (*s == R_CURLY) {
1112                     state = 5;
1113                     goto finish;
1114                 } else if (*s == ',') {
1115                     ++s;
1116                 }
1117             }
1118             break;
1119         default:
1120             break;
1121         }
1122     }
1123   finish:
1124     if (state < 4) {
1125         debugmsg("...state was only %d", state);
1126         if (result) {
1127             result = free_pics_head(result);
1128         }
1129     } else {
1130         finish_c_values(result);
1131     }
1132     return result;
1133 }
1134
1135 static PICS_HEAD *
1136 parse_xpm(char **data)
1137 {
1138     int state = 0;
1139     PICS_HEAD *result;
1140     RGB_NAME *by_name;
1141     int n;
1142     int cells = 0;
1143     int cpp = 1;                /* chars per pixel */
1144     int num[6];
1145     int found;
1146     int which = 0;
1147     int num_colors = 0;
1148     char ch;
1149     const char *cs;
1150     char *s;
1151     char buf[BUFSIZ];
1152     char arg1[BUFSIZ];
1153     char arg2[BUFSIZ];
1154     char arg3[BUFSIZ];
1155     char **list = 0;
1156
1157     debugmsg("called parse_xpm");
1158
1159     result = typeCalloc(PICS_HEAD, 1);
1160     how_much.head += sizeof(PICS_HEAD);
1161
1162     for (n = 0; data[n] != 0; ++n) {
1163         if (strlen(s = data[n]) >= sizeof(buf) - 1)
1164             continue;
1165         switch (state) {
1166         case 0:
1167             if (match_c(s, " /* XPM */ ")) {
1168                 state = 1;
1169             }
1170             break;
1171         case 1:
1172             if (match_c(s, " static char * %s [] = %c ", arg1, &ch) &&
1173                 ch == L_CURLY) {
1174                 result->name = strdup(arg1);
1175                 state = 2;
1176             }
1177             break;
1178         case 2:
1179             if (match_c(s, " \" %d %d %d %d \" , ",
1180                         num + 0, num + 1, num + 2, num + 3) ||
1181                 match_c(s, " \" %d %d %d %d %d %d \" , ",
1182                         num + 0, num + 1, num + 2, num + 3, num + 4, num + 5)) {
1183                 result->wide = (short) num[0];
1184                 result->high = (short) num[1];
1185                 result->colors = num[2];
1186
1187                 begin_c_values(num[2]);
1188
1189                 cells = (result->wide * result->high);
1190
1191                 result->cells = typeCalloc(PICS_CELL, cells);
1192                 how_much.cell += sizeof(PICS_CELL) * (size_t) cells;
1193
1194                 list = typeCalloc(char *, result->colors + 1);
1195                 how_much.list += sizeof(char *) * (size_t) (result->colors + 1);
1196
1197                 cpp = num[3];
1198                 state = 3;
1199             }
1200             break;
1201         case 3:
1202             if (!match_colors(s, cpp, arg1, arg2, arg3)) {
1203                 break;
1204             }
1205             num_colors++;
1206             free(list[reading_last]);
1207             list[reading_last] = strdup(arg1);
1208             if ((by_name = lookup_rgb(arg3)) != 0) {
1209                 found = gather_c_values(by_name->value);
1210             } else if (*arg3 == '#') {
1211                 char *rgb = arg3 + 1;
1212                 unsigned long value = strtoul(rgb, &s, 16);
1213                 switch ((int) strlen(rgb)) {
1214                 case 6:
1215                     break;
1216                 case 12:
1217                     value = (((value >> 24) & 0xff0000L)
1218                              | ((value >> 16) & 0xff00L)
1219                              | ((value >> 8) & 0xffL));
1220                     break;
1221                 default:
1222                     warning("unexpected rgb value %s", rgb);
1223                     break;
1224                 }
1225                 found = gather_c_values((int) value);
1226             } else {
1227                 found = gather_c_values(0);     /* actually an error */
1228             }
1229             debugmsg("  [%d:%d] %06X", num_colors, result->colors,
1230                      reading_ncols[(found >= 0) ? found : 0].fgcol);
1231             if (num_colors >= result->colors) {
1232                 finish_c_values(result);
1233                 state = 4;
1234                 if (list[0] == 0)
1235                     list[0] = strdup("\033");
1236             }
1237             break;
1238         case 4:
1239             if (*(cs = skip_cs(s)) == '"') {
1240                 ++cs;
1241                 while (*cs != '\0' && *cs != '"') {
1242                     int c;
1243
1244                     /* FIXME - factor out */
1245                     for (c = 0; c < result->colors; ++c) {
1246                         if (list[c] == 0) {
1247                             /* should not happen... */
1248                             continue;
1249                         }
1250                         if (!(strncmp) (cs, list[c], (size_t) cpp)) {
1251                             result->cells[which].ch = list[c][0];
1252                             result->cells[which].fg = c;
1253                             result->fgcol[c].count++;
1254                             break;
1255                         }
1256                     }
1257
1258                     if (result->cells[which].ch == 0) {
1259                         result->cells[which].ch = '?';
1260                         result->cells[which].fg = 0;
1261                     }
1262
1263                     if (++which >= cells) {
1264                         state = 5;
1265                         break;
1266                     }
1267                     for (c = cpp; c > 0; --c, ++cs) {
1268                         if (*cs == '\0')
1269                             break;
1270                     }
1271                 }
1272             }
1273             break;
1274         }
1275     }
1276
1277     if (result && list) {
1278         for (n = 0; n < result->colors; ++n)
1279             free(list[n]);
1280         free(list);
1281     }
1282
1283     if (state < 5) {
1284         debugmsg("...state was only %d", state);
1285         result = free_pics_head(result);
1286     }
1287
1288     if (result) {
1289         debugmsg("...allocated %d colors", result->colors);
1290     }
1291
1292     return result;
1293 }
1294
1295 /*
1296  * The obscurely-named "convert" is provided by ImageMagick
1297  */
1298 static PICS_HEAD *
1299 parse_img(const char *filename)
1300 {
1301     size_t need = strlen(filename) + 256;
1302     char *cmd = malloc(need);
1303     FILE *pp;
1304     char buffer[BUFSIZ];
1305     char dummy[BUFSIZ];
1306     bool okay = TRUE;
1307     PICS_HEAD *result;
1308     int pic_x = 0;
1309     int pic_y = 0;
1310     int width = in_curses ? COLS : 80;
1311
1312     _nc_SPRINTF(cmd, _nc_SLIMIT(need) "identify \"%s\"", filename);
1313     if (quiet)
1314         _nc_STRCAT(cmd, " 2>/dev/null", need);
1315
1316     logmsg("...opening pipe to %s", cmd);
1317
1318     result = typeCalloc(PICS_HEAD, 1);
1319     how_much.head += sizeof(PICS_HEAD);
1320
1321     if ((pp = popen(cmd, "r")) != 0) {
1322         if (fgets(buffer, sizeof(buffer), pp) != 0) {
1323             size_t n = strlen(filename);
1324             debugmsg2("...read %s", buffer);
1325             if (strlen(buffer) > n &&
1326                 !(strncmp) (buffer, filename, n) &&
1327                 isspace(UChar(buffer[n])) &&
1328                 sscanf(skip_word(buffer + n), " %dx%d ", &pic_x, &pic_y) == 2) {
1329                 /* distort image to make it show normally on terminal */
1330                 pic_x = (int) ((double) pic_x / aspect_ratio);
1331             } else {
1332                 pic_x = pic_y = 0;
1333             }
1334         }
1335         pclose(pp);
1336     }
1337     if (pic_x <= 0 || pic_y <= 0)
1338         goto finish;
1339
1340     _nc_SPRINTF(cmd, _nc_SLIMIT(need)
1341                 "convert " "-resize %dx%d\\! " "-thumbnail %dx \"%s\" "
1342                 "-define txt:compliance=SVG txt:-",
1343                 pic_x, pic_y, width, filename);
1344     if (quiet)
1345         _nc_STRCAT(cmd, " 2>/dev/null", need);
1346
1347     logmsg("...opening pipe to %s", cmd);
1348     if ((pp = popen(cmd, "r")) != 0) {
1349         int count = 0;
1350         int col = 0;
1351         int row = 0;
1352         int len = 0;
1353         while (fgets(buffer, sizeof(buffer), pp) != 0) {
1354             debugmsg2("[%5d] %s", count + 1, buffer);
1355             if (strlen(buffer) > 160) {         /* 80 columns would be enough */
1356                 okay = FALSE;
1357                 break;
1358             }
1359             if (count++ == 0) {
1360                 if (match_c(buffer,
1361                             "# ImageMagick pixel enumeration: %d,%d,%d,%s ",
1362                             &col, &row, &len, dummy)) {
1363                     result->name = strdup(filename);
1364                     result->wide = (short) col;
1365                     result->high = (short) row;
1366
1367                     begin_c_values(256);
1368
1369                     result->cells = typeCalloc(PICS_CELL, (size_t) (col * row));
1370                     how_much.cell += (sizeof(PICS_CELL) * (size_t) (col * row));
1371                 } else {
1372                     okay = FALSE;
1373                     break;
1374                 }
1375             } else {
1376                 /*
1377                  * subsequent lines begin "col,row: (r,g,b,a) #RGB".
1378                  * Those r/g/b could be integers (0..255) or float-percentages.
1379                  */
1380                 int r, g, b, nocolor;
1381                 float rf, gf, bf;
1382                 unsigned check;
1383                 char *t;
1384                 char *s = t = strchr(buffer, '#');
1385                 bool matched = FALSE;
1386
1387                 if (s != 0) {
1388                     /* after the "#RGB", there are differences - just ignore */
1389                     while (*s != '\0' && !isspace(UChar(*s)))
1390                         ++s;
1391                     *++s = '\0';
1392                 }
1393
1394                 if (match_c(buffer,
1395                             "%d,%d: (%d,%d,%d,%d) #%x ",
1396                             &col, &row,
1397                             &r, &g, &b, &nocolor,
1398                             &check)) {
1399                     matched = TRUE;
1400                 } else if (match_c(buffer,
1401                                    "%d,%d: (%f%%,%f%%,%f%%,%d) #%x ",
1402                                    &col, &row,
1403                                    &rf, &gf, &bf, &nocolor,
1404                                    &check) ||
1405                            match_c(buffer,
1406                                    "%d,%d: (%f%%,%f%%,%f%%) #%x ",
1407                                    &col, &row,
1408                                    &rf, &gf, &bf,
1409                                    &check)) {
1410                     matched = TRUE;
1411
1412 #define fp_fix(n) (int) (MaxRGB * (((n) > 100.0 ? 100.0 : (n)) / 100.0))
1413
1414                     r = fp_fix(rf);
1415                     g = fp_fix(gf);
1416                     b = fp_fix(bf);
1417                 }
1418                 if ((s - t) > 8)        /* 6 hex digits vs 8 */
1419                     check /= 256;
1420                 if (matched) {
1421                     int which, c;
1422                     int want_r = (check >> 16) & 0xff;
1423                     int want_g = (check >> 8) & 0xff;
1424                     int want_b = (check >> 0) & 0xff;
1425
1426 #define fp_err(tst,ref) ((tst > MaxRGB) || ((tst - ref)*(tst - ref)) > 4)
1427
1428                     if (fp_err(r, want_r) ||
1429                         fp_err(g, want_g) ||
1430                         fp_err(b, want_b)) {
1431                         okay = FALSE;
1432                         break;
1433                     }
1434                     c = gather_c_values((int) check);
1435                     which = col + (row * result->wide);
1436                     result->cells[which].ch = ((in_curses ||
1437                                                 check == 0xffffff)
1438                                                ? ' '
1439                                                : '#');
1440                     if (c >= 0 && c < reading_last) {
1441                         result->cells[which].fg = c;
1442                         reading_ncols[c].count++;
1443                     } else {
1444                         result->cells[which].fg = -1;
1445                     }
1446                 } else {
1447                     okay = FALSE;
1448                     break;
1449                 }
1450             }
1451         }
1452         finish_c_values(result);
1453         pclose(pp);
1454         if (okay) {
1455             /* FIXME - is this trimming needed? */
1456             for (len = result->colors; len > 3; len--) {
1457                 if (result->fgcol[len - 1].fgcol == 0) {
1458                     result->colors = len - 1;
1459                 } else {
1460                     break;
1461                 }
1462             }
1463         }
1464     }
1465   finish:
1466     free(cmd);
1467
1468     if (!okay) {
1469         result = free_pics_head(result);
1470     }
1471
1472     return result;
1473 }
1474
1475 static PICS_HEAD *
1476 read_picture(const char *filename, char **data)
1477 {
1478     PICS_HEAD *pics;
1479     if ((pics = parse_xbm(data)) == 0) {
1480         dispose_c_values();
1481         if ((pics = parse_xpm(data)) == 0) {
1482             dispose_c_values();
1483             if ((pics = parse_img(filename)) == 0) {
1484                 dispose_c_values();
1485                 free_data(data);
1486                 warning("unexpected file-format for \"%s\"", filename);
1487             } else if (pics->high == 0 || pics->wide == 0) {
1488                 dispose_c_values();
1489                 free_data(data);
1490                 pics = free_pics_head(pics);
1491                 warning("no picture found in \"%s\"", filename);
1492             }
1493         }
1494     }
1495     return pics;
1496 }
1497
1498 #define fg_color(pics,n) (pics->fgcol[n].fgcol)
1499
1500 static void
1501 dump_picture(PICS_HEAD * pics)
1502 {
1503     int y, x;
1504
1505     printf("Name %s\n", pics->name);
1506     printf("Size %dx%d\n", pics->high, pics->wide);
1507     printf("Color\n");
1508     for (y = 0; y < pics->colors; ++y) {
1509         if (fg_color(pics, y) < 0) {
1510             printf(" %3d: %d\n", y, fg_color(pics, y));
1511         } else {
1512             printf(" %3d: #%06x\n", y, fg_color(pics, y));
1513         }
1514     }
1515     for (y = 0; y < pics->high; ++y) {
1516         for (x = 0; x < pics->wide; ++x) {
1517             putchar(pics->cells[y * pics->wide + x].ch);
1518         }
1519         putchar('\n');
1520     }
1521 }
1522
1523 #ifndef USE_DISPLAY_DRIVER
1524 static void
1525 init_display(const char *palette_path, int opt_d)
1526 {
1527     (void) opt_d;
1528     if (isatty(fileno(stdout))) {
1529         in_curses = TRUE;
1530         setlocale(LC_ALL, "");
1531         initscr();
1532         cbreak();
1533         noecho();
1534         curs_set(0);
1535         if (has_colors()) {
1536             start_color();
1537 #if HAVE_USE_DEFAULT_COLORS
1538             if (opt_d)
1539                 use_default_colors();
1540 #endif
1541             init_palette(palette_path);
1542         }
1543         scrollok(stdscr, FALSE);
1544         stop_curses();
1545     }
1546 }
1547
1548 static void
1549 show_picture(PICS_HEAD * pics)
1550 {
1551     int y, x;
1552     int n;
1553
1554     debugmsg("called show_picture");
1555     logmsg("...using %dx%d screen", LINES, COLS);
1556 #if HAVE_RESET_COLOR_PAIRS
1557     reset_color_pairs();
1558 #elif HAVE_CURSCR
1559     wclear(curscr);
1560     clear();
1561 #endif
1562     if (has_colors()) {
1563         logmsg("...using %d colors", pics->colors);
1564         for (n = 0; n < pics->colors; ++n) {
1565             int my_pair = (n + 1);
1566             int my_color = map_color(fg_color(pics, n));
1567 #if USE_EXTENDED_COLORS
1568             if (use_extended_pairs) {
1569                 init_extended_pair(my_pair, my_color, my_color);
1570             } else
1571 #endif
1572             {
1573                 my_pair &= 0x7fff;
1574                 my_color &= 0x7fff;
1575                 init_pair((short) my_pair, (short) my_color, (short) my_color);
1576             }
1577         }
1578         attrset(COLOR_PAIR(1));
1579         erase();
1580     }
1581     for (y = 0; y < pics->high; ++y) {
1582         if (y >= LINES)
1583             break;
1584         move(y, 0);
1585
1586         for (x = 0; x < pics->wide; ++x) {
1587             int my_pair;
1588
1589             if (x >= COLS)
1590                 break;
1591             n = (y * pics->wide + x);
1592             my_pair = pics->cells[n].fg + 1;
1593 #if USE_EXTENDED_COLORS
1594             if (use_extended_pairs) {
1595                 cchar_t temp;
1596                 wchar_t wch[2];
1597                 wch[0] = (wchar_t) pics->cells[n].ch;
1598                 wch[1] = 0;
1599                 setcchar(&temp, wch, A_NORMAL, (short) my_pair, &my_pair);
1600                 add_wch(&temp);
1601             } else
1602 #endif
1603             {
1604                 attrset(COLOR_PAIR(my_pair));
1605                 addch((chtype) pics->cells[n].ch);
1606             }
1607         }
1608     }
1609     if (slow_time >= 0) {
1610         refresh();
1611         if (slow_time > 0) {
1612 #ifdef NCURSES_VERSION
1613             napms(1000 * slow_time);
1614 #else
1615             sleep((unsigned) slow_time);
1616 #endif
1617         }
1618     } else {
1619         wmove(stdscr, 0, 0);
1620         getch();
1621     }
1622     if (!quiet)
1623         endwin();
1624 }
1625 #endif
1626
1627 static int
1628 compare_fg_counts(const void *a, const void *b)
1629 {
1630     const FG_NODE *p = (const FG_NODE *) a;
1631     const FG_NODE *q = (const FG_NODE *) b;
1632     return (q->count - p->count);
1633 }
1634
1635 static void
1636 report_colors(PICS_HEAD * pics)
1637 {
1638     int accum;
1639     double level;
1640     int j;
1641     int shift;
1642     int total;
1643     char buffer[256];
1644
1645     if (logfp == 0)
1646         return;
1647
1648     qsort(pics->fgcol, (size_t) pics->colors, sizeof(FG_NODE), compare_fg_counts);
1649     /*
1650      * For debugging, show a (short) list of the colors used.
1651      */
1652     if (debugging && (pics->colors < 1000)) {
1653         int digits = 0;
1654         int high;
1655         int wide = 4;
1656         for (j = pics->colors; j != 0; j /= 10) {
1657             ++digits;
1658             if (j < 10)
1659                 ++digits;
1660         }
1661         if (digits > 8)
1662             digits = 8;
1663         logmsg("These colors were used:");
1664         high = (pics->colors + wide - 1) / wide;
1665         for (j = 0; j < high && j < pics->colors; ++j) {
1666             int k;
1667             char *s = buffer;
1668             *s = '\0';
1669             for (k = 0; k < wide; ++k) {
1670                 int n = j + (k * high);
1671                 size_t want = (sizeof(buffer) - (size_t) (s - buffer));
1672                 if (want < 100 || want >= sizeof(buffer))
1673                     break;
1674                 if (n >= pics->colors)
1675                     break;
1676                 if (k) {
1677                     *s++ = ' ';
1678                     if (digits < 8) {
1679                         _nc_SPRINTF(s, _nc_SLIMIT(want) "%*s", 8 - digits,
1680                                     " ");
1681                         s += strlen(s);
1682                     }
1683                 }
1684                 if (pics->fgcol[n].fgcol >= 0) {
1685                     _nc_SPRINTF(s, _nc_SLIMIT(want) "%3d #%06X %*d", n,
1686                                 pics->fgcol[n].fgcol,
1687                                 digits, pics->fgcol[n].count);
1688                 } else {
1689                     _nc_SPRINTF(s, _nc_SLIMIT(want) "%3d (empty) %*d", n,
1690                                 digits, pics->fgcol[n].count);
1691                 }
1692                 s += strlen(s);
1693                 if ((s - buffer) > 100)
1694                     break;
1695             }
1696             logmsg("%s", buffer);
1697         }
1698     }
1699
1700     /*
1701      * Given the list of colors sorted by the number of times they are used,
1702      * log a short report showing the number of colors for 90%, 99%, 99.9%,
1703      * etc.
1704      */
1705     logmsg("Number of colors versus number of cells");
1706     total = pics->high * pics->wide;
1707     accum = 0;
1708     level = 0.1;
1709     shift = 1;
1710     for (j = 0; j < pics->colors; ++j) {
1711         accum += pics->fgcol[j].count;
1712         if (accum >= (total * (1.0 - level))) {
1713             int after = (shift > 2) ? shift - 2 : 0;
1714             logmsg("%8d colors (%.1f%%) in %d cells (%.*f%%)",
1715                    j + 1,
1716                    (100.0 * (j + 1)) / pics->colors,
1717                    accum,
1718                    after, (100.0 * accum) / total);
1719             if (accum >= total)
1720                 break;
1721             level /= 10.0;
1722             shift++;
1723         }
1724     }
1725 }
1726
1727 int
1728 main(int argc, char *argv[])
1729 {
1730     int n;
1731     int opt_d = FALSE;
1732     char ignore_ch;
1733     const char *palette_path = 0;
1734     const char *rgb_path = RGB_PATH;
1735
1736     while ((n = getopt(argc, argv, "a:dLl:p:qr:s:x:")) != -1) {
1737         switch (n) {
1738         case 'a':
1739             if (sscanf(optarg, "%lf%c", &aspect_ratio, &ignore_ch) != 1
1740                 || aspect_ratio < 0.1
1741                 || aspect_ratio > 10.) {
1742                 fprintf(stderr, "Expected a number in [0.1 to 10.]: %s\n", optarg);
1743                 usage();
1744             }
1745             break;
1746 #if HAVE_USE_DEFAULT_COLORS
1747         case 'd':
1748             opt_d = TRUE;
1749             break;
1750 #endif
1751         case 'L':
1752             debugging = TRUE;
1753             break;
1754         case 'l':
1755             if ((logfp = fopen(optarg, "a")) == 0)
1756                 failed(optarg);
1757             break;
1758         case 'p':
1759             palette_path = optarg;
1760             break;
1761         case 'q':
1762             quiet = TRUE;
1763             break;
1764         case 'r':
1765             rgb_path = optarg;
1766             break;
1767         case 's':
1768             slow_time = atoi(optarg);
1769             break;
1770 #if USE_EXTENDED_COLORS
1771         case 'x':
1772             {
1773                 char *s = optarg;
1774                 while (*s) {
1775                     switch (*s++) {
1776                     case 'p':
1777                         use_extended_pairs = TRUE;
1778                         break;
1779                     case 'c':
1780                         use_extended_colors = TRUE;
1781                         break;
1782                     default:
1783                         usage();
1784                         break;
1785                     }
1786                 }
1787             }
1788             break;
1789 #endif
1790         default:
1791             usage();
1792             break;
1793         }
1794     }
1795
1796     if (optind < argc) {
1797         char **rgb_data = read_file(rgb_path);
1798
1799         if (rgb_data)
1800             rgb_table = parse_rgb(rgb_data);
1801
1802         init_display(palette_path, opt_d);
1803         if (optind >= argc)
1804             giveup("expected at least one image filename");
1805
1806         for (n = optind; n < argc; ++n) {
1807             PICS_HEAD *pics;
1808             char **data = read_file(argv[n]);
1809
1810             if (data == 0) {
1811                 warning("cannot read \"%s\"", argv[n]);
1812                 continue;
1813             }
1814             if ((pics = read_picture(argv[n], data)) != 0) {
1815                 if (in_curses) {
1816                     show_picture(pics);
1817                 } else {
1818                     dump_picture(pics);
1819                 }
1820                 report_colors(pics);
1821                 dispose_c_values();
1822                 free_data(data);
1823                 free_pics_head(pics);
1824             }
1825         }
1826         free_data(rgb_data);
1827         free(rgb_table);
1828         free(all_colors);
1829     } else {
1830         usage();
1831     }
1832
1833     cleanup(EXIT_SUCCESS);
1834 }