1use super::*;
60use serde_json::{json, Value};
61use std::borrow::Borrow;
62use std::collections::{BTreeMap, BTreeSet};
63
64pub const DERIVED_FROM_KEY: &str = "derivedFrom";
66
67pub const REPLACE_MARKER: &str = "replace";
69
70const BROKEN: [&str; 3] = ["invalid-selection", "unsupported-selection", "error"];
73
74pub const BROKEN_STATUSES: [&str; 3] = BROKEN;
76
77pub fn lineage_keys(
82 document: &Value,
83 identity: &str,
84 canonicalize: &dyn Fn(&str) -> String,
85) -> BTreeSet<String> {
86 let mut keys = BTreeSet::new();
87 if !identity.trim().is_empty() {
88 keys.insert(canonicalize(identity.trim()));
89 }
90 for entry in document[DERIVED_FROM_KEY].as_array().into_iter().flatten() {
91 if let Some(entry) = entry.as_str().map(str::trim).filter(|e| !e.is_empty()) {
92 if entry.starts_with("family:") {
94 keys.insert(entry.to_string());
95 } else {
96 keys.insert(canonicalize(entry));
97 }
98 }
99 }
100 if let Some(family) = family_key(document) {
101 keys.insert(family);
102 }
103 keys
104}
105
106pub fn family_key(document: &Value) -> Option<String> {
108 document["familySource"]["family"]
109 .as_str()
110 .map(str::trim)
111 .filter(|family| !family.is_empty())
112 .map(|family| format!("family:{family}"))
113}
114
115pub fn shared_lineage(old: &BTreeSet<String>, new: &BTreeSet<String>) -> Option<&'static str> {
117 let common: Vec<&String> = old.intersection(new).collect();
118 if common.is_empty() {
119 None
120 } else if common.iter().any(|key| !key.starts_with("family:")) {
121 Some("derived")
123 } else {
124 Some("family")
125 }
126}
127
128pub fn stamp_derived_from(document: &mut Value, source_identity: &str) {
133 let Some(object) = document.as_object_mut() else { return };
134 let family = object
135 .get("familySource")
136 .and_then(|source| source.get("family"))
137 .and_then(Value::as_str)
138 .map(str::trim)
139 .filter(|family| !family.is_empty())
140 .map(|family| format!("family:{family}"));
141 let chain = object
142 .entry(DERIVED_FROM_KEY)
143 .or_insert_with(|| Value::Array(Vec::new()));
144 if !chain.is_array() {
145 *chain = Value::Array(Vec::new());
146 }
147 let list = chain.as_array_mut().expect("array");
148 for entry in [Some(source_identity.trim().to_string()), family].into_iter().flatten() {
149 if !entry.is_empty() && !list.iter().any(|e| e.as_str() == Some(&entry)) {
150 list.push(Value::String(entry));
151 }
152 }
153}
154
155fn triple(value: &Value) -> Option<[f64; 3]> {
162 let list = value.as_array()?;
163 if list.len() != 3 {
164 return None;
165 }
166 Some([list[0].as_f64()?, list[1].as_f64()?, list[2].as_f64()?])
167}
168
169use crate::geometry3d::sub3 as sub;
170
171use crate::geometry3d::dot3 as dot;
172
173use crate::geometry3d::len3 as norm;
174
175fn line_distance(p: [f64; 3], origin: [f64; 3], direction: [f64; 3]) -> f64 {
177 let d = sub(p, origin);
178 let along = dot(d, direction);
179 (dot(d, d) - along * along).max(0.0).sqrt()
180}
181
182const POSITION_TOLERANCE: f64 = 1e-6;
187const ANGLE_TOLERANCE: f64 = 1e-9;
188
189pub fn geometry_agrees(old: &Value, new: &Value) -> bool {
194 if old["geom"] != new["geom"] {
195 return false;
196 }
197 let (Some(p_old), Some(p_new)) = (triple(&old["point"]), triple(&new["point"])) else {
198 return false;
199 };
200 let directions = (triple(&old["direction"]), triple(&new["direction"]));
201 let radius_agrees = match (old["radius"].as_f64(), new["radius"].as_f64()) {
202 (Some(a), Some(b)) => (a - b).abs() <= POSITION_TOLERANCE * (1.0 + a.abs()),
203 (None, None) => true,
204 _ => false,
205 };
206 let scale = POSITION_TOLERANCE * (1.0 + norm(p_old));
207 match old["geom"].as_str().unwrap_or("") {
208 "plane" => match directions {
209 (Some(n_old), Some(n_new)) => {
210 dot(n_old, n_new) >= 1.0 - ANGLE_TOLERANCE
211 && dot(sub(p_old, p_new), n_new).abs() <= scale
212 }
213 _ => false,
214 },
215 "axis" | "line" => match directions {
216 (Some(d_old), Some(d_new)) => {
217 dot(d_old, d_new).abs() >= 1.0 - ANGLE_TOLERANCE
218 && line_distance(p_old, p_new, d_new) <= scale
219 && radius_agrees
220 }
221 _ => false,
222 },
223 "circle" => match directions {
224 (Some(d_old), Some(d_new)) => {
225 dot(d_old, d_new).abs() >= 1.0 - ANGLE_TOLERANCE
226 && norm(sub(p_old, p_new)) <= scale
227 && radius_agrees
228 }
229 _ => false,
230 },
231 "sphere" | "point" => norm(sub(p_old, p_new)) <= scale && radius_agrees,
232 _ => false,
233 }
234}
235
236fn suggestion_score(old: &Value, new: &Value) -> f64 {
240 let distance = match (triple(&old["point"]), triple(&new["point"])) {
241 (Some(a), Some(b)) => norm(sub(a, b)),
242 _ => f64::INFINITY,
243 };
244 let misalignment = match (triple(&old["direction"]), triple(&new["direction"])) {
245 (Some(a), Some(b)) => {
246 if old["geom"] == "plane" {
247 1.0 - dot(a, b)
248 } else {
249 1.0 - dot(a, b).abs()
250 }
251 }
252 _ => 0.0,
253 };
254 distance + 1000.0 * misalignment
255}
256
257fn local_name<'a>(component: &str, reference: &'a str) -> &'a str {
259 reference
260 .strip_prefix(component)
261 .and_then(|rest| rest.strip_prefix(':'))
262 .unwrap_or(reference)
263}
264
265#[derive(Debug, Clone, PartialEq)]
267pub enum RefOutcome {
268 Kept { split: bool },
270 Unresolved {
274 reason: &'static str,
275 suggestion: Option<Suggestion>,
276 },
277}
278
279#[derive(Debug, Clone, PartialEq)]
280pub struct Suggestion {
281 pub reference: String,
282 pub basis: &'static str,
284 pub pre_ticked: bool,
287}
288
289impl Suggestion {
290 fn to_json(&self) -> Value {
291 json!({ "ref": self.reference, "basis": self.basis, "preTicked": self.pre_ticked })
292 }
293}
294
295pub fn classify_ref<V: std::borrow::Borrow<Value>>(
300 component: &str,
301 reference: &str,
302 pre: &Value,
303 candidates: &[V],
304 old_names: &BTreeSet<String>,
305 trusted: bool,
306) -> RefOutcome {
307 let name = local_name(component, reference);
308 let by_name = candidates
309 .iter()
310 .map(Borrow::borrow)
311 .find(|candidate| candidate["ref"].as_str().map(|r| local_name(component, r)) == Some(name));
312 if trusted {
313 match by_name {
314 Some(candidate) if candidate["geom"] == pre["geom"] => {
315 let split_piece = format!("{name}_1");
316 let split = !old_names.contains(&split_piece)
317 && candidates.iter().map(Borrow::borrow).any(|c: &Value| {
318 c["ref"].as_str().map(|r| local_name(component, r)) == Some(split_piece.as_str())
319 });
320 return RefOutcome::Kept { split };
321 }
322 Some(_) => {
323 return RefOutcome::Unresolved {
324 reason: "type-changed",
325 suggestion: nearest(pre, candidates),
326 }
327 }
328 None => {
329 return RefOutcome::Unresolved { reason: "missing", suggestion: nearest(pre, candidates) }
330 }
331 }
332 }
333 let suggestion = match by_name {
334 Some(candidate) if candidate["geom"] == pre["geom"] => Some(Suggestion {
335 reference: candidate["ref"].as_str().unwrap_or_default().to_string(),
336 basis: "same-name",
337 pre_ticked: geometry_agrees(pre, candidate),
338 }),
339 _ => nearest(pre, candidates),
340 };
341 RefOutcome::Unresolved { reason: "unconfirmed", suggestion }
342}
343
344pub fn classify_vertex_ref(reference: &str, pre: &Value, post: Option<&Value>, trusted: bool) -> RefOutcome {
350 let found = post.filter(|row| row["ok"] == true);
351 let same_point = found.is_some_and(|row| geometry_agrees(pre, row));
352 if trusted && same_point {
353 return RefOutcome::Kept { split: false };
354 }
355 let suggestion = found.map(|_| Suggestion {
356 reference: reference.to_string(),
357 basis: "same-name",
358 pre_ticked: same_point,
359 });
360 let reason = match (trusted, found) {
361 (false, _) => "unconfirmed",
362 (true, Some(_)) => "moved",
363 (true, None) => "missing",
364 };
365 RefOutcome::Unresolved { reason, suggestion }
366}
367
368fn nearest<V: std::borrow::Borrow<Value>>(pre: &Value, candidates: &[V]) -> Option<Suggestion> {
371 candidates
372 .iter()
373 .map(Borrow::borrow)
374 .filter(|candidate| candidate["geom"] == pre["geom"])
375 .map(|candidate| (suggestion_score(pre, candidate), candidate))
376 .filter(|(score, _)| score.is_finite())
377 .min_by(|a, b| a.0.total_cmp(&b.0))
378 .map(|(_, candidate)| Suggestion {
379 reference: candidate["ref"].as_str().unwrap_or_default().to_string(),
380 basis: "nearest",
381 pre_ticked: geometry_agrees(pre, candidate),
382 })
383}
384
385pub fn marker_json(origin: &str, from: &str, to: &str, was_enabled: bool, refs: Vec<Value>) -> Value {
389 json!({
390 "origin": origin,
391 "from": from,
392 "to": to,
393 "wasEnabled": was_enabled,
394 "refs": refs,
395 })
396}
397
398fn unique_carrier(pre: &Value, candidates: &[&Value]) -> Option<String> {
402 let mut agreeing = candidates.iter().filter(|candidate| geometry_agrees(pre, candidate));
403 let only = agreeing.next()?;
404 if agreeing.next().is_some() {
405 return None;
406 }
407 only["ref"].as_str().map(str::to_string)
408}
409
410#[derive(Debug, Clone)]
416pub(crate) struct AffectedMate {
417 id: String,
418 constraint_type: String,
419 was_enabled: bool,
420 refs: Vec<(String, String, Value)>,
422 home: Option<(String, String)>,
426}
427
428#[derive(Debug, Clone)]
430pub(crate) struct PendingReplace {
431 generation: u64,
432 components: Vec<String>,
433 from: BTreeMap<String, String>,
434 to: String,
435 lineage: BTreeMap<String, &'static str>,
437 affected: Vec<AffectedMate>,
438 old_names: BTreeMap<String, BTreeSet<String>>,
440 notes: Vec<String>,
442 origin: &'static str,
444 signatures: BTreeMap<String, String>,
447}
448
449
450#[derive(Debug, Clone)]
452pub struct ReplaceCapture {
453 components: Vec<String>,
454 affected: Vec<AffectedMate>,
455 old_names: BTreeMap<String, BTreeSet<String>>,
456}
457
458pub fn entries_lineage(old: &Value, new: &Value, canonicalize: &dyn Fn(&str) -> String) -> Option<&'static str> {
461 let old_keys = lineage_keys(&old["document"], old["sourceKey"].as_str().unwrap_or(""), canonicalize);
462 let new_keys = lineage_keys(&new["document"], new["sourceKey"].as_str().unwrap_or(""), canonicalize);
463 shared_lineage(&old_keys, &new_keys)
464}
465
466
467
468#[derive(Default)]
471struct EntityListings {
472 by_top: BTreeMap<String, Vec<Value>>,
473 names_by_owner: BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
478 rows_by_owner: BTreeMap<String, BTreeMap<String, Vec<usize>>>,
484}
485
486fn owners_below<'a>(top: &'a str, reference: &'a str) -> impl Iterator<Item = String> + 'a {
489 let rest = reference.strip_prefix(top).and_then(|r| r.strip_prefix(':')).unwrap_or("");
490 rest.match_indices(':').map(move |(at, _)| format!("{top}:{}", &rest[..at]))
491}
492
493impl EntityListings {
494 fn listed(&mut self, top: &str) -> &[Value] {
496 self.by_top.entry(top.to_string()).or_insert_with(|| {
497 entities_of(top)
498 })
499 }
500
501 fn index(&mut self, path: &str) {
503 let top = path.split(':').next().unwrap_or(path).to_string();
504 if self.rows_by_owner.contains_key(&top) {
505 return;
506 }
507 let rows = self.listed(&top);
508 let mut index: BTreeMap<String, Vec<usize>> = BTreeMap::new();
509 index.insert(top.clone(), (0..rows.len()).collect());
510 for (at, row) in rows.iter().enumerate() {
511 let Some(reference) = row["ref"].as_str() else { continue };
512 for owner in owners_below(&top, reference) {
513 index.entry(owner).or_default().push(at);
514 }
515 }
516 self.rows_by_owner.insert(top, index);
517 }
518
519 fn under(&self, path: &str) -> Vec<&Value> {
523 let top = path.split(':').next().unwrap_or(path);
524 let (Some(rows), Some(index)) = (self.by_top.get(top), self.rows_by_owner.get(top)) else {
525 return Vec::new();
526 };
527 index.get(path).into_iter().flatten().map(|&at| &rows[at]).collect()
528 }
529
530 fn names(&mut self, path: &str) -> BTreeSet<String> {
533 let top = path.split(':').next().unwrap_or(path).to_string();
534 if !self.names_by_owner.contains_key(&top) {
535 self.listed(&top);
536 let mut index: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
537 for row in self.by_top.get(&top).into_iter().flatten() {
538 let Some(reference) = row["ref"].as_str() else { continue };
539 let Some(rest) = reference.strip_prefix(&top).and_then(|r| r.strip_prefix(':')) else {
540 index.entry(top.clone()).or_default().insert(reference.to_string());
541 continue;
542 };
543 let mut owner = top.clone();
546 index.entry(owner.clone()).or_default().insert(rest.to_string());
547 let mut tail = rest;
548 while let Some((segment, after)) = tail.split_once(':') {
549 owner = format!("{owner}:{segment}");
550 index.entry(owner.clone()).or_default().insert(after.to_string());
551 tail = after;
552 }
553 }
554 self.names_by_owner.insert(top.clone(), index);
555 }
556 self.names_by_owner[&top].get(path).cloned().unwrap_or_default()
557 }
558}
559
560fn entities_of(path: &str) -> Vec<Value> {
563 let top = path.split(':').next().unwrap_or(path);
564 let prefix = format!("{path}:");
565 parse(&brep_kernel::assembly_component_entities_json(top))
566 .as_array()
567 .cloned()
568 .unwrap_or_default()
569 .into_iter()
570 .filter(|row| top == path || row["ref"].as_str().is_some_and(|r| r.starts_with(&prefix)))
571 .collect()
572}
573
574fn document_in_chain_mut<'a>(document: &'a mut Value, chain: &[String]) -> Option<&'a mut Value> {
577 let mut current = document;
578 for part in chain {
579 current = current.get_mut("partsLibrary")?.get_mut(part.as_str())?.get_mut("document")?;
580 }
581 Some(current)
582}
583
584fn owner_among<'a>(ids: &'a [String], reference: &str) -> Option<&'a String> {
586 ids.iter().find(|id| {
587 reference == id.as_str()
588 || reference
589 .strip_prefix(id.as_str())
590 .is_some_and(|rest| rest.starts_with(':'))
591 })
592}
593
594pub fn follow_pattern_seeds(
602 document: &Value,
603 from: &BTreeMap<String, String>,
604 to: &str,
605 instances: &[String],
606) -> Vec<String> {
607 let mut notes = Vec::new();
608 for feature in document["features"].as_array().into_iter().flatten() {
609 if feature["type"] != "APAT" {
610 continue;
611 }
612 let pattern = feature["inputParams"]["id"].as_str().unwrap_or_default().to_string();
613 let mut seeded = BTreeSet::new();
614 for name in feature["inputParams"]["seeds"].as_array().into_iter().flatten().filter_map(Value::as_str) {
615 let owner = name.split(':').next().unwrap_or(name).to_string();
616 if from.contains_key(&owner) {
617 seeded.insert(owner);
618 }
619 }
620 for owner in seeded {
621 let count = instances
622 .iter()
623 .filter_map(|id| brep_kernel::pattern_component_instance(id))
624 .filter(|(p, s, _)| *p == pattern && *s == owner)
625 .count();
626 notes.push(format!("{pattern}: its {count} instance(s) of {owner} follow the seed and now show '{to}'"));
627 }
628 }
629 notes
630}
631
632fn parse(json: &str) -> Value {
633 serde_json::from_str(json).unwrap_or(Value::Null)
634}
635
636impl EngineState {
637 pub fn replace_components(
644 &mut self,
645 component_ids: &[String],
646 insert: ComponentInsert<'_>,
647 canonicalize: &dyn Fn(&str) -> String,
648 ) -> Result<String, String> {
649 if component_ids.is_empty() {
650 return Err("replace: no component given".into());
651 }
652 let mut ids: Vec<String> = Vec::new();
656 let mut instance_notes = Vec::new();
657 for id in component_ids {
658 let id = match brep_kernel::pattern_component_instance(id) {
659 Some((pattern, seed, n)) => {
660 instance_notes.push(format!(
661 "{id} is instance {n} of {pattern} and follows its seed {seed}: the seed was replaced"
662 ));
663 seed
664 }
665 None => id.clone(),
666 };
667 if !ids.contains(&id) {
668 ids.push(id);
669 }
670 }
671 let component_ids = ids.as_slice();
672 let mut from = BTreeMap::new();
673 for id in component_ids {
674 let info = self
675 .component_info(id)
676 .ok_or_else(|| format!("replace: '{id}' is not an assembly component"))?;
677 from.insert(id.clone(), info.part_name);
678 }
679 let capture = self.capture_replace(component_ids)?;
680
681 let old_library = self.history.parts_library().clone();
683 let to = self.resolve_component_insert(insert)?;
684 let library = parse(&brep_kernel::parts_library_json());
685 let new_entry = &library[&to];
686 let mut lineage = BTreeMap::new();
687 for (id, part) in &from {
688 if part == &to {
689 continue;
690 }
691 let old_entry = if old_library[part].is_object() { &old_library[part] } else { &library[part] };
692 if let Some(word) = entries_lineage(old_entry, new_entry, canonicalize) {
693 lineage.insert(id.clone(), word);
694 }
695 }
696 if from.values().all(|part| part == &to) {
697 return Err(format!("replace: the component already shows '{to}'"));
698 }
699
700 let mut document = parse(&self.history_request_json());
704 document["partsLibrary"] = library.clone();
705 for feature in document["features"].as_array_mut().into_iter().flatten() {
706 let id = feature["inputParams"]["id"].as_str().unwrap_or_default().to_string();
707 if from.contains_key(&id) {
708 feature["inputParams"]["partName"] = Value::String(to.clone());
709 }
710 }
711 let mut notes = instance_notes;
712 notes.extend(follow_pattern_seeds(&document, &from, &to, &self.pattern_instance_ids()));
713 self.commit_replace(capture, document, from, to.clone(), lineage, notes)?;
714 Ok(to)
715 }
716
717 pub fn capture_replace(&mut self, paths: &[String]) -> Result<ReplaceCapture, String> {
727 self.capture_replace_listed(paths, &mut EntityListings::default())
728 }
729
730 fn capture_replace_listed(&mut self, paths: &[String], listings: &mut EntityListings) -> Result<ReplaceCapture, String> {
734 if !self.ensure_assembly_session() {
735 return Err(super::ASSEMBLY_SESSION_PENDING.into());
736 }
737 let state = parse(&brep_kernel::assembly_state_json());
738 let mut affected = Vec::new();
739 for entry in state["constraints"].as_array().into_iter().flatten() {
740 let refs: Vec<(String, String)> = entry["inputParams"]["elements"]
741 .as_array()
742 .into_iter()
743 .flatten()
744 .filter_map(Value::as_str)
745 .filter_map(|r| owner_among(paths, r).map(|owner| (owner.clone(), r.to_string())))
746 .collect();
747 if refs.is_empty() {
748 continue;
749 }
750 let enabled = entry["enabled"].as_bool().unwrap_or(true);
751 let status = entry["persistentData"]["status"].as_str().unwrap_or("");
752 if enabled && BROKEN.contains(&status) {
753 continue; }
755 let names: Vec<&String> = refs.iter().map(|(_, r)| r).collect();
756 let rows = parse(&brep_kernel::assembly_resolve_refs_json(
757 &serde_json::to_string(&names).unwrap_or_default(),
758 ));
759 let rows = rows.as_array().cloned().unwrap_or_default();
760 affected.push(AffectedMate {
761 id: entry["inputParams"]["id"].as_str().unwrap_or_default().to_string(),
762 constraint_type: entry["type"].as_str().unwrap_or_default().to_string(),
763 was_enabled: enabled,
764 refs: refs
765 .into_iter()
766 .zip(rows.into_iter().chain(std::iter::repeat(Value::Null)))
767 .map(|((owner, r), row)| (owner, r, row))
768 .collect(),
769 home: None,
770 });
771 }
772 let mut old_names = BTreeMap::new();
773 for path in paths {
774 old_names.insert(path.clone(), listings.names(path));
775 }
776 Ok(ReplaceCapture { components: paths.to_vec(), affected, old_names })
777 }
778
779 pub fn capture_part_edit(&mut self, paths: &[String]) -> Result<ReplaceCapture, String> {
786 let mut listings = EntityListings::default();
790 let mut capture = self.capture_replace_listed(paths, &mut listings)?;
791 let mut seen: BTreeSet<Vec<String>> = BTreeSet::new();
794 let mut stack: Vec<String> = paths.to_vec();
795 while let Some(path) = stack.pop() {
796 let Some(chain) = self.part_chain(&path) else { continue };
797 if !seen.insert(chain.clone()) {
798 continue;
799 }
800 let Some(document) = self.document_in_chain(&chain) else { continue };
801 for feature in document["features"].as_array().into_iter().flatten() {
802 if super::components::is_acomp_feature_type(feature["type"].as_str().unwrap_or("")) {
803 if let Some(id) = feature["inputParams"]["id"].as_str() {
804 stack.push(format!("{path}:{id}"));
805 }
806 }
807 }
808 for entry in document["assembly"]["constraints"].as_array().into_iter().flatten() {
809 let inner_id = entry["inputParams"]["id"].as_str().unwrap_or_default();
810 let refs: Vec<(String, String)> = entry["inputParams"]["elements"]
811 .as_array()
812 .into_iter()
813 .flatten()
814 .filter_map(Value::as_str)
815 .map(|r| {
816 let occurrence = r.split(':').next().unwrap_or(r);
817 (format!("{path}:{occurrence}"), format!("{path}:{r}"))
818 })
819 .collect();
820 if inner_id.is_empty() || refs.is_empty() {
821 continue;
822 }
823 let enabled = entry["enabled"].as_bool().unwrap_or(true);
824 let status = entry["persistentData"]["status"].as_str().unwrap_or("");
825 if enabled && BROKEN.contains(&status) {
826 continue; }
828 let names: Vec<&String> = refs.iter().map(|(_, r)| r).collect();
829 let rows = parse(&brep_kernel::assembly_resolve_refs_json(
830 &serde_json::to_string(&names).unwrap_or_default(),
831 ));
832 let rows = rows.as_array().cloned().unwrap_or_default();
833 if rows.len() != refs.len() || rows.iter().any(|row| row["ok"] != true) {
837 continue;
838 }
839 for (owner, _) in &refs {
840 if !capture.old_names.contains_key(owner) {
841 let names = listings.names(owner);
842 capture.old_names.insert(owner.clone(), names);
843 }
844 }
845 capture.affected.push(AffectedMate {
846 id: format!("{path}:{inner_id}"),
847 constraint_type: entry["type"].as_str().unwrap_or_default().to_string(),
848 was_enabled: enabled,
849 refs: refs
850 .into_iter()
851 .zip(rows.into_iter().chain(std::iter::repeat(Value::Null)))
852 .map(|((owner, r), row)| (owner, r, row))
853 .collect(),
854 home: Some((path.clone(), inner_id.to_string())),
855 });
856 }
857 }
858 Ok(capture)
859 }
860
861 fn write_back_inner_mates(
868 &mut self,
869 affected: &[AffectedMate],
870 reattached: &[(String, String, String)],
871 markers: &BTreeMap<String, Value>,
872 ) {
873 let touched: Vec<&AffectedMate> = affected
874 .iter()
875 .filter(|mate| mate.home.is_some())
876 .filter(|mate| markers.contains_key(&mate.id) || reattached.iter().any(|(id, _, _)| *id == mate.id))
877 .collect();
878 if touched.is_empty() {
879 return;
880 }
881 let Ok(mut document) = serde_json::from_str::<Value>(&self.history.request_json()) else { return };
882 let mut chains: BTreeSet<Vec<String>> = BTreeSet::new();
883 for mate in touched {
884 let (home, inner_id) = mate.home.as_ref().expect("filtered");
885 let Some(chain) = self.part_chain(home) else { continue };
886 let Some(inner) = document_in_chain_mut(&mut document, &chain) else { continue };
887 let prefix = format!("{home}:");
888 let local = |reference: &str| reference.strip_prefix(&prefix).unwrap_or(reference).to_string();
889 for entry in inner["assembly"]["constraints"].as_array_mut().into_iter().flatten() {
890 if entry["inputParams"]["id"].as_str() != Some(inner_id.as_str()) {
891 continue;
892 }
893 for (_, old_ref, new_ref) in reattached.iter().filter(|(id, _, _)| *id == mate.id) {
894 for element in entry["inputParams"]["elements"].as_array_mut().into_iter().flatten() {
895 if element == local(old_ref).as_str() {
896 *element = Value::String(local(new_ref));
897 }
898 }
899 }
900 if let Some(marker) = markers.get(&mate.id) {
901 let mut marker = marker.clone();
902 for row in marker["refs"].as_array_mut().into_iter().flatten() {
903 if let Some(reference) = row["ref"].as_str().map(|r| local(r)) {
904 row["ref"] = Value::String(reference);
905 }
906 if let Some(reference) = row["suggestion"]["ref"].as_str().map(|r| local(r)) {
907 row["suggestion"]["ref"] = Value::String(reference);
908 }
909 }
910 entry["enabled"] = Value::Bool(false);
911 if !entry["persistentData"].is_object() {
912 entry["persistentData"] = json!({});
913 }
914 entry["persistentData"][REPLACE_MARKER] = marker;
915 }
916 }
917 chains.insert(chain);
918 }
919 let mut prefixes: BTreeSet<Vec<String>> = BTreeSet::new();
921 for chain in &chains {
922 for depth in 1..=chain.len() {
923 prefixes.insert(chain[..depth].to_vec());
924 }
925 }
926 let mut prefixes: Vec<Vec<String>> = prefixes.into_iter().collect();
927 prefixes.sort_by_key(|chain| std::cmp::Reverse(chain.len()));
928 for chain in prefixes {
929 let (last, parent) = chain.split_last().expect("non-empty");
930 let library = if parent.is_empty() {
931 Some(&mut document["partsLibrary"])
932 } else {
933 document_in_chain_mut(&mut document, parent).map(|doc| &mut doc["partsLibrary"])
934 };
935 let Some(entry) = library.and_then(|library| library.get_mut(last.as_str())) else { continue };
936 let signature = super::assembly_ops::document_signature(&entry["document"].to_string());
937 entry["sourceSignature"] = Value::String(signature);
938 entry["snapshot"] = Value::String(String::new());
939 if let Some(object) = entry.as_object_mut() {
940 object.remove("nestedRows");
941 }
942 }
943 let written = serde_json::from_value::<brep_kernel::PartsLibraryMap>(document["partsLibrary"].clone())
946 .map_err(|error| error.to_string())
947 .and_then(|library| self.history.adopt_document(&document.to_string()).map(|()| library));
948 match written {
949 Ok(library) => {
950 brep_kernel::install_parts_library(&library);
951 }
952 Err(error) => {
953 self.push_notice(format!("part edit: the sub-assembly mates could not be written: {error}"));
954 }
955 }
956 }
957
958 fn document_in_chain(&self, chain: &[String]) -> Option<&Value> {
961 let mut library = self.history.parts_library();
962 let mut document = None;
963 for part in chain {
964 let entry = library.get(part.as_str())?;
965 document = Some(&entry["document"]);
966 library = &entry["document"]["partsLibrary"];
967 }
968 document
969 }
970
971 fn part_chain(&self, path: &str) -> Option<Vec<String>> {
975 let mut segments = path.split(':');
976 let top = segments.next()?;
977 let index = self.history.index_of(top)?;
978 let mut part = self.history.feature_params(index)?["partName"].as_str()?.to_string();
979 let mut chain = vec![part.clone()];
980 let mut library = self.history.parts_library();
981 for id in segments {
982 let document = &library.get(part.as_str())?["document"];
983 part = document["features"]
984 .as_array()?
985 .iter()
986 .find(|f| f["inputParams"]["id"].as_str() == Some(id))?["inputParams"]["partName"]
987 .as_str()?
988 .to_string();
989 chain.push(part.clone());
990 library = &document["partsLibrary"];
991 }
992 Some(chain)
993 }
994
995 pub fn commit_replace(
1001 &mut self,
1002 capture: ReplaceCapture,
1003 mut document: Value,
1004 from: BTreeMap<String, String>,
1005 to: String,
1006 lineage: BTreeMap<String, &'static str>,
1007 notes: Vec<String>,
1008 ) -> Result<(), String> {
1009 let untrusted: BTreeSet<&String> =
1010 capture.components.iter().filter(|id| !lineage.contains_key(*id)).collect();
1011 if let Some(constraints) = document["assembly"]["constraints"].as_array_mut() {
1012 for entry in constraints.iter_mut() {
1013 let id = entry["inputParams"]["id"].as_str().unwrap_or_default();
1014 let Some(mate) = capture.affected.iter().find(|m| m.id == id) else { continue };
1015 if mate.refs.iter().any(|(owner, _, _)| untrusted.contains(owner)) {
1016 entry["enabled"] = Value::Bool(false);
1017 }
1018 }
1019 }
1020 self.edit_document(document)?;
1021 self.replace_pending = Some(PendingReplace {
1022 generation: self.run_generation,
1023 components: capture.components,
1024 from,
1025 to,
1026 lineage,
1027 affected: capture.affected,
1028 old_names: capture.old_names,
1029 notes,
1030 origin: "replace",
1031 signatures: BTreeMap::new(),
1032 });
1033 self.last_replace_report = None;
1034 if !self.run_pending() {
1035 self.finish_component_replace();
1036 }
1037 Ok(())
1038 }
1039
1040 pub fn commit_part_edit(&mut self, capture: ReplaceCapture, document: Value, parts: &[String]) -> Result<(), String> {
1047 self.finish_component_replace();
1050 if self.replace_pending.is_some() {
1051 return Err("a component replace is still landing; try again in a moment".into());
1052 }
1053 let signatures: BTreeMap<String, String> = parts
1054 .iter()
1055 .map(|part| {
1056 let signature = document["partsLibrary"][part]["sourceSignature"].as_str().unwrap_or_default();
1057 (part.clone(), signature.to_string())
1058 })
1059 .collect();
1060 let from: BTreeMap<String, String> = capture
1061 .components
1062 .iter()
1063 .filter_map(|path| Some((path.clone(), self.part_at_path(path)?)))
1064 .collect();
1065 self.edit_document(document)?;
1066 if capture.affected.is_empty() {
1067 return Ok(());
1068 }
1069 self.replace_pending = Some(PendingReplace {
1070 generation: self.run_generation,
1071 lineage: capture.components.iter().map(|path| (path.clone(), "edit")).collect(),
1072 components: capture.components,
1073 to: parts.join(", "),
1074 from,
1075 affected: capture.affected,
1076 old_names: capture.old_names,
1077 notes: Vec::new(),
1078 origin: "edit",
1079 signatures,
1080 });
1081 self.last_replace_report = None;
1082 if !self.run_pending() {
1083 self.finish_component_replace();
1084 }
1085 Ok(())
1086 }
1087
1088 pub fn components_of_parts(&self, parts: &[String]) -> Vec<String> {
1090 self.history
1091 .features()
1092 .iter()
1093 .filter(|feature| super::components::is_acomp_feature_type(feature["type"].as_str().unwrap_or("")))
1094 .filter(|feature| {
1095 feature["inputParams"]["partName"].as_str().is_some_and(|part| parts.iter().any(|p| p == part))
1096 })
1097 .filter_map(|feature| feature["inputParams"]["id"].as_str().map(str::to_string))
1098 .collect()
1099 }
1100
1101 pub(crate) fn finish_component_replace(&mut self) {
1105 let Some(pending) = self.replace_pending.as_ref() else { return };
1106 if self.run_pending() || self.applied_generation < pending.generation {
1107 return;
1108 }
1109 if !self.ensure_assembly_session() {
1112 return;
1113 }
1114 let pending = self.replace_pending.take().expect("checked above");
1115 let landed = if pending.origin == "edit" {
1120 pending.signatures.iter().all(|(part, signature)| {
1121 self.history.parts_library()[part.as_str()]["sourceSignature"].as_str() == Some(signature.as_str())
1122 })
1123 } else {
1124 pending.components.iter().all(|path| self.part_at_path(path).as_deref() == Some(pending.to.as_str()))
1125 };
1126 if !landed {
1127 self.last_replace_report = None;
1128 return;
1129 }
1130 let statuses = parse(&brep_kernel::assembly_statuses_json());
1131 let nested = parse(&brep_kernel::assembly_dof_json())["nestedConstraints"].clone();
1133 let status_of = |id: &str| -> String {
1134 statuses
1135 .as_array()
1136 .into_iter()
1137 .flatten()
1138 .chain(nested.as_array().into_iter().flatten())
1139 .find(|row| row["id"] == id)
1140 .and_then(|row| row["status"].as_str())
1141 .unwrap_or("")
1142 .to_string()
1143 };
1144 let vertex_refs: Vec<&String> = pending
1147 .affected
1148 .iter()
1149 .flat_map(|mate| mate.refs.iter().map(|(_, r, _)| r))
1150 .filter(|r| r.contains('@'))
1151 .collect();
1152 let post_vertex: BTreeMap<String, Value> = if vertex_refs.is_empty() {
1153 BTreeMap::new()
1154 } else {
1155 parse(&brep_kernel::assembly_resolve_refs_json(&serde_json::to_string(&vertex_refs).unwrap_or_default()))
1156 .as_array()
1157 .cloned()
1158 .unwrap_or_default()
1159 .into_iter()
1160 .filter_map(|row| Some((row["ref"].as_str()?.to_string(), row)))
1161 .collect()
1162 };
1163 let mut listings = EntityListings::default();
1168 let owners: BTreeSet<&String> = pending
1169 .affected
1170 .iter()
1171 .flat_map(|mate| mate.refs.iter().map(move |(owner, _, _)| (mate, owner)))
1172 .filter(|(mate, owner)| mate.home.is_some() || pending.components.contains(owner))
1173 .map(|(_, owner)| owner)
1174 .collect();
1175 for owner in &owners {
1176 listings.index(owner);
1177 }
1178 let entities: BTreeMap<&String, Vec<&Value>> = owners.iter().map(|owner| (*owner, listings.under(owner))).collect();
1179
1180 let mut kept = Vec::new();
1181 let mut unresolved = Vec::new();
1182 let mut notes = pending.notes.clone();
1183 let mut markers: BTreeMap<String, Value> = BTreeMap::new();
1184 let mut reattached: Vec<(String, String, String)> = Vec::new();
1186 for mate in &pending.affected {
1187 let mut ref_rows = Vec::new();
1188 for (owner, reference, pre) in &mate.refs {
1189 let trusted = pending.lineage.contains_key(owner)
1192 || (mate.home.is_some() && owner_among(&pending.components, owner).is_some_and(|top| pending.lineage.contains_key(top)));
1193 let outcome = if pre["ok"] != true {
1194 RefOutcome::Unresolved { reason: "missing", suggestion: None }
1198 } else if reference.contains('@') {
1199 classify_vertex_ref(reference, pre, post_vertex.get(reference.as_str()), trusted)
1200 } else {
1201 classify_ref(
1202 owner,
1203 reference,
1204 pre,
1205 entities.get(owner).map(Vec::as_slice).unwrap_or(&[]),
1206 pending.old_names.get(owner).unwrap_or(&BTreeSet::new()),
1207 trusted,
1208 )
1209 };
1210 match outcome {
1211 RefOutcome::Kept { split } => {
1212 if split {
1213 notes.push(format!(
1214 "{}: '{}' was split by the new part; the mate keeps the piece that kept the name (same carrier)",
1215 mate.id, reference
1216 ));
1217 }
1218 }
1219 RefOutcome::Unresolved { reason, suggestion } => {
1220 let only = (pending.origin == "edit" && !reference.contains('@'))
1221 .then(|| unique_carrier(pre, entities.get(owner).map(Vec::as_slice).unwrap_or(&[])))
1222 .flatten();
1223 match only {
1224 Some(new_ref) => reattached.push((mate.id.clone(), reference.clone(), new_ref)),
1225 None => ref_rows.push(json!({
1226 "ref": reference,
1227 "reason": reason,
1228 "suggestion": suggestion.as_ref().map(Suggestion::to_json),
1229 })),
1230 }
1231 }
1232 }
1233 }
1234 let status = status_of(&mate.id);
1238 let mate_reattached = reattached.iter().any(|(id, _, _)| *id == mate.id);
1241 if ref_rows.is_empty() && !mate_reattached && mate.was_enabled && BROKEN.contains(&status.as_str()) {
1242 for (_, reference, _) in &mate.refs {
1243 ref_rows.push(json!({ "ref": reference, "reason": "no-longer-maps", "suggestion": null }));
1244 }
1245 }
1246 if ref_rows.is_empty() {
1247 kept.push(json!({ "id": mate.id, "type": mate.constraint_type }));
1248 continue;
1249 }
1250 let owner = &mate.refs[0].0;
1251 let marker = marker_json(
1252 pending.origin,
1253 &pending.from.get(owner).cloned().or_else(|| self.part_at_path(owner)).unwrap_or_default(),
1254 &pending.to,
1255 mate.was_enabled,
1256 ref_rows,
1257 );
1258 unresolved.push(json!({
1259 "id": mate.id,
1260 "type": mate.constraint_type,
1261 "refs": marker["refs"],
1262 }));
1263 markers.insert(mate.id.clone(), marker);
1264 }
1265
1266 if !markers.is_empty() || !reattached.is_empty() {
1267 let mut block = self.history.assembly_block().cloned().unwrap_or(Value::Null);
1268 let mut disabled_now = false;
1269 for entry in block["constraints"].as_array_mut().into_iter().flatten() {
1270 let id = entry["inputParams"]["id"].as_str().unwrap_or_default().to_string();
1271 for (mate, old_ref, new_ref) in &reattached {
1272 if *mate != id {
1273 continue;
1274 }
1275 for element in entry["inputParams"]["elements"].as_array_mut().into_iter().flatten() {
1276 if element == old_ref.as_str() {
1277 *element = Value::String(new_ref.clone());
1278 }
1279 }
1280 }
1281 let Some(marker) = markers.get(&id) else { continue };
1282 if entry["enabled"] != false {
1283 entry["enabled"] = Value::Bool(false);
1284 disabled_now = true;
1285 }
1286 if !entry["persistentData"].is_object() {
1287 entry["persistentData"] = json!({});
1288 }
1289 entry["persistentData"][REPLACE_MARKER] = marker.clone();
1290 }
1291 self.history.set_assembly_block(block, false);
1292 self.write_back_inner_mates(&pending.affected, &reattached, &markers);
1293 let _ = disabled_now;
1297 self.rerun_history();
1298 }
1299
1300 if pending.origin == "edit" && (!reattached.is_empty() || !unresolved.is_empty()) {
1303 let mut lines = Vec::new();
1304 if !reattached.is_empty() {
1305 let moves: Vec<String> = reattached.iter().map(|(id, from, to)| format!("{id} {from} → {to}")).collect();
1306 lines.push(format!("re-attached {}", moves.join(", ")));
1307 }
1308 if !unresolved.is_empty() {
1309 let ids: Vec<&str> = unresolved.iter().filter_map(|row| row["id"].as_str()).collect();
1310 lines.push(format!(
1311 "held for Repair (Constraints panel): {} — the face or edge it used is gone and no single one replaces it",
1312 ids.join(", ")
1313 ));
1314 }
1315 let severity = if unresolved.is_empty() { NoticeSeverity::Info } else { NoticeSeverity::Warning };
1316 self.push_notice_as(severity, format!("Mates after editing {}: {}.", pending.to, lines.join("; ")));
1317 }
1318 let report = json!({
1319 "ok": true,
1320 "origin": pending.origin,
1321 "reattached": reattached.iter().map(|(id, from, to)| json!({ "id": id, "from": from, "to": to })).collect::<Vec<_>>(),
1322 "components": pending.components,
1323 "from": pending.from,
1324 "to": pending.to,
1325 "lineage": pending.components.iter().map(|id| {
1326 (id.clone(), Value::String(pending.lineage.get(id).copied().unwrap_or("none").to_string()))
1327 }).collect::<serde_json::Map<String, Value>>(),
1328 "kept": kept,
1329 "unresolved": unresolved,
1330 "notes": notes,
1331 });
1332 self.last_replace_report = Some(report);
1333 }
1334
1335 pub fn occurrence_entities(&mut self, path: &str) -> Result<Vec<Value>, String> {
1341 if !self.ensure_assembly_session() {
1342 return Err(super::ASSEMBLY_SESSION_PENDING.into());
1343 }
1344 Ok(entities_of(path))
1345 }
1346
1347 pub fn resolve_refs(&mut self, refs: &[String]) -> Result<Vec<Value>, String> {
1352 if !self.ensure_assembly_session() {
1353 return Err(super::ASSEMBLY_SESSION_PENDING.into());
1354 }
1355 Ok(parse(&brep_kernel::assembly_resolve_refs_json(&serde_json::to_string(refs).unwrap_or_default()))
1356 .as_array()
1357 .cloned()
1358 .unwrap_or_default())
1359 }
1360
1361 pub fn replace_report(&mut self) -> Value {
1366 self.finish_component_replace();
1367 match &self.last_replace_report {
1370 Some(report) if self.report_in_effect(report) => report.clone(),
1371 _ => Value::Null,
1372 }
1373 }
1374
1375 fn report_in_effect(&self, report: &Value) -> bool {
1376 let to = report["to"].as_str().unwrap_or_default();
1377 report["components"]
1378 .as_array()
1379 .is_some_and(|paths| paths.iter().filter_map(Value::as_str).all(|path| self.part_at_path(path).as_deref() == Some(to)))
1380 }
1381
1382 pub fn part_at_path(&self, path: &str) -> Option<String> {
1386 let mut segments = path.split(':');
1387 let top = segments.next()?;
1388 let index = self.history.index_of(top)?;
1389 let mut part = self.history.feature_params(index)?["partName"].as_str()?.to_string();
1390 let mut library = self.history.parts_library();
1391 for id in segments {
1392 let document = &library[&part]["document"];
1393 part = document["features"]
1394 .as_array()?
1395 .iter()
1396 .find(|f| f["inputParams"]["id"].as_str() == Some(id))?["inputParams"]["partName"]
1397 .as_str()?
1398 .to_string();
1399 library = &document["partsLibrary"];
1400 }
1401 Some(part)
1402 }
1403
1404 pub fn replace_unresolved(&self) -> Value {
1407 let rows: Vec<Value> = self
1408 .history
1409 .assembly_block()
1410 .and_then(|block| block["constraints"].as_array().cloned())
1411 .unwrap_or_default()
1412 .into_iter()
1413 .filter(|entry| entry["persistentData"][REPLACE_MARKER].is_object())
1414 .map(|entry| {
1415 let marker = &entry["persistentData"][REPLACE_MARKER];
1416 json!({
1417 "id": entry["inputParams"]["id"],
1418 "type": entry["type"],
1419 "origin": marker["origin"].as_str().unwrap_or("replace"),
1420 "from": marker["from"],
1421 "to": marker["to"],
1422 "refs": marker["refs"],
1423 })
1424 })
1425 .collect();
1426 Value::Array(rows)
1427 }
1428
1429 pub fn begin_ref_select_for_replace_repair(&mut self, mate: &str, old_ref: &str) {
1435 let filter = vec!["FACE".to_string(), "EDGE".to_string()];
1436 let restore_index = self.history.rollback();
1437 self.selection_filter = SelectionFilter::from_ref_filter(&filter);
1438 self.replace_repair_pick = None;
1439 self.ref_select = Some(RefSelectState {
1440 feature_id: mate.to_string(),
1441 path: vec![old_ref.to_string()],
1442 label: format!("Replacement for {old_ref}"),
1443 filter,
1444 multiple: false,
1445 names: Vec::new(),
1446 restore_index,
1447 target: RefSelectTarget::ReplaceRepair,
1448 picks: 0,
1449 claimed: false,
1450 finish_requested: false,
1451 });
1452 self.sync_ref_select_emphasis();
1453 }
1454
1455 pub fn take_replace_repair_pick(&mut self) -> Option<(String, String, String)> {
1458 self.replace_repair_pick.take()
1459 }
1460
1461 pub fn replace_repair(&mut self, repairs: &[(String, String, String)]) -> Result<(), String> {
1467 let mut block = self
1468 .history
1469 .assembly_block()
1470 .cloned()
1471 .ok_or("replace repair: the document has no assembly")?;
1472 for (id, old_ref, new_ref) in repairs {
1473 let entry = block["constraints"]
1474 .as_array_mut()
1475 .into_iter()
1476 .flatten()
1477 .find(|entry| entry["inputParams"]["id"] == id.as_str())
1478 .ok_or_else(|| format!("replace repair: no constraint '{id}'"))?;
1479 let marker = &mut entry["persistentData"][REPLACE_MARKER];
1480 let refs = marker["refs"]
1481 .as_array_mut()
1482 .ok_or_else(|| format!("replace repair: '{id}' has nothing unresolved"))?;
1483 let before = refs.len();
1484 refs.retain(|row| row["ref"] != old_ref.as_str());
1485 if refs.len() == before {
1486 return Err(format!("replace repair: '{id}' has no unresolved ref '{old_ref}'"));
1487 }
1488 let done = refs.is_empty();
1489 let was_enabled = marker["wasEnabled"].as_bool().unwrap_or(true);
1490 for element in entry["inputParams"]["elements"].as_array_mut().into_iter().flatten() {
1491 if element == old_ref.as_str() {
1492 *element = Value::String(new_ref.clone());
1493 }
1494 }
1495 if done {
1496 if let Some(data) = entry["persistentData"].as_object_mut() {
1497 data.remove(REPLACE_MARKER);
1498 }
1499 entry["enabled"] = Value::Bool(was_enabled);
1500 }
1501 }
1502 self.history.set_assembly_block(block, true);
1503 self.rerun_history();
1504 Ok(())
1505 }
1506
1507 pub fn replace_accept_suggestions(&mut self, ids: &[String]) -> Result<usize, String> {
1511 let unresolved = self.replace_unresolved();
1512 let mut repairs = Vec::new();
1513 for mate in unresolved.as_array().into_iter().flatten() {
1514 let id = mate["id"].as_str().unwrap_or_default().to_string();
1515 if !ids.is_empty() && !ids.contains(&id) {
1516 continue;
1517 }
1518 for row in mate["refs"].as_array().into_iter().flatten() {
1519 if row["suggestion"]["preTicked"] == true {
1520 repairs.push((
1521 id.clone(),
1522 row["ref"].as_str().unwrap_or_default().to_string(),
1523 row["suggestion"]["ref"].as_str().unwrap_or_default().to_string(),
1524 ));
1525 }
1526 }
1527 }
1528 if repairs.is_empty() {
1529 return Ok(0);
1530 }
1531 self.replace_repair(&repairs)?;
1532 Ok(repairs.len())
1533 }
1534}
1535