Skip to main content

brep_ecad_core/
lib.rs

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