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

kicad_monkey_core/
pcb.rs

1//! Native, source-backed views and focused edits for KiCad PCB documents.
2//!
3//! The board model indexes exact source spans and decodes domain records on
4//! demand. It intentionally does not construct the generic compatibility tree.
5
6#[cfg(feature = "embedded-resource-zstd")]
7use crate::embedded_resource::decoded_data;
8use crate::embedded_resource::{encoded_data, metadata_from_span};
9use crate::sexpr::{
10    Error, ErrorKind, ErrorPhase, Lexer, Patch, Position, Sexp, Token, TokenKind,
11    apply_patches_with_limit, build_with_limit, decode_quoted, decode_quoted_with_limit,
12    is_teardrop_numeric_key,
13};
14use crate::sexpr_projection::{FormSpan, Selector};
15use crate::{KiCadPaper, KiCadTextEffects, KiCadTitleBlock};
16use std::collections::BTreeMap;
17use std::ops::Range;
18
19mod counts;
20mod decode;
21mod document;
22mod extended;
23mod fabrication;
24mod footprint_parameters;
25mod footprints;
26mod indexing;
27mod manufacturing;
28mod pads;
29mod padstacks;
30mod physical;
31mod primary;
32mod scalars;
33mod selection;
34mod setup;
35mod text;
36mod vias;
37mod view_edits;
38mod view_resources;
39mod zones;
40use self::{decode::*, indexing::*, scalars::*};
41pub use crate::embedded_resource::{
42    EmbeddedDataPresence as PcbEmbeddedDataPresence, EmbeddedFile as PcbEmbeddedFile,
43    EmbeddedFileOwner as PcbEmbeddedFileOwner,
44};
45pub use extended::{
46    PcbBarcode, PcbBoardMetadata, PcbBoardVariant, PcbImage, PcbTable, PcbTableCell,
47};
48pub use fabrication::PcbAnnularRingStats;
49pub use footprint_parameters::is_standalone_footprint_custom_property;
50pub(crate) use footprint_parameters::standalone_parameter_values;
51pub use footprints::{
52    PcbFootprintGraphic, PcbFootprintProperty, PcbFootprintText, PcbFootprintTextBox,
53};
54pub use manufacturing::{
55    PcbDrillLayerSpan, PcbDrillProperties, PcbPostMachiningProperties, PcbTeardropParameters,
56    PcbZoneLayerConnections,
57};
58pub use pads::{
59    PcbPad, PcbPadCustomOptions, PcbPadCustomPrimitive, PcbPadPolygonPoint, PcbPadPrimitiveGeometry,
60};
61pub use padstacks::{
62    PcbPadstack, PcbPadstackLayer, PcbResolvedPadCopperLayer, PcbViaStack, PcbViaStackLayer,
63    resolve_pad_copper_layer,
64};
65pub use physical::{
66    PcbFootprintTransform, PcbHole, PcbHoleOwner, PcbHoleShape, PcbPadDrill, PcbProfileOwner,
67    PcbProfilePrimitive,
68};
69pub use primary::{
70    PcbFootprintPrimaryBatch, PcbFootprintPrimaryFieldResults, footprint_primary_property_name,
71};
72pub(crate) use primary::{
73    standalone_primary_fields, standalone_primary_property_name, standalone_primary_values,
74};
75pub use selection::{PcbFamily, PcbSelection};
76pub use setup::{PcbSetup, PcbStackup, PcbStackupLayer, PcbStackupSubLayer};
77pub use text::{PcbBoardText, PcbBoardTextBox};
78pub use vias::{PcbFrontBackOptionalBool, PcbVia};
79pub use zones::{
80    PcbFootprintZone, PcbZone, PcbZoneFilledPolygon, PcbZoneKeepout, PcbZoneLayerProperty,
81    PcbZonePlacement, PcbZonePlacementSource, PcbZonePolygon,
82};
83
84/// Ignored ceilings, defaulting to `usize::MAX`: KiCad reads and plots boards
85/// and footprints without them (#612). Request hosts still pass caller values.
86#[derive(Clone, Copy, Debug, Eq, PartialEq)]
87pub struct PcbLimits {
88    pub max_source_bytes: usize,
89    pub max_output_bytes: usize,
90    pub max_depth: usize,
91    pub max_top_level_forms: usize,
92    pub max_object_children: usize,
93    pub max_setup_children: usize,
94    pub max_stackup_layers: usize,
95    pub max_title_block_children: usize,
96    pub max_title_block_comments: usize,
97    pub max_layers: usize,
98    pub max_nets: usize,
99    pub max_properties: usize,
100    pub max_footprints: usize,
101    pub max_footprint_children: usize,
102    pub max_footprint_header_scalars: usize,
103    pub max_footprint_attributes: usize,
104    pub max_footprint_properties: usize,
105    pub max_footprint_graphics: usize,
106    pub max_footprint_texts: usize,
107    pub max_footprint_text_boxes: usize,
108    pub max_text_effect_children: usize,
109    pub max_text_font_children: usize,
110    pub max_text_justify_tokens: usize,
111    pub max_text_box_points: usize,
112    pub max_pad_header_scalars: usize,
113    pub max_pad_children: usize,
114    pub max_pad_chamfer_corners: usize,
115    pub max_pad_custom_primitives: usize,
116    pub max_pad_custom_point_forms: usize,
117    pub max_pad_custom_points: usize,
118    pub max_via_header_scalars: usize,
119    pub max_via_children: usize,
120    pub max_via_policy_children: usize,
121    pub max_manufacturing_children: usize,
122    pub max_teardrop_scalars: usize,
123    pub max_zone_layer_connections: usize,
124    pub max_model_children: usize,
125    pub max_pads: usize,
126    pub max_models: usize,
127    pub max_segments: usize,
128    pub max_vias: usize,
129    pub max_zones: usize,
130    pub max_zone_polygons: usize,
131    pub max_zone_points: usize,
132    pub max_zone_layer_properties: usize,
133    pub max_arcs: usize,
134    pub max_graphics: usize,
135    pub max_graphic_points: usize,
136    pub max_dimensions: usize,
137    pub max_groups: usize,
138    pub max_generated_items: usize,
139    pub max_generated_children: usize,
140    pub max_members: usize,
141    pub max_embedded_files: usize,
142    pub max_variants: usize,
143    pub max_images: usize,
144    pub max_image_data_parts: usize,
145    pub max_barcodes: usize,
146    pub max_tables: usize,
147    pub max_table_cells: usize,
148    pub max_table_values: usize,
149}
150
151impl PcbLimits {
152    pub(crate) fn intersect(self, other: Self) -> Self {
153        macro_rules! minimums {
154            ($($field:ident),+ $(,)?) => {
155                Self {
156                    $($field: self.$field.min(other.$field),)+
157                }
158            };
159        }
160        minimums!(
161            max_source_bytes,
162            max_output_bytes,
163            max_depth,
164            max_top_level_forms,
165            max_object_children,
166            max_setup_children,
167            max_stackup_layers,
168            max_title_block_children,
169            max_title_block_comments,
170            max_layers,
171            max_nets,
172            max_properties,
173            max_footprints,
174            max_footprint_children,
175            max_footprint_header_scalars,
176            max_footprint_attributes,
177            max_footprint_properties,
178            max_footprint_graphics,
179            max_footprint_texts,
180            max_footprint_text_boxes,
181            max_text_effect_children,
182            max_text_font_children,
183            max_text_justify_tokens,
184            max_text_box_points,
185            max_pad_header_scalars,
186            max_pad_children,
187            max_pad_chamfer_corners,
188            max_pad_custom_primitives,
189            max_pad_custom_point_forms,
190            max_pad_custom_points,
191            max_via_header_scalars,
192            max_via_children,
193            max_via_policy_children,
194            max_manufacturing_children,
195            max_teardrop_scalars,
196            max_zone_layer_connections,
197            max_model_children,
198            max_pads,
199            max_models,
200            max_segments,
201            max_vias,
202            max_zones,
203            max_zone_polygons,
204            max_zone_points,
205            max_zone_layer_properties,
206            max_arcs,
207            max_graphics,
208            max_graphic_points,
209            max_dimensions,
210            max_groups,
211            max_generated_items,
212            max_generated_children,
213            max_members,
214            max_embedded_files,
215            max_variants,
216            max_images,
217            max_image_data_parts,
218            max_barcodes,
219            max_tables,
220            max_table_cells,
221            max_table_values,
222        )
223    }
224}
225
226impl Default for PcbLimits {
227    fn default() -> Self {
228        Self {
229            max_source_bytes: usize::MAX,
230            max_output_bytes: usize::MAX,
231            max_depth: usize::MAX,
232            max_top_level_forms: usize::MAX,
233            max_object_children: usize::MAX,
234            max_setup_children: usize::MAX,
235            max_stackup_layers: usize::MAX,
236            max_title_block_children: usize::MAX,
237            max_title_block_comments: usize::MAX,
238            max_layers: usize::MAX,
239            max_nets: usize::MAX,
240            max_properties: usize::MAX,
241            max_footprints: usize::MAX,
242            max_footprint_children: usize::MAX,
243            max_footprint_header_scalars: usize::MAX,
244            max_footprint_attributes: usize::MAX,
245            max_footprint_properties: usize::MAX,
246            max_footprint_graphics: usize::MAX,
247            max_footprint_texts: usize::MAX,
248            max_footprint_text_boxes: usize::MAX,
249            max_text_effect_children: usize::MAX,
250            max_text_font_children: usize::MAX,
251            max_text_justify_tokens: usize::MAX,
252            max_text_box_points: usize::MAX,
253            max_pad_header_scalars: usize::MAX,
254            max_pad_children: usize::MAX,
255            max_pad_chamfer_corners: usize::MAX,
256            max_pad_custom_primitives: usize::MAX,
257            max_pad_custom_point_forms: usize::MAX,
258            max_pad_custom_points: usize::MAX,
259            max_via_header_scalars: usize::MAX,
260            max_via_children: usize::MAX,
261            max_via_policy_children: usize::MAX,
262            max_manufacturing_children: usize::MAX,
263            max_teardrop_scalars: usize::MAX,
264            max_zone_layer_connections: usize::MAX,
265            max_model_children: usize::MAX,
266            max_pads: usize::MAX,
267            max_models: usize::MAX,
268            max_segments: usize::MAX,
269            max_vias: usize::MAX,
270            max_zones: usize::MAX,
271            max_zone_polygons: usize::MAX,
272            max_zone_points: usize::MAX,
273            max_zone_layer_properties: usize::MAX,
274            max_arcs: usize::MAX,
275            max_graphics: usize::MAX,
276            max_graphic_points: usize::MAX,
277            max_dimensions: usize::MAX,
278            max_groups: usize::MAX,
279            max_generated_items: usize::MAX,
280            max_generated_children: usize::MAX,
281            max_members: usize::MAX,
282            max_embedded_files: usize::MAX,
283            max_variants: usize::MAX,
284            max_images: usize::MAX,
285            max_image_data_parts: usize::MAX,
286            max_barcodes: usize::MAX,
287            max_tables: usize::MAX,
288            max_table_cells: usize::MAX,
289            max_table_values: usize::MAX,
290        }
291    }
292}
293
294/// Collection counts used to compare the lazy view with the Python model.
295#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
296pub struct PcbCounts {
297    pub layers: usize,
298    pub nets: usize,
299    pub properties: usize,
300    pub variants: usize,
301    pub footprints: usize,
302    pub footprint_properties: usize,
303    pub pads: usize,
304    pub models: usize,
305    pub footprint_graphics: usize,
306    pub footprint_texts: usize,
307    pub footprint_text_boxes: usize,
308    /// Zones and rule areas owned by board footprints.
309    pub footprint_zones: usize,
310    pub segments: usize,
311    pub vias: usize,
312    pub zones: usize,
313    pub arcs: usize,
314    pub graphics: usize,
315    pub gr_texts: usize,
316    pub gr_lines: usize,
317    pub gr_rects: usize,
318    pub gr_arcs: usize,
319    pub gr_circles: usize,
320    pub gr_polys: usize,
321    pub gr_curves: usize,
322    pub gr_text_boxes: usize,
323    pub images: usize,
324    pub barcodes: usize,
325    pub tables: usize,
326    pub table_cells: usize,
327    pub groups: usize,
328    pub dimensions: usize,
329    pub generated_items: usize,
330    pub embedded_files: usize,
331    pub footprint_embedded_files: usize,
332    pub unknown_top_level: usize,
333}
334
335/// One exact top-level PCB property and its editable value range.
336#[derive(Clone, Debug, PartialEq)]
337pub struct PcbProperty {
338    pub name: String,
339    pub value: String,
340    pub source_range: Range<usize>,
341    value_range: Range<usize>,
342}
343
344#[derive(Clone, Debug, PartialEq)]
345pub struct PcbLayer {
346    pub ordinal: i64,
347    pub name: String,
348    pub kind: String,
349    pub user_name: Option<String>,
350    pub source_range: Range<usize>,
351}
352
353#[derive(Clone, Debug, PartialEq)]
354pub struct PcbNet {
355    pub code: i64,
356    pub name: String,
357    pub source_range: Range<usize>,
358}
359
360/// A board-object net reference, which KiCad may encode by ordinal or name.
361#[derive(Clone, Debug, Default, Eq, PartialEq)]
362pub struct PcbNetRef {
363    pub ordinal: Option<i64>,
364    pub name: Option<String>,
365}
366
367#[derive(Clone, Debug, PartialEq)]
368pub struct PcbFootprint {
369    pub library_link: String,
370    pub reference: Option<String>,
371    pub value: Option<String>,
372    pub layer: Option<String>,
373    pub at_x: Option<f64>,
374    pub at_y: Option<f64>,
375    pub angle: Option<f64>,
376    pub locked: bool,
377    pub placement_path: Option<String>,
378    pub placement_sheet_name: Option<String>,
379    pub placement_sheet_file: Option<String>,
380    pub uuid: Option<String>,
381    pub description: String,
382    pub tags: String,
383    pub attributes: Vec<String>,
384    pub component_classes: Vec<PcbComponentClassRef>,
385    pub private_layers: Vec<String>,
386    pub net_tie_pad_groups: Vec<PcbPadNameGroup>,
387    pub embedded_fonts: bool,
388    pub duplicate_pad_numbers_are_jumpers: Option<bool>,
389    pub jumper_pad_groups: Vec<PcbPadNameGroup>,
390    pub solder_mask_margin: Option<f64>,
391    pub solder_paste_margin: Option<f64>,
392    pub solder_paste_margin_ratio: Option<f64>,
393    pub clearance: Option<f64>,
394    pub zone_connect: Option<i64>,
395    pub thermal_width: Option<f64>,
396    pub thermal_gap: Option<f64>,
397    pub property_count: usize,
398    pub graphic_count: usize,
399    pub text_count: usize,
400    pub text_box_count: usize,
401    pub pad_count: usize,
402    pub model_count: usize,
403    pub embedded_file_count: usize,
404    pub source_range: Range<usize>,
405}
406
407#[derive(Clone, Debug, Eq, PartialEq)]
408pub struct PcbComponentClassRef {
409    pub name: String,
410    pub source_range: Range<usize>,
411}
412
413#[derive(Clone, Debug, Eq, PartialEq)]
414pub struct PcbPadNameGroup {
415    pub pad_names: Vec<String>,
416    /// Exact authored net-tie token spelling, including quotes and escapes.
417    /// Jumper groups are authored as child forms and therefore use `None`.
418    pub raw_token: Option<String>,
419    pub source_range: Range<usize>,
420}
421
422/// Source owner for a footprint-local typed member reused by board and
423/// standalone readers.
424#[derive(Clone, Copy, Debug, Eq, PartialEq)]
425pub enum PcbFootprintMemberOwner {
426    EmbeddedFootprint { footprint_index: usize },
427    StandaloneFootprint,
428}
429
430/// One typed footprint 3D-model reference in board source order.
431#[derive(Clone, Debug, PartialEq)]
432pub struct PcbModelReference {
433    pub owner: PcbFootprintMemberOwner,
434    /// Compatibility index for board consumers; zero for standalone records.
435    /// Prefer `owner` when distinguishing document scope.
436    pub footprint_index: usize,
437    pub path: String,
438    pub offset: [f64; 3],
439    pub scale: [f64; 3],
440    pub rotate: [f64; 3],
441    /// Authored hide state; absent remains distinct from explicit false.
442    pub hidden: Option<bool>,
443    pub opacity: Option<f64>,
444    pub source_range: Range<usize>,
445}
446
447#[derive(Clone, Debug, PartialEq)]
448pub struct PcbSegment {
449    pub start_x: f64,
450    pub start_y: f64,
451    pub end_x: f64,
452    pub end_y: f64,
453    pub width: Option<f64>,
454    pub layer: Option<String>,
455    /// Plural source selector, distinct from the singular `layer` field.
456    /// `Some([])` preserves an explicitly empty `(layers)` form.
457    pub layers: Option<Vec<String>>,
458    /// Local solder-mask opening margin in millimetres, without rule resolution.
459    pub solder_mask_margin: Option<f64>,
460    /// Source editing lock state. False when the source omits or disables it.
461    pub locked: bool,
462    pub net: PcbNetRef,
463    pub uuid: Option<String>,
464    pub source_range: Range<usize>,
465}
466
467#[derive(Clone, Copy, Debug, PartialEq)]
468pub struct PcbPoint {
469    pub x: f64,
470    pub y: f64,
471}
472
473#[derive(Clone, Copy, Debug, Eq, PartialEq)]
474pub enum PcbGraphicKind {
475    Text,
476    Line,
477    Rect,
478    Arc,
479    Circle,
480    Poly,
481    Curve,
482    TextBox,
483}
484
485/// Ordered source polygon elements; embedded arcs are not tessellated or omitted.
486#[derive(Clone, Debug, PartialEq)]
487pub enum PcbPolygonPoint {
488    Xy(PcbPoint),
489    Arc {
490        start: PcbPoint,
491        mid: PcbPoint,
492        end: PcbPoint,
493    },
494}
495
496/// A producer-neutral typed view of one board graphic carrier.
497#[derive(Clone, Debug, PartialEq)]
498pub struct PcbGraphic {
499    pub kind: PcbGraphicKind,
500    pub text: Option<String>,
501    pub at: Option<PcbPoint>,
502    pub start: Option<PcbPoint>,
503    pub mid: Option<PcbPoint>,
504    pub end: Option<PcbPoint>,
505    pub center: Option<PcbPoint>,
506    /// Compatibility projection containing only authored XY elements. Use
507    /// `polygon_points` for complete polygon geometry, including embedded arcs.
508    pub points: Vec<PcbPoint>,
509    pub polygon_points: Vec<PcbPolygonPoint>,
510    pub layer: Option<String>,
511    /// Plural source selector, distinct from the singular `layer` field.
512    /// `Some([])` preserves an explicitly empty `(layers)` form.
513    pub layers: Option<Vec<String>>,
514    /// Authored association; absent and explicit unconnected net zero differ.
515    pub net: Option<PcbNetRef>,
516    /// Source rectangle corner radius in millimetres.
517    pub radius: Option<f64>,
518    /// Local solder-mask opening margin in millimetres, without rule resolution.
519    pub solder_mask_margin: Option<f64>,
520    pub stroke_width: Option<f64>,
521    pub stroke_kind: Option<String>,
522    /// Actual richer/unknown declarations outside the ordinary shape projection.
523    /// Includes unknown stroke leaves; source order and multiplicity are retained.
524    pub extra_declarations: Vec<String>,
525    pub fill: Option<String>,
526    /// Optional `gr_text_box` border state, including bare/empty forms.
527    pub border: Option<bool>,
528    /// Board graphic/text lock state. False when the source omits it.
529    pub locked: bool,
530    pub uuid: Option<String>,
531    pub source_range: Range<usize>,
532}
533
534impl PcbGraphic {
535    /// Resolve omitted shape fill using KiCad 10.0.6 `parsePCB_SHAPE` defaults.
536    ///
537    /// The caller supplies the resolved concrete layer; plural source selectors
538    /// are intentionally not expanded here. Authored tokens (including hatch
539    /// modes) are returned unchanged, and `self.fill` remains source evidence.
540    /// This does not resolve the separate fallback width for unfilled shapes.
541    pub fn effective_fill_for_layer(&self, layer: &str) -> &str {
542        if let Some(fill) = self.fill.as_deref() {
543            return fill;
544        }
545        // KiCad starts STROKE_PARAMS at zero and parses millimetres into integer
546        // nanometres before deciding whether the legacy shape implies filling.
547        let zero_width = (self.stroke_width.unwrap_or(0.0) * 1_000_000.0).round() == 0.0;
548        if (matches!(self.kind, PcbGraphicKind::Rect | PcbGraphicKind::Circle) && zero_width)
549            || (self.kind == PcbGraphicKind::Poly && layer != "Edge.Cuts")
550        {
551            "solid"
552        } else {
553            "none"
554        }
555    }
556
557    /// The outline width in millimetres that pcbnew draws for this shape on
558    /// `layer`. pcbnew loads an unfilled shape whose width is zero, negative
559    /// or absent with its 0.1 mm default line width (`parsePCB_SHAPE`; seen in
560    /// kicad-cli 10.0.5 `pcb upgrade`), and draws no outline for a filled
561    /// shape (solid or hatched) whose width is not positive. `stroke_width`
562    /// stays the stored value.
563    pub fn effective_stroke_width_for_layer(&self, layer: &str) -> f64 {
564        let width = self.stroke_width.unwrap_or(0.0);
565        // Compared at KiCad's integer nanometre precision.
566        let positive = (width * 1_000_000.0).round() > 0.0;
567        let filled = !matches!(
568            self.effective_fill_for_layer(layer),
569            "none" | "no" | "false" | "0"
570        );
571        match (positive, filled) {
572            (true, _) => width,
573            (false, true) => 0.0,
574            (false, false) => KICAD_DEFAULT_LINE_WIDTH_MM,
575        }
576    }
577}
578
579/// pcbnew's default line width for a shape stored without a usable one.
580const KICAD_DEFAULT_LINE_WIDTH_MM: f64 = 0.1;
581
582#[derive(Clone, Debug, PartialEq)]
583pub struct PcbRoutingArc {
584    pub start: PcbPoint,
585    pub mid: PcbPoint,
586    pub end: PcbPoint,
587    pub width: Option<f64>,
588    pub layer: Option<String>,
589    /// Plural source selector, distinct from the singular `layer` field.
590    /// `Some([])` preserves an explicitly empty `(layers)` form.
591    pub layers: Option<Vec<String>>,
592    /// Local solder-mask opening margin in millimetres, without rule resolution.
593    pub solder_mask_margin: Option<f64>,
594    /// Source editing lock state. False when the source omits or disables it.
595    pub locked: bool,
596    pub net: PcbNetRef,
597    pub uuid: Option<String>,
598    pub source_range: Range<usize>,
599}
600
601#[derive(Clone, Debug, PartialEq)]
602pub struct PcbDimensionFormat {
603    pub prefix: String,
604    pub suffix: String,
605    pub units: i64,
606    pub units_format: i64,
607    pub precision: i64,
608    pub override_value: Option<String>,
609    pub suppress_zeroes: bool,
610}
611
612impl Default for PcbDimensionFormat {
613    fn default() -> Self {
614        Self {
615            prefix: String::new(),
616            suffix: String::new(),
617            units: 2,
618            units_format: 1,
619            precision: 4,
620            override_value: None,
621            suppress_zeroes: false,
622        }
623    }
624}
625
626#[derive(Clone, Debug, PartialEq)]
627pub struct PcbDimensionStyle {
628    pub thickness: f64,
629    pub arrow_length: f64,
630    pub text_position_mode: i64,
631    pub arrow_direction: String,
632    pub extension_height: f64,
633    pub extension_offset: f64,
634    pub keep_text_aligned: bool,
635    pub text_frame: Option<i64>,
636}
637
638impl Default for PcbDimensionStyle {
639    fn default() -> Self {
640        Self {
641            thickness: 0.2,
642            arrow_length: 1.27,
643            text_position_mode: 0,
644            arrow_direction: "outward".to_owned(),
645            extension_height: 0.58642,
646            extension_offset: 0.0,
647            keep_text_aligned: true,
648            text_frame: None,
649        }
650    }
651}
652
653#[derive(Clone, Debug, PartialEq)]
654pub struct PcbDimension {
655    pub kind: String,
656    pub layer: String,
657    pub points: Vec<PcbPoint>,
658    pub height: f64,
659    pub leader_length: Option<f64>,
660    pub orientation: Option<i64>,
661    pub format: PcbDimensionFormat,
662    pub style: PcbDimensionStyle,
663    pub text: Option<PcbGraphic>,
664    pub locked: bool,
665    pub uuid: Option<String>,
666    pub source_range: Range<usize>,
667}
668
669#[derive(Clone, Debug, Eq, PartialEq)]
670pub struct PcbGroup {
671    pub name: String,
672    pub uuid: Option<String>,
673    pub locked: bool,
674    pub members: Vec<String>,
675    pub source_range: Range<usize>,
676}
677
678#[derive(Clone, Debug, Eq, PartialEq)]
679pub struct PcbGeneratedItem {
680    pub kind: Option<String>,
681    pub name: Option<String>,
682    pub layer: Option<String>,
683    pub uuid: Option<String>,
684    pub locked: bool,
685    pub members: Vec<String>,
686    pub property_heads: Vec<String>,
687    pub source_range: Range<usize>,
688}
689
690#[derive(Clone, Debug, Eq, PartialEq)]
691pub struct PcbEdit {
692    pub source: String,
693    pub changed: bool,
694}
695
696#[derive(Clone, Debug)]
697struct IndexedFootprint {
698    span: FormSpan,
699    property_count: usize,
700    graphic_count: usize,
701    text_count: usize,
702    text_box_count: usize,
703    pad_count: usize,
704    model_count: usize,
705    embedded_file_count: usize,
706}
707
708#[derive(Clone, Debug)]
709struct IndexedNestedForm {
710    parent_index: usize,
711    span: FormSpan,
712}
713
714#[derive(Clone, Debug)]
715struct IndexedEmbeddedFile {
716    owner: PcbEmbeddedFileOwner,
717    span: FormSpan,
718}
719
720#[derive(Clone, Debug, Default)]
721struct NetResolver {
722    name_by_ordinal: BTreeMap<i64, String>,
723    ordinal_by_name: BTreeMap<String, i64>,
724}
725
726impl NetResolver {
727    fn resolve(&self, mut net: PcbNetRef) -> PcbNetRef {
728        // Python's `NetRef.resolve_name` fills any falsy name, so a
729        // present-but-empty `(net_name "")` still resolves from the table.
730        if net.name.as_deref().is_none_or(str::is_empty)
731            && let Some(name) = net
732                .ordinal
733                .and_then(|ordinal| self.name_by_ordinal.get(&ordinal))
734                .filter(|name| !name.is_empty())
735        {
736            net.name = Some(name.clone());
737        }
738        if net.ordinal.is_none()
739            && let Some(ordinal) = net
740                .name
741                .as_ref()
742                .and_then(|name| self.ordinal_by_name.get(name))
743        {
744            net.ordinal = Some(*ordinal);
745        }
746        net
747    }
748}
749
750#[derive(Debug, Default)]
751struct PcbIndex {
752    layer_forms: Vec<FormSpan>,
753    properties: Vec<FormSpan>,
754    nets: Vec<FormSpan>,
755    footprints: Vec<IndexedFootprint>,
756    footprint_properties: Vec<IndexedNestedForm>,
757    pads: Vec<IndexedNestedForm>,
758    models: Vec<IndexedNestedForm>,
759    footprint_graphics: Vec<IndexedNestedForm>,
760    footprint_texts: Vec<IndexedNestedForm>,
761    footprint_text_boxes: Vec<IndexedNestedForm>,
762    footprint_zones: Vec<IndexedNestedForm>,
763    segments: Vec<FormSpan>,
764    vias: Vec<FormSpan>,
765    zones: Vec<FormSpan>,
766    graphics: Vec<FormSpan>,
767    arcs: Vec<FormSpan>,
768    dimensions: Vec<FormSpan>,
769    groups: Vec<FormSpan>,
770    generated_items: Vec<FormSpan>,
771    embedded_files: Vec<IndexedEmbeddedFile>,
772    variants: Vec<FormSpan>,
773    images: Vec<FormSpan>,
774    barcodes: Vec<FormSpan>,
775    tables: Vec<extended::IndexedTable>,
776    table_cells: Vec<IndexedNestedForm>,
777    counts: PcbCounts,
778}
779
780/// A board view backed by one source buffer and exact selected form spans.
781#[derive(Clone, Debug)]
782pub struct PcbView<'a> {
783    source: &'a str,
784    root: FormSpan,
785    top_level: Vec<FormSpan>,
786    layer_forms: Vec<FormSpan>,
787    properties: Vec<FormSpan>,
788    nets: Vec<FormSpan>,
789    footprints: Vec<IndexedFootprint>,
790    footprint_properties: Vec<IndexedNestedForm>,
791    pads: Vec<IndexedNestedForm>,
792    models: Vec<IndexedNestedForm>,
793    footprint_graphics: Vec<IndexedNestedForm>,
794    footprint_texts: Vec<IndexedNestedForm>,
795    footprint_text_boxes: Vec<IndexedNestedForm>,
796    footprint_zones: Vec<IndexedNestedForm>,
797    segments: Vec<FormSpan>,
798    vias: Vec<FormSpan>,
799    zones: Vec<FormSpan>,
800    graphics: Vec<FormSpan>,
801    arcs: Vec<FormSpan>,
802    dimensions: Vec<FormSpan>,
803    groups: Vec<FormSpan>,
804    generated_items: Vec<FormSpan>,
805    embedded_files: Vec<IndexedEmbeddedFile>,
806    variants: Vec<FormSpan>,
807    images: Vec<FormSpan>,
808    barcodes: Vec<FormSpan>,
809    tables: Vec<extended::IndexedTable>,
810    table_cells: Vec<IndexedNestedForm>,
811    net_resolver: NetResolver,
812    counts: PcbCounts,
813    limits: PcbLimits,
814    selection: PcbSelection,
815}
816
817impl<'a> PcbView<'a> {
818    /// Validate one `kicad_pcb` root and index its major domain families.
819    pub fn parse(source: &'a str, limits: PcbLimits) -> Result<Self, Error> {
820        Self::parse_selected(source, limits, PcbSelection::all())
821    }
822
823    /// Validate a board and index only the requested families plus dependencies.
824    pub fn parse_selected(
825        source: &'a str,
826        limits: PcbLimits,
827        selection: PcbSelection,
828    ) -> Result<Self, Error> {
829        let spans = crate::sexpr_projection::scan_form_spans(
830            source,
831            &Selector {
832                min_depth: Some(0),
833                max_depth: Some(1),
834                ..Selector::default()
835            },
836        )?;
837        let roots: Vec<_> = spans.iter().filter(|span| span.depth == 0).collect();
838        let [root] = roots.as_slice() else {
839            return Err(source_error(
840                "Expected exactly one top-level PCB form",
841                Position::START,
842            ));
843        };
844        if root.head.as_deref() != Some("kicad_pcb") {
845            return Err(source_error("Expected a kicad_pcb root", root.start));
846        }
847        let root = (*root).clone();
848        let top_level: Vec<_> = spans.into_iter().filter(|span| span.depth == 1).collect();
849        if top_level.len() > limits.max_top_level_forms {
850            return Err(limit_error());
851        }
852
853        let effective = selection.dependencies();
854        let mut index = index_top_level(source, &top_level, limits, effective)?;
855        let net_resolver = net_resolver_from_spans(source, &index.nets)?;
856        index.counts.retain_selection(selection);
857
858        Ok(Self {
859            source,
860            root,
861            top_level,
862            layer_forms: index.layer_forms,
863            properties: index.properties,
864            nets: index.nets,
865            footprints: index.footprints,
866            footprint_properties: index.footprint_properties,
867            pads: index.pads,
868            models: index.models,
869            footprint_graphics: index.footprint_graphics,
870            footprint_texts: index.footprint_texts,
871            footprint_text_boxes: index.footprint_text_boxes,
872            footprint_zones: index.footprint_zones,
873            segments: index.segments,
874            vias: index.vias,
875            zones: index.zones,
876            graphics: index.graphics,
877            arcs: index.arcs,
878            dimensions: index.dimensions,
879            groups: index.groups,
880            generated_items: index.generated_items,
881            embedded_files: index.embedded_files,
882            variants: index.variants,
883            images: index.images,
884            barcodes: index.barcodes,
885            tables: index.tables,
886            table_cells: index.table_cells,
887            net_resolver,
888            counts: index.counts,
889            limits,
890            selection,
891        })
892    }
893
894    pub fn counts(&self) -> PcbCounts {
895        self.counts
896    }
897
898    pub fn source(&self) -> &'a str {
899        self.source
900    }
901
902    /// Reuse the same admitted source/index with stricter lazy-reader ceilings.
903    /// This is not a second parse or proof that omitted families fit new limits.
904    pub(crate) fn with_reader_limits(&self, limits: PcbLimits) -> Self {
905        let mut view = self.clone();
906        view.limits = view.limits.intersect(limits);
907        view
908    }
909
910    pub fn selection(&self) -> PcbSelection {
911        self.selection
912    }
913
914    pub fn root_span(&self) -> &FormSpan {
915        &self.root
916    }
917
918    /// Iterate exact top-level spans in source order, including unknown forms.
919    pub fn top_level_forms(&self) -> impl Iterator<Item = &FormSpan> {
920        self.top_level.iter()
921    }
922
923    pub fn unknown_top_level_forms(&self) -> impl Iterator<Item = &FormSpan> {
924        self.top_level.iter().filter(|span| {
925            span.head
926                .as_deref()
927                .is_none_or(|head| !is_known_top_level(head))
928        })
929    }
930
931    pub fn layers(&self) -> impl Iterator<Item = Result<PcbLayer, Error>> + '_ {
932        self.layer_forms
933            .iter()
934            .filter(move |_| self.selection.contains(PcbFamily::Layers))
935            .map(|span| layer_from_span(self.source, span))
936    }
937
938    pub fn nets(&self) -> impl Iterator<Item = Result<PcbNet, Error>> + '_ {
939        self.nets
940            .iter()
941            .filter(move |_| self.selection.contains(PcbFamily::Nets))
942            .map(|span| net_from_span(self.source, span))
943    }
944
945    pub fn properties(&self) -> impl Iterator<Item = Result<PcbProperty, Error>> + '_ {
946        self.properties
947            .iter()
948            .filter(move |_| self.selection.contains(PcbFamily::Properties))
949            .map(|span| property_from_span(self.source, span))
950    }
951
952    pub fn footprints(&self) -> impl Iterator<Item = Result<PcbFootprint, Error>> + '_ {
953        self.footprints
954            .iter()
955            .filter(move |_| self.selection.contains(PcbFamily::Footprints))
956            .map(|indexed| footprint_from_span(self.source, indexed, self.limits))
957    }
958
959    pub fn pads(&self) -> impl Iterator<Item = Result<PcbPad, Error>> + '_ {
960        self.pads
961            .iter()
962            .filter(move |_| self.selection.contains(PcbFamily::Pads))
963            .map(|indexed| {
964                pads::pad_from_span(self.source, indexed, self.limits).map(|mut pad| {
965                    pad.net = self.net_resolver.resolve(pad.net);
966                    pad
967                })
968            })
969    }
970
971    pub fn models(&self) -> impl Iterator<Item = Result<PcbModelReference, Error>> + '_ {
972        self.models
973            .iter()
974            .filter(move |_| self.selection.contains(PcbFamily::Models))
975            .map(|indexed| model_from_span(self.source, indexed, self.limits))
976    }
977
978    pub fn segments(&self) -> impl Iterator<Item = Result<PcbSegment, Error>> + '_ {
979        self.segments
980            .iter()
981            .filter(move |_| self.selection.contains(PcbFamily::Segments))
982            .map(|span| {
983                segment_from_span(self.source, span, self.limits).map(|mut segment| {
984                    segment.net = self.net_resolver.resolve(segment.net);
985                    segment
986                })
987            })
988    }
989
990    pub fn vias(&self) -> impl Iterator<Item = Result<PcbVia, Error>> + '_ {
991        self.vias
992            .iter()
993            .filter(move |_| self.selection.contains(PcbFamily::Vias))
994            .map(|span| {
995                vias::via_from_span(self.source, span, self.limits).map(|mut via| {
996                    via.net = self.net_resolver.resolve(via.net);
997                    via
998                })
999            })
1000    }
1001
1002    pub fn zones(&self) -> impl Iterator<Item = Result<PcbZone, Error>> + '_ {
1003        self.zones
1004            .iter()
1005            .filter(move |_| self.selection.contains(PcbFamily::Zones))
1006            .map(|span| {
1007                zones::zone_from_span(self.source, span, self.limits).map(|mut zone| {
1008                    zone.net = self.net_resolver.resolve(zone.net);
1009                    zone
1010                })
1011            })
1012    }
1013
1014    /// Iterate requested footprint-owned zones and rule areas in board and
1015    /// child source order. KiCad stores their outlines in board coordinates.
1016    pub fn footprint_zones(&self) -> impl Iterator<Item = Result<PcbFootprintZone, Error>> + '_ {
1017        self.footprint_zones
1018            .iter()
1019            .filter(move |_| self.selection.contains(PcbFamily::FootprintZones))
1020            .map(|indexed| {
1021                zones::zone_from_span(self.source, &indexed.span, self.limits).map(|mut zone| {
1022                    zone.net = self.net_resolver.resolve(zone.net);
1023                    PcbFootprintZone {
1024                        footprint_index: indexed.parent_index,
1025                        zone,
1026                    }
1027                })
1028            })
1029    }
1030
1031    pub fn graphics(&self) -> impl Iterator<Item = Result<PcbGraphic, Error>> + '_ {
1032        self.graphics
1033            .iter()
1034            .filter(move |_| self.selection.contains(PcbFamily::Graphics))
1035            .map(|span| graphic_from_span(self.source, span, self.limits))
1036    }
1037
1038    pub fn arcs(&self) -> impl Iterator<Item = Result<PcbRoutingArc, Error>> + '_ {
1039        self.arcs
1040            .iter()
1041            .filter(move |_| self.selection.contains(PcbFamily::Arcs))
1042            .map(|span| {
1043                routing_arc_from_span(self.source, span, self.limits).map(|mut arc| {
1044                    arc.net = self.net_resolver.resolve(arc.net);
1045                    arc
1046                })
1047            })
1048    }
1049
1050    pub fn dimensions(&self) -> impl Iterator<Item = Result<PcbDimension, Error>> + '_ {
1051        self.dimensions
1052            .iter()
1053            .filter(move |_| self.selection.contains(PcbFamily::Dimensions))
1054            .map(|span| dimension_from_span(self.source, span, self.limits))
1055    }
1056
1057    pub fn groups(&self) -> impl Iterator<Item = Result<PcbGroup, Error>> + '_ {
1058        self.groups
1059            .iter()
1060            .filter(move |_| self.selection.contains(PcbFamily::Groups))
1061            .map(|span| group_from_span(self.source, span, self.limits))
1062    }
1063
1064    pub fn generated_items(&self) -> impl Iterator<Item = Result<PcbGeneratedItem, Error>> + '_ {
1065        self.generated_items
1066            .iter()
1067            .filter(move |_| self.selection.contains(PcbFamily::GeneratedItems))
1068            .map(|span| generated_from_span(self.source, span, self.limits))
1069    }
1070}
1071
1072pub use document::PcbDocument;
1073
1074#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1075pub(crate) struct StandaloneFootprintCounts {
1076    pub properties: usize,
1077    pub graphics: usize,
1078    pub texts: usize,
1079    pub text_boxes: usize,
1080    pub pads: usize,
1081    pub models: usize,
1082    pub embedded_files: usize,
1083}
1084
1085pub(crate) fn standalone_footprint_from_span(
1086    source: &str,
1087    span: &FormSpan,
1088    limits: PcbLimits,
1089    counts: StandaloneFootprintCounts,
1090) -> Result<PcbFootprint, Error> {
1091    footprint_from_span(
1092        source,
1093        &IndexedFootprint {
1094            span: span.clone(),
1095            property_count: counts.properties,
1096            graphic_count: counts.graphics,
1097            text_count: counts.texts,
1098            text_box_count: counts.text_boxes,
1099            pad_count: counts.pads,
1100            model_count: counts.models,
1101            embedded_file_count: counts.embedded_files,
1102        },
1103        limits,
1104    )
1105}
1106
1107pub(crate) fn standalone_pad_from_span(
1108    source: &str,
1109    span: &FormSpan,
1110    limits: PcbLimits,
1111) -> Result<PcbPad, Error> {
1112    let mut pad = pads::pad_from_span(
1113        source,
1114        &IndexedNestedForm {
1115            parent_index: 0,
1116            span: span.clone(),
1117        },
1118        limits,
1119    )?;
1120    pad.owner = PcbFootprintMemberOwner::StandaloneFootprint;
1121    Ok(pad)
1122}
1123
1124pub(crate) fn standalone_property_from_span(
1125    source: &str,
1126    span: &FormSpan,
1127    limits: PcbLimits,
1128) -> Result<PcbFootprintProperty, Error> {
1129    footprints::footprint_property_from_span(
1130        source,
1131        &IndexedNestedForm {
1132            parent_index: 0,
1133            span: span.clone(),
1134        },
1135        limits,
1136    )
1137}
1138
1139pub(crate) fn standalone_text_from_span(
1140    source: &str,
1141    span: &FormSpan,
1142    limits: PcbLimits,
1143) -> Result<PcbFootprintText, Error> {
1144    footprints::footprint_text_from_span(
1145        source,
1146        &IndexedNestedForm {
1147            parent_index: 0,
1148            span: span.clone(),
1149        },
1150        limits,
1151    )
1152}
1153
1154pub(crate) fn standalone_text_box_from_span(
1155    source: &str,
1156    span: &FormSpan,
1157    limits: PcbLimits,
1158) -> Result<PcbFootprintTextBox, Error> {
1159    footprints::footprint_text_box_from_span(
1160        source,
1161        &IndexedNestedForm {
1162            parent_index: 0,
1163            span: span.clone(),
1164        },
1165        limits,
1166    )
1167}
1168
1169pub(crate) fn standalone_model_from_span(
1170    source: &str,
1171    span: &FormSpan,
1172    limits: PcbLimits,
1173) -> Result<PcbModelReference, Error> {
1174    let mut model = model_from_span(
1175        source,
1176        &IndexedNestedForm {
1177            parent_index: 0,
1178            span: span.clone(),
1179        },
1180        limits,
1181    )?;
1182    model.owner = PcbFootprintMemberOwner::StandaloneFootprint;
1183    Ok(model)
1184}
1185
1186pub(crate) fn standalone_graphic_from_span(
1187    source: &str,
1188    span: &FormSpan,
1189    limits: PcbLimits,
1190) -> Result<PcbGraphic, Error> {
1191    graphic_from_span(source, span, limits)
1192}
1193
1194pub(crate) fn standalone_zone_from_span(
1195    source: &str,
1196    span: &FormSpan,
1197    limits: PcbLimits,
1198) -> Result<PcbZone, Error> {
1199    zones::zone_from_span(source, span, limits)
1200}