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

cad_text_realization/
contract.rs

1//! The engine's public text contract: shaping inputs, shaped glyphs, outline
2//! commands and the primitives they carry.
3//!
4//! Plain Rust + serde. The JSON shape (field names, enum strings, refused
5//! unknown fields, optional `script`/`language`) is the one KiCad Monkey's
6//! `ShapingRecord`/`OutlineVector` schemas publish, so records written against
7//! those schemas decode into these types unchanged.
8
9use serde::{Deserialize, Serialize};
10use std::collections::HashSet;
11use std::fmt;
12
13/// Integer exactly representable as an IEEE-754 double (|value| <= 2^53 - 1),
14/// so it crosses JSON and JavaScript/WASM boundaries unchanged.
15#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
16#[serde(transparent)]
17pub struct SafeInteger(i64);
18
19impl SafeInteger {
20    /// Largest exactly representable integer.
21    pub const MAX: i64 = 9_007_199_254_740_991;
22    /// Smallest exactly representable integer.
23    pub const MIN: i64 = -Self::MAX;
24
25    pub const fn get(self) -> i64 {
26        self.0
27    }
28}
29
30impl TryFrom<i64> for SafeInteger {
31    type Error = SafeIntegerError;
32
33    fn try_from(value: i64) -> Result<Self, Self::Error> {
34        if (Self::MIN..=Self::MAX).contains(&value) {
35            Ok(Self(value))
36        } else {
37            Err(SafeIntegerError { value })
38        }
39    }
40}
41
42impl From<i32> for SafeInteger {
43    fn from(value: i32) -> Self {
44        Self(i64::from(value))
45    }
46}
47
48impl From<SafeInteger> for i64 {
49    fn from(value: SafeInteger) -> Self {
50        value.0
51    }
52}
53
54impl<'de> Deserialize<'de> for SafeInteger {
55    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
56    where
57        D: serde::Deserializer<'de>,
58    {
59        let value = i64::deserialize(deserializer)?;
60        Self::try_from(value).map_err(serde::de::Error::custom)
61    }
62}
63
64#[derive(Clone, Copy, Debug, Eq, PartialEq)]
65pub struct SafeIntegerError {
66    value: i64,
67}
68
69impl fmt::Display for SafeIntegerError {
70    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
71        write!(
72            formatter,
73            "{} is outside the safe-integer range",
74            self.value
75        )
76    }
77}
78
79impl std::error::Error for SafeIntegerError {}
80
81/// Finite float64 value, including fractional CFF/CFF2 design coordinates.
82#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
83#[serde(transparent)]
84pub struct FiniteFloat(f64);
85
86impl FiniteFloat {
87    pub const fn get(self) -> f64 {
88        self.0
89    }
90}
91
92impl TryFrom<f64> for FiniteFloat {
93    type Error = FiniteFloatError;
94
95    fn try_from(value: f64) -> Result<Self, Self::Error> {
96        if value.is_finite() {
97            Ok(Self(value))
98        } else {
99            Err(FiniteFloatError { value })
100        }
101    }
102}
103
104impl<'de> Deserialize<'de> for FiniteFloat {
105    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
106    where
107        D: serde::Deserializer<'de>,
108    {
109        let value = f64::deserialize(deserializer)?;
110        Self::try_from(value).map_err(serde::de::Error::custom)
111    }
112}
113
114#[derive(Clone, Copy, Debug, PartialEq)]
115pub struct FiniteFloatError {
116    value: f64,
117}
118
119impl fmt::Display for FiniteFloatError {
120    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
121        write!(formatter, "{} is not finite", self.value)
122    }
123}
124
125impl std::error::Error for FiniteFloatError {}
126
127/// Nonempty stable ASCII identifier for fonts and cases
128/// (`^[A-Za-z0-9][A-Za-z0-9._:-]*$`).
129#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
130#[serde(transparent)]
131pub struct StableTextId(String);
132
133impl StableTextId {
134    pub fn as_str(&self) -> &str {
135        &self.0
136    }
137}
138
139impl std::ops::Deref for StableTextId {
140    type Target = str;
141
142    fn deref(&self) -> &Self::Target {
143        self.as_str()
144    }
145}
146
147impl fmt::Display for StableTextId {
148    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149        formatter.write_str(self.as_str())
150    }
151}
152
153impl std::str::FromStr for StableTextId {
154    type Err = StableTextIdError;
155
156    fn from_str(value: &str) -> Result<Self, Self::Err> {
157        let mut bytes = value.bytes();
158        let valid = bytes
159            .next()
160            .is_some_and(|byte| byte.is_ascii_alphanumeric())
161            && bytes.all(|byte| {
162                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
163            });
164        if valid {
165            Ok(Self(value.to_owned()))
166        } else {
167            Err(StableTextIdError)
168        }
169    }
170}
171
172impl<'de> Deserialize<'de> for StableTextId {
173    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
174    where
175        D: serde::Deserializer<'de>,
176    {
177        let value = String::deserialize(deserializer)?;
178        value.parse().map_err(serde::de::Error::custom)
179    }
180}
181
182#[derive(Clone, Copy, Debug, Eq, PartialEq)]
183pub struct StableTextIdError;
184
185impl fmt::Display for StableTextIdError {
186    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
187        formatter.write_str("value is not a stable text identifier")
188    }
189}
190
191impl std::error::Error for StableTextIdError {}
192
193/// A transparent string newtype whose grammar the validators check.
194macro_rules! string_newtype {
195    ($(#[$meta:meta])* $name:ident) => {
196        $(#[$meta])*
197        #[derive(
198            Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
199        )]
200        #[serde(transparent)]
201        pub struct $name(pub String);
202
203        impl std::ops::Deref for $name {
204            type Target = String;
205
206            fn deref(&self) -> &String {
207                &self.0
208            }
209        }
210
211        impl From<$name> for String {
212            fn from(value: $name) -> Self {
213                value.0
214            }
215        }
216
217        impl From<String> for $name {
218            fn from(value: String) -> Self {
219                Self(value)
220            }
221        }
222
223        impl std::str::FromStr for $name {
224            type Err = std::convert::Infallible;
225
226            fn from_str(value: &str) -> Result<Self, Self::Err> {
227                Ok(Self(value.to_owned()))
228            }
229        }
230
231        impl fmt::Display for $name {
232            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
233                self.0.fmt(formatter)
234            }
235        }
236    };
237}
238
239string_newtype!(
240    /// Four-byte OpenType variation, feature or script tag (`^[ -~]{4}$`).
241    OpenTypeTag
242);
243string_newtype!(
244    /// Lowercase SHA-256 digest of one out-of-band font buffer (`^[0-9a-f]{64}$`).
245    Sha256Hex
246);
247
248/// Shaping direction.
249#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
250#[serde(rename_all = "snake_case")]
251pub enum TextDirection {
252    LeftToRight,
253    RightToLeft,
254    TopToBottom,
255    BottomToTop,
256}
257
258/// HarfBuzz cluster level.
259#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
260#[serde(rename_all = "snake_case")]
261pub enum ShapingClusterLevel {
262    MonotoneGraphemes,
263    MonotoneCharacters,
264    Characters,
265}
266
267/// HarfBuzz default-ignorable handling.
268#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
269#[serde(rename_all = "snake_case")]
270pub enum DefaultIgnorablePolicy {
271    Normal,
272    Preserve,
273    Remove,
274}
275
276/// Explicit HarfBuzz buffer state; no ambient library defaults are implied.
277#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
278#[serde(deny_unknown_fields)]
279pub struct ShapingBufferProperties {
280    pub beginning_of_text: bool,
281    pub cluster_level: ShapingClusterLevel,
282    pub default_ignorables: DefaultIgnorablePolicy,
283    pub do_not_insert_dotted_circle: bool,
284    pub end_of_text: bool,
285    pub produce_safe_to_insert_tatweel: bool,
286    pub produce_unsafe_to_concat: bool,
287}
288
289/// HarfBuzz-compatible feature range over half-open UTF-8 byte offsets.
290/// Non-global endpoints are UTF-8 code-point boundaries. A global range is
291/// start=0 and end=4294967295. HarfRust receives these values unchanged after
292/// `UnicodeBuffer::push_str` assigns `char_indices` clusters.
293#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
294#[serde(deny_unknown_fields)]
295pub struct ShapingFeature {
296    pub end: u32,
297    pub start: u32,
298    pub tag: OpenTypeTag,
299    pub value: u32,
300}
301
302/// One ordered OpenType variation coordinate.
303#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
304#[serde(deny_unknown_fields)]
305pub struct FontVariationCoordinate {
306    pub axis: OpenTypeTag,
307    pub value: FiniteFloat,
308}
309
310/// Complete deterministic shaping input for one run of text in one font.
311#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
312#[serde(deny_unknown_fields)]
313pub struct ShapingInput {
314    pub buffer_properties: ShapingBufferProperties,
315    pub direction: TextDirection,
316    pub face_index: u32,
317    pub features: Vec<ShapingFeature>,
318    pub font_id: StableTextId,
319    pub font_sha256: Sha256Hex,
320    /// Nonempty BCP 47 language when supplied.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub language: Option<String>,
323    /// HarfBuzz `hb_font_set_scale` x value.
324    pub scale_x: i32,
325    /// HarfBuzz `hb_font_set_scale` y value.
326    pub scale_y: i32,
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub script: Option<OpenTypeTag>,
329    pub text: String,
330    /// Always `utf8_byte_offset`: clusters and feature ranges index UTF-8 bytes.
331    pub text_index_unit: String,
332    pub variations: Vec<FontVariationCoordinate>,
333}
334
335/// One shaped glyph in logical buffer order.
336#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
337#[serde(deny_unknown_fields)]
338pub struct ShapedGlyph {
339    /// UTF-8 scalar-start byte offset into `ShapingInput.text`, as assigned by `push_str`.
340    pub cluster: u32,
341    pub glyph_id: u32,
342    pub safe_to_insert_tatweel: bool,
343    pub unsafe_to_break: bool,
344    pub unsafe_to_concat: bool,
345    pub x_advance: SafeInteger,
346    pub x_offset: SafeInteger,
347    pub y_advance: SafeInteger,
348    pub y_offset: SafeInteger,
349}
350
351/// One glyph outline command in font design units.
352///
353/// `move_to` and `line_to` share one JSON shape, so either decodes into
354/// [`OutlineCommand::MoveTo`]. The `kind` literal stays authoritative;
355/// validators read it rather than the variant.
356#[derive(Clone, Debug, PartialEq, Serialize)]
357#[serde(untagged)]
358pub enum OutlineCommand {
359    MoveTo(OutlineMoveTo),
360    LineTo(OutlineLineTo),
361    QuadTo(OutlineQuadTo),
362    CurveTo(OutlineCurveTo),
363    Close(OutlineClose),
364}
365
366impl<'de> Deserialize<'de> for OutlineCommand {
367    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
368    where
369        D: serde::Deserializer<'de>,
370    {
371        #[derive(Deserialize)]
372        #[serde(deny_unknown_fields)]
373        struct RawOutlineCommand {
374            kind: String,
375            x: Option<FiniteFloat>,
376            y: Option<FiniteFloat>,
377            control_x: Option<FiniteFloat>,
378            control_y: Option<FiniteFloat>,
379            control1_x: Option<FiniteFloat>,
380            control1_y: Option<FiniteFloat>,
381            control2_x: Option<FiniteFloat>,
382            control2_y: Option<FiniteFloat>,
383        }
384
385        let raw = RawOutlineCommand::deserialize(deserializer)?;
386        match (
387            raw.x,
388            raw.y,
389            raw.control_x,
390            raw.control_y,
391            raw.control1_x,
392            raw.control1_y,
393            raw.control2_x,
394            raw.control2_y,
395        ) {
396            (None, None, None, None, None, None, None, None) => {
397                Ok(Self::Close(OutlineClose { kind: raw.kind }))
398            }
399            (Some(x), Some(y), None, None, None, None, None, None) => {
400                Ok(Self::MoveTo(OutlineMoveTo {
401                    kind: raw.kind,
402                    x,
403                    y,
404                }))
405            }
406            (Some(x), Some(y), Some(control_x), Some(control_y), None, None, None, None) => {
407                Ok(Self::QuadTo(OutlineQuadTo {
408                    control_x,
409                    control_y,
410                    kind: raw.kind,
411                    x,
412                    y,
413                }))
414            }
415            (
416                Some(x),
417                Some(y),
418                None,
419                None,
420                Some(control1_x),
421                Some(control1_y),
422                Some(control2_x),
423                Some(control2_y),
424            ) => Ok(Self::CurveTo(OutlineCurveTo {
425                control1_x,
426                control1_y,
427                control2_x,
428                control2_y,
429                kind: raw.kind,
430                x,
431                y,
432            })),
433            _ => Err(serde::de::Error::custom(
434                "data did not match any variant of OutlineCommand",
435            )),
436        }
437    }
438}
439
440impl From<OutlineMoveTo> for OutlineCommand {
441    fn from(value: OutlineMoveTo) -> Self {
442        Self::MoveTo(value)
443    }
444}
445
446impl From<OutlineLineTo> for OutlineCommand {
447    fn from(value: OutlineLineTo) -> Self {
448        Self::LineTo(value)
449    }
450}
451
452impl From<OutlineQuadTo> for OutlineCommand {
453    fn from(value: OutlineQuadTo) -> Self {
454        Self::QuadTo(value)
455    }
456}
457
458impl From<OutlineCurveTo> for OutlineCommand {
459    fn from(value: OutlineCurveTo) -> Self {
460        Self::CurveTo(value)
461    }
462}
463
464impl From<OutlineClose> for OutlineCommand {
465    fn from(value: OutlineClose) -> Self {
466        Self::Close(value)
467    }
468}
469
470/// `{"kind": "move_to", "x", "y"}`.
471#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
472#[serde(deny_unknown_fields)]
473pub struct OutlineMoveTo {
474    pub kind: String,
475    pub x: FiniteFloat,
476    pub y: FiniteFloat,
477}
478
479/// `{"kind": "line_to", "x", "y"}`.
480#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
481#[serde(deny_unknown_fields)]
482pub struct OutlineLineTo {
483    pub kind: String,
484    pub x: FiniteFloat,
485    pub y: FiniteFloat,
486}
487
488/// `{"kind": "quad_to", "control_x", "control_y", "x", "y"}`.
489#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
490#[serde(deny_unknown_fields)]
491pub struct OutlineQuadTo {
492    pub control_x: FiniteFloat,
493    pub control_y: FiniteFloat,
494    pub kind: String,
495    pub x: FiniteFloat,
496    pub y: FiniteFloat,
497}
498
499/// `{"kind": "curve_to", "control1_x", "control1_y", "control2_x", "control2_y", "x", "y"}`.
500#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
501#[serde(deny_unknown_fields)]
502pub struct OutlineCurveTo {
503    pub control1_x: FiniteFloat,
504    pub control1_y: FiniteFloat,
505    pub control2_x: FiniteFloat,
506    pub control2_y: FiniteFloat,
507    pub kind: String,
508    pub x: FiniteFloat,
509    pub y: FiniteFloat,
510}
511
512/// `{"kind": "close"}`.
513#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
514#[serde(deny_unknown_fields)]
515pub struct OutlineClose {
516    pub kind: String,
517}
518
519/// Stable semantic validation failure: a code, a JSON path and a message.
520#[derive(Clone, Debug, Eq, PartialEq)]
521pub struct ValidationError {
522    pub code: &'static str,
523    pub path: String,
524    pub message: &'static str,
525}
526
527impl fmt::Display for ValidationError {
528    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
529        write!(
530            formatter,
531            "{} at {}: {}",
532            self.code, self.path, self.message
533        )
534    }
535}
536
537impl std::error::Error for ValidationError {}
538
539/// Validate one shaping input before a shaper consumes caller-supplied font
540/// bytes: UTF-8 byte-offset indexing, the font digest, variation axes, the
541/// script tag, a nonempty language and half-open code-point feature ranges.
542/// Paths are relative to the input (`$` is the input itself).
543pub fn validate_shaping_input(input: &ShapingInput) -> Result<(), ValidationError> {
544    if input.text_index_unit != "utf8_byte_offset" {
545        return Err(error(
546            "unsupported_contract",
547            "$.text_index_unit",
548            "shaping indices must use UTF-8 byte offsets",
549        ));
550    }
551    validate_font_sha256(&input.font_sha256, "$.font_sha256")?;
552    validate_font_variations(&input.variations, "$.variations")?;
553    if input
554        .script
555        .as_ref()
556        .is_some_and(|script| !valid_tag(&script.0))
557    {
558        return Err(error(
559            "invalid_tag",
560            "$.script",
561            "script must be a printable four-byte OpenType tag",
562        ));
563    }
564    if input.language.as_ref().is_some_and(String::is_empty) {
565        return Err(error(
566            "invalid_language",
567            "$.language",
568            "language must be nonempty when supplied",
569        ));
570    }
571    validate_feature_indices(input)
572}
573
574/// Validate a font digest: 64 lowercase hexadecimal characters.
575pub fn validate_font_sha256(value: &Sha256Hex, path: &str) -> Result<(), ValidationError> {
576    if value.len() == 64
577        && value
578            .bytes()
579            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
580    {
581        Ok(())
582    } else {
583        Err(error(
584            "invalid_hash",
585            path,
586            "SHA-256 must be 64 lowercase hexadecimal characters",
587        ))
588    }
589}
590
591/// Validate variation coordinates: printable four-byte axis tags, each once.
592pub fn validate_font_variations(
593    variations: &[FontVariationCoordinate],
594    path: &str,
595) -> Result<(), ValidationError> {
596    let mut seen = HashSet::new();
597    if variations
598        .iter()
599        .map(|variation| variation.axis.as_str())
600        .any(|axis| !valid_tag(axis) || !seen.insert(axis))
601    {
602        Err(error(
603            "invalid_variation",
604            path,
605            "variation axes must be printable, four-byte, and unique",
606        ))
607    } else {
608        Ok(())
609    }
610}
611
612fn validate_feature_indices(input: &ShapingInput) -> Result<(), ValidationError> {
613    let text_bytes = u32::try_from(input.text.len()).map_err(|_| {
614        error(
615            "resource_limit",
616            "$.text",
617            "UTF-8 text length exceeds the shaping index range",
618        )
619    })?;
620    let mut char_starts = HashSet::with_capacity(input.text.chars().count());
621    char_starts.extend(input.text.char_indices().map(|(index, _)| index as u32));
622    let mut feature_tags = HashSet::with_capacity(input.features.len());
623    for (index, feature) in input.features.iter().enumerate() {
624        if !valid_tag(&feature.tag.0) {
625            return Err(error(
626                "invalid_tag",
627                format!("$.features[{index}].tag"),
628                "feature must use a printable four-byte OpenType tag",
629            ));
630        }
631        if !feature_tags.insert(feature.tag.0.as_str()) {
632            return Err(error(
633                "duplicate_feature_tag",
634                format!("$.features[{index}].tag"),
635                "feature tags must be unique at the shaping boundary",
636            ));
637        }
638        let global = feature.start == 0 && feature.end == u32::MAX;
639        let bounded = feature.start <= feature.end
640            && valid_feature_endpoint(feature.start, text_bytes, &char_starts)
641            && valid_feature_endpoint(feature.end, text_bytes, &char_starts);
642        if !global && !bounded {
643            return Err(error(
644                "invalid_text_index",
645                format!("$.features[{index}]"),
646                "feature range must use half-open UTF-8 code-point boundaries",
647            ));
648        }
649    }
650    Ok(())
651}
652
653fn valid_feature_endpoint(value: u32, text_bytes: u32, char_starts: &HashSet<u32>) -> bool {
654    value == text_bytes || char_starts.contains(&value)
655}
656
657fn valid_tag(value: &str) -> bool {
658    value.len() == 4 && value.bytes().all(|byte| (b' '..=b'~').contains(&byte))
659}
660
661fn error(code: &'static str, path: impl Into<String>, message: &'static str) -> ValidationError {
662    ValidationError {
663        code,
664        path: path.into(),
665        message,
666    }
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672
673    /// The published JSON shape: field names, enum strings, absent optionals.
674    #[test]
675    fn shaping_input_keeps_the_published_json_shape() {
676        let json = r#"{"buffer_properties":{"beginning_of_text":true,"cluster_level":"monotone_graphemes","default_ignorables":"normal","do_not_insert_dotted_circle":false,"end_of_text":true,"produce_safe_to_insert_tatweel":false,"produce_unsafe_to_concat":false},"direction":"left_to_right","face_index":0,"features":[{"end":4294967295,"start":0,"tag":"kern","value":1}],"font_id":"font.a","font_sha256":"0000000000000000000000000000000000000000000000000000000000000000","scale_x":2048,"scale_y":2048,"text":"Ab","text_index_unit":"utf8_byte_offset","variations":[{"axis":"wght","value":400.0}]}"#;
677        let input: ShapingInput = serde_json::from_str(json).expect("decodes");
678        assert_eq!(serde_json::to_string(&input).expect("encodes"), json);
679        assert_eq!(validate_shaping_input(&input), Ok(()));
680    }
681
682    #[test]
683    fn outline_line_to_decodes_into_the_shared_shape() {
684        let command: OutlineCommand =
685            serde_json::from_str(r#"{"kind":"line_to","x":1.0,"y":2.0}"#).expect("decodes");
686        assert!(matches!(&command, OutlineCommand::MoveTo(value) if value.kind == "line_to"));
687    }
688}