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

kicad_monkey_svg/
direct.rs

1//! Direct typed Plotter-IR rendering without JSON or Serde reconciliation.
2
3use kicad_monkey_contracts::generated::{
4    board_plot_document as board, footprint_plot_document as footprint,
5    schematic_plot_document as schematic, symbol_plot_document as symbol,
6};
7use kicad_monkey_contracts::{
8    validate_board_plot_document, validate_footprint_plot_document,
9    validate_schematic_plot_document, validate_symbol_plot_document,
10};
11use kicad_monkey_core::{ProjectedBoardPlotArtifact, ProjectedSchematicPagePlotArtifact};
12
13use crate::context::{
14    PlotterOperationKind, SvgBackground, SvgColor, SvgFillMode, SvgIdentityMode, SvgLineStyle,
15    SvgPrimitiveClass, SvgSemanticRole, SvgStyleOverride, ValidatedSvgRenderContextA1,
16};
17use crate::sink::SvgSink;
18use crate::{SvgArtifact, SvgError, SvgErrorKind, SvgMetrics};
19
20type Point = (i64, i64);
21
22#[derive(Clone, Copy)]
23struct PadOvalCenterline {
24    first_twice: (i128, i128),
25    second_twice: (i128, i128),
26    width_nm: i64,
27}
28
29/// Explicit SVG `viewBox` rectangle in integer nanometres.
30#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31pub struct SvgViewport {
32    /// Minimum X coordinate in nanometres.
33    pub min_x_nm: i64,
34    /// Minimum Y coordinate in nanometres.
35    pub min_y_nm: i64,
36    /// Viewport width in nanometres (must be positive).
37    pub width_nm: u64,
38    /// Viewport height in nanometres (must be positive).
39    pub height_nm: u64,
40}
41
42/// Axis-aligned bounding box of visible rendered geometry in nanometres.
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub struct SvgBounds {
45    /// Minimum X coordinate in nanometres.
46    pub min_x_nm: i64,
47    /// Minimum Y coordinate in nanometres.
48    pub min_y_nm: i64,
49    /// Maximum X coordinate in nanometres.
50    pub max_x_nm: i64,
51    /// Maximum Y coordinate in nanometres.
52    pub max_y_nm: i64,
53}
54
55/// Non-fatal diagnostic warning attached to an [`SvgArtifact`].
56#[derive(Clone, Debug, Eq, PartialEq)]
57pub enum SvgWarning {
58    /// Exact bounds could not be computed for one or more uncached text operations.
59    BoundsUnavailableForUncachedText,
60    /// Approximate glyph bounds were estimated for uncached text during fit-to-content.
61    EstimatedBoundsForUncachedText,
62}
63
64/// Parameters controlling [`ViewportPolicy::Fit`] automatic viewport sizing.
65#[derive(Clone, Copy, Debug, Eq, PartialEq)]
66pub struct SvgFitOptions {
67    /// Margin added around all four sides of visible bounds, in nanometres.
68    pub padding_nm: u64,
69    /// Minimum width and height enforced for degenerate or point-sized geometry, in nanometres.
70    pub min_extent_nm: u64,
71    /// Fallback viewport used if the rendered document contains no visible geometry.
72    pub fallback: Option<SvgViewport>,
73}
74
75/// Policy selecting either an explicit `viewBox` or automatic fit-to-content framing.
76#[derive(Clone, Copy, Debug, Eq, PartialEq)]
77pub enum ViewportPolicy {
78    /// Render into the exact caller-supplied viewport.
79    Explicit(SvgViewport),
80    /// Fit the viewport to the tight visible bounds using [`SvgFitOptions`].
81    Fit(SvgFitOptions),
82}
83
84#[derive(Clone, Debug)]
85struct PrimitiveStyle<'a> {
86    layer: Option<&'a str>,
87    role: Option<String>,
88    layers: &'a [String],
89    stroke: Option<&'a str>,
90    fill: Option<&'a str>,
91    width_nm: i64,
92    line_style: Option<String>,
93    filled: bool,
94}
95
96#[derive(Clone, Debug)]
97struct TextData<'a> {
98    x: i64,
99    y: i64,
100    text: &'a str,
101    color: &'a str,
102    orient_deg: f64,
103    size_x_nm: i64,
104    size_y_nm: i64,
105    mirror: bool,
106    h_align: String,
107    v_align: String,
108    italic: bool,
109    bold: bool,
110    multiline: bool,
111    font_face: &'a str,
112    layer: Option<&'a str>,
113    cache: Vec<Vec<Vec<Point>>>,
114    legacy_cache: Vec<Vec<Point>>,
115}
116
117#[derive(Clone, Debug)]
118enum OperationData<'a> {
119    Owned {
120        ownership: OwnershipData<'a>,
121        operation: Box<OperationData<'a>>,
122    },
123    Segment {
124        start: Point,
125        end: Point,
126        style: PrimitiveStyle<'a>,
127    },
128    Arc {
129        start: Point,
130        mid: Point,
131        end: Point,
132        style: PrimitiveStyle<'a>,
133    },
134    Circle {
135        center: Point,
136        diameter_nm: i64,
137        style: PrimitiveStyle<'a>,
138    },
139    Rect {
140        first: Point,
141        second: Point,
142        corner_radius_nm: i64,
143        style: PrimitiveStyle<'a>,
144    },
145    Poly {
146        points: Vec<Point>,
147        style: PrimitiveStyle<'a>,
148    },
149    Bezier {
150        points: [Point; 4],
151        style: PrimitiveStyle<'a>,
152    },
153    Text(TextData<'a>),
154    Image {
155        center: Point,
156        width_nm: i64,
157        height_nm: i64,
158        format: &'a str,
159        data: &'a str,
160    },
161    PadCircle {
162        center: Point,
163        diameter_nm: i64,
164        mask_margin_nm: i64,
165        layers: &'a [String],
166    },
167    PadOval {
168        center: Point,
169        size: Point,
170        angle_deg: f64,
171        mask_margin_nm: i64,
172        layers: &'a [String],
173    },
174    PadRect {
175        center: Point,
176        size: Point,
177        angle_deg: f64,
178        radius_nm: Option<i64>,
179        mask_margin_nm: i64,
180        layers: &'a [String],
181    },
182    PadCustom {
183        center: Point,
184        angle_deg: f64,
185        polygons: Vec<Vec<Point>>,
186        layers: &'a [String],
187    },
188    PadTrapez {
189        center: Point,
190        angle_deg: f64,
191        corners: Vec<Point>,
192        layers: &'a [String],
193    },
194    StartBlock {
195        label: &'a str,
196        data_uuid: &'a str,
197        data_ref: String,
198        object_id: &'a str,
199        extra_attrs: Vec<(String, String)>,
200    },
201    EndBlock,
202}
203
204#[derive(Clone, Debug)]
205struct OwnershipData<'a> {
206    label: Option<&'a str>,
207    data_uuid: Option<&'a str>,
208    data_ref: Option<String>,
209    object_id: Option<&'a str>,
210    extra_attrs: Vec<(String, String)>,
211}
212
213impl OwnershipData<'_> {
214    fn is_empty(&self) -> bool {
215        self.label.is_none()
216            && self.data_uuid.is_none()
217            && self.data_ref.is_none()
218            && self.object_id.is_none()
219            && self.extra_attrs.is_empty()
220    }
221}
222
223#[derive(Clone, Copy, Default)]
224struct Preflight {
225    operations: usize,
226    points: usize,
227    text_bytes: usize,
228    image_bytes: usize,
229    estimated_text_bounds_work: usize,
230}
231
232trait OperationLayers {
233    fn operation_layers(&self) -> &[String];
234}
235
236impl OperationLayers for Vec<String> {
237    fn operation_layers(&self) -> &[String] {
238        self
239    }
240}
241
242impl OperationLayers for Option<Vec<String>> {
243    fn operation_layers(&self) -> &[String] {
244        self.as_deref().unwrap_or_default()
245    }
246}
247
248fn operation_layers(value: &impl OperationLayers) -> &[String] {
249    value.operation_layers()
250}
251
252macro_rules! style {
253    ($value:expr, $filled:expr) => {
254        PrimitiveStyle {
255            layer: $value.layer.as_deref(),
256            role: None,
257            layers: &[],
258            stroke: $value.stroke_color.as_deref(),
259            fill: $value.fill_color.as_deref(),
260            width_nm: $value.width_nm.get(),
261            line_style: $value.line_style.as_ref().map(ToString::to_string),
262            filled: $filled,
263        }
264    };
265}
266
267macro_rules! define_operation_adapter {
268    ($name:ident, $operation:path, $module:path) => {
269        #[allow(
270            clippy::too_many_lines,
271            reason = "exhaustive generated PlotterOperation adapter"
272        )]
273        fn $name<'a>(operation: &'a $operation) -> OperationData<'a> {
274            use $module as m;
275            match operation {
276                m::PlotterOperation::ThickSegmentOperation(value) => OperationData::Segment {
277                    start: (value.start_x.get(), value.start_y.get()),
278                    end: (value.end_x.get(), value.end_y.get()),
279                    style: PrimitiveStyle {
280                        layer: value.layer.as_deref(),
281                        role: value.role.as_ref().map(ToString::to_string),
282                        layers: operation_layers(&value.layers),
283                        stroke: value.stroke_color.as_deref(),
284                        fill: None,
285                        width_nm: value.width_nm.get(),
286                        line_style: None,
287                        filled: false,
288                    },
289                },
290                m::PlotterOperation::ArcThreePointOperation(value) => OperationData::Arc {
291                    start: (value.start_x.get(), value.start_y.get()),
292                    mid: (value.mid_x.get(), value.mid_y.get()),
293                    end: (value.end_x.get(), value.end_y.get()),
294                    style: style!(value, value.fill.to_string() != "NO_FILL"),
295                },
296                m::PlotterOperation::CircleOperation(value) => OperationData::Circle {
297                    center: (value.cx.get(), value.cy.get()),
298                    diameter_nm: value.diameter_nm.get(),
299                    style: PrimitiveStyle {
300                        layer: value.layer.as_deref(),
301                        role: value.role.as_ref().map(ToString::to_string),
302                        layers: operation_layers(&value.layers),
303                        stroke: value.stroke_color.as_deref(),
304                        fill: value.fill_color.as_deref(),
305                        width_nm: value.width_nm.get(),
306                        line_style: value.line_style.as_ref().map(ToString::to_string),
307                        filled: value.fill.to_string() != "NO_FILL",
308                    },
309                },
310                m::PlotterOperation::RectOperation(value) => OperationData::Rect {
311                    first: (value.x1.get(), value.y1.get()),
312                    second: (value.x2.get(), value.y2.get()),
313                    corner_radius_nm: value.corner_radius_nm.get(),
314                    style: style!(value, value.fill.to_string() != "NO_FILL"),
315                },
316                m::PlotterOperation::PlotPolyOperation(value) => OperationData::Poly {
317                    points: value
318                        .points
319                        .iter()
320                        .map(|point| (point.0[0].get(), point.0[1].get()))
321                        .collect(),
322                    style: style!(value, value.fill.to_string() != "NO_FILL"),
323                },
324                m::PlotterOperation::BezierCurveOperation(value) => OperationData::Bezier {
325                    points: [
326                        (value.start_x.get(), value.start_y.get()),
327                        (value.ctrl1_x.get(), value.ctrl1_y.get()),
328                        (value.ctrl2_x.get(), value.ctrl2_y.get()),
329                        (value.end_x.get(), value.end_y.get()),
330                    ],
331                    style: PrimitiveStyle {
332                        layer: value.layer.as_deref(),
333                        role: None,
334                        layers: &[],
335                        stroke: value.stroke_color.as_deref(),
336                        fill: None,
337                        width_nm: value.width_nm.get(),
338                        line_style: value.line_style.as_ref().map(ToString::to_string),
339                        filled: false,
340                    },
341                },
342                m::PlotterOperation::TextOperation(value) => OperationData::Text(TextData {
343                    x: value.x.get(),
344                    y: value.y.get(),
345                    text: &value.text,
346                    color: &value.color,
347                    orient_deg: value.orient_deg,
348                    size_x_nm: value.size_x_nm.get(),
349                    size_y_nm: value.size_y_nm.get(),
350                    mirror: value.mirror.unwrap_or(false),
351                    h_align: value.h_align.to_string(),
352                    v_align: value.v_align.to_string(),
353                    italic: value.italic,
354                    bold: value.bold,
355                    multiline: value.multiline,
356                    font_face: &value.font_face,
357                    layer: value.layer.as_deref(),
358                    cache: value.render_cache.as_ref().map_or_else(Vec::new, |cache| {
359                        cache
360                            .polygons
361                            .iter()
362                            .map(|polygon| {
363                                polygon
364                                    .contours
365                                    .iter()
366                                    .map(|contour| {
367                                        contour
368                                            .iter()
369                                            .map(|point| (point.0[0].get(), point.0[1].get()))
370                                            .collect()
371                                    })
372                                    .collect()
373                            })
374                            .collect()
375                    }),
376                    legacy_cache: value
377                        .render_cache_polygons
378                        .iter()
379                        .map(|polygon| {
380                            polygon
381                                .iter()
382                                .map(|point| (point.0[0].get(), point.0[1].get()))
383                                .collect()
384                        })
385                        .collect(),
386                }),
387                m::PlotterOperation::PlotImageOperation(value) => OperationData::Image {
388                    center: (value.x.get(), value.y.get()),
389                    width_nm: value.width_nm.get(),
390                    height_nm: value.height_nm.get(),
391                    format: &value.image_format,
392                    data: &value.image_data_b64,
393                },
394                m::PlotterOperation::FlashPadCircleOperation(value) => OperationData::PadCircle {
395                    center: (value.x.get(), value.y.get()),
396                    diameter_nm: value.diameter_nm.get(),
397                    mask_margin_nm: value.mask_margin_nm.as_ref().map_or(0, |value| value.get()),
398                    layers: operation_layers(&value.layers),
399                },
400                m::PlotterOperation::FlashPadOvalOperation(value) => OperationData::PadOval {
401                    center: (value.x.get(), value.y.get()),
402                    size: (value.size_x_nm.get(), value.size_y_nm.get()),
403                    angle_deg: value.orient_deg,
404                    mask_margin_nm: value.mask_margin_nm.get(),
405                    layers: operation_layers(&value.layers),
406                },
407                m::PlotterOperation::FlashPadRectOperation(value) => OperationData::PadRect {
408                    center: (value.x.get(), value.y.get()),
409                    size: (value.size_x_nm.get(), value.size_y_nm.get()),
410                    angle_deg: value.orient_deg,
411                    radius_nm: None,
412                    mask_margin_nm: value.mask_margin_nm.get(),
413                    layers: operation_layers(&value.layers),
414                },
415                m::PlotterOperation::FlashPadRoundRectOperation(value) => OperationData::PadRect {
416                    center: (value.x.get(), value.y.get()),
417                    size: (value.size_x_nm.get(), value.size_y_nm.get()),
418                    angle_deg: value.orient_deg,
419                    radius_nm: Some(value.corner_radius_nm.get()),
420                    mask_margin_nm: value.mask_margin_nm.get(),
421                    layers: operation_layers(&value.layers),
422                },
423                m::PlotterOperation::FlashPadCustomOperation(value) => OperationData::PadCustom {
424                    center: (value.x.get(), value.y.get()),
425                    angle_deg: value.orient_deg,
426                    polygons: value
427                        .polygons
428                        .iter()
429                        .map(|polygon| {
430                            polygon
431                                .iter()
432                                .map(|point| (point.0[0].get(), point.0[1].get()))
433                                .collect()
434                        })
435                        .collect(),
436                    layers: operation_layers(&value.layers),
437                },
438                m::PlotterOperation::FlashPadTrapezOperation(value) => OperationData::PadTrapez {
439                    center: (value.x.get(), value.y.get()),
440                    angle_deg: value.orient_deg,
441                    corners: value
442                        .corners
443                        .0
444                        .iter()
445                        .map(|point| (point.0[0].get(), point.0[1].get()))
446                        .collect(),
447                    layers: operation_layers(&value.layers),
448                },
449            }
450        }
451    };
452}
453
454define_operation_adapter!(
455    footprint_operation,
456    footprint::PlotterOperation,
457    kicad_monkey_contracts::generated::footprint_plot_document
458);
459define_operation_adapter!(
460    symbol_operation,
461    symbol::PlotterOperation,
462    kicad_monkey_contracts::generated::symbol_plot_document
463);
464define_operation_adapter!(
465    board_operation,
466    board::PlotterOperation,
467    kicad_monkey_contracts::generated::board_plot_document
468);
469
470macro_rules! schematic_common_operation {
471    ($value:expr, ThickSegmentOperation) => {
472        OperationData::Segment {
473            start: ($value.start_x.get(), $value.start_y.get()),
474            end: ($value.end_x.get(), $value.end_y.get()),
475            style: PrimitiveStyle {
476                layer: $value.layer.as_deref(),
477                role: $value.role.as_ref().map(ToString::to_string),
478                layers: operation_layers(&$value.layers),
479                stroke: $value.stroke_color.as_deref(),
480                fill: None,
481                width_nm: $value.width_nm.get(),
482                line_style: None,
483                filled: false,
484            },
485        }
486    };
487    ($value:expr, ArcThreePointOperation) => {
488        OperationData::Arc {
489            start: ($value.start_x.get(), $value.start_y.get()),
490            mid: ($value.mid_x.get(), $value.mid_y.get()),
491            end: ($value.end_x.get(), $value.end_y.get()),
492            style: style!($value, $value.fill.to_string() != "NO_FILL"),
493        }
494    };
495    ($value:expr, CircleOperation) => {
496        OperationData::Circle {
497            center: ($value.cx.get(), $value.cy.get()),
498            diameter_nm: $value.diameter_nm.get(),
499            style: PrimitiveStyle {
500                layer: $value.layer.as_deref(),
501                role: $value.role.as_ref().map(ToString::to_string),
502                layers: operation_layers(&$value.layers),
503                stroke: $value.stroke_color.as_deref(),
504                fill: $value.fill_color.as_deref(),
505                width_nm: $value.width_nm.get(),
506                line_style: $value.line_style.as_ref().map(ToString::to_string),
507                filled: $value.fill.to_string() != "NO_FILL",
508            },
509        }
510    };
511    ($value:expr, RectOperation) => {
512        OperationData::Rect {
513            first: ($value.x1.get(), $value.y1.get()),
514            second: ($value.x2.get(), $value.y2.get()),
515            corner_radius_nm: $value.corner_radius_nm.get(),
516            style: style!($value, $value.fill.to_string() != "NO_FILL"),
517        }
518    };
519    ($value:expr, PlotPolyOperation) => {
520        OperationData::Poly {
521            points: $value
522                .points
523                .iter()
524                .map(|point| (point.0[0].get(), point.0[1].get()))
525                .collect(),
526            style: style!($value, $value.fill.to_string() != "NO_FILL"),
527        }
528    };
529    ($value:expr, BezierCurveOperation) => {
530        OperationData::Bezier {
531            points: [
532                ($value.start_x.get(), $value.start_y.get()),
533                ($value.ctrl1_x.get(), $value.ctrl1_y.get()),
534                ($value.ctrl2_x.get(), $value.ctrl2_y.get()),
535                ($value.end_x.get(), $value.end_y.get()),
536            ],
537            style: PrimitiveStyle {
538                layer: $value.layer.as_deref(),
539                role: None,
540                layers: &[],
541                stroke: $value.stroke_color.as_deref(),
542                fill: None,
543                width_nm: $value.width_nm.get(),
544                line_style: $value.line_style.as_ref().map(ToString::to_string),
545                filled: false,
546            },
547        }
548    };
549    ($value:expr, TextOperation) => {
550        OperationData::Text(TextData {
551            x: $value.x.get(),
552            y: $value.y.get(),
553            text: &$value.text,
554            color: &$value.color,
555            orient_deg: $value.orient_deg,
556            size_x_nm: $value.size_x_nm.get(),
557            size_y_nm: $value.size_y_nm.get(),
558            mirror: $value.mirror.unwrap_or(false),
559            h_align: $value.h_align.to_string(),
560            v_align: $value.v_align.to_string(),
561            italic: $value.italic,
562            bold: $value.bold,
563            multiline: $value.multiline,
564            font_face: &$value.font_face,
565            layer: $value.layer.as_deref(),
566            cache: $value.render_cache.as_ref().map_or_else(Vec::new, |cache| {
567                cache
568                    .polygons
569                    .iter()
570                    .map(|polygon| {
571                        polygon
572                            .contours
573                            .iter()
574                            .map(|contour| {
575                                contour
576                                    .iter()
577                                    .map(|point| (point.0[0].get(), point.0[1].get()))
578                                    .collect()
579                            })
580                            .collect()
581                    })
582                    .collect()
583            }),
584            legacy_cache: $value
585                .render_cache_polygons
586                .iter()
587                .map(|polygon| {
588                    polygon
589                        .iter()
590                        .map(|point| (point.0[0].get(), point.0[1].get()))
591                        .collect()
592                })
593                .collect(),
594        })
595    };
596    ($value:expr, PlotImageOperation) => {
597        OperationData::Image {
598            center: ($value.x.get(), $value.y.get()),
599            width_nm: $value.width_nm.get(),
600            height_nm: $value.height_nm.get(),
601            format: &$value.image_format,
602            data: &$value.image_data_b64,
603        }
604    };
605    ($value:expr, FlashPadCircleOperation) => {
606        OperationData::PadCircle {
607            center: ($value.x.get(), $value.y.get()),
608            diameter_nm: $value.diameter_nm.get(),
609            mask_margin_nm: 0,
610            layers: operation_layers(&$value.layers),
611        }
612    };
613    ($value:expr, FlashPadOvalOperation) => {
614        OperationData::PadOval {
615            center: ($value.x.get(), $value.y.get()),
616            size: ($value.size_x_nm.get(), $value.size_y_nm.get()),
617            angle_deg: $value.orient_deg,
618            mask_margin_nm: 0,
619            layers: operation_layers(&$value.layers),
620        }
621    };
622    ($value:expr, FlashPadRectOperation) => {
623        OperationData::PadRect {
624            center: ($value.x.get(), $value.y.get()),
625            size: ($value.size_x_nm.get(), $value.size_y_nm.get()),
626            angle_deg: $value.orient_deg,
627            radius_nm: None,
628            mask_margin_nm: 0,
629            layers: operation_layers(&$value.layers),
630        }
631    };
632    ($value:expr, FlashPadRoundRectOperation) => {
633        OperationData::PadRect {
634            center: ($value.x.get(), $value.y.get()),
635            size: ($value.size_x_nm.get(), $value.size_y_nm.get()),
636            angle_deg: $value.orient_deg,
637            radius_nm: Some($value.corner_radius_nm.get()),
638            mask_margin_nm: 0,
639            layers: operation_layers(&$value.layers),
640        }
641    };
642    ($value:expr, FlashPadCustomOperation) => {
643        OperationData::PadCustom {
644            center: ($value.x.get(), $value.y.get()),
645            angle_deg: $value.orient_deg,
646            polygons: $value
647                .polygons
648                .iter()
649                .map(|polygon| {
650                    polygon
651                        .iter()
652                        .map(|point| (point.0[0].get(), point.0[1].get()))
653                        .collect()
654                })
655                .collect(),
656            layers: operation_layers(&$value.layers),
657        }
658    };
659    ($value:expr, FlashPadTrapezOperation) => {
660        OperationData::PadTrapez {
661            center: ($value.x.get(), $value.y.get()),
662            angle_deg: $value.orient_deg,
663            corners: $value
664                .corners
665                .0
666                .iter()
667                .map(|point| (point.0[0].get(), point.0[1].get()))
668                .collect(),
669            layers: operation_layers(&$value.layers),
670        }
671    };
672}
673
674fn schematic_operation(operation: &schematic::PlotterOperation) -> OperationData<'_> {
675    match operation {
676        schematic::PlotterOperation::ThickSegmentOperation(value) => {
677            schematic_common_operation!(value, ThickSegmentOperation)
678        }
679        schematic::PlotterOperation::ArcThreePointOperation(value) => {
680            schematic_common_operation!(value, ArcThreePointOperation)
681        }
682        schematic::PlotterOperation::CircleOperation(value) => {
683            schematic_common_operation!(value, CircleOperation)
684        }
685        schematic::PlotterOperation::RectOperation(value) => {
686            schematic_common_operation!(value, RectOperation)
687        }
688        schematic::PlotterOperation::PlotPolyOperation(value) => {
689            schematic_common_operation!(value, PlotPolyOperation)
690        }
691        schematic::PlotterOperation::BezierCurveOperation(value) => {
692            schematic_common_operation!(value, BezierCurveOperation)
693        }
694        schematic::PlotterOperation::TextOperation(value) => {
695            schematic_common_operation!(value, TextOperation)
696        }
697        schematic::PlotterOperation::PlotImageOperation(value) => {
698            schematic_common_operation!(value, PlotImageOperation)
699        }
700        schematic::PlotterOperation::FlashPadCircleOperation(value) => {
701            schematic_common_operation!(value, FlashPadCircleOperation)
702        }
703        schematic::PlotterOperation::FlashPadOvalOperation(value) => {
704            schematic_common_operation!(value, FlashPadOvalOperation)
705        }
706        schematic::PlotterOperation::FlashPadRectOperation(value) => {
707            schematic_common_operation!(value, FlashPadRectOperation)
708        }
709        schematic::PlotterOperation::FlashPadRoundRectOperation(value) => {
710            schematic_common_operation!(value, FlashPadRoundRectOperation)
711        }
712        schematic::PlotterOperation::FlashPadCustomOperation(value) => {
713            schematic_common_operation!(value, FlashPadCustomOperation)
714        }
715        schematic::PlotterOperation::FlashPadTrapezOperation(value) => {
716            schematic_common_operation!(value, FlashPadTrapezOperation)
717        }
718    }
719}
720
721macro_rules! enriched_style {
722    ($value:expr, $filled:expr) => {
723        PrimitiveStyle {
724            layer: $value.layer.as_deref(),
725            role: None,
726            layers: &[],
727            stroke: $value.stroke_color.as_deref(),
728            fill: $value.fill_color.as_deref(),
729            width_nm: $value.width_nm.get(),
730            line_style: $value.line_style.as_ref().map(ToString::to_string),
731            filled: $filled,
732        }
733    };
734}
735
736#[allow(
737    clippy::cognitive_complexity,
738    reason = "exhaustive typed metadata field inventory is intentionally linear"
739)]
740fn board_pad_block_attrs(attrs: &board::BoardFootprintPadBlockAttrs) -> Vec<(String, String)> {
741    let mut values = Vec::with_capacity(22);
742    macro_rules! push_string {
743        ($field:ident) => {
744            if let Some(value) = &attrs.$field {
745                values.push((stringify!($field).replace('_', "-"), value.clone()));
746            }
747        };
748    }
749    macro_rules! push_display {
750        ($field:ident) => {
751            if let Some(value) = attrs.$field {
752                values.push((stringify!($field).replace('_', "-"), value.to_string()));
753            }
754        };
755    }
756    push_string!(component);
757    push_string!(component_uid);
758    push_string!(component_uuid);
759    push_string!(footprint);
760    push_string!(hole_diameter_mm);
761    push_string!(hole_height_mm);
762    push_display!(hole_kind);
763    push_string!(hole_owner);
764    push_display!(hole_plating);
765    push_string!(hole_render);
766    push_string!(hole_width_mm);
767    push_string!(layer_names);
768    push_string!(net);
769    push_string!(net_class);
770    push_string!(net_classes);
771    push_string!(net_id);
772    push_string!(net_index);
773    push_string!(pad_designator);
774    push_string!(pad_number);
775    push_string!(pad_shape);
776    push_string!(pad_type);
777    values.push(("primitive".to_owned(), attrs.primitive.to_string()));
778    values
779}
780
781fn board_child_attrs(attrs: &board::BoardFootprintChildAttrs) -> Vec<(String, String)> {
782    let mut values = vec![
783        ("component".to_owned(), attrs.component.clone()),
784        ("component-uid".to_owned(), attrs.component_uid.clone()),
785        ("component-uuid".to_owned(), attrs.component_uuid.clone()),
786        ("footprint".to_owned(), attrs.footprint.clone()),
787        (
788            "footprint-object-index".to_owned(),
789            attrs.footprint_object_index.to_string(),
790        ),
791        (
792            "footprint-primitive".to_owned(),
793            attrs.footprint_primitive.to_string(),
794        ),
795        ("primitive".to_owned(), attrs.primitive.to_string()),
796    ];
797    macro_rules! push_string {
798        ($field:ident) => {
799            if let Some(value) = &attrs.$field {
800                values.push((stringify!($field).replace('_', "-"), value.clone()));
801            }
802        };
803    }
804    macro_rules! push_display {
805        ($field:ident) => {
806            if let Some(value) = attrs.$field {
807                values.push((stringify!($field).replace('_', "-"), value.to_string()));
808            }
809        };
810    }
811    push_display!(footprint_graphic_kind);
812    push_display!(footprint_subop_index);
813    push_display!(footprint_text_role);
814    push_string!(fp_text_type);
815    push_string!(layer_name);
816    push_display!(layer_role);
817    push_string!(property_name);
818    values.sort_by(|left, right| left.0.cmp(&right.0));
819    values
820}
821
822fn board_footprint_ownership(
823    operation: &board::BoardFootprintOperation,
824) -> Option<OwnershipData<'_>> {
825    macro_rules! ownership {
826        ($value:expr) => {{
827            let ownership = OwnershipData {
828                label: $value.label.as_deref(),
829                data_uuid: $value.data_uuid.as_deref(),
830                data_ref: $value.data_ref.as_ref().map(ToString::to_string),
831                object_id: $value.object_id.as_deref(),
832                extra_attrs: $value
833                    .extra_attrs
834                    .as_ref()
835                    .map_or_else(Vec::new, board_child_attrs),
836            };
837            (!ownership.is_empty()).then_some(ownership)
838        }};
839    }
840    match operation {
841        board::BoardFootprintOperation::ThickSegmentOperation(value) => ownership!(value),
842        board::BoardFootprintOperation::ArcThreePointOperation(value) => ownership!(value),
843        board::BoardFootprintOperation::CircleOperation(value) => ownership!(value),
844        board::BoardFootprintOperation::RectOperation(value) => ownership!(value),
845        board::BoardFootprintOperation::PlotPolyOperation(value) => ownership!(value),
846        board::BoardFootprintOperation::BezierCurveOperation(value) => ownership!(value),
847        board::BoardFootprintOperation::TextOperation(value) => ownership!(value),
848        board::BoardFootprintOperation::FlashPadCircleOperation(value) => ownership!(value),
849        board::BoardFootprintOperation::FlashPadOvalOperation(value) => ownership!(value),
850        board::BoardFootprintOperation::FlashPadRectOperation(value) => ownership!(value),
851        board::BoardFootprintOperation::FlashPadRoundRectOperation(value) => ownership!(value),
852        board::BoardFootprintOperation::FlashPadCustomOperation(value) => ownership!(value),
853        board::BoardFootprintOperation::FlashPadTrapezOperation(value) => ownership!(value),
854        board::BoardFootprintOperation::StartBlockOperation(_)
855        | board::BoardFootprintOperation::EndBlockOperation(_) => None,
856    }
857}
858
859#[allow(
860    clippy::too_many_lines,
861    reason = "exhaustive embedded-footprint operation adapter"
862)]
863fn board_footprint_operation(operation: &board::BoardFootprintOperation) -> OperationData<'_> {
864    let rendered = match operation {
865        board::BoardFootprintOperation::ThickSegmentOperation(value) => OperationData::Segment {
866            start: (value.start_x.get(), value.start_y.get()),
867            end: (value.end_x.get(), value.end_y.get()),
868            style: PrimitiveStyle {
869                layer: value.layer.as_deref(),
870                role: value.role.as_ref().map(ToString::to_string),
871                layers: operation_layers(&value.layers),
872                stroke: value.stroke_color.as_deref(),
873                fill: None,
874                width_nm: value.width_nm.get(),
875                line_style: None,
876                filled: false,
877            },
878        },
879        board::BoardFootprintOperation::ArcThreePointOperation(value) => OperationData::Arc {
880            start: (value.start_x.get(), value.start_y.get()),
881            mid: (value.mid_x.get(), value.mid_y.get()),
882            end: (value.end_x.get(), value.end_y.get()),
883            style: enriched_style!(value, value.fill.to_string() != "NO_FILL"),
884        },
885        board::BoardFootprintOperation::CircleOperation(value) => OperationData::Circle {
886            center: (value.cx.get(), value.cy.get()),
887            diameter_nm: value.diameter_nm.get(),
888            style: PrimitiveStyle {
889                layer: value.layer.as_deref(),
890                role: value.role.as_ref().map(ToString::to_string),
891                layers: operation_layers(&value.layers),
892                stroke: value.stroke_color.as_deref(),
893                fill: value.fill_color.as_deref(),
894                width_nm: value.width_nm.get(),
895                line_style: value.line_style.as_ref().map(ToString::to_string),
896                filled: value.fill.to_string() != "NO_FILL",
897            },
898        },
899        board::BoardFootprintOperation::RectOperation(value) => OperationData::Rect {
900            first: (value.x1.get(), value.y1.get()),
901            second: (value.x2.get(), value.y2.get()),
902            corner_radius_nm: value.corner_radius_nm.get(),
903            style: enriched_style!(value, value.fill.to_string() != "NO_FILL"),
904        },
905        board::BoardFootprintOperation::PlotPolyOperation(value) => OperationData::Poly {
906            points: value
907                .points
908                .iter()
909                .map(|point| (point.0[0].get(), point.0[1].get()))
910                .collect(),
911            style: enriched_style!(value, value.fill.to_string() != "NO_FILL"),
912        },
913        board::BoardFootprintOperation::BezierCurveOperation(value) => OperationData::Bezier {
914            points: [
915                (value.start_x.get(), value.start_y.get()),
916                (value.ctrl1_x.get(), value.ctrl1_y.get()),
917                (value.ctrl2_x.get(), value.ctrl2_y.get()),
918                (value.end_x.get(), value.end_y.get()),
919            ],
920            style: PrimitiveStyle {
921                layer: value.layer.as_deref(),
922                role: None,
923                layers: &[],
924                stroke: value.stroke_color.as_deref(),
925                fill: None,
926                width_nm: value.width_nm.get(),
927                line_style: value.line_style.as_ref().map(ToString::to_string),
928                filled: false,
929            },
930        },
931        board::BoardFootprintOperation::TextOperation(value) => OperationData::Text(TextData {
932            x: value.x.get(),
933            y: value.y.get(),
934            text: &value.text,
935            color: &value.color,
936            orient_deg: value.orient_deg,
937            size_x_nm: value.size_x_nm.get(),
938            size_y_nm: value.size_y_nm.get(),
939            mirror: value.mirror.unwrap_or(false),
940            h_align: value.h_align.to_string(),
941            v_align: value.v_align.to_string(),
942            italic: value.italic,
943            bold: value.bold,
944            multiline: value.multiline,
945            font_face: &value.font_face,
946            layer: value.layer.as_deref(),
947            cache: value.render_cache.as_ref().map_or_else(Vec::new, |cache| {
948                cache
949                    .polygons
950                    .iter()
951                    .map(|polygon| {
952                        polygon
953                            .contours
954                            .iter()
955                            .map(|contour| {
956                                contour
957                                    .iter()
958                                    .map(|point| (point.0[0].get(), point.0[1].get()))
959                                    .collect()
960                            })
961                            .collect()
962                    })
963                    .collect()
964            }),
965            legacy_cache: value
966                .render_cache_polygons
967                .iter()
968                .map(|polygon| {
969                    polygon
970                        .iter()
971                        .map(|point| (point.0[0].get(), point.0[1].get()))
972                        .collect()
973                })
974                .collect(),
975        }),
976        board::BoardFootprintOperation::FlashPadCircleOperation(value) => {
977            OperationData::PadCircle {
978                center: (value.x.get(), value.y.get()),
979                diameter_nm: value.diameter_nm.get(),
980                mask_margin_nm: value.mask_margin_nm.as_ref().map_or(0, |value| value.get()),
981                layers: operation_layers(&value.layers),
982            }
983        }
984        board::BoardFootprintOperation::FlashPadOvalOperation(value) => OperationData::PadOval {
985            center: (value.x.get(), value.y.get()),
986            size: (value.size_x_nm.get(), value.size_y_nm.get()),
987            angle_deg: value.orient_deg,
988            mask_margin_nm: value.mask_margin_nm.get(),
989            layers: operation_layers(&value.layers),
990        },
991        board::BoardFootprintOperation::FlashPadRectOperation(value) => OperationData::PadRect {
992            center: (value.x.get(), value.y.get()),
993            size: (value.size_x_nm.get(), value.size_y_nm.get()),
994            angle_deg: value.orient_deg,
995            radius_nm: None,
996            mask_margin_nm: value.mask_margin_nm.get(),
997            layers: operation_layers(&value.layers),
998        },
999        board::BoardFootprintOperation::FlashPadRoundRectOperation(value) => {
1000            OperationData::PadRect {
1001                center: (value.x.get(), value.y.get()),
1002                size: (value.size_x_nm.get(), value.size_y_nm.get()),
1003                angle_deg: value.orient_deg,
1004                radius_nm: Some(value.corner_radius_nm.get()),
1005                mask_margin_nm: value.mask_margin_nm.get(),
1006                layers: operation_layers(&value.layers),
1007            }
1008        }
1009        board::BoardFootprintOperation::FlashPadCustomOperation(value) => {
1010            OperationData::PadCustom {
1011                center: (value.x.get(), value.y.get()),
1012                angle_deg: value.orient_deg,
1013                polygons: value
1014                    .polygons
1015                    .iter()
1016                    .map(|polygon| {
1017                        polygon
1018                            .iter()
1019                            .map(|point| (point.0[0].get(), point.0[1].get()))
1020                            .collect()
1021                    })
1022                    .collect(),
1023                layers: operation_layers(&value.layers),
1024            }
1025        }
1026        board::BoardFootprintOperation::FlashPadTrapezOperation(value) => {
1027            OperationData::PadTrapez {
1028                center: (value.x.get(), value.y.get()),
1029                angle_deg: value.orient_deg,
1030                corners: value
1031                    .corners
1032                    .0
1033                    .iter()
1034                    .map(|point| (point.0[0].get(), point.0[1].get()))
1035                    .collect(),
1036                layers: operation_layers(&value.layers),
1037            }
1038        }
1039        board::BoardFootprintOperation::StartBlockOperation(value) => OperationData::StartBlock {
1040            label: &value.label,
1041            data_uuid: &value.data_uuid,
1042            data_ref: value.data_ref.to_string(),
1043            object_id: &value.object_id,
1044            extra_attrs: board_pad_block_attrs(&value.extra_attrs),
1045        },
1046        board::BoardFootprintOperation::EndBlockOperation(_) => OperationData::EndBlock,
1047    };
1048    if let Some(ownership) = board_footprint_ownership(operation) {
1049        OperationData::Owned {
1050            ownership,
1051            operation: Box::new(rendered),
1052        }
1053    } else {
1054        rendered
1055    }
1056}
1057
1058fn block_attrs(
1059    attrs: &impl std::ops::Deref<Target = std::collections::BTreeMap<String, String>>,
1060) -> Vec<(String, String)> {
1061    attrs
1062        .iter()
1063        .map(|(key, value)| (key.clone(), value.clone()))
1064        .collect()
1065}
1066
1067#[allow(
1068    clippy::too_many_lines,
1069    reason = "exhaustive placed-symbol operation adapter"
1070)]
1071fn schematic_symbol_operation(
1072    operation: &schematic::SchematicSymbolOperation,
1073) -> OperationData<'_> {
1074    match operation {
1075        schematic::SchematicSymbolOperation::ThickSegmentOperation(value) => {
1076            schematic_common_operation!(value, ThickSegmentOperation)
1077        }
1078        schematic::SchematicSymbolOperation::ArcThreePointOperation(value) => {
1079            schematic_common_operation!(value, ArcThreePointOperation)
1080        }
1081        schematic::SchematicSymbolOperation::CircleOperation(value) => {
1082            schematic_common_operation!(value, CircleOperation)
1083        }
1084        schematic::SchematicSymbolOperation::RectOperation(value) => {
1085            schematic_common_operation!(value, RectOperation)
1086        }
1087        schematic::SchematicSymbolOperation::PlotPolyOperation(value) => {
1088            schematic_common_operation!(value, PlotPolyOperation)
1089        }
1090        schematic::SchematicSymbolOperation::BezierCurveOperation(value) => {
1091            schematic_common_operation!(value, BezierCurveOperation)
1092        }
1093        schematic::SchematicSymbolOperation::TextOperation(value) => {
1094            schematic_common_operation!(value, TextOperation)
1095        }
1096        schematic::SchematicSymbolOperation::PlotImageOperation(value) => {
1097            schematic_common_operation!(value, PlotImageOperation)
1098        }
1099        schematic::SchematicSymbolOperation::FlashPadCircleOperation(value) => {
1100            schematic_common_operation!(value, FlashPadCircleOperation)
1101        }
1102        schematic::SchematicSymbolOperation::FlashPadOvalOperation(value) => {
1103            schematic_common_operation!(value, FlashPadOvalOperation)
1104        }
1105        schematic::SchematicSymbolOperation::FlashPadRectOperation(value) => {
1106            schematic_common_operation!(value, FlashPadRectOperation)
1107        }
1108        schematic::SchematicSymbolOperation::FlashPadRoundRectOperation(value) => {
1109            schematic_common_operation!(value, FlashPadRoundRectOperation)
1110        }
1111        schematic::SchematicSymbolOperation::FlashPadCustomOperation(value) => {
1112            schematic_common_operation!(value, FlashPadCustomOperation)
1113        }
1114        schematic::SchematicSymbolOperation::FlashPadTrapezOperation(value) => {
1115            schematic_common_operation!(value, FlashPadTrapezOperation)
1116        }
1117        schematic::SchematicSymbolOperation::SchematicSymbolStartBlockOperation(value) => {
1118            OperationData::StartBlock {
1119                label: &value.label,
1120                data_uuid: &value.data_uuid,
1121                data_ref: value.data_ref.clone(),
1122                object_id: &value.object_id,
1123                extra_attrs: block_attrs(&value.extra_attrs),
1124            }
1125        }
1126        schematic::SchematicSymbolOperation::SchematicSymbolEndBlockOperation(_) => {
1127            OperationData::EndBlock
1128        }
1129    }
1130}
1131
1132fn schematic_sheet_operation(operation: &schematic::SchematicSheetOperation) -> OperationData<'_> {
1133    match operation {
1134        schematic::SchematicSheetOperation::ThickSegmentOperation(value) => {
1135            schematic_common_operation!(value, ThickSegmentOperation)
1136        }
1137        schematic::SchematicSheetOperation::RectOperation(value) => {
1138            schematic_common_operation!(value, RectOperation)
1139        }
1140        schematic::SchematicSheetOperation::PlotPolyOperation(value) => {
1141            schematic_common_operation!(value, PlotPolyOperation)
1142        }
1143        schematic::SchematicSheetOperation::TextOperation(value) => {
1144            schematic_common_operation!(value, TextOperation)
1145        }
1146        schematic::SchematicSheetOperation::SchematicSheetStartBlockOperation(value) => {
1147            OperationData::StartBlock {
1148                label: &value.label,
1149                data_uuid: &value.data_uuid,
1150                data_ref: value.data_ref.clone(),
1151                object_id: &value.object_id,
1152                extra_attrs: block_attrs(&value.extra_attrs),
1153            }
1154        }
1155        schematic::SchematicSheetOperation::SchematicSheetEndBlockOperation(_) => {
1156            OperationData::EndBlock
1157        }
1158    }
1159}
1160
1161/// Render a validated KiCad footprint Plotter-IR document directly to SVG.
1162pub fn render_footprint_svg(
1163    document: &footprint::FootprintPlotDocumentA0,
1164    viewport: ViewportPolicy,
1165    context: &ValidatedSvgRenderContextA1,
1166) -> Result<SvgArtifact, SvgError> {
1167    validate_footprint_plot_document(document).map_err(|error| {
1168        SvgError::new(
1169            SvgErrorKind::InvalidDocument,
1170            format!("invalid footprint plot document: {error}"),
1171        )
1172    })?;
1173    validate_footprint_layer_selection(document, context)?;
1174    render_typed_document(
1175        "MOD",
1176        &document.document_id,
1177        document.records.len(),
1178        document.records.iter().map(|record| RecordView {
1179            uuid: &record.uuid,
1180            kind: &record.kind,
1181            object_id: &record.object_id,
1182            operations: &record.operations,
1183        }),
1184        footprint_operation,
1185        viewport,
1186        context,
1187    )
1188}
1189
1190/// Render a validated KiCad symbol Plotter-IR document directly to SVG.
1191pub fn render_symbol_svg(
1192    document: &symbol::SymbolPlotDocumentA0,
1193    viewport: ViewportPolicy,
1194    context: &ValidatedSvgRenderContextA1,
1195) -> Result<SvgArtifact, SvgError> {
1196    validate_symbol_plot_document(document).map_err(|error| {
1197        direct_error(
1198            SvgErrorKind::InvalidDocument,
1199            format!("invalid symbol plot document: {error}"),
1200        )
1201    })?;
1202    if !context.layer_selection().is_all() {
1203        return Err(SvgError::new(
1204            SvgErrorKind::UnsupportedSelector,
1205            "symbol rendering does not accept PCB layer selectors".to_owned(),
1206        ));
1207    }
1208    let records = document.records.iter().map(|record| match record {
1209        symbol::SymbolPlotRecord::SymbolHeaderPlotRecord(record) => RecordView {
1210            uuid: &record.uuid,
1211            kind: &record.kind,
1212            object_id: &record.object_id,
1213            operations: &record.operations,
1214        },
1215        symbol::SymbolPlotRecord::LibSubsymbolPlotRecord(record) => RecordView {
1216            uuid: &record.uuid,
1217            kind: &record.kind,
1218            object_id: &record.object_id,
1219            operations: &record.operations,
1220        },
1221    });
1222    render_typed_document(
1223        "SYM",
1224        &document.document_id,
1225        document.records.len(),
1226        records,
1227        symbol_operation,
1228        viewport,
1229        context,
1230    )
1231}
1232
1233struct NormalizedRecord<'a> {
1234    uuid: &'a str,
1235    kind: String,
1236    object_id: &'a str,
1237    layer: Option<&'a str>,
1238    layers: &'a [String],
1239    placement: Option<(i64, i64, f64)>,
1240    operations: Vec<OperationData<'a>>,
1241}
1242
1243/// Render a projected PCB Plotter-IR artifact with full copper-stack layer filtering.
1244pub fn render_board_svg(
1245    artifact: &ProjectedBoardPlotArtifact,
1246    viewport: ViewportPolicy,
1247    context: &ValidatedSvgRenderContextA1,
1248) -> Result<SvgArtifact, SvgError> {
1249    validate_board_layer_selection(artifact, context)?;
1250    render_board_document(
1251        artifact.document(),
1252        viewport,
1253        context,
1254        Some(artifact.render_facts().copper_stack()),
1255    )
1256}
1257
1258/// Render a standalone typed PCB Plotter-IR document with all layers visible.
1259pub fn render_board_document_svg(
1260    document: &board::BoardPlotDocumentA0,
1261    viewport: ViewportPolicy,
1262    context: &ValidatedSvgRenderContextA1,
1263) -> Result<SvgArtifact, SvgError> {
1264    if !context.layer_selection().is_all() {
1265        return Err(SvgError::new(
1266            SvgErrorKind::UnsupportedSelector,
1267            "typed board documents require all-layer visibility; use ProjectedBoardPlotArtifact for filtering"
1268                .to_owned(),
1269        ));
1270    }
1271    render_board_document(document, viewport, context, None)
1272}
1273
1274fn render_board_document(
1275    document: &board::BoardPlotDocumentA0,
1276    viewport: ViewportPolicy,
1277    context: &ValidatedSvgRenderContextA1,
1278    copper_stack: Option<&[String]>,
1279) -> Result<SvgArtifact, SvgError> {
1280    validate_board_plot_document(document).map_err(|error| {
1281        SvgError::new(
1282            SvgErrorKind::InvalidDocument,
1283            format!("invalid board plot document: {error}"),
1284        )
1285    })?;
1286    let records = normalize_board_records(document);
1287    render_normalized_document(
1288        "PCB",
1289        &document.document_id,
1290        records,
1291        viewport,
1292        context,
1293        None,
1294        copper_stack,
1295    )
1296}
1297
1298/// Render a standalone typed schematic Plotter-IR document directly to SVG.
1299pub fn render_schematic_svg(
1300    document: &schematic::SchematicPlotDocumentA0,
1301    viewport: ViewportPolicy,
1302    context: &ValidatedSvgRenderContextA1,
1303) -> Result<SvgArtifact, SvgError> {
1304    render_schematic_document(document, viewport, context, None)
1305}
1306
1307/// Render a projected hierarchical schematic page artifact with occurrence identity preserved.
1308pub fn render_schematic_page_svg(
1309    artifact: &ProjectedSchematicPagePlotArtifact,
1310    viewport: ViewportPolicy,
1311    context: &ValidatedSvgRenderContextA1,
1312) -> Result<SvgArtifact, SvgError> {
1313    render_schematic_document(
1314        artifact.document(),
1315        viewport,
1316        context,
1317        Some(artifact.occurrence_address()),
1318    )
1319}
1320
1321fn render_schematic_document(
1322    document: &schematic::SchematicPlotDocumentA0,
1323    viewport: ViewportPolicy,
1324    context: &ValidatedSvgRenderContextA1,
1325    occurrence_address: Option<&str>,
1326) -> Result<SvgArtifact, SvgError> {
1327    validate_schematic_plot_document(document).map_err(|error| {
1328        let kind = if matches!(
1329            error.code,
1330            "invalid_symbol_pin_block" | "invalid_sheet_pin_block"
1331        ) {
1332            SvgErrorKind::UnbalancedBlock
1333        } else {
1334            SvgErrorKind::InvalidDocument
1335        };
1336        SvgError::new(kind, format!("invalid schematic plot document: {error}"))
1337    })?;
1338    if !matches!(context.layer_selection(), crate::LayerSelection::All) {
1339        return Err(SvgError::new(
1340            SvgErrorKind::UnsupportedSelector,
1341            "schematic rendering does not accept PCB layer selectors".to_owned(),
1342        ));
1343    }
1344    render_normalized_document(
1345        "SCH",
1346        &document.document_id,
1347        normalize_schematic_records(document),
1348        viewport,
1349        context,
1350        occurrence_address,
1351        None,
1352    )
1353}
1354
1355macro_rules! normalize_schematic_common_record {
1356    ($value:expr) => {
1357        NormalizedRecord {
1358            uuid: &$value.uuid,
1359            kind: $value.kind.clone(),
1360            object_id: &$value.object_id,
1361            layer: None,
1362            layers: &[],
1363            placement: None,
1364            operations: $value.operations.iter().map(schematic_operation).collect(),
1365        }
1366    };
1367}
1368
1369#[allow(
1370    clippy::too_many_lines,
1371    reason = "exhaustive schematic record-union inventory"
1372)]
1373fn normalize_schematic_records(
1374    document: &schematic::SchematicPlotDocumentA0,
1375) -> Vec<NormalizedRecord<'_>> {
1376    document
1377        .records
1378        .iter()
1379        .map(|record| match record {
1380            schematic::SchematicPlotRecord::SheetHeaderPlotRecord(value) => {
1381                normalize_schematic_common_record!(value)
1382            }
1383            schematic::SchematicPlotRecord::WirePlotRecord(value) => {
1384                normalize_schematic_common_record!(value)
1385            }
1386            schematic::SchematicPlotRecord::BusPlotRecord(value) => {
1387                normalize_schematic_common_record!(value)
1388            }
1389            schematic::SchematicPlotRecord::BusEntryPlotRecord(value) => {
1390                normalize_schematic_common_record!(value)
1391            }
1392            schematic::SchematicPlotRecord::JunctionPlotRecord(value) => {
1393                normalize_schematic_common_record!(value)
1394            }
1395            schematic::SchematicPlotRecord::NoConnectPlotRecord(value) => {
1396                normalize_schematic_common_record!(value)
1397            }
1398            schematic::SchematicPlotRecord::LabelPlotRecord(value) => {
1399                normalize_schematic_common_record!(value)
1400            }
1401            schematic::SchematicPlotRecord::GlobalLabelPlotRecord(value) => {
1402                normalize_schematic_common_record!(value)
1403            }
1404            schematic::SchematicPlotRecord::HierarchicalLabelPlotRecord(value) => {
1405                normalize_schematic_common_record!(value)
1406            }
1407            schematic::SchematicPlotRecord::NetclassFlagPlotRecord(value) => {
1408                normalize_schematic_common_record!(value)
1409            }
1410            schematic::SchematicPlotRecord::TextPlotRecord(value) => {
1411                normalize_schematic_common_record!(value)
1412            }
1413            schematic::SchematicPlotRecord::TextBoxPlotRecord(value) => {
1414                normalize_schematic_common_record!(value)
1415            }
1416            schematic::SchematicPlotRecord::GraphicPolylinePlotRecord(value) => {
1417                normalize_schematic_common_record!(value)
1418            }
1419            schematic::SchematicPlotRecord::GraphicArcPlotRecord(value) => {
1420                normalize_schematic_common_record!(value)
1421            }
1422            schematic::SchematicPlotRecord::GraphicCirclePlotRecord(value) => {
1423                normalize_schematic_common_record!(value)
1424            }
1425            schematic::SchematicPlotRecord::GraphicRectanglePlotRecord(value) => {
1426                normalize_schematic_common_record!(value)
1427            }
1428            schematic::SchematicPlotRecord::GraphicBezierPlotRecord(value) => {
1429                normalize_schematic_common_record!(value)
1430            }
1431            schematic::SchematicPlotRecord::RuleAreaPlotRecord(value) => {
1432                normalize_schematic_common_record!(value)
1433            }
1434            schematic::SchematicPlotRecord::ImagePlotRecord(value) => {
1435                normalize_schematic_common_record!(value)
1436            }
1437            schematic::SchematicPlotRecord::TablePlotRecord(value) => {
1438                normalize_schematic_common_record!(value)
1439            }
1440            schematic::SchematicPlotRecord::SymbolInstancePlotRecord(value) => NormalizedRecord {
1441                uuid: &value.uuid,
1442                kind: value.kind.clone(),
1443                object_id: &value.object_id,
1444                layer: None,
1445                layers: &[],
1446                placement: None,
1447                operations: value
1448                    .operations
1449                    .iter()
1450                    .map(schematic_symbol_operation)
1451                    .collect(),
1452            },
1453            schematic::SchematicPlotRecord::SymbolOverplotPlotRecord(value) => NormalizedRecord {
1454                uuid: &value.uuid,
1455                kind: value.kind.clone(),
1456                object_id: &value.object_id,
1457                layer: None,
1458                layers: &[],
1459                placement: None,
1460                operations: value
1461                    .operations
1462                    .iter()
1463                    .map(schematic_symbol_operation)
1464                    .collect(),
1465            },
1466            schematic::SchematicPlotRecord::SheetPlotRecord(value) => NormalizedRecord {
1467                uuid: &value.uuid,
1468                kind: value.kind.clone(),
1469                object_id: &value.object_id,
1470                layer: None,
1471                layers: &[],
1472                placement: None,
1473                operations: value
1474                    .operations
1475                    .iter()
1476                    .map(schematic_sheet_operation)
1477                    .collect(),
1478            },
1479        })
1480        .collect()
1481}
1482
1483#[allow(
1484    clippy::too_many_lines,
1485    reason = "exhaustive board record-union inventory"
1486)]
1487fn normalize_board_records(document: &board::BoardPlotDocumentA0) -> Vec<NormalizedRecord<'_>> {
1488    document
1489        .records
1490        .iter()
1491        .map(|record| match record {
1492            board::BoardPlotRecord::BoardGraphicPlotRecord(value) => normalized_common(
1493                &value.uuid,
1494                value.kind.to_string(),
1495                &value.object_id,
1496                value.layer.as_deref(),
1497                &[],
1498                &value.operations,
1499            ),
1500            board::BoardPlotRecord::TrackSegmentPlotRecord(value) => normalized_common(
1501                &value.uuid,
1502                value.kind.clone(),
1503                &value.object_id,
1504                Some(&value.layer),
1505                &[],
1506                &value.operations,
1507            ),
1508            board::BoardPlotRecord::TrackArcPlotRecord(value) => normalized_common(
1509                &value.uuid,
1510                value.kind.clone(),
1511                &value.object_id,
1512                Some(&value.layer),
1513                &[],
1514                &value.operations,
1515            ),
1516            board::BoardPlotRecord::ViaPlotRecord(value) => normalized_common(
1517                &value.uuid,
1518                value.kind.clone(),
1519                &value.object_id,
1520                None,
1521                &value.layers,
1522                &value.operations,
1523            ),
1524            board::BoardPlotRecord::TablePlotRecord(value) => normalized_common(
1525                &value.uuid,
1526                value.kind.clone(),
1527                &value.object_id,
1528                None,
1529                &value.layers,
1530                &value.operations,
1531            ),
1532            board::BoardPlotRecord::DimensionPlotRecord(value) => normalized_common(
1533                &value.uuid,
1534                value.kind.clone(),
1535                &value.object_id,
1536                None,
1537                &value.layers,
1538                &value.operations,
1539            ),
1540            board::BoardPlotRecord::ZoneFillPlotRecord(value) => {
1541                let mut record = normalized_common(
1542                    &value.uuid,
1543                    value.kind.clone(),
1544                    &value.object_id,
1545                    None,
1546                    &value.layers,
1547                    &value.operations,
1548                );
1549                for (operation, layer) in record.operations.iter_mut().zip(&value.fill_layers) {
1550                    set_operation_layer(operation, layer);
1551                }
1552                record
1553            }
1554            board::BoardPlotRecord::BoardTextPlotRecord(value) => normalized_common(
1555                &value.uuid,
1556                value.kind.clone(),
1557                &value.object_id,
1558                Some(&value.layer),
1559                &[],
1560                &value.operations,
1561            ),
1562            board::BoardPlotRecord::BoardTextBoxPlotRecord(value) => normalized_common(
1563                &value.uuid,
1564                value.kind.clone(),
1565                &value.object_id,
1566                Some(&value.layer),
1567                &[],
1568                &value.operations,
1569            ),
1570            board::BoardPlotRecord::BoardFootprintPlotRecord(value) => NormalizedRecord {
1571                uuid: &value.uuid,
1572                kind: value.kind.clone(),
1573                object_id: &value.object_id,
1574                // The footprint side is placement metadata. Its children and
1575                // ownership blocks carry the authoritative render layers.
1576                layer: None,
1577                layers: &[],
1578                placement: Some((
1579                    value.placement.x_nm.get(),
1580                    value.placement.y_nm.get(),
1581                    value.placement.angle_deg,
1582                )),
1583                operations: value
1584                    .operations
1585                    .iter()
1586                    .map(board_footprint_operation)
1587                    .collect(),
1588            },
1589        })
1590        .collect()
1591}
1592
1593fn normalized_common<'a>(
1594    uuid: &'a str,
1595    kind: String,
1596    object_id: &'a str,
1597    layer: Option<&'a str>,
1598    layers: &'a [String],
1599    operations: &'a [board::PlotterOperation],
1600) -> NormalizedRecord<'a> {
1601    NormalizedRecord {
1602        uuid,
1603        kind,
1604        object_id,
1605        layer,
1606        layers,
1607        placement: None,
1608        operations: operations.iter().map(board_operation).collect(),
1609    }
1610}
1611
1612fn set_operation_layer<'a>(operation: &mut OperationData<'a>, layer: &'a str) {
1613    match operation {
1614        OperationData::Owned { operation, .. } => set_operation_layer(operation, layer),
1615        OperationData::Segment { style, .. }
1616        | OperationData::Arc { style, .. }
1617        | OperationData::Circle { style, .. }
1618        | OperationData::Rect { style, .. }
1619        | OperationData::Poly { style, .. }
1620        | OperationData::Bezier { style, .. } => style.layer = Some(layer),
1621        OperationData::Text(text) => text.layer = Some(layer),
1622        _ => {}
1623    }
1624}
1625
1626fn validate_board_layer_selection(
1627    artifact: &ProjectedBoardPlotArtifact,
1628    context: &ValidatedSvgRenderContextA1,
1629) -> Result<(), SvgError> {
1630    let crate::LayerSelection::Include {
1631        patterns,
1632        strict: true,
1633    } = context.layer_selection()
1634    else {
1635        return Ok(());
1636    };
1637    for pattern in patterns {
1638        if !matches!(pattern, crate::LayerPattern::Unlayered)
1639            && !artifact
1640                .render_facts()
1641                .enabled_layers()
1642                .iter()
1643                .any(|enabled| pattern.matches(Some(enabled)))
1644        {
1645            return Err(direct_error(
1646                SvgErrorKind::UnsupportedSelector,
1647                format!("strict board layer selector {pattern:?} matches no enabled layer"),
1648            ));
1649        }
1650    }
1651    Ok(())
1652}
1653
1654fn validate_footprint_layer_selection(
1655    document: &footprint::FootprintPlotDocumentA0,
1656    context: &ValidatedSvgRenderContextA1,
1657) -> Result<(), SvgError> {
1658    let crate::LayerSelection::Include {
1659        patterns,
1660        strict: true,
1661    } = context.layer_selection()
1662    else {
1663        return Ok(());
1664    };
1665    let represented = document
1666        .records
1667        .iter()
1668        .flat_map(|record| &record.operations)
1669        .flat_map(|operation| {
1670            let operation = footprint_operation(operation);
1671            let (layer, layers, _) = operation_scope(&operation);
1672            layer
1673                .into_iter()
1674                .chain(layers.iter().map(String::as_str))
1675                .map(str::to_owned)
1676                .collect::<Vec<_>>()
1677        })
1678        .collect::<Vec<_>>();
1679    for pattern in patterns {
1680        let matched = match pattern {
1681            crate::LayerPattern::Unlayered => document.records.iter().any(|record| {
1682                record.operations.iter().any(|operation| {
1683                    let operation = footprint_operation(operation);
1684                    let (layer, layers, _) = operation_scope(&operation);
1685                    layer.is_none() && layers.is_empty()
1686                })
1687            }),
1688            _ => represented.iter().any(|layer| pattern.matches(Some(layer))),
1689        };
1690        if !matched {
1691            return Err(direct_error(
1692                SvgErrorKind::UnsupportedSelector,
1693                format!("strict footprint layer selector {pattern:?} matches no represented layer"),
1694            ));
1695        }
1696    }
1697    Ok(())
1698}
1699
1700struct RecordView<'a, O> {
1701    uuid: &'a str,
1702    kind: &'a str,
1703    object_id: &'a str,
1704    operations: &'a [O],
1705}
1706
1707#[derive(Clone, Copy, Debug)]
1708struct BoundsTransform {
1709    translate_x: f64,
1710    translate_y: f64,
1711    angle_deg: f64,
1712}
1713
1714impl Default for BoundsTransform {
1715    fn default() -> Self {
1716        Self {
1717            translate_x: 0.0,
1718            translate_y: 0.0,
1719            angle_deg: 0.0,
1720        }
1721    }
1722}
1723
1724impl BoundsTransform {
1725    fn point(self, point: Point) -> (f64, f64) {
1726        self.point_f64((point.0 as f64, point.1 as f64))
1727    }
1728
1729    fn point_f64(self, point: (f64, f64)) -> (f64, f64) {
1730        let (x, y) = rotate_offset(point.0, point.1, self.angle_deg);
1731        (x + self.translate_x, y + self.translate_y)
1732    }
1733}
1734
1735#[derive(Default)]
1736struct BoundsAccumulator {
1737    min_x: f64,
1738    min_y: f64,
1739    max_x: f64,
1740    max_y: f64,
1741    has_geometry: bool,
1742    estimated_text: bool,
1743}
1744
1745impl BoundsAccumulator {
1746    fn point(&mut self, point: (f64, f64), radius: f64) {
1747        let (min_x, min_y) = (point.0 - radius, point.1 - radius);
1748        let (max_x, max_y) = (point.0 + radius, point.1 + radius);
1749        if self.has_geometry {
1750            self.min_x = self.min_x.min(min_x);
1751            self.min_y = self.min_y.min(min_y);
1752            self.max_x = self.max_x.max(max_x);
1753            self.max_y = self.max_y.max(max_y);
1754        } else {
1755            self.min_x = min_x;
1756            self.min_y = min_y;
1757            self.max_x = max_x;
1758            self.max_y = max_y;
1759            self.has_geometry = true;
1760        }
1761    }
1762
1763    fn finish(&self) -> Result<Option<SvgBounds>, SvgError> {
1764        if !self.has_geometry {
1765            return Ok(None);
1766        }
1767        for value in [self.min_x, self.min_y, self.max_x, self.max_y] {
1768            if !value.is_finite() || value < i64::MIN as f64 || value > i64::MAX as f64 {
1769                return Err(direct_error(
1770                    SvgErrorKind::ArithmeticOverflow,
1771                    "SVG visible bounds exceed i64",
1772                ));
1773            }
1774        }
1775        Ok(Some(SvgBounds {
1776            min_x_nm: self.min_x.floor() as i64,
1777            min_y_nm: self.min_y.floor() as i64,
1778            max_x_nm: self.max_x.ceil() as i64,
1779            max_y_nm: self.max_y.ceil() as i64,
1780        }))
1781    }
1782}
1783
1784fn resolve_typed_viewport<'a, O: 'a>(
1785    records: impl Iterator<Item = RecordView<'a, O>>,
1786    adapter: fn(&'a O) -> OperationData<'a>,
1787    source_kind: &str,
1788    policy: ViewportPolicy,
1789    context: &ValidatedSvgRenderContextA1,
1790) -> Result<(SvgViewport, Option<SvgBounds>, Vec<SvgWarning>), SvgError> {
1791    let mut bounds = BoundsAccumulator::default();
1792    for record in records {
1793        let scope = RenderScope {
1794            semantic_role: Some(record_semantic_role(source_kind, record.kind)),
1795            ..RenderScope::default()
1796        };
1797        for operation in record.operations {
1798            add_operation_bounds(
1799                &adapter(operation),
1800                scope,
1801                context,
1802                BoundsTransform::default(),
1803                &mut bounds,
1804            )?;
1805        }
1806    }
1807    resolve_viewport(policy, bounds)
1808}
1809
1810fn resolve_normalized_viewport(
1811    records: &[NormalizedRecord<'_>],
1812    source_kind: &str,
1813    policy: ViewportPolicy,
1814    context: &ValidatedSvgRenderContextA1,
1815    copper_stack: Option<&[String]>,
1816) -> Result<(SvgViewport, Option<SvgBounds>, Vec<SvgWarning>), SvgError> {
1817    let mut bounds = BoundsAccumulator::default();
1818    for record in records {
1819        let scope = RenderScope {
1820            layer: record.layer,
1821            layers: record.layers,
1822            semantic_role: Some(record_semantic_role(source_kind, &record.kind)),
1823            primitive_class: record_primitive_class(source_kind, &record.kind),
1824            pin_text: None,
1825            pin_number: None,
1826            copper_stack,
1827        };
1828        let transform = record
1829            .placement
1830            .map_or_else(BoundsTransform::default, |value| BoundsTransform {
1831                translate_x: value.0 as f64,
1832                translate_y: value.1 as f64,
1833                angle_deg: -value.2,
1834            });
1835        add_operation_sequence_bounds(&record.operations, scope, context, transform, &mut bounds)?;
1836    }
1837    resolve_viewport(policy, bounds)
1838}
1839
1840fn add_operation_sequence_bounds(
1841    operations: &[OperationData<'_>],
1842    scope: RenderScope<'_>,
1843    context: &ValidatedSvgRenderContextA1,
1844    transform: BoundsTransform,
1845    bounds: &mut BoundsAccumulator,
1846) -> Result<(), SvgError> {
1847    let mut index = 0usize;
1848    while index < operations.len() {
1849        match &operations[index] {
1850            start @ OperationData::StartBlock { .. } => {
1851                let end = matching_block_end(operations, index)?;
1852                add_operation_sequence_bounds(
1853                    &operations[index + 1..end],
1854                    block_scope(scope, start),
1855                    context,
1856                    transform,
1857                    bounds,
1858                )?;
1859                index = end + 1;
1860            }
1861            OperationData::EndBlock => {
1862                return Err(direct_error(
1863                    SvgErrorKind::UnbalancedBlock,
1864                    "plot document contains an orphan EndBlock",
1865                ));
1866            }
1867            operation => {
1868                add_operation_bounds(
1869                    operation,
1870                    block_child_scope(scope, operation),
1871                    context,
1872                    transform,
1873                    bounds,
1874                )?;
1875                index += 1;
1876            }
1877        }
1878    }
1879    Ok(())
1880}
1881
1882fn resolve_viewport(
1883    policy: ViewportPolicy,
1884    bounds: BoundsAccumulator,
1885) -> Result<(SvgViewport, Option<SvgBounds>, Vec<SvgWarning>), SvgError> {
1886    let visible_bounds = bounds.finish()?;
1887    let mut warnings = Vec::new();
1888    if bounds.estimated_text {
1889        warnings.push(SvgWarning::EstimatedBoundsForUncachedText);
1890    }
1891    match policy {
1892        ViewportPolicy::Explicit(viewport) => {
1893            validate_viewport(viewport)?;
1894            Ok((viewport, visible_bounds, warnings))
1895        }
1896        ViewportPolicy::Fit(options) => {
1897            let Some(visible_bounds) = visible_bounds else {
1898                let viewport = options.fallback.ok_or_else(|| {
1899                    direct_error(
1900                        SvgErrorKind::EmptyBounds,
1901                        "fit viewport has no visible geometry",
1902                    )
1903                })?;
1904                validate_viewport(viewport)?;
1905                return Ok((viewport, None, warnings));
1906            };
1907            Ok((
1908                fit_viewport(visible_bounds, options)?,
1909                Some(visible_bounds),
1910                warnings,
1911            ))
1912        }
1913    }
1914}
1915
1916fn validate_viewport(viewport: SvgViewport) -> Result<(), SvgError> {
1917    if viewport.width_nm == 0 || viewport.height_nm == 0 {
1918        Err(direct_error(
1919            SvgErrorKind::InvalidViewport,
1920            "explicit SVG viewport must be positive",
1921        ))
1922    } else {
1923        Ok(())
1924    }
1925}
1926
1927fn fit_viewport(bounds: SvgBounds, options: SvgFitOptions) -> Result<SvgViewport, SvgError> {
1928    let padding = i128::from(options.padding_nm);
1929    let mut min_x = i128::from(bounds.min_x_nm) - padding;
1930    let mut min_y = i128::from(bounds.min_y_nm) - padding;
1931    let mut width = i128::from(bounds.max_x_nm) - i128::from(bounds.min_x_nm) + padding * 2;
1932    let mut height = i128::from(bounds.max_y_nm) - i128::from(bounds.min_y_nm) + padding * 2;
1933    let minimum = i128::from(options.min_extent_nm.max(1));
1934    if width < minimum {
1935        let difference = minimum - width;
1936        min_x -= difference / 2;
1937        width = minimum;
1938    }
1939    if height < minimum {
1940        let difference = minimum - height;
1941        min_y -= difference / 2;
1942        height = minimum;
1943    }
1944    Ok(SvgViewport {
1945        min_x_nm: i64::try_from(min_x)
1946            .map_err(|_| overflow_error("fitted viewport X exceeds i64"))?,
1947        min_y_nm: i64::try_from(min_y)
1948            .map_err(|_| overflow_error("fitted viewport Y exceeds i64"))?,
1949        width_nm: u64::try_from(width)
1950            .map_err(|_| overflow_error("fitted viewport width exceeds u64"))?,
1951        height_nm: u64::try_from(height)
1952            .map_err(|_| overflow_error("fitted viewport height exceeds u64"))?,
1953    })
1954}
1955
1956#[allow(
1957    clippy::too_many_lines,
1958    reason = "exhaustive geometry-union bounds traversal is kept auditable in one match"
1959)]
1960fn add_operation_bounds(
1961    operation: &OperationData<'_>,
1962    scope: RenderScope<'_>,
1963    context: &ValidatedSvgRenderContextA1,
1964    transform: BoundsTransform,
1965    bounds: &mut BoundsAccumulator,
1966) -> Result<(), SvgError> {
1967    let scope = owned_scope(scope, operation);
1968    if let OperationData::Owned { operation, .. } = operation {
1969        return add_operation_bounds(operation, scope, context, transform, bounds);
1970    }
1971    if !operation_visible(operation, context, scope) {
1972        return Ok(());
1973    }
1974    let stroke_radius = operation_stroke_radius(operation, scope, context)?;
1975    match operation {
1976        OperationData::Owned { .. } => unreachable!(),
1977        OperationData::Segment { start, end, .. } => {
1978            bounds.point(transform.point(*start), stroke_radius);
1979            bounds.point(transform.point(*end), stroke_radius);
1980        }
1981        OperationData::Arc {
1982            start, mid, end, ..
1983        } => {
1984            if let Some((center, radius)) = circumcircle(*start, *mid, *end) {
1985                add_arc_bounds(
1986                    *start,
1987                    *mid,
1988                    *end,
1989                    center,
1990                    radius,
1991                    transform,
1992                    stroke_radius,
1993                    bounds,
1994                );
1995            } else {
1996                bounds.point(transform.point(*start), stroke_radius);
1997                bounds.point(transform.point(*end), stroke_radius);
1998            }
1999        }
2000        OperationData::Circle {
2001            center,
2002            diameter_nm,
2003            ..
2004        } => {
2005            nonnegative(*diameter_nm, "diameter_nm")?;
2006            bounds.point(
2007                transform.point(*center),
2008                (*diameter_nm as f64) / 2.0 + stroke_radius,
2009            );
2010        }
2011        OperationData::Rect { first, second, .. } => {
2012            for point in [*first, (first.0, second.1), *second, (second.0, first.1)] {
2013                bounds.point(transform.point(point), stroke_radius);
2014            }
2015        }
2016        OperationData::Poly { points, .. } => {
2017            for point in points {
2018                bounds.point(transform.point(*point), stroke_radius);
2019            }
2020        }
2021        OperationData::Bezier { points, .. } => {
2022            for point in points {
2023                bounds.point(transform.point(*point), stroke_radius);
2024            }
2025        }
2026        OperationData::Text(text) => {
2027            nonnegative(text.size_x_nm, "size_x_nm")?;
2028            nonnegative(text.size_y_nm, "size_y_nm")?;
2029            if text.size_x_nm == 0 || text.size_y_nm == 0 {
2030                return Ok(());
2031            }
2032            let mut cached = false;
2033            for point in text.cache.iter().flatten().flatten() {
2034                bounds.point(transform.point(*point), 0.0);
2035                cached = true;
2036            }
2037            for point in text.legacy_cache.iter().flatten() {
2038                bounds.point(transform.point(*point), 0.0);
2039                cached = true;
2040            }
2041            if !cached {
2042                add_uncached_text_bounds(text, transform, bounds)?;
2043            }
2044        }
2045        OperationData::Image {
2046            center,
2047            width_nm,
2048            height_nm,
2049            ..
2050        } => {
2051            nonnegative(*width_nm, "width_nm")?;
2052            nonnegative(*height_nm, "height_nm")?;
2053            let half_x = (*width_nm as f64) / 2.0;
2054            let half_y = (*height_nm as f64) / 2.0;
2055            for point in [
2056                (center.0 as f64 - half_x, center.1 as f64 - half_y),
2057                (center.0 as f64 + half_x, center.1 as f64 - half_y),
2058                (center.0 as f64 + half_x, center.1 as f64 + half_y),
2059                (center.0 as f64 - half_x, center.1 as f64 + half_y),
2060            ] {
2061                bounds.point(
2062                    transform.point((point.0.round() as i64, point.1.round() as i64)),
2063                    0.0,
2064                );
2065            }
2066        }
2067        OperationData::PadCircle {
2068            center,
2069            diameter_nm,
2070            mask_margin_nm,
2071            layers,
2072            ..
2073        } => {
2074            let diameter_nm = expanded_pad_dimension(
2075                *diameter_nm,
2076                selected_mask_margin(context, scope, layers, *mask_margin_nm),
2077                "diameter_nm",
2078            )?;
2079            bounds.point(
2080                transform.point(*center),
2081                (diameter_nm as f64) / 2.0 + stroke_radius,
2082            );
2083        }
2084        OperationData::PadOval {
2085            center,
2086            size,
2087            angle_deg,
2088            mask_margin_nm,
2089            layers,
2090            ..
2091        } => {
2092            let size = expanded_pad_size(
2093                *size,
2094                selected_mask_margin(context, scope, layers, *mask_margin_nm),
2095            )?;
2096            if let Some(line) = pad_oval_centerline(*center, size)? {
2097                for point_twice in [line.first_twice, line.second_twice] {
2098                    let point = (point_twice.0 as f64 / 2.0, point_twice.1 as f64 / 2.0);
2099                    let offset = (point.0 - center.0 as f64, point.1 - center.1 as f64);
2100                    let rotated = rotate_offset(offset.0, offset.1, -*angle_deg);
2101                    bounds.point(
2102                        transform
2103                            .point_f64((center.0 as f64 + rotated.0, center.1 as f64 + rotated.1)),
2104                        stroke_radius,
2105                    );
2106                }
2107            } else {
2108                bounds.point(
2109                    transform.point(*center),
2110                    size.0 as f64 / 2.0 + stroke_radius,
2111                );
2112            }
2113        }
2114        OperationData::PadRect {
2115            center,
2116            size,
2117            angle_deg,
2118            mask_margin_nm,
2119            layers,
2120            ..
2121        } => add_rotated_box_bounds(
2122            *center,
2123            expanded_pad_size(
2124                *size,
2125                selected_mask_margin(context, scope, layers, *mask_margin_nm),
2126            )?,
2127            *angle_deg,
2128            transform,
2129            stroke_radius,
2130            bounds,
2131        )?,
2132        OperationData::PadCustom {
2133            center,
2134            angle_deg,
2135            polygons,
2136            ..
2137        } => {
2138            for polygon in polygons {
2139                add_local_points_bounds(
2140                    *center,
2141                    *angle_deg,
2142                    polygon,
2143                    transform,
2144                    stroke_radius,
2145                    bounds,
2146                );
2147            }
2148        }
2149        OperationData::PadTrapez {
2150            center,
2151            angle_deg,
2152            corners,
2153            ..
2154        } => add_local_points_bounds(
2155            *center,
2156            *angle_deg,
2157            corners,
2158            transform,
2159            stroke_radius,
2160            bounds,
2161        ),
2162        OperationData::StartBlock { .. } | OperationData::EndBlock => {}
2163    }
2164    Ok(())
2165}
2166
2167/// Add deterministic robust estimated bounds for browser-font text.
2168///
2169/// Plotter-IR a0 retains the nominal X/Y font size and alignment but no shaped
2170/// glyph metrics for uncached text. One horizontal em per Unicode scalar plus
2171/// an extra horizontal em for italic/bold and one nominal em of safety on every
2172/// side keeps ordinary browser fonts inside fitted previews. The warning
2173/// returned with the artifact distinguishes this heuristic from exact retained
2174/// contour bounds, especially when callers override the font face.
2175fn add_uncached_text_bounds(
2176    text: &TextData<'_>,
2177    transform: BoundsTransform,
2178    bounds: &mut BoundsAccumulator,
2179) -> Result<(), SvgError> {
2180    nonnegative(text.size_x_nm, "size_x_nm")?;
2181    nonnegative(text.size_y_nm, "size_y_nm")?;
2182    if text.size_x_nm == 0 || text.size_y_nm == 0 || text.text.is_empty() {
2183        return Ok(());
2184    }
2185    let line_count = if text.multiline {
2186        text.text
2187            .bytes()
2188            .filter(|byte| *byte == b'\n')
2189            .count()
2190            .checked_add(1)
2191            .ok_or_else(|| overflow_error("text line count overflowed"))?
2192    } else {
2193        1
2194    };
2195    let (first, step) = if line_count > 1 {
2196        direct_multiline_positions(text, line_count)?
2197    } else {
2198        ((text.x, text.y), (0, 0))
2199    };
2200    let height = text.size_y_nm as f64;
2201    let mut add_line = |index: usize, line: &str| -> Result<(), SvgError> {
2202        if line.is_empty() {
2203            return Ok(());
2204        }
2205        let index =
2206            i64::try_from(index).map_err(|_| overflow_error("text line index exceeds i64"))?;
2207        let x = checked_line_coordinate(first.0, step.0, index)?;
2208        let y = checked_line_coordinate(first.1, step.1, index)?;
2209        let scalar_count = i128::try_from(line.chars().count())
2210            .map_err(|_| overflow_error("text scalar count exceeds i128"))?;
2211        let overhang = i128::from(u8::from(text.bold || text.italic));
2212        let width_nm = i128::from(text.size_x_nm)
2213            .checked_mul(scalar_count + overhang)
2214            .ok_or_else(|| overflow_error("estimated text width overflowed"))?;
2215        let width = i64::try_from(width_nm)
2216            .map_err(|_| overflow_error("estimated text width exceeds i64"))?
2217            as f64;
2218        let (base_min_x, base_max_x) = if text.h_align.ends_with("CENTER") {
2219            (-width / 2.0, width / 2.0)
2220        } else if text.h_align.ends_with("RIGHT") {
2221            (-width, 0.0)
2222        } else {
2223            (0.0, width)
2224        };
2225        let (base_min_y, base_max_y) = if text.v_align.ends_with("TOP") {
2226            (0.0, height)
2227        } else if text.v_align.ends_with("CENTER") {
2228            (-height / 2.0, height / 2.0)
2229        } else if text.v_align.ends_with("BOTTOM") {
2230            (-height, 0.0)
2231        } else {
2232            (-height, height / 4.0)
2233        };
2234        let horizontal_margin = text.size_x_nm as f64;
2235        let vertical_margin = text.size_y_nm as f64;
2236        let min_x = base_min_x - horizontal_margin;
2237        let max_x = base_max_x + horizontal_margin;
2238        let min_y = base_min_y - vertical_margin;
2239        let max_y = base_max_y + vertical_margin;
2240        for offset in [
2241            (min_x, min_y),
2242            (max_x, min_y),
2243            (max_x, max_y),
2244            (min_x, max_y),
2245        ] {
2246            let local_x = if text.mirror { -offset.0 } else { offset.0 };
2247            let rotated = rotate_offset(local_x, offset.1, -text.orient_deg);
2248            bounds.point(
2249                transform.point_f64((x as f64 + rotated.0, y as f64 + rotated.1)),
2250                0.0,
2251            );
2252        }
2253        bounds.estimated_text = true;
2254        Ok(())
2255    };
2256    if text.multiline {
2257        for (index, line) in text.text.split('\n').enumerate() {
2258            add_line(index, line)?;
2259        }
2260    } else {
2261        add_line(0, text.text)?;
2262    }
2263    Ok(())
2264}
2265
2266#[allow(
2267    clippy::too_many_arguments,
2268    reason = "arc bounds receives the already-computed circle and render transform"
2269)]
2270fn add_arc_bounds(
2271    start: Point,
2272    mid: Point,
2273    end: Point,
2274    center: (f64, f64),
2275    radius: f64,
2276    transform: BoundsTransform,
2277    stroke_radius: f64,
2278    bounds: &mut BoundsAccumulator,
2279) {
2280    let angle = |point: Point| (point.1 as f64 - center.1).atan2(point.0 as f64 - center.0);
2281    let start_angle = angle(start);
2282    let mid_angle = angle(mid);
2283    let end_angle = angle(end);
2284    let ccw_total = (end_angle - start_angle).rem_euclid(std::f64::consts::TAU);
2285    let ccw_mid = (mid_angle - start_angle).rem_euclid(std::f64::consts::TAU);
2286    let counter_clockwise = ccw_mid <= ccw_total;
2287    let on_sweep = |candidate: f64| {
2288        let candidate_span = if counter_clockwise {
2289            (candidate - start_angle).rem_euclid(std::f64::consts::TAU)
2290        } else {
2291            (start_angle - candidate).rem_euclid(std::f64::consts::TAU)
2292        };
2293        let total_span = if counter_clockwise {
2294            ccw_total
2295        } else {
2296            (start_angle - end_angle).rem_euclid(std::f64::consts::TAU)
2297        };
2298        candidate_span <= total_span + f64::EPSILON * 16.0
2299    };
2300    for point in [start, end] {
2301        bounds.point(transform.point(point), stroke_radius);
2302    }
2303    let transform_radians = transform.angle_deg.to_radians();
2304    for world_cardinal in [
2305        0.0,
2306        std::f64::consts::FRAC_PI_2,
2307        std::f64::consts::PI,
2308        std::f64::consts::PI * 1.5,
2309    ] {
2310        let local_angle = world_cardinal - transform_radians;
2311        if on_sweep(local_angle) {
2312            let point = (
2313                center.0 + radius * local_angle.cos(),
2314                center.1 + radius * local_angle.sin(),
2315            );
2316            bounds.point(transform.point_f64(point), stroke_radius);
2317        }
2318    }
2319}
2320
2321fn add_rotated_box_bounds(
2322    center: Point,
2323    size: Point,
2324    angle_deg: f64,
2325    transform: BoundsTransform,
2326    radius: f64,
2327    bounds: &mut BoundsAccumulator,
2328) -> Result<(), SvgError> {
2329    nonnegative(size.0, "size_x_nm")?;
2330    nonnegative(size.1, "size_y_nm")?;
2331    let half_x = size.0 as f64 / 2.0;
2332    let half_y = size.1 as f64 / 2.0;
2333    for point in [
2334        (-half_x, -half_y),
2335        (half_x, -half_y),
2336        (half_x, half_y),
2337        (-half_x, half_y),
2338    ] {
2339        let rotated = rotate_offset(point.0, point.1, -angle_deg);
2340        bounds.point(
2341            transform.point((
2342                (center.0 as f64 + rotated.0).round() as i64,
2343                (center.1 as f64 + rotated.1).round() as i64,
2344            )),
2345            radius,
2346        );
2347    }
2348    Ok(())
2349}
2350
2351fn add_local_points_bounds(
2352    center: Point,
2353    angle_deg: f64,
2354    points: &[Point],
2355    transform: BoundsTransform,
2356    radius: f64,
2357    bounds: &mut BoundsAccumulator,
2358) {
2359    for point in points {
2360        let rotated = rotate_offset(point.0 as f64, point.1 as f64, -angle_deg);
2361        bounds.point(
2362            transform.point((
2363                (center.0 as f64 + rotated.0).round() as i64,
2364                (center.1 as f64 + rotated.1).round() as i64,
2365            )),
2366            radius,
2367        );
2368    }
2369}
2370
2371fn circumcircle(start: Point, mid: Point, end: Point) -> Option<((f64, f64), f64)> {
2372    let (ax, ay) = (start.0 as f64, start.1 as f64);
2373    let (bx, by) = (mid.0 as f64, mid.1 as f64);
2374    let (cx, cy) = (end.0 as f64, end.1 as f64);
2375    let divisor = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
2376    if divisor == 0.0 {
2377        return None;
2378    }
2379    let a2 = ax * ax + ay * ay;
2380    let b2 = bx * bx + by * by;
2381    let c2 = cx * cx + cy * cy;
2382    let x = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / divisor;
2383    let y = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / divisor;
2384    Some(((x, y), (ax - x).hypot(ay - y)))
2385}
2386
2387fn operation_stroke_radius(
2388    operation: &OperationData<'_>,
2389    scope: RenderScope<'_>,
2390    context: &ValidatedSvgRenderContextA1,
2391) -> Result<f64, SvgError> {
2392    let scope = owned_scope(scope, operation);
2393    if let OperationData::Owned { operation, .. } = operation {
2394        return operation_stroke_radius(operation, scope, context);
2395    }
2396    let (_, _, kind) = operation_scope(operation);
2397    let mut source = match operation {
2398        OperationData::Segment { style, .. }
2399        | OperationData::Arc { style, .. }
2400        | OperationData::Circle { style, .. }
2401        | OperationData::Rect { style, .. }
2402        | OperationData::Poly { style, .. }
2403        | OperationData::Bezier { style, .. } => style.clone(),
2404        OperationData::PadOval {
2405            center,
2406            size,
2407            mask_margin_nm,
2408            layers,
2409            ..
2410        } if size.0 != size.1 => {
2411            let size = expanded_pad_size(
2412                *size,
2413                selected_mask_margin(context, scope, layers, *mask_margin_nm),
2414            )?;
2415            let line = pad_oval_centerline(*center, size)?.ok_or_else(|| {
2416                direct_error(
2417                    SvgErrorKind::InvalidDocument,
2418                    "non-circular oval pad has no centerline",
2419                )
2420            })?;
2421            pad_oval_style(
2422                line.width_nm,
2423                RenderScope {
2424                    layers: if layers.is_empty() {
2425                        scope.layers
2426                    } else {
2427                        layers
2428                    },
2429                    ..scope
2430                },
2431            )
2432        }
2433        OperationData::PadCircle { layers, .. }
2434        | OperationData::PadOval { layers, .. }
2435        | OperationData::PadRect { layers, .. }
2436        | OperationData::PadCustom { layers, .. }
2437        | OperationData::PadTrapez { layers, .. } => PrimitiveStyle {
2438            layer: scope.layer,
2439            role: None,
2440            layers: if layers.is_empty() {
2441                scope.layers
2442            } else {
2443                layers
2444            },
2445            stroke: None,
2446            fill: Some("#000000FF"),
2447            width_nm: 0,
2448            line_style: None,
2449            filled: true,
2450        },
2451        _ => return Ok(0.0),
2452    };
2453    (source.layer, source.layers) = effective_operation_layers(source.layer, source.layers, scope);
2454    let style = resolve_effective_style(&source, kind, context, scope)?;
2455    // Width 0 draws no stroke, as in KiCad's SVG plotter
2456    // (common/plotters/SVG_plotter.cpp:268-271).
2457    Ok(style.width_nm as f64 / 2.0)
2458}
2459
2460#[allow(
2461    clippy::too_many_arguments,
2462    reason = "internal engine receives the complete validated rendering boundary"
2463)]
2464fn render_typed_document<'a, O: 'a>(
2465    source_kind: &'static str,
2466    document_id: &str,
2467    record_count: usize,
2468    records: impl Clone + Iterator<Item = RecordView<'a, O>>,
2469    operation: fn(&'a O) -> OperationData<'a>,
2470    viewport_policy: ViewportPolicy,
2471    context: &ValidatedSvgRenderContextA1,
2472) -> Result<SvgArtifact, SvgError> {
2473    let mut preflight = Preflight::default();
2474    for record in records.clone() {
2475        for item in record.operations {
2476            account(&operation(item), &mut preflight)?;
2477        }
2478    }
2479    let preflight_work = checked_add(
2480        checked_add(preflight.operations, preflight.points, "render work")?,
2481        checked_add(preflight.text_bytes, preflight.image_bytes, "render work")?,
2482        "render work",
2483    )?;
2484    let bounds_work = checked_add(
2485        checked_add(preflight.operations, preflight.points, "bounds work")?,
2486        preflight.estimated_text_bounds_work,
2487        "bounds work",
2488    )?;
2489    let (viewport, visible_bounds, warnings) = resolve_typed_viewport(
2490        records.clone(),
2491        operation,
2492        source_kind,
2493        viewport_policy,
2494        context,
2495    )?;
2496    let mut sink = SvgSink::new();
2497    open_svg(&mut sink, viewport, context)?;
2498    let mut blocks = BlockState::new();
2499    for record in records {
2500        open_record(&mut sink, &record, context)?;
2501        for item in record.operations {
2502            render_operation(
2503                &operation(item),
2504                &mut sink,
2505                context,
2506                RenderScope {
2507                    semantic_role: Some(record_semantic_role(source_kind, record.kind)),
2508                    ..RenderScope::default()
2509                },
2510                &mut blocks,
2511            )?;
2512        }
2513        sink.raw("</g>\n")?;
2514    }
2515    if blocks.depth != 0 {
2516        return Err(block_error("plot document contains an unclosed block"));
2517    }
2518    sink.raw("</g>\n</svg>\n")?;
2519    let repeated_ids = sink.repeated_ids();
2520    let (svg, svg_elements, serialization_work) = sink.finish()?;
2521    let render_work = checked_add(preflight_work, serialization_work, "render work")?;
2522    let svg_bytes = svg.len();
2523    Ok(SvgArtifact {
2524        source_kind,
2525        document_id: document_id.to_owned(),
2526        svg,
2527        occurrence_address: None,
2528        viewport,
2529        visible_bounds,
2530        warnings,
2531        repeated_ids,
2532        metrics: SvgMetrics {
2533            records: record_count,
2534            operations: preflight.operations,
2535            points: preflight.points,
2536            text_bytes: preflight.text_bytes,
2537            image_encoded_bytes: preflight.image_bytes,
2538            block_depth: blocks.maximum_depth,
2539            svg_elements,
2540            render_work,
2541            svg_bytes,
2542            bounds_work,
2543        },
2544    })
2545}
2546
2547#[allow(
2548    clippy::too_many_lines,
2549    reason = "normalized heterogeneous documents retain the same two-pass engine"
2550)]
2551#[allow(
2552    clippy::too_many_arguments,
2553    reason = "the internal heterogeneous renderer receives the complete validated boundary"
2554)]
2555fn render_normalized_document(
2556    source_kind: &'static str,
2557    document_id: &str,
2558    records: Vec<NormalizedRecord<'_>>,
2559    viewport_policy: ViewportPolicy,
2560    context: &ValidatedSvgRenderContextA1,
2561    occurrence_address: Option<&str>,
2562    copper_stack: Option<&[String]>,
2563) -> Result<SvgArtifact, SvgError> {
2564    let mut preflight = Preflight::default();
2565    for record in &records {
2566        for operation in &record.operations {
2567            account(operation, &mut preflight)?;
2568        }
2569    }
2570    let preflight_work = checked_add(
2571        checked_add(preflight.operations, preflight.points, "render work")?,
2572        checked_add(preflight.text_bytes, preflight.image_bytes, "render work")?,
2573        "render work",
2574    )?;
2575    let bounds_work = checked_add(
2576        checked_add(preflight.operations, preflight.points, "bounds work")?,
2577        preflight.estimated_text_bounds_work,
2578        "bounds work",
2579    )?;
2580    let (viewport, visible_bounds, warnings) = resolve_normalized_viewport(
2581        &records,
2582        source_kind,
2583        viewport_policy,
2584        context,
2585        copper_stack,
2586    )?;
2587    let mut sink = SvgSink::new();
2588    open_svg(&mut sink, viewport, context)?;
2589    let mut blocks = BlockState::new();
2590    for record in &records {
2591        open_normalized_record(&mut sink, record, context)?;
2592        let record_depth = blocks.depth;
2593        render_operation_sequence(
2594            &record.operations,
2595            &mut sink,
2596            context,
2597            RenderScope {
2598                layer: record.layer,
2599                layers: record.layers,
2600                semantic_role: Some(record_semantic_role(source_kind, &record.kind)),
2601                primitive_class: record_primitive_class(source_kind, &record.kind),
2602                pin_text: None,
2603                pin_number: None,
2604                copper_stack,
2605            },
2606            &mut blocks,
2607        )?;
2608        if blocks.depth != record_depth {
2609            return Err(block_error("plot record contains an unclosed block"));
2610        }
2611        sink.raw("</g>\n")?;
2612    }
2613    sink.raw("</g>\n</svg>\n")?;
2614    let repeated_ids = sink.repeated_ids();
2615    let (svg, svg_elements, serialization_work) = sink.finish()?;
2616    let render_work = checked_add(preflight_work, serialization_work, "render work")?;
2617    let svg_bytes = svg.len();
2618    Ok(SvgArtifact {
2619        source_kind,
2620        document_id: document_id.to_owned(),
2621        svg,
2622        occurrence_address: occurrence_address.map(str::to_owned),
2623        viewport,
2624        visible_bounds,
2625        warnings,
2626        repeated_ids,
2627        metrics: SvgMetrics {
2628            records: records.len(),
2629            operations: preflight.operations,
2630            points: preflight.points,
2631            text_bytes: preflight.text_bytes,
2632            image_encoded_bytes: preflight.image_bytes,
2633            block_depth: blocks.maximum_depth,
2634            svg_elements,
2635            render_work,
2636            svg_bytes,
2637            bounds_work,
2638        },
2639    })
2640}
2641
2642fn account(operation: &OperationData<'_>, counts: &mut Preflight) -> Result<(), SvgError> {
2643    if let OperationData::Owned { operation, .. } = operation {
2644        return account(operation, counts);
2645    }
2646    counts.operations = checked_add(counts.operations, 1, "operations")?;
2647    let (points, text, image) = match operation {
2648        OperationData::Owned { .. } => unreachable!("owned operations were unwrapped above"),
2649        OperationData::Segment { .. } | OperationData::Rect { .. } => (2, 0, 0),
2650        OperationData::Arc { .. } => (3, 0, 0),
2651        OperationData::Circle { .. }
2652        | OperationData::PadCircle { .. }
2653        | OperationData::PadOval { .. }
2654        | OperationData::PadRect { .. } => (1, 0, 0),
2655        OperationData::Poly { points, .. } => (points.len(), 0, 0),
2656        OperationData::Bezier { .. } | OperationData::PadTrapez { .. } => (4, 0, 0),
2657        OperationData::Text(text) => {
2658            let cache_points = text
2659                .cache
2660                .iter()
2661                .flatten()
2662                .chain(&text.legacy_cache)
2663                .try_fold(0usize, |sum, points| {
2664                    checked_add(sum, points.len(), "points")
2665                })?;
2666            let has_cache_geometry = cache_points > 0;
2667            if !has_cache_geometry && text.size_x_nm != 0 && text.size_y_nm != 0 {
2668                counts.estimated_text_bounds_work = checked_add(
2669                    counts.estimated_text_bounds_work,
2670                    text.text
2671                        .len()
2672                        .checked_mul(2)
2673                        .ok_or_else(|| overflow_error("estimated text bounds work overflowed"))?,
2674                    "bounds work",
2675                )?;
2676            }
2677            (checked_add(1, cache_points, "points")?, text.text.len(), 0)
2678        }
2679        OperationData::Image { data, .. } => (1, 0, data.len()),
2680        OperationData::PadCustom { polygons, .. } => (
2681            polygons.iter().try_fold(1usize, |sum, points| {
2682                checked_add(sum, points.len(), "points")
2683            })?,
2684            0,
2685            0,
2686        ),
2687        OperationData::StartBlock { .. } | OperationData::EndBlock => (0, 0, 0),
2688    };
2689    counts.points = checked_add(counts.points, points, "points")?;
2690    counts.text_bytes = checked_add(counts.text_bytes, text, "text bytes")?;
2691    counts.image_bytes = checked_add(counts.image_bytes, image, "image bytes")?;
2692    Ok(())
2693}
2694
2695fn open_svg(
2696    sink: &mut SvgSink,
2697    viewport: SvgViewport,
2698    context: &ValidatedSvgRenderContextA1,
2699) -> Result<(), SvgError> {
2700    sink.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")?;
2701    sink.element()?;
2702    sink.raw(&format!(
2703        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{}mm\" height=\"{}mm\" viewBox=\"0 0 {} {}\">\n",
2704        format_mm(viewport.width_nm),
2705        format_mm(viewport.height_nm),
2706        format_mm(viewport.width_nm),
2707        format_mm(viewport.height_nm),
2708    ))?;
2709    if let SvgBackground::Opaque(color) = context.background() {
2710        sink.element()?;
2711        sink.raw("<rect x=\"0\" y=\"0\"")?;
2712        sink.attribute("width", &format_mm(viewport.width_nm))?;
2713        sink.attribute("height", &format_mm(viewport.height_nm))?;
2714        color_attribute(sink, "fill", color.as_str(), None)?;
2715        sink.raw("/>\n")?;
2716    }
2717    sink.element()?;
2718    sink.raw("<g")?;
2719    let x = viewport
2720        .min_x_nm
2721        .checked_neg()
2722        .ok_or_else(|| overflow_error("viewport X offset overflowed"))?;
2723    let y = viewport
2724        .min_y_nm
2725        .checked_neg()
2726        .ok_or_else(|| overflow_error("viewport Y offset overflowed"))?;
2727    sink.attribute(
2728        "transform",
2729        &format!("translate({} {})", format_nm(x), format_nm(y)),
2730    )?;
2731    sink.raw(">\n")
2732}
2733
2734fn open_record<O>(
2735    sink: &mut SvgSink,
2736    record: &RecordView<'_, O>,
2737    context: &ValidatedSvgRenderContextA1,
2738) -> Result<(), SvgError> {
2739    sink.element()?;
2740    sink.raw("<g")?;
2741    if context.identity_mode() == SvgIdentityMode::Full {
2742        sink.id_attribute(record.uuid)?;
2743        sink.attribute("data-ref", record.kind)?;
2744        sink.attribute("data-object-id", record.object_id)?;
2745    }
2746    sink.raw(">\n")
2747}
2748
2749fn open_normalized_record(
2750    sink: &mut SvgSink,
2751    record: &NormalizedRecord<'_>,
2752    context: &ValidatedSvgRenderContextA1,
2753) -> Result<(), SvgError> {
2754    sink.element()?;
2755    sink.raw("<g")?;
2756    if context.identity_mode() == SvgIdentityMode::Full {
2757        sink.id_attribute(record.uuid)?;
2758        sink.attribute("data-ref", &record.kind)?;
2759        sink.attribute("data-object-id", record.object_id)?;
2760    }
2761    if let Some((x, y, angle)) = record.placement {
2762        let mut transforms = Vec::with_capacity(2);
2763        if x != 0 || y != 0 {
2764            transforms.push(format!("translate({} {})", format_nm(x), format_nm(y)));
2765        }
2766        if angle != 0.0 {
2767            transforms.push(format!("rotate({})", number(-angle)));
2768        }
2769        if !transforms.is_empty() {
2770            sink.attribute("transform", &transforms.join(" "))?;
2771        }
2772    }
2773    sink.raw(">\n")
2774}
2775
2776fn open_ownership_group(
2777    sink: &mut SvgSink,
2778    ownership: &OwnershipData<'_>,
2779    context: &ValidatedSvgRenderContextA1,
2780) -> Result<(), SvgError> {
2781    sink.element()?;
2782    sink.raw("<g")?;
2783    if context.identity_mode() == SvgIdentityMode::Full {
2784        if let Some(label) = ownership.label {
2785            sink.id_attribute(label)?;
2786        }
2787        for (name, value) in [
2788            ("data-uuid", ownership.data_uuid),
2789            ("data-ref", ownership.data_ref.as_deref()),
2790            ("data-object-id", ownership.object_id),
2791        ] {
2792            if let Some(value) = value.filter(|value| !value.is_empty()) {
2793                sink.attribute(name, value)?;
2794            }
2795        }
2796        for (key, value) in &ownership.extra_attrs {
2797            if !value.is_empty() {
2798                sink.attribute(&format!("data-{key}"), value)?;
2799            }
2800        }
2801    }
2802    sink.raw(">\n")
2803}
2804
2805#[derive(Clone, Copy, Default)]
2806struct RenderScope<'a> {
2807    layer: Option<&'a str>,
2808    layers: &'a [String],
2809    semantic_role: Option<SvgSemanticRole>,
2810    primitive_class: Option<SvgPrimitiveClass>,
2811    pin_text: Option<PinTextKind>,
2812    pin_number: Option<&'a str>,
2813    copper_stack: Option<&'a [String]>,
2814}
2815
2816#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2817enum PinTextKind {
2818    Name,
2819    Number,
2820}
2821
2822struct BlockState {
2823    depth: usize,
2824    maximum_depth: usize,
2825}
2826
2827impl BlockState {
2828    const fn new() -> Self {
2829        Self {
2830            depth: 0,
2831            maximum_depth: 0,
2832        }
2833    }
2834}
2835
2836fn render_operation_sequence(
2837    operations: &[OperationData<'_>],
2838    sink: &mut SvgSink,
2839    context: &ValidatedSvgRenderContextA1,
2840    scope: RenderScope<'_>,
2841    blocks: &mut BlockState,
2842) -> Result<(), SvgError> {
2843    let mut index = 0usize;
2844    while index < operations.len() {
2845        match &operations[index] {
2846            start @ OperationData::StartBlock { .. } => {
2847                let end = matching_block_end(operations, index)?;
2848                let child_scope = block_scope(scope, start);
2849                if sequence_has_visible(&operations[index + 1..end], context, child_scope)? {
2850                    emit_start_block(start, sink, context, blocks)?;
2851                    render_operation_sequence(
2852                        &operations[index + 1..end],
2853                        sink,
2854                        context,
2855                        child_scope,
2856                        blocks,
2857                    )?;
2858                    emit_end_block(sink, blocks)?;
2859                }
2860                index = end + 1;
2861            }
2862            OperationData::EndBlock => {
2863                return Err(block_error("plot document contains an orphan EndBlock"));
2864            }
2865            operation => {
2866                let operation_scope = block_child_scope(scope, operation);
2867                render_operation(operation, sink, context, operation_scope, blocks)?;
2868                index += 1;
2869            }
2870        }
2871    }
2872    Ok(())
2873}
2874
2875fn sequence_has_visible(
2876    operations: &[OperationData<'_>],
2877    context: &ValidatedSvgRenderContextA1,
2878    scope: RenderScope<'_>,
2879) -> Result<bool, SvgError> {
2880    let mut index = 0usize;
2881    while index < operations.len() {
2882        match &operations[index] {
2883            start @ OperationData::StartBlock { .. } => {
2884                let end = matching_block_end(operations, index)?;
2885                if sequence_has_visible(
2886                    &operations[index + 1..end],
2887                    context,
2888                    block_scope(scope, start),
2889                )? {
2890                    return Ok(true);
2891                }
2892                index = end + 1;
2893            }
2894            OperationData::EndBlock => {
2895                return Err(block_error("plot document contains an orphan EndBlock"));
2896            }
2897            operation => {
2898                if operation_visible(operation, context, block_child_scope(scope, operation)) {
2899                    return Ok(true);
2900                }
2901                index += 1;
2902            }
2903        }
2904    }
2905    Ok(false)
2906}
2907
2908fn matching_block_end(operations: &[OperationData<'_>], start: usize) -> Result<usize, SvgError> {
2909    let mut depth = 0usize;
2910    for (index, operation) in operations.iter().enumerate().skip(start + 1) {
2911        match operation {
2912            OperationData::StartBlock { .. } => depth = depth.saturating_add(1),
2913            OperationData::EndBlock if depth == 0 => return Ok(index),
2914            OperationData::EndBlock => depth -= 1,
2915            _ => {}
2916        }
2917    }
2918    Err(block_error("plot document contains an unclosed block"))
2919}
2920
2921fn block_scope<'a>(scope: RenderScope<'a>, start: &'a OperationData<'a>) -> RenderScope<'a> {
2922    let semantic_role = match start {
2923        OperationData::StartBlock { data_ref, .. } if data_ref.contains("pin") => {
2924            Some(SvgSemanticRole::Pin)
2925        }
2926        _ => scope.semantic_role,
2927    };
2928    let primitive_class = match start {
2929        OperationData::StartBlock { extra_attrs, .. } => {
2930            class_from_attrs(extra_attrs).or(scope.primitive_class)
2931        }
2932        _ => scope.primitive_class,
2933    };
2934    RenderScope {
2935        semantic_role,
2936        primitive_class,
2937        pin_text: None,
2938        pin_number: match start {
2939            OperationData::StartBlock { extra_attrs, .. } => extra_attrs
2940                .iter()
2941                .find(|(key, _)| key == "pin")
2942                .map(|(_, value)| value.as_str()),
2943            _ => None,
2944        },
2945        ..scope
2946    }
2947}
2948
2949fn block_child_scope<'a>(
2950    scope: RenderScope<'a>,
2951    operation: &'a OperationData<'a>,
2952) -> RenderScope<'a> {
2953    if scope.semantic_role != Some(SvgSemanticRole::Pin)
2954        || !matches!(operation, OperationData::Text(_))
2955    {
2956        return RenderScope {
2957            pin_text: None,
2958            ..scope
2959        };
2960    }
2961    let OperationData::Text(text) = operation else {
2962        unreachable!();
2963    };
2964    RenderScope {
2965        pin_text: Some(if scope.pin_number == Some(text.text) {
2966            PinTextKind::Number
2967        } else {
2968            PinTextKind::Name
2969        }),
2970        ..scope
2971    }
2972}
2973
2974fn emit_start_block(
2975    operation: &OperationData<'_>,
2976    sink: &mut SvgSink,
2977    context: &ValidatedSvgRenderContextA1,
2978    blocks: &mut BlockState,
2979) -> Result<(), SvgError> {
2980    let OperationData::StartBlock {
2981        label,
2982        data_uuid,
2983        data_ref,
2984        object_id,
2985        extra_attrs,
2986    } = operation
2987    else {
2988        return Err(block_error("expected StartBlock operation"));
2989    };
2990    blocks.depth = blocks
2991        .depth
2992        .checked_add(1)
2993        .ok_or_else(|| overflow_error("block depth overflowed"))?;
2994    blocks.maximum_depth = blocks.maximum_depth.max(blocks.depth);
2995    sink.element()?;
2996    sink.raw("<g")?;
2997    if context.identity_mode() == SvgIdentityMode::Full {
2998        sink.id_attribute(label)?;
2999        if !data_uuid.is_empty() {
3000            sink.attribute("data-uuid", data_uuid)?;
3001        }
3002        if !data_ref.is_empty() {
3003            sink.attribute("data-ref", data_ref)?;
3004        }
3005        if !object_id.is_empty() {
3006            sink.attribute("data-object-id", object_id)?;
3007        }
3008        for (key, value) in extra_attrs {
3009            if !value.is_empty() {
3010                sink.attribute(&format!("data-{key}"), value)?;
3011            }
3012        }
3013    }
3014    sink.raw(">\n")
3015}
3016
3017fn emit_end_block(sink: &mut SvgSink, blocks: &mut BlockState) -> Result<(), SvgError> {
3018    if blocks.depth == 0 {
3019        return Err(block_error("plot document contains an orphan EndBlock"));
3020    }
3021    blocks.depth -= 1;
3022    sink.raw("</g>\n")
3023}
3024
3025#[allow(
3026    clippy::cognitive_complexity,
3027    clippy::too_many_lines,
3028    reason = "exhaustive typed operation emission remains one auditable match"
3029)]
3030fn render_operation(
3031    operation: &OperationData<'_>,
3032    sink: &mut SvgSink,
3033    context: &ValidatedSvgRenderContextA1,
3034    scope: RenderScope<'_>,
3035    blocks: &mut BlockState,
3036) -> Result<(), SvgError> {
3037    let scope = owned_scope(scope, operation);
3038    let inherited_layer = scope.layer;
3039    let inherited_layers = scope.layers;
3040    if !operation_visible(operation, context, scope) {
3041        return Ok(());
3042    }
3043    match operation {
3044        OperationData::Owned {
3045            ownership,
3046            operation,
3047        } => {
3048            open_ownership_group(sink, ownership, context)?;
3049            render_operation(operation, sink, context, scope, blocks)?;
3050            sink.raw("</g>\n")
3051        }
3052        OperationData::Segment { start, end, style } => {
3053            sink.element()?;
3054            sink.raw("<line")?;
3055            point_attributes(sink, *start, *end)?;
3056            emit_inherited_style(
3057                sink,
3058                style,
3059                PlotterOperationKind::ThickSegment,
3060                context,
3061                scope,
3062            )?;
3063            sink.raw("/>\n")
3064        }
3065        OperationData::Arc {
3066            start,
3067            mid,
3068            end,
3069            style,
3070        } => {
3071            sink.element()?;
3072            if let Some((radius, large, sweep)) = arc_parameters(*start, *mid, *end) {
3073                sink.raw(&format!(
3074                    "<path d=\"M {} {} A {} {} 0 {} {} {} {}\"",
3075                    format_nm(start.0),
3076                    format_nm(start.1),
3077                    format_nm_f64(radius),
3078                    format_nm_f64(radius),
3079                    u8::from(large),
3080                    u8::from(sweep),
3081                    format_nm(end.0),
3082                    format_nm(end.1),
3083                ))?;
3084            } else {
3085                sink.raw("<line")?;
3086                point_attributes(sink, *start, *end)?;
3087            }
3088            emit_inherited_style(
3089                sink,
3090                style,
3091                PlotterOperationKind::ArcThreePoint,
3092                context,
3093                scope,
3094            )?;
3095            sink.raw("/>\n")
3096        }
3097        OperationData::Circle {
3098            center,
3099            diameter_nm,
3100            style,
3101        } => {
3102            nonnegative(*diameter_nm, "diameter_nm")?;
3103            sink.element()?;
3104            sink.raw("<circle")?;
3105            sink.attribute("cx", &format_nm(center.0))?;
3106            sink.attribute("cy", &format_nm(center.1))?;
3107            sink.attribute("r", &format_half_nm(i128::from(*diameter_nm)))?;
3108            emit_inherited_style(sink, style, PlotterOperationKind::Circle, context, scope)?;
3109            sink.raw("/>\n")
3110        }
3111        OperationData::Rect {
3112            first,
3113            second,
3114            corner_radius_nm,
3115            style,
3116        } => {
3117            sink.element()?;
3118            sink.raw("<rect")?;
3119            sink.attribute("x", &format_nm(first.0.min(second.0)))?;
3120            sink.attribute("y", &format_nm(first.1.min(second.1)))?;
3121            sink.attribute("width", &format_mm(first.0.abs_diff(second.0)))?;
3122            sink.attribute("height", &format_mm(first.1.abs_diff(second.1)))?;
3123            if *corner_radius_nm > 0 {
3124                sink.attribute("rx", &format_nm(*corner_radius_nm))?;
3125                sink.attribute("ry", &format_nm(*corner_radius_nm))?;
3126            }
3127            emit_inherited_style(sink, style, PlotterOperationKind::Rect, context, scope)?;
3128            sink.raw("/>\n")
3129        }
3130        OperationData::Poly { points, style } => {
3131            let closed = style.filled || points.first() == points.last();
3132            sink.element()?;
3133            sink.raw(if closed {
3134                "<polygon points=\""
3135            } else {
3136                "<polyline points=\""
3137            })?;
3138            write_points(sink, points)?;
3139            sink.raw("\"")?;
3140            emit_inherited_style(sink, style, PlotterOperationKind::PlotPoly, context, scope)?;
3141            sink.raw("/>\n")
3142        }
3143        OperationData::Bezier { points, style } => {
3144            sink.element()?;
3145            sink.raw(&format!(
3146                "<path d=\"M {} {} C {} {}, {} {}, {} {}\"",
3147                format_nm(points[0].0),
3148                format_nm(points[0].1),
3149                format_nm(points[1].0),
3150                format_nm(points[1].1),
3151                format_nm(points[2].0),
3152                format_nm(points[2].1),
3153                format_nm(points[3].0),
3154                format_nm(points[3].1),
3155            ))?;
3156            emit_inherited_style(
3157                sink,
3158                style,
3159                PlotterOperationKind::BezierCurve,
3160                context,
3161                scope,
3162            )?;
3163            sink.raw("/>\n")
3164        }
3165        OperationData::Text(text) => render_text(text, sink, context, scope),
3166        OperationData::Image {
3167            center,
3168            width_nm,
3169            height_nm,
3170            format,
3171            data,
3172        } => render_image(*center, *width_nm, *height_nm, format, data, sink, context),
3173        OperationData::PadCircle {
3174            center,
3175            diameter_nm,
3176            mask_margin_nm,
3177            layers,
3178        } => {
3179            let pad_scope = RenderScope {
3180                layer: inherited_layer,
3181                layers: if layers.is_empty() {
3182                    inherited_layers
3183                } else {
3184                    layers
3185                },
3186                ..scope
3187            };
3188            let diameter_nm = expanded_pad_dimension(
3189                *diameter_nm,
3190                selected_mask_margin(context, scope, layers, *mask_margin_nm),
3191                "diameter_nm",
3192            )?;
3193            sink.element()?;
3194            sink.raw("<circle")?;
3195            sink.attribute("cx", &format_nm(center.0))?;
3196            sink.attribute("cy", &format_nm(center.1))?;
3197            sink.attribute("r", &format_half_nm(i128::from(diameter_nm)))?;
3198            emit_pad_style(
3199                sink,
3200                PlotterOperationKind::FlashPadCircle,
3201                context,
3202                pad_scope,
3203            )?;
3204            sink.raw("/>\n")
3205        }
3206        OperationData::PadOval {
3207            center,
3208            size,
3209            angle_deg,
3210            mask_margin_nm,
3211            layers,
3212        } => render_pad_oval(
3213            *center,
3214            expanded_pad_size(
3215                *size,
3216                selected_mask_margin(context, scope, layers, *mask_margin_nm),
3217            )?,
3218            *angle_deg,
3219            sink,
3220            context,
3221            RenderScope {
3222                layer: inherited_layer,
3223                layers: if layers.is_empty() {
3224                    inherited_layers
3225                } else {
3226                    layers
3227                },
3228                ..scope
3229            },
3230        ),
3231        OperationData::PadRect {
3232            center,
3233            size,
3234            angle_deg,
3235            radius_nm,
3236            mask_margin_nm,
3237            layers,
3238        } => {
3239            let margin = selected_mask_margin(context, scope, layers, *mask_margin_nm);
3240            let radius = expanded_pad_radius(*radius_nm, margin)?;
3241            render_pad_rect(
3242                *center,
3243                expanded_pad_size(*size, margin)?,
3244                *angle_deg,
3245                radius,
3246                sink,
3247                context,
3248                RenderScope {
3249                    layer: inherited_layer,
3250                    layers: if layers.is_empty() {
3251                        inherited_layers
3252                    } else {
3253                        layers
3254                    },
3255                    ..scope
3256                },
3257            )
3258        }
3259        OperationData::PadCustom {
3260            center,
3261            angle_deg,
3262            polygons,
3263            layers,
3264        } => {
3265            for polygon in polygons {
3266                render_local_polygon(
3267                    *center,
3268                    *angle_deg,
3269                    polygon,
3270                    sink,
3271                    context,
3272                    PlotterOperationKind::FlashPadCustom,
3273                    RenderScope {
3274                        layer: inherited_layer,
3275                        layers: if layers.is_empty() {
3276                            inherited_layers
3277                        } else {
3278                            layers
3279                        },
3280                        ..scope
3281                    },
3282                )?;
3283            }
3284            Ok(())
3285        }
3286        OperationData::PadTrapez {
3287            center,
3288            angle_deg,
3289            corners,
3290            layers,
3291        } => render_local_polygon(
3292            *center,
3293            *angle_deg,
3294            corners,
3295            sink,
3296            context,
3297            PlotterOperationKind::FlashPadTrapez,
3298            RenderScope {
3299                layer: inherited_layer,
3300                layers: if layers.is_empty() {
3301                    inherited_layers
3302                } else {
3303                    layers
3304                },
3305                ..scope
3306            },
3307        ),
3308        OperationData::StartBlock { .. } => emit_start_block(operation, sink, context, blocks),
3309        OperationData::EndBlock => emit_end_block(sink, blocks),
3310    }
3311}
3312
3313fn operation_visible(
3314    operation: &OperationData<'_>,
3315    context: &ValidatedSvgRenderContextA1,
3316    scope: RenderScope<'_>,
3317) -> bool {
3318    let scope = owned_scope(scope, operation);
3319    let (operation_layer, operation_layers, kind) = operation_scope(operation);
3320    let (layer, layers) = effective_operation_layers(operation_layer, operation_layers, scope);
3321    let preliminary_semantic =
3322        operation_semantic_role(operation, layer, layers, scope.semantic_role);
3323    let selected = context.layer_selection().is_all()
3324        || layer.is_some_and(|layer| context.layer_selection().matches(Some(layer)))
3325        || represented_layers_match(
3326            context.layer_selection(),
3327            layers,
3328            preliminary_semantic,
3329            scope.copper_stack,
3330        )
3331        || (layer.is_none() && layers.is_empty() && context.layer_selection().matches(None));
3332    if !selected {
3333        return false;
3334    }
3335    let semantic = preliminary_semantic;
3336    let mut visible = context.fallback_style().visible().unwrap_or(true);
3337    for (pattern, style) in context.layer_styles() {
3338        if pattern.matches(layer)
3339            || pattern_matches_represented(
3340                pattern,
3341                layers,
3342                preliminary_semantic,
3343                scope.copper_stack,
3344            )
3345        {
3346            visible = style.visible().unwrap_or(visible);
3347        }
3348    }
3349    if let Some(style) = context.semantic_style(semantic) {
3350        visible = style.visible().unwrap_or(visible);
3351    }
3352    if let Some(style) = primitive_style(
3353        context,
3354        RenderScope {
3355            layer,
3356            layers,
3357            ..scope
3358        },
3359        semantic,
3360    ) {
3361        visible = style.visible().unwrap_or(visible);
3362    }
3363    if let Some(style) = context.operation_style(kind) {
3364        visible = style.visible().unwrap_or(visible);
3365    }
3366    visible
3367        && match scope.pin_text {
3368            Some(PinTextKind::Name) => context.visibility().pin_names(),
3369            Some(PinTextKind::Number) => context.visibility().pin_numbers(),
3370            None => true,
3371        }
3372}
3373
3374fn effective_operation_layers<'a>(
3375    operation_layer: Option<&'a str>,
3376    operation_layers: &'a [String],
3377    scope: RenderScope<'a>,
3378) -> (Option<&'a str>, &'a [String]) {
3379    if operation_layer.is_some() || !operation_layers.is_empty() {
3380        (operation_layer, operation_layers)
3381    } else if scope.layer.is_some() {
3382        (scope.layer, &[])
3383    } else {
3384        (None, scope.layers)
3385    }
3386}
3387
3388fn selected_mask_margin(
3389    context: &ValidatedSvgRenderContextA1,
3390    scope: RenderScope<'_>,
3391    operation_layers: &[String],
3392    margin_nm: i64,
3393) -> i64 {
3394    if margin_nm == 0 || context.layer_selection().is_all() {
3395        return 0;
3396    }
3397    let (layer, layers) = effective_operation_layers(None, operation_layers, scope);
3398    let selection = context.layer_selection();
3399    let mut selected_mask = layer
3400        .filter(|layer| selection.matches(Some(layer)))
3401        .is_some_and(|layer| layer.ends_with(".Mask"));
3402    let mut selected_non_mask = layer
3403        .filter(|layer| selection.matches(Some(layer)))
3404        .is_some_and(|layer| !layer.ends_with(".Mask"));
3405    for layer in layers {
3406        if layer == "*.Mask" {
3407            selected_mask |= ["F.Mask", "B.Mask"]
3408                .into_iter()
3409                .any(|candidate| selection.matches(Some(candidate)));
3410        } else if selection.matches(Some(layer)) {
3411            if layer.ends_with(".Mask") {
3412                selected_mask = true;
3413            } else {
3414                selected_non_mask = true;
3415            }
3416        }
3417    }
3418    if selected_mask && !selected_non_mask {
3419        margin_nm
3420    } else {
3421        0
3422    }
3423}
3424
3425fn expanded_pad_dimension(value: i64, margin_nm: i64, label: &str) -> Result<i64, SvgError> {
3426    nonnegative(value, label)?;
3427    let doubled_margin = margin_nm
3428        .checked_mul(2)
3429        .ok_or_else(|| overflow_error("pad mask margin exceeds i64"))?;
3430    let expanded = value
3431        .checked_add(doubled_margin)
3432        .ok_or_else(|| overflow_error("expanded pad dimension exceeds i64"))?;
3433    nonnegative(expanded, label)?;
3434    Ok(expanded)
3435}
3436
3437fn expanded_pad_size(size: Point, margin_nm: i64) -> Result<Point, SvgError> {
3438    Ok((
3439        expanded_pad_dimension(size.0, margin_nm, "size_x_nm")?,
3440        expanded_pad_dimension(size.1, margin_nm, "size_y_nm")?,
3441    ))
3442}
3443
3444fn expanded_pad_radius(radius_nm: Option<i64>, margin_nm: i64) -> Result<Option<i64>, SvgError> {
3445    let Some(radius_nm) = radius_nm else {
3446        return Ok((margin_nm > 0).then_some(margin_nm));
3447    };
3448    nonnegative(radius_nm, "corner_radius_nm")?;
3449    Ok(Some(radius_nm.saturating_add(margin_nm).max(0)))
3450}
3451
3452fn represented_layers_match(
3453    selection: &crate::LayerSelection,
3454    layers: &[String],
3455    semantic: SvgSemanticRole,
3456    copper_stack: Option<&[String]>,
3457) -> bool {
3458    if layers.iter().any(|layer| selection.matches(Some(layer))) {
3459        return true;
3460    }
3461    let matches_candidate = |candidate: &str| selection.matches(Some(candidate));
3462    if layers.iter().any(|layer| layer == "*.Mask")
3463        && ["F.Mask", "B.Mask"].into_iter().any(matches_candidate)
3464    {
3465        return true;
3466    }
3467    let Some(copper_stack) = copper_stack else {
3468        return false;
3469    };
3470    if semantic == SvgSemanticRole::Drill
3471        && !layers
3472            .iter()
3473            .any(|layer| layer.ends_with(".Cu") || matches!(layer.as_str(), "*.Cu" | "F&B.Cu"))
3474        && copper_stack.iter().any(|layer| matches_candidate(layer))
3475    {
3476        return true;
3477    }
3478    if layers.iter().any(|layer| layer == "*.Cu")
3479        && copper_stack.iter().any(|layer| matches_candidate(layer))
3480    {
3481        return true;
3482    }
3483    if layers.iter().any(|layer| layer == "F&B.Cu") {
3484        let candidates = if semantic == SvgSemanticRole::Drill {
3485            copper_stack
3486        } else if copper_stack.len() > 1 {
3487            &copper_stack[..1]
3488        } else {
3489            copper_stack
3490        };
3491        if candidates.iter().any(|layer| matches_candidate(layer))
3492            || (semantic != SvgSemanticRole::Drill
3493                && copper_stack
3494                    .last()
3495                    .is_some_and(|layer| matches_candidate(layer)))
3496        {
3497            return true;
3498        }
3499    }
3500    if semantic != SvgSemanticRole::Drill {
3501        return false;
3502    }
3503    let mut indexes = layers
3504        .iter()
3505        .filter_map(|layer| copper_stack.iter().position(|candidate| candidate == layer));
3506    let Some(first) = indexes.next() else {
3507        return false;
3508    };
3509    let last = indexes.next_back().unwrap_or(first);
3510    let (start, end) = if first <= last {
3511        (first, last)
3512    } else {
3513        (last, first)
3514    };
3515    copper_stack[start..=end]
3516        .iter()
3517        .any(|layer| matches_candidate(layer))
3518}
3519
3520fn pattern_matches_represented(
3521    pattern: &crate::LayerPattern,
3522    layers: &[String],
3523    semantic: SvgSemanticRole,
3524    copper_stack: Option<&[String]>,
3525) -> bool {
3526    if layers.iter().any(|layer| pattern.matches(Some(layer))) {
3527        return true;
3528    }
3529    if layers.iter().any(|layer| layer == "*.Mask")
3530        && ["F.Mask", "B.Mask"]
3531            .into_iter()
3532            .any(|layer| pattern.matches(Some(layer)))
3533    {
3534        return true;
3535    }
3536    let Some(copper_stack) = copper_stack else {
3537        return false;
3538    };
3539    if semantic == SvgSemanticRole::Drill
3540        && !layers
3541            .iter()
3542            .any(|layer| layer.ends_with(".Cu") || matches!(layer.as_str(), "*.Cu" | "F&B.Cu"))
3543        && copper_stack
3544            .iter()
3545            .any(|layer| pattern.matches(Some(layer)))
3546    {
3547        return true;
3548    }
3549    if layers.iter().any(|layer| layer == "*.Cu")
3550        && copper_stack
3551            .iter()
3552            .any(|layer| pattern.matches(Some(layer)))
3553    {
3554        return true;
3555    }
3556    if layers.iter().any(|layer| layer == "F&B.Cu") {
3557        if semantic == SvgSemanticRole::Drill
3558            && copper_stack
3559                .iter()
3560                .any(|layer| pattern.matches(Some(layer)))
3561        {
3562            return true;
3563        }
3564        if copper_stack
3565            .first()
3566            .is_some_and(|layer| pattern.matches(Some(layer)))
3567            || copper_stack
3568                .last()
3569                .is_some_and(|layer| pattern.matches(Some(layer)))
3570        {
3571            return true;
3572        }
3573    }
3574    if semantic != SvgSemanticRole::Drill {
3575        return false;
3576    }
3577    let indexes = layers
3578        .iter()
3579        .filter_map(|layer| copper_stack.iter().position(|candidate| candidate == layer))
3580        .collect::<Vec<_>>();
3581    let (Some(first), Some(last)) = (indexes.first(), indexes.last()) else {
3582        return false;
3583    };
3584    let (start, end) = if first <= last {
3585        (*first, *last)
3586    } else {
3587        (*last, *first)
3588    };
3589    copper_stack[start..=end]
3590        .iter()
3591        .any(|layer| pattern.matches(Some(layer)))
3592}
3593
3594fn operation_semantic_role(
3595    operation: &OperationData<'_>,
3596    layer: Option<&str>,
3597    layers: &[String],
3598    inherited: Option<SvgSemanticRole>,
3599) -> SvgSemanticRole {
3600    match operation {
3601        OperationData::Owned { operation, .. } => {
3602            operation_semantic_role(operation, layer, layers, inherited)
3603        }
3604        OperationData::Text(_) => inherited
3605            .filter(|role| *role == SvgSemanticRole::Pin)
3606            .unwrap_or(SvgSemanticRole::Text),
3607        OperationData::Image { .. } => SvgSemanticRole::Image,
3608        OperationData::Segment { style, .. }
3609        | OperationData::Arc { style, .. }
3610        | OperationData::Circle { style, .. }
3611        | OperationData::Rect { style, .. }
3612        | OperationData::Poly { style, .. }
3613        | OperationData::Bezier { style, .. } => {
3614            let mut style = style.clone();
3615            style.layer = layer;
3616            style.layers = layers;
3617            semantic_role(&style, inherited)
3618        }
3619        OperationData::PadCircle { .. }
3620        | OperationData::PadOval { .. }
3621        | OperationData::PadRect { .. }
3622        | OperationData::PadCustom { .. }
3623        | OperationData::PadTrapez { .. } => {
3624            let style = PrimitiveStyle {
3625                layer,
3626                layers,
3627                role: None,
3628                stroke: None,
3629                fill: None,
3630                width_nm: 0,
3631                line_style: None,
3632                filled: true,
3633            };
3634            semantic_role(&style, inherited)
3635        }
3636        OperationData::StartBlock { data_ref, .. } if data_ref.contains("pin") => {
3637            SvgSemanticRole::Pin
3638        }
3639        OperationData::StartBlock { .. } | OperationData::EndBlock => {
3640            inherited.unwrap_or(SvgSemanticRole::Other)
3641        }
3642    }
3643}
3644
3645fn operation_scope<'a>(
3646    operation: &'a OperationData<'a>,
3647) -> (Option<&'a str>, &'a [String], PlotterOperationKind) {
3648    match operation {
3649        OperationData::Owned { operation, .. } => operation_scope(operation),
3650        OperationData::Segment { style, .. } => (
3651            style.layer,
3652            style.layers,
3653            PlotterOperationKind::ThickSegment,
3654        ),
3655        OperationData::Arc { style, .. } => (
3656            style.layer,
3657            style.layers,
3658            PlotterOperationKind::ArcThreePoint,
3659        ),
3660        OperationData::Circle { style, .. } => {
3661            (style.layer, style.layers, PlotterOperationKind::Circle)
3662        }
3663        OperationData::Rect { style, .. } => {
3664            (style.layer, style.layers, PlotterOperationKind::Rect)
3665        }
3666        OperationData::Poly { style, .. } => {
3667            (style.layer, style.layers, PlotterOperationKind::PlotPoly)
3668        }
3669        OperationData::Bezier { style, .. } => {
3670            (style.layer, style.layers, PlotterOperationKind::BezierCurve)
3671        }
3672        OperationData::Text(text) => (text.layer, &[], PlotterOperationKind::Text),
3673        OperationData::Image { .. } => (None, &[], PlotterOperationKind::PlotImage),
3674        OperationData::PadCircle { layers, .. } => {
3675            (None, layers, PlotterOperationKind::FlashPadCircle)
3676        }
3677        OperationData::PadOval { layers, .. } => (None, layers, PlotterOperationKind::FlashPadOval),
3678        OperationData::PadRect {
3679            radius_nm: None,
3680            layers,
3681            ..
3682        } => (None, layers, PlotterOperationKind::FlashPadRect),
3683        OperationData::PadRect {
3684            radius_nm: Some(_),
3685            layers,
3686            ..
3687        } => (None, layers, PlotterOperationKind::FlashPadRoundRect),
3688        OperationData::PadCustom { layers, .. } => {
3689            (None, layers, PlotterOperationKind::FlashPadCustom)
3690        }
3691        OperationData::PadTrapez { layers, .. } => {
3692            (None, layers, PlotterOperationKind::FlashPadTrapez)
3693        }
3694        OperationData::StartBlock { .. } => (None, &[], PlotterOperationKind::StartBlock),
3695        OperationData::EndBlock => (None, &[], PlotterOperationKind::EndBlock),
3696    }
3697}
3698
3699#[derive(Clone)]
3700struct EffectiveStyle {
3701    stroke: Option<SvgColor>,
3702    fill: Option<SvgColor>,
3703    width_nm: i64,
3704    line_style: Option<SvgLineStyle>,
3705    filled: bool,
3706    opacity: f64,
3707}
3708
3709fn emit_inherited_style<'a>(
3710    sink: &mut SvgSink,
3711    source: &PrimitiveStyle<'a>,
3712    kind: PlotterOperationKind,
3713    context: &ValidatedSvgRenderContextA1,
3714    scope: RenderScope<'a>,
3715) -> Result<(), SvgError> {
3716    let mut effective = source.clone();
3717    (effective.layer, effective.layers) =
3718        effective_operation_layers(effective.layer, effective.layers, scope);
3719    emit_style(sink, &effective, kind, context, scope)
3720}
3721
3722fn emit_style(
3723    sink: &mut SvgSink,
3724    source: &PrimitiveStyle<'_>,
3725    kind: PlotterOperationKind,
3726    context: &ValidatedSvgRenderContextA1,
3727    scope: RenderScope<'_>,
3728) -> Result<(), SvgError> {
3729    let style = resolve_effective_style(source, kind, context, scope)?;
3730    // The IR carries the width KiCad's plotter is called with; KiCad's SVG
3731    // plotter strokes nothing at width 0 (common/plotters/SVG_plotter.cpp:268-271).
3732    if style.width_nm == 0 {
3733        sink.attribute("stroke", "none")?;
3734    } else {
3735        let width = style.width_nm;
3736        let color = style.stroke.as_ref().map_or("#000000FF", SvgColor::as_str);
3737        color_attribute(sink, "stroke", color, Some(style.opacity))?;
3738        sink.attribute("stroke-width", &format_nm(width))?;
3739        sink.attribute("stroke-linecap", "round")?;
3740        sink.attribute("stroke-linejoin", "round")?;
3741        emit_dash(sink, style.line_style, width)?;
3742    }
3743    if style.filled {
3744        let color = style
3745            .fill
3746            .as_ref()
3747            .or(style.stroke.as_ref())
3748            .map_or("#000000FF", SvgColor::as_str);
3749        color_attribute(sink, "fill", color, Some(style.opacity))?;
3750    } else {
3751        sink.attribute("fill", "none")?;
3752    }
3753    Ok(())
3754}
3755
3756fn resolve_effective_style(
3757    source: &PrimitiveStyle<'_>,
3758    kind: PlotterOperationKind,
3759    context: &ValidatedSvgRenderContextA1,
3760    scope: RenderScope<'_>,
3761) -> Result<EffectiveStyle, SvgError> {
3762    let mut style = EffectiveStyle {
3763        stroke: source.stroke.map(SvgColor::parse).transpose()?,
3764        fill: source.fill.map(SvgColor::parse).transpose()?,
3765        width_nm: source.width_nm,
3766        line_style: source.line_style.as_deref().and_then(source_line_style),
3767        filled: source.filled,
3768        opacity: 1.0,
3769    };
3770    apply_fallback(&mut style, context.fallback_style())?;
3771    style.stroke = style
3772        .stroke
3773        .as_ref()
3774        .map(|color| context.remap_color(color).clone());
3775    style.fill = style
3776        .fill
3777        .as_ref()
3778        .map(|color| context.remap_color(color).clone());
3779    let semantic = semantic_role(source, scope.semantic_role);
3780    for (pattern, value) in context.layer_styles() {
3781        if pattern.matches(source.layer)
3782            || pattern_matches_represented(pattern, source.layers, semantic, scope.copper_stack)
3783        {
3784            apply_override(&mut style, value)?;
3785        }
3786    }
3787    if let Some(value) = context.semantic_style(semantic) {
3788        apply_override(&mut style, value)?;
3789    }
3790    if let Some(value) = primitive_style(
3791        context,
3792        RenderScope {
3793            layer: source.layer,
3794            ..scope
3795        },
3796        semantic,
3797    ) {
3798        apply_override(&mut style, value)?;
3799    }
3800    if let Some(value) = context.operation_style(kind) {
3801        apply_override(&mut style, value)?;
3802    }
3803    nonnegative(style.width_nm, "width_nm")?;
3804    Ok(style)
3805}
3806
3807fn apply_override(style: &mut EffectiveStyle, value: &SvgStyleOverride) -> Result<(), SvgError> {
3808    if let Some(color) = value.stroke() {
3809        style.stroke = Some(color.clone());
3810    }
3811    if let Some(color) = value.fill() {
3812        style.fill = Some(color.clone());
3813    }
3814    if let Some(width) = value.stroke_width_nm() {
3815        style.width_nm = i64::try_from(width).map_err(|_| {
3816            direct_error(
3817                SvgErrorKind::InvalidContext,
3818                "SVG context stroke width exceeds i64",
3819            )
3820        })?;
3821    }
3822    if let Some(line_style) = value.line_style()
3823        && line_style != SvgLineStyle::Source
3824    {
3825        style.line_style = Some(line_style);
3826    }
3827    if let Some(fill_mode) = value.fill_mode() {
3828        match fill_mode {
3829            SvgFillMode::Source => {}
3830            SvgFillMode::None => style.filled = false,
3831            SvgFillMode::Solid => style.filled = true,
3832        }
3833    }
3834    if let Some(opacity) = value.opacity() {
3835        style.opacity *= opacity;
3836    }
3837    Ok(())
3838}
3839
3840fn apply_fallback(style: &mut EffectiveStyle, value: &SvgStyleOverride) -> Result<(), SvgError> {
3841    if style.stroke.is_none() {
3842        style.stroke.clone_from(&value.stroke().cloned());
3843    }
3844    if style.fill.is_none() {
3845        style.fill.clone_from(&value.fill().cloned());
3846    }
3847    if style.width_nm == 0
3848        && let Some(width) = value.stroke_width_nm()
3849    {
3850        style.width_nm = i64::try_from(width).map_err(|_| {
3851            direct_error(
3852                SvgErrorKind::InvalidContext,
3853                "SVG context stroke width exceeds i64",
3854            )
3855        })?;
3856    }
3857    if style.line_style.is_none()
3858        && let Some(line_style) = value.line_style()
3859        && line_style != SvgLineStyle::Source
3860    {
3861        style.line_style = Some(line_style);
3862    }
3863    if let Some(fill_mode) = value.fill_mode() {
3864        match fill_mode {
3865            SvgFillMode::Source => {}
3866            SvgFillMode::None => style.filled = false,
3867            SvgFillMode::Solid => style.filled = true,
3868        }
3869    }
3870    if let Some(opacity) = value.opacity() {
3871        style.opacity *= opacity;
3872    }
3873    Ok(())
3874}
3875
3876fn semantic_role(
3877    style: &PrimitiveStyle<'_>,
3878    inherited_role: Option<SvgSemanticRole>,
3879) -> SvgSemanticRole {
3880    if style
3881        .role
3882        .as_deref()
3883        .is_some_and(|role| role.contains("mask"))
3884    {
3885        SvgSemanticRole::Mask
3886    } else if style
3887        .role
3888        .as_deref()
3889        .is_some_and(|role| role.contains("drill") || role.contains("hole"))
3890    {
3891        SvgSemanticRole::Drill
3892    } else if style.layer.is_some_and(|layer| layer.ends_with(".Cu"))
3893        || style.layers.iter().any(|layer| layer.ends_with(".Cu"))
3894    {
3895        SvgSemanticRole::Copper
3896    } else if style.layer.is_some_and(|layer| layer.ends_with(".Mask"))
3897        || style.layers.iter().any(|layer| layer.ends_with(".Mask"))
3898    {
3899        SvgSemanticRole::Mask
3900    } else if style.layer.is_some_and(|layer| layer.ends_with(".SilkS"))
3901        || style.layers.iter().any(|layer| layer.ends_with(".SilkS"))
3902    {
3903        SvgSemanticRole::Silkscreen
3904    } else if style.layer.is_some_and(|layer| layer.ends_with(".Fab")) {
3905        SvgSemanticRole::Fabrication
3906    } else if style.layer.is_some_and(|layer| layer.contains(".CrtYd")) {
3907        SvgSemanticRole::Courtyard
3908    } else if style.layer == Some("Edge.Cuts") {
3909        SvgSemanticRole::BoardEdge
3910    } else {
3911        inherited_role.unwrap_or(SvgSemanticRole::Other)
3912    }
3913}
3914
3915fn record_primitive_class(source_kind: &str, kind: &str) -> Option<SvgPrimitiveClass> {
3916    use SvgPrimitiveClass::*;
3917    if source_kind != "PCB" {
3918        return None;
3919    }
3920    Some(match kind {
3921        "track" | "track_segment" | "segment" | "track_arc" => CopperTrace,
3922        "via" => Via,
3923        "zone_fill" => CopperPolygon,
3924        "footprint" | "board_footprint" => ComponentGraphic,
3925        _ => BoardGraphic,
3926    })
3927}
3928
3929fn class_from_attrs(attrs: &[(String, String)]) -> Option<SvgPrimitiveClass> {
3930    let get = |key: &str| {
3931        attrs
3932            .iter()
3933            .find(|(name, _)| name == key)
3934            .map(|(_, value)| value.as_str())
3935    };
3936    match get("pad-type") {
3937        Some("smd" | "connect") => return Some(SvgPrimitiveClass::SurfaceMountPad),
3938        Some("thru_hole" | "np_thru_hole") => return Some(SvgPrimitiveClass::ThroughHolePad),
3939        _ => {}
3940    }
3941    match get("footprint-text-role") {
3942        Some("designator") => Some(SvgPrimitiveClass::ComponentDesignator),
3943        Some(_) => Some(SvgPrimitiveClass::ComponentGraphic),
3944        _ => None,
3945    }
3946}
3947
3948fn owned_scope<'a>(scope: RenderScope<'a>, operation: &'a OperationData<'a>) -> RenderScope<'a> {
3949    if let OperationData::Owned { ownership, .. } = operation {
3950        RenderScope {
3951            primitive_class: class_from_attrs(&ownership.extra_attrs).or(scope.primitive_class),
3952            ..scope
3953        }
3954    } else {
3955        scope
3956    }
3957}
3958
3959fn primitive_style<'a>(
3960    context: &'a ValidatedSvgRenderContextA1,
3961    scope: RenderScope<'_>,
3962    semantic: SvgSemanticRole,
3963) -> Option<&'a SvgStyleOverride> {
3964    // Copper presentation must never consume mask openings or physical bores.
3965    if matches!(semantic, SvgSemanticRole::Drill | SvgSemanticRole::Mask)
3966        || scope.layer.is_some_and(|l| l.ends_with(".Mask"))
3967    {
3968        return None;
3969    }
3970    let class = scope.primitive_class?;
3971    let graphic = matches!(
3972        class,
3973        SvgPrimitiveClass::BoardGraphic
3974            | SvgPrimitiveClass::ComponentGraphic
3975            | SvgPrimitiveClass::ComponentDesignator
3976    );
3977    let copper =
3978        semantic == SvgSemanticRole::Copper || scope.layer.is_some_and(|l| l.ends_with(".Cu"));
3979    if graphic && !copper && !scope.layer.is_some_and(|l| l.ends_with(".SilkS")) {
3980        return None;
3981    }
3982    let class = if copper && graphic {
3983        SvgPrimitiveClass::CopperTrace
3984    } else {
3985        class
3986    };
3987    context.primitive_style(class)
3988}
3989
3990fn record_semantic_role(source_kind: &str, kind: &str) -> SvgSemanticRole {
3991    match (source_kind, kind) {
3992        ("SYM", _) => SvgSemanticRole::SymbolBody,
3993        ("SCH", "sheet_header") => SvgSemanticRole::Worksheet,
3994        ("SCH", "wire") => SvgSemanticRole::SchematicWire,
3995        ("SCH", "bus" | "bus_entry") => SvgSemanticRole::SchematicBus,
3996        ("SCH", "junction") => SvgSemanticRole::Junction,
3997        (
3998            "SCH",
3999            "label" | "global_label" | "hierarchical_label" | "netclass_flag" | "no_connect",
4000        ) => SvgSemanticRole::Label,
4001        ("SCH", "symbol_instance" | "symbol_overplot") => SvgSemanticRole::SymbolBody,
4002        ("SCH", "sheet") => SvgSemanticRole::HierarchicalSheet,
4003        ("SCH", "image") => SvgSemanticRole::Image,
4004        ("SCH", "text" | "text_box") | ("PCB", "board_text" | "board_text_box") => {
4005            SvgSemanticRole::Text
4006        }
4007        _ => SvgSemanticRole::Other,
4008    }
4009}
4010
4011fn emit_pad_style(
4012    sink: &mut SvgSink,
4013    kind: PlotterOperationKind,
4014    context: &ValidatedSvgRenderContextA1,
4015    scope: RenderScope<'_>,
4016) -> Result<(), SvgError> {
4017    if !context.has_style_overrides() {
4018        sink.attribute("fill", "#000000")?;
4019        return sink.attribute("stroke", "none");
4020    }
4021    let source = PrimitiveStyle {
4022        layer: scope.layer,
4023        role: None,
4024        layers: scope.layers,
4025        stroke: None,
4026        fill: Some("#000000FF"),
4027        width_nm: 0,
4028        line_style: None,
4029        filled: true,
4030    };
4031    emit_style(sink, &source, kind, context, scope)
4032}
4033
4034#[allow(
4035    clippy::cognitive_complexity,
4036    clippy::too_many_lines,
4037    reason = "semantic text, both retained cache forms, and browser text share one emitter"
4038)]
4039fn render_text(
4040    text: &TextData<'_>,
4041    sink: &mut SvgSink,
4042    context: &ValidatedSvgRenderContextA1,
4043    scope: RenderScope<'_>,
4044) -> Result<(), SvgError> {
4045    nonnegative(text.size_x_nm, "size_x_nm")?;
4046    nonnegative(text.size_y_nm, "size_y_nm")?;
4047    if text.size_x_nm == 0 || text.size_y_nm == 0 {
4048        return Ok(());
4049    }
4050    let (color, opacity) = resolved_text_style(
4051        text.color,
4052        text.layer.or(scope.layer),
4053        scope
4054            .semantic_role
4055            .filter(|role| *role == SvgSemanticRole::Pin)
4056            .unwrap_or(SvgSemanticRole::Text),
4057        context,
4058        scope,
4059    )?;
4060    if !text.cache.is_empty() {
4061        for polygon in &text.cache {
4062            sink.element()?;
4063            sink.raw("<path d=\"")?;
4064            let mut contours = 0usize;
4065            for contour in polygon {
4066                if contour.len() >= 3 {
4067                    write_path(sink, contour)?;
4068                    contours += 1;
4069                }
4070            }
4071            sink.raw("\"")?;
4072            color_attribute(sink, "fill", color.as_str(), Some(opacity))?;
4073            sink.attribute("stroke", "none")?;
4074            if contours > 1 {
4075                sink.attribute("fill-rule", "evenodd")?;
4076            }
4077            sink.raw("/>\n")?;
4078        }
4079        return Ok(());
4080    }
4081    if !text.legacy_cache.is_empty() {
4082        for polygon in &text.legacy_cache {
4083            if polygon.len() < 3 {
4084                continue;
4085            }
4086            sink.element()?;
4087            sink.raw("<polygon points=\"")?;
4088            write_points(sink, polygon)?;
4089            sink.raw("\"")?;
4090            color_attribute(sink, "fill", color.as_str(), Some(opacity))?;
4091            sink.attribute("stroke", "none")?;
4092            sink.raw("/>\n")?;
4093        }
4094        return Ok(());
4095    }
4096    let lines = if text.multiline {
4097        text.text.split('\n').collect::<Vec<_>>()
4098    } else {
4099        vec![text.text]
4100    };
4101    let (first, step) = if text.multiline && text.text.contains('\n') {
4102        direct_multiline_positions(text, lines.len())?
4103    } else {
4104        ((text.x, text.y), (0, 0))
4105    };
4106    for (index, line) in lines.iter().enumerate() {
4107        if line.is_empty() && text.multiline && text.text.contains('\n') {
4108            continue;
4109        }
4110        let index =
4111            i64::try_from(index).map_err(|_| overflow_error("text line index exceeds i64"))?;
4112        let x = checked_line_coordinate(first.0, step.0, index)?;
4113        let y = checked_line_coordinate(first.1, step.1, index)?;
4114        sink.element()?;
4115        sink.raw("<text")?;
4116        sink.attribute("x", &format_nm(x))?;
4117        sink.attribute("y", &format_nm(y))?;
4118        sink.attribute("font-size", &format_nm(text.size_y_nm))?;
4119        let face = context.font_face_override().unwrap_or(text.font_face);
4120        if !face.is_empty() {
4121            sink.attribute("font-family", face)?;
4122        }
4123        if text.bold {
4124            sink.attribute("font-weight", "bold")?;
4125        }
4126        if text.italic {
4127            sink.attribute("font-style", "italic")?;
4128        }
4129        sink.attribute(
4130            "text-anchor",
4131            if text.h_align.ends_with("CENTER") {
4132                "middle"
4133            } else if text.h_align.ends_with("RIGHT") {
4134                "end"
4135            } else {
4136                "start"
4137            },
4138        )?;
4139        sink.attribute(
4140            "dominant-baseline",
4141            if text.v_align.ends_with("TOP") {
4142                "hanging"
4143            } else if text.v_align.ends_with("CENTER") {
4144                "central"
4145            } else {
4146                "alphabetic"
4147            },
4148        )?;
4149        color_attribute(sink, "fill", color.as_str(), Some(opacity))?;
4150        let horizontal_scale =
4151            (text.size_x_nm as f64 / text.size_y_nm as f64) * if text.mirror { -1.0 } else { 1.0 };
4152        if text.orient_deg != 0.0 || text.size_x_nm != text.size_y_nm || text.mirror {
4153            let mut transforms = Vec::new();
4154            if text.orient_deg != 0.0 {
4155                transforms.push(format!(
4156                    "rotate({} {} {})",
4157                    number(-text.orient_deg),
4158                    format_nm(x),
4159                    format_nm(y)
4160                ));
4161            }
4162            if text.size_x_nm != text.size_y_nm || text.mirror {
4163                transforms.push(format!(
4164                    "translate({} {}) scale({} 1) translate({} {})",
4165                    format_nm(x),
4166                    format_nm(y),
4167                    number(horizontal_scale),
4168                    format_nm_i128(-i128::from(x)),
4169                    format_nm_i128(-i128::from(y))
4170                ));
4171            }
4172            sink.attribute("transform", &transforms.join(" "))?;
4173        }
4174        sink.raw(">")?;
4175        sink.escaped(line)?;
4176        sink.raw("</text>\n")?;
4177    }
4178    Ok(())
4179}
4180
4181fn direct_multiline_positions(
4182    text: &TextData<'_>,
4183    line_count: usize,
4184) -> Result<(Point, Point), SvgError> {
4185    let size_iu = rounded_i64((text.size_y_nm as f64) / 100.0, false)?;
4186    let line_step_iu = rounded_i64((size_iu as f64) * 1.68, false)?;
4187    let line_step = line_step_iu
4188        .checked_mul(100)
4189        .ok_or_else(|| overflow_error("text line step overflowed"))?;
4190    let gaps = i64::try_from(line_count.saturating_sub(1))
4191        .map_err(|_| overflow_error("text line count exceeds i64"))?;
4192    let total_step = gaps
4193        .checked_mul(line_step)
4194        .ok_or_else(|| overflow_error("text block height overflowed"))?;
4195    let vertical_offset = if text.v_align.ends_with("CENTER") {
4196        gaps.checked_mul(line_step_iu)
4197            .and_then(|value| (value / 2).checked_mul(-100))
4198            .ok_or_else(|| overflow_error("text centered offset overflowed"))?
4199    } else if text.v_align.ends_with("BOTTOM") {
4200        total_step
4201            .checked_neg()
4202            .ok_or_else(|| overflow_error("text bottom offset overflowed"))?
4203    } else {
4204        0
4205    };
4206    let first_offset = rotate_offset(0.0, vertical_offset as f64, -text.orient_deg);
4207    let step_offset = rotate_offset(0.0, line_step as f64, -text.orient_deg);
4208    Ok((
4209        (
4210            rounded_i64((text.x as f64) + first_offset.0, true)?,
4211            rounded_i64((text.y as f64) + first_offset.1, true)?,
4212        ),
4213        (
4214            rounded_i64(step_offset.0, true)?,
4215            rounded_i64(step_offset.1, true)?,
4216        ),
4217    ))
4218}
4219
4220fn checked_line_coordinate(first: i64, step: i64, index: i64) -> Result<i64, SvgError> {
4221    first
4222        .checked_add(
4223            step.checked_mul(index)
4224                .ok_or_else(|| overflow_error("text line offset overflowed"))?,
4225        )
4226        .ok_or_else(|| overflow_error("text line position overflowed"))
4227}
4228
4229fn rotate_offset(x: f64, y: f64, angle_degrees: f64) -> (f64, f64) {
4230    match angle_degrees.rem_euclid(360.0) {
4231        0.0 => (x, y),
4232        90.0 => (-y, x),
4233        180.0 => (-x, -y),
4234        270.0 => (y, -x),
4235        angle => {
4236            let (sine, cosine) = angle.to_radians().sin_cos();
4237            (x * cosine - y * sine, x * sine + y * cosine)
4238        }
4239    }
4240}
4241
4242fn rounded_i64(value: f64, ties_even: bool) -> Result<i64, SvgError> {
4243    let value = if ties_even {
4244        value.round_ties_even()
4245    } else {
4246        value.round()
4247    };
4248    if !value.is_finite() || value < i64::MIN as f64 || value > i64::MAX as f64 {
4249        return Err(overflow_error("text rounding exceeds i64"));
4250    }
4251    Ok(value as i64)
4252}
4253
4254fn resolved_text_style(
4255    source: &str,
4256    layer: Option<&str>,
4257    semantic: SvgSemanticRole,
4258    context: &ValidatedSvgRenderContextA1,
4259    scope: RenderScope<'_>,
4260) -> Result<(SvgColor, f64), SvgError> {
4261    let mut color = SvgColor::parse(source)?;
4262    color = context.remap_color(&color).clone();
4263    let mut style = EffectiveStyle {
4264        stroke: None,
4265        fill: Some(color),
4266        width_nm: 0,
4267        line_style: None,
4268        filled: true,
4269        opacity: 1.0,
4270    };
4271    apply_fallback(&mut style, context.fallback_style())?;
4272    if let Some(layer) = layer {
4273        for (pattern, value) in context.layer_styles() {
4274            if pattern.matches(Some(layer)) {
4275                apply_override(&mut style, value)?;
4276            }
4277        }
4278    }
4279    if let Some(value) = context.semantic_style(semantic) {
4280        apply_override(&mut style, value)?;
4281    }
4282    if let Some(value) = primitive_style(context, RenderScope { layer, ..scope }, semantic) {
4283        apply_override(&mut style, value)?;
4284    }
4285    if let Some(value) = context.operation_style(PlotterOperationKind::Text) {
4286        apply_override(&mut style, value)?;
4287    }
4288    Ok((
4289        style
4290            .fill
4291            .map_or_else(|| SvgColor::parse("#000000FF"), Ok)?,
4292        style.opacity,
4293    ))
4294}
4295
4296fn render_image(
4297    center: Point,
4298    width: i64,
4299    height: i64,
4300    format: &str,
4301    data: &str,
4302    sink: &mut SvgSink,
4303    context: &ValidatedSvgRenderContextA1,
4304) -> Result<(), SvgError> {
4305    nonnegative(width, "width_nm")?;
4306    nonnegative(height, "height_nm")?;
4307    sink.element()?;
4308    sink.raw("<image")?;
4309    sink.attribute("x", &centered_start(center.0, width))?;
4310    sink.attribute("y", &centered_start(center.1, height))?;
4311    sink.attribute("width", &format_nm(width))?;
4312    sink.attribute("height", &format_nm(height))?;
4313    sink.attribute("preserveAspectRatio", "none")?;
4314    let mut style = EffectiveStyle {
4315        stroke: None,
4316        fill: None,
4317        width_nm: 0,
4318        line_style: None,
4319        filled: false,
4320        opacity: 1.0,
4321    };
4322    apply_fallback(&mut style, context.fallback_style())?;
4323    if let Some(value) = context.semantic_style(SvgSemanticRole::Image) {
4324        apply_override(&mut style, value)?;
4325    }
4326    if let Some(value) = context.operation_style(PlotterOperationKind::PlotImage) {
4327        apply_override(&mut style, value)?;
4328    }
4329    if style.opacity < 1.0 {
4330        sink.attribute("opacity", &number(style.opacity))?;
4331    }
4332    let mime = match format {
4333        "jpeg" | "jpg" => "image/jpeg",
4334        "bmp" => "image/bmp",
4335        _ => "image/png",
4336    };
4337    sink.raw(" href=\"data:")?;
4338    sink.raw(mime)?;
4339    sink.raw(";base64,")?;
4340    sink.escaped(data)?;
4341    sink.raw("\"/>\n")
4342}
4343
4344fn render_pad_oval(
4345    center: Point,
4346    size: Point,
4347    angle: f64,
4348    sink: &mut SvgSink,
4349    context: &ValidatedSvgRenderContextA1,
4350    scope: RenderScope<'_>,
4351) -> Result<(), SvgError> {
4352    let Some(line) = pad_oval_centerline(center, size)? else {
4353        sink.element()?;
4354        sink.raw("<circle")?;
4355        sink.attribute("cx", &format_nm(center.0))?;
4356        sink.attribute("cy", &format_nm(center.1))?;
4357        sink.attribute("r", &format_half_nm(i128::from(size.0)))?;
4358        emit_pad_style(sink, PlotterOperationKind::FlashPadOval, context, scope)?;
4359        return sink.raw("/>\n");
4360    };
4361    sink.element()?;
4362    sink.raw("<line")?;
4363    for (name, value) in [
4364        ("x1", line.first_twice.0),
4365        ("y1", line.first_twice.1),
4366        ("x2", line.second_twice.0),
4367        ("y2", line.second_twice.1),
4368    ] {
4369        sink.attribute(name, &format_half_nm(value))?;
4370    }
4371    rotation(sink, center, angle)?;
4372    if !context.has_style_overrides() {
4373        sink.attribute("fill", "none")?;
4374        sink.attribute("stroke", "#000000")?;
4375        sink.attribute("stroke-width", &format_nm(line.width_nm))?;
4376        sink.attribute("stroke-linecap", "round")?;
4377        sink.attribute("stroke-linejoin", "round")?;
4378        return sink.raw("/>\n");
4379    }
4380    let source = pad_oval_style(line.width_nm, scope);
4381    emit_style(
4382        sink,
4383        &source,
4384        PlotterOperationKind::FlashPadOval,
4385        context,
4386        scope,
4387    )?;
4388    sink.raw("/>\n")
4389}
4390
4391fn pad_oval_centerline(center: Point, size: Point) -> Result<Option<PadOvalCenterline>, SvgError> {
4392    nonnegative(size.0, "size_x_nm")?;
4393    nonnegative(size.1, "size_y_nm")?;
4394    if size.0 == size.1 {
4395        return Ok(None);
4396    }
4397    let center_twice = (i128::from(center.0) * 2, i128::from(center.1) * 2);
4398    Ok(Some(if size.0 > size.1 {
4399        let difference = i128::from(size.0 - size.1);
4400        PadOvalCenterline {
4401            first_twice: (center_twice.0 - difference, center_twice.1),
4402            second_twice: (center_twice.0 + difference, center_twice.1),
4403            width_nm: size.1,
4404        }
4405    } else {
4406        let difference = i128::from(size.1 - size.0);
4407        PadOvalCenterline {
4408            first_twice: (center_twice.0, center_twice.1 - difference),
4409            second_twice: (center_twice.0, center_twice.1 + difference),
4410            width_nm: size.0,
4411        }
4412    }))
4413}
4414
4415fn pad_oval_style(width_nm: i64, scope: RenderScope<'_>) -> PrimitiveStyle<'_> {
4416    PrimitiveStyle {
4417        layer: scope.layer,
4418        role: None,
4419        layers: scope.layers,
4420        stroke: Some("#000000FF"),
4421        fill: None,
4422        width_nm,
4423        line_style: None,
4424        filled: false,
4425    }
4426}
4427
4428fn render_pad_rect(
4429    center: Point,
4430    size: Point,
4431    angle: f64,
4432    radius: Option<i64>,
4433    sink: &mut SvgSink,
4434    context: &ValidatedSvgRenderContextA1,
4435    scope: RenderScope<'_>,
4436) -> Result<(), SvgError> {
4437    nonnegative(size.0, "size_x_nm")?;
4438    nonnegative(size.1, "size_y_nm")?;
4439    if let Some(radius) = radius {
4440        nonnegative(radius, "corner_radius_nm")?;
4441    }
4442    sink.element()?;
4443    sink.raw("<rect")?;
4444    sink.attribute("x", &centered_start(center.0, size.0))?;
4445    sink.attribute("y", &centered_start(center.1, size.1))?;
4446    sink.attribute("width", &format_nm(size.0))?;
4447    sink.attribute("height", &format_nm(size.1))?;
4448    if let Some(radius) = radius {
4449        sink.attribute("rx", &format_nm(radius))?;
4450        sink.attribute("ry", &format_nm(radius))?;
4451    }
4452    rotation(sink, center, angle)?;
4453    emit_pad_style(
4454        sink,
4455        if radius.is_some() {
4456            PlotterOperationKind::FlashPadRoundRect
4457        } else {
4458            PlotterOperationKind::FlashPadRect
4459        },
4460        context,
4461        scope,
4462    )?;
4463    sink.raw("/>\n")
4464}
4465
4466fn render_local_polygon(
4467    center: Point,
4468    angle: f64,
4469    points: &[Point],
4470    sink: &mut SvgSink,
4471    context: &ValidatedSvgRenderContextA1,
4472    kind: PlotterOperationKind,
4473    scope: RenderScope<'_>,
4474) -> Result<(), SvgError> {
4475    sink.element()?;
4476    sink.raw("<polygon points=\"")?;
4477    write_points(sink, points)?;
4478    sink.raw("\"")?;
4479    sink.attribute(
4480        "transform",
4481        &format!(
4482            "translate({} {}) rotate({})",
4483            format_nm(center.0),
4484            format_nm(center.1),
4485            number(-angle),
4486        ),
4487    )?;
4488    emit_pad_style(sink, kind, context, scope)?;
4489    sink.raw("/>\n")
4490}
4491
4492fn point_attributes(sink: &mut SvgSink, start: Point, end: Point) -> Result<(), SvgError> {
4493    for (name, value) in [
4494        ("x1", start.0),
4495        ("y1", start.1),
4496        ("x2", end.0),
4497        ("y2", end.1),
4498    ] {
4499        sink.attribute(name, &format_nm(value))?;
4500    }
4501    Ok(())
4502}
4503
4504fn write_points(sink: &mut SvgSink, points: &[Point]) -> Result<(), SvgError> {
4505    for (index, (x, y)) in points.iter().enumerate() {
4506        if index > 0 {
4507            sink.raw(" ")?;
4508        }
4509        sink.raw(&format!("{},{}", format_nm(*x), format_nm(*y)))?;
4510    }
4511    Ok(())
4512}
4513
4514fn write_path(sink: &mut SvgSink, points: &[Point]) -> Result<(), SvgError> {
4515    for (index, (x, y)) in points.iter().enumerate() {
4516        sink.raw(if index == 0 { "M " } else { " L " })?;
4517        sink.raw(&format!("{} {}", format_nm(*x), format_nm(*y)))?;
4518    }
4519    sink.raw(" Z ")
4520}
4521
4522fn rotation(sink: &mut SvgSink, center: Point, angle: f64) -> Result<(), SvgError> {
4523    if angle != 0.0 {
4524        sink.attribute(
4525            "transform",
4526            &format!(
4527                "rotate({} {} {})",
4528                number(-angle),
4529                format_nm(center.0),
4530                format_nm(center.1),
4531            ),
4532        )?;
4533    }
4534    Ok(())
4535}
4536
4537fn color_attribute(
4538    sink: &mut SvgSink,
4539    name: &str,
4540    rgba: &str,
4541    opacity: Option<f64>,
4542) -> Result<(), SvgError> {
4543    let color = SvgColor::parse(rgba)?;
4544    sink.attribute(name, &color.as_str()[..7])?;
4545    let source_alpha = if color.as_str().len() == 9 {
4546        u8::from_str_radix(&color.as_str()[7..], 16)
4547            .map_err(|_| direct_error(SvgErrorKind::Serialization, "invalid SVG alpha"))?
4548    } else {
4549        u8::MAX
4550    };
4551    let effective = f64::from(source_alpha) / 255.0 * opacity.unwrap_or(1.0);
4552    if effective < 1.0 {
4553        sink.attribute(&format!("{name}-opacity"), &number(effective))?;
4554    }
4555    Ok(())
4556}
4557
4558fn emit_dash(sink: &mut SvgSink, style: Option<SvgLineStyle>, width: i64) -> Result<(), SvgError> {
4559    let scaled = |factor: i64| {
4560        width
4561            .checked_mul(factor)
4562            .ok_or_else(|| overflow_error("SVG dash length overflowed"))
4563    };
4564    let pattern = match style {
4565        Some(SvgLineStyle::Dash) => Some(format!(
4566            "{} {}",
4567            format_nm(scaled(4)?),
4568            format_nm(scaled(2)?)
4569        )),
4570        Some(SvgLineStyle::Dot) => Some(format!("{} {}", format_nm(width), format_nm(scaled(2)?))),
4571        Some(SvgLineStyle::DashDot) => Some(format!(
4572            "{} {} {} {}",
4573            format_nm(scaled(4)?),
4574            format_nm(scaled(2)?),
4575            format_nm(width),
4576            format_nm(scaled(2)?)
4577        )),
4578        Some(SvgLineStyle::DashDotDot) => Some(format!(
4579            "{} {} {} {} {} {}",
4580            format_nm(scaled(4)?),
4581            format_nm(scaled(2)?),
4582            format_nm(width),
4583            format_nm(scaled(2)?),
4584            format_nm(width),
4585            format_nm(scaled(2)?)
4586        )),
4587        _ => None,
4588    };
4589    if let Some(pattern) = pattern {
4590        sink.attribute("stroke-dasharray", &pattern)?;
4591    }
4592    Ok(())
4593}
4594
4595fn source_line_style(value: &str) -> Option<SvgLineStyle> {
4596    match value {
4597        "DASH" => Some(SvgLineStyle::Dash),
4598        "DOT" => Some(SvgLineStyle::Dot),
4599        "DASH_DOT" => Some(SvgLineStyle::DashDot),
4600        "DASH_DOT_DOT" => Some(SvgLineStyle::DashDotDot),
4601        "SOLID" => Some(SvgLineStyle::Solid),
4602        _ => None,
4603    }
4604}
4605
4606fn arc_parameters(start: Point, mid: Point, end: Point) -> Option<(f64, bool, bool)> {
4607    let (ax, ay) = (start.0 as f64, start.1 as f64);
4608    let (bx, by) = (mid.0 as f64, mid.1 as f64);
4609    let (cx, cy) = (end.0 as f64, end.1 as f64);
4610    let determinant = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
4611    if determinant.abs() < f64::EPSILON {
4612        return None;
4613    }
4614    let a2 = ax * ax + ay * ay;
4615    let b2 = bx * bx + by * by;
4616    let c2 = cx * cx + cy * cy;
4617    let ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / determinant;
4618    let uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / determinant;
4619    let radius = ((ax - ux).powi(2) + (ay - uy).powi(2)).sqrt();
4620    let start_angle = (ay - uy).atan2(ax - ux);
4621    let mid_angle = (by - uy).atan2(bx - ux);
4622    let end_angle = (cy - uy).atan2(cx - ux);
4623    let ccw_total = (end_angle - start_angle).rem_euclid(std::f64::consts::TAU);
4624    let ccw_mid = (mid_angle - start_angle).rem_euclid(std::f64::consts::TAU);
4625    let sweep = ccw_mid <= ccw_total;
4626    let span = if sweep {
4627        ccw_total
4628    } else {
4629        (start_angle - end_angle).rem_euclid(std::f64::consts::TAU)
4630    };
4631    Some((radius, span > std::f64::consts::PI, sweep))
4632}
4633
4634fn centered_start(center: i64, size: i64) -> String {
4635    format_half_nm(i128::from(center) * 2 - i128::from(size))
4636}
4637
4638fn format_nm(value_nm: i64) -> String {
4639    format_nm_i128(i128::from(value_nm))
4640}
4641
4642fn format_nm_i128(value_nm: i128) -> String {
4643    format_scaled_decimal(value_nm, 1_000_000, 6)
4644}
4645
4646fn format_half_nm(twice_value_nm: i128) -> String {
4647    format_scaled_decimal(twice_value_nm, 2_000_000, 7)
4648}
4649
4650fn format_nm_f64(value_nm: f64) -> String {
4651    number(value_nm / 1_000_000.0)
4652}
4653
4654fn format_scaled_decimal(numerator: i128, denominator: u128, fractional_digits: usize) -> String {
4655    let negative = numerator.is_negative();
4656    let magnitude = numerator.unsigned_abs();
4657    let whole = magnitude / denominator;
4658    let remainder = magnitude % denominator;
4659    let sign = if negative { "-" } else { "" };
4660    if remainder == 0 {
4661        return format!("{sign}{whole}");
4662    }
4663    let scale = 10_u128.pow(u32::try_from(fractional_digits).expect("fraction digits fit u32"));
4664    let fraction = remainder * scale / denominator;
4665    let fraction = format!("{fraction:0fractional_digits$}")
4666        .trim_end_matches('0')
4667        .to_owned();
4668    format!("{sign}{whole}.{fraction}")
4669}
4670
4671fn number(value: f64) -> String {
4672    let value = if value.abs() < 0.000_000_5 {
4673        0.0
4674    } else {
4675        value
4676    };
4677    format!("{value:.6}")
4678        .trim_end_matches('0')
4679        .trim_end_matches('.')
4680        .to_owned()
4681}
4682
4683fn format_mm(value_nm: u64) -> String {
4684    format_scaled_decimal(i128::from(value_nm), 1_000_000, 6)
4685}
4686
4687fn nonnegative(value: i64, label: &str) -> Result<(), SvgError> {
4688    if value < 0 {
4689        Err(SvgError::new(
4690            SvgErrorKind::InvalidDocument,
4691            format!("field {label} must be nonnegative"),
4692        ))
4693    } else {
4694        Ok(())
4695    }
4696}
4697
4698fn direct_error(kind: SvgErrorKind, message: impl Into<String>) -> SvgError {
4699    SvgError::new(kind, message)
4700}
4701
4702fn overflow_error(message: impl Into<String>) -> SvgError {
4703    direct_error(SvgErrorKind::ArithmeticOverflow, message)
4704}
4705
4706fn block_error(message: impl Into<String>) -> SvgError {
4707    direct_error(SvgErrorKind::UnbalancedBlock, message)
4708}
4709
4710fn checked_add(left: usize, right: usize, label: &str) -> Result<usize, SvgError> {
4711    left.checked_add(right).ok_or_else(|| {
4712        SvgError::new(
4713            SvgErrorKind::ArithmeticOverflow,
4714            format!("{label} overflowed"),
4715        )
4716    })
4717}
4718
4719#[cfg(test)]
4720mod tests {
4721    use super::*;
4722    use crate::{LayerPattern, SvgRenderContextA1, SvgVisibility};
4723
4724    #[test]
4725    fn svg_lengths_format_exact_signed_and_half_nanometres_as_millimetres() {
4726        assert_eq!(format_nm(0), "0");
4727        assert_eq!(format_nm(1), "0.000001");
4728        assert_eq!(format_nm(-1), "-0.000001");
4729        assert_eq!(format_nm(1_270_000), "1.27");
4730        assert_eq!(format_nm(-12_345_678), "-12.345678");
4731        assert_eq!(
4732            format_nm_i128(-i128::from(i64::MIN)),
4733            "9223372036854.775808"
4734        );
4735        assert_eq!(format_half_nm(1), "0.0000005");
4736        assert_eq!(format_half_nm(-1), "-0.0000005");
4737        assert_eq!(format_half_nm(2_000_001), "1.0000005");
4738        assert_eq!(format_mm(200_000_000), "200");
4739    }
4740
4741    #[test]
4742    fn mask_only_selection_applies_pad_margin_without_changing_copper() {
4743        let layers = vec!["F.Cu".to_owned(), "F.Mask".to_owned()];
4744        let operation = OperationData::PadRect {
4745            center: (0, 0),
4746            size: (2_000_000, 1_000_000),
4747            angle_deg: 0.0,
4748            radius_nm: None,
4749            mask_margin_nm: 200_000,
4750            layers: &layers,
4751        };
4752        let render = |selected: &str| {
4753            let context = SvgRenderContextA1::builder()
4754                .layer_selection(crate::LayerSelection::include(
4755                    vec![LayerPattern::parse(selected).unwrap()],
4756                    true,
4757                ))
4758                .build()
4759                .validate()
4760                .unwrap();
4761            let mut sink = SvgSink::new();
4762            render_operation(
4763                &operation,
4764                &mut sink,
4765                &context,
4766                RenderScope::default(),
4767                &mut BlockState::new(),
4768            )
4769            .unwrap();
4770            sink.finish().unwrap().0
4771        };
4772
4773        let copper = render("F.Cu");
4774        assert!(copper.contains("width=\"2\" height=\"1\""), "{copper}");
4775        let mask = render("F.Mask");
4776        assert!(
4777            mask.contains("width=\"2.4\" height=\"1.4\" rx=\"0.2\""),
4778            "{mask}"
4779        );
4780    }
4781
4782    #[test]
4783    #[allow(
4784        clippy::too_many_lines,
4785        reason = "one serializer matrix covers every dimensional SVG operation family"
4786    )]
4787    fn every_dimensional_operation_serializes_in_millimetres_exactly_once() {
4788        let style = PrimitiveStyle {
4789            layer: None,
4790            role: None,
4791            layers: &[],
4792            stroke: Some("#000000FF"),
4793            fill: None,
4794            width_nm: 100_001,
4795            line_style: Some("DASH".to_owned()),
4796            filled: false,
4797        };
4798        let operations = vec![
4799            OperationData::Segment {
4800                start: (-1, 1),
4801                end: (1_000_001, -1_000_001),
4802                style: style.clone(),
4803            },
4804            OperationData::Arc {
4805                start: (0, 0),
4806                mid: (1_000_000, 1_000_000),
4807                end: (2_000_000, 0),
4808                style: style.clone(),
4809            },
4810            OperationData::Circle {
4811                center: (1, -1),
4812                diameter_nm: 1_000_001,
4813                style: style.clone(),
4814            },
4815            OperationData::Rect {
4816                first: (-1, -2),
4817                second: (1_000_001, 2_000_002),
4818                corner_radius_nm: 500_001,
4819                style: style.clone(),
4820            },
4821            OperationData::Poly {
4822                points: vec![(-1, 1), (1_000_001, 2_000_002)],
4823                style: style.clone(),
4824            },
4825            OperationData::Bezier {
4826                points: [(-1, 1), (2, -2), (3, -3), (1_000_001, -1_000_001)],
4827                style: style.clone(),
4828            },
4829            OperationData::Text(TextData {
4830                x: 1,
4831                y: -1,
4832                text: "T",
4833                color: "#000000FF",
4834                orient_deg: 30.0,
4835                size_x_nm: 1_270_001,
4836                size_y_nm: 1_270_001,
4837                mirror: false,
4838                h_align: "GR_TEXT_H_ALIGN_LEFT".to_owned(),
4839                v_align: "GR_TEXT_V_ALIGN_BOTTOM".to_owned(),
4840                italic: false,
4841                bold: false,
4842                multiline: false,
4843                font_face: "",
4844                layer: None,
4845                cache: vec![vec![vec![(1, -1), (1_000_001, 2_000_002), (3, 4)]]],
4846                legacy_cache: Vec::new(),
4847            }),
4848            OperationData::Text(TextData {
4849                x: 1,
4850                y: -1,
4851                text: "fallback",
4852                color: "#000000FF",
4853                orient_deg: 30.0,
4854                size_x_nm: 1_270_001,
4855                size_y_nm: 1_270_001,
4856                mirror: false,
4857                h_align: "GR_TEXT_H_ALIGN_LEFT".to_owned(),
4858                v_align: "GR_TEXT_V_ALIGN_BOTTOM".to_owned(),
4859                italic: false,
4860                bold: false,
4861                multiline: false,
4862                font_face: "",
4863                layer: None,
4864                cache: Vec::new(),
4865                legacy_cache: Vec::new(),
4866            }),
4867            OperationData::Image {
4868                center: (0, 0),
4869                width_nm: 1,
4870                height_nm: 3,
4871                format: "png",
4872                data: "AA==",
4873            },
4874            OperationData::PadCircle {
4875                center: (1, -1),
4876                diameter_nm: 3,
4877                mask_margin_nm: 0,
4878                layers: &[],
4879            },
4880            OperationData::PadOval {
4881                center: (1, -1),
4882                size: (1_000_001, 3),
4883                angle_deg: 30.0,
4884                mask_margin_nm: 0,
4885                layers: &[],
4886            },
4887            OperationData::PadRect {
4888                center: (1, -1),
4889                size: (3, 5),
4890                angle_deg: 45.0,
4891                radius_nm: Some(1),
4892                mask_margin_nm: 0,
4893                layers: &[],
4894            },
4895            OperationData::PadCustom {
4896                center: (1, -1),
4897                angle_deg: 15.0,
4898                polygons: vec![vec![(-1, 1), (1_000_001, 2_000_002), (3, 4)]],
4899                layers: &[],
4900            },
4901            OperationData::PadTrapez {
4902                center: (1, -1),
4903                angle_deg: 60.0,
4904                corners: vec![(-1, 1), (1_000_001, 2_000_002), (3, 4)],
4905                layers: &[],
4906            },
4907        ];
4908        let context = ValidatedSvgRenderContextA1::defaults();
4909        let mut sink = SvgSink::new();
4910        let mut blocks = BlockState::new();
4911        for operation in &operations {
4912            render_operation(
4913                operation,
4914                &mut sink,
4915                &context,
4916                RenderScope::default(),
4917                &mut blocks,
4918            )
4919            .unwrap();
4920        }
4921        let (svg, elements, _) = sink.finish().unwrap();
4922        assert_eq!(elements, operations.len());
4923        for expected in [
4924            "x1=\"-0.000001\" y1=\"0.000001\" x2=\"1.000001\" y2=\"-1.000001\"",
4925            "stroke-width=\"0.100001\"",
4926            "stroke-dasharray=\"0.400004 0.200002\"",
4927            "d=\"M 0 0 A 1 1 0 0 0 2 0\"",
4928            "cx=\"0.000001\" cy=\"-0.000001\" r=\"0.5000005\"",
4929            "x=\"-0.000001\" y=\"-0.000002\" width=\"1.000002\" height=\"2.000004\" rx=\"0.500001\"",
4930            "points=\"-0.000001,0.000001 1.000001,2.000002\"",
4931            "d=\"M -0.000001 0.000001 C 0.000002 -0.000002, 0.000003 -0.000003, 1.000001 -1.000001\"",
4932            "font-size=\"1.270001\"",
4933            "rotate(-30 0.000001 -0.000001)",
4934            "d=\"M 0.000001 -0.000001 L 1.000001 2.000002 L 0.000003 0.000004 Z \"",
4935            "x=\"-0.0000005\" y=\"-0.0000015\" width=\"0.000001\" height=\"0.000003\"",
4936            "r=\"0.0000015\"",
4937            "translate(0.000001 -0.000001) rotate(-15)",
4938            "translate(0.000001 -0.000001) rotate(-60)",
4939        ] {
4940            assert!(svg.contains(expected), "missing {expected:?} in:\n{svg}");
4941        }
4942        assert!(!svg.contains("x2=\"1000001\""));
4943        assert!(!svg.contains("stroke-width=\"100001\""));
4944        assert!(!svg.contains("font-size=\"1270001\""));
4945        assert!(!svg.contains("1000001,2000002"));
4946    }
4947
4948    fn filled_style() -> PrimitiveStyle<'static> {
4949        PrimitiveStyle {
4950            layer: None,
4951            role: None,
4952            layers: &[],
4953            stroke: Some("#000000FF"),
4954            fill: Some("#000000FF"),
4955            width_nm: 0,
4956            line_style: None,
4957            filled: true,
4958        }
4959    }
4960
4961    #[test]
4962    fn bounds_follow_nested_pin_visibility_and_exact_transformed_arc_sweep() {
4963        let context = SvgRenderContextA1::builder()
4964            .visibility(SvgVisibility::new(false, true))
4965            .build()
4966            .validate()
4967            .unwrap();
4968        let operations = vec![
4969            OperationData::StartBlock {
4970                label: "outer",
4971                data_uuid: "",
4972                data_ref: "symbol".to_owned(),
4973                object_id: "",
4974                extra_attrs: Vec::new(),
4975            },
4976            OperationData::StartBlock {
4977                label: "pin",
4978                data_uuid: "",
4979                data_ref: "pin".to_owned(),
4980                object_id: "",
4981                extra_attrs: vec![("pin".to_owned(), "1".to_owned())],
4982            },
4983            OperationData::Text(TextData {
4984                x: 0,
4985                y: 0,
4986                text: "IN",
4987                color: "#000000FF",
4988                orient_deg: 0.0,
4989                size_x_nm: 1,
4990                size_y_nm: 1,
4991                mirror: false,
4992                h_align: "LEFT".to_owned(),
4993                v_align: "TOP".to_owned(),
4994                italic: false,
4995                bold: false,
4996                multiline: false,
4997                font_face: "",
4998                layer: None,
4999                cache: vec![vec![vec![(1_000, 1_000), (2_000, 1_000), (2_000, 2_000)]]],
5000                legacy_cache: Vec::new(),
5001            }),
5002            OperationData::Segment {
5003                start: (0, 0),
5004                end: (10, 0),
5005                style: filled_style(),
5006            },
5007            OperationData::EndBlock,
5008            OperationData::EndBlock,
5009        ];
5010        let mut bounds = BoundsAccumulator::default();
5011        add_operation_sequence_bounds(
5012            &operations,
5013            RenderScope::default(),
5014            &context,
5015            BoundsTransform::default(),
5016            &mut bounds,
5017        )
5018        .unwrap();
5019        assert_eq!(
5020            bounds.finish().unwrap(),
5021            Some(SvgBounds {
5022                min_x_nm: 0,
5023                min_y_nm: 0,
5024                max_x_nm: 10,
5025                max_y_nm: 0,
5026            })
5027        );
5028
5029        let arc = OperationData::Arc {
5030            start: (10, 0),
5031            mid: (0, 10),
5032            end: (-10, 0),
5033            style: filled_style(),
5034        };
5035        let mut arc_bounds = BoundsAccumulator::default();
5036        add_operation_bounds(
5037            &arc,
5038            RenderScope::default(),
5039            &context,
5040            BoundsTransform {
5041                translate_x: 0.0,
5042                translate_y: 0.0,
5043                angle_deg: 90.0,
5044            },
5045            &mut arc_bounds,
5046        )
5047        .unwrap();
5048        assert_eq!(
5049            arc_bounds.finish().unwrap(),
5050            Some(SvgBounds {
5051                min_x_nm: -10,
5052                min_y_nm: -10,
5053                max_x_nm: 0,
5054                max_y_nm: 10,
5055            })
5056        );
5057    }
5058
5059    fn fitted_zero_width_circle(
5060        filled: bool,
5061        context: &ValidatedSvgRenderContextA1,
5062    ) -> (SvgViewport, SvgBounds) {
5063        let operation = OperationData::Circle {
5064            center: (0, 0),
5065            diameter_nm: 1_000_000,
5066            style: PrimitiveStyle {
5067                layer: Some("F.Cu"),
5068                role: None,
5069                layers: &[],
5070                stroke: Some("#000000FF"),
5071                fill: Some("#000000FF"),
5072                width_nm: 0,
5073                line_style: None,
5074                filled,
5075            },
5076        };
5077        fitted_operation_bounds(&operation, RenderScope::default(), context)
5078    }
5079
5080    fn fitted_operation_bounds(
5081        operation: &OperationData<'_>,
5082        scope: RenderScope<'_>,
5083        context: &ValidatedSvgRenderContextA1,
5084    ) -> (SvgViewport, SvgBounds) {
5085        let mut bounds = BoundsAccumulator::default();
5086        add_operation_bounds(
5087            operation,
5088            scope,
5089            context,
5090            BoundsTransform::default(),
5091            &mut bounds,
5092        )
5093        .unwrap();
5094        let (viewport, visible, warnings) = resolve_viewport(
5095            ViewportPolicy::Fit(SvgFitOptions {
5096                padding_nm: 0,
5097                min_extent_nm: 1,
5098                fallback: None,
5099            }),
5100            bounds,
5101        )
5102        .unwrap();
5103        assert!(warnings.is_empty());
5104        (viewport, visible.unwrap())
5105    }
5106
5107    #[test]
5108    fn fitted_bounds_use_effective_fill_mode_and_style_precedence() {
5109        let none = SvgStyleOverride::new().with_fill_mode(SvgFillMode::None);
5110        let solid = SvgStyleOverride::new().with_fill_mode(SvgFillMode::Solid);
5111        let validate =
5112            |builder: crate::SvgRenderContextBuilder| builder.build().validate().unwrap();
5113        let layer = LayerPattern::parse("F.Cu").unwrap();
5114
5115        let source_filled = validate(SvgRenderContextA1::builder());
5116        let fallback_none = validate(SvgRenderContextA1::builder().fallback_style(none.clone()));
5117        let layer_solid = validate(
5118            SvgRenderContextA1::builder()
5119                .fallback_style(none.clone())
5120                .layer_style(layer.clone(), solid.clone()),
5121        );
5122        let semantic_none = validate(
5123            SvgRenderContextA1::builder()
5124                .fallback_style(none.clone())
5125                .layer_style(layer.clone(), solid.clone())
5126                .semantic_style(SvgSemanticRole::Copper, none.clone()),
5127        );
5128        let operation_solid = validate(
5129            SvgRenderContextA1::builder()
5130                .fallback_style(none)
5131                .layer_style(layer, solid.clone())
5132                .semantic_style(
5133                    SvgSemanticRole::Copper,
5134                    SvgStyleOverride::new().with_fill_mode(SvgFillMode::None),
5135                )
5136                .operation_style(PlotterOperationKind::Circle, solid.clone()),
5137        );
5138        let source_unfilled_to_solid = validate(
5139            SvgRenderContextA1::builder().operation_style(PlotterOperationKind::Circle, solid),
5140        );
5141
5142        for context in [&source_filled, &layer_solid, &operation_solid] {
5143            let (viewport, visible) = fitted_zero_width_circle(true, context);
5144            assert_eq!(viewport.width_nm, 1_000_000);
5145            assert_eq!(visible.min_x_nm, -500_000);
5146            assert_eq!(visible.max_x_nm, 500_000);
5147        }
5148        // A width-0 outline has no stroke, as in KiCad's SVG plotter
5149        // (common/plotters/SVG_plotter.cpp:268-271), so it adds no extent.
5150        for context in [&fallback_none, &semantic_none] {
5151            let (viewport, visible) = fitted_zero_width_circle(true, context);
5152            assert_eq!(viewport.width_nm, 1_000_000);
5153            assert_eq!(visible.min_x_nm, -500_000);
5154            assert_eq!(visible.max_x_nm, 500_000);
5155        }
5156        let (viewport, visible) = fitted_zero_width_circle(false, &source_unfilled_to_solid);
5157        assert_eq!(viewport.width_nm, 1_000_000);
5158        assert_eq!(visible.min_x_nm, -500_000);
5159        assert_eq!(visible.max_x_nm, 500_000);
5160    }
5161
5162    #[test]
5163    fn fitted_oval_pad_bounds_share_emitted_centerline_style_and_layer_precedence() {
5164        let inherited_layers = vec!["F.Cu".to_owned()];
5165        let represented_layers = vec!["*.Cu".to_owned()];
5166        let copper_stack = vec!["F.Cu".to_owned(), "In1.Cu".to_owned(), "B.Cu".to_owned()];
5167        let inherited_oval = OperationData::PadOval {
5168            center: (0, 0),
5169            size: (2_000_000, 1_000_000),
5170            angle_deg: 0.0,
5171            mask_margin_nm: 0,
5172            layers: &[],
5173        };
5174        let represented_oval = OperationData::PadOval {
5175            center: (0, 0),
5176            size: (2_000_000, 1_000_000),
5177            angle_deg: 0.0,
5178            mask_margin_nm: 0,
5179            layers: &represented_layers,
5180        };
5181        let validate =
5182            |builder: crate::SvgRenderContextBuilder| builder.build().validate().unwrap();
5183        let inherited_none = validate(SvgRenderContextA1::builder().layer_style(
5184            LayerPattern::parse("F.Cu").unwrap(),
5185            SvgStyleOverride::new().with_fill_mode(SvgFillMode::None),
5186        ));
5187        let inherited_scope = RenderScope {
5188            layers: &inherited_layers,
5189            ..RenderScope::default()
5190        };
5191        let (viewport, visible) =
5192            fitted_operation_bounds(&inherited_oval, inherited_scope, &inherited_none);
5193        assert_eq!(
5194            (viewport.width_nm, viewport.height_nm),
5195            (2_000_000, 1_000_000)
5196        );
5197        assert_eq!(
5198            (visible.min_x_nm, visible.max_x_nm),
5199            (-1_000_000, 1_000_000)
5200        );
5201
5202        let layer_width = SvgStyleOverride::new().with_stroke_width_nm(800_000);
5203        let semantic_width = SvgStyleOverride::new().with_stroke_width_nm(600_000);
5204        let operation_width = SvgStyleOverride::new().with_stroke_width_nm(200_000);
5205        let layer_context = validate(
5206            SvgRenderContextA1::builder()
5207                .fallback_style(SvgStyleOverride::new().with_stroke_width_nm(3_000_000))
5208                .layer_style(LayerPattern::parse("In1.Cu").unwrap(), layer_width.clone()),
5209        );
5210        let semantic_context = validate(
5211            SvgRenderContextA1::builder()
5212                .layer_style(LayerPattern::parse("In1.Cu").unwrap(), layer_width.clone())
5213                .semantic_style(SvgSemanticRole::Copper, semantic_width.clone()),
5214        );
5215        let operation_context = validate(
5216            SvgRenderContextA1::builder()
5217                .layer_style(LayerPattern::parse("In1.Cu").unwrap(), layer_width)
5218                .semantic_style(SvgSemanticRole::Copper, semantic_width)
5219                .operation_style(PlotterOperationKind::FlashPadOval, operation_width),
5220        );
5221        let represented_scope = RenderScope {
5222            copper_stack: Some(&copper_stack),
5223            ..RenderScope::default()
5224        };
5225        for (context, expected) in [
5226            (&layer_context, (1_800_000, 800_000)),
5227            (&semantic_context, (1_600_000, 600_000)),
5228            (&operation_context, (1_200_000, 200_000)),
5229        ] {
5230            let (viewport, _) =
5231                fitted_operation_bounds(&represented_oval, represented_scope, context);
5232            assert_eq!((viewport.width_nm, viewport.height_nm), expected);
5233        }
5234    }
5235}