Skip to main content

sim_engine/text/font/
session.rs

1use super::{
2    FontBudgetResource, FontError, FontFace, ShapedGlyph, ShapedLine, TextDirection,
3    TextLayoutBudget, TextStyle, check, represent, reserve,
4};
5
6/// A prepared line cannot be reused with the requested font, style or limits.
7/// Kept separate from [`FontError`] so existing exhaustive matches remain valid.
8#[derive(Debug, Clone, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum ShapedLineError {
11    /// The line came from a separately loaded font, even if its bytes match.
12    FontMismatch,
13    /// Logical em size, raster DPI or requested direction differs.
14    StyleMismatch,
15    /// Input, output, allocation or geometry validation failed.
16    Font(FontError),
17}
18
19impl std::fmt::Display for ShapedLineError {
20    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        match self {
22            Self::FontMismatch => formatter.write_str("prepared text belongs to another font face"),
23            Self::StyleMismatch => formatter.write_str("prepared text uses another text style"),
24            Self::Font(error) => write!(formatter, "prepared text: {error}"),
25        }
26    }
27}
28
29impl std::error::Error for ShapedLineError {
30    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
31        match self {
32            Self::Font(error) => Some(error),
33            _ => None,
34        }
35    }
36}
37
38impl From<FontError> for ShapedLineError {
39    fn from(error: FontError) -> Self {
40        Self::Font(error)
41    }
42}
43
44#[derive(PartialEq)]
45struct PlanKey {
46    script: rustybuzz::Script,
47    direction: rustybuzz::Direction,
48    language: Option<rustybuzz::Language>,
49}
50
51/// Caller-owned reusable CPU shaping state for one borrowed font and fixed style.
52/// Available with `fonts`, without a renderer or GPU dependency.
53///
54/// The parsed rustybuzz face, one exact-property shaping plan and one buffer are
55/// reused. An inferred script/direction change replaces that single plan rather
56/// than growing a cache. Language is unspecified and OpenType features use the
57/// same defaults as [`FontFace::shape_line`]; no cross-font/global cache exists.
58///
59/// [`Self::update_line`] reuses two bounded UTF-8/glyph allocations transactionally.
60/// Input and output limits remain mandatory. Dependency-owned face/plan/buffer
61/// allocations are excluded from [`Self::allocation_bytes`]: rustybuzz does not
62/// expose their capacities or fallible allocation. These are trusted-font work
63/// limits, not an exact process-memory or hostile-font sandbox. Dependency buffer
64/// storage is dropped after a shaping failure; [`Self::clear_scratch`] releases
65/// successful-run scratch and the one cached plan on demand.
66///
67/// ```no_run
68/// use sim_engine::{FontBudget, FontFace, LogicalPixels, PhysicalPerLogical,
69///     TextLayoutBudget, TextShapingSession, TextStyle};
70///
71/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
72/// let font = FontFace::from_bytes(std::fs::read("assets/Label.ttf")?, FontBudget::default())?;
73/// let style = TextStyle::new(LogicalPixels::new(24.0)?, PhysicalPerLogical::new(1.0)?)?;
74/// let mut session = TextShapingSession::new(&font, style, TextLayoutBudget::default())?;
75/// let mut line = session.shape_line("Count: 100")?;
76/// session.update_line(&mut line, "Count: 101")?;
77/// // Hand `line` to TextAtlas2d::prepare_from_shaped when using the `text` feature.
78/// assert_eq!(line.text(), "Count: 101");
79/// # Ok(())
80/// # }
81/// ```
82pub struct TextShapingSession<'font> {
83    font: &'font FontFace,
84    face: rustybuzz::Face<'font>,
85    style: TextStyle,
86    budget: TextLayoutBudget,
87    input: rustybuzz::UnicodeBuffer,
88    plan: Option<(PlanKey, rustybuzz::ShapePlan)>,
89    glyphs: Vec<ShapedGlyph>,
90    text: String,
91    factor: f64,
92    ascent: f32,
93    descent: f32,
94    line_height: f32,
95}
96
97impl<'font> TextShapingSession<'font> {
98    /// Parses the borrowed font once and fixes style and work limits for this session.
99    /// Does not preallocate the maximum permitted line length.
100    pub fn new(
101        font: &'font FontFace,
102        style: TextStyle,
103        budget: TextLayoutBudget,
104    ) -> Result<Self, FontError> {
105        let face =
106            rustybuzz::Face::from_slice(font.font_data(), 0).ok_or(FontError::InvalidFont)?;
107        let factor = f64::from(style.logical_em_size().get()) / f64::from(face.units_per_em());
108        let ascent = represent(f64::from(face.ascender()) * factor)?;
109        let descent = represent(f64::from(face.descender()) * factor)?;
110        let line_height = represent(
111            (f64::from(face.ascender()) - f64::from(face.descender()) + f64::from(face.line_gap()))
112                * factor,
113        )?;
114        if line_height <= 0.0 {
115            return Err(FontError::InvalidFont);
116        }
117        Ok(Self {
118            font,
119            face,
120            style,
121            budget,
122            input: rustybuzz::UnicodeBuffer::new(),
123            plan: None,
124            glyphs: Vec::new(),
125            text: String::new(),
126            factor,
127            ascent,
128            descent,
129            line_height,
130        })
131    }
132
133    /// Returns the immutable style, including requested direction and raster DPI.
134    pub const fn style(&self) -> &TextStyle {
135        &self.style
136    }
137
138    /// Returns fixed per-line and per-glyph work limits.
139    pub const fn budget(&self) -> TextLayoutBudget {
140        self.budget
141    }
142
143    /// Shapes a new owned line; later updates can reuse its allocation.
144    /// Separate returned lines each own their own bounded UTF-8 and glyph vectors.
145    pub fn shape_line(&mut self, text: &str) -> Result<ShapedLine, FontError> {
146        let advance = self.shape_to_scratch(text)?;
147        Ok(ShapedLine {
148            font: self.font.clone(),
149            style: self.style,
150            text: std::mem::take(&mut self.text),
151            glyphs: std::mem::take(&mut self.glyphs),
152            advance,
153            ascent: self.ascent,
154            descent: self.descent,
155            line_height: self.line_height,
156        })
157    }
158
159    /// Replaces a compatible line atomically, returning whether its UTF-8 changed.
160    ///
161    /// Font/style and current line limits are checked even for unchanged text.
162    /// A successful change swaps the session's scratch with the previous line's
163    /// storage, allowing equal or shorter warmed lengths to avoid engine-owned
164    /// allocations. The old line's capacities must also fit this session's input
165    /// and output limits so swapping cannot import unbounded retained storage.
166    /// Any returned error preserves the old text, glyphs, metrics and allocations.
167    pub fn update_line(
168        &mut self,
169        line: &mut ShapedLine,
170        text: &str,
171    ) -> Result<bool, ShapedLineError> {
172        line.validate_for(self.font, &self.style, &self.budget)?;
173        check(
174            FontBudgetResource::TextBytes,
175            line.text.capacity(),
176            self.budget.max_text_bytes(),
177        )?;
178        check(
179            FontBudgetResource::ShapedGlyphs,
180            line.glyphs.capacity(),
181            self.budget.max_shaped_glyphs(),
182        )?;
183        if line.text == text {
184            return Ok(false);
185        }
186        let advance = self.shape_to_scratch(text)?;
187        std::mem::swap(&mut line.text, &mut self.text);
188        std::mem::swap(&mut line.glyphs, &mut self.glyphs);
189        line.advance = advance;
190        Ok(true)
191    }
192
193    /// Engine-owned scratch capacity in bytes, excluding returned lines, shared
194    /// source font and dependency-owned face/plan/buffer allocations.
195    pub fn allocation_bytes(&self) -> usize {
196        self.glyphs
197            .capacity()
198            .saturating_mul(std::mem::size_of::<ShapedGlyph>())
199            .saturating_add(self.text.capacity())
200    }
201
202    /// Number of retained plans, always zero or one regardless of strings seen.
203    pub fn cached_plan_count(&self) -> usize {
204        usize::from(self.plan.is_some())
205    }
206
207    /// Releases scratch and cached plan while preserving the borrowed parsed face.
208    /// Previously returned lines remain valid and independent of this session.
209    pub fn clear_scratch(&mut self) {
210        self.input = rustybuzz::UnicodeBuffer::new();
211        self.plan = None;
212        self.glyphs = Vec::new();
213        self.text = String::new();
214    }
215
216    fn shape_to_scratch(&mut self, text: &str) -> Result<f32, FontError> {
217        validate_text(text, self.budget)?;
218        self.input.clear();
219        self.input.push_str(text);
220        match self.style.direction() {
221            TextDirection::Auto => {}
222            TextDirection::Ltr => self.input.set_direction(rustybuzz::Direction::LeftToRight),
223            TextDirection::Rtl => self.input.set_direction(rustybuzz::Direction::RightToLeft),
224        }
225        self.input.guess_segment_properties();
226        let key = PlanKey {
227            script: self.input.script(),
228            direction: self.input.direction(),
229            language: self.input.language(),
230        };
231        if self
232            .plan
233            .as_ref()
234            .is_none_or(|(previous, _)| *previous != key)
235        {
236            let plan = rustybuzz::ShapePlan::new(
237                &self.face,
238                key.direction,
239                Some(key.script),
240                key.language.as_ref(),
241                &[],
242            );
243            self.plan = Some((key, plan));
244        }
245        let Some((_, plan)) = &self.plan else {
246            return Err(FontError::InvalidFont);
247        };
248        let output = rustybuzz::shape_with_plan(&self.face, plan, std::mem::take(&mut self.input));
249        let result = self.copy_output(text, &output);
250        // A rejected expanded output must not remain as hidden retained scratch.
251        if result.is_ok() {
252            self.input = output.clear();
253        }
254        result
255    }
256
257    fn copy_output(
258        &mut self,
259        text: &str,
260        output: &rustybuzz::GlyphBuffer,
261    ) -> Result<f32, FontError> {
262        check(
263            FontBudgetResource::ShapedGlyphs,
264            output.len(),
265            self.budget.max_shaped_glyphs(),
266        )?;
267        self.glyphs.clear();
268        reserve(&mut self.glyphs, output.len())?;
269        let mut pen_x = 0.0f64;
270        let mut pen_y = 0.0f64;
271        for (information, position) in output.glyph_infos().iter().zip(output.glyph_positions()) {
272            if information.glyph_id == 0 {
273                return Err(FontError::MissingGlyph {
274                    byte_index: information.cluster as usize,
275                });
276            }
277            self.glyphs.push(ShapedGlyph {
278                glyph_id: u16::try_from(information.glyph_id)
279                    .map_err(|_| FontError::InvalidGeometry)?,
280                logical_x: represent((pen_x + f64::from(position.x_offset)) * self.factor)?,
281                logical_y: represent(-(pen_y + f64::from(position.y_offset)) * self.factor)?,
282                cluster: information.cluster as usize,
283            });
284            pen_x += f64::from(position.x_advance);
285            pen_y += f64::from(position.y_advance);
286        }
287        let advance = represent(pen_x * self.factor)?;
288        self.text.clear();
289        self.text
290            .try_reserve_exact(text.len())
291            .map_err(|_| FontError::AllocationFailed {
292                requested_bytes: text.len(),
293            })?;
294        self.text.push_str(text);
295        Ok(advance)
296    }
297}
298
299fn validate_text(text: &str, budget: TextLayoutBudget) -> Result<(), FontError> {
300    check(
301        FontBudgetResource::TextBytes,
302        text.len(),
303        budget.max_text_bytes().min(u32::MAX as usize),
304    )?;
305    for (byte_index, character) in text.char_indices() {
306        if character.is_control() || matches!(character, '\u{2028}' | '\u{2029}') {
307            return Err(FontError::UnsupportedText { byte_index });
308        }
309    }
310    Ok(())
311}