caprs 0.1.1

Image-based click, slide, drag and rotate CAPTCHA generation and verification
Documentation
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
//! Generate ordered point-and-click puzzles using text labels or raster shapes.

use std::{collections::HashSet, ops::RangeInclusive, sync::Arc};

use image::imageops;
use image::{Pixel, Rgba, RgbaImage};
use rand::Rng;
use rand::seq::{IndexedRandom, SliceRandom};
use swash::scale::ScaleContext;
use swash::shape::{Direction, ShapeContext};
use swash::text::{BidiClass, Codepoint, Script};
use swash::zeno::{Mask, Origin, Placement, Vector};
use swash::{CacheKey, FontRef};
use thiserror::Error;

use crate::{CaptchaError, Challenge, Format, Image, Point, Rect, Size, render};

const DEFAULT_LABELS: [&str; 15] = [
    "我", "是", "行", "为", "式", "验", "证", "码", "的", "随", "机", "文", "本", "种", "子",
];
const MAX_SYMBOLS: u32 = 64;
const MAX_LABEL_CHARS: usize = 32;
const CELL_MARGIN: u32 = 2;

/// A parsed OpenType or TrueType outline font for click labels.
#[derive(Clone)]
pub struct Font {
    data: Arc<[u8]>,
    offset: u32,
    key: CacheKey,
}

impl std::fmt::Debug for Font {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Font").finish_non_exhaustive()
    }
}

impl Font {
    /// Parses the first face in an OpenType or TrueType font.
    ///
    /// # Errors
    ///
    /// Returns an error if the font bytes cannot be parsed.
    pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self, FontError> {
        let bytes = bytes.as_ref();
        let font = FontRef::from_index(bytes, 0).ok_or(FontError("invalid font header"))?;
        let metrics = font.metrics(&[]);
        if metrics.units_per_em < 16 || metrics.glyph_count == 0 {
            return Err(FontError("invalid font metrics"));
        }
        if !ScaleContext::new().builder(font).build().has_outlines() {
            return Err(FontError("no supported glyph outlines"));
        }
        Ok(Self {
            data: Arc::from(bytes),
            offset: font.offset,
            key: font.key,
        })
    }

    /// Loads the bundled SIL Open Font License Noto Sans CJK subset.
    ///
    /// It covers the default labels, printable ASCII, and a small set of extra CJK glyphs.
    ///
    /// # Errors
    ///
    /// Returns an error if the bundled font cannot be parsed.
    pub fn bundled() -> Result<Self, FontError> {
        Self::from_bytes(include_bytes!("fonts/caprs-sans.otf"))
    }

    fn font_ref(&self) -> FontRef<'_> {
        FontRef {
            data: &self.data,
            offset: self.offset,
            key: self.key,
        }
    }
}

/// A font could not be read from the supplied bytes.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("could not parse font: {0}")]
pub struct FontError(&'static str);

/// A named shape with RGBA pixels. Transparent pixels define the shape's outline.
#[derive(Clone, Debug)]
pub struct Shape {
    name: String,
    pixels: RgbaImage,
}

impl Shape {
    /// Creates a named shape from caller-provided pixels.
    #[must_use]
    pub fn new(name: impl Into<String>, pixels: RgbaImage) -> Self {
        Self {
            name: name.into(),
            pixels,
        }
    }

    /// Copies a rectangular sprite from a full image or sprite sheet.
    ///
    /// # Errors
    ///
    /// Returns an error if the region is empty or extends beyond the image.
    pub fn from_region(
        name: impl Into<String>,
        source: &RgbaImage,
        region: Rect,
    ) -> Result<Self, CaptchaError> {
        render::check_size(region.size, "shape region")?;
        let x = u32::try_from(region.origin.x).ok();
        let y = u32::try_from(region.origin.y).ok();
        let Some((x, y)) = x.zip(y).filter(|&(x, y)| {
            u64::from(x) + u64::from(region.size.width) <= u64::from(source.width())
                && u64::from(y) + u64::from(region.size.height) <= u64::from(source.height())
        }) else {
            return Err(CaptchaError::invalid(
                "shape region",
                "must fit inside the source image",
            ));
        };
        let pixels =
            imageops::crop_imm(source, x, y, region.size.width, region.size.height).to_image();
        Ok(Self::new(name, pixels))
    }
}

/// Labels and assets for one click CAPTCHA mode.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Symbols {
    /// Rasterize labels using any supplied font that covers the whole label.
    Text {
        /// Distinct Unicode labels to sample.
        labels: Vec<String>,
        /// Fonts from which the generator picks a compatible face for each label.
        fonts: Vec<Font>,
    },
    /// Draw named raster shapes.
    Shapes(Vec<Shape>),
}

impl Symbols {
    /// Provides the upstream default Chinese labels with the bundled font.
    ///
    /// # Errors
    ///
    /// Returns an error if the bundled font cannot be parsed.
    pub fn bundled_text() -> Result<Self, FontError> {
        Ok(Self::Text {
            labels: DEFAULT_LABELS.map(str::to_owned).to_vec(),
            fonts: vec![Font::bundled()?],
        })
    }
}

/// Images to sample when filling the main and hint canvases.
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct Backgrounds {
    /// Main backgrounds. An empty list uses a solid dark canvas.
    pub master: Vec<RgbaImage>,
    /// Hint backgrounds. An empty list uses a solid light canvas.
    pub thumbnail: Vec<RgbaImage>,
}

impl Backgrounds {
    /// Sets independent image lists for the main image and the hint.
    #[must_use]
    pub fn new(master: Vec<RgbaImage>, thumbnail: Vec<RgbaImage>) -> Self {
        Self { master, thumbnail }
    }
}

/// Which of the drawn symbols appear in the ordered prompt.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Prompt {
    /// Randomly select this many symbols, capped by the number drawn.
    Subset(RangeInclusive<u32>),
    /// Request every drawn symbol in a shuffled order.
    All,
}

/// How the main and hint images color their graphic shapes.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum ShapeColor {
    /// Use a sampled color over the shape's alpha channel.
    #[default]
    Tint,
    /// Preserve the original colors of each shape.
    Original,
}

/// Shadow drawn behind a symbol on the main image.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Shadow {
    /// Offset relative to the rendered symbol.
    pub offset: Point,
    /// Color of the shadow, including its opacity.
    pub color: Rgba<u8>,
}

impl Shadow {
    /// Sets a shadow color and offset.
    #[must_use]
    pub fn new(color: Rgba<u8>, offset: Point) -> Self {
        Self { offset, color }
    }
}

/// The scope and magnitude of the thumbnail's sinusoidal distortion.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum Distortion {
    /// Keep the image undistorted.
    #[default]
    None,
    /// Distort the background and noise before placing the hint symbols.
    Background {
        /// Maximum horizontal displacement in pixels.
        amplitude: u8,
    },
    /// Distort the background, noise, and hint symbols together.
    Whole {
        /// Maximum horizontal displacement in pixels.
        amplitude: u8,
    },
}

/// Noise drawn on the hint background.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Noise {
    /// Number of small background circles.
    pub circles: u16,
    /// Number of thin background lines.
    pub lines: u16,
    /// Foreground palette for the circles and lines.
    pub colors: Vec<Rgba<u8>>,
    /// Opacity multiplier applied to the noise.
    pub opacity: u8,
    /// Optional distortion for the hint.
    pub distortion: Distortion,
}

impl Default for Noise {
    fn default() -> Self {
        Self {
            circles: 24,
            lines: 2,
            colors: hint_colors(),
            opacity: 62,
            distortion: Distortion::Background { amplitude: 3 },
        }
    }
}

/// Layout, palette and visual options for click challenges.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Options {
    /// Pixel dimensions of the main image.
    pub image_size: Size,
    /// Pixel dimensions of the ordered hint.
    pub thumbnail_size: Size,
    /// Inclusive range of symbols to place on the main image.
    pub symbol_count: RangeInclusive<u32>,
    /// How many symbols the user is asked to find.
    pub prompt: Prompt,
    /// Inclusive range of nominal symbol sizes on the main image.
    pub symbol_size: RangeInclusive<u32>,
    /// Inclusive range of nominal symbol sizes on the hint.
    pub thumbnail_symbol_size: RangeInclusive<u32>,
    /// Inclusive clockwise rotation ranges. Empty means upright symbols.
    pub angles: Vec<RangeInclusive<i16>>,
    /// Palette for text or tinted shapes on the main image.
    pub colors: Vec<Rgba<u8>>,
    /// Palette for text or tinted shapes on the hint.
    pub thumbnail_colors: Vec<Rgba<u8>>,
    /// Optional shadow on the main image.
    pub shadow: Option<Shadow>,
    /// Opacity multiplier for the composed main image.
    pub image_opacity: u8,
    /// Whether shape pixels retain their original color.
    pub shape_color: ShapeColor,
    /// Noise and distortion on the hint.
    pub noise: Noise,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            image_size: Size::new(300, 220),
            thumbnail_size: Size::new(150, 40),
            symbol_count: 6..=7,
            prompt: Prompt::Subset(2..=4),
            symbol_size: 26..=32,
            thumbnail_symbol_size: 22..=28,
            angles: vec![20..=35, 35..=45, 45..=60, -70..=-55, -55..=-35, -35..=-30],
            colors: vec![
                Rgba([253, 233, 142, 255]),
                Rgba([96, 193, 255, 255]),
                Rgba([252, 176, 142, 255]),
                Rgba([251, 136, 255, 255]),
                Rgba([180, 254, 212, 255]),
                Rgba([203, 250, 169, 255]),
                Rgba([120, 214, 248, 255]),
            ],
            thumbnail_colors: hint_colors(),
            shadow: Some(Shadow::new(Rgba([16, 16, 16, 255]), Point::new(-1, -1))),
            image_opacity: 255,
            shape_color: ShapeColor::Tint,
            noise: Noise::default(),
        }
    }
}

impl Options {
    /// Uses smaller nominal symbols and gentler hint distortion for graphic click puzzles.
    #[must_use]
    pub fn for_shapes() -> Self {
        Self {
            symbol_size: 24..=30,
            thumbnail_symbol_size: 14..=20,
            noise: Noise {
                distortion: Distortion::Background { amplitude: 1 },
                ..Noise::default()
            },
            ..Self::default()
        }
    }
}

fn hint_colors() -> Vec<Rgba<u8>> {
    vec![
        Rgba([31, 85, 196, 255]),
        Rgba([120, 5, 146, 255]),
        Rgba([47, 107, 0, 255]),
        Rgba([145, 0, 0, 255]),
        Rgba([134, 68, 1, 255]),
        Rgba([103, 89, 1, 255]),
        Rgba([1, 110, 92, 255]),
    ]
}

/// One requested symbol and its hit rectangle on the main image.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Target {
    label: String,
    bounds: Rect,
}

impl Target {
    /// Returns the text label or shape name for this target.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Returns the target hit rectangle in original main-image coordinates.
    #[must_use]
    pub fn bounds(&self) -> Rect {
        self.bounds
    }
}

/// Ordered click targets to keep on the server.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Answer {
    image_size: Size,
    targets: Vec<Target>,
}

impl Answer {
    /// Returns the requested targets in the order in which they must be clicked.
    #[must_use]
    pub fn targets(&self) -> &[Target] {
        &self.targets
    }

    /// Verifies exactly one in-bounds click per target in the order shown in the hint.
    ///
    /// Padding follows the standalone validation function.
    #[must_use]
    pub fn verify(&self, points: &[Point], padding: u32) -> bool {
        !self.targets.is_empty()
            && points.len() == self.targets.len()
            && points.iter().zip(&self.targets).all(|(&point, target)| {
                point.x >= 0
                    && point.y >= 0
                    && (point.x as u32) < self.image_size.width
                    && (point.y as u32) < self.image_size.height
                    && validate(point, target.bounds, padding)
            })
    }
}

/// Checks the upstream inclusive hitbox, extending padding toward the right and bottom.
#[must_use]
pub fn validate(point: Point, target: Rect, padding: u32) -> bool {
    let x = i64::from(point.x) - i64::from(target.origin.x);
    let y = i64::from(point.y) - i64::from(target.origin.y);
    let extension = i64::from(padding) * 2;
    (0..=i64::from(target.size.width) + extension).contains(&x)
        && (0..=i64::from(target.size.height) + extension).contains(&y)
}

/// A reusable generator for text or graphic click CAPTCHAs.
#[derive(Debug)]
pub struct Captcha {
    options: Options,
    symbols: Symbols,
    backgrounds: Backgrounds,
}

impl Captcha {
    /// Validates the generator's options, labels, fonts, and shape assets.
    ///
    /// # Errors
    ///
    /// Returns an error if configuration or resources are invalid.
    pub fn new(options: Options, symbols: Symbols) -> Result<Self, CaptchaError> {
        validate_options(&options)?;
        validate_symbols(&symbols, *options.symbol_count.end() as usize)?;
        Ok(Self {
            options,
            symbols,
            backgrounds: Backgrounds::default(),
        })
    }

    /// Adds independent backgrounds for the main image and hint.
    ///
    /// # Errors
    ///
    /// Returns an error if a supplied image has an empty dimension.
    pub fn with_backgrounds(mut self, backgrounds: Backgrounds) -> Result<Self, CaptchaError> {
        for image in backgrounds.master.iter().chain(&backgrounds.thumbnail) {
            render::check_image(image, "click backgrounds")?;
        }
        self.backgrounds = backgrounds;
        Ok(self)
    }

    /// Returns the options used by this generator.
    #[must_use]
    pub fn options(&self) -> &Options {
        &self.options
    }

    /// Draws a JPEG main image and a PNG hint with newly sampled positions and order.
    ///
    /// # Errors
    ///
    /// Returns an error if randomness is unavailable or a font cannot render a selected label.
    pub fn generate(&self) -> Result<Challenge<Answer>, CaptchaError> {
        let mut rng = crate::rng()?;
        let options = &self.options;
        let count = rng.random_range(options.symbol_count.clone()) as usize;
        let symbols = self.choose_symbols(count, &mut rng);
        let draw = symbols
            .iter()
            .map(|symbol| self.draw_main_symbol(symbol, &mut rng))
            .collect::<Result<Vec<_>, _>>()?;
        let (mut master, targets) = self.draw_master(&symbols, draw, &mut rng);
        render::opacity(&mut master, options.image_opacity);

        // Sample the target sequence independently of the placement and drawing order.
        let mut order: Vec<_> = (0..count).collect();
        order.shuffle(&mut rng);
        if let Prompt::Subset(range) = &options.prompt {
            order.truncate(rng.random_range(range.clone()) as usize);
        }
        let hint = self.draw_hint(&symbols, &order, &mut rng)?;
        let targets = order
            .into_iter()
            .map(|index| targets[index].clone())
            .collect();
        Ok(Challenge::new(
            Image::new(master, Format::Jpeg),
            Image::new(hint, Format::Png),
            Answer {
                image_size: options.image_size,
                targets,
            },
        ))
    }

    fn choose_symbols(&self, count: usize, rng: &mut impl Rng) -> Vec<Symbol<'_>> {
        use rand::seq::IteratorRandom;

        match &self.symbols {
            Symbols::Text { labels, fonts } => labels
                .choose_multiple(rng, count)
                .map(|label| {
                    let font = fonts
                        .iter()
                        .filter(|font| covers(font, label))
                        .choose(rng)
                        .expect("each configured label has a compatible font");
                    Symbol::Text(label, font)
                })
                .collect(),
            Symbols::Shapes(shapes) => shapes
                .choose_multiple(rng, count)
                .map(Symbol::Shape)
                .collect(),
        }
    }

    fn draw_main_symbol(
        &self,
        symbol: &Symbol<'_>,
        rng: &mut impl Rng,
    ) -> Result<RgbaImage, CaptchaError> {
        let options = &self.options;
        let size = rng.random_range(options.symbol_size.clone());
        let color = options.colors[rng.random_range(0..options.colors.len())];
        let bitmap = symbol.render(size, color, options.shape_color)?;
        Ok(render::rotate_fit(
            bitmap,
            render::angle(&options.angles, rng),
        ))
    }

    fn draw_master(
        &self,
        symbols: &[Symbol<'_>],
        bitmaps: Vec<RgbaImage>,
        rng: &mut impl Rng,
    ) -> (RgbaImage, Vec<Target>) {
        let size = self.options.image_size;
        let mut master = background(&self.backgrounds.master, size, Rgba([59, 68, 86, 255]), rng);
        let (columns, rows) = grid(size, symbols.len() as u32);
        let cell_width = size.width / columns;
        let cell_height = size.height / rows;
        let mut cells: Vec<_> = (0..columns * rows).collect();
        cells.shuffle(rng);

        let targets = symbols
            .iter()
            .zip(bitmaps)
            .zip(cells)
            .map(|((symbol, bitmap), cell)| {
                let bitmap = render::scale_fit(
                    bitmap,
                    cell_width - 2 * CELL_MARGIN,
                    cell_height - 2 * CELL_MARGIN,
                );
                let x = (cell % columns) * cell_width
                    + rng.random_range(CELL_MARGIN..=cell_width - bitmap.width() - CELL_MARGIN);
                let y = (cell / columns) * cell_height
                    + rng.random_range(CELL_MARGIN..=cell_height - bitmap.height() - CELL_MARGIN);
                if let Some(shadow) = self.options.shadow {
                    let mut shadow_image = bitmap.clone();
                    render::tint(&mut shadow_image, shadow.color);
                    imageops::overlay(
                        &mut master,
                        &shadow_image,
                        i64::from(x) + i64::from(shadow.offset.x),
                        i64::from(y) + i64::from(shadow.offset.y),
                    );
                }
                imageops::overlay(&mut master, &bitmap, i64::from(x), i64::from(y));
                Target {
                    label: symbol.label().to_owned(),
                    bounds: Rect::new(
                        Point::new(x as i32, y as i32),
                        Size::new(bitmap.width(), bitmap.height()),
                    ),
                }
            })
            .collect();
        (master, targets)
    }

    fn draw_hint(
        &self,
        symbols: &[Symbol<'_>],
        order: &[usize],
        rng: &mut impl Rng,
    ) -> Result<RgbaImage, CaptchaError> {
        let options = &self.options;
        let size = options.thumbnail_size;
        let mut hint = background(
            &self.backgrounds.thumbnail,
            size,
            Rgba([249, 249, 249, 255]),
            rng,
        );
        add_noise(&mut hint, &options.noise, rng);
        let phase = rng.random_range(0.0..std::f64::consts::TAU);
        if let Distortion::Background { amplitude } = options.noise.distortion {
            hint = distort(&hint, amplitude, phase);
        }
        let cell_width = size.width / order.len() as u32;
        for (slot, &index) in order.iter().enumerate() {
            let scale = rng.random_range(options.thumbnail_symbol_size.clone());
            let color =
                options.thumbnail_colors[rng.random_range(0..options.thumbnail_colors.len())];
            let bitmap = symbols[index].render(scale, color, options.shape_color)?;
            let bitmap = render::scale_fit(
                bitmap,
                cell_width - 2 * CELL_MARGIN,
                size.height - 2 * CELL_MARGIN,
            );
            let x = slot as u32 * cell_width + (cell_width - bitmap.width()) / 2;
            let y = (size.height - bitmap.height()) / 2;
            imageops::overlay(&mut hint, &bitmap, i64::from(x), i64::from(y));
        }
        if let Distortion::Whole { amplitude } = options.noise.distortion {
            hint = distort(&hint, amplitude, phase);
        }
        Ok(hint)
    }
}

fn grid(size: Size, count: u32) -> (u32, u32) {
    // Prefer cells with room for rotated symbols in both directions.
    (1..=count)
        .map(|columns| (columns, count.div_ceil(columns)))
        .max_by_key(|&(columns, rows)| (size.width / columns).min(size.height / rows))
        .unwrap_or((1, 1))
}

fn validate_options(options: &Options) -> Result<(), CaptchaError> {
    render::check_size(options.image_size, "image_size")?;
    render::check_size(options.thumbnail_size, "thumbnail_size")?;
    render::check_range(&options.symbol_count, 1..=MAX_SYMBOLS, "symbol_count")?;
    render::check_range(&options.symbol_size, 1..=256, "symbol_size")?;
    render::check_range(
        &options.thumbnail_symbol_size,
        1..=256,
        "thumbnail_symbol_size",
    )?;
    render::check_angles(&options.angles, -360..=360)?;
    let count = *options.symbol_count.end();
    let max_prompt = match &options.prompt {
        Prompt::All => count,
        Prompt::Subset(range) => {
            render::check_range(range, 1..=MAX_SYMBOLS, "prompt")?;
            (*range.end()).min(count)
        }
    };
    let (columns, rows) = grid(options.image_size, count);
    let min_cell = 2 * CELL_MARGIN + 1;
    if options.image_size.width / columns < min_cell || options.image_size.height / rows < min_cell
    {
        return Err(CaptchaError::invalid(
            "image_size",
            "too small for the maximum symbol count",
        ));
    }
    if options.thumbnail_size.width / max_prompt < min_cell
        || options.thumbnail_size.height < min_cell
    {
        return Err(CaptchaError::invalid(
            "thumbnail_size",
            "too small for the longest prompt",
        ));
    }
    if options.colors.is_empty() || options.thumbnail_colors.is_empty() {
        return Err(CaptchaError::invalid(
            "click colors",
            "main and hint palettes must not be empty",
        ));
    }
    if options.noise.circles > 256 || options.noise.lines > 256 {
        return Err(CaptchaError::invalid(
            "noise",
            "at most 256 circles and 256 lines are allowed",
        ));
    }
    Ok(())
}

fn covers(font: &Font, label: &str) -> bool {
    let map = font.font_ref().charmap();
    label
        .chars()
        .all(|character| character == ' ' || map.map(character) != 0)
}

fn validate_symbols(symbols: &Symbols, minimum: usize) -> Result<(), CaptchaError> {
    let mut labels = HashSet::new();
    match symbols {
        Symbols::Text {
            labels: text,
            fonts,
        } => {
            for label in text {
                if label.is_empty()
                    || label.trim() != label
                    || label.chars().count() > MAX_LABEL_CHARS
                    || label.chars().any(char::is_control)
                    || !fonts.iter().any(|font| covers(font, label))
                {
                    return Err(CaptchaError::invalid(
                        "text labels",
                        "each label needs 1 to 32 printable characters covered by a font",
                    ));
                }
                labels.insert(label);
            }
            if labels.len() != text.len() {
                return Err(CaptchaError::invalid(
                    "text labels",
                    "labels must be unique",
                ));
            }
        }
        Symbols::Shapes(shapes) => {
            for shape in shapes {
                render::check_size(
                    Size::new(shape.pixels.width(), shape.pixels.height()),
                    "shape",
                )?;
                if shape.name.trim().is_empty() || !shape.pixels.pixels().any(|pixel| pixel[3] != 0)
                {
                    return Err(CaptchaError::invalid(
                        "shape",
                        "needs a name and visible pixels",
                    ));
                }
                labels.insert(&shape.name);
            }
            if labels.len() != shapes.len() {
                return Err(CaptchaError::invalid("shapes", "names must be unique"));
            }
        }
    }
    if labels.len() < minimum {
        return Err(CaptchaError::invalid(
            "symbols",
            "need at least as many distinct labels as the maximum symbol count",
        ));
    }
    Ok(())
}

enum Symbol<'a> {
    Text(&'a str, &'a Font),
    Shape(&'a Shape),
}

impl Symbol<'_> {
    fn label(&self) -> &str {
        match self {
            Self::Text(label, _) => label,
            Self::Shape(shape) => &shape.name,
        }
    }

    fn render(
        &self,
        size: u32,
        color: Rgba<u8>,
        style: ShapeColor,
    ) -> Result<RgbaImage, CaptchaError> {
        match self {
            Self::Text(label, font) => draw_text(label, font, size, color),
            Self::Shape(shape) => {
                let ratio =
                    f64::from(size) / f64::from(shape.pixels.width().max(shape.pixels.height()));
                let width = (f64::from(shape.pixels.width()) * ratio).round().max(1.0) as u32;
                let height = (f64::from(shape.pixels.height()) * ratio).round().max(1.0) as u32;
                let mut bitmap = render::scale(shape.pixels.clone(), width, height);
                if style == ShapeColor::Tint {
                    render::tint(&mut bitmap, color);
                }
                Ok(bitmap)
            }
        }
    }
}

fn draw_text(
    label: &str,
    font: &Font,
    size: u32,
    color: Rgba<u8>,
) -> Result<RgbaImage, CaptchaError> {
    let font = font.font_ref();
    let mut context = ShapeContext::new();
    let size = size as f32;
    // CAPTCHA labels are short, single-run strings. Choose the script and direction
    // from the first strong character so the shaper can place marks and ligatures.
    let script = label
        .chars()
        .map(Codepoint::script)
        .find(|script| !matches!(script, Script::Common | Script::Inherited | Script::Unknown))
        .unwrap_or(Script::Latin);
    let direction = label
        .chars()
        .map(Codepoint::bidi_class)
        .find_map(|class| match class {
            BidiClass::L => Some(Direction::LeftToRight),
            BidiClass::R | BidiClass::AL => Some(Direction::RightToLeft),
            _ => None,
        })
        .unwrap_or(Direction::LeftToRight);
    let mut shaper = context
        .builder(font)
        .script(script)
        .direction(direction)
        .size(size)
        .build();
    shaper.add_str(label);
    let mut glyphs = Vec::with_capacity(label.chars().count());
    let mut pen = 0.0;
    shaper.shape_with(|cluster| {
        for glyph in cluster.glyphs {
            glyphs.push((glyph.id, pen + glyph.x, glyph.y));
            pen += glyph.advance;
        }
    });

    let mut context = ScaleContext::new();
    let mut scaler = context.builder(font).size(size).build();
    let mut layers = Vec::with_capacity(glyphs.len());
    for (id, x, y) in glyphs {
        let Some(outline) = scaler.scale_outline(id) else {
            continue;
        };
        let bounds = outline.bounds();
        if bounds.is_empty() {
            continue;
        }

        // Validate font-provided dimensions before the rasterizer allocates the mask.
        let (_, placement) = Placement::compute(Origin::BottomLeft, Vector::ZERO, &bounds);
        render::check_size(
            Size::new(placement.width, placement.height),
            "glyph outline",
        )?;
        let (mask, placement) = Mask::new(outline.path())
            .origin(Origin::BottomLeft)
            .render();
        if placement.width != 0 && mask.iter().any(|&alpha| alpha != 0) {
            let left = i64::from(x.round() as i32) + i64::from(placement.left);
            let top = -i64::from(y.round() as i32) - i64::from(placement.top);
            layers.push((left, top, placement, mask));
        }
    }

    let Some(left) = layers.iter().map(|layer| layer.0).min() else {
        return Err(CaptchaError::EmptyGlyphs {
            label: label.to_owned(),
        });
    };
    let top = layers.iter().map(|layer| layer.1).min().unwrap_or(0);
    let right = layers
        .iter()
        .map(|(x, _, placement, _)| x + i64::from(placement.width))
        .max()
        .unwrap_or(left);
    let bottom = layers
        .iter()
        .map(|(_, y, placement, _)| y + i64::from(placement.height))
        .max()
        .unwrap_or(top);
    let width = u32::try_from(right - left).unwrap_or(u32::MAX);
    let height = u32::try_from(bottom - top).unwrap_or(u32::MAX);
    render::check_size(Size::new(width, height), "rasterized text size")?;

    let [r, g, b, opacity] = color.0;
    let mut image = RgbaImage::new(width, height);
    for (x, y, placement, mask) in layers {
        let offset_x = (x - left) as u32;
        let offset_y = (y - top) as u32;
        for (y, row) in mask.chunks_exact(placement.width as usize).enumerate() {
            for (x, &alpha) in row.iter().enumerate() {
                let pixel = image.get_pixel_mut(offset_x + x as u32, offset_y + y as u32);
                pixel.blend(&Rgba([r, g, b, render::multiply_alpha(alpha, opacity)]));
            }
        }
    }
    Ok(image)
}

fn background(
    images: &[RgbaImage],
    size: Size,
    fallback: Rgba<u8>,
    rng: &mut impl Rng,
) -> RgbaImage {
    match images.choose(rng) {
        Some(source) => render::crop_background(source, size, rng),
        None => RgbaImage::from_pixel(size.width, size.height, fallback),
    }
}

fn noise_color(noise: &Noise, rng: &mut impl Rng) -> Rgba<u8> {
    let mut pixel = noise.colors[rng.random_range(0..noise.colors.len())];
    pixel[3] = render::multiply_alpha(pixel[3], noise.opacity);
    pixel
}

fn add_noise(image: &mut RgbaImage, noise: &Noise, rng: &mut impl Rng) {
    if noise.colors.is_empty() || noise.opacity == 0 {
        return;
    }
    let width = image.width() as i32;
    let height = image.height() as i32;
    for _ in 0..noise.circles {
        let x = rng.random_range(0..width);
        let y = rng.random_range(0..height);
        let radius: i32 = rng.random_range(1..=3);
        let pixel = noise_color(noise, rng);
        for dy in -radius..=radius {
            for dx in -radius..=radius {
                if dx * dx + dy * dy <= radius * radius
                    && let Some(target) =
                        image.get_pixel_mut_checked((x + dx) as u32, (y + dy) as u32)
                {
                    target.blend(&pixel);
                }
            }
        }
    }
    for _ in 0..noise.lines {
        let start = rng.random_range(0..height);
        let end = rng.random_range(0..height);
        let pixel = noise_color(noise, rng);
        for x in 0..width {
            let y = start + (end - start) * x / width;
            image.get_pixel_mut(x as u32, y as u32).blend(&pixel);
        }
    }
}

fn distort(image: &RgbaImage, amplitude: u8, phase: f64) -> RgbaImage {
    let width = f64::from(image.width() - 1);
    let cycle = std::f64::consts::TAU / f64::from(image.height());
    RgbaImage::from_fn(image.width(), image.height(), |x, y| {
        let shift = (f64::from(y) * cycle + phase).sin() * f64::from(amplitude);
        render::sample(
            image,
            (f64::from(x) - shift).clamp(0.0, width),
            f64::from(y),
        )
    })
}