Skip to main content

brep_app/document/
work_part.rs

1//! Work part: edit one part occurrence's own history in the context of its
2//! assembly, at any depth of the product structure (NX "Make Work Part").
3//!
4//! IN PLACE (the default, a BOM double-click): the part's document is HOSTED by
5//! the assembly tab. It is not a tab of its own; the tab strip, the tab's name,
6//! Save and the dirty dot all stay the assembly's. [`Documents::engine`] answers
7//! with the hosted part engine, so every modeling tool and the history panel
8//! edit the part, while the rest of the assembly is drawn around it as a
9//! translucent, non-selectable context scene in the same camera.
10//!
11//! NEW TAB (the row menu's "Open in new tab"): the same session, but the part
12//! document is an ordinary tab and the assembly a background one.
13//!
14//! LIVE UPDATE. Every settled part change is pushed into the assembly's
15//! embedded definitions (every copy with the same source identity, at every
16//! depth) through `edit_document_json`, which re-runs the assembly on its own
17//! runner. Mates are solved at the tail of that run, so components constrained
18//! to the edited geometry move in the same update. When the assembly's run
19//! lands the context scene is rebuilt from it (and re-mapped if the work
20//! occurrence itself moved). A push is never queued behind a running assembly
21//! run: while one is in flight the latest part state waits, so a burst of edits
22//! costs one rerun of the newest state.
23//!
24//! UNDO. One part edit is one part undo step and one assembly undo step. The
25//! session remembers the part states it pushed; a part undo (redo) that returns
26//! to the previous (next) pushed state undoes (redoes) the assembly step
27//! instead of pushing a new one, and a different edit after an undo discards
28//! the redo branch of both. Coalesced part edits (one slider drag) replace the
29//! assembly step they started rather than stacking. Returning adds nothing:
30//! the assembly already holds one step per part edit.
31use super::{Document, Documents};
32use brep_render::{brep_kernel, camera::Aabb, engine_state::EngineState, scene::RenderScene};
33use serde_json::Value;
34
35type Matrix = [f64; 16];
36const IDENTITY: Matrix = [
37    1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.,
38];
39
40/// Where the work part's document lives while it is being edited.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum WorkPartMode {
43    /// Hosted by the assembly tab (no tab switch).
44    InPlace,
45    /// An ordinary tab of its own; the assembly keeps running in the background.
46    NewTab,
47}
48
49/// The entry at the end of a part-name chain in an assembly document.
50pub(super) fn entry_at<'a>(document: &'a Value, names: &[String]) -> Option<&'a Value> {
51    let (last, parents) = names.split_last()?;
52    let mut owner = document;
53    for name in parents {
54        owner = &owner["partsLibrary"][name]["document"];
55    }
56    let entry = &owner["partsLibrary"][last];
57    entry.is_object().then_some(entry)
58}
59
60/// One part state the session pushed into the assembly.
61struct Pushed {
62    signature: String,
63    /// The part's undo-stack top when it was pushed: unchanged across two
64    /// pushes means the second edit coalesced into the first's undo step.
65    undo_top: Option<u64>,
66    /// The parts this push re-signed and the mates it captured before its
67    /// commit, from the document its assembly step starts from. A coalesced
68    /// edit replaces the step from that same document, so it reuses them.
69    capture: Option<(Vec<String>, brep_render::engine_state::replace_component::ReplaceCapture)>,
70}
71
72pub(super) struct WorkPart {
73    pub assembly_id: u64,
74    pub part_id: u64,
75    /// `Some` while in place: the hosted part document.
76    pub(super) hosted: Option<Box<Document>>,
77    name: String,
78    component_path: String,
79    part_path: Vec<String>,
80    source: Option<String>,
81    world: Matrix,
82    /// Pushed part states, oldest first; `[0]` is the state the session began
83    /// with (nothing to undo past it).
84    pushed: Vec<Pushed>,
85    /// Pushed states undone in step with the part, newest last.
86    redo: Vec<Pushed>,
87    /// The part's (applied generation, history revision) last examined.
88    seen: Option<(u64, u64)>,
89    /// The assembly's (applied generation, history revision) the context was
90    /// built from.
91    context_seen: Option<(u64, u64)>,
92    /// Constraints of the assembly that are not satisfied after the last
93    /// update: `(id, type, status, message)`.
94    problems: Vec<(String, String, String, String)>,
95    /// How many pushes reached the assembly (automation readback).
96    pushes: u64,
97    /// The next push is a step of its own, not a replacement of the last
98    /// coalesced one: that one's capture needed the undone document's session,
99    /// which a background runner had not handed over yet.
100    no_coalesce: bool,
101    /// The last push refusal, shown in the bar.
102    error: Option<String>,
103    /// A PLM part not checked out to this user: the offer to check it out
104    /// now (asked once per session), and the checkout in flight.
105    checkout: CheckoutOffer,
106}
107
108/// [`WorkPart::checkout`].
109#[derive(Default)]
110enum CheckoutOffer {
111    /// Not asked yet (or not a PLM part: asked of nothing).
112    #[default]
113    Unasked,
114    /// The question is on screen.
115    Asking { part: String, revision: String },
116    Running(crate::plm::PlmFuture<()>),
117    /// Answered, landed, or nothing to ask; `Some` is a line for the bar.
118    Done(Option<String>),
119}
120
121/// Resolve `component_path` (`ACOMP1:ACOMP2`) in the assembly: the
122/// occurrence's world matrix, the part-name chain, the part's source key and
123/// its embedded document.
124pub(super) fn resolve_occurrence(
125    root: &EngineState,
126    root_document: &Value,
127    component_path: &str,
128) -> Result<(Matrix, Vec<String>, Option<String>, Value), String> {
129    let mut document = root_document;
130    let mut world = IDENTITY;
131    let mut part_path = Vec::new();
132    let mut source = None;
133    let ids: Vec<&str> = component_path.split(':').collect();
134    let mut top: Option<&brep_render::pipeline::ComponentSnapshot> = None;
135    for (depth, &id) in ids.iter().enumerate() {
136        let feature = document["features"]
137            .as_array()
138            .and_then(|features| {
139                features.iter().find(|f| {
140                    matches!(f["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT"))
141                        && f["inputParams"]["id"].as_str() == Some(id)
142                })
143            })
144            .ok_or_else(|| format!("component '{id}' is missing"))?;
145        let name = feature["inputParams"]["partName"]
146            .as_str()
147            .ok_or("component has no part name")?;
148        // Every depth reads the SOLVED pose: the assembly's mates move a
149        // top-level component, and a sub-assembly's own mates (solved inside
150        // it, rigid to the parent) can move a nested occurrence away from the
151        // transform its document authors. The top-level record carries where
152        // each nested occurrence ended up, in its own frame; the authored
153        // transform is only the fallback for a record that has none.
154        world = if depth == 0 {
155            let record = root
156                .assembly_components()
157                .iter()
158                .find(|c| c.id == id)
159                .ok_or("component is not present in the current assembly")?;
160            top = Some(record);
161            record.transform
162        } else {
163            match top.and_then(|record| Some((record, record.nested_poses.get(&ids[1..=depth].join(":"))?))) {
164                Some((record, solved)) => multiply(record.transform, *solved),
165                None => multiply(world, component_pose(document, &feature["inputParams"]["transform"])?),
166            }
167        };
168        part_path.push(name.to_string());
169        let entry = &document["partsLibrary"][name];
170        source = entry["sourceKey"]
171            .as_str()
172            .filter(|s| !s.is_empty() && !s.starts_with('@'))
173            .map(str::to_string);
174        document = &entry["document"];
175        if !document.is_object() {
176            return Err(format!("part '{name}' has no embedded document"));
177        }
178    }
179    Ok((world, part_path, source, document.clone()))
180}
181
182/// The assembly drawn around the work part: every visible solid OUTSIDE the
183/// work occurrence, mapped into the part's frame, without kernel handles.
184///
185/// A ghost built exactly as it stood in `previous` keeps that one's revision,
186/// so the GPU keeps its buffers. A run of the assembly gives every solid it
187/// rebuilt a new revision, and on l500 each edit rebuilds all five modules:
188/// the 490 context solids were uploaded again on the frame the run landed
189/// (~60 ms), the same meshes nearly all of them.
190fn context_scene(host: &EngineState, component_path: &str, world: Matrix, previous: &RenderScene) -> RenderScene {
191    let inverse = inverse_rigid(world);
192    let prefix = format!("{component_path}:");
193    // A remap moves every vertex without a new host revision, so the GPU
194    // cache must see a different one: derive it from the host revision and
195    // the frame (high bit set, clear of the scene's own monotonic counter).
196    let frame = world
197        .iter()
198        .fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ v.to_bits()).wrapping_mul(0x100_0000_01b3));
199    let mut context = RenderScene::new();
200    for solid in host
201        .scene
202        .solids()
203        .iter()
204        .filter(|solid| solid.visible && !solid.name.starts_with(&prefix))
205    {
206        let mut ghost = solid.clone();
207        ghost.source_handle = 0;
208        ghost.revision = ((solid.revision ^ frame).wrapping_mul(0x9e37_79b9_7f4a_7c15)) | (1 << 63);
209        ghost.shape_revision = 0;
210        ghost.pose = None;
211        ghost.bbox = Aabb::empty();
212        for point in &mut ghost.mesh.positions {
213            let mapped = point_at(inverse, point.map(f64::from));
214            ghost.bbox.expand(mapped);
215            *point = mapped.map(|v| v as f32);
216        }
217        for normal in &mut ghost.mesh.normals {
218            *normal = vector_at(inverse, normal.map(f64::from)).map(|v| v as f32);
219        }
220        // Context edges stay, in the part's frame, so a sketch can copy one;
221        // vertices and exact kernel handles do not.
222        for edge in &mut ghost.edges {
223            for point in &mut edge.polyline {
224                *point = point_at(inverse, point.map(f64::from)).map(|v| v as f32);
225            }
226        }
227        ghost.vertices.clear();
228        if let Some(before) = previous.solid(&ghost.name) {
229            let fresh = ghost.revision;
230            ghost.revision = before.revision;
231            if ghost != *before {
232                ghost.revision = fresh;
233            }
234        }
235        context.insert_solid(ghost);
236    }
237    context
238}
239
240fn edit_key(engine: &EngineState) -> (u64, u64) {
241    (engine.applied_generation(), engine.history_revision())
242}
243
244impl Documents {
245    /// The part an occurrence places, at any depth (`ACOMP1:ACOMP2`), in the
246    /// active tab: its part-library name and its source file (`None` or empty:
247    /// a part with no file of its own).
248    pub fn occurrence_part(&self, component_path: &str) -> Result<(String, Option<String>), String> {
249        let root = self.engine();
250        let document: Value = serde_json::from_str(&root.history_request_json()).map_err(|e| e.to_string())?;
251        let (_, names, source, _) = resolve_occurrence(root, &document, component_path)?;
252        Ok((names.last().cloned().unwrap_or_default(), source))
253    }
254
255    /// Make `component_path` the Work part, in place (no tab switch).
256    pub fn begin_work_part(&mut self, component_path: &str) -> Result<(), String> {
257        self.begin_work_part_as(component_path, WorkPartMode::InPlace)
258    }
259
260    pub fn begin_work_part_as(
261        &mut self,
262        component_path: &str,
263        mode: WorkPartMode,
264    ) -> Result<(), String> {
265        if self.work_part.is_some() {
266            // Another line of the same assembly: switch the Work part.
267            let host = self.work_part.as_ref().map(|s| s.assembly_id);
268            self.finish_work_part()?;
269            if let Some(index) = host.and_then(|id| self.open.iter().position(|d| d.id() == id)) {
270                self.activate(index);
271            }
272        }
273        let root = &self.open[self.active].engine;
274        if root.run_pending()
275            || root.sketch_mode()
276            || root.sketch3d_mode()
277            || root.ref_select_active()
278        {
279            return Err("finish the current operation before choosing a Work part".into());
280        }
281        if !self.active().access().is_editable() {
282            return Err("the assembly is read-only".into());
283        }
284        let assembly_id = self.active_id();
285        let root_document: Value =
286            serde_json::from_str(&root.history_request_json()).map_err(|e| e.to_string())?;
287        let (world, part_path, source, document) =
288            resolve_occurrence(root, &root_document, component_path)?;
289        let context = context_scene(root, component_path, world, &RenderScene::new());
290        let inverse = inverse_rigid(world);
291        let mut camera = root.camera.clone();
292        camera.eye = point_at(inverse, camera.eye);
293        camera.target = point_at(inverse, camera.target);
294        camera.up = vector_at(inverse, camera.up);
295        let existing = source.as_deref().and_then(|name| self.index_of(name));
296        if existing == Some(self.active_index()) {
297            return Err("the component source refers to its assembly".into());
298        }
299        // A part also open in its own tab is fine in place: the two are kept
300        // one by the live link (`super::live_link`) on every tab switch.
301        let load = |docs: &Documents| -> Result<Document, String> {
302            let mut engine = docs.spawn_engine();
303            engine.set_history_json(&document.to_string())?;
304            // A part without its own workbench must not inherit Assembly tools.
305            if document["workbench"].as_str().is_none() {
306                let is_assembly = document["features"].as_array().is_some_and(|features| {
307                    features
308                        .iter()
309                        .any(|f| matches!(f["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT")))
310                });
311                engine.settings.workbench =
312                    if is_assembly { "assembly" } else { "modeling" }.into();
313            }
314            let mut doc = Document::new(engine);
315            doc.set_name(source.clone());
316            doc.mark_clean();
317            Ok(doc)
318        };
319        let (hosted, part_id) = match (mode, existing) {
320            (WorkPartMode::NewTab, Some(index)) => {
321                if !self.open[index].access().is_editable() {
322                    return Err("the part is read-only".into());
323                }
324                let id = self.open[index].id();
325                self.activate(index);
326                (None, id)
327            }
328            (WorkPartMode::NewTab, None) => {
329                let doc = load(self).inspect_err(|_| self.install_active_library())?;
330                let id = doc.id();
331                self.open_document(doc);
332                (None, id)
333            }
334            (WorkPartMode::InPlace, _) => {
335                let doc = load(self).inspect_err(|_| self.install_active_library())?;
336                let id = doc.id();
337                (Some(Box::new(doc)), id)
338            }
339        };
340        let mut session = WorkPart {
341            assembly_id,
342            part_id,
343            hosted,
344            name: part_path.last().cloned().unwrap_or_default(),
345            component_path: component_path.into(),
346            part_path,
347            source,
348            world,
349            pushed: Vec::new(),
350            redo: Vec::new(),
351            seen: None,
352            context_seen: None,
353            problems: Vec::new(),
354            pushes: 0,
355            no_coalesce: false,
356            error: None,
357            checkout: CheckoutOffer::default(),
358        };
359        let host_key = edit_key(&self.open[self.active_host_index(&session)].engine);
360        session.context_seen = Some(host_key);
361        self.work_part = Some(session);
362        let part = self.work_engine_mut().expect("work part engine");
363        part.context_scene = context;
364        part.sync_context_highlight();
365        part.camera = camera;
366        part.clear_selection();
367        part.dirty = true;
368        let baseline = Pushed {
369            signature: super::signature(part),
370            undo_top: part.history.undo_top(),
371            capture: None,
372        };
373        let seen = edit_key(part);
374        let session = self.work_part.as_mut().unwrap();
375        session.pushed.push(baseline);
376        session.seen = Some(seen);
377        self.install_active_library();
378        Ok(())
379    }
380
381    fn active_host_index(&self, session: &WorkPart) -> usize {
382        self.open
383            .iter()
384            .position(|d| d.id() == session.assembly_id)
385            .unwrap_or(self.active)
386    }
387
388    /// The hosted part document, while a Work part is edited in place.
389    pub(super) fn hosted(&self) -> Option<&Document> {
390        self.work_part.as_ref().and_then(|s| s.hosted.as_deref())
391    }
392
393    pub(super) fn hosted_mut(&mut self) -> Option<&mut Document> {
394        self.work_part.as_mut().and_then(|s| s.hosted.as_deref_mut())
395    }
396
397    fn work_engine_mut(&mut self) -> Option<&mut EngineState> {
398        let session = self.work_part.as_mut()?;
399        if let Some(doc) = session.hosted.as_deref_mut() {
400            return Some(&mut doc.engine);
401        }
402        let id = session.part_id;
403        self.open.iter_mut().find(|d| d.id() == id).map(|d| &mut d.engine)
404    }
405
406    fn work_engine(&self) -> Option<&EngineState> {
407        let session = self.work_part.as_ref()?;
408        if let Some(doc) = session.hosted.as_deref() {
409            return Some(&doc.engine);
410        }
411        self.open.iter().find(|d| d.id() == session.part_id).map(|d| &d.engine)
412    }
413
414    /// Whether a Work part is being edited in place in the active tab.
415    pub fn work_part_in_place(&self) -> bool {
416        self.hosted().is_some()
417    }
418
419    /// The assembly engine of the active Work part session (the tab's own
420    /// engine while in place).
421    pub fn work_part_assembly(&self) -> Option<&EngineState> {
422        let session = self.work_part.as_ref()?;
423        self.open.iter().find(|d| d.id() == session.assembly_id).map(|d| &d.engine)
424    }
425
426    pub fn work_part_assembly_mut(&mut self) -> Option<&mut EngineState> {
427        let id = self.work_part.as_ref()?.assembly_id;
428        self.open.iter_mut().find(|d| d.id() == id).map(|d| &mut d.engine)
429    }
430
431    /// The component path being edited, if any.
432    pub fn work_part_path(&self) -> Option<&str> {
433        self.work_part.as_ref().map(|s| s.component_path.as_str())
434    }
435
436    /// Push the part's settled state into the assembly and keep the context
437    /// current. Called every frame after the pumps ([`Documents::pump_all`]).
438    pub(super) fn sync_work_part(&mut self) {
439        let Some(session) = self.work_part.as_ref() else {
440            return;
441        };
442        let Some(host) = self.open.iter().position(|d| d.id() == session.assembly_id) else {
443            return;
444        };
445        let Some(part) = self.work_engine() else {
446            return;
447        };
448        let busy = part.run_pending()
449            || part.sketch_mode()
450            || part.sketch3d_mode()
451            || part.ref_select_active();
452        let key = edit_key(part);
453        if !busy && Some(key) != session.seen && !self.open[host].engine.run_pending() {
454            // Coalesce: while the assembly is still running the previous push,
455            // `seen` stays put so the NEWEST part state goes next frame.
456            let _ = self.push_work_part(false);
457        }
458        self.refresh_context();
459    }
460
461    /// Push the work part's current state, if it differs from the last pushed
462    /// one. `force` pushes even while the assembly is running (Return).
463    fn push_work_part(&mut self, force: bool) -> Result<(), String> {
464        let session = self.work_part.as_ref().ok_or("no Work part is active")?;
465        let host = self
466            .open
467            .iter()
468            .position(|d| d.id() == session.assembly_id)
469            .ok_or("assembly tab is missing")?;
470        if !force && self.open[host].engine.run_pending() {
471            return Ok(());
472        }
473        let part = self.work_engine().ok_or("part document is missing")?;
474        let key = edit_key(part);
475        let signature = super::signature(part);
476        let undo_top = part.history.undo_top();
477        let edited: Value =
478            serde_json::from_str(&part.history_request_json()).map_err(|e| e.to_string())?;
479        let session = self.work_part.as_mut().unwrap();
480        let previous_seen = session.seen;
481        session.seen = Some(key);
482        if session.pushed.last().is_some_and(|p| p.signature == signature) {
483            return Ok(());
484        }
485        let pushed_len = session.pushed.len();
486        // A part undo back to the previous pushed state: undo the assembly step.
487        if pushed_len >= 2 && session.pushed[pushed_len - 2].signature == signature {
488            let step = session.pushed.pop().unwrap();
489            session.redo.push(step);
490            self.open[host].engine.undo();
491            self.install_active_library();
492            self.work_part.as_mut().unwrap().context_seen = None;
493            return Ok(());
494        }
495        // A part redo to the next pushed state: redo the assembly step.
496        if session.redo.last().is_some_and(|p| p.signature == signature) {
497            let step = session.redo.pop().unwrap();
498            session.pushed.push(step);
499            self.open[host].engine.redo();
500            self.install_active_library();
501            self.work_part.as_mut().unwrap().context_seen = None;
502            return Ok(());
503        }
504        // The same part undo step as the last push (a coalesced drag): replace
505        // that assembly step instead of stacking another.
506        let replace = pushed_len >= 2
507            && undo_top.is_some()
508            && !session.no_coalesce
509            && session.pushed.last().is_some_and(|p| p.undo_top == undo_top);
510        if !self.open[host].access().is_editable() {
511            let session = self.work_part.as_mut().unwrap();
512            session.error = Some("the assembly is read-only; part edits are not applied".into());
513            return Err("the assembly is read-only".into());
514        }
515        // The mates are captured off the host's main-side session. A
516        // background runner hands it over as a copy that lands a frame or so
517        // after it is asked for — never by replaying the whole assembly here —
518        // so until then nothing is pushed and the same state is tried again
519        // next frame (`seen` goes back). The host's library goes in first: an
520        // inline runner may replay, and replays against it.
521        super::install_library_of(&self.open[host]);
522        let ready = self.open[host].engine.assembly_session_ready();
523        self.install_active_library();
524        if !ready {
525            self.work_part.as_mut().unwrap().seen = previous_seen;
526            return if force { Err(brep_render::engine_state::ASSEMBLY_SESSION_PENDING.into()) } else { Ok(()) };
527        }
528        let session = self.work_part.as_mut().unwrap();
529        // Replacing a coalesced step: its capture is reused, so the undo
530        // runs nothing (the commit's run is the one the assembly needs); the
531        // replay a capture would take with that run in flight goes too.
532        let reused = if replace { session.pushed.last().and_then(|p| p.capture.clone()) } else { None };
533        if replace {
534            if reused.is_some() {
535                self.open[host].engine.undo_before_edit();
536            } else {
537                self.open[host].engine.undo();
538            }
539        }
540        let path = session.part_path.clone();
541        let source = session.source.clone();
542        let mut assembly_document: Value =
543            serde_json::from_str(&self.open[host].engine.history_request_json())
544                .map_err(|e| e.to_string())?;
545        let mut notes = Vec::new();
546        let signatures_before = library_signatures(&assembly_document);
547        let result = refresh_parts(&mut assembly_document, &path, source.as_deref(), &edited, &mut notes)
548            .and_then(|changed| {
549                if changed {
550                    Ok(())
551                } else {
552                    Err("the assembly no longer holds this part's definition".to_string())
553                }
554            })
555            .and_then(|()| {
556                // Mates on the edited parts' occurrences are checked once the
557                // run lands: a face the edit renamed on the same plane is
558                // re-attached, anything ambiguous is held for Repair.
559                let after = library_signatures(&assembly_document);
560                let parts: Vec<String> =
561                    after.iter().filter(|(name, sig)| signatures_before.get(*name) != Some(*sig)).map(|(name, _)| name.clone()).collect();
562                // The capture reads the HOST's assembly session, replayed on
563                // this thread: with the Work part active the kernel store holds
564                // the part's library, and the last replay may be another
565                // document's, so both are put back to the host's first.
566                super::install_library_of(&self.open[host]);
567                let engine = &mut self.open[host].engine;
568                let capture = match reused {
569                    Some((reused_parts, capture)) if reused_parts == parts => capture,
570                    stale => {
571                        // Other parts this time: capture from the undone
572                        // document, run as the plain undo would have.
573                        if stale.is_some() {
574                            engine.rebuild_current_history();
575                        }
576                        engine.capture_part_edit(&engine.components_of_parts(&parts))?
577                    }
578                };
579                let kept = (parts.clone(), capture.clone());
580                engine.commit_part_edit(capture, assembly_document.clone(), &parts).map(|()| kept)
581            });
582        self.install_active_library();
583        let session = self.work_part.as_mut().unwrap();
584        match result {
585            Ok(capture) => {
586                if replace {
587                    session.pushed.pop();
588                }
589                session.pushed.push(Pushed { signature, undo_top, capture: Some(capture) });
590                session.redo.clear();
591                session.no_coalesce = false;
592                session.pushes += 1;
593                session.error = None;
594                session.context_seen = None;
595                for note in notes {
596                    self.open[host].engine.push_notice(format!("Work part: {note}"));
597                }
598                Ok(())
599            }
600            Err(error) => {
601                if replace {
602                    self.open[host].engine.redo();
603                    self.install_active_library();
604                }
605                let session = self.work_part.as_mut().unwrap();
606                if error == brep_render::engine_state::ASSEMBLY_SESSION_PENDING {
607                    // Only a coalesced step whose capture had to come from the
608                    // undone document's run gets here (on a background runner
609                    // that run is not in yet): push it as a step of its own
610                    // next frame, captured off the session already here.
611                    session.seen = previous_seen;
612                    session.no_coalesce = true;
613                    return if force { Err(error) } else { Ok(()) };
614                }
615                session.error = Some(error.clone());
616                Err(error)
617            }
618        }
619    }
620
621    /// Whether the Work part session still owes the assembly an update: a
622    /// settled part state not pushed yet, an assembly run in flight, or a
623    /// context not rebuilt from the assembly's latest run.
624    pub fn work_part_settling(&self) -> bool {
625        // Going up to a sub-assembly: it begins when the assembly's run lands.
626        if self.work_part_next.is_some() {
627            return true;
628        }
629        let Some(session) = self.work_part.as_ref() else {
630            return false;
631        };
632        let (Some(part), Some(host)) = (self.work_engine(), self.work_part_assembly()) else {
633            return false;
634        };
635        let editing = part.sketch_mode() || part.sketch3d_mode() || part.ref_select_active();
636        host.run_pending()
637            || (!editing && Some(edit_key(part)) != session.seen && session.error.is_none())
638            || session.context_seen != Some(edit_key(host))
639    }
640
641    /// The source files the ACTIVE tab's next Save writes besides itself:
642    /// every owned document its edits changed ([`super::owned_save`]).
643    pub fn work_part_modified_sources(&self) -> Vec<String> {
644        self.owned_modified_keys()
645    }
646
647    /// Push the Work part's latest state now, even while the assembly is still
648    /// running (Save and the document readback call this). A refusal is kept
649    /// for the bar; the part edits stay in the Work part.
650    pub fn flush_work_part(&mut self) {
651        if self.work_part.is_some() {
652            let _ = self.push_work_part(true);
653        }
654    }
655
656    /// Rebuild the context scene once the assembly's latest run has landed.
657    fn refresh_context(&mut self) {
658        let Some(session) = self.work_part.as_ref() else {
659            return;
660        };
661        let Some(host) = self.open.iter().position(|d| d.id() == session.assembly_id) else {
662            return;
663        };
664        let engine = &self.open[host].engine;
665        if engine.run_pending() || session.context_seen == Some(edit_key(engine)) {
666            return;
667        }
668        let key = edit_key(engine);
669        let world = serde_json::from_str::<Value>(&engine.history_request_json())
670            .ok()
671            .and_then(|document| resolve_occurrence(engine, &document, &session.component_path).ok())
672            .map(|(world, ..)| world)
673            .unwrap_or(session.world);
674        let previous = self.work_engine().map(|part| &part.context_scene);
675        let context = context_scene(engine, &session.component_path, world, previous.unwrap_or(&RenderScene::new()));
676        let mut statuses = self.open[host].engine.assembly_statuses_value();
677        let mut problems: Vec<(String, String, String, String)> = statuses
678            .as_array_mut()
679            .map(|rows| {
680                rows.iter()
681                    .filter(|row| {
682                        let status = row["status"].as_str().unwrap_or("");
683                        row["enabled"].as_bool() != Some(false)
684                            && !matches!(status, "satisfied" | "disabled" | "over" | "")
685                    })
686                    .map(|row| {
687                        let text = |k: &str| row[k].as_str().unwrap_or("").to_string();
688                        (text("id"), text("type"), text("status"), text("message"))
689                    })
690                    .collect()
691            })
692            .unwrap_or_default();
693        // A mate the push held for Repair is disabled, so its status no longer
694        // says so: it is a problem all the same until it is repaired.
695        for held in self.open[host].engine.replace_unresolved().as_array().into_iter().flatten() {
696            let id = held["id"].as_str().unwrap_or("").to_string();
697            if !problems.iter().any(|(known, ..)| *known == id) {
698                let message = "held for Repair: the face or edge it used is gone".to_string();
699                problems.push((id, held["type"].as_str().unwrap_or("").to_string(), "held".into(), message));
700            }
701        }
702        let moved = world != session.world;
703        let session = self.work_part.as_mut().unwrap();
704        session.context_seen = Some(key);
705        session.problems = problems;
706        if moved {
707            // The work occurrence itself moved (a mate re-posed it): keep the
708            // view where it was in the assembly by re-mapping the camera too.
709            let delta = multiply(inverse_rigid(world), session.world);
710            session.world = world;
711            if let Some(part) = self.work_engine_mut() {
712                part.camera.eye = point_at(delta, part.camera.eye);
713                part.camera.target = point_at(delta, part.camera.target);
714                part.camera.up = vector_at(delta, part.camera.up);
715            }
716        }
717        if let Some(part) = self.work_engine_mut() {
718            part.context_scene = context;
719            part.sync_context_highlight();
720            part.dirty = true;
721        }
722    }
723
724    /// Called before leaving the work context, including ordinary tab changes.
725    pub(super) fn finish_work_part(&mut self) -> Result<(), String> {
726        let Some(session) = &self.work_part else {
727            return Ok(());
728        };
729        let assembly = self
730            .open
731            .iter()
732            .position(|d| d.id() == session.assembly_id)
733            .ok_or("assembly tab is missing")?;
734        if self.work_engine().is_none() {
735            self.work_part = None;
736            return Err("part document is missing".into());
737        }
738        {
739            let part = self.work_engine_mut().unwrap();
740            if part.ref_select_active() {
741                part.cancel_ref_select();
742            }
743            // Sketch edits are already kept in the document. Finish the editor
744            // so a standalone tab does not retain context references.
745            if part.sketch_mode() {
746                part.exit_sketch_mode(true);
747            }
748            if part.sketch3d_mode() {
749                part.exit_sketch3d_mode(true);
750            }
751        }
752        let part = self.work_engine().unwrap();
753        let changed = self
754            .work_part
755            .as_ref()
756            .and_then(|s| s.pushed.last())
757            .is_none_or(|p| p.signature != super::signature(part));
758        if changed {
759            if !self.open[assembly].access().is_editable() {
760                return Err("assembly is read-only; part edits remain open".into());
761            }
762            self.push_work_part(true).map_err(|error| {
763                format!("{error}; edits remain in the Work part")
764            })?;
765        }
766        let session = self.work_part.take().unwrap();
767        let world = session.world;
768        let camera = match &session.hosted {
769            Some(doc) => doc.engine.camera.clone(),
770            None => {
771                let part = self.open.iter_mut().find(|d| d.id() == session.part_id).unwrap();
772                part.engine.context_scene.clear();
773                part.engine.sync_context_highlight();
774                part.engine.dirty = true;
775                part.engine.camera.clone()
776            }
777        };
778        let host = &mut self.open[assembly].engine;
779        host.camera.eye = point_at(world, camera.eye);
780        host.camera.target = point_at(world, camera.target);
781        host.camera.up = vector_at(world, camera.up);
782        host.camera.projection = camera.projection;
783        host.dirty = true;
784        self.install_active_library();
785        Ok(())
786    }
787
788    /// Go up the Work part's path to `depth`: 0 is the assembly itself, `k`
789    /// the occurrence of its first `k` components (a sub-assembly above the
790    /// part). The part's edits are pushed first, and the sub-assembly becomes
791    /// the Work part once that update has landed, so it is placed where the
792    /// solved assembly puts it (`Self::begin_next_work_part`).
793    pub fn work_part_up_to(&mut self, depth: usize) -> Result<(), String> {
794        let session = self.work_part.as_ref().ok_or("no Work part is active")?;
795        let ids: Vec<&str> = session.component_path.split(':').collect();
796        if depth >= ids.len() {
797            return Ok(());
798        }
799        let next = (
800            session.assembly_id,
801            ids[..depth].join(":"),
802            if session.hosted.is_some() { WorkPartMode::InPlace } else { WorkPartMode::NewTab },
803        );
804        self.return_to_assembly()?;
805        if depth > 0 {
806            self.work_part_next = Some(next);
807            self.begin_next_work_part();
808        }
809        Ok(())
810    }
811
812    /// One level up: the sub-assembly holding the Work part, or the assembly.
813    pub fn work_part_up(&mut self) -> Result<(), String> {
814        let depth = self.work_part.as_ref().ok_or("no Work part is active")?.part_path.len();
815        self.work_part_up_to(depth.saturating_sub(1))
816    }
817
818    /// Begin the Work part [`Self::work_part_up_to`] left waiting, once its
819    /// assembly is the active tab with no run in flight. Dropped if the user
820    /// moved to another tab or chose another Work part meanwhile.
821    pub(super) fn begin_next_work_part(&mut self) {
822        let Some((assembly, _, _)) = &self.work_part_next else {
823            return;
824        };
825        if self.work_part.is_some() || self.active_id() != *assembly {
826            self.work_part_next = None;
827            return;
828        }
829        if self.engine().run_pending() {
830            return;
831        }
832        let (_, path, mode) = self.work_part_next.take().unwrap();
833        if let Err(error) = self.begin_work_part_as(&path, mode) {
834            self.engine_mut().push_notice(format!("Work part: {error}"));
835        }
836    }
837
838    pub fn return_to_assembly(&mut self) -> Result<(), String> {
839        let id = self
840            .work_part
841            .as_ref()
842            .ok_or("no Work part is active")?
843            .assembly_id;
844        self.finish_work_part()?;
845        let index = self
846            .open
847            .iter()
848            .position(|d| d.id() == id)
849            .ok_or("assembly tab is missing")?;
850        self.activate(index);
851        Ok(())
852    }
853
854    /// The Work part session as automation state (`null` when inactive).
855    pub fn work_part_state(&self) -> Value {
856        let Some(s) = self.work_part.as_ref() else {
857            return Value::Null;
858        };
859        let assembly = self.work_part_assembly();
860        let part = self.work_engine();
861        // Context solids in ASSEMBLY coordinates, so a script can read where
862        // the other components are after an update.
863        // Rebuilt only when the host scene changed (a solid's revision or
864        // visibility, or the set): built every frame it cost 35-58 ms at 500
865        // parts, about half of a Work part edit's measured time.
866        let context: Value = assembly
867            .map(|engine| {
868                let fingerprint = engine.scene.solids().iter().fold(engine.scene.solids().len() as u64, |h, solid| {
869                    (h ^ solid.revision ^ u64::from(solid.visible)).wrapping_mul(0x100_0000_01b3)
870                });
871                let key = (s.component_path.clone(), fingerprint);
872                if let Some((cached, value)) = self.work_part_context.borrow().as_ref() {
873                    if *cached == key {
874                        return value.clone();
875                    }
876                }
877                let prefix = format!("{}:", s.component_path);
878                let map: serde_json::Map<String, Value> = engine
879                    .scene
880                    .solids()
881                    .iter()
882                    .filter(|solid| solid.visible && !solid.name.starts_with(&prefix))
883                    .map(|solid| {
884                        (solid.name.clone(), serde_json::json!({"min": solid.bbox.min, "max": solid.bbox.max}))
885                    })
886                    .collect();
887                let value = Value::Object(map);
888                *self.work_part_context.borrow_mut() = Some((key, value.clone()));
889                value
890            })
891            .unwrap_or_else(|| Value::Object(Default::default()));
892        let [r, g, b, _] = brep_render::render::WORK_PART_CONTEXT_RGBA;
893        let (shown, alpha) = part.map_or((true, 0.0), |engine| engine.context_display());
894        let style = serde_json::json!({"rgba": [r, g, b, alpha], "alpha": alpha, "shown": shown, "depthWrite": false, "dimmed": alpha < 1.0});
895        serde_json::json!({
896            "name": s.name,
897            "componentPath": s.component_path,
898            "partPath": s.part_path,
899            "mode": if s.hosted.is_some() { "inPlace" } else { "newTab" },
900            "contextSolids": part.map_or(0, |engine| engine.context_scene.solids().len()),
901            "contextSelectable": true,
902            "contextSelection": part.map_or(serde_json::Value::Null, |engine| engine.context_selection_json()),
903            "contextHover": part.map_or(serde_json::Value::Null, |engine| engine.context_hover_json()),
904            "contextStyle": style,
905            "context": context,
906            "modifiedSources": self.owned_modified_keys_of(s.assembly_id),
907            "assemblyId": s.assembly_id,
908            "partId": s.part_id,
909            "pushes": s.pushes,
910            "pending": assembly.is_some_and(EngineState::run_pending),
911            "undoSteps": s.pushed.len().saturating_sub(1),
912            "redoSteps": s.redo.len(),
913            "error": s.error,
914            "constraintProblems": s.problems.iter().map(|(id, ty, status, message)| {
915                serde_json::json!({"id": id, "type": ty, "status": status, "message": message})
916            }).collect::<Vec<_>>(),
917        })
918    }
919
920    /// Starting to edit a PLM part in context that is not checked out to this
921    /// user: offer the checkout right there, Yes by default (owner,
922    /// 2026-10-20). Locked by someone else or not editable: said in the bar;
923    /// the edits stay in the assembly. A file store never reaches this.
924    fn offer_checkout(&mut self, ui: &mut eframe::egui::Ui, store: &dyn crate::store::ModelStore, hits: &mut Value) {
925        use eframe::egui;
926        let Some(session) = self.work_part.as_mut() else {
927            return;
928        };
929        if matches!(session.checkout, CheckoutOffer::Unasked) {
930            session.checkout = CheckoutOffer::Done(None);
931            let key = session.source.clone().unwrap_or_default();
932            if let (Some(_), Some((part, revision))) = (store.plm_client(), crate::plm::bom::revision_of_document(&key)) {
933                session.checkout = match store.plm_revision(&key) {
934                    Some(entry) if entry.editable && entry.locked_by_me => CheckoutOffer::Done(None),
935                    Some(entry) if !entry.editable => CheckoutOffer::Done(Some(format!(
936                        "{key}: revision {} is {} — your edits stay in the assembly", entry.revision_label, entry.lifecycle
937                    ))),
938                    Some(entry) if entry.locked_by.is_some() => CheckoutOffer::Done(Some(format!(
939                        "{key} is checked out by {} — your edits stay in the assembly", entry.locked_by.unwrap_or_default()
940                    ))),
941                    _ => CheckoutOffer::Asking { part, revision },
942                };
943            }
944        }
945        let name = session.name.clone();
946        match &mut session.checkout {
947            CheckoutOffer::Asking { part, revision } => {
948                let (part, revision) = (part.clone(), revision.clone());
949                let mut answer = None;
950                let modal = egui::Modal::new(egui::Id::new("brep-work-part-checkout")).show(ui.ctx(), |ui| {
951                    ui.heading("Check out before editing?");
952                    ui.label(format!("{name} is not checked out to you. Check it out now, so Save can write it?"));
953                    ui.horizontal(|ui| {
954                        let yes = ui.button("Check out");
955                        hits["checkout:yes"] = serde_json::json!([yes.rect.min.x, yes.rect.min.y, yes.rect.width(), yes.rect.height()]);
956                        if yes.clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
957                            answer = Some(true);
958                        }
959                        let no = ui.button("Not now");
960                        hits["checkout:no"] = serde_json::json!([no.rect.min.x, no.rect.min.y, no.rect.width(), no.rect.height()]);
961                        if no.clicked() {
962                            answer = Some(false);
963                        }
964                    });
965                });
966                let answer = answer.or_else(|| modal.should_close().then_some(false));
967                match (answer, store.plm_client()) {
968                    (Some(true), Some(client)) => {
969                        use crate::panels::plm::PlmLifecycle;
970                        session.checkout = CheckoutOffer::Running(client.checkout(&part, &revision));
971                    }
972                    (Some(_), _) => session.checkout = CheckoutOffer::Done(Some(format!("{name} is not checked out; Save will offer it"))),
973                    (None, _) => {}
974                }
975            }
976            CheckoutOffer::Running(future) => {
977                let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
978                match std::future::Future::poll(future.as_mut(), &mut cx) {
979                    std::task::Poll::Ready(Ok(())) => {
980                        session.checkout = CheckoutOffer::Done(Some(format!("{name} is checked out to you")));
981                        store.refresh_plm_index(&[session.source.clone().unwrap_or_default()], false);
982                    }
983                    std::task::Poll::Ready(Err(error)) => {
984                        session.checkout = CheckoutOffer::Done(Some(format!("{name} could not be checked out: {error}")));
985                    }
986                    std::task::Poll::Pending => ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)),
987                }
988            }
989            CheckoutOffer::Unasked | CheckoutOffer::Done(_) => {}
990        }
991    }
992
993    pub fn show_work_part_bar(&mut self, ui: &mut eframe::egui::Ui, store: &dyn crate::store::ModelStore) {
994        // The readback walks every assembly solid: only for automation.
995        let state = crate::automation::registry::enabled().then(|| self.work_part_state());
996        let mut hits = serde_json::json!({});
997        self.offer_checkout(ui, store, &mut hits);
998        // The checkout question is a modal: the bar behind it takes no click,
999        // so its widgets are not published while it is up (a script's click on
1000        // `return` would otherwise report a hit that did nothing).
1001        let modal = self.work_part.as_ref().is_some_and(|s| matches!(s.checkout, CheckoutOffer::Asking { .. }));
1002        if let Some(session) = &self.work_part {
1003            // The breadcrumb: the assembly, each sub-assembly above the part,
1004            // the part. Every level above the part can be clicked.
1005            let assembly = self.open.iter().find(|d| d.id() == session.assembly_id).map_or_else(|| "assembly".into(), |d| d.title());
1006            let crumbs: Vec<String> = std::iter::once(assembly).chain(session.part_path.iter().cloned()).collect();
1007            let component_path = session.component_path.clone();
1008            let problems: Vec<String> = session
1009                .problems
1010                .iter()
1011                .map(|(id, ty, status, message)| {
1012                    if message.is_empty() {
1013                        format!("{id} ({ty}): {status}")
1014                    } else {
1015                        format!("{id} ({ty}): {status}, {message}")
1016                    }
1017                })
1018                .collect();
1019            let error = session.error.clone();
1020            let checkout = match &session.checkout {
1021                CheckoutOffer::Done(line) => line.clone(),
1022                CheckoutOffer::Running(_) => Some("checking out…".into()),
1023                _ => None,
1024            };
1025            let modified: Vec<String> = self.owned_modified_keys_of(session.assembly_id);
1026            let context_part = self.work_engine().and_then(|engine| engine.context_selection().map(|c| c.solid.rsplit(':').next().unwrap_or(&c.solid).to_string()));
1027            let display = self.work_engine().map(|engine| engine.context_display());
1028            let mut new_display = display;
1029            // Some(true): sketch on the face; Some(false): datum only.
1030            let mut context_action: Option<bool> = None;
1031            let mut finish = false;
1032            // A breadcrumb level clicked (or Up): its depth.
1033            let mut up_to: Option<usize> = None;
1034            eframe::egui::Frame::group(ui.style()).show(ui, |ui| {
1035                ui.horizontal_wrapped(|ui| {
1036                    ui.label("Work part:");
1037                    let last = crumbs.len() - 1;
1038                    for (depth, crumb) in crumbs.iter().enumerate() {
1039                        if depth > 0 {
1040                            ui.weak("›");
1041                        }
1042                        if depth == last {
1043                            ui.strong(crumb);
1044                            continue;
1045                        }
1046                        let link = ui.link(crumb).on_hover_text(if depth == 0 {
1047                            "Return to the assembly"
1048                        } else {
1049                            "Make this sub-assembly the Work part"
1050                        });
1051                        hits[format!("crumb:{depth}")] = serde_json::json!([link.rect.min.x, link.rect.min.y, link.rect.width(), link.rect.height()]);
1052                        if link.clicked() {
1053                            up_to = Some(depth);
1054                        }
1055                    }
1056                    ui.weak(format!("({component_path})"));
1057                    // Nested: one level up is the sub-assembly holding the part.
1058                    if last > 1 {
1059                        let button = ui.button("Up").on_hover_text(format!("Make {} the Work part", crumbs[last - 1]));
1060                        hits["up"] = serde_json::json!([button.rect.min.x, button.rect.min.y, button.rect.width(), button.rect.height()]);
1061                        if button.clicked() {
1062                            up_to = Some(last - 1);
1063                        }
1064                    }
1065                    let button = ui
1066                        .button("Return to assembly")
1067                        .on_hover_text("Make the assembly the work context again (Esc)");
1068                    hits["return"] = serde_json::json!([
1069                        button.rect.min.x,
1070                        button.rect.min.y,
1071                        button.rect.width(),
1072                        button.rect.height()
1073                    ]);
1074                    finish = button.clicked();
1075                    // The rest of the assembly: shown for reference (it updates
1076                    // as you edit), or hidden, and how solid it looks.
1077                    if let Some((shown, opacity)) = &mut new_display {
1078                        let toggle = ui
1079                            .checkbox(shown, "Show the rest of the assembly")
1080                            .on_hover_text("Shown for reference; it updates as you edit. Hidden, it is neither drawn nor picked");
1081                        hits["display:show"] = serde_json::json!([toggle.rect.min.x, toggle.rect.min.y, toggle.rect.width(), toggle.rect.height()]);
1082                        ui.add_enabled_ui(*shown, |ui| {
1083                            let slider = ui
1084                                .add(eframe::egui::Slider::new(opacity, 0.05..=1.0).show_value(false))
1085                                .on_hover_text("How solid the rest of the assembly looks");
1086                            hits["display:opacity"] = serde_json::json!([slider.rect.min.x, slider.rect.min.y, slider.rect.width(), slider.rect.height()]);
1087                        });
1088                    }
1089                });
1090                // A face of another part selected: what it can become in this
1091                // part (copied, never linked).
1092                if let Some(part) = &context_part {
1093                    ui.horizontal_wrapped(|ui| {
1094                        ui.label(format!("Face of {part}:"));
1095                        let button = ui.button("Sketch on this face").on_hover_text(
1096                            "A datum on this face (copied, not linked: it stays if that part moves), and a new sketch on it",
1097                        );
1098                        hits["context-sketch"] = serde_json::json!([button.rect.min.x, button.rect.min.y, button.rect.width(), button.rect.height()]);
1099                        if button.clicked() {
1100                            context_action = Some(true);
1101                        }
1102                        let button = ui.button("Datum here").on_hover_text(
1103                            "A datum on this face (copied, not linked: it stays if that part moves)",
1104                        );
1105                        hits["context-datum"] = serde_json::json!([button.rect.min.x, button.rect.min.y, button.rect.width(), button.rect.height()]);
1106                        if button.clicked() {
1107                            context_action = Some(false);
1108                        }
1109                    });
1110                }
1111                for problem in &problems {
1112                    ui.colored_label(ui.visuals().warn_fg_color, format!("Constraint {problem}"));
1113                }
1114                if !modified.is_empty() {
1115                    ui.weak(format!(
1116                        "Modified with their own files (written when the assembly is saved): {}",
1117                        modified.join(", ")
1118                    ));
1119                }
1120                if let Some(error) = &error {
1121                    ui.colored_label(ui.visuals().error_fg_color, format!("Not applied: {error}"));
1122                }
1123                if let Some(line) = &checkout {
1124                    ui.weak(line);
1125                }
1126            });
1127            let escape = ui.input(|i| i.key_pressed(eframe::egui::Key::Escape))
1128                && ui.ctx().memory(|m| m.focused().is_none())
1129                && self.work_engine().is_some_and(|engine| {
1130                    !engine.has_selection()
1131                        && engine.context_selection().is_none()
1132                        && !engine.sketch_mode()
1133                        && !engine.sketch3d_mode()
1134                        && !engine.ref_select_active()
1135                });
1136            if let (Some((shown, opacity)), true) = (new_display, new_display != display) {
1137                if let Some(engine) = self.work_engine_mut() {
1138                    engine.set_context_display(shown, opacity);
1139                }
1140            }
1141            if let Some(sketch) = context_action {
1142                if let Some(engine) = self.work_engine_mut() {
1143                    let made = if sketch { engine.sketch_on_context() } else { engine.datum_on_context() };
1144                    if let Err(error) = made {
1145                        engine.push_notice(format!("Work part: {error}"));
1146                    }
1147                }
1148            }
1149            if finish || escape {
1150                if let Err(error) = self.return_to_assembly() {
1151                    self.engine_mut().push_notice(format!("Work part: {error}"));
1152                }
1153            } else if let Some(depth) = up_to {
1154                if let Err(error) = self.work_part_up_to(depth) {
1155                    self.engine_mut().push_notice(format!("Work part: {error}"));
1156                }
1157            }
1158        }
1159        if modal {
1160            if let Some(hits) = hits.as_object_mut() {
1161                hits.retain(|key, _| key.starts_with("checkout:"));
1162            }
1163        }
1164        if let Some(state) = state {
1165            crate::automation::registry::publish(
1166                "__brepWorkPart",
1167                "active Work part session: component path, part path, mode (inPlace|newTab), context render state, assembly context solids (assembly coordinates), pushes, undo coupling, constraint problems; null when inactive",
1168                &state.to_string(),
1169            );
1170            crate::automation::registry::publish(
1171                "__brepWorkPartHit",
1172                "Work part controls: return, crumb:<depth> (the breadcrumb: 0 the assembly, then each sub-assembly above the part), up (nested parts), and checkout:yes / checkout:no while the checkout offer is shown",
1173                &hits.to_string(),
1174            );
1175        }
1176    }
1177}
1178
1179/// The assembly's parts-library entries → their `sourceSignature`.
1180fn library_signatures(document: &Value) -> std::collections::BTreeMap<String, String> {
1181    document["partsLibrary"]
1182        .as_object()
1183        .into_iter()
1184        .flatten()
1185        .map(|(name, entry)| (name.clone(), entry["sourceSignature"].as_str().unwrap_or_default().to_string()))
1186        .collect()
1187}
1188
1189/// Refresh the selected definition and any copies with the same source identity.
1190/// Invalidate every changed ancestor snapshot so nested assemblies rebuild too.
1191pub(crate) fn refresh_parts(
1192    owner: &mut Value,
1193    path: &[String],
1194    source: Option<&str>,
1195    edited: &Value,
1196    notes: &mut Vec<String>,
1197) -> Result<bool, String> {
1198    let names: Vec<String> = owner["partsLibrary"]
1199        .as_object()
1200        .map(|entries| entries.keys().cloned().collect())
1201        .unwrap_or_default();
1202    let mut changed = false;
1203    for name in names {
1204        let entry = &owner["partsLibrary"][&name];
1205        let on_path = path.first() == Some(&name);
1206        let target = (on_path && path.len() == 1)
1207            || source.is_some_and(|s| entry["sourceKey"].as_str() == Some(s));
1208        let tail = if on_path { &path[1..] } else { &[] };
1209        // A definition that holds no copy of the part is left as it is, without
1210        // the copy of it a refresh would make and throw away (on l500 most of
1211        // each module, at every depth).
1212        if !target && !holds_part(&entry["document"], tail, source) {
1213            continue;
1214        }
1215        let mut child = entry["document"].clone();
1216        let updated = if target {
1217            child = edited.clone();
1218            true
1219        } else {
1220            refresh_parts(&mut child, tail, source, edited, notes)?
1221        };
1222        if updated {
1223            notes.extend(crate::panels::parts_library::refresh_library_entry_value(owner, &name, child)?);
1224            changed = true;
1225        }
1226    }
1227    Ok(changed)
1228}
1229
1230/// Whether `owner`'s library holds, at any depth, an entry [`refresh_parts`]
1231/// would replace: the one at the end of `path`, or one with `source`.
1232fn holds_part(owner: &Value, path: &[String], source: Option<&str>) -> bool {
1233    owner["partsLibrary"].as_object().into_iter().flatten().any(|(name, entry)| {
1234        let on_path = path.first() == Some(name);
1235        (on_path && path.len() == 1)
1236            || source.is_some_and(|s| entry["sourceKey"].as_str() == Some(s))
1237            || holds_part(&entry["document"], if on_path { &path[1..] } else { &[] }, source)
1238    })
1239}
1240
1241fn component_pose(document: &Value, transform: &Value) -> Result<Matrix, String> {
1242    let read = |field: &str| -> Result<[f64; 3], String> {
1243        let mut out = [0.; 3];
1244        for (i, key) in ["x", "y", "z"].iter().enumerate() {
1245            let value = if transform[field].is_object() {
1246                &transform[field][*key]
1247            } else {
1248                &transform[field][i]
1249            };
1250            out[i] = match value {
1251                Value::Null => 0.,
1252                Value::Number(n) => n.as_f64().ok_or("invalid component pose")?,
1253                Value::String(s) => brep_kernel::eval_expression(
1254                    document["expressions"].as_str().unwrap_or(""),
1255                    &document["configurator"],
1256                    s,
1257                )?,
1258                _ => return Err("invalid component pose".into()),
1259            };
1260            if !out[i].is_finite() {
1261                return Err("non-finite component pose".into());
1262            }
1263        }
1264        Ok(out)
1265    };
1266    let t = read("translate")?;
1267    let r = read("rotateEulerDeg")?.map(f64::to_radians);
1268    let (a, b) = (r[0].cos(), r[0].sin());
1269    let (c, d) = (r[1].cos(), r[1].sin());
1270    let (e, f) = (r[2].cos(), r[2].sin());
1271    Ok([
1272        c * e,
1273        -c * f,
1274        d,
1275        t[0],
1276        a * f + b * e * d,
1277        a * e - b * f * d,
1278        -b * c,
1279        t[1],
1280        b * f - a * e * d,
1281        b * e + a * f * d,
1282        a * c,
1283        t[2],
1284        0.,
1285        0.,
1286        0.,
1287        1.,
1288    ])
1289}
1290fn multiply(a: Matrix, b: Matrix) -> Matrix {
1291    brep_render::geometry3d::mat4_mul_row_major(&a, &b)
1292}
1293fn inverse_rigid(m: Matrix) -> Matrix {
1294    brep_render::geometry3d::mat4_rigid_inverse(&m)
1295}
1296fn vector_at(m: Matrix, p: [f64; 3]) -> [f64; 3] {
1297    std::array::from_fn(|r| (0..3).map(|k| m[r * 4 + k] * p[k]).sum())
1298}
1299fn point_at(m: Matrix, p: [f64; 3]) -> [f64; 3] {
1300    let v = vector_at(m, p);
1301    std::array::from_fn(|r| v[r] + m[r * 4 + 3])
1302}
1303
1304pub static HIT_KEYS: &[crate::automation::hit_keys::HitKeyDoc] =
1305    &[crate::automation::hit_keys::HitKeyDoc {
1306        panel: "workpart",
1307        prefix: "return",
1308        meaning: "return to assembly and apply Work part edits",
1309        command: None,
1310    },
1311    crate::automation::hit_keys::HitKeyDoc {
1312        panel: "workpart",
1313        prefix: "checkout:",
1314        meaning: "the offer to check out a PLM part made the Work part: checkout:yes (default), checkout:no",
1315        command: None,
1316    },
1317    crate::automation::hit_keys::HitKeyDoc {
1318        panel: "workpart",
1319        prefix: "context-",
1320        meaning: "a face of another part selected (context): context-sketch (a datum on it, copied not linked, and a new sketch there), context-datum (the datum only)",
1321        command: None,
1322    },
1323    crate::automation::hit_keys::HitKeyDoc {
1324        panel: "workpart",
1325        prefix: "display:",
1326        meaning: "the rest of the assembly (context): display:show (show/hide it), display:opacity (its opacity slider)",
1327        command: None,
1328    },
1329    crate::automation::hit_keys::HitKeyDoc {
1330        panel: "workpart",
1331        prefix: "crumb:",
1332        meaning: "the Work part breadcrumb: crumb:0 returns to the assembly, crumb:<k> makes the k-th sub-assembly above the part the Work part",
1333        command: None,
1334    },
1335    crate::automation::hit_keys::HitKeyDoc {
1336        panel: "workpart",
1337        prefix: "up",
1338        meaning: "a nested Work part: make the sub-assembly holding it the Work part",
1339        command: None,
1340    }];
1341