Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/
plotter_text_cache.rs

1//! Caller-supplied native outline-font resources for plotter producers.
2//!
3//! Core never discovers platform fonts. Callers bind one exact KiCad
4//! face/style request to deterministic font bytes and a complete shaping
5//! template; the accepted hinted layout/cache engine validates the declared
6//! font identity and applies every caller-owned work ceiling.
7
8use crate::sexpr::{Error, ErrorKind, ErrorPhase, Position};
9use crate::{
10    TextBlockLayoutRequest, TextHorizontalAlignment, TextLayoutRequest, TextRenderCache,
11    TextRenderCacheErrorKind, TextVerticalAlignment, generate_text_render_cache_a0,
12    generate_text_render_cache_block_hinted_a0, layout_text_block_hinted_a0,
13    linebreak_text_block_hinted_a0,
14};
15use cad_text_realization::ShapingInput;
16use sha2::{Digest, Sha256};
17use std::cell::Cell;
18use std::cmp::Ordering;
19
20/// One deterministic font/style selection supplied outside a KiCad source.
21#[derive(Clone, Debug)]
22pub struct PlotterTextFont<'a> {
23    pub face: &'a str,
24    pub bold: bool,
25    pub italic: bool,
26    pub font_bytes: &'a [u8],
27    /// Complete shaping context. `text` is replaced by each carrier's
28    /// resolved text; all other fields, including direction/script/language,
29    /// scale, features, face index, variations, ID, and digest, are retained.
30    pub shaping: ShapingInput,
31    pub fake_bold: bool,
32    pub fake_italic: bool,
33}
34
35/// KiCad's outline flattening error in internal face units, the default for
36/// [`PlotterTextCacheResources::max_error`].
37pub const PLOTTER_TEXT_MAX_ERROR: f64 = 2.0;
38
39/// Read-only font/cache generation resources shared across plotter carriers.
40#[derive(Clone, Copy, Debug)]
41pub struct PlotterTextCacheResources<'a> {
42    pub fonts: &'a [PlotterTextFont<'a>],
43    /// KiCad outline flattening error in internal face units.
44    pub max_error: f64,
45}
46
47/// Per-document work state over immutable caller-supplied font resources.
48pub(crate) struct PlotterTextCacheSession<'a> {
49    resources: &'a PlotterTextCacheResources<'a>,
50    hash_bytes: Cell<usize>,
51}
52
53/// Carrier layout facts passed to the neutral native cache bridge.
54#[derive(Clone, Copy, Debug)]
55pub(crate) struct PlotterTextLayout<'a> {
56    pub text: &'a str,
57    pub face: &'a str,
58    pub bold: bool,
59    pub italic: bool,
60    pub size_x: f64,
61    pub size_y: f64,
62    pub position_x: f64,
63    pub position_y: f64,
64    pub angle_degrees: f64,
65    pub mirrored: bool,
66    pub horizontal_alignment: TextHorizontalAlignment,
67    pub vertical_alignment: TextVerticalAlignment,
68    pub line_spacing: f64,
69    pub stroke_width: f64,
70}
71
72/// Deterministic outline-font dimensions in the same coordinate units as the
73/// corresponding [`PlotterTextLayout`].
74#[derive(Clone, Debug, PartialEq)]
75pub(crate) struct PlotterTextMetrics {
76    pub width: f64,
77    pub height: f64,
78    /// KiCad/FreeType face ascender plus descender after its high-resolution
79    /// metric grid is reduced to schematic millimetres.
80    pub line_height: f64,
81    pub line_widths: Vec<f64>,
82}
83
84impl PlotterTextCacheResources<'_> {
85    pub(crate) fn validate(&self) -> Result<(), Error> {
86        let mut retained = 0usize;
87        for (index, font) in self.fonts.iter().enumerate() {
88            let metadata_bytes = shaping_metadata_bytes(&font.shaping)?;
89            retained = validate_font(self, font, index, metadata_bytes, retained)?;
90        }
91        Ok(())
92    }
93
94    pub(crate) fn linebreak(
95        &self,
96        layout: PlotterTextLayout<'_>,
97        column_width: f64,
98    ) -> Result<String, Error> {
99        let (font, shaping) = self.selection_and_shaping(layout)?;
100        linebreak_text_block_hinted_a0(
101            font.font_bytes,
102            block_request(
103                layout,
104                &shaping,
105                self.max_error,
106                font.fake_bold,
107                font.fake_italic,
108            ),
109            column_width,
110        )
111        .map_err(text_pipeline_error)
112    }
113
114    pub(crate) fn generate(
115        &self,
116        layout: PlotterTextLayout<'_>,
117        _max_retained_points: usize,
118        _max_polygons: usize,
119        _max_contours: usize,
120    ) -> Result<TextRenderCache, Error> {
121        let (font, shaping) = self.selection_and_shaping(layout)?;
122        generate_text_render_cache_block_hinted_a0(
123            font.font_bytes,
124            block_request(
125                layout,
126                &shaping,
127                self.max_error,
128                font.fake_bold,
129                font.fake_italic,
130            ),
131        )
132        .map_err(|error| match error.kind {
133            TextRenderCacheErrorKind::ResourceLimit => resource(error.message),
134            _ => invalid(error.message),
135        })
136    }
137
138    pub(crate) fn measure(
139        &self,
140        layout: PlotterTextLayout<'_>,
141    ) -> Result<PlotterTextMetrics, Error> {
142        let (font, shaping) = self.selection_and_shaping(layout)?;
143        let output = layout_text_block_hinted_a0(
144            font.font_bytes,
145            block_request(
146                layout,
147                &shaping,
148                self.max_error,
149                font.fake_bold,
150                font.fake_italic,
151            ),
152        )
153        .map_err(|error| match error.kind {
154            crate::TextContourErrorKind::ResourceLimit => resource(error.message),
155            _ => invalid(error.message),
156        })?;
157        Ok(PlotterTextMetrics {
158            width: output.width,
159            height: output.height,
160            line_height: hinted_line_height(font, layout)?,
161            line_widths: output.line_widths,
162        })
163    }
164
165    fn selection_and_shaping(
166        &self,
167        layout: PlotterTextLayout<'_>,
168    ) -> Result<(&PlotterTextFont<'_>, ShapingInput), Error> {
169        let font = self.selection(layout)?;
170        let mut shaping = font.shaping.clone();
171        shaping.text = layout.text.to_owned();
172        Ok((font, shaping))
173    }
174
175    fn selection(&self, layout: PlotterTextLayout<'_>) -> Result<&PlotterTextFont<'_>, Error> {
176        let key = (layout.face, layout.bold, layout.italic);
177        let index = self
178            .fonts
179            .binary_search_by(|font| font_key(font).cmp(&key))
180            .map_err(|_| invalid("Native plotter font selection is missing"))?;
181        Ok(&self.fonts[index])
182    }
183}
184
185fn hinted_line_height(
186    font: &PlotterTextFont<'_>,
187    layout: PlotterTextLayout<'_>,
188) -> Result<f64, Error> {
189    let face = ttf_parser::Face::parse(font.font_bytes, font.shaping.face_index)
190        .map_err(|_| invalid("Native plotter font vertical metrics are invalid"))?;
191    let units_per_em = f64::from(face.units_per_em());
192    let hinted = |metric: i16| {
193        // The Python authority requests a 1433/64 point face at 1152 dpi,
194        // then reduces FreeType's 26.6 metrics by 16. The resulting values
195        // occupy a four-unit grid on KiCad's 1433-unit outline face.
196        ((f64::from(metric).abs() * cad_text_realization::OUTLINE_FACE_SCALER / units_per_em / 4.0)
197            .ceil())
198            * 4.0
199    };
200    let size_y_iu = (layout.size_y * 10_000.0).round_ties_even();
201    let scale =
202        size_y_iu / cad_text_realization::OUTLINE_FACE_SCALER * crate::KICAD_OUTLINE_EM_PER_SIZE;
203    let height_iu =
204        (hinted(face.ascender()) * scale) as i64 + (hinted(face.descender()) * scale) as i64;
205    Ok(height_iu as f64 / 10_000.0)
206}
207
208impl<'a> PlotterTextCacheSession<'a> {
209    pub(crate) fn new(resources: &'a PlotterTextCacheResources<'a>) -> Result<Self, Error> {
210        resources.validate()?;
211        let validated_hash_bytes = total_font_bytes(resources)?;
212        Ok(Self {
213            resources,
214            hash_bytes: Cell::new(validated_hash_bytes),
215        })
216    }
217
218    pub(crate) fn linebreak(
219        &self,
220        layout: PlotterTextLayout<'_>,
221        column_width: f64,
222    ) -> Result<String, Error> {
223        if column_width.is_finite()
224            && column_width > 0.0
225            && !layout.text.is_empty()
226            && layout.text.contains(' ')
227        {
228            self.charge_session_hashes(layout)?;
229        }
230        self.resources.linebreak(layout, column_width)
231    }
232
233    pub(crate) fn generate(
234        &self,
235        layout: PlotterTextLayout<'_>,
236        max_retained_points: usize,
237        max_polygons: usize,
238        max_contours: usize,
239    ) -> Result<TextRenderCache, Error> {
240        self.charge_session_hashes(layout)?;
241        self.resources
242            .generate(layout, max_retained_points, max_polygons, max_contours)
243    }
244
245    pub(crate) fn generate_single_line_unhinted(
246        &self,
247        layout: PlotterTextLayout<'_>,
248        _max_retained_points: usize,
249        _max_polygons: usize,
250        _max_contours: usize,
251    ) -> Result<TextRenderCache, Error> {
252        self.charge_session_hashes(layout)?;
253        let (font, shaping) = self.resources.selection_and_shaping(layout)?;
254        generate_text_render_cache_a0(
255            font.font_bytes,
256            TextLayoutRequest {
257                shaping: &shaping,
258                em_x: layout.size_x * crate::KICAD_OUTLINE_EM_PER_SIZE,
259                em_y: layout.size_y * crate::KICAD_OUTLINE_EM_PER_SIZE,
260                alignment_height: layout.size_y,
261                position_x: layout.position_x,
262                position_y: layout.position_y,
263                angle_degrees: layout.angle_degrees,
264                mirrored: layout.mirrored,
265                horizontal_alignment: layout.horizontal_alignment,
266                vertical_alignment: layout.vertical_alignment,
267                max_error: self.resources.max_error,
268            },
269        )
270        .map_err(|error| match error.kind {
271            TextRenderCacheErrorKind::ResourceLimit => resource(error.message),
272            _ => invalid(error.message),
273        })
274    }
275
276    pub(crate) fn measure(
277        &self,
278        layout: PlotterTextLayout<'_>,
279    ) -> Result<PlotterTextMetrics, Error> {
280        self.charge_session_hashes(layout)?;
281        self.resources.measure(layout)
282    }
283
284    fn charge_session_hashes(&self, layout: PlotterTextLayout<'_>) -> Result<(), Error> {
285        let font = self.resources.selection(layout)?;
286        let passes = 2 + usize::from(layout.text.contains("_{") || layout.text.contains("^{"));
287        let amount = font
288            .font_bytes
289            .len()
290            .checked_mul(passes)
291            .ok_or_else(|| resource("Native plotter font hash work overflowed"))?;
292        let next = self
293            .hash_bytes
294            .get()
295            .checked_add(amount)
296            .ok_or_else(|| resource("Native plotter font hash work exceeds max_hash_bytes"))?;
297        self.hash_bytes.set(next);
298        Ok(())
299    }
300}
301
302fn total_font_bytes(resources: &PlotterTextCacheResources<'_>) -> Result<usize, Error> {
303    resources
304        .fonts
305        .iter()
306        .try_fold(0usize, |total, font| {
307            total.checked_add(font.font_bytes.len())
308        })
309        .ok_or_else(|| resource("Native plotter font byte count overflowed"))
310}
311
312fn validate_font(
313    resources: &PlotterTextCacheResources<'_>,
314    font: &PlotterTextFont<'_>,
315    index: usize,
316    metadata_bytes: usize,
317    retained: usize,
318) -> Result<usize, Error> {
319    if index > 0 && font_key(&resources.fonts[index - 1]).cmp(&font_key(font)) != Ordering::Less {
320        return Err(invalid(
321            "Native plotter font selection keys must be strictly sorted and unique",
322        ));
323    }
324    validate_font_identity(font)?;
325    retained
326        .checked_add(font.face.len())
327        .and_then(|value| value.checked_add(font.shaping.text.len()))
328        .and_then(|value| value.checked_add(metadata_bytes))
329        .ok_or_else(|| resource("Native plotter font selections exceed max_selection_bytes"))
330}
331
332fn validate_font_identity(font: &PlotterTextFont<'_>) -> Result<(), Error> {
333    if cad_text_realization::validate_shaping_input(&font.shaping).is_err() {
334        return Err(invalid("Native plotter shaping template is invalid"));
335    }
336    if font
337        .shaping
338        .features
339        .iter()
340        .any(|feature| feature.start != 0 || feature.end != u32::MAX)
341    {
342        return Err(invalid(
343            "Native plotter shaping templates require global feature ranges",
344        ));
345    }
346    const HEX: &[u8; 16] = b"0123456789abcdef";
347    let matches = Sha256::digest(font.font_bytes)
348        .iter()
349        .zip(font.shaping.font_sha256.0.as_bytes().as_chunks::<2>().0)
350        .all(|(byte, pair)| *pair == [HEX[(byte >> 4) as usize], HEX[(byte & 0x0f) as usize]]);
351    if !matches {
352        return Err(invalid(
353            "Native plotter font buffer does not match its declared SHA-256",
354        ));
355    }
356    Ok(())
357}
358
359fn font_key<'a>(font: &'a PlotterTextFont<'_>) -> (&'a str, bool, bool) {
360    (font.face, font.bold, font.italic)
361}
362
363fn shaping_metadata_bytes(input: &ShapingInput) -> Result<usize, Error> {
364    let mut total = input.font_id.len().checked_add(input.font_sha256.0.len());
365    total = total.and_then(|value| value.checked_add(input.text_index_unit.len()));
366    total =
367        total.and_then(|value| value.checked_add(input.language.as_deref().map_or(0, str::len)));
368    total = total.and_then(|value| {
369        value.checked_add(input.script.as_ref().map_or(0, |script| script.0.len()))
370    });
371    for feature in &input.features {
372        total = total.and_then(|value| {
373            value
374                .checked_add(feature.tag.0.len())
375                .and_then(|value| value.checked_add(std::mem::size_of_val(feature)))
376        });
377    }
378    for variation in &input.variations {
379        total = total.and_then(|value| {
380            value
381                .checked_add(variation.axis.0.len())
382                .and_then(|value| value.checked_add(std::mem::size_of_val(variation)))
383        });
384    }
385    total.ok_or_else(|| resource("Native plotter shaping metadata byte count overflowed"))
386}
387
388fn block_request<'a>(
389    layout: PlotterTextLayout<'_>,
390    shaping: &'a ShapingInput,
391    max_error: f64,
392    fake_bold: bool,
393    fake_italic: bool,
394) -> TextBlockLayoutRequest<'a> {
395    TextBlockLayoutRequest {
396        shaping,
397        size_x: layout.size_x,
398        size_y: layout.size_y,
399        position_x: layout.position_x,
400        position_y: layout.position_y,
401        angle_degrees: layout.angle_degrees,
402        mirrored: layout.mirrored,
403        horizontal_alignment: layout.horizontal_alignment,
404        vertical_alignment: layout.vertical_alignment,
405        line_spacing: layout.line_spacing,
406        stroke_width: layout.stroke_width,
407        max_error,
408        fake_bold,
409        fake_italic,
410    }
411}
412
413fn text_pipeline_error(error: crate::TextContourError) -> Error {
414    match error.kind {
415        crate::TextContourErrorKind::ResourceLimit => resource(error.message),
416        _ => invalid(error.message),
417    }
418}
419
420fn resource(message: &'static str) -> Error {
421    Error::at(
422        ErrorPhase::Tree,
423        ErrorKind::ResourceLimit,
424        message,
425        Position::START,
426    )
427}
428
429fn invalid(message: &'static str) -> Error {
430    Error::at(
431        ErrorPhase::Tree,
432        ErrorKind::InvalidBuildValue,
433        message,
434        Position::START,
435    )
436}