Skip to main content

brep_app/panels/
replace_component.rs

1//! REPLACE COMPONENT, the app side: what a replacement can be (a stored
2//! part, or a part the assembly already carries), which occurrences a
3//! "Replace all instances" covers, and the one door the menu, the summary and
4//! the automation command share. The engine does the swap and the mate
5//! classification (`brep_render::engine_state::replace_component`).
6
7use brep_render::engine_state::{document_signature, ComponentInsert, EngineState, RefSelectTarget};
8use eframe::egui;
9
10use crate::automation::hit_keys::HitKeyDoc;
11use crate::store::{model_display_name, ModelStore};
12
13/// The parts-library name a stored source takes: a PLM revision is named
14/// after its part (`sub-b`, from the store's index), not after its key's
15/// last segment, which is the revision label (`B`); a file by its name.
16fn stored_display_name(store: &dyn ModelStore, name: &str) -> String {
17    crate::plm::bom::revision_of_document(name)
18        .and_then(|(part, revision)| store.plm_revision(&crate::plm::identity::document_key(&part, &revision)))
19        .map(|row| row.part_name)
20        .filter(|part_name| !part_name.is_empty())
21        .unwrap_or_else(|| model_display_name(name))
22}
23
24/// What the occurrence is replaced WITH.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum ReplaceSource {
27    /// A part document in the store, by its identity (as Insert component
28    /// names it).
29    Stored(String),
30    /// A parts-library entry the assembly already carries.
31    Library(String),
32}
33
34/// Every ACOMP occurrence that shows the same part as `component_id`
35/// (itself included), in history order — the "Replace all instances of
36/// `<part>`" set.
37pub fn instances_of(engine: &EngineState, component_id: &str) -> Vec<String> {
38    let Some(part) = engine.component_info(component_id).map(|info| info.part_name) else {
39        return Vec::new();
40    };
41    (0..engine.history_len())
42        .filter_map(|index| engine.feature_id_at(index))
43        .filter(|id| engine.component_info(id).is_some_and(|info| info.part_name == part))
44        .collect()
45}
46
47/// A replace edits the assembly, and a Work part edited in context couples its
48/// part's undo to the assembly's: a part undo after the replace would undo the
49/// REPLACE, and a push meant for the old part would land on whatever the
50/// occurrence shows now. So when the active assembly hosts a Work part
51/// session, the replace first finishes it (Return to assembly: its edits are
52/// kept) and says so. Returns that line, or `None` when no session was open.
53pub fn finish_work_part_for_replace(docs: &mut crate::document::Documents) -> Result<Option<String>, String> {
54    let Some(path) = docs.work_part_path().map(str::to_string) else { return Ok(None) };
55    let hosted_here = docs.work_part_assembly().is_some_and(|host| std::ptr::eq(host, docs.tab_engine()));
56    if !hosted_here {
57        return Ok(None);
58    }
59    docs.return_to_assembly()?;
60    let line = format!("Replace: the Work part {path} was finished first (its edits are kept); the replace edits the assembly.");
61    docs.engine_mut().push_notice_as(brep_render::engine_state::NoticeSeverity::Info, line.clone());
62    Ok(Some(line))
63}
64
65/// What a Pattern Component makes of replacing `seed`: opened on one of its
66/// instances (`instance`: the instance id, its pattern and number), why the
67/// chooser shows the seed; else how many instances follow it. `None` when no
68/// pattern is seeded by it.
69pub fn pattern_line(engine: &EngineState, seed: &str, instance: Option<&(String, String, i64)>) -> Option<String> {
70    let mut follow: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
71    for id in engine.pattern_instance_ids() {
72        if let Some((pattern, s, _)) = brep_render::brep_kernel::pattern_component_instance(&id) {
73            if s == seed {
74                *follow.entry(pattern).or_default() += 1;
75            }
76        }
77    }
78    if let Some((id, pattern, n)) = instance {
79        let places = follow.get(pattern).copied().unwrap_or(0) + 1;
80        return Some(format!(
81            "{id} is instance {n} of {pattern} and follows its seed {seed}: replacing {seed} changes all {places} places."
82        ));
83    }
84    (!follow.is_empty()).then(|| {
85        let parts: Vec<String> = follow.iter().map(|(pattern, count)| format!("{count} in {pattern}")).collect();
86        format!("Its pattern instances follow it ({}).", parts.join(", "))
87    })
88}
89
90/// How the replace compares identities for LINEAGE: the store's own
91/// spelling, and, in a PLM session, every revision of one PLM part as that
92/// part (`plm-part:<id>`): replacing revision A with revision C of the same
93/// part keeps the mates by name, as a variation of the same part should.
94fn lineage_canonicalizer(store: &dyn ModelStore) -> impl Fn(&str) -> String {
95    let canonicalize = store.canonicalizer();
96    let plm = store.plm_session().is_some();
97    move |key: &str| lineage_key(key, plm, &*canonicalize)
98}
99
100/// One identity as lineage compares it (see [`lineage_canonicalizer`]).
101fn lineage_key(key: &str, plm: bool, canonicalize: &dyn Fn(&str) -> String) -> String {
102    match plm.then(|| crate::panels::plm_host::revision_of(key)).flatten() {
103        Some((part, _revision)) => format!("plm-part:{part}"),
104        None => canonicalize(key),
105    }
106}
107
108/// Replace the part shown by `component_ids` with `source`. One undo step;
109/// the mates' report lands with the run (`EngineState::replace_report`).
110/// Returns the new parts-library entry name.
111pub fn replace(
112    engine: &mut EngineState,
113    store: &dyn ModelStore,
114    component_ids: &[String],
115    source: &ReplaceSource,
116) -> Result<String, String> {
117    let canonicalize = lineage_canonicalizer(store);
118    match source {
119        ReplaceSource::Library(part_name) => engine.replace_components(
120            component_ids,
121            ComponentInsert::Existing { part_name },
122            &canonicalize,
123        ),
124        ReplaceSource::Stored(name) => {
125            let contents = match crate::store::read_now(store, name) {
126                crate::store::ReadNow::Ready(contents) => contents,
127                crate::store::ReadNow::Loading => return Err(format!("'{name}' is still loading; try again")),
128                crate::store::ReadNow::Absent => return Err(format!("'{name}' not found")),
129            };
130            let display = stored_display_name(store, name);
131            engine.replace_components(
132                component_ids,
133                ComponentInsert::New {
134                    name: &display,
135                    source_key: name,
136                    source_signature: &document_signature(&contents),
137                    document_json: &contents,
138                },
139                &canonicalize,
140            )
141        }
142    }
143}
144
145// ---------------------------------------------------------------------------
146// Inside a sub-assembly: replace from the top
147// ---------------------------------------------------------------------------
148
149fn acomp_mut<'a>(document: &'a mut serde_json::Value, id: &str) -> Option<&'a mut serde_json::Value> {
150    document["features"].as_array_mut()?.iter_mut().find(|feature| {
151        matches!(feature["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT")) && feature["inputParams"]["id"].as_str() == Some(id)
152    })
153}
154
155/// Replace a part placed INSIDE a sub-assembly, from the top assembly.
156/// `path` is the occurrence path (`ACOMP3:ACOMP1`: the top occurrence, then
157/// the placement inside its definition, at any depth). The sub-assembly's
158/// definition is edited, so every placement of that sub-assembly follows,
159/// and a Save writes it into the sub-assembly's own file. With
160/// `all_instances`, every placement of the same part in that sub-assembly is
161/// replaced. Mates inside the sub-assembly are held (disabled, marked) when
162/// the parts share no lineage, exactly as at the top; the top assembly's mates
163/// on the replaced part go through the usual classification. One undo step.
164pub fn replace_nested(
165    engine: &mut EngineState,
166    store: &dyn ModelStore,
167    path: &str,
168    source: &ReplaceSource,
169    all_instances: bool,
170) -> Result<String, String> {
171    use serde_json::Value;
172    let segments: Vec<&str> = path.split(':').collect();
173    let [top, inner @ ..] = segments.as_slice() else { return Err("replace: empty path".into()) };
174    let Some((target, owners)) = inner.split_last() else {
175        return Err(format!("replace: '{path}' is not inside a sub-assembly"));
176    };
177    let library = engine.history.parts_library().clone();
178    let top_part = engine
179        .component_info(top)
180        .ok_or_else(|| format!("replace: '{top}' is not an assembly component"))?
181        .part_name;
182    // The definition chain down to the sub-assembly that places `target`.
183    let mut names = vec![top_part];
184    let mut owner = library[&names[0]].clone();
185    for id in owners {
186        let part = owner["document"]["features"]
187            .as_array()
188            .into_iter()
189            .flatten()
190            .find(|f| f["inputParams"]["id"].as_str() == Some(*id))
191            .and_then(|f| f["inputParams"]["partName"].as_str())
192            .ok_or_else(|| format!("replace: '{id}' is not placed in '{}'", names.last().unwrap()))?
193            .to_string();
194        owner = owner["document"]["partsLibrary"][&part].clone();
195        names.push(part);
196    }
197    let owner_source = owner["sourceKey"].as_str().filter(|k| !k.is_empty()).map(str::to_string);
198    let mut definition = owner["document"].clone();
199    let old_part = definition["features"]
200        .as_array()
201        .into_iter()
202        .flatten()
203        .find(|f| f["inputParams"]["id"].as_str() == Some(*target))
204        .and_then(|f| f["inputParams"]["partName"].as_str())
205        .ok_or_else(|| format!("replace: '{target}' is not placed in '{}'", names.last().unwrap()))?
206        .to_string();
207
208    // The replacement's entry, as the sub-assembly's library holds it.
209    let (display, entry) = match source {
210        ReplaceSource::Library(part) => (part.clone(), library[part].clone()),
211        ReplaceSource::Stored(name) => {
212            let contents = match crate::store::read_now(store, name) {
213                crate::store::ReadNow::Ready(contents) => contents,
214                crate::store::ReadNow::Loading => return Err(format!("'{name}' is still loading; try again")),
215                crate::store::ReadNow::Absent => return Err(format!("'{name}' not found")),
216            };
217            let document: Value = serde_json::from_str(&contents).map_err(|e| format!("'{name}': {e}"))?;
218            let entry = serde_json::json!({
219                "sourceKey": name,
220                "sourceSignature": document_signature(&contents),
221                "document": document,
222                "snapshot": "",
223            });
224            (stored_display_name(store, name), entry)
225        }
226    };
227    if !entry["document"].is_object() {
228        return Err("replace: the replacement has no part document".into());
229    }
230    let mut to = display.clone();
231    let mut n = 2;
232    while definition["partsLibrary"][&to].is_object() && definition["partsLibrary"][&to]["sourceKey"] != entry["sourceKey"] {
233        to = format!("{display} ({n})");
234        n += 1;
235    }
236    if to == old_part {
237        return Err(format!("replace: '{path}' already shows '{to}'"));
238    }
239    let canonicalize = lineage_canonicalizer(store);
240    let lineage = brep_render::engine_state::replace_component::entries_lineage(
241        &definition["partsLibrary"][&old_part],
242        &entry,
243        &canonicalize,
244    );
245
246    // Which placements: the one, or every one of the same part in there.
247    let prefix: String = segments[..segments.len() - 1].join(":");
248    let targets: Vec<String> = if all_instances {
249        definition["features"]
250            .as_array()
251            .into_iter()
252            .flatten()
253            .filter(|f| f["inputParams"]["partName"].as_str() == Some(old_part.as_str()))
254            .filter_map(|f| f["inputParams"]["id"].as_str().map(str::to_string))
255            .collect()
256    } else {
257        vec![target.to_string()]
258    };
259    if !definition["partsLibrary"].is_object() {
260        definition["partsLibrary"] = serde_json::json!({});
261    }
262    definition["partsLibrary"][&to] = entry;
263    for id in &targets {
264        if let Some(feature) = acomp_mut(&mut definition, id) {
265            feature["inputParams"]["partName"] = Value::String(to.clone());
266        }
267    }
268    // The sub-assembly's own mates on a replaced placement: held when the
269    // parts are not related (the run inside the sub-assembly would otherwise
270    // resolve colliding names), confirmed later in that sub-assembly.
271    let mut held = Vec::new();
272    if lineage.is_none() {
273        for constraint in definition["assembly"]["constraints"].as_array_mut().into_iter().flatten() {
274            let refs: Vec<String> = constraint["inputParams"]["elements"]
275                .as_array()
276                .into_iter()
277                .flatten()
278                .filter_map(Value::as_str)
279                .filter(|r| targets.iter().any(|id| *r == id.as_str() || r.starts_with(&format!("{id}:"))))
280                .map(str::to_string)
281                .collect();
282            if refs.is_empty() {
283                continue;
284            }
285            let was_enabled = constraint["enabled"].as_bool().unwrap_or(true);
286            constraint["enabled"] = Value::Bool(false);
287            if !constraint["persistentData"].is_object() {
288                constraint["persistentData"] = serde_json::json!({});
289            }
290            // Each reference's frame BEFORE the swap (read through the top
291            // assembly, in the top occurrence's frame), kept in the marker:
292            // the top window chooses and ticks suggestions from it later.
293            let namespaced: Vec<String> = refs.iter().map(|r| format!("{prefix}:{r}")).collect();
294            let pre = engine.resolve_refs(&namespaced)?;
295            constraint["persistentData"][brep_render::engine_state::replace_component::REPLACE_MARKER] = serde_json::json!({
296                "from": old_part,
297                "to": to,
298                "wasEnabled": was_enabled,
299                "refs": refs.iter().zip(pre.iter().chain(std::iter::repeat(&Value::Null))).map(|(r, pre)| serde_json::json!({
300                    "ref": r,
301                    "reason": "unconfirmed",
302                    "suggestion": { "ref": r, "basis": "same-name", "preTicked": false },
303                    "pre": pre,
304                })).collect::<Vec<_>>(),
305            });
306            held.push(constraint["inputParams"]["id"].as_str().unwrap_or("").to_string());
307        }
308    }
309
310    // ONE document edit through the Work part's refresh (every copy of the
311    // sub-assembly definition follows, ancestors rebuild).
312    let paths: Vec<String> = targets.iter().map(|id| format!("{prefix}:{id}")).collect();
313    let capture = engine.capture_replace(&paths)?;
314    let mut assembly: Value = serde_json::from_str(&engine.history_request_json()).map_err(|e| e.to_string())?;
315    let mut notes = Vec::new();
316    if !crate::document::work_part::refresh_parts(&mut assembly, &names, owner_source.as_deref(), &definition, &mut notes)? {
317        return Err("replace: the assembly no longer holds that sub-assembly".into());
318    }
319    if !held.is_empty() {
320        notes.push(format!(
321            "{} mate(s) inside '{}' are held until confirmed there: {} (make it the Work part, then Review)",
322            held.len(),
323            names.last().unwrap(),
324            held.join(", ")
325        ));
326    }
327    // A Pattern Component of that sub-assembly seeded by a replaced
328    // placement follows it, as at the top: name it, counting the instances
329    // this occurrence of the sub-assembly shows.
330    let inner_from: std::collections::BTreeMap<String, String> =
331        targets.iter().map(|id| (id.clone(), old_part.clone())).collect();
332    let mut instances: Vec<String> = engine
333        .scene
334        .solids()
335        .iter()
336        .filter_map(|solid| solid.name.strip_prefix(&format!("{prefix}:")))
337        .filter_map(|rest| rest.split(':').next())
338        .filter(|id| brep_render::brep_kernel::pattern_component_instance(id).is_some())
339        .map(str::to_string)
340        .collect();
341    instances.sort();
342    instances.dedup();
343    for note in brep_render::engine_state::replace_component::follow_pattern_seeds(&definition, &inner_from, &to, &instances) {
344        notes.push(format!("In '{}', {note}", names.last().unwrap()));
345    }
346    let from = paths.iter().map(|p| (p.clone(), old_part.clone())).collect();
347    let lineage = match lineage {
348        Some(word) => paths.iter().map(|p| (p.clone(), word)).collect(),
349        None => Default::default(),
350    };
351    engine.commit_replace(capture, assembly, from, to.clone(), lineage, notes)?;
352    Ok(to)
353}
354
355// ---------------------------------------------------------------------------
356// Held mates at every level: the top window lists, repairs and deletes them
357// ---------------------------------------------------------------------------
358
359/// Every mate a replace is holding, at every depth, as the top window lists
360/// them. A top-level mate is the engine's row. A mate inside a sub-assembly is
361/// listed per occurrence path of that sub-assembly: its id is
362/// `<occurrence path>:<constraint id>` (`ACOMP1:CONC1`) and its refs are
363/// namespaced the same way (`ACOMP1:ACOMP1:Hole_S`), with its suggestion
364/// chosen and ticked from the new part's geometry exactly as at the top.
365pub fn held_mates(engine: &mut EngineState) -> Vec<serde_json::Value> {
366    use serde_json::Value;
367    let mut rows = engine.replace_unresolved().as_array().cloned().unwrap_or_default();
368    let library = engine.history.parts_library().clone();
369    let mut nested = Vec::new();
370    for index in 0..engine.history_len() {
371        let Some(id) = engine.feature_id_at(index) else { continue };
372        let Some(info) = engine.component_info(&id) else { continue };
373        collect_held(&library[&info.part_name]["document"], &id, &info.part_name, 0, &mut nested);
374    }
375    // A mate held inside a definition is ONE mate however many times that
376    // definition is placed: listed once, at its first placement (a Repair
377    // there rewrites the definition, so every placement takes it). It was
378    // listed once per placement: 18 rows for 9 mates on l500.
379    let mut listed: std::collections::BTreeSet<(String, String)> = std::collections::BTreeSet::new();
380    nested.retain(|(_, definition, entry)| {
381        listed.insert((definition.clone(), entry["inputParams"]["id"].as_str().unwrap_or("").to_string()))
382    });
383    for (prefix, _, entry) in nested {
384        let marker = &entry["persistentData"][brep_render::engine_state::replace_component::REPLACE_MARKER];
385        let refs: Vec<Value> = marker["refs"]
386            .as_array()
387            .into_iter()
388            .flatten()
389            .map(|row| {
390                let local = row["ref"].as_str().unwrap_or("");
391                let reference = format!("{prefix}:{local}");
392                let owner = format!("{prefix}:{}", local.split(':').next().unwrap_or(local));
393                let pre = &row["pre"];
394                let suggestion = if pre["ok"] == true {
395                    // Read off the main-side session; while its copy is on the
396                    // way this frame offers no suggestion, and the window,
397                    // which lists these every frame, shows it once it lands.
398                    let candidates = engine.occurrence_entities(&owner).unwrap_or_default();
399                    match brep_render::engine_state::replace_component::classify_ref(
400                        &owner,
401                        &reference,
402                        pre,
403                        &candidates,
404                        &Default::default(),
405                        false,
406                    ) {
407                        brep_render::engine_state::replace_component::RefOutcome::Unresolved { suggestion: Some(s), .. } => {
408                            serde_json::json!({ "ref": s.reference, "basis": s.basis, "preTicked": s.pre_ticked })
409                        }
410                        _ => Value::Null,
411                    }
412                } else {
413                    Value::Null
414                };
415                serde_json::json!({ "ref": reference, "reason": row["reason"], "suggestion": suggestion })
416            })
417            .collect();
418        rows.push(serde_json::json!({
419            "id": format!("{prefix}:{}", entry["inputParams"]["id"].as_str().unwrap_or("")),
420            "type": entry["type"],
421            "origin": marker["origin"].as_str().unwrap_or("replace"),
422            "from": marker["from"],
423            "to": marker["to"],
424            "refs": refs,
425        }));
426    }
427    rows
428}
429
430/// What the Constraints pane says about held mates, `(count, wording)`, kept
431/// in `cache` per history revision. [`held_mates`] clones the whole parts
432/// library and walks every nested definition (~5 ms a frame on l500); the
433/// count and the wording read only the document, never the suggestions that
434/// follow the scene, and every document write moves the revision (undo and
435/// redo included).
436pub fn held_summary(cache: &mut Option<(u64, usize, &'static str)>, engine: &mut EngineState) -> (usize, &'static str) {
437    let revision = engine.history.revision();
438    if let Some((at, count, after)) = *cache {
439        if at == revision {
440            return (count, after);
441        }
442    }
443    let rows = held_mates(engine);
444    let after = if rows.iter().all(|row| row["origin"] == "edit") {
445        "a part edit"
446    } else if rows.iter().all(|row| row["origin"] != "edit") {
447        "Replace"
448    } else {
449        "Replace or a part edit"
450    };
451    *cache = Some((revision, rows.len(), after));
452    (rows.len(), after)
453}
454
455/// Walk a sub-assembly definition placed at `prefix` (its part-name chain
456/// `definition`, `/`-joined), collecting its marked constraints and those of
457/// everything it places, each with the definition it lives in.
458fn collect_held(
459    document: &serde_json::Value,
460    prefix: &str,
461    definition: &str,
462    depth: usize,
463    out: &mut Vec<(String, String, serde_json::Value)>,
464) {
465    if depth > 32 || !document.is_object() {
466        return;
467    }
468    for entry in document["assembly"]["constraints"].as_array().into_iter().flatten() {
469        if entry["persistentData"][brep_render::engine_state::replace_component::REPLACE_MARKER].is_object() {
470            out.push((prefix.to_string(), definition.to_string(), entry.clone()));
471        }
472    }
473    for feature in document["features"].as_array().into_iter().flatten() {
474        if !matches!(feature["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT")) {
475            continue;
476        }
477        let (Some(id), Some(part)) = (feature["inputParams"]["id"].as_str(), feature["inputParams"]["partName"].as_str()) else {
478            continue;
479        };
480        collect_held(&document["partsLibrary"][part]["document"], &format!("{prefix}:{id}"), &format!("{definition}/{part}"), depth + 1, out);
481    }
482}
483
484/// The definition chain of the sub-assembly placed at occurrence `path`
485/// (`ACOMP3`, `ACOMP3:ACOMP1`): its part names from the top library down, its
486/// source key, and its document.
487fn definition_at(engine: &EngineState, path: &str) -> Result<(Vec<String>, Option<String>, serde_json::Value), String> {
488    let segments: Vec<&str> = path.split(':').collect();
489    let library = engine.history.parts_library().clone();
490    let top = engine
491        .component_info(segments[0])
492        .ok_or_else(|| format!("'{}' is not an assembly component", segments[0]))?
493        .part_name;
494    let mut names = vec![top];
495    let mut entry = library[&names[0]].clone();
496    for id in &segments[1..] {
497        let part = entry["document"]["features"]
498            .as_array()
499            .into_iter()
500            .flatten()
501            .find(|f| f["inputParams"]["id"].as_str() == Some(*id))
502            .and_then(|f| f["inputParams"]["partName"].as_str())
503            .ok_or_else(|| format!("'{id}' is not placed in '{}'", names.last().unwrap()))?
504            .to_string();
505        entry = entry["document"]["partsLibrary"][&part].clone();
506        names.push(part);
507    }
508    let source = entry["sourceKey"].as_str().filter(|k| !k.is_empty()).map(str::to_string);
509    Ok((names, source, entry["document"].clone()))
510}
511
512/// Split a held-mate id into (sub-assembly occurrence path, constraint id);
513/// `None` for a top-level mate.
514fn nested_id(id: &str) -> Option<(&str, &str)> {
515    id.rsplit_once(':')
516}
517
518/// Apply edits to nested definitions, one sub-assembly at a time, as ONE
519/// document edit (one undo step) through the Work part's refresh.
520fn edit_definitions(
521    engine: &mut EngineState,
522    top: &[(String, String, String)],
523    edits: std::collections::BTreeMap<String, Vec<Box<dyn FnOnce(&mut serde_json::Value) -> Result<(), String>>>>,
524) -> Result<(), String> {
525    let mut assembly: serde_json::Value = serde_json::from_str(&engine.history_request_json()).map_err(|e| e.to_string())?;
526    // Top-level repairs ride in the same document edit (one undo step).
527    if !top.is_empty() {
528        repair_block(&mut assembly["assembly"], top, "")?;
529    }
530    let mut notes = Vec::new();
531    for (path, changes) in edits {
532        let (names, source, mut definition) = definition_at(engine, &path)?;
533        for change in changes {
534            change(&mut definition)?;
535        }
536        if !crate::document::work_part::refresh_parts(&mut assembly, &names, source.as_deref(), &definition, &mut notes)? {
537            return Err(format!("the assembly no longer holds the sub-assembly at '{path}'"));
538        }
539    }
540    engine.edit_document_json(&assembly.to_string())?;
541    for note in notes {
542        engine.push_notice(format!("Replace: {note}"));
543    }
544    Ok(())
545}
546
547/// Repair held references at any depth, as ONE undo step: `(mate id, old ref,
548/// new ref)` with the ids and refs [`held_mates`] lists. A nested mate's new
549/// ref must lie inside the same sub-assembly. A mate with nothing left held
550/// is re-enabled (if it was enabled before) and loses its marker.
551pub fn repair(engine: &mut EngineState, repairs: &[(String, String, String)]) -> Result<(), String> {
552    let (top, nested): (Vec<_>, Vec<_>) = repairs.iter().cloned().partition(|(id, _, _)| nested_id(id).is_none());
553    if nested.is_empty() {
554        return engine.replace_repair(&top);
555    }
556    let mut edits: std::collections::BTreeMap<String, Vec<Box<dyn FnOnce(&mut serde_json::Value) -> Result<(), String>>>> =
557        Default::default();
558    for (id, old_ref, new_ref) in nested {
559        let (path, _) = nested_id(&id).unwrap();
560        let path = path.to_string();
561        let prefix = format!("{path}:");
562        let local = |r: &str| r.strip_prefix(&prefix).map(str::to_string);
563        let old_local = local(&old_ref).ok_or_else(|| format!("'{old_ref}' is not inside '{path}'"))?;
564        let new_local = local(&new_ref).ok_or_else(|| format!("pick a face inside '{path}' for {id}"))?;
565        let constraint = nested_id(&id).unwrap().1.to_string();
566        edits.entry(path).or_default().push(Box::new(move |definition: &mut serde_json::Value| {
567            repair_block(&mut definition["assembly"], &[(constraint, old_local, new_local)], "")
568        }));
569    }
570    edit_definitions(engine, &top, edits)
571}
572
573/// `replace_repair`'s rule on one `assembly` block (also a nested one).
574fn repair_block(block: &mut serde_json::Value, repairs: &[(String, String, String)], _prefix: &str) -> Result<(), String> {
575    use brep_render::engine_state::replace_component::REPLACE_MARKER;
576    for (id, old_ref, new_ref) in repairs {
577        let entry = block["constraints"]
578            .as_array_mut()
579            .into_iter()
580            .flatten()
581            .find(|entry| entry["inputParams"]["id"] == id.as_str())
582            .ok_or_else(|| format!("no constraint '{id}'"))?;
583        let marker = &mut entry["persistentData"][REPLACE_MARKER];
584        let refs = marker["refs"].as_array_mut().ok_or_else(|| format!("'{id}' has nothing held"))?;
585        let before = refs.len();
586        refs.retain(|row| row["ref"] != old_ref.as_str());
587        if refs.len() == before {
588            return Err(format!("'{id}' holds no ref '{old_ref}'"));
589        }
590        let done = refs.is_empty();
591        let was_enabled = marker["wasEnabled"].as_bool().unwrap_or(true);
592        for element in entry["inputParams"]["elements"].as_array_mut().into_iter().flatten() {
593            if element == old_ref.as_str() {
594                *element = serde_json::Value::String(new_ref.clone());
595            }
596        }
597        if done {
598            if let Some(data) = entry["persistentData"].as_object_mut() {
599                data.remove(REPLACE_MARKER);
600            }
601            entry["enabled"] = serde_json::Value::Bool(was_enabled);
602        }
603    }
604    Ok(())
605}
606
607/// Accept every PRE-TICKED suggestion of the given held mates (every held
608/// mate, at every depth, when `ids` is empty) as one undo step.
609pub fn accept_suggestions(engine: &mut EngineState, ids: &[String]) -> Result<usize, String> {
610    let mut repairs = Vec::new();
611    for mate in held_mates(engine) {
612        let id = mate["id"].as_str().unwrap_or_default().to_string();
613        if !ids.is_empty() && !ids.contains(&id) {
614            continue;
615        }
616        for row in mate["refs"].as_array().into_iter().flatten() {
617            if row["suggestion"]["preTicked"] == true {
618                repairs.push((
619                    id.clone(),
620                    row["ref"].as_str().unwrap_or_default().to_string(),
621                    row["suggestion"]["ref"].as_str().unwrap_or_default().to_string(),
622                ));
623            }
624        }
625    }
626    if repairs.is_empty() {
627        return Ok(0);
628    }
629    repair(engine, &repairs)?;
630    Ok(repairs.len())
631}
632
633/// Delete a held mate at any depth (one undo step).
634pub fn delete_held(engine: &mut EngineState, id: &str) -> Result<(), String> {
635    let Some((path, constraint)) = nested_id(id) else {
636        return engine.assembly_remove_constraint(id);
637    };
638    let constraint = constraint.to_string();
639    let mut edits: std::collections::BTreeMap<String, Vec<Box<dyn FnOnce(&mut serde_json::Value) -> Result<(), String>>>> =
640        Default::default();
641    let id = id.to_string();
642    edits.entry(path.to_string()).or_default().push(Box::new(move |definition: &mut serde_json::Value| {
643        let list = definition["assembly"]["constraints"].as_array_mut().ok_or("the sub-assembly has no constraints")?;
644        let before = list.len();
645        list.retain(|entry| entry["inputParams"]["id"] != constraint.as_str());
646        if list.len() == before {
647            return Err(format!("no constraint '{id}'"));
648        }
649        Ok(())
650    }));
651    edit_definitions(engine, &[], edits)
652}
653
654// ---------------------------------------------------------------------------
655// The chooser: what the occurrence can be replaced WITH
656// ---------------------------------------------------------------------------
657
658/// One offered replacement.
659#[derive(Debug, Clone, PartialEq, Eq)]
660pub struct Candidate {
661    pub source: ReplaceSource,
662    /// What the row says: a family member by its row name (part number), a
663    /// file by its display name, a library entry by its entry name.
664    pub label: String,
665    /// The section it sits in: `revisions` (PLM), `family`, `assembly`,
666    /// `folder`, `recent`, `browse`.
667    pub group: &'static str,
668}
669
670impl Candidate {
671    /// The row's stable key (widget keys, automation).
672    pub fn key(&self) -> String {
673        match &self.source {
674            ReplaceSource::Stored(name) => format!("file:{name}"),
675            ReplaceSource::Library(part) => format!("part:{part}"),
676        }
677    }
678}
679
680/// Section titles, in the order the chooser shows them.
681pub const GROUPS: [(&str, &str); 6] = [
682    ("revisions", "Other revisions"),
683    ("family", "Same family"),
684    ("assembly", "In this assembly"),
685    ("folder", "Same folder"),
686    ("recent", "Recent"),
687    ("browse", "All parts"),
688];
689
690/// A listed document that can be a component: anything but a family or a
691/// template (a store may list bare names with no extension at all).
692fn is_part_file(name: &str) -> bool {
693    use crate::document_class::DocumentClass;
694    !matches!(DocumentClass::of_name(name), Some(DocumentClass::Family | DocumentClass::Template))
695}
696
697/// The candidates for replacing `component_id`, best first: other members of
698/// its family (when it is one; by row name), the other parts this assembly
699/// already carries, the part files beside it (its folder, or the PLM
700/// workspace a PLM store lists), recent files. `browse` adds every part file
701/// the store lists. The occurrence's own part is never offered, and neither
702/// is `exclude` (the assembly being edited: it cannot contain itself).
703pub fn candidates(
704    engine: &EngineState,
705    store: &dyn ModelStore,
706    component_id: &str,
707    browse: bool,
708    exclude: Option<&str>,
709) -> Vec<Candidate> {
710    let Some(info) = engine.component_info(component_id) else { return Vec::new() };
711    let canonicalize = store.canonicalizer();
712    let source_key = engine
713        .part_source(&info.part_name)
714        .map(|(key, _)| key)
715        .filter(|key| !key.is_empty());
716    let current = source_key.as_deref().map(|key| canonicalize(key));
717    let mut seen: std::collections::BTreeSet<String> = current.iter().cloned().collect();
718    if let Some(exclude) = exclude {
719        seen.insert(canonicalize(exclude));
720    }
721    let mut out = Vec::new();
722    let push_file = |out: &mut Vec<Candidate>, seen: &mut std::collections::BTreeSet<String>, name: String, label: String, group: &'static str| {
723        if seen.insert(canonicalize(&name)) {
724            out.push(Candidate { source: ReplaceSource::Stored(name), label, group });
725        }
726    };
727
728    // In a PLM session: the part's OTHER revisions first (newest first), by
729    // label and state. The store lists every indexed revision, loaded or not.
730    let listing = store.list();
731    if store.plm_session().is_some() {
732        if let Some((part, revision)) = source_key.as_deref().and_then(crate::panels::plm_host::revision_of) {
733            let mut revisions: Vec<(String, String)> = listing
734                .iter()
735                .filter_map(|name| {
736                    let (other_part, other) = crate::panels::plm_host::revision_of(name)?;
737                    (other_part == part && other != revision).then(|| {
738                        let key = crate::plm::identity::document_key(&other_part, &other);
739                        let label = match store.plm_revision(&key) {
740                            Some(entry) => format!("Revision {} ({})", entry.revision_label, entry.lifecycle),
741                            None => format!("Revision {other}"),
742                        };
743                        (name.clone(), label)
744                    })
745                })
746                .collect();
747            revisions.reverse();
748            for (name, label) in revisions {
749                push_file(&mut out, &mut seen, name, label, "revisions");
750            }
751        }
752    }
753
754    // Same family: the family's table rows, by part number, beside the
755    // family file (members sit beside their family).
756    let document = engine.history.parts_library()[&info.part_name]["document"].clone();
757    if let (Some(family), Some(key)) = (crate::family_table::family_source(&document), source_key.as_deref()) {
758        let family_identity = crate::store::sibling_identity(key, &family.family);
759        if let crate::store::ReadNow::Ready(text) = crate::store::read_now(store, &family_identity) {
760            let table = crate::family_table::read_table(&text);
761            for row in &table.rows {
762                if let Some(member) = crate::family_table::member_identity(Some(&family_identity), &row.part_number) {
763                    if store.read(&member).is_some() {
764                        push_file(&mut out, &mut seen, member, row.part_number.trim().to_string(), "family");
765                    }
766                }
767            }
768        } else {
769            // The family file is not here (moved, or members copied without
770            // it): the members beside this one still say which family they
771            // are, by their stamp.
772            for name in store.list() {
773                if crate::store::sibling_identity(key, &crate::store::file_name_of(&name)) != name {
774                    continue;
775                }
776                let Some(text) = store.read(&name) else { continue };
777                let Ok(other) = serde_json::from_str::<serde_json::Value>(&text) else { continue };
778                if let Some(stamp) = crate::family_table::family_source(&other).filter(|s| s.family == family.family) {
779                    push_file(&mut out, &mut seen, name, stamp.part_number, "family");
780                }
781            }
782        }
783    }
784
785    // Parts this assembly already carries.
786    let mut library = engine.history.parts_library().as_object().cloned().unwrap_or_default();
787    library.remove(&info.part_name);
788    for (part, entry) in library {
789        if let Some(key) = entry["sourceKey"].as_str().filter(|k| !k.is_empty()) {
790            seen.insert(canonicalize(key));
791        }
792        out.push(Candidate { source: ReplaceSource::Library(part.clone()), label: part, group: "assembly" });
793    }
794
795    // Beside it: the same folder (or the whole PLM workspace).
796    if let Some(key) = source_key.as_deref() {
797        for name in listing.iter().filter(|name| is_part_file(name)) {
798            let beside = crate::store::sibling_identity(key, &crate::store::file_name_of(name)) == *name;
799            if beside || store.plm_session().is_some() {
800                push_file(&mut out, &mut seen, name.clone(), model_display_name(name), "folder");
801            }
802        }
803    }
804    for name in crate::panels::file::recent_documents(store).into_iter().filter(|name| is_part_file(name)) {
805        let label = model_display_name(&name);
806        push_file(&mut out, &mut seen, name, label, "recent");
807    }
808    if browse {
809        for name in listing.into_iter().filter(|name| is_part_file(name)) {
810            let label = model_display_name(&name);
811            push_file(&mut out, &mut seen, name, label, "browse");
812        }
813    }
814    out
815}
816
817/// Whether `candidate` matches what the user typed: its label, its store
818/// name, and in a PLM session the part number and name the index holds for
819/// it. Case-insensitive; an empty filter matches everything.
820pub fn candidate_matches(store: &dyn ModelStore, candidate: &Candidate, filter: &str) -> bool {
821    let filter = filter.trim().to_lowercase();
822    if filter.is_empty() {
823        return true;
824    }
825    let mut haystack = candidate.label.to_lowercase();
826    match &candidate.source {
827        ReplaceSource::Stored(name) => {
828            haystack.push(' ');
829            haystack.push_str(&name.to_lowercase());
830            if let Some((part, revision)) = crate::panels::plm_host::revision_of(name) {
831                if let Some(entry) = store.plm_revision(&crate::plm::identity::document_key(&part, &revision)) {
832                    haystack.push_str(&format!(" {} {}", entry.part_number, entry.part_name).to_lowercase());
833                }
834            }
835        }
836        ReplaceSource::Library(part) => {
837            haystack.push(' ');
838            haystack.push_str(&part.to_lowercase());
839        }
840    }
841    filter.split_whitespace().all(|word| haystack.contains(word))
842}
843
844/// The chooser's list for what was typed: the usual sections when nothing
845/// is, and EVERY part the store lists (other folders, the whole PLM index)
846/// narrowed to the matches once something is, with no Browse click.
847pub fn search_candidates(
848    engine: &EngineState,
849    store: &dyn ModelStore,
850    component_id: &str,
851    filter: &str,
852    exclude: Option<&str>,
853) -> Vec<Candidate> {
854    if filter.trim().is_empty() {
855        return candidates(engine, store, component_id, false, exclude);
856    }
857    candidates(engine, store, component_id, true, exclude)
858        .into_iter()
859        .filter(|candidate| candidate_matches(store, candidate, filter))
860        .collect()
861}
862
863/// How long the chooser trusts a store listing (or a document it found
864/// missing) it read at one store generation: a file copied in outside the
865/// app shows within this, without a re-read on every keystroke or frame.
866const SEARCH_LISTING_TTL: f64 = 1.0;
867
868/// What replacing `component_id` with `candidate` will do, BEFORE it is done.
869#[derive(Debug, Clone, PartialEq)]
870pub struct Preview {
871    /// `family` / `derived` (mates keep their faces by name), `None` for an
872    /// unrelated part (every mate waits for confirmation).
873    pub lineage: Option<&'static str>,
874    /// How many mates touch the occurrence.
875    pub mates: usize,
876    /// The candidate's own document, for its picture (`None` while loading).
877    pub document: Option<serde_json::Value>,
878}
879
880impl Preview {
881    /// The one line the chooser shows.
882    pub fn sentence(&self) -> String {
883        match (self.lineage, self.mates) {
884            (_, 0) => "No mates on this component.".into(),
885            (Some("family"), n) => format!("Same family: the {n} mate(s) keep their faces by name where the faces still exist."),
886            (Some(_), n) => format!("A variation of this part: the {n} mate(s) keep their faces by name where the faces still exist."),
887            (None, n) => format!("An unrelated part: the {n} mate(s) will wait for your confirmation."),
888        }
889    }
890}
891
892/// The preview for `candidate` (lineage against the occurrence's current
893/// part, the mates it touches, the candidate's document). `None` for an
894/// unknown component.
895pub fn preview(engine: &EngineState, store: &dyn ModelStore, component_id: &str, candidate: &Candidate) -> Option<Preview> {
896    let info = engine.component_info(component_id)?;
897    let library = engine.history.parts_library();
898    let old = &library[&info.part_name];
899    let new = match &candidate.source {
900        ReplaceSource::Library(part) => Some(library[part].clone()),
901        ReplaceSource::Stored(name) => match crate::store::read_now(store, name) {
902            crate::store::ReadNow::Ready(text) => serde_json::from_str::<serde_json::Value>(&text)
903                .ok()
904                .map(|document| serde_json::json!({ "sourceKey": name, "document": document })),
905            _ => None,
906        },
907    };
908    let canonicalize = lineage_canonicalizer(store);
909    let lineage = new
910        .as_ref()
911        .and_then(|new| brep_render::engine_state::replace_component::entries_lineage(old, new, &canonicalize));
912    let prefix = format!("{component_id}:");
913    let mates = engine
914        .history
915        .assembly_block()
916        .and_then(|block| block["constraints"].as_array().cloned())
917        .unwrap_or_default()
918        .iter()
919        .filter(|entry| {
920            entry["inputParams"]["elements"]
921                .as_array()
922                .into_iter()
923                .flatten()
924                .filter_map(serde_json::Value::as_str)
925                .any(|r| r == component_id || r.starts_with(&prefix))
926        })
927        .count();
928    Some(Preview { lineage, mates, document: new.map(|entry| entry["document"].clone()) })
929}
930
931// ---------------------------------------------------------------------------
932// The dialog: choose, then the summary (kept / unresolved, repair, delete)
933// ---------------------------------------------------------------------------
934
935/// The Replace component window. `open` it on an occurrence; it shows the
936/// chooser, runs the replace, then the summary of what happened to the mates
937/// until the user closes it. Reopened with no target ([`Self::review`]) it is
938/// the summary alone, for mates still held from an earlier replace.
939#[derive(Default)]
940pub struct ReplaceDialog {
941    target: Option<String>,
942    /// The document being edited (never offered as its own component).
943    document: Option<String>,
944    part: String,
945    instances: Vec<String>,
946    all: bool,
947    filter: String,
948    candidates: Vec<Candidate>,
949    chosen: Option<usize>,
950    /// After the replace: the summary is up.
951    summary: bool,
952    /// User's suggestion ticks, `(constraint, ref)` → ticked; absent = the
953    /// suggestion's own `preTicked`.
954    ticks: std::collections::BTreeMap<(String, String), bool>,
955    /// The repair pick running in the result window, `(mate, ref)`: a mirror
956    /// of the engine's [`RefSelectTarget::ReplaceRepair`] pick, refreshed each
957    /// frame the window draws, for the automation state.
958    picking: Option<(String, String)>,
959    /// The chosen candidate is still loading (a PLM revision listed by the
960    /// index, not read yet): the replace runs the frame it arrives.
961    waiting: Option<usize>,
962    /// The filter the candidate list was last built for.
963    searched: String,
964    /// The chosen candidate's preview and picture, for the key it was made for.
965    preview: Option<(String, Preview, Option<egui::TextureHandle>)>,
966    /// When a preview found no document it could load (missing, unreadable,
967    /// not JSON): the store generation and time it looked. It looks again
968    /// only once the store changed or a second passed, not every frame.
969    preview_missing: Option<(u64, f64)>,
970    /// Every part the store lists for the search, read once per store
971    /// generation (at most once a second for changes made outside the app),
972    /// not on every keystroke: `(target, document, generation, time)`.
973    searchable: Option<((String, Option<String>, u64, f64), Vec<Candidate>)>,
974    /// What a Pattern Component makes of this replace (see [`pattern_line`]).
975    pattern: Option<String>,
976    status: String,
977    hits: std::collections::HashMap<String, egui::Rect>,
978}
979
980impl ReplaceDialog {
981    pub fn is_open(&self) -> bool {
982        self.target.is_some() || self.summary
983    }
984
985    /// Open the chooser on `component_id`.
986    pub fn open(&mut self, engine: &EngineState, store: &dyn ModelStore, component_id: &str, document: Option<&str>) {
987        *self = Self::default();
988        // A Pattern Component instance shows its seed's part and has no
989        // feature to replace: the chooser opens on the seed and says so.
990        let (component_id, instance) = match brep_render::brep_kernel::pattern_component_instance(component_id) {
991            Some((pattern, seed, n)) => (seed, Some((component_id.to_string(), pattern, n))),
992            None => (component_id.to_string(), None),
993        };
994        let component_id = component_id.as_str();
995        self.pattern = pattern_line(engine, component_id, instance.as_ref());
996        let Some(info) = engine.component_info(component_id) else { return };
997        self.part = info.part_name;
998        self.instances = instances_of(engine, component_id);
999        self.target = Some(component_id.to_string());
1000        self.document = document.map(str::to_string);
1001        self.candidates = candidates(engine, store, component_id, false, document);
1002    }
1003
1004    /// Open the summary alone (mates held by an earlier replace).
1005    pub fn review(&mut self) {
1006        *self = Self::default();
1007        self.summary = true;
1008    }
1009
1010    pub fn close(&mut self) {
1011        *self = Self::default();
1012    }
1013
1014    /// The shell's Escape: close the chooser. `true` when it took the key.
1015    /// A repair pick is the engine's reference pick, which the shell's own
1016    /// Escape cancels next; the result window (summary) stays: held mates are
1017    /// not something to dismiss by a stray key.
1018    pub fn escape(&mut self) -> bool {
1019        if self.target.is_some() {
1020            self.close();
1021            return true;
1022        }
1023        false
1024    }
1025
1026    /// Replace with candidate `index` (the chooser's Replace button, and the
1027    /// automation door). Opens the summary. A candidate still loading, or an
1028    /// assembly session still on its way from a background runner, is asked
1029    /// for and waited on (`waiting`), not refused.
1030    pub fn apply(&mut self, engine: &mut EngineState, store: &dyn ModelStore, index: usize) -> Result<(), String> {
1031        let target = self.target.clone().ok_or("no component to replace")?;
1032        let candidate = self.candidates.get(index).cloned().ok_or("no such candidate")?;
1033        if let ReplaceSource::Stored(name) = &candidate.source {
1034            if matches!(crate::store::read_now(store, name), crate::store::ReadNow::Loading) {
1035                self.waiting = Some(index);
1036                self.status = format!("Loading {}\u{2026}", candidate.label);
1037                return Ok(());
1038            }
1039        }
1040        let ids = if self.all { self.instances.clone() } else { vec![target] };
1041        // A background runner (the browser's worker) hands the assembly
1042        // session over asynchronously: the first replace only asks for it and
1043        // is refused with nothing read or moved. Wait for it like a loading
1044        // candidate rather than dropping the user's Enter.
1045        match replace(engine, store, &ids, &candidate.source) {
1046            Err(error) if error == brep_render::engine_state::ASSEMBLY_SESSION_PENDING => {
1047                self.waiting = Some(index);
1048                self.status = format!("Preparing the assembly for {}\u{2026}", candidate.label);
1049                return Ok(());
1050            }
1051            result => {
1052                self.waiting = None;
1053                result?;
1054            }
1055        }
1056        self.target = None;
1057        self.summary = true;
1058        Ok(())
1059    }
1060
1061    /// The automation state of the open window.
1062    pub fn state_json(&self) -> serde_json::Value {
1063        serde_json::json!({
1064            "open": self.is_open(),
1065            "target": self.target,
1066            "part": self.part,
1067            "instances": self.instances,
1068            "all": self.all,
1069            "summary": self.summary,
1070            "picking": self.picking.as_ref().map(|(id, r)| serde_json::json!({ "id": id, "ref": r })),
1071            "status": self.status,
1072            "pattern": self.pattern,
1073            "waiting": self.waiting.is_some(),
1074            "chosen": self.chosen,
1075            "preview": self.preview.as_ref().map(|(key, preview, picture)| serde_json::json!({
1076                "key": key,
1077                "lineage": preview.lineage,
1078                "mates": preview.mates,
1079                "sentence": preview.sentence(),
1080                "picture": picture.is_some(),
1081                "loading": preview.document.is_none(),
1082            })),
1083            "candidates": self.candidates.iter().map(|c| serde_json::json!({
1084                "key": c.key(), "label": c.label, "group": c.group,
1085            })).collect::<Vec<_>>(),
1086        })
1087    }
1088
1089    pub fn hits_json(&self) -> String {
1090        crate::automation::hit_rects::hits_json(&self.hits)
1091    }
1092
1093    pub fn show(&mut self, ctx: &egui::Context, engine: &mut EngineState, store: &dyn ModelStore) {
1094        self.hits.clear();
1095        if self.is_open() {
1096            self.window(ctx, engine, store);
1097        }
1098        // Published on every frame, a closed window included: closed by
1099        // Escape, by its x or by a replace, the blob must say so rather than
1100        // keep the last open frame's state.
1101        if crate::automation::registry::enabled() {
1102            crate::automation::registry::publish("__brepReplaceHit", "replace component window widget rects", &self.hits_json());
1103            crate::automation::registry::publish("__brepReplace", "replace component window state", &self.state_json().to_string());
1104        }
1105    }
1106
1107    fn window(&mut self, ctx: &egui::Context, engine: &mut EngineState, store: &dyn ModelStore) {
1108        // A chosen candidate that was still loading: replace when it lands.
1109        if let Some(index) = self.waiting {
1110            if let Err(error) = self.apply(engine, store, index) {
1111                self.waiting = None;
1112                self.status = error;
1113            }
1114            if self.waiting.is_some() {
1115                ctx.request_repaint_after(std::time::Duration::from_millis(100));
1116            }
1117        }
1118        let mut open = true;
1119        let title = if self.summary { "Replace component: result" } else { "Replace component" };
1120        egui::Window::new(title)
1121            .id(egui::Id::new("replace-component"))
1122            .open(&mut open)
1123            .resizable(true)
1124            .default_size([420.0, 460.0])
1125            .default_pos(super::below_chrome(ctx, 420.0, 60.0))
1126            .show(ctx, |ui| {
1127                if self.summary {
1128                    self.summary_ui(ui, engine);
1129                } else {
1130                    self.chooser_ui(ui, engine, store);
1131                }
1132            });
1133        if !open {
1134            self.close();
1135        }
1136    }
1137
1138    fn chooser_ui(&mut self, ui: &mut egui::Ui, engine: &mut EngineState, store: &dyn ModelStore) {
1139        let Some(target) = self.target.clone() else { return };
1140        // The keyboard, read BEFORE the filter field draws: a focused text
1141        // field swallows Escape and the arrows, and the shell leaves every key
1142        // to a focused field, so read later nobody would see them. Arrows move
1143        // through the shown rows, Enter replaces, Escape closes.
1144        let (down, up, enter, escape) = ui.ctx().input(|i| {
1145            (
1146                i.key_pressed(egui::Key::ArrowDown),
1147                i.key_pressed(egui::Key::ArrowUp),
1148                i.key_pressed(egui::Key::Enter),
1149                i.key_pressed(egui::Key::Escape),
1150            )
1151        });
1152        if escape {
1153            self.target = None;
1154            return;
1155        }
1156        ui.label(egui::RichText::new(format!("Replace {} ({target}) with:", self.part)).strong());
1157        if let Some(line) = &self.pattern {
1158            ui.label(line);
1159        }
1160        if self.instances.len() > 1 {
1161            let label = format!("Replace all {} instances of {}", self.instances.len(), self.part);
1162            let response = ui.checkbox(&mut self.all, label);
1163            self.hits.insert("replace:all".into(), response.rect);
1164        }
1165        ui.horizontal(|ui| {
1166            ui.label("Filter");
1167            let response = ui.text_edit_singleline(&mut self.filter);
1168            self.hits.insert("replace:filter".into(), response.rect);
1169            let browse = ui.button("Browse\u{2026}").on_hover_text("List every part file in the store");
1170            self.hits.insert("replace:browse".into(), browse.rect);
1171            if browse.clicked() {
1172                self.candidates = candidates(engine, store, &target, true, self.document.as_deref());
1173                self.chosen = None;
1174            }
1175        });
1176        ui.separator();
1177        // Typing searches every part the store lists (no Browse click).
1178        if self.filter.trim() != self.searched {
1179            self.searched = self.filter.trim().to_string();
1180            self.candidates = if self.searched.is_empty() {
1181                candidates(engine, store, &target, false, self.document.as_deref())
1182            } else {
1183                let now = ui.input(|i| i.time);
1184                let generation = store.mutation_generation();
1185                let fresh = self.searchable.as_ref().is_some_and(|((t, d, g, at), _)| {
1186                    *t == target && *d == self.document && *g == generation && now - at < SEARCH_LISTING_TTL
1187                });
1188                if !fresh {
1189                    let all = candidates(engine, store, &target, true, self.document.as_deref());
1190                    self.searchable = Some(((target.clone(), self.document.clone(), generation, now), all));
1191                }
1192                let all = self.searchable.as_ref().map(|(_, all)| all.as_slice()).unwrap_or_default();
1193                all.iter().filter(|candidate| candidate_matches(store, candidate, &self.searched)).cloned().collect()
1194            };
1195            self.chosen = None;
1196        }
1197        let filter = self.filter.trim().to_lowercase();
1198        let mut double_clicked = None;
1199        let mut shown: Vec<usize> = Vec::new();
1200        egui::ScrollArea::vertical().max_height(300.0).auto_shrink([false, true]).show(ui, |ui| {
1201            if self.candidates.is_empty() {
1202                ui.weak("No other parts found: use Browse\u{2026}");
1203            }
1204            for (group, heading) in GROUPS {
1205                let rows: Vec<usize> = (0..self.candidates.len())
1206                    .filter(|&i| self.candidates[i].group == group)
1207                    .filter(|&i| candidate_matches(store, &self.candidates[i], &filter))
1208                    .collect();
1209                if rows.is_empty() {
1210                    continue;
1211                }
1212                let heading = if group == "folder" && store.plm_session().is_some() { "PLM workspace" } else { heading };
1213                ui.label(egui::RichText::new(heading).weak().small());
1214                for i in rows {
1215                    let response = ui.selectable_label(self.chosen == Some(i), &self.candidates[i].label);
1216                    self.hits.insert(format!("replace:candidate:{}", self.candidates[i].key()), response.rect);
1217                    self.hits.insert(format!("replace:row:{}", shown.len()), response.rect);
1218                    shown.push(i);
1219                    if response.clicked() {
1220                        self.chosen = Some(i);
1221                    }
1222                    if response.double_clicked() {
1223                        double_clicked = Some(i);
1224                    }
1225                }
1226            }
1227        });
1228        if (down || up) && !shown.is_empty() {
1229            let at = self.chosen.and_then(|c| shown.iter().position(|&i| i == c));
1230            let next = match (at, down) {
1231                (None, true) => 0,
1232                (None, false) => shown.len() - 1,
1233                (Some(p), true) => (p + 1).min(shown.len() - 1),
1234                (Some(p), false) => p.saturating_sub(1),
1235            };
1236            self.chosen = Some(shown[next]);
1237        }
1238        ui.separator();
1239        if !self.status.is_empty() {
1240            ui.colored_label(ui.visuals().warn_fg_color, &self.status);
1241        }
1242        // The chosen candidate's preview: its picture and what will happen
1243        // to the mates.
1244        if let Some(index) = self.chosen {
1245            let key = self.candidates[index].key();
1246            let now = ui.input(|i| i.time);
1247            let generation = store.mutation_generation();
1248            // A document still loading is looked for every frame (the store
1249            // answers from memory); one that is not there, again only once
1250            // the store changed or a second passed.
1251            let settled_missing = self
1252                .preview_missing
1253                .is_some_and(|(g, at)| g == generation && now - at < SEARCH_LISTING_TTL);
1254            if self.preview.as_ref().is_none_or(|(k, p, _)| *k != key || (p.document.is_none() && !settled_missing)) {
1255                let loading = match &self.candidates[index].source {
1256                    ReplaceSource::Stored(name) => store.residency(name) == crate::store::Residency::OnDisk,
1257                    ReplaceSource::Library(_) => false,
1258                };
1259                self.preview = preview(engine, store, &target, &self.candidates[index]).map(|preview| {
1260                    let picture = preview
1261                        .document
1262                        .as_ref()
1263                        .and_then(crate::plm::thumbnail::embedded_image)
1264                        .map(|image| ui.ctx().load_texture(format!("replace-preview:{key}"), image, egui::TextureOptions::LINEAR));
1265                    (key, preview, picture)
1266                });
1267                self.preview_missing = match &self.preview {
1268                    Some((_, preview, _)) if preview.document.is_none() && !loading => Some((generation, now)),
1269                    _ => None,
1270                };
1271            }
1272            if let Some((_, preview, picture)) = &self.preview {
1273                ui.horizontal(|ui| {
1274                    match picture {
1275                        Some(texture) => {
1276                            let response = ui.add(egui::Image::new(texture).fit_to_exact_size(egui::vec2(96.0, 96.0)));
1277                            self.hits.insert("replace:preview".into(), response.rect);
1278                        }
1279                        None if preview.document.is_none() => {
1280                            ui.weak("Loading\u{2026}");
1281                        }
1282                        None => {
1283                            ui.weak("(no picture)");
1284                        }
1285                    }
1286                    ui.label(preview.sentence());
1287                });
1288            }
1289        } else {
1290            self.preview = None;
1291        }
1292        // Enter takes the chosen row, or the top hit of what was typed.
1293        let top_hit = (!filter.is_empty()).then(|| shown.first().copied()).flatten();
1294        let mut apply = double_clicked.or(if enter { self.chosen.or(top_hit) } else { None });
1295        ui.horizontal(|ui| {
1296            let replace = ui.add_enabled(self.chosen.is_some(), egui::Button::new("Replace"));
1297            self.hits.insert("replace:apply".into(), replace.rect);
1298            if replace.clicked() {
1299                apply = self.chosen;
1300            }
1301            let cancel = ui.button("Cancel");
1302            self.hits.insert("replace:cancel".into(), cancel.rect);
1303            if cancel.clicked() {
1304                self.target = None;
1305            }
1306        });
1307        if let Some(index) = apply {
1308            if let Err(error) = self.apply(engine, store, index) {
1309                self.status = error;
1310            }
1311        }
1312    }
1313
1314    fn summary_ui(&mut self, ui: &mut egui::Ui, engine: &mut EngineState) {
1315        let report = engine.replace_report();
1316        let unresolved = serde_json::Value::Array(held_mates(engine));
1317        if report.is_null() && unresolved.as_array().is_none_or(Vec::is_empty) {
1318            if engine.run_pending() {
1319                ui.label("Solving\u{2026}");
1320            } else {
1321                ui.label("Nothing to review.");
1322            }
1323        }
1324        if !report.is_null() && report["origin"] == "edit" {
1325            ui.label(format!("After editing {}:", report["to"].as_str().unwrap_or("")));
1326            let kept = report["kept"].as_array().map_or(0, Vec::len);
1327            ui.label(format!("{kept} mate(s) kept."));
1328            for moved in report["reattached"].as_array().into_iter().flatten() {
1329                ui.label(format!(
1330                    "{}: re-attached {} \u{2192} {} (the one face on the same carrier)",
1331                    moved["id"].as_str().unwrap_or(""),
1332                    moved["from"].as_str().unwrap_or(""),
1333                    moved["to"].as_str().unwrap_or("")
1334                ));
1335            }
1336            for note in report["notes"].as_array().into_iter().flatten() {
1337                ui.weak(note.as_str().unwrap_or(""));
1338            }
1339        } else if !report.is_null() {
1340            let lineage = report["lineage"].as_object().and_then(|m| m.values().next()).and_then(|v| v.as_str()).unwrap_or("none");
1341            let words = match lineage {
1342                "family" => "a member of the same family: mates kept by face name",
1343                "derived" => "a variation of the same part: mates kept by face name",
1344                _ => "an unrelated part: every mate waits for your confirmation",
1345            };
1346            ui.label(format!("Now showing {} ({words}).", report["to"].as_str().unwrap_or("")));
1347            let kept = report["kept"].as_array().map_or(0, Vec::len);
1348            ui.label(format!("{kept} mate(s) kept."));
1349            for note in report["notes"].as_array().into_iter().flatten() {
1350                ui.weak(note.as_str().unwrap_or(""));
1351            }
1352        }
1353        let rows = unresolved.as_array().cloned().unwrap_or_default();
1354        let mut repairs: Vec<(String, String, String)> = Vec::new();
1355        // A finished repair pick: it must lie in the same occurrence as the
1356        // reference it replaces — the ref minus its entity name
1357        // (`ACOMP1:ACOMP1:Hole_S` → `ACOMP1:ACOMP1`).
1358        if let Some((id, reference, picked)) = engine.take_replace_repair_pick() {
1359            let owner = reference.rsplit_once(':').map(|(path, _)| path).unwrap_or("").to_string();
1360            if picked.starts_with(&format!("{owner}:")) {
1361                repairs.push((id, reference, picked));
1362            } else {
1363                self.status = format!("Pick a face or edge of {owner} for {id}: {picked} is on another part");
1364            }
1365        }
1366        let running = engine.ref_select_field().filter(|f| f.target == RefSelectTarget::ReplaceRepair);
1367        self.picking = running.as_ref().map(|f| (f.subject.clone(), f.path.first().cloned().unwrap_or_default()));
1368        let mut delete: Option<String> = None;
1369        if !rows.is_empty() {
1370            ui.separator();
1371            ui.label(egui::RichText::new(format!("{} mate(s) need a face (held, not solved):", rows.len())).strong());
1372        }
1373        egui::ScrollArea::vertical().max_height(300.0).auto_shrink([false, true]).show(ui, |ui| {
1374            for mate in &rows {
1375                let id = mate["id"].as_str().unwrap_or("").to_string();
1376                ui.horizontal(|ui| {
1377                    ui.label(egui::RichText::new(format!("{id} ({})", mate["type"].as_str().unwrap_or(""))).strong());
1378                    let delete_button = ui.small_button("\u{2716} Delete mate").on_hover_text("Delete this mate");
1379                    self.hits.insert(format!("replace:delete:{id}"), delete_button.rect);
1380                    if delete_button.clicked() {
1381                        delete = Some(id.clone());
1382                    }
1383                });
1384                for row in mate["refs"].as_array().into_iter().flatten() {
1385                    let reference = row["ref"].as_str().unwrap_or("").to_string();
1386                    let edited = mate["origin"] == "edit";
1387                    let reason = match row["reason"].as_str().unwrap_or("") {
1388                        "missing" if edited => "gone after the edit, and no single face replaces it",
1389                        "missing" => "not on the new part",
1390                        "type-changed" => "now a different kind of face",
1391                        "moved" => "that corner moved on the new part",
1392                        "no-longer-maps" => "no longer fits this mate",
1393                        _ => "unrelated part: confirm",
1394                    };
1395                    ui.indent(format!("ref-{id}-{reference}"), |ui| {
1396                        ui.label(format!("{reference}: {reason}"));
1397                        let row_key = format!("{id}:{reference}");
1398                        if let Some(suggestion) = row["suggestion"]["ref"].as_str() {
1399                            let pre = row["suggestion"]["preTicked"].as_bool().unwrap_or(false);
1400                            let tick = self.ticks.entry((id.clone(), reference.clone())).or_insert(pre);
1401                            let basis = if row["suggestion"]["basis"] == "same-name" { "same name" } else { "nearest" };
1402                            let label = format!("Use {suggestion} ({basis}{})", if pre { ", same geometry" } else { "" });
1403                            let response = ui.checkbox(tick, label);
1404                            self.hits.insert(format!("replace:tick:{row_key}"), response.rect);
1405                        }
1406                        let picking = self.picking.as_ref() == Some(&(id.clone(), reference.clone()));
1407                        if picking {
1408                            // The standard reference pick runs for this row:
1409                            // a face or edge clicked in the view finishes it
1410                            // (one pick) and the repair lands next frame.
1411                            engine.ref_select_claim();
1412                            ui.weak("Click the face or edge to use in the viewport.");
1413                            let cancel = ui.small_button("Cancel pick");
1414                            self.hits.insert(format!("replace:cancel-pick:{row_key}"), cancel.rect);
1415                            if cancel.clicked() {
1416                                engine.cancel_ref_select();
1417                            }
1418                        } else {
1419                            let pick = ui.small_button("Pick\u{2026}").on_hover_text("Pick the replacement face or edge in the viewport");
1420                            self.hits.insert(format!("replace:pick:{row_key}"), pick.rect);
1421                            if pick.clicked() {
1422                                if engine.ref_select_active() {
1423                                    engine.finish_ref_select();
1424                                }
1425                                self.status.clear();
1426                                engine.begin_ref_select_for_replace_repair(&id, &reference);
1427                                // Claimed the frame it opens, too: the shell
1428                                // finishes an in-form pick no form claims.
1429                                engine.ref_select_claim();
1430                            }
1431                        }
1432                    });
1433                }
1434            }
1435        });
1436        ui.separator();
1437        ui.horizontal(|ui| {
1438            let ticked: Vec<(String, String, String)> = rows
1439                .iter()
1440                .flat_map(|mate| {
1441                    let id = mate["id"].as_str().unwrap_or("").to_string();
1442                    mate["refs"].as_array().cloned().unwrap_or_default().into_iter().filter_map(move |row| {
1443                        let reference = row["ref"].as_str()?.to_string();
1444                        let suggestion = row["suggestion"]["ref"].as_str()?.to_string();
1445                        Some((id.clone(), reference, suggestion))
1446                    })
1447                })
1448                .filter(|(id, reference, _)| self.ticks.get(&(id.clone(), reference.clone())).copied().unwrap_or(false))
1449                .collect();
1450            let apply = ui.add_enabled(!ticked.is_empty(), egui::Button::new(format!("Apply ticked ({})", ticked.len())));
1451            self.hits.insert("replace:apply-ticked".into(), apply.rect);
1452            if apply.clicked() {
1453                repairs.extend(ticked);
1454            }
1455            let close = ui.button("Close").on_hover_text("Held mates stay disabled and listed; reopen this from the Constraints panel");
1456            self.hits.insert("replace:close".into(), close.rect);
1457            if close.clicked() {
1458                self.summary = false;
1459            }
1460        });
1461        if !self.status.is_empty() {
1462            ui.colored_label(ui.visuals().warn_fg_color, &self.status);
1463        }
1464        if !repairs.is_empty() {
1465            match repair(engine, &repairs) {
1466                Ok(()) => self.status.clear(),
1467                Err(error) => self.status = error,
1468            }
1469        }
1470        if let Some(id) = delete {
1471            if let Err(error) = delete_held(engine, &id) {
1472                self.status = error;
1473            }
1474        }
1475    }
1476}
1477
1478/// The hit keys this window publishes (see `automation::hit_keys`).
1479pub static HIT_KEYS: &[HitKeyDoc] = &[
1480    HitKeyDoc { panel: "replace", prefix: "replace:all", meaning: "Replace all instances of the part (checkbox)", command: Some("assembly_replace_component") },
1481    HitKeyDoc { panel: "replace", prefix: "replace:filter", meaning: "filter the candidate list", command: None },
1482    HitKeyDoc { panel: "replace", prefix: "replace:browse", meaning: "list every part file in the store", command: None },
1483    HitKeyDoc { panel: "replace", prefix: "replace:candidate:", meaning: "a replacement candidate (replace:candidate:file:<name> or replace:candidate:part:<entry>)", command: None },
1484    HitKeyDoc { panel: "replace", prefix: "replace:row:", meaning: "a candidate by its position in the list as shown (replace:row:0 is the first row, under its section heading); the keyboard moves through the same rows (arrows, Enter replaces, Escape closes)", command: None },
1485    HitKeyDoc { panel: "replace", prefix: "replace:preview", meaning: "the chosen candidate's picture (shown when its document carries one)", command: None },
1486    HitKeyDoc { panel: "replace", prefix: "replace:apply", meaning: "replace with the chosen candidate", command: Some("assembly_replace_component") },
1487    HitKeyDoc { panel: "replace", prefix: "replace:cancel", meaning: "close the chooser without replacing", command: None },
1488    HitKeyDoc { panel: "replace", prefix: "replace:tick:", meaning: "use the suggested face for an unresolved reference (replace:tick:<mate>:<ref>)", command: None },
1489    HitKeyDoc { panel: "replace", prefix: "replace:pick:", meaning: "start the reference pick for one held reference (replace:pick:<mate>:<ref>): faces and edges only, and the one face or edge clicked in the viewport repairs it", command: Some("assembly_replace_repair") },
1490    HitKeyDoc { panel: "replace", prefix: "replace:cancel-pick:", meaning: "cancel the running repair pick (replace:cancel-pick:<mate>:<ref>)", command: None },
1491    HitKeyDoc { panel: "replace", prefix: "replace:delete:", meaning: "delete an unresolved mate (replace:delete:<mate>)", command: Some("assembly_remove_constraint") },
1492    HitKeyDoc { panel: "replace", prefix: "replace:apply-ticked", meaning: "apply every ticked suggestion", command: Some("assembly_replace_accept") },
1493    HitKeyDoc { panel: "replace", prefix: "replace:close", meaning: "close the summary (held mates stay listed)", command: None },
1494];
1495