Skip to main content

cranpose_render_common/
text_paint.rs

1//! What a renderer reads of a text's style to draw its glyphs, worked out
2//! once per text node so that drawing a plain text never loads its style.
3
4use std::cell::Cell;
5
6use cranpose_ui::{
7    Brush, Color, TextStyle,
8    text::{RangeStyle, SpanStyle, TextDecoration, TextDrawStyle},
9};
10
11/// The paint of a text node's glyphs.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct TextPaint {
14    /// Whether the glyphs in `color` are all the text draws: no background,
15    /// shadow, brush, stroke or decoration, and no span that paints its own
16    /// range.
17    pub plain: bool,
18    /// The style's colour, or its solid brush, times its alpha; white when
19    /// it names neither.
20    pub color: Color,
21    /// How far the style's baseline shift moves the glyphs down.
22    pub baseline_shift: f32,
23    /// The style's [`TextStyle::render_hash`], which keys the glyph caches
24    /// a renderer draws the text from, so no frame hashes the style again.
25    pub style_hash: u64,
26}
27
28impl TextPaint {
29    /// The paint of a text in `style` with `spans`, at `font_size`.
30    pub fn of(style: &TextStyle, spans: &[RangeStyle<SpanStyle>], font_size: f32) -> Self {
31        let span_style = &style.span_style;
32        let plain = span_style.background.is_none()
33            && span_style.shadow.is_none()
34            && span_style.brush.is_none()
35            && !matches!(
36                span_style.draw_style,
37                Some(TextDrawStyle::Stroke { width }) if width.is_finite() && width > 0.0
38            )
39            && !spans_override_foreground(spans)
40            && !has_visible_decoration(spans, style);
41        Self {
42            plain,
43            color: resolve_text_color_without_gradient_fallback(style, Color::WHITE),
44            baseline_shift: span_style
45                .baseline_shift
46                .filter(|shift| shift.is_specified())
47                .map_or(0.0, |shift| -(shift.0 * font_size)),
48            style_hash: style.render_hash(),
49        }
50    }
51}
52
53/// A text node's [`TextPaint`], set when the scene builds the node or when a
54/// renderer first asks for it. It is derived data, so two caches always
55/// compare equal.
56#[derive(Clone, Debug, Default)]
57pub struct TextPaintCache(Cell<Option<TextPaint>>);
58
59impl TextPaintCache {
60    /// A cache holding `paint`.
61    pub fn holding(paint: TextPaint) -> Self {
62        Self(Cell::new(Some(paint)))
63    }
64
65    /// The cached paint, or the one `compute` returns, which the cache then
66    /// keeps.
67    pub fn get_or(&self, compute: impl FnOnce() -> TextPaint) -> TextPaint {
68        if let Some(paint) = self.0.get() {
69            return paint;
70        }
71        let paint = compute();
72        self.0.set(Some(paint));
73        paint
74    }
75}
76
77impl PartialEq for TextPaintCache {
78    fn eq(&self, _other: &Self) -> bool {
79        true
80    }
81}
82
83/// The text colour a style names, its solid brush's colour, or `default`,
84/// times the style's alpha.
85pub fn resolve_text_color_without_gradient_fallback(
86    text_style: &TextStyle,
87    default: Color,
88) -> Color {
89    let mut color = text_style
90        .span_style
91        .color
92        .or(match text_style.span_style.brush.as_ref() {
93            Some(Brush::Solid(color)) => Some(*color),
94            _ => None,
95        })
96        .unwrap_or(default);
97    if let Some(alpha) = text_style.span_style.alpha {
98        color.3 *= alpha.clamp(0.0, 1.0);
99    }
100    color
101}
102
103fn span_has_foreground_override(span_style: &SpanStyle) -> bool {
104    matches!(
105        span_style.brush.as_ref(),
106        Some(
107            Brush::LinearGradient { .. }
108                | Brush::RadialGradient { .. }
109                | Brush::SweepGradient { .. }
110        )
111    ) || span_style.alpha.is_some()
112        || span_style.draw_style.is_some()
113}
114
115/// Whether a span paints its range with a gradient, an alpha or a draw
116/// style of its own.
117pub fn spans_override_foreground(spans: &[RangeStyle<SpanStyle>]) -> bool {
118    spans
119        .iter()
120        .any(|span| span_has_foreground_override(&span.item))
121}
122
123/// Whether a span gives its range a colour or a solid brush of its own.
124pub fn spans_override_foreground_color(spans: &[RangeStyle<SpanStyle>]) -> bool {
125    spans
126        .iter()
127        .any(|span| span.item.color.is_some() || matches!(span.item.brush, Some(Brush::Solid(_))))
128}
129
130/// Whether the style or a span draws an underline or a line-through.
131pub fn has_visible_decoration(spans: &[RangeStyle<SpanStyle>], global_style: &TextStyle) -> bool {
132    let visible = |decoration: Option<TextDecoration>| {
133        decoration.is_some_and(|decoration| decoration != TextDecoration::NONE)
134    };
135    visible(global_style.span_style.text_decoration)
136        || spans.iter().any(|span| visible(span.item.text_decoration))
137}