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