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

kicad_monkey_core/
board_plotter_ir.rs

1//! Board-level plotter IR producer over selected PCB families.
2//!
3//! Mirrors the Python `pcb_to_ir` gr_*/segment/track_arc/via/zone record
4//! subset: layerless graphic-state operations, per-category record ordering,
5//! PCB stroke widths without the footprint pen-width clamps, dash/dot
6//! decomposition parity, reversed track-arc endpoints, via aperture/
7//! drill/mask-hint operation sequences, zone fill rings, and project
8//! sidecar net-class extras.
9
10mod copper;
11mod dimension;
12mod footprint;
13mod graphics;
14mod import_facts;
15mod layer_policy;
16mod limits;
17mod outline_page;
18mod stroke_text_bounds;
19mod table;
20mod text;
21mod text_cache;
22mod text_native;
23mod text_variables;
24pub(crate) mod text_wrap;
25
26use crate::pcb::{
27    PcbDimension, PcbFamily, PcbGraphic, PcbLimits, PcbNetRef, PcbSelection, PcbView,
28};
29use crate::plotter_ir::ensure_javascript_safe_integer;
30use crate::plotter_text_cache::{PlotterTextCacheResources, PlotterTextCacheSession};
31use crate::plotter_types::{PlotterOperation, ThickSegment};
32use crate::sexpr::{Error, ErrorKind, ErrorPhase, Position};
33use std::collections::{BTreeMap, HashSet};
34use std::time::Instant;
35
36use copper::{segment_record, track_arc_record, via_operation_count, via_record, zone_record};
37use graphics::graphic_records;
38pub use import_facts::{
39    BoardImportFacts, BoardPadFlashFact, BoardViaFlashFact, board_import_facts_from_view,
40};
41use layer_policy::BoardLayerFlashResolver;
42use limits::board_pcb_limits;
43pub use outline_page::board_outline_page_bounds;
44pub use stroke_text_bounds::BoardBoundsLimits;
45pub(crate) use text::authored_knockout_margin_nm;
46pub use text::{
47    BoardTextBoxOperation, BoardTextBoxRecord, BoardTextHAlign, BoardTextOperation,
48    BoardTextRecord, BoardTextRenderCache, BoardTextRenderCacheCoordinateSpace,
49    BoardTextRenderCacheSource, BoardTextVAlign,
50};
51pub(crate) use text_cache::{KnockoutFrame, knockout_hull, knockout_polygons};
52pub use text_variables::BoardTextVariables;
53
54/// One operation within a table record. Grid/border segments precede cached
55/// cell text, matching the established Python producer.
56#[derive(Clone, Debug, PartialEq)]
57pub enum BoardTableOperation {
58    Segment(PlotterOperation),
59    Text(BoardTextOperation),
60}
61
62/// One `(table ...)` record with its source cell count and participating
63/// layers.
64#[derive(Clone, Debug, PartialEq)]
65pub struct BoardTableRecord {
66    pub uuid: String,
67    pub layers: Vec<String>,
68    pub cell_count: usize,
69    /// Source cell rectangles retained for the all-layer viewport authority.
70    pub cell_bounds_nm: Vec<[i64; 4]>,
71    pub operations: Vec<BoardTableOperation>,
72}
73
74/// One board dimension operation. Stroke-font text and dimension geometry use
75/// shared layered geometry operations; faced text retains the board cache
76/// payload used by ordinary board text.
77#[derive(Clone, Debug, PartialEq)]
78pub enum BoardDimensionOperation {
79    Geometry(PlotterOperation),
80    Text(BoardTextOperation),
81}
82
83/// One `(dimension ...)` record in Python text-before-shape order.
84#[derive(Clone, Debug, PartialEq)]
85pub struct BoardDimensionRecord {
86    pub uuid: String,
87    pub layers: Vec<String>,
88    pub dimension_type: String,
89    pub text: Option<String>,
90    pub operations: Vec<BoardDimensionOperation>,
91}
92
93/// Canonical ownership metadata attached to one embedded-footprint child
94/// operation by the established Python producer.
95#[derive(Clone, Debug, Eq, PartialEq)]
96pub struct BoardFootprintChildMetadata {
97    pub label: String,
98    pub data_uuid: String,
99    pub data_ref: String,
100    pub object_id: String,
101    pub extra_attrs: BoardFootprintChildAttributes,
102}
103
104/// Closed, typed child attributes serialized under `extra_attrs`.
105#[derive(Clone, Debug, Eq, PartialEq)]
106pub struct BoardFootprintChildAttributes {
107    pub component: String,
108    pub component_uid: String,
109    pub component_uuid: String,
110    pub footprint: String,
111    pub layer_name: Option<String>,
112    pub layer_role: Option<String>,
113    pub primitive: String,
114    pub footprint_primitive: String,
115    pub footprint_object_index: usize,
116    pub footprint_subop_index: Option<usize>,
117    pub footprint_text_role: Option<String>,
118    pub property_name: Option<String>,
119    pub fp_text_type: Option<String>,
120    pub footprint_graphic_kind: Option<String>,
121}
122
123/// Closed string-valued block attributes. Python's `start_block` helper
124/// stringifies every retained value and drops empty values.
125#[derive(Clone, Debug, Eq, PartialEq)]
126pub struct BoardFootprintBlockAttributes {
127    pub primitive: String,
128    pub component: Option<String>,
129    pub component_uid: Option<String>,
130    pub component_uuid: Option<String>,
131    pub footprint: Option<String>,
132    pub pad_number: Option<String>,
133    pub pad_designator: Option<String>,
134    pub pad_type: Option<String>,
135    pub pad_shape: Option<String>,
136    pub layer_names: Option<String>,
137    pub net_index: Option<String>,
138    pub net_id: Option<String>,
139    pub net: Option<String>,
140    pub net_class: Option<String>,
141    pub net_classes: Option<String>,
142    pub hole_owner: Option<String>,
143    pub hole_kind: Option<String>,
144    pub hole_plating: Option<String>,
145    pub hole_render: Option<String>,
146    pub hole_diameter_mm: Option<String>,
147    pub hole_width_mm: Option<String>,
148    pub hole_height_mm: Option<String>,
149}
150
151/// One grouping marker surrounding a pad flash or its independently grouped
152/// drill operation.
153#[derive(Clone, Debug, Eq, PartialEq)]
154pub struct BoardFootprintBlock {
155    pub label: String,
156    pub data_uuid: String,
157    pub data_ref: String,
158    pub object_id: String,
159    pub layers: Vec<String>,
160    pub extra_attrs: BoardFootprintBlockAttributes,
161}
162
163/// One operation in an embedded board-footprint record. Geometry and text
164/// children retain source ownership metadata; pad payloads are bracketed by
165/// explicit block markers exactly as in the Python plotter IR.
166#[derive(Clone, Debug, PartialEq)]
167pub enum BoardFootprintOperation {
168    Geometry {
169        operation: PlotterOperation,
170        metadata: BoardFootprintChildMetadata,
171    },
172    Text {
173        operation: BoardTextOperation,
174        metadata: BoardFootprintChildMetadata,
175    },
176    Pad(PlotterOperation),
177    StartBlock(BoardFootprintBlock),
178    EndBlock,
179}
180
181/// Board-local placement carried separately from footprint-local operations.
182#[derive(Clone, Copy, Debug, PartialEq)]
183pub struct BoardFootprintPlacement {
184    pub x_nm: i64,
185    pub y_nm: i64,
186    pub angle_deg: f64,
187}
188
189/// One PCB-embedded footprint record in canonical child-family order.
190#[derive(Clone, Debug, PartialEq)]
191pub struct BoardFootprintRecord {
192    pub uuid: String,
193    pub library_link: String,
194    pub reference: String,
195    pub value: String,
196    pub layer: String,
197    pub locked: bool,
198    pub descr: String,
199    pub tags: String,
200    pub attr: Vec<String>,
201    pub placement: BoardFootprintPlacement,
202    pub operations: Vec<BoardFootprintOperation>,
203}
204
205/// Ignored ceilings, defaulting to `usize::MAX`: KiCad reads and plots boards
206/// and footprints without them (#612). Request hosts still pass caller values.
207#[derive(Clone, Copy, Debug, Eq, PartialEq)]
208pub struct BoardPlotLimits {
209    pub max_source_bytes: usize,
210    pub max_depth: usize,
211    pub max_graphics: usize,
212    pub max_operations: usize,
213    pub max_points: usize,
214    /// Aggregate bytes of resolved text retained in records.
215    pub max_text_bytes: usize,
216    /// Aggregate net-class string bytes retained across emitted records.
217    pub max_net_class_bytes: usize,
218    /// Aggregate embedded-footprint ownership/record metadata bytes retained
219    /// after source decoding.
220    pub max_metadata_bytes: usize,
221    /// Maximum generic S-expression nodes or direct children in one carrier.
222    pub max_parse_nodes: usize,
223    /// Aggregate decoded input points retained before operation conversion.
224    pub max_input_points: usize,
225    /// Aggregate decoded input polygons retained before operation conversion.
226    pub max_input_polygons: usize,
227    /// Maximum authored render-cache polygons in one text carrier.
228    pub max_cache_polygons: usize,
229    /// Maximum authored render-cache contours in one text carrier.
230    pub max_cache_contours: usize,
231}
232
233impl Default for BoardPlotLimits {
234    fn default() -> Self {
235        Self {
236            max_source_bytes: usize::MAX,
237            max_depth: usize::MAX,
238            max_graphics: usize::MAX,
239            max_operations: usize::MAX,
240            max_points: usize::MAX,
241            max_text_bytes: usize::MAX,
242            max_net_class_bytes: usize::MAX,
243            max_metadata_bytes: usize::MAX,
244            max_parse_nodes: usize::MAX,
245            max_input_points: usize::MAX,
246            max_input_polygons: usize::MAX,
247            max_cache_polygons: usize::MAX,
248            max_cache_contours: usize::MAX,
249        }
250    }
251}
252
253/// Board graphic record kinds promoted in the first board slice.
254#[derive(Clone, Copy, Debug, Eq, PartialEq)]
255pub enum BoardGraphicRecordKind {
256    GrLine,
257    GrArc,
258    GrCircle,
259    GrRect,
260    GrPoly,
261    GrCurve,
262}
263
264impl BoardGraphicRecordKind {
265    pub const fn as_str(self) -> &'static str {
266        match self {
267            Self::GrLine => "gr_line",
268            Self::GrArc => "gr_arc",
269            Self::GrCircle => "gr_circle",
270            Self::GrRect => "gr_rect",
271            Self::GrPoly => "gr_poly",
272            Self::GrCurve => "gr_curve",
273        }
274    }
275}
276
277/// One board-level graphic record; the carrier layer travels on the record.
278#[derive(Clone, Debug, PartialEq)]
279pub struct BoardGraphicRecord {
280    pub uuid: String,
281    pub kind: BoardGraphicRecordKind,
282    pub layer: String,
283    pub operations: Vec<PlotterOperation>,
284}
285
286/// Python `_with_net_class_extras`: optional exact-match sidecar classes.
287#[derive(Clone, Debug, Default, Eq, PartialEq)]
288pub struct BoardNetClassExtras {
289    pub net_class: Option<String>,
290    pub net_classes: Vec<String>,
291}
292
293/// One `(segment ...)` track record; Python emits exactly one thick segment.
294#[derive(Clone, Debug, PartialEq)]
295pub struct BoardSegmentRecord {
296    pub uuid: String,
297    pub layer: String,
298    pub locked: bool,
299    pub net_id: Option<i64>,
300    pub net_name: Option<String>,
301    pub net_classes: BoardNetClassExtras,
302    pub operations: Vec<PlotterOperation>,
303}
304
305/// One `(arc ...)` routing record; the Python serializer reverses the
306/// file-order endpoints so the arc plots end-to-start.
307#[derive(Clone, Debug, PartialEq)]
308pub struct BoardTrackArcRecord {
309    pub uuid: String,
310    pub layer: String,
311    pub net_id: Option<i64>,
312    pub net_name: Option<String>,
313    pub net_classes: BoardNetClassExtras,
314    pub operations: Vec<PlotterOperation>,
315}
316
317/// Python via types serialized in the `via_type` extra.
318#[derive(Clone, Copy, Debug, Eq, PartialEq)]
319pub enum BoardViaType {
320    Through,
321    Blind,
322    Buried,
323    Micro,
324}
325
326impl BoardViaType {
327    pub const fn as_str(self) -> &'static str {
328        match self {
329            Self::Through => "through",
330            Self::Blind => "blind",
331            Self::Buried => "buried",
332            Self::Micro => "micro",
333        }
334    }
335}
336
337/// The role of one operation inside a via record's fixed sequence.
338#[derive(Clone, Copy, Debug, Eq, PartialEq)]
339pub enum BoardViaOperationKind {
340    /// `FlashPadCircle` with role `via_aperture` on effective flashed copper layers.
341    Aperture,
342    /// Filled `Circle` with role `via_drill` on the authored physical span.
343    Drill,
344    /// `FlashPadCircle` with role `via_mask_opening` on one mask layer.
345    MaskOpening,
346    /// Filled `Circle` with role `via_mask_drill` on one mask layer.
347    MaskDrill,
348}
349
350/// One via operation; flashes and drills share the circular payload.
351#[derive(Clone, Debug, PartialEq)]
352pub struct BoardViaOperation {
353    pub kind: BoardViaOperationKind,
354    pub x: i64,
355    pub y: i64,
356    pub diameter_nm: i64,
357    pub layers: Vec<String>,
358}
359
360/// Front/back optional fabrication metadata mirrored from the via carrier.
361#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
362pub struct BoardViaFabrication {
363    pub tenting_front: Option<bool>,
364    pub tenting_back: Option<bool>,
365    pub covering_front: Option<bool>,
366    pub covering_back: Option<bool>,
367    pub plugging_front: Option<bool>,
368    pub plugging_back: Option<bool>,
369    pub capping: Option<bool>,
370    pub filling: Option<bool>,
371}
372
373impl BoardViaFabrication {
374    /// Python emits `ipc4761_metadata` only when any ipc key is present.
375    pub const fn any(self) -> bool {
376        self.tenting_front.is_some()
377            || self.tenting_back.is_some()
378            || self.covering_front.is_some()
379            || self.covering_back.is_some()
380            || self.plugging_front.is_some()
381            || self.plugging_back.is_some()
382            || self.capping.is_some()
383            || self.filling.is_some()
384    }
385}
386
387/// One `(via ...)` record with its raw-mm extras and operation sequence.
388#[derive(Clone, Debug, PartialEq)]
389pub struct BoardViaRecord {
390    pub uuid: String,
391    pub layers: Vec<String>,
392    pub drill: f64,
393    pub size: f64,
394    pub via_type: BoardViaType,
395    pub fabrication: BoardViaFabrication,
396    pub net_id: Option<i64>,
397    pub net_name: Option<String>,
398    pub net_classes: BoardNetClassExtras,
399    pub operations: Vec<BoardViaOperation>,
400}
401
402/// One `(zone ...)` record bundling every `filled_polygon` fill ring.
403#[derive(Clone, Debug, PartialEq)]
404pub struct BoardZoneRecord {
405    pub uuid: String,
406    pub layers: Vec<String>,
407    pub fill_layers: Vec<String>,
408    pub fill_island: Vec<bool>,
409    pub net_id: Option<i64>,
410    pub net_name: Option<String>,
411    pub net_classes: BoardNetClassExtras,
412    pub operations: Vec<PlotterOperation>,
413}
414
415/// One record of the promoted board plotter subset in Python emission order.
416#[derive(Clone, Debug, PartialEq)]
417pub enum BoardPlotRecord {
418    Graphic(BoardGraphicRecord),
419    Text(BoardTextRecord),
420    TextBox(BoardTextBoxRecord),
421    Segment(BoardSegmentRecord),
422    TrackArc(BoardTrackArcRecord),
423    Via(BoardViaRecord),
424    Table(BoardTableRecord),
425    Dimension(BoardDimensionRecord),
426    Zone(BoardZoneRecord),
427    Footprint(BoardFootprintRecord),
428}
429
430impl BoardPlotRecord {
431    pub fn operation_count(&self) -> usize {
432        match self {
433            Self::Graphic(record) => record.operations.len(),
434            Self::Text(record) => record.operations.len(),
435            Self::TextBox(record) => record.operations.len(),
436            Self::Segment(record) => record.operations.len(),
437            Self::TrackArc(record) => record.operations.len(),
438            Self::Via(record) => record.operations.len(),
439            Self::Table(record) => record.operations.len(),
440            Self::Dimension(record) => record.operations.len(),
441            Self::Zone(record) => record.operations.len(),
442            Self::Footprint(record) => record.operations.len(),
443        }
444    }
445}
446
447/// Typed facts needed to serialize the promoted board plotter subset.
448#[derive(Clone, Debug, PartialEq)]
449pub struct BoardPlotDocument {
450    pub version: i64,
451    pub generator: String,
452    pub generator_version: String,
453    pub thickness_mm: f64,
454    pub paper: String,
455    pub records: Vec<BoardPlotRecord>,
456}
457
458/// Exact net-name to net-class assignments from the project sidecar.
459///
460/// Mirrors Python `project_net_name_to_classes`: empty net names are
461/// skipped, empty class strings are dropped, and later duplicate names
462/// overwrite earlier ones.
463#[derive(Clone, Debug, Default, Eq, PartialEq)]
464pub struct BoardNetClassAssignments {
465    by_net_name: BTreeMap<String, Vec<String>>,
466}
467
468impl BoardNetClassAssignments {
469    pub fn from_entries<N, C>(entries: impl IntoIterator<Item = (N, Vec<C>)>) -> Self
470    where
471        N: Into<String>,
472        C: Into<String>,
473    {
474        let mut by_net_name = BTreeMap::new();
475        for (net_name, classes) in entries {
476            let net_name = net_name.into();
477            if net_name.is_empty() {
478                continue;
479            }
480            let classes: Vec<String> = classes
481                .into_iter()
482                .map(Into::into)
483                .filter(|class| !class.is_empty())
484                .collect();
485            by_net_name.insert(net_name, classes);
486        }
487        Self { by_net_name }
488    }
489
490    /// Python `_with_net_class_extras`: extras appear only for truthy net
491    /// names with a non-empty class list; the first class is `net_class`.
492    pub fn extras_for(&self, net_name: Option<&str>) -> BoardNetClassExtras {
493        let classes = net_name
494            .filter(|name| !name.is_empty())
495            .and_then(|name| self.by_net_name.get(name))
496            .filter(|classes| !classes.is_empty());
497        match classes {
498            Some(classes) => BoardNetClassExtras {
499                net_class: classes.first().cloned(),
500                net_classes: classes.clone(),
501            },
502            None => BoardNetClassExtras::default(),
503        }
504    }
505
506    fn extras_for_bounded(
507        &self,
508        net_name: Option<&str>,
509        budget: &mut BudgetTracker,
510    ) -> Result<BoardNetClassExtras, Error> {
511        let classes = net_name
512            .filter(|name| !name.is_empty())
513            .and_then(|name| self.by_net_name.get(name))
514            .filter(|classes| !classes.is_empty());
515        let Some(classes) = classes else {
516            return Ok(BoardNetClassExtras::default());
517        };
518        let payload_bytes = classes
519            .iter()
520            .try_fold(classes[0].len(), |total, class| {
521                total.checked_add(class.len())
522            })
523            .ok_or_else(net_class_limit_error)?;
524        let structural_bytes = classes
525            .len()
526            .checked_add(1)
527            .and_then(|count| count.checked_mul(std::mem::size_of::<String>()))
528            .ok_or_else(net_class_limit_error)?;
529        let retained_bytes = payload_bytes
530            .checked_add(structural_bytes)
531            .ok_or_else(net_class_limit_error)?;
532        budget.charge_net_class(retained_bytes)?;
533        Ok(BoardNetClassExtras {
534            net_class: classes.first().cloned(),
535            net_classes: classes.clone(),
536        })
537    }
538}
539
540/// Track record-level operation and point budgets fail-closed.
541struct BudgetTracker {
542    max_operations: usize,
543    max_points: usize,
544    operation_count: usize,
545    point_count: usize,
546    max_text_bytes: usize,
547    text_bytes: usize,
548    max_net_class_bytes: usize,
549    net_class_bytes: usize,
550    max_metadata_bytes: usize,
551    metadata_bytes: usize,
552}
553
554impl BudgetTracker {
555    fn new(limits: BoardPlotLimits) -> Self {
556        Self {
557            max_operations: limits.max_operations,
558            max_points: limits.max_points,
559            operation_count: 0,
560            point_count: 0,
561            max_text_bytes: limits.max_text_bytes,
562            text_bytes: 0,
563            max_net_class_bytes: limits.max_net_class_bytes,
564            net_class_bytes: 0,
565            max_metadata_bytes: limits.max_metadata_bytes,
566            metadata_bytes: 0,
567        }
568    }
569
570    fn remaining_operations(&self) -> Result<usize, Error> {
571        self.max_operations
572            .checked_sub(self.operation_count)
573            .ok_or_else(limit_error)
574    }
575
576    fn charge(&mut self, operations: usize, points: usize) -> Result<(), Error> {
577        self.operation_count = self.operation_count.saturating_add(operations);
578        if self.operation_count > self.max_operations {
579            return Err(limit_error());
580        }
581        self.point_count = self.point_count.saturating_add(points);
582        if self.point_count > self.max_points {
583            return Err(point_limit_error());
584        }
585        Ok(())
586    }
587
588    fn ensure_capacity(&self, operations: usize, points: usize) -> Result<(), Error> {
589        self.operation_count
590            .checked_add(operations)
591            .filter(|total| *total <= self.max_operations)
592            .ok_or_else(limit_error)?;
593        self.point_count
594            .checked_add(points)
595            .filter(|total| *total <= self.max_points)
596            .ok_or_else(point_limit_error)?;
597        Ok(())
598    }
599
600    fn remaining_points(&self) -> Result<usize, Error> {
601        self.max_points
602            .checked_sub(self.point_count)
603            .ok_or_else(point_limit_error)
604    }
605
606    fn remaining_text_bytes(&self) -> Result<usize, Error> {
607        self.max_text_bytes
608            .checked_sub(self.text_bytes)
609            .ok_or_else(text_limit_error)
610    }
611
612    fn ensure_text_capacity(&self, bytes: usize) -> Result<(), Error> {
613        self.text_bytes
614            .checked_add(bytes)
615            .filter(|total| *total <= self.max_text_bytes)
616            .ok_or_else(text_limit_error)?;
617        Ok(())
618    }
619
620    fn charge_text(&mut self, bytes: usize) -> Result<(), Error> {
621        self.text_bytes = self.text_bytes.saturating_add(bytes);
622        if self.text_bytes > self.max_text_bytes {
623            return Err(text_limit_error());
624        }
625        Ok(())
626    }
627
628    fn charge_net_class(&mut self, bytes: usize) -> Result<(), Error> {
629        self.net_class_bytes = self
630            .net_class_bytes
631            .checked_add(bytes)
632            .filter(|total| *total <= self.max_net_class_bytes)
633            .ok_or_else(net_class_limit_error)?;
634        Ok(())
635    }
636
637    fn charge_metadata(&mut self, bytes: usize) -> Result<(), Error> {
638        self.metadata_bytes = self
639            .metadata_bytes
640            .checked_add(bytes)
641            .filter(|total| *total <= self.max_metadata_bytes)
642            .ok_or_else(metadata_limit_error)?;
643        Ok(())
644    }
645}
646
647/// Read supported board families into plotter records without sidecar extras.
648pub fn board_plot_document(
649    source: &str,
650    limits: BoardPlotLimits,
651) -> Result<BoardPlotDocument, Error> {
652    board_plot_document_with_net_classes(source, limits, &BoardNetClassAssignments::default())
653}
654
655/// Localize primary drawing capability failures without emitting error wire fields.
656/// Scalar fields, other drawings and pads remain in the ordinary plot document.
657pub fn board_plot_document_with_primary_errors(
658    source: &str,
659    limits: BoardPlotLimits,
660) -> Result<(BoardPlotDocument, Vec<Error>), Error> {
661    let view = PcbView::parse_selected(source, board_pcb_limits(limits), board_selection())?;
662    let mut errors = Vec::new();
663    let (document, _) = board_plot_document_from_view_internal(
664        source,
665        &view,
666        limits,
667        &BoardNetClassAssignments::default(),
668        &BoardTextVariables::default(),
669        PreparedTextCache {
670            session: None,
671            setup_ns: 0,
672        },
673        false,
674        Some(&mut errors),
675    )?;
676    Ok((document, errors))
677}
678
679/// Read supported board graphics, tracks, vias, and zones into plotter
680/// records, attaching project-sidecar net-class extras by exact net name.
681pub fn board_plot_document_with_net_classes(
682    source: &str,
683    limits: BoardPlotLimits,
684    net_classes: &BoardNetClassAssignments,
685) -> Result<BoardPlotDocument, Error> {
686    board_plot_document_with_sidecars(source, limits, net_classes, &BoardTextVariables::default())
687}
688
689/// Read the supported board families into plotter records with both project
690/// sidecar inputs: net-class extras and `${NAME}` text variables (which the
691/// board `(property ...)` entries overlay key-by-key).
692pub fn board_plot_document_with_sidecars(
693    source: &str,
694    limits: BoardPlotLimits,
695    net_classes: &BoardNetClassAssignments,
696    text_variables: &BoardTextVariables,
697) -> Result<BoardPlotDocument, Error> {
698    board_plot_document_with_text_cache_sidecar(source, limits, net_classes, text_variables, None)
699}
700
701/// Source-bound board plot facts used by downstream presentation.
702///
703/// The typed plot document and PCB view are always derived from the same
704/// borrowed source, preventing stale or cross-design bounds composition.
705pub struct BoardPlotFacts<'a> {
706    document: BoardPlotDocument,
707    view: PcbView<'a>,
708}
709
710/// Complete source-layer facts required by truthful presentation filtering.
711#[derive(Clone, Debug, Eq, PartialEq)]
712pub struct BoardRenderFacts {
713    enabled_layers: Vec<String>,
714    copper_stack: Vec<String>,
715}
716
717impl BoardRenderFacts {
718    pub fn enabled_layers(&self) -> &[String] {
719        &self.enabled_layers
720    }
721
722    pub fn copper_stack(&self) -> &[String] {
723        &self.copper_stack
724    }
725}
726
727/// One atomic source-model document/facts pair. Construction is core-owned so
728/// facts from a different board cannot be paired with the document.
729#[derive(Clone, Debug, PartialEq)]
730pub struct BoardPlotSourceArtifact {
731    document: BoardPlotDocument,
732    render_facts: BoardRenderFacts,
733}
734
735impl BoardPlotSourceArtifact {
736    pub fn document(&self) -> &BoardPlotDocument {
737        &self.document
738    }
739
740    pub fn render_facts(&self) -> &BoardRenderFacts {
741        &self.render_facts
742    }
743
744    pub(crate) fn into_parts(self) -> (BoardPlotDocument, BoardRenderFacts) {
745        (self.document, self.render_facts)
746    }
747}
748
749/// Opt-in successful-build timings for board Plotter-IR production.
750#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
751pub struct BoardPlotBuildProfile {
752    pub text_cache_setup_ns: u64,
753    pub selected_view_parse_ns: u64,
754    pub metadata_ns: u64,
755    pub decode_graphics_ns: u64,
756    pub decode_tables_ns: u64,
757    pub decode_dimensions_ns: u64,
758    pub graphic_records_ns: u64,
759    pub variables_ns: u64,
760    pub text_records_ns: u64,
761    pub copper_records_ns: u64,
762    pub table_records_ns: u64,
763    pub dimension_records_ns: u64,
764    pub zone_records_ns: u64,
765    pub footprint_records_ns: u64,
766}
767
768#[derive(Default)]
769struct PreparedTextCache<'a> {
770    session: Option<PlotterTextCacheSession<'a>>,
771    setup_ns: u64,
772}
773
774#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
775pub struct BoardPlotFactsBuildProfile {
776    pub plot: BoardPlotBuildProfile,
777    pub bound_pcb_view_parse_ns: u64,
778}
779
780impl BoardPlotFacts<'_> {
781    pub fn view(&self) -> &PcbView<'_> {
782        &self.view
783    }
784
785    pub fn bounds(
786        &self,
787        outline_fonts: Option<&PlotterTextCacheResources<'_>>,
788        limits: BoardBoundsLimits,
789    ) -> Result<Option<[i64; 4]>, Error> {
790        stroke_text_bounds::board_bounds(&self.document, &self.view, outline_fonts, limits)
791    }
792
793    pub fn into_document(self) -> BoardPlotDocument {
794        self.document
795    }
796
797    pub fn into_source_artifact(self) -> Result<BoardPlotSourceArtifact, Error> {
798        let mut enabled_layers = Vec::new();
799        let mut seen = HashSet::new();
800        for layer in self.view.layers() {
801            let name = layer?.name;
802            if !seen.insert(name.clone()) {
803                return Err(Error::build(
804                    ErrorKind::UnexpectedToken,
805                    format!("duplicate board layer name {name:?}"),
806                ));
807            }
808            enabled_layers.push(name);
809        }
810        let copper_stack = enabled_layers
811            .iter()
812            .filter(|name| name.ends_with(".Cu"))
813            .cloned()
814            .collect();
815        Ok(BoardPlotSourceArtifact {
816            document: self.document,
817            render_facts: BoardRenderFacts {
818                enabled_layers,
819                copper_stack,
820            },
821        })
822    }
823}
824
825/// Build one atomic board Plotter-IR/source-layer artifact with project
826/// sidecars. This parses the source once through the existing source-bound
827/// facts path.
828pub fn board_plot_artifact_with_sidecars(
829    source: &str,
830    plot_limits: BoardPlotLimits,
831    pcb_limits: PcbLimits,
832    net_classes: &BoardNetClassAssignments,
833    text_variables: &BoardTextVariables,
834) -> Result<BoardPlotSourceArtifact, Error> {
835    board_plot_artifact_with_text_cache_sidecar(
836        source,
837        plot_limits,
838        pcb_limits,
839        net_classes,
840        text_variables,
841        None,
842    )
843}
844
845/// Build one atomic board artifact with optional deterministic text-cache
846/// resources. This is the fit-capable direct-render producer; the document and
847/// complete layer facts are derived from the same parsed board view.
848pub fn board_plot_artifact_with_text_cache_sidecar(
849    source: &str,
850    plot_limits: BoardPlotLimits,
851    pcb_limits: PcbLimits,
852    net_classes: &BoardNetClassAssignments,
853    text_variables: &BoardTextVariables,
854    text_cache: Option<&PlotterTextCacheResources<'_>>,
855) -> Result<BoardPlotSourceArtifact, Error> {
856    build_board_plot_facts_internal(
857        source,
858        plot_limits,
859        pcb_limits,
860        net_classes,
861        text_variables,
862        text_cache,
863        false,
864    )
865    .map(|(facts, _profile)| facts)
866    .and_then(BoardPlotFacts::into_source_artifact)
867}
868
869/// Build one immutable, source-bound board fact set with project sidecars.
870pub fn board_plot_facts_with_sidecars<'a>(
871    source: &'a str,
872    plot_limits: BoardPlotLimits,
873    pcb_limits: PcbLimits,
874    net_classes: &BoardNetClassAssignments,
875    text_variables: &BoardTextVariables,
876) -> Result<BoardPlotFacts<'a>, Error> {
877    build_board_plot_facts_internal(
878        source,
879        plot_limits,
880        pcb_limits,
881        net_classes,
882        text_variables,
883        None,
884        false,
885    )
886    .map(|(facts, _profile)| facts)
887}
888
889pub fn board_plot_facts_with_sidecars_profiled<'a>(
890    source: &'a str,
891    plot_limits: BoardPlotLimits,
892    pcb_limits: PcbLimits,
893    net_classes: &BoardNetClassAssignments,
894    text_variables: &BoardTextVariables,
895) -> Result<(BoardPlotFacts<'a>, BoardPlotFactsBuildProfile), Error> {
896    build_board_plot_facts_internal(
897        source,
898        plot_limits,
899        pcb_limits,
900        net_classes,
901        text_variables,
902        None,
903        true,
904    )
905}
906
907fn build_board_plot_facts_internal<'a>(
908    source: &'a str,
909    plot_limits: BoardPlotLimits,
910    pcb_limits: PcbLimits,
911    net_classes: &BoardNetClassAssignments,
912    text_variables: &BoardTextVariables,
913    text_cache: Option<&PlotterTextCacheResources<'_>>,
914    profile_enabled: bool,
915) -> Result<(BoardPlotFacts<'a>, BoardPlotFactsBuildProfile), Error> {
916    let text_cache_started = profile_enabled.then(Instant::now);
917    let text_cache = text_cache.map(PlotterTextCacheSession::new).transpose()?;
918    let text_cache_setup_ns = elapsed_ns(text_cache_started);
919    let view_started = profile_enabled.then(Instant::now);
920    let view = PcbView::parse_selected(
921        source,
922        pcb_limits.intersect(board_pcb_limits(plot_limits)),
923        PcbSelection::all(),
924    )?;
925    let bound_pcb_view_parse_ns = elapsed_ns(view_started);
926    let (document, plot) = board_plot_document_from_view_internal(
927        source,
928        &view,
929        plot_limits,
930        net_classes,
931        text_variables,
932        PreparedTextCache {
933            session: text_cache,
934            setup_ns: text_cache_setup_ns,
935        },
936        profile_enabled,
937        None,
938    )?;
939    Ok((
940        BoardPlotFacts { document, view },
941        BoardPlotFactsBuildProfile {
942            plot,
943            bound_pcb_view_parse_ns,
944        },
945    ))
946}
947
948/// Read the supported board families with project sidecars plus optional,
949/// caller-supplied deterministic outline-font/cache-generation resources.
950pub fn board_plot_document_with_text_cache_sidecar(
951    source: &str,
952    limits: BoardPlotLimits,
953    net_classes: &BoardNetClassAssignments,
954    text_variables: &BoardTextVariables,
955    text_cache: Option<&PlotterTextCacheResources<'_>>,
956) -> Result<BoardPlotDocument, Error> {
957    board_plot_document_with_text_cache_sidecar_internal(
958        source,
959        limits,
960        net_classes,
961        text_variables,
962        text_cache,
963        false,
964    )
965    .map(|(document, _profile)| document)
966}
967
968#[allow(
969    clippy::too_many_lines,
970    reason = "one ordered board render pass keeps every bounded family and its opt-in timings aligned"
971)]
972fn board_plot_document_with_text_cache_sidecar_internal(
973    source: &str,
974    limits: BoardPlotLimits,
975    net_classes: &BoardNetClassAssignments,
976    text_variables: &BoardTextVariables,
977    text_cache: Option<&PlotterTextCacheResources<'_>>,
978    profile_enabled: bool,
979) -> Result<(BoardPlotDocument, BoardPlotBuildProfile), Error> {
980    let text_cache_started = profile_enabled.then(Instant::now);
981    let text_cache = text_cache.map(PlotterTextCacheSession::new).transpose()?;
982    let text_cache_setup_ns = elapsed_ns(text_cache_started);
983    let view_started = profile_enabled.then(Instant::now);
984    let view = PcbView::parse_selected(source, board_pcb_limits(limits), board_selection())?;
985    let selected_view_parse_ns = elapsed_ns(view_started);
986    let (document, mut profile) = board_plot_document_from_view_internal(
987        source,
988        &view,
989        limits,
990        net_classes,
991        text_variables,
992        PreparedTextCache {
993            session: text_cache,
994            setup_ns: text_cache_setup_ns,
995        },
996        profile_enabled,
997        None,
998    )?;
999    profile.selected_view_parse_ns = selected_view_parse_ns;
1000    Ok((document, profile))
1001}
1002
1003#[allow(
1004    clippy::too_many_arguments,
1005    clippy::too_many_lines,
1006    reason = "one ordered board render pass keeps every bounded family and its opt-in timings aligned"
1007)]
1008fn board_plot_document_from_view_internal(
1009    source: &str,
1010    view: &PcbView<'_>,
1011    limits: BoardPlotLimits,
1012    net_classes: &BoardNetClassAssignments,
1013    text_variables: &BoardTextVariables,
1014    text_cache: PreparedTextCache<'_>,
1015    profile_enabled: bool,
1016    primary_errors: Option<&mut Vec<Error>>,
1017) -> Result<(BoardPlotDocument, BoardPlotBuildProfile), Error> {
1018    let mut profile = BoardPlotBuildProfile {
1019        text_cache_setup_ns: text_cache.setup_ns,
1020        ..BoardPlotBuildProfile::default()
1021    };
1022    let text_cache = text_cache.session;
1023    let metadata_started = profile_enabled.then(Instant::now);
1024    let metadata = view.metadata()?;
1025    ensure_javascript_safe_integer(metadata.version)?;
1026    profile.metadata_ns = elapsed_ns(metadata_started);
1027
1028    let mut budget = BudgetTracker::new(limits);
1029    let layer_flash_resolver = BoardLayerFlashResolver::from_view(view)?;
1030    // Decode the shared graphics family once, then partition borrowed carriers
1031    // into the Python category order for geometry and text producers.
1032    let graphics_started = profile_enabled.then(Instant::now);
1033    let (graphics, decoded_graphic_points) = decoded_graphics(view, limits)?;
1034    profile.decode_graphics_ns = elapsed_ns(graphics_started);
1035    let remaining_input_points = limits
1036        .max_input_points
1037        .checked_sub(decoded_graphic_points)
1038        .ok_or_else(input_point_limit_error)?;
1039    let tables_started = profile_enabled.then(Instant::now);
1040    let (tables, table_cells, decoded_table_points) =
1041        table::decoded_tables(view, remaining_input_points)?;
1042    profile.decode_tables_ns = elapsed_ns(tables_started);
1043    let remaining_input_points = remaining_input_points
1044        .checked_sub(decoded_table_points)
1045        .ok_or_else(input_point_limit_error)?;
1046    let dimensions_started = profile_enabled.then(Instant::now);
1047    let (dimensions, decoded_dimension_points) = decoded_dimensions(view, remaining_input_points)?;
1048    profile.decode_dimensions_ns = elapsed_ns(dimensions_started);
1049    let graphic_records_started = profile_enabled.then(Instant::now);
1050    let mut records = graphic_records(source, &graphics, &mut budget, limits)?;
1051    profile.graphic_records_ns = elapsed_ns(graphic_records_started);
1052    let variables_started = profile_enabled.then(Instant::now);
1053    let dimension_variables = dimensions.iter().try_fold(false, |needed, dimension| {
1054        if needed {
1055            Ok(true)
1056        } else {
1057            dimension::needs_variables(source, dimension, limits)
1058        }
1059    })?;
1060    let variables = text::board_variables(
1061        view,
1062        &graphics,
1063        table_cells.iter().any(|cell| cell.text.contains("${")) || dimension_variables,
1064        text_variables,
1065    )?;
1066    profile.variables_ns = elapsed_ns(variables_started);
1067    let text_started = profile_enabled.then(Instant::now);
1068    records.extend(text::text_records(
1069        source,
1070        &graphics,
1071        &mut budget,
1072        &variables,
1073        text_cache.as_ref(),
1074        limits,
1075    )?);
1076    profile.text_records_ns = elapsed_ns(text_started);
1077    let copper_started = profile_enabled.then(Instant::now);
1078    append_copper_records(
1079        view,
1080        metadata.pad_to_mask_clearance,
1081        net_classes,
1082        &layer_flash_resolver,
1083        &mut budget,
1084        &mut records,
1085    )?;
1086    profile.copper_records_ns = elapsed_ns(copper_started);
1087    let table_records_started = profile_enabled.then(Instant::now);
1088    records.extend(table::table_records(
1089        source,
1090        &tables,
1091        &table_cells,
1092        &variables,
1093        &mut budget,
1094        text_cache.as_ref(),
1095        limits,
1096    )?);
1097    profile.table_records_ns = elapsed_ns(table_records_started);
1098    let dimension_records_started = profile_enabled.then(Instant::now);
1099    append_dimension_records(
1100        source,
1101        &dimensions,
1102        &variables,
1103        &mut budget,
1104        text_cache.as_ref(),
1105        limits,
1106        &mut records,
1107    )?;
1108    profile.dimension_records_ns = elapsed_ns(dimension_records_started);
1109    let decoded_input_points = decoded_graphic_points
1110        .checked_add(decoded_table_points)
1111        .and_then(|count| count.checked_add(decoded_dimension_points))
1112        .filter(|count| *count <= limits.max_input_points)
1113        .ok_or_else(input_point_limit_error)?;
1114    let mut decoded_inputs = (decoded_input_points, 0usize);
1115    let zones_started = profile_enabled.then(Instant::now);
1116    append_zone_records(
1117        view,
1118        net_classes,
1119        &mut budget,
1120        limits,
1121        &mut decoded_inputs.0,
1122        &mut decoded_inputs.1,
1123        &mut records,
1124    )?;
1125    profile.zone_records_ns = elapsed_ns(zones_started);
1126    let footprints_started = profile_enabled.then(Instant::now);
1127    footprint::append_footprint_records(
1128        footprint::FootprintAppendContext {
1129            source,
1130            view,
1131            net_classes,
1132            text_cache: text_cache.as_ref(),
1133            board_mask_clearance: metadata.pad_to_mask_clearance,
1134            limits,
1135            layer_flash_resolver: &layer_flash_resolver,
1136        },
1137        &mut budget,
1138        &mut decoded_inputs,
1139        &mut records,
1140        primary_errors,
1141    )?;
1142    profile.footprint_records_ns = elapsed_ns(footprints_started);
1143    Ok((
1144        BoardPlotDocument {
1145            version: metadata.version,
1146            generator: metadata.generator,
1147            generator_version: metadata.generator_version,
1148            thickness_mm: metadata.thickness,
1149            paper: metadata.paper,
1150            records,
1151        },
1152        profile,
1153    ))
1154}
1155
1156fn elapsed_ns(started: Option<Instant>) -> u64 {
1157    started.map_or(0, |started| {
1158        u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX)
1159    })
1160}
1161
1162fn append_dimension_records(
1163    source: &str,
1164    dimensions: &[PcbDimension],
1165    variables: &BoardTextVariables,
1166    budget: &mut BudgetTracker,
1167    text_cache: Option<&PlotterTextCacheSession<'_>>,
1168    limits: BoardPlotLimits,
1169    records: &mut Vec<BoardPlotRecord>,
1170) -> Result<(), Error> {
1171    for dimension in dimensions {
1172        budget.ensure_capacity(0, 0)?;
1173        let record =
1174            dimension::dimension_record(source, dimension, variables, budget, text_cache, limits)?;
1175        budget.charge(
1176            record.operations.len(),
1177            dimension::cache_point_total(&record),
1178        )?;
1179        budget.charge_text(dimension::retained_text_bytes(&record))?;
1180        records.push(BoardPlotRecord::Dimension(record));
1181    }
1182    Ok(())
1183}
1184
1185fn append_zone_records(
1186    view: &PcbView<'_>,
1187    net_classes: &BoardNetClassAssignments,
1188    budget: &mut BudgetTracker,
1189    limits: BoardPlotLimits,
1190    decoded_input_points: &mut usize,
1191    decoded_input_polygons: &mut usize,
1192    records: &mut Vec<BoardPlotRecord>,
1193) -> Result<(), Error> {
1194    for zone in view.zones() {
1195        let zone = zone.map_err(normalize_input_limit_error)?;
1196        let zone_polygons = zone
1197            .polygons
1198            .len()
1199            .saturating_add(zone.filled_polygons.len());
1200        *decoded_input_polygons = decoded_input_polygons
1201            .checked_add(zone_polygons)
1202            .filter(|count| *count <= limits.max_input_polygons)
1203            .ok_or_else(input_polygon_limit_error)?;
1204        let zone_points = zone
1205            .polygons
1206            .iter()
1207            .map(|polygon| polygon.points.len())
1208            .chain(
1209                zone.filled_polygons
1210                    .iter()
1211                    .map(|polygon| polygon.points.len()),
1212            )
1213            .fold(0usize, usize::saturating_add);
1214        *decoded_input_points = decoded_input_points
1215            .checked_add(zone_points)
1216            .filter(|count| *count <= limits.max_input_points)
1217            .ok_or_else(input_point_limit_error)?;
1218        let output_points = zone
1219            .filled_polygons
1220            .iter()
1221            .map(|polygon| polygon.points.len())
1222            .fold(0usize, usize::saturating_add);
1223        budget.ensure_capacity(zone.filled_polygons.len(), output_points)?;
1224        let record = zone_record(zone, net_classes, budget)?;
1225        budget.charge(
1226            record.operations.len(),
1227            poly_point_total(&record.operations),
1228        )?;
1229        records.push(BoardPlotRecord::Zone(record));
1230    }
1231    Ok(())
1232}
1233
1234fn append_copper_records(
1235    view: &PcbView<'_>,
1236    mask_clearance: f64,
1237    net_classes: &BoardNetClassAssignments,
1238    layer_flash_resolver: &BoardLayerFlashResolver,
1239    budget: &mut BudgetTracker,
1240    records: &mut Vec<BoardPlotRecord>,
1241) -> Result<(), Error> {
1242    for segment in view.segments() {
1243        budget.ensure_capacity(1, 0)?;
1244        let record = segment_record(segment?, net_classes, budget)?;
1245        budget.charge(record.operations.len(), 0)?;
1246        records.push(BoardPlotRecord::Segment(record));
1247    }
1248    for arc in view.arcs() {
1249        budget.ensure_capacity(1, 0)?;
1250        let record = track_arc_record(arc?, net_classes, budget)?;
1251        budget.charge(record.operations.len(), 0)?;
1252        records.push(BoardPlotRecord::TrackArc(record));
1253    }
1254    for via in view.vias() {
1255        let via = via?;
1256        let flashed_layers = layer_flash_resolver.via_flash_layers(&via);
1257        let has_aperture = !flashed_layers.is_empty()
1258            || (via.layers.is_empty()
1259                && via.remove_unused_layers != Some(true)
1260                && via.start_end_only != Some(true));
1261        budget.ensure_capacity(via_operation_count(&via, has_aperture), 0)?;
1262        let record = via_record(
1263            via,
1264            flashed_layers,
1265            has_aperture,
1266            mask_clearance,
1267            net_classes,
1268            budget,
1269        )?;
1270        budget.charge(record.operations.len(), 0)?;
1271        records.push(BoardPlotRecord::Via(record));
1272    }
1273    Ok(())
1274}
1275
1276fn decoded_graphics(
1277    view: &PcbView<'_>,
1278    limits: BoardPlotLimits,
1279) -> Result<(Vec<PcbGraphic>, usize), Error> {
1280    let mut graphics = Vec::new();
1281    let mut point_count = 0usize;
1282    for graphic in view.graphics() {
1283        let graphic = graphic.map_err(normalize_input_limit_error)?;
1284        point_count = point_count
1285            .checked_add(graphic.points.len())
1286            .filter(|count| *count <= limits.max_input_points)
1287            .ok_or_else(input_point_limit_error)?;
1288        graphics.push(graphic);
1289    }
1290    Ok((graphics, point_count))
1291}
1292
1293fn decoded_dimensions(
1294    view: &PcbView<'_>,
1295    maximum_points: usize,
1296) -> Result<(Vec<PcbDimension>, usize), Error> {
1297    let mut dimensions = Vec::new();
1298    let mut point_count = 0usize;
1299    for dimension in view.dimensions() {
1300        let dimension = dimension.map_err(normalize_input_limit_error)?;
1301        point_count = point_count
1302            .checked_add(dimension.points.len())
1303            .filter(|count| *count <= maximum_points)
1304            .ok_or_else(input_point_limit_error)?;
1305        dimensions.push(dimension);
1306    }
1307    Ok((dimensions, point_count))
1308}
1309
1310fn board_selection() -> PcbSelection {
1311    PcbSelection::only(PcbFamily::Graphics)
1312        .with(PcbFamily::Layers)
1313        .with(PcbFamily::Properties)
1314        .with(PcbFamily::Segments)
1315        .with(PcbFamily::Arcs)
1316        .with(PcbFamily::Vias)
1317        .with(PcbFamily::Tables)
1318        .with(PcbFamily::Dimensions)
1319        .with(PcbFamily::Zones)
1320        .with(PcbFamily::Footprints)
1321        .with(PcbFamily::FootprintProperties)
1322        .with(PcbFamily::FootprintGraphics)
1323        .with(PcbFamily::FootprintTexts)
1324        .with(PcbFamily::FootprintTextBoxes)
1325        .with(PcbFamily::Pads)
1326        .with(PcbFamily::Images)
1327}
1328
1329/// Python `_net_extras`: `net_id` follows the resolved ordinal and
1330/// `net_name` only appears for truthy resolved names.
1331fn net_parts(net: &PcbNetRef) -> (Option<i64>, Option<String>) {
1332    (
1333        net.ordinal,
1334        net.name.clone().filter(|name| !name.is_empty()),
1335    )
1336}
1337
1338fn poly_point_total(operations: &[PlotterOperation]) -> usize {
1339    operations
1340        .iter()
1341        .map(|operation| match operation {
1342            PlotterOperation::PlotPoly(value) => value.points.len(),
1343            _ => 0,
1344        })
1345        .sum()
1346}
1347
1348fn layerless_segment(start: [i64; 2], end: [i64; 2], width_nm: i64) -> PlotterOperation {
1349    PlotterOperation::ThickSegment(ThickSegment {
1350        start_x: start[0],
1351        start_y: start[1],
1352        end_x: end[0],
1353        end_y: end[1],
1354        width_nm,
1355        layer: None,
1356        role: None,
1357        layers: Vec::new(),
1358        mask_margin_nm: None,
1359        pad_size_x_nm: None,
1360        pad_size_y_nm: None,
1361    })
1362}
1363
1364fn limit_error() -> Error {
1365    Error::at(
1366        ErrorPhase::Tree,
1367        ErrorKind::ResourceLimit,
1368        "Board plotter operation exceeds configured limits",
1369        Position::START,
1370    )
1371}
1372
1373fn point_limit_error() -> Error {
1374    Error::at(
1375        ErrorPhase::Tree,
1376        ErrorKind::ResourceLimit,
1377        "Board plotter geometry exceeds max_points",
1378        Position::START,
1379    )
1380}
1381
1382fn input_point_limit_error() -> Error {
1383    Error::at(
1384        ErrorPhase::Tree,
1385        ErrorKind::ResourceLimit,
1386        "Board plotter decoded points exceed max_input_points",
1387        Position::START,
1388    )
1389}
1390
1391fn input_polygon_limit_error() -> Error {
1392    Error::at(
1393        ErrorPhase::Tree,
1394        ErrorKind::ResourceLimit,
1395        "Board plotter decoded polygons exceed max_input_polygons",
1396        Position::START,
1397    )
1398}
1399
1400fn normalize_input_limit_error(error: Error) -> Error {
1401    if error.message.contains("max_zone_polygons") {
1402        input_polygon_limit_error()
1403    } else if error.message.contains("max_zone_points")
1404        || error.message.contains("max_graphic_points")
1405    {
1406        input_point_limit_error()
1407    } else {
1408        error
1409    }
1410}
1411
1412fn text_limit_error() -> Error {
1413    Error::at(
1414        ErrorPhase::Tree,
1415        ErrorKind::ResourceLimit,
1416        "Board plotter retained text exceeds max_text_bytes",
1417        Position::START,
1418    )
1419}
1420
1421fn net_class_limit_error() -> Error {
1422    Error::at(
1423        ErrorPhase::Tree,
1424        ErrorKind::ResourceLimit,
1425        "Board plotter retained net-class strings exceed max_net_class_bytes",
1426        Position::START,
1427    )
1428}
1429
1430fn metadata_limit_error() -> Error {
1431    Error::at(
1432        ErrorPhase::Tree,
1433        ErrorKind::ResourceLimit,
1434        "Board footprint metadata exceeds max_metadata_bytes",
1435        Position::START,
1436    )
1437}