Skip to main content

brep_ecad_core/
sheet.rs

1//! One sheet over a board's schematic and the harness wiring round it.
2//!
3//! A host keeps an assembly's eCAD in two documents: a schematic (the board this
4//! assembly is: its parts, its nets and its layout) and a wiring diagram (the parts
5//! off that board and the harness wires between them). The user edits them as ONE
6//! sheet, a [`DocumentKind::Sheet`]: the board is drawn as a zone round the parts on
7//! it, and the rest of the sheet holds the parts off it.
8//!
9//! - [`Document::merge_sheet`] reads the two into a sheet, and [`Document::split_sheet`]
10//!   writes a sheet back as the two. A split of a sheet nothing has edited gives back
11//!   documents EQUAL to the ones merged, so a host that writes only the documents that
12//!   changed writes nothing for an open.
13//! - A part on BOTH documents (a connector with nets on the board and a harness wire
14//!   off it) is ONE component on the sheet, matched by its assembly occurrence. The
15//!   wiring diagram keeps its own copy of it, its TWIN, which is where its harness
16//!   wires land when the diagram is stored.
17//! - The two documents were drawn on separate canvases, so the diagram's content is
18//!   moved onto the sheet by an offset: the diagram's [`Document::board_zone`] once it
19//!   has been written from a sheet, else one the host keeps for the session, else one
20//!   that puts the diagram's parts to the left of the board's.
21//!
22//! - A board of its own that the assembly places (a sub-board) is a ZONE of the sheet
23//!   ([`SheetZone`]): its schematic, drawn read-only where the diagram says
24//!   ([`Document::zones`]), else beside everything else. Its parts and nets belong to
25//!   its own document and are never written to this one's; a harness wire may end on
26//!   a pin inside it only where the board declares a point for that pin.
27//!
28//! The sheet's own rules ([`Document::validate`]): a net joins only parts on the board
29//! (owner 2026-11-22: "nets should only work inside of a board zone"); a harness wire
30//! joins two pins, and a pin takes one harness wire, though it may carry a net as well.
31use crate::{Component, Document, DocumentKind, Point, Terminal, Uuid, Wire};
32use serde::{Deserialize, Serialize};
33use std::collections::{BTreeMap, BTreeSet};
34
35/// A board of its own on a sheet: one placement of a sub-board.
36///
37/// A wiring diagram stores `occurrence` and `at` alone (where the zone is drawn, in
38/// the diagram's coordinates). On a sheet `at` is in the sheet's coordinates and the
39/// rest says what the zone holds.
40#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
41pub struct SheetZone {
42    /// The sub-board's assembly occurrence (`ACOMP9`).
43    pub occurrence: String,
44    /// Where the board's schematic origin is drawn.
45    pub at: Point,
46    /// On a sheet: the board's label (`A1`).
47    #[serde(skip)]
48    pub reference: String,
49    /// On a sheet: the parts drawn from the board's schematic.
50    #[serde(skip)]
51    pub members: Vec<Uuid>,
52    /// On a sheet: the board's nets, drawn from its schematic.
53    #[serde(skip)]
54    pub nets: Vec<Uuid>,
55    /// On a sheet: the pins of `members` the board declares a point for, the only
56    /// pins inside it a harness wire may end on.
57    #[serde(skip)]
58    pub declared: Vec<Terminal>,
59    /// On a sheet: the board's net labels, drawn from its schematic.
60    #[serde(skip)]
61    pub labels: Vec<Uuid>,
62    /// On a sheet: the board's junctions, where the sheet draws them.
63    #[serde(skip)]
64    pub junctions: Vec<Point>,
65}
66
67/// A sub-board as a host hands it to [`Document::merge_sheet_with`].
68#[derive(Clone, Debug, PartialEq)]
69pub struct SubBoard {
70    /// Its occurrence in this assembly (`ACOMP9`).
71    pub occurrence: String,
72    /// Its label (`A1`).
73    pub reference: String,
74    /// Its own schematic, its `pcb` block.
75    pub schematic: Document,
76    /// The pins of `schematic`'s parts the board declares a point for.
77    pub declared: Vec<Terminal>,
78}
79
80/// A sub-board's part or net id on a sheet: its own id, made distinct per placement
81/// so two placements of one board do not share ids.
82fn zone_id(occurrence: &str, id: Uuid) -> Uuid {
83    let mut h: u128 = 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d;
84    for b in occurrence.bytes() {
85        h ^= b as u128;
86        h = h.wrapping_mul(0x0000_0000_0100_0000_0000_0000_0000_013b);
87    }
88    Uuid::from_u128(id.as_u128() ^ h)
89}
90
91/// Format version of a sheet. It is never stored by a host, which stores the two
92/// documents it splits into; newer than both so an older build refuses one.
93pub const SHEET_DOCUMENT_VERSION: u32 = 6;
94
95/// The gap left between the diagram's parts and the board's when a merge places
96/// them side by side: 25.4 mm.
97const SIDE_BY_SIDE_GAP: i32 = 25_400;
98
99/// What [`Document::merge_sheet`] read, kept by the host for the split.
100#[derive(Clone, Debug, Default, PartialEq)]
101pub struct SheetSource {
102    /// The schematic as merged; `None` when the assembly has no board of its own.
103    pub pcb: Option<Document>,
104    /// The wiring diagram as merged; `None` when it has none.
105    pub diagram: Option<Document>,
106    /// Where the board's schematic origin sits in the diagram's coordinates: a diagram
107    /// point `p` is drawn at `p - offset` on the sheet.
108    pub offset: Point,
109    /// A part on both documents: the sheet component's id (the schematic's), and the
110    /// diagram's own copy of it as merged.
111    pub twins: BTreeMap<Uuid, Component>,
112    /// A harness wire whose end the merge moved onto a part's place on the board
113    /// (its twin sat elsewhere): the diagram's wire, and the sheet's as merged. An
114    /// unedited one splits back to the diagram's.
115    pub moved_wires: BTreeMap<Uuid, (Wire, Wire)>,
116    /// The sub-board zones as merged, in the sheet's coordinates.
117    pub zones: Vec<SheetZone>,
118}
119
120/// Move a wire's ends onto the pins it names in `doc`, where they are elsewhere.
121fn reattach(doc: &Document, w: &mut Wire) {
122    let a = w.start.as_ref().and_then(|t| doc.terminal_position(t)).unwrap_or(w.a);
123    let b = w.end.as_ref().and_then(|t| doc.terminal_position(t)).unwrap_or(w.b);
124    if (a, b) != (w.a, w.b) {
125        w.follow(a, b);
126    }
127}
128
129/// A sheet written back as its two documents.
130#[derive(Clone, Debug, Default, PartialEq)]
131pub struct SplitSheet {
132    pub pcb: Option<Document>,
133    pub diagram: Option<Document>,
134    /// The sheet's id of every part the diagram holds → the diagram's id for it.
135    pub diagram_ids: BTreeMap<Uuid, Uuid>,
136}
137
138impl SheetSource {
139    /// What a merge of `split` would have read, for the sheet `sheet` it was split
140    /// from: the source the NEXT split of the same sheet is taken against, once the
141    /// host has stored `split`. The sheet keeps its own ids, so its editor keeps its
142    /// selection; re-merging would rename a part that moved off the board.
143    pub fn after(sheet: &Document, split: &SplitSheet, offset: Point) -> SheetSource {
144        let mut twins = BTreeMap::new();
145        let mut moved_wires = BTreeMap::new();
146        if let Some(d) = &split.diagram {
147            for (sheet_id, diagram_id) in &split.diagram_ids {
148                let on_board = sheet.components.iter().any(|c| c.id == *sheet_id && (!c.off_board || sheet.zone_member(c.id).is_some()));
149                if (on_board || sheet_id != diagram_id)
150                    && let Some(copy) = d.components.iter().find(|c| c.id == *diagram_id)
151                {
152                    twins.insert(*sheet_id, copy.clone());
153                }
154            }
155            let back: BTreeMap<Uuid, Uuid> = split.diagram_ids.iter().map(|(s, d)| (*d, *s)).collect();
156            for dw in &d.wires {
157                let Some(w) = sheet.wires.iter().find(|w| w.id == dw.id) else { continue };
158                let mut merged = dw.clone();
159                shift_wire(&mut merged, neg(offset));
160                for t in [&mut merged.start, &mut merged.end].into_iter().flatten() {
161                    if let Some(id) = back.get(&t.component) {
162                        t.component = *id;
163                    }
164                }
165                merged.harness = true;
166                if merged != *w {
167                    moved_wires.insert(w.id, (dw.clone(), w.clone()));
168                }
169            }
170        }
171        SheetSource {
172            pcb: split.pcb.clone(),
173            diagram: split.diagram.clone(),
174            offset,
175            twins,
176            moved_wires,
177            zones: sheet.zones.clone(),
178        }
179    }
180}
181
182fn shift_component(c: &mut Component, by: Point) {
183    c.at = c.at.offset(by);
184    for g in &mut c.gates {
185        g.at = g.at.offset(by);
186    }
187}
188
189fn shift_wire(w: &mut Wire, by: Point) {
190    w.a = w.a.offset(by);
191    w.b = w.b.offset(by);
192    for p in &mut w.bends {
193        *p = p.offset(by);
194    }
195}
196
197fn neg(p: Point) -> Point {
198    Point::new(-p.x, -p.y)
199}
200
201fn extent_of(components: &[Component]) -> Option<(Point, Point)> {
202    let boxes: Vec<(Point, Point)> =
203        components.iter().flat_map(Component::sheet_boxes).map(|(_, a, b)| (a, b)).collect();
204    let lo = Point::new(boxes.iter().map(|b| b.0.x).min()?, boxes.iter().map(|b| b.0.y).min()?);
205    let hi = Point::new(boxes.iter().map(|b| b.1.x).max()?, boxes.iter().map(|b| b.1.y).max()?);
206    Some((lo, hi))
207}
208
209/// Whether two components are one assembly part drawn on both documents: the same
210/// occurrence, or, for a legacy component with none, the same part and label.
211fn same_part(a: &Component, b: &Component) -> bool {
212    match (&a.part, &b.part) {
213        (Some(a_part), Some(b_part)) => match (&a_part.instance, &b_part.instance) {
214            (Some(x), Some(y)) => x == y,
215            (None, None) => a_part.key == b_part.key && a.reference == b.reference,
216            _ => false,
217        },
218        _ => false,
219    }
220}
221
222impl Document {
223    /// Whether `wire` is a harness wire, by this document's kind.
224    pub fn is_harness(&self, wire: &Wire) -> bool {
225        Self::harness_in(self.kind, wire)
226    }
227    pub(crate) fn harness_in(kind: DocumentKind, wire: &Wire) -> bool {
228        match kind {
229            DocumentKind::Schematic => false,
230            DocumentKind::Wiring => true,
231            DocumentKind::Sheet => wire.harness,
232        }
233    }
234    /// Whether `component` is on the board, by this document's kind.
235    pub fn on_board(&self, component: &Component) -> bool {
236        match self.kind {
237            DocumentKind::Schematic => true,
238            DocumentKind::Wiring => false,
239            DocumentKind::Sheet => !component.off_board,
240        }
241    }
242    /// Whether a net may reach `terminal`: on a sheet, only a pin of a part on the
243    /// board. The refusal names the part.
244    pub fn net_reaches(&self, terminal: &Terminal) -> Result<(), String> {
245        if self.kind != DocumentKind::Sheet {
246            return Ok(());
247        }
248        if let Some(z) = self.zone_member(terminal.component) {
249            return Err(format!(
250                "{} is inside the board {}, a document of its own, and its nets are drawn there. Connect to it with a \
251                 harness wire on a point the board declares (Harness diagram).",
252                self.terminal_name(terminal),
253                z.reference
254            ));
255        }
256        match self.components.iter().find(|c| c.id == terminal.component) {
257            Some(c) if c.off_board => Err(format!(
258                "{} is off the board, and a net works only inside a board zone. Connect it with a harness wire \
259                 (Harness diagram), or drag it onto the board.",
260                c.reference
261            )),
262            _ => Ok(()),
263        }
264    }
265    /// Whether a harness wire may end on `terminal`: anywhere but a pin inside a
266    /// sub-board the board declares no point for. The refusal names the pin and says
267    /// what to do.
268    pub fn harness_reaches(&self, terminal: &Terminal) -> Result<(), String> {
269        match self.zone_member(terminal.component) {
270            Some(z) if !z.declared.contains(terminal) => Err(format!(
271                "{} is inside the board {}, which declares no point for it, and a harness wire ends inside a board \
272                 only on a point it declares. Declare it on the board: a port point that maps to it (Qualify).",
273                self.terminal_name(terminal),
274                z.reference
275            )),
276            _ => Ok(()),
277        }
278    }
279    /// The sub-board zone a part of the sheet is drawn from.
280    pub fn zone_member(&self, id: Uuid) -> Option<&SheetZone> {
281        self.zones.iter().find(|z| z.members.contains(&id))
282    }
283    /// The sub-board zone a net of the sheet is drawn from.
284    pub fn zone_of_net(&self, id: Uuid) -> Option<&SheetZone> {
285        self.zones.iter().find(|z| z.nets.contains(&id))
286    }
287    /// This sheet with its sub-board zones left out: its own board's parts, nets and
288    /// markers, and the parts off any board. What its nets and its check read.
289    pub fn without_zones(&self) -> Document {
290        let mut own = self.clone();
291        for z in &self.zones {
292            own.components.retain(|c| !z.members.contains(&c.id));
293            own.wires.retain(|w| !z.nets.contains(&w.id));
294            own.labels.retain(|l| !z.labels.contains(&l.id));
295            for j in &z.junctions {
296                own.junctions.remove(j);
297            }
298        }
299        own.zones.clear();
300        let gone: BTreeSet<Uuid> = self.zones.iter().flat_map(|z| z.members.iter().copied()).collect();
301        for w in &mut own.wires {
302            for t in [&mut w.start, &mut w.end] {
303                if t.as_ref().is_some_and(|t| gone.contains(&t.component)) {
304                    *t = None;
305                }
306            }
307        }
308        own
309    }
310    /// The box round a sub-board zone's parts: `None` for one with none.
311    pub fn sub_zone_extent(&self, occurrence: &str) -> Option<(Point, Point)> {
312        let z = self.zones.iter().find(|z| z.occurrence == occurrence)?;
313        let members: Vec<Component> =
314            self.components.iter().filter(|c| z.members.contains(&c.id)).cloned().collect();
315        extent_of(&members)
316    }
317    /// Move a sub-board zone, its parts and nets with it, and the harness wire ends
318    /// on them.
319    pub fn move_zone(&mut self, occurrence: &str, by: Point) -> Result<(), String> {
320        let z = self
321            .zones
322            .iter_mut()
323            .find(|z| z.occurrence == occurrence)
324            .ok_or_else(|| format!("No sub-board zone {occurrence}"))?;
325        z.at = z.at.offset(by);
326        let (members, nets, labels) = (z.members.clone(), z.nets.clone(), z.labels.clone());
327        let junctions: Vec<Point> = z.junctions.iter().map(|j| j.offset(by)).collect();
328        for j in &z.junctions {
329            self.junctions.remove(j);
330        }
331        z.junctions = junctions;
332        self.junctions.extend(z.junctions.iter().copied());
333        for l in self.labels.iter_mut().filter(|l| labels.contains(&l.id)) {
334            l.at = l.at.offset(by);
335        }
336        for c in self.components.iter_mut().filter(|c| members.contains(&c.id)) {
337            shift_component(c, by);
338        }
339        for w in self.wires.iter_mut().filter(|w| nets.contains(&w.id)) {
340            shift_wire(w, by);
341        }
342        let touching: Vec<usize> = (0..self.wires.len())
343            .filter(|i| {
344                let w = &self.wires[*i];
345                w.harness && [&w.start, &w.end].into_iter().flatten().any(|t| members.contains(&t.component))
346            })
347            .collect();
348        for i in touching {
349            let mut w = self.wires[i].clone();
350            reattach(self, &mut w);
351            self.wires[i] = w;
352        }
353        Ok(())
354    }
355    /// Why the edit from `before` to `self` is refused: it changed a sub-board's parts
356    /// or nets other than by moving the whole zone. They are the board's own document,
357    /// read-only on this sheet until the zone is entered (step 3).
358    pub fn zone_edit_refusal(&self, before: &Document) -> Option<String> {
359        if self.kind != DocumentKind::Sheet {
360            return None;
361        }
362        for was in &before.zones {
363            let refusal = || {
364                Some(format!(
365                    "{}'s parts and nets are read-only here: they are the board's own document. Move the whole zone, \
366                     or edit the board in its own document.",
367                    was.reference
368                ))
369            };
370            let Some(now) = self.zones.iter().find(|z| z.occurrence == was.occurrence) else { return refusal() };
371            if (&now.members, &now.nets, &now.declared, &now.labels) != (&was.members, &was.nets, &was.declared, &was.labels) {
372                return refusal();
373            }
374            let by = Point::new(now.at.x - was.at.x, now.at.y - was.at.y);
375            let moved: Vec<Point> = was.junctions.iter().map(|j| j.offset(by)).collect();
376            if now.junctions != moved || now.junctions.iter().any(|j| !self.junctions.contains(j)) {
377                return refusal();
378            }
379            for id in &was.labels {
380                let (Some(a), Some(b)) =
381                    (before.labels.iter().find(|l| l.id == *id), self.labels.iter().find(|l| l.id == *id))
382                else {
383                    return refusal();
384                };
385                let mut a = a.clone();
386                a.at = a.at.offset(by);
387                if a != *b {
388                    return refusal();
389                }
390            }
391            for id in &was.members {
392                let (Some(a), Some(b)) = (
393                    before.components.iter().find(|c| c.id == *id),
394                    self.components.iter().find(|c| c.id == *id),
395                ) else {
396                    return refusal();
397                };
398                let mut a = a.clone();
399                shift_component(&mut a, by);
400                if a != *b {
401                    return refusal();
402                }
403            }
404            for id in &was.nets {
405                let (Some(a), Some(b)) =
406                    (before.wires.iter().find(|w| w.id == *id), self.wires.iter().find(|w| w.id == *id))
407                else {
408                    return refusal();
409                };
410                let mut a = a.clone();
411                shift_wire(&mut a, by);
412                if a != *b {
413                    return refusal();
414                }
415            }
416        }
417        None
418    }
419    /// The parts on the board, as the zone drawn round them spans the sheet: `None`
420    /// when none is.
421    pub fn board_zone_extent(&self) -> Option<(Point, Point)> {
422        if self.kind != DocumentKind::Sheet {
423            return None;
424        }
425        let on: Vec<Component> = self.components.iter().filter(|c| !c.off_board).cloned().collect();
426        extent_of(&on)
427    }
428    /// Put a part of a sheet on the board (`off_board == false`) or take it off.
429    ///
430    /// Taking it off lets go of everything of the board's that holds its pins (net
431    /// wire ends, net flags, no-connect and power-flag markers); its harness wires
432    /// stay. A part placed from an assembly part that has no pads is refused entry,
433    /// with the reason, because the board could not seat it.
434    pub fn set_off_board(&mut self, id: Uuid, off_board: bool) -> Result<(), String> {
435        if self.kind != DocumentKind::Sheet {
436            return Err("Only a sheet has parts off the board".into());
437        }
438        let c = self.components.iter().find(|c| c.id == id).ok_or("Component no longer exists")?;
439        if let Some(z) = self.zone_member(id) {
440            return Err(format!(
441                "{} is a part of the board {}, a document of its own. To move it, delete it here and add it inside \
442                 the board: enter the board's zone, then Add component.",
443                c.reference, z.reference
444            ));
445        }
446        if c.off_board == off_board {
447            return Ok(());
448        }
449        if !off_board && c.part.is_some() && c.pads.is_none() {
450            return Err(format!(
451                "{} has no pads, so the board cannot seat it. Give its part pads in the Pads workbench first.",
452                c.reference
453            ));
454        }
455        if off_board {
456            let mine = |t: &Option<Terminal>| t.as_ref().is_some_and(|t| t.component == id);
457            for w in self.wires.iter_mut().filter(|w| !w.harness) {
458                if mine(&w.start) {
459                    w.start = None;
460                }
461                if mine(&w.end) {
462                    w.end = None;
463                }
464            }
465            for l in &mut self.labels {
466                if l.terminal.as_ref().is_some_and(|t| t.component == id) {
467                    l.terminal = None;
468                    l.flag = true;
469                }
470            }
471            self.no_connects.retain(|t| t.component != id);
472            self.power_flags.retain(|t| t.component != id);
473            self.board.placements.retain(|p| p.component != id);
474        }
475        self.components.iter_mut().find(|c| c.id == id).unwrap().off_board = off_board;
476        Ok(())
477    }
478    /// A sheet's rules, past the ones every document keeps.
479    pub(crate) fn validate_sheet(&self) -> Result<(), String> {
480        let off: BTreeSet<Uuid> = self.components.iter().filter(|c| c.off_board).map(|c| c.id).collect();
481        let reference = |t: &Terminal| self.terminal_name(t);
482        let mut seen = BTreeSet::new();
483        for z in &self.zones {
484            if !seen.insert(&z.occurrence) {
485                return Err(format!("The board {} has two zones", z.reference));
486            }
487            if z.members.iter().any(|id| !off.contains(id)) || z.nets.iter().any(|id| !self.wires.iter().any(|w| w.id == *id && !w.harness)) {
488                return Err(format!("The zone of the board {} names a part or net the sheet does not hold as its own", z.reference));
489            }
490        }
491        let mut ids = BTreeSet::new();
492        let mut pins = BTreeSet::new();
493        for w in &self.wires {
494            if let Some(z) = self.zone_of_net(w.id) {
495                if [&w.start, &w.end].into_iter().flatten().any(|t| !z.members.contains(&t.component)) {
496                    return Err(format!("A net of the board {} leaves its zone", z.reference));
497                }
498                continue;
499            }
500            if w.harness {
501                if w.connection_id.trim().is_empty() || !ids.insert(&w.connection_id) {
502                    return Err("Connection IDs must be nonempty and unique".into());
503                }
504                let (Some(start), Some(end)) = (&w.start, &w.end) else {
505                    return Err(format!("Connection {} must join two pins", w.connection_id));
506                };
507                for t in [start, end] {
508                    if !pins.insert((t.component, &t.pin)) {
509                        return Err(format!(
510                            "{} has more than one harness wire; a pin takes one",
511                            reference(t)
512                        ));
513                    }
514                }
515            } else {
516                for t in [&w.start, &w.end].into_iter().flatten() {
517                    if self.zone_member(t.component).is_some() {
518                        self.net_reaches(t)?;
519                    }
520                    if off.contains(&t.component) {
521                        return Err(format!(
522                            "A net reaches {}, which is off the board; a net works only inside a board zone",
523                            reference(t)
524                        ));
525                    }
526                }
527            }
528        }
529        let zone_labels: BTreeSet<Uuid> = self.zones.iter().flat_map(|z| z.labels.iter().copied()).collect();
530        let marks = self
531            .labels
532            .iter()
533            .filter(|l| !zone_labels.contains(&l.id))
534            .filter_map(|l| l.terminal.as_ref())
535            .chain(&self.no_connects)
536            .chain(&self.power_flags);
537        for t in marks {
538            if off.contains(&t.component) {
539                return Err(format!("{} is off the board and takes no net marker", reference(t)));
540            }
541        }
542        if self.board.placements.iter().any(|p| off.contains(&p.component)) {
543            return Err("A part off the board has a board placement".into());
544        }
545        Ok(())
546    }
547
548    /// Read a board's schematic and a wiring diagram into one sheet. `offset` is where
549    /// the host last drew the diagram this session (the schematic origin, in diagram
550    /// coordinates); the diagram's own [`Document::board_zone`] wins over it, and
551    /// with neither the diagram is put to the left of the board.
552    pub fn merge_sheet(
553        pcb: Option<Document>,
554        diagram: Option<Document>,
555        offset: Option<Point>,
556    ) -> Result<(Document, SheetSource), String> {
557        Self::merge_sheet_with(pcb, diagram, offset, vec![])
558    }
559    /// [`Document::merge_sheet`] for an assembly that places boards of its own: each
560    /// is a zone of the sheet, drawn from its schematic where the diagram's
561    /// [`Document::zones`] say, else beside everything else.
562    pub fn merge_sheet_with(
563        pcb: Option<Document>,
564        diagram: Option<Document>,
565        offset: Option<Point>,
566        boards: Vec<SubBoard>,
567    ) -> Result<(Document, SheetSource), String> {
568        if let Some(p) = &pcb
569            && p.kind != DocumentKind::Schematic
570        {
571            return Err(format!("the PCB sheet holds a {:?} document, not a schematic", p.kind));
572        }
573        if let Some(d) = &diagram
574            && d.kind != DocumentKind::Wiring
575        {
576            return Err(format!("the harness diagram holds a {:?} document, not a wiring diagram", d.kind));
577        }
578        let offset = diagram.as_ref().and_then(|d| d.board_zone).or(offset).unwrap_or_else(|| {
579            match (
580                pcb.as_ref().and_then(|p| extent_of(&p.components)),
581                diagram.as_ref().and_then(|d| extent_of(&d.components)),
582            ) {
583                (Some((board_lo, _)), Some((diagram_lo, diagram_hi))) => Point::new(
584                    diagram_hi.x + SIDE_BY_SIDE_GAP - board_lo.x,
585                    diagram_lo.y - board_lo.y,
586                ),
587                _ => Point::default(),
588            }
589        });
590        let mut sheet = Document::new(DocumentKind::Sheet);
591        if let Some(p) = pcb.as_ref() {
592            sheet.title = p.title.clone();
593            sheet.components = p.components.clone();
594            sheet.wires = p.wires.clone();
595            sheet.junctions = p.junctions.clone();
596            sheet.labels = p.labels.clone();
597            sheet.board = p.board.clone();
598            sheet.no_connects = p.no_connects.clone();
599            sheet.power_flags = p.power_flags.clone();
600        } else if let Some(d) = diagram.as_ref() {
601            sheet.title = d.title.clone();
602        }
603        // The sub-board zones, where the diagram drew them, else beside everything else.
604        let mut drawn: Vec<Component> = sheet.components.clone();
605        if let Some(d) = diagram.as_ref() {
606            drawn.extend(d.components.iter().map(|c| {
607                let mut c = c.clone();
608                shift_component(&mut c, neg(offset));
609                c
610            }));
611        }
612        for b in &boards {
613            if b.schematic.kind != DocumentKind::Schematic {
614                return Err(format!("the board {} holds a {:?} document, not a schematic", b.reference, b.schematic.kind));
615            }
616            let occ = &b.occurrence;
617            let stored = diagram
618                .as_ref()
619                .and_then(|d| d.zones.iter().find(|z| z.occurrence == *occ))
620                .map(|z| z.at.offset(neg(offset)));
621            let at = stored.unwrap_or_else(|| match (extent_of(&drawn), extent_of(&b.schematic.components)) {
622                (Some((lo, hi)), Some((inner_lo, _))) => {
623                    Point::new(hi.x + SIDE_BY_SIDE_GAP - inner_lo.x, lo.y - inner_lo.y)
624                }
625                _ => Point::default(),
626            });
627            let mut zone = SheetZone { occurrence: occ.clone(), at, reference: b.reference.clone(), ..SheetZone::default() };
628            for c in &b.schematic.components {
629                let mut c = c.clone();
630                c.id = zone_id(occ, c.id);
631                c.reference = format!("{}/{}", b.reference, c.reference);
632                if let Some(part) = &mut c.part
633                    && let Some(inner) = &part.instance
634                {
635                    part.instance = Some(format!("{occ}:{inner}"));
636                }
637                c.off_board = true;
638                shift_component(&mut c, at);
639                zone.members.push(c.id);
640                drawn.push(c.clone());
641                sheet.components.push(c);
642            }
643            for w in &b.schematic.wires {
644                let mut w = w.clone();
645                w.id = zone_id(occ, w.id);
646                for t in [&mut w.start, &mut w.end].into_iter().flatten() {
647                    t.component = zone_id(occ, t.component);
648                }
649                shift_wire(&mut w, at);
650                w.harness = false;
651                zone.nets.push(w.id);
652                sheet.wires.push(w);
653            }
654            for l in &b.schematic.labels {
655                let mut l = l.clone();
656                l.id = zone_id(occ, l.id);
657                l.at = l.at.offset(at);
658                if let Some(t) = &mut l.terminal {
659                    t.component = zone_id(occ, t.component);
660                }
661                zone.labels.push(l.id);
662                sheet.labels.push(l);
663            }
664            for j in &b.schematic.junctions {
665                let j = j.offset(at);
666                if sheet.junctions.insert(j) {
667                    zone.junctions.push(j);
668                }
669            }
670            zone.declared = b
671                .declared
672                .iter()
673                .map(|t| Terminal { component: zone_id(occ, t.component), pin: t.pin.clone() })
674                .collect();
675            sheet.zones.push(zone);
676        }
677        let candidates: Vec<Component> = sheet.components.iter().filter(|c| !c.off_board || sheet.zone_member(c.id).is_some()).cloned().collect();
678        let mut twins = BTreeMap::new();
679        if let Some(d) = diagram.as_ref() {
680            // The diagram's id for a part → the sheet's.
681            let mut renamed: BTreeMap<Uuid, Uuid> = BTreeMap::new();
682            let mut taken: BTreeSet<Uuid> = BTreeSet::new();
683            for c in &d.components {
684                let twin = candidates.iter().find(|b| !taken.contains(&b.id) && (b.id == c.id || same_part(b, c)));
685                match twin {
686                    Some(b) => {
687                        taken.insert(b.id);
688                        renamed.insert(c.id, b.id);
689                        twins.insert(b.id, c.clone());
690                    }
691                    None => {
692                        let mut c = c.clone();
693                        shift_component(&mut c, neg(offset));
694                        c.off_board = true;
695                        sheet.components.push(c);
696                    }
697                }
698            }
699            for w in &d.wires {
700                let mut w = w.clone();
701                shift_wire(&mut w, neg(offset));
702                for t in [&mut w.start, &mut w.end].into_iter().flatten() {
703                    if let Some(id) = renamed.get(&t.component) {
704                        t.component = *id;
705                    }
706                }
707                w.harness = true;
708                sheet.wires.push(w);
709            }
710        }
711        let mut moved_wires = BTreeMap::new();
712        if let Some(d) = diagram.as_ref() {
713            let first = sheet.wires.len() - d.wires.len();
714            for (i, original) in d.wires.iter().enumerate() {
715                let mut w = sheet.wires[first + i].clone();
716                reattach(&sheet, &mut w);
717                if w != sheet.wires[first + i] {
718                    moved_wires.insert(w.id, (original.clone(), w.clone()));
719                    sheet.wires[first + i] = w;
720                }
721            }
722        }
723        sheet.validate()?;
724        let zones = sheet.zones.clone();
725        Ok((sheet, SheetSource { pcb, diagram, offset, twins, moved_wires, zones }))
726    }
727
728    /// Write a sheet back as a board's schematic and a wiring diagram, each one EQUAL
729    /// to the one [`SheetSource`] merged where nothing of it was edited.
730    ///
731    /// - The schematic holds the parts on the board, the nets and the layout; it is
732    ///   `None` when there was none and the sheet has nothing of the board's.
733    /// - The diagram holds the parts off the board, the harness wires, and a twin of
734    ///   each part on the board that a harness wire reaches (or that had one).
735    pub fn split_sheet(&self, source: &SheetSource) -> Result<SplitSheet, String> {
736        if self.kind != DocumentKind::Sheet {
737            return Err("only a sheet splits".into());
738        }
739        let by_id: BTreeMap<Uuid, &Component> = self.components.iter().map(|c| (c.id, c)).collect();
740        let order = |base: Option<&Document>, wanted: &dyn Fn(&Component) -> bool| -> Vec<Uuid> {
741            let mut ids: Vec<Uuid> = base
742                .into_iter()
743                .flat_map(|d| d.components.iter().map(|c| c.id))
744                .filter(|id| by_id.get(id).is_some_and(|c| wanted(c)))
745                .collect();
746            for c in &self.components {
747                if wanted(c) && !ids.contains(&c.id) {
748                    ids.push(c.id);
749                }
750            }
751            ids
752        };
753
754        // The schematic.
755        let on_ids = order(source.pcb.as_ref(), &|c: &Component| !c.off_board);
756        let nets: Vec<Wire> =
757            self.wires.iter().filter(|w| !w.harness && self.zone_of_net(w.id).is_none()).cloned().collect();
758        let zone_labels: BTreeSet<Uuid> = self.zones.iter().flat_map(|z| z.labels.iter().copied()).collect();
759        let zone_junctions: BTreeSet<Point> = self.zones.iter().flat_map(|z| z.junctions.iter().copied()).collect();
760        let labels: Vec<crate::Label> = self.labels.iter().filter(|l| !zone_labels.contains(&l.id)).cloned().collect();
761        let junctions: BTreeSet<Point> = self.junctions.difference(&zone_junctions).copied().collect();
762        let board_has_content = source.pcb.is_some()
763            || !on_ids.is_empty()
764            || !nets.is_empty()
765            || !labels.is_empty()
766            || !junctions.is_empty()
767            || self.board != crate::board::Board::default();
768        let pcb = board_has_content.then(|| {
769            let mut p = source.pcb.clone().unwrap_or_else(|| Document::new(DocumentKind::Schematic));
770            p.components = on_ids.iter().map(|id| by_id[id].clone()).collect();
771            p.wires = nets;
772            p.junctions = junctions;
773            p.labels = labels;
774            p.board = self.board.clone();
775            p.board.placements.retain(|pl| on_ids.contains(&pl.component));
776            p.no_connects = self.no_connects.clone();
777            p.power_flags = self.power_flags.clone();
778            p
779        });
780
781        // The diagram.
782        let harness: Vec<&Wire> = self.wires.iter().filter(|w| w.harness).collect();
783        let reached: BTreeSet<Uuid> = harness
784            .iter()
785            .flat_map(|w| [&w.start, &w.end])
786            .flatten()
787            .map(|t| t.component)
788            .collect();
789        // The sheet's id → the diagram's id, for every part the diagram holds.
790        let mut diagram_id: BTreeMap<Uuid, Uuid> = BTreeMap::new();
791        let mut components: Vec<Component> = Vec::new();
792        let offset = source.offset;
793        let pcb_base = |id: &Uuid| source.pcb.as_ref().and_then(|p| p.components.iter().find(|c| c.id == *id));
794        // A part on the board, as its twin writes it: the twin as merged while the
795        // part is the one merged; else the part, where the twin was or where it is.
796        let twin_of = |c: &Component, twin: Option<&Component>| -> Component {
797            match twin {
798                Some(t) if pcb_base(&c.id) == Some(c) => t.clone(),
799                Some(t) => {
800                    let mut out = c.clone();
801                    out.id = t.id;
802                    out.off_board = false;
803                    if c.symbol == t.symbol {
804                        out.at = t.at;
805                        out.rotation = t.rotation;
806                        out.gates = t.gates.clone();
807                    } else {
808                        shift_component(&mut out, offset);
809                    }
810                    out
811                }
812                None => {
813                    let mut out = c.clone();
814                    out.off_board = false;
815                    shift_component(&mut out, offset);
816                    out
817                }
818            }
819        };
820        let emit = |c: &Component, components: &mut Vec<Component>, diagram_id: &mut BTreeMap<Uuid, Uuid>| {
821            let twin = source.twins.get(&c.id);
822            // A sub-board's part, as the diagram keeps it to land harness wires on:
823            // the copy it had, else the part where the sheet draws it.
824            let member = self.zone_member(c.id).is_some();
825            let out = if member && let Some(t) = twin {
826                t.clone()
827            } else if c.off_board {
828                let mut out = c.clone();
829                out.off_board = false;
830                shift_component(&mut out, offset);
831                // A part the board had, and its twin's id still the diagram's.
832                if let Some(t) = twin {
833                    out.id = t.id;
834                }
835                out
836            } else {
837                twin_of(c, twin)
838            };
839            diagram_id.insert(c.id, out.id);
840            components.push(out);
841        };
842        let wants_diagram = |c: &Component| {
843            (c.off_board && self.zone_member(c.id).is_none())
844                || reached.contains(&c.id)
845                || source.twins.contains_key(&c.id)
846        };
847        // The diagram's own order first: a twin by the sheet id it merged into, any
848        // other part by its own id.
849        let twin_sheet_id: BTreeMap<Uuid, Uuid> = source.twins.iter().map(|(sheet, t)| (t.id, *sheet)).collect();
850        if let Some(d) = source.diagram.as_ref() {
851            for base in &d.components {
852                let sheet_id = twin_sheet_id.get(&base.id).copied().unwrap_or(base.id);
853                if let Some(c) = by_id.get(&sheet_id)
854                    && wants_diagram(c)
855                    && !diagram_id.contains_key(&sheet_id)
856                {
857                    emit(c, &mut components, &mut diagram_id);
858                }
859            }
860        }
861        for c in &self.components {
862            if wants_diagram(c) && !diagram_id.contains_key(&c.id) {
863                emit(c, &mut components, &mut diagram_id);
864            }
865        }
866        // Ends land where the diagram's copy of each part is.
867        let mut placed = Document::new(DocumentKind::Wiring);
868        placed.components = components.clone();
869        let wires: Vec<Wire> = harness
870            .iter()
871            .map(|w| {
872                // An unedited wire whose ends the merge moved goes back as the
873                // diagram had it, while the parts it joins are where they were.
874                if let Some((original, merged)) = source.moved_wires.get(&w.id)
875                    && merged == *w
876                {
877                    let mut kept = original.clone();
878                    reattach(&placed, &mut kept);
879                    if kept == *original {
880                        return kept;
881                    }
882                }
883                let mut w = (*w).clone();
884                w.harness = false;
885                shift_wire(&mut w, offset);
886                for t in [&mut w.start, &mut w.end].into_iter().flatten() {
887                    if let Some(id) = diagram_id.get(&t.component) {
888                        t.component = *id;
889                    }
890                }
891                reattach(&placed, &mut w);
892                w
893            })
894            .collect();
895        // Where each sub-board zone sits, written once anything of the diagram's or a
896        // zone moved, so an open writes nothing.
897        // A stored place for a board the assembly no longer places is dead: it is
898        // dropped with the first write of this sheet, a board edit included, so a
899        // saved file carries no dead placement. An open alone writes nothing.
900        let dead = source.diagram.as_ref().is_some_and(|d| {
901            d.zones.iter().any(|z| !self.zones.iter().any(|live| live.occurrence == z.occurrence))
902        });
903        let zones_moved = self.zones.len() != source.zones.len()
904            || self.zones.iter().zip(&source.zones).any(|(a, b)| (&a.occurrence, a.at) != (&b.occurrence, b.at))
905            || (dead && pcb != source.pcb);
906        let diagram = (source.diagram.is_some() || !components.is_empty() || !wires.is_empty() || zones_moved).then(|| {
907            let mut d = source.diagram.clone().unwrap_or_else(|| Document::new(DocumentKind::Wiring));
908            let unchanged = source.diagram.as_ref().is_some_and(|base| base.components == components && base.wires == wires);
909            d.components = components;
910            d.wires = wires;
911            if (!unchanged || zones_moved) && (offset != Point::default() || d.board_zone.is_some()) {
912                d.board_zone = Some(offset);
913            }
914            if !unchanged || zones_moved {
915                d.zones = self
916                    .zones
917                    .iter()
918                    .map(|z| SheetZone { occurrence: z.occurrence.clone(), at: z.at.offset(offset), ..SheetZone::default() })
919                    .collect();
920            }
921            d
922        });
923        Ok(SplitSheet { pcb, diagram, diagram_ids: diagram_id })
924    }
925}
926