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

kicad_monkey_core/
symbol_plotter_ir.rs

1//! Source-selected library-symbol geometry and text plotter producer.
2
3use crate::plotter_ir::{
4    ArcThreePoint, BezierCurve, PlotterCircle, PlotterFill, PlotterLineStyle, PlotterOperation,
5    PlotterPoly, PlotterRect,
6};
7use crate::sexpr::{
8    Error, ErrorKind, ErrorPhase, Lexer, Position, Sexp, TokenKind, decode_quoted, parse,
9};
10use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
11use crate::symbol_pin::pin_operations;
12use crate::symbol_text::{
13    SymbolTextBudget, SymbolTextSettings, SymbolTextVariables, body_text_operation,
14    pin_text_operations,
15};
16use std::collections::{BTreeMap, BTreeSet};
17
18mod selector_inventory;
19pub use selector_inventory::{SymbolPlotSelectorEntry, symbol_plot_selector_inventory};
20
21const DEFAULT_BODY_WIDTH_NM: i64 = 152_400;
22const DEFAULT_POLYLINE_WIDTH_NM: i64 = 152_400;
23const MIN_PLOT_WIDTH_NM: i64 = 84_700;
24const DEVICE_COLOR: &str = "#840000FF";
25const DEVICE_BACKGROUND_COLOR: &str = "#FFFFC2FF";
26const JS_SAFE_MAX: f64 = 9_007_199_254_740_991.0;
27
28/// One selected unit/style body from a library symbol.
29#[derive(Clone, Debug, PartialEq)]
30pub struct SymbolPlotRecord {
31    pub name: String,
32    pub unit: u32,
33    pub style: u32,
34    pub operations: Vec<PlotterOperation>,
35}
36
37/// Typed facts needed to serialize the symbol geometry and text plotter subset.
38#[derive(Clone, Debug, PartialEq)]
39pub struct SymbolPlotDocument {
40    pub name: String,
41    pub extends: Option<String>,
42    pub unit: Option<u32>,
43    pub style: u32,
44    pub in_bom: bool,
45    pub on_board: bool,
46    pub power: bool,
47    pub records: Vec<SymbolPlotRecord>,
48}
49
50/// Positive authored unit and body-style selectors for the Source plotter.
51///
52/// IDs are sorted and unique; gaps are retained. Common unit/style 0 is not a
53/// separate selection: the plotter includes it with every positive selection.
54/// Empty or common-only geometry has the stable unit/style selection 1.
55#[derive(Clone, Debug, Eq, PartialEq)]
56pub struct SymbolPlotSelectors {
57    pub units: Vec<u32>,
58    pub styles: Vec<u32>,
59}
60
61/// Read selector facts without plotting graphics or realizing text. Exact
62/// member lookup, inheritance and unrecognized subsymbol names follow the
63/// same Source rules as [`symbol_plot_document`]. In particular, an authored
64/// child body overrides inherited geometry; missing/cyclic inheritance has
65/// no inherited geometry. No generic-model import is required.
66///
67/// Returned style IDs are positive authored IDs. Plot requests additionally
68/// accept style 0 as an alias of standard style 1; authored style-0 bodies
69/// themselves are common and are included with every style.
70pub fn symbol_plot_selectors(
71    source: &str,
72    symbol_name: &str,
73) -> Result<SymbolPlotSelectors, Error> {
74    validate_limits(source, symbol_name)?;
75    validate_library_root(source)?;
76    let spans = select_symbol_spans(source)?;
77    let index = index_symbol_spans(source, &spans)?;
78    let span = find_symbol_span(&spans, &index, symbol_name)?
79        .ok_or_else(|| model_error("Requested library symbol was not found", Position::START))?;
80    let form = parse_selected_symbol(source, span)?;
81    let inherited = inherited_geometry(source, &spans, &index, &form, symbol_name)?;
82    let geometry = inherited.as_ref().unwrap_or(&form);
83    selector_ids(geometry).map_err(|()| model_error("Subsymbol name is missing", span.start))
84}
85
86fn selector_ids(geometry: &Sexp) -> Result<SymbolPlotSelectors, ()> {
87    let mut units = BTreeSet::new();
88    let mut styles = BTreeSet::new();
89    for body in children(geometry, "symbol") {
90        let name = value_at(body, 1).ok_or(())?;
91        let (unit, style) = subsymbol_identity(name);
92        if unit > 0 {
93            units.insert(unit);
94        }
95        if style > 0 {
96            styles.insert(style);
97        }
98    }
99    if units.is_empty() {
100        units.insert(1);
101    }
102    if styles.is_empty() {
103        styles.insert(1);
104    }
105    Ok(SymbolPlotSelectors {
106        units: units.into_iter().collect(),
107        styles: styles.into_iter().collect(),
108    })
109}
110
111#[derive(Clone, Copy, Debug)]
112enum SymbolSpanLookup {
113    Unique(usize),
114    Duplicate(Position),
115}
116
117/// Select and convert one symbol without materializing the complete library.
118pub fn symbol_plot_document(
119    source: &str,
120    symbol_name: &str,
121    unit: Option<u32>,
122    style: u32,
123) -> Result<SymbolPlotDocument, Error> {
124    symbol_plot_document_with_text_variables(
125        source,
126        symbol_name,
127        unit,
128        style,
129        &SymbolTextVariables::default(),
130    )
131}
132
133/// Select and convert one symbol with bounded caller-supplied project text variables.
134pub fn symbol_plot_document_with_text_variables(
135    source: &str,
136    symbol_name: &str,
137    unit: Option<u32>,
138    style: u32,
139    text_variables: &SymbolTextVariables,
140) -> Result<SymbolPlotDocument, Error> {
141    validate_limits(source, symbol_name)?;
142    validate_library_root(source)?;
143    let spans = select_symbol_spans(source)?;
144    let index = index_symbol_spans(source, &spans)?;
145    let span = find_symbol_span(&spans, &index, symbol_name)?
146        .ok_or_else(|| model_error("Requested library symbol was not found", Position::START))?;
147    let form = parse_selected_symbol(source, span)?;
148    let inherited = inherited_geometry(source, &spans, &index, &form, symbol_name)?;
149    let geometry = inherited.as_ref().unwrap_or(&form);
150    build_document(
151        &form,
152        geometry,
153        SymbolBuildContext {
154            symbol_name,
155            unit,
156            style,
157            position: span.start,
158            text_variables,
159        },
160    )
161}
162
163fn validate_limits(_source: &str, symbol_name: &str) -> Result<(), Error> {
164    if symbol_name.is_empty() {
165        return Err(model_error(
166            "symbol_name must not be empty",
167            Position::START,
168        ));
169    }
170    Ok(())
171}
172
173fn validate_library_root(source: &str) -> Result<(), Error> {
174    let roots = scan_form_spans(
175        source,
176        &Selector {
177            min_depth: Some(0),
178            max_depth: Some(0),
179            ..Selector::default()
180        },
181    )?;
182    if roots.len() != 1 || roots[0].head.as_deref() != Some("kicad_symbol_lib") {
183        return Err(model_error(
184            "Expected exactly one kicad_symbol_lib root",
185            roots.first().map_or(Position::START, |root| root.start),
186        ));
187    }
188    Ok(())
189}
190
191fn select_symbol_spans(source: &str) -> Result<Vec<FormSpan>, Error> {
192    scan_form_spans(
193        source,
194        &Selector {
195            paths: Some(
196                [vec!["kicad_symbol_lib".to_owned(), "symbol".to_owned()]]
197                    .into_iter()
198                    .collect(),
199            ),
200            min_depth: Some(1),
201            max_depth: Some(1),
202            ..Selector::default()
203        },
204    )
205}
206
207fn index_symbol_spans(
208    source: &str,
209    spans: &[FormSpan],
210) -> Result<BTreeMap<String, SymbolSpanLookup>, Error> {
211    let mut index = BTreeMap::new();
212    for (span_index, span) in spans.iter().enumerate() {
213        let name = selected_name(source, span)?;
214        index
215            .entry(name)
216            .and_modify(|entry| *entry = SymbolSpanLookup::Duplicate(span.start))
217            .or_insert(SymbolSpanLookup::Unique(span_index));
218    }
219    Ok(index)
220}
221
222fn find_symbol_span<'a>(
223    spans: &'a [FormSpan],
224    index: &BTreeMap<String, SymbolSpanLookup>,
225    symbol_name: &str,
226) -> Result<Option<&'a FormSpan>, Error> {
227    match index.get(symbol_name) {
228        Some(SymbolSpanLookup::Unique(span_index)) => Ok(spans.get(*span_index)),
229        Some(SymbolSpanLookup::Duplicate(position)) => {
230            Err(model_error("Duplicate library symbol name", *position))
231        }
232        None => Ok(None),
233    }
234}
235
236fn inherited_geometry(
237    source: &str,
238    spans: &[FormSpan],
239    index: &BTreeMap<String, SymbolSpanLookup>,
240    target: &Sexp,
241    target_name: &str,
242) -> Result<Option<Sexp>, Error> {
243    if children(target, "symbol").next().is_some() {
244        return Ok(None);
245    }
246    let mut base_name = extends_name(target);
247    let mut seen = BTreeSet::from([target_name.to_owned()]);
248    while let Some(name) = base_name {
249        if !seen.insert(name.clone()) {
250            return Ok(None);
251        }
252        let Some(span) = find_symbol_span(spans, index, &name)? else {
253            return Ok(None);
254        };
255        let form = parse_selected_symbol(source, span)?;
256        if children(&form, "symbol").next().is_some() {
257            return Ok(Some(form));
258        }
259        base_name = extends_name(&form);
260    }
261    Ok(None)
262}
263
264fn extends_name(form: &Sexp) -> Option<String> {
265    child(form, "extends")
266        .and_then(|value| value_at(value, 1))
267        .map(str::to_owned)
268}
269
270fn selected_name(source: &str, span: &FormSpan) -> Result<String, Error> {
271    let text = span.text(source)?;
272    (|| {
273        let mut lexer = Lexer::new(text);
274        let _left = lexer.next().transpose()?;
275        let _head = lexer.next().transpose()?;
276        let token = lexer
277            .next()
278            .transpose()?
279            .ok_or_else(|| model_error("Library symbol name is missing", Position::START))?;
280        match token.kind {
281            TokenKind::QuotedString => Ok(decode_quoted(token.lexeme)),
282            TokenKind::Atom => Ok(token.lexeme.to_owned()),
283            _ => Err(model_error(
284                "Library symbol name is invalid",
285                token.position,
286            )),
287        }
288    })()
289    .map_err(|error| rebase_error(error, span))
290}
291
292fn parse_selected_symbol(source: &str, span: &FormSpan) -> Result<Sexp, Error> {
293    parse(span.text(source)?).map_err(|error| rebase_error(error, span))
294}
295
296#[derive(Clone, Copy)]
297struct SymbolBuildContext<'a> {
298    symbol_name: &'a str,
299    unit: Option<u32>,
300    style: u32,
301    position: Position,
302    text_variables: &'a SymbolTextVariables,
303}
304
305fn build_document(
306    header: &Sexp,
307    geometry: &Sexp,
308    context: SymbolBuildContext<'_>,
309) -> Result<SymbolPlotDocument, Error> {
310    let SymbolBuildContext {
311        symbol_name,
312        unit,
313        style,
314        position,
315        text_variables,
316    } = context;
317    let forms = list(header).ok_or_else(|| model_error("Expected symbol list", position))?;
318    let mut point_count = 0usize;
319    let mut records = Vec::new();
320    let mut subsymbol_count = 0usize;
321    let mut operation_count = 0usize;
322    let settings = SymbolTextSettings::from_header(geometry, position)?;
323    let mut text_budget = SymbolTextBudget::new();
324    for subsymbol in children(geometry, "symbol") {
325        subsymbol_count = subsymbol_count.saturating_add(1);
326        let name = value_at(subsymbol, 1)
327            .ok_or_else(|| model_error("Subsymbol name is missing", position))?;
328        let (sub_unit, sub_style) = subsymbol_identity(name);
329        if !selected_subsymbol(sub_unit, sub_style, unit, style) {
330            continue;
331        }
332        let remaining_operations = usize::MAX.saturating_sub(operation_count);
333        let operations = convert_subsymbol(
334            subsymbol,
335            SubsymbolContext {
336                max_operations: remaining_operations,
337                max_points: usize::MAX,
338                position,
339                settings,
340                text_variables,
341            },
342            &mut point_count,
343            &mut text_budget,
344        )?;
345        operation_count = operation_count.saturating_add(operations.len());
346        records.push(SymbolPlotRecord {
347            name: name.to_owned(),
348            unit: sub_unit,
349            style: sub_style,
350            operations,
351        });
352    }
353    let _ = forms;
354    Ok(SymbolPlotDocument {
355        name: symbol_name.to_owned(),
356        extends: child(header, "extends")
357            .and_then(|value| value_at(value, 1))
358            .map(str::to_owned),
359        unit,
360        style,
361        in_bom: yes_flag(header, "in_bom", true),
362        on_board: yes_flag(header, "on_board", true),
363        power: child(header, "power").is_some() || has_atom(header, "power"),
364        records,
365    })
366}
367
368pub(crate) fn selected_subsymbol(
369    sub_unit: u32,
370    sub_style: u32,
371    unit: Option<u32>,
372    style: u32,
373) -> bool {
374    let style_matches = sub_style == 0 || sub_style == style || (style == 0 && sub_style == 1);
375    let unit_matches = unit.is_none_or(|requested| sub_unit == 0 || sub_unit == requested);
376    style_matches && unit_matches
377}
378
379pub(crate) fn subsymbol_identity(name: &str) -> (u32, u32) {
380    let mut suffix = name.rsplitn(3, '_');
381    let style = suffix.next().and_then(|value| value.parse().ok());
382    let unit = suffix.next().and_then(|value| value.parse().ok());
383    match (unit, style) {
384        (Some(unit), Some(style)) => (unit, style),
385        _ => (1, 0),
386    }
387}
388
389#[derive(Clone, Copy)]
390struct SubsymbolContext<'a> {
391    max_operations: usize,
392    max_points: usize,
393    position: Position,
394    settings: SymbolTextSettings,
395    text_variables: &'a SymbolTextVariables,
396}
397
398fn convert_subsymbol(
399    form: &Sexp,
400    context: SubsymbolContext<'_>,
401    point_count: &mut usize,
402    text_budget: &mut SymbolTextBudget,
403) -> Result<Vec<PlotterOperation>, Error> {
404    let SubsymbolContext {
405        max_operations,
406        max_points,
407        position,
408        settings,
409        text_variables,
410    } = context;
411    let mut fills = Vec::new();
412    let mut outlines = Vec::new();
413    for head in ["rectangle", "circle", "arc", "polyline", "bezier"] {
414        for shape in children(form, head) {
415            let operation = convert_shape(shape, head, max_points, point_count, position)?;
416            let Some(operation) = operation else { continue };
417            let (fill, outline) = split_filled_outline(operation);
418            push_operation(&mut fills, fill, max_operations)?;
419            if let Some(outline) = outline {
420                push_operation(&mut outlines, outline, max_operations)?;
421            }
422        }
423    }
424    for text in children(form, "text") {
425        if let Some(operation) = body_text_operation(text, text_variables, text_budget, position)? {
426            push_operation(&mut fills, operation, max_operations)?;
427        }
428    }
429    for pin in children(form, "pin") {
430        for operation in pin_operations(pin, max_points, point_count, position)? {
431            push_operation(&mut fills, operation, max_operations)?;
432        }
433        for operation in pin_text_operations(pin, settings, None, text_budget, position)? {
434            push_operation(&mut fills, operation, max_operations)?;
435        }
436    }
437    fills.extend(outlines);
438    Ok(fills)
439}
440
441pub(crate) fn convert_shape(
442    form: &Sexp,
443    head: &str,
444    max_points: usize,
445    point_count: &mut usize,
446    position: Position,
447) -> Result<Option<PlotterOperation>, Error> {
448    let stroke = stroke_spec(form, head == "polyline", position)?;
449    let mut fill = fill_spec(form, position)?;
450    if fill.kind == PlotterFill::FilledShape && fill.color.is_none() {
451        fill.color = Some(stroke.color.clone());
452    }
453    let operation = match head {
454        "rectangle" => Some(rectangle(form, stroke, fill, position)?),
455        "circle" => Some(circle(form, stroke, fill, position)?),
456        "arc" => Some(arc(form, stroke, fill, position)?),
457        "polyline" => Some(polyline(
458            form,
459            stroke,
460            fill,
461            max_points,
462            point_count,
463            position,
464        )?),
465        "bezier" => bezier(form, stroke, fill, max_points, point_count, position)?,
466        _ => None,
467    };
468    Ok(operation)
469}
470
471#[derive(Clone, Debug)]
472struct StrokeSpec {
473    width_nm: i64,
474    color: String,
475    style: PlotterLineStyle,
476}
477
478#[derive(Clone, Debug)]
479struct FillSpec {
480    kind: PlotterFill,
481    color: Option<String>,
482}
483
484fn stroke_spec(form: &Sexp, polyline: bool, position: Position) -> Result<StrokeSpec, Error> {
485    let stroke = child(form, "stroke");
486    let width = stroke
487        .and_then(|value| child(value, "width"))
488        .map_or(Ok(0.0), |value| numeric_at(value, 1, position))?;
489    let default_width = if polyline {
490        DEFAULT_POLYLINE_WIDTH_NM
491    } else {
492        DEFAULT_BODY_WIDTH_NM
493    };
494    let width_nm = if width < 0.0 {
495        0
496    } else if width == 0.0 {
497        default_width.max(MIN_PLOT_WIDTH_NM)
498    } else {
499        mm_to_nm(width)?.max(MIN_PLOT_WIDTH_NM)
500    };
501    let style = match stroke
502        .and_then(|value| child(value, "type"))
503        .and_then(|value| value_at(value, 1))
504        .unwrap_or("default")
505    {
506        "default" => PlotterLineStyle::Default,
507        "solid" => PlotterLineStyle::Solid,
508        "dash" => PlotterLineStyle::Dash,
509        "dot" => PlotterLineStyle::Dot,
510        "dash_dot" => PlotterLineStyle::DashDot,
511        "dash_dot_dot" => PlotterLineStyle::DashDotDot,
512        _ => return Err(model_error("Unsupported symbol stroke type", position)),
513    };
514    Ok(StrokeSpec {
515        width_nm,
516        color: color(stroke.and_then(|value| child(value, "color")), position)?
517            .unwrap_or_else(|| DEVICE_COLOR.to_owned()),
518        style,
519    })
520}
521
522fn fill_spec(form: &Sexp, position: Position) -> Result<FillSpec, Error> {
523    let fill = child(form, "fill");
524    let kind = match fill
525        .and_then(|value| child(value, "type"))
526        .and_then(|value| value_at(value, 1))
527        .unwrap_or("none")
528    {
529        "outline" => PlotterFill::FilledShape,
530        "background" => PlotterFill::FilledWithBackgroundBodyColor,
531        "color" => PlotterFill::FilledWithColor,
532        "hatch" => PlotterFill::Hatch,
533        "reverse_hatch" => PlotterFill::ReverseHatch,
534        "cross_hatch" => PlotterFill::CrossHatch,
535        _ => PlotterFill::NoFill,
536    };
537    let explicit = color(fill.and_then(|value| child(value, "color")), position)?;
538    let color = explicit.or_else(|| match kind {
539        PlotterFill::FilledWithBackgroundBodyColor => Some(DEVICE_BACKGROUND_COLOR.to_owned()),
540        PlotterFill::FilledWithColor => Some(DEVICE_COLOR.to_owned()),
541        _ => None,
542    });
543    Ok(FillSpec { kind, color })
544}
545
546fn rectangle(
547    form: &Sexp,
548    stroke: StrokeSpec,
549    fill: FillSpec,
550    position: Position,
551) -> Result<PlotterOperation, Error> {
552    let start = required_child(form, "start", position)?;
553    let end = required_child(form, "end", position)?;
554    Ok(PlotterOperation::Rect(PlotterRect {
555        x1: coordinate(start, 1, false, position)?,
556        y1: coordinate(start, 2, true, position)?,
557        x2: coordinate(end, 1, false, position)?,
558        y2: coordinate(end, 2, true, position)?,
559        fill: fill.kind,
560        width_nm: stroke.width_nm,
561        corner_radius_nm: 0,
562        layer: None,
563        stroke_color: Some(stroke.color),
564        fill_color: fill.color,
565        line_style: Some(stroke.style),
566    }))
567}
568
569fn circle(
570    form: &Sexp,
571    stroke: StrokeSpec,
572    fill: FillSpec,
573    position: Position,
574) -> Result<PlotterOperation, Error> {
575    let center = required_child(form, "center", position)?;
576    let radius = required_child(form, "radius", position)?;
577    Ok(PlotterOperation::Circle(PlotterCircle {
578        cx: coordinate(center, 1, false, position)?,
579        cy: coordinate(center, 2, true, position)?,
580        diameter_nm: mm_to_nm(numeric_at(radius, 1, position)? * 2.0)?,
581        fill: fill.kind,
582        width_nm: stroke.width_nm,
583        layer: None,
584        role: None,
585        layers: Vec::new(),
586        mask_margin_nm: None,
587        pad_size_x_nm: None,
588        pad_size_y_nm: None,
589        stroke_color: Some(stroke.color),
590        fill_color: fill.color,
591        line_style: Some(stroke.style),
592    }))
593}
594
595fn arc(
596    form: &Sexp,
597    stroke: StrokeSpec,
598    fill: FillSpec,
599    position: Position,
600) -> Result<PlotterOperation, Error> {
601    let start = required_child(form, "start", position)?;
602    let end = required_child(form, "end", position)?;
603    let [start, mid, end] = if let Some(mid) = child(form, "mid") {
604        [
605            point(start, position)?,
606            point(mid, position)?,
607            point(end, position)?,
608        ]
609    } else {
610        legacy_arc(
611            form,
612            point(start, position)?,
613            point(end, position)?,
614            position,
615        )?
616    };
617    Ok(PlotterOperation::ArcThreePoint(ArcThreePoint {
618        start_x: start[0],
619        start_y: start[1],
620        mid_x: mid[0],
621        mid_y: mid[1],
622        end_x: end[0],
623        end_y: end[1],
624        fill: fill.kind,
625        width_nm: stroke.width_nm,
626        layer: None,
627        stroke_color: Some(stroke.color),
628        fill_color: fill.color,
629        line_style: Some(stroke.style),
630    }))
631}
632
633fn polyline(
634    form: &Sexp,
635    stroke: StrokeSpec,
636    fill: FillSpec,
637    max_points: usize,
638    point_count: &mut usize,
639    position: Position,
640) -> Result<PlotterOperation, Error> {
641    let points = points(form, max_points, point_count, position)?;
642    Ok(PlotterOperation::PlotPoly(PlotterPoly {
643        points,
644        fill: fill.kind,
645        width_nm: stroke.width_nm,
646        layer: None,
647        stroke_color: Some(stroke.color),
648        fill_color: fill.color,
649        line_style: Some(stroke.style),
650    }))
651}
652
653fn bezier(
654    form: &Sexp,
655    stroke: StrokeSpec,
656    fill: FillSpec,
657    max_points: usize,
658    point_count: &mut usize,
659    position: Position,
660) -> Result<Option<PlotterOperation>, Error> {
661    let points = points(form, max_points, point_count, position)?;
662    if let [start, ctrl1, ctrl2, end] = points.as_slice() {
663        return Ok(Some(PlotterOperation::BezierCurve(BezierCurve {
664            start_x: start[0],
665            start_y: start[1],
666            ctrl1_x: ctrl1[0],
667            ctrl1_y: ctrl1[1],
668            ctrl2_x: ctrl2[0],
669            ctrl2_y: ctrl2[1],
670            end_x: end[0],
671            end_y: end[1],
672            width_nm: stroke.width_nm,
673            tolerance_nm: 0,
674            layer: None,
675            stroke_color: Some(stroke.color),
676            line_style: Some(stroke.style),
677        })));
678    }
679    if points.len() < 2 {
680        return Ok(None);
681    }
682    Ok(Some(PlotterOperation::PlotPoly(PlotterPoly {
683        points,
684        fill: fill.kind,
685        width_nm: stroke.width_nm,
686        layer: None,
687        stroke_color: Some(stroke.color),
688        fill_color: fill.color,
689        line_style: Some(stroke.style),
690    })))
691}
692
693fn points(
694    form: &Sexp,
695    _max_points: usize,
696    point_count: &mut usize,
697    position: Position,
698) -> Result<Vec<[i64; 2]>, Error> {
699    let pts = required_child(form, "pts", position)?;
700    let mut output = Vec::new();
701    for point in children(pts, "xy") {
702        *point_count = point_count.saturating_add(1);
703        output.push([
704            coordinate(point, 1, false, position)?,
705            coordinate(point, 2, true, position)?,
706        ]);
707    }
708    Ok(output)
709}
710
711pub(crate) fn split_filled_outline(
712    mut operation: PlotterOperation,
713) -> (PlotterOperation, Option<PlotterOperation>) {
714    let fill = operation_fill(&operation);
715    if matches!(
716        fill,
717        None | Some(PlotterFill::NoFill | PlotterFill::FilledShape)
718    ) {
719        return (operation, None);
720    }
721    let mut outline = operation.clone();
722    set_fill_pass(&mut operation);
723    set_outline_pass(&mut outline);
724    (operation, Some(outline))
725}
726
727fn operation_fill(operation: &PlotterOperation) -> Option<PlotterFill> {
728    match operation {
729        PlotterOperation::ArcThreePoint(value) => Some(value.fill),
730        PlotterOperation::Circle(value) => Some(value.fill),
731        PlotterOperation::Rect(value) => Some(value.fill),
732        PlotterOperation::PlotPoly(value) => Some(value.fill),
733        _ => None,
734    }
735}
736
737fn set_fill_pass(operation: &mut PlotterOperation) {
738    macro_rules! apply {
739        ($value:ident) => {{
740            $value.width_nm = 0;
741            if let Some(color) = $value
742                .fill_color
743                .clone()
744                .or_else(|| $value.stroke_color.clone())
745            {
746                $value.stroke_color = Some(color.clone());
747                $value.fill_color = Some(color);
748            }
749        }};
750    }
751    match operation {
752        PlotterOperation::ArcThreePoint(value) => apply!(value),
753        PlotterOperation::Circle(value) => apply!(value),
754        PlotterOperation::Rect(value) => apply!(value),
755        PlotterOperation::PlotPoly(value) => apply!(value),
756        _ => {}
757    }
758}
759
760fn set_outline_pass(operation: &mut PlotterOperation) {
761    macro_rules! apply {
762        ($value:ident) => {{
763            $value.fill = PlotterFill::NoFill;
764            $value.fill_color = None;
765        }};
766    }
767    match operation {
768        PlotterOperation::ArcThreePoint(value) => apply!(value),
769        PlotterOperation::Circle(value) => apply!(value),
770        PlotterOperation::Rect(value) => apply!(value),
771        PlotterOperation::PlotPoly(value) => apply!(value),
772        _ => {}
773    }
774}
775
776fn push_operation(
777    operations: &mut Vec<PlotterOperation>,
778    operation: PlotterOperation,
779    _max_operations: usize,
780) -> Result<(), Error> {
781    operations.push(operation);
782    Ok(())
783}
784
785fn color(form: Option<&Sexp>, position: Position) -> Result<Option<String>, Error> {
786    let Some(form) = form else { return Ok(None) };
787    let r = color_channel(form, 1, position)?;
788    let g = color_channel(form, 2, position)?;
789    let b = color_channel(form, 3, position)?;
790    let alpha = numeric_at(form, 4, position)?;
791    if alpha <= 0.0 {
792        return Ok(None);
793    }
794    let scaled = if alpha <= 1.0 { alpha * 255.0 } else { alpha };
795    let a = scaled.clamp(0.0, 255.0).round_ties_even() as u8;
796    Ok(Some(format!("#{r:02X}{g:02X}{b:02X}{a:02X}")))
797}
798
799fn color_channel(form: &Sexp, index: usize, position: Position) -> Result<u8, Error> {
800    Ok(numeric_at(form, index, position)?.clamp(0.0, 255.0) as u8)
801}
802
803/// One `(xy ...)`-style point in KiCad's internal Y-down orientation.
804fn point(form: &Sexp, position: Position) -> Result<[i64; 2], Error> {
805    Ok([
806        coordinate(form, 1, false, position)?,
807        coordinate(form, 2, true, position)?,
808    ])
809}
810
811/// Start, mid and end of an arc stored the pre-7.0 way, as
812/// `(radius (at cx cy) (length r) (angles a1 a2))` with no mid point.
813/// KiCad keeps the center, swaps the stored ends, and swaps them back when the
814/// arc would exceed 180 degrees; the mid point sits half way along the sweep
815/// (eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr_parser.cpp:1766-1792;
816/// common/eda_shape.cpp:1346-1372).
817fn legacy_arc(
818    form: &Sexp,
819    start: [i64; 2],
820    end: [i64; 2],
821    position: Position,
822) -> Result<[[i64; 2]; 3], Error> {
823    let radius = required_child(form, "radius", position)?;
824    let center = point(required_child(radius, "at", position)?, position)?;
825    let sweep = |from: [i64; 2], to: [i64; 2]| {
826        let angle = |value: [i64; 2]| {
827            ((value[1] - center[1]) as f64)
828                .atan2((value[0] - center[0]) as f64)
829                .to_degrees()
830                .rem_euclid(360.0)
831        };
832        let first = angle(from);
833        let mut last = angle(to);
834        if last == first {
835            last = first + 360.0;
836        }
837        while last < first {
838            last += 360.0;
839        }
840        (first, last - first)
841    };
842    let (mut arc_start, mut arc_end) = (end, start);
843    let (mut first, mut span) = sweep(arc_start, arc_end);
844    if span > 180.0 {
845        (arc_start, arc_end) = (start, end);
846        (first, span) = sweep(arc_start, arc_end);
847    }
848    let radius = ((arc_start[0] - center[0]) as f64).hypot((arc_start[1] - center[1]) as f64);
849    let middle = (first + span / 2.0).to_radians();
850    let mid = [
851        center[0] + (radius * middle.cos()).round() as i64,
852        center[1] + (radius * middle.sin()).round() as i64,
853    ];
854    Ok([arc_start, mid, arc_end])
855}
856
857fn coordinate(form: &Sexp, index: usize, flip_y: bool, position: Position) -> Result<i64, Error> {
858    let value = numeric_at(form, index, position)?;
859    mm_to_nm(if flip_y { -value } else { value })
860}
861
862fn mm_to_nm(value: f64) -> Result<i64, Error> {
863    let scaled = value * 1_000_000.0;
864    if !scaled.is_finite() || !(-JS_SAFE_MAX..=JS_SAFE_MAX).contains(&scaled) {
865        return Err(model_error(
866            "Symbol coordinate exceeds JavaScript safe-integer range",
867            Position::START,
868        ));
869    }
870    Ok(scaled.round_ties_even() as i64)
871}
872
873fn yes_flag(form: &Sexp, head: &str, default: bool) -> bool {
874    child(form, head)
875        .and_then(|value| value_at(value, 1))
876        .map_or(default, |value| value == "yes")
877}
878
879fn has_atom(form: &Sexp, expected: &str) -> bool {
880    list(form).is_some_and(|values| values.iter().any(|value| text(value) == Some(expected)))
881}
882
883fn required_child<'a>(form: &'a Sexp, head: &str, position: Position) -> Result<&'a Sexp, Error> {
884    child(form, head)
885        .ok_or_else(|| model_error("Required symbol geometry form is missing", position))
886}
887
888fn children<'a>(form: &'a Sexp, head: &'a str) -> impl Iterator<Item = &'a Sexp> + 'a {
889    list(form).into_iter().flatten().filter(move |candidate| {
890        list(candidate)
891            .and_then(|values| values.first())
892            .and_then(text)
893            == Some(head)
894    })
895}
896
897fn child<'a>(form: &'a Sexp, head: &str) -> Option<&'a Sexp> {
898    list(form)?.iter().find(|candidate| {
899        list(candidate)
900            .and_then(|values| values.first())
901            .and_then(text)
902            == Some(head)
903    })
904}
905
906fn list(form: &Sexp) -> Option<&[Sexp]> {
907    match form {
908        Sexp::List(values) => Some(values),
909        _ => None,
910    }
911}
912
913fn text(value: &Sexp) -> Option<&str> {
914    match value {
915        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
916        _ => None,
917    }
918}
919
920fn value_at(form: &Sexp, index: usize) -> Option<&str> {
921    list(form)?.get(index).and_then(text)
922}
923
924fn numeric_at(form: &Sexp, index: usize, position: Position) -> Result<f64, Error> {
925    let value = list(form)
926        .and_then(|values| values.get(index))
927        .ok_or_else(|| model_error("Expected numeric symbol value", position))?;
928    let number = match value {
929        Sexp::Integer(value) => *value as f64,
930        Sexp::Float(value) => *value,
931        Sexp::Atom(value) => value
932            .parse()
933            .map_err(|_| model_error("Expected numeric symbol value", position))?,
934        _ => return Err(model_error("Expected numeric symbol value", position)),
935    };
936    if !number.is_finite() {
937        return Err(model_error("Symbol numeric value must be finite", position));
938    }
939    Ok(number)
940}
941
942fn rebase_error(mut error: Error, span: &FormSpan) -> Error {
943    if let Some(position) = error.position {
944        error.position = Some(Position {
945            offset: span.start.offset.saturating_add(position.offset),
946            line: span
947                .start
948                .line
949                .saturating_add(position.line.saturating_sub(1)),
950            column: if position.line == 1 {
951                span.start
952                    .column
953                    .saturating_add(position.column.saturating_sub(1))
954            } else {
955                position.column
956            },
957        });
958    }
959    error
960}
961
962fn model_error(message: &'static str, position: Position) -> Error {
963    Error::at(
964        ErrorPhase::Tree,
965        ErrorKind::UnexpectedToken,
966        message,
967        position,
968    )
969}