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

kicad_monkey_core/
schematic_plotter_ir.rs

1//! Bounded native schematic Plotter-IR foundation.
2//!
3//! The plotting decoder intentionally reads exact source millimetres instead
4//! of reusing the connectivity model's 100 nm grid. Project variables, page
5//! context, and worksheet bytes are explicit sidecars;
6//! this module performs no filesystem discovery.
7
8mod annotation_render;
9mod graphic_render;
10pub(crate) mod image_decode;
11pub(crate) mod owned;
12mod sheet_render;
13mod symbol_render;
14mod table_render;
15mod text_metrics;
16mod worksheet_render;
17
18use crate::plotter_ir::{ensure_javascript_safe_integer, mm_to_nm};
19use crate::plotter_text_cache::{PlotterTextCacheResources, PlotterTextCacheSession};
20use crate::plotter_types::{
21    PlotterCircle, PlotterFill, PlotterImage, PlotterLineStyle, PlotterOperation, PlotterPoly,
22    PlotterText, ThickSegment,
23};
24use crate::schematic_diagnostics::{KiCadDiagnostic, KiCadDiagnosticCode};
25use crate::sexpr::{Error, ErrorKind, ErrorPhase, Position, Sexp, parse};
26use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
27use std::collections::{BTreeMap, BTreeSet};
28use std::time::Instant;
29
30use annotation_render::{annotation_variables, append_annotation_records};
31use graphic_render::{append_graphic_records, append_image_records, append_rule_area_records};
32use sheet_render::append_sheet_records;
33use symbol_render::append_symbol_records;
34use table_render::append_table_records;
35use worksheet_render::drawing_sheet_operations;
36
37const DEFAULT_VERSION: i64 = 20_260_306;
38const DEFAULT_GENERATOR: &str = "eeschema";
39const DEFAULT_GENERATOR_VERSION: &str = "10.0";
40pub(super) const DEFAULT_KICAD_VERSION_TEXT: &str = "KiCad E.D.A. 10.0.8";
41const MIN_PLOT_PEN_WIDTH_NM: i64 = 84_700;
42const DEFAULT_WIRE_WIDTH_MM: f64 = 0.1524;
43const DEFAULT_BUS_WIDTH_MM: f64 = 0.3048;
44const DEFAULT_JUNCTION_DIAMETER_MM: f64 = 0.9144;
45const DEFAULT_NO_CONNECT_HALF_MM: f64 = 0.6096;
46const WIRE_COLOR: &str = "#009600FF";
47const BUS_COLOR: &str = "#000084FF";
48const JUNCTION_COLOR: &str = "#009600FF";
49const NO_CONNECT_COLOR: &str = "#000084FF";
50
51/// Opt-in successful-build timings for the bounded schematic Plotter-IR path.
52/// Normal builders do not read a clock.
53#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
54pub struct SchematicPlotBuildProfile {
55    pub validate_source_parse_ns: u64,
56    pub select_and_collect_inputs_ns: u64,
57    pub worksheet_header_ns: u64,
58    pub connectivity_ns: u64,
59    pub text_resource_setup_ns: u64,
60    pub annotations_ns: u64,
61    pub graphics_and_rule_areas_ns: u64,
62    pub images_ns: u64,
63    pub tables_ns: u64,
64    pub symbols_ns: u64,
65    pub sheets_ns: u64,
66}
67
68/// Effective project drawing settings supplied by the caller. The transport
69/// adapter owns conversion from KiCad's project-file mil representation.
70#[derive(Clone, Copy, Debug, PartialEq)]
71pub struct SchematicDrawingSettings {
72    pub text_offset_ratio: f64,
73    pub default_line_width_nm: i64,
74}
75
76impl Default for SchematicDrawingSettings {
77    fn default() -> Self {
78        Self {
79            text_offset_ratio: 0.15,
80            default_line_width_nm: 152_400,
81        }
82    }
83}
84
85/// Caller-supplied project variables. Later duplicate names overwrite earlier
86/// ones, matching JSON object semantics.
87#[derive(Clone, Debug, Default, Eq, PartialEq)]
88pub struct SchematicPlotVariables {
89    values: BTreeMap<String, String>,
90}
91
92impl SchematicPlotVariables {
93    pub fn from_entries<N, V>(entries: impl IntoIterator<Item = (N, V)>) -> Self
94    where
95        N: Into<String>,
96        V: Into<String>,
97    {
98        Self {
99            values: entries
100                .into_iter()
101                .map(|(name, value)| (name.into(), value.into()))
102                .collect(),
103        }
104    }
105
106    pub fn get(&self, name: &str) -> Option<&str> {
107        self.values.get(name).map(String::as_str)
108    }
109}
110
111/// Explicit page and project sidecars. `worksheet_source`, when present, is
112/// the already-selected, decompressed worksheet file; absence uses KiCad's
113/// built-in default drawing sheet.
114#[derive(Clone, Debug, PartialEq)]
115pub struct SchematicPlotContext {
116    pub source_path: Option<String>,
117    pub document_id: Option<String>,
118    pub sheet_index: usize,
119    pub sheet_count: usize,
120    pub sheet_path: String,
121    /// KiCad UUID occurrence path used to select instance-specific references.
122    pub sheet_instance_path: String,
123    pub sheet_name: String,
124    pub project_variables: SchematicPlotVariables,
125    pub worksheet_source: Option<Vec<u8>>,
126}
127
128impl Default for SchematicPlotContext {
129    fn default() -> Self {
130        Self {
131            source_path: None,
132            document_id: None,
133            sheet_index: 1,
134            sheet_count: 1,
135            sheet_path: "/".to_owned(),
136            sheet_instance_path: "/".to_owned(),
137            sheet_name: String::new(),
138            project_variables: SchematicPlotVariables::default(),
139            worksheet_source: None,
140        }
141    }
142}
143
144#[derive(Clone, Copy, Debug, Eq, PartialEq)]
145pub struct SchematicCanvas {
146    pub width_nm: i64,
147    pub height_nm: i64,
148}
149
150#[derive(Clone, Debug, Default, Eq, PartialEq)]
151pub struct SchematicTitleBlock {
152    pub title: String,
153    pub date: String,
154    pub revision: String,
155    pub company: String,
156    pub comments: BTreeMap<i64, String>,
157}
158
159#[derive(Clone, Debug, PartialEq)]
160pub struct SchematicSheetHeaderRecord {
161    pub uuid: String,
162    pub paper_size: String,
163    pub paper_width_mm: Option<f64>,
164    pub paper_height_mm: Option<f64>,
165    pub paper_portrait: bool,
166    pub sheet_width_nm: i64,
167    pub sheet_height_nm: i64,
168    pub version: i64,
169    pub generator: String,
170    pub generator_version: String,
171    pub title_block: Option<SchematicTitleBlock>,
172    pub operations: Vec<SchematicPlotOperation>,
173}
174
175#[derive(Clone, Copy, Debug, Eq, PartialEq)]
176pub enum SchematicConnectivityRecordKind {
177    Wire,
178    Bus,
179    BusEntry,
180    Junction,
181    NoConnect,
182}
183
184impl SchematicConnectivityRecordKind {
185    pub const fn as_str(self) -> &'static str {
186        match self {
187            Self::Wire => "wire",
188            Self::Bus => "bus",
189            Self::BusEntry => "bus_entry",
190            Self::Junction => "junction",
191            Self::NoConnect => "no_connect",
192        }
193    }
194}
195
196#[derive(Clone, Debug, PartialEq)]
197pub struct SchematicConnectivityRecord {
198    pub uuid: String,
199    pub kind: SchematicConnectivityRecordKind,
200    /// Distinguishes no authored junction color from an authored transparent
201    /// color, whose normalized value is `None` but whose extra is present.
202    pub junction_color_authored: bool,
203    pub junction_color: Option<String>,
204    pub operations: Vec<SchematicPlotOperation>,
205}
206
207#[derive(Clone, Copy, Debug, Eq, PartialEq)]
208pub enum SchematicAnnotationRecordKind {
209    Label,
210    GlobalLabel,
211    HierarchicalLabel,
212    NetclassFlag,
213    Text,
214    TextBox,
215}
216
217impl SchematicAnnotationRecordKind {
218    pub const fn as_str(self) -> &'static str {
219        match self {
220            Self::Label => "label",
221            Self::GlobalLabel => "global_label",
222            Self::HierarchicalLabel => "hierarchical_label",
223            Self::NetclassFlag => "netclass_flag",
224            Self::Text => "text",
225            Self::TextBox => "text_box",
226        }
227    }
228}
229
230/// Annotation extras are optional only where the corresponding strict record
231/// kind does not carry them. Producers populate every required field.
232#[derive(Clone, Debug, PartialEq)]
233pub struct SchematicAnnotationRecord {
234    pub uuid: String,
235    pub kind: SchematicAnnotationRecordKind,
236    pub object_id: String,
237    pub text: Option<String>,
238    pub shape: Option<String>,
239    pub at_x_nm: Option<i64>,
240    pub at_y_nm: Option<i64>,
241    pub length_nm: Option<i64>,
242    pub operations: Vec<SchematicPlotOperation>,
243}
244
245#[derive(Clone, Copy, Debug, Eq, PartialEq)]
246pub enum SchematicGraphicRecordKind {
247    GraphicPolyline,
248    GraphicArc,
249    GraphicCircle,
250    GraphicRectangle,
251    GraphicBezier,
252}
253
254impl SchematicGraphicRecordKind {
255    pub const fn as_str(self) -> &'static str {
256        match self {
257            Self::GraphicPolyline => "graphic_polyline",
258            Self::GraphicArc => "graphic_arc",
259            Self::GraphicCircle => "graphic_circle",
260            Self::GraphicRectangle => "graphic_rectangle",
261            Self::GraphicBezier => "graphic_bezier",
262        }
263    }
264}
265
266#[derive(Clone, Debug, PartialEq)]
267pub struct SchematicGraphicRecord {
268    pub uuid: String,
269    pub kind: SchematicGraphicRecordKind,
270    pub operations: Vec<SchematicPlotOperation>,
271}
272
273#[derive(Clone, Copy, Debug, Eq, PartialEq)]
274pub enum SchematicRuleAreaShape {
275    Polyline,
276    Rectangle,
277    Arc,
278    Circle,
279    Bezier,
280}
281
282impl SchematicRuleAreaShape {
283    pub const fn as_str(self) -> &'static str {
284        match self {
285            Self::Polyline => "polyline",
286            Self::Rectangle => "rectangle",
287            Self::Arc => "arc",
288            Self::Circle => "circle",
289            Self::Bezier => "bezier",
290        }
291    }
292}
293
294#[derive(Clone, Debug, PartialEq)]
295pub struct SchematicRuleAreaRecord {
296    pub uuid: String,
297    pub shape: SchematicRuleAreaShape,
298    pub locked: bool,
299    pub exclude_from_sim: bool,
300    pub in_bom: bool,
301    pub on_board: bool,
302    pub dnp: bool,
303    pub operations: Vec<SchematicPlotOperation>,
304}
305
306#[derive(Clone, Debug, PartialEq)]
307pub struct SchematicImageRecord {
308    pub uuid: String,
309    pub scale: f64,
310    pub image_format: String,
311    pub width_nm: i64,
312    pub height_nm: i64,
313    pub operations: Vec<SchematicPlotOperation>,
314}
315
316#[derive(Clone, Debug, PartialEq)]
317pub struct SchematicTableRecord {
318    pub uuid: String,
319    pub cell_count: usize,
320    pub operations: Vec<SchematicPlotOperation>,
321}
322
323#[derive(Clone, Debug, PartialEq)]
324pub struct SchematicSymbolInstanceRecord {
325    pub uuid: String,
326    pub lib_id: String,
327    pub lib_name: String,
328    pub reference: String,
329    pub at_x_nm: i64,
330    pub at_y_nm: i64,
331    pub at_angle_deg: f64,
332    pub mirror: Option<String>,
333    pub unit: u32,
334    pub convert: u32,
335    pub in_bom: bool,
336    pub on_board: bool,
337    pub dnp: bool,
338    pub exclude_from_sim: bool,
339    pub in_pos_files: bool,
340    pub operations: Vec<SchematicPlotOperation>,
341}
342
343#[derive(Clone, Debug, PartialEq)]
344pub struct SchematicSymbolOverplotRecord {
345    pub uuid: String,
346    pub source_symbol_uuid: String,
347    pub lib_id: String,
348    pub operations: Vec<SchematicPlotOperation>,
349}
350
351#[derive(Clone, Debug, PartialEq)]
352pub struct SchematicSheetRecord {
353    pub uuid: String,
354    pub sheet_name: String,
355    pub sheet_file: String,
356    pub at_x_nm: i64,
357    pub at_y_nm: i64,
358    pub size_x_nm: i64,
359    pub size_y_nm: i64,
360    pub dnp: bool,
361    pub operations: Vec<SchematicPlotOperation>,
362}
363
364#[derive(Clone, Debug, Default, Eq, PartialEq)]
365pub struct SchematicSymbolPinAttrs {
366    pub primitive: String,
367    pub object_type: String,
368    pub pin: String,
369    pub symbol_uuid: String,
370    pub designator: String,
371    pub lib_pin_uuid: String,
372}
373
374#[derive(Clone, Debug, Eq, PartialEq)]
375pub struct SchematicSymbolPinBlock {
376    pub label: String,
377    pub data_uuid: String,
378    pub object_id: String,
379    pub extra_attrs: SchematicSymbolPinAttrs,
380}
381
382#[derive(Clone, Debug, Default, Eq, PartialEq)]
383pub struct SchematicSheetPinAttrs {
384    pub primitive: String,
385    pub object_type: String,
386    pub sheet_uuid: String,
387    pub sheet_name: String,
388    pub sheet_file: String,
389    pub pin: String,
390    pub pin_name: String,
391    pub shape: String,
392}
393
394#[derive(Clone, Debug, Eq, PartialEq)]
395pub struct SchematicSheetPinBlock {
396    pub label: String,
397    pub data_uuid: String,
398    pub object_id: String,
399    pub extra_attrs: SchematicSheetPinAttrs,
400}
401
402/// Schematic-only Text wrapper for operation-local hyperlink context without
403/// broadening established producer-neutral Text payloads.
404#[derive(Clone, Debug, PartialEq)]
405pub struct SchematicTextOperation {
406    pub text: PlotterText,
407    pub hyperlink_href: Option<String>,
408}
409
410/// Schematic-only styled segment used by directive/netclass flag markers.
411#[derive(Clone, Debug, PartialEq)]
412pub struct SchematicStyledThickSegment {
413    pub segment: ThickSegment,
414    pub stroke_color: String,
415}
416
417/// Schematic plotting extends the shared vector vocabulary with worksheet
418/// raster placement without changing the established board/footprint ABI.
419#[derive(Clone, Debug, PartialEq)]
420pub enum SchematicPlotOperation {
421    Plotter(PlotterOperation),
422    PlotImage(PlotterImage),
423    Text(SchematicTextOperation),
424    StyledThickSegment(SchematicStyledThickSegment),
425    StartSymbolPinBlock(SchematicSymbolPinBlock),
426    StartSheetPinBlock(SchematicSheetPinBlock),
427    EndBlock,
428}
429
430impl From<PlotterOperation> for SchematicPlotOperation {
431    fn from(value: PlotterOperation) -> Self {
432        Self::Plotter(value)
433    }
434}
435
436#[derive(Clone, Debug, PartialEq)]
437pub enum SchematicPlotRecord {
438    SheetHeader(SchematicSheetHeaderRecord),
439    Connectivity(SchematicConnectivityRecord),
440    Annotation(SchematicAnnotationRecord),
441    Graphic(SchematicGraphicRecord),
442    RuleArea(SchematicRuleAreaRecord),
443    Image(SchematicImageRecord),
444    Table(SchematicTableRecord),
445    SymbolInstance(SchematicSymbolInstanceRecord),
446    SymbolOverplot(SchematicSymbolOverplotRecord),
447    Sheet(SchematicSheetRecord),
448}
449
450impl SchematicPlotRecord {
451    pub fn operation_count(&self) -> usize {
452        match self {
453            Self::SheetHeader(record) => record.operations.len(),
454            Self::Connectivity(record) => record.operations.len(),
455            Self::Annotation(record) => record.operations.len(),
456            Self::Graphic(record) => record.operations.len(),
457            Self::RuleArea(record) => record.operations.len(),
458            Self::Image(record) => record.operations.len(),
459            Self::Table(record) => record.operations.len(),
460            Self::SymbolInstance(record) => record.operations.len(),
461            Self::SymbolOverplot(record) => record.operations.len(),
462            Self::Sheet(record) => record.operations.len(),
463        }
464    }
465}
466
467#[derive(Clone, Debug, PartialEq)]
468pub struct SchematicPlotDocument {
469    pub source_path: Option<String>,
470    pub document_id: String,
471    pub canvas: SchematicCanvas,
472    pub records: Vec<SchematicPlotRecord>,
473}
474
475#[derive(Default)]
476struct CarrierSpans {
477    wires: Vec<FormSpan>,
478    buses: Vec<FormSpan>,
479    bus_entries: Vec<FormSpan>,
480    junctions: Vec<FormSpan>,
481    no_connects: Vec<FormSpan>,
482    labels: Vec<FormSpan>,
483    global_labels: Vec<FormSpan>,
484    hierarchical_labels: Vec<FormSpan>,
485    netclass_flags: Vec<FormSpan>,
486    texts: Vec<FormSpan>,
487    text_boxes: Vec<FormSpan>,
488    polylines: Vec<FormSpan>,
489    arcs: Vec<FormSpan>,
490    circles: Vec<FormSpan>,
491    rectangles: Vec<FormSpan>,
492    beziers: Vec<FormSpan>,
493    rule_areas: Vec<FormSpan>,
494    images: Vec<FormSpan>,
495    tables: Vec<FormSpan>,
496    lib_symbols: Option<FormSpan>,
497    symbols: Vec<FormSpan>,
498    sheets: Vec<FormSpan>,
499}
500
501struct SchematicBuildContext<'a, 'font> {
502    source: &'a str,
503    plot: &'a SchematicPlotContext,
504    scope: SchematicPlotScope,
505    drawing: Option<SchematicDrawingSettings>,
506    text_resources: Option<&'a PlotterTextCacheResources<'font>>,
507}
508
509struct SchematicSourceInputs {
510    version: i64,
511    generator: String,
512    generator_version: String,
513    uuid: String,
514    paper: Paper,
515    title_block: Option<SchematicTitleBlock>,
516    carriers: CarrierSpans,
517}
518
519struct SchematicHeaderBuild {
520    header: SchematicSheetHeaderRecord,
521    document_id: String,
522    width_nm: i64,
523    height_nm: i64,
524    budget: PlotBudget,
525}
526
527struct ConnectivityPolylineStyle {
528    kind: SchematicConnectivityRecordKind,
529    default_width_mm: f64,
530    default_color: &'static str,
531}
532
533pub(super) struct AnnotationSpans {
534    labels: Vec<FormSpan>,
535    global_labels: Vec<FormSpan>,
536    hierarchical_labels: Vec<FormSpan>,
537    netclass_flags: Vec<FormSpan>,
538    texts: Vec<FormSpan>,
539    text_boxes: Vec<FormSpan>,
540}
541
542pub(super) struct GraphicSpans {
543    polylines: Vec<FormSpan>,
544    arcs: Vec<FormSpan>,
545    circles: Vec<FormSpan>,
546    rectangles: Vec<FormSpan>,
547    beziers: Vec<FormSpan>,
548    rule_areas: Vec<FormSpan>,
549    images: Vec<FormSpan>,
550    tables: Vec<FormSpan>,
551}
552
553#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
554enum SchematicPlotScope {
555    Foundation,
556    Annotations,
557    Graphics,
558    Symbols,
559    Sheets,
560}
561
562pub(crate) struct PlotBudget {
563    owned: Option<owned::OwnedPlotCapture>,
564    source_path: String,
565    pub(crate) diagnostics: Vec<KiCadDiagnostic>,
566    /// First object failure, returned by the strict document functions.
567    first_error: Option<Error>,
568}
569
570/// Output lengths before one object is drawn, so a failure can be undone.
571#[derive(Clone, Copy)]
572pub(crate) struct ObjectMark {
573    records: usize,
574    bindings: usize,
575}
576
577impl PlotBudget {
578    fn new() -> Self {
579        Self {
580            owned: None,
581            source_path: String::new(),
582            diagnostics: Vec::new(),
583            first_error: None,
584        }
585    }
586
587    pub(crate) fn mark(&self, records: &[SchematicPlotRecord]) -> ObjectMark {
588        ObjectMark {
589            records: records.len(),
590            bindings: self
591                .owned
592                .as_ref()
593                .map_or(0, |capture| capture.bindings.len()),
594        }
595    }
596
597    /// Finish one object. A failure removes whatever the object emitted and
598    /// leaves it out with an error diagnostic; the page continues.
599    pub(crate) fn settle(
600        &mut self,
601        mark: ObjectMark,
602        records: &mut Vec<SchematicPlotRecord>,
603        result: Result<(), Error>,
604        object: (&str, &FormSpan),
605    ) {
606        let Err(error) = result else {
607            return;
608        };
609        records.truncate(mark.records);
610        if let Some(capture) = self.owned.as_mut() {
611            capture.bindings.truncate(mark.bindings);
612        }
613        let (source, span) = object;
614        let kind = span.head.clone().unwrap_or_else(|| "object".to_owned());
615        let message = format!("{kind} could not be drawn ({error}); it is left out");
616        self.first_error.get_or_insert(error);
617        let uuid = source
618            .get(span.range.clone())
619            .and_then(crate::schematic_diagnostics::direct_uuid);
620        self.diagnostics.push(KiCadDiagnostic::new(
621            KiCadDiagnosticCode::ObjectNotDrawn,
622            self.source_path.clone(),
623            kind.clone(),
624            uuid,
625            message,
626        ));
627    }
628}
629
630/// Produce the P5_060 page header and connectivity families from raw source.
631pub fn schematic_plot_document(
632    source: &str,
633    context: &SchematicPlotContext,
634) -> Result<SchematicPlotDocument, Error> {
635    schematic_plot_document_impl(
636        source,
637        context,
638        SchematicPlotScope::Foundation,
639        None,
640        None,
641        None,
642    )
643}
644
645/// Produce the P5_061 page foundation and annotation families. Drawing
646/// settings and optional font bytes are explicit sidecars; core never reads a
647/// project or discovers a platform font.
648pub fn schematic_plot_document_with_annotations(
649    source: &str,
650    context: &SchematicPlotContext,
651    drawing_settings: SchematicDrawingSettings,
652    text_resources: Option<&PlotterTextCacheResources<'_>>,
653) -> Result<SchematicPlotDocument, Error> {
654    validate_drawing_settings(drawing_settings)?;
655    schematic_plot_document_impl(
656        source,
657        context,
658        SchematicPlotScope::Annotations,
659        Some(drawing_settings),
660        text_resources,
661        None,
662    )
663}
664
665/// Produce the complete P5_062 page foundation, annotations, graphics,
666/// rule areas, embedded images, and tables. All project and font inputs are
667/// explicit sidecars; core performs no path or platform-font discovery.
668pub fn schematic_plot_document_with_graphics(
669    source: &str,
670    context: &SchematicPlotContext,
671    drawing_settings: SchematicDrawingSettings,
672    text_resources: Option<&PlotterTextCacheResources<'_>>,
673) -> Result<SchematicPlotDocument, Error> {
674    validate_drawing_settings(drawing_settings)?;
675    schematic_plot_document_impl(
676        source,
677        context,
678        SchematicPlotScope::Graphics,
679        Some(drawing_settings),
680        text_resources,
681        None,
682    )
683}
684
685/// Produce the complete P5_070 page through placed symbols and overlap
686/// overplots. Embedded library data, occurrence selection, drawing settings,
687/// project variables, and font bytes are all explicit source or sidecars.
688pub fn schematic_plot_document_with_symbols(
689    source: &str,
690    context: &SchematicPlotContext,
691    drawing_settings: SchematicDrawingSettings,
692    text_resources: Option<&PlotterTextCacheResources<'_>>,
693) -> Result<SchematicPlotDocument, Error> {
694    validate_drawing_settings(drawing_settings)?;
695    schematic_plot_document_impl(
696        source,
697        context,
698        SchematicPlotScope::Symbols,
699        Some(drawing_settings),
700        text_resources,
701        None,
702    )
703}
704
705/// Produce the complete P5_071 page through terminal hierarchical sheets.
706/// Sheet source, drawing settings, page context, and optional font bytes are
707/// explicit inputs; core performs no project, path, or platform discovery.
708pub fn schematic_plot_document_with_sheets(
709    source: &str,
710    context: &SchematicPlotContext,
711    drawing_settings: SchematicDrawingSettings,
712    text_resources: Option<&PlotterTextCacheResources<'_>>,
713) -> Result<SchematicPlotDocument, Error> {
714    validate_drawing_settings(drawing_settings)?;
715    schematic_plot_document_impl(
716        source,
717        context,
718        SchematicPlotScope::Sheets,
719        Some(drawing_settings),
720        text_resources,
721        None,
722    )
723}
724
725/// Produce a complete schematic page and successful-build phase timings.
726pub fn schematic_plot_document_with_sheets_profiled(
727    source: &str,
728    context: &SchematicPlotContext,
729    drawing_settings: SchematicDrawingSettings,
730    text_resources: Option<&PlotterTextCacheResources<'_>>,
731) -> Result<(SchematicPlotDocument, SchematicPlotBuildProfile), Error> {
732    validate_drawing_settings(drawing_settings)?;
733    let mut profile = SchematicPlotBuildProfile::default();
734    let document = schematic_plot_document_impl(
735        source,
736        context,
737        SchematicPlotScope::Sheets,
738        Some(drawing_settings),
739        text_resources,
740        Some(&mut profile),
741    )?;
742    Ok((document, profile))
743}
744
745fn schematic_plot_document_impl(
746    source: &str,
747    context: &SchematicPlotContext,
748    scope: SchematicPlotScope,
749    drawing_settings: Option<SchematicDrawingSettings>,
750    text_resources: Option<&PlotterTextCacheResources<'_>>,
751    profile: Option<&mut SchematicPlotBuildProfile>,
752) -> Result<SchematicPlotDocument, Error> {
753    let build = SchematicBuildContext {
754        source,
755        plot: context,
756        scope,
757        drawing: drawing_settings,
758        text_resources,
759    };
760    // Strict output is the reporting path with nothing left out: the first
761    // object failure is returned instead of a document missing that object.
762    build_document(&build, profile, None)
763        .and_then(|(document, _, _, first_error)| first_error.map_or(Ok(document), Err))
764}
765
766/// A built page: its document, captured source bindings, the diagnostics for
767/// objects left out, and the first such failure for the strict functions.
768type DocumentBuild = (
769    SchematicPlotDocument,
770    Vec<owned::NativePlotBinding>,
771    Vec<KiCadDiagnostic>,
772    Option<Error>,
773);
774
775fn build_document(
776    build: &SchematicBuildContext<'_, '_>,
777    mut profile: Option<&mut SchematicPlotBuildProfile>,
778    owned: Option<owned::OwnedPlotInput>,
779) -> Result<DocumentBuild, Error> {
780    let context = build.plot;
781    let validate_started = profile.is_some().then(Instant::now);
782    validate_schematic_source(build)?;
783    if let Some(profile) = profile.as_deref_mut() {
784        profile.validate_source_parse_ns = elapsed_ns(validate_started);
785    }
786    let collect_started = profile.is_some().then(Instant::now);
787    let inputs = collect_schematic_inputs(build)?;
788    if let Some(profile) = profile.as_deref_mut() {
789        profile.select_and_collect_inputs_ns = elapsed_ns(collect_started);
790    }
791    let SchematicSourceInputs {
792        version,
793        generator,
794        generator_version,
795        uuid,
796        paper,
797        title_block,
798        carriers,
799    } = inputs;
800    let header_started = profile.is_some().then(Instant::now);
801    let header = build_schematic_header(
802        build,
803        version,
804        generator,
805        generator_version,
806        uuid,
807        paper,
808        title_block,
809    )?;
810    if let Some(profile) = profile.as_deref_mut() {
811        profile.worksheet_header_ns = elapsed_ns(header_started);
812    }
813    let mut budget = header.budget;
814    budget.owned = owned.map(|input| owned::OwnedPlotCapture {
815        input,
816        bindings: Vec::new(),
817    });
818    let records = render_schematic_records(build, carriers, header.header, &mut budget, profile)?;
819    let diagnostics = std::mem::take(&mut budget.diagnostics);
820    let first_error = budget.first_error.take();
821    let bindings = budget
822        .owned
823        .map_or_else(Vec::new, |capture| capture.bindings);
824    Ok((
825        SchematicPlotDocument {
826            source_path: context.source_path.clone(),
827            document_id: header.document_id,
828            canvas: SchematicCanvas {
829                width_nm: header.width_nm,
830                height_nm: header.height_nm,
831            },
832            records,
833        },
834        bindings,
835        diagnostics,
836        first_error,
837    ))
838}
839
840fn elapsed_ns(started: Option<Instant>) -> u64 {
841    started.map_or(0, |started| {
842        u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX)
843    })
844}
845
846fn validate_schematic_source(build: &SchematicBuildContext<'_, '_>) -> Result<(), Error> {
847    validate_context(build.plot)?;
848    // The page must be one well-formed S-expression before its forms are
849    // projected, as KiCad's loader requires.
850    parse(build.source)?;
851    Ok(())
852}
853
854fn collect_schematic_inputs(
855    build: &SchematicBuildContext<'_, '_>,
856) -> Result<SchematicSourceInputs, Error> {
857    let spans = selected_spans(build.source, build.scope)?;
858    let roots = spans
859        .iter()
860        .filter(|span| span.depth == 0)
861        .collect::<Vec<_>>();
862    if roots.len() != 1 || roots[0].head.as_deref() != Some("kicad_sch") {
863        return Err(model_error("Expected exactly one kicad_sch root"));
864    }
865    let mut version = None;
866    let mut generator = None;
867    let mut generator_version = None;
868    let mut uuid = None;
869    let mut paper = None;
870    let mut title_block = None;
871    let mut carriers = CarrierSpans::default();
872    for span in spans.into_iter().filter(|span| span.depth == 1) {
873        match span.head.as_deref() {
874            Some("version") if version.is_none() => version = Some(form_i64(build.source, &span)?),
875            Some("generator") if generator.is_none() => {
876                generator = Some(form_string(build.source, &span)?)
877            }
878            Some("generator_version") if generator_version.is_none() => {
879                generator_version = Some(form_string(build.source, &span)?)
880            }
881            Some("uuid") if uuid.is_none() => uuid = Some(form_string(build.source, &span)?),
882            Some("paper") if paper.is_none() => paper = Some(parse_paper(build.source, &span)?),
883            Some("title_block") if title_block.is_none() => {
884                title_block = Some(parse_title_block(build.source, &span)?)
885            }
886            Some("wire") => carriers.wires.push(span),
887            Some("bus") => carriers.buses.push(span),
888            Some("bus_entry") => carriers.bus_entries.push(span),
889            Some("junction") => carriers.junctions.push(span),
890            Some("no_connect") => carriers.no_connects.push(span),
891            Some("label") => carriers.labels.push(span),
892            Some("global_label") => carriers.global_labels.push(span),
893            Some("hierarchical_label") => carriers.hierarchical_labels.push(span),
894            Some("netclass_flag") => carriers.netclass_flags.push(span),
895            Some("text") => carriers.texts.push(span),
896            Some("text_box") => carriers.text_boxes.push(span),
897            Some("polyline") => carriers.polylines.push(span),
898            Some("arc") => carriers.arcs.push(span),
899            Some("circle") => carriers.circles.push(span),
900            Some("rectangle") => carriers.rectangles.push(span),
901            Some("bezier") => carriers.beziers.push(span),
902            Some("rule_area") => carriers.rule_areas.push(span),
903            Some("image") => carriers.images.push(span),
904            Some("table") => carriers.tables.push(span),
905            Some("lib_symbols") if carriers.lib_symbols.is_none() => {
906                carriers.lib_symbols = Some(span)
907            }
908            Some("symbol") => carriers.symbols.push(span),
909            Some("sheet") => carriers.sheets.push(span),
910            _ => {}
911        }
912    }
913    let version = version.unwrap_or(DEFAULT_VERSION);
914    ensure_javascript_safe_integer(version)?;
915    Ok(SchematicSourceInputs {
916        version,
917        generator: generator.unwrap_or_else(|| DEFAULT_GENERATOR.to_owned()),
918        generator_version: generator_version
919            .unwrap_or_else(|| DEFAULT_GENERATOR_VERSION.to_owned()),
920        uuid: uuid.unwrap_or_default(),
921        paper: paper.unwrap_or_default(),
922        title_block,
923        carriers,
924    })
925}
926
927fn build_schematic_header(
928    build: &SchematicBuildContext<'_, '_>,
929    version: i64,
930    generator: String,
931    generator_version: String,
932    uuid: String,
933    paper: Paper,
934    title_block: Option<SchematicTitleBlock>,
935) -> Result<SchematicHeaderBuild, Error> {
936    let document_id = build
937        .plot
938        .document_id
939        .clone()
940        .or_else(|| (!uuid.is_empty()).then(|| uuid.clone()))
941        .unwrap_or_default();
942    let (sheet_width_nm, sheet_height_nm) = paper_dimensions(&paper)?;
943    let mut budget = PlotBudget::new();
944    budget.source_path = build.plot.source_path.clone().unwrap_or_default();
945    let header_operations = drawing_sheet_operations(
946        &paper,
947        title_block.as_ref(),
948        sheet_width_nm,
949        sheet_height_nm,
950        build.plot,
951    )?;
952    Ok(SchematicHeaderBuild {
953        header: SchematicSheetHeaderRecord {
954            uuid,
955            paper_size: paper.size,
956            paper_width_mm: paper.width,
957            paper_height_mm: paper.height,
958            paper_portrait: paper.portrait,
959            sheet_width_nm,
960            sheet_height_nm,
961            version,
962            generator,
963            generator_version,
964            title_block,
965            operations: header_operations,
966        },
967        document_id,
968        width_nm: sheet_width_nm,
969        height_nm: sheet_height_nm,
970        budget,
971    })
972}
973
974fn render_schematic_records(
975    build: &SchematicBuildContext<'_, '_>,
976    mut carriers: CarrierSpans,
977    header: SchematicSheetHeaderRecord,
978    budget: &mut PlotBudget,
979    mut profile: Option<&mut SchematicPlotBuildProfile>,
980) -> Result<Vec<SchematicPlotRecord>, Error> {
981    let mut records = vec![SchematicPlotRecord::SheetHeader(header)];
982    let connectivity_started = profile.is_some().then(Instant::now);
983    append_connectivity_records(build, &mut carriers, budget, &mut records)?;
984    if let Some(profile) = profile.as_deref_mut() {
985        profile.connectivity_ns = elapsed_ns(connectivity_started);
986    }
987    append_scoped_records(build, carriers, budget, &mut records, profile)?;
988    Ok(records)
989}
990
991fn append_connectivity_records(
992    build: &SchematicBuildContext<'_, '_>,
993    carriers: &mut CarrierSpans,
994    budget: &mut PlotBudget,
995    records: &mut Vec<SchematicPlotRecord>,
996) -> Result<(), Error> {
997    append_polyline_records(
998        build.source,
999        std::mem::take(&mut carriers.wires),
1000        ConnectivityPolylineStyle {
1001            kind: SchematicConnectivityRecordKind::Wire,
1002            default_width_mm: DEFAULT_WIRE_WIDTH_MM,
1003            default_color: WIRE_COLOR,
1004        },
1005        budget,
1006        records,
1007    )?;
1008    append_polyline_records(
1009        build.source,
1010        std::mem::take(&mut carriers.buses),
1011        ConnectivityPolylineStyle {
1012            kind: SchematicConnectivityRecordKind::Bus,
1013            default_width_mm: DEFAULT_BUS_WIDTH_MM,
1014            default_color: BUS_COLOR,
1015        },
1016        budget,
1017        records,
1018    )?;
1019    append_bus_entry_records(
1020        build.source,
1021        std::mem::take(&mut carriers.bus_entries),
1022        budget,
1023        records,
1024    )?;
1025    append_junction_records(
1026        build.source,
1027        std::mem::take(&mut carriers.junctions),
1028        budget,
1029        records,
1030    )?;
1031    append_no_connect_records(
1032        build.source,
1033        std::mem::take(&mut carriers.no_connects),
1034        build.drawing.map(|settings| settings.default_line_width_nm),
1035        budget,
1036        records,
1037    )
1038}
1039
1040fn append_scoped_records(
1041    build: &SchematicBuildContext<'_, '_>,
1042    mut carriers: CarrierSpans,
1043    budget: &mut PlotBudget,
1044    records: &mut Vec<SchematicPlotRecord>,
1045    mut profile: Option<&mut SchematicPlotBuildProfile>,
1046) -> Result<(), Error> {
1047    let annotation_spans = AnnotationSpans {
1048        labels: std::mem::take(&mut carriers.labels),
1049        global_labels: std::mem::take(&mut carriers.global_labels),
1050        hierarchical_labels: std::mem::take(&mut carriers.hierarchical_labels),
1051        netclass_flags: std::mem::take(&mut carriers.netclass_flags),
1052        texts: std::mem::take(&mut carriers.texts),
1053        text_boxes: std::mem::take(&mut carriers.text_boxes),
1054    };
1055    let graphic_spans = GraphicSpans {
1056        polylines: std::mem::take(&mut carriers.polylines),
1057        arcs: std::mem::take(&mut carriers.arcs),
1058        circles: std::mem::take(&mut carriers.circles),
1059        rectangles: std::mem::take(&mut carriers.rectangles),
1060        beziers: std::mem::take(&mut carriers.beziers),
1061        rule_areas: std::mem::take(&mut carriers.rule_areas),
1062        images: std::mem::take(&mut carriers.images),
1063        tables: std::mem::take(&mut carriers.tables),
1064    };
1065    let setup_started = profile.is_some().then(Instant::now);
1066    let session = if build.scope >= SchematicPlotScope::Annotations {
1067        build
1068            .text_resources
1069            .map(PlotterTextCacheSession::new)
1070            .transpose()?
1071    } else {
1072        None
1073    };
1074    let title_block = records.first().and_then(|record| match record {
1075        SchematicPlotRecord::SheetHeader(header) => header.title_block.as_ref(),
1076        _ => None,
1077    });
1078    let variables = if build.scope >= SchematicPlotScope::Annotations {
1079        Some(annotation_variables(build.plot, title_block)?)
1080    } else {
1081        None
1082    };
1083    if let Some(profile) = profile.as_deref_mut() {
1084        profile.text_resource_setup_ns = elapsed_ns(setup_started);
1085    }
1086    append_annotation_scope(
1087        build,
1088        annotation_spans,
1089        &graphic_spans,
1090        &carriers,
1091        variables.as_ref(),
1092        session.as_ref(),
1093        (budget, records),
1094        profile,
1095    )
1096}
1097
1098#[allow(
1099    clippy::too_many_arguments,
1100    reason = "one ordered render pass keeps every bounded family and its opt-in profile together"
1101)]
1102fn append_annotation_scope(
1103    build: &SchematicBuildContext<'_, '_>,
1104    annotation_spans: AnnotationSpans,
1105    graphic_spans: &GraphicSpans,
1106    carriers: &CarrierSpans,
1107    variables: Option<&BTreeMap<String, String>>,
1108    session: Option<&PlotterTextCacheSession<'_>>,
1109    output: (&mut PlotBudget, &mut Vec<SchematicPlotRecord>),
1110    mut profile: Option<&mut SchematicPlotBuildProfile>,
1111) -> Result<(), Error> {
1112    let (budget, records) = output;
1113    let annotations_started = profile.is_some().then(Instant::now);
1114    if let Some(drawing) = build.drawing {
1115        append_annotation_records(
1116            build.source,
1117            annotation_spans,
1118            drawing,
1119            variables.expect("annotation scope has variables"),
1120            session,
1121            (budget, records),
1122        )?;
1123    }
1124    if let Some(profile) = profile.as_deref_mut() {
1125        profile.annotations_ns = elapsed_ns(annotations_started);
1126    }
1127    if build.scope >= SchematicPlotScope::Graphics {
1128        let graphics_started = profile.is_some().then(Instant::now);
1129        append_graphic_records(build.source, graphic_spans, budget, records)?;
1130        append_rule_area_records(build.source, graphic_spans, budget, records)?;
1131        if let Some(profile) = profile.as_deref_mut() {
1132            profile.graphics_and_rule_areas_ns = elapsed_ns(graphics_started);
1133        }
1134        let images_started = profile.is_some().then(Instant::now);
1135        append_image_records(build.source, graphic_spans, budget, records)?;
1136        if let Some(profile) = profile.as_deref_mut() {
1137            profile.images_ns = elapsed_ns(images_started);
1138        }
1139        let tables_started = profile.is_some().then(Instant::now);
1140        append_table_records(
1141            build.source,
1142            graphic_spans,
1143            variables.expect("graphics scope has variables"),
1144            session,
1145            budget,
1146            records,
1147        )?;
1148        if let Some(profile) = profile.as_deref_mut() {
1149            profile.tables_ns = elapsed_ns(tables_started);
1150        }
1151    }
1152    if build.scope >= SchematicPlotScope::Symbols {
1153        let symbols_started = profile.is_some().then(Instant::now);
1154        append_symbol_records(
1155            build.source,
1156            carriers.lib_symbols.as_ref(),
1157            &carriers.symbols,
1158            build.plot,
1159            build.drawing.expect("symbol scope has drawing settings"),
1160            variables.expect("symbol scope has variables"),
1161            session,
1162            budget,
1163            records,
1164        )?;
1165        if let Some(profile) = profile.as_deref_mut() {
1166            profile.symbols_ns = elapsed_ns(symbols_started);
1167        }
1168    }
1169    if build.scope >= SchematicPlotScope::Sheets {
1170        let sheets_started = profile.is_some().then(Instant::now);
1171        append_sheet_records(
1172            build.source,
1173            &carriers.sheets,
1174            build.drawing.expect("sheet scope has drawing settings"),
1175            session,
1176            budget,
1177            records,
1178        )?;
1179        if let Some(profile) = profile {
1180            profile.sheets_ns = elapsed_ns(sheets_started);
1181        }
1182    }
1183    Ok(())
1184}
1185
1186#[derive(Clone, Debug, PartialEq)]
1187pub(crate) struct Paper {
1188    pub size: String,
1189    pub width: Option<f64>,
1190    pub height: Option<f64>,
1191    pub portrait: bool,
1192}
1193
1194impl Default for Paper {
1195    fn default() -> Self {
1196        Self {
1197            size: "A4".to_owned(),
1198            width: None,
1199            height: None,
1200            portrait: false,
1201        }
1202    }
1203}
1204
1205fn selected_spans(source: &str, scope: SchematicPlotScope) -> Result<Vec<FormSpan>, Error> {
1206    let mut heads = vec![
1207        "version",
1208        "generator",
1209        "generator_version",
1210        "uuid",
1211        "paper",
1212        "title_block",
1213        "wire",
1214        "bus",
1215        "bus_entry",
1216        "junction",
1217        "no_connect",
1218    ];
1219    if scope >= SchematicPlotScope::Annotations {
1220        heads.extend([
1221            "label",
1222            "global_label",
1223            "hierarchical_label",
1224            "netclass_flag",
1225            "text",
1226            "text_box",
1227        ]);
1228    }
1229    if scope >= SchematicPlotScope::Graphics {
1230        heads.extend([
1231            "polyline",
1232            "arc",
1233            "circle",
1234            "rectangle",
1235            "bezier",
1236            "rule_area",
1237            "image",
1238            "table",
1239        ]);
1240    }
1241    if scope >= SchematicPlotScope::Symbols {
1242        heads.extend(["lib_symbols", "symbol"]);
1243    }
1244    if scope >= SchematicPlotScope::Sheets {
1245        heads.push("sheet");
1246    }
1247    let mut paths = BTreeSet::from([vec!["kicad_sch".to_owned()]]);
1248    paths.extend(
1249        heads
1250            .into_iter()
1251            .map(|head| vec!["kicad_sch".to_owned(), head.to_owned()]),
1252    );
1253    scan_form_spans(
1254        source,
1255        &Selector {
1256            paths: Some(paths),
1257            min_depth: Some(0),
1258            max_depth: Some(1),
1259            ..Selector::default()
1260        },
1261    )
1262}
1263
1264fn parse_span(source: &str, span: &FormSpan) -> Result<Sexp, Error> {
1265    let text = span.text(source)?;
1266    parse(text)
1267}
1268
1269fn append_polyline_records(
1270    source: &str,
1271    spans: Vec<FormSpan>,
1272    style: ConnectivityPolylineStyle,
1273    budget: &mut PlotBudget,
1274    records: &mut Vec<SchematicPlotRecord>,
1275) -> Result<(), Error> {
1276    for (source_index, span) in spans.into_iter().enumerate() {
1277        let mark = budget.mark(records);
1278        let result = (|| -> Result<(), Error> {
1279            let form = parse_span(source, &span)?;
1280            let points = child(&form, "pts").map_or(Ok(Vec::new()), parse_points)?;
1281            if points.is_empty() {
1282                return Ok(());
1283            }
1284            let uuid = child_string(&form, "uuid").unwrap_or_default();
1285            let stroke = resolve_stroke(&form, style.default_width_mm, style.default_color)?;
1286            if style.kind == SchematicConnectivityRecordKind::Wire {
1287                budget.capture_source(
1288                    records.len(),
1289                    None,
1290                    owned::NativePlotSource::Wire(source_index),
1291                );
1292            }
1293            records.push(SchematicPlotRecord::Connectivity(
1294                SchematicConnectivityRecord {
1295                    uuid,
1296                    kind: style.kind,
1297                    junction_color_authored: false,
1298                    junction_color: None,
1299                    operations: vec![
1300                        PlotterOperation::PlotPoly(PlotterPoly {
1301                            points,
1302                            fill: PlotterFill::NoFill,
1303                            width_nm: stroke.width_nm,
1304                            layer: None,
1305                            stroke_color: Some(stroke.color),
1306                            fill_color: None,
1307                            line_style: Some(stroke.style),
1308                        })
1309                        .into(),
1310                    ],
1311                },
1312            ));
1313            Ok(())
1314        })();
1315        budget.settle(mark, records, result, (source, &span));
1316    }
1317    Ok(())
1318}
1319
1320fn append_bus_entry_records(
1321    source: &str,
1322    spans: Vec<FormSpan>,
1323    budget: &mut PlotBudget,
1324    records: &mut Vec<SchematicPlotRecord>,
1325) -> Result<(), Error> {
1326    for span in spans {
1327        let mark = budget.mark(records);
1328        let result = (|| -> Result<(), Error> {
1329            let form = parse_span(source, &span)?;
1330            let [x, y] = child(&form, "at").map_or(Ok([0, 0]), parse_point)?;
1331            let [dx, dy] = child(&form, "size")
1332                .map_or_else(|| Ok([mm_to_nm(2.54)?, mm_to_nm(2.54)?]), parse_point)?;
1333            let end_x = x.checked_add(dx).ok_or_else(limit_error)?;
1334            let end_y = y.checked_add(dy).ok_or_else(limit_error)?;
1335            ensure_javascript_safe_integer(end_x)?;
1336            ensure_javascript_safe_integer(end_y)?;
1337            let uuid = child_string(&form, "uuid").unwrap_or_default();
1338            let stroke = resolve_stroke(&form, DEFAULT_WIRE_WIDTH_MM, WIRE_COLOR)?;
1339            records.push(SchematicPlotRecord::Connectivity(
1340                SchematicConnectivityRecord {
1341                    uuid,
1342                    kind: SchematicConnectivityRecordKind::BusEntry,
1343                    junction_color_authored: false,
1344                    junction_color: None,
1345                    operations: vec![
1346                        PlotterOperation::PlotPoly(PlotterPoly {
1347                            points: vec![[x, y], [end_x, end_y]],
1348                            fill: PlotterFill::NoFill,
1349                            width_nm: stroke.width_nm,
1350                            layer: None,
1351                            stroke_color: Some(stroke.color),
1352                            fill_color: None,
1353                            line_style: Some(stroke.style),
1354                        })
1355                        .into(),
1356                    ],
1357                },
1358            ));
1359            Ok(())
1360        })();
1361        budget.settle(mark, records, result, (source, &span));
1362    }
1363    Ok(())
1364}
1365
1366fn append_junction_records(
1367    source: &str,
1368    spans: Vec<FormSpan>,
1369    budget: &mut PlotBudget,
1370    records: &mut Vec<SchematicPlotRecord>,
1371) -> Result<(), Error> {
1372    for span in spans {
1373        let mark = budget.mark(records);
1374        let result = (|| -> Result<(), Error> {
1375            let form = parse_span(source, &span)?;
1376            let [cx, cy] = child(&form, "at").map_or(Ok([0, 0]), parse_point)?;
1377            let diameter =
1378                child(&form, "diameter").map_or(Ok(DEFAULT_JUNCTION_DIAMETER_MM), |value| {
1379                    let value = number_at(value, 1)?;
1380                    Ok(if value > 0.0 {
1381                        value
1382                    } else {
1383                        DEFAULT_JUNCTION_DIAMETER_MM
1384                    })
1385                })?;
1386            let authored = child(&form, "color").is_some();
1387            let authored_color = child(&form, "color")
1388                .map(parse_color)
1389                .transpose()?
1390                .flatten();
1391            let color = authored_color
1392                .clone()
1393                .unwrap_or_else(|| JUNCTION_COLOR.to_owned());
1394            let uuid = child_string(&form, "uuid").unwrap_or_default();
1395            records.push(SchematicPlotRecord::Connectivity(
1396                SchematicConnectivityRecord {
1397                    uuid,
1398                    kind: SchematicConnectivityRecordKind::Junction,
1399                    junction_color_authored: authored,
1400                    junction_color: authored_color,
1401                    operations: vec![
1402                        PlotterOperation::Circle(PlotterCircle {
1403                            cx,
1404                            cy,
1405                            diameter_nm: mm_to_nm(diameter)?,
1406                            fill: PlotterFill::FilledShape,
1407                            width_nm: 0,
1408                            layer: None,
1409                            role: None,
1410                            layers: Vec::new(),
1411                            mask_margin_nm: None,
1412                            pad_size_x_nm: None,
1413                            pad_size_y_nm: None,
1414                            stroke_color: Some(color.clone()),
1415                            fill_color: Some(color),
1416                            line_style: None,
1417                        })
1418                        .into(),
1419                    ],
1420                },
1421            ));
1422            Ok(())
1423        })();
1424        budget.settle(mark, records, result, (source, &span));
1425    }
1426    Ok(())
1427}
1428
1429fn append_no_connect_records(
1430    source: &str,
1431    spans: Vec<FormSpan>,
1432    default_line_width_nm: Option<i64>,
1433    budget: &mut PlotBudget,
1434    records: &mut Vec<SchematicPlotRecord>,
1435) -> Result<(), Error> {
1436    let half = mm_to_nm(DEFAULT_NO_CONNECT_HALF_MM)?;
1437    let width_nm = match default_line_width_nm {
1438        Some(width) => width,
1439        None => mm_to_nm(6.0 * 0.0254)?.max(MIN_PLOT_PEN_WIDTH_NM),
1440    };
1441    for span in spans {
1442        let mark = budget.mark(records);
1443        let result = (|| -> Result<(), Error> {
1444            let form = parse_span(source, &span)?;
1445            let [cx, cy] = child(&form, "at").map_or(Ok([0, 0]), parse_point)?;
1446            let uuid = child_string(&form, "uuid").unwrap_or_default();
1447            let coords = [
1448                cx.checked_sub(half),
1449                cy.checked_sub(half),
1450                cx.checked_add(half),
1451                cy.checked_add(half),
1452            ];
1453            if coords.iter().any(Option::is_none) {
1454                return Err(limit_error());
1455            }
1456            let [x0, y0, x1, y1] = coords.map(Option::unwrap);
1457            for value in [x0, y0, x1, y1] {
1458                ensure_javascript_safe_integer(value)?;
1459            }
1460            let poly = |points| {
1461                SchematicPlotOperation::Plotter(PlotterOperation::PlotPoly(PlotterPoly {
1462                    points,
1463                    fill: PlotterFill::NoFill,
1464                    width_nm,
1465                    layer: None,
1466                    stroke_color: Some(NO_CONNECT_COLOR.to_owned()),
1467                    fill_color: None,
1468                    line_style: None,
1469                }))
1470            };
1471            records.push(SchematicPlotRecord::Connectivity(
1472                SchematicConnectivityRecord {
1473                    uuid,
1474                    kind: SchematicConnectivityRecordKind::NoConnect,
1475                    junction_color_authored: false,
1476                    junction_color: None,
1477                    operations: vec![
1478                        poly(vec![[x0, y0], [x1, y1]]),
1479                        poly(vec![[x0, y1], [x1, y0]]),
1480                    ],
1481                },
1482            ));
1483            Ok(())
1484        })();
1485        budget.settle(mark, records, result, (source, &span));
1486    }
1487    Ok(())
1488}
1489
1490#[derive(Clone)]
1491struct Stroke {
1492    width_nm: i64,
1493    style: PlotterLineStyle,
1494    color: String,
1495}
1496
1497fn resolve_stroke(
1498    form: &Sexp,
1499    default_width_mm: f64,
1500    default_color: &str,
1501) -> Result<Stroke, Error> {
1502    let stroke = child(form, "stroke");
1503    let raw_width = stroke
1504        .and_then(|value| child(value, "width"))
1505        .map_or(Ok(0.0), |value| number_at(value, 1))?;
1506    let width_nm = if raw_width < 0.0 {
1507        0
1508    } else if raw_width == 0.0 {
1509        mm_to_nm(default_width_mm)?.max(MIN_PLOT_PEN_WIDTH_NM)
1510    } else {
1511        mm_to_nm(raw_width)?.max(MIN_PLOT_PEN_WIDTH_NM)
1512    };
1513    let style = match stroke
1514        .and_then(|value| child_string(value, "type"))
1515        .as_deref()
1516        .unwrap_or("default")
1517    {
1518        "solid" => PlotterLineStyle::Solid,
1519        "dash" => PlotterLineStyle::Dash,
1520        "dot" => PlotterLineStyle::Dot,
1521        "dash_dot" => PlotterLineStyle::DashDot,
1522        "dash_dot_dot" => PlotterLineStyle::DashDotDot,
1523        "default" => PlotterLineStyle::Default,
1524        _ => return Err(model_error("Unsupported schematic stroke type")),
1525    };
1526    let color = stroke
1527        .and_then(|value| child(value, "color"))
1528        .map(parse_color)
1529        .transpose()?
1530        .flatten()
1531        .unwrap_or_else(|| default_color.to_owned());
1532    Ok(Stroke {
1533        width_nm,
1534        style,
1535        color,
1536    })
1537}
1538
1539fn parse_paper(source: &str, span: &FormSpan) -> Result<Paper, Error> {
1540    let form = parse_span(source, span)?;
1541    let values = list(&form).ok_or_else(|| model_error("Malformed paper form"))?;
1542    let size = values.get(1).and_then(text).unwrap_or("A4").to_owned();
1543    let width = positional_number(values.get(2))?;
1544    let height = positional_number(values.get(3))?;
1545    Ok(Paper {
1546        size,
1547        width,
1548        height,
1549        portrait: values
1550            .iter()
1551            .skip(2)
1552            .any(|value| text(value) == Some("portrait")),
1553    })
1554}
1555
1556fn parse_title_block(source: &str, span: &FormSpan) -> Result<SchematicTitleBlock, Error> {
1557    let form = parse_span(source, span)?;
1558    let mut result = SchematicTitleBlock::default();
1559    let (mut saw_title, mut saw_date, mut saw_revision, mut saw_company) =
1560        (false, false, false, false);
1561    for item in list(&form).into_iter().flatten().skip(1) {
1562        match list(item).and_then(|values| values.first()).and_then(text) {
1563            Some("title") if !saw_title => {
1564                saw_title = true;
1565                result.title = value_at(item, 1).unwrap_or_default();
1566            }
1567            Some("date") if !saw_date => {
1568                saw_date = true;
1569                result.date = value_at(item, 1).unwrap_or_default();
1570            }
1571            Some("rev") if !saw_revision => {
1572                saw_revision = true;
1573                result.revision = value_at(item, 1).unwrap_or_default();
1574            }
1575            Some("company") if !saw_company => {
1576                saw_company = true;
1577                result.company = value_at(item, 1).unwrap_or_default();
1578            }
1579            Some("comment") => {
1580                if let (Some(number), Some(value)) = (integer_at(item, 1), scalar_at(item, 2)) {
1581                    result.comments.insert(number, value);
1582                }
1583            }
1584            _ => {}
1585        }
1586    }
1587    Ok(result)
1588}
1589
1590fn paper_dimensions(paper: &Paper) -> Result<(i64, i64), Error> {
1591    let standard = |w: f64, h: f64| {
1592        (
1593            ((w * 1000.0 / 25.4 + 0.5) as i64 as f64) * 0.0254,
1594            ((h * 1000.0 / 25.4 + 0.5) as i64 as f64) * 0.0254,
1595        )
1596    };
1597    let (mut width, mut height) = if paper.size == "User" {
1598        match (paper.width, paper.height) {
1599            (Some(w), Some(h)) => (w, h),
1600            _ => standard(297.0, 210.0),
1601        }
1602    } else {
1603        match paper.size.as_str() {
1604            "A0" => standard(1189.0, 841.0),
1605            "A1" => standard(841.0, 594.0),
1606            "A2" => standard(594.0, 420.0),
1607            "A3" => standard(420.0, 297.0),
1608            "A4" => standard(297.0, 210.0),
1609            "A5" => standard(210.0, 148.0),
1610            "A" | "USLetter" => (279.4, 215.9),
1611            "B" => (431.8, 279.4),
1612            "C" => (558.8, 431.8),
1613            "D" => (863.6, 558.8),
1614            "E" => (1117.6, 863.6),
1615            "USLegal" => (355.6, 215.9),
1616            "USLedger" => (431.8, 279.4),
1617            _ => standard(297.0, 210.0),
1618        }
1619    };
1620    if paper.portrait {
1621        std::mem::swap(&mut width, &mut height);
1622    }
1623    if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 {
1624        return Err(model_error("Paper dimensions must be finite and positive"));
1625    }
1626    Ok((mm_to_nm(width)?, mm_to_nm(height)?))
1627}
1628
1629fn validate_context(context: &SchematicPlotContext) -> Result<(), Error> {
1630    // KiCad page numbers are positive labels, not dense indexes. A project can
1631    // contain six concrete sheets numbered 1, 2, 5, 6, 7, and 8.
1632    if context.sheet_index == 0 || context.sheet_count == 0 {
1633        return Err(model_error("Invalid schematic page context"));
1634    }
1635    Ok(())
1636}
1637
1638fn validate_drawing_settings(settings: SchematicDrawingSettings) -> Result<(), Error> {
1639    if !settings.text_offset_ratio.is_finite() || settings.text_offset_ratio < 0.0 {
1640        return Err(model_error(
1641            "Schematic text_offset_ratio must be finite and non-negative",
1642        ));
1643    }
1644    if settings.default_line_width_nm < MIN_PLOT_PEN_WIDTH_NM {
1645        return Err(model_error(
1646            "Schematic default_line_width_nm must be at least 84700 nm",
1647        ));
1648    }
1649    ensure_javascript_safe_integer(settings.default_line_width_nm).map(|_| ())
1650}
1651
1652fn form_string(source: &str, span: &FormSpan) -> Result<String, Error> {
1653    Ok(value_at(&parse_span(source, span)?, 1).unwrap_or_default())
1654}
1655fn form_i64(source: &str, span: &FormSpan) -> Result<i64, Error> {
1656    integer_at(&parse_span(source, span)?, 1)
1657        .ok_or_else(|| model_error("Expected schematic integer"))
1658}
1659fn parse_points(form: &Sexp) -> Result<Vec<[i64; 2]>, Error> {
1660    list(form)
1661        .into_iter()
1662        .flatten()
1663        .skip(1)
1664        .filter(|value| {
1665            list(value).and_then(|values| values.first()).and_then(text) == Some("xy")
1666                && list(value).is_some_and(|values| values.len() >= 3)
1667        })
1668        .map(parse_point)
1669        .collect()
1670}
1671fn parse_point(form: &Sexp) -> Result<[i64; 2], Error> {
1672    Ok([
1673        mm_to_nm(number_at(form, 1)?)?,
1674        mm_to_nm(number_at(form, 2)?)?,
1675    ])
1676}
1677fn child<'a>(form: &'a Sexp, head: &str) -> Option<&'a Sexp> {
1678    list(form)?
1679        .iter()
1680        .find(|value| list(value).and_then(|values| values.first()).and_then(text) == Some(head))
1681}
1682fn child_string(form: &Sexp, head: &str) -> Option<String> {
1683    child(form, head).and_then(|value| scalar_at(value, 1))
1684}
1685fn list(form: &Sexp) -> Option<&[Sexp]> {
1686    if let Sexp::List(values) = form {
1687        Some(values)
1688    } else {
1689        None
1690    }
1691}
1692fn text(value: &Sexp) -> Option<&str> {
1693    match value {
1694        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
1695        _ => None,
1696    }
1697}
1698fn scalar_at(form: &Sexp, index: usize) -> Option<String> {
1699    list(form)?.get(index).map(|value| match value {
1700        Sexp::Atom(value) | Sexp::Quoted(value) => value.clone(),
1701        Sexp::Integer(value) => value.to_string(),
1702        Sexp::Float(value) => value.to_string(),
1703        Sexp::List(_) => String::new(),
1704    })
1705}
1706fn value_at(form: &Sexp, index: usize) -> Option<String> {
1707    scalar_at(form, index)
1708}
1709fn integer_at(form: &Sexp, index: usize) -> Option<i64> {
1710    match list(form)?.get(index)? {
1711        Sexp::Integer(value) => Some(*value),
1712        Sexp::Atom(value) | Sexp::Quoted(value) => value.parse().ok(),
1713        Sexp::Float(value) if value.fract() == 0.0 => Some(*value as i64),
1714        _ => None,
1715    }
1716}
1717fn number_at(form: &Sexp, index: usize) -> Result<f64, Error> {
1718    let value = match list(form).and_then(|values| values.get(index)) {
1719        Some(Sexp::Integer(value)) => *value as f64,
1720        Some(Sexp::Float(value)) => *value,
1721        Some(Sexp::Atom(value)) | Some(Sexp::Quoted(value)) => value
1722            .parse()
1723            .map_err(|_| model_error("Expected finite number"))?,
1724        _ => return Err(model_error("Expected finite number")),
1725    };
1726    if value.is_finite() {
1727        Ok(value)
1728    } else {
1729        Err(model_error("Expected finite number"))
1730    }
1731}
1732
1733fn positional_number(value: Option<&Sexp>) -> Result<Option<f64>, Error> {
1734    let value = match value {
1735        Some(Sexp::Integer(value)) => Some(*value as f64),
1736        Some(Sexp::Float(value)) => Some(*value),
1737        _ => None,
1738    };
1739    if value.is_some_and(|value| !value.is_finite()) {
1740        Err(model_error("Paper dimensions must be finite"))
1741    } else {
1742        Ok(value)
1743    }
1744}
1745
1746pub(crate) fn color_hex(red: i64, green: i64, blue: i64, alpha: f64) -> Option<String> {
1747    if alpha <= 0.0 {
1748        return None;
1749    }
1750    let component = |value: i64| value.clamp(0, 255);
1751    let alpha = if alpha <= 1.0 {
1752        (alpha * 255.0).round_ties_even() as i64
1753    } else {
1754        alpha.round_ties_even() as i64
1755    }
1756    .clamp(0, 255);
1757    Some(format!(
1758        "#{:02X}{:02X}{:02X}{:02X}",
1759        component(red),
1760        component(green),
1761        component(blue),
1762        alpha
1763    ))
1764}
1765fn parse_color(form: &Sexp) -> Result<Option<String>, Error> {
1766    Ok(color_hex(
1767        integer_at(form, 1).unwrap_or(0),
1768        integer_at(form, 2).unwrap_or(0),
1769        integer_at(form, 3).unwrap_or(0),
1770        number_at(form, 4)?,
1771    ))
1772}
1773pub(crate) fn model_error(message: &'static str) -> Error {
1774    Error::at(
1775        ErrorPhase::Build,
1776        ErrorKind::InvalidBuildValue,
1777        message,
1778        Position::START,
1779    )
1780}
1781pub(crate) fn limit_error() -> Error {
1782    Error::at(
1783        ErrorPhase::Build,
1784        ErrorKind::ResourceLimit,
1785        "schematic plot exceeds configured limits",
1786        Position::START,
1787    )
1788}