Skip to main content

sim_logic/text/
font.rs

1use std::{
2    fmt,
3    hash::{Hash, Hasher},
4    sync::Arc,
5};
6
7use sim_engine::FontFace;
8
9use crate::identity::ApplicationId;
10
11use super::{TextError, TextLimits, TextPreparationSession, TextSettings};
12
13/// Opaque handle to one application-owned font and immutable size configuration.
14///
15/// Cloning shares parsed font bytes and settings without duplicating them.
16/// Equal registrations still issue different identities. A handle survives
17/// World replacement within its issuing application, but is not a file path,
18/// persistent key, or GPU resource. Foreign handles are rejected by extraction.
19/// Keeping a clone after application shutdown retains its shared font bytes.
20#[derive(Clone)]
21pub struct TextFont {
22    application: ApplicationId,
23    slot: usize,
24    data: Arc<FontData>,
25}
26
27#[derive(Debug)]
28struct FontData {
29    face: FontFace,
30    face_slot: usize,
31    settings: TextSettings,
32}
33
34impl TextFont {
35    /// Reports shared parsed face/source storage, independent of size/style identity.
36    /// Equal file contents loaded separately are not treated as shared storage.
37    pub fn shares_face_with(&self, other: &Self) -> bool {
38        self.application == other.application && self.data.face_slot == other.data.face_slot
39    }
40    /// Returns immutable logical size, shaping policy, and preparation budgets.
41    pub fn settings(&self) -> TextSettings {
42        self.data.settings
43    }
44
45    /// Returns the referenced source-font Vec capacity in bytes. Shared styles
46    /// report the same source; application accounting charges that source once.
47    /// Parsed dependency metadata and allocator overhead are excluded.
48    pub fn font_bytes(&self) -> usize {
49        self.data.face.allocation_bytes()
50    }
51
52    /// Borrows this registration for reusable CPU label shaping at logical scale 1.0.
53    ///
54    /// The caller owns the session lifetime; no global cache, interior lock or
55    /// self-referencing component is created. This parses shaping state but does
56    /// not allocate an atlas or GPU resource. Font/layout limits stay fixed.
57    pub fn shaping_session(&self) -> Result<TextPreparationSession<'_>, TextError> {
58        TextPreparationSession::new(self)
59    }
60
61    pub(crate) fn face(&self) -> &FontFace {
62        &self.data.face
63    }
64
65    #[cfg(any(all(feature = "desktop", feature = "text"), test))]
66    pub(crate) const fn slot(&self) -> usize {
67        self.slot
68    }
69}
70
71impl fmt::Debug for TextFont {
72    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
73        // Never dump parsed font internals or hundreds of kilobytes of source
74        // data into a visual's error report.
75        formatter
76            .debug_struct("TextFont")
77            .field("application", &self.application)
78            .field("slot", &self.slot)
79            .finish_non_exhaustive()
80    }
81}
82
83impl PartialEq for TextFont {
84    fn eq(&self, other: &Self) -> bool {
85        self.application == other.application && self.slot == other.slot
86    }
87}
88
89impl Eq for TextFont {}
90
91impl Hash for TextFont {
92    fn hash<H: Hasher>(&self, state: &mut H) {
93        self.application.hash(state);
94        self.slot.hash(state);
95    }
96}
97
98#[derive(Debug)]
99pub(crate) struct TextRegistry {
100    application: ApplicationId,
101    limits: TextLimits,
102    fonts: Vec<TextFont>,
103    font_bytes: usize,
104}
105
106impl TextRegistry {
107    pub(crate) const fn new(application: ApplicationId, limits: TextLimits) -> Self {
108        Self {
109            application,
110            limits,
111            fonts: Vec::new(),
112            font_bytes: 0,
113        }
114    }
115
116    pub(crate) fn register(
117        &mut self,
118        bytes: Vec<u8>,
119        settings: TextSettings,
120    ) -> Result<TextFont, TextError> {
121        settings.style(1.0)?;
122        if self.fonts.len() >= self.limits.max_fonts() {
123            return Err(TextError::FontLimitExceeded {
124                limit: self.limits.max_fonts(),
125            });
126        }
127        let incoming = bytes.capacity();
128        if incoming > self.limits.max_font_bytes().saturating_sub(self.font_bytes) {
129            return Err(TextError::FontByteLimitExceeded {
130                limit: self.limits.max_font_bytes(),
131                retained: self.font_bytes,
132                incoming,
133            });
134        }
135        let face = FontFace::from_bytes(bytes, settings.font_budget())?;
136        self.fonts
137            .try_reserve_exact(1)
138            .map_err(|source| TextError::AllocationFailed { source })?;
139        let font = TextFont {
140            application: self.application,
141            slot: self.fonts.len(),
142            data: Arc::new(FontData {
143                face,
144                settings,
145                face_slot: self.fonts.len(),
146            }),
147        };
148        self.font_bytes += incoming;
149        self.fonts.push(font.clone());
150        Ok(font)
151    }
152
153    pub(crate) fn register_style(
154        &mut self,
155        source: &TextFont,
156        settings: TextSettings,
157    ) -> Result<TextFont, TextError> {
158        if !self.contains(source) {
159            return Err(TextError::ForeignFont);
160        }
161        settings.style(1.0)?;
162        if self.fonts.len() >= self.limits.max_fonts() {
163            return Err(TextError::FontLimitExceeded {
164                limit: self.limits.max_fonts(),
165            });
166        }
167        let face = source.face();
168        for (resource, requested, limit) in [
169            (
170                sim_engine::FontBudgetResource::FontBytes,
171                face.allocation_bytes(),
172                settings.font_budget().max_font_bytes(),
173            ),
174            (
175                sim_engine::FontBudgetResource::FontGlyphs,
176                face.glyph_count(),
177                settings.font_budget().max_font_glyphs(),
178            ),
179        ] {
180            if requested > limit {
181                return Err(sim_engine::FontError::BudgetExceeded {
182                    resource,
183                    required: requested,
184                    limit,
185                }
186                .into());
187            }
188        }
189        self.fonts
190            .try_reserve_exact(1)
191            .map_err(|source| TextError::AllocationFailed { source })?;
192        let font = TextFont {
193            application: self.application,
194            slot: self.fonts.len(),
195            data: Arc::new(FontData {
196                face: face.clone(),
197                settings,
198                face_slot: source.data.face_slot,
199            }),
200        };
201        self.fonts.push(font.clone());
202        // Engine's FontFace clone shares its parsed face and original byte Vec.
203        // Charge neither source bytes nor parsing a second time; atlases remain per style.
204        Ok(font)
205    }
206
207    pub(crate) fn contains(&self, font: &TextFont) -> bool {
208        font.application == self.application
209            && self
210                .fonts
211                .get(font.slot)
212                .is_some_and(|stored| stored == font && Arc::ptr_eq(&stored.data, &font.data))
213    }
214
215    pub(crate) fn len(&self) -> usize {
216        self.fonts.len()
217    }
218
219    pub(crate) const fn font_bytes(&self) -> usize {
220        self.font_bytes
221    }
222}