1use crate::generated::board_plot_document::{
4 BoardDimensionType, BoardFootprintChildAttrs, BoardFootprintChildAttrsFootprintGraphicKind,
5 BoardFootprintChildAttrsPrimitive, BoardFootprintChildRef, BoardFootprintLayerRole,
6 BoardFootprintOperation, BoardFootprintPadBlockAttrs, BoardFootprintPadBlockAttrsPrimitive,
7 BoardFootprintPlotRecord, BoardFootprintStartBlockOperation,
8 BoardFootprintStartBlockOperationDataRef, BoardFootprintTextOperation, BoardPlotDocumentA0,
9 BoardPlotRecord, BoardTextBoxPlotRecord, BoardTextPlotRecord, CircleOperation,
10 DimensionPlotRecord, FlashPadCircleOperation, PlotterDrillRole as BoardDrillRole,
11 PlotterFill as BoardFill, PlotterOperation as BoardOperation,
12 PlotterTextRenderCacheCoordinateSpace, PlotterViaFlashRole, RectOperation, TablePlotRecord,
13 TextOperation, ThickSegmentOperation,
14};
15use crate::{ValidationError, validation_error};
16
17pub fn validate_board_plot_document(document: &BoardPlotDocumentA0) -> Result<(), ValidationError> {
19 if document.schema != "kicad.plotter_ir.a0"
20 || document.source_kind != "PCB"
21 || document.coordinate_space.unit != "nm"
22 || document.coordinate_space.y_axis != "down"
23 {
24 return Err(validation_error(
25 "unsupported_contract",
26 "$",
27 "board plot document identity and coordinate space must match a0",
28 ));
29 }
30 let mut total_operations = 0usize;
31 let mut saw_footprint = false;
32 for (record_index, record) in document.records.iter().enumerate() {
33 if matches!(record, BoardPlotRecord::BoardFootprintPlotRecord(_)) {
34 saw_footprint = true;
35 } else if saw_footprint {
36 return Err(validation_error(
37 "invalid_board_record_order",
38 format!("$.records[{record_index}]"),
39 "embedded footprint records form the terminal board record phase",
40 ));
41 }
42 let (declared, operation_count) = validate_board_record(record, record_index)?;
43 if declared != operation_count {
44 return Err(validation_error(
45 "operation_count_mismatch",
46 format!("$.records[{record_index}].operation_count"),
47 "operation_count must equal the operation array length",
48 ));
49 }
50 total_operations = total_operations.saturating_add(operation_count);
51 }
52 if document.total_operations as usize != total_operations {
53 return Err(validation_error(
54 "operation_count_mismatch",
55 "$.total_operations",
56 "total_operations must equal all record operation counts",
57 ));
58 }
59 Ok(())
60}
61
62fn validate_board_record(
63 record: &BoardPlotRecord,
64 record_index: usize,
65) -> Result<(usize, usize), ValidationError> {
66 let counts = match record {
67 BoardPlotRecord::BoardGraphicPlotRecord(value) => {
68 validate_board_graphic_operations(&value.operations, record_index)?;
69 (value.operation_count as usize, value.operations.len())
70 }
71 BoardPlotRecord::TrackSegmentPlotRecord(value) => {
72 validate_track_segment_operations(&value.operations, record_index)?;
73 (value.operation_count as usize, value.operations.len())
74 }
75 BoardPlotRecord::TrackArcPlotRecord(value) => {
76 validate_track_arc_operations(&value.operations, record_index)?;
77 (value.operation_count as usize, value.operations.len())
78 }
79 BoardPlotRecord::ViaPlotRecord(value) => {
80 validate_via_operations(&value.operations, record_index)?;
81 (value.operation_count as usize, value.operations.len())
82 }
83 BoardPlotRecord::TablePlotRecord(value) => {
84 validate_table_operations(value, record_index)?;
85 (value.operation_count as usize, value.operations.len())
86 }
87 BoardPlotRecord::DimensionPlotRecord(value) => {
88 validate_dimension_operations(value, record_index)?;
89 (value.operation_count as usize, value.operations.len())
90 }
91 BoardPlotRecord::ZoneFillPlotRecord(value) => {
92 validate_zone_fill_operations(value, record_index)?;
93 (value.operation_count as usize, value.operations.len())
94 }
95 BoardPlotRecord::BoardTextPlotRecord(value) => {
96 validate_board_text_operations(value, record_index)?;
97 (value.operation_count as usize, value.operations.len())
98 }
99 BoardPlotRecord::BoardTextBoxPlotRecord(value) => {
100 validate_board_text_box_operations(value, record_index)?;
101 (value.operation_count as usize, value.operations.len())
102 }
103 BoardPlotRecord::BoardFootprintPlotRecord(value) => {
104 validate_board_footprint_record(value, record_index)?;
105 (value.operation_count as usize, value.operations.len())
106 }
107 };
108 Ok(counts)
109}
110
111struct FootprintChildMetadata<'a> {
112 index: u32,
113 kind: &'a str,
114 label: Option<&'a str>,
115 data_uuid: Option<&'a str>,
116 data_ref: Option<BoardFootprintChildRef>,
117 object_id: Option<&'a str>,
118 extra_attrs: Option<&'a BoardFootprintChildAttrs>,
119 layer: Option<&'a str>,
120}
121
122macro_rules! footprint_child_metadata {
123 ($value:expr) => {
124 FootprintChildMetadata {
125 index: $value.index,
126 kind: &$value.kind,
127 label: $value.label.as_deref(),
128 data_uuid: $value.data_uuid.as_deref(),
129 data_ref: $value.data_ref,
130 object_id: $value.object_id.as_deref(),
131 extra_attrs: $value.extra_attrs.as_ref(),
132 layer: $value.layer.as_deref(),
133 }
134 };
135}
136
137fn validate_board_footprint_record(
138 record: &BoardFootprintPlotRecord,
139 record_index: usize,
140) -> Result<(), ValidationError> {
141 let record_path = format!("$.records[{record_index}]");
142 if record.kind != "footprint"
143 || record.object_id != record.library_link
144 || !record.placement.angle_deg.is_finite()
145 {
146 return Err(invalid_board_footprint(
147 record_path,
148 "embedded footprint identity and finite placement must be canonical",
149 ));
150 }
151 let mut operation_index = 0usize;
152 let mut pad_phase = false;
153 let mut last_child_key: Option<(u8, u32, u32)> = None;
154 while operation_index < record.operations.len() {
155 let path = format!("$.records[{record_index}].operations[{operation_index}]");
156 match &record.operations[operation_index] {
157 BoardFootprintOperation::StartBlockOperation(start) => {
158 pad_phase = true;
159 let Some(inner) = record.operations.get(operation_index + 1) else {
160 return Err(invalid_board_footprint(
161 path,
162 "pad blocks must contain exactly one operation and an EndBlock",
163 ));
164 };
165 let Some(BoardFootprintOperation::EndBlockOperation(end)) =
166 record.operations.get(operation_index + 2)
167 else {
168 return Err(invalid_board_footprint(
169 path,
170 "pad blocks must contain exactly one operation and an EndBlock",
171 ));
172 };
173 validate_board_footprint_header(
174 start.index,
175 &start.kind,
176 operation_index,
177 "StartBlock",
178 &path,
179 )?;
180 validate_board_footprint_header(
181 board_footprint_operation_index(inner),
182 board_footprint_operation_kind(inner),
183 operation_index + 1,
184 board_footprint_expected_kind(inner),
185 &format!(
186 "$.records[{record_index}].operations[{}]",
187 operation_index + 1
188 ),
189 )?;
190 validate_board_footprint_header(
191 end.index,
192 &end.kind,
193 operation_index + 2,
194 "EndBlock",
195 &format!(
196 "$.records[{record_index}].operations[{}]",
197 operation_index + 2
198 ),
199 )?;
200 validate_board_footprint_pad_block(record, start, inner, path)?;
201 operation_index += 3;
202 }
203 BoardFootprintOperation::EndBlockOperation(_) if pad_phase => {
204 return Err(invalid_board_footprint(
205 path,
206 "EndBlock must close a complete pad block",
207 ));
208 }
209 _ if pad_phase => {
210 return Err(invalid_board_footprint(
211 path,
212 "footprint child operations cannot follow the terminal pad-block phase",
213 ));
214 }
215 operation => {
216 validate_board_footprint_child(
217 record,
218 operation,
219 operation_index,
220 &mut last_child_key,
221 path,
222 )?;
223 operation_index += 1;
224 }
225 }
226 }
227 Ok(())
228}
229
230fn validate_board_footprint_child(
231 record: &BoardFootprintPlotRecord,
232 operation: &BoardFootprintOperation,
233 expected_index: usize,
234 last_key: &mut Option<(u8, u32, u32)>,
235 path: String,
236) -> Result<(), ValidationError> {
237 let metadata = match operation {
238 BoardFootprintOperation::ThickSegmentOperation(value) => footprint_child_metadata!(value),
239 BoardFootprintOperation::ArcThreePointOperation(value) => footprint_child_metadata!(value),
240 BoardFootprintOperation::CircleOperation(value) => footprint_child_metadata!(value),
241 BoardFootprintOperation::RectOperation(value) => footprint_child_metadata!(value),
242 BoardFootprintOperation::PlotPolyOperation(value) => footprint_child_metadata!(value),
243 BoardFootprintOperation::TextOperation(value) => {
244 validate_board_footprint_text(value, &path)?;
245 footprint_child_metadata!(value)
246 }
247 BoardFootprintOperation::BezierCurveOperation(_)
248 | BoardFootprintOperation::FlashPadCircleOperation(_)
249 | BoardFootprintOperation::FlashPadOvalOperation(_)
250 | BoardFootprintOperation::FlashPadRectOperation(_)
251 | BoardFootprintOperation::FlashPadRoundRectOperation(_)
252 | BoardFootprintOperation::FlashPadCustomOperation(_)
253 | BoardFootprintOperation::FlashPadTrapezOperation(_)
254 | BoardFootprintOperation::StartBlockOperation(_)
255 | BoardFootprintOperation::EndBlockOperation(_) => {
256 return Err(invalid_board_footprint(
257 path,
258 "direct footprint children admit only emitted text and graphic geometry",
259 ));
260 }
261 };
262 validate_board_footprint_header(
263 metadata.index,
264 metadata.kind,
265 expected_index,
266 board_footprint_expected_kind(operation),
267 &path,
268 )?;
269 let (Some(label), Some(data_uuid), Some(data_ref), Some(object_id), Some(attrs)) = (
270 metadata.label,
271 metadata.data_uuid,
272 metadata.data_ref,
273 metadata.object_id,
274 metadata.extra_attrs,
275 ) else {
276 return Err(invalid_board_footprint(
277 path,
278 "direct footprint child metadata fields are all required together",
279 ));
280 };
281 if label.is_empty()
282 || data_uuid.is_empty()
283 || object_id.is_empty()
284 || data_ref != attrs.footprint_primitive
285 || attrs.component != record.reference
286 || attrs.component_uid != record.uuid
287 || attrs.component_uuid != record.uuid
288 || attrs.footprint != record.library_link
289 || attrs.layer_name.as_deref() != metadata.layer
290 || attrs.layer_name.is_some() != attrs.layer_role.is_some()
291 || attrs
292 .layer_name
293 .as_deref()
294 .is_some_and(|layer| attrs.layer_role != Some(board_footprint_layer_role(layer)))
295 {
296 return Err(invalid_board_footprint(
297 path,
298 "child metadata must identify its source, parent footprint, and operation layer",
299 ));
300 }
301 validate_board_footprint_child_shape(operation, data_ref, attrs, &path)?;
302 let key = (
303 board_footprint_child_phase(data_ref),
304 attrs.footprint_object_index,
305 attrs.footprint_subop_index.unwrap_or(0),
306 );
307 if last_key.is_some_and(|previous| previous >= key) {
308 return Err(invalid_board_footprint(
309 path,
310 "footprint children must remain in canonical source-kind and object order",
311 ));
312 }
313 *last_key = Some(key);
314 Ok(())
315}
316
317fn validate_board_footprint_child_shape(
318 operation: &BoardFootprintOperation,
319 data_ref: BoardFootprintChildRef,
320 attrs: &BoardFootprintChildAttrs,
321 path: &str,
322) -> Result<(), ValidationError> {
323 let text_ref = matches!(
324 data_ref,
325 BoardFootprintChildRef::Property
326 | BoardFootprintChildRef::FpText
327 | BoardFootprintChildRef::FpTextBox
328 );
329 let is_text = matches!(operation, BoardFootprintOperation::TextOperation(_));
330 let graphic_kind = match operation {
331 BoardFootprintOperation::ThickSegmentOperation(value) => {
332 if value.stroke_color.is_some() {
333 return Err(invalid_board_footprint(
334 path.to_owned(),
335 "embedded footprint segments do not emit stroke_color",
336 ));
337 }
338 Some(if data_ref == BoardFootprintChildRef::FpTextBox {
339 BoardFootprintChildAttrsFootprintGraphicKind::TextBoxBorder
340 } else {
341 BoardFootprintChildAttrsFootprintGraphicKind::Line
342 })
343 }
344 BoardFootprintOperation::ArcThreePointOperation(_) => {
345 Some(BoardFootprintChildAttrsFootprintGraphicKind::Arc)
346 }
347 BoardFootprintOperation::CircleOperation(_) => {
348 Some(BoardFootprintChildAttrsFootprintGraphicKind::Circle)
349 }
350 BoardFootprintOperation::RectOperation(_) => {
351 Some(if data_ref == BoardFootprintChildRef::FpTextBox {
352 BoardFootprintChildAttrsFootprintGraphicKind::TextBoxBorder
353 } else {
354 BoardFootprintChildAttrsFootprintGraphicKind::Rect
355 })
356 }
357 BoardFootprintOperation::PlotPolyOperation(_) => {
358 Some(BoardFootprintChildAttrsFootprintGraphicKind::Poly)
359 }
360 _ => None,
361 };
362 let valid_ref = match operation {
363 BoardFootprintOperation::TextOperation(_) => text_ref,
364 BoardFootprintOperation::ThickSegmentOperation(_) => matches!(
365 data_ref,
366 BoardFootprintChildRef::FpTextBox | BoardFootprintChildRef::FpLine
367 ),
368 BoardFootprintOperation::ArcThreePointOperation(_) => {
369 data_ref == BoardFootprintChildRef::FpArc
370 }
371 BoardFootprintOperation::CircleOperation(_) => data_ref == BoardFootprintChildRef::FpCircle,
372 BoardFootprintOperation::RectOperation(_) => matches!(
373 data_ref,
374 BoardFootprintChildRef::FpTextBox | BoardFootprintChildRef::FpRect
375 ),
376 BoardFootprintOperation::PlotPolyOperation(_) => data_ref == BoardFootprintChildRef::FpPoly,
377 _ => false,
378 };
379 let shape_valid = if is_text {
380 attrs.primitive == BoardFootprintChildAttrsPrimitive::FootprintText
381 && attrs.footprint_text_role.is_some()
382 && attrs.footprint_graphic_kind.is_none()
383 && (data_ref == BoardFootprintChildRef::Property) == attrs.property_name.is_some()
384 && (data_ref == BoardFootprintChildRef::FpText) == attrs.fp_text_type.is_some()
385 } else {
386 attrs.primitive == BoardFootprintChildAttrsPrimitive::FootprintGraphic
387 && attrs.footprint_text_role.is_none()
388 && attrs.property_name.is_none()
389 && attrs.fp_text_type.is_none()
390 && attrs.footprint_graphic_kind == graphic_kind
391 };
392 let subop_required = matches!(
393 data_ref,
394 BoardFootprintChildRef::FpTextBox
395 | BoardFootprintChildRef::FpLine
396 | BoardFootprintChildRef::FpArc
397 );
398 if valid_ref && shape_valid && (attrs.footprint_subop_index.is_some() == subop_required) {
399 Ok(())
400 } else {
401 Err(invalid_board_footprint(
402 path.to_owned(),
403 "child ref, primitive, and typed attributes must match the operation shape",
404 ))
405 }
406}
407
408fn board_footprint_layer_role(layer: &str) -> BoardFootprintLayerRole {
409 if layer.ends_with(".Cu") || matches!(layer, "*.Cu" | "F&B.Cu") {
410 BoardFootprintLayerRole::Copper
411 } else if layer.ends_with(".SilkS") {
412 BoardFootprintLayerRole::Silkscreen
413 } else if layer.ends_with(".Mask") || layer == "*.Mask" {
414 BoardFootprintLayerRole::Soldermask
415 } else if layer.ends_with(".Paste") {
416 BoardFootprintLayerRole::Paste
417 } else if layer.ends_with(".Fab") {
418 BoardFootprintLayerRole::Fab
419 } else if layer.ends_with(".Courtyard") {
420 BoardFootprintLayerRole::Courtyard
421 } else if layer == "Edge.Cuts" {
422 BoardFootprintLayerRole::BoardOutline
423 } else if layer == "DRILLS" {
424 BoardFootprintLayerRole::Drill
425 } else if layer.ends_with(".User") || layer.starts_with("User.") {
426 BoardFootprintLayerRole::User
427 } else {
428 BoardFootprintLayerRole::Other
429 }
430}
431
432fn board_footprint_child_phase(value: BoardFootprintChildRef) -> u8 {
433 match value {
434 BoardFootprintChildRef::Property => 0,
435 BoardFootprintChildRef::FpText => 1,
436 BoardFootprintChildRef::FpTextBox => 2,
437 BoardFootprintChildRef::FpLine => 3,
438 BoardFootprintChildRef::FpArc => 4,
439 BoardFootprintChildRef::FpCircle => 5,
440 BoardFootprintChildRef::FpRect => 6,
441 BoardFootprintChildRef::FpPoly => 7,
442 }
443}
444
445fn validate_board_footprint_pad_block(
446 record: &BoardFootprintPlotRecord,
447 start: &BoardFootprintStartBlockOperation,
448 inner: &BoardFootprintOperation,
449 path: String,
450) -> Result<(), ValidationError> {
451 let attrs = &start.extra_attrs;
452 let pad_number = attrs.pad_number.as_deref();
453 let pad_number_matches = pad_number
454 .map(|number| number == start.object_id)
455 .unwrap_or(start.object_id == "pad");
456 let designator = match (record.reference.as_str(), pad_number) {
457 ("", None) => None,
458 ("", Some(number)) => Some(number.to_owned()),
459 (component, Some(number)) => Some(format!("{component}-{number}")),
460 (_, None) => None,
461 };
462 let layer_names = board_footprint_inner_layers(inner).join(",");
463 let common = optional_nonempty_matches(attrs.component.as_deref(), &record.reference)
464 && optional_nonempty_matches(attrs.component_uid.as_deref(), &record.uuid)
465 && optional_nonempty_matches(attrs.component_uuid.as_deref(), &record.uuid)
466 && optional_nonempty_matches(attrs.footprint.as_deref(), &record.library_link)
467 && pad_number_matches
468 && attrs.pad_designator.as_deref() == designator.as_deref()
469 && attrs
470 .pad_type
471 .as_ref()
472 .is_none_or(|value| !value.is_empty())
473 && attrs
474 .pad_shape
475 .as_ref()
476 .is_none_or(|value| !value.is_empty())
477 && optional_nonempty_matches(attrs.layer_names.as_deref(), &layer_names)
478 && start.label == start.data_uuid;
479 if !common || !board_footprint_operation_metadata_absent(inner) {
480 return Err(invalid_board_footprint(
481 path,
482 "pad block metadata must identify its parent and remain only on StartBlock",
483 ));
484 }
485 match start.data_ref {
486 BoardFootprintStartBlockOperationDataRef::Pad => {
487 let no_hole_attrs = attrs.primitive == BoardFootprintPadBlockAttrsPrimitive::Pad
488 && attrs.hole_owner.is_none()
489 && attrs.hole_kind.is_none()
490 && attrs.hole_plating.is_none()
491 && attrs.hole_render.is_none()
492 && attrs.hole_width_mm.is_none()
493 && attrs.hole_height_mm.is_none()
494 && attrs.hole_diameter_mm.is_none();
495 let layers_are_canonical =
496 !start.layers.is_empty() || attrs.pad_type.as_deref() == Some("np_thru_hole");
497 if no_hole_attrs
498 && layers_are_canonical
499 && validate_board_footprint_pad_flash(inner, &start.layers)
500 {
501 Ok(())
502 } else {
503 Err(invalid_board_footprint(
504 path,
505 "pad blocks require one canonical layered flash and no hole attributes",
506 ))
507 }
508 }
509 BoardFootprintStartBlockOperationDataRef::PadHole => {
510 if validate_board_footprint_hole_attrs(attrs, &start.label)
511 && validate_board_footprint_drill(inner, attrs)
512 {
513 Ok(())
514 } else {
515 Err(invalid_board_footprint(
516 path,
517 "pad_hole blocks require one drill operation and complete matching hole attributes",
518 ))
519 }
520 }
521 }
522}
523
524fn optional_nonempty_matches(actual: Option<&str>, source: &str) -> bool {
525 actual == (!source.is_empty()).then_some(source)
526}
527
528fn board_footprint_inner_layers(operation: &BoardFootprintOperation) -> &[String] {
529 match operation {
530 BoardFootprintOperation::ThickSegmentOperation(value) => &value.layers,
531 BoardFootprintOperation::CircleOperation(value) => &value.layers,
532 BoardFootprintOperation::FlashPadCircleOperation(value) => &value.layers,
533 BoardFootprintOperation::FlashPadOvalOperation(value) => &value.layers,
534 BoardFootprintOperation::FlashPadRectOperation(value) => &value.layers,
535 BoardFootprintOperation::FlashPadRoundRectOperation(value) => &value.layers,
536 BoardFootprintOperation::FlashPadCustomOperation(value) => &value.layers,
537 BoardFootprintOperation::FlashPadTrapezOperation(value) => &value.layers,
538 _ => &[],
539 }
540}
541
542fn validate_board_footprint_hole_attrs(attrs: &BoardFootprintPadBlockAttrs, label: &str) -> bool {
543 use crate::generated::board_plot_document::BoardFootprintPadBlockAttrsHoleKind as HoleKind;
544 use crate::generated::board_plot_document::BoardFootprintPadBlockAttrsHolePlating as Plating;
545 let dimensions = match attrs.hole_kind {
546 Some(HoleKind::Round) => {
547 attrs.hole_diameter_mm.is_some()
548 && attrs.hole_width_mm.is_none()
549 && attrs.hole_height_mm.is_none()
550 }
551 Some(HoleKind::Slot) => {
552 attrs.hole_diameter_mm.is_none()
553 && attrs.hole_width_mm.is_some()
554 && attrs.hole_height_mm.is_some()
555 }
556 None => false,
557 };
558 let owner = label.strip_suffix(":hole");
559 attrs.primitive == BoardFootprintPadBlockAttrsPrimitive::PadHole
560 && owner.is_some()
561 && attrs.hole_owner.as_deref() == owner
562 && attrs
563 .hole_plating
564 .is_some_and(|value| matches!(value, Plating::Plated | Plating::NonPlated))
565 && attrs.hole_render.is_some()
566 && dimensions
567}
568
569fn validate_board_footprint_pad_flash(
570 operation: &BoardFootprintOperation,
571 start_layers: &[String],
572) -> bool {
573 match operation {
574 BoardFootprintOperation::FlashPadCircleOperation(value) => {
575 value.kind == "FlashPadCircle"
576 && value.role.is_none()
577 && value.mask_margin_nm.is_some()
578 && value.layers == start_layers
579 }
580 BoardFootprintOperation::FlashPadOvalOperation(value) => {
581 value.kind == "FlashPadOval" && value.layers == start_layers
582 }
583 BoardFootprintOperation::FlashPadRectOperation(value) => {
584 value.kind == "FlashPadRect" && value.layers == start_layers
585 }
586 BoardFootprintOperation::FlashPadRoundRectOperation(value) => {
587 value.kind == "FlashPadRoundRect" && value.layers == start_layers
588 }
589 BoardFootprintOperation::FlashPadCustomOperation(value) => {
590 value.kind == "FlashPadCustom"
591 && value.layers == start_layers
592 && (value.polygon_widths_nm.is_empty()
593 || value.polygon_widths_nm.len() == value.polygons.len())
594 }
595 BoardFootprintOperation::FlashPadTrapezOperation(value) => {
596 value.kind == "FlashPadTrapez" && value.layers == start_layers
597 }
598 _ => false,
599 }
600}
601
602fn validate_board_footprint_drill(
603 operation: &BoardFootprintOperation,
604 attrs: &BoardFootprintPadBlockAttrs,
605) -> bool {
606 use crate::generated::board_plot_document::BoardFootprintPadBlockAttrsHolePlating as Plating;
607 let (role, layer, layers, mask, size_x, size_y) = match operation {
608 BoardFootprintOperation::CircleOperation(value) => (
609 value.role,
610 value.layer.as_deref(),
611 value.layers.as_slice(),
612 value.mask_margin_nm.is_some(),
613 value.pad_size_x_nm.is_some(),
614 value.pad_size_y_nm.is_some(),
615 ),
616 BoardFootprintOperation::ThickSegmentOperation(value) => (
617 value.role,
618 value.layer.as_deref(),
619 value.layers.as_slice(),
620 value.mask_margin_nm.is_some(),
621 value.pad_size_x_nm.is_some(),
622 value.pad_size_y_nm.is_some(),
623 ),
624 _ => return false,
625 };
626 if layer.is_some() {
627 return false;
628 }
629 match attrs.hole_plating {
630 Some(Plating::Plated) => {
631 !layers.is_empty()
632 && role == Some(BoardDrillRole::PadDrill)
633 && !mask
634 && !size_x
635 && !size_y
636 }
637 Some(Plating::NonPlated) => {
638 role == Some(BoardDrillRole::NpthHole) && mask && size_x && size_y
639 }
640 None => false,
641 }
642}
643
644fn board_footprint_operation_metadata_absent(operation: &BoardFootprintOperation) -> bool {
645 macro_rules! absent {
646 ($value:expr) => {
647 $value.label.is_none()
648 && $value.data_uuid.is_none()
649 && $value.data_ref.is_none()
650 && $value.object_id.is_none()
651 && $value.extra_attrs.is_none()
652 };
653 }
654 match operation {
655 BoardFootprintOperation::ThickSegmentOperation(value) => absent!(value),
656 BoardFootprintOperation::ArcThreePointOperation(value) => absent!(value),
657 BoardFootprintOperation::CircleOperation(value) => absent!(value),
658 BoardFootprintOperation::RectOperation(value) => absent!(value),
659 BoardFootprintOperation::PlotPolyOperation(value) => absent!(value),
660 BoardFootprintOperation::BezierCurveOperation(value) => absent!(value),
661 BoardFootprintOperation::TextOperation(value) => absent!(value),
662 BoardFootprintOperation::FlashPadCircleOperation(value) => absent!(value),
663 BoardFootprintOperation::FlashPadOvalOperation(value) => absent!(value),
664 BoardFootprintOperation::FlashPadRectOperation(value) => absent!(value),
665 BoardFootprintOperation::FlashPadRoundRectOperation(value) => absent!(value),
666 BoardFootprintOperation::FlashPadCustomOperation(value) => absent!(value),
667 BoardFootprintOperation::FlashPadTrapezOperation(value) => absent!(value),
668 BoardFootprintOperation::StartBlockOperation(_)
669 | BoardFootprintOperation::EndBlockOperation(_) => false,
670 }
671}
672
673fn validate_board_footprint_text(
674 value: &BoardFootprintTextOperation,
675 path: &str,
676) -> Result<(), ValidationError> {
677 let marker_state = value.context.is_none()
678 && value.mirror.is_none()
679 && value.text_as_polygons.is_none()
680 && value.polyline_per_segment.is_none()
681 && value.knockout != Some(false);
682 let has_cache = value.render_cache.is_some();
683 let cache_keys = has_cache == value.render_cache_source.is_some()
684 && has_cache == value.render_cache_exact.is_some()
685 && has_cache != value.render_cache_polygons.is_empty();
686 let cache_state = match &value.render_cache {
687 Some(cache) => {
688 cache.schema == "kicad.render_cache.v1"
689 && cache.unit == "nm"
690 && cache.coordinate_space == PlotterTextRenderCacheCoordinateSpace::FootprintLocal
691 && value.render_cache_source == Some(cache.source)
692 && value.render_cache_exact == Some(cache.exact)
693 && cache.text == value.text
694 && cache.angle.is_finite()
695 && cache.knockout == value.knockout
696 && cache.polygons.len() == value.render_cache_polygons.len()
697 && cache.polygons.iter().zip(&value.render_cache_polygons).all(
698 |(polygon, exterior)| {
699 !polygon.contours.is_empty()
700 && polygon.contours.iter().all(|contour| contour.len() >= 3)
701 && points_equal(&polygon.contours[0], exterior)
702 },
703 )
704 }
705 None => value.knockout.is_none(),
706 };
707 if value.orient_deg.is_finite() && marker_state && cache_keys && cache_state {
708 Ok(())
709 } else {
710 Err(invalid_board_footprint(
711 path.to_owned(),
712 "footprint text markers and footprint-local render cache must be coherent",
713 ))
714 }
715}
716
717fn validate_board_footprint_header(
718 actual_index: u32,
719 actual_kind: &str,
720 expected_index: usize,
721 expected_kind: &str,
722 path: &str,
723) -> Result<(), ValidationError> {
724 let expected_index = u32::try_from(expected_index).map_err(|_| {
725 invalid_board_footprint(
726 format!("{path}.index"),
727 "operation index exceeds the contract range",
728 )
729 })?;
730 if actual_index != expected_index || actual_kind != expected_kind {
731 Err(invalid_board_footprint(
732 path.to_owned(),
733 "operation kind and index must match its structural variant and array position",
734 ))
735 } else {
736 Ok(())
737 }
738}
739
740fn board_footprint_operation_index(operation: &BoardFootprintOperation) -> u32 {
741 match operation {
742 BoardFootprintOperation::ThickSegmentOperation(value) => value.index,
743 BoardFootprintOperation::ArcThreePointOperation(value) => value.index,
744 BoardFootprintOperation::CircleOperation(value) => value.index,
745 BoardFootprintOperation::RectOperation(value) => value.index,
746 BoardFootprintOperation::PlotPolyOperation(value) => value.index,
747 BoardFootprintOperation::BezierCurveOperation(value) => value.index,
748 BoardFootprintOperation::TextOperation(value) => value.index,
749 BoardFootprintOperation::FlashPadCircleOperation(value) => value.index,
750 BoardFootprintOperation::FlashPadOvalOperation(value) => value.index,
751 BoardFootprintOperation::FlashPadRectOperation(value) => value.index,
752 BoardFootprintOperation::FlashPadRoundRectOperation(value) => value.index,
753 BoardFootprintOperation::FlashPadCustomOperation(value) => value.index,
754 BoardFootprintOperation::FlashPadTrapezOperation(value) => value.index,
755 BoardFootprintOperation::StartBlockOperation(value) => value.index,
756 BoardFootprintOperation::EndBlockOperation(value) => value.index,
757 }
758}
759
760fn board_footprint_operation_kind(operation: &BoardFootprintOperation) -> &str {
761 match operation {
762 BoardFootprintOperation::ThickSegmentOperation(value) => &value.kind,
763 BoardFootprintOperation::ArcThreePointOperation(value) => &value.kind,
764 BoardFootprintOperation::CircleOperation(value) => &value.kind,
765 BoardFootprintOperation::RectOperation(value) => &value.kind,
766 BoardFootprintOperation::PlotPolyOperation(value) => &value.kind,
767 BoardFootprintOperation::BezierCurveOperation(value) => &value.kind,
768 BoardFootprintOperation::TextOperation(value) => &value.kind,
769 BoardFootprintOperation::FlashPadCircleOperation(value) => &value.kind,
770 BoardFootprintOperation::FlashPadOvalOperation(value) => &value.kind,
771 BoardFootprintOperation::FlashPadRectOperation(value) => &value.kind,
772 BoardFootprintOperation::FlashPadRoundRectOperation(value) => &value.kind,
773 BoardFootprintOperation::FlashPadCustomOperation(value) => &value.kind,
774 BoardFootprintOperation::FlashPadTrapezOperation(value) => &value.kind,
775 BoardFootprintOperation::StartBlockOperation(value) => &value.kind,
776 BoardFootprintOperation::EndBlockOperation(value) => &value.kind,
777 }
778}
779
780fn board_footprint_expected_kind(operation: &BoardFootprintOperation) -> &'static str {
781 match operation {
782 BoardFootprintOperation::ThickSegmentOperation(_) => "ThickSegment",
783 BoardFootprintOperation::ArcThreePointOperation(_) => "ArcThreePoint",
784 BoardFootprintOperation::CircleOperation(_) => "Circle",
785 BoardFootprintOperation::RectOperation(_) => "Rect",
786 BoardFootprintOperation::PlotPolyOperation(_) => "PlotPoly",
787 BoardFootprintOperation::BezierCurveOperation(_) => "BezierCurve",
788 BoardFootprintOperation::TextOperation(_) => "Text",
789 BoardFootprintOperation::FlashPadCircleOperation(_) => "FlashPadCircle",
790 BoardFootprintOperation::FlashPadOvalOperation(_) => "FlashPadOval",
791 BoardFootprintOperation::FlashPadRectOperation(_) => "FlashPadRect",
792 BoardFootprintOperation::FlashPadRoundRectOperation(_) => "FlashPadRoundRect",
793 BoardFootprintOperation::FlashPadCustomOperation(_) => "FlashPadCustom",
794 BoardFootprintOperation::FlashPadTrapezOperation(_) => "FlashPadTrapez",
795 BoardFootprintOperation::StartBlockOperation(_) => "StartBlock",
796 BoardFootprintOperation::EndBlockOperation(_) => "EndBlock",
797 }
798}
799
800fn invalid_board_footprint(path: String, message: &'static str) -> ValidationError {
801 validation_error("invalid_board_footprint", path, message)
802}
803
804fn validate_dimension_operations(
805 record: &DimensionPlotRecord,
806 record_index: usize,
807) -> Result<(), ValidationError> {
808 if record.kind != "dimension"
809 || record.object_id != "dimension"
810 || record.layers.is_empty()
811 || !record.layers.windows(2).all(|pair| pair[0] < pair[1])
812 {
813 return Err(invalid_dimension(
814 format!("$.records[{record_index}]"),
815 "dimension identity must be canonical and layers must be nonempty, sorted, and unique",
816 ));
817 }
818 let mut saw_text = false;
819 let mut marker_count = 0usize;
820 for (operation_index, operation) in record.operations.iter().enumerate() {
821 let path = format!("$.records[{record_index}].operations[{operation_index}]");
822 match operation {
823 BoardOperation::TextOperation(value) => {
824 if operation_index != 0 || saw_text || value.index as usize != operation_index {
825 return Err(invalid_dimension(
826 path,
827 "dimension faced text appears at most once and first",
828 ));
829 }
830 saw_text = true;
831 validate_text_payload(value, &path)?;
832 let layer_is_declared = value
833 .layer
834 .as_ref()
835 .is_some_and(|layer| record.layers.binary_search(layer).is_ok());
836 if value.font_face.is_empty() || !layer_is_declared {
837 return Err(invalid_dimension(
838 path,
839 "dimension Text must be faced and use one declared layer",
840 ));
841 }
842 }
843 BoardOperation::ThickSegmentOperation(value) => {
844 if value.index as usize != operation_index
845 || value.kind != "ThickSegment"
846 || !dimension_layer_is_declared(value.layer.as_deref(), &record.layers)
847 || !table_segment_has_graphic_state(value)
848 {
849 return Err(invalid_dimension(
850 path,
851 "dimension segments require exact kind/index and one declared layer",
852 ));
853 }
854 }
855 BoardOperation::CircleOperation(value) => {
856 marker_count += 1;
857 if value.index as usize != operation_index
858 || record.dimension_type != BoardDimensionType::Orthogonal
859 || marker_count > 1
860 || value.kind != "Circle"
861 || !dimension_layer_is_declared(value.layer.as_deref(), &record.layers)
862 || !dimension_marker_state(value)
863 {
864 return Err(invalid_dimension(
865 path,
866 "only orthogonal dimensions admit the canonical declared-layer marker circle",
867 ));
868 }
869 }
870 _ => {
871 return Err(invalid_dimension(
872 path,
873 "dimension records admit only layered ThickSegment, marker Circle, and leading faced Text operations",
874 ));
875 }
876 }
877 }
878 Ok(())
879}
880
881fn dimension_layer_is_declared(layer: Option<&str>, layers: &[String]) -> bool {
882 layer.is_some_and(|layer| {
883 layers
884 .binary_search_by(|value| value.as_str().cmp(layer))
885 .is_ok()
886 })
887}
888
889fn dimension_marker_state(value: &CircleOperation) -> bool {
890 value.fill == BoardFill::FilledShape
891 && value.diameter_nm.get() == 200_000
892 && value.width_nm.get() == 0
893 && value.role.is_none()
894 && value.layers.as_ref().is_none_or(Vec::is_empty)
895 && value.mask_margin_nm.is_none()
896 && value.pad_size_x_nm.is_none()
897 && value.pad_size_y_nm.is_none()
898 && value.stroke_color.is_none()
899 && value.fill_color.is_none()
900 && value.line_style.is_none()
901}
902
903fn invalid_dimension(path: String, message: &'static str) -> ValidationError {
904 validation_error("invalid_board_operation", path, message)
905}
906
907fn validate_board_graphic_operations(
908 operations: &[BoardOperation],
909 record_index: usize,
910) -> Result<(), ValidationError> {
911 for (operation_index, operation) in operations.iter().enumerate() {
912 let path = format!("$.records[{record_index}].operations[{operation_index}]");
913 validate_board_operation(operation, path)?;
914 }
915 Ok(())
916}
917
918fn validate_track_segment_operations(
919 operations: &[BoardOperation],
920 record_index: usize,
921) -> Result<(), ValidationError> {
922 if let [BoardOperation::ThickSegmentOperation(value)] = operations
923 && board_segment_is_layer_free(value)
924 {
925 return Ok(());
926 }
927 Err(validation_error(
928 "invalid_board_operation",
929 format!("$.records[{record_index}].operations"),
930 "track segment records carry exactly one layerless thick segment",
931 ))
932}
933
934fn validate_track_arc_operations(
935 operations: &[BoardOperation],
936 record_index: usize,
937) -> Result<(), ValidationError> {
938 if let [BoardOperation::ArcThreePointOperation(value)] = operations
939 && value.layer.is_none()
940 {
941 return Ok(());
942 }
943 Err(validation_error(
944 "invalid_board_operation",
945 format!("$.records[{record_index}].operations"),
946 "track arc records carry exactly one layerless three-point arc",
947 ))
948}
949
950fn validate_zone_fill_operations(
951 record: &crate::generated::board_plot_document::ZoneFillPlotRecord,
952 record_index: usize,
953) -> Result<(), ValidationError> {
954 let rings = record.operations.len();
957 if record.fill_layers.len() != rings || record.fill_island.len() != rings {
958 return Err(validation_error(
959 "invalid_board_operation",
960 format!("$.records[{record_index}].fill_layers"),
961 "zone fill ring annotations must match the operation count",
962 ));
963 }
964 for (operation_index, operation) in record.operations.iter().enumerate() {
965 let valid = matches!(
966 operation,
967 BoardOperation::PlotPolyOperation(value) if value.layer.is_none()
968 );
969 if !valid {
970 return Err(validation_error(
971 "invalid_board_operation",
972 format!("$.records[{record_index}].operations[{operation_index}]"),
973 "zone fill records carry only layerless filled polygons",
974 ));
975 }
976 }
977 Ok(())
978}
979
980fn validate_board_text_operations(
981 record: &BoardTextPlotRecord,
982 record_index: usize,
983) -> Result<(), ValidationError> {
984 if record.kind != "gr_text" || record.object_id != "gr_text" {
985 return Err(validation_error(
986 "invalid_board_operation",
987 format!("$.records[{record_index}]"),
988 "board text record identity must be gr_text",
989 ));
990 }
991 if record.hide {
993 return Err(validation_error(
994 "invalid_board_operation",
995 format!("$.records[{record_index}].hide"),
996 "board gr_text records always carry hide false",
997 ));
998 }
999 match record.operations.as_slice() {
1000 [] if record.text.is_empty() => Ok(()),
1002 [BoardOperation::TextOperation(value)] => {
1003 let path = format!("$.records[{record_index}].operations[0]");
1004 validate_text_payload(value, &path)?;
1005 let valid = value.layer.is_none()
1008 && !value.multiline
1009 && value.polyline_per_segment.is_some() == value.font_face.is_empty()
1010 && record.text == value.text;
1011 if valid {
1012 Ok(())
1013 } else {
1014 Err(validation_error("invalid_board_operation", path, {
1015 "gr_text records carry one matching single-line text operation"
1016 }))
1017 }
1018 }
1019 _ => Err(validation_error(
1020 "invalid_board_operation",
1021 format!("$.records[{record_index}].operations"),
1022 "gr_text records carry at most one text operation",
1023 )),
1024 }
1025}
1026
1027fn validate_board_text_box_operations(
1028 record: &BoardTextBoxPlotRecord,
1029 record_index: usize,
1030) -> Result<(), ValidationError> {
1031 if record.kind != "gr_text_box" || record.object_id != "gr_text_box" {
1032 return Err(validation_error(
1033 "invalid_board_operation",
1034 format!("$.records[{record_index}]"),
1035 "board text-box record identity must be gr_text_box",
1036 ));
1037 }
1038 let (rect, text) = text_box_operation_parts(record, record_index)?;
1039 validate_text_box_border(record, record_index, rect)?;
1040 if let Some(value) = text {
1041 validate_text_box_text(value, record_index, rect.is_some())?;
1042 if record.text != value.text {
1043 return Err(validation_error(
1044 "invalid_board_operation",
1045 format!("$.records[{record_index}].text"),
1046 "gr_text_box record text must match its text operation",
1047 ));
1048 }
1049 } else if !record.text.is_empty() {
1050 return Err(validation_error(
1051 "invalid_board_operation",
1052 format!("$.records[{record_index}].text"),
1053 "gr_text_box records without text operations carry empty text",
1054 ));
1055 }
1056 Ok(())
1057}
1058
1059fn text_box_operation_parts(
1060 record: &BoardTextBoxPlotRecord,
1061 record_index: usize,
1062) -> Result<(Option<&RectOperation>, Option<&TextOperation>), ValidationError> {
1063 let parts = match record.operations.as_slice() {
1064 [] => (None, None),
1065 [BoardOperation::TextOperation(value)] => (None, Some(value)),
1066 [BoardOperation::RectOperation(rect)] => (Some(rect), None),
1067 [
1068 BoardOperation::RectOperation(rect),
1069 BoardOperation::TextOperation(value),
1070 ] => (Some(rect), Some(value)),
1071 _ => {
1072 return Err(validation_error(
1073 "invalid_board_operation",
1074 format!("$.records[{record_index}].operations"),
1075 "gr_text_box records carry an optional border rect then text",
1076 ));
1077 }
1078 };
1079 Ok(parts)
1080}
1081
1082fn validate_text_box_border(
1083 record: &BoardTextBoxPlotRecord,
1084 record_index: usize,
1085 rect: Option<&RectOperation>,
1086) -> Result<(), ValidationError> {
1087 if record.border != rect.is_some() {
1089 return Err(validation_error(
1090 "invalid_board_operation",
1091 format!("$.records[{record_index}].border"),
1092 "gr_text_box border must match the leading rect operation",
1093 ));
1094 }
1095 if let Some(rect) = rect
1096 && !(rect.layer.is_none()
1097 && rect.fill == BoardFill::NoFill
1098 && text_box_rect_is_square(rect))
1099 {
1100 return Err(validation_error(
1101 "invalid_board_operation",
1102 format!("$.records[{record_index}].operations[0]"),
1103 "gr_text_box borders are layerless unfilled square-corner rects",
1104 ));
1105 }
1106 Ok(())
1107}
1108
1109fn validate_text_box_text(
1110 value: &TextOperation,
1111 record_index: usize,
1112 has_border: bool,
1113) -> Result<(), ValidationError> {
1114 let operation_index = usize::from(has_border);
1115 let path = format!("$.records[{record_index}].operations[{operation_index}]");
1116 validate_text_payload(value, &path)?;
1117 if value.layer.is_some() || value.mirror.is_some() || value.polyline_per_segment.is_some() {
1119 return Err(validation_error(
1120 "invalid_board_operation",
1121 path,
1122 "gr_text_box text operations omit mirror and polyline markers",
1123 ));
1124 }
1125 Ok(())
1126}
1127
1128fn validate_table_operations(
1129 record: &TablePlotRecord,
1130 record_index: usize,
1131) -> Result<(), ValidationError> {
1132 if !table_identity_and_layers_are_valid(record) {
1133 return Err(validation_error(
1134 "invalid_board_operation",
1135 format!("$.records[{record_index}]"),
1136 "table identity must be canonical and layers must be nonempty, sorted, and unique",
1137 ));
1138 }
1139 let mut saw_text = false;
1140 let mut grid_layer: Option<String> = None;
1141 for (operation_index, operation) in record.operations.iter().enumerate() {
1142 let path = format!("$.records[{record_index}].operations[{operation_index}]");
1143 match operation {
1144 BoardOperation::ThickSegmentOperation(value) => {
1145 if saw_text {
1146 return Err(invalid_table_phase(path));
1147 }
1148 validate_table_segment(value, record, &mut grid_layer, path)?;
1149 }
1150 BoardOperation::TextOperation(value) => {
1151 saw_text = true;
1152 validate_table_text(value, record, path)?;
1153 }
1154 _ => return Err(invalid_table_phase(path)),
1155 }
1156 }
1157 Ok(())
1158}
1159
1160fn table_identity_and_layers_are_valid(record: &TablePlotRecord) -> bool {
1161 record.kind == "table"
1162 && record.object_id == "table"
1163 && !record.layers.is_empty()
1164 && record.layers.windows(2).all(|pair| pair[0] < pair[1])
1165}
1166
1167fn validate_table_segment(
1168 value: &ThickSegmentOperation,
1169 record: &TablePlotRecord,
1170 grid_layer: &mut Option<String>,
1171 path: String,
1172) -> Result<(), ValidationError> {
1173 let Some(layer) = value.layer.as_deref() else {
1174 return Err(invalid_table_segment(path));
1175 };
1176 if !table_segment_has_graphic_state(value)
1177 || record
1178 .layers
1179 .binary_search_by(|candidate| candidate.as_str().cmp(layer))
1180 .is_err()
1181 || grid_layer.as_deref().is_some_and(|grid| grid != layer)
1182 {
1183 return Err(invalid_table_segment(path));
1184 }
1185 if grid_layer.is_none() {
1186 *grid_layer = Some(layer.to_owned());
1187 }
1188 Ok(())
1189}
1190
1191fn validate_table_text(
1192 value: &TextOperation,
1193 record: &TablePlotRecord,
1194 path: String,
1195) -> Result<(), ValidationError> {
1196 let layer_is_declared = value
1197 .layer
1198 .as_ref()
1199 .is_some_and(|layer| record.layers.binary_search(layer).is_ok());
1200 if !layer_is_declared {
1201 return Err(invalid_table_text(path));
1202 }
1203 validate_text_payload_without_cache_angle(value, &path)?;
1204 if !table_text_has_required_state(value) {
1205 return Err(invalid_table_text(path));
1206 }
1207 Ok(())
1208}
1209
1210fn table_text_has_required_state(value: &TextOperation) -> bool {
1211 let cache_state = match value.render_cache.as_ref() {
1212 Some(_) => value.render_cache_exact == Some(false),
1213 None => value.text.is_empty(),
1214 };
1215 !value.font_face.is_empty()
1216 && cache_state
1217 && value.mirror.is_none()
1218 && value.polyline_per_segment.is_none()
1219}
1220
1221fn invalid_table_segment(path: String) -> ValidationError {
1222 validation_error(
1223 "invalid_board_operation",
1224 path,
1225 "table grid segments share one declared graphic-state layer",
1226 )
1227}
1228
1229fn invalid_table_text(path: String) -> ValidationError {
1230 validation_error(
1231 "invalid_board_operation",
1232 path,
1233 "table text requires a faced cached payload on a declared layer",
1234 )
1235}
1236
1237fn invalid_table_phase(path: String) -> ValidationError {
1238 validation_error(
1239 "invalid_board_operation",
1240 path,
1241 "table records carry grid segments followed by faced cached text",
1242 )
1243}
1244
1245fn table_segment_has_graphic_state(value: &ThickSegmentOperation) -> bool {
1246 value.kind == "ThickSegment"
1247 && value.role.is_none()
1248 && value.layers.is_empty()
1249 && value.mask_margin_nm.is_none()
1250 && value.pad_size_x_nm.is_none()
1251 && value.pad_size_y_nm.is_none()
1252 && value.stroke_color.is_none()
1253}
1254
1255fn text_box_rect_is_square(rect: &RectOperation) -> bool {
1256 i64::from(rect.corner_radius_nm) == 0
1257}
1258
1259fn validate_text_payload(value: &TextOperation, path: &str) -> Result<(), ValidationError> {
1261 validate_text_payload_with_cache_angle(value, path, true)
1262}
1263
1264fn validate_text_payload_without_cache_angle(
1265 value: &TextOperation,
1266 path: &str,
1267) -> Result<(), ValidationError> {
1268 validate_text_payload_with_cache_angle(value, path, false)
1269}
1270
1271fn validate_text_payload_with_cache_angle(
1272 value: &TextOperation,
1273 path: &str,
1274 require_cache_angle: bool,
1275) -> Result<(), ValidationError> {
1276 if value.kind != "Text" {
1277 return Err(validation_error(
1278 "invalid_board_operation",
1279 path.to_owned(),
1280 "board text operation kind must be Text",
1281 ));
1282 }
1283 if value.context.is_some() {
1284 return Err(validation_error(
1285 "invalid_board_operation",
1286 format!("{path}.context"),
1287 "board text does not emit operation context",
1288 ));
1289 }
1290 validate_text_markers(value, path)?;
1291 validate_text_cache(value, path, require_cache_angle)
1292}
1293
1294fn validate_text_markers(value: &TextOperation, path: &str) -> Result<(), ValidationError> {
1295 let markers_true = [
1296 value.mirror,
1297 value.text_as_polygons,
1298 value.polyline_per_segment,
1299 value.knockout,
1300 ]
1301 .iter()
1302 .all(|marker| *marker != Some(false));
1303 if !markers_true {
1304 return Err(validation_error(
1305 "invalid_board_operation",
1306 path.to_owned(),
1307 "text marker keys are present only when true",
1308 ));
1309 }
1310 if value.text_as_polygons.is_some() != value.font_face.is_empty() {
1312 return Err(validation_error(
1313 "invalid_board_operation",
1314 path.to_owned(),
1315 "text_as_polygons appears exactly when no font face is set",
1316 ));
1317 }
1318 Ok(())
1319}
1320
1321fn validate_text_cache(
1322 value: &TextOperation,
1323 path: &str,
1324 require_cache_angle: bool,
1325) -> Result<(), ValidationError> {
1326 validate_text_cache_keys(value, path)?;
1327 if let Some(cache) = &value.render_cache {
1328 validate_text_cache_payload(value, cache, path, require_cache_angle)?;
1329 }
1330 if value.render_cache.is_none() && value.knockout.is_some() {
1331 return Err(validation_error(
1332 "invalid_board_operation",
1333 path.to_owned(),
1334 "knockout text operations require a restructured render cache",
1335 ));
1336 }
1337 Ok(())
1338}
1339
1340fn validate_text_cache_keys(value: &TextOperation, path: &str) -> Result<(), ValidationError> {
1341 let has_cache = value.render_cache.is_some();
1342 let coherent = has_cache == value.render_cache_source.is_some()
1343 && has_cache == value.render_cache_exact.is_some()
1344 && has_cache != value.render_cache_polygons.is_empty();
1345 if !coherent {
1346 return Err(validation_error(
1347 "invalid_board_operation",
1348 path.to_owned(),
1349 "render-cache keys must appear together",
1350 ));
1351 }
1352 Ok(())
1353}
1354
1355fn validate_text_cache_payload(
1356 value: &TextOperation,
1357 cache: &crate::generated::board_plot_document::TextRenderCache,
1358 path: &str,
1359 require_cache_angle: bool,
1360) -> Result<(), ValidationError> {
1361 if !cache_identities_match(value, cache)
1362 || !cache_payload_matches(value, cache, require_cache_angle)
1363 {
1364 return Err(validation_error(
1365 "invalid_board_operation",
1366 path.to_owned(),
1367 "render-cache payload must agree with text, angle, markers, polygons, and identities",
1368 ));
1369 }
1370 Ok(())
1371}
1372
1373fn cache_identities_match(
1374 value: &TextOperation,
1375 cache: &crate::generated::board_plot_document::TextRenderCache,
1376) -> bool {
1377 let source_matches = value.render_cache_source == Some(cache.source);
1378 cache.schema == "kicad.render_cache.v1"
1379 && cache.unit == "nm"
1380 && cache.coordinate_space == PlotterTextRenderCacheCoordinateSpace::Board
1381 && source_matches
1382}
1383
1384fn cache_payload_matches(
1385 value: &TextOperation,
1386 cache: &crate::generated::board_plot_document::TextRenderCache,
1387 require_cache_angle: bool,
1388) -> bool {
1389 let knockout = value.knockout == cache.knockout && !matches!(cache.knockout, Some(false));
1390 value.render_cache_exact == Some(cache.exact)
1391 && cache.text == value.text
1392 && (!require_cache_angle || cache.angle == value.orient_deg)
1393 && knockout
1394 && cache_polygons_match(value, cache)
1395}
1396
1397fn cache_polygons_match(
1398 value: &TextOperation,
1399 cache: &crate::generated::board_plot_document::TextRenderCache,
1400) -> bool {
1401 cache.polygons.len() == value.render_cache_polygons.len()
1402 && cache
1403 .polygons
1404 .iter()
1405 .zip(&value.render_cache_polygons)
1406 .all(|(polygon, exterior)| {
1407 !polygon.contours.is_empty()
1408 && polygon.contours.iter().all(|contour| contour.len() >= 3)
1409 && points_equal(&polygon.contours[0], exterior)
1410 })
1411}
1412
1413fn points_equal(
1414 left: &[crate::generated::board_plot_document::PlotterPoint],
1415 right: &[crate::generated::board_plot_document::PlotterPoint],
1416) -> bool {
1417 left.len() == right.len()
1418 && left.iter().zip(right).all(|(left, right)| {
1419 left.0[0].get() == right.0[0].get() && left.0[1].get() == right.0[1].get()
1420 })
1421}
1422
1423fn validate_via_operations(
1424 operations: &[BoardOperation],
1425 record_index: usize,
1426) -> Result<(), ValidationError> {
1427 let mut index = 0;
1428 if operations.first().is_some_and(|operation| {
1429 matches!(operation, BoardOperation::FlashPadCircleOperation(value)
1430 if via_flash_has_role(value, PlotterViaFlashRole::ViaAperture))
1431 }) {
1432 index += 1;
1433 }
1434 let mut valid = operations.get(index).is_some_and(|operation| {
1435 matches!(operation, BoardOperation::CircleOperation(value)
1436 if via_drill_has_role(value, BoardDrillRole::ViaDrill))
1437 });
1438 index += usize::from(valid);
1439 while valid && index < operations.len() {
1440 valid = operations.get(index).is_some_and(|operation| {
1441 matches!(operation, BoardOperation::FlashPadCircleOperation(value)
1442 if via_flash_has_role(value, PlotterViaFlashRole::ViaMaskOpening))
1443 }) && operations.get(index + 1).is_some_and(|operation| {
1444 matches!(operation, BoardOperation::CircleOperation(value)
1445 if via_drill_has_role(value, BoardDrillRole::ViaMaskDrill))
1446 });
1447 index += 2;
1448 }
1449 if valid {
1450 Ok(())
1451 } else {
1452 Err(validation_error(
1453 "invalid_board_operation",
1454 format!("$.records[{record_index}].operations"),
1455 "via records carry an optional copper aperture, a drill, then mask opening/drill pairs",
1456 ))
1457 }
1458}
1459
1460fn via_flash_has_role(value: &FlashPadCircleOperation, role: PlotterViaFlashRole) -> bool {
1464 value.role == Some(role) && value.mask_margin_nm.is_none()
1465}
1466
1467fn via_drill_has_role(value: &CircleOperation, role: BoardDrillRole) -> bool {
1468 value.role == Some(role)
1469 && value.layer.is_none()
1470 && value.mask_margin_nm.is_none()
1471 && value.pad_size_x_nm.is_none()
1472 && value.pad_size_y_nm.is_none()
1473}
1474
1475fn validate_board_operation(
1476 operation: &BoardOperation,
1477 path: String,
1478) -> Result<(), ValidationError> {
1479 let valid = match operation {
1480 BoardOperation::ThickSegmentOperation(value) => board_segment_is_layer_free(value),
1481 BoardOperation::CircleOperation(value) => board_circle_is_layer_free(value),
1482 BoardOperation::ArcThreePointOperation(value) => value.layer.is_none(),
1483 BoardOperation::RectOperation(value) => value.layer.is_none(),
1484 BoardOperation::PlotPolyOperation(value) => value.layer.is_none(),
1485 BoardOperation::BezierCurveOperation(value) => value.layer.is_none(),
1486 _ => false,
1487 };
1488 if valid {
1489 Ok(())
1490 } else {
1491 Err(validation_error(
1492 "invalid_board_operation",
1493 path,
1494 "board graphic records accept only layerless graphic-state geometry",
1495 ))
1496 }
1497}
1498
1499fn board_segment_is_layer_free(value: &ThickSegmentOperation) -> bool {
1500 value.layer.is_none()
1501 && value.role.is_none()
1502 && value.layers.is_empty()
1503 && value.mask_margin_nm.is_none()
1504 && value.pad_size_x_nm.is_none()
1505 && value.pad_size_y_nm.is_none()
1506 && value.stroke_color.is_none()
1507}
1508
1509fn board_circle_is_layer_free(value: &CircleOperation) -> bool {
1510 value.layer.is_none()
1511 && value.role.is_none()
1512 && value.layers.is_none()
1513 && value.mask_margin_nm.is_none()
1514 && value.pad_size_x_nm.is_none()
1515 && value.pad_size_y_nm.is_none()
1516}