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

kicad_monkey_svg/
context.rs

1//! Validated presentation policy shared by every direct typed SVG renderer.
2
3use std::collections::BTreeMap;
4
5use crate::{SvgError as SvgErrorType, SvgErrorKind};
6
7type SvgError = SvgErrorType;
8
9#[allow(
10    non_snake_case,
11    reason = "local constructor preserves concise context error call sites"
12)]
13fn SvgError(message: String) -> SvgErrorType {
14    SvgErrorType::new(SvgErrorKind::InvalidContext, message)
15}
16
17/// SVG rendering profile governing element structure and styling semantics.
18#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
19pub enum SvgProfile {
20    /// Frozen base Plotter-IR A0 profile.
21    #[default]
22    PlotterBaseA0,
23}
24
25/// Validated canonical uppercase `#RRGGBB` or `#RRGGBBAA` sRGB hex color.
26#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
27pub struct SvgColor(String);
28
29impl SvgColor {
30    /// Parse and canonicalize a `#RRGGBB` or `#RRGGBBAA` hex color string.
31    pub fn parse(value: impl Into<String>) -> Result<Self, SvgError> {
32        let value = value.into();
33        let bytes = value.as_bytes();
34        if !matches!(bytes.len(), 7 | 9)
35            || bytes.first() != Some(&b'#')
36            || !bytes[1..].iter().all(u8::is_ascii_hexdigit)
37        {
38            return Err(SvgError(format!(
39                "SVG context color must be #RRGGBB or #RRGGBBAA, got {value:?}"
40            )));
41        }
42        Ok(Self(value.to_ascii_uppercase()))
43    }
44
45    /// Return the canonical uppercase `#RRGGBB` / `#RRGGBBAA` string slice.
46    pub fn as_str(&self) -> &str {
47        &self.0
48    }
49}
50
51/// Canvas background fill policy for an emitted SVG document.
52#[derive(Clone, Debug, Eq, PartialEq)]
53pub enum SvgBackground {
54    /// Fill the full viewport rectangle with an opaque color.
55    Opaque(SvgColor),
56    /// Emit no background rectangle (transparent canvas).
57    Transparent,
58}
59
60impl Default for SvgBackground {
61    fn default() -> Self {
62        Self::Opaque(SvgColor("#FFFFFFFF".to_owned()))
63    }
64}
65
66/// High-level CAD semantic role used to apply theme-level style overrides.
67#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
68pub enum SvgSemanticRole {
69    Copper,
70    Drill,
71    Mask,
72    Silkscreen,
73    Fabrication,
74    Courtyard,
75    BoardEdge,
76    Worksheet,
77    SchematicWire,
78    SchematicBus,
79    Junction,
80    Label,
81    Pin,
82    SymbolBody,
83    HierarchicalSheet,
84    Text,
85    Image,
86    Other,
87}
88
89/// Source-owned primitive categories; shape alone does not identify a pad's role.
90#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
91pub enum SvgPrimitiveClass {
92    CopperTrace,
93    Via,
94    CopperPolygon,
95    SurfaceMountPad,
96    ThroughHolePad,
97    ComponentGraphic,
98    ComponentDesignator,
99    BoardGraphic,
100}
101
102/// Plotter-IR drawing operation kind addressable by style overrides.
103#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
104pub enum PlotterOperationKind {
105    ThickSegment,
106    ArcThreePoint,
107    Circle,
108    Rect,
109    PlotPoly,
110    BezierCurve,
111    Text,
112    PlotImage,
113    FlashPadCircle,
114    FlashPadOval,
115    FlashPadRect,
116    FlashPadRoundRect,
117    FlashPadCustom,
118    FlashPadTrapez,
119    StartBlock,
120    EndBlock,
121}
122
123/// Stroke dash-pattern override policy.
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125pub enum SvgLineStyle {
126    /// Preserve the source Plotter-IR stroke dash style.
127    Source,
128    /// Render as a continuous solid stroke.
129    Solid,
130    /// Render as a dashed stroke.
131    Dash,
132    /// Render as a dotted stroke.
133    Dot,
134    /// Render as an alternating dash-dot stroke.
135    DashDot,
136    /// Render as a dash-dot-dot stroke.
137    DashDotDot,
138}
139
140/// Shape fill override policy.
141#[derive(Clone, Copy, Debug, Eq, PartialEq)]
142pub enum SvgFillMode {
143    /// Preserve the source Plotter-IR fill behavior.
144    Source,
145    /// Suppress fill (`fill="none"`).
146    None,
147    /// Force solid fill.
148    Solid,
149}
150
151/// Partial style override merged in precedence order during SVG emission.
152#[derive(Clone, Debug, Default, PartialEq)]
153pub struct SvgStyleOverride {
154    stroke: Option<SvgColor>,
155    fill: Option<SvgColor>,
156    stroke_width_nm: Option<u64>,
157    line_style: Option<SvgLineStyle>,
158    fill_mode: Option<SvgFillMode>,
159    opacity: Option<f64>,
160    visible: Option<bool>,
161}
162
163impl SvgStyleOverride {
164    pub fn new() -> Self {
165        Self::default()
166    }
167
168    pub fn with_stroke(mut self, color: SvgColor) -> Self {
169        self.stroke = Some(color);
170        self
171    }
172
173    pub fn with_fill(mut self, color: SvgColor) -> Self {
174        self.fill = Some(color);
175        self
176    }
177
178    pub const fn with_stroke_width_nm(mut self, width_nm: u64) -> Self {
179        self.stroke_width_nm = Some(width_nm);
180        self
181    }
182
183    pub const fn with_line_style(mut self, line_style: SvgLineStyle) -> Self {
184        self.line_style = Some(line_style);
185        self
186    }
187
188    pub const fn with_fill_mode(mut self, fill_mode: SvgFillMode) -> Self {
189        self.fill_mode = Some(fill_mode);
190        self
191    }
192
193    pub const fn with_opacity(mut self, opacity: f64) -> Self {
194        self.opacity = Some(opacity);
195        self
196    }
197
198    pub const fn with_visibility(mut self, visible: bool) -> Self {
199        self.visible = Some(visible);
200        self
201    }
202
203    pub fn stroke(&self) -> Option<&SvgColor> {
204        self.stroke.as_ref()
205    }
206
207    pub fn fill(&self) -> Option<&SvgColor> {
208        self.fill.as_ref()
209    }
210
211    pub const fn stroke_width_nm(&self) -> Option<u64> {
212        self.stroke_width_nm
213    }
214
215    pub const fn line_style(&self) -> Option<SvgLineStyle> {
216        self.line_style
217    }
218
219    pub const fn fill_mode(&self) -> Option<SvgFillMode> {
220        self.fill_mode
221    }
222
223    pub const fn opacity(&self) -> Option<f64> {
224        self.opacity
225    }
226
227    pub const fn visible(&self) -> Option<bool> {
228        self.visible
229    }
230}
231
232/// Case-sensitive KiCad layer selector (`*`, exact name, `*.Suffix`, or `<unlayered>`).
233#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
234pub enum LayerPattern {
235    /// Match every layer and unlayered operations.
236    All,
237    /// Match one exact KiCad canonical layer name (e.g., `"F.Cu"`).
238    Exact(String),
239    /// Match any layer ending with the given dot-prefixed suffix (e.g., `".Cu"`).
240    Suffix(String),
241    /// Match only operations without an assigned PCB layer.
242    Unlayered,
243}
244
245impl LayerPattern {
246    pub fn parse(value: impl Into<String>) -> Result<Self, SvgError> {
247        let value = value.into();
248        if value == "*" {
249            return Ok(Self::All);
250        }
251        if value == "<unlayered>" {
252            return Ok(Self::Unlayered);
253        }
254        if value.is_empty()
255            || value.bytes().any(|byte| byte.is_ascii_whitespace())
256            || value.bytes().any(|byte| byte.is_ascii_control())
257        {
258            return Err(SvgError(
259                "SVG layer patterns cannot be empty or contain whitespace/control bytes".to_owned(),
260            ));
261        }
262        let stars = value.bytes().filter(|byte| *byte == b'*').count();
263        if stars == 0 {
264            return Ok(Self::Exact(value));
265        }
266        if stars == 1 && value.starts_with("*.") && value.len() > 2 {
267            return Ok(Self::Suffix(value[1..].to_owned()));
268        }
269        Err(SvgError(format!(
270            "unsupported SVG layer pattern {value:?}; use exact, *, or one leading-star suffix"
271        )))
272    }
273
274    pub fn matches(&self, layer: Option<&str>) -> bool {
275        match (self, layer) {
276            (Self::All, _) => true,
277            (Self::Unlayered, None) => true,
278            (Self::Exact(pattern), Some(layer)) => pattern == layer,
279            (Self::Suffix(suffix), Some(layer)) => layer.ends_with(suffix),
280            _ => false,
281        }
282    }
283}
284
285/// Layer inclusion filter applied to PCB and footprint SVG renders.
286#[derive(Clone, Debug, Default, Eq, PartialEq)]
287pub enum LayerSelection {
288    /// Emit operations from all layers.
289    #[default]
290    All,
291    /// Emit only operations matching at least one [`LayerPattern`].
292    Include {
293        patterns: Vec<LayerPattern>,
294        /// When `true`, fail if a selected exact layer is absent from the source document.
295        strict: bool,
296    },
297}
298
299impl LayerSelection {
300    pub fn include(patterns: Vec<LayerPattern>, strict: bool) -> Self {
301        Self::Include { patterns, strict }
302    }
303
304    pub fn matches(&self, layer: Option<&str>) -> bool {
305        match self {
306            Self::All => true,
307            Self::Include { patterns, .. } => patterns.iter().any(|pattern| pattern.matches(layer)),
308        }
309    }
310
311    pub const fn is_all(&self) -> bool {
312        matches!(self, Self::All)
313    }
314}
315
316/// Visibility toggles for schematic symbol pin annotations.
317#[derive(Clone, Copy, Debug, Eq, PartialEq)]
318pub struct SvgVisibility {
319    pin_names: bool,
320    pin_numbers: bool,
321}
322
323impl Default for SvgVisibility {
324    fn default() -> Self {
325        Self {
326            pin_names: true,
327            pin_numbers: true,
328        }
329    }
330}
331
332impl SvgVisibility {
333    pub const fn new(pin_names: bool, pin_numbers: bool) -> Self {
334        Self {
335            pin_names,
336            pin_numbers,
337        }
338    }
339
340    pub const fn pin_names(self) -> bool {
341        self.pin_names
342    }
343
344    pub const fn pin_numbers(self) -> bool {
345        self.pin_numbers
346    }
347}
348
349/// Controls whether source UUID/object identity attributes are emitted on SVG elements.
350#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
351pub enum SvgIdentityMode {
352    /// Emit full `id` and `data-*` source identity attributes.
353    #[default]
354    Full,
355    /// Omit source identity attributes for minimal presentation-only output.
356    None,
357}
358
359/// Unvalidated SVG presentation policy; call [`SvgRenderContextA1::validate`] before rendering.
360#[derive(Clone, Debug, PartialEq)]
361pub struct SvgRenderContextA1 {
362    profile: SvgProfile,
363    background: SvgBackground,
364    fallback_style: SvgStyleOverride,
365    semantic_styles: BTreeMap<SvgSemanticRole, SvgStyleOverride>,
366    layer_styles: Vec<(LayerPattern, SvgStyleOverride)>,
367    operation_styles: BTreeMap<PlotterOperationKind, SvgStyleOverride>,
368    raw_color_remap: BTreeMap<SvgColor, SvgColor>,
369    primitive_styles: BTreeMap<SvgPrimitiveClass, SvgStyleOverride>,
370    layer_selection: LayerSelection,
371    visibility: SvgVisibility,
372    identity_mode: SvgIdentityMode,
373    font_face_override: Option<String>,
374}
375
376impl Default for SvgRenderContextA1 {
377    fn default() -> Self {
378        SvgRenderContextBuilder::new().build()
379    }
380}
381
382impl SvgRenderContextA1 {
383    pub fn builder() -> SvgRenderContextBuilder {
384        SvgRenderContextBuilder::new()
385    }
386
387    pub fn validate(self) -> Result<ValidatedSvgRenderContextA1, SvgError> {
388        validate_context(&self)?;
389        Ok(ValidatedSvgRenderContextA1(self))
390    }
391}
392
393/// Validated, immutable SVG render context shared across direct typed renderers.
394#[derive(Clone, Debug, PartialEq)]
395pub struct ValidatedSvgRenderContextA1(SvgRenderContextA1);
396
397impl ValidatedSvgRenderContextA1 {
398    pub fn defaults() -> Self {
399        SvgRenderContextA1::default()
400            .validate()
401            .expect("built-in SVG context is valid")
402    }
403
404    pub const fn profile(&self) -> SvgProfile {
405        self.0.profile
406    }
407
408    pub fn background(&self) -> &SvgBackground {
409        &self.0.background
410    }
411
412    pub fn fallback_style(&self) -> &SvgStyleOverride {
413        &self.0.fallback_style
414    }
415
416    pub fn semantic_style(&self, role: SvgSemanticRole) -> Option<&SvgStyleOverride> {
417        self.0.semantic_styles.get(&role)
418    }
419
420    pub fn layer_styles(&self) -> &[(LayerPattern, SvgStyleOverride)] {
421        &self.0.layer_styles
422    }
423
424    pub fn operation_style(&self, kind: PlotterOperationKind) -> Option<&SvgStyleOverride> {
425        self.0.operation_styles.get(&kind)
426    }
427
428    pub fn primitive_style(&self, class: SvgPrimitiveClass) -> Option<&SvgStyleOverride> {
429        self.0.primitive_styles.get(&class)
430    }
431
432    pub fn remap_color<'a>(&'a self, color: &'a SvgColor) -> &'a SvgColor {
433        self.0.raw_color_remap.get(color).unwrap_or(color)
434    }
435
436    pub fn layer_selection(&self) -> &LayerSelection {
437        &self.0.layer_selection
438    }
439
440    pub const fn visibility(&self) -> SvgVisibility {
441        self.0.visibility
442    }
443
444    pub const fn identity_mode(&self) -> SvgIdentityMode {
445        self.0.identity_mode
446    }
447
448    pub fn font_face_override(&self) -> Option<&str> {
449        self.0.font_face_override.as_deref()
450    }
451
452    pub(crate) fn has_style_overrides(&self) -> bool {
453        self.0.fallback_style != SvgStyleOverride::default()
454            || !self.0.semantic_styles.is_empty()
455            || !self.0.layer_styles.is_empty()
456            || !self.0.operation_styles.is_empty()
457            || !self.0.raw_color_remap.is_empty()
458            || !self.0.primitive_styles.is_empty()
459    }
460}
461
462/// Fluent builder for constructing an [`SvgRenderContextA1`].
463#[derive(Clone, Debug)]
464pub struct SvgRenderContextBuilder(SvgRenderContextA1);
465
466impl Default for SvgRenderContextBuilder {
467    fn default() -> Self {
468        Self::new()
469    }
470}
471
472impl SvgRenderContextBuilder {
473    pub fn new() -> Self {
474        Self(SvgRenderContextA1 {
475            profile: SvgProfile::PlotterBaseA0,
476            background: SvgBackground::default(),
477            fallback_style: SvgStyleOverride::default(),
478            semantic_styles: BTreeMap::new(),
479            layer_styles: Vec::new(),
480            operation_styles: BTreeMap::new(),
481            raw_color_remap: BTreeMap::new(),
482            primitive_styles: BTreeMap::new(),
483            layer_selection: LayerSelection::All,
484            visibility: SvgVisibility::default(),
485            identity_mode: SvgIdentityMode::Full,
486            font_face_override: None,
487        })
488    }
489
490    pub fn profile(mut self, profile: SvgProfile) -> Self {
491        self.0.profile = profile;
492        self
493    }
494
495    pub fn background(mut self, background: SvgBackground) -> Self {
496        self.0.background = background;
497        self
498    }
499
500    pub fn fallback_style(mut self, style: SvgStyleOverride) -> Self {
501        self.0.fallback_style = style;
502        self
503    }
504
505    pub fn semantic_style(mut self, role: SvgSemanticRole, style: SvgStyleOverride) -> Self {
506        self.0.semantic_styles.insert(role, style);
507        self
508    }
509
510    pub fn layer_style(mut self, pattern: LayerPattern, style: SvgStyleOverride) -> Self {
511        self.0.layer_styles.push((pattern, style));
512        self
513    }
514
515    pub fn operation_style(mut self, kind: PlotterOperationKind, style: SvgStyleOverride) -> Self {
516        self.0.operation_styles.insert(kind, style);
517        self
518    }
519
520    pub fn primitive_style(mut self, class: SvgPrimitiveClass, style: SvgStyleOverride) -> Self {
521        self.0.primitive_styles.insert(class, style);
522        self
523    }
524
525    pub fn raw_color_remap(mut self, source: SvgColor, target: SvgColor) -> Self {
526        self.0.raw_color_remap.insert(source, target);
527        self
528    }
529
530    pub fn layer_selection(mut self, selection: LayerSelection) -> Self {
531        self.0.layer_selection = selection;
532        self
533    }
534
535    pub fn visibility(mut self, visibility: SvgVisibility) -> Self {
536        self.0.visibility = visibility;
537        self
538    }
539
540    pub fn identity_mode(mut self, mode: SvgIdentityMode) -> Self {
541        self.0.identity_mode = mode;
542        self
543    }
544
545    pub fn font_face_override(mut self, font_face: impl Into<String>) -> Self {
546        self.0.font_face_override = Some(font_face.into());
547        self
548    }
549
550    pub fn build(self) -> SvgRenderContextA1 {
551        self.0
552    }
553}
554
555fn validate_context(context: &SvgRenderContextA1) -> Result<(), SvgError> {
556    for (pattern, _) in &context.layer_styles {
557        validate_layer_pattern(pattern)?;
558    }
559    ensure_unique_patterns(
560        &context
561            .layer_styles
562            .iter()
563            .map(|(pattern, _)| pattern.clone())
564            .collect::<Vec<_>>(),
565    )?;
566    if let LayerSelection::Include { patterns, .. } = &context.layer_selection {
567        if patterns.is_empty() {
568            return Err(SvgError(
569                "SVG context layer selection cannot be empty".to_owned(),
570            ));
571        }
572        for pattern in patterns {
573            validate_layer_pattern(pattern)?;
574        }
575        ensure_unique_patterns(patterns)?;
576    }
577    validate_style(&context.fallback_style)?;
578    for style in context
579        .semantic_styles
580        .values()
581        .chain(context.layer_styles.iter().map(|(_, style)| style))
582        .chain(context.operation_styles.values())
583        .chain(context.primitive_styles.values())
584    {
585        validate_style(style)?;
586    }
587    if context
588        .font_face_override
589        .as_ref()
590        .is_some_and(|value| value.is_empty() || value.chars().any(char::is_control))
591    {
592        return Err(SvgError(
593            "SVG context font override cannot be empty or contain control characters".to_owned(),
594        ));
595    }
596    Ok(())
597}
598
599fn validate_layer_pattern(pattern: &LayerPattern) -> Result<(), SvgError> {
600    let valid_text = |value: &str| {
601        !value.is_empty()
602            && !value.bytes().any(|byte| byte.is_ascii_whitespace())
603            && !value.bytes().any(|byte| byte.is_ascii_control())
604    };
605    match pattern {
606        LayerPattern::All | LayerPattern::Unlayered => Ok(()),
607        LayerPattern::Exact(value) if valid_text(value) && !value.contains('*') => Ok(()),
608        LayerPattern::Suffix(value)
609            if valid_text(value)
610                && value.starts_with('.')
611                && value.len() > 1
612                && !value.contains('*') =>
613        {
614            Ok(())
615        }
616        _ => Err(SvgError(
617            "SVG context contains a malformed layer pattern; construct patterns with LayerPattern::parse"
618                .to_owned(),
619        )),
620    }
621}
622
623fn validate_style(style: &SvgStyleOverride) -> Result<(), SvgError> {
624    if style
625        .opacity
626        .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
627    {
628        return Err(SvgError(
629            "SVG context style opacity must be finite and in [0,1]".to_owned(),
630        ));
631    }
632    if style
633        .stroke_width_nm
634        .is_some_and(|width| i64::try_from(width).is_err())
635    {
636        return Err(SvgError(
637            "SVG context stroke width exceeds the renderer numeric range".to_owned(),
638        ));
639    }
640    Ok(())
641}
642
643fn ensure_unique_patterns(patterns: &[LayerPattern]) -> Result<(), SvgError> {
644    let mut sorted = patterns.to_vec();
645    sorted.sort();
646    if sorted.windows(2).any(|pair| pair[0] == pair[1]) {
647        return Err(SvgError(
648            "SVG context layer patterns must be unique".to_owned(),
649        ));
650    }
651    Ok(())
652}
653
654#[cfg(test)]
655mod tests {
656    use super::*;
657
658    #[test]
659    fn defaults_are_valid_and_exact_layer_patterns_are_case_sensitive() {
660        let context = SvgRenderContextA1::default().validate().unwrap();
661        assert!(context.layer_selection().is_all());
662        assert!(LayerPattern::parse("*.Cu").unwrap().matches(Some("F.Cu")));
663        assert!(!LayerPattern::parse("*.Cu").unwrap().matches(Some("F.cu")));
664        assert!(LayerPattern::parse("<unlayered>").unwrap().matches(None));
665        assert!(LayerPattern::parse("F.*.Cu").is_err());
666    }
667
668    #[test]
669    fn colors_are_canonical_and_duplicate_selectors_fail_closed() {
670        assert_eq!(SvgColor::parse("#aabbcc80").unwrap().as_str(), "#AABBCC80");
671        assert!(SvgColor::parse("blue").is_err());
672        let exact = LayerPattern::parse("F.Cu").unwrap();
673        let context = SvgRenderContextA1::builder()
674            .layer_selection(LayerSelection::include(vec![exact.clone(), exact], false))
675            .build();
676        assert!(context.validate().is_err());
677        assert!(
678            SvgRenderContextA1::builder()
679                .layer_style(LayerPattern::Suffix(String::new()), SvgStyleOverride::new(),)
680                .build()
681                .validate()
682                .is_err()
683        );
684    }
685}