1 /****************************************************************************
2  * Copyright 2018-2020,2021 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.139 2021/05/08 15:56:05 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
logmsg(const char * fmt,...)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
logmsg2(const char * fmt,...)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
close_log(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
cleanup(int code)189 cleanup(int code)
190 {
191     pause_curses();
192     close_log();
193     ExitProgram(code);
194     /* NOTREACHED */
195 }
196 
197 static void
failed(const char * msg)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
warning(const char * fmt,...)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
free_data(char ** data)227 free_data(char **data)
228 {
229     if (data != 0) {
230 	free(data[0]);
231 	free(data);
232     }
233 }
234 
235 static PICS_HEAD *
free_pics_head(PICS_HEAD * pics)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
begin_c_values(int size)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
compare_c_values(const void * p,const void * q)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
check_c_values(int ln)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
gather_c_values(int fg)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
finish_c_values(PICS_HEAD * head)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
dispose_c_values(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
is_file(const char * filename,struct stat * sb)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 **
read_file(const char * filename)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
usage(void)490 usage(void)
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 	,"Options:"
498 	,"  -a ratio     aspect-ratio correction for ImageMagick"
499 #if HAVE_USE_DEFAULT_COLORS
500 	,"  -d           invoke use_default_colors"
501 #endif
502 	,"  -L           add debugging information to logfile"
503 	,"  -l logfile   write informational messages to logfile"
504 	,"  -p palette   color-palette file (default \"$TERM.dat\")"
505 	,"  -q           less verbose"
506 	,"  -r rgb-path  xpm uses X rgb color-names (default \"" RGB_PATH "\")"
507 	,"  -s SECS      pause for SECS seconds after display vs getch"
508 #if USE_EXTENDED_COLORS
509 	,"  -x [pc]      use extension (p=extended-pairs, c=extended-colors)"
510 	,"               Either/both extension may be given"
511 #endif
512     };
513     size_t n;
514 
515     pause_curses();
516 
517     fflush(stdout);
518     for (n = 0; n < SIZEOF(msg); n++)
519 	fprintf(stderr, "%s\n", msg[n]);
520     cleanup(EXIT_FAILURE);
521 }
522 
523 static void
giveup(const char * fmt,...)524 giveup(const char *fmt, ...)
525 {
526     va_list ap;
527 
528     pause_curses();
529     fflush(stdout);
530 
531     va_start(ap, fmt);
532     vfprintf(stderr, fmt, ap);
533     fputc('\n', stderr);
534     va_end(ap);
535 
536     if (logfp) {
537 	va_start(ap, fmt);
538 	vfprintf(logfp, fmt, ap);
539 	fputc('\n', logfp);
540 	va_end(ap);
541 	fflush(logfp);
542     }
543 
544     usage();
545 }
546 
547 /*
548  * Palette files are named for $TERM values.  However, there are fewer palette
549  * files than $TERM's.  Although there are known problems (some cannot even get
550  * black and white correct), for the purpose of comparison, pretending that
551  * those map into "xterm" is useful.
552  */
553 static char **
read_palette(const char * filename)554 read_palette(const char *filename)
555 {
556     static const char *data_dir = DATA_DIR;
557     char **result = 0;
558     size_t last = strlen(filename);
559     size_t need = (strlen(data_dir) + 20 + last);
560     char *full_name = malloc(need);
561     char *s;
562     struct stat sb;
563 
564     if (full_name != 0) {
565 	int tries;
566 	for (tries = 0; tries < 8; ++tries) {
567 
568 	    *(s = full_name) = '\0';
569 	    if (tries & 1) {
570 		if (strchr(filename, '/') == 0) {
571 		    _nc_SPRINTF(full_name, _nc_SLIMIT(need) "%s/", data_dir);
572 		} else {
573 		    continue;
574 		}
575 	    }
576 	    s += strlen(s);
577 	    if (((size_t) (s - full_name) + last + 1) >= need)
578 		continue;
579 
580 	    _nc_STRCAT(full_name, filename, need);
581 	    if (tries & 4) {
582 		char *t = s;
583 		char *tc;
584 		int num;
585 		char chr;
586 		int found = 0;
587 		while (*t != '\0') {
588 		    if (*t == '-') {
589 			if (sscanf(t, "-%d%c", &num, &chr) == 2 &&
590 			    chr == 'c' &&
591 			    (tc = strchr(t, chr)) != 0 &&
592 			    !(strncmp) (tc, "color", 5)) {
593 			    found = 1;
594 			}
595 			break;
596 		    }
597 		    ++t;
598 		}
599 		if (found && (t != s)
600 		    && (strncmp) (s, "xterm", (size_t) (t - s))) {
601 		    _nc_SPRINTF(s, _nc_SLIMIT(need - (size_t) (s - full_name))
602 				"xterm%s", filename + (t - s));
603 		} else {
604 		    continue;
605 		}
606 	    }
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
init_palette(const char * palette_file)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
map_color(int value)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
bytes_of(int value)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 *
skip_s(char * s)767 skip_s(char *s)
768 {
769     while (isspace(UChar(*s)))
770 	s++;
771     return s;
772 }
773 
774 static const char *
skip_cs(const char * s)775 skip_cs(const char *s)
776 {
777     while (isspace(UChar(*s)))
778 	s++;
779     return s;
780 }
781 
782 static char *
skip_word(char * s)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
match_c(const char * source,const char * pattern,...)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
match_colors(const char * source,int cpp,char * arg1,char * arg2,char * arg3)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 *
parse_rgb(char ** data)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 #define LOWERCASE(c) ((isalpha(UChar(c)) && isupper(UChar(c))) ? tolower(UChar(c)) : (c))
958 
959 static int
CaselessCmp(const char * a,const char * b)960 CaselessCmp(const char *a, const char *b)
961 {				/* strcasecmp isn't portable */
962     while (*a && *b) {
963 	int cmp = LOWERCASE(*a) - LOWERCASE(*b);
964 	if (cmp != 0)
965 	    break;
966 	a++, b++;
967     }
968     return LOWERCASE(*a) - LOWERCASE(*b);
969 }
970 
971 static RGB_NAME *
lookup_rgb(const char * name)972 lookup_rgb(const char *name)
973 {
974     RGB_NAME *result = 0;
975     if (rgb_table != 0) {
976 	int n;
977 	for (n = 0; rgb_table[n].name != 0; ++n) {
978 	    if (!CaselessCmp(name, rgb_table[n].name)) {
979 		result = &rgb_table[n];
980 		break;
981 	    }
982 	}
983     }
984     return result;
985 }
986 
987 static PICS_HEAD *
parse_xbm(char ** data)988 parse_xbm(char **data)
989 {
990     int n;
991     int state = 0;
992     char buf[2048];
993     int num;
994     char ch;
995     char *s;
996     char *t;
997     PICS_HEAD *result;
998     size_t which = 0;
999     size_t cells = 0;
1000 
1001     debugmsg("called parse_xbm");
1002 
1003     result = typeCalloc(PICS_HEAD, 1);
1004     how_much.head += sizeof(PICS_HEAD);
1005 
1006     begin_c_values(2);
1007     gather_c_values(0);
1008     gather_c_values(0xffffff);
1009 
1010     for (n = 0; data[n] != 0; ++n) {
1011 	if (strlen(s = data[n]) >= sizeof(buf) - 1)
1012 	    continue;
1013 	switch (state) {
1014 	case 0:
1015 	case 1:
1016 	case 2:
1017 	    if (sscanf(s, "#define %1024s %d%c", buf, &num, &ch) >= 2) {
1018 		if ((t = strstr(buf, "_width")) != 0) {
1019 		    state |= 1;
1020 		    result->wide = (short) bytes_of(num);
1021 		} else if ((t = strstr(buf, "_height")) != 0) {
1022 		    state |= 2;
1023 		    result->high = (short) num;
1024 		} else {
1025 		    break;
1026 		}
1027 		*t = '\0';
1028 		if (result->name) {
1029 		    if (strcmp(result->name, buf)) {
1030 			goto finish;
1031 		    }
1032 		} else {
1033 		    result->name = strdup(buf);
1034 		}
1035 	    }
1036 	    break;
1037 	case 3:
1038 	    if (sscanf(s, "static char %1024[^_ ]_bits[]%c", buf, &ch) >= 1) {
1039 		if (strcmp(result->name, buf)) {
1040 		    goto finish;
1041 		}
1042 		state = 4;
1043 		cells = (size_t) (result->wide * result->high);
1044 
1045 		result->cells = typeCalloc(PICS_CELL, cells);
1046 		how_much.cell += (sizeof(PICS_CELL) * cells);
1047 
1048 		if ((s = strchr(s, L_CURLY)) == 0)
1049 		    break;
1050 		++s;
1051 	    } else {
1052 		break;
1053 	    }
1054 	case 4:
1055 	    while (*s != '\0') {
1056 		while (isspace(UChar(*s))) {
1057 		    ++s;
1058 		}
1059 		if (isdigit(UChar(*s))) {
1060 		    long value = strtol(s, &t, 0);
1061 		    int b;
1062 		    if (t != s || value > MaxRGB || value < 0) {
1063 			s = t;
1064 		    } else {
1065 			state = -1;
1066 			goto finish;
1067 		    }
1068 		    for (b = 0; b < 8; ++b) {
1069 			if (((1L << b) & value) != 0) {
1070 			    result->cells[which].ch = '*';
1071 			    result->cells[which].fg = 1;
1072 			    reading_ncols[1].count++;
1073 			} else {
1074 			    result->cells[which].ch = ' ';
1075 			    result->cells[which].fg = 0;
1076 			    reading_ncols[0].count++;
1077 			}
1078 			if (++which > cells) {
1079 			    state = -1;
1080 			    goto finish;
1081 			}
1082 		    }
1083 		}
1084 		if (*s == R_CURLY) {
1085 		    state = 5;
1086 		    goto finish;
1087 		} else if (*s == ',') {
1088 		    ++s;
1089 		}
1090 	    }
1091 	    break;
1092 	default:
1093 	    break;
1094 	}
1095     }
1096   finish:
1097     if (state < 4) {
1098 	debugmsg("...state was only %d", state);
1099 	if (result) {
1100 	    result = free_pics_head(result);
1101 	}
1102     } else {
1103 	finish_c_values(result);
1104     }
1105     return result;
1106 }
1107 
1108 static PICS_HEAD *
parse_xpm(char ** data)1109 parse_xpm(char **data)
1110 {
1111     int state = 0;
1112     PICS_HEAD *result;
1113     RGB_NAME *by_name;
1114     int n;
1115     int cells = 0;
1116     int cpp = 1;		/* chars per pixel */
1117     int num[6];
1118     int found;
1119     int which = 0;
1120     int num_colors = 0;
1121     char ch;
1122     const char *cs;
1123     char *s;
1124     char buf[BUFSIZ];
1125     char arg1[BUFSIZ];
1126     char arg2[BUFSIZ];
1127     char arg3[BUFSIZ];
1128     char **list = 0;
1129 
1130     debugmsg("called parse_xpm");
1131 
1132     result = typeCalloc(PICS_HEAD, 1);
1133     how_much.head += sizeof(PICS_HEAD);
1134 
1135     for (n = 0; data[n] != 0; ++n) {
1136 	if (strlen(s = data[n]) >= sizeof(buf) - 1)
1137 	    continue;
1138 	switch (state) {
1139 	case 0:
1140 	    if (match_c(s, " /* XPM */ ")) {
1141 		state = 1;
1142 	    }
1143 	    break;
1144 	case 1:
1145 	    if (match_c(s, " static char * %s [] = %c ", arg1, &ch) &&
1146 		ch == L_CURLY) {
1147 		result->name = strdup(arg1);
1148 		state = 2;
1149 	    }
1150 	    break;
1151 	case 2:
1152 	    if (match_c(s, " \" %d %d %d %d \" , ",
1153 			num + 0, num + 1, num + 2, num + 3) ||
1154 		match_c(s, " \" %d %d %d %d %d %d \" , ",
1155 			num + 0, num + 1, num + 2, num + 3, num + 4, num + 5)) {
1156 		result->wide = (short) num[0];
1157 		result->high = (short) num[1];
1158 		result->colors = num[2];
1159 
1160 		begin_c_values(num[2]);
1161 
1162 		cells = (result->wide * result->high);
1163 
1164 		result->cells = typeCalloc(PICS_CELL, cells);
1165 		how_much.cell += sizeof(PICS_CELL) * (size_t) cells;
1166 
1167 		list = typeCalloc(char *, result->colors + 1);
1168 		how_much.list += sizeof(char *) * (size_t) (result->colors + 1);
1169 
1170 		cpp = num[3];
1171 		state = 3;
1172 	    }
1173 	    break;
1174 	case 3:
1175 	    if (!match_colors(s, cpp, arg1, arg2, arg3)) {
1176 		break;
1177 	    }
1178 	    num_colors++;
1179 	    free(list[reading_last]);
1180 	    list[reading_last] = strdup(arg1);
1181 	    if ((by_name = lookup_rgb(arg3)) != 0) {
1182 		found = gather_c_values(by_name->value);
1183 	    } else if (*arg3 == '#') {
1184 		char *rgb = arg3 + 1;
1185 		unsigned long value = strtoul(rgb, &s, 16);
1186 		switch ((int) strlen(rgb)) {
1187 		case 6:
1188 		    break;
1189 		case 12:
1190 		    value = (((value >> 24) & 0xff0000L)
1191 			     | ((value >> 16) & 0xff00L)
1192 			     | ((value >> 8) & 0xffL));
1193 		    break;
1194 		default:
1195 		    warning("unexpected rgb value %s", rgb);
1196 		    break;
1197 		}
1198 		found = gather_c_values((int) value);
1199 	    } else {
1200 		found = gather_c_values(0);	/* actually an error */
1201 	    }
1202 	    debugmsg("  [%d:%d] %06X", num_colors, result->colors,
1203 		     reading_ncols[(found >= 0) ? found : 0].fgcol);
1204 	    if (num_colors >= result->colors) {
1205 		finish_c_values(result);
1206 		state = 4;
1207 		if (list[0] == 0)
1208 		    list[0] = strdup("\033");
1209 	    }
1210 	    break;
1211 	case 4:
1212 	    if (*(cs = skip_cs(s)) == '"') {
1213 		++cs;
1214 		while (*cs != '\0' && *cs != '"') {
1215 		    int c;
1216 
1217 		    /* FIXME - factor out */
1218 		    for (c = 0; c < result->colors; ++c) {
1219 			if (list[c] == 0) {
1220 			    /* should not happen... */
1221 			    continue;
1222 			}
1223 			if (!(strncmp) (cs, list[c], (size_t) cpp)) {
1224 			    result->cells[which].ch = list[c][0];
1225 			    result->cells[which].fg = c;
1226 			    result->fgcol[c].count++;
1227 			    break;
1228 			}
1229 		    }
1230 
1231 		    if (result->cells[which].ch == 0) {
1232 			result->cells[which].ch = '?';
1233 			result->cells[which].fg = 0;
1234 		    }
1235 
1236 		    if (++which >= cells) {
1237 			state = 5;
1238 			break;
1239 		    }
1240 		    for (c = cpp; c > 0; --c, ++cs) {
1241 			if (*cs == '\0')
1242 			    break;
1243 		    }
1244 		}
1245 	    }
1246 	    break;
1247 	}
1248     }
1249 
1250     if (result && list) {
1251 	for (n = 0; n < result->colors; ++n)
1252 	    free(list[n]);
1253 	free(list);
1254     }
1255 
1256     if (state < 5) {
1257 	debugmsg("...state was only %d", state);
1258 	result = free_pics_head(result);
1259     }
1260 
1261     if (result) {
1262 	debugmsg("...allocated %d colors", result->colors);
1263     }
1264 
1265     return result;
1266 }
1267 
1268 /*
1269  * The obscurely-named "convert" is provided by ImageMagick
1270  */
1271 static PICS_HEAD *
parse_img(const char * filename)1272 parse_img(const char *filename)
1273 {
1274     size_t need = strlen(filename) + 256;
1275     char *cmd = malloc(need);
1276     FILE *pp;
1277     char buffer[BUFSIZ];
1278     char dummy[BUFSIZ];
1279     bool okay = TRUE;
1280     PICS_HEAD *result;
1281     int pic_x = 0;
1282     int pic_y = 0;
1283     int width = in_curses ? COLS : 80;
1284 
1285     _nc_SPRINTF(cmd, _nc_SLIMIT(need) "identify \"%s\"", filename);
1286     if (quiet)
1287 	_nc_STRCAT(cmd, " 2>/dev/null", need);
1288 
1289     logmsg("...opening pipe to %s", cmd);
1290 
1291     result = typeCalloc(PICS_HEAD, 1);
1292     how_much.head += sizeof(PICS_HEAD);
1293 
1294     if ((pp = popen(cmd, "r")) != 0) {
1295 	if (fgets(buffer, sizeof(buffer), pp) != 0) {
1296 	    size_t n = strlen(filename);
1297 	    debugmsg2("...read %s", buffer);
1298 	    if (strlen(buffer) > n &&
1299 		!(strncmp) (buffer, filename, n) &&
1300 		isspace(UChar(buffer[n])) &&
1301 		sscanf(skip_word(buffer + n), " %dx%d ", &pic_x, &pic_y) == 2) {
1302 		/* distort image to make it show normally on terminal */
1303 		pic_x = (int) ((double) pic_x / aspect_ratio);
1304 	    } else {
1305 		pic_x = pic_y = 0;
1306 	    }
1307 	}
1308 	pclose(pp);
1309     }
1310     if (pic_x <= 0 || pic_y <= 0)
1311 	goto finish;
1312 
1313     _nc_SPRINTF(cmd, _nc_SLIMIT(need)
1314 		"convert " "-resize %dx%d\\! " "-thumbnail %dx \"%s\" "
1315 		"-define txt:compliance=SVG txt:-",
1316 		pic_x, pic_y, width, filename);
1317     if (quiet)
1318 	_nc_STRCAT(cmd, " 2>/dev/null", need);
1319 
1320     logmsg("...opening pipe to %s", cmd);
1321     if ((pp = popen(cmd, "r")) != 0) {
1322 	int count = 0;
1323 	int col = 0;
1324 	int row = 0;
1325 	int len = 0;
1326 	while (fgets(buffer, sizeof(buffer), pp) != 0) {
1327 	    debugmsg2("[%5d] %s", count + 1, buffer);
1328 	    if (strlen(buffer) > 160) {		/* 80 columns would be enough */
1329 		okay = FALSE;
1330 		break;
1331 	    }
1332 	    if (count++ == 0) {
1333 		if (match_c(buffer,
1334 			    "# ImageMagick pixel enumeration: %d,%d,%d,%s ",
1335 			    &col, &row, &len, dummy)) {
1336 		    result->name = strdup(filename);
1337 		    result->wide = (short) col;
1338 		    result->high = (short) row;
1339 
1340 		    begin_c_values(256);
1341 
1342 		    result->cells = typeCalloc(PICS_CELL, (size_t) (col * row));
1343 		    how_much.cell += (sizeof(PICS_CELL) * (size_t) (col * row));
1344 		} else {
1345 		    okay = FALSE;
1346 		    break;
1347 		}
1348 	    } else {
1349 		/* subsequent lines begin "col,row: (r,g,b,a) #RGB" */
1350 		int r, g, b, nocolor;
1351 		unsigned check;
1352 		char *t;
1353 		char *s = t = strchr(buffer, '#');
1354 
1355 		if (s != 0) {
1356 		    /* after the "#RGB", there are differences - just ignore */
1357 		    while (*s != '\0' && !isspace(UChar(*s)))
1358 			++s;
1359 		    *++s = '\0';
1360 		}
1361 		if (match_c(buffer,
1362 			    "%d,%d: (%d,%d,%d,%d) #%x ",
1363 			    &col, &row,
1364 			    &r, &g, &b, &nocolor,
1365 			    &check)) {
1366 		    int which, c;
1367 
1368 		    if ((s - t) > 8)	/* 6 hex digits vs 8 */
1369 			check /= 256;
1370 		    if (r > MaxRGB ||
1371 			g > MaxRGB ||
1372 			b > MaxRGB ||
1373 			check != (unsigned) ((r << 16) | (g << 8) | b)) {
1374 			okay = FALSE;
1375 			break;
1376 		    }
1377 		    c = gather_c_values((int) check);
1378 		    which = col + (row * result->wide);
1379 		    result->cells[which].ch = ((in_curses ||
1380 						check == 0xffffff)
1381 					       ? ' '
1382 					       : '#');
1383 		    if (c >= 0 && c < reading_last) {
1384 			result->cells[which].fg = c;
1385 			reading_ncols[c].count++;
1386 		    } else {
1387 			result->cells[which].fg = -1;
1388 		    }
1389 		} else {
1390 		    okay = FALSE;
1391 		    break;
1392 		}
1393 	    }
1394 	}
1395 	finish_c_values(result);
1396 	pclose(pp);
1397 	if (okay) {
1398 	    /* FIXME - is this trimming needed? */
1399 	    for (len = result->colors; len > 3; len--) {
1400 		if (result->fgcol[len - 1].fgcol == 0) {
1401 		    result->colors = len - 1;
1402 		} else {
1403 		    break;
1404 		}
1405 	    }
1406 	}
1407     }
1408   finish:
1409     free(cmd);
1410 
1411     if (!okay) {
1412 	result = free_pics_head(result);
1413     }
1414 
1415     return result;
1416 }
1417 
1418 static PICS_HEAD *
read_picture(const char * filename,char ** data)1419 read_picture(const char *filename, char **data)
1420 {
1421     PICS_HEAD *pics;
1422     if ((pics = parse_xbm(data)) == 0) {
1423 	dispose_c_values();
1424 	if ((pics = parse_xpm(data)) == 0) {
1425 	    dispose_c_values();
1426 	    if ((pics = parse_img(filename)) == 0) {
1427 		dispose_c_values();
1428 		free_data(data);
1429 		warning("unexpected file-format for \"%s\"", filename);
1430 	    } else if (pics->high == 0 || pics->wide == 0) {
1431 		dispose_c_values();
1432 		free_data(data);
1433 		pics = free_pics_head(pics);
1434 		warning("no picture found in \"%s\"", filename);
1435 	    }
1436 	}
1437     }
1438     return pics;
1439 }
1440 
1441 #define fg_color(pics,n) (pics->fgcol[n].fgcol)
1442 
1443 static void
dump_picture(PICS_HEAD * pics)1444 dump_picture(PICS_HEAD * pics)
1445 {
1446     int y, x;
1447 
1448     printf("Name %s\n", pics->name);
1449     printf("Size %dx%d\n", pics->high, pics->wide);
1450     printf("Color\n");
1451     for (y = 0; y < pics->colors; ++y) {
1452 	if (fg_color(pics, y) < 0) {
1453 	    printf(" %3d: %d\n", y, fg_color(pics, y));
1454 	} else {
1455 	    printf(" %3d: #%06x\n", y, fg_color(pics, y));
1456 	}
1457     }
1458     for (y = 0; y < pics->high; ++y) {
1459 	for (x = 0; x < pics->wide; ++x) {
1460 	    putchar(pics->cells[y * pics->wide + x].ch);
1461 	}
1462 	putchar('\n');
1463     }
1464 }
1465 
1466 #ifndef USE_DISPLAY_DRIVER
1467 static void
init_display(const char * palette_path,int opt_d)1468 init_display(const char *palette_path, int opt_d)
1469 {
1470     (void) opt_d;
1471     if (isatty(fileno(stdout))) {
1472 	in_curses = TRUE;
1473 	initscr();
1474 	cbreak();
1475 	noecho();
1476 	curs_set(0);
1477 	if (has_colors()) {
1478 	    start_color();
1479 #if HAVE_USE_DEFAULT_COLORS
1480 	    if (opt_d)
1481 		use_default_colors();
1482 #endif
1483 	    init_palette(palette_path);
1484 	}
1485 	scrollok(stdscr, FALSE);
1486 	stop_curses();
1487     }
1488 }
1489 
1490 static void
show_picture(PICS_HEAD * pics)1491 show_picture(PICS_HEAD * pics)
1492 {
1493     int y, x;
1494     int n;
1495 
1496     debugmsg("called show_picture");
1497     logmsg("...using %dx%d screen", LINES, COLS);
1498 #if HAVE_RESET_COLOR_PAIRS
1499     reset_color_pairs();
1500 #elif HAVE_CURSCR
1501     wclear(curscr);
1502     clear();
1503 #endif
1504     if (has_colors()) {
1505 	logmsg("...using %d colors", pics->colors);
1506 	for (n = 0; n < pics->colors; ++n) {
1507 	    int my_pair = (n + 1);
1508 	    int my_color = map_color(fg_color(pics, n));
1509 #if USE_EXTENDED_COLORS
1510 	    if (use_extended_pairs) {
1511 		init_extended_pair(my_pair, my_color, my_color);
1512 	    } else
1513 #endif
1514 	    {
1515 		my_pair &= 0x7fff;
1516 		my_color &= 0x7fff;
1517 		init_pair((short) my_pair, (short) my_color, (short) my_color);
1518 	    }
1519 	}
1520 	attrset(COLOR_PAIR(1));
1521 	erase();
1522     }
1523     for (y = 0; y < pics->high; ++y) {
1524 	if (y >= LINES)
1525 	    break;
1526 	move(y, 0);
1527 
1528 	for (x = 0; x < pics->wide; ++x) {
1529 	    int my_pair;
1530 
1531 	    if (x >= COLS)
1532 		break;
1533 	    n = (y * pics->wide + x);
1534 	    my_pair = pics->cells[n].fg + 1;
1535 #if USE_EXTENDED_COLORS
1536 	    if (use_extended_pairs) {
1537 		cchar_t temp;
1538 		wchar_t wch[2];
1539 		wch[0] = (wchar_t) pics->cells[n].ch;
1540 		wch[1] = 0;
1541 		setcchar(&temp, wch, A_NORMAL, (short) my_pair, &my_pair);
1542 		add_wch(&temp);
1543 	    } else
1544 #endif
1545 	    {
1546 		attrset(COLOR_PAIR(my_pair));
1547 		addch((chtype) pics->cells[n].ch);
1548 	    }
1549 	}
1550     }
1551     if (slow_time >= 0) {
1552 	refresh();
1553 	if (slow_time > 0) {
1554 #ifdef NCURSES_VERSION
1555 	    napms(1000 * slow_time);
1556 #else
1557 	    sleep((unsigned) slow_time);
1558 #endif
1559 	}
1560     } else {
1561 	wmove(stdscr, 0, 0);
1562 	getch();
1563     }
1564     if (!quiet)
1565 	endwin();
1566 }
1567 #endif
1568 
1569 static int
compare_fg_counts(const void * a,const void * b)1570 compare_fg_counts(const void *a, const void *b)
1571 {
1572     const FG_NODE *p = (const FG_NODE *) a;
1573     const FG_NODE *q = (const FG_NODE *) b;
1574     return (q->count - p->count);
1575 }
1576 
1577 static void
report_colors(PICS_HEAD * pics)1578 report_colors(PICS_HEAD * pics)
1579 {
1580     int accum;
1581     double level;
1582     int j;
1583     int shift;
1584     int total;
1585     char buffer[256];
1586 
1587     if (logfp == 0)
1588 	return;
1589 
1590     qsort(pics->fgcol, (size_t) pics->colors, sizeof(FG_NODE), compare_fg_counts);
1591     /*
1592      * For debugging, show a (short) list of the colors used.
1593      */
1594     if (debugging && (pics->colors < 1000)) {
1595 	int digits = 0;
1596 	int high;
1597 	int wide = 4;
1598 	for (j = pics->colors; j != 0; j /= 10) {
1599 	    ++digits;
1600 	    if (j < 10)
1601 		++digits;
1602 	}
1603 	if (digits > 8)
1604 	    digits = 8;
1605 	logmsg("These colors were used:");
1606 	high = (pics->colors + wide - 1) / wide;
1607 	for (j = 0; j < high && j < pics->colors; ++j) {
1608 	    int k;
1609 	    char *s = buffer;
1610 	    *s = '\0';
1611 	    for (k = 0; k < wide; ++k) {
1612 		int n = j + (k * high);
1613 		size_t want = (sizeof(buffer) - (size_t) (s - buffer));
1614 		if (want < 100 || want >= sizeof(buffer))
1615 		    break;
1616 		if (n >= pics->colors)
1617 		    break;
1618 		if (k) {
1619 		    *s++ = ' ';
1620 		    if (digits < 8) {
1621 			_nc_SPRINTF(s, _nc_SLIMIT(want) "%*s", 8 - digits,
1622 				    " ");
1623 			s += strlen(s);
1624 		    }
1625 		}
1626 		if (pics->fgcol[n].fgcol >= 0) {
1627 		    _nc_SPRINTF(s, _nc_SLIMIT(want) "%3d #%06X %*d", n,
1628 				pics->fgcol[n].fgcol,
1629 				digits, pics->fgcol[n].count);
1630 		} else {
1631 		    _nc_SPRINTF(s, _nc_SLIMIT(want) "%3d (empty) %*d", n,
1632 				digits, pics->fgcol[n].count);
1633 		}
1634 		s += strlen(s);
1635 		if ((s - buffer) > 100)
1636 		    break;
1637 	    }
1638 	    logmsg("%s", buffer);
1639 	}
1640     }
1641 
1642     /*
1643      * Given the list of colors sorted by the number of times they are used,
1644      * log a short report showing the number of colors for 90%, 99%, 99.9%,
1645      * etc.
1646      */
1647     logmsg("Number of colors versus number of cells");
1648     total = pics->high * pics->wide;
1649     accum = 0;
1650     level = 0.1;
1651     shift = 1;
1652     for (j = 0; j < pics->colors; ++j) {
1653 	accum += pics->fgcol[j].count;
1654 	if (accum >= (total * (1.0 - level))) {
1655 	    int after = (shift > 2) ? shift - 2 : 0;
1656 	    logmsg("%8d colors (%.1f%%) in %d cells (%.*f%%)",
1657 		   j + 1,
1658 		   (100.0 * (j + 1)) / pics->colors,
1659 		   accum,
1660 		   after, (100.0 * accum) / total);
1661 	    if (accum >= total)
1662 		break;
1663 	    level /= 10.0;
1664 	    shift++;
1665 	}
1666     }
1667 }
1668 
1669 int
main(int argc,char * argv[])1670 main(int argc, char *argv[])
1671 {
1672     int n;
1673     int opt_d = FALSE;
1674     char ignore_ch;
1675     const char *palette_path = 0;
1676     const char *rgb_path = RGB_PATH;
1677 
1678     while ((n = getopt(argc, argv, "a:dLl:p:qr:s:x:")) != -1) {
1679 	switch (n) {
1680 	case 'a':
1681 	    if (sscanf(optarg, "%lf%c", &aspect_ratio, &ignore_ch) != 1
1682 		|| aspect_ratio < 0.1
1683 		|| aspect_ratio > 10.) {
1684 		fprintf(stderr, "Expected a number in [0.1 to 10.]: %s\n", optarg);
1685 		usage();
1686 	    }
1687 	    break;
1688 #if HAVE_USE_DEFAULT_COLORS
1689 	case 'd':
1690 	    opt_d = TRUE;
1691 	    break;
1692 #endif
1693 	case 'L':
1694 	    debugging = TRUE;
1695 	    break;
1696 	case 'l':
1697 	    if ((logfp = fopen(optarg, "a")) == 0)
1698 		failed(optarg);
1699 	    break;
1700 	case 'p':
1701 	    palette_path = optarg;
1702 	    break;
1703 	case 'q':
1704 	    quiet = TRUE;
1705 	    break;
1706 	case 'r':
1707 	    rgb_path = optarg;
1708 	    break;
1709 	case 's':
1710 	    slow_time = atoi(optarg);
1711 	    break;
1712 #if USE_EXTENDED_COLORS
1713 	case 'x':
1714 	    {
1715 		char *s = optarg;
1716 		while (*s) {
1717 		    switch (*s++) {
1718 		    case 'p':
1719 			use_extended_pairs = TRUE;
1720 			break;
1721 		    case 'c':
1722 			use_extended_colors = TRUE;
1723 			break;
1724 		    default:
1725 			usage();
1726 			break;
1727 		    }
1728 		}
1729 	    }
1730 	    break;
1731 #endif
1732 	default:
1733 	    usage();
1734 	    break;
1735 	}
1736     }
1737 
1738     if (optind < argc) {
1739 	char **rgb_data = read_file(rgb_path);
1740 
1741 	if (rgb_data)
1742 	    rgb_table = parse_rgb(rgb_data);
1743 
1744 	init_display(palette_path, opt_d);
1745 	if (optind >= argc)
1746 	    giveup("expected at least one image filename");
1747 
1748 	for (n = optind; n < argc; ++n) {
1749 	    PICS_HEAD *pics;
1750 	    char **data = read_file(argv[n]);
1751 
1752 	    if (data == 0) {
1753 		warning("cannot read \"%s\"", argv[n]);
1754 		continue;
1755 	    }
1756 	    if ((pics = read_picture(argv[n], data)) != 0) {
1757 		if (in_curses) {
1758 		    show_picture(pics);
1759 		} else {
1760 		    dump_picture(pics);
1761 		}
1762 		report_colors(pics);
1763 		dispose_c_values();
1764 		free_data(data);
1765 		free_pics_head(pics);
1766 	    }
1767 	}
1768 	free_data(rgb_data);
1769 	free(rgb_table);
1770 	free(all_colors);
1771     } else {
1772 	usage();
1773     }
1774 
1775     cleanup(EXIT_SUCCESS);
1776 }
1777