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