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