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