/
chafa.c
3153 lines (2638 loc) · 101 KB
/
chafa.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Copyright (C) 2018-2023 Hans Petter Jansson
*
* This file is part of Chafa, a program that shows pictures on text terminals.
*
* Chafa is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chafa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Chafa. If not, see <http://www.gnu.org/licenses/>. */
#include "config.h"
#include <errno.h>
#include <stdio.h>
#include <string.h> /* strspn, strlen, strcmp, strncmp, memset */
#include <locale.h> /* setlocale */
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h> /* ioctl */
#endif
#include <sys/types.h> /* open */
#include <sys/stat.h> /* stat */
#include <fcntl.h> /* open */
#include <unistd.h> /* STDOUT_FILENO */
#ifdef HAVE_SIGACTION
# include <signal.h> /* sigaction */
#endif
#include <stdlib.h> /* exit */
#ifdef HAVE_TERMIOS_H
# include <termios.h> /* tcgetattr, tcsetattr */
#endif
#include <glib/gstdio.h>
#include <chafa.h>
#include "font-loader.h"
#include "media-loader.h"
#include "named-colors.h"
#include "placement-counter.h"
/* Include after glib.h for G_OS_WIN32 */
#ifdef G_OS_WIN32
# ifdef HAVE_WINDOWS_H
# include <windows.h>
# endif
# include <wchar.h>
# include <io.h>
# include "conhost.h"
#endif
/* Maximum size of stack-allocated read/write buffer */
#define BUFFER_MAX 4096
#define ANIM_FPS_MAX 100000.0
#define FILE_DURATION_DEFAULT 0.0
#define SCALE_MAX 9999.0
#define CELL_EXTENT_AUTO_MAX 65535
#define PIXEL_EXTENT_MAX 32767
typedef enum
{
TRISTATE_FALSE = 0,
TRISTATE_TRUE,
TRISTATE_AUTO
}
Tristate;
typedef struct
{
gchar *executable_name;
gboolean show_help;
gboolean show_version;
gboolean skip_processing;
GList *args;
ChafaCanvasMode mode;
ChafaColorExtractor color_extractor;
ChafaColorSpace color_space;
ChafaDitherMode dither_mode;
ChafaPixelMode pixel_mode;
gint dither_grain_width;
gint dither_grain_height;
gdouble dither_intensity;
ChafaSymbolMap *symbol_map;
ChafaSymbolMap *fill_symbol_map;
gboolean symbols_specified;
gboolean is_interactive;
gboolean clear;
gboolean verbose;
gboolean invert;
gboolean preprocess;
gboolean polite;
gboolean stretch;
gboolean zoom;
gboolean watch;
gboolean fg_only;
gboolean animate;
gboolean relative;
gboolean relative_set;
gboolean fit_to_width;
ChafaAlign horiz_align;
ChafaAlign vert_align;
gint view_width, view_height;
gint width, height;
gint cell_width, cell_height;
gint margin_bottom, margin_right;
gdouble scale;
gdouble font_ratio;
gint work_factor;
gint optimization_level;
gint n_threads;
ChafaOptimizations optimizations;
ChafaPassthrough passthrough;
gboolean passthrough_set;
guint32 fg_color;
gboolean fg_color_set;
guint32 bg_color;
gboolean bg_color_set;
gdouble transparency_threshold;
gboolean transparency_threshold_set;
gdouble file_duration_s;
/* If > 0.0, override the framerate specified by the input file. */
gdouble anim_fps;
/* Applied after FPS is determined. If final value >= ANIM_FPS_MAX,
* eliminate interframe delay altogether. */
gdouble anim_speed_multiplier;
Tristate use_exact_size;
/* Automatically set if terminal size is detected and there is
* zero bottom margin. */
gboolean have_parking_row;
/* Whether to perturb the options based on a seed read from the first
* input file. This improves coverage when fuzzing. */
gboolean fuzz_options;
ChafaTermInfo *term_info;
gboolean output_utf_16_on_windows;
gboolean is_conhost_mode;
}
GlobalOptions;
typedef struct
{
gint width_cells, height_cells;
gint width_pixels, height_pixels;
}
TermSize;
static GlobalOptions options;
static TermSize detected_term_size;
static gboolean using_detected_size = FALSE;
static volatile sig_atomic_t interrupted_by_user = FALSE;
static PlacementCounter *placement_counter;
#ifdef HAVE_TERMIOS_H
static struct termios saved_termios;
#endif
#ifdef G_OS_WIN32
static UINT saved_console_output_cp;
static UINT saved_console_input_cp;
#endif
#ifdef HAVE_SIGACTION
static void
sigint_handler (G_GNUC_UNUSED int sig)
{
interrupted_by_user = TRUE;
}
#endif
static void
interruptible_usleep (gdouble us)
{
while (us > 0.0 && !interrupted_by_user)
{
gdouble sleep_us = MIN (us, 50000.0);
g_usleep (sleep_us);
us -= sleep_us;
}
}
static gboolean
write_to_stdout (gconstpointer buf, gsize len)
{
gboolean result = TRUE;
if (len == 0)
return TRUE;
#ifdef G_OS_WIN32
{
HANDLE chd = GetStdHandle (STD_OUTPUT_HANDLE);
gsize total_written = 0;
const void * const newline = "\r\n";
const gchar *p0, *p1, *end;
/* On MS Windows, we convert line feeds to DOS-style CRLF as we go. */
for (p0 = buf, end = p0 + len;
chd != INVALID_HANDLE_VALUE && total_written < len;
p0 = p1)
{
p1 = memchr (p0, '\n', end - p0);
if (!p1)
p1 = end;
if (!safe_WriteConsoleA (chd, p0, p1 - p0))
break;
total_written += p1 - p0;
if (p1 != end)
{
if (!safe_WriteConsoleA (chd, newline, 2))
break;
p1 += 1;
total_written += 1;
}
}
result = total_written == len ? TRUE : FALSE;
}
#else
{
gsize total_written;
for (total_written = 0; total_written < len; )
{
gsize n_written = fwrite (((const gchar *) buf) + total_written, 1,
len - total_written, stdout);
total_written += n_written;
if (total_written < len && n_written == 0 && errno != EINTR)
result = FALSE;
}
}
#endif
return result;
}
static guchar
get_hex_byte (const gchar *str)
{
gint b = 0;
if (*str >= '0' && *str <= '9')
b = *str - '0';
else if (*str >= 'a' && *str <= 'f')
b = *str - 'a' + 10;
else if (*str >= 'A' && *str <= 'F')
b = *str - 'A' + 10;
else
g_assert_not_reached ();
b <<= 4;
str++;
if (*str >= '0' && *str <= '9')
b |= *str - '0';
else if (*str >= 'a' && *str <= 'f')
b |= *str - 'a' + 10;
else if (*str >= 'A' && *str <= 'F')
b |= *str - 'A' + 10;
else
g_assert_not_reached ();
return b;
}
static gint
count_dash_strings (GList *l)
{
gint n = 0;
for ( ; l; l = g_list_next (l))
{
if (!strcmp (l->data, "-"))
n++;
}
return n;
}
static gboolean
parse_color (const gchar *str, guint32 *col_out, GError **error)
{
gint len;
gchar *label = NULL;
gchar *p0;
gboolean result = FALSE;
str += strspn (str, " \t");
len = strspn (str, "#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
if (len < 1)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Unrecognized color '%s'.", str);
goto out;
}
p0 = label = g_ascii_strdown (str, len);
/* Hex triplet, optionally prefixed with # or 0x */
if (*p0 == '#') p0++;
else if (p0 [0] == '0' && (p0 [1] == 'x')) p0 += 2;
len = strspn (p0, "0123456789abcdef");
if (len != (gint) strlen (p0) || len < 6)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Unrecognized color '%s'.", str);
goto out;
}
if (len > 6) p0 += (len - 6);
*col_out = (get_hex_byte (p0) << 16) + (get_hex_byte (p0 + 2) << 8) + get_hex_byte (p0 + 4);
result = TRUE;
out:
g_free (label);
return result;
}
static GList *
collect_variable_arguments (int *argc, char **argv [], gint first_arg)
{
GList *l = NULL;
gint i;
for (i = first_arg; i < *argc; i++)
l = g_list_prepend (l, g_strdup ((*argv) [i]));
return g_list_reverse (l);
}
static const gchar copyright_notice [] =
"Copyright (C) 2018-2023 Hans Petter Jansson et al.\n"
"Incl. libnsgif copyright (C) 2004 Richard Wilson, copyright (C) 2008 Sean Fox\n"
"Incl. LodePNG copyright (C) 2005-2018 Lode Vandevenne\n"
"Incl. QOI decoder copyright (C) 2021 Dominic Szablewski\n\n"
"This is free software; see the source for copying conditions. There is NO\n"
"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n";
static void
print_version (void)
{
gchar *builtin_features_str = chafa_describe_features (chafa_get_builtin_features ());
gchar *supported_features_str = chafa_describe_features (chafa_get_supported_features ());
gchar **loaders = get_loader_names ();
gchar *loaders_joined = g_strjoinv (" ", loaders);
g_print ("Chafa version %s\n\nLoaders: %s\nFeatures: %s\nApplying: %s\n\n%s\n",
CHAFA_VERSION,
loaders_joined,
chafa_get_builtin_features () ? builtin_features_str : "none",
chafa_get_supported_features () ? supported_features_str : "none",
copyright_notice);
g_free (builtin_features_str);
g_free (supported_features_str);
g_strfreev (loaders);
g_free (loaders_joined);
}
static void
print_brief_summary (void)
{
g_printerr ("%s: You must specify input files as arguments or pipe a file to stdin.\n"
"Try '%s --help' for more information.\n",
options.executable_name,
options.executable_name);
}
static void
print_summary (void)
{
const gchar *summary =
" Chafa (Character Art Facsimile) terminal graphics and character art generator.\n"
"\nGeneral options:\n"
" -h, --help Show help.\n"
" --version Show version.\n"
" -v, --verbose Be verbose.\n"
"\nOutput encoding:\n"
#ifdef G_OS_WIN32
" -f, --format=FORMAT Set output format; one of [conhost, iterm, kitty, sixels,\n"
#else
" -f, --format=FORMAT Set output format; one of [iterm, kitty, sixels,\n"
#endif
" symbols]. Iterm, kitty and sixels yield much higher\n"
" quality but enjoy limited support. Symbols mode yields\n"
" beautiful character art.\n"
" -O, --optimize=NUM Compress the output by using control sequences\n"
" intelligently [0-9]. 0 disables, 9 enables every\n"
" available optimization. Defaults to 5, except for when\n"
" used with \"-c none\", where it defaults to 0.\n"
" --relative=BOOL Use relative cursor positioning [on, off]. When on,\n"
" control sequences will be used to position images relative\n"
" to the cursor. When off, newlines will be used to separate\n"
" rows instead for e.g. 'less -R' interop. Defaults to off.\n"
" --passthrough=MODE Graphics protocol passthrough [auto, none, screen,\n"
" tmux]. Used to show pixel graphics through multiplexers.\n"
" --polite=BOOL Polite mode [on, off]. Inhibits escape sequences that may\n"
" confuse other programs. Defaults to off.\n"
"\nSize and layout:\n"
" --align=ALIGN Horizontal and vertical alignment (e.g. \"top,left\").\n"
" --clear Clear screen before processing each file.\n"
" --exact-size=MODE Try to match the input's size exactly [auto, on, off].\n"
" --fit-width Fit images to view's width, possibly exceeding its height.\n"
" --font-ratio=W/H Target font's width/height ratio. Can be specified as\n"
" a real number or a fraction. Defaults to 1/2.\n"
" --margin-bottom=NUM When terminal size is detected, reserve at least NUM\n"
" rows at the bottom as a safety margin. Can be used to\n"
" prevent images from scrolling out. Defaults to 1.\n"
" --margin-right=NUM When terminal size is detected, reserve at least NUM\n"
" columns safety margin on right-hand side. Defaults to 0.\n"
" --scale=NUM Scale image, respecting view's dimensions. 1.0 approximates\n"
" image's pixel dimensions. Specify \"max\" to fit view.\n"
" Defaults to 1.0 for pixel graphics and 4.0 for symbols.\n"
" -s, --size=WxH Set maximum image dimensions in columns and rows. By\n"
" default this will be equal to the view size.\n"
" --stretch Stretch image to fit output dimensions; ignore aspect.\n"
" Implies --scale max.\n"
" --view-size=WxH Set the view size in columns and rows. By default this\n"
" will be the size of your terminal, or 80x25 if size\n"
" detection fails. If one dimension is omitted, it will\n"
" be set to a reasonable approximation of infinity.\n"
"\nAnimation and timing:\n"
" --animate=BOOL Whether to allow animation [on, off]. Defaults to on.\n"
" When off, will show a still frame from each animation.\n"
" -d, --duration=SECONDS How long to show each file. If showing a single file,\n"
" defaults to zero for a still image and infinite for an\n"
" animation. For multiple files, defaults to zero. Animations\n"
" will always be played through at least once.\n"
" --speed=SPEED Animation speed. Either a unitless multiplier, or a real\n"
" number followed by \"fps\" to apply a specific framerate.\n"
" --watch Watch a single input file, redisplaying it whenever its\n"
" contents change. Will run until manually interrupted\n"
" or, if --duration is set, until it expires.\n"
"\nColors and processing:\n"
" --bg=COLOR Background color of display (color name or hex).\n"
" -c, --colors=MODE Set output color mode; one of [none, 2, 8, 16/8, 16, 240,\n"
" 256, full]. Defaults to best guess.\n"
" --color-extractor=EXTR Method for extracting color from an area\n"
" [average, median]. Average is the default.\n"
" --color-space=CS Color space used for quantization; one of [rgb, din99d].\n"
" Defaults to rgb, which is faster but less accurate.\n"
" --dither=DITHER Set output dither mode; one of [none, ordered,\n"
" diffusion]. No effect with 24-bit color. Defaults to none.\n"
" --dither-grain=WxH Set dimensions of dither grains in 1/8ths of a\n"
" character cell [1, 2, 4, 8]. Defaults to 4x4.\n"
" --dither-intensity=NUM Multiplier for dither intensity [0.0 - inf].\n"
" Defaults to 1.0.\n"
" --fg=COLOR Foreground color of display (color name or hex).\n"
" --invert Swaps --fg and --bg. Useful with light terminal background.\n"
" -p, --preprocess=BOOL Image preprocessing [on, off]. Defaults to on with 16\n"
" colors or lower, off otherwise.\n"
" -t, --threshold=NUM Lower threshold for full transparency [0.0 - 1.0].\n"
"\nResource allocation:\n"
" --threads=NUM Maximum number of CPU threads to use. If left unspecified\n"
" or negative, this will equal available CPU cores.\n"
" -w, --work=NUM How hard to work in terms of CPU and memory [1-9]. 1 is the\n"
" cheapest, 9 is the most accurate. Defaults to 5.\n"
"\nExtra options for symbol encoding:\n"
" --fg-only Leave the background color untouched. This produces\n"
" character-cell output using foreground colors only.\n"
" --fill=SYMS Specify character symbols to use for fill/gradients.\n"
" Defaults to none. See below for full usage.\n"
" --glyph-file=FILE Load glyph information from FILE, which can be any\n"
" font file supported by FreeType (TTF, PCF, etc).\n"
" --symbols=SYMS Specify character symbols to employ in final output.\n"
" See below for full usage and a list of symbol classes.\n"
"\nAccepted classes for --symbols and --fill:\n"
" all ascii braille extra imported narrow solid ugly\n"
" alnum bad diagonal geometric inverted none space vhalf\n"
" alpha block digit half latin quad stipple wedge\n"
" ambiguous border dot hhalf legacy sextant technical wide\n"
"\n These can be combined with + and -, e.g. block+border-diagonal or all-wide.\n"
"\nExamples:\n"
" $ chafa --scale max in.jpg # As big as will fit\n"
" $ chafa --clear --align mid,mid -d 5 *.gif # A well-paced slideshow\n"
" $ chafa -f symbols --symbols ascii -c none in.png # Old-school ASCII art\n\n"
"If your OS comes with manual pages, you can type 'man chafa' for more.\n";
g_print ("Usage:\n %s [OPTION...] [FILE...]\n\n%s",
options.executable_name,
summary);
}
/* ---------------------------------- *
* Option fuzzing with --fuzz-options *
* ---------------------------------- */
#define FUZZ_SEED_LEN 150
static gboolean
fuzz_seed_get_bool (gconstpointer seed, gint seed_len, gint *ofs)
{
const guchar *seed_u8 = seed;
return seed_u8 [(*ofs)++ % seed_len] < 128 ? TRUE : FALSE;
}
static Tristate
fuzz_seed_get_tristate (gconstpointer seed, gint seed_len, gint *ofs)
{
const guchar *seed_u8 = seed;
guint v = seed_u8 [(*ofs)++ % seed_len];
return (v < 256 / 3) ? TRISTATE_FALSE
: (v < (256 * 2) / 3) ? TRISTATE_TRUE
: TRISTATE_AUTO;
}
static guint32
fuzz_seed_get_u32 (gconstpointer seed, gint seed_len, gint *ofs)
{
const guchar *seed_u8 = seed;
guint32 u32 = 0;
gint i;
for (i = 0; i < 4; i++)
{
u32 |= seed_u8 [(*ofs)++ % seed_len];
u32 <<= 8;
}
return u32;
}
static guint32
fuzz_seed_get_uint (gconstpointer seed, gint seed_len, gint *ofs,
guint32 min, guint32 max)
{
guint32 u32;
u32 = fuzz_seed_get_u32 (seed, seed_len, ofs);
return min + (u32 % (max - min));
}
static gdouble
fuzz_seed_get_double (gconstpointer seed, gint seed_len, gint *ofs,
gdouble min, gdouble max)
{
guint32 u32;
u32 = fuzz_seed_get_u32 (seed, seed_len, ofs);
return min + (u32 % 65536) * ((max - min) / 65535.0);
}
static void
fuzz_options_with_seed (GlobalOptions *opt, gconstpointer seed, gint seed_len)
{
gint ofs = 0;
if (seed_len < 1)
return;
/* Fuzz as many options as possible, but avoid those needed to control
* the fuzzing process -- e.g. n_threads, duration, animation speed, watch. */
opt->mode = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, CHAFA_CANVAS_MODE_MAX);
opt->color_extractor = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, CHAFA_COLOR_EXTRACTOR_MAX);
opt->color_space = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, CHAFA_COLOR_SPACE_MAX);
opt->dither_mode = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, CHAFA_DITHER_MODE_MAX);
opt->pixel_mode = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, CHAFA_PIXEL_MODE_MAX);
opt->dither_grain_width = 1 << (fuzz_seed_get_uint (seed, seed_len, &ofs, 0, 4));
opt->dither_grain_height = 1 << (fuzz_seed_get_uint (seed, seed_len, &ofs, 0, 4));
opt->dither_intensity = fuzz_seed_get_double (seed, seed_len, &ofs, 0.0, 10.0);
opt->clear = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->verbose = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->invert = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->preprocess = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->polite = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->stretch = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->zoom = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->fg_only = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->animate = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->horiz_align = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, 3);
opt->vert_align = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, 3);
opt->relative = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->relative_set = TRUE;
opt->fit_to_width = fuzz_seed_get_bool (seed, seed_len, &ofs);
opt->view_width = fuzz_seed_get_uint (seed, seed_len, &ofs, 1, 32);
opt->view_height = fuzz_seed_get_uint (seed, seed_len, &ofs, 1, 32);
opt->width = fuzz_seed_get_uint (seed, seed_len, &ofs, 1, 32);
opt->height = fuzz_seed_get_uint (seed, seed_len, &ofs, 1, 32);
opt->cell_width = fuzz_seed_get_uint (seed, seed_len, &ofs, 1, 32);
opt->cell_height = fuzz_seed_get_uint (seed, seed_len, &ofs, 1, 32);
opt->margin_bottom = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, 16);
opt->margin_right = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, 16);
opt->scale = fuzz_seed_get_double (seed, seed_len, &ofs, 0.0, 10000.0);
opt->work_factor = fuzz_seed_get_uint (seed, seed_len, &ofs, 1, 10);
opt->optimization_level = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, 10);
opt->passthrough = fuzz_seed_get_uint (seed, seed_len, &ofs, 0, CHAFA_PASSTHROUGH_MAX);
opt->passthrough_set = TRUE;
opt->transparency_threshold = fuzz_seed_get_double (seed, seed_len, &ofs, 0.0, 1.0);
opt->transparency_threshold_set = TRUE;
opt->use_exact_size = fuzz_seed_get_tristate (seed, seed_len, &ofs);
}
static void
fuzz_options_with_file (GlobalOptions *opt, const gchar *filename)
{
FILE *fhd;
guchar seed [FUZZ_SEED_LEN];
gint seed_len;
fhd = fopen (filename, "rb");
if (!fhd)
return;
/* Read seed from the file's tail to avoid correlation with image
* format headers etc. */
fseek (fhd, -FUZZ_SEED_LEN, SEEK_END);
seed_len = fread (seed, sizeof (guchar), FUZZ_SEED_LEN, fhd);
fclose (fhd);
fuzz_options_with_seed (opt, seed, seed_len);
}
static gboolean
parse_boolean_token (const gchar *token, gboolean *value_out)
{
gboolean success = FALSE;
if (!g_ascii_strcasecmp (token, "on")
|| !g_ascii_strcasecmp (token, "yes")
|| !g_ascii_strcasecmp (token, "true"))
{
*value_out = TRUE;
}
else if (!g_ascii_strcasecmp (token, "off")
|| !g_ascii_strcasecmp (token, "no")
|| !g_ascii_strcasecmp (token, "false"))
{
*value_out = FALSE;
}
else
{
goto out;
}
success = TRUE;
out:
return success;
}
static gboolean
parse_tristate_token (const gchar *token, Tristate *value_out)
{
gboolean success = FALSE;
gboolean value_bool = FALSE;
if (!g_ascii_strcasecmp (token, "auto")
|| !g_ascii_strcasecmp (token, "default"))
{
*value_out = TRISTATE_AUTO;
}
else
{
success = parse_boolean_token (token, &value_bool);
if (!success)
goto out;
*value_out = value_bool ? TRISTATE_TRUE : TRISTATE_FALSE;
}
success = TRUE;
out:
return success;
}
static gboolean
parse_colors_arg (G_GNUC_UNUSED const gchar *option_name, const gchar *value, G_GNUC_UNUSED gpointer data, GError **error)
{
gboolean result = TRUE;
if (!g_ascii_strcasecmp (value, "none"))
options.mode = CHAFA_CANVAS_MODE_FGBG;
else if (!g_ascii_strcasecmp (value, "2"))
options.mode = CHAFA_CANVAS_MODE_FGBG_BGFG;
else if (!g_ascii_strcasecmp (value, "8"))
options.mode = CHAFA_CANVAS_MODE_INDEXED_8;
else if (!g_ascii_strcasecmp (value, "16-8")
|| !g_ascii_strcasecmp (value, "16/8"))
options.mode = CHAFA_CANVAS_MODE_INDEXED_16_8;
else if (!g_ascii_strcasecmp (value, "16"))
options.mode = CHAFA_CANVAS_MODE_INDEXED_16;
else if (!g_ascii_strcasecmp (value, "240"))
options.mode = CHAFA_CANVAS_MODE_INDEXED_240;
else if (!g_ascii_strcasecmp (value, "256"))
options.mode = CHAFA_CANVAS_MODE_INDEXED_256;
else if (!g_ascii_strcasecmp (value, "full")
|| !g_ascii_strcasecmp (value, "rgb")
|| !g_ascii_strcasecmp (value, "tc")
|| !g_ascii_strcasecmp (value, "direct")
|| !g_ascii_strcasecmp (value, "directcolor")
|| !g_ascii_strcasecmp (value, "truecolor"))
options.mode = CHAFA_CANVAS_MODE_TRUECOLOR;
else
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Colors must be one of [none, 2, 8, 16/8, 16, 240, 256, full].");
result = FALSE;
}
return result;
}
static gboolean
parse_color_extractor_arg (G_GNUC_UNUSED const gchar *option_name, const gchar *value, G_GNUC_UNUSED gpointer data, GError **error)
{
gboolean result = TRUE;
if (!g_ascii_strcasecmp (value, "average"))
options.color_extractor = CHAFA_COLOR_EXTRACTOR_AVERAGE;
else if (!g_ascii_strcasecmp (value, "median"))
options.color_extractor = CHAFA_COLOR_EXTRACTOR_MEDIAN;
else
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Color extractor must be one of [average, median].");
result = FALSE;
}
return result;
}
static gboolean
parse_color_space_arg (G_GNUC_UNUSED const gchar *option_name, const gchar *value, G_GNUC_UNUSED gpointer data, GError **error)
{
gboolean result = TRUE;
if (!g_ascii_strcasecmp (value, "rgb"))
options.color_space = CHAFA_COLOR_SPACE_RGB;
else if (!g_ascii_strcasecmp (value, "din99d"))
options.color_space = CHAFA_COLOR_SPACE_DIN99D;
else
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Color space must be one of [rgb, din99d].");
result = FALSE;
}
return result;
}
static gboolean
parse_dither_arg (G_GNUC_UNUSED const gchar *option_name, const gchar *value, G_GNUC_UNUSED gpointer data, GError **error)
{
gboolean result = TRUE;
if (!g_ascii_strcasecmp (value, "none"))
options.dither_mode = CHAFA_DITHER_MODE_NONE;
else if (!g_ascii_strcasecmp (value, "ordered")
|| !g_ascii_strcasecmp (value, "bayer"))
options.dither_mode = CHAFA_DITHER_MODE_ORDERED;
else if (!g_ascii_strcasecmp (value, "diffusion")
|| !g_ascii_strcasecmp (value, "fs"))
options.dither_mode = CHAFA_DITHER_MODE_DIFFUSION;
else
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Dither must be one of [none, ordered, diffusion].");
result = FALSE;
}
return result;
}
/* FIXME: Make it parse negative values too, and use sscanf() return values properly */
static gboolean
parse_fraction_or_real (const gchar *str, gdouble *real_out)
{
gboolean success = FALSE;
gdouble ratio = -1.0;
gint width = -1, height = -1;
gint o = 0;
sscanf (str, "%d/%d%n", &width, &height, &o);
if (width < 0 || height < 0)
sscanf (str, "%d:%d%n", &width, &height, &o);
if (width < 0 || height < 0)
sscanf (str, "%lf%n", &ratio, &o);
if (o != 0 && str [o] != '\0')
{
width = -1;
height = -1;
ratio = -1.0;
goto out;
}
if (width > 0 && height > 0)
ratio = width / (gdouble) height;
if (ratio < 0.0)
goto out;
*real_out = ratio;
success = TRUE;
out:
return success;
}
static gboolean
parse_align_arg (G_GNUC_UNUSED const gchar *option_name, const gchar *value, G_GNUC_UNUSED gpointer data, GError **error)
{
gboolean success = FALSE;
gchar **tokens = NULL;
ChafaAlign halign = CHAFA_ALIGN_MAX;
ChafaAlign valign = CHAFA_ALIGN_MAX;
gint i;
tokens = g_strsplit (value, ",", -1);
for (i = 0; tokens [i]; i++)
{
gchar *t = tokens [i];
if (i >= 2)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Too many alignment specifiers in \"%s\". Must be at most two.",
value);
goto out;
}
if (!strcasecmp (t, "left"))
halign = CHAFA_ALIGN_START;
else if (!strcasecmp (t, "right"))
halign = CHAFA_ALIGN_END;
else if (!strcasecmp (t, "hcenter") || !strcasecmp (t, "hmid"))
halign = CHAFA_ALIGN_CENTER;
else if (!strcasecmp (t, "top") || !strcasecmp (t, "up"))
valign = CHAFA_ALIGN_START;
else if (!strcasecmp (t, "bottom") || !strcasecmp (t, "down"))
valign = CHAFA_ALIGN_END;
else if (!strcasecmp (t, "vcenter") || !strcasecmp (t, "vmid"))
valign = CHAFA_ALIGN_CENTER;
else if (!strcasecmp (t, "center") || !strcasecmp (t, "mid"))
; /* Skip */
else
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Unknown alignment specifier \"%s\".", t);
goto out;
}
}
/* Process "center" in a second pass to allow both e.g. "center,left"
* and "left,center" */
for (i = 0; tokens [i]; i++)
{
gchar *t = tokens [i];
if (!strcasecmp (t, "center") || !strcasecmp (t, "mid"))
{
/* Allow "center,center" to center in both dimensions */
if (halign == CHAFA_ALIGN_MAX)
halign = CHAFA_ALIGN_CENTER;
else
valign = CHAFA_ALIGN_CENTER;
}
}
if (halign != CHAFA_ALIGN_MAX)
options.horiz_align = halign;
if (valign != CHAFA_ALIGN_MAX)
options.vert_align = valign;
success = TRUE;
out:
g_strfreev (tokens);
return success;
}
static gboolean
parse_font_ratio_arg (G_GNUC_UNUSED const gchar *option_name, const gchar *value, G_GNUC_UNUSED gpointer data, GError **error)
{
gdouble ratio = -1.0;
gboolean success = FALSE;
if (!parse_fraction_or_real (value, &ratio) || ratio <= 0.0)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Font ratio must be specified as a positive real number or fraction.");
goto out;
}
options.font_ratio = ratio;
success = TRUE;
out:
return success;
}
static gboolean
parse_scale_arg (G_GNUC_UNUSED const gchar *option_name, const gchar *value, G_GNUC_UNUSED gpointer data, GError **error)
{
gdouble scale = -1.0;
gboolean success = FALSE;
if (!strcasecmp (value, "max") || !strcasecmp (value, "fill"))
{
scale = SCALE_MAX;
}
else if (!parse_fraction_or_real (value, &scale) || scale <= 0.0)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Scale must be specified as a positive real number or fraction.");
goto out;
}
options.scale = scale;
success = TRUE;
out:
return success;
}
static gboolean
parse_duration_arg (G_GNUC_UNUSED const gchar *option_name, const gchar *value, G_GNUC_UNUSED gpointer data, GError **error)
{
gdouble duration = -1.0;
gboolean success = FALSE;
if (!strcasecmp (value, "max")
|| !strcasecmp (value, "inf")
|| !strcasecmp (value, "infinite"))
{
duration = G_MAXDOUBLE;
}
else if (!parse_fraction_or_real (value, &duration) || duration < 0.0)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
"Duration must be a positive real number or fraction, \"inf\" or \"infinite\".");
goto out;
}
options.file_duration_s = duration;
success = TRUE;
out:
return success;
}
static gboolean
parse_symbols_arg (G_GNUC_UNUSED const gchar *option_name, const gchar *value, G_GNUC_UNUSED gpointer data, GError **error)
{
options.symbols_specified = TRUE;
return chafa_symbol_map_apply_selectors (options.symbol_map, value, error);
}
static gboolean