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