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