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