Skip to main content

alpha2_layout/
text.rs

1//! Text in a text style: its text host request, its identity, and where it lies on a picture.
2
3use std::borrow::Cow;
4
5use alpha2_media::EmojiPolicy;
6use alpha2_model::{
7    FontStyle, Paint, Rgba, Spread, TextAlign, TextContent, TextShadow, TextStroke, TextStyle,
8};
9use alpha2_text::{
10    ShapedText, TextFill, TextGradient, TextGradientKind, TextGradientStop, TextRasterError,
11    TextRasterRequest, TextRasterizer, TextSpread,
12};
13use alpha2_time::MediaTime;
14
15use crate::{Baselines, CanvasRect, PictureSize};
16
17/// The largest font, stroke extent, and padding the text host draws, in pixels.
18pub const MAX_FONT_PIXELS: f32 = 2_048.0;
19/// The most a text's strokes reach together, in pixels. See [`MAX_FONT_PIXELS`].
20pub const MAX_STROKE_PIXELS: f32 = 64.0;
21/// See [`MAX_FONT_PIXELS`].
22pub const MAX_PADDING_PIXELS: f32 = 256.0;
23
24/// Where a text lies, as fractions of the canvas from `(0, 0)` top-left to `(1, 1)`
25/// bottom-right. For a text generator this is on its picture, before the clip's transform
26/// and effects; for a caption it is on the canvas.
27#[derive(Copy, Clone, Debug, PartialEq)]
28pub struct TextBounds {
29    /// The box the style's anchor and position place: the wrapping width wide, every line's
30    /// em box tall, plus whole pixels of outline and background padding.
31    pub layout: CanvasRect,
32    /// The span of the lines' advances, as tall as the layout and with the same decorations.
33    /// It moves only with the advances, not with glyph ink.
34    pub content: CanvasRect,
35    /// What the text draws (glyphs, outline, background boxes), as
36    /// [`alpha2_text::TextMeasure::ink`] bounds it, within the texture's sampling spread.
37    /// `None` when the text draws nothing.
38    pub ink: Option<CanvasRect>,
39    /// Number of laid-out lines.
40    pub line_count: u32,
41    /// The first and last lines' alphabetic baselines.
42    pub baselines: Baselines,
43    /// The font size drawn after any `font_size_fit`, a fraction of the canvas's shorter side.
44    pub font_size: f32,
45    /// Whether the style's `line_clamp` discarded lines.
46    pub truncated: bool,
47    /// Whether the drawn text still splits a word or is taller than `max_height`.
48    pub overflow: bool,
49    /// The most the text's animators can widen its advances; its lines break at `max_width`
50    /// over this ([`alpha2_eval::advance_headroom`]).
51    pub advance_headroom: f32,
52}
53
54/// A text at a time since its holder started (a caption cue's start, a text generator's picture
55/// time), which samples its runs' keyframed `font_scale`.
56#[derive(Clone, Debug, PartialEq)]
57pub struct TextAt<'a> {
58    /// The text, a string or runs.
59    pub content: Cow<'a, TextContent>,
60    /// When.
61    pub time: MediaTime,
62}
63
64impl<'a> TextAt<'a> {
65    /// `content` at `time`.
66    #[must_use]
67    pub const fn new(content: &'a TextContent, time: MediaTime) -> Self {
68        Self {
69            content: Cow::Borrowed(content),
70            time,
71        }
72    }
73
74    /// Each run's `font_scale` at the time, 1 for a run without one.
75    #[must_use]
76    pub fn scales(&self) -> Vec<f32> {
77        self.content
78            .runs()
79            .iter()
80            .map(|run| {
81                run.style
82                    .as_ref()
83                    .and_then(|style| style.font_scale.as_ref())
84                    .map_or(1.0, |scale| {
85                        alpha2_eval::sample_scalar(
86                            scale,
87                            self.time,
88                            &alpha2_eval::SampleContext::NONE,
89                        )
90                        .clamp(
91                            *alpha2_model::FONT_SCALE_RANGE.start(),
92                            *alpha2_model::FONT_SCALE_RANGE.end(),
93                        )
94                    })
95            })
96            .collect()
97    }
98}
99
100impl From<&str> for TextAt<'static> {
101    fn from(text: &str) -> Self {
102        Self {
103            content: Cow::Owned(TextContent::from(text)),
104            time: MediaTime::ZERO,
105        }
106    }
107}
108
109/// The text host spans of `text` in `style` at `font_size` pixels: one per run, each run's style
110/// applied over `style` and its size `font_size` times its sampled `font_scale`; none when no run
111/// has a style and `style` is upright and undecorated, so such a request is a plain one.
112#[must_use]
113pub fn text_spans(
114    text: &TextAt<'_>,
115    style: &TextStyle,
116    font_size: f32,
117) -> Vec<alpha2_text::TextSpan> {
118    let content = &*text.content;
119    let base_plain = style.font_style.is_normal() && !style.underline && !style.line_through;
120    if base_plain && !content.has_run_styles() {
121        return Vec::new();
122    }
123    let span = |bytes: std::ops::Range<usize>,
124                run: Option<&alpha2_model::TextRunStyle>,
125                scale: f32| {
126        let merged = run.map_or_else(|| Cow::Borrowed(style), |run| Cow::Owned(run.apply(style)));
127        let size = (font_size * scale).clamp(f32::MIN_POSITIVE, MAX_FONT_PIXELS);
128        alpha2_text::TextSpan {
129            bytes,
130            font_family: merged.font_family.clone(),
131            font_weight: merged.font_weight,
132            font_style: match merged.font_style {
133                FontStyle::Normal => alpha2_text::FontStyle::Normal,
134                FontStyle::Italic => alpha2_text::FontStyle::Italic,
135                FontStyle::Oblique => alpha2_text::FontStyle::Oblique,
136            },
137            font_size: size,
138            letter_spacing: merged.letter_spacing * size,
139            fill: text_fill(&merged.fill),
140            strokes: stroke_pixels(&merged.strokes, size),
141            background_color: run.and_then(|run| run.background_color).map(rgba8),
142            underline: merged.underline,
143            line_through: merged.line_through,
144        }
145    };
146    if content.runs().is_empty() {
147        return vec![span(0..content.len(), None, 1.0)];
148    }
149    let mut start = 0;
150    content
151        .runs()
152        .iter()
153        .zip(text.scales())
154        .map(|(run, scale)| {
155            let bytes = start..start + run.text.len();
156            start = bytes.end;
157            span(bytes, run.style.as_ref(), scale)
158        })
159        .collect()
160}
161
162/// A layout text's raster request, shadows and animators hashed as a text store key
163/// (FNV-1a over a domain byte and every field). Never zero.
164#[must_use]
165pub fn layout_text_key(
166    request: &TextRasterRequest,
167    shadows: &[ShadowPixels],
168    animators: &[alpha2_eval::SampledAnimator],
169) -> u64 {
170    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
171    let mut feed = |bytes: &[u8]| {
172        for byte in bytes {
173            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
174        }
175    };
176    // Layout texts take keys apart from captions' and text generators'.
177    feed(&[0x4c]);
178    feed_request(&mut feed, request);
179    if !shadows.is_empty() {
180        feed(&[0xfd]);
181        feed_count(&mut feed, shadows.len());
182        for shadow in shadows {
183            for value in [shadow.offset[0], shadow.offset[1], shadow.sigma] {
184                feed(&value.to_bits().to_le_bytes());
185            }
186            for value in shadow.color {
187                feed(&value.to_bits().to_le_bytes());
188            }
189        }
190    }
191    if !animators.is_empty() {
192        let mut stable = alpha2_geometry::StableHash::new();
193        alpha2_eval::hash_sampled_animators(&mut stable, animators);
194        feed(&[0xfa]);
195        feed(&stable.finish().to_le_bytes());
196    }
197    hash.max(1)
198}
199
200/// What a request is shaped from, as a shaped-text cache key. Equal keys shape alike with
201/// the same fonts.
202#[must_use]
203pub fn shaped_key(request: &TextRasterRequest) -> u64 {
204    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
205    let mut feed = |bytes: &[u8]| {
206        for byte in bytes {
207            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
208        }
209    };
210    feed(request.text.as_bytes());
211    feed(&[0xff]);
212    feed(
213        request
214            .font_family
215            .as_deref()
216            .unwrap_or_default()
217            .as_bytes(),
218    );
219    feed(&[0xff, u8::from(request.font_family.is_some())]);
220    feed(&request.font_size.to_bits().to_le_bytes());
221    feed(&request.line_height.to_bits().to_le_bytes());
222    feed(&request.letter_spacing.to_bits().to_le_bytes());
223    feed(&request.font_weight.to_le_bytes());
224    hash
225}
226
227fn feed_request(feed: &mut impl FnMut(&[u8]), request: &TextRasterRequest) {
228    // No `..`: a new field must decide whether it is part of the key.
229    let TextRasterRequest {
230        text,
231        font_size,
232        max_width,
233        line_height,
234        align,
235        fill,
236        emoji_policy,
237        content_version: _,
238        strokes,
239        background,
240        split_background,
241        font_family,
242        letter_spacing,
243        font_weight,
244        clamp,
245        spans,
246        advance_headroom,
247        animator_grouping,
248        animator_pivot,
249        highlight,
250    } = request;
251    feed(text.as_bytes());
252    feed(&[0xff]);
253    feed(font_family.as_deref().unwrap_or_default().as_bytes());
254    feed(&[0xff, u8::from(font_family.is_some())]);
255    for value in [*font_size, *max_width, *line_height, *letter_spacing] {
256        feed(&value.to_bits().to_le_bytes());
257    }
258    feed(&font_weight.to_le_bytes());
259    match fill {
260        TextFill::Solid(color) => feed(color),
261        TextFill::Gradient(gradient) => feed_text_gradient(feed, gradient),
262    }
263    feed(&[match align {
264        alpha2_media::TextAlign::Start => 0,
265        alpha2_media::TextAlign::Center => 1,
266        alpha2_media::TextAlign::End => 2,
267    }]);
268    feed_count(feed, strokes.len());
269    for stroke in strokes {
270        feed(&stroke.color);
271        feed(&stroke.width.to_bits().to_le_bytes());
272    }
273    if *split_background {
274        feed(&[0xfd]);
275    }
276    if let Some(background) = background {
277        feed(&[0xfb]);
278        feed(&background.color);
279        feed_box_shape(feed, background);
280    }
281    // The default policy feeds nothing, so keys of requests that never set it stay as they were.
282    match emoji_policy {
283        alpha2_media::EmojiPolicy::Color => {}
284        alpha2_media::EmojiPolicy::Monochrome => feed(&[0xf9, 1]),
285        alpha2_media::EmojiPolicy::Replace => feed(&[0xf9, 2]),
286    }
287    if let Some(clamp) = clamp {
288        feed(&[0xfc]);
289        feed(&clamp.max_lines.unwrap_or(0).to_le_bytes());
290        feed(&clamp.max_height.to_bits().to_le_bytes());
291        feed(clamp.ellipsis.as_deref().unwrap_or_default().as_bytes());
292        feed(&[0xff, u8::from(clamp.ellipsis.is_some())]);
293    }
294    feed_spans(feed, spans);
295    if *advance_headroom > 1.0 {
296        feed(&[0xf8]);
297        feed(&advance_headroom.to_bits().to_le_bytes());
298    }
299    feed_motion(feed, *animator_grouping, *animator_pivot);
300    if let Some(highlight) = highlight {
301        feed(&[0xee]);
302        feed(&highlight.look.color);
303        feed_box_shape(feed, &highlight.look);
304        feed_count(feed, highlight.steps.len());
305        for (bytes, progress) in &highlight.steps {
306            feed(&bytes.start.to_le_bytes());
307            feed(&bytes.end.to_le_bytes());
308            feed(&progress.to_bits().to_le_bytes());
309        }
310    }
311}
312
313/// Feeds a grouping and pivot other than the default's.
314fn feed_motion(
315    feed: &mut impl FnMut(&[u8]),
316    grouping: alpha2_text::ClusterGrouping,
317    pivot: [f32; 2],
318) {
319    if grouping != alpha2_text::ClusterGrouping::Character
320        || pivot.map(f32::to_bits) != [0.5_f32.to_bits(); 2]
321    {
322        feed(&[0xf7]);
323        feed(&[grouping as u8]);
324        for value in pivot {
325            feed(&value.to_bits().to_le_bytes());
326        }
327    }
328}
329
330/// The grouping of `grouping` in the text host's terms.
331#[must_use]
332pub const fn cluster_grouping(
333    grouping: alpha2_model::AnimatorGrouping,
334) -> alpha2_text::ClusterGrouping {
335    match grouping {
336        alpha2_model::AnimatorGrouping::Character => alpha2_text::ClusterGrouping::Character,
337        alpha2_model::AnimatorGrouping::Word => alpha2_text::ClusterGrouping::Word,
338        alpha2_model::AnimatorGrouping::Line => alpha2_text::ClusterGrouping::Line,
339        alpha2_model::AnimatorGrouping::All => alpha2_text::ClusterGrouping::All,
340    }
341}
342
343fn feed_spans(feed: &mut impl FnMut(&[u8]), spans: &[alpha2_text::TextSpan]) {
344    if spans.is_empty() {
345        return;
346    }
347    feed(&[0xf8]);
348    feed(&spans.len().to_le_bytes());
349    for span in spans {
350        let alpha2_text::TextSpan {
351            bytes,
352            font_family,
353            font_weight,
354            font_style,
355            font_size,
356            letter_spacing,
357            fill,
358            strokes,
359            background_color,
360            underline,
361            line_through,
362        } = span;
363        feed(&bytes.start.to_le_bytes());
364        feed(&bytes.end.to_le_bytes());
365        feed(font_family.as_deref().unwrap_or_default().as_bytes());
366        feed(&[0xff, u8::from(font_family.is_some())]);
367        feed(&font_weight.to_le_bytes());
368        feed(&[*font_style as u8]);
369        feed(&font_size.to_bits().to_le_bytes());
370        feed(&letter_spacing.to_bits().to_le_bytes());
371        match fill {
372            TextFill::Solid(color) => feed(color),
373            TextFill::Gradient(gradient) => feed_text_gradient(feed, gradient),
374        }
375        feed_count(feed, strokes.len());
376        for stroke in strokes {
377            feed(&stroke.color);
378            feed(&stroke.width.to_bits().to_le_bytes());
379        }
380        match background_color {
381            Some(color) => {
382                feed(&[1]);
383                feed(color);
384            }
385            None => feed(&[0]),
386        }
387        feed(&[u8::from(*underline), u8::from(*line_through)]);
388    }
389}
390
391/// Feeds a box's padding (one side alone when all four are the same, as the single padding
392/// keyed before), radius and border, the last two only when set.
393fn feed_box_shape(feed: &mut impl FnMut(&[u8]), background: &alpha2_text::TextBackground) {
394    let padding = background.padding;
395    let [top, right, bottom, left] = padding.map(f32::to_bits);
396    if top == right && top == bottom && top == left {
397        feed(&padding[0].to_bits().to_le_bytes());
398    } else {
399        feed(&[0xf7]);
400        for side in padding {
401            feed(&side.to_bits().to_le_bytes());
402        }
403    }
404    if background.radius != 0.0 {
405        feed(&[0xf6]);
406        feed(&background.radius.to_bits().to_le_bytes());
407    }
408    if let Some(border) = &background.border {
409        feed(&[0xf5]);
410        feed(&border.width.to_bits().to_le_bytes());
411        feed(&border.color);
412        if let Some(dash) = &border.dash {
413            feed_count(feed, dash.pattern.len());
414            for entry in &dash.pattern {
415                feed(&entry.to_bits().to_le_bytes());
416            }
417            feed(&dash.offset.to_bits().to_le_bytes());
418        }
419    }
420}
421
422/// A list's length as one byte. A list of one feeds the same byte the single optional value
423/// it replaced fed, which keeps existing keys stable.
424#[allow(clippy::cast_possible_truncation)]
425fn feed_count(feed: &mut impl FnMut(&[u8]), count: usize) {
426    feed(&[count.min(255) as u8]);
427}
428
429fn feed_text_gradient(feed: &mut impl FnMut(&[u8]), gradient: &TextGradient) {
430    // A tag no color's first byte can be mistaken for: a solid fill feeds four bytes only.
431    feed(&[0xfe]);
432    let points: &[f32] = match &gradient.kind {
433        TextGradientKind::Linear { start, end } => &[0.0, start[0], start[1], end[0], end[1]],
434        TextGradientKind::Radial { center, radius } => &[1.0, center[0], center[1], *radius],
435        TextGradientKind::Conic { center, angle } => &[2.0, center[0], center[1], *angle],
436    };
437    for value in points {
438        feed(&value.to_bits().to_le_bytes());
439    }
440    feed(&[gradient.spread as u8]);
441    feed_count(feed, gradient.stops.len());
442    for stop in &gradient.stops {
443        feed(&stop.offset.to_bits().to_le_bytes());
444        for value in stop.color {
445            feed(&value.to_bits().to_le_bytes());
446        }
447    }
448}
449
450/// A paint's identity for a text key: a solid color as its bytes, a gradient by every field.
451fn feed_paint(feed: &mut impl FnMut(&[u8]), paint: &Paint) {
452    match paint {
453        Paint::Solid { color } => feed(&rgba8(*color)),
454        gradient => feed_text_gradient(feed, &text_gradient(gradient)),
455    }
456}
457
458/// A text style's strokes and shadows for a text key. One stroke feeds what an outline fed,
459/// and no shadows feed nothing.
460fn feed_look(feed: &mut impl FnMut(&[u8]), strokes: &[TextStroke], shadows: &[TextShadow]) {
461    feed_count(feed, strokes.len());
462    for stroke in strokes {
463        feed(&rgba8(stroke.color));
464        feed(&stroke.width.to_bits().to_le_bytes());
465    }
466    if !shadows.is_empty() {
467        feed(&[0xfd]);
468        feed_count(feed, shadows.len());
469        for shadow in shadows {
470            feed(&rgba8(shadow.color));
471            for value in [shadow.offset.x, shadow.offset.y, shadow.blur] {
472                feed(&value.to_bits().to_le_bytes());
473            }
474        }
475    }
476}
477
478/// A text's identity at a render size: the text, its runs' styles and sampled scales, its style
479/// and the size, hashed with FNV-1a. A text without run styles keys as its plain string. Never
480/// zero.
481#[must_use]
482pub fn text_key(text: &TextAt<'_>, style: &TextStyle, size: PictureSize) -> u64 {
483    // No `..`: a new field must decide whether it is part of the key.
484    let TextStyle {
485        font_family,
486        font_size,
487        fill,
488        line_height,
489        letter_spacing,
490        font_weight,
491        font_style,
492        underline,
493        line_through,
494        align,
495        max_width,
496        max_height,
497        font_size_fit,
498        line_clamp,
499        position,
500        anchor,
501        strokes,
502        shadows,
503        background,
504        highlight,
505        // `animated_text_key` adds the sampled animators.
506        animators: _,
507        animator_grouping,
508        animator_pivot,
509    } = style;
510    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
511    let mut feed = |bytes: &[u8]| {
512        for byte in bytes {
513            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
514        }
515    };
516    feed(text.content.text().as_bytes());
517    feed(&[0xff]);
518    // Family names cannot hold 0xff (they are UTF-8), so the text and family stay apart.
519    feed(font_family.as_deref().unwrap_or_default().as_bytes());
520    feed(&[0xff, u8::from(font_family.is_some())]);
521    for value in [
522        *font_size,
523        *line_height,
524        *letter_spacing,
525        *max_width,
526        position.x,
527        position.y,
528        anchor.x,
529        anchor.y,
530    ] {
531        feed(&value.to_bits().to_le_bytes());
532    }
533    feed(&font_weight.to_le_bytes());
534    feed_paint(&mut feed, fill);
535    feed(&[match align {
536        TextAlign::Start => 0,
537        TextAlign::Center => 1,
538        TextAlign::End => 2,
539    }]);
540    feed_look(&mut feed, strokes, shadows);
541    match background {
542        Some(background) => {
543            let unit = text_background(background, 1.0);
544            feed(&[1]);
545            feed(&unit.color);
546            feed_box_shape(&mut feed, &unit);
547        }
548        None => feed(&[0]),
549    }
550    // Only fields that are set are fed.
551    feed_fit(&mut feed, *max_height, *font_size_fit, line_clamp.as_ref());
552    if !font_style.is_normal() {
553        feed(&[0xf3, *font_style as u8]);
554    }
555    if *underline || *line_through {
556        feed(&[0xf4, u8::from(*underline), u8::from(*line_through)]);
557    }
558    if text.content.has_run_styles() {
559        feed_spans(&mut feed, &text_spans(text, style, 1.0));
560    }
561    if let Some(highlight) = highlight {
562        feed_highlight(&mut feed, highlight);
563    }
564    let headroom = advance_headroom(text, style);
565    if headroom > 1.0 {
566        feed(&[0xf8]);
567        feed(&headroom.to_bits().to_le_bytes());
568    }
569    feed_motion(
570        &mut feed,
571        cluster_grouping(*animator_grouping),
572        [animator_pivot.x, animator_pivot.y],
573    );
574    feed(&size.width().to_le_bytes());
575    feed(&size.height().to_le_bytes());
576    hash.max(1)
577}
578
579/// Where `text` in `style` lies on a canvas of `size`, laid out with `rasterizer`'s fonts and
580/// placed exactly as a frame places it, without drawing it.
581///
582/// Measured at the frame's render size it agrees with that frame to the pixel; at another
583/// size lines can break elsewhere.
584///
585/// # Errors
586/// Returns the text host's refusal: no fonts, or a style out of range.
587pub fn measure_text(
588    rasterizer: &TextRasterizer,
589    text: &TextAt<'_>,
590    style: &TextStyle,
591    size: PictureSize,
592) -> Result<TextBounds, TextRasterError> {
593    let placed = place(rasterizer, text, style, size)?;
594    let shaped = rasterizer.shape(&placed.request)?;
595    let boxed = style_lines(&shaped, style, size, &placed.request);
596    let measure = &placed.measure;
597    let height = placed.canvas[1];
598    Ok(TextBounds {
599        layout: placed.layout,
600        content: placed.rect(measure.content),
601        ink: measure.ink.map(|ink| placed.rect(ink)),
602        line_count: measure.line_count,
603        baselines: Baselines {
604            first: (placed.origin[1] + measure.first_baseline) / height,
605            last: (placed.origin[1] + measure.last_baseline) / height,
606        },
607        font_size: placed.font_size,
608        truncated: measure.truncated,
609        overflow: boxed.overflow,
610        advance_headroom: placed.request.advance_headroom,
611    })
612}
613
614/// A text's request at its fitted size, its measure, and where its layout box lies.
615pub(crate) struct Placed {
616    pub(crate) request: TextRasterRequest,
617    pub(crate) measure: alpha2_text::TextMeasure,
618    /// The layout box's top-left corner on the canvas, in pixels.
619    pub(crate) origin: [f32; 2],
620    pub(crate) canvas: [f32; 2],
621    pub(crate) layout: CanvasRect,
622    pub(crate) font_size: f32,
623}
624
625impl Placed {
626    /// A rectangle of the layout box, in pixels, on the canvas in fractions.
627    pub(crate) fn rect(&self, [left, top, right, bottom]: [f32; 4]) -> CanvasRect {
628        CanvasRect {
629            left: (self.origin[0] + left) / self.canvas[0],
630            top: (self.origin[1] + top) / self.canvas[1],
631            right: (self.origin[0] + right) / self.canvas[0],
632            bottom: (self.origin[1] + bottom) / self.canvas[1],
633        }
634    }
635}
636
637#[expect(
638    clippy::cast_precision_loss,
639    reason = "picture sides are far below 2^24"
640)]
641pub(crate) fn place(
642    rasterizer: &TextRasterizer,
643    text: &TextAt<'_>,
644    style: &TextStyle,
645    size: PictureSize,
646) -> Result<Placed, TextRasterError> {
647    let fitted = fit_text(text, style, size, |request| {
648        rasterizer.shape(request).map(std::sync::Arc::new)
649    })?;
650    let request = text_request_at(
651        text,
652        style,
653        size,
654        text_key(text, style, size),
655        fitted.font_pixels,
656    );
657    let measure = rasterizer.measure(&request)?;
658    let (width, height) = (size.width() as f32, size.height() as f32);
659    let [margin_x, margin_y] = measure.decoration_margin.map(|margin| margin as f32);
660    let (box_width, box_height) = (measure.box_width as f32, measure.box_height as f32);
661    // The layout box's top-left corner on the canvas. The anchor of the decorated box lies at the
662    // position, as `text_placement` places the texture.
663    let origin = [
664        style.position.x * width - style.anchor.x * (box_width + 2.0 * margin_x) + margin_x,
665        style.position.y * height - style.anchor.y * (box_height + 2.0 * margin_y) + margin_y,
666    ];
667    let mut placed = Placed {
668        request,
669        measure,
670        origin,
671        canvas: [width, height],
672        layout: CanvasRect {
673            left: 0.0,
674            top: 0.0,
675            right: 0.0,
676            bottom: 0.0,
677        },
678        font_size: fitted.font_size,
679    };
680    placed.layout = placed.rect([
681        -margin_x,
682        -margin_y,
683        box_width + margin_x,
684        box_height + margin_y,
685    ]);
686    Ok(placed)
687}
688
689/// The height in pixels of `style`'s box on a picture of `size`, zero for none.
690#[allow(clippy::cast_precision_loss)]
691fn box_height(style: &TextStyle, size: PictureSize) -> f32 {
692    style
693        .max_height
694        .map_or(0.0, |height| height * size.height() as f32)
695}
696
697/// How `shaped`, shaped for `request`, lies in `style`'s box.
698fn style_lines(
699    shaped: &ShapedText,
700    style: &TextStyle,
701    size: PictureSize,
702    request: &TextRasterRequest,
703) -> crate::fit::BoxedLines {
704    crate::fit::boxed_lines(
705        shaped,
706        request.wrap_width(),
707        box_height(style, size),
708        style.line_clamp.as_ref().and_then(|clamp| clamp.max_lines),
709        style.line_clamp.is_some(),
710    )
711}
712
713/// The font size `text` in `style` draws at on a picture of `size`: the largest its
714/// `font_size_fit` allows at which the text fits its box, with lines from `shape`.
715///
716/// The box is the wrapping width by `max_height`, and `line_clamp.max_lines` also bounds it.
717/// Without a fit it is the style's own size and `shape` is not called.
718///
719/// # Errors
720/// Returns the first refusal of `shape`.
721pub fn fit_text<S: std::ops::Deref<Target = ShapedText>>(
722    text: &TextAt<'_>,
723    style: &TextStyle,
724    size: PictureSize,
725    mut shape: impl FnMut(&TextRasterRequest) -> Result<S, TextRasterError>,
726) -> Result<crate::FittedSize, TextRasterError> {
727    crate::fit::fit_font_size(
728        style.font_size,
729        style.font_size_fit,
730        size.unit(),
731        |pixels| {
732            let request = text_request_at(text, style, size, 1, pixels);
733            let shaped = shape(&request)?;
734            Ok(style_lines(&shaped, style, size, &request).fits)
735        },
736    )
737}
738
739/// A straight, sRGB-encoded color as bytes.
740#[must_use]
741#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
742pub fn rgba8(color: Rgba) -> [u8; 4] {
743    [color.red, color.green, color.blue, color.alpha]
744        .map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8)
745}
746
747/// The text host request for `text` in `style` on a picture of `size`, with content version
748/// `key`. Sizes are scaled from canvas fractions to pixels and clamped to what the host draws.
749#[must_use]
750pub fn text_request(
751    text: &TextAt<'_>,
752    style: &TextStyle,
753    size: PictureSize,
754    key: u64,
755) -> TextRasterRequest {
756    text_request_at(text, style, size, key, font_pixels(style, size))
757}
758
759/// [`text_request`] at a font size of `font_size` pixels, such as [`fit_text`] finds.
760#[must_use]
761#[allow(clippy::cast_precision_loss)]
762pub fn text_request_at(
763    text: &TextAt<'_>,
764    style: &TextStyle,
765    size: PictureSize,
766    key: u64,
767    font_size: f32,
768) -> TextRasterRequest {
769    let spans = text_spans(text, style, font_size);
770    TextRasterRequest {
771        text: text.content.text().into_owned(),
772        font_size,
773        max_width: (style.max_width * size.width() as f32).max(1.0),
774        line_height: style.line_height,
775        align: match style.align {
776            TextAlign::Start => alpha2_media::TextAlign::Start,
777            TextAlign::Center => alpha2_media::TextAlign::Center,
778            TextAlign::End => alpha2_media::TextAlign::End,
779        },
780        fill: text_fill(&style.fill),
781        emoji_policy: EmojiPolicy::Color,
782        content_version: key,
783        strokes: stroke_pixels(&style.strokes, font_size),
784        split_background: !style.shadows.is_empty()
785            && (style.background.is_some()
786                || style.highlight.is_some()
787                || spans.iter().any(|span| span.background_color.is_some())),
788        background: style
789            .background
790            .as_ref()
791            .map(|background| text_background(background, font_size)),
792        font_family: style.font_family.clone(),
793        letter_spacing: style.letter_spacing * font_size,
794        font_weight: style.font_weight,
795        clamp: style
796            .line_clamp
797            .as_ref()
798            .map(|clamp| crate::fit::text_clamp(clamp, box_height(style, size))),
799        spans,
800        advance_headroom: advance_headroom(text, style),
801        animator_grouping: cluster_grouping(style.animator_grouping),
802        animator_pivot: [style.animator_pivot.x, style.animator_pivot.y],
803        highlight: style.highlight.as_ref().and_then(|highlight| {
804            let steps =
805                crate::text_animation::highlight_steps(text.content.runs(), text.time, highlight);
806            (!steps.is_empty()).then(|| alpha2_text::TextHighlightRequest {
807                look: highlight_look(highlight, font_size),
808                steps,
809            })
810        }),
811    }
812}
813
814/// Feeds a style's box height, fit and clamp, each only when set.
815fn feed_fit(
816    feed: &mut impl FnMut(&[u8]),
817    max_height: Option<f32>,
818    font_size_fit: Option<alpha2_model::FontSizeFit>,
819    line_clamp: Option<&alpha2_model::LineClamp>,
820) {
821    if let Some(height) = max_height {
822        feed(&[0xf0]);
823        feed(&height.to_bits().to_le_bytes());
824    }
825    if let Some(fit) = font_size_fit {
826        feed(&[0xf1]);
827        feed(&fit.min.to_bits().to_le_bytes());
828        feed(&fit.max.unwrap_or(-1.0).to_bits().to_le_bytes());
829    }
830    if let Some(clamp) = line_clamp {
831        feed(&[0xf2]);
832        feed(&clamp.max_lines.unwrap_or(0).to_le_bytes());
833        feed(clamp.block_ellipsis.text().unwrap_or_default().as_bytes());
834        feed(&[0xff, u8::from(clamp.block_ellipsis.text().is_some())]);
835    }
836}
837
838/// Feeds `highlight`'s look at a one-pixel font and its timing.
839fn feed_highlight(feed: &mut impl FnMut(&[u8]), highlight: &alpha2_model::TextHighlight) {
840    let unit = highlight_look(highlight, 1.0);
841    feed(&[0xee]);
842    feed(&unit.color);
843    feed_box_shape(feed, &unit);
844    feed(&highlight.transition.ticks().to_le_bytes());
845    match highlight.easing {
846        alpha2_model::Easing::Linear => feed(&[0]),
847        alpha2_model::Easing::CubicBezier(curve) => {
848            feed(&[1]);
849            for value in [curve.x1, curve.y1, curve.x2, curve.y2] {
850                feed(&value.to_bits().to_le_bytes());
851            }
852        }
853    }
854    feed(&[highlight.gap as u8]);
855}
856
857/// `highlight`'s box look in pixels of a `font_size`-pixel font, as [`text_background`] sizes a
858/// background.
859#[must_use]
860pub fn highlight_look(
861    highlight: &alpha2_model::TextHighlight,
862    font_size: f32,
863) -> alpha2_text::TextBackground {
864    text_background(
865        &alpha2_model::TextBackground {
866            color: highlight.color,
867            padding: highlight.padding,
868            radius: highlight.radius,
869            border: highlight.border.clone(),
870            extent: alpha2_model::TextBoxExtent::Line,
871        },
872        font_size,
873    )
874}
875
876/// The most `style`'s animators can widen an advance of `text` ([`alpha2_eval::advance_headroom`]).
877#[must_use]
878pub fn advance_headroom(text: &TextAt<'_>, style: &TextStyle) -> f32 {
879    if style.animators.is_empty() {
880        1.0
881    } else {
882        alpha2_eval::advance_headroom(&style.animators, text.content.runs())
883    }
884}
885
886/// `background` in pixels of a `font_size`-pixel font, padding clamped to what the host draws.
887#[must_use]
888pub fn text_background(
889    background: &alpha2_model::TextBackground,
890    font_size: f32,
891) -> alpha2_text::TextBackground {
892    alpha2_text::TextBackground {
893        color: rgba8(background.color),
894        padding: background
895            .padding
896            .sides()
897            .map(|side| (side * font_size).clamp(0.0, MAX_PADDING_PIXELS)),
898        radius: background.radius * font_size,
899        border: background
900            .border
901            .as_ref()
902            .map(|border| alpha2_text::TextBoxBorder {
903                width: border.width * font_size,
904                color: rgba8(border.color),
905                dash: border.dash.as_ref().map(|dash| alpha2_text::TextBoxDash {
906                    pattern: dash.pattern.iter().map(|entry| entry * font_size).collect(),
907                    offset: dash.offset * font_size,
908                }),
909            }),
910        extent: match background.extent {
911            alpha2_model::TextBoxExtent::Line => alpha2_text::BoxExtent::Line,
912            alpha2_model::TextBoxExtent::Revealed => alpha2_text::BoxExtent::Revealed,
913            alpha2_model::TextBoxExtent::Block => alpha2_text::BoxExtent::Block,
914        },
915    }
916}
917
918/// A paint as the text host's fill: a color as bytes, or a gradient over the layout box with
919/// the same stops and the conic angle in radians.
920#[must_use]
921pub fn text_fill(paint: &Paint) -> TextFill {
922    match paint {
923        Paint::Solid { color } => TextFill::Solid(rgba8(*color)),
924        gradient => TextFill::Gradient(text_gradient(gradient)),
925    }
926}
927
928fn text_gradient(paint: &Paint) -> TextGradient {
929    let pair = |value: alpha2_model::Vec2| [value.x, value.y];
930    let stops = |stops: &[alpha2_model::GradientStop]| {
931        stops
932            .iter()
933            .map(|stop| TextGradientStop {
934                offset: stop.offset,
935                color: [
936                    stop.color.red,
937                    stop.color.green,
938                    stop.color.blue,
939                    stop.color.alpha,
940                ],
941            })
942            .collect()
943    };
944    let spread = |spread: Spread| match spread {
945        Spread::Pad => TextSpread::Pad,
946        Spread::Repeat => TextSpread::Repeat,
947        Spread::Reflect => TextSpread::Reflect,
948    };
949    match paint {
950        // A solid paint is a gradient of one color, for a caller that needs the gradient form.
951        Paint::Solid { color } => TextGradient {
952            kind: TextGradientKind::Linear {
953                start: [0.0, 0.0],
954                end: [1.0, 0.0],
955            },
956            stops: stops(&[
957                alpha2_model::GradientStop {
958                    offset: 0.0,
959                    color: *color,
960                },
961                alpha2_model::GradientStop {
962                    offset: 1.0,
963                    color: *color,
964                },
965            ]),
966            spread: TextSpread::Pad,
967        },
968        Paint::LinearGradient {
969            start,
970            end,
971            stops: list,
972            spread: mode,
973        } => TextGradient {
974            kind: TextGradientKind::Linear {
975                start: pair(*start),
976                end: pair(*end),
977            },
978            stops: stops(list),
979            spread: spread(*mode),
980        },
981        Paint::RadialGradient {
982            center,
983            radius,
984            stops: list,
985            spread: mode,
986        } => TextGradient {
987            kind: TextGradientKind::Radial {
988                center: pair(*center),
989                radius: *radius,
990            },
991            stops: stops(list),
992            spread: spread(*mode),
993        },
994        Paint::ConicGradient {
995            center,
996            angle_degrees,
997            stops: list,
998        } => TextGradient {
999            kind: TextGradientKind::Conic {
1000                center: pair(*center),
1001                angle: angle_degrees.to_radians(),
1002            },
1003            stops: stops(list),
1004            spread: TextSpread::Pad,
1005        },
1006    }
1007}
1008
1009/// `strokes` in pixels of a `font_size`-pixel font (widths are fractions of the font size).
1010/// Each is at least the smallest positive width, and the last is shortened so together they
1011/// reach at most [`MAX_STROKE_PIXELS`].
1012#[must_use]
1013pub fn stroke_pixels(strokes: &[TextStroke], font_size: f32) -> Vec<alpha2_text::TextStroke> {
1014    let mut reach = 0.0_f32;
1015    let mut pixels = Vec::with_capacity(strokes.len());
1016    for stroke in strokes {
1017        let room = MAX_STROKE_PIXELS - reach;
1018        if room <= 0.0 {
1019            break;
1020        }
1021        let width = (stroke.width * font_size).clamp(f32::MIN_POSITIVE, room);
1022        reach += width;
1023        pixels.push(alpha2_text::TextStroke {
1024            color: rgba8(stroke.color),
1025            width,
1026        });
1027    }
1028    pixels
1029}
1030
1031/// What the engine draws for one text: the raster, and the shadows composited under its
1032/// glyphs.
1033#[derive(Clone, Debug, PartialEq)]
1034pub struct TextDraw {
1035    /// The raster request.
1036    pub request: TextRasterRequest,
1037    /// The shadows, first on top.
1038    pub shadows: Vec<ShadowPixels>,
1039    /// The text's animators at its time, for a text that has them.
1040    pub animation: Option<TextAnimation>,
1041}
1042
1043/// A text's animators sampled at one time, with what they select from.
1044#[derive(Clone, Debug, PartialEq)]
1045pub struct TextAnimation {
1046    /// The animators, in order.
1047    pub animators: Vec<alpha2_eval::SampledAnimator>,
1048    /// The text's runs, none for a plain string.
1049    pub runs: Vec<alpha2_model::TextRun>,
1050    /// The time Timing selectors compare run times with.
1051    pub time: alpha2_time::MediaTime,
1052}
1053
1054impl TextDraw {
1055    /// Each cluster's state and the states' hash
1056    /// ([`crate::text_animation::cluster_states`]), `None` without animators.
1057    ///
1058    /// # Errors
1059    /// Returns the text host's refusal to lay the text out.
1060    pub fn states(
1061        &self,
1062        rasterizer: &TextRasterizer,
1063    ) -> Result<Option<(Vec<alpha2_text::ClusterState>, u64)>, TextRasterError> {
1064        let Some(animation) = &self.animation else {
1065            return Ok(None);
1066        };
1067        let layout = rasterizer.layout(&self.request)?;
1068        Ok(Some(crate::text_animation::cluster_states(
1069            &layout,
1070            &animation.runs,
1071            &animation.animators,
1072            animation.time,
1073            self.request.font_size,
1074        )))
1075    }
1076}
1077
1078/// [`text_key`] for `content` in `style` shown `time` after its holder started. Without
1079/// animators this is the static key; otherwise the runs and time are mixed in, so each moment
1080/// of an animation is a distinct text. Never zero.
1081#[must_use]
1082pub fn animated_text_key(
1083    content: &alpha2_model::TextContent,
1084    style: &TextStyle,
1085    size: PictureSize,
1086    time: alpha2_time::MediaTime,
1087) -> u64 {
1088    let key = text_key(&TextAt::new(content, time), style, size);
1089    if style.animators.is_empty() && style.highlight.is_none() {
1090        return key;
1091    }
1092    let mut hash = key;
1093    let mut feed = |bytes: &[u8]| {
1094        for byte in bytes {
1095            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
1096        }
1097    };
1098    if let Some(highlight) = &style.highlight {
1099        let steps = crate::text_animation::highlight_steps(content.runs(), time, highlight);
1100        feed(&[0xee]);
1101        feed_count(&mut feed, steps.len());
1102        for (bytes, progress) in &steps {
1103            feed(&bytes.start.to_le_bytes());
1104            feed(&progress.to_bits().to_le_bytes());
1105        }
1106    }
1107    if style.animators.is_empty() {
1108        return hash.max(1);
1109    }
1110    feed(&[0xfa]);
1111    let mut stable = alpha2_geometry::StableHash::new();
1112    alpha2_eval::hash_sampled_animators(
1113        &mut stable,
1114        &alpha2_eval::sample_text_animators(&style.animators, time),
1115    );
1116    feed(&stable.finish().to_le_bytes());
1117    for run in content.runs() {
1118        feed(&run.text.len().to_le_bytes());
1119        for class in &run.class {
1120            feed(class.as_bytes());
1121            feed(&[0xff]);
1122        }
1123        if let Some(span) = run.time {
1124            feed(&span.start.ticks().to_le_bytes());
1125            feed(&span.end.ticks().to_le_bytes());
1126        }
1127        feed(&[0xfe]);
1128    }
1129    feed(&time.ticks().to_le_bytes());
1130    hash.max(1)
1131}
1132
1133/// The [`TextDraw`] of `text` in `style` on a picture of `size` at a font size of
1134/// `font_size` pixels ([`fit_text`]), with content version `key`.
1135#[must_use]
1136pub fn text_draw(
1137    text: &TextAt<'_>,
1138    style: &TextStyle,
1139    size: PictureSize,
1140    key: u64,
1141    font_size: f32,
1142) -> TextDraw {
1143    let request = text_request_at(text, style, size, key, font_size);
1144    let shadows = shadow_pixels(&style.shadows, request.font_size);
1145    TextDraw {
1146        request,
1147        shadows,
1148        animation: None,
1149    }
1150}
1151
1152/// A text shadow in pixels of the picture its text is placed on.
1153#[derive(Copy, Clone, Debug, PartialEq)]
1154pub struct ShadowPixels {
1155    /// Offset in pixels, +x right, +y down.
1156    pub offset: [f32; 2],
1157    /// The Gaussian's standard deviation in pixels: half the blur radius.
1158    pub sigma: f32,
1159    /// Straight, sRGB-encoded RGBA in `0..=1`.
1160    pub color: [f32; 4],
1161}
1162
1163/// `shadows` in pixels of a `font_size`-pixel font (lengths are fractions of the font size),
1164/// first on top.
1165#[must_use]
1166pub fn shadow_pixels(shadows: &[TextShadow], font_size: f32) -> Vec<ShadowPixels> {
1167    shadows
1168        .iter()
1169        .map(|shadow| ShadowPixels {
1170            offset: [shadow.offset.x * font_size, shadow.offset.y * font_size],
1171            sigma: shadow.blur * font_size * 0.5,
1172            color: [
1173                shadow.color.red,
1174                shadow.color.green,
1175                shadow.color.blue,
1176                shadow.color.alpha,
1177            ],
1178        })
1179        .collect()
1180}
1181
1182/// The pixel font size `style` sets on a picture of `size`, before any fit, as
1183/// [`text_request`] sets it.
1184#[must_use]
1185pub fn font_pixels(style: &TextStyle, size: PictureSize) -> f32 {
1186    crate::fit::pixels(style.font_size, size.unit())
1187}
1188
1189#[cfg(test)]
1190#[path = "text_tests.rs"]
1191mod tests;