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