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

kicad_monkey_core/
schematic_plot_contract.rs

1//! Bounded projection of the typed schematic plot model into the frozen a0 contract.
2
3use crate::{
4    PlotterCircle, PlotterFill, PlotterLineStyle, PlotterOperation, PlotterText, PlotterTextHAlign,
5    PlotterTextVAlign, SchematicAnnotationRecord, SchematicConnectivityRecord,
6    SchematicConnectivityRecordKind, SchematicPlotDocument, SchematicPlotOperation,
7    SchematicPlotRecord, ThickSegment,
8};
9use serde_json::{Map, Value, json};
10use std::fmt;
11use std::io::{self, Write};
12use std::mem::size_of;
13
14// The converter briefly holds the source model, JSON Value tree, and decoded
15// strict contract. Small plot documents have proportionally high map/vector
16// overhead, so retain a conservative preflight ratio while still coupling a
17// tiny output ceiling to bounded work before materialization.
18const OUTPUT_TO_MODEL_RATIO: usize = 128;
19const VALUE_ALLOCATION_MULTIPLIER: usize = 8;
20const ROOT_VALUES: usize = 16;
21const VALUES_PER_RECORD: usize = 32;
22const VALUES_PER_OPERATION: usize = 32;
23const VALUES_PER_POINT: usize = 2;
24
25#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct SchematicPlotContractError(String);
27
28impl fmt::Display for SchematicPlotContractError {
29    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
30        formatter.write_str(&self.0)
31    }
32}
33
34impl std::error::Error for SchematicPlotContractError {}
35
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37pub struct SchematicPlotContractBudget {
38    pub derived_items: usize,
39    pub materialized_bytes: usize,
40}
41
42/// Project a typed schematic plot document into the strict a0 JSON vocabulary.
43pub fn schematic_plot_document_json(
44    document: &SchematicPlotDocument,
45) -> Result<Value, SchematicPlotContractError> {
46    let budget = schematic_plot_document_budget(document)?;
47    validate_budget(budget)?;
48    let contract = crate::project_schematic_plot_document_a0(document)
49        .map_err(|error| SchematicPlotContractError(error.to_string()))?;
50    let value = serde_json::to_value(contract).map_err(|error| {
51        SchematicPlotContractError(format!("schematic plot contract encode failed: {error}"))
52    })?;
53    let mut writer = LimitedWriter::new(usize::MAX);
54    serde_json::to_writer(&mut writer, &value).map_err(|error| {
55        SchematicPlotContractError(format!(
56            "schematic plot contract output limit exceeded: {error}"
57        ))
58    })?;
59    Ok(value)
60}
61
62pub fn schematic_plot_document_budget(
63    document: &SchematicPlotDocument,
64) -> Result<SchematicPlotContractBudget, SchematicPlotContractError> {
65    let records = document.records.len();
66    let operations = document.records.iter().try_fold(0_usize, |count, record| {
67        count.checked_add(record.operation_count()).ok_or_else(|| {
68            SchematicPlotContractError("schematic plot operation count overflow".to_owned())
69        })
70    })?;
71    let points = document
72        .records
73        .iter()
74        .flat_map(record_operations)
75        .try_fold(0_usize, |count, operation| {
76            count
77                .checked_add(operation_point_count(operation))
78                .ok_or_else(|| {
79                    SchematicPlotContractError("schematic plot point count overflow".to_owned())
80                })
81        })?;
82    let items = ROOT_VALUES
83        .checked_add(
84            records
85                .checked_mul(VALUES_PER_RECORD)
86                .ok_or_else(item_overflow)?,
87        )
88        .and_then(|value| {
89            operations
90                .checked_mul(VALUES_PER_OPERATION)
91                .and_then(|count| value.checked_add(count))
92        })
93        .and_then(|value| {
94            points
95                .checked_mul(VALUES_PER_POINT)
96                .and_then(|count| value.checked_add(count))
97        })
98        .ok_or_else(item_overflow)?;
99    let payload = payload_bytes(document)?;
100    let materialized = items
101        .checked_mul(size_of::<Value>())
102        .and_then(|bytes| bytes.checked_mul(VALUE_ALLOCATION_MULTIPLIER))
103        .and_then(|bytes| {
104            payload
105                .checked_mul(VALUE_ALLOCATION_MULTIPLIER)
106                .and_then(|payload| bytes.checked_add(payload))
107        })
108        .ok_or_else(item_overflow)?;
109    Ok(SchematicPlotContractBudget {
110        derived_items: items,
111        materialized_bytes: materialized,
112    })
113}
114
115fn validate_budget(budget: SchematicPlotContractBudget) -> Result<(), SchematicPlotContractError> {
116    let effective_limit = usize::MAX.saturating_mul(OUTPUT_TO_MODEL_RATIO);
117    if budget.materialized_bytes > effective_limit {
118        return Err(SchematicPlotContractError(format!(
119            "schematic plot materialized byte limit exceeded: {} > {effective_limit}",
120            budget.materialized_bytes
121        )));
122    }
123    Ok(())
124}
125
126fn payload_bytes(document: &SchematicPlotDocument) -> Result<usize, SchematicPlotContractError> {
127    let mut bytes = 0_usize;
128    add_optional_text(&mut bytes, document.source_path.as_deref())?;
129    add_text(&mut bytes, &document.document_id)?;
130    for record in &document.records {
131        match record {
132            SchematicPlotRecord::SheetHeader(value) => {
133                add_texts(
134                    &mut bytes,
135                    [
136                        value.uuid.as_str(),
137                        value.paper_size.as_str(),
138                        value.generator.as_str(),
139                        value.generator_version.as_str(),
140                    ],
141                )?;
142                if let Some(title) = &value.title_block {
143                    add_texts(
144                        &mut bytes,
145                        [
146                            title.title.as_str(),
147                            title.date.as_str(),
148                            title.revision.as_str(),
149                            title.company.as_str(),
150                        ],
151                    )?;
152                    for comment in title.comments.values() {
153                        add_text(&mut bytes, comment)?;
154                    }
155                }
156            }
157            SchematicPlotRecord::Connectivity(value) => {
158                add_text(&mut bytes, &value.uuid)?;
159                add_optional_text(&mut bytes, value.junction_color.as_deref())?;
160            }
161            SchematicPlotRecord::Annotation(value) => {
162                add_texts(&mut bytes, [value.uuid.as_str(), value.object_id.as_str()])?;
163                add_optional_text(&mut bytes, value.text.as_deref())?;
164                add_optional_text(&mut bytes, value.shape.as_deref())?;
165            }
166            SchematicPlotRecord::Graphic(value) => add_text(&mut bytes, &value.uuid)?,
167            SchematicPlotRecord::RuleArea(value) => add_text(&mut bytes, &value.uuid)?,
168            SchematicPlotRecord::Image(value) => {
169                add_texts(
170                    &mut bytes,
171                    [value.uuid.as_str(), value.image_format.as_str()],
172                )?;
173            }
174            SchematicPlotRecord::Table(value) => add_text(&mut bytes, &value.uuid)?,
175            SchematicPlotRecord::SymbolInstance(value) => add_texts(
176                &mut bytes,
177                [
178                    value.uuid.as_str(),
179                    value.lib_id.as_str(),
180                    value.lib_name.as_str(),
181                    value.reference.as_str(),
182                ],
183            )?,
184            SchematicPlotRecord::SymbolOverplot(value) => add_texts(
185                &mut bytes,
186                [
187                    value.uuid.as_str(),
188                    value.source_symbol_uuid.as_str(),
189                    value.lib_id.as_str(),
190                ],
191            )?,
192            SchematicPlotRecord::Sheet(value) => add_texts(
193                &mut bytes,
194                [
195                    value.uuid.as_str(),
196                    value.sheet_name.as_str(),
197                    value.sheet_file.as_str(),
198                ],
199            )?,
200        }
201        if let SchematicPlotRecord::SymbolInstance(value) = record {
202            add_optional_text(&mut bytes, value.mirror.as_deref())?;
203        }
204        for operation in record_operations(record) {
205            operation_payload_bytes(&mut bytes, operation)?;
206        }
207    }
208    Ok(bytes)
209}
210
211fn operation_payload_bytes(
212    bytes: &mut usize,
213    operation: &SchematicPlotOperation,
214) -> Result<(), SchematicPlotContractError> {
215    match operation {
216        SchematicPlotOperation::Text(value) => {
217            plotter_text_payload_bytes(bytes, &value.text)?;
218            add_optional_text(bytes, value.hyperlink_href.as_deref())?;
219        }
220        SchematicPlotOperation::StyledThickSegment(value) => {
221            thick_segment_payload_bytes(bytes, &value.segment)?;
222            add_text(bytes, &value.stroke_color)?;
223        }
224        SchematicPlotOperation::PlotImage(value) => {
225            add_texts(
226                bytes,
227                [value.image_data_b64.as_str(), value.image_format.as_str()],
228            )?;
229            add_optional_text(bytes, value.stroke_color.as_deref())?;
230        }
231        SchematicPlotOperation::StartSymbolPinBlock(value) => {
232            add_texts(
233                bytes,
234                [
235                    value.label.as_str(),
236                    value.data_uuid.as_str(),
237                    value.object_id.as_str(),
238                    value.extra_attrs.primitive.as_str(),
239                    value.extra_attrs.object_type.as_str(),
240                    value.extra_attrs.pin.as_str(),
241                    value.extra_attrs.symbol_uuid.as_str(),
242                    value.extra_attrs.designator.as_str(),
243                    value.extra_attrs.lib_pin_uuid.as_str(),
244                ],
245            )?;
246        }
247        SchematicPlotOperation::StartSheetPinBlock(value) => {
248            add_texts(
249                bytes,
250                [
251                    value.label.as_str(),
252                    value.data_uuid.as_str(),
253                    value.object_id.as_str(),
254                    value.extra_attrs.primitive.as_str(),
255                    value.extra_attrs.object_type.as_str(),
256                    value.extra_attrs.sheet_uuid.as_str(),
257                    value.extra_attrs.sheet_name.as_str(),
258                    value.extra_attrs.sheet_file.as_str(),
259                    value.extra_attrs.pin.as_str(),
260                    value.extra_attrs.pin_name.as_str(),
261                    value.extra_attrs.shape.as_str(),
262                ],
263            )?;
264        }
265        SchematicPlotOperation::EndBlock => {}
266        SchematicPlotOperation::Plotter(operation) => {
267            plotter_operation_payload_bytes(bytes, operation)?;
268        }
269    }
270    Ok(())
271}
272
273fn plotter_operation_payload_bytes(
274    bytes: &mut usize,
275    operation: &PlotterOperation,
276) -> Result<(), SchematicPlotContractError> {
277    match operation {
278        PlotterOperation::Rect(value) => add_style_payload(
279            bytes,
280            value.layer.as_deref(),
281            value.stroke_color.as_deref(),
282            value.fill_color.as_deref(),
283        )?,
284        PlotterOperation::PlotPoly(value) => add_style_payload(
285            bytes,
286            value.layer.as_deref(),
287            value.stroke_color.as_deref(),
288            value.fill_color.as_deref(),
289        )?,
290        PlotterOperation::Circle(value) => {
291            add_style_payload(
292                bytes,
293                value.layer.as_deref(),
294                value.stroke_color.as_deref(),
295                value.fill_color.as_deref(),
296            )?;
297            add_optional_text(bytes, value.role.as_deref())?;
298            for layer in &value.layers {
299                add_text(bytes, layer)?;
300            }
301        }
302        PlotterOperation::Text(value) => plotter_text_payload_bytes(bytes, value)?,
303        PlotterOperation::ArcThreePoint(value) => add_style_payload(
304            bytes,
305            value.layer.as_deref(),
306            value.stroke_color.as_deref(),
307            value.fill_color.as_deref(),
308        )?,
309        PlotterOperation::BezierCurve(value) => {
310            add_optional_text(bytes, value.layer.as_deref())?;
311            add_optional_text(bytes, value.stroke_color.as_deref())?;
312        }
313        PlotterOperation::ThickSegment(value) => thick_segment_payload_bytes(bytes, value)?,
314        PlotterOperation::FlashPadCircle(_)
315        | PlotterOperation::FlashPadOval(_)
316        | PlotterOperation::FlashPadRect(_)
317        | PlotterOperation::FlashPadRoundRect(_)
318        | PlotterOperation::FlashPadCustom(_)
319        | PlotterOperation::FlashPadTrapez(_) => {
320            return Err(SchematicPlotContractError(
321                "operation is outside the schematic plot vocabulary".to_owned(),
322            ));
323        }
324    }
325    Ok(())
326}
327
328fn plotter_text_payload_bytes(
329    bytes: &mut usize,
330    value: &PlotterText,
331) -> Result<(), SchematicPlotContractError> {
332    add_texts(
333        bytes,
334        [
335            value.text.as_str(),
336            value.color.as_str(),
337            value.font_face.as_str(),
338        ],
339    )?;
340    add_optional_text(bytes, value.layer.as_deref())
341}
342
343fn thick_segment_payload_bytes(
344    bytes: &mut usize,
345    value: &ThickSegment,
346) -> Result<(), SchematicPlotContractError> {
347    add_optional_text(bytes, value.layer.as_deref())?;
348    add_optional_text(bytes, value.role.as_deref())?;
349    for layer in &value.layers {
350        add_text(bytes, layer)?;
351    }
352    Ok(())
353}
354
355fn add_style_payload(
356    bytes: &mut usize,
357    layer: Option<&str>,
358    stroke: Option<&str>,
359    fill: Option<&str>,
360) -> Result<(), SchematicPlotContractError> {
361    add_optional_text(bytes, layer)?;
362    add_optional_text(bytes, stroke)?;
363    add_optional_text(bytes, fill)
364}
365
366fn add_texts<'a>(
367    bytes: &mut usize,
368    values: impl IntoIterator<Item = &'a str>,
369) -> Result<(), SchematicPlotContractError> {
370    for value in values {
371        add_text(bytes, value)?;
372    }
373    Ok(())
374}
375
376fn add_optional_text(
377    bytes: &mut usize,
378    value: Option<&str>,
379) -> Result<(), SchematicPlotContractError> {
380    value.map_or(Ok(()), |value| add_text(bytes, value))
381}
382
383fn add_text(bytes: &mut usize, value: &str) -> Result<(), SchematicPlotContractError> {
384    *bytes = bytes.checked_add(value.len()).ok_or_else(item_overflow)?;
385    Ok(())
386}
387
388fn item_overflow() -> SchematicPlotContractError {
389    SchematicPlotContractError("schematic plot materialization count overflow".to_owned())
390}
391
392fn record_operations(record: &SchematicPlotRecord) -> std::slice::Iter<'_, SchematicPlotOperation> {
393    match record {
394        SchematicPlotRecord::SheetHeader(value) => value.operations.iter(),
395        SchematicPlotRecord::Connectivity(value) => value.operations.iter(),
396        SchematicPlotRecord::Annotation(value) => value.operations.iter(),
397        SchematicPlotRecord::Graphic(value) => value.operations.iter(),
398        SchematicPlotRecord::RuleArea(value) => value.operations.iter(),
399        SchematicPlotRecord::Image(value) => value.operations.iter(),
400        SchematicPlotRecord::Table(value) => value.operations.iter(),
401        SchematicPlotRecord::SymbolInstance(value) => value.operations.iter(),
402        SchematicPlotRecord::SymbolOverplot(value) => value.operations.iter(),
403        SchematicPlotRecord::Sheet(value) => value.operations.iter(),
404    }
405}
406
407fn operation_point_count(operation: &SchematicPlotOperation) -> usize {
408    let SchematicPlotOperation::Plotter(operation) = operation else {
409        return 0;
410    };
411    match operation {
412        PlotterOperation::PlotPoly(value) => value.points.len(),
413        PlotterOperation::BezierCurve(_) | PlotterOperation::FlashPadCustom(_) => 4,
414        PlotterOperation::ArcThreePoint(_) => 3,
415        _ => 0,
416    }
417}
418
419#[allow(
420    dead_code,
421    reason = "retained temporarily as a parity oracle during typed migration"
422)]
423mod legacy_json_mapping {
424    use super::*;
425
426    fn insert_optional(object: &mut Map<String, Value>, name: &str, value: Option<Value>) {
427        if let Some(value) = value {
428            object.insert(name.to_owned(), value);
429        }
430    }
431
432    const fn fill_name(fill: PlotterFill) -> &'static str {
433        match fill {
434            PlotterFill::NoFill => "NO_FILL",
435            PlotterFill::FilledShape => "FILLED_SHAPE",
436            PlotterFill::FilledWithBackgroundBodyColor => "FILLED_WITH_BG_BODYCOLOR",
437            PlotterFill::FilledWithColor => "FILLED_WITH_COLOR",
438            PlotterFill::Hatch => "HATCH",
439            PlotterFill::ReverseHatch => "REVERSE_HATCH",
440            PlotterFill::CrossHatch => "CROSS_HATCH",
441        }
442    }
443
444    const fn line_style_name(style: PlotterLineStyle) -> &'static str {
445        match style {
446            PlotterLineStyle::Default => "DEFAULT",
447            PlotterLineStyle::Solid => "SOLID",
448            PlotterLineStyle::Dash => "DASH",
449            PlotterLineStyle::Dot => "DOT",
450            PlotterLineStyle::DashDot => "DASH_DOT",
451            PlotterLineStyle::DashDotDot => "DASH_DOT_DOT",
452        }
453    }
454
455    const fn h_align_name(align: PlotterTextHAlign) -> &'static str {
456        match align {
457            PlotterTextHAlign::Left => "GR_TEXT_H_ALIGN_LEFT",
458            PlotterTextHAlign::Center => "GR_TEXT_H_ALIGN_CENTER",
459            PlotterTextHAlign::Right => "GR_TEXT_H_ALIGN_RIGHT",
460        }
461    }
462
463    const fn v_align_name(align: PlotterTextVAlign) -> &'static str {
464        match align {
465            PlotterTextVAlign::Top => "GR_TEXT_V_ALIGN_TOP",
466            PlotterTextVAlign::Center => "GR_TEXT_V_ALIGN_CENTER",
467            PlotterTextVAlign::Bottom => "GR_TEXT_V_ALIGN_BOTTOM",
468        }
469    }
470
471    fn text_json(value: &PlotterText, index: usize, hyperlink: Option<&str>) -> Value {
472        let mut object = json!({
473            "kind": "Text", "index": index, "x": value.x, "y": value.y,
474            "text": value.text, "color": value.color, "orient_deg": value.orient_deg,
475            "size_x_nm": value.size_x_nm, "size_y_nm": value.size_y_nm,
476            "h_align": h_align_name(value.h_align), "v_align": v_align_name(value.v_align),
477            "pen_width_nm": value.pen_width_nm, "italic": value.italic, "bold": value.bold,
478            "multiline": value.multiline, "font_face": value.font_face,
479        })
480        .as_object()
481        .expect("text JSON object")
482        .clone();
483        insert_optional(
484            &mut object,
485            "layer",
486            value.layer.as_ref().map(|value| json!(value)),
487        );
488        insert_optional(
489            &mut object,
490            "context",
491            hyperlink.map(|href| json!({"hyperlink": {"href": href}})),
492        );
493        Value::Object(object)
494    }
495
496    #[allow(
497        clippy::too_many_lines,
498        reason = "the exhaustive contract mapping is a compile-time ratchet"
499    )]
500    fn operation_json(operation: &SchematicPlotOperation, index: usize) -> Value {
501        match operation {
502            SchematicPlotOperation::Text(value) => {
503                text_json(&value.text, index, value.hyperlink_href.as_deref())
504            }
505            SchematicPlotOperation::StyledThickSegment(value) => {
506                let segment = &value.segment;
507                json!({"kind": "ThickSegment", "index": index,
508                "start_x": segment.start_x, "start_y": segment.start_y,
509                "end_x": segment.end_x, "end_y": segment.end_y,
510                "width_nm": segment.width_nm, "stroke_color": value.stroke_color})
511            }
512            SchematicPlotOperation::PlotImage(value) => {
513                let mut object = json!({"kind": "PlotImage", "index": index,
514                "x": value.x, "y": value.y, "width_nm": value.width_nm,
515                "height_nm": value.height_nm, "scale": value.scale,
516                "image_data_b64": value.image_data_b64, "image_format": value.image_format})
517                .as_object()
518                .expect("image JSON object")
519                .clone();
520                insert_optional(
521                    &mut object,
522                    "stroke_color",
523                    value.stroke_color.as_ref().map(|value| json!(value)),
524                );
525                Value::Object(object)
526            }
527            SchematicPlotOperation::StartSymbolPinBlock(value) => {
528                let attrs = [
529                    ("primitive", value.extra_attrs.primitive.as_str()),
530                    ("object-type", value.extra_attrs.object_type.as_str()),
531                    ("pin", value.extra_attrs.pin.as_str()),
532                    ("symbol-uuid", value.extra_attrs.symbol_uuid.as_str()),
533                    ("designator", value.extra_attrs.designator.as_str()),
534                    ("lib-pin-uuid", value.extra_attrs.lib_pin_uuid.as_str()),
535                ]
536                .into_iter()
537                .filter(|(_, value)| !value.is_empty())
538                .map(|(name, value)| (name.to_owned(), json!(value)))
539                .collect::<Map<_, _>>();
540                json!({"kind": "StartBlock", "index": index, "label": value.label,
541                "data_uuid": value.data_uuid, "data_ref": "symbol_pin",
542                "object_id": value.object_id, "extra_attrs": attrs})
543            }
544            SchematicPlotOperation::StartSheetPinBlock(value) => {
545                let attrs = [
546                    ("primitive", value.extra_attrs.primitive.as_str()),
547                    ("object-type", value.extra_attrs.object_type.as_str()),
548                    ("sheet-uuid", value.extra_attrs.sheet_uuid.as_str()),
549                    ("sheet-name", value.extra_attrs.sheet_name.as_str()),
550                    ("sheet-file", value.extra_attrs.sheet_file.as_str()),
551                    ("pin", value.extra_attrs.pin.as_str()),
552                    ("pin-name", value.extra_attrs.pin_name.as_str()),
553                    ("shape", value.extra_attrs.shape.as_str()),
554                ]
555                .into_iter()
556                .filter(|(_, value)| !value.is_empty())
557                .map(|(name, value)| (name.to_owned(), json!(value)))
558                .collect::<Map<_, _>>();
559                json!({"kind": "StartBlock", "index": index, "label": value.label,
560                "data_uuid": value.data_uuid, "data_ref": "sheet_pin",
561                "object_id": value.object_id, "extra_attrs": attrs})
562            }
563            SchematicPlotOperation::EndBlock => json!({"kind": "EndBlock", "index": index}),
564            SchematicPlotOperation::Plotter(operation) => plotter_operation_json(operation, index),
565        }
566    }
567
568    fn plotter_operation_json(operation: &PlotterOperation, index: usize) -> Value {
569        match operation {
570            PlotterOperation::Rect(value) => styled_shape_json(
571                json!({"kind": "Rect", "index": index, "x1": value.x1, "y1": value.y1,
572                "x2": value.x2, "y2": value.y2, "fill": fill_name(value.fill),
573                "width_nm": value.width_nm, "corner_radius_nm": value.corner_radius_nm}),
574                value.layer.as_deref(),
575                value.stroke_color.as_deref(),
576                value.fill_color.as_deref(),
577                value.line_style,
578            ),
579            PlotterOperation::PlotPoly(value) => styled_shape_json(
580                json!({"kind": "PlotPoly", "index": index, "points": value.points,
581                "fill": fill_name(value.fill), "width_nm": value.width_nm}),
582                value.layer.as_deref(),
583                value.stroke_color.as_deref(),
584                value.fill_color.as_deref(),
585                value.line_style,
586            ),
587            PlotterOperation::Circle(value) => circle_json(value, index),
588            PlotterOperation::Text(value) => text_json(value, index, None),
589            PlotterOperation::ArcThreePoint(value) => styled_shape_json(
590                json!({"kind": "ArcThreePoint", "index": index,
591                "start_x": value.start_x, "start_y": value.start_y,
592                "mid_x": value.mid_x, "mid_y": value.mid_y,
593                "end_x": value.end_x, "end_y": value.end_y,
594                "fill": fill_name(value.fill), "width_nm": value.width_nm}),
595                value.layer.as_deref(),
596                value.stroke_color.as_deref(),
597                value.fill_color.as_deref(),
598                value.line_style,
599            ),
600            PlotterOperation::BezierCurve(value) => styled_shape_json(
601                json!({"kind": "BezierCurve", "index": index,
602                "start_x": value.start_x, "start_y": value.start_y,
603                "ctrl1_x": value.ctrl1_x, "ctrl1_y": value.ctrl1_y,
604                "ctrl2_x": value.ctrl2_x, "ctrl2_y": value.ctrl2_y,
605                "end_x": value.end_x, "end_y": value.end_y,
606                "width_nm": value.width_nm, "tolerance_nm": value.tolerance_nm}),
607                value.layer.as_deref(),
608                value.stroke_color.as_deref(),
609                None,
610                value.line_style,
611            ),
612            PlotterOperation::ThickSegment(value) => thick_segment_json(value, index),
613            PlotterOperation::FlashPadCircle(_)
614            | PlotterOperation::FlashPadOval(_)
615            | PlotterOperation::FlashPadRect(_)
616            | PlotterOperation::FlashPadRoundRect(_)
617            | PlotterOperation::FlashPadCustom(_)
618            | PlotterOperation::FlashPadTrapez(_) => {
619                unreachable!(
620                    "operations outside the schematic vocabulary are rejected by the producer"
621                )
622            }
623        }
624    }
625
626    fn styled_shape_json(
627        base: Value,
628        layer: Option<&str>,
629        stroke_color: Option<&str>,
630        fill_color: Option<&str>,
631        line_style: Option<PlotterLineStyle>,
632    ) -> Value {
633        let mut object = base.as_object().expect("shape JSON object").clone();
634        insert_optional(&mut object, "layer", layer.map(|value| json!(value)));
635        insert_optional(
636            &mut object,
637            "stroke_color",
638            stroke_color.map(|value| json!(value)),
639        );
640        insert_optional(
641            &mut object,
642            "fill_color",
643            fill_color.map(|value| json!(value)),
644        );
645        insert_optional(
646            &mut object,
647            "line_style",
648            line_style.map(|value| json!(line_style_name(value))),
649        );
650        Value::Object(object)
651    }
652
653    fn circle_json(value: &PlotterCircle, index: usize) -> Value {
654        let styled = styled_shape_json(
655            json!({"kind": "Circle", "index": index, "cx": value.cx, "cy": value.cy,
656            "diameter_nm": value.diameter_nm, "fill": fill_name(value.fill),
657            "width_nm": value.width_nm}),
658            value.layer.as_deref(),
659            value.stroke_color.as_deref(),
660            value.fill_color.as_deref(),
661            value.line_style,
662        );
663        let mut object = styled.as_object().expect("circle JSON object").clone();
664        insert_pad_fields(
665            &mut object,
666            value.role.as_deref(),
667            &value.layers,
668            value.mask_margin_nm,
669            value.pad_size_x_nm,
670            value.pad_size_y_nm,
671        );
672        Value::Object(object)
673    }
674
675    fn thick_segment_json(value: &ThickSegment, index: usize) -> Value {
676        let mut object = json!({"kind": "ThickSegment", "index": index,
677        "start_x": value.start_x, "start_y": value.start_y,
678        "end_x": value.end_x, "end_y": value.end_y, "width_nm": value.width_nm})
679        .as_object()
680        .expect("segment JSON object")
681        .clone();
682        insert_optional(
683            &mut object,
684            "layer",
685            value.layer.as_deref().map(|value| json!(value)),
686        );
687        insert_pad_fields(
688            &mut object,
689            value.role.as_deref(),
690            &value.layers,
691            value.mask_margin_nm,
692            value.pad_size_x_nm,
693            value.pad_size_y_nm,
694        );
695        Value::Object(object)
696    }
697
698    fn insert_pad_fields(
699        object: &mut Map<String, Value>,
700        role: Option<&str>,
701        layers: &[String],
702        mask_margin_nm: Option<i64>,
703        pad_size_x_nm: Option<i64>,
704        pad_size_y_nm: Option<i64>,
705    ) {
706        insert_optional(object, "role", role.map(|value| json!(value)));
707        if !layers.is_empty() {
708            object.insert("layers".to_owned(), json!(layers));
709        }
710        insert_optional(
711            object,
712            "mask_margin_nm",
713            mask_margin_nm.map(|value| json!(value)),
714        );
715        insert_optional(
716            object,
717            "pad_size_x_nm",
718            pad_size_x_nm.map(|value| json!(value)),
719        );
720        insert_optional(
721            object,
722            "pad_size_y_nm",
723            pad_size_y_nm.map(|value| json!(value)),
724        );
725    }
726
727    fn document_json(document: &SchematicPlotDocument) -> Value {
728        let records = document.records.iter().map(record_json).collect::<Vec<_>>();
729        let mut object = json!({
730        "schema": "kicad.plotter_ir.a0", "source_kind": "SCH",
731        "total_operations": document.records.iter().map(SchematicPlotRecord::operation_count).sum::<usize>(),
732        "records": records, "document_id": document.document_id,
733        "canvas": {"width_nm": document.canvas.width_nm, "height_nm": document.canvas.height_nm},
734        "coordinate_space": {"unit": "nm", "y_axis": "down"},
735    }).as_object().expect("document JSON object").clone();
736        insert_optional(
737            &mut object,
738            "source_path",
739            document.source_path.as_ref().map(|value| json!(value)),
740        );
741        Value::Object(object)
742    }
743
744    #[allow(
745        clippy::too_many_lines,
746        reason = "the exhaustive record mapping is a compile-time ratchet"
747    )]
748    fn record_json(record: &SchematicPlotRecord) -> Value {
749        match record {
750            SchematicPlotRecord::SheetHeader(value) => header_record_json(value),
751            SchematicPlotRecord::Connectivity(value) => connectivity_record_json(value),
752            SchematicPlotRecord::Annotation(value) => annotation_record_json(value),
753            SchematicPlotRecord::Graphic(value) => json!({
754                "uuid": value.uuid, "kind": value.kind.as_str(), "object_id": value.uuid,
755                "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
756            }),
757            SchematicPlotRecord::RuleArea(value) => json!({
758                "uuid": value.uuid, "kind": "rule_area", "object_id": value.uuid,
759                "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
760                "shape": value.shape.as_str(), "locked": value.locked,
761                "exclude_from_sim": value.exclude_from_sim, "in_bom": value.in_bom,
762                "on_board": value.on_board, "dnp": value.dnp,
763            }),
764            SchematicPlotRecord::Image(value) => json!({
765                "uuid": value.uuid, "kind": "image", "object_id": value.uuid,
766                "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
767                "scale": value.scale, "image_format": value.image_format,
768                "width_nm": value.width_nm, "height_nm": value.height_nm,
769            }),
770            SchematicPlotRecord::Table(value) => json!({
771                "uuid": value.uuid, "kind": "table", "object_id": value.uuid,
772                "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
773                "cell_count": value.cell_count,
774            }),
775            SchematicPlotRecord::SymbolInstance(value) => json!({
776                "uuid": value.uuid, "kind": "symbol_instance",
777                "object_id": if value.lib_id.is_empty() { &value.uuid } else { &value.lib_id },
778                "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
779                "lib_id": value.lib_id, "lib_name": value.lib_name, "reference": value.reference,
780                "at_x_nm": value.at_x_nm, "at_y_nm": value.at_y_nm,
781                "at_angle_deg": value.at_angle_deg, "mirror": value.mirror,
782                "unit": value.unit, "convert": value.convert, "in_bom": value.in_bom,
783                "on_board": value.on_board, "dnp": value.dnp,
784                "exclude_from_sim": value.exclude_from_sim, "in_pos_files": value.in_pos_files,
785            }),
786            SchematicPlotRecord::SymbolOverplot(value) => json!({
787                "uuid": value.uuid, "kind": "symbol_overplot",
788                "object_id": if value.lib_id.is_empty() { &value.source_symbol_uuid } else { &value.lib_id },
789                "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
790                "source_symbol_uuid": value.source_symbol_uuid, "lib_id": value.lib_id,
791            }),
792            SchematicPlotRecord::Sheet(value) => json!({
793                "uuid": value.uuid, "kind": "sheet", "object_id": value.sheet_name,
794                "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
795                "sheet_name": value.sheet_name, "sheet_file": value.sheet_file,
796                "at_x_nm": value.at_x_nm, "at_y_nm": value.at_y_nm,
797                "size_x_nm": value.size_x_nm, "size_y_nm": value.size_y_nm, "dnp": value.dnp,
798            }),
799        }
800    }
801
802    fn operations_json(operations: &[SchematicPlotOperation]) -> Vec<Value> {
803        operations
804            .iter()
805            .enumerate()
806            .map(|(index, value)| operation_json(value, index))
807            .collect()
808    }
809
810    fn header_record_json(value: &crate::SchematicSheetHeaderRecord) -> Value {
811        let mut object = json!({
812        "uuid": value.uuid, "kind": "sheet_header", "object_id": value.uuid,
813        "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
814        "paper_size": value.paper_size, "paper_width_mm": value.paper_width_mm,
815        "paper_height_mm": value.paper_height_mm, "paper_portrait": value.paper_portrait,
816        "sheet_width_nm": value.sheet_width_nm, "sheet_height_nm": value.sheet_height_nm,
817        "version": value.version, "generator": value.generator,
818        "generator_version": value.generator_version,
819    })
820    .as_object()
821    .expect("header JSON object")
822    .clone();
823        insert_optional(
824            &mut object,
825            "title_block",
826            value.title_block.as_ref().map(|title| {
827                json!({
828                    "title": title.title, "date": title.date, "rev": title.revision,
829                    "company": title.company, "comments": title.comments,
830                })
831            }),
832        );
833        Value::Object(object)
834    }
835
836    fn connectivity_record_json(value: &SchematicConnectivityRecord) -> Value {
837        let mut object = json!({
838        "uuid": value.uuid, "kind": value.kind.as_str(), "object_id": value.uuid,
839        "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
840    })
841    .as_object()
842    .expect("connectivity JSON object")
843    .clone();
844        if value.kind == SchematicConnectivityRecordKind::Junction && value.junction_color_authored
845        {
846            object.insert(
847                "color".to_owned(),
848                value
849                    .junction_color
850                    .as_ref()
851                    .map_or(Value::Null, |value| json!(value)),
852            );
853        }
854        Value::Object(object)
855    }
856
857    fn annotation_record_json(value: &SchematicAnnotationRecord) -> Value {
858        let mut object = json!({
859        "uuid": value.uuid, "kind": value.kind.as_str(), "object_id": value.object_id,
860        "operation_count": value.operations.len(), "operations": operations_json(&value.operations),
861    })
862    .as_object()
863    .expect("annotation JSON object")
864    .clone();
865        insert_optional(
866            &mut object,
867            "text",
868            value.text.as_ref().map(|value| json!(value)),
869        );
870        insert_optional(
871            &mut object,
872            "shape",
873            value.shape.as_ref().map(|value| json!(value)),
874        );
875        insert_optional(
876            &mut object,
877            "at_x_nm",
878            value.at_x_nm.map(|value| json!(value)),
879        );
880        insert_optional(
881            &mut object,
882            "at_y_nm",
883            value.at_y_nm.map(|value| json!(value)),
884        );
885        insert_optional(
886            &mut object,
887            "length_nm",
888            value.length_nm.map(|value| json!(value)),
889        );
890        Value::Object(object)
891    }
892}
893
894struct LimitedWriter {
895    written: usize,
896    limit: usize,
897}
898
899impl LimitedWriter {
900    const fn new(limit: usize) -> Self {
901        Self { written: 0, limit }
902    }
903}
904
905impl Write for LimitedWriter {
906    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
907        let next = self
908            .written
909            .checked_add(buffer.len())
910            .filter(|next| *next <= self.limit)
911            .ok_or_else(|| io::Error::other(format!("output exceeds {} bytes", self.limit)))?;
912        self.written = next;
913        Ok(buffer.len())
914    }
915
916    fn flush(&mut self) -> io::Result<()> {
917        Ok(())
918    }
919}
920
921#[cfg(test)]
922mod tests {
923    use super::*;
924    use crate::{SchematicPlotContext, SchematicPlotVariables, schematic_plot_document};
925
926    const SOURCE: &str = r#"(kicad_sch
927      (version 20240101)
928      (generator eeschema)
929      (generator_version "10.0")
930      (uuid "contract-test")
931      (paper "A4")
932      (wire (pts (xy 1 2) (xy 3 4))
933        (stroke (width 0) (type default)) (uuid "wire-1")))"#;
934
935    fn document() -> SchematicPlotDocument {
936        schematic_plot_document(
937            SOURCE,
938            &SchematicPlotContext {
939                source_path: Some("contract-test.kicad_sch".to_owned()),
940                document_id: Some("contract-test".to_owned()),
941                sheet_index: 1,
942                sheet_count: 1,
943                sheet_path: "/".to_owned(),
944                sheet_instance_path: "/contract-test".to_owned(),
945                sheet_name: "Root".to_owned(),
946                project_variables: SchematicPlotVariables::default(),
947                worksheet_source: None,
948            },
949        )
950        .expect("plot document")
951    }
952
953    #[test]
954    fn projection_rejects_publicly_constructible_invalid_documents() {
955        let mut invalid_document = document();
956        invalid_document.records.clear();
957        assert!(
958            schematic_plot_document_json(&invalid_document,)
959                .unwrap_err()
960                .to_string()
961                .contains("validation failed")
962        );
963
964        let mut document = document();
965        let SchematicPlotRecord::SheetHeader(header) = &mut document.records[0] else {
966            panic!("first producer record must be the sheet header");
967        };
968        header.operations.push(SchematicPlotOperation::Plotter(
969            PlotterOperation::FlashPadCircle(crate::FlashPadCircle {
970                x: 0,
971                y: 0,
972                diameter_nm: 1,
973                layers: Vec::new(),
974                mask_margin_nm: 0,
975            }),
976        ));
977        assert!(
978            schematic_plot_document_json(&document)
979                .unwrap_err()
980                .to_string()
981                .contains("outside the schematic plot vocabulary")
982        );
983    }
984}