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