1use kicad_monkey_contracts::JavaScriptSafeInteger;
4use kicad_monkey_contracts::generated::board_plot_document as board_contract;
5use kicad_monkey_contracts::generated::board_plot_document::{
6 BoardDimensionType, BoardFootprintOperation as ContractBoardFootprintOperation,
7 BoardFootprintPlacement as ContractBoardFootprintPlacement, BoardFootprintPlotRecord,
8 BoardGraphicPlotRecord, BoardGraphicRecordKind, BoardPlotDocumentA0, BoardPlotRecord,
9 BoardTextBoxPlotRecord, BoardTextPlotRecord, BoardViaType, CircleOperation,
10 DimensionPlotRecord, FlashPadCircleOperation, PlotterCoordinateSpace, PlotterDrillRole,
11 PlotterFill, PlotterOperation, PlotterPoint, PlotterStringBool, PlotterTextHAlign,
12 PlotterTextRenderCacheCoordinateSpace, PlotterTextRenderCacheSource, PlotterTextVAlign,
13 PlotterViaFlashRole, TablePlotRecord, TextOperation, TextRenderCache, TextRenderCachePolygon,
14 TrackArcPlotRecord, TrackSegmentPlotRecord, ViaPlotRecord, ZoneFillPlotRecord,
15};
16use kicad_monkey_contracts::validate_board_plot_document;
17
18use crate::plotter_contract::contract_board_plotter_operation as contract_plotter_operation;
19use crate::{
20 BoardDimensionOperation, BoardDimensionRecord, BoardFootprintChildMetadata,
21 BoardFootprintOperation as CoreBoardFootprintOperation, BoardFootprintRecord,
22 BoardGraphicRecordKind as CoreGraphicRecordKind, BoardPlotRecord as CoreBoardPlotRecord,
23 BoardTableOperation, BoardTableRecord, BoardTextBoxOperation, BoardTextBoxRecord,
24 BoardTextHAlign, BoardTextOperation, BoardTextRecord,
25 BoardTextRenderCacheCoordinateSpace as CoreTextRenderCacheCoordinateSpace,
26 BoardTextRenderCacheSource, BoardTextVAlign, BoardViaOperation, BoardViaOperationKind,
27 BoardViaRecord,
28};
29use crate::{
30 BoardPlotSourceArtifact, BoardRenderFacts, PlotDocumentMetadata, PlotProjectionError,
31 PlotProjectionErrorKind,
32};
33
34#[derive(Clone, Debug)]
35pub struct ProjectedBoardPlotArtifact {
36 document: BoardPlotDocumentA0,
37 render_facts: BoardRenderFacts,
38}
39
40impl ProjectedBoardPlotArtifact {
41 pub fn document(&self) -> &BoardPlotDocumentA0 {
42 &self.document
43 }
44
45 pub fn render_facts(&self) -> &BoardRenderFacts {
46 &self.render_facts
47 }
48
49 pub fn select_footprint_reference(&self, reference: &str) -> Self {
56 let mut document = self.document.clone();
57 document.records.retain(|record| {
58 matches!(
59 record,
60 board_contract::BoardPlotRecord::BoardFootprintPlotRecord(footprint)
61 if footprint.reference == reference
62 )
63 });
64 document.total_operations = document
65 .records
66 .iter()
67 .map(|record| match record {
68 board_contract::BoardPlotRecord::BoardFootprintPlotRecord(footprint) => {
69 footprint.operation_count
70 }
71 _ => 0,
72 })
73 .sum();
74 Self {
75 document,
76 render_facts: self.render_facts.clone(),
77 }
78 }
79}
80
81#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub struct BoardPlotContractLimits {
83 pub max_records: usize,
84 pub max_operations: usize,
85 pub max_points: usize,
86 pub max_text_bytes: usize,
87 pub max_nested_items: usize,
88 pub max_materialized_bytes: usize,
89}
90
91impl Default for BoardPlotContractLimits {
92 fn default() -> Self {
93 Self {
94 max_records: 1_000_000,
95 max_operations: 4_000_000,
96 max_points: 16_000_000,
97 max_text_bytes: 256 * 1024 * 1024,
98 max_nested_items: 32_000_000,
99 max_materialized_bytes: 2 * 1024 * 1024 * 1024,
100 }
101 }
102}
103
104pub fn project_board_plot_document_a0(
107 document: crate::BoardPlotDocument,
108 source_path: Option<String>,
109 document_id: String,
110 limits: BoardPlotContractLimits,
111) -> Result<BoardPlotDocumentA0, String> {
112 project_board_plot_document_with_limits_a0(
113 document,
114 PlotDocumentMetadata {
115 document_id,
116 source_path,
117 },
118 limits,
119 )
120 .map_err(|error| error.to_string())
121}
122
123pub fn project_board_plot_document_with_metadata_a0(
125 document: crate::BoardPlotDocument,
126 metadata: PlotDocumentMetadata,
127) -> Result<BoardPlotDocumentA0, PlotProjectionError> {
128 project_board_plot_document_with_limits_a0(
129 document,
130 metadata,
131 BoardPlotContractLimits {
132 max_records: usize::MAX,
133 max_operations: usize::MAX,
134 max_points: usize::MAX,
135 max_text_bytes: usize::MAX,
136 max_nested_items: usize::MAX,
137 max_materialized_bytes: usize::MAX,
138 },
139 )
140}
141
142fn project_board_plot_document_with_limits_a0(
143 document: crate::BoardPlotDocument,
144 metadata: PlotDocumentMetadata,
145 limits: BoardPlotContractLimits,
146) -> Result<BoardPlotDocumentA0, PlotProjectionError> {
147 let PlotDocumentMetadata {
148 source_path,
149 document_id,
150 } = metadata;
151 let usage = projection_usage(&document, source_path.as_deref(), &document_id)?;
152 usage.enforce(limits)?;
153 let total_operations = usage.operations;
154 let mut records = Vec::with_capacity(document.records.len());
155 for record in document.records {
156 records.push(contract_record(record)?);
157 }
158 let contract = BoardPlotDocumentA0 {
159 coordinate_space: PlotterCoordinateSpace {
160 unit: "nm".to_owned(),
161 y_axis: "down".to_owned(),
162 },
163 document_id,
164 generator: document.generator,
165 generator_version: document.generator_version,
166 paper: document.paper,
167 records,
168 schema: "kicad.plotter_ir.a0".to_owned(),
169 source_kind: "PCB".to_owned(),
170 source_path,
171 thickness_mm: document.thickness_mm,
172 total_operations: contract_count(total_operations)?,
173 version: safe_integer(document.version)?,
174 };
175 validate_board_plot_document(&contract).map_err(|error| {
176 PlotProjectionError::new(
177 PlotProjectionErrorKind::ContractValidation,
178 error.to_string(),
179 )
180 })?;
181 Ok(contract)
182}
183
184pub fn project_board_plot_artifact_a0(
188 source: BoardPlotSourceArtifact,
189 metadata: PlotDocumentMetadata,
190) -> Result<ProjectedBoardPlotArtifact, PlotProjectionError> {
191 let (document, render_facts) = source.into_parts();
192 let contract = project_board_plot_document_with_metadata_a0(document, metadata)?;
193 Ok(ProjectedBoardPlotArtifact {
194 document: contract,
195 render_facts,
196 })
197}
198
199#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
200struct ProjectionUsage {
201 records: usize,
202 operations: usize,
203 points: usize,
204 text_bytes: usize,
205 nested_items: usize,
206 materialized_bytes: usize,
207}
208
209impl ProjectionUsage {
210 fn enforce(self, limits: BoardPlotContractLimits) -> Result<(), PlotProjectionError> {
211 for (actual, maximum, label) in [
212 (self.records, limits.max_records, "record count"),
213 (self.operations, limits.max_operations, "operation count"),
214 (self.points, limits.max_points, "point count"),
215 (self.text_bytes, limits.max_text_bytes, "text byte count"),
216 (
217 self.nested_items,
218 limits.max_nested_items,
219 "nested item count",
220 ),
221 (
222 self.materialized_bytes,
223 limits.max_materialized_bytes,
224 "materialized byte count",
225 ),
226 ] {
227 if actual > maximum {
228 return Err(resource_error(format!(
229 "board plot projection {label} exceeds its limit"
230 )));
231 }
232 }
233 Ok(())
234 }
235}
236
237#[derive(Default)]
238struct ProjectionCounter {
239 usage: ProjectionUsage,
240}
241
242impl ProjectionCounter {
243 fn add(
244 &mut self,
245 target: fn(&mut ProjectionUsage) -> &mut usize,
246 value: usize,
247 ) -> Result<(), PlotProjectionError> {
248 let slot = target(&mut self.usage);
249 *slot = slot
250 .checked_add(value)
251 .ok_or_else(|| resource_error("board plot projection preflight overflowed"))?;
252 Ok(())
253 }
254
255 fn text(&mut self, value: &str) -> Result<(), PlotProjectionError> {
256 self.add(|usage| &mut usage.text_bytes, value.len())
257 }
258
259 fn optional_text(&mut self, value: Option<&str>) -> Result<(), PlotProjectionError> {
260 value.map_or(Ok(()), |value| self.text(value))
261 }
262
263 fn strings<'a>(
264 &mut self,
265 values: impl IntoIterator<Item = &'a String>,
266 ) -> Result<(), PlotProjectionError> {
267 for value in values {
268 self.text(value)?;
269 self.add(|usage| &mut usage.nested_items, 1)?;
270 }
271 Ok(())
272 }
273
274 fn points(&mut self, count: usize) -> Result<(), PlotProjectionError> {
275 self.add(|usage| &mut usage.points, count)?;
276 self.add(|usage| &mut usage.nested_items, count)
277 }
278
279 fn items(&mut self, count: usize) -> Result<(), PlotProjectionError> {
280 self.add(|usage| &mut usage.nested_items, count)
281 }
282
283 fn finish(mut self) -> Result<ProjectionUsage, PlotProjectionError> {
284 self.usage.materialized_bytes = 64_usize
287 .checked_mul(1024)
288 .and_then(|value| value.checked_add(self.usage.text_bytes.checked_mul(4)?))
289 .and_then(|value| value.checked_add(self.usage.nested_items.checked_mul(4096)?))
290 .ok_or_else(|| {
291 resource_error("board plot projection materialized byte estimate overflowed")
292 })?;
293 Ok(self.usage)
294 }
295}
296
297fn projection_usage(
298 document: &crate::BoardPlotDocument,
299 source_path: Option<&str>,
300 document_id: &str,
301) -> Result<ProjectionUsage, PlotProjectionError> {
302 let mut counter = ProjectionCounter::default();
303 counter.usage.records = document.records.len();
304 counter.usage.operations = document
305 .records
306 .iter()
307 .map(crate::BoardPlotRecord::operation_count)
308 .try_fold(0_usize, |total, count| total.checked_add(count))
309 .ok_or_else(|| resource_error("board plot projection operation count overflowed"))?;
310 counter.items(
311 document
312 .records
313 .len()
314 .checked_add(counter.usage.operations)
315 .ok_or_else(|| resource_error("board plot projection nested item count overflowed"))?,
316 )?;
317 for value in [
318 &document.generator,
319 &document.generator_version,
320 &document.paper,
321 ] {
322 counter.text(value)?;
323 }
324 counter.optional_text(source_path)?;
325 counter.text(document_id)?;
326 for record in &document.records {
327 preflight_record(record, &mut counter)?;
328 }
329 counter.finish()
330}
331
332fn preflight_record(
333 record: &CoreBoardPlotRecord,
334 counter: &mut ProjectionCounter,
335) -> Result<(), PlotProjectionError> {
336 match record {
337 CoreBoardPlotRecord::Graphic(value) => {
338 counter.text(&value.uuid)?;
339 counter.text(&value.layer)?;
340 preflight_operations(&value.operations, counter)
341 }
342 CoreBoardPlotRecord::Segment(value) => {
343 counter.text(&value.uuid)?;
344 counter.text(&value.layer)?;
345 preflight_net_facts(value.net_name.as_deref(), &value.net_classes, counter)?;
346 preflight_operations(&value.operations, counter)
347 }
348 CoreBoardPlotRecord::TrackArc(value) => {
349 counter.text(&value.uuid)?;
350 counter.text(&value.layer)?;
351 preflight_net_facts(value.net_name.as_deref(), &value.net_classes, counter)?;
352 preflight_operations(&value.operations, counter)
353 }
354 CoreBoardPlotRecord::Text(value) => {
355 counter.text(&value.uuid)?;
356 counter.text(&value.layer)?;
357 counter.text(&value.text)?;
358 for operation in &value.operations {
359 preflight_text_operation(operation, counter)?;
360 }
361 Ok(())
362 }
363 CoreBoardPlotRecord::TextBox(value) => {
364 counter.text(&value.uuid)?;
365 counter.text(&value.layer)?;
366 counter.text(&value.text)?;
367 for operation in &value.operations {
368 match operation {
369 BoardTextBoxOperation::Border(operation) => {
370 preflight_operation(operation, counter)?
371 }
372 BoardTextBoxOperation::Text(operation) => {
373 preflight_text_operation(operation, counter)?
374 }
375 }
376 }
377 Ok(())
378 }
379 CoreBoardPlotRecord::Via(value) => {
380 counter.text(&value.uuid)?;
381 counter.strings(&value.layers)?;
382 preflight_net_facts(value.net_name.as_deref(), &value.net_classes, counter)?;
383 for operation in &value.operations {
384 counter.strings(&operation.layers)?;
385 }
386 Ok(())
387 }
388 CoreBoardPlotRecord::Table(value) => {
389 counter.text(&value.uuid)?;
390 counter.strings(&value.layers)?;
391 counter.items(value.cell_bounds_nm.len())?;
392 for operation in &value.operations {
393 match operation {
394 BoardTableOperation::Segment(operation) => {
395 preflight_operation(operation, counter)?
396 }
397 BoardTableOperation::Text(operation) => {
398 preflight_text_operation(operation, counter)?
399 }
400 }
401 }
402 Ok(())
403 }
404 CoreBoardPlotRecord::Dimension(value) => {
405 counter.text(&value.uuid)?;
406 counter.strings(&value.layers)?;
407 counter.text(&value.dimension_type)?;
408 counter.optional_text(value.text.as_deref())?;
409 for operation in &value.operations {
410 match operation {
411 BoardDimensionOperation::Geometry(operation) => {
412 preflight_operation(operation, counter)?
413 }
414 BoardDimensionOperation::Text(operation) => {
415 preflight_text_operation(operation, counter)?
416 }
417 }
418 }
419 Ok(())
420 }
421 CoreBoardPlotRecord::Zone(value) => {
422 counter.text(&value.uuid)?;
423 counter.strings(&value.layers)?;
424 counter.strings(&value.fill_layers)?;
425 counter.items(value.fill_island.len())?;
426 preflight_net_facts(value.net_name.as_deref(), &value.net_classes, counter)?;
427 preflight_operations(&value.operations, counter)
428 }
429 CoreBoardPlotRecord::Footprint(value) => preflight_footprint(value, counter),
430 }
431}
432
433fn preflight_net_facts(
434 name: Option<&str>,
435 classes: &crate::BoardNetClassExtras,
436 counter: &mut ProjectionCounter,
437) -> Result<(), PlotProjectionError> {
438 counter.optional_text(name)?;
439 counter.optional_text(classes.net_class.as_deref())?;
440 counter.strings(&classes.net_classes)
441}
442
443fn preflight_footprint(
444 value: &BoardFootprintRecord,
445 counter: &mut ProjectionCounter,
446) -> Result<(), PlotProjectionError> {
447 for text in [
448 &value.uuid,
449 &value.library_link,
450 &value.reference,
451 &value.value,
452 &value.layer,
453 &value.descr,
454 &value.tags,
455 ] {
456 counter.text(text)?;
457 }
458 counter.strings(&value.attr)?;
459 for operation in &value.operations {
460 match operation {
461 CoreBoardFootprintOperation::Geometry {
462 operation,
463 metadata,
464 } => {
465 preflight_operation(operation, counter)?;
466 preflight_child_metadata(metadata, counter)?;
467 }
468 CoreBoardFootprintOperation::Text {
469 operation,
470 metadata,
471 } => {
472 preflight_text_operation(operation, counter)?;
473 preflight_child_metadata(metadata, counter)?;
474 }
475 CoreBoardFootprintOperation::Pad(operation) => preflight_operation(operation, counter)?,
476 CoreBoardFootprintOperation::StartBlock(block) => {
477 for text in [
478 &block.label,
479 &block.data_uuid,
480 &block.data_ref,
481 &block.object_id,
482 ] {
483 counter.text(text)?;
484 }
485 counter.strings(&block.layers)?;
486 counter.text(&block.extra_attrs.primitive)?;
487 for text in [
488 block.extra_attrs.component.as_deref(),
489 block.extra_attrs.component_uid.as_deref(),
490 block.extra_attrs.component_uuid.as_deref(),
491 block.extra_attrs.footprint.as_deref(),
492 block.extra_attrs.pad_number.as_deref(),
493 block.extra_attrs.pad_designator.as_deref(),
494 block.extra_attrs.pad_type.as_deref(),
495 block.extra_attrs.pad_shape.as_deref(),
496 block.extra_attrs.layer_names.as_deref(),
497 block.extra_attrs.net_index.as_deref(),
498 block.extra_attrs.net_id.as_deref(),
499 block.extra_attrs.net.as_deref(),
500 block.extra_attrs.net_class.as_deref(),
501 block.extra_attrs.net_classes.as_deref(),
502 block.extra_attrs.hole_owner.as_deref(),
503 block.extra_attrs.hole_kind.as_deref(),
504 block.extra_attrs.hole_plating.as_deref(),
505 block.extra_attrs.hole_render.as_deref(),
506 block.extra_attrs.hole_diameter_mm.as_deref(),
507 block.extra_attrs.hole_width_mm.as_deref(),
508 block.extra_attrs.hole_height_mm.as_deref(),
509 ] {
510 counter.optional_text(text)?;
511 }
512 }
513 CoreBoardFootprintOperation::EndBlock => {}
514 }
515 }
516 Ok(())
517}
518
519fn preflight_child_metadata(
520 value: &BoardFootprintChildMetadata,
521 counter: &mut ProjectionCounter,
522) -> Result<(), PlotProjectionError> {
523 let attrs = &value.extra_attrs;
524 for text in [
525 &value.label,
526 &value.data_uuid,
527 &value.data_ref,
528 &value.object_id,
529 &attrs.component,
530 &attrs.component_uid,
531 &attrs.component_uuid,
532 &attrs.footprint,
533 &attrs.primitive,
534 &attrs.footprint_primitive,
535 ] {
536 counter.text(text)?;
537 }
538 for text in [
539 attrs.layer_name.as_deref(),
540 attrs.layer_role.as_deref(),
541 attrs.footprint_text_role.as_deref(),
542 attrs.property_name.as_deref(),
543 attrs.fp_text_type.as_deref(),
544 attrs.footprint_graphic_kind.as_deref(),
545 ] {
546 counter.optional_text(text)?;
547 }
548 Ok(())
549}
550
551fn preflight_operations(
552 operations: &[crate::PlotterOperation],
553 counter: &mut ProjectionCounter,
554) -> Result<(), PlotProjectionError> {
555 for operation in operations {
556 preflight_operation(operation, counter)?;
557 }
558 Ok(())
559}
560
561fn preflight_operation(
562 operation: &crate::PlotterOperation,
563 counter: &mut ProjectionCounter,
564) -> Result<(), PlotProjectionError> {
565 use crate::PlotterOperation as Operation;
566 let strings =
567 |counter: &mut ProjectionCounter, layer: Option<&str>, colors: &[Option<&str>]| {
568 counter.optional_text(layer)?;
569 for color in colors {
570 counter.optional_text(*color)?;
571 }
572 Ok::<(), PlotProjectionError>(())
573 };
574 match operation {
575 Operation::ThickSegment(value) => {
576 strings(counter, value.layer.as_deref(), &[value.role.as_deref()])?;
577 counter.strings(&value.layers)
578 }
579 Operation::ArcThreePoint(value) => strings(
580 counter,
581 value.layer.as_deref(),
582 &[value.stroke_color.as_deref(), value.fill_color.as_deref()],
583 ),
584 Operation::Circle(value) => {
585 strings(
586 counter,
587 value.layer.as_deref(),
588 &[
589 value.role.as_deref(),
590 value.stroke_color.as_deref(),
591 value.fill_color.as_deref(),
592 ],
593 )?;
594 counter.strings(&value.layers)
595 }
596 Operation::Rect(value) => strings(
597 counter,
598 value.layer.as_deref(),
599 &[value.stroke_color.as_deref(), value.fill_color.as_deref()],
600 ),
601 Operation::PlotPoly(value) => {
602 strings(
603 counter,
604 value.layer.as_deref(),
605 &[value.stroke_color.as_deref(), value.fill_color.as_deref()],
606 )?;
607 counter.points(value.points.len())
608 }
609 Operation::BezierCurve(value) => {
610 strings(
611 counter,
612 value.layer.as_deref(),
613 &[value.stroke_color.as_deref()],
614 )?;
615 counter.points(4)
616 }
617 Operation::Text(value) => {
618 for text in [&value.text, &value.color, &value.font_face] {
619 counter.text(text)?;
620 }
621 counter.optional_text(value.layer.as_deref())
622 }
623 Operation::FlashPadCircle(value) => counter.strings(&value.layers),
624 Operation::FlashPadOval(value) => counter.strings(&value.layers),
625 Operation::FlashPadRect(value) => counter.strings(&value.layers),
626 Operation::FlashPadRoundRect(value) => counter.strings(&value.layers),
627 Operation::FlashPadCustom(value) => {
628 counter.optional_text(value.anchor_shape.as_deref())?;
629 counter.strings(&value.layers)?;
630 counter.items(value.polygons.len())?;
631 counter.items(value.polygon_widths_nm.as_ref().map_or(0, Vec::len))?;
632 for polygon in &value.polygons {
633 counter.points(polygon.len())?;
634 }
635 Ok(())
636 }
637 Operation::FlashPadTrapez(value) => {
638 counter.strings(&value.layers)?;
639 counter.points(value.corners.len())
640 }
641 }
642}
643
644fn preflight_text_operation(
645 operation: &BoardTextOperation,
646 counter: &mut ProjectionCounter,
647) -> Result<(), PlotProjectionError> {
648 for text in [&operation.text, &operation.color, &operation.font_face] {
649 counter.text(text)?;
650 }
651 counter.optional_text(operation.layer.as_deref())?;
652 counter.items(operation.render_cache_polygons.len())?;
653 for polygon in &operation.render_cache_polygons {
654 counter.points(polygon.len())?;
655 }
656 if let Some(cache) = &operation.render_cache {
657 counter.text(&cache.text)?;
658 counter.items(cache.polygons.len())?;
659 for polygon in &cache.polygons {
660 counter.items(polygon.len())?;
661 for contour in polygon {
662 counter.points(contour.len())?;
663 }
664 }
665 }
666 Ok(())
667}
668
669fn contract_record(record: CoreBoardPlotRecord) -> Result<BoardPlotRecord, PlotProjectionError> {
670 Ok(match record {
671 CoreBoardPlotRecord::Graphic(record) => BoardGraphicPlotRecord {
672 kind: contract_record_kind(record.kind),
673 layer: Some(record.layer),
674 object_id: record.kind.as_str().to_owned(),
675 operation_count: contract_count(record.operations.len())?,
676 operations: shared_operations(record.operations)?,
677 uuid: record.uuid,
678 }
679 .into(),
680 CoreBoardPlotRecord::Segment(record) => TrackSegmentPlotRecord {
681 kind: "segment".to_owned(),
682 layer: record.layer,
683 locked: record.locked,
684 net_class: record.net_classes.net_class,
685 net_classes: record.net_classes.net_classes,
686 net_id: optional_safe_integer(record.net_id)?,
687 net_name: record.net_name,
688 object_id: "segment".to_owned(),
689 operation_count: contract_count(record.operations.len())?,
690 operations: shared_operations(record.operations)?,
691 uuid: record.uuid,
692 }
693 .into(),
694 CoreBoardPlotRecord::TrackArc(record) => TrackArcPlotRecord {
695 kind: "track_arc".to_owned(),
696 layer: record.layer,
697 net_class: record.net_classes.net_class,
698 net_classes: record.net_classes.net_classes,
699 net_id: optional_safe_integer(record.net_id)?,
700 net_name: record.net_name,
701 object_id: "track_arc".to_owned(),
702 operation_count: contract_count(record.operations.len())?,
703 operations: shared_operations(record.operations)?,
704 uuid: record.uuid,
705 }
706 .into(),
707 CoreBoardPlotRecord::Text(record) => contract_text_record(record)?,
708 CoreBoardPlotRecord::TextBox(record) => contract_text_box_record(record)?,
709 CoreBoardPlotRecord::Via(record) => contract_via_record(record)?.into(),
710 CoreBoardPlotRecord::Table(record) => contract_table_record(record)?.into(),
711 CoreBoardPlotRecord::Dimension(record) => contract_dimension_record(record)?.into(),
712 CoreBoardPlotRecord::Footprint(record) => contract_footprint_record(record)?.into(),
713 CoreBoardPlotRecord::Zone(record) => ZoneFillPlotRecord {
714 fill_island: record.fill_island,
715 fill_layers: record.fill_layers,
716 kind: "zone_fill".to_owned(),
717 layers: record.layers,
718 net_class: record.net_classes.net_class,
719 net_classes: record.net_classes.net_classes,
720 net_id: optional_safe_integer(record.net_id)?,
721 net_name: record.net_name,
722 object_id: "zone".to_owned(),
723 operation_count: contract_count(record.operations.len())?,
724 operations: shared_operations(record.operations)?,
725 uuid: record.uuid,
726 }
727 .into(),
728 })
729}
730
731fn contract_footprint_record(
732 record: BoardFootprintRecord,
733) -> Result<BoardFootprintPlotRecord, PlotProjectionError> {
734 let operation_count = contract_count(record.operations.len())?;
735 let operations = record
736 .operations
737 .into_iter()
738 .enumerate()
739 .map(|(index, operation)| contract_footprint_operation(index, operation))
740 .collect::<Result<Vec<_>, _>>()?;
741 Ok(BoardFootprintPlotRecord {
742 attr: record.attr,
743 descr: record.descr,
744 kind: "footprint".to_owned(),
745 layer: record.layer,
746 library_link: record.library_link.clone(),
747 locked: record.locked,
748 object_id: record.library_link,
749 operation_count,
750 operations,
751 placement: ContractBoardFootprintPlacement {
752 angle_deg: record.placement.angle_deg,
753 x_nm: safe_integer(record.placement.x_nm)?,
754 y_nm: safe_integer(record.placement.y_nm)?,
755 },
756 reference: record.reference,
757 tags: record.tags,
758 uuid: record.uuid,
759 value: record.value,
760 })
761}
762
763fn contract_footprint_operation(
764 index: usize,
765 operation: CoreBoardFootprintOperation,
766) -> Result<ContractBoardFootprintOperation, PlotProjectionError> {
767 match operation {
768 CoreBoardFootprintOperation::Geometry {
769 operation,
770 metadata,
771 } => {
772 let shared = contract_plotter_operation(index, operation)?;
773 contract_enriched_footprint_operation(shared, Some(metadata))
774 }
775 CoreBoardFootprintOperation::Text {
776 operation,
777 metadata,
778 } => {
779 let text = contract_text_operation(index, operation)?;
780 contract_enriched_footprint_operation(text.into(), Some(metadata))
781 }
782 CoreBoardFootprintOperation::Pad(operation) => {
783 let shared = contract_plotter_operation(index, operation)?;
784 contract_enriched_footprint_operation(shared, None)
785 }
786 CoreBoardFootprintOperation::StartBlock(block) => {
787 let attrs = block.extra_attrs;
788 Ok(board_contract::BoardFootprintStartBlockOperation {
789 data_ref: enum_value(block.data_ref)?,
790 data_uuid: block.data_uuid,
791 extra_attrs: board_contract::BoardFootprintPadBlockAttrs {
792 component: attrs.component,
793 component_uid: attrs.component_uid,
794 component_uuid: attrs.component_uuid,
795 footprint: attrs.footprint,
796 hole_diameter_mm: attrs.hole_diameter_mm,
797 hole_height_mm: attrs.hole_height_mm,
798 hole_kind: optional_enum_value(attrs.hole_kind)?,
799 hole_owner: attrs.hole_owner,
800 hole_plating: optional_enum_value(attrs.hole_plating)?,
801 hole_render: attrs.hole_render,
802 hole_width_mm: attrs.hole_width_mm,
803 layer_names: attrs.layer_names,
804 net: attrs.net,
805 net_class: attrs.net_class,
806 net_classes: attrs.net_classes,
807 net_id: attrs.net_id,
808 net_index: attrs.net_index,
809 pad_designator: attrs.pad_designator,
810 pad_number: attrs.pad_number,
811 pad_shape: attrs.pad_shape,
812 pad_type: attrs.pad_type,
813 primitive: enum_value(attrs.primitive)?,
814 },
815 index: contract_count(index)?,
816 kind: "StartBlock".to_owned(),
817 label: block.label,
818 layers: block.layers,
819 object_id: block.object_id,
820 }
821 .into())
822 }
823 CoreBoardFootprintOperation::EndBlock => {
824 Ok(board_contract::BoardFootprintEndBlockOperation {
825 index: contract_count(index)?,
826 kind: "EndBlock".to_owned(),
827 }
828 .into())
829 }
830 }
831}
832
833struct ContractFootprintChildMetadata {
834 data_ref: Option<board_contract::BoardFootprintChildRef>,
835 data_uuid: Option<String>,
836 extra_attrs: Option<board_contract::BoardFootprintChildAttrs>,
837 label: Option<String>,
838 object_id: Option<String>,
839}
840
841fn contract_footprint_child_metadata(
842 metadata: Option<BoardFootprintChildMetadata>,
843) -> Result<ContractFootprintChildMetadata, PlotProjectionError> {
844 let Some(metadata) = metadata else {
845 return Ok(ContractFootprintChildMetadata {
846 data_ref: None,
847 data_uuid: None,
848 extra_attrs: None,
849 label: None,
850 object_id: None,
851 });
852 };
853 let attrs = metadata.extra_attrs;
854 Ok(ContractFootprintChildMetadata {
855 data_ref: Some(enum_value(metadata.data_ref)?),
856 data_uuid: Some(metadata.data_uuid),
857 extra_attrs: Some(board_contract::BoardFootprintChildAttrs {
858 component: attrs.component,
859 component_uid: attrs.component_uid,
860 component_uuid: attrs.component_uuid,
861 footprint: attrs.footprint,
862 footprint_graphic_kind: optional_enum_value(attrs.footprint_graphic_kind)?,
863 footprint_object_index: contract_count(attrs.footprint_object_index)?,
864 footprint_primitive: enum_value(attrs.footprint_primitive)?,
865 footprint_subop_index: attrs
866 .footprint_subop_index
867 .map(contract_count)
868 .transpose()?,
869 footprint_text_role: optional_enum_value(attrs.footprint_text_role)?,
870 fp_text_type: attrs.fp_text_type,
871 layer_name: attrs.layer_name,
872 layer_role: optional_enum_value(attrs.layer_role)?,
873 primitive: enum_value(attrs.primitive)?,
874 property_name: attrs.property_name,
875 }),
876 label: Some(metadata.label),
877 object_id: Some(metadata.object_id),
878 })
879}
880
881macro_rules! enriched_operation {
882 ($value:ident, $metadata:ident, $target:ident, $variant:ident, [$($field:ident),+ $(,)?]) => {
883 ContractBoardFootprintOperation::$variant(board_contract::$target {
884 $($field: $value.$field,)+
885 data_ref: $metadata.data_ref,
886 data_uuid: $metadata.data_uuid,
887 extra_attrs: $metadata.extra_attrs,
888 label: $metadata.label,
889 object_id: $metadata.object_id,
890 })
891 };
892}
893
894#[allow(
895 clippy::too_many_lines,
896 reason = "exhaustive frozen-contract union adapter"
897)]
898fn contract_enriched_footprint_operation(
899 operation: PlotterOperation,
900 metadata: Option<BoardFootprintChildMetadata>,
901) -> Result<ContractBoardFootprintOperation, PlotProjectionError> {
902 let metadata = contract_footprint_child_metadata(metadata)?;
903 Ok(match operation {
904 PlotterOperation::PlotImageOperation(_) => {
905 return Err(invalid_model_error(
906 "board embedded-footprint operations cannot contain PlotImage",
907 ));
908 }
909 PlotterOperation::ThickSegmentOperation(value) => enriched_operation!(
910 value,
911 metadata,
912 BoardFootprintThickSegmentOperation,
913 ThickSegmentOperation,
914 [
915 end_x,
916 end_y,
917 index,
918 kind,
919 layer,
920 layers,
921 mask_margin_nm,
922 pad_size_x_nm,
923 pad_size_y_nm,
924 role,
925 start_x,
926 start_y,
927 stroke_color,
928 width_nm
929 ]
930 ),
931 PlotterOperation::ArcThreePointOperation(value) => enriched_operation!(
932 value,
933 metadata,
934 BoardFootprintArcThreePointOperation,
935 ArcThreePointOperation,
936 [
937 end_x,
938 end_y,
939 fill,
940 fill_color,
941 index,
942 kind,
943 layer,
944 line_style,
945 mid_x,
946 mid_y,
947 start_x,
948 start_y,
949 stroke_color,
950 width_nm
951 ]
952 ),
953 PlotterOperation::CircleOperation(value) => {
954 let layers = value.layers.unwrap_or_default();
955 ContractBoardFootprintOperation::CircleOperation(
956 board_contract::BoardFootprintCircleOperation {
957 cx: value.cx,
958 cy: value.cy,
959 diameter_nm: value.diameter_nm,
960 fill: value.fill,
961 fill_color: value.fill_color,
962 index: value.index,
963 kind: value.kind,
964 layer: value.layer,
965 layers,
966 line_style: value.line_style,
967 mask_margin_nm: value.mask_margin_nm,
968 pad_size_x_nm: value.pad_size_x_nm,
969 pad_size_y_nm: value.pad_size_y_nm,
970 role: value.role,
971 stroke_color: value.stroke_color,
972 width_nm: value.width_nm,
973 data_ref: metadata.data_ref,
974 data_uuid: metadata.data_uuid,
975 extra_attrs: metadata.extra_attrs,
976 label: metadata.label,
977 object_id: metadata.object_id,
978 },
979 )
980 }
981 PlotterOperation::RectOperation(value) => enriched_operation!(
982 value,
983 metadata,
984 BoardFootprintRectOperation,
985 RectOperation,
986 [
987 corner_radius_nm,
988 fill,
989 fill_color,
990 index,
991 kind,
992 layer,
993 line_style,
994 stroke_color,
995 width_nm,
996 x1,
997 x2,
998 y1,
999 y2
1000 ]
1001 ),
1002 PlotterOperation::PlotPolyOperation(value) => enriched_operation!(
1003 value,
1004 metadata,
1005 BoardFootprintPlotPolyOperation,
1006 PlotPolyOperation,
1007 [
1008 fill,
1009 fill_color,
1010 index,
1011 kind,
1012 layer,
1013 line_style,
1014 points,
1015 stroke_color,
1016 width_nm
1017 ]
1018 ),
1019 PlotterOperation::BezierCurveOperation(value) => enriched_operation!(
1020 value,
1021 metadata,
1022 BoardFootprintBezierCurveOperation,
1023 BezierCurveOperation,
1024 [
1025 ctrl1_x,
1026 ctrl1_y,
1027 ctrl2_x,
1028 ctrl2_y,
1029 end_x,
1030 end_y,
1031 index,
1032 kind,
1033 layer,
1034 line_style,
1035 start_x,
1036 start_y,
1037 stroke_color,
1038 tolerance_nm,
1039 width_nm
1040 ]
1041 ),
1042 PlotterOperation::TextOperation(value) => enriched_operation!(
1043 value,
1044 metadata,
1045 BoardFootprintTextOperation,
1046 TextOperation,
1047 [
1048 bold,
1049 color,
1050 context,
1051 font_face,
1052 h_align,
1053 index,
1054 italic,
1055 kind,
1056 knockout,
1057 layer,
1058 mirror,
1059 multiline,
1060 orient_deg,
1061 pen_width_nm,
1062 polyline_per_segment,
1063 render_cache,
1064 render_cache_exact,
1065 render_cache_polygons,
1066 render_cache_source,
1067 size_x_nm,
1068 size_y_nm,
1069 text,
1070 text_as_polygons,
1071 v_align,
1072 x,
1073 y
1074 ]
1075 ),
1076 PlotterOperation::FlashPadCircleOperation(value) => enriched_operation!(
1077 value,
1078 metadata,
1079 BoardFootprintFlashPadCircleOperation,
1080 FlashPadCircleOperation,
1081 [diameter_nm, index, kind, layers, mask_margin_nm, role, x, y]
1082 ),
1083 PlotterOperation::FlashPadOvalOperation(value) => enriched_operation!(
1084 value,
1085 metadata,
1086 BoardFootprintFlashPadOvalOperation,
1087 FlashPadOvalOperation,
1088 [
1089 index,
1090 kind,
1091 layers,
1092 mask_margin_nm,
1093 orient_deg,
1094 size_x_nm,
1095 size_y_nm,
1096 x,
1097 y
1098 ]
1099 ),
1100 PlotterOperation::FlashPadRectOperation(value) => enriched_operation!(
1101 value,
1102 metadata,
1103 BoardFootprintFlashPadRectOperation,
1104 FlashPadRectOperation,
1105 [
1106 index,
1107 kind,
1108 layers,
1109 mask_margin_nm,
1110 orient_deg,
1111 size_x_nm,
1112 size_y_nm,
1113 x,
1114 y
1115 ]
1116 ),
1117 PlotterOperation::FlashPadRoundRectOperation(value) => enriched_operation!(
1118 value,
1119 metadata,
1120 BoardFootprintFlashPadRoundRectOperation,
1121 FlashPadRoundRectOperation,
1122 [
1123 corner_radius_nm,
1124 index,
1125 kind,
1126 layers,
1127 mask_margin_nm,
1128 orient_deg,
1129 size_x_nm,
1130 size_y_nm,
1131 x,
1132 y
1133 ]
1134 ),
1135 PlotterOperation::FlashPadCustomOperation(value) => enriched_operation!(
1136 value,
1137 metadata,
1138 BoardFootprintFlashPadCustomOperation,
1139 FlashPadCustomOperation,
1140 [
1141 anchor_shape,
1142 index,
1143 kind,
1144 layers,
1145 mask_margin_nm,
1146 orient_deg,
1147 polygon_widths_nm,
1148 polygons,
1149 size_x_nm,
1150 size_y_nm,
1151 x,
1152 y
1153 ]
1154 ),
1155 PlotterOperation::FlashPadTrapezOperation(value) => enriched_operation!(
1156 value,
1157 metadata,
1158 BoardFootprintFlashPadTrapezOperation,
1159 FlashPadTrapezOperation,
1160 [
1161 corners,
1162 index,
1163 kind,
1164 layers,
1165 mask_margin_nm,
1166 orient_deg,
1167 x,
1168 y
1169 ]
1170 ),
1171 })
1172}
1173
1174fn enum_value<T>(value: String) -> Result<T, PlotProjectionError>
1175where
1176 T: TryFrom<String>,
1177 T::Error: std::fmt::Display,
1178{
1179 T::try_from(value).map_err(|error| invalid_model_error(error.to_string()))
1180}
1181
1182fn optional_enum_value<T>(value: Option<String>) -> Result<Option<T>, PlotProjectionError>
1183where
1184 T: TryFrom<String>,
1185 T::Error: std::fmt::Display,
1186{
1187 value.map(enum_value).transpose()
1188}
1189
1190fn contract_dimension_record(
1191 record: BoardDimensionRecord,
1192) -> Result<DimensionPlotRecord, PlotProjectionError> {
1193 let operations = record
1194 .operations
1195 .into_iter()
1196 .enumerate()
1197 .map(|(index, operation)| match operation {
1198 BoardDimensionOperation::Geometry(operation) => {
1199 contract_plotter_operation(index, operation)
1200 }
1201 BoardDimensionOperation::Text(operation) => {
1202 contract_text_operation(index, operation).map(PlotterOperation::from)
1203 }
1204 })
1205 .collect::<Result<Vec<_>, PlotProjectionError>>()?;
1206 Ok(DimensionPlotRecord {
1207 dimension_type: match record.dimension_type.as_str() {
1208 "aligned" => BoardDimensionType::Aligned,
1209 "orthogonal" => BoardDimensionType::Orthogonal,
1210 "radial" => BoardDimensionType::Radial,
1211 "leader" => BoardDimensionType::Leader,
1212 "center" => BoardDimensionType::Center,
1213 _ => return Err(invalid_model_error("unsupported board dimension type")),
1214 },
1215 kind: "dimension".to_owned(),
1216 layers: record.layers,
1217 object_id: "dimension".to_owned(),
1218 operation_count: contract_count(operations.len())?,
1219 operations,
1220 text: record.text,
1221 uuid: record.uuid,
1222 })
1223}
1224
1225fn contract_table_record(record: BoardTableRecord) -> Result<TablePlotRecord, PlotProjectionError> {
1226 let operations = record
1227 .operations
1228 .into_iter()
1229 .enumerate()
1230 .map(|(index, operation)| match operation {
1231 BoardTableOperation::Segment(operation) => contract_plotter_operation(index, operation),
1232 BoardTableOperation::Text(operation) => {
1233 contract_text_operation(index, operation).map(PlotterOperation::from)
1234 }
1235 })
1236 .collect::<Result<Vec<_>, PlotProjectionError>>()?;
1237 Ok(TablePlotRecord {
1238 cell_count: contract_count(record.cell_count)?,
1239 kind: "table".to_owned(),
1240 layers: record.layers,
1241 object_id: "table".to_owned(),
1242 operation_count: contract_count(operations.len())?,
1243 operations,
1244 uuid: record.uuid,
1245 })
1246}
1247
1248fn contract_text_record(record: BoardTextRecord) -> Result<BoardPlotRecord, PlotProjectionError> {
1249 let operations = record
1250 .operations
1251 .into_iter()
1252 .enumerate()
1253 .map(|(index, operation)| {
1254 contract_text_operation(index, operation).map(PlotterOperation::from)
1255 })
1256 .collect::<Result<Vec<_>, PlotProjectionError>>()?;
1257 Ok(BoardTextPlotRecord {
1258 hide: false,
1261 kind: "gr_text".to_owned(),
1262 layer: record.layer,
1263 object_id: "gr_text".to_owned(),
1264 operation_count: contract_count(operations.len())?,
1265 operations,
1266 text: record.text,
1267 uuid: record.uuid,
1268 }
1269 .into())
1270}
1271
1272fn contract_text_box_record(
1273 record: BoardTextBoxRecord,
1274) -> Result<BoardPlotRecord, PlotProjectionError> {
1275 let operations = record
1276 .operations
1277 .into_iter()
1278 .enumerate()
1279 .map(|(index, operation)| contract_text_box_operation(index, operation))
1280 .collect::<Result<Vec<_>, PlotProjectionError>>()?;
1281 Ok(BoardTextBoxPlotRecord {
1282 border: record.border,
1283 kind: "gr_text_box".to_owned(),
1284 layer: record.layer,
1285 object_id: "gr_text_box".to_owned(),
1286 operation_count: contract_count(operations.len())?,
1287 operations,
1288 text: record.text,
1289 uuid: record.uuid,
1290 }
1291 .into())
1292}
1293
1294fn contract_text_box_operation(
1295 index: usize,
1296 operation: BoardTextBoxOperation,
1297) -> Result<PlotterOperation, PlotProjectionError> {
1298 match operation {
1299 BoardTextBoxOperation::Border(operation) => contract_plotter_operation(index, operation),
1300 BoardTextBoxOperation::Text(operation) => {
1301 contract_text_operation(index, operation).map(PlotterOperation::from)
1302 }
1303 }
1304}
1305
1306fn contract_points(points: Vec<[i64; 2]>) -> Result<Vec<PlotterPoint>, PlotProjectionError> {
1307 points
1308 .into_iter()
1309 .map(|[x, y]| Ok(PlotterPoint([safe_integer(x)?, safe_integer(y)?])))
1310 .collect()
1311}
1312
1313fn contract_text_operation(
1314 index: usize,
1315 operation: BoardTextOperation,
1316) -> Result<TextOperation, PlotProjectionError> {
1317 let marker = |value: bool| value.then_some(true);
1319 let render_cache = operation
1320 .render_cache
1321 .map(|cache| -> Result<TextRenderCache, PlotProjectionError> {
1322 let source = match cache.source {
1323 BoardTextRenderCacheSource::ExistingFile => {
1324 PlotterTextRenderCacheSource::ExistingFileCache
1325 }
1326 BoardTextRenderCacheSource::NativeGenerated => {
1327 PlotterTextRenderCacheSource::NativeGeneratedCache
1328 }
1329 };
1330 Ok(TextRenderCache {
1331 angle: cache.angle,
1332 coordinate_space: match cache.coordinate_space {
1333 CoreTextRenderCacheCoordinateSpace::Board => {
1334 PlotterTextRenderCacheCoordinateSpace::Board
1335 }
1336 CoreTextRenderCacheCoordinateSpace::FootprintLocal => {
1337 PlotterTextRenderCacheCoordinateSpace::FootprintLocal
1338 }
1339 },
1340 exact: cache.exact,
1341 knockout: marker(cache.knockout),
1342 polygons: cache
1343 .polygons
1344 .into_iter()
1345 .map(|contours| {
1346 Ok(TextRenderCachePolygon {
1347 contours: contours.into_iter().map(contract_points).collect::<Result<
1348 Vec<_>,
1349 PlotProjectionError,
1350 >>(
1351 )?,
1352 })
1353 })
1354 .collect::<Result<Vec<_>, PlotProjectionError>>()?,
1355 schema: "kicad.render_cache.v1".to_owned(),
1356 source,
1357 text: cache.text,
1358 unit: "nm".to_owned(),
1359 })
1360 })
1361 .transpose()?;
1362 let render_cache_exact = render_cache.as_ref().map(|cache| cache.exact);
1363 let render_cache_source = render_cache.as_ref().map(|cache| cache.source);
1364 Ok(TextOperation {
1365 bold: operation.bold,
1366 color: operation.color,
1367 context: None,
1368 font_face: operation.font_face,
1369 h_align: match operation.h_align {
1370 BoardTextHAlign::Left => PlotterTextHAlign::GrTextHAlignLeft,
1371 BoardTextHAlign::Center => PlotterTextHAlign::GrTextHAlignCenter,
1372 BoardTextHAlign::Right => PlotterTextHAlign::GrTextHAlignRight,
1373 },
1374 index: contract_count(index)?,
1375 italic: operation.italic,
1376 kind: "Text".to_owned(),
1377 layer: operation.layer,
1378 knockout: marker(operation.knockout),
1379 mirror: marker(operation.mirror),
1380 multiline: operation.multiline,
1381 orient_deg: operation.orient_deg,
1382 pen_width_nm: safe_integer(operation.pen_width_nm)?,
1383 polyline_per_segment: marker(operation.polyline_per_segment),
1384 render_cache,
1385 render_cache_exact,
1386 render_cache_polygons: operation
1387 .render_cache_polygons
1388 .into_iter()
1389 .map(contract_points)
1390 .collect::<Result<Vec<_>, PlotProjectionError>>()?,
1391 render_cache_source,
1392 size_x_nm: safe_integer(operation.size_x_nm)?,
1393 size_y_nm: safe_integer(operation.size_y_nm)?,
1394 text: operation.text,
1395 text_as_polygons: marker(operation.text_as_polygons),
1396 v_align: match operation.v_align {
1397 BoardTextVAlign::Top => PlotterTextVAlign::GrTextVAlignTop,
1398 BoardTextVAlign::Center => PlotterTextVAlign::GrTextVAlignCenter,
1399 BoardTextVAlign::Bottom => PlotterTextVAlign::GrTextVAlignBottom,
1400 },
1401 x: safe_integer(operation.x)?,
1402 y: safe_integer(operation.y)?,
1403 })
1404}
1405
1406fn contract_via_record(record: BoardViaRecord) -> Result<ViaPlotRecord, PlotProjectionError> {
1407 let string_bool = |value: Option<bool>| {
1408 value.map(|value| {
1409 if value {
1410 PlotterStringBool::True
1411 } else {
1412 PlotterStringBool::False
1413 }
1414 })
1415 };
1416 let fabrication = record.fabrication;
1417 let operations = record
1418 .operations
1419 .into_iter()
1420 .enumerate()
1421 .map(|(index, operation)| contract_via_operation(index, operation))
1422 .collect::<Result<Vec<_>, PlotProjectionError>>()?;
1423 Ok(ViaPlotRecord {
1424 drill: record.drill,
1425 hole_kind: "round".to_owned(),
1426 hole_plating: "plated".to_owned(),
1427 hole_render: "drill".to_owned(),
1428 ipc4761_capping: string_bool(fabrication.capping),
1429 ipc4761_covering_back: string_bool(fabrication.covering_back),
1430 ipc4761_covering_front: string_bool(fabrication.covering_front),
1431 ipc4761_filling: string_bool(fabrication.filling),
1432 ipc4761_metadata: fabrication.any().then(|| "true".to_owned()),
1433 ipc4761_plugging_back: string_bool(fabrication.plugging_back),
1434 ipc4761_plugging_front: string_bool(fabrication.plugging_front),
1435 ipc4761_tenting_back: string_bool(fabrication.tenting_back),
1436 ipc4761_tenting_front: string_bool(fabrication.tenting_front),
1437 kind: "via".to_owned(),
1438 layers: record.layers,
1439 net_class: record.net_classes.net_class,
1440 net_classes: record.net_classes.net_classes,
1441 net_id: optional_safe_integer(record.net_id)?,
1442 net_name: record.net_name,
1443 object_id: "via".to_owned(),
1444 operation_count: contract_count(operations.len())?,
1445 operations,
1446 size: record.size,
1447 uuid: record.uuid,
1448 via_type: match record.via_type {
1449 crate::BoardViaType::Through => BoardViaType::Through,
1450 crate::BoardViaType::Blind => BoardViaType::Blind,
1451 crate::BoardViaType::Buried => BoardViaType::Buried,
1452 crate::BoardViaType::Micro => BoardViaType::Micro,
1453 },
1454 })
1455}
1456
1457fn contract_via_operation(
1458 index: usize,
1459 operation: BoardViaOperation,
1460) -> Result<PlotterOperation, PlotProjectionError> {
1461 let index = contract_count(index)?;
1462 let x = safe_integer(operation.x)?;
1463 let y = safe_integer(operation.y)?;
1464 let diameter_nm = safe_integer(operation.diameter_nm)?;
1465 Ok(match operation.kind {
1466 BoardViaOperationKind::Aperture | BoardViaOperationKind::MaskOpening => {
1467 FlashPadCircleOperation {
1468 diameter_nm,
1469 index,
1470 kind: "FlashPadCircle".to_owned(),
1471 layers: operation.layers,
1472 mask_margin_nm: None,
1473 role: Some(match operation.kind {
1474 BoardViaOperationKind::Aperture => PlotterViaFlashRole::ViaAperture,
1475 _ => PlotterViaFlashRole::ViaMaskOpening,
1476 }),
1477 x,
1478 y,
1479 }
1480 .into()
1481 }
1482 BoardViaOperationKind::Drill | BoardViaOperationKind::MaskDrill => CircleOperation {
1483 cx: x,
1484 cy: y,
1485 diameter_nm,
1486 fill: PlotterFill::FilledShape,
1487 fill_color: None,
1488 index,
1489 kind: "Circle".to_owned(),
1490 layer: None,
1491 layers: Some(operation.layers),
1494 line_style: None,
1495 mask_margin_nm: None,
1496 pad_size_x_nm: None,
1497 pad_size_y_nm: None,
1498 role: Some(match operation.kind {
1499 BoardViaOperationKind::Drill => PlotterDrillRole::ViaDrill,
1500 _ => PlotterDrillRole::ViaMaskDrill,
1501 }),
1502 stroke_color: None,
1503 width_nm: safe_integer(0)?,
1504 }
1505 .into(),
1506 })
1507}
1508
1509fn shared_operations(
1510 operations: Vec<crate::PlotterOperation>,
1511) -> Result<Vec<PlotterOperation>, PlotProjectionError> {
1512 operations
1514 .into_iter()
1515 .enumerate()
1516 .map(|(index, operation)| contract_plotter_operation(index, operation))
1517 .collect()
1518}
1519
1520fn contract_count(count: usize) -> Result<u32, PlotProjectionError> {
1521 u32::try_from(count).map_err(|_| {
1522 PlotProjectionError::new(
1523 PlotProjectionErrorKind::NumericRange,
1524 "board plot count or index exceeds uint32",
1525 )
1526 })
1527}
1528
1529fn safe_integer(value: i64) -> Result<JavaScriptSafeInteger, PlotProjectionError> {
1530 JavaScriptSafeInteger::try_from(value).map_err(|error| {
1531 PlotProjectionError::new(PlotProjectionErrorKind::NumericRange, error.to_string())
1532 })
1533}
1534
1535fn optional_safe_integer(
1536 value: Option<i64>,
1537) -> Result<Option<JavaScriptSafeInteger>, PlotProjectionError> {
1538 value.map(safe_integer).transpose()
1539}
1540
1541fn resource_error(message: impl Into<String>) -> PlotProjectionError {
1542 PlotProjectionError::new(PlotProjectionErrorKind::ResourceLimit, message)
1543}
1544
1545fn invalid_model_error(message: impl Into<String>) -> PlotProjectionError {
1546 PlotProjectionError::new(PlotProjectionErrorKind::InvalidModel, message)
1547}
1548
1549fn contract_record_kind(kind: CoreGraphicRecordKind) -> BoardGraphicRecordKind {
1550 match kind {
1551 CoreGraphicRecordKind::GrLine => BoardGraphicRecordKind::GrLine,
1552 CoreGraphicRecordKind::GrArc => BoardGraphicRecordKind::GrArc,
1553 CoreGraphicRecordKind::GrCircle => BoardGraphicRecordKind::GrCircle,
1554 CoreGraphicRecordKind::GrRect => BoardGraphicRecordKind::GrRect,
1555 CoreGraphicRecordKind::GrPoly => BoardGraphicRecordKind::GrPoly,
1556 CoreGraphicRecordKind::GrCurve => BoardGraphicRecordKind::GrCurve,
1557 }
1558}
1559
1560#[cfg(test)]
1561mod tests {
1562 use super::*;
1563 use crate::{BoardPlotLimits, board_plot_document};
1564
1565 const SOURCE: &str = r#"(kicad_pcb
1566 (version 20240108) (generator pcbnew)
1567 (general (thickness 1.6)) (paper "A4")
1568 (layers (0 "F.Cu" signal) (31 "B.Cu" signal) (36 "B.SilkS" user "b.silkscreen"))
1569 (gr_line (start 0 0) (end 1 1)
1570 (stroke (width 0.1) (type solid)) (layer "B.SilkS"))
1571 (gr_poly (pts (xy 0 0) (xy 2 0) (xy 1 1))
1572 (stroke (width 0.1) (type solid)) (fill none) (layer "B.SilkS")))"#;
1573
1574 fn project(limits: BoardPlotContractLimits) -> Result<BoardPlotDocumentA0, String> {
1575 project_board_plot_document_a0(
1576 board_plot_document(SOURCE, BoardPlotLimits::default()).expect("board plot document"),
1577 Some("fixture.kicad_pcb".to_owned()),
1578 "fixture".to_owned(),
1579 limits,
1580 )
1581 }
1582
1583 #[test]
1584 fn projection_limits_accept_exact_and_reject_one_under() {
1585 let source = board_plot_document(SOURCE, BoardPlotLimits::default()).expect("document");
1586 let usage = projection_usage(&source, Some("fixture.kicad_pcb"), "fixture")
1587 .expect("projection preflight");
1588 let exact_limits = BoardPlotContractLimits {
1589 max_records: usage.records,
1590 max_operations: usage.operations,
1591 max_points: usage.points,
1592 max_text_bytes: usage.text_bytes,
1593 max_nested_items: usage.nested_items,
1594 max_materialized_bytes: usage.materialized_bytes,
1595 };
1596 let exact = project(exact_limits).expect("inclusive projection boundaries");
1597 assert_eq!(exact.records.len(), usage.records);
1598 for limits in [
1599 BoardPlotContractLimits {
1600 max_records: usage.records - 1,
1601 ..exact_limits
1602 },
1603 BoardPlotContractLimits {
1604 max_operations: usage.operations - 1,
1605 ..exact_limits
1606 },
1607 BoardPlotContractLimits {
1608 max_points: usage.points - 1,
1609 ..exact_limits
1610 },
1611 BoardPlotContractLimits {
1612 max_text_bytes: usage.text_bytes - 1,
1613 ..exact_limits
1614 },
1615 BoardPlotContractLimits {
1616 max_nested_items: usage.nested_items - 1,
1617 ..exact_limits
1618 },
1619 BoardPlotContractLimits {
1620 max_materialized_bytes: usage.materialized_bytes - 1,
1621 ..exact_limits
1622 },
1623 ] {
1624 assert!(project(limits).is_err());
1625 }
1626 }
1627}