Skip to main content

brep_app/document/
ecad.rs

1//! The eCAD workbenches' documents, kept inside the BREP document.
2//!
3//! Each eCAD editor edits a copy of one top-level block of its tab's document:
4//! Diagram and PCB edit the assembly's `diagram` and `pcb`, Symbol and Pads the
5//! part's `symbol` and `pads` (`brep_render::history`). The editor commits
6//! every edit at once and reports it through `take_change`; [`BlockSync::store`]
7//! writes it into the block as one undo checkpoint, a typing run coalesced.
8//! That write is also what lights the tab's unsaved dot and re-arms the
9//! autosave, since both key on the history revision it moves
10//! ([`super::Document::edit_key`]).
11//!
12//! When the block moves under the editor — BREP's undo or redo, an import that
13//! writes it, a document replaced by a load — [`BlockSync::pull`] hands back
14//! the host's copy for the editor's `set_document` (or `set_symbol`,
15//! `set_footprint`), which keeps the view and clears the editor's own history.
16//! So there is one undo stack, BREP's, and Ctrl+Z reverts an eCAD edit and a
17//! feature edit newest first.
18
19use brep_render::history::{History, DIAGRAM, PADS, PCB, SYMBOL};
20use serde_json::Value;
21
22/// Which block an editor reads and writes.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum Block {
25    /// The assembly's wiring diagram (an eCAD `Document` of kind `Wiring`).
26    Diagram,
27    /// The assembly's schematic and board (an eCAD `Document`).
28    Pcb,
29    /// The part's schematic symbol (an eCAD `Symbol`).
30    Symbol,
31    /// The part's footprint pads (an eCAD `Footprint`).
32    Pads,
33}
34
35impl Block {
36    /// The top-level key in the saved document.
37    pub fn key(self) -> &'static str {
38        match self {
39            Block::Diagram => DIAGRAM,
40            Block::Pcb => PCB,
41            Block::Symbol => SYMBOL,
42            Block::Pads => PADS,
43        }
44    }
45
46    /// The block as the document holds it; `None` when no editor wrote it.
47    pub fn read(self, history: &History) -> Option<&Value> {
48        match self {
49            Block::Diagram => history.diagram_block(),
50            Block::Pcb => history.pcb_block(),
51            Block::Symbol => history.symbol_block(),
52            Block::Pads => history.pads_block(),
53        }
54    }
55
56    /// Write the block as one user edit; `coalesce` is eCAD's
57    /// `Change::coalesce`, which the setter namespaces by block.
58    pub fn write(self, history: &mut History, value: Value, coalesce: Option<&str>) {
59        match self {
60            Block::Diagram => history.set_diagram_block(Some(value), coalesce),
61            Block::Pcb => history.set_pcb_block(Some(value), coalesce),
62            Block::Symbol => history.set_symbol_block(Some(value), coalesce),
63            Block::Pads => history.set_pads_block(Some(value), coalesce),
64        }
65    }
66}
67
68/// One editor's standing with its block: the value it holds and the history
69/// revision it was last in step at, so a frame in which nothing changed costs
70/// one integer comparison.
71/// What the sheet-and-board editor's sheet was merged from, kept between frames:
72/// the `pcb` and `diagram` blocks it splits back into, and where the diagram was
73/// drawn on the sheet this session (`brep_ecad_core::sheet`). The two blocks keep
74/// their own [`BlockSync`]s; this is what joins them.
75#[derive(Debug, Default)]
76pub struct SheetState {
77    pub source: Option<brep_ecad_core::sheet::SheetSource>,
78    /// Where the diagram's content was drawn, held for the session so an undo
79    /// that re-merges does not move it while the diagram has none stored.
80    pub offset: Option<brep_ecad_core::Point>,
81    /// The boards of their own the assembly places, as last merged, and the
82    /// revision they were read at: the sheet is merged again when they change.
83    pub boards: Vec<brep_ecad_core::sheet::SubBoard>,
84    pub boards_revision: Option<u64>,
85}
86
87#[derive(Debug)]
88pub struct BlockSync {
89    block: Block,
90    /// The revision the editor was last in step at; `None` before the first
91    /// [`Self::pull`], which therefore always loads.
92    revision: Option<u64>,
93    /// The block value the editor holds, as far as the host knows.
94    held: Option<Value>,
95    /// Why the editor could not read the block last pulled (a block from a
96    /// newer eCAD, say). While set, [`Self::store`] refuses, so the editor's
97    /// stand-in document can never be written over the block it failed to read.
98    unreadable: Option<String>,
99    /// The per-component problems this block last reported ([`Self::unreported`]).
100    reported: Vec<String>,
101    /// The last edit a read-only document refused ([`Self::refused_again`]).
102    refused: Option<Value>,
103    /// How many times a read-only document took an edit back ([`Self::reload`]).
104    reloads: u64,
105}
106
107impl BlockSync {
108    pub fn new(block: Block) -> Self {
109        Self { block, revision: None, held: None, unreadable: None, reported: Vec::new(), refused: None, reloads: 0 }
110    }
111
112    pub fn block(&self) -> Block {
113        self.block
114    }
115
116    /// Which of `lines` this block has not already reported, remembering the
117    /// set for next time.
118    ///
119    /// An UNLINKED component is a STANDING state, not an event: the fold
120    /// reports it on every sheet edit, and one toast per keystroke is noise.
121    /// A problem that goes and comes back is reported again, which is right —
122    /// it is news both times.
123    pub fn unreported(&mut self, lines: Vec<String>) -> Vec<String> {
124        let fresh = lines.iter().filter(|line| !self.reported.contains(line)).cloned().collect();
125        self.reported = lines;
126        fresh
127    }
128
129    /// Write an edit the editor reported: `value` is the editor's document
130    /// (`to_value`), `coalesce` its `Change::coalesce`. Refused while the
131    /// block is [`Self::unreadable`].
132    pub fn store(&mut self, history: &mut History, value: Value, coalesce: Option<&str>) -> Result<(), String> {
133        if let Some(reason) = &self.unreadable {
134            return Err(format!("the {} block was not written: {reason}", self.block.key()));
135        }
136        self.block.write(history, value.clone(), coalesce);
137        self.held = Some(value);
138        self.revision = Some(history.revision());
139        Ok(())
140    }
141
142    /// Whether [`Self::pull`] has run at all: `false` until the editor first
143    /// loads this block, which is the document's OPEN as far as the editor can
144    /// tell (a document is built with its syncs, and a load builds a document).
145    /// [`Self::store`] without an undo checkpoint: the second block of ONE sheet
146    /// edit, which belongs to the checkpoint the first block's store just took.
147    pub fn store_no_undo(&mut self, history: &mut History, value: Value) -> Result<(), String> {
148        if let Some(reason) = &self.unreadable {
149            return Err(format!("the {} block was not written: {reason}", self.block.key()));
150        }
151        history.set_document_block_no_undo(self.block.key(), Some(value.clone()));
152        self.held = Some(value);
153        self.revision = Some(history.revision());
154        Ok(())
155    }
156
157    /// Take the block as it now stands as the editor's, at the current revision:
158    /// after a write of the OTHER block of a sheet moved the revision past this
159    /// one's store.
160    pub fn hold(&mut self, history: &History) {
161        self.held = self.block.read(history).cloned();
162        self.revision = Some(history.revision());
163    }
164
165    pub fn pulled(&self) -> bool {
166        self.revision.is_some()
167    }
168
169    /// Write `value` as the block with NO undo step: `document` is the whole
170    /// saved document with `value` already in it, adopted as it stands. For
171    /// what the editor did to a block the frame it first loaded it — an older
172    /// file brought up to the current shape, which is part of opening it and
173    /// not an edit anyone made (see `viewport::ecad::store`). Refused while
174    /// the block is [`Self::unreadable`], as [`Self::store`] is.
175    pub fn adopt(&mut self, history: &mut History, document: &Value, value: Value) -> Result<(), String> {
176        if let Some(reason) = &self.unreadable {
177            return Err(format!("the {} block was not written: {reason}", self.block.key()));
178        }
179        history.adopt_document(&document.to_string())?;
180        self.held = Some(value);
181        self.revision = Some(history.revision());
182        Ok(())
183    }
184
185    /// The host's copy when the editor does not hold it: `Some(Some(block))`,
186    /// or `Some(None)` when the block is absent (never written, or undone past
187    /// its first edit), for the editor to load its empty document. `None` when
188    /// the editor is in step. The first call always loads.
189    ///
190    /// Every `Some` clears [`Self::unreadable`], so the caller owes this after
191    /// EACH `Some(Some(block))`: try to read it (`from_value`) and call
192    /// [`Self::refuse`] if that fails. Refusing once and not again on a later
193    /// `Some` lets the stand-in the editor shows be stored over the block.
194    pub fn pull(&mut self, history: &History) -> Option<Option<Value>> {
195        let revision = history.revision();
196        let first = self.revision.is_none();
197        if self.revision == Some(revision) {
198            return None;
199        }
200        self.revision = Some(revision);
201        let current = self.block.read(history);
202        if !first && current == self.held.as_ref() {
203            return None;
204        }
205        self.held = current.cloned();
206        self.unreadable = None;
207        Some(self.held.clone())
208    }
209
210    /// On a read-only document, the editor's first frame brought the block up
211    /// to the current shape: keep that on screen as held, unwritten. The saved
212    /// bytes do not move (`History::lock`), and the next pull does not undo
213    /// what the editor showed on opening.
214    pub fn hold_unwritten(&mut self, history: &History, value: Value) {
215        self.held = Some(value);
216        self.revision = Some(history.revision());
217    }
218
219    /// On a read-only document an edit is taken back: the next [`Self::pull`]
220    /// loads the stored block again whatever the editor holds.
221    pub fn reload(&mut self) {
222        self.revision = None;
223        self.reloads += 1;
224    }
225
226    /// How many edits a read-only document has taken back from this editor.
227    pub fn reloads(&self) -> u64 {
228        self.reloads
229    }
230
231    /// Whether `value` is the edit a read-only document refused last time, so
232    /// an editor that reports the same change every frame is told once.
233    pub fn refused_again(&mut self, value: &Value) -> bool {
234        let again = self.refused.as_ref() == Some(value);
235        self.refused = Some(value.clone());
236        again
237    }
238
239    /// The editor could not read the block [`Self::pull`] just handed it.
240    /// Forget a refusal: the sheet's two blocks are refused together, and read
241    /// together once both can be (`viewport::ecad::pull_sheet`), though only the
242    /// one that moved is handed out again by [`Self::pull`].
243    pub fn clear_refusal(&mut self) {
244        self.unreadable = None;
245    }
246
247    pub fn refuse(&mut self, reason: String) {
248        self.unreadable = Some(reason);
249    }
250
251    /// Why the block is not being edited, while the editor cannot read it.
252    pub fn unreadable(&self) -> Option<&str> {
253        self.unreadable.as_deref()
254    }
255}
256
257