Skip to main content

sim_engine/text/font/
config.rs

1use crate::{LogicalPixels, PhysicalPerLogical};
2
3/// Resource whose explicit font or layout limit was exceeded.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum FontBudgetResource {
6    /// Capacity of the owned source-font byte vector.
7    FontBytes,
8    /// Glyph entries declared by the font.
9    FontGlyphs,
10    /// UTF-8 bytes submitted for one line, checked before shaping.
11    TextBytes,
12    /// Shaped output glyphs, checked after dependency shaping.
13    ShapedGlyphs,
14    /// Pixel cells in one glyph's physical coverage bitmap.
15    GlyphPixels,
16    /// Outline commands in one glyph, counted before outline/raster allocation.
17    OutlineSegments,
18}
19
20/// Explicit loading, shaping or rasterization failure.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum FontError {
23    /// Invalid, unsupported or inconsistent TrueType/OpenType source.
24    InvalidFont,
25    /// A source or layout resource exceeded its configured limit.
26    BudgetExceeded {
27        /// Rejected resource category.
28        resource: FontBudgetResource,
29        /// Required elements or bytes.
30        required: usize,
31        /// Configured maximum.
32        limit: usize,
33    },
34    /// Logical em size and DPI produce non-normal or overflowing physical size.
35    InvalidScale,
36    /// Single-line shaping does not accept control characters or line separators.
37    UnsupportedText {
38        /// UTF-8 byte offset of the unsupported character.
39        byte_index: usize,
40    },
41    /// The selected font has no glyph; this API never silently selects a fallback.
42    MissingGlyph {
43        /// UTF-8 byte offset of the missing cluster.
44        byte_index: usize,
45    },
46    /// Raster input is outside this font's glyph table.
47    InvalidGlyph {
48        /// Rejected font-local glyph identifier.
49        glyph_id: u16,
50    },
51    /// A glyph requires color/SVG/bitmap presentation rather than this outline path.
52    UnsupportedGlyph {
53        /// Font-local identifier requiring an unsupported glyph representation.
54        glyph_id: u16,
55    },
56    /// Shaped positions, outline bounds or raster arithmetic are not representable.
57    InvalidGeometry,
58    /// A library-owned vector could not be reserved.
59    AllocationFailed {
60        /// Requested payload or metadata allocation size.
61        requested_bytes: usize,
62    },
63}
64
65impl std::fmt::Display for FontError {
66    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        match self {
68            Self::InvalidFont => formatter.write_str("invalid or unsupported outline font"),
69            Self::BudgetExceeded {
70                resource,
71                required,
72                limit,
73            } => write!(
74                formatter,
75                "font {resource:?} requires {required}, limit is {limit}"
76            ),
77            Self::InvalidScale => formatter.write_str("invalid physical font scale"),
78            Self::UnsupportedText { byte_index } => write!(
79                formatter,
80                "unsupported single-line character at UTF-8 byte {byte_index}"
81            ),
82            Self::MissingGlyph { byte_index } => write!(
83                formatter,
84                "font has no glyph for UTF-8 cluster at byte {byte_index}"
85            ),
86            Self::InvalidGlyph { glyph_id } => {
87                write!(formatter, "invalid font glyph id {glyph_id}")
88            }
89            Self::UnsupportedGlyph { glyph_id } => write!(
90                formatter,
91                "font glyph {glyph_id} requires unsupported color or bitmap presentation"
92            ),
93            Self::InvalidGeometry => {
94                formatter.write_str("font geometry is not finite or representable")
95            }
96            Self::AllocationFailed { requested_bytes } => write!(
97                formatter,
98                "font allocation failed for {requested_bytes} bytes"
99            ),
100        }
101    }
102}
103
104impl std::error::Error for FontError {}
105
106/// Limits checked before taking ownership of a parsed font.
107/// Parser-owned metadata and allocator overhead are not included in source bytes.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct FontBudget {
110    max_font_bytes: usize,
111    max_font_glyphs: usize,
112}
113
114impl FontBudget {
115    /// Creates exact limits. Zero is valid and rejects nonempty resources.
116    pub const fn new(max_font_bytes: usize, max_font_glyphs: usize) -> Self {
117        Self {
118            max_font_bytes,
119            max_font_glyphs,
120        }
121    }
122    /// Maximum source Vec capacity in bytes, not merely its initialized length.
123    pub const fn max_font_bytes(self) -> usize {
124        self.max_font_bytes
125    }
126    /// Maximum number of glyph entries in the selected font face.
127    pub const fn max_font_glyphs(self) -> usize {
128        self.max_font_glyphs
129    }
130}
131
132impl Default for FontBudget {
133    fn default() -> Self {
134        Self::new(8 * 1024 * 1024, 65_535)
135    }
136}
137
138/// Per-line and per-glyph work limits.
139///
140/// UTF-8 input is bounded before rustybuzz runs; its output is checked before
141/// library-owned glyph allocation. Dependency parser/shaper allocations are
142/// not allocation-fallible through this API. Raster pixel and outline limits
143/// are checked before ab_glyph allocates its pixel scratch (roughly four bytes
144/// per pixel). These are not an OS OOM or hostile-font execution-time sandbox.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct TextLayoutBudget {
147    max_text_bytes: usize,
148    max_shaped_glyphs: usize,
149    max_glyph_pixels: usize,
150    max_outline_segments: usize,
151}
152
153impl TextLayoutBudget {
154    /// Creates exact limits; raster limits apply independently to each glyph.
155    pub const fn new(
156        text_bytes: usize,
157        shaped_glyphs: usize,
158        glyph_pixels: usize,
159        outline_segments: usize,
160    ) -> Self {
161        Self {
162            max_text_bytes: text_bytes,
163            max_shaped_glyphs: shaped_glyphs,
164            max_glyph_pixels: glyph_pixels,
165            max_outline_segments: outline_segments,
166        }
167    }
168    /// Maximum UTF-8 source-line length in bytes.
169    pub const fn max_text_bytes(self) -> usize {
170        self.max_text_bytes
171    }
172    /// Maximum shaped output glyph count.
173    pub const fn max_shaped_glyphs(self) -> usize {
174        self.max_shaped_glyphs
175    }
176    /// Maximum coverage pixels in one rasterized glyph.
177    pub const fn max_glyph_pixels(self) -> usize {
178        self.max_glyph_pixels
179    }
180    /// Maximum outline commands per glyph, including moves and closes.
181    pub const fn max_outline_segments(self) -> usize {
182        self.max_outline_segments
183    }
184}
185
186impl Default for TextLayoutBudget {
187    fn default() -> Self {
188        Self::new(16 * 1024, 16 * 1024, 1024 * 1024, 16 * 1024)
189    }
190}
191
192/// Horizontal shaping direction for one single-script directional run.
193/// This does not perform Unicode bidi paragraph segmentation.
194#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
195pub enum TextDirection {
196    /// Infer direction and script from this line's first strong character.
197    #[default]
198    Auto,
199    /// Explicit left-to-right shaping.
200    Ltr,
201    /// Explicit right-to-left shaping; glyph ordering follows rustybuzz.
202    Rtl,
203}
204
205/// Immutable logical em size and raster DPI, independent of text color/placement.
206#[derive(Debug, Clone, Copy, PartialEq)]
207pub struct TextStyle {
208    logical_em_size: LogicalPixels,
209    scale: PhysicalPerLogical,
210    direction: TextDirection,
211}
212
213impl TextStyle {
214    /// Creates a logical-pixel em size and physical-pixels-per-logical-pixel scale.
215    /// Rejects an overflowing or subnormal physical em size.
216    pub fn new(
217        logical_em_size: LogicalPixels,
218        scale: PhysicalPerLogical,
219    ) -> Result<Self, FontError> {
220        let physical = logical_em_size.get() * scale.get();
221        if !physical.is_normal() || physical <= 0.0 {
222            return Err(FontError::InvalidScale);
223        }
224        Ok(Self {
225            logical_em_size,
226            scale,
227            direction: TextDirection::Auto,
228        })
229    }
230    /// Selects shaping direction without changing em size or raster DPI.
231    pub const fn with_direction(mut self, direction: TextDirection) -> Self {
232        self.direction = direction;
233        self
234    }
235    /// Logical pixels per em; not font ascent-minus-descent height.
236    pub const fn logical_em_size(self) -> LogicalPixels {
237        self.logical_em_size
238    }
239    /// Physical pixels per logical pixel used for glyph rasterization.
240    pub const fn scale(self) -> PhysicalPerLogical {
241        self.scale
242    }
243    /// Requested horizontal shaping direction.
244    pub const fn direction(self) -> TextDirection {
245        self.direction
246    }
247    /// Physical pixels per em, validated at construction.
248    pub fn physical_em_size(self) -> f32 {
249        self.logical_em_size.get() * self.scale.get()
250    }
251}
252
253pub(super) fn check(
254    resource: FontBudgetResource,
255    required: usize,
256    limit: usize,
257) -> Result<(), FontError> {
258    if required > limit {
259        Err(FontError::BudgetExceeded {
260            resource,
261            required,
262            limit,
263        })
264    } else {
265        Ok(())
266    }
267}
268
269pub(super) fn reserve<T>(values: &mut Vec<T>, count: usize) -> Result<(), FontError> {
270    let requested_bytes = count
271        .checked_mul(std::mem::size_of::<T>())
272        .ok_or(FontError::InvalidGeometry)?;
273    values
274        .try_reserve_exact(count)
275        .map_err(|_| FontError::AllocationFailed { requested_bytes })
276}