Skip to main content

sim_logic/text/
session.rs

1//! Caller-owned shaping state; labels remain independent immutable snapshots.
2
3use sim_engine::{ShapedLine, TextShapingSession};
4
5use super::{TextError, TextFont};
6
7/// Reusable CPU shaping state borrowed from one application font registration.
8///
9/// Create with [`TextFont::shaping_session`], then use
10/// [`super::ScreenTextVisual::new_with_session`] or
11/// [`super::ScreenTextVisual::set_text_with_session`]. Each successful changed
12/// label owns new UTF-8/glyph storage so old clones and published frames remain
13/// immutable. Only parsed shaping state and one property-matched plan are reused;
14/// this does not promise allocation-free changing labels.
15///
16/// The font, logical size, direction and work limits cannot change in a session.
17/// Raster DPI is 1.0 for canonical labels. Desktop DPI rebuilds are separate.
18/// This object does not own the font, create a GPU resource, or use global state.
19pub struct TextPreparationSession<'font> {
20    font: &'font TextFont,
21    engine: TextShapingSession<'font>,
22}
23
24impl<'font> TextPreparationSession<'font> {
25    pub(super) fn new(font: &'font TextFont) -> Result<Self, TextError> {
26        let settings = font.settings();
27        Ok(Self {
28            font,
29            engine: TextShapingSession::new(
30                font.face(),
31                settings.style(1.0)?,
32                settings.layout_budget(),
33            )?,
34        })
35    }
36
37    /// Returns the exact borrowed application registration, not just its source bytes.
38    pub const fn font(&self) -> &TextFont {
39        self.font
40    }
41
42    /// Returns Engine-owned scratch capacity bytes, excluding returned labels,
43    /// source font, and dependency-owned parsed face/plan/buffer allocations.
44    pub fn allocation_bytes(&self) -> usize {
45        self.engine.allocation_bytes()
46    }
47
48    /// Returns the number of retained property-matched plans, always zero or one.
49    pub fn cached_plan_count(&self) -> usize {
50        self.engine.cached_plan_count()
51    }
52
53    /// Releases shaping scratch and the cached plan without invalidating labels.
54    /// The borrowed parsed font face remains available for subsequent work.
55    pub fn clear_scratch(&mut self) {
56        self.engine.clear_scratch();
57    }
58
59    pub(super) fn shape_line(&mut self, text: &str) -> Result<ShapedLine, TextError> {
60        Ok(self.engine.shape_line(text)?)
61    }
62}