Skip to main content

cranpose_ui_graphics/
text_primitive.rs

1//! The text a draw scope records: its primitive, the shared copy of its
2//! characters and where its block goes inside a rect.
3
4use std::rc::Rc;
5
6use crate::{
7    Brush, DrawPrimitive, Point, Rect,
8    typography::{
9        DrawTextMeasurer, DrawTextStyle, MeasuredText, TextAlign, TextMeasurement,
10        TextVerticalAlign, estimate_text_measurement,
11    },
12};
13
14/// A run of text, positioned and ready to rasterize.
15///
16/// `rect` is *already resolved*:
17/// [`DrawScope::draw_text_at`](crate::DrawScope::draw_text_at) measures the
18/// string, applies [`DrawTextStyle::align`] / [`DrawTextStyle::vertical_align`] inside
19/// the requested box, and stores the result here. Renderers therefore lay the
20/// glyphs out from `rect`'s top-left and never re-align — which is what keeps
21/// what [`DrawScope::measure_text`](crate::DrawScope::measure_text) reported
22/// and what lands on screen the same geometry.
23#[derive(Clone, Debug, PartialEq)]
24pub struct TextPrimitive {
25    /// Tight block box: origin is the top-left of the first line's slot, size
26    /// is the measured size.
27    pub rect: Rect,
28    /// Shared so redrawing an unchanged string each frame clones a pointer
29    /// rather than the characters.
30    pub text: Rc<str>,
31    /// Font, size, alignment and other styling the glyphs are laid out and drawn with.
32    pub style: DrawTextStyle,
33    /// Paint for the glyphs: a solid colour, or a gradient laid over the
34    /// text block, as Compose's `drawText(brush)` lays it over the layout.
35    pub brush: Brush,
36    /// The layout the text was measured in, which the renderer draws.
37    /// `None` when no text system measured it.
38    pub layout: Option<crate::TextLayoutHandle>,
39}
40
41/// Returns a shared `Rc<str>` for `text`, reusing the copy made on an earlier
42/// frame when the content matches.
43///
44/// Apps hand `draw_text*` a `&str` every frame, and a score counter or label
45/// is the same characters frame after frame — without this pool every call
46/// copied them into a fresh `Rc<str>` anyway, defeating the sharing
47/// [`TextPrimitive::text`] exists for. Hits are verified by content, so a hash
48/// collision costs one fresh copy, never the wrong text. The pool keeps the
49/// copies that recordings still hold, as [`crate::ContentPool`] does.
50pub(crate) fn shared_text_str(text: &str) -> Rc<str> {
51    use std::hash::{Hash, Hasher};
52
53    let mut hasher = crate::FxHasher::default();
54    text.hash(&mut hasher);
55    crate::thread_state::with(|state| {
56        state.shared_texts.borrow_mut().with(
57            hasher.finish(),
58            |shared| &**shared == text,
59            || Rc::from(text),
60            Rc::clone,
61        )
62    })
63}
64
65/// Resolves the top-left corner a text block of `measurement` gets when it is
66/// aligned inside `rect`.
67///
68/// Split out so the placement rule is stated once and can be unit-tested
69/// against the measurement it is derived from.
70pub fn align_text_block(rect: Rect, measurement: TextMeasurement, style: &DrawTextStyle) -> Point {
71    let x = match style.align {
72        TextAlign::Left => rect.x,
73        TextAlign::Center => rect.x + (rect.width - measurement.size.width) * 0.5,
74        TextAlign::Right => rect.x + rect.width - measurement.size.width,
75    };
76    let y = match style.vertical_align {
77        TextVerticalAlign::Top => rect.y,
78        TextVerticalAlign::Center => rect.y + (rect.height - measurement.size.height) * 0.5,
79        TextVerticalAlign::Bottom => rect.y + rect.height - measurement.size.height,
80        TextVerticalAlign::Baseline => rect.y - measurement.first_baseline,
81    };
82    Point::new(x, y)
83}
84
85// Where a drawn text's block goes.
86#[derive(Clone, Copy)]
87pub(crate) enum TextBlockAt {
88    // Inside a rect, placed by the style's alignments.
89    Aligned(Rect),
90    // With its top left corner at a point, the style's alignments set to
91    // the top left.
92    From(Point),
93}
94
95// `text` in `style` measured by `measurer`, or estimated without one.
96pub(crate) fn measured_text(
97    measurer: Option<&dyn DrawTextMeasurer>,
98    text: &str,
99    style: &DrawTextStyle,
100) -> MeasuredText {
101    match measurer {
102        Some(measurer) => measurer.measure_text(text, style),
103        None => MeasuredText {
104            measurement: estimate_text_measurement(text, style),
105            layout: None,
106        },
107    }
108}
109
110// The primitive that draws `text` in `style` with `brush`, measured once by
111// `measurer`, its block placed `at`. `None` when nothing would draw: the
112// text is empty, the brush paints nothing, the block has no area or its
113// corner is not finite.
114pub(crate) fn text_primitive(
115    measurer: Option<&dyn DrawTextMeasurer>,
116    at: TextBlockAt,
117    brush: Brush,
118    text: &str,
119    style: &DrawTextStyle,
120) -> Option<DrawPrimitive> {
121    if text.is_empty() || !brush.paints() {
122        return None;
123    }
124    let measured = measured_text(measurer, text, style);
125    let size = measured.measurement.size;
126    if !(size.width > 0.0 && size.height > 0.0) {
127        return None;
128    }
129    let (origin, style) = match at {
130        TextBlockAt::Aligned(rect) => (
131            align_text_block(rect, measured.measurement, style),
132            style.clone(),
133        ),
134        TextBlockAt::From(top_left) => (
135            top_left,
136            DrawTextStyle {
137                align: TextAlign::Left,
138                vertical_align: TextVerticalAlign::Top,
139                ..style.clone()
140            },
141        ),
142    };
143    if !origin.x.is_finite() || !origin.y.is_finite() {
144        return None;
145    }
146    Some(DrawPrimitive::Text(Box::new(TextPrimitive {
147        rect: Rect::from_origin_size(origin, size),
148        text: shared_text_str(text),
149        style,
150        brush,
151        layout: measured.layout,
152    })))
153}