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

kicad_monkey_contracts/
schematic_plot_contract.rs

1//! Semantic validation for the strict schematic-foundation plot contract.
2
3use crate::generated::schematic_plot_document::{
4    ArcThreePointOperation, BezierCurveOperation, CircleOperation, PlotImageOperation,
5    PlotPolyOperation, PlotterFill, PlotterOperation, RectOperation,
6    SchematicGlobalLabelPlotRecord, SchematicGraphicBezierPlotRecord,
7    SchematicHierarchicalLabelPlotRecord, SchematicImageFormat, SchematicImagePlotRecord,
8    SchematicJunctionPlotRecord, SchematicLabelShape, SchematicNetclassFlagPlotRecord,
9    SchematicNetclassFlagShape, SchematicNoConnectPlotRecord, SchematicPlotDocumentA0,
10    SchematicPlotRecord, SchematicRuleAreaPlotRecord, SchematicRuleAreaShape,
11    SchematicSheetHeaderPlotRecord, SchematicSheetOperation, SchematicSheetPlotRecord,
12    SchematicSheetStartBlockOperation, SchematicSymbolInstancePlotRecord, SchematicSymbolOperation,
13    SchematicSymbolOverplotPlotRecord, SchematicTablePlotRecord, SchematicTextBoxPlotRecord,
14    SchematicTextPlotRecord, TextOperation, ThickSegmentOperation,
15};
16use crate::{ValidationError, validation_error};
17
18const BACKGROUND_COLOR: &str = "#F5F4EFFF";
19const DRAWING_SHEET_COLOR: &str = "#840000FF";
20const DEFAULT_JUNCTION_COLOR: &str = "#009600FF";
21const NO_CONNECT_COLOR: &str = "#000084FF";
22const GLOBAL_LABEL_COLOR: &str = "#840000FF";
23const HIERARCHICAL_LABEL_COLOR: &str = "#725600FF";
24const NETCLASS_COLOR: &str = "#484848FF";
25const SHEET_LABEL_COLOR: &str = "#006464FF";
26const DIMMED_SHEET_LABEL_COLOR: &str = "#949391FF";
27const DNP_MARKER_COLOR: &str = "#DC090DD9";
28const DNP_MARKER_WIDTH_NM: i64 = 457_200;
29
30/// Enforce document identity, record order, operation shape, and local indexes.
31// The exhaustive producer phase dispatcher is intentionally kept in one place
32// so newly generated record arms cannot bypass the common identity checks.
33#[allow(
34    clippy::too_many_lines,
35    reason = "the exhaustive record-phase dispatcher is a deliberate compile-time ratchet"
36)]
37pub fn validate_schematic_plot_document(
38    document: &SchematicPlotDocumentA0,
39) -> Result<(), ValidationError> {
40    if document.schema != "kicad.plotter_ir.a0"
41        || document.source_kind != "SCH"
42        || document.coordinate_space.unit != "nm"
43        || document.coordinate_space.y_axis != "down"
44    {
45        return Err(error(
46            "unsupported_contract",
47            "$",
48            "schematic plot document identity and coordinate space must match a0",
49        ));
50    }
51    if !matches!(
52        document.records.first(),
53        Some(SchematicPlotRecord::SheetHeaderPlotRecord(_))
54    ) {
55        return Err(error(
56            "missing_sheet_header",
57            "$.records[0]",
58            "the first schematic record must be the unique sheet header",
59        ));
60    }
61
62    let mut previous_phase = 0_u8;
63    let mut total_operations = 0usize;
64    for (record_index, record) in document.records.iter().enumerate() {
65        let phase = record_phase(record);
66        if phase < previous_phase || (phase == 0 && record_index != 0) {
67            return Err(error(
68                "invalid_schematic_record_order",
69                format!("$.records[{record_index}]"),
70                "schematic foundation records must remain in canonical family order",
71            ));
72        }
73        previous_phase = phase;
74        let path = format!("$.records[{record_index}]");
75        if let SchematicPlotRecord::SymbolInstancePlotRecord(value) = record {
76            validate_symbol_instance(value, &path)?;
77            total_operations = total_operations.saturating_add(value.operations.len());
78            continue;
79        }
80        if let SchematicPlotRecord::SymbolOverplotPlotRecord(value) = record {
81            validate_symbol_overplot(value, &path)?;
82            total_operations = total_operations.saturating_add(value.operations.len());
83            continue;
84        }
85        if let SchematicPlotRecord::SheetPlotRecord(value) = record {
86            validate_sheet(value, &path)?;
87            total_operations = total_operations.saturating_add(value.operations.len());
88            continue;
89        }
90        let (uuid, kind, expected_kind, object_id, declared, operations) = record_fields(record);
91        let identity_matches = match record {
92            SchematicPlotRecord::LabelPlotRecord(value) => value.object_id == value.text,
93            SchematicPlotRecord::GlobalLabelPlotRecord(value) => value.object_id == value.text,
94            SchematicPlotRecord::HierarchicalLabelPlotRecord(value) => {
95                value.object_id == value.text
96            }
97            SchematicPlotRecord::NetclassFlagPlotRecord(_) => true,
98            _ => uuid == object_id,
99        };
100        if kind != expected_kind || !identity_matches {
101            return Err(error(
102                "invalid_schematic_record_identity",
103                &path,
104                "foundation record object_id must equal uuid",
105            ));
106        }
107        if declared as usize != operations.len() {
108            return Err(error(
109                "operation_count_mismatch",
110                format!("{path}.operation_count"),
111                "operation_count must equal the operation array length",
112            ));
113        }
114        for (operation_index, operation) in operations.iter().enumerate() {
115            validate_operation_header(operation, operation_index, &path)?;
116        }
117        match record {
118            SchematicPlotRecord::SheetHeaderPlotRecord(value) => {
119                validate_sheet_header(document, value, &path)?;
120            }
121            SchematicPlotRecord::WirePlotRecord(value) => {
122                validate_polyline(&value.operations, false, &path)?;
123            }
124            SchematicPlotRecord::BusPlotRecord(value) => {
125                validate_polyline(&value.operations, false, &path)?;
126            }
127            SchematicPlotRecord::BusEntryPlotRecord(value) => {
128                validate_polyline(&value.operations, true, &path)?;
129            }
130            SchematicPlotRecord::JunctionPlotRecord(value) => {
131                validate_junction(value, &path)?;
132            }
133            SchematicPlotRecord::NoConnectPlotRecord(value) => {
134                validate_no_connect(value, &path)?;
135            }
136            SchematicPlotRecord::LabelPlotRecord(value) => {
137                validate_label(&value.operations, &value.text, None, false, &path)?;
138            }
139            SchematicPlotRecord::GlobalLabelPlotRecord(value) => {
140                validate_global_label(value, &path)?;
141            }
142            SchematicPlotRecord::HierarchicalLabelPlotRecord(value) => {
143                validate_hierarchical_label(value, &path)?;
144            }
145            SchematicPlotRecord::NetclassFlagPlotRecord(value) => {
146                validate_netclass_flag(value, &path)?;
147            }
148            SchematicPlotRecord::TextPlotRecord(value) => {
149                validate_schematic_text(value, &path)?;
150            }
151            SchematicPlotRecord::TextBoxPlotRecord(value) => {
152                validate_text_box(value, &path)?;
153            }
154            SchematicPlotRecord::GraphicPolylinePlotRecord(value) => {
155                validate_graphic_record(&value.operations, GraphicKind::Polyline, false, &path)?;
156            }
157            SchematicPlotRecord::GraphicArcPlotRecord(value) => {
158                validate_graphic_record(&value.operations, GraphicKind::Arc, false, &path)?;
159            }
160            SchematicPlotRecord::GraphicCirclePlotRecord(value) => {
161                validate_graphic_record(&value.operations, GraphicKind::Circle, false, &path)?;
162            }
163            SchematicPlotRecord::GraphicRectanglePlotRecord(value) => {
164                validate_graphic_record(&value.operations, GraphicKind::Rectangle, false, &path)?;
165            }
166            SchematicPlotRecord::GraphicBezierPlotRecord(value) => {
167                validate_bezier_record(value, &path)?;
168            }
169            SchematicPlotRecord::RuleAreaPlotRecord(value) => {
170                validate_rule_area(value, &path)?;
171            }
172            SchematicPlotRecord::ImagePlotRecord(value) => {
173                validate_schematic_image(value, &path)?;
174            }
175            SchematicPlotRecord::TablePlotRecord(value) => {
176                validate_table(value, &path)?;
177            }
178            SchematicPlotRecord::SymbolInstancePlotRecord(_)
179            | SchematicPlotRecord::SymbolOverplotPlotRecord(_)
180            | SchematicPlotRecord::SheetPlotRecord(_) => unreachable!(),
181        }
182        total_operations = total_operations.saturating_add(operations.len());
183    }
184    if document.total_operations as usize != total_operations {
185        return Err(error(
186            "operation_count_mismatch",
187            "$.total_operations",
188            "total_operations must equal all record operation counts",
189        ));
190    }
191    Ok(())
192}
193
194fn record_phase(record: &SchematicPlotRecord) -> u8 {
195    match record {
196        SchematicPlotRecord::SheetHeaderPlotRecord(_) => 0,
197        SchematicPlotRecord::WirePlotRecord(_) => 1,
198        SchematicPlotRecord::BusPlotRecord(_) => 2,
199        SchematicPlotRecord::BusEntryPlotRecord(_) => 3,
200        SchematicPlotRecord::JunctionPlotRecord(_) => 4,
201        SchematicPlotRecord::NoConnectPlotRecord(_) => 5,
202        SchematicPlotRecord::LabelPlotRecord(_) => 6,
203        SchematicPlotRecord::GlobalLabelPlotRecord(_) => 7,
204        SchematicPlotRecord::HierarchicalLabelPlotRecord(_) => 8,
205        SchematicPlotRecord::NetclassFlagPlotRecord(_) => 9,
206        SchematicPlotRecord::TextPlotRecord(_) => 10,
207        SchematicPlotRecord::TextBoxPlotRecord(_) => 11,
208        SchematicPlotRecord::GraphicPolylinePlotRecord(_) => 12,
209        SchematicPlotRecord::GraphicArcPlotRecord(_) => 13,
210        SchematicPlotRecord::GraphicCirclePlotRecord(_) => 14,
211        SchematicPlotRecord::GraphicRectanglePlotRecord(_) => 15,
212        SchematicPlotRecord::GraphicBezierPlotRecord(_) => 16,
213        SchematicPlotRecord::RuleAreaPlotRecord(_) => 17,
214        SchematicPlotRecord::ImagePlotRecord(_) => 18,
215        SchematicPlotRecord::TablePlotRecord(_) => 19,
216        SchematicPlotRecord::SymbolInstancePlotRecord(_) => 20,
217        SchematicPlotRecord::SymbolOverplotPlotRecord(_) => 21,
218        SchematicPlotRecord::SheetPlotRecord(_) => 22,
219    }
220}
221
222// Keeping the generated union projection exhaustive makes missing record arms
223// a compile error; splitting it would weaken that ratchet without simplifying it.
224#[allow(
225    clippy::too_many_lines,
226    reason = "the generated record-union projection must remain visibly exhaustive"
227)]
228fn record_fields(
229    record: &SchematicPlotRecord,
230) -> (&str, &str, &'static str, &str, u32, &[PlotterOperation]) {
231    match record {
232        SchematicPlotRecord::SheetHeaderPlotRecord(value) => (
233            &value.uuid,
234            &value.kind,
235            "sheet_header",
236            &value.object_id,
237            value.operation_count,
238            &value.operations,
239        ),
240        SchematicPlotRecord::WirePlotRecord(value) => (
241            &value.uuid,
242            &value.kind,
243            "wire",
244            &value.object_id,
245            value.operation_count,
246            &value.operations,
247        ),
248        SchematicPlotRecord::BusPlotRecord(value) => (
249            &value.uuid,
250            &value.kind,
251            "bus",
252            &value.object_id,
253            value.operation_count,
254            &value.operations,
255        ),
256        SchematicPlotRecord::BusEntryPlotRecord(value) => (
257            &value.uuid,
258            &value.kind,
259            "bus_entry",
260            &value.object_id,
261            value.operation_count,
262            &value.operations,
263        ),
264        SchematicPlotRecord::JunctionPlotRecord(value) => (
265            &value.uuid,
266            &value.kind,
267            "junction",
268            &value.object_id,
269            value.operation_count,
270            &value.operations,
271        ),
272        SchematicPlotRecord::NoConnectPlotRecord(value) => (
273            &value.uuid,
274            &value.kind,
275            "no_connect",
276            &value.object_id,
277            value.operation_count,
278            &value.operations,
279        ),
280        SchematicPlotRecord::LabelPlotRecord(value) => (
281            &value.uuid,
282            &value.kind,
283            "label",
284            &value.object_id,
285            value.operation_count,
286            &value.operations,
287        ),
288        SchematicPlotRecord::GlobalLabelPlotRecord(value) => (
289            &value.uuid,
290            &value.kind,
291            "global_label",
292            &value.object_id,
293            value.operation_count,
294            &value.operations,
295        ),
296        SchematicPlotRecord::HierarchicalLabelPlotRecord(value) => (
297            &value.uuid,
298            &value.kind,
299            "hierarchical_label",
300            &value.object_id,
301            value.operation_count,
302            &value.operations,
303        ),
304        SchematicPlotRecord::NetclassFlagPlotRecord(value) => (
305            &value.uuid,
306            &value.kind,
307            "netclass_flag",
308            &value.object_id,
309            value.operation_count,
310            &value.operations,
311        ),
312        SchematicPlotRecord::TextPlotRecord(value) => (
313            &value.uuid,
314            &value.kind,
315            "text",
316            &value.object_id,
317            value.operation_count,
318            &value.operations,
319        ),
320        SchematicPlotRecord::TextBoxPlotRecord(value) => (
321            &value.uuid,
322            &value.kind,
323            "text_box",
324            &value.object_id,
325            value.operation_count,
326            &value.operations,
327        ),
328        SchematicPlotRecord::GraphicPolylinePlotRecord(value) => (
329            &value.uuid,
330            &value.kind,
331            "graphic_polyline",
332            &value.object_id,
333            value.operation_count,
334            &value.operations,
335        ),
336        SchematicPlotRecord::GraphicArcPlotRecord(value) => (
337            &value.uuid,
338            &value.kind,
339            "graphic_arc",
340            &value.object_id,
341            value.operation_count,
342            &value.operations,
343        ),
344        SchematicPlotRecord::GraphicCirclePlotRecord(value) => (
345            &value.uuid,
346            &value.kind,
347            "graphic_circle",
348            &value.object_id,
349            value.operation_count,
350            &value.operations,
351        ),
352        SchematicPlotRecord::GraphicRectanglePlotRecord(value) => (
353            &value.uuid,
354            &value.kind,
355            "graphic_rectangle",
356            &value.object_id,
357            value.operation_count,
358            &value.operations,
359        ),
360        SchematicPlotRecord::GraphicBezierPlotRecord(value) => (
361            &value.uuid,
362            &value.kind,
363            "graphic_bezier",
364            &value.object_id,
365            value.operation_count,
366            &value.operations,
367        ),
368        SchematicPlotRecord::RuleAreaPlotRecord(value) => (
369            &value.uuid,
370            &value.kind,
371            "rule_area",
372            &value.object_id,
373            value.operation_count,
374            &value.operations,
375        ),
376        SchematicPlotRecord::ImagePlotRecord(value) => (
377            &value.uuid,
378            &value.kind,
379            "image",
380            &value.object_id,
381            value.operation_count,
382            &value.operations,
383        ),
384        SchematicPlotRecord::TablePlotRecord(value) => (
385            &value.uuid,
386            &value.kind,
387            "table",
388            &value.object_id,
389            value.operation_count,
390            &value.operations,
391        ),
392        SchematicPlotRecord::SymbolInstancePlotRecord(_)
393        | SchematicPlotRecord::SymbolOverplotPlotRecord(_)
394        | SchematicPlotRecord::SheetPlotRecord(_) => {
395            unreachable!("symbol and sheet records have distinct operation unions")
396        }
397    }
398}
399
400fn validate_operation_header(
401    operation: &PlotterOperation,
402    expected_index: usize,
403    record_path: &str,
404) -> Result<(), ValidationError> {
405    let (index, kind, expected_kind) = operation_header(operation);
406    let path = format!("{record_path}.operations[{expected_index}]");
407    if kind != expected_kind {
408        return Err(error(
409            "invalid_schematic_operation",
410            format!("{path}.kind"),
411            "operation kind must match its structural variant",
412        ));
413    }
414    if index as usize != expected_index {
415        return Err(error(
416            "operation_index_mismatch",
417            format!("{path}.index"),
418            "operation index must equal its record-local position",
419        ));
420    }
421    Ok(())
422}
423
424fn operation_header(operation: &PlotterOperation) -> (u32, &str, &'static str) {
425    match operation {
426        PlotterOperation::ThickSegmentOperation(value) => {
427            (value.index, &value.kind, "ThickSegment")
428        }
429        PlotterOperation::ArcThreePointOperation(value) => {
430            (value.index, &value.kind, "ArcThreePoint")
431        }
432        PlotterOperation::CircleOperation(value) => (value.index, &value.kind, "Circle"),
433        PlotterOperation::RectOperation(value) => (value.index, &value.kind, "Rect"),
434        PlotterOperation::PlotPolyOperation(value) => (value.index, &value.kind, "PlotPoly"),
435        PlotterOperation::BezierCurveOperation(value) => (value.index, &value.kind, "BezierCurve"),
436        PlotterOperation::TextOperation(value) => (value.index, &value.kind, "Text"),
437        PlotterOperation::PlotImageOperation(value) => (value.index, &value.kind, "PlotImage"),
438        PlotterOperation::FlashPadCircleOperation(value) => {
439            (value.index, &value.kind, "FlashPadCircle")
440        }
441        PlotterOperation::FlashPadOvalOperation(value) => {
442            (value.index, &value.kind, "FlashPadOval")
443        }
444        PlotterOperation::FlashPadRectOperation(value) => {
445            (value.index, &value.kind, "FlashPadRect")
446        }
447        PlotterOperation::FlashPadRoundRectOperation(value) => {
448            (value.index, &value.kind, "FlashPadRoundRect")
449        }
450        PlotterOperation::FlashPadCustomOperation(value) => {
451            (value.index, &value.kind, "FlashPadCustom")
452        }
453        PlotterOperation::FlashPadTrapezOperation(value) => {
454            (value.index, &value.kind, "FlashPadTrapez")
455        }
456    }
457}
458
459fn validate_symbol_instance(
460    record: &SchematicSymbolInstancePlotRecord,
461    path: &str,
462) -> Result<(), ValidationError> {
463    if record.kind != "symbol_instance"
464        || record.object_id
465            != if record.lib_id.is_empty() {
466                record.uuid.as_str()
467            } else {
468                record.lib_id.as_str()
469            }
470        || !record.at_angle_deg.is_finite()
471        || !matches!(record.mirror.as_deref(), None | Some("x") | Some("y"))
472    {
473        return Err(error(
474            "invalid_symbol_instance",
475            path,
476            "placed-symbol identity, angle, and mirror must be canonical",
477        ));
478    }
479    validate_symbol_operations(
480        &record.operations,
481        &record.uuid,
482        record.operation_count,
483        path,
484    )
485}
486
487fn validate_symbol_overplot(
488    record: &SchematicSymbolOverplotPlotRecord,
489    path: &str,
490) -> Result<(), ValidationError> {
491    let expected_uuid = format!("{}:overplot", record.source_symbol_uuid);
492    let expected_object = if record.lib_id.is_empty() {
493        &record.source_symbol_uuid
494    } else {
495        &record.lib_id
496    };
497    if record.kind != "symbol_overplot"
498        || record.uuid != expected_uuid
499        || record.object_id != *expected_object
500    {
501        return Err(error(
502            "invalid_symbol_overplot",
503            path,
504            "symbol overplot identity must remain linked to its source symbol",
505        ));
506    }
507    validate_symbol_operations(
508        &record.operations,
509        &record.source_symbol_uuid,
510        record.operation_count,
511        path,
512    )
513}
514
515// Pin-block state, the closed operation vocabulary, and shared drawing checks
516// are deliberately validated in one linear state machine.
517#[allow(
518    clippy::too_many_lines,
519    reason = "one linear state machine owns the complete pin-block validation invariant"
520)]
521fn validate_symbol_operations(
522    operations: &[SchematicSymbolOperation],
523    parent_uuid: &str,
524    declared: u32,
525    path: &str,
526) -> Result<(), ValidationError> {
527    if declared as usize != operations.len() {
528        return Err(error(
529            "operation_count_mismatch",
530            format!("{path}.operation_count"),
531            "operation_count must equal the operation array length",
532        ));
533    }
534    let mut block_start = None;
535    for (expected_index, operation) in operations.iter().enumerate() {
536        let operation_path = format!("{path}.operations[{expected_index}]");
537        let (index, kind, expected_kind) = symbol_operation_header(operation);
538        if index as usize != expected_index || kind != expected_kind {
539            return Err(error(
540                "invalid_schematic_operation",
541                &operation_path,
542                "symbol operation kind and local index must match its structural variant",
543            ));
544        }
545        match operation {
546            SchematicSymbolOperation::SchematicSymbolStartBlockOperation(value) => {
547                if block_start.is_some()
548                    || value.label.is_empty()
549                    || value.label != value.data_uuid
550                    || value.data_ref != "symbol_pin"
551                    || value.object_id.is_empty()
552                {
553                    return Err(error(
554                        "invalid_symbol_pin_block",
555                        &operation_path,
556                        "pin blocks must be nonnested and retain exact ownership",
557                    ));
558                }
559                let allowed = [
560                    "primitive",
561                    "object-type",
562                    "pin",
563                    "symbol-uuid",
564                    "designator",
565                    "lib-pin-uuid",
566                ];
567                if value
568                    .extra_attrs
569                    .keys()
570                    .any(|key| !allowed.contains(&key.as_str()))
571                    || value.extra_attrs.values().any(String::is_empty)
572                    || value.extra_attrs.get("primitive").map(String::as_str) != Some("pin")
573                    || value.extra_attrs.get("object-type").map(String::as_str) != Some("pin")
574                    || value.extra_attrs.get("symbol-uuid").map(String::as_str) != Some(parent_uuid)
575                {
576                    return Err(error(
577                        "invalid_symbol_pin_attrs",
578                        format!("{operation_path}.extra_attrs"),
579                        "pin block metadata must use the closed symbol-pin vocabulary",
580                    ));
581                }
582                block_start = Some(expected_index);
583            }
584            SchematicSymbolOperation::SchematicSymbolEndBlockOperation(_) => {
585                let Some(start) = block_start else {
586                    return Err(error(
587                        "invalid_symbol_pin_block",
588                        &operation_path,
589                        "pin block end must follow a matching start",
590                    ));
591                };
592                if expected_index == start + 1 {
593                    return Err(error(
594                        "invalid_symbol_pin_block",
595                        &operation_path,
596                        "pin blocks must contain at least one operation",
597                    ));
598                }
599                block_start = None;
600            }
601            SchematicSymbolOperation::PlotImageOperation(_)
602            | SchematicSymbolOperation::FlashPadCircleOperation(_)
603            | SchematicSymbolOperation::FlashPadOvalOperation(_)
604            | SchematicSymbolOperation::FlashPadRectOperation(_)
605            | SchematicSymbolOperation::FlashPadRoundRectOperation(_)
606            | SchematicSymbolOperation::FlashPadCustomOperation(_)
607            | SchematicSymbolOperation::FlashPadTrapezOperation(_) => {
608                return Err(error(
609                    "invalid_symbol_operation",
610                    &operation_path,
611                    "placed symbols do not admit images or pad flashes",
612                ));
613            }
614            SchematicSymbolOperation::TextOperation(value) => {
615                validate_annotation_text(value, &operation_path)?;
616                if block_start.is_some() && value.context.is_some() {
617                    return Err(error(
618                        "invalid_symbol_pin_text",
619                        &operation_path,
620                        "pin text cannot carry hyperlink context",
621                    ));
622                }
623            }
624            _ => validate_symbol_draw_operation(operation, &operation_path)?,
625        }
626    }
627    if block_start.is_some() {
628        return Err(error(
629            "invalid_symbol_pin_block",
630            format!("{path}.operations"),
631            "pin block must terminate before the record ends",
632        ));
633    }
634    Ok(())
635}
636
637fn validate_symbol_draw_operation(
638    operation: &SchematicSymbolOperation,
639    path: &str,
640) -> Result<(), ValidationError> {
641    let layer = match operation {
642        SchematicSymbolOperation::ThickSegmentOperation(value) => {
643            if value.role.is_some()
644                || !value.layers.is_empty()
645                || value.mask_margin_nm.is_some()
646                || value.pad_size_x_nm.is_some()
647                || value.pad_size_y_nm.is_some()
648            {
649                return Err(error(
650                    "invalid_symbol_operation",
651                    path,
652                    "symbol segment state is invalid",
653                ));
654            }
655            value.layer.as_deref()
656        }
657        SchematicSymbolOperation::ArcThreePointOperation(value) => value.layer.as_deref(),
658        SchematicSymbolOperation::CircleOperation(value) => {
659            if value.role.is_some()
660                || !value.layers.is_empty()
661                || value.mask_margin_nm.is_some()
662                || value.pad_size_x_nm.is_some()
663                || value.pad_size_y_nm.is_some()
664            {
665                return Err(error(
666                    "invalid_symbol_operation",
667                    path,
668                    "symbol circle state is invalid",
669                ));
670            }
671            value.layer.as_deref()
672        }
673        SchematicSymbolOperation::RectOperation(value) => value.layer.as_deref(),
674        SchematicSymbolOperation::PlotPolyOperation(value) => value.layer.as_deref(),
675        SchematicSymbolOperation::BezierCurveOperation(value) => value.layer.as_deref(),
676        _ => unreachable!("non-drawing symbol operation was handled by the caller"),
677    };
678    if layer.is_some() {
679        return Err(error(
680            "invalid_symbol_operation",
681            path,
682            "placed-symbol operations must remain layerless",
683        ));
684    }
685    Ok(())
686}
687
688fn symbol_operation_header(operation: &SchematicSymbolOperation) -> (u32, &str, &'static str) {
689    match operation {
690        SchematicSymbolOperation::ThickSegmentOperation(value) => {
691            (value.index, &value.kind, "ThickSegment")
692        }
693        SchematicSymbolOperation::ArcThreePointOperation(value) => {
694            (value.index, &value.kind, "ArcThreePoint")
695        }
696        SchematicSymbolOperation::CircleOperation(value) => (value.index, &value.kind, "Circle"),
697        SchematicSymbolOperation::RectOperation(value) => (value.index, &value.kind, "Rect"),
698        SchematicSymbolOperation::PlotPolyOperation(value) => {
699            (value.index, &value.kind, "PlotPoly")
700        }
701        SchematicSymbolOperation::BezierCurveOperation(value) => {
702            (value.index, &value.kind, "BezierCurve")
703        }
704        SchematicSymbolOperation::TextOperation(value) => (value.index, &value.kind, "Text"),
705        SchematicSymbolOperation::PlotImageOperation(value) => {
706            (value.index, &value.kind, "PlotImage")
707        }
708        SchematicSymbolOperation::FlashPadCircleOperation(value) => {
709            (value.index, &value.kind, "FlashPadCircle")
710        }
711        SchematicSymbolOperation::FlashPadOvalOperation(value) => {
712            (value.index, &value.kind, "FlashPadOval")
713        }
714        SchematicSymbolOperation::FlashPadRectOperation(value) => {
715            (value.index, &value.kind, "FlashPadRect")
716        }
717        SchematicSymbolOperation::FlashPadRoundRectOperation(value) => {
718            (value.index, &value.kind, "FlashPadRoundRect")
719        }
720        SchematicSymbolOperation::FlashPadCustomOperation(value) => {
721            (value.index, &value.kind, "FlashPadCustom")
722        }
723        SchematicSymbolOperation::FlashPadTrapezOperation(value) => {
724            (value.index, &value.kind, "FlashPadTrapez")
725        }
726        SchematicSymbolOperation::SchematicSymbolStartBlockOperation(value) => {
727            (value.index, &value.kind, "StartBlock")
728        }
729        SchematicSymbolOperation::SchematicSymbolEndBlockOperation(value) => {
730            (value.index, &value.kind, "EndBlock")
731        }
732    }
733}
734
735fn validate_sheet(record: &SchematicSheetPlotRecord, path: &str) -> Result<(), ValidationError> {
736    validate_sheet_identity(record, path)?;
737    validate_sheet_operation_headers(record, path)?;
738    validate_sheet_body_passes(record, path)?;
739    let content_end = validate_sheet_terminal_markers(record, path)?;
740    validate_sheet_contents(record, content_end, path)
741}
742
743fn validate_sheet_identity(
744    record: &SchematicSheetPlotRecord,
745    path: &str,
746) -> Result<(), ValidationError> {
747    if record.kind != "sheet"
748        || record.object_id != record.sheet_name
749        || record.size_x_nm.get() <= 0
750        || record.size_y_nm.get() <= 0
751        || record.operation_count as usize != record.operations.len()
752    {
753        return Err(error(
754            "invalid_sheet_record",
755            path,
756            "hierarchical-sheet identity, size, and operation count must be canonical",
757        ));
758    }
759    Ok(())
760}
761
762fn validate_sheet_operation_headers(
763    record: &SchematicSheetPlotRecord,
764    path: &str,
765) -> Result<(), ValidationError> {
766    for (index, operation) in record.operations.iter().enumerate() {
767        let (actual_index, kind, expected_kind) = sheet_operation_header(operation);
768        if actual_index as usize != index || kind != expected_kind {
769            return Err(error(
770                "invalid_schematic_operation",
771                format!("{path}.operations[{index}]"),
772                "sheet operation kind and local index must match its structural variant",
773            ));
774        }
775    }
776    Ok(())
777}
778
779fn validate_sheet_body_passes(
780    record: &SchematicSheetPlotRecord,
781    path: &str,
782) -> Result<(), ValidationError> {
783    let [
784        SchematicSheetOperation::RectOperation(first),
785        SchematicSheetOperation::RectOperation(outline),
786        ..,
787    ] = record.operations.as_slice()
788    else {
789        return Err(error(
790            "invalid_sheet_record",
791            format!("{path}.operations"),
792            "hierarchical sheet must begin with its two body passes",
793        ));
794    };
795    validate_sheet_outline(outline, record, &format!("{path}.operations[1]"))?;
796    if first.fill == PlotterFill::FilledShape {
797        if !sheet_rect_geometry(first, record)
798            || first.width_nm.get() != 0
799            || first.corner_radius_nm.get() != 0
800            || first.layer.is_some()
801            || !first.stroke_color.as_deref().is_some_and(valid_color)
802            || first.stroke_color != first.fill_color
803            || first.line_style.is_some()
804        {
805            return Err(error(
806                "invalid_sheet_background",
807                format!("{path}.operations[0]"),
808                "opaque sheet background must be the canonical undashed fill pass",
809            ));
810        }
811    } else {
812        validate_sheet_outline(first, record, &format!("{path}.operations[0]"))?;
813        if !same_sheet_rect_state(first, outline) {
814            return Err(error(
815                "invalid_sheet_outline_pair",
816                format!("{path}.operations[..2]"),
817                "transparent sheets must retain two identical outline passes",
818            ));
819        }
820    }
821    Ok(())
822}
823
824fn validate_sheet_terminal_markers(
825    record: &SchematicSheetPlotRecord,
826    path: &str,
827) -> Result<usize, ValidationError> {
828    let content_end = record
829        .operations
830        .len()
831        .checked_sub(usize::from(record.dnp) * 2)
832        .ok_or_else(|| {
833            error(
834                "invalid_sheet_dnp_marker",
835                format!("{path}.operations"),
836                "DNP sheet must retain two terminal markers",
837            )
838        })?;
839    if content_end < 2 {
840        return Err(error(
841            "invalid_sheet_dnp_marker",
842            format!("{path}.operations"),
843            "DNP sheet must retain its body before terminal markers",
844        ));
845    }
846    if record.dnp {
847        let (
848            SchematicSheetOperation::ThickSegmentOperation(first_marker),
849            SchematicSheetOperation::ThickSegmentOperation(second_marker),
850        ) = (
851            &record.operations[content_end],
852            &record.operations[content_end + 1],
853        )
854        else {
855            return Err(error(
856                "invalid_sheet_dnp_marker",
857                format!("{path}.operations[{content_end}]"),
858                "DNP sheet must end with two marker segments",
859            ));
860        };
861        validate_sheet_marker(first_marker, &format!("{path}.operations[{content_end}]"))?;
862        validate_sheet_marker(
863            second_marker,
864            &format!("{path}.operations[{}]", content_end + 1),
865        )?;
866        if first_marker.start_x != second_marker.end_x
867            || first_marker.end_x != second_marker.start_x
868            || first_marker.start_y != second_marker.start_y
869            || first_marker.end_y != second_marker.end_y
870        {
871            return Err(error(
872                "invalid_sheet_dnp_geometry",
873                format!("{path}.operations[{content_end}]"),
874                "DNP marker segments must be opposite diagonals of one box",
875            ));
876        }
877    }
878    Ok(content_end)
879}
880
881fn validate_sheet_contents(
882    record: &SchematicSheetPlotRecord,
883    content_end: usize,
884    path: &str,
885) -> Result<(), ValidationError> {
886    let mut index = 2usize;
887    let mut saw_property = false;
888    while index < content_end {
889        let operation_path = format!("{path}.operations[{index}]");
890        match &record.operations[index] {
891            SchematicSheetOperation::SchematicSheetStartBlockOperation(start) => {
892                let Some((text, decoration, consumed)) =
893                    sheet_pin_block(&record.operations, index, content_end)
894                else {
895                    return Err(error(
896                        "invalid_sheet_pin_block",
897                        &operation_path,
898                        "sheet-pin block must contain Text, optional decoration, and EndBlock",
899                    ));
900                };
901                validate_sheet_pin_owner(start, saw_property, &operation_path)?;
902                validate_sheet_pin(
903                    text,
904                    decoration,
905                    record,
906                    Some(&start.extra_attrs),
907                    &operation_path,
908                )?;
909                index += consumed;
910            }
911            SchematicSheetOperation::TextOperation(text) => {
912                if let Some(SchematicSheetOperation::PlotPolyOperation(decoration)) = record
913                    .operations
914                    .get(index + 1)
915                    .filter(|_| index + 1 < content_end)
916                {
917                    if saw_property {
918                        return Err(error(
919                            "invalid_sheet_pin_order",
920                            &operation_path,
921                            "sheet pins must precede visible properties",
922                        ));
923                    }
924                    validate_sheet_pin(text, Some(decoration), record, None, &operation_path)?;
925                    index += 2;
926                } else {
927                    saw_property = true;
928                    validate_annotation_text(text, &operation_path)?;
929                    if text.multiline {
930                        return Err(error(
931                            "invalid_sheet_property_text",
932                            &operation_path,
933                            "sheet properties are single plotter text operations",
934                        ));
935                    }
936                    index += 1;
937                }
938            }
939            _ => {
940                return Err(error(
941                    "invalid_sheet_operation",
942                    &operation_path,
943                    "sheet body admits only pin groups followed by property text",
944                ));
945            }
946        }
947    }
948    Ok(())
949}
950
951fn validate_sheet_pin_owner(
952    start: &SchematicSheetStartBlockOperation,
953    saw_property: bool,
954    path: &str,
955) -> Result<(), ValidationError> {
956    if saw_property
957        || start.label.is_empty()
958        || start.label != start.data_uuid
959        || start.label != start.object_id
960        || start.data_ref != "sheet_pin"
961    {
962        return Err(error(
963            "invalid_sheet_pin_block",
964            path,
965            "sheet-pin ownership must be nonempty, linked, and precede properties",
966        ));
967    }
968    Ok(())
969}
970
971fn sheet_rect_geometry(value: &RectOperation, record: &SchematicSheetPlotRecord) -> bool {
972    value.x1.get() == record.at_x_nm.get()
973        && value.y1.get() == record.at_y_nm.get()
974        && value.x2.get() == record.at_x_nm.get() + record.size_x_nm.get()
975        && value.y2.get() == record.at_y_nm.get() + record.size_y_nm.get()
976}
977
978fn validate_sheet_outline(
979    value: &RectOperation,
980    record: &SchematicSheetPlotRecord,
981    path: &str,
982) -> Result<(), ValidationError> {
983    if !sheet_rect_geometry(value, record)
984        || value.fill != PlotterFill::NoFill
985        || value.width_nm.get() < 0
986        || value.corner_radius_nm.get() != 0
987        || value.layer.is_some()
988        || !value.stroke_color.as_deref().is_some_and(valid_color)
989        || value.fill_color.is_some()
990        || value.line_style.is_none()
991    {
992        return Err(error(
993            "invalid_sheet_outline",
994            path,
995            "sheet outline geometry and layerless style must be canonical",
996        ));
997    }
998    Ok(())
999}
1000
1001fn same_sheet_rect_state(first: &RectOperation, second: &RectOperation) -> bool {
1002    first.x1 == second.x1
1003        && first.y1 == second.y1
1004        && first.x2 == second.x2
1005        && first.y2 == second.y2
1006        && first.fill == second.fill
1007        && first.width_nm == second.width_nm
1008        && first.corner_radius_nm == second.corner_radius_nm
1009        && first.layer == second.layer
1010        && first.stroke_color == second.stroke_color
1011        && first.fill_color == second.fill_color
1012        && first.line_style == second.line_style
1013}
1014
1015fn sheet_pin_block(
1016    operations: &[SchematicSheetOperation],
1017    index: usize,
1018    content_end: usize,
1019) -> Option<(&TextOperation, Option<&PlotPolyOperation>, usize)> {
1020    if index.checked_add(2)? >= content_end {
1021        return None;
1022    }
1023    let SchematicSheetOperation::TextOperation(text) = &operations[index + 1] else {
1024        return None;
1025    };
1026    match &operations[index + 2] {
1027        SchematicSheetOperation::PlotPolyOperation(decoration)
1028            if index + 3 < content_end
1029                && matches!(
1030                    operations[index + 3],
1031                    SchematicSheetOperation::SchematicSheetEndBlockOperation(_)
1032                ) =>
1033        {
1034            Some((text, Some(decoration), 4))
1035        }
1036        SchematicSheetOperation::SchematicSheetEndBlockOperation(_) => Some((text, None, 3)),
1037        _ => None,
1038    }
1039}
1040
1041fn validate_sheet_pin(
1042    text: &TextOperation,
1043    decoration: Option<&PlotPolyOperation>,
1044    record: &SchematicSheetPlotRecord,
1045    attrs: Option<&std::collections::BTreeMap<String, String>>,
1046    path: &str,
1047) -> Result<(), ValidationError> {
1048    validate_sheet_pin_text(text, path)?;
1049    let shape = validate_sheet_pin_attrs(attrs, text, record, path)?;
1050    validate_sheet_pin_decoration(decoration, text, record, shape, path)
1051}
1052
1053fn validate_sheet_pin_text(text: &TextOperation, path: &str) -> Result<(), ValidationError> {
1054    validate_annotation_text(text, &format!("{path}.text"))?;
1055    if text.multiline {
1056        return Err(error(
1057            "invalid_sheet_pin_text",
1058            format!("{path}.text"),
1059            "sheet pin text must remain a single plotter text operation",
1060        ));
1061    }
1062    Ok(())
1063}
1064
1065fn validate_sheet_pin_attrs<'a>(
1066    attrs: Option<&'a std::collections::BTreeMap<String, String>>,
1067    text: &TextOperation,
1068    record: &SchematicSheetPlotRecord,
1069    path: &str,
1070) -> Result<Option<&'a str>, ValidationError> {
1071    let Some(attrs) = attrs else {
1072        return Ok(None);
1073    };
1074    let required = [
1075        "primitive",
1076        "object-type",
1077        "sheet-uuid",
1078        "sheet-name",
1079        "sheet-file",
1080        "pin",
1081        "pin-name",
1082        "shape",
1083    ];
1084    let attrs_valid = attrs.len() == required.len()
1085        && required.iter().all(|key| attrs.contains_key(*key))
1086        && attrs.get("primitive").map(String::as_str) == Some("sheet-entry")
1087        && attrs.get("object-type").map(String::as_str) == Some("sheet-pin")
1088        && attrs.get("sheet-uuid").map(String::as_str) == Some(record.uuid.as_str())
1089        && attrs.get("sheet-name").map(String::as_str) == Some(record.sheet_name.as_str())
1090        && attrs.get("sheet-file").map(String::as_str) == Some(record.sheet_file.as_str())
1091        && attrs.get("pin") == attrs.get("pin-name");
1092    let shape = attrs.get("shape").map(String::as_str);
1093    if !attrs_valid
1094        || !matches!(
1095            shape,
1096            Some(
1097                "input"
1098                    | "output"
1099                    | "bidirectional"
1100                    | "tri_state"
1101                    | "passive"
1102                    | "dot"
1103                    | "round"
1104                    | "diamond"
1105                    | "rectangle"
1106            )
1107        )
1108        || attrs
1109            .get("pin-name")
1110            .is_none_or(|name| text.text != name.replace("{slash}", "/"))
1111    {
1112        return Err(error(
1113            "invalid_sheet_pin_attrs",
1114            format!("{path}.extra_attrs"),
1115            "sheet-pin metadata must use the exact linked vocabulary",
1116        ));
1117    }
1118    Ok(shape)
1119}
1120
1121fn validate_sheet_pin_decoration(
1122    decoration: Option<&PlotPolyOperation>,
1123    text: &TextOperation,
1124    record: &SchematicSheetPlotRecord,
1125    shape: Option<&str>,
1126    path: &str,
1127) -> Result<(), ValidationError> {
1128    let decoration_required = shape.is_none_or(|shape| {
1129        matches!(
1130            shape,
1131            "input" | "output" | "bidirectional" | "tri_state" | "passive"
1132        )
1133    });
1134    if decoration_required != decoration.is_some() {
1135        return Err(error(
1136            "invalid_sheet_pin_decoration",
1137            format!("{path}.decoration"),
1138            "sheet-pin decoration presence must match its shape",
1139        ));
1140    }
1141    let Some(decoration) = decoration else {
1142        return Ok(());
1143    };
1144    let expected_points = match shape {
1145        Some("input" | "output") => decoration.points.len() == 6,
1146        Some(_) => decoration.points.len() == 5,
1147        None => matches!(decoration.points.len(), 5 | 6),
1148    };
1149    let closed = decoration
1150        .points
1151        .first()
1152        .zip(decoration.points.last())
1153        .is_some_and(|(first, last)| first.0 == last.0);
1154    let expected_color = if record.dnp {
1155        DIMMED_SHEET_LABEL_COLOR
1156    } else {
1157        SHEET_LABEL_COLOR
1158    };
1159    if decoration.layer.is_some()
1160        || decoration.fill != PlotterFill::NoFill
1161        || decoration.width_nm != text.pen_width_nm
1162        || decoration.stroke_color.as_deref() != Some(expected_color)
1163        || decoration.fill_color.is_some()
1164        || decoration.line_style.is_some()
1165        || !expected_points
1166        || !closed
1167    {
1168        return Err(error(
1169            "invalid_sheet_pin_decoration",
1170            format!("{path}.decoration"),
1171            "sheet-pin decoration must be the canonical closed layerless outline",
1172        ));
1173    }
1174    Ok(())
1175}
1176
1177fn validate_sheet_marker(value: &ThickSegmentOperation, path: &str) -> Result<(), ValidationError> {
1178    if value.layer.is_some()
1179        || value.role.is_some()
1180        || !value.layers.is_empty()
1181        || value.mask_margin_nm.is_some()
1182        || value.pad_size_x_nm.is_some()
1183        || value.pad_size_y_nm.is_some()
1184        || value.width_nm.get() != DNP_MARKER_WIDTH_NM
1185        || value.stroke_color.as_deref() != Some(DNP_MARKER_COLOR)
1186    {
1187        return Err(error(
1188            "invalid_sheet_dnp_marker",
1189            path,
1190            "sheet DNP marker must be the canonical layerless segment",
1191        ));
1192    }
1193    Ok(())
1194}
1195
1196fn sheet_operation_header(operation: &SchematicSheetOperation) -> (u32, &str, &'static str) {
1197    match operation {
1198        SchematicSheetOperation::ThickSegmentOperation(value) => {
1199            (value.index, &value.kind, "ThickSegment")
1200        }
1201        SchematicSheetOperation::RectOperation(value) => (value.index, &value.kind, "Rect"),
1202        SchematicSheetOperation::PlotPolyOperation(value) => (value.index, &value.kind, "PlotPoly"),
1203        SchematicSheetOperation::TextOperation(value) => (value.index, &value.kind, "Text"),
1204        SchematicSheetOperation::SchematicSheetStartBlockOperation(value) => {
1205            (value.index, &value.kind, "StartBlock")
1206        }
1207        SchematicSheetOperation::SchematicSheetEndBlockOperation(value) => {
1208            (value.index, &value.kind, "EndBlock")
1209        }
1210    }
1211}
1212
1213fn validate_sheet_header(
1214    document: &SchematicPlotDocumentA0,
1215    record: &SchematicSheetHeaderPlotRecord,
1216    path: &str,
1217) -> Result<(), ValidationError> {
1218    if record.kind != "sheet_header"
1219        || record.sheet_width_nm != document.canvas.width_nm
1220        || record.sheet_height_nm != document.canvas.height_nm
1221        || record.sheet_width_nm.get() <= 0
1222        || record.sheet_height_nm.get() <= 0
1223        || record
1224            .paper_width_mm
1225            .is_some_and(|value| !value.is_finite())
1226        || record
1227            .paper_height_mm
1228            .is_some_and(|value| !value.is_finite())
1229    {
1230        return Err(error(
1231            "invalid_sheet_header",
1232            path,
1233            "sheet header identity, canvas, paper, and dimensions must be canonical",
1234        ));
1235    }
1236    let Some(PlotterOperation::RectOperation(background)) = record.operations.first() else {
1237        return Err(error(
1238            "invalid_sheet_background",
1239            format!("{path}.operations[0]"),
1240            "sheet header must begin with the canonical page background",
1241        ));
1242    };
1243    if !valid_background(background, record) {
1244        return Err(error(
1245            "invalid_sheet_background",
1246            format!("{path}.operations[0]"),
1247            "sheet background must cover the canvas with canonical styling",
1248        ));
1249    }
1250    for (index, operation) in record.operations.iter().enumerate().skip(1) {
1251        let operation_path = format!("{path}.operations[{index}]");
1252        match operation {
1253            PlotterOperation::RectOperation(value) if valid_worksheet_rect(value) => {}
1254            PlotterOperation::PlotPolyOperation(value) if valid_worksheet_polyline(value) => {}
1255            PlotterOperation::TextOperation(value) => {
1256                validate_worksheet_text(value, &operation_path)?;
1257            }
1258            PlotterOperation::PlotImageOperation(value) => {
1259                validate_worksheet_image(value, &operation_path)?;
1260            }
1261            _ => {
1262                return Err(error(
1263                    "invalid_worksheet_operation",
1264                    operation_path,
1265                    "worksheet admits only layerless rect, polyline, text, and image operations",
1266                ));
1267            }
1268        }
1269    }
1270    Ok(())
1271}
1272
1273fn valid_worksheet_rect(value: &RectOperation) -> bool {
1274    value.fill == PlotterFill::NoFill
1275        && value.width_nm.get() >= 152_400
1276        && value.corner_radius_nm.get() == 0
1277        && value.layer.is_none()
1278        && value.stroke_color.as_deref() == Some(DRAWING_SHEET_COLOR)
1279        && value.fill_color.is_none()
1280        && value.line_style.is_none()
1281}
1282
1283fn valid_worksheet_polyline(value: &PlotPolyOperation) -> bool {
1284    value.points.len() == 2
1285        && value.fill == PlotterFill::NoFill
1286        && value.width_nm.get() >= 152_400
1287        && value.layer.is_none()
1288        && value.stroke_color.as_deref() == Some(DRAWING_SHEET_COLOR)
1289        && value.fill_color.is_none()
1290        && value.line_style.is_none()
1291}
1292
1293fn valid_background(value: &RectOperation, record: &SchematicSheetHeaderPlotRecord) -> bool {
1294    value.x1.get() == 0
1295        && value.y1.get() == 0
1296        && value.x2 == record.sheet_width_nm
1297        && value.y2 == record.sheet_height_nm
1298        && value.fill == PlotterFill::FilledShape
1299        && value.width_nm.get() == 100
1300        && value.corner_radius_nm.get() == 0
1301        && value.layer.is_none()
1302        && value.stroke_color.as_deref() == Some(BACKGROUND_COLOR)
1303        && value.fill_color.as_deref() == Some(BACKGROUND_COLOR)
1304}
1305
1306fn validate_worksheet_text(value: &TextOperation, path: &str) -> Result<(), ValidationError> {
1307    if value.context.is_some()
1308        || value.layer.is_some()
1309        || value.mirror.is_some()
1310        || value.text_as_polygons.is_some()
1311        || value.polyline_per_segment.is_some()
1312        || value.knockout.is_some()
1313        || !value.render_cache_polygons.is_empty()
1314        || value.render_cache.is_some()
1315        || value.render_cache_source.is_some()
1316        || value.render_cache_exact.is_some()
1317        || !value.orient_deg.is_finite()
1318    {
1319        return Err(error(
1320            "invalid_worksheet_text",
1321            path,
1322            "worksheet text must remain layerless, finite, stroke text without cache markers",
1323        ));
1324    }
1325    Ok(())
1326}
1327
1328fn validate_worksheet_image(value: &PlotImageOperation, path: &str) -> Result<(), ValidationError> {
1329    if value.image_format != "png"
1330        || !value.scale.is_finite()
1331        || value.scale <= 0.0
1332        || value.width_nm.get() < 0
1333        || value.height_nm.get() < 0
1334        || value.stroke_color.as_deref() != Some(DRAWING_SHEET_COLOR)
1335        || !valid_png_base64(&value.image_data_b64)
1336    {
1337        return Err(error(
1338            "invalid_worksheet_image",
1339            path,
1340            "worksheet image must be a finite positive-scale PNG placement",
1341        ));
1342    }
1343    Ok(())
1344}
1345
1346fn valid_png_base64(value: &str) -> bool {
1347    let mut prefix = [0_u8; 33];
1348    let mut prefix_len = 0_usize;
1349    let mut quartet = [0_u8; 4];
1350    let mut quartet_len = 0_usize;
1351    let mut ended = false;
1352
1353    for byte in value.bytes() {
1354        if byte.is_ascii_whitespace() {
1355            return false;
1356        }
1357        if ended {
1358            return false;
1359        }
1360        let sextet = match byte {
1361            b'A'..=b'Z' => byte - b'A',
1362            b'a'..=b'z' => byte - b'a' + 26,
1363            b'0'..=b'9' => byte - b'0' + 52,
1364            b'+' => 62,
1365            b'/' => 63,
1366            b'=' => 64,
1367            _ => return false,
1368        };
1369        quartet[quartet_len] = sextet;
1370        quartet_len += 1;
1371        if quartet_len != 4 {
1372            continue;
1373        }
1374        if quartet[0] >= 64 || quartet[1] >= 64 {
1375            return false;
1376        }
1377        let decoded_len = if quartet[2] == 64 {
1378            if quartet[3] != 64 || quartet[1] & 0x0f != 0 {
1379                return false;
1380            }
1381            ended = true;
1382            1
1383        } else if quartet[3] == 64 {
1384            if quartet[2] & 0x03 != 0 {
1385                return false;
1386            }
1387            ended = true;
1388            2
1389        } else {
1390            3
1391        };
1392        let decoded = [
1393            (quartet[0] << 2) | (quartet[1] >> 4),
1394            (quartet[1] << 4) | (quartet[2] >> 2),
1395            (quartet[2] << 6) | quartet[3],
1396        ];
1397        for byte in decoded.into_iter().take(decoded_len) {
1398            if prefix_len < prefix.len() {
1399                prefix[prefix_len] = byte;
1400                prefix_len += 1;
1401            }
1402        }
1403        quartet_len = 0;
1404    }
1405    if quartet_len != 0 || prefix_len < prefix.len() {
1406        return false;
1407    }
1408    let width = u32::from_be_bytes([prefix[16], prefix[17], prefix[18], prefix[19]]);
1409    let height = u32::from_be_bytes([prefix[20], prefix[21], prefix[22], prefix[23]]);
1410    prefix[..8] == *b"\x89PNG\r\n\x1a\n"
1411        && prefix[8..12] == [0, 0, 0, 13]
1412        && prefix[12..16] == *b"IHDR"
1413        && width > 0
1414        && height > 0
1415}
1416
1417fn validate_polyline(
1418    operations: &[PlotterOperation],
1419    bus_entry: bool,
1420    path: &str,
1421) -> Result<(), ValidationError> {
1422    let [PlotterOperation::PlotPolyOperation(value)] = operations else {
1423        return Err(error(
1424            "invalid_connectivity_record",
1425            path,
1426            "wire, bus, and bus-entry records contain exactly one polygon operation",
1427        ));
1428    };
1429    if !valid_connectivity_poly(value) || (bus_entry && value.points.len() != 2) {
1430        return Err(error(
1431            if bus_entry {
1432                "invalid_bus_entry"
1433            } else {
1434                "invalid_connectivity_polyline"
1435            },
1436            format!("{path}.operations[0]"),
1437            "connectivity polyline state and point count must be canonical",
1438        ));
1439    }
1440    Ok(())
1441}
1442
1443fn valid_connectivity_poly(value: &PlotPolyOperation) -> bool {
1444    value.layer.is_none()
1445        && value.fill == PlotterFill::NoFill
1446        && value.width_nm.get() >= 0
1447        && value
1448            .stroke_color
1449            .as_deref()
1450            .is_some_and(|color| !color.is_empty())
1451        && value.line_style.is_some()
1452        && !value.points.is_empty()
1453}
1454
1455fn validate_junction(
1456    record: &SchematicJunctionPlotRecord,
1457    path: &str,
1458) -> Result<(), ValidationError> {
1459    if record.kind != "junction" {
1460        return Err(error(
1461            "invalid_junction",
1462            path,
1463            "junction record kind must be canonical",
1464        ));
1465    }
1466    let [PlotterOperation::CircleOperation(value)] = record.operations.as_slice() else {
1467        return Err(error(
1468            "invalid_junction",
1469            path,
1470            "junction records contain exactly one circle operation",
1471        ));
1472    };
1473    let expected_color = match &record.color {
1474        None | Some(None) => DEFAULT_JUNCTION_COLOR,
1475        Some(Some(color)) => color,
1476    };
1477    if !valid_junction_circle(value) || value.stroke_color.as_deref() != Some(expected_color) {
1478        return Err(error(
1479            "invalid_junction",
1480            format!("{path}.operations[0]"),
1481            "junction circle and optional authored color must agree",
1482        ));
1483    }
1484    Ok(())
1485}
1486
1487fn valid_junction_circle(value: &CircleOperation) -> bool {
1488    value.layer.is_none()
1489        && value.role.is_none()
1490        && value.layers.is_empty()
1491        && value.mask_margin_nm.is_none()
1492        && value.pad_size_x_nm.is_none()
1493        && value.pad_size_y_nm.is_none()
1494        && value.fill == PlotterFill::FilledShape
1495        && value.width_nm.get() == 0
1496        && value.diameter_nm.get() > 0
1497        && value.stroke_color.is_some()
1498        && value.stroke_color == value.fill_color
1499}
1500
1501fn validate_no_connect(
1502    record: &SchematicNoConnectPlotRecord,
1503    path: &str,
1504) -> Result<(), ValidationError> {
1505    if record.kind != "no_connect" {
1506        return Err(error(
1507            "invalid_no_connect",
1508            path,
1509            "no-connect record kind must be canonical",
1510        ));
1511    }
1512    let [
1513        PlotterOperation::PlotPolyOperation(first),
1514        PlotterOperation::PlotPolyOperation(second),
1515    ] = record.operations.as_slice()
1516    else {
1517        return Err(error(
1518            "invalid_no_connect",
1519            path,
1520            "no-connect records contain exactly two polygon operations",
1521        ));
1522    };
1523    if !valid_no_connect_segment(first)
1524        || !valid_no_connect_segment(second)
1525        || first.width_nm != second.width_nm
1526        || !cross_geometry(first, second)
1527    {
1528        return Err(error(
1529            "invalid_no_connect",
1530            format!("{path}.operations"),
1531            "no-connect segments must form one canonical equal-width cross",
1532        ));
1533    }
1534    Ok(())
1535}
1536
1537fn valid_no_connect_segment(value: &PlotPolyOperation) -> bool {
1538    value.layer.is_none()
1539        && value.fill == PlotterFill::NoFill
1540        && value.width_nm.get() > 0
1541        && value.stroke_color.as_deref() == Some(NO_CONNECT_COLOR)
1542        && value.line_style.is_none()
1543        && value.points.len() == 2
1544}
1545
1546fn cross_geometry(first: &PlotPolyOperation, second: &PlotPolyOperation) -> bool {
1547    let left = [&first.points[0].0, &first.points[1].0];
1548    let right = [&second.points[0].0, &second.points[1].0];
1549    left[0][0] == right[0][0]
1550        && left[1][0] == right[1][0]
1551        && left[0][1] == right[1][1]
1552        && left[1][1] == right[0][1]
1553}
1554
1555fn validate_annotation_text(value: &TextOperation, path: &str) -> Result<(), ValidationError> {
1556    if value.layer.is_some()
1557        || value.mirror.is_some()
1558        || value.text_as_polygons.is_some()
1559        || value.polyline_per_segment.is_some()
1560        || value.knockout.is_some()
1561        || !value.render_cache_polygons.is_empty()
1562        || value.render_cache.is_some()
1563        || value.render_cache_source.is_some()
1564        || value.render_cache_exact.is_some()
1565        || !value.orient_deg.is_finite()
1566        || value.context.as_ref().is_some_and(|context| {
1567            let href: &str = &context.hyperlink.href;
1568            href.is_empty() || href.trim() != href
1569        })
1570    {
1571        return Err(error(
1572            "invalid_annotation_text",
1573            path,
1574            "schematic annotation text must be canonical layerless stroke text",
1575        ));
1576    }
1577    Ok(())
1578}
1579
1580fn validate_global_label(
1581    record: &SchematicGlobalLabelPlotRecord,
1582    path: &str,
1583) -> Result<(), ValidationError> {
1584    validate_label(
1585        &record.operations,
1586        &record.text,
1587        Some(record.shape),
1588        true,
1589        path,
1590    )
1591}
1592
1593fn validate_hierarchical_label(
1594    record: &SchematicHierarchicalLabelPlotRecord,
1595    path: &str,
1596) -> Result<(), ValidationError> {
1597    validate_label(
1598        &record.operations,
1599        &record.text,
1600        Some(record.shape),
1601        false,
1602        path,
1603    )
1604}
1605
1606fn validate_label(
1607    operations: &[PlotterOperation],
1608    metadata_text: &str,
1609    shape: Option<SchematicLabelShape>,
1610    global: bool,
1611    path: &str,
1612) -> Result<(), ValidationError> {
1613    let decorated = shape.is_some_and(|value| {
1614        matches!(
1615            value,
1616            SchematicLabelShape::Input
1617                | SchematicLabelShape::Output
1618                | SchematicLabelShape::Bidirectional
1619                | SchematicLabelShape::TriState
1620                | SchematicLabelShape::Passive
1621        )
1622    });
1623    let expected_count = if decorated { 2 } else { 1 };
1624    if operations.len() != expected_count {
1625        return Err(error(
1626            "invalid_label_record",
1627            format!("{path}.operations"),
1628            "label operation count and decoration presence must match its shape",
1629        ));
1630    }
1631    let PlotterOperation::TextOperation(text) = &operations[0] else {
1632        return Err(error(
1633            "invalid_label_record",
1634            format!("{path}.operations[0]"),
1635            "labels begin with exactly one text operation",
1636        ));
1637    };
1638    validate_annotation_text(text, &format!("{path}.operations[0]"))?;
1639    if text.text != metadata_text.replace("{slash}", "/") {
1640        return Err(error(
1641            "invalid_label_text",
1642            format!("{path}.text"),
1643            "label metadata and plotted display text must agree",
1644        ));
1645    }
1646    if !decorated {
1647        return Ok(());
1648    }
1649    let PlotterOperation::PlotPolyOperation(decoration) = &operations[1] else {
1650        return Err(error(
1651            "invalid_label_decoration",
1652            format!("{path}.operations[1]"),
1653            "decorated labels end with one polygon",
1654        ));
1655    };
1656    let shape = shape.expect("decorated label shape");
1657    let expected_points = if global {
1658        7
1659    } else if matches!(
1660        shape,
1661        SchematicLabelShape::Input | SchematicLabelShape::Output
1662    ) {
1663        6
1664    } else {
1665        5
1666    };
1667    let expected_color = if global {
1668        GLOBAL_LABEL_COLOR
1669    } else {
1670        HIERARCHICAL_LABEL_COLOR
1671    };
1672    let closed = decoration
1673        .points
1674        .first()
1675        .zip(decoration.points.last())
1676        .is_some_and(|(first, last)| first.0 == last.0);
1677    if decoration.layer.is_some()
1678        || decoration.fill != PlotterFill::NoFill
1679        || decoration.width_nm.get() != 152_400
1680        || decoration.stroke_color.as_deref() != Some(expected_color)
1681        || decoration.fill_color.is_some()
1682        || decoration.line_style.is_some()
1683        || decoration.points.len() != expected_points
1684        || !closed
1685    {
1686        return Err(error(
1687            "invalid_label_decoration",
1688            format!("{path}.operations[1]"),
1689            "label decoration geometry and style must be canonical",
1690        ));
1691    }
1692    Ok(())
1693}
1694
1695fn validate_netclass_flag(
1696    record: &SchematicNetclassFlagPlotRecord,
1697    path: &str,
1698) -> Result<(), ValidationError> {
1699    let text_start = match record.shape {
1700        SchematicNetclassFlagShape::Round | SchematicNetclassFlagShape::Dot => {
1701            let [
1702                PlotterOperation::ThickSegmentOperation(segment),
1703                PlotterOperation::CircleOperation(marker),
1704                ..,
1705            ] = record.operations.as_slice()
1706            else {
1707                return Err(error(
1708                    "invalid_netclass_marker",
1709                    format!("{path}.operations"),
1710                    "round and dot flags begin with segment and circle markers",
1711                ));
1712            };
1713            validate_netclass_segment(segment, record, &format!("{path}.operations[0]"))?;
1714            validate_netclass_circle(marker, segment, record, &format!("{path}.operations[1]"))?;
1715            2
1716        }
1717        SchematicNetclassFlagShape::Diamond | SchematicNetclassFlagShape::Rectangle => {
1718            let Some(PlotterOperation::PlotPolyOperation(marker)) = record.operations.first()
1719            else {
1720                return Err(error(
1721                    "invalid_netclass_marker",
1722                    format!("{path}.operations[0]"),
1723                    "diamond and rectangle flags begin with one polygon marker",
1724                ));
1725            };
1726            let expected_points = if record.shape == SchematicNetclassFlagShape::Diamond {
1727                7
1728            } else {
1729                8
1730            };
1731            let anchor = [record.at_x_nm, record.at_y_nm];
1732            let closed_at_anchor = marker
1733                .points
1734                .first()
1735                .zip(marker.points.last())
1736                .is_some_and(|(first, last)| first.0 == anchor && first.0 == last.0);
1737            if marker.layer.is_some()
1738                || marker.fill != PlotterFill::NoFill
1739                || marker.width_nm.get() <= 0
1740                || marker.stroke_color.as_deref() != Some(NETCLASS_COLOR)
1741                || marker.fill_color.is_some()
1742                || marker.line_style.is_some()
1743                || marker.points.len() != expected_points
1744                || !closed_at_anchor
1745            {
1746                return Err(error(
1747                    "invalid_netclass_polygon",
1748                    format!("{path}.operations[0]"),
1749                    "netclass polygon marker must have canonical geometry and style",
1750                ));
1751            }
1752            1
1753        }
1754    };
1755    for (index, operation) in record.operations.iter().enumerate().skip(text_start) {
1756        let PlotterOperation::TextOperation(text) = operation else {
1757            return Err(error(
1758                "invalid_netclass_property",
1759                format!("{path}.operations[{index}]"),
1760                "netclass marker may only be followed by visible property text",
1761            ));
1762        };
1763        validate_annotation_text(text, &format!("{path}.operations[{index}]"))?;
1764    }
1765    Ok(())
1766}
1767
1768fn validate_netclass_segment(
1769    segment: &ThickSegmentOperation,
1770    record: &SchematicNetclassFlagPlotRecord,
1771    path: &str,
1772) -> Result<(), ValidationError> {
1773    if segment.layer.is_some()
1774        || segment.role.is_some()
1775        || !segment.layers.is_empty()
1776        || segment.mask_margin_nm.is_some()
1777        || segment.pad_size_x_nm.is_some()
1778        || segment.pad_size_y_nm.is_some()
1779        || segment.width_nm.get() <= 0
1780        || segment.stroke_color.as_deref() != Some(NETCLASS_COLOR)
1781        || segment.start_x != record.at_x_nm
1782        || segment.start_y != record.at_y_nm
1783    {
1784        return Err(error(
1785            "invalid_netclass_segment",
1786            path,
1787            "netclass segment must begin at the flag anchor with canonical style",
1788        ));
1789    }
1790    Ok(())
1791}
1792
1793fn validate_netclass_circle(
1794    marker: &CircleOperation,
1795    segment: &ThickSegmentOperation,
1796    record: &SchematicNetclassFlagPlotRecord,
1797    path: &str,
1798) -> Result<(), ValidationError> {
1799    let dot = record.shape == SchematicNetclassFlagShape::Dot;
1800    let symbol_size = if dot { 355_600 } else { 508_000 };
1801    let expected_fill = if dot {
1802        PlotterFill::FilledShape
1803    } else {
1804        PlotterFill::NoFill
1805    };
1806    let expected_width = if dot { 0 } else { segment.width_nm.get() };
1807    let expected_fill_color = dot.then_some(NETCLASS_COLOR);
1808    if marker.layer.is_some()
1809        || marker.role.is_some()
1810        || !marker.layers.is_empty()
1811        || marker.mask_margin_nm.is_some()
1812        || marker.pad_size_x_nm.is_some()
1813        || marker.pad_size_y_nm.is_some()
1814        || marker.line_style.is_some()
1815        || marker.diameter_nm.get() != 2 * symbol_size
1816        || marker.fill != expected_fill
1817        || marker.width_nm.get() != expected_width
1818        || marker.stroke_color.as_deref() != Some(NETCLASS_COLOR)
1819        || marker.fill_color.as_deref() != expected_fill_color
1820    {
1821        return Err(error(
1822            "invalid_netclass_circle",
1823            path,
1824            "netclass circle marker must have canonical geometry and style",
1825        ));
1826    }
1827    Ok(())
1828}
1829
1830fn validate_schematic_text(
1831    record: &SchematicTextPlotRecord,
1832    path: &str,
1833) -> Result<(), ValidationError> {
1834    let [PlotterOperation::TextOperation(text)] = record.operations.as_slice() else {
1835        return Err(error(
1836            "invalid_schematic_text",
1837            format!("{path}.operations"),
1838            "ordinary schematic text contains exactly one text operation",
1839        ));
1840    };
1841    validate_annotation_text(text, &format!("{path}.operations[0]"))?;
1842    let expected = record.text.strip_suffix('\n').unwrap_or(&record.text);
1843    if text.text != expected || text.multiline != text.text.contains('\n') {
1844        return Err(error(
1845            "invalid_schematic_text",
1846            format!("{path}.text"),
1847            "schematic text metadata and trailing-newline normalization must agree",
1848        ));
1849    }
1850    Ok(())
1851}
1852
1853fn validate_text_box(
1854    record: &SchematicTextBoxPlotRecord,
1855    path: &str,
1856) -> Result<(), ValidationError> {
1857    let text_start = validate_text_box_prefix(&record.operations, path)?;
1858    validate_text_box_lines(&record.operations, text_start, path)
1859}
1860
1861fn validate_text_box_prefix(
1862    operations: &[PlotterOperation],
1863    path: &str,
1864) -> Result<usize, ValidationError> {
1865    let Some(PlotterOperation::RectOperation(first)) = operations.first() else {
1866        return Err(error(
1867            "invalid_text_box",
1868            format!("{path}.operations"),
1869            "text box begins with an outline rectangle",
1870        ));
1871    };
1872    let single_fill_valid = match first.fill {
1873        PlotterFill::NoFill => first.fill_color.is_none(),
1874        PlotterFill::FilledShape => true,
1875        _ => true,
1876    };
1877    if first.layer.is_some()
1878        || first.corner_radius_nm.get() != 0
1879        || first.width_nm.get() < 0
1880        || !first.stroke_color.as_deref().is_some_and(valid_color)
1881        || !first.fill_color.as_deref().is_none_or(valid_color)
1882        || first.line_style.is_none()
1883        || !single_fill_valid
1884    {
1885        return Err(error(
1886            "invalid_text_box_outline",
1887            format!("{path}.operations[0]"),
1888            "text box rectangle style must be canonical",
1889        ));
1890    }
1891    let text_start = if matches!(first.fill, PlotterFill::NoFill | PlotterFill::FilledShape) {
1892        1
1893    } else {
1894        let Some(PlotterOperation::RectOperation(outline)) = operations.get(1) else {
1895            return Err(error(
1896                "invalid_text_box_fill_pass",
1897                format!("{path}.operations"),
1898                "noncanonical fills require a fill pass and outline pass",
1899            ));
1900        };
1901        let same_geometry = first.x1 == outline.x1
1902            && first.y1 == outline.y1
1903            && first.x2 == outline.x2
1904            && first.y2 == outline.y2
1905            && first.corner_radius_nm == outline.corner_radius_nm;
1906        if first.width_nm.get() != 0
1907            || first.fill_color.is_none()
1908            || first.stroke_color != first.fill_color
1909            || outline.layer.is_some()
1910            || !same_geometry
1911            || outline.fill != PlotterFill::NoFill
1912            || outline.width_nm.get() < 0
1913            || !outline.stroke_color.as_deref().is_some_and(valid_color)
1914            || outline.fill_color.is_some()
1915            || outline.line_style != first.line_style
1916        {
1917            return Err(error(
1918                "invalid_text_box_fill_pass",
1919                format!("{path}.operations[0]"),
1920                "text box fill and outline passes must be coherent",
1921            ));
1922        }
1923        2
1924    };
1925    Ok(text_start)
1926}
1927
1928fn validate_text_box_lines(
1929    operations: &[PlotterOperation],
1930    text_start: usize,
1931    path: &str,
1932) -> Result<(), ValidationError> {
1933    for (index, operation) in operations.iter().enumerate().skip(text_start) {
1934        let PlotterOperation::TextOperation(text) = operation else {
1935            return Err(error(
1936                "invalid_text_box_line",
1937                format!("{path}.operations[{index}]"),
1938                "text box outline may only be followed by plotted text lines",
1939            ));
1940        };
1941        if text.text.is_empty() || text.multiline {
1942            return Err(error(
1943                "invalid_text_box_line",
1944                format!("{path}.operations[{index}]"),
1945                "text box lines are nonempty single-line text operations",
1946            ));
1947        }
1948        validate_annotation_text(text, &format!("{path}.operations[{index}]"))?;
1949    }
1950    Ok(())
1951}
1952
1953#[derive(Clone, Copy)]
1954enum GraphicKind {
1955    Polyline,
1956    Arc,
1957    Circle,
1958    Rectangle,
1959}
1960
1961#[derive(Clone, Copy)]
1962enum GraphicRef<'a> {
1963    Polyline(&'a PlotPolyOperation),
1964    Arc(&'a ArcThreePointOperation),
1965    Circle(&'a CircleOperation),
1966    Rectangle(&'a RectOperation),
1967}
1968
1969impl<'a> GraphicRef<'a> {
1970    fn fill(self) -> PlotterFill {
1971        match self {
1972            Self::Polyline(value) => value.fill,
1973            Self::Arc(value) => value.fill,
1974            Self::Circle(value) => value.fill,
1975            Self::Rectangle(value) => value.fill,
1976        }
1977    }
1978
1979    fn width(self) -> i64 {
1980        match self {
1981            Self::Polyline(value) => value.width_nm.get(),
1982            Self::Arc(value) => value.width_nm.get(),
1983            Self::Circle(value) => value.width_nm.get(),
1984            Self::Rectangle(value) => value.width_nm.get(),
1985        }
1986    }
1987
1988    fn layer(self) -> Option<&'static str> {
1989        let present = match self {
1990            Self::Polyline(value) => value.layer.is_some(),
1991            Self::Arc(value) => value.layer.is_some(),
1992            Self::Circle(value) => value.layer.is_some(),
1993            Self::Rectangle(value) => value.layer.is_some(),
1994        };
1995        present.then_some("present")
1996    }
1997
1998    fn stroke_color(self) -> Option<&'static str> {
1999        let valid = match self {
2000            Self::Polyline(value) => value.stroke_color.as_deref().is_some_and(valid_color),
2001            Self::Arc(value) => value.stroke_color.as_deref().is_some_and(valid_color),
2002            Self::Circle(value) => value.stroke_color.as_deref().is_some_and(valid_color),
2003            Self::Rectangle(value) => value.stroke_color.as_deref().is_some_and(valid_color),
2004        };
2005        valid.then_some("valid")
2006    }
2007
2008    fn stroke(self) -> Option<&'a str> {
2009        match self {
2010            Self::Polyline(value) => value.stroke_color.as_deref(),
2011            Self::Arc(value) => value.stroke_color.as_deref(),
2012            Self::Circle(value) => value.stroke_color.as_deref(),
2013            Self::Rectangle(value) => value.stroke_color.as_deref(),
2014        }
2015    }
2016
2017    fn fill_color(self) -> Option<&'a str> {
2018        match self {
2019            Self::Polyline(value) => value.fill_color.as_deref(),
2020            Self::Arc(value) => value.fill_color.as_deref(),
2021            Self::Circle(value) => value.fill_color.as_deref(),
2022            Self::Rectangle(value) => value.fill_color.as_deref(),
2023        }
2024    }
2025
2026    fn line_style_present(self) -> bool {
2027        match self {
2028            Self::Polyline(value) => value.line_style.is_some(),
2029            Self::Arc(value) => value.line_style.is_some(),
2030            Self::Circle(value) => value.line_style.is_some(),
2031            Self::Rectangle(value) => value.line_style.is_some(),
2032        }
2033    }
2034
2035    fn same_line_style(self, other: Self) -> bool {
2036        match (self, other) {
2037            (Self::Polyline(a), Self::Polyline(b)) => a.line_style == b.line_style,
2038            (Self::Arc(a), Self::Arc(b)) => a.line_style == b.line_style,
2039            (Self::Circle(a), Self::Circle(b)) => a.line_style == b.line_style,
2040            (Self::Rectangle(a), Self::Rectangle(b)) => a.line_style == b.line_style,
2041            _ => false,
2042        }
2043    }
2044
2045    fn same_geometry(self, other: Self) -> bool {
2046        match (self, other) {
2047            (Self::Polyline(a), Self::Polyline(b)) => {
2048                a.points.len() == b.points.len()
2049                    && a.points
2050                        .iter()
2051                        .zip(&b.points)
2052                        .all(|(left, right)| left.0 == right.0)
2053            }
2054            (Self::Arc(a), Self::Arc(b)) => {
2055                a.start_x == b.start_x
2056                    && a.start_y == b.start_y
2057                    && a.mid_x == b.mid_x
2058                    && a.mid_y == b.mid_y
2059                    && a.end_x == b.end_x
2060                    && a.end_y == b.end_y
2061            }
2062            (Self::Circle(a), Self::Circle(b)) => {
2063                a.cx == b.cx && a.cy == b.cy && a.diameter_nm == b.diameter_nm
2064            }
2065            (Self::Rectangle(a), Self::Rectangle(b)) => {
2066                a.x1 == b.x1
2067                    && a.y1 == b.y1
2068                    && a.x2 == b.x2
2069                    && a.y2 == b.y2
2070                    && a.corner_radius_nm == b.corner_radius_nm
2071            }
2072            _ => false,
2073        }
2074    }
2075}
2076
2077fn graphic_ref(operation: &PlotterOperation, kind: GraphicKind) -> Option<GraphicRef<'_>> {
2078    match (operation, kind) {
2079        (PlotterOperation::PlotPolyOperation(value), GraphicKind::Polyline) => {
2080            Some(GraphicRef::Polyline(value))
2081        }
2082        (PlotterOperation::ArcThreePointOperation(value), GraphicKind::Arc) => {
2083            Some(GraphicRef::Arc(value))
2084        }
2085        (PlotterOperation::CircleOperation(value), GraphicKind::Circle) => {
2086            Some(GraphicRef::Circle(value))
2087        }
2088        (PlotterOperation::RectOperation(value), GraphicKind::Rectangle) => {
2089            Some(GraphicRef::Rectangle(value))
2090        }
2091        _ => None,
2092    }
2093}
2094
2095fn validate_graphic_record(
2096    operations: &[PlotterOperation],
2097    kind: GraphicKind,
2098    closed: bool,
2099    path: &str,
2100) -> Result<(), ValidationError> {
2101    if !matches!(operations.len(), 1 | 2) {
2102        return Err(error(
2103            "invalid_graphic_record",
2104            format!("{path}.operations"),
2105            "schematic graphics contain one operation or a coherent fill pair",
2106        ));
2107    }
2108    let first = graphic_ref(&operations[0], kind).ok_or_else(|| {
2109        error(
2110            "invalid_graphic_record",
2111            format!("{path}.operations[0]"),
2112            "schematic graphic operation kind must match its record",
2113        )
2114    })?;
2115    validate_graphic_operation(first, &format!("{path}.operations[0]"))?;
2116    if closed
2117        && !matches!(
2118            first,
2119            GraphicRef::Polyline(value)
2120                if !value.points.is_empty()
2121                    && value
2122                        .points
2123                        .first()
2124                        .zip(value.points.last())
2125                        .is_some_and(|(first, last)| first.0 == last.0)
2126        )
2127    {
2128        return Err(error(
2129            "open_rule_area",
2130            format!("{path}.operations[0].points"),
2131            "rule-area polylines must be closed",
2132        ));
2133    }
2134    if operations.len() == 1 {
2135        let canonical = match first.fill() {
2136            PlotterFill::NoFill => first.fill_color().is_none(),
2137            PlotterFill::FilledShape => true,
2138            _ => false,
2139        };
2140        return canonical.then_some(()).ok_or_else(|| {
2141            error(
2142                "invalid_graphic_fill",
2143                format!("{path}.operations[0]"),
2144                "single-pass schematic graphic fill state must be canonical",
2145            )
2146        });
2147    }
2148    let outline = graphic_ref(&operations[1], kind).ok_or_else(|| {
2149        error(
2150            "invalid_graphic_fill_pair",
2151            format!("{path}.operations[1]"),
2152            "schematic graphic fill pair must retain one operation kind",
2153        )
2154    })?;
2155    validate_graphic_operation(outline, &format!("{path}.operations[1]"))?;
2156    if matches!(first.fill(), PlotterFill::NoFill | PlotterFill::FilledShape)
2157        || first.width() != 0
2158        || first.fill_color().is_none()
2159        || first.stroke() != first.fill_color()
2160        || outline.fill() != PlotterFill::NoFill
2161        || outline.fill_color().is_some()
2162        || !first.same_line_style(outline)
2163        || !first.same_geometry(outline)
2164    {
2165        return Err(error(
2166            "invalid_graphic_fill_pair",
2167            format!("{path}.operations"),
2168            "schematic graphic fill and outline passes must be coherent",
2169        ));
2170    }
2171    Ok(())
2172}
2173
2174fn validate_graphic_operation(value: GraphicRef<'_>, path: &str) -> Result<(), ValidationError> {
2175    let specialized = match value {
2176        GraphicRef::Polyline(polyline) => polyline.points.len() >= 2,
2177        GraphicRef::Circle(circle) => {
2178            circle.diameter_nm.get() >= 0
2179                && circle.role.is_none()
2180                && circle.layers.is_empty()
2181                && circle.mask_margin_nm.is_none()
2182                && circle.pad_size_x_nm.is_none()
2183                && circle.pad_size_y_nm.is_none()
2184        }
2185        GraphicRef::Rectangle(rectangle) => rectangle.corner_radius_nm.get() >= 0,
2186        GraphicRef::Arc(_) => true,
2187    };
2188    if value.layer().is_some()
2189        || value.width() < 0
2190        || value.stroke_color().is_none()
2191        || value.fill_color().is_some_and(|color| !valid_color(color))
2192        || !value.line_style_present()
2193        || !specialized
2194    {
2195        return Err(error(
2196            "invalid_graphic_style",
2197            path,
2198            "schematic graphic geometry and layerless style must be canonical",
2199        ));
2200    }
2201    Ok(())
2202}
2203
2204fn valid_color(value: &str) -> bool {
2205    value.len() == 9
2206        && value.starts_with('#')
2207        && value[1..]
2208            .bytes()
2209            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'A'..=b'F'))
2210}
2211
2212fn validate_bezier_operation(
2213    value: &BezierCurveOperation,
2214    path: &str,
2215) -> Result<(), ValidationError> {
2216    if value.layer.is_some()
2217        || value.width_nm.get() < 0
2218        || value.tolerance_nm.get() != 0
2219        || !value.stroke_color.as_deref().is_some_and(valid_color)
2220        || value.line_style.is_none()
2221    {
2222        return Err(error(
2223            "invalid_graphic_bezier",
2224            path,
2225            "schematic Bezier geometry and layerless style must be canonical",
2226        ));
2227    }
2228    Ok(())
2229}
2230
2231fn validate_bezier_record(
2232    record: &SchematicGraphicBezierPlotRecord,
2233    path: &str,
2234) -> Result<(), ValidationError> {
2235    let [PlotterOperation::BezierCurveOperation(value)] = record.operations.as_slice() else {
2236        return Err(error(
2237            "invalid_graphic_bezier",
2238            format!("{path}.operations"),
2239            "schematic Bezier records contain exactly one cubic operation",
2240        ));
2241    };
2242    validate_bezier_operation(value, &format!("{path}.operations[0]"))
2243}
2244
2245fn validate_rule_area(
2246    record: &SchematicRuleAreaPlotRecord,
2247    path: &str,
2248) -> Result<(), ValidationError> {
2249    match record.shape {
2250        SchematicRuleAreaShape::Polyline => {
2251            validate_graphic_record(&record.operations, GraphicKind::Polyline, true, path)
2252        }
2253        SchematicRuleAreaShape::Rectangle => {
2254            validate_graphic_record(&record.operations, GraphicKind::Rectangle, false, path)
2255        }
2256        SchematicRuleAreaShape::Arc => {
2257            validate_graphic_record(&record.operations, GraphicKind::Arc, false, path)
2258        }
2259        SchematicRuleAreaShape::Circle => {
2260            validate_graphic_record(&record.operations, GraphicKind::Circle, false, path)
2261        }
2262        SchematicRuleAreaShape::Bezier => {
2263            let [PlotterOperation::BezierCurveOperation(value)] = record.operations.as_slice()
2264            else {
2265                return Err(error(
2266                    "invalid_rule_area",
2267                    format!("{path}.operations"),
2268                    "Bezier rule areas contain exactly one cubic operation",
2269                ));
2270            };
2271            validate_bezier_operation(value, &format!("{path}.operations[0]"))
2272        }
2273    }
2274}
2275
2276#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2277enum ImageFormat {
2278    Png,
2279    Jpeg,
2280    Bmp,
2281}
2282
2283#[derive(Clone, Copy, Debug)]
2284struct ImageMetadata {
2285    format: ImageFormat,
2286    width: u32,
2287    height: u32,
2288    ppi_x: Option<u32>,
2289    ppi_y: Option<u32>,
2290}
2291
2292fn validate_schematic_image(
2293    record: &SchematicImagePlotRecord,
2294    path: &str,
2295) -> Result<(), ValidationError> {
2296    let [PlotterOperation::PlotImageOperation(operation)] = record.operations.as_slice() else {
2297        return Err(error(
2298            "invalid_schematic_image",
2299            format!("{path}.operations"),
2300            "schematic image records contain exactly one image operation",
2301        ));
2302    };
2303    let metadata = decode_image_metadata(&operation.image_data_b64).ok_or_else(|| {
2304        error(
2305            "invalid_schematic_image",
2306            format!("{path}.operations[0].image_data_b64"),
2307            "schematic image data must be canonical supported base64",
2308        )
2309    })?;
2310    let expected_format = match metadata.format {
2311        ImageFormat::Png => SchematicImageFormat::Png,
2312        ImageFormat::Jpeg => SchematicImageFormat::Jpeg,
2313        ImageFormat::Bmp => SchematicImageFormat::Bmp,
2314    };
2315    let width_nm =
2316        image_extent(metadata.width, operation.scale, metadata.ppi_x).ok_or_else(|| {
2317            error(
2318                "invalid_schematic_image_extent",
2319                format!("{path}.operations[0].width_nm"),
2320                "schematic image width must remain finite and JavaScript-safe",
2321            )
2322        })?;
2323    let height_nm =
2324        image_extent(metadata.height, operation.scale, metadata.ppi_y).ok_or_else(|| {
2325            error(
2326                "invalid_schematic_image_extent",
2327                format!("{path}.operations[0].height_nm"),
2328                "schematic image height must remain finite and JavaScript-safe",
2329            )
2330        })?;
2331    if !operation.scale.is_finite()
2332        || operation.scale <= 0.0
2333        || operation.stroke_color.as_deref() != Some("#0000C2FF")
2334        || operation.image_format != expected_format.to_string()
2335        || record.image_format != expected_format
2336        || record.scale != operation.scale
2337        || record.width_nm != operation.width_nm
2338        || record.height_nm != operation.height_nm
2339        || operation.width_nm.get() != width_nm
2340        || operation.height_nm.get() != height_nm
2341        || width_nm <= 0
2342        || height_nm <= 0
2343    {
2344        return Err(error(
2345            "invalid_schematic_image_metadata",
2346            path,
2347            "schematic image record, operation, decoded metadata, and extent must agree",
2348        ));
2349    }
2350    Ok(())
2351}
2352
2353fn decode_image_metadata(value: &str) -> Option<ImageMetadata> {
2354    let data = decode_base64(value)?;
2355    if data.len() >= 33
2356        && data.get(..8) == Some(b"\x89PNG\r\n\x1a\n")
2357        && data.get(8..16) == Some(b"\0\0\0\rIHDR")
2358    {
2359        return png_metadata(&data);
2360    }
2361    if data.len() >= 4 && data.get(..2) == Some(b"\xff\xd8") {
2362        return jpeg_metadata(&data);
2363    }
2364    if data.len() >= 26 && data.get(..2) == Some(b"BM") {
2365        return bmp_metadata(&data);
2366    }
2367    None
2368}
2369
2370fn decode_base64(value: &str) -> Option<Vec<u8>> {
2371    let mut output = Vec::with_capacity(value.len().saturating_mul(3) / 4);
2372    let mut quartet = [0_u8; 4];
2373    let mut quartet_len = 0usize;
2374    let mut ended = false;
2375    for byte in value.bytes() {
2376        if byte.is_ascii_whitespace() || ended {
2377            return None;
2378        }
2379        quartet[quartet_len] = match byte {
2380            b'A'..=b'Z' => byte - b'A',
2381            b'a'..=b'z' => byte - b'a' + 26,
2382            b'0'..=b'9' => byte - b'0' + 52,
2383            b'+' => 62,
2384            b'/' => 63,
2385            b'=' => 64,
2386            _ => return None,
2387        };
2388        quartet_len += 1;
2389        if quartet_len != 4 {
2390            continue;
2391        }
2392        if quartet[0] >= 64 || quartet[1] >= 64 {
2393            return None;
2394        }
2395        output.push((quartet[0] << 2) | (quartet[1] >> 4));
2396        if quartet[2] == 64 {
2397            if quartet[3] != 64 || quartet[1] & 0x0f != 0 {
2398                return None;
2399            }
2400            ended = true;
2401        } else {
2402            output.push((quartet[1] << 4) | (quartet[2] >> 2));
2403            if quartet[3] == 64 {
2404                if quartet[2] & 0x03 != 0 {
2405                    return None;
2406                }
2407                ended = true;
2408            } else {
2409                output.push((quartet[2] << 6) | quartet[3]);
2410            }
2411        }
2412        quartet_len = 0;
2413    }
2414    (quartet_len == 0).then_some(output)
2415}
2416
2417fn png_metadata(data: &[u8]) -> Option<ImageMetadata> {
2418    let width = read_u32_be(data.get(16..20)?)?;
2419    let height = read_u32_be(data.get(20..24)?)?;
2420    if width == 0 || height == 0 {
2421        return None;
2422    }
2423    let mut ppi_x = None;
2424    let mut ppi_y = None;
2425    let mut position = 8usize;
2426    while position.checked_add(12)? <= data.len() {
2427        let length = usize::try_from(read_u32_be(data.get(position..position + 4)?)?).ok()?;
2428        let payload_start = position.checked_add(8)?;
2429        let payload_end = payload_start.checked_add(length)?;
2430        let end = payload_end.checked_add(4)?;
2431        if end > data.len() {
2432            return None;
2433        }
2434        let kind = data.get(position + 4..position + 8)?;
2435        if kind == b"pHYs" && length >= 9 {
2436            let payload = data.get(payload_start..payload_end)?;
2437            if payload[8] == 1 {
2438                ppi_x = ppi_from_ppm(read_u32_be(&payload[..4])?);
2439                ppi_y = ppi_from_ppm(read_u32_be(&payload[4..8])?);
2440            }
2441        }
2442        position = end;
2443        if kind == b"IEND" {
2444            break;
2445        }
2446    }
2447    Some(ImageMetadata {
2448        format: ImageFormat::Png,
2449        width,
2450        height,
2451        ppi_x,
2452        ppi_y,
2453    })
2454}
2455
2456// This is a direct, allocation-free marker scanner. Keeping the marker state
2457// explicit makes the accepted JPEG subset auditable against the Python oracle.
2458#[allow(
2459    clippy::cognitive_complexity,
2460    reason = "the allocation-free marker scanner intentionally mirrors the Python authority"
2461)]
2462fn jpeg_metadata(data: &[u8]) -> Option<ImageMetadata> {
2463    let mut position = 2usize;
2464    let mut ppi_x = None;
2465    let mut ppi_y = None;
2466    while position.checked_add(9)? <= data.len() {
2467        if data[position] != 0xff {
2468            position += 1;
2469            continue;
2470        }
2471        let marker = data[position + 1];
2472        position += 2;
2473        if matches!(marker, 0xd8 | 0xd9) {
2474            continue;
2475        }
2476        let length = usize::from(read_u16_be(data.get(position..position + 2)?)?);
2477        if length < 2 || position.checked_add(length)? > data.len() {
2478            return None;
2479        }
2480        let payload = data.get(position + 2..position + length)?;
2481        if marker == 0xe0 && payload.starts_with(b"JFIF\0") && payload.len() >= 12 {
2482            let units = payload[7];
2483            let density_x = u32::from(read_u16_be(&payload[8..10])?);
2484            let density_y = u32::from(read_u16_be(&payload[10..12])?);
2485            if density_x > 0 && density_y > 0 {
2486                match units {
2487                    1 => {
2488                        ppi_x = Some(density_x);
2489                        ppi_y = Some(density_y);
2490                    }
2491                    2 => {
2492                        ppi_x = density_to_ppi(density_x);
2493                        ppi_y = density_to_ppi(density_y);
2494                    }
2495                    _ => {}
2496                }
2497            }
2498        }
2499        if matches!(
2500            marker,
2501            0xc0 | 0xc1
2502                | 0xc2
2503                | 0xc3
2504                | 0xc5
2505                | 0xc6
2506                | 0xc7
2507                | 0xc9
2508                | 0xca
2509                | 0xcb
2510                | 0xcd
2511                | 0xce
2512                | 0xcf
2513        ) {
2514            if length < 7 {
2515                return None;
2516            }
2517            let height = u32::from(read_u16_be(data.get(position + 3..position + 5)?)?);
2518            let width = u32::from(read_u16_be(data.get(position + 5..position + 7)?)?);
2519            return (width > 0 && height > 0).then_some(ImageMetadata {
2520                format: ImageFormat::Jpeg,
2521                width,
2522                height,
2523                ppi_x,
2524                ppi_y,
2525            });
2526        }
2527        position += length;
2528    }
2529    None
2530}
2531
2532fn bmp_metadata(data: &[u8]) -> Option<ImageMetadata> {
2533    let dib = read_u32_le(data.get(14..18)?)?;
2534    let (width, height, ppi_x, ppi_y) = if dib == 12 {
2535        (
2536            u32::from(read_u16_le(data.get(18..20)?)?),
2537            u32::from(read_u16_le(data.get(20..22)?)?),
2538            None,
2539            None,
2540        )
2541    } else if dib >= 40 && data.len() >= 54 {
2542        let width = read_i32_le(data.get(18..22)?)?.unsigned_abs();
2543        let height = read_i32_le(data.get(22..26)?)?.unsigned_abs();
2544        let ppi_x = bmp_ppi(read_i32_le(data.get(38..42)?)?);
2545        let ppi_y = bmp_ppi(read_i32_le(data.get(42..46)?)?);
2546        (width, height, ppi_x, ppi_y)
2547    } else {
2548        return None;
2549    };
2550    (width > 0 && height > 0).then_some(ImageMetadata {
2551        format: ImageFormat::Bmp,
2552        width,
2553        height,
2554        ppi_x,
2555        ppi_y,
2556    })
2557}
2558
2559fn ppi_from_ppm(value: u32) -> Option<u32> {
2560    (value > 0)
2561        .then(|| (f64::from(value) * 0.0254).round_ties_even() as u32)
2562        .filter(|value| *value > 0)
2563}
2564
2565fn density_to_ppi(value: u32) -> Option<u32> {
2566    (value > 0)
2567        .then(|| (f64::from(value) * 2.54).round_ties_even() as u32)
2568        .filter(|value| *value > 0)
2569}
2570
2571fn bmp_ppi(value: i32) -> Option<u32> {
2572    (value > 0)
2573        .then(|| ((value / 100) as f64 * 2.54).round_ties_even() as u32)
2574        .filter(|value| *value > 0)
2575}
2576
2577fn image_extent(size: u32, scale: f64, ppi: Option<u32>) -> Option<i64> {
2578    let density = f64::from(ppi.unwrap_or(300));
2579    let value = f64::from(size) * scale * 25.4 / density * 1_000_000.0;
2580    (value.is_finite()
2581        && value >= crate::JAVASCRIPT_SAFE_INTEGER_MIN as f64
2582        && value <= crate::JAVASCRIPT_SAFE_INTEGER_MAX as f64)
2583        .then(|| value.round_ties_even() as i64)
2584}
2585
2586fn read_u16_be(value: &[u8]) -> Option<u16> {
2587    Some(u16::from_be_bytes(value.try_into().ok()?))
2588}
2589
2590fn read_u16_le(value: &[u8]) -> Option<u16> {
2591    Some(u16::from_le_bytes(value.try_into().ok()?))
2592}
2593
2594fn read_u32_be(value: &[u8]) -> Option<u32> {
2595    Some(u32::from_be_bytes(value.try_into().ok()?))
2596}
2597
2598fn read_u32_le(value: &[u8]) -> Option<u32> {
2599    Some(u32::from_le_bytes(value.try_into().ok()?))
2600}
2601
2602fn read_i32_le(value: &[u8]) -> Option<i32> {
2603    Some(i32::from_le_bytes(value.try_into().ok()?))
2604}
2605
2606fn validate_table(record: &SchematicTablePlotRecord, path: &str) -> Result<(), ValidationError> {
2607    let mut operation_index = 0usize;
2608    let mut cells = 0usize;
2609    while operation_index < record.operations.len() {
2610        let prefix = validate_text_box_prefix(
2611            &record.operations[operation_index..],
2612            &format!("{path}.operations[{operation_index}]"),
2613        )?;
2614        operation_index += prefix;
2615        while let Some(PlotterOperation::TextOperation(text)) =
2616            record.operations.get(operation_index)
2617        {
2618            if text.text.is_empty() || text.multiline {
2619                return Err(error(
2620                    "invalid_table_cell_line",
2621                    format!("{path}.operations[{operation_index}]"),
2622                    "table cell lines must be nonempty single-line text",
2623                ));
2624            }
2625            validate_annotation_text(text, &format!("{path}.operations[{operation_index}]"))?;
2626            operation_index += 1;
2627        }
2628        cells = cells.saturating_add(1);
2629    }
2630    if cells != record.cell_count as usize {
2631        return Err(error(
2632            "table_cell_count_mismatch",
2633            format!("{path}.cell_count"),
2634            "table cell_count must equal the rendered cell blocks",
2635        ));
2636    }
2637    Ok(())
2638}
2639
2640fn error(code: &'static str, path: impl Into<String>, message: &'static str) -> ValidationError {
2641    validation_error(code, path, message)
2642}