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