Skip to main content

brep_render/
history.rs

1//! [`History`] — the engine-owned, editable model recipe: the ordered feature
2//! history plus the rollback index (the feature the model is currently built up
3//! to). This is the SINGLE SOURCE OF TRUTH for the model — the UI keeps NO copy;
4//! it mutates and reads the history only through [`crate::engine_state::EngineState`]
5//! methods. That keeps one engine-owned history (UI-agnostic) and converges with
6//! the in-flight "whole history in Rust" pipeline migration — later this sinks
7//! into `brep-kernel-rs` proper without touching the UI.
8//!
9//! Rolling to a step re-runs `features[0..=rollback]` through the SAME kernel
10//! pipeline: the full feature list stays in the request and `stopAtId` (the
11//! editor's "stop at the expanded feature") halts execution AFTER the rolled-to
12//! feature, so the kernel's incremental history cache is RETAINED across rolls
13//! (no thrash) and the viewport shows the model as of that step.
14
15use serde_json::Value;
16
17/// The cap on the undo (and redo) stack depth — old entries fall off the bottom.
18const MAX_UNDO: usize = 100;
19
20/// A restorable model state: the whole document PLUS the rolled-to step, captured
21/// together so an undo returns both the geometry and the view to the state they
22/// were in right before the mutation.
23#[derive(Debug, Clone)]
24struct Snapshot {
25    request: Value,
26    rollback: usize,
27    /// The parts-library block as it stood before the mutation. An `Rc`, so
28    /// capturing it costs a pointer bump however large the library is — undo
29    /// and redo still rewind it exactly as they did when it lived inside
30    /// `request` (a redo of a component insert must restore the entry its
31    /// ACOMP references).
32    parts_library: std::rc::Rc<Value>,
33    /// Names this undo step, so a caller can later ask whether the step it
34    /// took is still the newest one ([`History::undo_top`]). Drawn from one
35    /// process-wide counter; a redo entry keeps no serial of its own.
36    serial: u64,
37}
38
39/// Hands out every [`Snapshot::serial`] in this process.
40static NEXT_STEP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
41
42fn next_step() -> u64 {
43    NEXT_STEP.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
44}
45
46/// The engine-owned mutable history.
47#[derive(Debug, Clone)]
48pub struct History {
49    /// The whole `HistoryRequest` document
50    /// (`{expressions, configurator, features: [...]}`).
51    ///
52    /// PRIVATE and reached only through [`Self::document`] /
53    /// [`Self::document_mut`] — the `_mut` door bumps [`Self::revision`], which
54    /// is what lets a per-frame cache key off the document without having to
55    /// enumerate the mutation sites. Naming the field `document` (not
56    /// `request`) is what makes that total: the compiler, not a reviewer, finds
57    /// a site that bypasses the doors.
58    document: Value,
59    /// A ticket drawn from one process-wide counter on construction and again on
60    /// every `&mut` reach into [`Self::document`]. Deliberately coarse — it
61    /// counts mutation OPPORTUNITIES, so it moves when nothing actually changed
62    /// (a cache then rebuilds once, harmlessly) but it cannot fail to move when
63    /// something did.
64    ///
65    /// Drawn from a shared counter rather than incremented per instance, because
66    /// a `History` is not only mutated, it is REPLACED: `set_history_json`
67    /// installs a fresh one on the engine a document ALREADY owns — the
68    /// `?loadModel=` boot drain, a recovery restore, an STL import accept, New.
69    /// A per-instance counter restarts there, so a replacement would hand a
70    /// cache a revision it had already seen for the same document and the cache
71    /// would serve the PREVIOUS model's values. One counter makes the guarantee
72    /// the same for both: no two states of any `History` in this process ever
73    /// share a revision.
74    revision: u64,
75    /// Index into `features` the model is rolled to (clamped to the last).
76    rollback: usize,
77    /// Undo/redo over the MODEL document. A snapshot is pushed BEFORE each model
78    /// mutation (edit / add / delete / reorder); roll-to-step is view state and
79    /// is NOT snapshotted. Rapid same-target edits (a slider drag) coalesce into a
80    /// single undo entry via `last_edit_key`. The stacks live here in the engine
81    /// core — the model is engine-owned, so its undo history is too; the UI only
82    /// triggers `undo()` / `redo()`.
83    undo_stack: Vec<Snapshot>,
84    redo_stack: Vec<Snapshot>,
85    /// The coalescing token of the most recently recorded edit (see `checkpoint`).
86    last_edit_key: Option<String>,
87    /// The persistent GLOBAL feature counter: bumped by one on every new-feature
88    /// mint ([`Self::next_feature_id`]), so a new id is `{shortName}{counter}`.
89    /// MONOTONIC and NEVER reused — deleting a feature does not free its number,
90    /// and (deliberately) undo does NOT rewind it, so re-doing an add can't collide
91    /// with a number already handed out. It is kept OFF `self.document` in memory
92    /// (so the undo snapshots that clone `request` never rewind it) and folded into
93    /// the serialized document under `"featureCounter"` so it round-trips save/load
94    /// (see [`Self::request_json`] / [`Self::from_request_json`]).
95    feature_counter: u64,
96    /// The assemblies PARTS LIBRARY block (`partsLibrary`), kept OFF
97    /// `self.document` for the same reason as `feature_counter`: every per-edit
98    /// pass over the document — the undo checkpoint clone, the kernel request
99    /// built by [`Self::prefix_request`], the assembly pose fold's serialize →
100    /// parse round trip — would otherwise copy the whole library, which for an
101    /// imported STEP assembly is megabytes of embedded part payload PER EDIT
102    /// and froze the browser UI. Folded back in by [`Self::request_json`] so
103    /// the SAVED document is byte-identical to before, and lifted back out by
104    /// [`Self::from_request_json`] / the adopt doors.
105    ///
106    /// `Rc` because undo/redo MUST rewind it (a redo of a component insert has
107    /// to restore the entry its ACOMP references) while a checkpoint must stay
108    /// a pointer copy — the whole point of moving it off `request`.
109    parts_library: std::rc::Rc<Value>,
110    /// Why the latest edit of a part's pins or ports was not followed to the
111    /// other side, naming the label that blocks it (see the pins-and-ports
112    /// block below). `None` once an edit binds, and after undo, redo or a
113    /// replaced document, which restore both sides together.
114    pin_port_hold: Option<String>,
115    /// A symbol edit changed the part's declared connection points, which only
116    /// a history run publishes. The engine's `pump` re-runs and clears it, so
117    /// no host has to remember to.
118    ports_followed: bool,
119    /// A ticket (from the same counter as [`Self::revision`]) redrawn on every
120    /// USER edit: every undo checkpoint, coalesced or not, and every undo and
121    /// redo. Machine writes (a solver fold, a parts-library heal, a
122    /// `_no_undo` block) and rolling do not move it. See [`Self::edit_serial`].
123    edit_serial: u64,
124    /// Why this document may not change — a PLM revision that is released, or
125    /// that this user has not checked out (`BREP_app`'s `Document::access`).
126    /// `None`: editable, as every file-based document always is. See
127    /// [`Self::lock`].
128    lock: Option<String>,
129    /// Where a mutation lands while [`Self::lock`] holds: a copy of the
130    /// document taken by [`Self::document_mut`] and thrown away by the next.
131    scratch: Value,
132    /// How many mutations were refused since construction — the count a host
133    /// watches to tell the user "check out to edit" ([`Self::refused_edits`]).
134    refused: u64,
135    /// Of those, the ones that were a USER's edit ([`Self::refused_user_edits`]).
136    refused_user: u64,
137}
138
139/// Hands out every revision ticket in this process — see [`History::revision`].
140/// Relaxed is enough: the value is only ever compared for equality against one
141/// a single thread read earlier, never used to order anything.
142static NEXT_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
143
144fn next_revision() -> u64 {
145    NEXT_REVISION.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
146}
147
148impl Default for History {
149    fn default() -> Self {
150        Self {
151            document: empty_request(),
152            revision: next_revision(),
153            edit_serial: next_revision(),
154            rollback: 0,
155            undo_stack: Vec::new(),
156            redo_stack: Vec::new(),
157            last_edit_key: None,
158            feature_counter: 0,
159            parts_library: std::rc::Rc::new(Value::Null),
160            pin_port_hold: None,
161            ports_followed: false,
162            lock: None,
163            scratch: Value::Null,
164            refused: 0,
165            refused_user: 0,
166        }
167    }
168}
169
170fn empty_request() -> Value {
171    serde_json::json!({ "expressions": "", "configurator": {}, "features": [] })
172}
173
174/// The trailing run of ASCII digits of `id` read as a number (`"P.CU12"` → 12,
175/// `"Box"` → 0). Trailing digits are ASCII (one byte each), so the slice boundary
176/// is always a valid char boundary; a missing/overflowing run yields 0.
177fn trailing_number(id: &str) -> u64 {
178    let digit_bytes = id
179        .bytes()
180        .rev()
181        .take_while(u8::is_ascii_digit)
182        .count();
183    id[id.len() - digit_bytes..].parse().unwrap_or(0)
184}
185
186impl History {
187    /// Load a whole history document (a saved part file parses as one). Rolls to
188    /// the last feature. Ensures a `features` array exists.
189    pub fn from_request_json(json: &str) -> Result<Self, String> {
190        let mut request: Value =
191            serde_json::from_str(json).map_err(|e| format!("history parse: {e}"))?;
192        if !request.get("features").map(Value::is_array).unwrap_or(false) {
193            if let Some(obj) = request.as_object_mut() {
194                obj.insert("features".into(), Value::Array(Vec::new()));
195            } else {
196                request = empty_request();
197            }
198        }
199        // Lift the persistent feature counter OUT of the document so it lives ONLY
200        // in the struct field: kept off `self.document`, the undo snapshots (which
201        // clone `request`) can never rewind it, and it can't be double-folded on
202        // re-serialize. A document with no stored counter (fresh or saved before
203        // this field existed) safe-inits below.
204        let stored = request
205            .as_object_mut()
206            .and_then(|obj| obj.remove("featureCounter"))
207            .and_then(|value| value.as_u64());
208        // Lift the parts-library block out of the document for the same reason
209        // (see the `parts_library` field): every per-edit copy of `request`
210        // would otherwise carry megabytes of embedded part payload.
211        let parts_library = request
212            .as_object_mut()
213            .and_then(|obj| obj.remove("partsLibrary"))
214            .unwrap_or(Value::Null);
215        let mut history = Self {
216            document: request,
217            rollback: 0,
218            parts_library: std::rc::Rc::new(parts_library),
219            ..Self::default()
220        };
221        history.rollback = history.len().saturating_sub(1);
222        // Safe init when unstored: start ABOVE the largest numeric suffix already
223        // present among feature ids so the next mint (`{shortName}{counter+1}`)
224        // cannot collide with an existing id. This holds because no shortName ends
225        // in a digit (verified — even `IMPORT3D` ends in `D`), so an id's trailing
226        // digits ARE its numeric suffix and `counter+1` strictly exceeds them all.
227        history.feature_counter = stored.unwrap_or_else(|| history.max_id_suffix());
228        Ok(history)
229    }
230
231    /// The largest trailing-integer suffix among all existing feature ids (0 when
232    /// none carry one) — the floor for a safe counter init on a document with no
233    /// stored `featureCounter` (see [`Self::from_request_json`]).
234    fn max_id_suffix(&self) -> u64 {
235        self.features()
236            .iter()
237            .filter_map(|f| {
238                f.get("inputParams")
239                    .and_then(|p| p.get("id"))
240                    .and_then(Value::as_str)
241            })
242            .map(trailing_number)
243            .max()
244            .unwrap_or(0)
245    }
246
247    /// The whole document, read-only.
248    fn document(&self) -> &Value {
249        &self.document
250    }
251
252    /// The whole document for mutation. Bumps [`Self::revision`] — this is the
253    /// only way to reach `self.document` mutably.
254    ///
255    /// It is NOT the only door a cache keyed on the revision has to cover. The
256    /// `partsLibrary` block is held in [`Self::parts_library`], beside the
257    /// document rather than inside it, and [`Self::request_json`] folds it back
258    /// in — so it is part of the saved document and has its own two setters,
259    /// which bump the revision themselves. Anything else lifted out of
260    /// `self.document` into a field of its own owes the same.
261    ///
262    /// While the history is [locked](Self::lock), the reach lands on a SCRATCH
263    /// copy that the next reach replaces, and the refusal is counted: every
264    /// mutation that goes through this door — a user edit, and equally a
265    /// solver fold or a pin settle — leaves [`Self::request_json`] exactly as
266    /// it was. The revision does not move either, since nothing changed.
267    fn document_mut(&mut self) -> &mut Value {
268        if self.lock.is_some() {
269            self.refused += 1;
270            self.scratch = self.document.clone();
271            return &mut self.scratch;
272        }
273        self.revision = next_revision();
274        &mut self.document
275    }
276
277    /// Refuse every change to the saved document until [`Self::unlock`]:
278    /// [`Self::request_json`] stays byte for byte what it is now, whatever is
279    /// called. `reason` is the sentence a host shows ("released", "checked out
280    /// by grace", "not checked out"). Rolling ([`Self::set_rollback`]) is view
281    /// state and stays free, and so does reading.
282    ///
283    /// The three writes that do not pass [`Self::document_mut`] — the parts
284    /// library, the feature counter and the undo/redo stacks — check the lock
285    /// themselves; `a_locked_history_keeps_its_saved_bytes` calls every
286    /// mutator and pins the invariant.
287    pub fn lock(&mut self, reason: impl Into<String>) {
288        self.lock = Some(reason.into());
289        // A typing run from before the lock must not coalesce with the first
290        // edit after the next checkout into one undo entry.
291        self.break_coalescing();
292    }
293
294    /// Allow changes again (a checkout took the lock).
295    pub fn unlock(&mut self) {
296        self.lock = None;
297        self.scratch = Value::Null;
298    }
299
300    /// Why the document may not change, or `None` when it may.
301    pub fn locked(&self) -> Option<&str> {
302        self.lock.as_deref()
303    }
304
305    /// Mutations refused while locked, counted since this history was built.
306    /// A host compares it frame to frame to tell the user an edit was refused.
307    pub fn refused_edits(&self) -> u64 {
308        self.refused
309    }
310
311    /// Refused mutations that were a user's edit: every one that takes an undo
312    /// checkpoint, an undo, redo or retract, a feature id minted, a parts-library
313    /// edit. A kernel write-back (a solver fold, a pin settle, a parts-library
314    /// heal) is refused just the same but not counted here: it is nobody's edit,
315    /// so a host tells the user about THIS count, not [`Self::refused_edits`].
316    pub fn refused_user_edits(&self) -> u64 {
317        self.refused_user
318    }
319
320    /// Count a refused write that does not pass [`Self::document_mut`], and
321    /// say whether to refuse it.
322    fn refuse(&mut self) -> bool {
323        if self.lock.is_some() {
324            self.refused += 1;
325            return true;
326        }
327        false
328    }
329
330    /// [`Self::refuse`] for a write only a user makes.
331    fn refuse_user(&mut self) -> bool {
332        let refused = self.refuse();
333        if refused {
334            self.refused_user += 1;
335        }
336        refused
337    }
338
339    /// A monotonic counter of mutation opportunities on the document — the
340    /// cache key for anything derived from it that would otherwise be rebuilt
341    /// every frame (see the `__brepParams` blob in `BREP_app`).
342    pub fn revision(&self) -> u64 {
343        self.revision
344    }
345
346    /// Moves on every user edit of the model and on every undo and redo, and
347    /// on nothing else: not on a run's write-back, not on rolling. What a
348    /// transient view of the model (the family-row preview) keys on to know
349    /// that the user changed the model under it.
350    pub fn edit_serial(&self) -> u64 {
351        self.edit_serial
352    }
353
354    /// The features slice (empty if none).
355    pub fn features(&self) -> &[Value] {
356        self.document()
357            .get("features")
358            .and_then(Value::as_array)
359            .map(Vec::as_slice)
360            .unwrap_or(&[])
361    }
362
363    fn features_mut(&mut self) -> &mut Vec<Value> {
364        let obj = self
365            .document_mut()
366            .as_object_mut()
367            .expect("history request is a JSON object");
368        obj.entry("features")
369            .or_insert_with(|| Value::Array(Vec::new()));
370        obj.get_mut("features")
371            .and_then(Value::as_array_mut)
372            .expect("features is a JSON array")
373    }
374
375    pub fn len(&self) -> usize {
376        self.features().len()
377    }
378
379    pub fn is_empty(&self) -> bool {
380        self.len() == 0
381    }
382
383    /// The rolled-to index, clamped to a valid feature (0 when empty).
384    pub fn rollback(&self) -> usize {
385        self.rollback.min(self.len().saturating_sub(1))
386    }
387
388    pub fn set_rollback(&mut self, index: usize) {
389        self.rollback = if self.is_empty() {
390            0
391        } else {
392            index.min(self.len() - 1)
393        };
394        // Rolling to a step is a view move, not a model edit: it records NO undo
395        // snapshot, but it DOES break the edit-coalescing run so the next edit
396        // starts a fresh undo entry rather than merging with a pre-roll edit.
397        self.last_edit_key = None;
398    }
399
400    pub fn feature_type(&self, index: usize) -> Option<String> {
401        self.features()
402            .get(index)?
403            .get("type")
404            .and_then(Value::as_str)
405            .map(String::from)
406    }
407
408    pub fn feature_id(&self, index: usize) -> Option<String> {
409        self.features()
410            .get(index)?
411            .get("inputParams")
412            .and_then(|p| p.get("id"))
413            .and_then(Value::as_str)
414            .map(String::from)
415    }
416
417    pub fn index_of(&self, id: &str) -> Option<usize> {
418        self.features().iter().position(|f| {
419            f.get("inputParams")
420                .and_then(|p| p.get("id"))
421                .and_then(Value::as_str)
422                == Some(id)
423        })
424    }
425
426    /// The `inputParams` document of the feature at `index` (for the dialog).
427    pub fn feature_params(&self, index: usize) -> Option<Value> {
428        self.features().get(index)?.get("inputParams").cloned()
429    }
430
431    /// SOLVER write-back fold (the assembly pose-authority contract): set ONE
432    /// `inputParams` key of the feature whose `inputParams.id == id`, WITHOUT an
433    /// undo checkpoint and WITHOUT breaking edit coalescing — a solve write-back
434    /// is the kernel adopting its own result, not a user edit, so it must never
435    /// mint an undo entry (undoing a user action then re-running re-solves and
436    /// re-folds anyway). Returns whether a feature matched.
437    pub fn fold_param_no_undo(&mut self, id: &str, key: &str, value: Value) -> bool {
438        let Some(index) = self.index_of(id) else {
439            return false;
440        };
441        if let Some(feature) = self.features_mut().get_mut(index) {
442            if let Some(params) = feature
443                .get_mut("inputParams")
444                .and_then(Value::as_object_mut)
445            {
446                params.insert(key.to_string(), value);
447                return true;
448            }
449        }
450        false
451    }
452
453    pub fn set_feature_params(&mut self, index: usize, params: Value) {
454        if index >= self.len() {
455            return;
456        }
457        // Coalesce a slider drag (many consecutive edits of the SAME feature) into
458        // one undo entry, keyed by the feature index.
459        self.checkpoint(Some(&format!("param:{index}")));
460        if let Some(feat) = self.features_mut().get_mut(index) {
461            if let Some(obj) = feat.as_object_mut() {
462                obj.insert("inputParams".into(), params);
463            }
464        }
465    }
466
467    /// Replace the `inputParams` of MANY features as ONE mutation —
468    /// [`Self::set_feature_params`]'s batch sibling, and the reason it exists:
469    /// a packed BOM row rolls up N occurrences, so editing one cell writes N
470    /// features. A `set_feature_params` loop would mint N undo entries (each
471    /// keyed `param:{index}`, so none of them coalesce with each other), and
472    /// the user would have to press undo N times to take back ONE edit.
473    ///
474    /// Exactly ONE checkpoint covers the whole batch. The coalesce key names
475    /// the SET of indices, so a run of edits to the SAME set (typing into one
476    /// packed cell) still merges into a single entry, while switching to a
477    /// different set starts a new one — the `param:{index}` rule, lifted to a
478    /// group. Out-of-range indices are skipped; an empty batch is a no-op (no
479    /// checkpoint, so a fan-out that matched nothing leaves no empty entry).
480    pub fn set_many_feature_params(&mut self, edits: &[(usize, Value)]) {
481        let len = self.len();
482        let mut in_range: Vec<&(usize, Value)> =
483            edits.iter().filter(|(index, _)| *index < len).collect();
484        if in_range.is_empty() {
485            return;
486        }
487        // The key must not depend on the caller's ordering, or the same packed
488        // row could produce two different keys and stop coalescing.
489        in_range.sort_by_key(|(index, _)| *index);
490        let key: Vec<String> = in_range
491            .iter()
492            .map(|(index, _)| index.to_string())
493            .collect();
494        self.checkpoint(Some(&format!("params:{}", key.join(","))));
495        for (index, params) in in_range {
496            if let Some(feature) = self.features_mut().get_mut(*index) {
497                if let Some(object) = feature.as_object_mut() {
498                    object.insert("inputParams".into(), params.clone());
499                }
500            }
501        }
502    }
503
504    pub fn push_feature(&mut self, feature: Value) {
505        self.checkpoint(None);
506        self.features_mut().push(feature);
507    }
508
509    /// Append MANY features as ONE mutation — the batch an import lane needs
510    /// (`EngineState::add_features`). Distinct from a `push_feature` loop in the
511    /// two ways that matter: exactly ONE undo checkpoint (an N-instance assembly
512    /// import undoes in one step, not N), and the caller re-runs once instead of
513    /// once per feature. No-op for an empty batch (no checkpoint, so an import
514    /// that produced nothing leaves no empty undo entry).
515    pub fn push_features(&mut self, features: Vec<Value>) {
516        if features.is_empty() {
517            return;
518        }
519        self.checkpoint(None);
520        self.features_mut().extend(features);
521    }
522
523    pub fn remove_feature(&mut self, index: usize) {
524        if index >= self.len() {
525            return;
526        }
527        self.checkpoint(None);
528        self.features_mut().remove(index);
529    }
530
531    pub fn swap(&mut self, a: usize, b: usize) {
532        let len = self.len();
533        if a < len && b < len && a != b {
534            self.checkpoint(None);
535            self.features_mut().swap(a, b);
536        }
537    }
538
539    /// Mint the id for a NEW feature: `{base}{N}` where `base` is the feature's
540    /// shortName and `N` is this history's persistent GLOBAL counter, bumped by one
541    /// on every mint (`P.CU` → `P.CU7`, `S` → `S8`). GLOBAL across all feature
542    /// types, MONOTONIC, and NEVER reused — a delete does not free a number and
543    /// undo does not rewind the counter — and it persists across save/load, so two
544    /// features can never receive the same id over the document's whole lifetime.
545    pub fn next_feature_id(&mut self, base: &str) -> String {
546        // Locked, the counter is saved state and does not move; the id is
547        // still minted, for a feature whose push will be refused anyway.
548        if self.refuse_user() {
549            return format!("{base}{}", self.feature_counter + 1);
550        }
551        self.feature_counter += 1;
552        format!("{base}{}", self.feature_counter)
553    }
554
555    /// The `stopAtId`-truncated request that stops AFTER the rolled-to feature —
556    /// the roll-to-step request the pipeline runs. Empty history → empty request.
557    pub fn prefix_request(&self) -> Value {
558        let mut request = self.document().clone();
559        if let Some(id) = self.feature_id(self.rollback()) {
560            if let Some(obj) = request.as_object_mut() {
561                obj.insert("stopAtId".into(), Value::String(id));
562            }
563        }
564        request
565    }
566
567    /// The request that stops BEFORE feature `index` — the scene that feature
568    /// resolves its references against, wherever the model is rolled to. `None`
569    /// when there is no feature at `index`.
570    pub fn request_before(&self, index: usize) -> Option<Value> {
571        let id = self.feature_id(index)?;
572        let mut request = self.document().clone();
573        request.as_object_mut()?.insert("stopBeforeId".into(), Value::String(id));
574        Some(request)
575    }
576
577    /// The tree listing for the UI: `{ step, features: [{index, type, id}] }`.
578    pub fn listing_json(&self) -> String {
579        let features: Vec<Value> = self
580            .features()
581            .iter()
582            .enumerate()
583            .map(|(index, _)| {
584                serde_json::json!({
585                    "index": index,
586                    "type": self.feature_type(index).unwrap_or_else(|| "?".into()),
587                    "id": self.feature_id(index).unwrap_or_else(|| "(no id)".into()),
588                })
589            })
590            .collect();
591        serde_json::json!({ "step": self.rollback(), "features": features }).to_string()
592    }
593
594    /// The whole request document (for persistence / debugging), with the
595    /// persistent global feature counter folded back in under `"featureCounter"`
596    /// so it round-trips through save/load (the twin of [`Self::from_request_json`],
597    /// which lifts it back out). Written only when non-zero, so a document that has
598    /// never minted a feature persists byte-for-byte as before (mirrors the
599    /// metadata field's "un-annotated model persists unchanged" convention).
600    pub fn request_json(&self) -> String {
601        let has_library = self
602            .parts_library
603            .as_object()
604            .map(|map| !map.is_empty())
605            .unwrap_or(false);
606        if self.feature_counter == 0 && !has_library {
607            return self.document().to_string();
608        }
609        let mut document = self.document().clone();
610        if let Some(obj) = document.as_object_mut() {
611            if self.feature_counter != 0 {
612                obj.insert("featureCounter".into(), Value::from(self.feature_counter));
613            }
614            if has_library {
615                obj.insert("partsLibrary".into(), (*self.parts_library).clone());
616            }
617        }
618        document.to_string()
619    }
620
621    /// The document WITHOUT the parts-library block — for the kernel round
622    /// trips that never read it. The assembly pose fold
623    /// (`assembly_apply_document_json`) only rewrites the `assembly` block and
624    /// per-feature `inputParams`, so handing it the library would serialize,
625    /// parse and re-serialize megabytes of part payload on every edit for
626    /// nothing. [`Self::request_json`] is the SAVE door and still carries it.
627    pub fn request_json_without_parts_library(&self) -> String {
628        if self.feature_counter == 0 {
629            return self.document().to_string();
630        }
631        let mut document = self.document().clone();
632        if let Some(obj) = document.as_object_mut() {
633            obj.insert("featureCounter".into(), Value::from(self.feature_counter));
634        }
635        document.to_string()
636    }
637
638    // --- Undo / redo over the model document ------------------------------
639
640    fn snapshot(&self) -> Snapshot {
641        Snapshot {
642            request: self.document().clone(),
643            rollback: self.rollback,
644            parts_library: self.parts_library.clone(),
645            serial: next_step(),
646        }
647    }
648
649    fn restore(&mut self, snap: Snapshot) {
650        self.edit_serial = next_revision();
651        *self.document_mut() = snap.request;
652        self.parts_library = snap.parts_library;
653        // A snapshot holds both sides as they stood together, so whatever the
654        // last pin or port edit held is no longer on screen.
655        self.pin_port_hold = None;
656        let last = self.len().saturating_sub(1);
657        self.rollback = snap.rollback.min(last);
658    }
659
660    /// Record a pre-mutation snapshot for undo. `coalesce_key` groups a run of
661    /// rapid same-target edits (one slider drag) into a SINGLE undo entry: while
662    /// the same non-empty key repeats, no new snapshot is pushed. A `None` key
663    /// never coalesces, so every structural add/delete/reorder is its own entry.
664    /// Any new snapshot clears the redo stack (a fresh edit forks the timeline)
665    /// and the oldest entry falls off once the stack passes [`MAX_UNDO`].
666    ///
667    /// A run has no time limit: only another key, an undo or
668    /// [`Self::break_coalescing`] ends it. The PMI label drag and the sheet
669    /// view, dimension and ordinate moves call that on release; nothing else
670    /// does, and a typing run has no release. So a param slider or
671    /// field (`param:{index}`) or an eCAD field (`component:{id}:text`) edited,
672    /// left, and edited again later with nothing in between is ONE undo step
673    /// across the pause, even across a Save. An eCAD host should call it when
674    /// focus leaves the editor's fields. Param runs are left as they are, a
675    /// decision not yet taken.
676    fn checkpoint(&mut self, coalesce_key: Option<&str>) {
677        // Locked, the edit this checkpoint precedes is refused at
678        // `document_mut`: no undo entry for an edit that never happened.
679        if self.lock.is_some() {
680            self.refused_user += 1;
681            return;
682        }
683        // Before the coalesce return: the second keystroke of a typing run is
684        // an edit too.
685        self.edit_serial = next_revision();
686        if coalesce_key.is_some() && coalesce_key == self.last_edit_key.as_deref() {
687            return;
688        }
689        self.undo_stack.push(self.snapshot());
690        if self.undo_stack.len() > MAX_UNDO {
691            self.undo_stack.remove(0);
692        }
693        self.redo_stack.clear();
694        self.last_edit_key = coalesce_key.map(str::to_string);
695    }
696
697    /// Whether an undo step is available (for enabling the toolbar button).
698    pub fn can_undo(&self) -> bool {
699        !self.undo_stack.is_empty()
700    }
701
702    /// Whether a redo step is available.
703    pub fn can_redo(&self) -> bool {
704        !self.redo_stack.is_empty()
705    }
706
707    /// Undo the last model mutation: push the current state onto the redo stack
708    /// and restore the previous document + rolled-to step. Returns whether it
709    /// changed anything (false when the undo stack is empty).
710    pub fn undo(&mut self) -> bool {
711        if self.refuse_user() {
712            return false;
713        }
714        let Some(prev) = self.undo_stack.pop() else {
715            return false;
716        };
717        self.redo_stack.push(self.snapshot());
718        self.restore(prev);
719        // A distinct undo breaks any coalescing run so the next edit is fresh.
720        self.last_edit_key = None;
721        true
722    }
723
724    /// Redo the last undone model mutation (symmetric with [`Self::undo`]).
725    pub fn redo(&mut self) -> bool {
726        if self.refuse_user() {
727            return false;
728        }
729        let Some(next) = self.redo_stack.pop() else {
730            return false;
731        };
732        self.undo_stack.push(self.snapshot());
733        self.restore(next);
734        self.last_edit_key = None;
735        true
736    }
737}
738
739// ============================================================================
740// Assembly document accessors (appended — the assemblies Wave-3 slice). A
741// SEPARATE `impl` block so concurrent edits to the primary block don't
742// conflict; purely additive over the existing history API.
743// ============================================================================
744impl History {
745    /// ADOPT a whole replacement document — the assembly FOLD's write-back lane
746    /// (`assembly_apply_document_json` returns the document with the solved
747    /// `assembly` block + poses/isFixed folded into the features; the engine
748    /// adopts it before persisting or re-running — the pose-authority contract).
749    ///
750    /// `checkpoint` chooses the undo semantics: a USER constraint mutation
751    /// records an undo snapshot (so constraint edits stay undoable like any
752    /// model edit); the silent post-run pose fold passes `false` (solver
753    /// write-back is not a user edit — undoing the user's LAST edit must not
754    /// strand an extra fold step in between).
755    ///
756    /// A stray `featureCounter` in the adopted document is stripped (the
757    /// in-memory counter stays authoritative — `request_json` re-folds it on
758    /// serialize, exactly like `from_request_json` lifts it on load). The
759    /// rollback index is preserved (the fold never changes the feature count).
760    pub fn adopt_document(&mut self, document_json: &str) -> Result<(), String> {
761        // Locked, say so: a caller that checks the result (an eCAD block sync
762        // recording what it wrote) must not believe a refused write landed.
763        if let Some(reason) = &self.lock {
764            let error = format!("the document is read-only: {reason}");
765            self.refused += 1;
766            return Err(error);
767        }
768        let mut document: Value = serde_json::from_str(document_json)
769            .map_err(|error| format!("adopt document parse: {error}"))?;
770        if !document.is_object() {
771            return Err("adopt document: not a JSON object".into());
772        }
773        let mut adopted_library = None;
774        if let Some(obj) = document.as_object_mut() {
775            obj.remove("featureCounter");
776            // A block PRESENT in the adopted document replaces the field; one
777            // ABSENT leaves it alone (the fold lane is handed a library-free
778            // document by `request_json_without_parts_library` and must not
779            // silently drop the library on the way back).
780            adopted_library = obj.remove("partsLibrary");
781            if !obj.get("features").map(Value::is_array).unwrap_or(false) {
782                obj.insert("features".into(), Value::Array(Vec::new()));
783            }
784        }
785        *self.document_mut() = document;
786        // A replaced document is not the one a pin or port edit was held on.
787        self.pin_port_hold = None;
788        if let Some(library) = adopted_library {
789            self.set_parts_library(library);
790            }
791        Ok(())
792    }
793
794    /// Same adoption with an undo snapshot recorded FIRST (never coalesced) —
795    /// the user-mutation twin of [`Self::adopt_document`].
796    pub fn adopt_document_checkpointed(&mut self, document_json: &str) -> Result<(), String> {
797        // Validate BEFORE snapshotting so a parse failure never pushes a
798        // phantom undo entry.
799        let probe: Value = serde_json::from_str(document_json)
800            .map_err(|error| format!("adopt document parse: {error}"))?;
801        if !probe.is_object() {
802            return Err("adopt document: not a JSON object".into());
803        }
804        self.checkpoint(None);
805        self.adopt_document(document_json)
806    }
807
808    /// Replace the document's `partsLibrary` block (the assemblies parts
809    /// library) — the caller feeds `brep_kernel::parts_library_json()` here
810    /// (never an echo of a loaded block), so SAVE serializes the kernel
811    /// store with its heals and GC. An empty map clears the field, so a
812    /// non-assembly document serializes byte-identically to before.
813    ///
814    /// The block is held in the `parts_library` FIELD rather than on
815    /// `self.document`; [`Self::request_json`] folds it back into the saved
816    /// document. The on-disk shape is unchanged.
817    pub fn set_parts_library(&mut self, library: Value) {
818        if self.refuse() {
819            return;
820        }
821        let empty = library.as_object().map(|m| m.is_empty()).unwrap_or(true);
822        self.parts_library = std::rc::Rc::new(if empty { Value::Null } else { library });
823        // The block is part of the saved document, so this is a document
824        // mutation and owes the revision a tick — `document_mut` never sees it.
825        self.revision = next_revision();
826    }
827
828    /// Replace the `partsLibrary` block as a USER EDIT: one undo checkpoint,
829    /// and the mirror flag CLEARED so the next run ships the block to the
830    /// runner instead of assuming the kernel store already agrees.
831    ///
832    /// [`Self::set_parts_library`] is the other door and means the opposite —
833    /// "this block came OUT of the kernel store" — so it must not be reused
834    /// here: a part-attribute edit is authored on this side and the runner has
835    /// never seen it. `coalesce_key` follows the `param:{index}` rule so a run
836    /// of keystrokes into one attribute is one undo entry.
837    pub fn set_parts_library_edited(&mut self, library: Value, coalesce_key: Option<&str>) {
838        if self.refuse_user() {
839            return;
840        }
841        self.checkpoint(coalesce_key);
842        let empty = library.as_object().map(|m| m.is_empty()).unwrap_or(true);
843        self.parts_library = std::rc::Rc::new(if empty { Value::Null } else { library });
844        // As [`Self::set_parts_library`]: `checkpoint` records an undo entry
845        // and moves nothing a cache can see.
846        self.revision = next_revision();
847    }
848
849    /// The `partsLibrary` block (`Value::Null` when the document has none).
850    pub fn parts_library(&self) -> &Value {
851        &self.parts_library
852    }
853
854    /// The document's `assembly` block (`{constraints, idCounter}`), if any.
855    pub fn assembly_block(&self) -> Option<&Value> {
856        self.document().get("assembly")
857    }
858
859    /// Replace the `assembly` block (`{constraints, idCounter}`) — the STATE
860    /// half of the assembly write-back, which the engine folds from the run's
861    /// reply after every run and from the live session after a constraint
862    /// mutation. `checkpoint` = true makes it an undoable USER edit (a
863    /// mutation); false writes it silently, because a solver adopting its own
864    /// result is not a user edit and must never mint an undo entry — undoing a
865    /// user action then re-running re-solves and re-folds anyway.
866    pub fn set_assembly_block(&mut self, block: Value, checkpoint: bool) {
867        if checkpoint {
868            self.checkpoint(None);
869        }
870        if let Some(object) = self.document_mut().as_object_mut() {
871            object.insert("assembly".into(), block);
872        }
873    }
874
875    /// The document's `wireHarness` block (`{connections, idCounter,
876    /// buildBundles}`), if any.
877    pub fn wire_harness_block(&self) -> Option<&Value> {
878        self.document().get("wireHarness")
879    }
880
881    /// Replace (or, with `None`, remove) the `wireHarness` block. A USER edit:
882    /// snapshotted for undo, never coalesced — each add / edit / remove of a
883    /// connection is its own undo step, like a feature add or delete.
884    pub fn set_wire_harness_block(&mut self, block: Option<Value>) {
885        self.checkpoint(None);
886        if let Some(object) = self.document_mut().as_object_mut() {
887            match block {
888                Some(block) => {
889                    object.insert("wireHarness".into(), block);
890                }
891                None => {
892                    object.remove("wireHarness");
893                }
894            }
895        }
896    }
897}
898
899// ============================================================================
900// PMI block accessors (the PMI workbench slice). A SEPARATE `impl` block —
901// purely additive over the history API.
902// ============================================================================
903impl History {
904    /// The document's `pmi` block (`{views, idCounter}`), if any.
905    pub fn pmi_block(&self) -> Option<&Value> {
906        self.document().get("pmi")
907    }
908
909    /// Replace (or, with `None`, remove) the `pmi` block as a USER edit:
910    /// snapshotted for undo. `coalesce_key` groups a run of rapid same-target
911    /// edits (a label drag: `pmi:label:{id}`) into ONE undo entry; `None`
912    /// makes the edit its own step (a view capture, an annotation add / edit
913    /// / delete).
914    pub fn set_pmi_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
915        self.checkpoint(coalesce_key);
916        self.put_pmi_block(block);
917    }
918
919    /// Replace the `pmi` block WITHOUT an undo checkpoint — for a write that
920    /// belongs to the checkpoint just taken (an import lifting a file's PMI
921    /// beside the feature it added, so one undo removes both).
922    pub fn set_pmi_block_no_undo(&mut self, block: Option<Value>) {
923        self.put_pmi_block(block);
924    }
925
926    fn put_pmi_block(&mut self, block: Option<Value>) {
927        if let Some(object) = self.document_mut().as_object_mut() {
928            match block {
929                Some(block) => {
930                    object.insert("pmi".into(), block);
931                }
932                None => {
933                    object.remove("pmi");
934                }
935            }
936        }
937    }
938
939    /// End a coalescing run (a label drag released): the next edit with the
940    /// same key starts a fresh undo entry.
941    pub fn break_coalescing(&mut self) {
942        self.last_edit_key = None;
943    }
944}
945
946// ============================================================================
947// SHEETS block accessors (the drawing-sheet slice).
948//
949// `sheets` is a top-level document key like `pmi` and `partAttributes`: a
950// sheet places saved PMI views and adds no geometry, so the kernel never needs
951// it and `HistoryRequest` has no field for it — the document's unknown-key
952// pass-through ([`Self::request_json`] serializes the raw document) is what
953// round-trips it through save, load and undo. Absent on every document without
954// a sheet, so those files re-serialize byte-identically.
955// ============================================================================
956impl History {
957    /// The document's `sheets` block (`{sheets, idCounter}`), if any.
958    pub fn sheets_block(&self) -> Option<&Value> {
959        self.document().get(crate::sheets::SHEETS)
960    }
961
962    /// Replace (or, with `None`, remove) the `sheets` block as a USER edit:
963    /// snapshotted for undo. `coalesce_key` groups a run of rapid same-target
964    /// edits (dragging a placed view: `sheet:view:{id}`) into ONE undo entry,
965    /// exactly as the PMI label drag's does.
966    pub fn set_sheets_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
967        self.checkpoint(coalesce_key);
968        if let Some(object) = self.document_mut().as_object_mut() {
969            match block {
970                Some(block) => {
971                    object.insert(crate::sheets::SHEETS.into(), block);
972                }
973                None => {
974                    object.remove(crate::sheets::SHEETS);
975                }
976            }
977        }
978    }
979}
980
981// ============================================================================
982// PART ATTRIBUTES block accessors — the BOM attributes of the document ITSELF.
983//
984// `partAttributes` is a top-level document key (see
985// `engine_state::bom`'s attributes block), so a document carries the BOM data
986// of the PART it is. On a part in an assembly's library that record is written
987// through the library entry's embedded document; on the document you have OPEN
988// it is written here, by the toolbar's Properties dialog. Same key, same
989// shape, two doors — which is what makes a part's Part Number the same value
990// whether it is read from the assembly's BOM or from the part's own tab.
991// ============================================================================
992impl History {
993    /// The document's own `partAttributes` record, if any.
994    pub fn part_attributes_block(&self) -> Option<&Value> {
995        self.document().get(crate::engine_state::PART_ATTRIBUTES)
996    }
997
998    /// Replace (or, with `None`, remove) the document's own `partAttributes`
999    /// record as a USER edit: snapshotted for undo. `coalesce_key` groups a run
1000    /// of edits to ONE field (a typing run in the Properties dialog) into a
1001    /// single undo entry, exactly as the PMI block's does.
1002    pub fn set_part_attributes_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1003        self.checkpoint(coalesce_key);
1004        if let Some(object) = self.document_mut().as_object_mut() {
1005            match block {
1006                Some(block) => {
1007                    object.insert(crate::engine_state::PART_ATTRIBUTES.into(), block);
1008                }
1009                None => {
1010                    object.remove(crate::engine_state::PART_ATTRIBUTES);
1011                }
1012            }
1013        }
1014    }
1015}
1016
1017// ============================================================================
1018// Expressions / configurator accessors (appended — the expressions/parameters
1019// panel slice). A SEPARATE `impl` block so concurrent edits to the primary block
1020// don't conflict; purely additive over the existing history API.
1021//
1022// The history document carries an `expressions` source string — the variable
1023// sheet feature params evaluate against (a numeric param may be the string
1024// `"boxW"`, evaluated by the pipeline's shared expression env). The panel edits
1025// this and re-runs; the `configurator` object (typed named inputs) is exposed
1026// read-only for display.
1027// ============================================================================
1028impl History {
1029    /// The history document's `expressions` source string (empty when absent or
1030    /// stored as `null`). The panel's editor binds to this.
1031    pub fn expressions(&self) -> String {
1032        self.document()
1033            .get("expressions")
1034            .and_then(Value::as_str)
1035            .unwrap_or("")
1036            .to_string()
1037    }
1038
1039    /// Replace the `expressions` source string. Snapshotted for undo, coalescing a
1040    /// run of keystroke edits into ONE undo entry (like a slider drag) via the
1041    /// shared `"expressions"` coalesce key, so a distinct add/edit/roll starts a
1042    /// fresh entry. A no-op re-set (same text) still records under the same key.
1043    pub fn set_expressions(&mut self, expressions: &str) {
1044        self.checkpoint(Some("expressions"));
1045        if let Some(obj) = self.document_mut().as_object_mut() {
1046            obj.insert(
1047                "expressions".into(),
1048                Value::String(expressions.to_string()),
1049            );
1050        }
1051    }
1052
1053    /// The `configurator` object (typed named inputs), or `{}` when absent —
1054    /// read-only for the panel's display (deeper configurator editing deferred).
1055    pub fn configurator(&self) -> Value {
1056        self.document()
1057            .get("configurator")
1058            .cloned()
1059            .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
1060    }
1061}
1062
1063// ============================================================================
1064// Feature `persistentData` accessors (appended — the engine-native sketch mode
1065// slice). A SEPARATE `impl` block (like the expressions accessors above) so
1066// concurrent edits don't conflict; purely additive over the primary history API.
1067//
1068// A feature's `persistentData` is the kernel-persisted, non-input state (a
1069// SKETCH feature stores its solved `{points, geometries, constraints}` under the
1070// `sketch` key and the plane `basis` there). Sketch mode reads that state on
1071// enter and writes the edited doc back on commit — mirroring how the ref-select
1072// slice reads/writes `inputParams` through `feature_params` / `set_feature_params`.
1073// ============================================================================
1074impl History {
1075    /// The `persistentData` document of the feature at `index` (`None` if the
1076    /// feature or the field is absent) — the read twin of [`Self::feature_params`].
1077    pub fn feature_persistent_data(&self, index: usize) -> Option<Value> {
1078        self.features().get(index)?.get("persistentData").cloned()
1079    }
1080
1081    /// Set a single `key` inside the feature-at-`index`'s `persistentData` object,
1082    /// creating (or replacing a non-object) `persistentData` as needed. Snapshotted
1083    /// for undo (a structural edit — never coalesced), like an add/delete.
1084    pub fn set_feature_persistent_field(&mut self, index: usize, key: &str, value: Value) {
1085        self.set_feature_persistent_field_coalesced(index, key, value, None);
1086    }
1087
1088    /// [`Self::set_feature_persistent_field`] with an optional COALESCE key: a
1089    /// run of same-key writes (a gizmo drag moving a spline anchor, frame after
1090    /// frame) records ONE undo entry, exactly as a slider drag on a param does.
1091    pub fn set_feature_persistent_field_coalesced(
1092        &mut self,
1093        index: usize,
1094        key: &str,
1095        value: Value,
1096        coalesce_key: Option<&str>,
1097    ) {
1098        if index >= self.len() {
1099            return;
1100        }
1101        self.checkpoint(coalesce_key);
1102        if let Some(feat) = self.features_mut().get_mut(index).and_then(Value::as_object_mut) {
1103            let entry = feat
1104                .entry("persistentData")
1105                .or_insert_with(|| Value::Object(serde_json::Map::new()));
1106            if !entry.is_object() {
1107                *entry = Value::Object(serde_json::Map::new());
1108            }
1109            if let Some(obj) = entry.as_object_mut() {
1110                obj.insert(key.to_string(), value);
1111            }
1112        }
1113    }
1114
1115    /// Write several `persistentData` fields of the feature at `index` as ONE
1116    /// user edit: one undo checkpoint covers them all, and there is none when
1117    /// every field already holds its value, so an action that changed nothing
1118    /// leaves no undo step that does nothing. Returns whether anything changed.
1119    ///
1120    /// Leaving a sketch writes its geometry, its dimension label offsets and
1121    /// its external references this way. Written one field at a time they were
1122    /// three undo steps, and only the third Ctrl+Z took the drawing back.
1123    pub fn set_feature_persistent_fields(&mut self, index: usize, fields: Vec<(&str, Value)>) -> bool {
1124        let Some(feature) = self.features().get(index) else {
1125            return false;
1126        };
1127        let current = feature.get("persistentData");
1128        if fields.iter().all(|(key, value)| current.and_then(|data| data.get(*key)) == Some(value)) {
1129            return false;
1130        }
1131        self.checkpoint(None);
1132        if let Some(feat) = self.features_mut().get_mut(index).and_then(Value::as_object_mut) {
1133            let entry = feat
1134                .entry("persistentData")
1135                .or_insert_with(|| Value::Object(serde_json::Map::new()));
1136            if !entry.is_object() {
1137                *entry = Value::Object(serde_json::Map::new());
1138            }
1139            if let Some(obj) = entry.as_object_mut() {
1140                for (key, value) in fields {
1141                    obj.insert(key.to_string(), value);
1142                }
1143            }
1144        }
1145        true
1146    }
1147
1148    /// The undo step on top of the stack right now, as a token for
1149    /// [`Self::retract`] and [`Self::set_feature_persistent_fields_in_step`];
1150    /// `None` when there is nothing to undo.
1151    pub fn undo_top(&self) -> Option<u64> {
1152        self.undo_stack.last().map(|snapshot| snapshot.serial)
1153    }
1154
1155    /// Take back undo step `step` as though its edit had never been made:
1156    /// restore the state it holds and DROP it, leaving no redo entry. Only while
1157    /// `step` is still the newest step; otherwise nothing happens and this
1158    /// returns false, and the caller undoes the ordinary way.
1159    ///
1160    /// Cancelling a sketch created in the same session uses it, so the cancel
1161    /// leaves no undo step behind: two presses, one of which brought the
1162    /// cancelled sketch back, before. It cannot restore a redo stack the step's
1163    /// own edit cleared when it was taken. Neither could the cancel it replaces.
1164    pub fn retract(&mut self, step: u64) -> bool {
1165        if self.refuse_user() {
1166            return false;
1167        }
1168        if self.undo_top() != Some(step) {
1169            return false;
1170        }
1171        let Some(snapshot) = self.undo_stack.pop() else {
1172            return false;
1173        };
1174        self.restore(snapshot);
1175        self.last_edit_key = None;
1176        true
1177    }
1178
1179    /// [`Self::set_feature_persistent_fields`] as part of undo step `step`,
1180    /// with no checkpoint of its own, while `step` is still the newest step;
1181    /// otherwise an ordinary write with its own step. Finishing a sketch
1182    /// created in the same session writes this way, so creating, drawing and
1183    /// finishing it is one undo step.
1184    pub fn set_feature_persistent_fields_in_step(
1185        &mut self,
1186        index: usize,
1187        fields: Vec<(&str, Value)>,
1188        step: u64,
1189    ) -> bool {
1190        if self.undo_top() != Some(step) {
1191            return self.set_feature_persistent_fields(index, fields);
1192        }
1193        let Some(feat) = self.features_mut().get_mut(index).and_then(Value::as_object_mut) else {
1194            return false;
1195        };
1196        let entry = feat
1197            .entry("persistentData")
1198            .or_insert_with(|| Value::Object(serde_json::Map::new()));
1199        if !entry.is_object() {
1200            *entry = Value::Object(serde_json::Map::new());
1201        }
1202        if let Some(obj) = entry.as_object_mut() {
1203            for (key, value) in fields {
1204                obj.insert(key.to_string(), value);
1205            }
1206        }
1207        true
1208    }
1209}
1210
1211// ============================================================================
1212// eCAD block accessors (the eCAD documents slice).
1213//
1214// The four eCAD workbenches keep their documents as top-level keys: `diagram`
1215// (the wiring diagram) and `pcb` (schematic and board) are blocks of an
1216// ASSEMBLY document, since a board is an assembly; `symbol` and `pads` are
1217// blocks of a PART document, since a part carries its own symbol and pads.
1218// Like `sheets`, the kernel never reads them and `HistoryRequest` has no field
1219// for them: the raw document is what carries them through save, load, undo and
1220// the assembly fold. Absent on every document the eCAD editors never wrote, so
1221// those files re-serialize byte-identically.
1222//
1223// None of these setters runs the history. The tab's dirty dot and the autosave
1224// see the edit through [`History::revision`], which every write here moves. The
1225// two symbol setters also carry a pin edit to the part's PORT features (the
1226// pins-and-ports block below), and the engine's `pump` runs the history when
1227// that moved a port.
1228// ============================================================================
1229
1230/// The assembly document's wiring diagram (an eCAD `Document`).
1231pub const DIAGRAM: &str = "diagram";
1232/// The assembly document's schematic and board (an eCAD `Document`).
1233pub const PCB: &str = "pcb";
1234/// The part document's schematic symbol (an eCAD `Symbol`). Defined AS the
1235/// kernel's key: the pin/port binding (`brep_kernel` `part_pins`) reads the same
1236/// block, so the two can never name different keys.
1237pub const SYMBOL: &str = brep_kernel::SYMBOL_BLOCK;
1238/// The part document's footprint pads (an eCAD `Footprint`), defined AS the
1239/// kernel's key for the same reason.
1240pub const PADS: &str = brep_kernel::PADS_BLOCK;
1241/// The part's declared connection points (`ports.rs`) — data, not history,
1242/// and a sibling of `symbol` and `pads`.
1243pub const PORTS: &str = brep_kernel::PORTS_BLOCK;
1244
1245impl History {
1246    /// The document's `diagram` block, if any.
1247    pub fn diagram_block(&self) -> Option<&Value> {
1248        self.document().get(DIAGRAM)
1249    }
1250
1251    /// The document's `pcb` block, if any.
1252    pub fn pcb_block(&self) -> Option<&Value> {
1253        self.document().get(PCB)
1254    }
1255
1256    /// The document's `symbol` block, if any.
1257    pub fn symbol_block(&self) -> Option<&Value> {
1258        self.document().get(SYMBOL)
1259    }
1260
1261    /// The document's `pads` block, if any.
1262    pub fn pads_block(&self) -> Option<&Value> {
1263        self.document().get(PADS)
1264    }
1265
1266    /// The document's `ports` block (its declared connection points), if any.
1267    pub fn ports_block(&self) -> Option<&Value> {
1268        self.document().get(PORTS)
1269    }
1270
1271    /// The part's declared connection points, in block order.
1272    pub fn declared_points(&self) -> Vec<brep_kernel::DeclaredPoint> {
1273        brep_kernel::declared_points(self.document())
1274    }
1275
1276    /// The symbol's pin labels in pin order, or `None` without a symbol.
1277    pub fn pin_labels(&self) -> Option<Vec<String>> {
1278        brep_kernel::pin_labels(self.document())
1279    }
1280
1281    /// The symbol's pins with the UNIT each belongs to, in pin order, or `None`
1282    /// without a symbol. [`Self::pin_labels`] with the unit kept, for a caller
1283    /// that must say WHICH group a pin binds into.
1284    pub fn pins(&self) -> Option<Vec<brep_kernel::DeclaredPin>> {
1285        brep_kernel::pins(self.document())
1286    }
1287
1288    /// The port group the pins of symbol unit `unit` bind into, when one is
1289    /// mapped. The unit map's rule is the kernel's ([`brep_kernel::unit_groups`]).
1290    pub fn port_group_for_unit(&self, unit: u32) -> Option<String> {
1291        brep_kernel::port_group_for_unit(self.document(), unit)
1292    }
1293
1294    /// Replace (or, with `None`, remove) the `diagram` block as a USER edit.
1295    /// See [`Self::set_ecad_block`] for `coalesce_key`.
1296    pub fn set_diagram_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1297        self.set_ecad_block(DIAGRAM, block, coalesce_key);
1298    }
1299
1300    /// Replace (or, with `None`, remove) the `pcb` block as a USER edit.
1301    /// See [`Self::set_ecad_block`] for `coalesce_key`.
1302    pub fn set_pcb_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1303        self.set_ecad_block(PCB, block, coalesce_key);
1304    }
1305
1306    /// Replace (or, with `None`, remove) the `symbol` block as a USER edit,
1307    /// and follow it to the part's ports in the same undo step (see
1308    /// [`Self::follow_pins`]). See [`Self::set_ecad_block`] for `coalesce_key`.
1309    pub fn set_symbol_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1310        self.set_ecad_block(SYMBOL, block, coalesce_key);
1311        self.follow_pins(None);
1312    }
1313
1314    /// Replace (or, with `None`, remove) the `pads` block as a USER edit.
1315    /// See [`Self::set_ecad_block`] for `coalesce_key`.
1316    pub fn set_pads_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1317        self.set_ecad_block(PADS, block, coalesce_key);
1318    }
1319
1320    /// Write the `symbol` block WITHOUT an undo checkpoint, for a write that
1321    /// belongs to the checkpoint just taken: a KiCad import adds its Import 3D
1322    /// feature (one checkpoint) and writes the symbol and pads it read beside
1323    /// it, so one undo removes the whole import. The PMI import's
1324    /// [`Self::set_pmi_block_no_undo`] is the precedent.
1325    ///
1326    /// Skipping the checkpoint is deliberate, and costs the tab nothing: the
1327    /// write still goes through `document_mut`, which moves the revision the
1328    /// unsaved dot and the autosave key on.
1329    pub fn set_symbol_block_no_undo(&mut self, block: Option<Value>) {
1330        // No checkpoint marks where this write starts, so its base is the
1331        // document just before it.
1332        let base = self.document().clone();
1333        self.put_ecad_block(SYMBOL, block);
1334        self.follow_pins(Some(base));
1335    }
1336
1337    /// The `pads` twin of [`Self::set_symbol_block_no_undo`].
1338    pub fn set_pads_block_no_undo(&mut self, block: Option<Value>) {
1339        self.put_ecad_block(PADS, block);
1340    }
1341
1342    /// Replace (or, with `None`, remove) the `ports` block as a USER edit, and
1343    /// follow it to the part's pins in the same undo step (see
1344    /// [`Self::follow_ports`]).
1345    pub fn set_ports_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1346        self.set_ecad_block(PORTS, block, coalesce_key);
1347        self.follow_ports();
1348        self.ports_followed = true;
1349    }
1350
1351    /// The `ports` twin of [`Self::set_symbol_block_no_undo`] — for a write
1352    /// that belongs to the checkpoint just taken (the KiCad import).
1353    pub fn set_ports_block_no_undo(&mut self, block: Option<Value>) {
1354        self.put_ecad_block(PORTS, block);
1355        self.ports_followed = true;
1356    }
1357
1358    /// Write block `key`, snapshotted for undo. `coalesce_key` is eCAD's own
1359    /// `Change::coalesce`, passed as the editor reported it: typing in one
1360    /// field of one object reports `component:{uuid}:text` on every frame, and
1361    /// a run of writes with that key is ONE undo entry. It is namespaced by the
1362    /// block here (`diagram:component:{uuid}:text`), so a run in one block never
1363    /// swallows an edit to another. `None` (a drag, a placement, the editor's
1364    /// own undo) is its own step.
1365    fn set_ecad_block(&mut self, key: &str, block: Option<Value>, coalesce_key: Option<&str>) {
1366        let coalesce_key = coalesce_key.map(|change| format!("{key}:{change}"));
1367        self.checkpoint(coalesce_key.as_deref());
1368        self.put_ecad_block(key, block);
1369    }
1370
1371    fn put_ecad_block(&mut self, key: &str, block: Option<Value>) {
1372        if let Some(object) = self.document_mut().as_object_mut() {
1373            match block {
1374                Some(block) => {
1375                    object.insert(key.into(), block);
1376                }
1377                None => {
1378                    object.remove(key);
1379                }
1380            }
1381        }
1382    }
1383}
1384
1385// ============================================================================
1386// Pins and points: a part's symbol pins ARE its declared connection points,
1387// bound by NAME (eCAD plan decision 8; `brep_kernel` `part_pins` holds the
1388// rules).
1389//
1390// The binding lives HERE, inside the writes, so no caller can edit one side
1391// without the other: the symbol setters follow a pin edit to the points, and
1392// every mutator that can add, remove or rename a point follows it to the pins,
1393// inside the same undo step. Undo, redo and a replaced document need nothing,
1394// since a snapshot restores both sides together.
1395//
1396// Each follow diffs against the RUN BASE: the document the current coalesced
1397// run started from. Typing `10` over pin `2` is four writes under one eCAD key
1398// (`2`, ``, `1`, `10`). The two in the middle cannot bind (no label, and a
1399// label pin 1 already has), so they are HELD: the user's edit stands, the
1400// other side keeps what the last bound write gave it, and `pin_port_hold`
1401// names why. Replaying from the base makes the last keystroke decide
1402// whichever came before it.
1403// ============================================================================
1404
1405impl History {
1406    /// Why the latest pin or port edit was not followed to the other side, in
1407    /// words that name the label (`two pins are labelled '1'`), or `None`.
1408    pub fn pin_port_hold(&self) -> Option<&str> {
1409        self.pin_port_hold.as_deref()
1410    }
1411
1412    /// Everything about this part's pins and connection points that does not
1413    /// pair, by name; `None` for a document without a symbol.
1414    pub fn pin_point_report(&self) -> Option<brep_kernel::PinPointReport> {
1415        brep_kernel::pin_point_report(self.document())
1416    }
1417
1418    /// Whether a symbol edit has changed the declared points since the history
1419    /// last ran, clearing it. The engine re-runs when it was set.
1420    pub(crate) fn take_ports_followed(&mut self) -> bool {
1421        std::mem::take(&mut self.ports_followed)
1422    }
1423
1424    /// Whether the next [`crate::engine_state::EngineState::pump`] will re-run
1425    /// for a moved point, without clearing it — so the app can hand a document
1426    /// that is not in front its own parts library before that run is submitted.
1427    pub fn ports_follow_pending(&self) -> bool {
1428        self.ports_followed
1429    }
1430
1431    /// The document the current coalesced run started from. Right after a
1432    /// checkpointing write it is the top of the undo stack: [`Self::checkpoint`]
1433    /// pushes the pre-write state unless the write joins a run, and a run's
1434    /// first write pushed the state the run started from. Eviction takes the
1435    /// OLDEST entry, never the top. The stack is never empty after a
1436    /// checkpoint, so the fallback (the current document, which binds nothing)
1437    /// is never taken by a follow. Borrowed: a follow runs on every write of a
1438    /// drag, so the base is compared in place and never copied.
1439    fn run_base(&self) -> &Value {
1440        self.undo_stack
1441            .last()
1442            .map(|snapshot| &snapshot.request)
1443            .unwrap_or_else(|| self.document())
1444    }
1445
1446    /// Carry the symbol edit between the base (`base`, else the run base) and
1447    /// now to the connection points and the pads: a renamed pin renames its
1448    /// point in place (so the point keeps its placement), a removed pin removes
1449    /// its point, and a new pin gets a new point in the part's first port
1450    /// group.
1451    fn follow_pins(&mut self, base: Option<Value>) {
1452        let mut document = self.document().clone();
1453        let outcome = {
1454            let base = base.as_ref().unwrap_or_else(|| self.run_base());
1455            brep_kernel::follow_pin_edit(base, &mut document)
1456        };
1457        self.settle(outcome, document);
1458    }
1459
1460    /// Carry a connection-point edit between the run base and now to the pins
1461    /// and pads. Only an edit that changed the declared points is followed, so
1462    /// an unrelated edit neither binds nor clears a standing hold.
1463    fn follow_ports(&mut self) {
1464        if self.symbol_block().is_none() {
1465            return;
1466        }
1467        if brep_kernel::declared_points(self.run_base()) == brep_kernel::declared_points(self.document()) {
1468            return;
1469        }
1470        let mut document = self.document().clone();
1471        let outcome = brep_kernel::follow_point_edit(self.run_base(), &mut document);
1472        self.settle(outcome, document);
1473    }
1474
1475    /// Adopt a follow's result, or record why it was held. The write goes
1476    /// through `document_mut`, not a checkpoint: it belongs to the step the
1477    /// user's own write just took. The rolled-to step keeps its meaning: a
1478    /// model rolled to its last feature is still rolled to its last feature
1479    /// once a port is appended or removed, and one rolled back stays on the
1480    /// same feature.
1481    fn settle(&mut self, outcome: Result<Vec<brep_kernel::PinPointChange>, String>, document: Value) {
1482        let changes = match outcome {
1483            Ok(changes) => changes,
1484            Err(reason) => {
1485                self.pin_port_hold = Some(reason);
1486                return;
1487            }
1488        };
1489        self.pin_port_hold = None;
1490        if changes.is_empty() {
1491            return;
1492        }
1493        let moves_a_port = changes.iter().any(|change| {
1494            use brep_kernel::PinPointChange::*;
1495            // Exhaustive on purpose: a new kind of change must say whether
1496            // it touches the geometry a run publishes.
1497            match change {
1498                PointRenamed { .. } | PointAdded { .. } | PointRemoved { .. } => true,
1499                PinRelabelled { .. } | PinAdded { .. } | PinRemoved { .. }
1500                | PadsRenumbered { .. } | PadsAmbiguous { .. } => false,
1501            }
1502        });
1503        let at_end = self.rollback + 1 >= self.len();
1504        let rolled_to = self.feature_id(self.rollback());
1505        *self.document_mut() = document;
1506        let len = self.len();
1507        self.rollback = if len == 0 {
1508            0
1509        } else if at_end {
1510            len - 1
1511        } else {
1512            rolled_to
1513                .and_then(|id| self.index_of(&id))
1514                .unwrap_or_else(|| self.rollback.saturating_sub(1))
1515                .min(len - 1)
1516        };
1517        self.ports_followed |= moves_a_port;
1518    }
1519}
1520
1521
1522// ============================================================================
1523// Named top-level blocks the APP owns (appended — the document-classes slice).
1524// The history holds the document as a JSON value, so a key the kernel never
1525// reads (`documentClass`, a family's `familyTable`, a template's
1526// `templateInputs`, a member's `familySource`) rides save, open and every undo
1527// snapshot untouched. These are the doors that change one: the user-edit one
1528// records an undo step, the other is for a write that is bookkeeping rather
1529// than an edit (the class a load reads off the file's extension).
1530// ============================================================================
1531impl History {
1532    /// The document's top-level block `key`, if present.
1533    pub fn document_block(&self, key: &str) -> Option<&Value> {
1534        self.document().get(key)
1535    }
1536
1537    /// Replace (or, with `None`, remove) top-level block `key` as a USER edit:
1538    /// snapshotted for undo. `coalesce_key` groups a typing run into one step,
1539    /// namespaced by the block so a run in one never swallows another's.
1540    pub fn set_document_block(&mut self, key: &str, block: Option<Value>, coalesce_key: Option<&str>) {
1541        let coalesce_key = coalesce_key.map(|change| format!("block:{key}:{change}"));
1542        self.checkpoint(coalesce_key.as_deref());
1543        self.set_document_block_no_undo(key, block);
1544    }
1545
1546    /// [`Self::set_document_block`] with no undo step.
1547    pub fn set_document_block_no_undo(&mut self, key: &str, block: Option<Value>) {
1548        if let Some(object) = self.document_mut().as_object_mut() {
1549            match block {
1550                Some(block) => {
1551                    object.insert(key.to_string(), block);
1552                }
1553                None => {
1554                    object.remove(key);
1555                }
1556            }
1557        }
1558    }
1559}
1560