Skip to main content

brep_ecad_core/
lib.rs

1//! UI-independent schematic and board documents, symbol import, and connectivity.
2//!
3//! Object IDs are random version 4 UUIDs. On `wasm32-unknown-unknown` the randomness
4//! comes from the host: enable the `uuid` crate's `js` feature (as `BREP_app` does) or
5//! configure another `getrandom` backend, or creating an object fails.
6pub mod autoroute;
7pub mod board;
8pub mod erc;
9pub mod fabrication;
10pub mod footprint;
11pub mod kicad;
12pub mod kicad_git;
13pub mod netlist;
14use serde::{Deserialize, Serialize};
15use std::collections::{BTreeMap, BTreeSet};
16pub use uuid::Uuid;
17
18/// Integer micrometres; positive Y points down on a schematic sheet.
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
20pub struct Point {
21    pub x: i32,
22    pub y: i32,
23}
24impl Point {
25    pub const fn new(x: i32, y: i32) -> Self {
26        Self { x, y }
27    }
28    pub fn offset(self, other: Self) -> Self {
29        Self::new(self.x + other.x, self.y + other.y)
30    }
31    pub fn rotate(self, turns: u8) -> Self {
32        match turns % 4 {
33            1 => Self::new(-self.y, self.x),
34            2 => Self::new(-self.x, -self.y),
35            3 => Self::new(self.y, -self.x),
36            _ => self,
37        }
38    }
39    pub fn snapped(self) -> Self {
40        Self::new(
41            (self.x as f64 / 1270.).round() as i32 * 1270,
42            (self.y as f64 / 1270.).round() as i32 * 1270,
43        )
44    }
45}
46#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
47pub enum Graphic {
48    Path(Vec<Point>),
49    Circle { center: Point, radius: i32 },
50    Text { at: Point, text: String, size: i32 },
51}
52fn unit_is_unset(unit: &u32) -> bool {
53    *unit == 0
54}
55
56#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
57pub struct Pin {
58    #[serde(default)]
59    pub hidden: bool,
60    /// The symbol UNIT this pin belongs to, 1-based, as KiCad tags one. `0`
61    /// means unassigned and reads as unit 1. A BREP part maps one unit to one
62    /// port group, so this is what says which connector a pin is on
63    /// (`BREP_kernel/src/feature_pipeline/part_pins.rs`).
64    ///
65    /// Omitted when unset, so a SINGLE-UNIT symbol serializes exactly as it did
66    /// before units existed. The editor compares its held symbol against the
67    /// document's block byte for byte to know whether it is in step, and a
68    /// field that always wrote itself would put every stored symbol out of step
69    /// until it was saved again.
70    #[serde(default, skip_serializing_if = "unit_is_unset")]
71    pub unit: u32,
72    /// The GATE this pin is drawn with, 1-based: one of the separately placed
73    /// sections of a device, such as the two amplifiers and the power section of
74    /// a dual op-amp (KiCad calls them units and a sheet names them `U1A`, `U1B`,
75    /// …). `0` means the symbol is not split into gates.
76    ///
77    /// A gate is a DRAWING matter only. Every gate of a device is one package,
78    /// one footprint and one port group, and a pin still binds by its number.
79    /// That is what keeps it apart from [`Pin::unit`], which says which port
80    /// GROUP (which connector) a pin is on: the LM358's pin 5 is on gate B and in
81    /// the same group as pin 1. Omitted when unset, for the reason `unit` is.
82    #[serde(default, skip_serializing_if = "unit_is_unset")]
83    pub gate: u32,
84    pub number: String,
85    pub name: String,
86    pub electrical_type: String,
87    pub at: Point,
88    pub end: Point,
89}
90#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
91pub struct Symbol {
92    #[serde(default)]
93    pub unit_count: u32,
94    #[serde(default)]
95    pub properties: BTreeMap<String, String>,
96    #[serde(default)]
97    pub power_net: Option<String>,
98    pub library_id: String,
99    pub reference_prefix: String,
100    pub description: String,
101    pub graphics: Vec<Graphic>,
102    pub pins: Vec<Pin>,
103    /// The gate ([`Pin::gate`]) each of [`Symbol::graphics`] is drawn with, by
104    /// index. A graphic past the end of this list, or tagged `0`, belongs to no
105    /// gate and is drawn where the component itself is. Empty for a symbol not
106    /// split into gates, and then omitted.
107    #[serde(default, skip_serializing_if = "Vec::is_empty")]
108    pub graphic_gates: Vec<u32>,
109    /// KiCad's symbol-level `(pin_names (hide yes))`: the pins keep their names,
110    /// and the sheet does not print them. A connector's `Pin_1` … `Pin_4` or a
111    /// resistor's `~` say nothing the pin number does not.
112    #[serde(default, skip_serializing_if = "is_false")]
113    pub hide_pin_names: bool,
114    /// KiCad's symbol-level `(pin_numbers (hide yes))`, as a resistor or a
115    /// capacitor carries it.
116    #[serde(default, skip_serializing_if = "is_false")]
117    pub hide_pin_numbers: bool,
118}
119fn is_false(value: &bool) -> bool {
120    !*value
121}
122impl Symbol {
123    /// The value a part placed from this symbol starts with: KiCad's `Value`
124    /// property when the symbol carries one (`R`, `LM358`, `Conn_01x04`), else
125    /// the part of its library id after the `:`, which is what every component
126    /// was given before the property was read. The user's value (`10k`) is typed
127    /// over it on the sheet; see [`Document::set_value`].
128    pub fn default_value(&self) -> String {
129        match self.properties.get("Value").map(|v| v.trim()).filter(|v| !v.is_empty()) {
130            Some(value) => value.to_owned(),
131            None => self.library_id.split(':').next_back().unwrap_or("").to_owned(),
132        }
133    }
134    /// How many gates the symbol is split into; `0` or `1` is a symbol drawn
135    /// whole.
136    pub fn gate_count(&self) -> u32 {
137        self.pins
138            .iter()
139            .map(|p| p.gate)
140            .chain(self.graphic_gates.iter().copied())
141            .max()
142            .unwrap_or(0)
143    }
144    /// Bring a multi-unit symbol written by the KiCad import BEFORE gates
145    /// existed up to the gate shape, as a fresh import would write it now.
146    /// Returns whether it changed anything.
147    ///
148    /// That import put each KiCad unit into [`Pin::unit`], which is the PORT
149    /// GROUP a pin binds into, set `unit_count` to the number of units, and
150    /// wrote a `Unit N` caption after each unit's graphics. So an LM358 bound 3
151    /// of its 8 pins and was placed as one block. It is recognised by exactly
152    /// those captions: one `Graphic::Text { text: "Unit N", size: 1270 }` at
153    /// `y == -15000` for every N in 1..=`unit_count`, in order, with every pin's
154    /// unit in that range and no gate tagged yet. Nothing else wrote them, and
155    /// a part split into connectors on purpose (two headers, `Pin::unit` 1 and
156    /// 2) has no such captions and is left alone.
157    ///
158    /// Each unit becomes a gate: `Pin::gate` takes the unit and `Pin::unit`
159    /// goes back to `0`, a graphic takes the gate of the caption that closes
160    /// its run, the captions go (a sheet names each gate `U1A` itself), and
161    /// `unit_count` becomes 1. Coordinates are not touched.
162    pub fn migrate_legacy_units(&mut self) -> bool {
163        let Some(captions) = self.legacy_unit_captions() else {
164            return false;
165        };
166        let mut gates = Vec::with_capacity(self.graphics.len());
167        let mut gate = 1;
168        for (index, _) in self.graphics.iter().enumerate() {
169            if captions.contains(&index) {
170                gate += 1;
171            } else {
172                // Nothing the old import wrote follows the last caption; if
173                // something does, it is drawn with the part, as before.
174                gates.push(if gate <= self.unit_count { gate } else { 0 });
175            }
176        }
177        let mut index = 0;
178        self.graphics.retain(|_| {
179            index += 1;
180            !captions.contains(&(index - 1))
181        });
182        self.graphic_gates = gates;
183        for pin in &mut self.pins {
184            pin.gate = pin.unit;
185            pin.unit = 0;
186        }
187        self.unit_count = 1;
188        true
189    }
190    /// The indices of the `Unit 1` … `Unit N` captions of a symbol in the
191    /// pre-gate import's shape ([`Symbol::migrate_legacy_units`]), or `None`
192    /// when it is not in that shape.
193    fn legacy_unit_captions(&self) -> Option<Vec<usize>> {
194        let count = self.unit_count;
195        if count < 2 || self.gate_count() > 0 {
196            return None;
197        }
198        if !self.pins.iter().all(|p| (1..=count).contains(&p.unit)) {
199            return None;
200        }
201        let captions: Vec<(usize, u32)> = self
202            .graphics
203            .iter()
204            .enumerate()
205            .filter_map(|(i, g)| match g {
206                Graphic::Text { at, text, size } if *size == 1270 && at.y == -15000 => text
207                    .strip_prefix("Unit ")
208                    .and_then(|n| n.parse::<u32>().ok())
209                    .map(|n| (i, n)),
210                _ => None,
211            })
212            .collect();
213        let in_order = captions.iter().map(|&(_, n)| n).eq(1..=count);
214        in_order.then(|| captions.into_iter().map(|(i, _)| i).collect())
215    }
216    /// The gate graphic `index` is drawn with; `0` for none.
217    pub fn graphic_gate(&self, index: usize) -> u32 {
218        self.graphic_gates.get(index).copied().unwrap_or(0)
219    }
220    /// The box gate `gate`'s pins and graphics span in symbol coordinates, or
221    /// `None` when nothing is drawn with it.
222    pub fn gate_extent(&self, gate: u32) -> Option<(Point, Point)> {
223        let mut points = vec![];
224        for pin in self.pins.iter().filter(|p| p.gate == gate) {
225            points.extend([pin.at, pin.end]);
226        }
227        for (i, g) in self.graphics.iter().enumerate() {
228            if self.graphic_gate(i) == gate {
229                points.extend(graphic_points(g));
230            }
231        }
232        extent(&points)
233    }
234}
235/// The letter a sheet adds to a reference for gate `gate`: `A` for 1, `B` for
236/// 2, …, `Z`, then `AA`, as KiCad names units.
237pub fn gate_letter(gate: u32) -> String {
238    let mut n = gate.max(1);
239    let mut letters = vec![];
240    while n > 0 {
241        n -= 1;
242        letters.push(char::from(b'A' + (n % 26) as u8));
243        n /= 26;
244    }
245    letters.iter().rev().collect()
246}
247fn graphic_points(g: &Graphic) -> Vec<Point> {
248    match g {
249        Graphic::Path(path) => path.clone(),
250        Graphic::Circle { center, radius } => vec![
251            Point::new(center.x - radius, center.y - radius),
252            Point::new(center.x + radius, center.y + radius),
253        ],
254        Graphic::Text { at, .. } => vec![*at],
255    }
256}
257fn extent(points: &[Point]) -> Option<(Point, Point)> {
258    let lo = Point::new(points.iter().map(|p| p.x).min()?, points.iter().map(|p| p.y).min()?);
259    let hi = Point::new(points.iter().map(|p| p.x).max()?, points.iter().map(|p| p.y).max()?);
260    Some((lo, hi))
261}
262/// The part a component was placed from: the host's key for that part, and the
263/// signature of the version whose symbol and pads were copied. A host compares the
264/// signature against the part as it stands now to find components to refresh.
265#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
266pub struct PartSource {
267    /// Opaque native assembly occurrence identity, independent of its display label.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub instance: Option<String>,
270    pub key: String,
271    pub signature: String,
272}
273#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
274pub struct Component {
275    pub id: Uuid,
276    /// The label this placed part goes by, such as `J1`. A host that keeps its own
277    /// labels sets it with [`Document::set_reference`].
278    pub reference: String,
279    pub value: String,
280    pub symbol: Symbol,
281    pub at: Point,
282    pub rotation: u8,
283    /// The part this was placed from, absent for a component drawn without one.
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub part: Option<PartSource>,
286    /// The part's board pads, copied when it was placed.
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub pads: Option<board::Footprint>,
289    /// Where each gate of a symbol split into gates ([`Pin::gate`]) sits on the
290    /// sheet, one entry per gate: each is moved and turned on its own and named
291    /// by the reference and its letter (`U1A`), while the component stays ONE
292    /// part with one reference, one set of pads and one board placement. Empty,
293    /// and omitted, for a symbol drawn whole.
294    #[serde(default, skip_serializing_if = "Vec::is_empty")]
295    pub gates: Vec<GatePlacement>,
296}
297/// One gate of a component on the sheet: the gate's geometry, taken about
298/// `pivot` in symbol coordinates, turned by `rotation` quarter turns and put
299/// at `at`.
300#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
301pub struct GatePlacement {
302    pub gate: u32,
303    pub pivot: Point,
304    pub at: Point,
305    #[serde(default)]
306    pub rotation: u8,
307}
308impl Component {
309    /// Whether this is a part with a value of its own: not a power symbol or flag
310    /// (a `#` reference, as KiCad's `#PWR` and `#FLG`, which name a net and are left
311    /// out of the netlist and the BOM), and not a pinless placeholder.
312    pub fn is_valued_part(&self) -> bool {
313        self.symbol.power_net.is_none() && !self.reference.starts_with('#') && !self.symbol.pins.is_empty()
314    }
315    pub fn transform(&self, p: Point) -> Point {
316        p.rotate(self.rotation).offset(self.at)
317    }
318    /// Where a symbol point drawn with gate `gate` lands on the sheet: through
319    /// that gate's own placement when the component has one, else through the
320    /// component's.
321    pub fn gate_transform(&self, gate: u32, p: Point) -> Point {
322        match self.gate(gate) {
323            Some(g) => Point::new(p.x - g.pivot.x, p.y - g.pivot.y)
324                .rotate(g.rotation)
325                .offset(g.at),
326            None => self.transform(p),
327        }
328    }
329    /// The placement of gate `gate`, when the component places its gates apart.
330    pub fn gate(&self, gate: u32) -> Option<&GatePlacement> {
331        (gate > 0).then(|| self.gates.iter().find(|g| g.gate == gate)).flatten()
332    }
333    /// A pin's terminal on the sheet.
334    pub fn pin_at(&self, pin: &Pin) -> Point {
335        self.gate_transform(pin.gate, pin.at)
336    }
337    /// A pin's body end on the sheet.
338    pub fn pin_end(&self, pin: &Pin) -> Point {
339        self.gate_transform(pin.gate, pin.end)
340    }
341    /// Where a point of graphic `index` lands on the sheet.
342    pub fn graphic_transform(&self, index: usize, p: Point) -> Point {
343        self.gate_transform(self.symbol.graphic_gate(index), p)
344    }
345    /// The name a gate goes by on the sheet: `U1A` for gate 1 of `U1`; the
346    /// reference alone for a component drawn whole.
347    pub fn gate_reference(&self, gate: u32) -> String {
348        if self.gates.is_empty() || gate == 0 {
349            self.reference.clone()
350        } else {
351            format!("{}{}", self.reference, gate_letter(gate))
352        }
353    }
354    /// The boxes the component covers on the sheet, one for each gate placed
355    /// apart, else one for the whole symbol.
356    pub fn sheet_boxes(&self) -> Vec<(u32, Point, Point)> {
357        let gates: Vec<u32> = if self.gates.is_empty() {
358            vec![0]
359        } else {
360            self.gates.iter().map(|g| g.gate).collect()
361        };
362        gates
363            .into_iter()
364            .map(|gate| {
365                let mut points = vec![];
366                for pin in &self.symbol.pins {
367                    if self.gates.is_empty() || pin.gate == gate {
368                        points.extend([self.pin_at(pin), self.pin_end(pin)]);
369                    }
370                }
371                for (i, g) in self.symbol.graphics.iter().enumerate() {
372                    if self.gates.is_empty() || self.symbol.graphic_gate(i) == gate {
373                        points.extend(graphic_points(g).into_iter().map(|p| self.graphic_transform(i, p)));
374                    }
375                }
376                let at = self.gate(gate).map_or(self.at, |g| g.at);
377                points.push(at);
378                let (lo, hi) = extent(&points).unwrap_or((at, at));
379                (gate, lo, hi)
380            })
381            .collect()
382    }
383    /// Give the component one [`GatePlacement`] per gate of its symbol, keeping
384    /// those it has. A new gate starts exactly where the symbol drawn whole puts
385    /// it, so splitting moves nothing; a symbol drawn whole has none.
386    pub fn sync_gates(&mut self) {
387        let count = self.symbol.gate_count();
388        if count <= 1 {
389            self.gates.clear();
390            return;
391        }
392        self.gates.retain(|g| (1..=count).contains(&g.gate));
393        for gate in 1..=count {
394            if self.gates.iter().any(|g| g.gate == gate) {
395                continue;
396            }
397            let Some((lo, hi)) = self.symbol.gate_extent(gate) else {
398                continue;
399            };
400            let pivot = Point::new((lo.x + hi.x) / 2, (lo.y + hi.y) / 2).snapped();
401            self.gates.push(GatePlacement {
402                gate,
403                pivot,
404                at: self.transform(pivot),
405                rotation: self.rotation,
406            });
407        }
408        self.gates.sort_by_key(|g| g.gate);
409    }
410}
411/// A stable reference to a component terminal, independent of drawing position.
412#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
413pub struct Terminal {
414    pub component: Uuid,
415    pub pin: String,
416}
417/// Interactive connection targets. Junctions use their exact sheet coordinates.
418#[derive(Clone, Debug, PartialEq, Eq)]
419pub enum ConnectionTarget {
420    Terminal(Terminal),
421    Junction(Point),
422}
423
424#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
425pub struct Wire {
426    pub id: Uuid,
427    pub a: Point,
428    pub b: Point,
429    #[serde(default)]
430    pub bends: Vec<Point>,
431    #[serde(default)]
432    pub start: Option<Terminal>,
433    #[serde(default)]
434    pub end: Option<Terminal>,
435    /// Wiring diagrams only: the connection's identifier in the connection list.
436    #[serde(default, skip_serializing_if = "String::is_empty")]
437    pub connection_id: String,
438    /// Wiring diagrams only: stock part number of the wire or cable.
439    #[serde(default, skip_serializing_if = "String::is_empty")]
440    pub stock_part_number: String,
441}
442impl Wire {
443    pub fn new(a: Point, b: Point) -> Self {
444        Self {
445            id: Uuid::new_v4(),
446            a,
447            b,
448            bends: vec![],
449            start: None,
450            end: None,
451            connection_id: String::new(),
452            stock_part_number: String::new(),
453        }
454    }
455    pub fn points(&self) -> Vec<Point> {
456        std::iter::once(self.a)
457            .chain(self.bends.iter().copied())
458            .chain(std::iter::once(self.b))
459            .collect()
460    }
461    pub fn set_points(&mut self, points: Vec<Point>) {
462        let mut clean: Vec<Point> = vec![];
463        for p in points {
464            if clean.last() == Some(&p) {
465                continue;
466            }
467            while clean.len() >= 2 {
468                let a = clean[clean.len() - 2];
469                let b = clean[clean.len() - 1];
470                if (a.x == b.x && b.x == p.x) || (a.y == b.y && b.y == p.y) {
471                    clean.pop();
472                } else {
473                    break;
474                }
475            }
476            clean.push(p);
477        }
478        if clean.len() >= 2 {
479            self.a = clean[0];
480            self.b = *clean.last().unwrap();
481            self.bends = clean[1..clean.len() - 1].to_vec();
482        }
483    }
484    /// Move a segment perpendicular to itself. Outer terminals remain fixed.
485    pub fn slide_segment(&mut self, index: usize, delta: Point) {
486        let mut points = self.points();
487        if index + 1 >= points.len() {
488            return;
489        }
490        let a = points[index];
491        let b = points[index + 1];
492        let shift = if a.y == b.y {
493            Point::new(0, delta.y)
494        } else {
495            Point::new(delta.x, 0)
496        };
497        if shift == Point::default() {
498            return;
499        }
500        let moved_a = a.offset(shift);
501        let moved_b = b.offset(shift);
502        if index == 0 {
503            points.insert(1, moved_a);
504            points[2] = moved_b;
505            if points.len() == 3 {
506                points.push(b);
507            }
508        } else if index + 1 == points.len() - 1 {
509            points[index] = moved_a;
510            points.insert(index + 1, moved_b);
511        } else {
512            points[index] = moved_a;
513            points[index + 1] = moved_b;
514        }
515        self.set_points(points);
516    }
517    /// Insert an offset in the middle of the selected segment.
518    pub fn add_jog(&mut self, index: usize) {
519        let mut points = self.points();
520        if index + 1 >= points.len() {
521            return;
522        }
523        let a = points[index];
524        let b = points[index + 1];
525        let p = Point::new(a.x + (b.x - a.x) / 3, a.y + (b.y - a.y) / 3);
526        let q = Point::new(a.x + 2 * (b.x - a.x) / 3, a.y + 2 * (b.y - a.y) / 3);
527        if a == p || p == q || q == b {
528            return;
529        }
530        let offset = if a.y == b.y {
531            Point::new(0, 2540)
532        } else {
533            Point::new(2540, 0)
534        };
535        points.splice(
536            index + 1..index + 1,
537            [p, p.offset(offset), q.offset(offset), q],
538        );
539        self.set_points(points);
540    }
541    pub fn removable_jog(&self, near: usize) -> Option<usize> {
542        self.points()
543            .windows(4)
544            .enumerate()
545            .filter(|(_, p)| p[0] != p[3] && (p[0].x == p[3].x || p[0].y == p[3].y))
546            .min_by_key(|(i, _)| (i + 1).abs_diff(near))
547            .map(|(i, _)| i)
548    }
549    pub fn remove_jog(&mut self, near: usize) {
550        if let Some(i) = self.removable_jog(near) {
551            let mut p = self.points();
552            p.drain(i + 1..i + 3);
553            self.set_points(p);
554        }
555    }
556    fn follow_start(&mut self, at: Point) {
557        if at == self.a {
558            return;
559        }
560        let mut points = self.points();
561        let horizontal = points[0].y == points[1].y;
562        points[0] = at;
563        if points.len() == 2 {
564            let b = points[1];
565            let bend = if horizontal {
566                Point::new(b.x, at.y)
567            } else {
568                Point::new(at.x, b.y)
569            };
570            points.insert(1, bend);
571        } else if horizontal {
572            points[1].y = at.y;
573        } else {
574            points[1].x = at.x;
575        }
576        self.set_points(points);
577    }
578    pub fn follow(&mut self, a: Point, b: Point) {
579        if a == b {
580            self.set_points(vec![
581                a,
582                a.offset(Point::new(2540, 0)),
583                a.offset(Point::new(2540, 2540)),
584                a.offset(Point::new(0, 2540)),
585                b,
586            ]);
587            return;
588        }
589        self.follow_start(a);
590        let mut points = self.points();
591        points.reverse();
592        self.set_points(points);
593        self.follow_start(b);
594        let mut points = self.points();
595        points.reverse();
596        self.set_points(points);
597    }
598}
599#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
600pub struct Label {
601    #[serde(default)]
602    pub flag: bool,
603    #[serde(default)]
604    pub rotation: u8,
605    #[serde(default)]
606    pub terminal: Option<Terminal>,
607    pub id: Uuid,
608    pub name: String,
609    pub at: Point,
610}
611/// What a document is drawn for.
612#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
613pub enum DocumentKind {
614    /// Wires, junctions, and labels form nets, which the board is laid out from.
615    #[default]
616    Schematic,
617    /// Point-to-point connections without nets: every wire joins two symbol pins, each
618    /// pin takes at most one wire, and the output is a connection list.
619    Wiring,
620}
621impl DocumentKind {
622    fn is_schematic(&self) -> bool {
623        *self == Self::Schematic
624    }
625}
626#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
627pub struct Document {
628    pub version: u32,
629    #[serde(default, skip_serializing_if = "DocumentKind::is_schematic")]
630    pub kind: DocumentKind,
631    pub title: String,
632    pub components: Vec<Component>,
633    pub wires: Vec<Wire>,
634    pub junctions: BTreeSet<Point>,
635    pub labels: Vec<Label>,
636    /// Physical layout. Absent in version 1-3 documents.
637    #[serde(default)]
638    pub board: board::Board,
639    /// Pins the user marked as meant to be left open: the electrical rule check
640    /// ([`Document::erc`]) does not ask for them to be connected. Omitted when
641    /// empty, so a document without markers reads as it did before they existed.
642    #[serde(default, skip_serializing_if = "Vec::is_empty")]
643    pub no_connects: Vec<Terminal>,
644    /// Pins carrying a power flag, KiCad's PWR_FLAG: the net they are on is driven
645    /// from off the sheet, so its power inputs are not reported undriven.
646    #[serde(default, skip_serializing_if = "Vec::is_empty")]
647    pub power_flags: Vec<Terminal>,
648}
649/// Current document format version.
650pub const DOCUMENT_VERSION: u32 = 4;
651/// Format version of wiring diagrams. It is newer than a schematic's so that earlier
652/// builds refuse a wiring diagram instead of opening it as a schematic.
653pub const WIRING_DOCUMENT_VERSION: u32 = 5;
654impl Default for Document {
655    fn default() -> Self {
656        Self {
657            version: DOCUMENT_VERSION,
658            kind: DocumentKind::Schematic,
659            title: "Untitled schematic".into(),
660            components: vec![],
661            wires: vec![],
662            junctions: BTreeSet::new(),
663            labels: vec![],
664            board: board::Board::default(),
665            no_connects: vec![],
666            power_flags: vec![],
667        }
668    }
669}
670/// One row of a wiring diagram's connection list.
671#[derive(Clone, Debug, PartialEq, Eq)]
672pub struct Connection {
673    pub connection_id: String,
674    pub from_ref_des: String,
675    pub from_port: String,
676    pub to_ref_des: String,
677    pub to_port: String,
678    pub stock_part_number: String,
679}
680impl Document {
681    /// An empty document of the given kind.
682    pub fn new(kind: DocumentKind) -> Self {
683        match kind {
684            DocumentKind::Schematic => Self::default(),
685            DocumentKind::Wiring => Self {
686                version: WIRING_DOCUMENT_VERSION,
687                kind,
688                title: "Untitled wiring diagram".into(),
689                ..Self::default()
690            },
691        }
692    }
693    /// Put a symbol on the sheet with NO part and NO assembly occurrence behind it.
694    ///
695    /// A BREP sheet is one view of an assembly: every valued component on it is an
696    /// assembly component, and the one way to put one down is
697    /// [`Document::place_assembly_component`], after the part has been added to the
698    /// assembly. This primitive is left public for the two things that are NOT
699    /// assembly components — a power symbol, which names a net
700    /// ([`Document::place_power_symbol`]), and an editor's preview sheet — and for
701    /// tests that build a sheet shape directly. No editor door reaches it for a
702    /// valued part: a saved component with a part and no occurrence is the LEGACY
703    /// shape, which the host binds to an assembly component on open.
704    pub fn place_unbound(&mut self, mut symbol: Symbol, at: Point, rotation: u8) -> Uuid {
705        // A part saved before gates existed places as gates too.
706        symbol.migrate_legacy_units();
707        let mut n = 1;
708        while self
709            .components
710            .iter()
711            .any(|c| c.reference == format!("{}{n}", symbol.reference_prefix))
712        {
713            n += 1;
714        }
715        let id = Uuid::new_v4();
716        self.components.push(Component {
717            id,
718            reference: format!("{}{n}", symbol.reference_prefix),
719            value: symbol.default_value(),
720            symbol,
721            at,
722            rotation: rotation % 4,
723            part: None,
724            pads: None,
725            gates: vec![],
726        });
727        self.components.last_mut().unwrap().sync_gates();
728        let flags: Vec<_> = self
729            .components
730            .last()
731            .unwrap()
732            .symbol
733            .pins
734            .iter()
735            .filter_map(|p| {
736                let symbol = &self.components.last().unwrap().symbol;
737                symbol
738                    .power_net
739                    .clone()
740                    .or_else(|| {
741                        (p.hidden && p.electrical_type == "power_in" && p.name != "~")
742                            .then(|| p.name.clone())
743                    })
744                    .map(|name| (p.number.clone(), name))
745            })
746            .collect();
747        for (pin, name) in flags {
748            let _ = self.set_net_flag(Terminal { component: id, pin }, &name);
749        }
750        id
751    }
752    /// Put a power symbol on the sheet: a `#PWR` symbol that names a net
753    /// ([`Symbol::power_net`]) and is no part — it has no footprint, no BOM line
754    /// and no assembly occurrence. Refused for any other symbol: a valued part
755    /// goes on a sheet through [`Document::place_assembly_component`] alone.
756    pub fn place_power_symbol(&mut self, symbol: Symbol, at: Point, rotation: u8) -> Result<Uuid, String> {
757        if symbol.power_net.is_none() {
758            return Err(format!(
759                "{} is not a power symbol: a part goes on the sheet as an assembly component, \
760                 added with Add component",
761                symbol.library_id
762            ));
763        }
764        Ok(self.place_unbound(symbol, at, rotation))
765    }
766    /// Place an ASSEMBLY COMPONENT on the sheet. `occurrence` is the assembly
767    /// occurrence the component IS (`ACOMP3`, or `ACOMP7:ACOMP1` for a device
768    /// inside a sub-assembly): the symbol and pads of its part are copied into
769    /// the document, and the component records the occurrence with the part's
770    /// key and version (`part.key`, `part.signature`; `part.instance` is
771    /// overwritten with `occurrence`). `reference` is the label the host gives
772    /// it — its reference designator — or the next free one when it has none.
773    ///
774    /// This is the ONE way a valued component reaches a sheet. It takes the
775    /// occurrence as a required argument so that a sheet component without an
776    /// assembly component behind it cannot be written: a board is an assembly,
777    /// and its footprints are the assembly's components seen from above. An
778    /// occurrence already on the sheet is refused — one component per occurrence.
779    pub fn place_assembly_component(
780        &mut self,
781        occurrence: &str,
782        mut part: PartSource,
783        symbol: Symbol,
784        pads: Option<board::Footprint>,
785        reference: Option<String>,
786        at: Point,
787        rotation: u8,
788    ) -> Result<Uuid, String> {
789        let occurrence = occurrence.trim();
790        if occurrence.is_empty() {
791            return Err("A sheet component is an assembly component: add the part to the assembly first".into());
792        }
793        if self.components.iter().any(|c| c.part.as_ref().and_then(|p| p.instance.as_deref()) == Some(occurrence)) {
794            return Err("This native assembly instance is already placed".into());
795        }
796        // A power symbol names a net; it has no footprint, no BOM line and no
797        // part, so it can never carry a part source or an occurrence.
798        if let Some(net) = &symbol.power_net {
799            return Err(format!(
800                "{} is a power symbol for net {net}: it names a net and is no assembly component",
801                symbol.library_id
802            ));
803        }
804        part.instance = Some(occurrence.to_owned());
805        let id = self.place_unbound(symbol, at, rotation);
806        if let Some(reference) = reference {
807            self.set_reference(id, &reference).inspect_err(|_| {
808                self.delete_component(id);
809            })?;
810        }
811        let c = self.components.iter_mut().find(|c| c.id == id).unwrap();
812        c.part = Some(part);
813        c.pads = pads;
814        Ok(id)
815    }
816    /// Give a placed part the label a host keeps for it, such as its reference
817    /// designator. Labels are nonempty and unique in the document.
818    pub fn set_reference(&mut self, id: Uuid, reference: &str) -> Result<(), String> {
819        let reference = reference.trim();
820        if reference.is_empty() {
821            return Err("A label cannot be empty".into());
822        }
823        if self
824            .components
825            .iter()
826            .any(|c| c.id != id && c.reference == reference)
827        {
828            return Err(format!("{reference} is already used by another part"));
829        }
830        let c = self
831            .components
832            .iter_mut()
833            .find(|c| c.id == id)
834            .ok_or("Component no longer exists")?;
835        c.reference = reference.into();
836        Ok(())
837    }
838    /// Give each of `ids` the value `value` (`10k`), as one edit: the value the
839    /// sheet draws under the reference, and the one the BOM groups by and the
840    /// netlist and pick-and-place write. Taken as given, as the Inspector's field
841    /// types it (trimming there would eat the space of `10 k` as it is typed); an
842    /// empty value is allowed, as KiCad allows it. Returns how many changed.
843    pub fn set_value(&mut self, ids: &[Uuid], value: &str) -> usize {
844        let mut changed = 0;
845        for c in self.components.iter_mut().filter(|c| ids.contains(&c.id)) {
846            if c.value != value {
847                c.value = value.into();
848                changed += 1;
849            }
850        }
851        changed
852    }
853    /// The components that still carry the value their symbol gave them when
854    /// they were placed ([`Symbol::default_value`]) and are placed from the same
855    /// symbol as `id`, other than `id` itself, in reference order: the parts a
856    /// value typed for `id` is offered to as well.
857    pub fn unvalued_siblings(&self, id: Uuid) -> Vec<Uuid> {
858        let Some(c) = self.components.iter().find(|c| c.id == id) else {
859            return vec![];
860        };
861        let mut siblings: Vec<&Component> = self
862            .components
863            .iter()
864            .filter(|o| {
865                o.id != id
866                    && o.is_valued_part()
867                    && o.symbol.library_id == c.symbol.library_id
868                    && o.value == o.symbol.default_value()
869            })
870            .collect();
871        siblings.sort_by(|a, b| footprint::natural_cmp(&a.reference, &b.reference));
872        siblings.into_iter().map(|o| o.id).collect()
873    }
874    /// Every part the document has components from, with the version each was copied
875    /// from. A host compares these against its own parts to find what to refresh.
876    pub fn parts(&self) -> Vec<PartSource> {
877        let mut parts: Vec<_> = self
878            .components
879            .iter()
880            .filter_map(|c| c.part.clone())
881            .collect();
882        parts.sort();
883        parts.dedup();
884        parts
885    }
886    /// Take a new version of one part into every component placed from it: its symbol
887    /// and pads are copied again, and each component records `signature`. `renames`
888    /// maps a pin label of the old version to its label in the new one; connections on
889    /// a renamed pin move to its new label, connections on the pins whose labels remain
890    /// stay, and the rest go. Returns how many components were refreshed. A refusal
891    /// leaves the document as it was.
892    pub fn refresh_part(
893        &mut self,
894        key: &str,
895        symbol: &Symbol,
896        pads: Option<&board::Footprint>,
897        signature: &str,
898        renames: &BTreeMap<String, String>,
899    ) -> Result<usize, String> {
900        if signature.trim().is_empty() {
901            return Err("A part needs a key and a signature".into());
902        }
903        let stale: Vec<Uuid> = self
904            .components
905            .iter()
906            .filter(|c| {
907                c.part
908                    .as_ref()
909                    .is_some_and(|p| p.key == key && p.signature != signature)
910            })
911            .map(|c| c.id)
912            .collect();
913        let mut draft = self.clone();
914        for id in &stale {
915            draft.rebind(*id, symbol, pads, renames, |part| part.signature = signature.into())?;
916        }
917        *self = draft;
918        Ok(stale.len())
919    }
920    /// Take a new version of a part into ONE placed component — the
921    /// per-component half of [`Document::refresh_part`], for a host that
922    /// decides component by component which version each carries.
923    ///
924    /// A host whose parts nest cannot name one key and mean them all: the same
925    /// key spells a different part at every level of an assembly tree, and one
926    /// occurrence's version lives in its OWN parent's library. Such a host
927    /// resolves each component's device itself and hands the result here.
928    /// `renames` and the atomicity are [`Document::refresh_part`]'s; only the
929    /// [`PartSource`]'s `signature` is re-stamped, so a component keeps the key
930    /// it was placed from — [`Document::relink`] is the call that moves that.
931    pub fn refresh_component(
932        &mut self,
933        component: Uuid,
934        symbol: &Symbol,
935        pads: Option<&board::Footprint>,
936        signature: &str,
937        renames: &BTreeMap<String, String>,
938    ) -> Result<(), String> {
939        if signature.trim().is_empty() {
940            return Err("A part needs a key and a signature".into());
941        }
942        let mut draft = self.clone();
943        draft.rebind(component, symbol, pads, renames, |part| part.signature = signature.into())?;
944        *self = draft;
945        Ok(())
946    }
947    /// Copy one part version into ONE placed component: its terminals move by
948    /// `renames`, its symbol and pads are replaced, its board placement follows
949    /// the new footprint (and goes when the part has none), and `bind` says what
950    /// becomes of its [`PartSource`]. The ONE place a component takes a new
951    /// version of a part, whether that is the same part refreshed
952    /// ([`Document::refresh_part`], [`Document::refresh_component`]) or a
953    /// different device ([`Document::relink`]).
954    fn rebind(
955        &mut self,
956        id: Uuid,
957        symbol: &Symbol,
958        pads: Option<&board::Footprint>,
959        renames: &BTreeMap<String, String>,
960        bind: impl FnOnce(&mut PartSource),
961    ) -> Result<(), String> {
962        self.rename_terminals(id, renames);
963        self.replace_component_symbol(id, symbol.clone())?;
964        let c = self
965            .components
966            .iter_mut()
967            .find(|c| c.id == id)
968            .ok_or("Component no longer exists")?;
969        c.pads = pads.cloned();
970        if let Some(part) = &mut c.part {
971            bind(part);
972        }
973        if let Some(pads) = pads
974            && let Some(placement) = self.board.placements.iter_mut().find(|p| p.component == id)
975        {
976            placement.footprint = pads.clone();
977        }
978        if pads.is_none() {
979            self.board.placements.retain(|placement| placement.component != id);
980        }
981        Ok(())
982    }
983    /// Bind a placed component to a DIFFERENT device — the resolving half of
984    /// the UNLINKED lane.
985    ///
986    /// A sheet component names its device by OCCURRENCE ([`PartSource::instance`]),
987    /// and neither half of that is stable on its own: an occurrence chain
988    /// changes whenever the device is moved in the assembly tree, and the
989    /// parts-library key is not stable across a part's version history. When
990    /// the binding cannot be resolved the component goes UNLINKED and the USER
991    /// picks its device; this is what that pick does. Nothing is guessed at
992    /// here, and nothing but the binding moves: the component keeps where it
993    /// sits, what it is called, and every wire landing on a pin it still has.
994    ///
995    /// A device already placed on this sheet is refused, as
996    /// [`Document::place_assembly_component`] refuses one.
997    pub fn relink(
998        &mut self,
999        component: Uuid,
1000        part: PartSource,
1001        symbol: &Symbol,
1002        pads: Option<&board::Footprint>,
1003        renames: &BTreeMap<String, String>,
1004    ) -> Result<(), String> {
1005        if part.signature.trim().is_empty() {
1006            return Err("A part needs a key and a signature".into());
1007        }
1008        if !self.components.iter().any(|c| c.id == component) {
1009            return Err("Component no longer exists".into());
1010        }
1011        if let Some(instance) = &part.instance
1012            && self.components.iter().any(|c| {
1013                c.id != component
1014                    && c.part.as_ref().and_then(|p| p.instance.as_ref()) == Some(instance)
1015            })
1016        {
1017            return Err("This native assembly instance is already placed".into());
1018        }
1019        let mut draft = self.clone();
1020        // A component drawn without a part has none to bind; give it one, so a
1021        // legacy symbol can be linked to a device for the first time.
1022        if let Some(c) = draft.components.iter_mut().find(|c| c.id == component)
1023            && c.part.is_none()
1024        {
1025            c.part = Some(part.clone());
1026        }
1027        draft.rebind(component, symbol, pads, renames, |bound| *bound = part)?;
1028        *self = draft;
1029        Ok(())
1030    }
1031    /// Move every terminal of component `id` from an old pin label to its new one.
1032    /// All move at once, so two labels that trade places swap rather than merge.
1033    fn rename_terminals(&mut self, id: Uuid, renames: &BTreeMap<String, String>) {
1034        let rename = |terminal: &mut Terminal| {
1035            if terminal.component == id
1036                && let Some(label) = renames.get(&terminal.pin)
1037            {
1038                terminal.pin = label.clone();
1039            }
1040        };
1041        let terminals = self
1042            .wires
1043            .iter_mut()
1044            .flat_map(|w| [w.start.as_mut(), w.end.as_mut()])
1045            .chain(self.labels.iter_mut().map(|l| l.terminal.as_mut()));
1046        for terminal in terminals.flatten() {
1047            rename(terminal);
1048        }
1049        // The check's markers follow their pin the same way.
1050        for terminal in self.no_connects.iter_mut().chain(self.power_flags.iter_mut()) {
1051            rename(terminal);
1052        }
1053    }
1054    pub fn add_wire(&mut self, a: Point, b: Point) {
1055        if self.kind == DocumentKind::Schematic
1056            && a != b
1057            && (a.x == b.x || a.y == b.y)
1058            && !self
1059                .wires
1060                .iter()
1061                .any(|w| (w.a == a && w.b == b) || (w.a == b && w.b == a))
1062        {
1063            let mut wire = Wire::new(a, b);
1064            wire.start = self.terminal_at(a);
1065            wire.end = self.terminal_at(b);
1066            self.wires.push(wire);
1067        }
1068    }
1069    /// Create or rename the flag attached to this pin. Equal names share a net.
1070    pub fn set_net_flag(&mut self, terminal: Terminal, name: &str) -> Result<Uuid, String> {
1071        if self.kind == DocumentKind::Wiring {
1072            return Err("A wiring diagram has no nets".into());
1073        }
1074        let name = name.trim();
1075        if name.is_empty() {
1076            return Err("Enter a net name".into());
1077        }
1078        let at = self
1079            .terminal_position(&terminal)
1080            .ok_or("Terminal no longer exists")?;
1081        if let Some(label) = self
1082            .labels
1083            .iter_mut()
1084            .find(|l| l.terminal.as_ref() == Some(&terminal))
1085        {
1086            label.name = name.into();
1087            label.at = at;
1088            return Ok(label.id);
1089        }
1090        let id = Uuid::new_v4();
1091        self.labels.push(Label {
1092            flag: true,
1093            rotation: 0,
1094            id,
1095            name: name.into(),
1096            at,
1097            terminal: Some(terminal),
1098        });
1099        Ok(id)
1100    }
1101    /// Move the tip; free wire endpoints follow, and direct pin contact is
1102    /// recomputed at the new location.
1103    pub fn transform_label(&mut self, id: Uuid, at: Point, rotation: u8) {
1104        let terminal = self.terminal_at(at);
1105        let Some(label) = self.labels.iter_mut().find(|l| l.id == id) else {
1106            return;
1107        };
1108        let old = label.at;
1109        label.flag |= label.terminal.is_some();
1110        label.at = at;
1111        label.rotation = rotation % 4;
1112        label.terminal = terminal;
1113        for wire in &mut self.wires {
1114            let a = if wire.a == old && wire.start.is_none() {
1115                at
1116            } else {
1117                wire.a
1118            };
1119            let b = if wire.b == old && wire.end.is_none() {
1120                at
1121            } else {
1122                wire.b
1123            };
1124            wire.follow(a, b);
1125        }
1126    }
1127    pub fn terminal_position(&self, terminal: &Terminal) -> Option<Point> {
1128        let c = self
1129            .components
1130            .iter()
1131            .find(|c| c.id == terminal.component)?;
1132        c.symbol
1133            .pins
1134            .iter()
1135            .find(|p| p.number == terminal.pin)
1136            .map(|p| c.pin_at(p))
1137    }
1138    pub fn terminal_at(&self, at: Point) -> Option<Terminal> {
1139        self.components.iter().find_map(|c| {
1140            c.symbol
1141                .pins
1142                .iter()
1143                .find(|p| c.pin_at(p) == at)
1144                .map(|p| Terminal {
1145                    component: c.id,
1146                    pin: p.number.clone(),
1147                })
1148        })
1149    }
1150    /// Short orthogonal route with outward terminal leads. Avoid crossing other
1151    /// terminal positions; this is deliberately not a full obstacle router.
1152    pub fn connection_path(&self, start: &Terminal, end: &Terminal) -> Option<Vec<Point>> {
1153        let a = self.terminal_position(start)?;
1154        let b = self.terminal_position(end)?;
1155        let outward = |t: &Terminal, at: Point| -> Option<Point> {
1156            let c = self.components.iter().find(|c| c.id == t.component)?;
1157            let p = c.symbol.pins.iter().find(|p| p.number == t.pin)?;
1158            let inside = c.pin_end(p);
1159            Some(Point::new(
1160                (at.x - inside.x).signum() * 2540,
1161                (at.y - inside.y).signum() * 2540,
1162            ))
1163        };
1164        let da = outward(start, a)?;
1165        let db = outward(end, b)?;
1166        let sa = a.offset(da);
1167        let sb = b.offset(db);
1168        let pins: Vec<_> = self
1169            .components
1170            .iter()
1171            .flat_map(|c| c.symbol.pins.iter().map(|p| c.pin_at(p)))
1172            .collect();
1173        let min_x = pins
1174            .iter()
1175            .map(|p| p.x)
1176            .min()
1177            .unwrap_or(0)
1178            .min(sa.x)
1179            .min(sb.x)
1180            - 5080;
1181        let max_x = pins
1182            .iter()
1183            .map(|p| p.x)
1184            .max()
1185            .unwrap_or(0)
1186            .max(sa.x)
1187            .max(sb.x)
1188            + 5080;
1189        let min_y = pins
1190            .iter()
1191            .map(|p| p.y)
1192            .min()
1193            .unwrap_or(0)
1194            .min(sa.y)
1195            .min(sb.y)
1196            - 5080;
1197        let max_y = pins
1198            .iter()
1199            .map(|p| p.y)
1200            .max()
1201            .unwrap_or(0)
1202            .max(sa.y)
1203            .max(sb.y)
1204            + 5080;
1205        let mut candidates = vec![
1206            vec![a, sa, Point::new(sb.x, sa.y), sb, b],
1207            vec![a, sa, Point::new(sa.x, sb.y), sb, b],
1208        ];
1209        for x in [min_x, max_x] {
1210            candidates.push(vec![a, sa, Point::new(x, sa.y), Point::new(x, sb.y), sb, b]);
1211        }
1212        for y in [min_y, max_y] {
1213            candidates.push(vec![a, sa, Point::new(sa.x, y), Point::new(sb.x, y), sb, b]);
1214        }
1215        candidates
1216            .into_iter()
1217            .filter_map(|p| {
1218                let mut w = Wire::new(a, b);
1219                w.set_points(p);
1220                let p = w.points();
1221                let first = Point::new(p[1].x - a.x, p[1].y - a.y);
1222                let n = p.len();
1223                let last = Point::new(p[n - 2].x - b.x, p[n - 2].y - b.y);
1224                let dot = |x: Point, y: Point| {
1225                    i64::from(x.x) * i64::from(y.x) + i64::from(x.y) * i64::from(y.y)
1226                };
1227                if dot(first, da) <= 0 || dot(last, db) <= 0 {
1228                    return None;
1229                }
1230                if pins
1231                    .iter()
1232                    .filter(|p| **p != a && **p != b)
1233                    .any(|pin| p.windows(2).any(|s| on_segment(*pin, s[0], s[1])))
1234                {
1235                    return None;
1236                }
1237                let length: u64 = p
1238                    .windows(2)
1239                    .map(|s| {
1240                        u64::from(s[0].x.abs_diff(s[1].x)) + u64::from(s[0].y.abs_diff(s[1].y))
1241                    })
1242                    .sum();
1243                Some((length, p))
1244            })
1245            .min_by_key(|(length, _)| *length)
1246            .map(|(_, p)| p)
1247    }
1248    pub fn target_position(&self, target: &ConnectionTarget) -> Option<Point> {
1249        match target {
1250            ConnectionTarget::Terminal(t) => self.terminal_position(t),
1251            ConnectionTarget::Junction(p) => {
1252                (self.junctions.contains(p) || self.labels.iter().any(|l| l.at == *p)).then_some(*p)
1253            }
1254        }
1255    }
1256    pub fn target_path(
1257        &self,
1258        start: &ConnectionTarget,
1259        end: &ConnectionTarget,
1260    ) -> Option<Vec<Point>> {
1261        let a = self.target_position(start)?;
1262        let b = self.target_position(end)?;
1263        if let (ConnectionTarget::Terminal(start), ConnectionTarget::Terminal(end)) = (start, end) {
1264            return Some(
1265                self.connection_path(start, end)
1266                    .unwrap_or_else(|| vec![a, Point::new(b.x, a.y), b]),
1267            );
1268        }
1269        Some(vec![a, Point::new(b.x, a.y), b])
1270    }
1271    pub fn connect_targets(
1272        &mut self,
1273        start: ConnectionTarget,
1274        end: ConnectionTarget,
1275    ) -> Option<Uuid> {
1276        if let (ConnectionTarget::Terminal(a), ConnectionTarget::Terminal(b)) = (&start, &end) {
1277            return self.connect(a.clone(), b.clone());
1278        }
1279        if self.kind == DocumentKind::Wiring {
1280            return None; // Connections run pin to pin; there are no junctions.
1281        }
1282        let a = self.target_position(&start)?;
1283        let b = self.target_position(&end)?;
1284        if a == b
1285            || self
1286                .wires
1287                .iter()
1288                .any(|w| (w.a == a && w.b == b) || (w.a == b && w.b == a))
1289        {
1290            return None;
1291        }
1292        let mut w = Wire::new(a, b);
1293        w.set_points(self.target_path(&start, &end)?);
1294        if let ConnectionTarget::Terminal(t) = start {
1295            w.start = Some(t);
1296        }
1297        if let ConnectionTarget::Terminal(t) = end {
1298            w.end = Some(t);
1299        }
1300        let id = w.id;
1301        self.wires.push(w);
1302        Some(id)
1303    }
1304    pub fn connect(&mut self, start: Terminal, end: Terminal) -> Option<Uuid> {
1305        if start == end {
1306            return None;
1307        }
1308        let a = self.terminal_position(&start)?;
1309        let b = self.terminal_position(&end)?;
1310        if a == b {
1311            return None;
1312        }
1313        if self.wires.iter().any(|w| {
1314            (w.start.as_ref() == Some(&start) && w.end.as_ref() == Some(&end))
1315                || (w.start.as_ref() == Some(&end) && w.end.as_ref() == Some(&start))
1316        }) {
1317            return None;
1318        }
1319        let wiring = self.kind == DocumentKind::Wiring;
1320        if wiring && (self.attached_wire(&start).is_some() || self.attached_wire(&end).is_some()) {
1321            return None;
1322        }
1323        let mut wire = Wire::new(a, b);
1324        wire.set_points(
1325            self.connection_path(&start, &end)
1326                .unwrap_or_else(|| vec![a, Point::new(b.x, a.y), b]),
1327        );
1328        wire.start = Some(start);
1329        wire.end = Some(end);
1330        if wiring {
1331            let mut n = 1;
1332            while self
1333                .wires
1334                .iter()
1335                .any(|w| w.connection_id == format!("W{n}"))
1336            {
1337                n += 1;
1338            }
1339            wire.connection_id = format!("W{n}");
1340        }
1341        let id = wire.id;
1342        self.wires.push(wire);
1343        Some(id)
1344    }
1345    /// The wire with an end attached to this pin, if any.
1346    pub fn attached_wire(&self, terminal: &Terminal) -> Option<&Wire> {
1347        self.wires
1348            .iter()
1349            .find(|w| w.start.as_ref() == Some(terminal) || w.end.as_ref() == Some(terminal))
1350    }
1351    /// A pin as reference and pin number, such as `R1.2`.
1352    pub fn terminal_name(&self, terminal: &Terminal) -> String {
1353        let reference = self
1354            .components
1355            .iter()
1356            .find(|c| c.id == terminal.component)
1357            .map_or("?", |c| c.reference.as_str());
1358        format!("{reference}.{}", terminal.pin)
1359    }
1360    /// A wiring diagram's point-to-point connections, ordered by connection ID. Each runs
1361    /// from the pin its wire was drawn from; a port is a pin number.
1362    pub fn connections(&self) -> Vec<Connection> {
1363        let reference = |t: &Terminal| {
1364            self.components
1365                .iter()
1366                .find(|c| c.id == t.component)
1367                .map(|c| c.reference.clone())
1368        };
1369        let mut rows: Vec<_> = self
1370            .wires
1371            .iter()
1372            .filter_map(|w| {
1373                let (start, end) = (w.start.as_ref()?, w.end.as_ref()?);
1374                Some(Connection {
1375                    connection_id: w.connection_id.clone(),
1376                    from_ref_des: reference(start)?,
1377                    from_port: start.pin.clone(),
1378                    to_ref_des: reference(end)?,
1379                    to_port: end.pin.clone(),
1380                    stock_part_number: w.stock_part_number.clone(),
1381                })
1382            })
1383            .collect();
1384        rows.sort_by(|a, b| id_order(&a.connection_id).cmp(&id_order(&b.connection_id)));
1385        rows
1386    }
1387    /// The connection list as CSV: a header row, then one row per connection.
1388    pub fn connections_csv(&self) -> Result<String, String> {
1389        if self.kind != DocumentKind::Wiring {
1390            return Err("Only a wiring diagram has a connection list".into());
1391        }
1392        self.validate()?;
1393        let mut csv =
1394            String::from("connectionID,fromRefDes,fromPort,toRefDes,toPort,stockPartNumber\n");
1395        for c in self.connections() {
1396            let fields = [
1397                &c.connection_id,
1398                &c.from_ref_des,
1399                &c.from_port,
1400                &c.to_ref_des,
1401                &c.to_port,
1402                &c.stock_part_number,
1403            ];
1404            csv.push_str(&fields.map(|f| csv_field(f)).join(","));
1405            csv.push('\n');
1406        }
1407        Ok(csv)
1408    }
1409    /// Bring every component whose symbol the KiCad import wrote before gates
1410    /// existed up to the gate shape ([`Symbol::migrate_legacy_units`]), each
1411    /// gate placed exactly where the symbol drawn whole put it, so no pin, wire
1412    /// or flag moves. Returns the references of the components it changed.
1413    ///
1414    /// A host calls this where it OPENS a stored sheet, and adopts the result
1415    /// as part of the document rather than as an edit: nothing the user drew
1416    /// changes, and a sheet not saved again is migrated the same way the next
1417    /// time it is opened.
1418    pub fn migrate_legacy_units(&mut self) -> Vec<String> {
1419        let mut migrated = vec![];
1420        for c in &mut self.components {
1421            if c.symbol.migrate_legacy_units() {
1422                c.gates.clear();
1423                c.sync_gates();
1424                migrated.push(c.reference.clone());
1425            }
1426        }
1427        migrated
1428    }
1429    /// Replace one instance's definition, retaining connectivity by pin number.
1430    pub fn replace_component_symbol(&mut self, id: Uuid, mut symbol: Symbol) -> Result<(), String> {
1431        symbol.migrate_legacy_units();
1432        let mut draft = self.clone();
1433        let c = draft
1434            .components
1435            .iter()
1436            .find(|c| c.id == id)
1437            .ok_or("Component no longer exists")?;
1438        let (at, rotation) = (c.at, c.rotation);
1439        draft.transform_component(id, at, rotation); // bind legacy endpoints before changing geometry
1440        let valid_terminal =
1441            |t: &Terminal| t.component != id || symbol.pins.iter().any(|p| p.number == t.pin);
1442        if draft.kind == DocumentKind::Wiring {
1443            // A connection needs both of its pins; one that loses a pin goes with it.
1444            draft.wires.retain(|w| {
1445                w.start.as_ref().is_none_or(valid_terminal)
1446                    && w.end.as_ref().is_none_or(valid_terminal)
1447            });
1448        }
1449        for wire in &mut draft.wires {
1450            if wire.start.as_ref().is_some_and(|t| !valid_terminal(t)) {
1451                wire.start = None;
1452            }
1453            if wire.end.as_ref().is_some_and(|t| !valid_terminal(t)) {
1454                wire.end = None;
1455            }
1456        }
1457        for label in &mut draft.labels {
1458            if label.terminal.as_ref().is_some_and(|t| !valid_terminal(t)) {
1459                label.flag = true;
1460                label.terminal = None;
1461            }
1462        }
1463        draft.no_connects.retain(valid_terminal);
1464        draft.power_flags.retain(valid_terminal);
1465        let c = draft.components.iter_mut().find(|c| c.id == id).unwrap();
1466        c.symbol = symbol;
1467        c.sync_gates();
1468        draft.transform_component(id, at, rotation);
1469        draft.validate()?;
1470        *self = draft;
1471        Ok(())
1472    }
1473    /// Infer attachments on legacy/free wires before moving, then keep them attached.
1474    /// A component whose gates are placed apart moves as one: every gate goes
1475    /// with it, turned about `at` by the same quarter turns.
1476    pub fn transform_component(&mut self, id: Uuid, at: Point, rotation: u8) {
1477        self.reposition(id, |c| {
1478            let turn = (rotation % 4 + 4 - c.rotation) % 4;
1479            for g in &mut c.gates {
1480                g.at = Point::new(g.at.x - c.at.x, g.at.y - c.at.y).rotate(turn).offset(at);
1481                g.rotation = (g.rotation + turn) % 4;
1482            }
1483            let rotated = c.rotation != rotation % 4;
1484            c.at = at;
1485            c.rotation = rotation % 4;
1486            rotated
1487        });
1488    }
1489    /// Move and turn ONE gate of a component whose gates are placed apart
1490    /// ([`Component::gates`]); its wires and flags follow as they follow a
1491    /// component. Nothing happens for a gate the component does not place.
1492    pub fn transform_gate(&mut self, id: Uuid, gate: u32, at: Point, rotation: u8) {
1493        self.reposition(id, |c| {
1494            let Some(g) = c.gates.iter_mut().find(|g| g.gate == gate) else {
1495                return false;
1496            };
1497            let rotated = g.rotation != rotation % 4;
1498            g.at = at;
1499            g.rotation = rotation % 4;
1500            rotated
1501        });
1502    }
1503    /// Change where component `id` is drawn with `change`, which says whether it
1504    /// turned anything; wires attached to it follow (a turn reroutes them) and
1505    /// its flags move with their pins.
1506    fn reposition(&mut self, id: Uuid, change: impl FnOnce(&mut Component) -> bool) {
1507        let bindings: Vec<_> = self
1508            .wires
1509            .iter()
1510            .map(|w| {
1511                (
1512                    w.start.clone().or_else(|| self.terminal_at(w.a)),
1513                    w.end.clone().or_else(|| self.terminal_at(w.b)),
1514                )
1515            })
1516            .collect();
1517        // Which way each flag's pin on this component points, before the turn.
1518        let leads_before: Vec<_> = self
1519            .labels
1520            .iter()
1521            .map(|l| l.terminal.as_ref().filter(|t| t.component == id).and_then(|t| self.lead(t)))
1522            .collect();
1523        let Some(c) = self.components.iter_mut().find(|c| c.id == id) else {
1524            return;
1525        };
1526        let rotated = change(c);
1527        let routes: Vec<_> = bindings
1528            .iter()
1529            .map(|(a, b)| {
1530                if rotated && a.as_ref().is_some_and(|t| t.component == id)
1531                    || rotated && b.as_ref().is_some_and(|t| t.component == id)
1532                {
1533                    a.as_ref()
1534                        .zip(b.as_ref())
1535                        .and_then(|(a, b)| self.connection_path(a, b))
1536                } else {
1537                    None
1538                }
1539            })
1540            .collect();
1541        let positions: Vec<_> = bindings
1542            .iter()
1543            .map(|(a, b)| {
1544                (
1545                    a.as_ref().and_then(|t| self.terminal_position(t)),
1546                    b.as_ref().and_then(|t| self.terminal_position(t)),
1547                )
1548            })
1549            .collect();
1550        for (((w, (start, end)), (a, b)), route) in self
1551            .wires
1552            .iter_mut()
1553            .zip(bindings)
1554            .zip(positions)
1555            .zip(routes)
1556        {
1557            w.start = start;
1558            w.end = end;
1559            w.follow(a.unwrap_or(w.a), b.unwrap_or(w.b));
1560            if let Some(route) = route {
1561                w.set_points(route);
1562            }
1563        }
1564        let flag_positions: Vec<_> = self
1565            .labels
1566            .iter()
1567            .map(|l| l.terminal.as_ref().and_then(|t| self.terminal_position(t)))
1568            .collect();
1569        let leads_after: Vec<_> = self
1570            .labels
1571            .iter()
1572            .map(|l| l.terminal.as_ref().filter(|t| t.component == id).and_then(|t| self.lead(t)))
1573            .collect();
1574        for (((label, at), before), after) in self
1575            .labels
1576            .iter_mut()
1577            .zip(flag_positions)
1578            .zip(leads_before)
1579            .zip(leads_after)
1580        {
1581            if let Some(at) = at {
1582                label.at = at;
1583            }
1584            // A flag turns with the pin it stands on, by the same quarter
1585            // turns, so one set to point away from a gate still does after the
1586            // gate turns. Relative, so a flag the user turned keeps that.
1587            if let (Some(before), Some(after)) = (before, after)
1588                && let Some(turn) = (0..4u8).find(|&k| before.rotate(k) == after)
1589            {
1590                label.rotation = (label.rotation + turn) % 4;
1591            }
1592        }
1593    }
1594    /// The way a pin's lead runs on the sheet, from its terminal toward its
1595    /// body, as a unit step along one axis; `None` for a pin of no length or
1596    /// a terminal that no longer exists.
1597    fn lead(&self, terminal: &Terminal) -> Option<Point> {
1598        let c = self.components.iter().find(|c| c.id == terminal.component)?;
1599        let pin = c.symbol.pins.iter().find(|p| p.number == terminal.pin)?;
1600        let (at, end) = (c.pin_at(pin), c.pin_end(pin));
1601        let step = Point::new((end.x - at.x).signum(), (end.y - at.y).signum());
1602        (step != Point::default()).then_some(step)
1603    }
1604    /// Where a new component drawn with `symbol` can go without covering one already
1605    /// on the sheet: the first free cell, row by row and eight to a row, of a grid
1606    /// that starts at the sheet origin. A cell is the symbol's own box plus a gap:
1607    /// 10.16 mm across, which is room for the reference and value an editor writes
1608    /// to the right of a symbol (two lines of text, some 80 points wide at the
1609    /// default zoom), and 5.08 mm down. The origin itself when it is free, so the
1610    /// first part lands where it always did.
1611    ///
1612    /// A host that seats parts on its own, with no pointer to say where, asks this
1613    /// rather than stacking every part at the origin: stacked parts publish the same
1614    /// rect, and a click or a drag reaches only the one drawn last (the eCAD workflow
1615    /// audit, issue 6).
1616    pub fn open_spot(&self, symbol: &Symbol) -> Point {
1617        const ACROSS: i32 = 10160;
1618        const DOWN: i32 = 5080;
1619        let (lo, hi) = symbol_extent(symbol, 0);
1620        let cell = |span: i32, gap: i32| (span.max(0) + gap + 1269) / 1270 * 1270;
1621        let (w, h) = (cell(hi.x - lo.x, ACROSS), cell(hi.y - lo.y, DOWN));
1622        let taken: Vec<(Point, Point)> = self
1623            .components
1624            .iter()
1625            .flat_map(Component::sheet_boxes)
1626            .map(|(_, a, b)| (a, b))
1627            .collect();
1628        let (x, y) = (ACROSS / 2, DOWN / 2);
1629        for row in 0..256 {
1630            for col in 0..8 {
1631                let at = Point::new(col * w, row * h);
1632                let (a, b) = (lo.offset(at), hi.offset(at));
1633                let clear = taken.iter().all(|(c, d)| {
1634                    a.x - x > d.x || b.x + x < c.x || a.y - y > d.y || b.y + y < c.y
1635                });
1636                if clear {
1637                    return at;
1638                }
1639            }
1640        }
1641        Point::default()
1642    }
1643    /// Whether component `id` covers part of another component, each taken as the box
1644    /// its symbol spans grown by half a sheet grid step (635 µm) on every side — so a
1645    /// symbol that is only a row of pins, whose box has no height, still covers one
1646    /// drawn on top of it, and parts a whole grid step apart do not.
1647    pub fn covers_another(&self, id: Uuid) -> bool {
1648        let spans = |c: &Component| -> Vec<(Point, Point)> {
1649            c.sheet_boxes()
1650                .into_iter()
1651                .map(|(_, a, b)| (a.offset(Point::new(-635, -635)), b.offset(Point::new(635, 635))))
1652                .collect()
1653        };
1654        let Some(mine) = self.components.iter().find(|c| c.id == id).map(spans) else {
1655            return false;
1656        };
1657        self.components
1658            .iter()
1659            .filter(|c| c.id != id)
1660            .flat_map(spans)
1661            .any(|(c, d)| mine.iter().any(|(a, b)| a.x < d.x && c.x < b.x && a.y < d.y && c.y < b.y))
1662    }
1663    pub fn delete_component(&mut self, id: Uuid) {
1664        self.components.retain(|c| c.id != id);
1665        self.board.placements.retain(|p| p.component != id);
1666        self.labels
1667            .retain(|l| !l.terminal.as_ref().is_some_and(|t| t.component == id));
1668        self.no_connects.retain(|t| t.component != id);
1669        self.power_flags.retain(|t| t.component != id);
1670        if self.kind == DocumentKind::Wiring {
1671            // A connection needs both of its pins.
1672            let attached = |t: &Option<Terminal>| t.as_ref().is_some_and(|t| t.component == id);
1673            self.wires
1674                .retain(|w| !attached(&w.start) && !attached(&w.end));
1675        }
1676        for w in &mut self.wires {
1677            if w.start.as_ref().is_some_and(|t| t.component == id) {
1678                w.start = None;
1679            }
1680            if w.end.as_ref().is_some_and(|t| t.component == id) {
1681                w.end = None;
1682            }
1683        }
1684    }
1685    pub fn from_json(text: &str) -> Result<Self, String> {
1686        Self::migrated(serde_json::from_str(text).map_err(|e| e.to_string())?)
1687    }
1688    pub fn to_json(&self) -> Result<String, String> {
1689        self.validate()?;
1690        serde_json::to_string_pretty(self).map_err(|e| e.to_string())
1691    }
1692    /// Read a document kept inside a host's own JSON file, with the same migration and
1693    /// checks as [`Document::from_json`].
1694    pub fn from_value(value: serde_json::Value) -> Result<Self, String> {
1695        Self::migrated(serde_json::from_value(value).map_err(|e| e.to_string())?)
1696    }
1697    /// The document as a JSON value for a host's own file, checked as
1698    /// [`Document::to_json`] checks it.
1699    pub fn to_value(&self) -> Result<serde_json::Value, String> {
1700        self.validate()?;
1701        serde_json::to_value(self).map_err(|e| e.to_string())
1702    }
1703    fn migrated(mut doc: Self) -> Result<Self, String> {
1704        if (1..DOCUMENT_VERSION).contains(&doc.version) {
1705            doc.version = DOCUMENT_VERSION;
1706        }
1707        doc.validate()?;
1708        Ok(doc)
1709    }
1710    pub fn validate(&self) -> Result<(), String> {
1711        let version = match self.kind {
1712            DocumentKind::Schematic => DOCUMENT_VERSION,
1713            DocumentKind::Wiring => WIRING_DOCUMENT_VERSION,
1714        };
1715        if self.version != version {
1716            return Err(format!("Unsupported document version {}", self.version));
1717        }
1718        let mut ids = BTreeSet::new();
1719        let mut refs = BTreeSet::new();
1720        for id in self
1721            .components
1722            .iter()
1723            .map(|c| c.id)
1724            .chain(self.wires.iter().map(|w| w.id))
1725            .chain(self.labels.iter().map(|l| l.id))
1726            .chain(self.board.tracks.iter().map(|t| t.id))
1727            .chain(self.board.vias.iter().map(|v| v.id))
1728        {
1729            if !ids.insert(id) {
1730                return Err("Duplicate object ID".into());
1731            }
1732        }
1733        let valid = |p: Point| p.x.abs_diff(0) <= 100_000_000 && p.y.abs_diff(0) <= 100_000_000;
1734        for c in &self.components {
1735            if c.reference.trim().is_empty() || !refs.insert(&c.reference) {
1736                return Err("Component references must be nonempty and unique".into());
1737            }
1738            if !valid(c.at) || c.rotation > 3 {
1739                return Err("Invalid component placement".into());
1740            }
1741            let mut gates = BTreeSet::new();
1742            for g in &c.gates {
1743                if g.gate == 0 || !gates.insert(g.gate) || !valid(g.at) || !valid(g.pivot) || g.rotation > 3 {
1744                    return Err("Invalid gate placement".into());
1745                }
1746            }
1747            let mut pins = BTreeSet::new();
1748            for pin in &c.symbol.pins {
1749                if pin.number.is_empty()
1750                    || !pins.insert(&pin.number)
1751                    || !valid(pin.at)
1752                    || !valid(pin.end)
1753                {
1754                    return Err("Invalid or duplicate symbol pin".into());
1755                }
1756            }
1757            if let Some(part) = &c.part
1758                && (part.key.trim().is_empty() || part.signature.trim().is_empty())
1759            {
1760                return Err("A part needs a key and a signature".into());
1761            }
1762            if let Some(pads) = &c.pads {
1763                pads.validate_placeable()?;
1764            }
1765            for g in &c.symbol.graphics {
1766                match g {
1767                    Graphic::Path(p) if p.iter().any(|p| !valid(*p)) => {
1768                        return Err("Invalid graphic coordinates".into());
1769                    }
1770                    Graphic::Circle { center, radius }
1771                        if !valid(*center) || !(0..=100_000_000).contains(radius) =>
1772                    {
1773                        return Err("Invalid circle".into());
1774                    }
1775                    Graphic::Text { at, size, .. }
1776                        if !valid(*at) || !(1..=100_000_000).contains(size) =>
1777                    {
1778                        return Err("Invalid symbol text".into());
1779                    }
1780                    _ => {}
1781                }
1782            }
1783        }
1784        for w in &self.wires {
1785            let points = w.points();
1786            if points.iter().any(|p| !valid(*p))
1787                || points
1788                    .windows(2)
1789                    .any(|p| p[0] == p[1] || (p[0].x != p[1].x && p[0].y != p[1].y))
1790            {
1791                return Err("Wire paths must contain nonzero orthogonal segments".into());
1792            }
1793            for (t, p) in [(&w.start, w.a), (&w.end, w.b)] {
1794                if let Some(t) = t
1795                    && self.terminal_position(t) != Some(p)
1796                {
1797                    return Err("Wire terminal attachment is missing or out of date".into());
1798                }
1799            }
1800        }
1801        for label in &self.labels {
1802            if let Some(t) = &label.terminal
1803                && self.terminal_position(t) != Some(label.at)
1804            {
1805                return Err("Net flag terminal attachment is missing or out of date".into());
1806            }
1807        }
1808        if self.junctions.iter().any(|p| !valid(*p))
1809            || self
1810                .labels
1811                .iter()
1812                .any(|l| l.name.trim().is_empty() || l.rotation > 3 || !valid(l.at))
1813        {
1814            return Err("Invalid junction or label".into());
1815        }
1816        if self.kind == DocumentKind::Wiring {
1817            self.validate_wiring()?;
1818        }
1819        self.board
1820            .validate(&self.components.iter().map(|c| c.id).collect())?;
1821        Ok(())
1822    }
1823    /// A wiring diagram has no nets: every wire is a connection between two symbol pins,
1824    /// no pin takes more than one, and connection IDs are nonempty and unique.
1825    fn validate_wiring(&self) -> Result<(), String> {
1826        if !self.junctions.is_empty() || !self.labels.is_empty() {
1827            return Err("A wiring diagram has no junctions or net labels".into());
1828        }
1829        let mut ids = BTreeSet::new();
1830        let mut pins = BTreeSet::new();
1831        for w in &self.wires {
1832            if w.connection_id.trim().is_empty() || !ids.insert(&w.connection_id) {
1833                return Err("Connection IDs must be nonempty and unique".into());
1834            }
1835            let (Some(start), Some(end)) = (&w.start, &w.end) else {
1836                return Err(format!("Connection {} must join two pins", w.connection_id));
1837            };
1838            for t in [start, end] {
1839                if !pins.insert((t.component, &t.pin)) {
1840                    return Err(format!(
1841                        "{} has more than one connection; a wiring diagram pin takes one",
1842                        self.terminal_name(t)
1843                    ));
1844                }
1845            }
1846        }
1847        Ok(())
1848    }
1849    /// Rebuild electrical equivalence classes. Interior crossings do not connect
1850    /// unless a junction, pin, or label is explicitly present there.
1851    pub fn netlist(&self) -> Netlist {
1852        let mut points = BTreeSet::new();
1853        for w in &self.wires {
1854            points.extend([w.a, w.b]);
1855        }
1856        points.extend(self.junctions.iter().copied());
1857        points.extend(self.labels.iter().map(|l| l.at));
1858        for c in &self.components {
1859            points.extend(c.symbol.pins.iter().map(|p| c.pin_at(p)));
1860        }
1861        let points: Vec<_> = points.into_iter().collect();
1862        let index: BTreeMap<_, _> = points.iter().enumerate().map(|(i, p)| (*p, i)).collect();
1863        let mut groups: Vec<usize> = (0..points.len()).collect();
1864        fn root(g: &[usize], mut i: usize) -> usize {
1865            while g[i] != i {
1866                i = g[i];
1867            }
1868            i
1869        }
1870        fn join(g: &mut [usize], a: usize, b: usize) {
1871            let a = root(g, a);
1872            let b = root(g, b);
1873            g[b] = a;
1874        }
1875        for w in &self.wires {
1876            let a = index[&w.a];
1877            let path = w.points();
1878            for (i, p) in points.iter().enumerate() {
1879                if path.windows(2).any(|s| on_segment(*p, s[0], s[1])) {
1880                    join(&mut groups, a, i);
1881                }
1882            }
1883        }
1884        let mut names = BTreeMap::new();
1885        for l in &self.labels {
1886            let i = index[&l.at];
1887            if let Some(&other) = names.get(&l.name) {
1888                join(&mut groups, i, other);
1889            } else {
1890                names.insert(l.name.clone(), i);
1891            }
1892        }
1893        let mut nets: BTreeMap<usize, Net> = BTreeMap::new();
1894        for (i, p) in points.iter().enumerate() {
1895            nets.entry(root(&groups, i)).or_default().points.push(*p);
1896        }
1897        for l in &self.labels {
1898            nets.get_mut(&root(&groups, index[&l.at]))
1899                .unwrap()
1900                .labels
1901                .insert(l.name.clone());
1902        }
1903        for c in &self.components {
1904            for p in &c.symbol.pins {
1905                nets.get_mut(&root(&groups, index[&c.pin_at(p)]))
1906                    .unwrap()
1907                    .pins
1908                    .push(NetPin {
1909                        component_id: c.id,
1910                        reference: c.reference.clone(),
1911                        number: p.number.clone(),
1912                        electrical_type: p.electrical_type.clone(),
1913                    });
1914            }
1915        }
1916        let mut nets: Vec<_> = nets.into_values().collect();
1917        nets.sort_by_key(|n| n.points[0]);
1918        let mut diagnostics = vec![];
1919        for (i, n) in nets.iter_mut().enumerate() {
1920            n.name = n
1921                .labels
1922                .iter()
1923                .next()
1924                .cloned()
1925                .unwrap_or_else(|| format!("N${}", i + 1));
1926            if n.labels.len() > 1 {
1927                diagnostics.push(format!(
1928                    "{}: conflicting labels {}",
1929                    n.name,
1930                    n.labels.iter().cloned().collect::<Vec<_>>().join(", ")
1931                ));
1932            }
1933            if n.pins.len() == 1 {
1934                diagnostics.push(format!(
1935                    "{}.{} has no other connected pin",
1936                    n.pins[0].reference, n.pins[0].number
1937                ));
1938            }
1939            if n.pins
1940                .iter()
1941                .filter(|p| p.electrical_type == "output")
1942                .count()
1943                > 1
1944            {
1945                diagnostics.push(format!("{}: multiple output pins", n.name));
1946            }
1947        }
1948        Netlist {
1949            version: 1,
1950            nets,
1951            diagnostics,
1952        }
1953    }
1954}
1955/// Sorts IDs such as `W2` before `W10`.
1956fn id_order(id: &str) -> (&str, u64, &str) {
1957    let prefix = id.trim_end_matches(|c: char| c.is_ascii_digit());
1958    (prefix, id[prefix.len()..].parse().unwrap_or(0), id)
1959}
1960/// The box a symbol covers turned by `rotation` quarter turns about its origin: its
1961/// pins end to end, its paths, circles and text anchors. A symbol with nothing in
1962/// it covers its origin.
1963fn symbol_extent(symbol: &Symbol, rotation: u8) -> (Point, Point) {
1964    let mut points = vec![Point::default()];
1965    for pin in &symbol.pins {
1966        points.extend([pin.at, pin.end]);
1967    }
1968    for g in &symbol.graphics {
1969        match g {
1970            Graphic::Path(path) => points.extend(path.iter().copied()),
1971            Graphic::Circle { center, radius } => points.extend([
1972                Point::new(center.x - radius, center.y - radius),
1973                Point::new(center.x + radius, center.y + radius),
1974            ]),
1975            Graphic::Text { at, .. } => points.push(*at),
1976        }
1977    }
1978    let turned: Vec<Point> = points.into_iter().map(|p| p.rotate(rotation)).collect();
1979    let lo = Point::new(
1980        turned.iter().map(|p| p.x).min().unwrap_or(0),
1981        turned.iter().map(|p| p.y).min().unwrap_or(0),
1982    );
1983    let hi = Point::new(
1984        turned.iter().map(|p| p.x).max().unwrap_or(0),
1985        turned.iter().map(|p| p.y).max().unwrap_or(0),
1986    );
1987    (lo, hi)
1988}
1989/// A CSV field, quoted (inner quotes doubled) when it holds a comma, a quote
1990/// or a line break: the one rule for the crate's CSVs (the BOM here, the
1991/// fabrication pick-and-place and parts BOM).
1992pub(crate) fn csv_field(text: &str) -> String {
1993    if text.contains([',', '"', '\n', '\r']) {
1994        format!("\"{}\"", text.replace('"', "\"\""))
1995    } else {
1996        text.into()
1997    }
1998}
1999pub fn on_segment(p: Point, a: Point, b: Point) -> bool {
2000    (a.x == b.x && p.x == a.x && p.y >= a.y.min(b.y) && p.y <= a.y.max(b.y))
2001        || (a.y == b.y && p.y == a.y && p.x >= a.x.min(b.x) && p.x <= a.x.max(b.x))
2002}
2003#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2004pub struct Net {
2005    pub name: String,
2006    pub labels: BTreeSet<String>,
2007    pub pins: Vec<NetPin>,
2008    pub points: Vec<Point>,
2009}
2010#[derive(Clone, Debug, Serialize, Deserialize)]
2011pub struct NetPin {
2012    pub component_id: Uuid,
2013    pub reference: String,
2014    pub number: String,
2015    pub electrical_type: String,
2016}
2017#[derive(Clone, Debug, Serialize, Deserialize)]
2018pub struct Netlist {
2019    pub version: u32,
2020    pub nets: Vec<Net>,
2021    pub diagnostics: Vec<String>,
2022}
2023
2024/// Snapshot history: one transaction per gesture; no filesystem or UI dependency.
2025/// Defaults to a document, and also serves the symbol and footprint editors.
2026pub struct History<T = Document> {
2027    undo: Vec<T>,
2028    redo: Vec<T>,
2029}
2030impl<T> Default for History<T> {
2031    fn default() -> Self {
2032        Self { undo: Vec::new(), redo: Vec::new() }
2033    }
2034}
2035impl<T: PartialEq> History<T> {
2036    pub fn record(&mut self, before: T, after: &T) {
2037        if &before != after {
2038            self.undo.push(before);
2039            if self.undo.len() > 100 {
2040                self.undo.remove(0);
2041            }
2042            self.redo.clear();
2043        }
2044    }
2045    pub fn undo(&mut self, doc: &mut T) {
2046        if let Some(previous) = self.undo.pop() {
2047            self.redo.push(std::mem::replace(doc, previous));
2048        }
2049    }
2050    pub fn redo(&mut self, doc: &mut T) {
2051        if let Some(next) = self.redo.pop() {
2052            self.undo.push(std::mem::replace(doc, next));
2053        }
2054    }
2055    pub fn can_undo(&self) -> bool {
2056        !self.undo.is_empty()
2057    }
2058    pub fn can_redo(&self) -> bool {
2059        !self.redo.is_empty()
2060    }
2061}