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