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

kicad_monkey_svg/
lib.rs

1//! Deterministic SVG serializer for KiCad Plotter-IR documents.
2//!
3//! Renders typed KiCad footprint, symbol, board, and schematic-page Plotter-IR
4//! documents directly into reproducible SVG with validated styling, layer
5//! filtering, viewport fitting, and source-identity preservation.
6
7#![forbid(unsafe_code)]
8
9mod context;
10mod direct;
11mod sink;
12
13pub use context::{
14    LayerPattern, LayerSelection, PlotterOperationKind, SvgBackground, SvgColor, SvgFillMode,
15    SvgIdentityMode, SvgLineStyle, SvgPrimitiveClass, SvgProfile, SvgRenderContextA1,
16    SvgRenderContextBuilder, SvgSemanticRole, SvgStyleOverride, SvgVisibility,
17    ValidatedSvgRenderContextA1,
18};
19pub use direct::{
20    SvgBounds, SvgFitOptions, SvgViewport, SvgWarning, ViewportPolicy, render_board_document_svg,
21    render_board_svg, render_footprint_svg, render_schematic_page_svg, render_schematic_svg,
22    render_symbol_svg,
23};
24
25/// Structured error returned by SVG context validation or rendering.
26#[derive(Debug)]
27pub struct SvgError {
28    kind: SvgErrorKind,
29    message: String,
30}
31
32/// Machine-readable category for an [`SvgError`].
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub enum SvgErrorKind {
35    /// Render context configuration failed validation.
36    InvalidContext,
37    /// Input Plotter-IR document failed structural or semantic validation.
38    InvalidDocument,
39    /// Explicit or fitted viewport had invalid or non-positive dimensions.
40    InvalidViewport,
41    /// Layer or style selector pattern is unsupported.
42    UnsupportedSelector,
43    /// Document or output exceeded a configured resource limit.
44    ResourceLimit,
45    /// Uncached text prevented exact fit-bounds computation when disallowed.
46    UnsupportedFitText,
47    /// Fit-to-content requested on a document with no visible geometry.
48    EmptyBounds,
49    /// Coordinate or extent arithmetic overflowed integer bounds.
50    ArithmeticOverflow,
51    /// Plotter-IR `StartBlock` / `EndBlock` nesting was unbalanced.
52    UnbalancedBlock,
53    /// SVG/XML serialization rejected invalid characters or control bytes.
54    Serialization,
55    /// Uncategorized internal rendering failure.
56    Other,
57}
58
59impl SvgError {
60    /// Construct a new structured SVG error.
61    pub fn new(kind: SvgErrorKind, message: impl Into<String>) -> Self {
62        Self {
63            kind,
64            message: message.into(),
65        }
66    }
67
68    /// Return the machine-readable error category.
69    pub const fn kind(&self) -> SvgErrorKind {
70        self.kind
71    }
72
73    /// Return the human-readable diagnostic message.
74    pub fn message(&self) -> &str {
75        &self.message
76    }
77}
78
79impl std::fmt::Display for SvgError {
80    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        formatter.write_str(&self.message)
82    }
83}
84
85impl std::error::Error for SvgError {}
86
87#[cfg(test)]
88mod error_tests {
89    use super::{SvgError, SvgErrorKind};
90
91    #[test]
92    fn every_public_error_kind_is_stored_explicitly() {
93        for kind in [
94            SvgErrorKind::InvalidContext,
95            SvgErrorKind::InvalidDocument,
96            SvgErrorKind::InvalidViewport,
97            SvgErrorKind::UnsupportedSelector,
98            SvgErrorKind::ResourceLimit,
99            SvgErrorKind::UnsupportedFitText,
100            SvgErrorKind::EmptyBounds,
101            SvgErrorKind::ArithmeticOverflow,
102            SvgErrorKind::UnbalancedBlock,
103            SvgErrorKind::Serialization,
104            SvgErrorKind::Other,
105        ] {
106            let error = SvgError::new(kind, "message deliberately has no classification words");
107            assert_eq!(error.kind(), kind);
108        }
109    }
110}
111
112/// Rendered SVG document together with resolved viewport, bounds, and telemetry.
113#[derive(Debug)]
114pub struct SvgArtifact {
115    /// Plotter-IR family tag (e.g., `"board"`, `"footprint"`, `"symbol"`, `"schematic"`).
116    pub source_kind: &'static str,
117    /// Stable document identifier propagated from the Plotter-IR source.
118    pub document_id: String,
119    /// Serialized UTF-8 SVG document text.
120    pub svg: String,
121    /// Hierarchical page occurrence address when rendering a schematic sheet instance.
122    pub occurrence_address: Option<String>,
123    /// Final rendered viewport in nanometres.
124    pub viewport: SvgViewport,
125    /// Tight visible geometry bounding box in nanometres, if any geometry was emitted.
126    pub visible_bounds: Option<SvgBounds>,
127    /// Non-fatal warnings recorded during rendering or bounds estimation.
128    pub warnings: Vec<SvgWarning>,
129    /// Ids the source repeats, one entry per later element, in document
130    /// order. Those elements were written as `<id>-2`, `<id>-3`, ...
131    /// (skipping a suffix another id uses) instead of being refused.
132    pub repeated_ids: Vec<String>,
133    /// Accounting counters for processed operations and emitted SVG output.
134    pub metrics: SvgMetrics,
135}
136
137/// Deterministic work and size counters reported on every [`SvgArtifact`].
138#[derive(Clone, Copy, Debug, Eq, PartialEq)]
139pub struct SvgMetrics {
140    /// Number of Plotter-IR records traversed.
141    pub records: usize,
142    /// Number of drawing operations traversed.
143    pub operations: usize,
144    /// Total polyline/polygon/arc vertices processed.
145    pub points: usize,
146    /// Total UTF-8 bytes of rendered text strings.
147    pub text_bytes: usize,
148    /// Total base64 bytes of embedded raster images.
149    pub image_encoded_bytes: usize,
150    /// Maximum nested `StartBlock` / `EndBlock` depth observed.
151    pub block_depth: usize,
152    /// Number of SVG elements emitted.
153    pub svg_elements: usize,
154    /// Byte-weighted rendering work counter.
155    pub render_work: usize,
156    /// Final serialized SVG byte length.
157    pub svg_bytes: usize,
158    /// Operation-weighted bounds calculation counter.
159    pub bounds_work: usize,
160}