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

kicad_monkey_core/
schematic_native_load.rs

1//! Pinned KiCad10.0.5 source-loading geometry beside the unchanged exact reader.
2//! No model IDs, electrical permission, snapping or saved-source mutation.
3use crate::schematic_connection_source::{scalars, selected, selected_range, wire_point_sources};
4use crate::schematic_segment_index::{SchematicSegment, SchematicSegmentIndex};
5use crate::sexpr::{Sexp, Token, TokenKind};
6use crate::{
7    SchematicConnectionSourceView, SchematicJunctionRecord, SchematicPoint,
8    SchematicSymbolSourceView, SchematicWireGeometryOmission, SchematicWireGeometryOmissionReason,
9    SchematicWireRecord, SourceBundleError, SourceBundleErrorKind,
10};
11use std::collections::BTreeSet;
12
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub struct SchematicNativeLoadedNumber {
15    pub iu: i64,
16    pub normalized: bool,
17    pub clamped: bool,
18}
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub struct SchematicNativeLoadedPoint {
21    pub at: SchematicPoint,
22    pub normalized: bool,
23    pub clamped: bool,
24}
25#[derive(Clone, Debug)]
26pub struct SchematicNativeLoadedWireRecord<'a> {
27    pub source: SchematicWireRecord<'a>,
28    pub points: Result<[SchematicNativeLoadedPoint; 2], SourceBundleError>,
29    pub width_iu: Result<Option<SchematicNativeLoadedNumber>, SourceBundleError>,
30}
31#[derive(Clone, Debug)]
32pub struct SchematicNativeLoadedJunctionRecord<'a> {
33    pub source: SchematicJunctionRecord<'a>,
34    pub at: Result<SchematicNativeLoadedPoint, SourceBundleError>,
35    pub diameter_iu: Result<Option<SchematicNativeLoadedNumber>, SourceBundleError>,
36}
37
38fn error(path: &str, message: impl ToString) -> SourceBundleError {
39    SourceBundleError::new(
40        SourceBundleErrorKind::Schematic,
41        Some(path),
42        message.to_string(),
43    )
44}
45pub(crate) fn loaded_number(
46    mm: f64,
47    path: &str,
48) -> Result<SchematicNativeLoadedNumber, SourceBundleError> {
49    if !mm.is_finite() {
50        return Err(error(
51            path,
52            "native coordinate requires finite parseDouble input",
53        ));
54    }
55    // Native parseInternalUnits: binary double scaling, screen bound clamp,
56    // then KiROUND/std::llround. Do not substitute exact-decimal tie handling.
57    let scaled = mm * 10_000.;
58    #[allow(
59        clippy::approx_constant,
60        reason = "KiCad C++ uses literal 0.7071 for schematic coordinate clamping"
61    )]
62    let limit = f64::from(i32::MAX) * 0.7071;
63    let bounded = scaled.clamp(-limit, limit);
64    let rounded = bounded.round();
65    Ok(SchematicNativeLoadedNumber {
66        iu: rounded as i64,
67        normalized: mm != rounded / 10_000.,
68        clamped: scaled != bounded,
69    })
70}
71fn token_number(
72    token: &Token<'_>,
73    path: &str,
74) -> Result<SchematicNativeLoadedNumber, SourceBundleError> {
75    if !matches!(token.kind, TokenKind::Integer | TokenKind::Float) {
76        return Err(error(path, "native coordinate requires numeric scalar"));
77    }
78    loaded_number(
79        token.lexeme.parse::<f64>().map_err(|e| error(path, e))?,
80        path,
81    )
82}
83fn combine(
84    x: SchematicNativeLoadedNumber,
85    y: SchematicNativeLoadedNumber,
86) -> SchematicNativeLoadedPoint {
87    SchematicNativeLoadedPoint {
88        at: SchematicPoint {
89            x_iu: x.iu,
90            y_iu: y.iu,
91        },
92        normalized: x.normalized || y.normalized,
93        clamped: x.clamped || y.clamped,
94    }
95}
96fn point(source: &str, path: &str) -> Result<SchematicNativeLoadedPoint, SourceBundleError> {
97    let values = scalars(source, 2, path)?;
98    Ok(combine(
99        token_number(&values[0], path)?,
100        token_number(&values[1], path)?,
101    ))
102}
103
104impl<'a> SchematicConnectionSourceView<'a> {
105    pub fn native_loaded_wire(
106        &self,
107        ordinal: usize,
108    ) -> Option<SchematicNativeLoadedWireRecord<'a>> {
109        let source = self.wire(ordinal)?;
110        let path = self.source_path();
111        let points = (|| {
112            let forms = wire_point_sources(source.form.source, path)?;
113            Ok([point(forms[0], path)?, point(forms[1], path)?])
114        })();
115        let width_iu = (|| {
116            let Some(stroke) = selected(source.form.source, "stroke", path)? else {
117                return Ok(None);
118            };
119            let Some(width) = selected(stroke, "width", path)? else {
120                return Ok(None);
121            };
122            let values = scalars(width, 1, path)?;
123            if !matches!(values[0].kind, TokenKind::Integer | TokenKind::Float) {
124                return Err(error(path, "native stroke width requires numeric scalar"));
125            }
126            let mm = values[0]
127                .lexeme
128                .parse::<f64>()
129                .map_err(|e| error(path, e))?;
130            let scaled = mm * 10_000.;
131            // STROKE_PARAMS_PARSER uses KiROUND directly, without the smaller
132            // schematic screen clamp. Refuse undefined llround overflow.
133            if !mm.is_finite()
134                || !scaled.is_finite()
135                || scaled.round() < i64::MIN as f64
136                || scaled.round() >= -(i64::MIN as f64)
137            {
138                return Err(error(
139                    path,
140                    "native stroke width exceeds defined llround input range",
141                ));
142            }
143            let rounded = scaled.round();
144            let bounded = rounded.clamp(f64::from(i32::MIN), f64::from(i32::MAX));
145            Ok(Some(SchematicNativeLoadedNumber {
146                iu: bounded as i64,
147                normalized: mm != bounded / 10_000.,
148                clamped: rounded != bounded,
149            }))
150        })();
151        Some(SchematicNativeLoadedWireRecord {
152            source,
153            points,
154            width_iu,
155        })
156    }
157    pub fn native_loaded_junction(
158        &self,
159        ordinal: usize,
160    ) -> Option<SchematicNativeLoadedJunctionRecord<'a>> {
161        let source = self.junction(ordinal)?;
162        let path = self.source_path();
163        let at = selected(source.form.source, "at", path).and_then(|form| {
164            point(
165                form.ok_or_else(|| error(path, "junction is missing at"))?,
166                path,
167            )
168        });
169        let diameter_iu = selected(source.form.source, "diameter", path).and_then(|form| {
170            form.map(|form| token_number(&scalars(form, 1, path)?[0], path))
171                .transpose()
172        });
173        Some(SchematicNativeLoadedJunctionRecord {
174            source,
175            at,
176            diameter_iu,
177        })
178    }
179    pub fn native_loaded_wire_geometry_index(
180        &self,
181        ordinals: &[usize],
182    ) -> Result<SchematicNativeWireGeometryIndex, SourceBundleError> {
183        let mut selected = BTreeSet::new();
184        for &ordinal in ordinals {
185            if ordinal >= self.wire_count() || !selected.insert(ordinal) {
186                return Err(SourceBundleError::new(
187                    SourceBundleErrorKind::Contract,
188                    Some(self.source_path()),
189                    format!("native wire selector {ordinal} is foreign or repeated"),
190                ));
191            }
192        }
193        let mut segments = Vec::new();
194        let mut omissions = Vec::new();
195        for ordinal in selected {
196            match self
197                .native_loaded_wire(ordinal)
198                .expect("validated native wire ordinal")
199                .points
200            {
201                Ok([a, b]) => match SchematicSegment::new(a.at, b.at, ordinal) {
202                    Some(segment) => segments.push(segment),
203                    None => omissions.push(SchematicWireGeometryOmission {
204                        ordinal,
205                        reason: SchematicWireGeometryOmissionReason::ZeroLength,
206                    }),
207                },
208                Err(e) => omissions.push(SchematicWireGeometryOmission {
209                    ordinal,
210                    reason: SchematicWireGeometryOmissionReason::Malformed(e),
211                }),
212            }
213        }
214        Ok(SchematicNativeWireGeometryIndex {
215            index: SchematicSegmentIndex::build(segments, self.source_path())?,
216            omissions,
217        })
218    }
219}
220#[derive(Debug)]
221pub struct SchematicNativeWireGeometryIndex {
222    index: SchematicSegmentIndex,
223    omissions: Vec<SchematicWireGeometryOmission>,
224}
225impl SchematicNativeWireGeometryIndex {
226    pub fn omissions(&self) -> &[SchematicWireGeometryOmission] {
227        &self.omissions
228    }
229    /// Query a point already projected through this native loading policy.
230    /// Exact containment remains separate from electrical contact authority.
231    pub fn containing(&self, point: SchematicPoint) -> Result<Vec<usize>, SourceBundleError> {
232        let mut ordinals = Vec::new();
233        self.index.for_each_containing(point, |segment| {
234            ordinals.push(segment.ordinal);
235            true
236        })?;
237        ordinals.sort_unstable();
238        Ok(ordinals)
239    }
240}
241
242#[derive(Clone, Debug)]
243pub struct SchematicNativeLoadedPose {
244    pub position: SchematicNativeLoadedPoint,
245    angle_degrees: f64,
246    frame_normalized: bool,
247    mirror: Option<String>,
248    path: String,
249}
250impl SchematicSymbolSourceView<'_> {
251    pub fn native_loaded_pose(
252        &self,
253        ordinal: usize,
254    ) -> Result<Option<SchematicNativeLoadedPose>, SourceBundleError> {
255        let Some(source) = self.placed_symbol_source(ordinal) else {
256            return Ok(None);
257        };
258        let path = self.source_path();
259        let at_range = selected_range(source.source, "at", path)?
260            .ok_or_else(|| error(path, "placement is missing at"))?;
261        let form = &source.source[at_range.clone()];
262        let values = scalars(form, 3, path)?;
263        let angle = values[2]
264            .lexeme
265            .parse::<f64>()
266            .map_err(|e| error(path, e))?;
267        if !matches!(values[2].kind, TokenKind::Integer | TokenKind::Float)
268            || !angle.is_finite()
269            || angle < f64::from(i32::MIN)
270            || angle > f64::from(i32::MAX)
271            || !matches!(angle as i32, 0 | 90 | 180 | 270)
272        {
273            return Err(error(
274                path,
275                "native-loaded contact pose requires a checked quarter turn",
276            ));
277        }
278        let mirror_range = selected_range(source.source, "mirror", path)?;
279        let mut mirror = mirror_range
280            .as_ref()
281            .map(|range| &source.source[range.clone()])
282            .map(|form| {
283                let tokens = scalars(form, 1, path)?;
284                if tokens[0].kind != TokenKind::Atom || !matches!(tokens[0].lexeme, "x" | "y") {
285                    return Err(error(path, "unsupported native pose mirror"));
286                }
287                Ok(tokens[0].lexeme.to_owned())
288            })
289            .transpose()?;
290        // Native at assigns a fresh transform; an earlier valid mirror token
291        // is parsed, then overwritten. Preserve original source field order.
292        let mirror_overwritten = mirror_range.is_some_and(|range| range.start < at_range.start);
293        if mirror_overwritten {
294            mirror = None;
295        }
296        Ok(Some(SchematicNativeLoadedPose {
297            position: combine(
298                token_number(&values[0], path)?,
299                token_number(&values[1], path)?,
300            ),
301            angle_degrees: f64::from(angle as i32),
302            frame_normalized: angle != f64::from(angle as i32) || mirror_overwritten,
303            mirror,
304            path: path.to_owned(),
305        }))
306    }
307}
308impl SchematicNativeLoadedPose {
309    /// Library and placement positions were normalized independently before
310    /// composing this pose. Out-of-int32 native composition is not guessed.
311    pub fn place_library_pin(
312        &self,
313        pin: SchematicNativeLoadedPoint,
314    ) -> Result<SchematicNativeLoadedPoint, SourceBundleError> {
315        #[allow(
316            clippy::approx_constant,
317            reason = "KiCad C++ uses literal 0.7071 for schematic coordinate clamping"
318        )]
319        let limit = (f64::from(i32::MAX) * 0.7071).round() as i64;
320        if [
321            self.position.at.x_iu,
322            self.position.at.y_iu,
323            pin.at.x_iu,
324            pin.at.y_iu,
325        ]
326        .iter()
327        .any(|v| *v < -limit || *v > limit)
328        {
329            return Err(SourceBundleError::new(
330                SourceBundleErrorKind::Contract,
331                Some(&self.path),
332                "native loaded constituent is outside its checked range",
333            ));
334        }
335        let at = crate::schematic_terminals::transform_pin_point(
336            self.position.at,
337            self.angle_degrees,
338            self.mirror.as_deref(),
339            pin.at,
340            &self.path,
341        )?;
342        if i32::try_from(at.x_iu).is_err() || i32::try_from(at.y_iu).is_err() {
343            return Err(error(
344                &self.path,
345                "native composed pin coordinate exceeds int32; contact cannot be qualified",
346            ));
347        }
348        Ok(SchematicNativeLoadedPoint {
349            at,
350            normalized: self.position.normalized || pin.normalized || self.frame_normalized,
351            clamped: self.position.clamped || pin.clamped,
352        })
353    }
354}
355
356/// The exact same parsed pin AST used by the caller's mapper, before any model
357/// geometry exists. This only qualifies native terminal position, not its role.
358pub fn native_loaded_library_pin_point(
359    form: &Sexp,
360) -> Result<SchematicNativeLoadedPoint, SourceBundleError> {
361    let Sexp::List(items) = form else {
362        return Err(error("", "native library pin requires a list"));
363    };
364    if !matches!(items.first(),Some(Sexp::Atom(head)) if head=="pin") {
365        return Err(error("", "native library point requires a pin form"));
366    }
367    let forms = items
368        .iter()
369        .filter_map(|item| match item {
370            Sexp::List(v) if matches!(v.first(),Some(Sexp::Atom(head)) if head=="at") => Some(v),
371            _ => None,
372        })
373        .collect::<Vec<_>>();
374    let [at] = forms.as_slice() else {
375        return Err(error("", "native library pin requires exactly one at"));
376    };
377    if at.len() != 4 {
378        return Err(error("", "native library pin at requires x,y,orientation"));
379    }
380    if !matches!(&at[3], Sexp::Integer(0 | 90 | 180 | 270)) {
381        return Err(error(
382            "",
383            "native library pin requires an integer quarter-turn orientation",
384        ));
385    }
386    let number = |v: &Sexp| match v {
387        Sexp::Integer(v) => loaded_number(*v as f64, ""),
388        Sexp::Float(v) => loaded_number(*v, ""),
389        _ => Err(error(
390            "",
391            "native library pin coordinate requires numeric scalar",
392        )),
393    };
394    Ok(combine(number(&at[1])?, number(&at[2])?))
395}