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

kicad_monkey_core/
pcb_authoring.rs

1//! Typed fresh-source authoring for KiCad PCB and footprint files.
2
3mod custom_pads;
4mod emit;
5mod knockout;
6pub use knockout::recover_board_text_knockout_cache;
7mod padstacks;
8mod resource;
9mod rule_areas;
10mod validate;
11
12pub use rule_areas::{
13    AuthoredKeepout, AuthoredPlacementConstraint, AuthoredPlacementSource, AuthoredRestriction,
14    AuthoredRuleArea,
15};
16
17use crate::footprint::{FootprintDocument, FootprintLimits};
18use crate::pcb::{PcbDocument, PcbLimits};
19use crate::sexpr::Error;
20use crate::text_render_cache::TextRenderCache;
21pub use custom_pads::{
22    AuthoredCustomPadClearance, AuthoredPadAnchor, AuthoredPadPolygonPoint, AuthoredPadPrimitive,
23    AuthoredPadPrimitiveFill, AuthoredPadPrimitiveGeometry,
24};
25pub use padstacks::{
26    AuthoredPadstack, AuthoredPadstackLayer, AuthoredPadstackLayerSelector, AuthoredPadstackMode,
27    AuthoredPadstackZoneConnection, AuthoredViaStack, AuthoredViaStackLayer,
28};
29
30/// First explicitly supported PCB and footprint source format revision.
31pub const KICAD_SOURCE_VERSION_2024_12_29: i64 = 20_241_229;
32
33/// Independent ceilings for fresh typed source construction.
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub struct PcbAuthoringLimits {
36    pub max_objects: usize,
37    pub max_points: usize,
38    pub max_string_bytes: usize,
39    pub max_resource_input_bytes: usize,
40    /// Conservative aggregate zstd/base64 allocation bound checked before encoding.
41    pub max_resource_work_bytes: usize,
42    pub max_resource_encoded_bytes: usize,
43    pub max_output_bytes: usize,
44    pub pcb_limits: PcbLimits,
45    pub footprint_limits: FootprintLimits,
46}
47
48impl Default for PcbAuthoringLimits {
49    fn default() -> Self {
50        Self {
51            max_objects: 1_000_000,
52            max_points: 16_000_000,
53            max_string_bytes: 256 * 1024 * 1024,
54            max_resource_input_bytes: 256 * 1024 * 1024,
55            max_resource_work_bytes: 512 * 1024 * 1024,
56            max_resource_encoded_bytes: 384 * 1024 * 1024,
57            max_output_bytes: 256 * 1024 * 1024,
58            pcb_limits: PcbLimits::default(),
59            footprint_limits: FootprintLimits::default(),
60        }
61    }
62}
63
64#[derive(Clone, Copy, Debug, Default, PartialEq)]
65pub struct AuthoredPoint {
66    pub x_mm: f64,
67    pub y_mm: f64,
68}
69
70#[derive(Clone, Debug, Eq, PartialEq)]
71pub struct AuthoredLayer {
72    pub ordinal: i64,
73    pub name: String,
74    pub kind: String,
75    pub user_name: Option<String>,
76}
77
78#[derive(Clone, Debug, PartialEq)]
79pub struct AuthoredStackupLayer {
80    pub name: String,
81    pub type_name: String,
82    pub thickness_mm: Option<f64>,
83    pub thickness_locked: bool,
84    pub material: Option<String>,
85    pub epsilon_r: Option<f64>,
86    pub loss_tangent: Option<f64>,
87    pub color: Option<String>,
88    /// Further parameter groups of this dielectric, written as `addsublayer`.
89    pub sublayers: Vec<AuthoredStackupSubLayer>,
90}
91
92/// One `addsublayer` parameter group of a dielectric stackup layer.
93#[derive(Clone, Debug, Default, PartialEq)]
94pub struct AuthoredStackupSubLayer {
95    pub thickness_mm: Option<f64>,
96    pub thickness_locked: bool,
97    pub material: Option<String>,
98    pub epsilon_r: Option<f64>,
99    pub loss_tangent: Option<f64>,
100    pub color: Option<String>,
101}
102
103#[derive(Clone, Debug, Default, PartialEq)]
104pub struct AuthoredStackup {
105    pub layers: Vec<AuthoredStackupLayer>,
106    pub copper_finish: Option<String>,
107    pub dielectric_constraints: bool,
108    pub edge_connector: Option<String>,
109    pub edge_plating: bool,
110}
111
112#[derive(Clone, Debug, Default, PartialEq)]
113pub struct AuthoredSetup {
114    pub aux_axis_origin: AuthoredPoint,
115    pub grid_origin: AuthoredPoint,
116    /// None keeps legacy emission; explicit intent may omit or emit zero.
117    pub emit_grid_origin: Option<bool>,
118    /// Board-level surface-policy fallbacks used when neither the footprint
119    /// nor the pad authors a corresponding override.
120    pub pad_to_mask_clearance_mm: f64,
121    pub pad_to_paste_clearance_mm: f64,
122    pub pad_to_paste_clearance_ratio: f64,
123    pub allow_soldermask_bridges_in_footprints: bool,
124    /// Effective board defaults; via-local optional overrides remain separate.
125    pub tenting_front: bool,
126    pub tenting_back: bool,
127    /// None keeps legacy bare-side emission. Some uses exact optional sides;
128    /// an empty policy omits the clause rather than manufacturing defaults.
129    pub tenting_declaration: Option<AuthoredFrontBackPolicy>,
130    pub stackup: Option<AuthoredStackup>,
131}
132
133impl AuthoredSetup {
134    /// Select declaration presence independently of the effective zero default.
135    pub fn set_grid_origin_declaration(&mut self, point: Option<AuthoredPoint>) {
136        self.emit_grid_origin = Some(point.is_some());
137        self.grid_origin = point.unwrap_or_default();
138    }
139
140    /// Retain absent sides and explicit yes/no board-policy declarations.
141    /// Omitting this operation preserves legacy constructor/output behavior.
142    pub fn set_tenting_declaration(&mut self, policy: AuthoredFrontBackPolicy) {
143        self.tenting_front = policy.front.unwrap_or(false);
144        self.tenting_back = policy.back.unwrap_or(false);
145        self.tenting_declaration = Some(policy);
146    }
147}
148
149#[derive(Clone, Debug, Eq, PartialEq)]
150pub struct AuthoredNet {
151    pub code: i64,
152    pub name: String,
153}
154
155#[derive(Clone, Debug, PartialEq)]
156pub enum AuthoredPolygonPoint {
157    Xy(AuthoredPoint),
158    Arc {
159        start: AuthoredPoint,
160        mid: AuthoredPoint,
161        end: AuthoredPoint,
162    },
163}
164
165impl From<AuthoredPoint> for AuthoredPolygonPoint {
166    fn from(value: AuthoredPoint) -> Self {
167        Self::Xy(value)
168    }
169}
170
171#[derive(Clone, Debug, PartialEq)]
172pub enum AuthoredGraphicGeometry {
173    Line {
174        start: AuthoredPoint,
175        end: AuthoredPoint,
176    },
177    Arc {
178        start: AuthoredPoint,
179        mid: AuthoredPoint,
180        end: AuthoredPoint,
181    },
182    /// KiCad's ordered cubic Bezier tuple: start, control 1, control 2, end.
183    Curve {
184        points: [AuthoredPoint; 4],
185    },
186    Rect {
187        start: AuthoredPoint,
188        end: AuthoredPoint,
189    },
190    Circle {
191        center: AuthoredPoint,
192        end: AuthoredPoint,
193    },
194    Polygon {
195        points: Vec<AuthoredPolygonPoint>,
196    },
197}
198
199#[derive(Clone, Debug, PartialEq)]
200pub struct AuthoredGraphic {
201    pub geometry: AuthoredGraphicGeometry,
202    pub layer: String,
203    /// Board connectivity for copper graphics. KiCad 10 serializes shape nets
204    /// by name; the code is retained here so validation can bind the name to
205    /// the authored board net table before source emission.
206    pub net: Option<AuthoredNetRef>,
207    pub locked: bool,
208    pub stroke_width_mm: f64,
209    pub stroke_kind: String,
210    pub fill: Option<String>,
211    pub uuid: String,
212}
213
214#[derive(Clone, Debug, PartialEq)]
215pub struct AuthoredTextEffects {
216    /// `None` selects KiCad's native Newstroke source font. A named face
217    /// selects a TrueType/OpenType source font and permits a render cache.
218    pub face: Option<String>,
219    pub size_x_mm: f64,
220    pub size_y_mm: f64,
221    pub thickness_mm: Option<f64>,
222    pub line_spacing: Option<f64>,
223    pub bold: bool,
224    pub italic: bool,
225    pub color: Option<AuthoredColor>,
226    pub horizontal_justify: AuthoredTextHorizontalJustification,
227    pub vertical_justify: AuthoredTextVerticalJustification,
228    pub mirrored: bool,
229    pub href: Option<String>,
230}
231
232impl Default for AuthoredTextEffects {
233    fn default() -> Self {
234        Self {
235            face: None,
236            size_x_mm: 1.0,
237            size_y_mm: 1.0,
238            thickness_mm: Some(0.15),
239            line_spacing: None,
240            bold: false,
241            italic: false,
242            color: None,
243            horizontal_justify: AuthoredTextHorizontalJustification::Center,
244            vertical_justify: AuthoredTextVerticalJustification::Center,
245            mirrored: false,
246            href: None,
247        }
248    }
249}
250
251#[derive(Clone, Copy, Debug, PartialEq)]
252pub struct AuthoredColor {
253    pub red: i64,
254    pub green: i64,
255    pub blue: i64,
256    pub alpha: f64,
257}
258
259#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
260pub enum AuthoredTextHorizontalJustification {
261    Left,
262    #[default]
263    Center,
264    Right,
265}
266
267#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
268pub enum AuthoredTextVerticalJustification {
269    Top,
270    #[default]
271    Center,
272    Bottom,
273}
274
275#[derive(Clone, Debug, PartialEq)]
276pub struct AuthoredFootprintText {
277    /// User-authored footprint text. Reference and value source facts use
278    /// `AuthoredFootprintProperty`, matching current KiCad canonical output.
279    pub text: String,
280    pub at: AuthoredPoint,
281    pub angle_degrees: f64,
282    pub layer: String,
283    /// Must be `false` for target revision 20241229: KiCad 10 rewrites a
284    /// hidden user `fp_text` as a generated property with a new identity.
285    pub hidden: bool,
286    pub unlocked: bool,
287    pub knockout: bool,
288    pub effects: AuthoredTextEffects,
289    /// Optional realized named-font geometry. Points use the reusable
290    /// footprint-local cache frame; board emission applies KiCad's
291    /// carrier-anchor translation. The cache text is resolved display text.
292    pub render_cache: Option<TextRenderCache>,
293    pub uuid: String,
294}
295
296#[derive(Clone, Debug, PartialEq)]
297pub struct AuthoredFootprintScalarProperty {
298    pub name: String,
299    pub value: String,
300}
301
302/// A graphical footprint property with an explicit local presentation.
303#[derive(Clone, Debug, PartialEq)]
304pub struct AuthoredFootprintProperty {
305    pub name: String,
306    pub value: String,
307    pub at: AuthoredPoint,
308    pub angle_degrees: f64,
309    pub layer: String,
310    pub knockout: bool,
311    pub hidden: bool,
312    pub unlocked: bool,
313    pub effects: AuthoredTextEffects,
314    /// Optional realized named-font geometry in the reusable footprint-local
315    /// cache frame. The cache text is resolved after footprint properties.
316    pub render_cache: Option<TextRenderCache>,
317    pub uuid: String,
318}
319
320#[derive(Clone, Debug, PartialEq)]
321pub struct AuthoredTextBox {
322    pub text: String,
323    pub geometry: AuthoredTextBoxGeometry,
324    /// KiCad source order: `[left, top, right, bottom]`.
325    pub margins_mm: [f64; 4],
326    pub angle_degrees: f64,
327    pub layer: String,
328    pub locked: bool,
329    pub border: bool,
330    pub knockout: bool,
331    pub stroke_width_mm: f64,
332    pub stroke_kind: String,
333    pub effects: AuthoredTextEffects,
334    /// Optional realized named-font geometry. Footprint text-box cache points
335    /// are local in a reusable definition and become board-frame when placed.
336    pub render_cache: Option<TextRenderCache>,
337    pub uuid: String,
338}
339
340#[derive(Clone, Debug, PartialEq)]
341pub enum AuthoredTextBoxGeometry {
342    Rectangle {
343        start: AuthoredPoint,
344        end: AuthoredPoint,
345    },
346    Polygon {
347        points: Vec<AuthoredPoint>,
348    },
349}
350
351#[derive(Clone, Debug, PartialEq)]
352pub struct AuthoredBoardText {
353    pub text: String,
354    pub at: AuthoredPoint,
355    pub angle_degrees: f64,
356    pub layer: String,
357    pub locked: bool,
358    pub knockout: bool,
359    pub effects: AuthoredTextEffects,
360    pub render_cache: Option<TextRenderCache>,
361    pub uuid: String,
362}
363
364impl AuthoredBoardText {
365    /// Emit one actual board text through existing Source validation/emission.
366    /// The explicit catalogue proves local layer membership; the caller retains
367    /// complete board occurrence, resource and receipt closure obligations.
368    pub fn canonical_text(
369        &self,
370        layers: &[AuthoredLayer],
371        limits: PcbAuthoringLimits,
372    ) -> Result<String, Error> {
373        emit::board_text_fragment(self, layers, limits)
374    }
375}
376
377/// A KiCad 10 barcode symbology, by its source `type` token.
378#[derive(Clone, Copy, Debug, Eq, PartialEq)]
379pub enum AuthoredBarcodeKind {
380    Code39,
381    Code128,
382    DataMatrix,
383    Qr,
384    MicroQr,
385}
386
387impl AuthoredBarcodeKind {
388    pub const fn source_token(self) -> &'static str {
389        match self {
390            Self::Code39 => "code39",
391            Self::Code128 => "code128",
392            Self::DataMatrix => "datamatrix",
393            Self::Qr => "qr",
394            Self::MicroQr => "microqr",
395        }
396    }
397
398    pub const fn has_error_correction(self) -> bool {
399        matches!(self, Self::Qr | Self::MicroQr)
400    }
401}
402
403/// QR and Micro QR error-correction level, by its source `ecc_level` token.
404#[derive(Clone, Copy, Debug, Eq, PartialEq)]
405pub enum AuthoredBarcodeEccLevel {
406    L,
407    M,
408    Q,
409    H,
410}
411
412impl AuthoredBarcodeEccLevel {
413    pub const fn source_token(self) -> &'static str {
414        match self {
415            Self::L => "L",
416            Self::M => "M",
417            Self::Q => "Q",
418            Self::H => "H",
419        }
420    }
421}
422
423/// One `(barcode ...)` on a board or in a footprint. A footprint barcode's
424/// `at` is local to the footprint, as a footprint text's is.
425#[derive(Clone, Debug, PartialEq)]
426pub struct AuthoredBarcode {
427    pub at: AuthoredPoint,
428    pub angle_degrees: f64,
429    pub layer: String,
430    pub width_mm: f64,
431    pub height_mm: f64,
432    pub text: String,
433    pub text_height_mm: f64,
434    pub kind: AuthoredBarcodeKind,
435    /// QR and Micro QR only.
436    pub ecc_level: Option<AuthoredBarcodeEccLevel>,
437    pub locked: bool,
438    pub show_text: bool,
439    pub knockout: bool,
440    /// `margins`: x for left and right, y for top and bottom. Written when the
441    /// barcode is a knockout or either margin is nonzero.
442    pub margins_mm: AuthoredPoint,
443    pub uuid: String,
444}
445
446#[derive(Clone, Copy, Debug, Eq, PartialEq)]
447pub enum AuthoredPadKind {
448    Smd,
449    ThroughHole,
450    NonPlatedThroughHole,
451}
452
453impl AuthoredPadKind {
454    pub const fn as_str(self) -> &'static str {
455        match self {
456            Self::Smd => "smd",
457            Self::ThroughHole => "thru_hole",
458            Self::NonPlatedThroughHole => "np_thru_hole",
459        }
460    }
461}
462
463#[derive(Clone, Debug, PartialEq)]
464pub enum AuthoredPadShape {
465    Circle,
466    Oval,
467    Rect,
468    Trapezoid {
469        delta_x_mm: f64,
470        delta_y_mm: f64,
471    },
472    RoundRect {
473        radius_ratio: f64,
474    },
475    ChamferedRoundRect {
476        radius_ratio: f64,
477        chamfer_ratio: f64,
478        corners: Vec<AuthoredChamferCorner>,
479    },
480    CustomPolygon {
481        points: Vec<AuthoredPoint>,
482    },
483    /// Complete source composition. Prefer this over the legacy single-polygon
484    /// convenience when retaining an imported custom pad's policies.
485    Custom {
486        anchor: Option<AuthoredPadAnchor>,
487        clearance: Option<AuthoredCustomPadClearance>,
488        primitives: Vec<AuthoredPadPrimitive>,
489    },
490}
491
492impl AuthoredPadShape {
493    pub const fn as_str(&self) -> &'static str {
494        match self {
495            Self::Circle => "circle",
496            Self::Oval => "oval",
497            Self::Rect => "rect",
498            Self::Trapezoid { .. } => "trapezoid",
499            Self::RoundRect { .. } | Self::ChamferedRoundRect { .. } => "roundrect",
500            Self::CustomPolygon { .. } | Self::Custom { .. } => "custom",
501        }
502    }
503}
504
505#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
506pub enum AuthoredChamferCorner {
507    TopLeft,
508    TopRight,
509    BottomLeft,
510    BottomRight,
511}
512
513impl AuthoredChamferCorner {
514    pub const fn as_str(self) -> &'static str {
515        match self {
516            Self::TopLeft => "top_left",
517            Self::TopRight => "top_right",
518            Self::BottomLeft => "bottom_left",
519            Self::BottomRight => "bottom_right",
520        }
521    }
522}
523
524#[derive(Clone, Debug, PartialEq)]
525pub struct AuthoredDrill {
526    pub width_mm: f64,
527    pub height_mm: Option<f64>,
528    pub offset: AuthoredPoint,
529}
530
531#[derive(Clone, Debug, Eq, PartialEq)]
532pub struct AuthoredNetRef {
533    pub code: i64,
534    pub name: String,
535}
536
537#[derive(Clone, Copy, Debug, Eq, PartialEq)]
538pub enum AuthoredZoneConnection {
539    NoConnection,
540    ThermalRelief,
541    Solid,
542    ThermalReliefForThroughHole,
543}
544
545impl AuthoredZoneConnection {
546    pub const fn source_code(self) -> i64 {
547        match self {
548            Self::NoConnection => 0,
549            Self::ThermalRelief => 1,
550            Self::Solid => 2,
551            Self::ThermalReliefForThroughHole => 3,
552        }
553    }
554}
555
556#[derive(Clone, Debug, PartialEq)]
557pub struct AuthoredPad {
558    pub padstack: Option<AuthoredPadstack>,
559    pub number: String,
560    /// Board occurrence pin metadata; KiCad omits these in library footprints.
561    pub pin_function: Option<String>,
562    pub pin_type: Option<String>,
563    /// Signed, nonzero source length. Zero is KiCad's omitted default.
564    pub die_length_mm: Option<f64>,
565    pub kind: AuthoredPadKind,
566    pub shape: AuthoredPadShape,
567    pub at: AuthoredPoint,
568    pub angle_degrees: f64,
569    pub size_x_mm: f64,
570    pub size_y_mm: f64,
571    pub drill: Option<AuthoredDrill>,
572    pub layers: Vec<String>,
573    pub net: Option<AuthoredNetRef>,
574    pub uuid: String,
575    pub solder_mask_margin_mm: Option<f64>,
576    pub solder_paste_margin_mm: Option<f64>,
577    pub solder_paste_margin_ratio: Option<f64>,
578    pub clearance_mm: Option<f64>,
579    pub thermal_bridge_width_mm: Option<f64>,
580    pub thermal_bridge_angle_degrees: Option<f64>,
581    pub thermal_gap_mm: Option<f64>,
582    pub zone_connect: Option<AuthoredZoneConnection>,
583    pub zone_layer_connections: Vec<String>,
584    pub remove_unused_layers: Option<bool>,
585    pub keep_end_layers: Option<bool>,
586}
587
588#[derive(Clone, Copy, Debug, Eq, PartialEq)]
589pub enum AuthoredViaKind {
590    Through,
591    /// KiCad uses the `blind` source token for both blind and buried spans;
592    /// the selected copper endpoints preserve which case was authored.
593    BlindBuried,
594    Micro,
595}
596
597impl AuthoredViaKind {
598    pub const fn source_token(self) -> Option<&'static str> {
599        match self {
600            Self::Through => None,
601            Self::BlindBuried => Some("blind"),
602            Self::Micro => Some("micro"),
603        }
604    }
605}
606
607#[derive(Clone, Debug, Default, Eq, PartialEq)]
608pub struct AuthoredFrontBackPolicy {
609    pub front: Option<bool>,
610    pub back: Option<bool>,
611}
612
613#[derive(Clone, Debug, PartialEq)]
614pub struct AuthoredBackdrill {
615    pub size_mm: f64,
616    /// Source drill direction, which may run from B.Cu toward an inner layer.
617    pub start_layer: String,
618    pub end_layer: String,
619}
620
621#[derive(Clone, Debug, PartialEq)]
622pub struct AuthoredVia {
623    pub padstack: Option<AuthoredViaStack>,
624    pub kind: AuthoredViaKind,
625    pub at: AuthoredPoint,
626    pub size_mm: f64,
627    pub drill_mm: f64,
628    pub backdrill: Option<AuthoredBackdrill>,
629    pub start_layer: String,
630    pub end_layer: String,
631    pub free: bool,
632    pub net_code: i64,
633    pub uuid: String,
634    pub tenting: Option<AuthoredFrontBackPolicy>,
635    pub covering: Option<AuthoredFrontBackPolicy>,
636    pub plugging: Option<AuthoredFrontBackPolicy>,
637    pub capping: Option<bool>,
638    pub filling: Option<bool>,
639    pub zone_layer_connections: Vec<String>,
640    pub remove_unused_layers: Option<bool>,
641    pub keep_end_layers: Option<bool>,
642    pub start_end_only: Option<bool>,
643}
644
645#[derive(Clone, Debug, PartialEq)]
646pub struct AuthoredModel {
647    pub path: String,
648    /// Written `(hide yes)` when set; KiCad shows a model by default.
649    pub hidden: bool,
650    /// Written `(opacity x.xxxx)` when present; KiCad writes it only when the
651    /// opacity is not 1, its default.
652    pub opacity: Option<f64>,
653    pub offset_mm: [f64; 3],
654    pub scale: [f64; 3],
655    pub rotate_degrees: [f64; 3],
656}
657
658#[derive(Clone, Debug, Eq, PartialEq)]
659pub enum AuthoredResourceData {
660    DeclarationOnly,
661    Empty,
662    Bytes(Vec<u8>),
663}
664
665#[derive(Clone, Debug, Eq, PartialEq)]
666pub struct AuthoredEmbeddedFile {
667    pub name: String,
668    pub file_type: String,
669    pub data: AuthoredResourceData,
670}
671
672#[derive(Clone, Debug, PartialEq)]
673pub struct AuthoredFootprint {
674    pub name: String,
675    pub description: Option<String>,
676    pub tags: Option<String>,
677    pub attributes: Vec<String>,
678    /// Footprint-level surface-policy defaults. A pad-local value takes
679    /// precedence; otherwise these take precedence over the board setup.
680    pub solder_mask_margin_mm: Option<f64>,
681    pub solder_paste_margin_mm: Option<f64>,
682    pub solder_paste_margin_ratio: Option<f64>,
683    pub clearance_mm: Option<f64>,
684    /// Absent means inherit the zone's connection policy.
685    pub zone_connect: Option<AuthoredZoneConnection>,
686    /// `net_tie_pad_groups`: the pad numbers of each net tie, written as one
687    /// comma-separated string per group (`"1, 2"`).
688    pub net_tie_pad_groups: Vec<Vec<String>>,
689    /// `duplicate_pad_numbers_are_jumpers`: pads that share a number are one
690    /// jumper. Written only when set (KiCad's default is no).
691    pub duplicate_pad_numbers_are_jumpers: bool,
692    /// `jumper_pad_groups`: the pad numbers of each jumper, one child list
693    /// per group (`("1" "2")`).
694    pub jumper_pad_groups: Vec<Vec<String>>,
695    /// Properties with no authored presentation children. These remain
696    /// distinct from hidden graphical properties: emitting default coordinates
697    /// would create source geometry that did not exist.
698    pub scalar_properties: Vec<AuthoredFootprintScalarProperty>,
699    pub properties: Vec<AuthoredFootprintProperty>,
700    pub texts: Vec<AuthoredFootprintText>,
701    pub text_boxes: Vec<AuthoredTextBox>,
702    pub barcodes: Vec<AuthoredBarcode>,
703    pub graphics: Vec<AuthoredGraphic>,
704    pub pads: Vec<AuthoredPad>,
705    /// Rule areas the footprint owns, in its local frame as its graphics
706    /// are. A board occurrence writes them in board coordinates, as KiCad
707    /// stores a footprint's zones.
708    pub rule_areas: Vec<AuthoredRuleArea>,
709    /// `component_classes`: the names of the classes a board occurrence
710    /// belongs to (KiCad 9 static component classes).
711    pub component_classes: Vec<String>,
712    pub models: Vec<AuthoredModel>,
713    pub embedded_files: Vec<AuthoredEmbeddedFile>,
714}
715
716impl AuthoredFootprint {
717    pub fn new(name: impl Into<String>) -> Self {
718        Self {
719            name: name.into(),
720            description: None,
721            tags: None,
722            attributes: Vec::new(),
723            solder_mask_margin_mm: None,
724            solder_paste_margin_mm: None,
725            solder_paste_margin_ratio: None,
726            clearance_mm: None,
727            zone_connect: None,
728            net_tie_pad_groups: Vec::new(),
729            duplicate_pad_numbers_are_jumpers: false,
730            jumper_pad_groups: Vec::new(),
731            scalar_properties: Vec::new(),
732            properties: Vec::new(),
733            texts: Vec::new(),
734            text_boxes: Vec::new(),
735            barcodes: Vec::new(),
736            graphics: Vec::new(),
737            pads: Vec::new(),
738            rule_areas: Vec::new(),
739            component_classes: Vec::new(),
740            models: Vec::new(),
741            embedded_files: Vec::new(),
742        }
743    }
744}
745
746/// A fresh standalone `.kicad_mod` envelope around one local footprint definition.
747///
748/// This type owns document-only revision, producer, and default-layer facts so
749/// they cannot be silently ignored when the same definition is placed on a board.
750#[derive(Clone, Debug, PartialEq)]
751pub struct AuthoredStandaloneFootprint {
752    pub version: i64,
753    pub generator: String,
754    pub generator_version: String,
755    pub layer: String,
756    pub footprint: AuthoredFootprint,
757}
758
759impl AuthoredStandaloneFootprint {
760    pub fn new(name: impl Into<String>, layer: impl Into<String>) -> Self {
761        Self {
762            version: KICAD_SOURCE_VERSION_2024_12_29,
763            generator: "kicad_monkey".to_owned(),
764            generator_version: crate::ENGINE_VERSION.to_owned(),
765            layer: layer.into(),
766            footprint: AuthoredFootprint::new(name),
767        }
768    }
769
770    pub fn canonical_text(&self, limits: PcbAuthoringLimits) -> Result<String, Error> {
771        Ok(emit::footprint_text(self, limits)?.text)
772    }
773
774    /// The written footprint and the warnings about objects written as given.
775    pub fn canonical_text_with_warnings(
776        &self,
777        limits: PcbAuthoringLimits,
778    ) -> Result<PcbAuthoredText, Error> {
779        emit::footprint_text(self, limits)
780    }
781
782    pub fn to_document(&self, limits: PcbAuthoringLimits) -> Result<FootprintDocument, Error> {
783        FootprintDocument::parse(self.canonical_text(limits)?, limits.footprint_limits)
784    }
785}
786
787/// One placed board occurrence of a footprint definition.
788///
789/// Occurrence identity and transform are deliberately separate from the
790/// standalone document envelope. Member UUIDs inside `footprint` must also
791/// be distinct across repeated occurrences.
792#[derive(Clone, Debug, PartialEq)]
793pub struct AuthoredFootprintOccurrence {
794    pub footprint: AuthoredFootprint,
795    pub layer: String,
796    pub at: AuthoredPoint,
797    pub angle_degrees: f64,
798    pub uuid: String,
799    pub locked: bool,
800    /// Schematic UUID path, not a filesystem path. Owned by this occurrence.
801    pub placement_path: Option<String>,
802    pub placement_sheet_name: Option<String>,
803    pub placement_sheet_file: Option<String>,
804}
805
806impl AuthoredFootprintOccurrence {
807    /// Emit this actual occurrence fragment through the source writer.
808    /// Root pose/identity, fields and derived cache coordinates are validated.
809    /// This context-free fragment cannot prove board net/resource closure;
810    /// callers must separately validate actual board membership and bindings.
811    pub fn canonical_text(&self, limits: PcbAuthoringLimits) -> Result<String, Error> {
812        emit::occurrence_text(self, limits)
813    }
814}
815
816#[derive(Clone, Debug, PartialEq)]
817pub struct AuthoredSegment {
818    pub start: AuthoredPoint,
819    pub end: AuthoredPoint,
820    pub width_mm: f64,
821    pub layer: String,
822    /// Same-side solder-mask layer when the route is explicitly exposed.
823    pub solder_mask_layer: Option<String>,
824    /// Local opening expansion. Absence uses the board setup expansion.
825    pub solder_mask_margin_mm: Option<f64>,
826    pub net_code: i64,
827    pub uuid: String,
828}
829
830#[derive(Clone, Debug, PartialEq)]
831pub struct AuthoredRoutingArc {
832    pub start: AuthoredPoint,
833    pub mid: AuthoredPoint,
834    pub end: AuthoredPoint,
835    pub width_mm: f64,
836    pub layer: String,
837    /// Same-side solder-mask layer when the route is explicitly exposed.
838    pub solder_mask_layer: Option<String>,
839    /// Local opening expansion. Absence uses the board setup expansion.
840    pub solder_mask_margin_mm: Option<f64>,
841    pub net_code: i64,
842    pub uuid: String,
843}
844
845#[derive(Clone, Copy, Debug, Eq, PartialEq)]
846pub enum AuthoredZoneHatch {
847    None,
848    Edge,
849    Full,
850}
851
852impl AuthoredZoneHatch {
853    pub const fn as_str(self) -> &'static str {
854        match self {
855            Self::None => "none",
856            Self::Edge => "edge",
857            Self::Full => "full",
858        }
859    }
860}
861
862#[derive(Clone, Copy, Debug, Eq, PartialEq)]
863pub enum AuthoredZonePadConnection {
864    ThermalRelief,
865    NoConnection,
866    Solid,
867    ThroughHoleOnly,
868}
869
870impl AuthoredZonePadConnection {
871    pub const fn source_token(self) -> Option<&'static str> {
872        match self {
873            Self::ThermalRelief => None,
874            Self::NoConnection => Some("no"),
875            Self::Solid => Some("yes"),
876            Self::ThroughHoleOnly => Some("thru_hole_only"),
877        }
878    }
879}
880
881/// KiCad's `hatch_border_algorithm`: the hatch fill's border is as wide as
882/// the hatch lines or as the zone's minimum thickness.
883#[derive(Clone, Copy, Debug, Eq, PartialEq)]
884pub enum AuthoredZoneHatchBorder {
885    HatchThickness,
886    MinThickness,
887}
888
889impl AuthoredZoneHatchBorder {
890    pub const fn as_str(self) -> &'static str {
891        match self {
892            Self::HatchThickness => "hatch_thickness",
893            Self::MinThickness => "min_thickness",
894        }
895    }
896
897    pub fn from_source_token(token: &str) -> Option<Self> {
898        match token {
899            "hatch_thickness" => Some(Self::HatchThickness),
900            "min_thickness" => Some(Self::MinThickness),
901            _ => None,
902        }
903    }
904}
905
906/// A hatch-pattern fill (`(mode hatch)`), written as pcbnew writes it.
907#[derive(Clone, Debug, PartialEq)]
908pub struct AuthoredZoneHatchedFill {
909    pub thickness_mm: f64,
910    pub gap_mm: f64,
911    pub orientation_deg: f64,
912    /// `hatch_smoothing_level` (0 is none; written, with
913    /// `hatch_smoothing_value`, only when positive).
914    pub smoothing_level: i64,
915    pub smoothing_value: f64,
916    pub border: AuthoredZoneHatchBorder,
917    pub min_hole_area: f64,
918}
919
920impl AuthoredZoneHatchedFill {
921    /// A hatch fill with pcbnew's defaults for the refinements: no
922    /// smoothing (value 0.1), hatch-thickness border, minimum hole area 0.3.
923    pub fn new(thickness_mm: f64, gap_mm: f64, orientation_deg: f64) -> Self {
924        Self {
925            thickness_mm,
926            gap_mm,
927            orientation_deg,
928            smoothing_level: 0,
929            smoothing_value: 0.1,
930            border: AuthoredZoneHatchBorder::HatchThickness,
931            min_hole_area: 0.3,
932        }
933    }
934}
935
936#[derive(Clone, Debug, PartialEq)]
937pub struct AuthoredZoneFill {
938    pub enabled: bool,
939    pub hatch: Option<AuthoredZoneHatchedFill>,
940    pub thermal_gap_mm: f64,
941    pub thermal_bridge_width_mm: f64,
942    pub island_removal_mode: Option<i64>,
943    pub island_area_min_mm2: Option<f64>,
944}
945
946#[derive(Clone, Debug, PartialEq)]
947pub struct AuthoredZonePolygon {
948    /// One source ring in board coordinates. Winding/topology remains caller-owned.
949    pub points: Vec<AuthoredPoint>,
950    /// The edge from `points[i]` to the next point is an arc through
951    /// `arc_mids[i]` when that is `Some`; empty means every edge is straight.
952    /// An arc edge is written as KiCad's `(arc (start) (mid) (end))`.
953    pub arc_mids: Vec<Option<AuthoredPoint>>,
954}
955
956#[derive(Clone, Debug, PartialEq)]
957pub struct AuthoredZoneFilledPolygon {
958    pub layer: String,
959    pub island: bool,
960    /// One authoritative KiCad fill-cache point chain in board coordinates.
961    /// Holes are already bridge/fracture-encoded within this chain; they are
962    /// not separate `filled_polygon` records and are not inferred here.
963    pub points: Vec<AuthoredPoint>,
964}
965
966#[derive(Clone, Debug, PartialEq)]
967pub struct AuthoredZone {
968    pub net: AuthoredNetRef,
969    pub layers: Vec<String>,
970    pub locked: bool,
971    pub uuid: String,
972    pub name: Option<String>,
973    pub hatch: AuthoredZoneHatch,
974    pub hatch_pitch_mm: f64,
975    pub priority: i64,
976    pub pad_connection: AuthoredZonePadConnection,
977    pub connect_pads_clearance_mm: f64,
978    pub min_thickness_mm: f64,
979    pub filled_areas_thickness: Option<bool>,
980    pub fill: Option<AuthoredZoneFill>,
981    pub outlines: Vec<AuthoredZonePolygon>,
982    pub filled_polygons: Vec<AuthoredZoneFilledPolygon>,
983}
984
985impl AuthoredZone {
986    /// Emit one zone with explicit actual net/layer catalogues. This proves
987    /// those references and local Source fields, not other board-family closure.
988    pub fn canonical_text(
989        &self,
990        layers: &[AuthoredLayer],
991        nets: &[AuthoredNet],
992        limits: PcbAuthoringLimits,
993    ) -> Result<String, Error> {
994        emit::zone_text(self, layers, nets, limits)
995    }
996}
997
998/// A KiCad 10 board dimension kind, with the fields only that kind has.
999#[derive(Clone, Debug, PartialEq)]
1000pub enum AuthoredDimensionKind {
1001    /// Measures the distance between its two points along their line.
1002    Aligned {
1003        /// Signed distance of the dimension line from the measured points.
1004        height_mm: f64,
1005        extension_height_mm: f64,
1006        arrow_direction: AuthoredDimensionArrowDirection,
1007    },
1008    /// Measures the horizontal or vertical distance between its two points.
1009    Orthogonal {
1010        height_mm: f64,
1011        extension_height_mm: f64,
1012        arrow_direction: AuthoredDimensionArrowDirection,
1013        orientation: AuthoredDimensionOrientation,
1014    },
1015    /// An arrow from its start to a text at the end of a leader line.
1016    Leader {
1017        text_frame: AuthoredDimensionTextFrame,
1018    },
1019    /// A center mark: a cross at its start, one arm reaching its end. KiCad
1020    /// writes no `format` and no text for it.
1021    Center,
1022    /// Measures the radius from its start (the center) to its end, with a
1023    /// leader of this length.
1024    Radial { leader_length_mm: f64 },
1025}
1026
1027impl AuthoredDimensionKind {
1028    /// The `(type ...)` token KiCad writes.
1029    pub const fn source_token(&self) -> &'static str {
1030        match self {
1031            Self::Aligned { .. } => "aligned",
1032            Self::Orthogonal { .. } => "orthogonal",
1033            Self::Leader { .. } => "leader",
1034            Self::Center => "center",
1035            Self::Radial { .. } => "radial",
1036        }
1037    }
1038}
1039
1040/// KiCad's `arrow_direction`, written for aligned and orthogonal dimensions.
1041#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1042pub enum AuthoredDimensionArrowDirection {
1043    Inward,
1044    #[default]
1045    Outward,
1046}
1047
1048impl AuthoredDimensionArrowDirection {
1049    pub const fn source_token(self) -> &'static str {
1050        match self {
1051            Self::Inward => "inward",
1052            Self::Outward => "outward",
1053        }
1054    }
1055
1056    pub fn from_source_token(token: &str) -> Option<Self> {
1057        match token {
1058            "inward" => Some(Self::Inward),
1059            "outward" => Some(Self::Outward),
1060            _ => None,
1061        }
1062    }
1063}
1064
1065/// An orthogonal dimension's `orientation` (KiCad's `PCB_DIM_ORTHOGONAL::DIR`).
1066#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1067pub enum AuthoredDimensionOrientation {
1068    Horizontal,
1069    Vertical,
1070}
1071
1072impl AuthoredDimensionOrientation {
1073    pub const fn source_code(self) -> i64 {
1074        match self {
1075            Self::Horizontal => 0,
1076            Self::Vertical => 1,
1077        }
1078    }
1079
1080    pub const fn from_source_code(code: i64) -> Option<Self> {
1081        match code {
1082            0 => Some(Self::Horizontal),
1083            1 => Some(Self::Vertical),
1084            _ => None,
1085        }
1086    }
1087}
1088
1089/// A leader's `text_frame` (KiCad's `DIM_TEXT_BORDER`).
1090#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1091pub enum AuthoredDimensionTextFrame {
1092    #[default]
1093    None,
1094    Rectangle,
1095    Circle,
1096    RoundRect,
1097}
1098
1099impl AuthoredDimensionTextFrame {
1100    pub const fn source_code(self) -> i64 {
1101        match self {
1102            Self::None => 0,
1103            Self::Rectangle => 1,
1104            Self::Circle => 2,
1105            Self::RoundRect => 3,
1106        }
1107    }
1108
1109    pub const fn from_source_code(code: i64) -> Option<Self> {
1110        match code {
1111            0 => Some(Self::None),
1112            1 => Some(Self::Rectangle),
1113            2 => Some(Self::Circle),
1114            3 => Some(Self::RoundRect),
1115            _ => None,
1116        }
1117    }
1118}
1119
1120/// The `units` of a dimension's value (KiCad's `DIM_UNITS_MODE`).
1121#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1122pub enum AuthoredDimensionUnits {
1123    Inch,
1124    Mils,
1125    #[default]
1126    Mm,
1127    Automatic,
1128}
1129
1130impl AuthoredDimensionUnits {
1131    pub const fn source_code(self) -> i64 {
1132        match self {
1133            Self::Inch => 0,
1134            Self::Mils => 1,
1135            Self::Mm => 2,
1136            Self::Automatic => 3,
1137        }
1138    }
1139
1140    pub const fn from_source_code(code: i64) -> Option<Self> {
1141        match code {
1142            0 => Some(Self::Inch),
1143            1 => Some(Self::Mils),
1144            2 => Some(Self::Mm),
1145            3 => Some(Self::Automatic),
1146            _ => None,
1147        }
1148    }
1149}
1150
1151/// How a dimension's value shows its unit (KiCad's `DIM_UNITS_FORMAT`).
1152#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1153pub enum AuthoredDimensionUnitsFormat {
1154    /// `1234.0`
1155    NoSuffix,
1156    /// `1234.0 mm`
1157    #[default]
1158    BareSuffix,
1159    /// `1234.0 (mm)`
1160    ParenSuffix,
1161}
1162
1163impl AuthoredDimensionUnitsFormat {
1164    pub const fn source_code(self) -> i64 {
1165        match self {
1166            Self::NoSuffix => 0,
1167            Self::BareSuffix => 1,
1168            Self::ParenSuffix => 2,
1169        }
1170    }
1171
1172    pub const fn from_source_code(code: i64) -> Option<Self> {
1173        match code {
1174            0 => Some(Self::NoSuffix),
1175            1 => Some(Self::BareSuffix),
1176            2 => Some(Self::ParenSuffix),
1177            _ => None,
1178        }
1179    }
1180}
1181
1182/// Where a dimension's text sits (KiCad's `DIM_TEXT_POSITION`).
1183#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1184pub enum AuthoredDimensionTextPosition {
1185    #[default]
1186    Outside,
1187    Inline,
1188    Manual,
1189}
1190
1191impl AuthoredDimensionTextPosition {
1192    pub const fn source_code(self) -> i64 {
1193        match self {
1194            Self::Outside => 0,
1195            Self::Inline => 1,
1196            Self::Manual => 2,
1197        }
1198    }
1199
1200    pub const fn from_source_code(code: i64) -> Option<Self> {
1201        match code {
1202            0 => Some(Self::Outside),
1203            1 => Some(Self::Inline),
1204            2 => Some(Self::Manual),
1205            _ => None,
1206        }
1207    }
1208}
1209
1210/// A dimension's `format`: how its value is written.
1211#[derive(Clone, Debug, PartialEq)]
1212pub struct AuthoredDimensionFormat {
1213    pub prefix: String,
1214    pub suffix: String,
1215    pub units: AuthoredDimensionUnits,
1216    pub units_format: AuthoredDimensionUnitsFormat,
1217    /// KiCad's `DIM_PRECISION` code, written as given: 0 to 5 are fixed
1218    /// decimal places, 6 to 9 the unit-scaled `V_VV` forms.
1219    pub precision: i64,
1220    /// Text shown in place of the measured value.
1221    pub override_value: Option<String>,
1222    pub suppress_zeroes: bool,
1223}
1224
1225impl Default for AuthoredDimensionFormat {
1226    /// KiCad's defaults, as the reader takes them when `format` is absent.
1227    fn default() -> Self {
1228        Self {
1229            prefix: String::new(),
1230            suffix: String::new(),
1231            units: AuthoredDimensionUnits::Mm,
1232            units_format: AuthoredDimensionUnitsFormat::BareSuffix,
1233            precision: 4,
1234            override_value: None,
1235            suppress_zeroes: false,
1236        }
1237    }
1238}
1239
1240/// A dimension's `style`, the fields every kind writes.
1241#[derive(Clone, Debug, PartialEq)]
1242pub struct AuthoredDimensionStyle {
1243    pub thickness_mm: f64,
1244    pub arrow_length_mm: f64,
1245    pub text_position: AuthoredDimensionTextPosition,
1246    pub extension_offset_mm: f64,
1247    pub keep_text_aligned: bool,
1248}
1249
1250/// A dimension's `gr_text`. Its layer, lock and UUID are the dimension's:
1251/// KiCad writes the dimension's own as the text's
1252/// (pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.cpp:994-995 and 2265-2329
1253/// at 10.0.8). Color and hyperlink are never written (:2318-2322).
1254#[derive(Clone, Debug, PartialEq)]
1255pub struct AuthoredDimensionText {
1256    /// The shown text, value with prefix and suffix, as KiCad last drew it.
1257    pub text: String,
1258    pub at: AuthoredPoint,
1259    pub angle_degrees: f64,
1260    pub knockout: bool,
1261    pub effects: AuthoredTextEffects,
1262    pub render_cache: Option<TextRenderCache>,
1263}
1264
1265/// One board `(dimension ...)`, written as KiCad 10.0.8 saves it
1266/// (pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.cpp:886-998).
1267#[derive(Clone, Debug, PartialEq)]
1268pub struct AuthoredDimension {
1269    pub kind: AuthoredDimensionKind,
1270    pub layer: String,
1271    pub locked: bool,
1272    /// Written as the dimension's and its text's UUID. A source dimension
1273    /// whose `gr_text` carries another UUID loads in KiCad with the text's
1274    /// (parseDIMENSION parses the text into the dimension,
1275    /// pcb_io_kicad_sexpr_parser.cpp:4715 and 4019-4024 at 10.0.8).
1276    pub uuid: String,
1277    /// The `pts` pair: KiCad's start and end.
1278    pub start: AuthoredPoint,
1279    pub end: AuthoredPoint,
1280    /// KiCad writes one for every kind but [`AuthoredDimensionKind::Center`],
1281    /// which must have `None`. `None` on another kind writes none, and KiCad
1282    /// loads its defaults (those of [`AuthoredDimensionFormat::default`]).
1283    pub format: Option<AuthoredDimensionFormat>,
1284    pub style: AuthoredDimensionStyle,
1285    /// KiCad writes one for every kind but a center mark, which must have
1286    /// `None`. `None` on another kind writes no `gr_text`.
1287    pub text: Option<AuthoredDimensionText>,
1288}
1289
1290/// What the writer reports about a source it wrote.
1291#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1292pub enum PcbAuthoringWarningCode {
1293    /// A KiCad UUID occurs more than once. It is written as given: KiCad
1294    /// loads and saves repeated UUIDs as they are.
1295    UuidRepeated,
1296    /// A group's own UUID, or a UUID it names as a member, is repeated. The
1297    /// group is written as given, but KiCad binds it through a cache that
1298    /// keeps only the last item loaded with a UUID, so the membership it
1299    /// loads is ambiguous in the source itself.
1300    GroupMembershipAmbiguous,
1301}
1302
1303impl PcbAuthoringWarningCode {
1304    pub const fn as_str(self) -> &'static str {
1305        match self {
1306            Self::UuidRepeated => "uuid_repeated",
1307            Self::GroupMembershipAmbiguous => "group_membership_ambiguous",
1308        }
1309    }
1310}
1311
1312/// One warning about a written source; the object was written.
1313#[derive(Clone, Debug, Eq, PartialEq)]
1314pub struct PcbAuthoringWarning {
1315    pub code: PcbAuthoringWarningCode,
1316    /// The authored object kind, for example `pad` or `footprint property`.
1317    pub object_kind: String,
1318    pub uuid: Option<String>,
1319    pub message: String,
1320}
1321
1322/// A written source and the warnings about it.
1323#[derive(Clone, Debug, Eq, PartialEq)]
1324pub struct PcbAuthoredText {
1325    pub text: String,
1326    /// One warning per reported object, in validation order.
1327    pub warnings: Vec<PcbAuthoringWarning>,
1328}
1329
1330/// One board-root source property, independent of footprint graphical fields.
1331#[derive(Clone, Debug, Eq, PartialEq)]
1332pub struct AuthoredProperty {
1333    pub name: String,
1334    pub value: String,
1335}
1336
1337/// A board-owned editor group. Members are UUIDs of board-root items or groups,
1338/// not footprint children. This does not author design-block library links.
1339#[derive(Clone, Debug, Eq, PartialEq)]
1340pub struct AuthoredGroup {
1341    pub name: String,
1342    pub uuid: String,
1343    pub locked: bool,
1344    pub members: Vec<String>,
1345}
1346
1347#[derive(Clone, Debug, PartialEq)]
1348pub struct AuthoredPcb {
1349    pub version: i64,
1350    pub generator: String,
1351    pub generator_version: String,
1352    pub thickness_mm: f64,
1353    pub paper: String,
1354    pub layers: Vec<AuthoredLayer>,
1355    pub setup: AuthoredSetup,
1356    pub properties: Vec<AuthoredProperty>,
1357    pub nets: Vec<AuthoredNet>,
1358    pub profile: Vec<AuthoredGraphic>,
1359    pub graphics: Vec<AuthoredGraphic>,
1360    pub texts: Vec<AuthoredBoardText>,
1361    pub text_boxes: Vec<AuthoredTextBox>,
1362    pub barcodes: Vec<AuthoredBarcode>,
1363    pub dimensions: Vec<AuthoredDimension>,
1364    pub footprints: Vec<AuthoredFootprintOccurrence>,
1365    pub vias: Vec<AuthoredVia>,
1366    pub segments: Vec<AuthoredSegment>,
1367    pub arcs: Vec<AuthoredRoutingArc>,
1368    pub zones: Vec<AuthoredZone>,
1369    pub rule_areas: Vec<AuthoredRuleArea>,
1370    pub groups: Vec<AuthoredGroup>,
1371    pub embedded_files: Vec<AuthoredEmbeddedFile>,
1372}
1373
1374impl Default for AuthoredPcb {
1375    fn default() -> Self {
1376        Self {
1377            version: KICAD_SOURCE_VERSION_2024_12_29,
1378            generator: "kicad_monkey".to_owned(),
1379            generator_version: crate::ENGINE_VERSION.to_owned(),
1380            thickness_mm: 1.6,
1381            paper: "A4".to_owned(),
1382            layers: Vec::new(),
1383            setup: AuthoredSetup::default(),
1384            properties: Vec::new(),
1385            nets: Vec::new(),
1386            profile: Vec::new(),
1387            graphics: Vec::new(),
1388            texts: Vec::new(),
1389            text_boxes: Vec::new(),
1390            barcodes: Vec::new(),
1391            dimensions: Vec::new(),
1392            footprints: Vec::new(),
1393            vias: Vec::new(),
1394            segments: Vec::new(),
1395            arcs: Vec::new(),
1396            zones: Vec::new(),
1397            rule_areas: Vec::new(),
1398            groups: Vec::new(),
1399            embedded_files: Vec::new(),
1400        }
1401    }
1402}
1403
1404impl AuthoredPcb {
1405    /// The written board. Use [`Self::canonical_text_with_warnings`] to keep
1406    /// what the writer reports, such as repeated UUIDs.
1407    pub fn canonical_text(&self, limits: PcbAuthoringLimits) -> Result<String, Error> {
1408        Ok(emit::board_text(self, limits)?.text)
1409    }
1410
1411    /// The written board and the warnings about objects written as given.
1412    pub fn canonical_text_with_warnings(
1413        &self,
1414        limits: PcbAuthoringLimits,
1415    ) -> Result<PcbAuthoredText, Error> {
1416        emit::board_text(self, limits)
1417    }
1418
1419    pub fn to_document(&self, limits: PcbAuthoringLimits) -> Result<PcbDocument, Error> {
1420        PcbDocument::parse(self.canonical_text(limits)?, limits.pcb_limits)
1421    }
1422}