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