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

kicad_monkey_core/
schematic_terminals.rs

1use crate::{
2    SchematicDefinition, SchematicEffectiveSymbol, SchematicLibraryPin, SchematicOccurrence,
3    SchematicPlacedSymbol, SchematicPoint, SourceBundleError, SourceBundleErrorKind,
4};
5use std::collections::{HashMap, VecDeque};
6
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub struct SchematicSymbolTerminal {
9    pub symbol_index: usize,
10    pub symbol_uuid: String,
11    pub reference: String,
12    pub pin_number: String,
13    /// This library pin's own saved placed-pin UUID; empty when none is saved.
14    pub source_pin_uuid: String,
15    pub pin_name: String,
16    pub electrical_type: String,
17    pub graphic_style: String,
18    pub hidden: bool,
19    pub has_drawing: bool,
20    pub library_at: SchematicPoint,
21    pub at: SchematicPoint,
22}
23
24pub(crate) fn resolve_symbol_terminals(
25    definition: &SchematicDefinition,
26    occurrence: &SchematicOccurrence,
27    effective_symbols: &[SchematicEffectiveSymbol],
28) -> Result<Vec<SchematicSymbolTerminal>, SourceBundleError> {
29    let mut terminals = Vec::new();
30    let mut retained_string_bytes = 0_usize;
31    for effective in effective_symbols {
32        let Some(placed) = definition.symbols.get(effective.symbol_index) else {
33            continue;
34        };
35        let Some(library) = definition.library_pin_symbol_for_placement(placed) else {
36            continue;
37        };
38        let pin_uuids = placed_pin_uuids(library, placed);
39        for (subsymbol_index, subsymbol) in library.subsymbols.iter().enumerate() {
40            if !active_subsymbol(
41                subsymbol.unit,
42                subsymbol.style,
43                effective.unit,
44                placed.convert,
45            ) {
46                continue;
47            }
48            for (pin_index, pin) in subsymbol.pins.iter().enumerate() {
49                let source_pin_uuid = pin_uuids
50                    .get(&(subsymbol_index, pin_index))
51                    .copied()
52                    .unwrap_or_default();
53                let terminal_bytes = terminal_string_bytes(placed, effective, pin)
54                    .and_then(|bytes| bytes.checked_add(source_pin_uuid.len()))
55                    .ok_or_else(|| {
56                        limit_error(occurrence, "symbol terminal retained bytes overflow")
57                    })?;
58                retained_string_bytes = retained_string_bytes
59                    .checked_add(terminal_bytes)
60                    .ok_or_else(|| {
61                        limit_error(occurrence, "symbol terminal retained bytes overflow")
62                    })?;
63                terminals.push(SchematicSymbolTerminal {
64                    symbol_index: effective.symbol_index,
65                    symbol_uuid: placed.uuid.clone(),
66                    reference: effective.reference.clone(),
67                    pin_number: pin.number.clone(),
68                    source_pin_uuid: source_pin_uuid.to_owned(),
69                    pin_name: pin.name.clone(),
70                    electrical_type: pin.electrical_type.clone(),
71                    graphic_style: pin.graphic_style.clone(),
72                    hidden: pin.hidden,
73                    has_drawing: placed_pin_has_drawing(library, placed, pin),
74                    library_at: pin.at,
75                    at: transform_pin(placed, pin, occurrence)?,
76                });
77            }
78        }
79    }
80    Ok(terminals)
81}
82
83fn terminal_string_bytes(
84    placed: &SchematicPlacedSymbol,
85    effective: &SchematicEffectiveSymbol,
86    pin: &SchematicLibraryPin,
87) -> Option<usize> {
88    [
89        placed.uuid.len(),
90        effective.reference.len(),
91        pin.number.len(),
92        pin.name.len(),
93        pin.electrical_type.len(),
94        pin.graphic_style.len(),
95    ]
96    .into_iter()
97    .try_fold(0_usize, usize::checked_add)
98}
99
100fn placed_pin_has_drawing(
101    library: &crate::SchematicLibrarySymbol,
102    placed: &SchematicPlacedSymbol,
103    pin: &SchematicLibraryPin,
104) -> bool {
105    if pin.hidden {
106        return false;
107    }
108    // A selected alternate can replace both the pin name and graphic style.
109    // The compact connectivity model does not retain alternate definitions, so
110    // preserve the selector conservatively whenever an alternate is selected.
111    if placed
112        .pins
113        .iter()
114        .any(|placed_pin| placed_pin.number == pin.number && placed_pin.alternate.is_some())
115    {
116        return true;
117    }
118    let draws_geometry = pin.graphic_style != "line" || !pin.length_is_zero;
119    let draws_name = !library.pin_names_hide
120        && !matches!(pin.name.as_str(), "" | "~")
121        && pin.name_has_visible_size;
122    let draws_number =
123        !library.pin_numbers_hide && !pin.number.is_empty() && pin.number_has_visible_size;
124    draws_geometry || draws_name || draws_number
125}
126
127fn active_subsymbol(unit: i64, style: i64, placed_unit: i64, convert: i64) -> bool {
128    (unit == 0 || unit == placed_unit) && (style == 0 || style == convert)
129}
130
131/// Each library pin's own saved placed-pin UUID, by (subsymbol, pin) position.
132///
133/// KiCad gives every library pin its own placed pin. `SCH_SYMBOL::updatePins`
134/// (eeschema/sch_symbol.cpp:1201-1286) hands the saved `(pin "N" (uuid ..))`
135/// entries of one number, in saved order, to the library pins of that number,
136/// over every unit of the placed body style. Pins that share a number keep
137/// separate UUIDs; a pin left without a saved entry gets none.
138fn placed_pin_uuids<'a>(
139    library: &crate::SchematicLibrarySymbol,
140    placed: &'a SchematicPlacedSymbol,
141) -> HashMap<(usize, usize), &'a str> {
142    let mut saved = HashMap::<&str, VecDeque<&str>>::new();
143    for pin in &placed.pins {
144        saved
145            .entry(pin.number.as_str())
146            .or_default()
147            .push_back(pin.uuid.as_str());
148    }
149    let mut found = HashMap::new();
150    for (subsymbol_index, subsymbol) in library.subsymbols.iter().enumerate() {
151        if placed.convert != 0 && subsymbol.style != 0 && subsymbol.style != placed.convert {
152            continue;
153        }
154        for (pin_index, pin) in subsymbol.pins.iter().enumerate() {
155            if let Some(uuid) = saved
156                .get_mut(pin.number.as_str())
157                .and_then(VecDeque::pop_front)
158            {
159                found.insert((subsymbol_index, pin_index), uuid);
160            }
161        }
162    }
163    found
164}
165
166fn transform_pin(
167    symbol: &SchematicPlacedSymbol,
168    pin: &SchematicLibraryPin,
169    occurrence: &SchematicOccurrence,
170) -> Result<SchematicPoint, SourceBundleError> {
171    transform_pin_point(
172        symbol.at,
173        symbol.angle_degrees,
174        symbol.mirror.as_deref(),
175        pin.at,
176        &occurrence.source_path,
177    )
178}
179
180pub(crate) fn transform_pin_point(
181    at: SchematicPoint,
182    angle_degrees: f64,
183    mirror: Option<&str>,
184    pin: SchematicPoint,
185    path: &str,
186) -> Result<SchematicPoint, SourceBundleError> {
187    let x = pin.x_iu;
188    let y = pin
189        .y_iu
190        .checked_neg()
191        .ok_or_else(|| error(path, "library pin Y transform overflows"))?;
192    let angle = angle_degrees.rem_euclid(360.0);
193    let (mut x, mut y) = if angle == 0.0 {
194        (x, y)
195    } else if angle == 90.0 {
196        (y, checked_neg(x, path)?)
197    } else if angle == 180.0 {
198        (checked_neg(x, path)?, checked_neg(y, path)?)
199    } else if angle == 270.0 {
200        (checked_neg(y, path)?, x)
201    } else {
202        arbitrary_rotation(x, y, angle, path)?
203    };
204    match mirror {
205        Some("x") => y = checked_neg(y, path)?,
206        Some("y") => x = checked_neg(x, path)?,
207        _ => {}
208    }
209    Ok(SchematicPoint {
210        x_iu: at
211            .x_iu
212            .checked_add(x)
213            .ok_or_else(|| error(path, "library pin X translation overflows"))?,
214        y_iu: at
215            .y_iu
216            .checked_add(y)
217            .ok_or_else(|| error(path, "library pin Y translation overflows"))?,
218    })
219}
220
221fn arbitrary_rotation(
222    x: i64,
223    y: i64,
224    angle: f64,
225    path: &str,
226) -> Result<(i64, i64), SourceBundleError> {
227    let radians = angle.to_radians();
228    let cosine = radians.cos();
229    let sine = radians.sin();
230    let rotated_x = (x as f64).mul_add(cosine, y as f64 * sine);
231    let rotated_y = (-(x as f64)).mul_add(sine, y as f64 * cosine);
232    Ok((
233        rounded_i64_at_path(rotated_x, path)?,
234        rounded_i64_at_path(rotated_y, path)?,
235    ))
236}
237
238#[cfg(test)]
239fn rounded_i64(value: f64, occurrence: &SchematicOccurrence) -> Result<i64, SourceBundleError> {
240    rounded_i64_at_path(value, &occurrence.source_path)
241}
242
243fn rounded_i64_at_path(value: f64, path: &str) -> Result<i64, SourceBundleError> {
244    let rounded = value.round_ties_even();
245    if !rounded.is_finite() || rounded < i64::MIN as f64 || rounded >= -(i64::MIN as f64) {
246        return Err(error(path, "library pin rotation exceeds i64"));
247    }
248    Ok(rounded as i64)
249}
250
251fn checked_neg(value: i64, path: &str) -> Result<i64, SourceBundleError> {
252    value
253        .checked_neg()
254        .ok_or_else(|| error(path, "library pin transform overflows"))
255}
256
257fn error(path: &str, message: &str) -> SourceBundleError {
258    SourceBundleError::new(SourceBundleErrorKind::Schematic, Some(path), message)
259}
260
261fn limit_error(occurrence: &SchematicOccurrence, message: &str) -> SourceBundleError {
262    SourceBundleError::new(
263        SourceBundleErrorKind::ResourceLimit,
264        Some(&occurrence.source_path),
265        message,
266    )
267}
268
269#[cfg(test)]
270mod tests {
271    use super::rounded_i64;
272    use crate::SchematicOccurrence;
273
274    #[test]
275    fn half_grid_rounding_is_ties_to_even() {
276        let occurrence = occurrence();
277        assert_eq!(rounded_i64(2.5, &occurrence), Ok(2));
278        assert_eq!(rounded_i64(3.5, &occurrence), Ok(4));
279        assert_eq!(rounded_i64(-2.5, &occurrence), Ok(-2));
280        assert_eq!(rounded_i64(-3.5, &occurrence), Ok(-4));
281    }
282
283    #[test]
284    fn arbitrary_rotation_rejects_non_finite_and_out_of_range_values() {
285        let occurrence = occurrence();
286        assert!(rounded_i64(f64::INFINITY, &occurrence).is_err());
287        assert!(rounded_i64(i64::MAX as f64, &occurrence).is_err());
288    }
289
290    fn occurrence() -> SchematicOccurrence {
291        SchematicOccurrence {
292            index: 1,
293            source_path: "test.kicad_sch".to_owned(),
294            parent_index: None,
295            parent_sheet_index: None,
296            sheet_uuid: None,
297            sheet_name: String::new(),
298            sheet_file: "test.kicad_sch".to_owned(),
299            occurrence_address: "/".to_owned(),
300            legacy_address: "/".to_owned(),
301            human_address: "/".to_owned(),
302            effective_in_bom: true,
303            effective_on_board: true,
304            effective_dnp: false,
305            effective_exclude_from_sim: false,
306        }
307    }
308}