alpha2-layout 0.8.0

Text and layout boxes measures for alpha2
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
//! Text in a text style: its text host request, its identity, and where it lies on a picture.

use std::borrow::Cow;

use alpha2_media::EmojiPolicy;
use alpha2_model::{
    FontStyle, Paint, Rgba, Spread, TextAlign, TextContent, TextShadow, TextStroke, TextStyle,
};
use alpha2_text::{
    ShapedText, TextFill, TextGradient, TextGradientKind, TextGradientStop, TextRasterError,
    TextRasterRequest, TextRasterizer, TextSpread,
};
use alpha2_time::MediaTime;

use crate::{Baselines, CanvasRect, PictureSize};

/// The largest font, stroke extent, and padding the text host draws, in pixels.
pub const MAX_FONT_PIXELS: f32 = 2_048.0;
/// The most a text's strokes reach together, in pixels. See [`MAX_FONT_PIXELS`].
pub const MAX_STROKE_PIXELS: f32 = 64.0;
/// See [`MAX_FONT_PIXELS`].
pub const MAX_PADDING_PIXELS: f32 = 256.0;

/// Where a text lies, as fractions of the canvas from `(0, 0)` top-left to `(1, 1)`
/// bottom-right. For a text generator this is on its picture, before the clip's transform
/// and effects; for a caption it is on the canvas.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TextBounds {
    /// The box the style's anchor and position place: the wrapping width wide, every line's
    /// em box tall, plus whole pixels of outline and background padding.
    pub layout: CanvasRect,
    /// The span of the lines' advances, as tall as the layout and with the same decorations.
    /// It moves only with the advances, not with glyph ink.
    pub content: CanvasRect,
    /// What the text draws (glyphs, outline, background boxes), as
    /// [`alpha2_text::TextMeasure::ink`] bounds it, within the texture's sampling spread.
    /// `None` when the text draws nothing.
    pub ink: Option<CanvasRect>,
    /// Number of laid-out lines.
    pub line_count: u32,
    /// The first and last lines' alphabetic baselines.
    pub baselines: Baselines,
    /// The font size drawn after any `font_size_fit`, a fraction of the canvas's shorter side.
    pub font_size: f32,
    /// Whether the style's `line_clamp` discarded lines.
    pub truncated: bool,
    /// Whether the drawn text still splits a word or is taller than `max_height`.
    pub overflow: bool,
    /// The most the text's animators can widen its advances; its lines break at `max_width`
    /// over this ([`alpha2_eval::advance_headroom`]).
    pub advance_headroom: f32,
}

/// A text at a time since its holder started (a caption cue's start, a text generator's picture
/// time), which samples its runs' keyframed `font_scale`.
#[derive(Clone, Debug, PartialEq)]
pub struct TextAt<'a> {
    /// The text, a string or runs.
    pub content: Cow<'a, TextContent>,
    /// When.
    pub time: MediaTime,
}

impl<'a> TextAt<'a> {
    /// `content` at `time`.
    #[must_use]
    pub const fn new(content: &'a TextContent, time: MediaTime) -> Self {
        Self {
            content: Cow::Borrowed(content),
            time,
        }
    }

    /// Each run's `font_scale` at the time, 1 for a run without one.
    #[must_use]
    pub fn scales(&self) -> Vec<f32> {
        self.content
            .runs()
            .iter()
            .map(|run| {
                run.style
                    .as_ref()
                    .and_then(|style| style.font_scale.as_ref())
                    .map_or(1.0, |scale| {
                        alpha2_eval::sample_scalar(
                            scale,
                            self.time,
                            &alpha2_eval::SampleContext::NONE,
                        )
                        .clamp(
                            *alpha2_model::FONT_SCALE_RANGE.start(),
                            *alpha2_model::FONT_SCALE_RANGE.end(),
                        )
                    })
            })
            .collect()
    }
}

impl From<&str> for TextAt<'static> {
    fn from(text: &str) -> Self {
        Self {
            content: Cow::Owned(TextContent::from(text)),
            time: MediaTime::ZERO,
        }
    }
}

/// The text host spans of `text` in `style` at `font_size` pixels: one per run, each run's style
/// applied over `style` and its size `font_size` times its sampled `font_scale`; none when no run
/// has a style and `style` is upright and undecorated, so such a request is a plain one.
#[must_use]
pub fn text_spans(
    text: &TextAt<'_>,
    style: &TextStyle,
    font_size: f32,
) -> Vec<alpha2_text::TextSpan> {
    let content = &*text.content;
    let base_plain = style.font_style.is_normal() && !style.underline && !style.line_through;
    if base_plain && !content.has_run_styles() {
        return Vec::new();
    }
    let span = |bytes: std::ops::Range<usize>,
                run: Option<&alpha2_model::TextRunStyle>,
                scale: f32| {
        let merged = run.map_or_else(|| Cow::Borrowed(style), |run| Cow::Owned(run.apply(style)));
        let size = (font_size * scale).clamp(f32::MIN_POSITIVE, MAX_FONT_PIXELS);
        alpha2_text::TextSpan {
            bytes,
            font_family: merged.font_family.clone(),
            font_weight: merged.font_weight,
            font_style: match merged.font_style {
                FontStyle::Normal => alpha2_text::FontStyle::Normal,
                FontStyle::Italic => alpha2_text::FontStyle::Italic,
                FontStyle::Oblique => alpha2_text::FontStyle::Oblique,
            },
            font_size: size,
            letter_spacing: merged.letter_spacing * size,
            fill: text_fill(&merged.fill),
            strokes: stroke_pixels(&merged.strokes, size),
            background_color: run.and_then(|run| run.background_color).map(rgba8),
            underline: merged.underline,
            line_through: merged.line_through,
        }
    };
    if content.runs().is_empty() {
        return vec![span(0..content.len(), None, 1.0)];
    }
    let mut start = 0;
    content
        .runs()
        .iter()
        .zip(text.scales())
        .map(|(run, scale)| {
            let bytes = start..start + run.text.len();
            start = bytes.end;
            span(bytes, run.style.as_ref(), scale)
        })
        .collect()
}

/// A layout text's raster request, shadows and animators hashed as a text store key
/// (FNV-1a over a domain byte and every field). Never zero.
#[must_use]
pub fn layout_text_key(
    request: &TextRasterRequest,
    shadows: &[ShadowPixels],
    animators: &[alpha2_eval::SampledAnimator],
) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    let mut feed = |bytes: &[u8]| {
        for byte in bytes {
            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    // Layout texts take keys apart from captions' and text generators'.
    feed(&[0x4c]);
    feed_request(&mut feed, request);
    if !shadows.is_empty() {
        feed(&[0xfd]);
        feed_count(&mut feed, shadows.len());
        for shadow in shadows {
            for value in [shadow.offset[0], shadow.offset[1], shadow.sigma] {
                feed(&value.to_bits().to_le_bytes());
            }
            for value in shadow.color {
                feed(&value.to_bits().to_le_bytes());
            }
        }
    }
    if !animators.is_empty() {
        let mut stable = alpha2_geometry::StableHash::new();
        alpha2_eval::hash_sampled_animators(&mut stable, animators);
        feed(&[0xfa]);
        feed(&stable.finish().to_le_bytes());
    }
    hash.max(1)
}

/// What a request is shaped from, as a shaped-text cache key. Equal keys shape alike with
/// the same fonts.
#[must_use]
pub fn shaped_key(request: &TextRasterRequest) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    let mut feed = |bytes: &[u8]| {
        for byte in bytes {
            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    feed(request.text.as_bytes());
    feed(&[0xff]);
    feed(
        request
            .font_family
            .as_deref()
            .unwrap_or_default()
            .as_bytes(),
    );
    feed(&[0xff, u8::from(request.font_family.is_some())]);
    feed(&request.font_size.to_bits().to_le_bytes());
    feed(&request.line_height.to_bits().to_le_bytes());
    feed(&request.letter_spacing.to_bits().to_le_bytes());
    feed(&request.font_weight.to_le_bytes());
    hash
}

fn feed_request(feed: &mut impl FnMut(&[u8]), request: &TextRasterRequest) {
    // No `..`: a new field must decide whether it is part of the key.
    let TextRasterRequest {
        text,
        font_size,
        max_width,
        line_height,
        align,
        fill,
        emoji_policy,
        content_version: _,
        strokes,
        background,
        split_background,
        font_family,
        letter_spacing,
        font_weight,
        clamp,
        spans,
        advance_headroom,
        animator_grouping,
        animator_pivot,
        highlight,
    } = request;
    feed(text.as_bytes());
    feed(&[0xff]);
    feed(font_family.as_deref().unwrap_or_default().as_bytes());
    feed(&[0xff, u8::from(font_family.is_some())]);
    for value in [*font_size, *max_width, *line_height, *letter_spacing] {
        feed(&value.to_bits().to_le_bytes());
    }
    feed(&font_weight.to_le_bytes());
    match fill {
        TextFill::Solid(color) => feed(color),
        TextFill::Gradient(gradient) => feed_text_gradient(feed, gradient),
    }
    feed(&[match align {
        alpha2_media::TextAlign::Start => 0,
        alpha2_media::TextAlign::Center => 1,
        alpha2_media::TextAlign::End => 2,
    }]);
    feed_count(feed, strokes.len());
    for stroke in strokes {
        feed(&stroke.color);
        feed(&stroke.width.to_bits().to_le_bytes());
    }
    if *split_background {
        feed(&[0xfd]);
    }
    if let Some(background) = background {
        feed(&[0xfb]);
        feed(&background.color);
        feed_box_shape(feed, background);
    }
    // The default policy feeds nothing, so keys of requests that never set it stay as they were.
    match emoji_policy {
        alpha2_media::EmojiPolicy::Color => {}
        alpha2_media::EmojiPolicy::Monochrome => feed(&[0xf9, 1]),
        alpha2_media::EmojiPolicy::Replace => feed(&[0xf9, 2]),
    }
    if let Some(clamp) = clamp {
        feed(&[0xfc]);
        feed(&clamp.max_lines.unwrap_or(0).to_le_bytes());
        feed(&clamp.max_height.to_bits().to_le_bytes());
        feed(clamp.ellipsis.as_deref().unwrap_or_default().as_bytes());
        feed(&[0xff, u8::from(clamp.ellipsis.is_some())]);
    }
    feed_spans(feed, spans);
    if *advance_headroom > 1.0 {
        feed(&[0xf8]);
        feed(&advance_headroom.to_bits().to_le_bytes());
    }
    feed_motion(feed, *animator_grouping, *animator_pivot);
    if let Some(highlight) = highlight {
        feed(&[0xee]);
        feed(&highlight.look.color);
        feed_box_shape(feed, &highlight.look);
        feed_count(feed, highlight.steps.len());
        for (bytes, progress) in &highlight.steps {
            feed(&bytes.start.to_le_bytes());
            feed(&bytes.end.to_le_bytes());
            feed(&progress.to_bits().to_le_bytes());
        }
    }
}

/// Feeds a grouping and pivot other than the default's.
fn feed_motion(
    feed: &mut impl FnMut(&[u8]),
    grouping: alpha2_text::ClusterGrouping,
    pivot: [f32; 2],
) {
    if grouping != alpha2_text::ClusterGrouping::Character
        || pivot.map(f32::to_bits) != [0.5_f32.to_bits(); 2]
    {
        feed(&[0xf7]);
        feed(&[grouping as u8]);
        for value in pivot {
            feed(&value.to_bits().to_le_bytes());
        }
    }
}

/// The grouping of `grouping` in the text host's terms.
#[must_use]
pub const fn cluster_grouping(
    grouping: alpha2_model::AnimatorGrouping,
) -> alpha2_text::ClusterGrouping {
    match grouping {
        alpha2_model::AnimatorGrouping::Character => alpha2_text::ClusterGrouping::Character,
        alpha2_model::AnimatorGrouping::Word => alpha2_text::ClusterGrouping::Word,
        alpha2_model::AnimatorGrouping::Line => alpha2_text::ClusterGrouping::Line,
        alpha2_model::AnimatorGrouping::All => alpha2_text::ClusterGrouping::All,
    }
}

fn feed_spans(feed: &mut impl FnMut(&[u8]), spans: &[alpha2_text::TextSpan]) {
    if spans.is_empty() {
        return;
    }
    feed(&[0xf8]);
    feed(&spans.len().to_le_bytes());
    for span in spans {
        let alpha2_text::TextSpan {
            bytes,
            font_family,
            font_weight,
            font_style,
            font_size,
            letter_spacing,
            fill,
            strokes,
            background_color,
            underline,
            line_through,
        } = span;
        feed(&bytes.start.to_le_bytes());
        feed(&bytes.end.to_le_bytes());
        feed(font_family.as_deref().unwrap_or_default().as_bytes());
        feed(&[0xff, u8::from(font_family.is_some())]);
        feed(&font_weight.to_le_bytes());
        feed(&[*font_style as u8]);
        feed(&font_size.to_bits().to_le_bytes());
        feed(&letter_spacing.to_bits().to_le_bytes());
        match fill {
            TextFill::Solid(color) => feed(color),
            TextFill::Gradient(gradient) => feed_text_gradient(feed, gradient),
        }
        feed_count(feed, strokes.len());
        for stroke in strokes {
            feed(&stroke.color);
            feed(&stroke.width.to_bits().to_le_bytes());
        }
        match background_color {
            Some(color) => {
                feed(&[1]);
                feed(color);
            }
            None => feed(&[0]),
        }
        feed(&[u8::from(*underline), u8::from(*line_through)]);
    }
}

/// Feeds a box's padding (one side alone when all four are the same, as the single padding
/// keyed before), radius and border, the last two only when set.
fn feed_box_shape(feed: &mut impl FnMut(&[u8]), background: &alpha2_text::TextBackground) {
    let padding = background.padding;
    let [top, right, bottom, left] = padding.map(f32::to_bits);
    if top == right && top == bottom && top == left {
        feed(&padding[0].to_bits().to_le_bytes());
    } else {
        feed(&[0xf7]);
        for side in padding {
            feed(&side.to_bits().to_le_bytes());
        }
    }
    if background.radius != 0.0 {
        feed(&[0xf6]);
        feed(&background.radius.to_bits().to_le_bytes());
    }
    if let Some(border) = &background.border {
        feed(&[0xf5]);
        feed(&border.width.to_bits().to_le_bytes());
        feed(&border.color);
        if let Some(dash) = &border.dash {
            feed_count(feed, dash.pattern.len());
            for entry in &dash.pattern {
                feed(&entry.to_bits().to_le_bytes());
            }
            feed(&dash.offset.to_bits().to_le_bytes());
        }
    }
}

/// A list's length as one byte. A list of one feeds the same byte the single optional value
/// it replaced fed, which keeps existing keys stable.
#[allow(clippy::cast_possible_truncation)]
fn feed_count(feed: &mut impl FnMut(&[u8]), count: usize) {
    feed(&[count.min(255) as u8]);
}

fn feed_text_gradient(feed: &mut impl FnMut(&[u8]), gradient: &TextGradient) {
    // A tag no color's first byte can be mistaken for: a solid fill feeds four bytes only.
    feed(&[0xfe]);
    let points: &[f32] = match &gradient.kind {
        TextGradientKind::Linear { start, end } => &[0.0, start[0], start[1], end[0], end[1]],
        TextGradientKind::Radial { center, radius } => &[1.0, center[0], center[1], *radius],
        TextGradientKind::Conic { center, angle } => &[2.0, center[0], center[1], *angle],
    };
    for value in points {
        feed(&value.to_bits().to_le_bytes());
    }
    feed(&[gradient.spread as u8]);
    feed_count(feed, gradient.stops.len());
    for stop in &gradient.stops {
        feed(&stop.offset.to_bits().to_le_bytes());
        for value in stop.color {
            feed(&value.to_bits().to_le_bytes());
        }
    }
}

/// A paint's identity for a text key: a solid color as its bytes, a gradient by every field.
fn feed_paint(feed: &mut impl FnMut(&[u8]), paint: &Paint) {
    match paint {
        Paint::Solid { color } => feed(&rgba8(*color)),
        gradient => feed_text_gradient(feed, &text_gradient(gradient)),
    }
}

/// A text style's strokes and shadows for a text key. One stroke feeds what an outline fed,
/// and no shadows feed nothing.
fn feed_look(feed: &mut impl FnMut(&[u8]), strokes: &[TextStroke], shadows: &[TextShadow]) {
    feed_count(feed, strokes.len());
    for stroke in strokes {
        feed(&rgba8(stroke.color));
        feed(&stroke.width.to_bits().to_le_bytes());
    }
    if !shadows.is_empty() {
        feed(&[0xfd]);
        feed_count(feed, shadows.len());
        for shadow in shadows {
            feed(&rgba8(shadow.color));
            for value in [shadow.offset.x, shadow.offset.y, shadow.blur] {
                feed(&value.to_bits().to_le_bytes());
            }
        }
    }
}

/// A text's identity at a render size: the text, its runs' styles and sampled scales, its style
/// and the size, hashed with FNV-1a. A text without run styles keys as its plain string. Never
/// zero.
#[must_use]
pub fn text_key(text: &TextAt<'_>, style: &TextStyle, size: PictureSize) -> u64 {
    // No `..`: a new field must decide whether it is part of the key.
    let TextStyle {
        font_family,
        font_size,
        fill,
        line_height,
        letter_spacing,
        font_weight,
        font_style,
        underline,
        line_through,
        align,
        max_width,
        max_height,
        font_size_fit,
        line_clamp,
        position,
        anchor,
        strokes,
        shadows,
        background,
        highlight,
        // `animated_text_key` adds the sampled animators.
        animators: _,
        animator_grouping,
        animator_pivot,
    } = style;
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    let mut feed = |bytes: &[u8]| {
        for byte in bytes {
            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    feed(text.content.text().as_bytes());
    feed(&[0xff]);
    // Family names cannot hold 0xff (they are UTF-8), so the text and family stay apart.
    feed(font_family.as_deref().unwrap_or_default().as_bytes());
    feed(&[0xff, u8::from(font_family.is_some())]);
    for value in [
        *font_size,
        *line_height,
        *letter_spacing,
        *max_width,
        position.x,
        position.y,
        anchor.x,
        anchor.y,
    ] {
        feed(&value.to_bits().to_le_bytes());
    }
    feed(&font_weight.to_le_bytes());
    feed_paint(&mut feed, fill);
    feed(&[match align {
        TextAlign::Start => 0,
        TextAlign::Center => 1,
        TextAlign::End => 2,
    }]);
    feed_look(&mut feed, strokes, shadows);
    match background {
        Some(background) => {
            let unit = text_background(background, 1.0);
            feed(&[1]);
            feed(&unit.color);
            feed_box_shape(&mut feed, &unit);
        }
        None => feed(&[0]),
    }
    // Only fields that are set are fed.
    feed_fit(&mut feed, *max_height, *font_size_fit, line_clamp.as_ref());
    if !font_style.is_normal() {
        feed(&[0xf3, *font_style as u8]);
    }
    if *underline || *line_through {
        feed(&[0xf4, u8::from(*underline), u8::from(*line_through)]);
    }
    if text.content.has_run_styles() {
        feed_spans(&mut feed, &text_spans(text, style, 1.0));
    }
    if let Some(highlight) = highlight {
        feed_highlight(&mut feed, highlight);
    }
    let headroom = advance_headroom(text, style);
    if headroom > 1.0 {
        feed(&[0xf8]);
        feed(&headroom.to_bits().to_le_bytes());
    }
    feed_motion(
        &mut feed,
        cluster_grouping(*animator_grouping),
        [animator_pivot.x, animator_pivot.y],
    );
    feed(&size.width().to_le_bytes());
    feed(&size.height().to_le_bytes());
    hash.max(1)
}

/// Where `text` in `style` lies on a canvas of `size`, laid out with `rasterizer`'s fonts and
/// placed exactly as a frame places it, without drawing it.
///
/// Measured at the frame's render size it agrees with that frame to the pixel; at another
/// size lines can break elsewhere.
///
/// # Errors
/// Returns the text host's refusal: no fonts, or a style out of range.
pub fn measure_text(
    rasterizer: &TextRasterizer,
    text: &TextAt<'_>,
    style: &TextStyle,
    size: PictureSize,
) -> Result<TextBounds, TextRasterError> {
    let placed = place(rasterizer, text, style, size)?;
    let shaped = rasterizer.shape(&placed.request)?;
    let boxed = style_lines(&shaped, style, size, &placed.request);
    let measure = &placed.measure;
    let height = placed.canvas[1];
    Ok(TextBounds {
        layout: placed.layout,
        content: placed.rect(measure.content),
        ink: measure.ink.map(|ink| placed.rect(ink)),
        line_count: measure.line_count,
        baselines: Baselines {
            first: (placed.origin[1] + measure.first_baseline) / height,
            last: (placed.origin[1] + measure.last_baseline) / height,
        },
        font_size: placed.font_size,
        truncated: measure.truncated,
        overflow: boxed.overflow,
        advance_headroom: placed.request.advance_headroom,
    })
}

/// A text's request at its fitted size, its measure, and where its layout box lies.
pub(crate) struct Placed {
    pub(crate) request: TextRasterRequest,
    pub(crate) measure: alpha2_text::TextMeasure,
    /// The layout box's top-left corner on the canvas, in pixels.
    pub(crate) origin: [f32; 2],
    pub(crate) canvas: [f32; 2],
    pub(crate) layout: CanvasRect,
    pub(crate) font_size: f32,
}

impl Placed {
    /// A rectangle of the layout box, in pixels, on the canvas in fractions.
    pub(crate) fn rect(&self, [left, top, right, bottom]: [f32; 4]) -> CanvasRect {
        CanvasRect {
            left: (self.origin[0] + left) / self.canvas[0],
            top: (self.origin[1] + top) / self.canvas[1],
            right: (self.origin[0] + right) / self.canvas[0],
            bottom: (self.origin[1] + bottom) / self.canvas[1],
        }
    }
}

#[expect(
    clippy::cast_precision_loss,
    reason = "picture sides are far below 2^24"
)]
pub(crate) fn place(
    rasterizer: &TextRasterizer,
    text: &TextAt<'_>,
    style: &TextStyle,
    size: PictureSize,
) -> Result<Placed, TextRasterError> {
    let fitted = fit_text(text, style, size, |request| {
        rasterizer.shape(request).map(std::sync::Arc::new)
    })?;
    let request = text_request_at(
        text,
        style,
        size,
        text_key(text, style, size),
        fitted.font_pixels,
    );
    let measure = rasterizer.measure(&request)?;
    let (width, height) = (size.width() as f32, size.height() as f32);
    let [margin_x, margin_y] = measure.decoration_margin.map(|margin| margin as f32);
    let (box_width, box_height) = (measure.box_width as f32, measure.box_height as f32);
    // The layout box's top-left corner on the canvas. The anchor of the decorated box lies at the
    // position, as `text_placement` places the texture.
    let origin = [
        style.position.x * width - style.anchor.x * (box_width + 2.0 * margin_x) + margin_x,
        style.position.y * height - style.anchor.y * (box_height + 2.0 * margin_y) + margin_y,
    ];
    let mut placed = Placed {
        request,
        measure,
        origin,
        canvas: [width, height],
        layout: CanvasRect {
            left: 0.0,
            top: 0.0,
            right: 0.0,
            bottom: 0.0,
        },
        font_size: fitted.font_size,
    };
    placed.layout = placed.rect([
        -margin_x,
        -margin_y,
        box_width + margin_x,
        box_height + margin_y,
    ]);
    Ok(placed)
}

/// The height in pixels of `style`'s box on a picture of `size`, zero for none.
#[allow(clippy::cast_precision_loss)]
fn box_height(style: &TextStyle, size: PictureSize) -> f32 {
    style
        .max_height
        .map_or(0.0, |height| height * size.height() as f32)
}

/// How `shaped`, shaped for `request`, lies in `style`'s box.
fn style_lines(
    shaped: &ShapedText,
    style: &TextStyle,
    size: PictureSize,
    request: &TextRasterRequest,
) -> crate::fit::BoxedLines {
    crate::fit::boxed_lines(
        shaped,
        request.wrap_width(),
        box_height(style, size),
        style.line_clamp.as_ref().and_then(|clamp| clamp.max_lines),
        style.line_clamp.is_some(),
    )
}

/// The font size `text` in `style` draws at on a picture of `size`: the largest its
/// `font_size_fit` allows at which the text fits its box, with lines from `shape`.
///
/// The box is the wrapping width by `max_height`, and `line_clamp.max_lines` also bounds it.
/// Without a fit it is the style's own size and `shape` is not called.
///
/// # Errors
/// Returns the first refusal of `shape`.
pub fn fit_text<S: std::ops::Deref<Target = ShapedText>>(
    text: &TextAt<'_>,
    style: &TextStyle,
    size: PictureSize,
    mut shape: impl FnMut(&TextRasterRequest) -> Result<S, TextRasterError>,
) -> Result<crate::FittedSize, TextRasterError> {
    crate::fit::fit_font_size(
        style.font_size,
        style.font_size_fit,
        size.unit(),
        |pixels| {
            let request = text_request_at(text, style, size, 1, pixels);
            let shaped = shape(&request)?;
            Ok(style_lines(&shaped, style, size, &request).fits)
        },
    )
}

/// A straight, sRGB-encoded color as bytes.
#[must_use]
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
pub fn rgba8(color: Rgba) -> [u8; 4] {
    [color.red, color.green, color.blue, color.alpha]
        .map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8)
}

/// The text host request for `text` in `style` on a picture of `size`, with content version
/// `key`. Sizes are scaled from canvas fractions to pixels and clamped to what the host draws.
#[must_use]
pub fn text_request(
    text: &TextAt<'_>,
    style: &TextStyle,
    size: PictureSize,
    key: u64,
) -> TextRasterRequest {
    text_request_at(text, style, size, key, font_pixels(style, size))
}

/// [`text_request`] at a font size of `font_size` pixels, such as [`fit_text`] finds.
#[must_use]
#[allow(clippy::cast_precision_loss)]
pub fn text_request_at(
    text: &TextAt<'_>,
    style: &TextStyle,
    size: PictureSize,
    key: u64,
    font_size: f32,
) -> TextRasterRequest {
    let spans = text_spans(text, style, font_size);
    TextRasterRequest {
        text: text.content.text().into_owned(),
        font_size,
        max_width: (style.max_width * size.width() as f32).max(1.0),
        line_height: style.line_height,
        align: match style.align {
            TextAlign::Start => alpha2_media::TextAlign::Start,
            TextAlign::Center => alpha2_media::TextAlign::Center,
            TextAlign::End => alpha2_media::TextAlign::End,
        },
        fill: text_fill(&style.fill),
        emoji_policy: EmojiPolicy::Color,
        content_version: key,
        strokes: stroke_pixels(&style.strokes, font_size),
        split_background: !style.shadows.is_empty()
            && (style.background.is_some()
                || style.highlight.is_some()
                || spans.iter().any(|span| span.background_color.is_some())),
        background: style
            .background
            .as_ref()
            .map(|background| text_background(background, font_size)),
        font_family: style.font_family.clone(),
        letter_spacing: style.letter_spacing * font_size,
        font_weight: style.font_weight,
        clamp: style
            .line_clamp
            .as_ref()
            .map(|clamp| crate::fit::text_clamp(clamp, box_height(style, size))),
        spans,
        advance_headroom: advance_headroom(text, style),
        animator_grouping: cluster_grouping(style.animator_grouping),
        animator_pivot: [style.animator_pivot.x, style.animator_pivot.y],
        highlight: style.highlight.as_ref().and_then(|highlight| {
            let steps =
                crate::text_animation::highlight_steps(text.content.runs(), text.time, highlight);
            (!steps.is_empty()).then(|| alpha2_text::TextHighlightRequest {
                look: highlight_look(highlight, font_size),
                steps,
            })
        }),
    }
}

/// Feeds a style's box height, fit and clamp, each only when set.
fn feed_fit(
    feed: &mut impl FnMut(&[u8]),
    max_height: Option<f32>,
    font_size_fit: Option<alpha2_model::FontSizeFit>,
    line_clamp: Option<&alpha2_model::LineClamp>,
) {
    if let Some(height) = max_height {
        feed(&[0xf0]);
        feed(&height.to_bits().to_le_bytes());
    }
    if let Some(fit) = font_size_fit {
        feed(&[0xf1]);
        feed(&fit.min.to_bits().to_le_bytes());
        feed(&fit.max.unwrap_or(-1.0).to_bits().to_le_bytes());
    }
    if let Some(clamp) = line_clamp {
        feed(&[0xf2]);
        feed(&clamp.max_lines.unwrap_or(0).to_le_bytes());
        feed(clamp.block_ellipsis.text().unwrap_or_default().as_bytes());
        feed(&[0xff, u8::from(clamp.block_ellipsis.text().is_some())]);
    }
}

/// Feeds `highlight`'s look at a one-pixel font and its timing.
fn feed_highlight(feed: &mut impl FnMut(&[u8]), highlight: &alpha2_model::TextHighlight) {
    let unit = highlight_look(highlight, 1.0);
    feed(&[0xee]);
    feed(&unit.color);
    feed_box_shape(feed, &unit);
    feed(&highlight.transition.ticks().to_le_bytes());
    match highlight.easing {
        alpha2_model::Easing::Linear => feed(&[0]),
        alpha2_model::Easing::CubicBezier(curve) => {
            feed(&[1]);
            for value in [curve.x1, curve.y1, curve.x2, curve.y2] {
                feed(&value.to_bits().to_le_bytes());
            }
        }
    }
    feed(&[highlight.gap as u8]);
}

/// `highlight`'s box look in pixels of a `font_size`-pixel font, as [`text_background`] sizes a
/// background.
#[must_use]
pub fn highlight_look(
    highlight: &alpha2_model::TextHighlight,
    font_size: f32,
) -> alpha2_text::TextBackground {
    text_background(
        &alpha2_model::TextBackground {
            color: highlight.color,
            padding: highlight.padding,
            radius: highlight.radius,
            border: highlight.border.clone(),
            extent: alpha2_model::TextBoxExtent::Line,
        },
        font_size,
    )
}

/// The most `style`'s animators can widen an advance of `text` ([`alpha2_eval::advance_headroom`]).
#[must_use]
pub fn advance_headroom(text: &TextAt<'_>, style: &TextStyle) -> f32 {
    if style.animators.is_empty() {
        1.0
    } else {
        alpha2_eval::advance_headroom(&style.animators, text.content.runs())
    }
}

/// `background` in pixels of a `font_size`-pixel font, padding clamped to what the host draws.
#[must_use]
pub fn text_background(
    background: &alpha2_model::TextBackground,
    font_size: f32,
) -> alpha2_text::TextBackground {
    alpha2_text::TextBackground {
        color: rgba8(background.color),
        padding: background
            .padding
            .sides()
            .map(|side| (side * font_size).clamp(0.0, MAX_PADDING_PIXELS)),
        radius: background.radius * font_size,
        border: background
            .border
            .as_ref()
            .map(|border| alpha2_text::TextBoxBorder {
                width: border.width * font_size,
                color: rgba8(border.color),
                dash: border.dash.as_ref().map(|dash| alpha2_text::TextBoxDash {
                    pattern: dash.pattern.iter().map(|entry| entry * font_size).collect(),
                    offset: dash.offset * font_size,
                }),
            }),
        extent: match background.extent {
            alpha2_model::TextBoxExtent::Line => alpha2_text::BoxExtent::Line,
            alpha2_model::TextBoxExtent::Revealed => alpha2_text::BoxExtent::Revealed,
            alpha2_model::TextBoxExtent::Block => alpha2_text::BoxExtent::Block,
        },
    }
}

/// A paint as the text host's fill: a color as bytes, or a gradient over the layout box with
/// the same stops and the conic angle in radians.
#[must_use]
pub fn text_fill(paint: &Paint) -> TextFill {
    match paint {
        Paint::Solid { color } => TextFill::Solid(rgba8(*color)),
        gradient => TextFill::Gradient(text_gradient(gradient)),
    }
}

fn text_gradient(paint: &Paint) -> TextGradient {
    let pair = |value: alpha2_model::Vec2| [value.x, value.y];
    let stops = |stops: &[alpha2_model::GradientStop]| {
        stops
            .iter()
            .map(|stop| TextGradientStop {
                offset: stop.offset,
                color: [
                    stop.color.red,
                    stop.color.green,
                    stop.color.blue,
                    stop.color.alpha,
                ],
            })
            .collect()
    };
    let spread = |spread: Spread| match spread {
        Spread::Pad => TextSpread::Pad,
        Spread::Repeat => TextSpread::Repeat,
        Spread::Reflect => TextSpread::Reflect,
    };
    match paint {
        // A solid paint is a gradient of one color, for a caller that needs the gradient form.
        Paint::Solid { color } => TextGradient {
            kind: TextGradientKind::Linear {
                start: [0.0, 0.0],
                end: [1.0, 0.0],
            },
            stops: stops(&[
                alpha2_model::GradientStop {
                    offset: 0.0,
                    color: *color,
                },
                alpha2_model::GradientStop {
                    offset: 1.0,
                    color: *color,
                },
            ]),
            spread: TextSpread::Pad,
        },
        Paint::LinearGradient {
            start,
            end,
            stops: list,
            spread: mode,
        } => TextGradient {
            kind: TextGradientKind::Linear {
                start: pair(*start),
                end: pair(*end),
            },
            stops: stops(list),
            spread: spread(*mode),
        },
        Paint::RadialGradient {
            center,
            radius,
            stops: list,
            spread: mode,
        } => TextGradient {
            kind: TextGradientKind::Radial {
                center: pair(*center),
                radius: *radius,
            },
            stops: stops(list),
            spread: spread(*mode),
        },
        Paint::ConicGradient {
            center,
            angle_degrees,
            stops: list,
        } => TextGradient {
            kind: TextGradientKind::Conic {
                center: pair(*center),
                angle: angle_degrees.to_radians(),
            },
            stops: stops(list),
            spread: TextSpread::Pad,
        },
    }
}

/// `strokes` in pixels of a `font_size`-pixel font (widths are fractions of the font size).
/// Each is at least the smallest positive width, and the last is shortened so together they
/// reach at most [`MAX_STROKE_PIXELS`].
#[must_use]
pub fn stroke_pixels(strokes: &[TextStroke], font_size: f32) -> Vec<alpha2_text::TextStroke> {
    let mut reach = 0.0_f32;
    let mut pixels = Vec::with_capacity(strokes.len());
    for stroke in strokes {
        let room = MAX_STROKE_PIXELS - reach;
        if room <= 0.0 {
            break;
        }
        let width = (stroke.width * font_size).clamp(f32::MIN_POSITIVE, room);
        reach += width;
        pixels.push(alpha2_text::TextStroke {
            color: rgba8(stroke.color),
            width,
        });
    }
    pixels
}

/// What the engine draws for one text: the raster, and the shadows composited under its
/// glyphs.
#[derive(Clone, Debug, PartialEq)]
pub struct TextDraw {
    /// The raster request.
    pub request: TextRasterRequest,
    /// The shadows, first on top.
    pub shadows: Vec<ShadowPixels>,
    /// The text's animators at its time, for a text that has them.
    pub animation: Option<TextAnimation>,
}

/// A text's animators sampled at one time, with what they select from.
#[derive(Clone, Debug, PartialEq)]
pub struct TextAnimation {
    /// The animators, in order.
    pub animators: Vec<alpha2_eval::SampledAnimator>,
    /// The text's runs, none for a plain string.
    pub runs: Vec<alpha2_model::TextRun>,
    /// The time Timing selectors compare run times with.
    pub time: alpha2_time::MediaTime,
}

impl TextDraw {
    /// Each cluster's state and the states' hash
    /// ([`crate::text_animation::cluster_states`]), `None` without animators.
    ///
    /// # Errors
    /// Returns the text host's refusal to lay the text out.
    pub fn states(
        &self,
        rasterizer: &TextRasterizer,
    ) -> Result<Option<(Vec<alpha2_text::ClusterState>, u64)>, TextRasterError> {
        let Some(animation) = &self.animation else {
            return Ok(None);
        };
        let layout = rasterizer.layout(&self.request)?;
        Ok(Some(crate::text_animation::cluster_states(
            &layout,
            &animation.runs,
            &animation.animators,
            animation.time,
            self.request.font_size,
        )))
    }
}

/// [`text_key`] for `content` in `style` shown `time` after its holder started. Without
/// animators this is the static key; otherwise the runs and time are mixed in, so each moment
/// of an animation is a distinct text. Never zero.
#[must_use]
pub fn animated_text_key(
    content: &alpha2_model::TextContent,
    style: &TextStyle,
    size: PictureSize,
    time: alpha2_time::MediaTime,
) -> u64 {
    let key = text_key(&TextAt::new(content, time), style, size);
    if style.animators.is_empty() && style.highlight.is_none() {
        return key;
    }
    let mut hash = key;
    let mut feed = |bytes: &[u8]| {
        for byte in bytes {
            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    if let Some(highlight) = &style.highlight {
        let steps = crate::text_animation::highlight_steps(content.runs(), time, highlight);
        feed(&[0xee]);
        feed_count(&mut feed, steps.len());
        for (bytes, progress) in &steps {
            feed(&bytes.start.to_le_bytes());
            feed(&progress.to_bits().to_le_bytes());
        }
    }
    if style.animators.is_empty() {
        return hash.max(1);
    }
    feed(&[0xfa]);
    let mut stable = alpha2_geometry::StableHash::new();
    alpha2_eval::hash_sampled_animators(
        &mut stable,
        &alpha2_eval::sample_text_animators(&style.animators, time),
    );
    feed(&stable.finish().to_le_bytes());
    for run in content.runs() {
        feed(&run.text.len().to_le_bytes());
        for class in &run.class {
            feed(class.as_bytes());
            feed(&[0xff]);
        }
        if let Some(span) = run.time {
            feed(&span.start.ticks().to_le_bytes());
            feed(&span.end.ticks().to_le_bytes());
        }
        feed(&[0xfe]);
    }
    feed(&time.ticks().to_le_bytes());
    hash.max(1)
}

/// The [`TextDraw`] of `text` in `style` on a picture of `size` at a font size of
/// `font_size` pixels ([`fit_text`]), with content version `key`.
#[must_use]
pub fn text_draw(
    text: &TextAt<'_>,
    style: &TextStyle,
    size: PictureSize,
    key: u64,
    font_size: f32,
) -> TextDraw {
    let request = text_request_at(text, style, size, key, font_size);
    let shadows = shadow_pixels(&style.shadows, request.font_size);
    TextDraw {
        request,
        shadows,
        animation: None,
    }
}

/// A text shadow in pixels of the picture its text is placed on.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ShadowPixels {
    /// Offset in pixels, +x right, +y down.
    pub offset: [f32; 2],
    /// The Gaussian's standard deviation in pixels: half the blur radius.
    pub sigma: f32,
    /// Straight, sRGB-encoded RGBA in `0..=1`.
    pub color: [f32; 4],
}

/// `shadows` in pixels of a `font_size`-pixel font (lengths are fractions of the font size),
/// first on top.
#[must_use]
pub fn shadow_pixels(shadows: &[TextShadow], font_size: f32) -> Vec<ShadowPixels> {
    shadows
        .iter()
        .map(|shadow| ShadowPixels {
            offset: [shadow.offset.x * font_size, shadow.offset.y * font_size],
            sigma: shadow.blur * font_size * 0.5,
            color: [
                shadow.color.red,
                shadow.color.green,
                shadow.color.blue,
                shadow.color.alpha,
            ],
        })
        .collect()
}

/// The pixel font size `style` sets on a picture of `size`, before any fit, as
/// [`text_request`] sets it.
#[must_use]
pub fn font_pixels(style: &TextStyle, size: PictureSize) -> f32 {
    crate::fit::pixels(style.font_size, size.unit())
}

#[cfg(test)]
#[path = "text_tests.rs"]
mod tests;