Skip to main content

serge_native_text/
lib.rs

1//! `serge-native-text` — text shaping, line breaking and measurement for
2//! native targets on `parley` (pinned, `docs/02-architecture.md` §3), with
3//! system fonts and fallback (CJK included). Shaped runs become
4//! [`ScenePrimitive::Glyphs`]; renderers rasterize the glyph outlines.
5
6// Linux: fontconfig is loaded at run time (see Cargo.toml).
7#[cfg(target_os = "linux")]
8use fontique as _;
9use std::collections::HashMap;
10use std::sync::Arc;
11
12mod glyph_run;
13
14use parley::{FontContext, FontWeight, LayoutContext, PositionedLayoutItem, StyleProperty};
15use serge_core::{FontHandle, Glyph, Point, ScenePrimitive};
16use serge_style::Color;
17
18/// The font type behind [`FontHandle`] on native targets.
19pub use parley::FontData as Font;
20
21/// A shaped run.
22#[derive(Clone, Debug)]
23pub struct Run {
24    /// The font.
25    pub font: FontHandle,
26    /// Size in logical pixels.
27    pub size: f32,
28    /// Glyphs relative to the layout's top-left corner.
29    pub glyphs: Vec<Glyph>,
30}
31
32/// A laid-out paragraph.
33#[derive(Clone, Debug, Default)]
34pub struct TextLayout {
35    /// Width of the widest line.
36    pub width: f32,
37    /// Total height.
38    pub height: f32,
39    /// The runs.
40    pub runs: Vec<Run>,
41}
42
43impl TextLayout {
44    /// The paragraph drawn with its top-left corner at `origin`.
45    pub fn primitives(
46        &self,
47        origin: Point,
48        color: Color,
49    ) -> impl Iterator<Item = ScenePrimitive> + '_ {
50        self.runs.iter().map(move |r| ScenePrimitive::Glyphs {
51            origin,
52            font: r.font.clone(),
53            size: r.size,
54            color,
55            glyphs: r.glyphs.clone(),
56        })
57    }
58}
59
60#[derive(Hash, PartialEq, Eq, Clone)]
61struct Key {
62    size: u32,
63    weight: u16,
64    max_width: Option<u32>,
65}
66
67/// Fonts, scratch space and a layout cache. One per UI thread.
68pub struct TextSystem {
69    fonts: FontContext,
70    layouts: LayoutContext<()>,
71    cache: HashMap<Box<str>, HashMap<Key, TextLayout>>,
72    cached_layouts: usize,
73    handles: HashMap<(u64, u32), FontHandle>,
74}
75
76impl Default for TextSystem {
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82impl std::fmt::Debug for TextSystem {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.debug_struct("TextSystem").finish_non_exhaustive()
85    }
86}
87
88impl TextSystem {
89    /// A text system over the platform's fonts.
90    pub fn new() -> TextSystem {
91        TextSystem {
92            fonts: FontContext::new(),
93            layouts: LayoutContext::new(),
94            cache: HashMap::new(),
95            cached_layouts: 0,
96            handles: HashMap::new(),
97        }
98    }
99
100    /// Lays out `text` (wrapped at `max_width` when given).
101    pub fn layout(
102        &mut self,
103        text: &str,
104        size: f32,
105        weight: u16,
106        max_width: Option<f32>,
107    ) -> TextLayout {
108        self.layout_ref(text, size, weight, max_width).clone()
109    }
110
111    /// Borrows the shaped paragraph until the next mutable access to the text system.
112    pub fn layout_ref(
113        &mut self,
114        text: &str,
115        size: f32,
116        weight: u16,
117        max_width: Option<f32>,
118    ) -> &TextLayout {
119        // Key on the actual line-breaking width, including its half-pixel rounding allowance.
120        let wrap = max_width.map(|w| (w.max(1.0) + 0.5).ceil());
121        let key = Key {
122            size: size.to_bits(),
123            weight,
124            max_width: wrap.map(f32::to_bits),
125        };
126        if self
127            .cache
128            .get(text)
129            .is_some_and(|styles| styles.contains_key(&key))
130        {
131            return &self.cache[text][&key];
132        }
133        if self.cached_layouts >= 2048 {
134            self.cache.clear();
135            self.cached_layouts = 0;
136        }
137        let mut b = self
138            .layouts
139            .ranged_builder(&mut self.fonts, text, 1.0, true);
140        b.push_default(StyleProperty::FontSize(size));
141        b.push_default(StyleProperty::FontWeight(FontWeight::new(f32::from(
142            weight,
143        ))));
144        // The web target's `line-height: 1.25`.
145        b.push_default(StyleProperty::LineHeight(
146            parley::LineHeight::FontSizeRelative(1.25),
147        ));
148        let mut layout: parley::Layout<()> = b.build(text);
149        layout.break_all_lines(wrap);
150        let mut runs = Vec::new();
151        for line in layout.lines() {
152            for item in line.items() {
153                if let PositionedLayoutItem::GlyphRun(g) = item {
154                    let run = g.run();
155                    let font = run.font();
156                    let handle = self
157                        .handles
158                        .entry((font.data.id(), font.index))
159                        .or_insert_with(|| FontHandle(Arc::new(font.clone())))
160                        .clone();
161                    runs.push(Run {
162                        font: handle,
163                        size: run.font_size(),
164                        glyphs: glyph_run::positioned(&g),
165                    });
166                }
167            }
168        }
169        let out = TextLayout {
170            width: layout.width(),
171            height: layout.height().max(size * 1.2),
172            runs,
173        };
174        self.cached_layouts += 1;
175        self.cache
176            .entry(text.into())
177            .or_default()
178            .entry(key)
179            .or_insert(out)
180    }
181
182    /// The size of `text` (wrapped at `max_width` when given).
183    pub fn measure(
184        &mut self,
185        text: &str,
186        size: f32,
187        weight: u16,
188        max_width: Option<f32>,
189    ) -> (f32, f32) {
190        let l = self.layout_ref(text, size, weight, max_width);
191        (l.width.ceil(), l.height.ceil())
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn wider_text_measures_wider_and_wraps() {
201        let mut t = TextSystem::new();
202        let (w1, h1) = t.measure("Count: 0", 16.0, 400, None);
203        let (w2, _) = t.measure("Count: 0 and more words here", 16.0, 400, None);
204        assert!(w1 > 0.0 && h1 > 0.0 && w2 > w1, "{w1} {w2}");
205        let (_, wrapped) = t.measure("Count: 0 and more words here", 16.0, 400, Some(60.0));
206        assert!(wrapped > h1, "wrapping adds lines");
207    }
208}