Skip to main content

sim_engine/text/font/
session.rs

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