diff --git a/crates/ocs_save/src/ifccad.rs b/crates/ocs_save/src/ifccad.rs index debf9e0224..c2ac9e302b 100644 --- a/crates/ocs_save/src/ifccad.rs +++ b/crates/ocs_save/src/ifccad.rs @@ -12,13 +12,213 @@ use serde_json::Value; pub struct IfccadSession( Option>>, Arc>, + Arc>>, + Arc>>, ); +/// Explicit browser choice, scoped to one open drawing and stored locator. +#[derive(Clone, Debug)] +pub struct ExternalSourceBytes { + pub file_name: String, + pub bytes: Arc>, +} + impl IfccadSession { + /// Last successfully loaded identity belongs to this tab, even when two + /// native files share a name/header and allocate the same local source IDs. + pub fn observe_external_source_guid( + &self, + handle: document::Handle, + guid: &str, + ) -> Option { + let source = self.external_source(handle)?; + let Some(loaded) = document::ifccad::normalize_ifccad_fingerprint_guid(guid) else { + return Some(false); + }; + let document::ifccad::IfccadExternalSourceContent::Dwg { + fingerprint_guid, .. + } = source.source; + let previous = self + .3 + .lock() + .ok()? + .insert(source.id, loaded.clone()) + .or(fingerprint_guid); + Some(previous.is_some_and(|previous| previous != loaded)) + } + pub fn external_source_bytes( + &self, + handle: document::Handle, + path: &str, + ) -> Option { + let source = self.external_source(handle)?; + self.2 + .lock() + .ok()? + .get(&(source.id, path.to_owned())) + .cloned() + } + + pub fn bind_external_source_bytes( + &self, + handle: document::Handle, + path: &str, + file_name: String, + bytes: Arc>, + ) -> Result<(), String> { + let source = self + .external_source(handle) + .ok_or("Unknown native external source")?; + self.2 + .lock() + .map_err(|_| "External source bytes are unavailable")? + .insert( + (source.id, path.to_owned()), + ExternalSourceBytes { file_name, bytes }, + ); + Ok(()) + } + pub fn has_native_context(&self) -> bool { self.0.is_some() } + pub fn external_source( + &self, + handle: document::Handle, + ) -> Option { + self.0 + .as_ref()? + .lock() + .ok()? + .external_source(handle) + .cloned() + } + + /// Remember source metadata read during an explicit native attachment. + pub fn register_external_source( + &self, + doc: &Document, + handle: document::Handle, + content: document::ifccad::IfccadExternalSourceContent, + ) -> Result<(), String> { + let Some(context) = &self.0 else { + return Ok(()); + }; + let record = doc + .block_records + .iter() + .find(|r| r.handle == handle) + .ok_or("XREF definition is unavailable")?; + context + .lock() + .map_err(|_| "IFCCAD source state is unavailable")? + .register_external_source( + handle, + record.name.clone(), + record.xref_path.clone(), + content, + ) + .map_err(|e| e.to_string())?; + Ok(()) + } + + /// A changed source basis/unit needs an explicit placement reassessment. + /// A changed GUID alone continues through the shared DWG warning policy. + pub fn check_external_source_reload( + &self, + handle: document::Handle, + content: &document::ifccad::IfccadExternalSourceContent, + ) -> Result<(), String> { + let Some(source) = self.external_source(handle) else { + return Ok(()); + }; + let document::ifccad::IfccadExternalSourceContent::Dwg { + base_point, + insertion_unit, + .. + } = &source.source; + let document::ifccad::IfccadExternalSourceContent::Dwg { + base_point: actual, + insertion_unit: unit, + .. + } = content; + if base_point != actual + || insertion_unit + .as_ref() + .is_some_and(|u| Some(u) != unit.as_ref()) + { + return Err(format!("XREF {}: source base point or insertion unit changed; reassess placement and scale before reloading",source.name)); + } + Ok(()) + } + + /// Restore external definition metadata in a disposable CAD save copy. + pub fn prepare_cad_external_sources(&self, doc: &mut Document) -> Result<(), String> { + let Some(context) = &self.0 else { + return Ok(()); + }; + let context = context + .lock() + .map_err(|_| "IFCCAD source state is unavailable")?; + let sources = doc + .block_records + .iter() + .filter_map(|r| { + if !r.flags.is_xref { + return None; + } + Some( + context + .external_source_for_path(r.handle, &r.xref_path) + .map(|source| { + source + .map(|s| (r.handle, r.block_entity_handle, r.xref_path.clone(), s)) + }), + ) + }) + .collect::, _>>() + .map_err(|e| e.to_string())?; + for (handle, marker, path, source) in sources.into_iter().flatten() { + let document::ifccad::IfccadExternalSourceContent::Dwg { + base_point, + fingerprint_guid, + .. + } = source.source; + let base = document::Vector3::new(base_point[0], base_point[1], base_point[2]); + if let Some(record) = doc.block_records.iter_mut().find(|r| r.handle == handle) { + record.base_point = base; + } + if let Some(document::EntityType::Block(block)) = doc.get_entity_mut(marker) { + block.base_point = base; + } + if let Some(guid) = fingerprint_guid { + let dependency = doc + .file_dependencies + .iter_mut() + .find(|d| d.feature.eq_ignore_ascii_case("Acad:XRef") && d.file_name == path); + if let Some(dependency) = dependency { + dependency.fingerprint_guid = + Some(format!("{{{}}}", guid.to_ascii_uppercase())); + } else { + doc.file_dependencies + .push(document::acadrust::document::FileDependency { + feature: "Acad:XRef".into(), + file_name: path, + found_path: String::new(), + fingerprint_guid: Some(format!("{{{}}}", guid.to_ascii_uppercase())), + version_guid: None, + timestamp: 0, + file_size: 0, + affects_graphics: true, + reference_count: 1, + }); + } + } + } + Ok(()) + } + pub fn bind_plot_style( &mut self, layout: document::Handle, @@ -87,6 +287,7 @@ impl IfccadSession { "dxf" | "dwg" | "dwt" | "dws" ) { self.check_cad_plot_style_bindings(doc)?; + document::validate_cad_external_sources(doc).map_err(|e| e.to_string())?; } if super::is_ifccad_extension(ext) || !self.has_blocked_entities() { Ok(()) @@ -202,6 +403,8 @@ pub fn read_ifccad_for_edit( let session = Some(IfccadSession( Some(Arc::new(Mutex::new(context))), Arc::new(sources), + Default::default(), + Default::default(), )); Ok(( super::external_read_outcome(outcome.document, outcome.losses), diff --git a/crates/ocs_save/src/lib.rs b/crates/ocs_save/src/lib.rs index 161b6e82ea..06910b8221 100644 --- a/crates/ocs_save/src/lib.rs +++ b/crates/ocs_save/src/lib.rs @@ -28,7 +28,8 @@ pub use dxf_reference_integrity::{has_omitted_dxf_records, prune_omitted_dxf_rec /// `serialize` action and extends the runtime-field sidecar with /// `graphic_data`. /// v6 selects the updated Document codec for external plot styles. -pub const PROTOCOL_VERSION: u16 = 6; +/// v7 includes typed DWG FileDepList records in the serialized Document. +pub const PROTOCOL_VERSION: u16 = 7; /// Serialize a document to an in-memory byte buffer, format chosen by `ext` /// (`dxf` → DXF, a listed converter's extension → that converter, anything diff --git a/crates/ocs_save/tests/fixtures/xref.ifcx b/crates/ocs_save/tests/fixtures/xref.ifcx new file mode 100644 index 0000000000..ef335de44d --- /dev/null +++ b/crates/ocs_save/tests/fixtures/xref.ifcx @@ -0,0 +1,306 @@ +{ + "header": { + "id": "viewport-reference", + "ifcxVersion": "ifcx_alpha", + "dataVersion": "0.1.0", + "author": "OpenAEC viewport reference", + "timestamp": "2026-10-01T00:00:00Z" + }, + "imports": [ + { + "uri": "urn:example:ifccad:0.12.0" + } + ], + "schemas": {}, + "data": [ + { + "path": "/cad/d1", + "children": { + "layer0": "/cad/d1/layer/0", + "layer4": "/cad/d1/layer/4", + "linePattern0": "/cad/d1/linePattern/0", + "model": "/cad/d1/layout/1", + "paper42": "/cad/d1/layout/42", + "externalSource1": "/cad/d1/externalSource/1" + }, + "attributes": { + "ifccad::drawing": { + "lengthUnit": "mm", + "linePatternScale": 1.0, + "nextBlockId": 1, + "nextEntityId": 1003, + "nextLayerId": 5, + "nextLayoutId": 43, + "nextLinePatternId": 1, + "nextSymbolSourceId": 1, + "profileVersion": "0.12.0", + "nextUcsId": 1, + "nextModelWindowId": 1, + "nextAnnotationScaleId": 1, + "nextExternalSourceId": 2 + } + } + }, + { + "path": "/cad/d1/layout/1", + "children": { + "0": "/cad/d1/e1000" + }, + "attributes": { + "ifccad::layout": { + "kind": "Model", + "tabIndex": 0 + } + } + }, + { + "path": "/cad/d1/layout/42", + "children": { + "0": "/cad/d1/e1001", + "1": "/cad/d1/e1002" + }, + "attributes": { + "ifccad::layout": { + "kind": "Paper", + "name": "Sheet", + "tabIndex": 1 + } + } + }, + { + "path": "/cad/d1/linePattern/0", + "attributes": { + "ifccad::linePattern": { + "description": "Solid line", + "name": "Continuous", + "pattern": [] + } + } + }, + { + "path": "/cad/d1/layer/0", + "attributes": { + "ifccad::layer": { + "appearance": { + "color": { + "rgb": [ + 255, + 255, + 255 + ] + }, + "linePattern": "/cad/d1/linePattern/0", + "lineWeight": 0.25, + "opacity": 1.0 + }, + "name": "0" + } + } + }, + { + "path": "/cad/d1/layer/4", + "attributes": { + "ifccad::layer": { + "appearance": { + "color": { + "rgb": [ + 255, + 255, + 255 + ] + }, + "linePattern": "/cad/d1/linePattern/0", + "lineWeight": 0.25, + "opacity": 1.0 + }, + "name": "Notes" + } + } + }, + { + "path": "/cad/d1/e1000", + "attributes": { + "ifccad::entity": { + "appearance": { + "color": { + "mode": "ByLayer" + }, + "linePattern": { + "mode": "ByLayer" + }, + "lineWeight": { + "mode": "ByLayer" + }, + "opacity": { + "mode": "ByLayer" + } + }, + "layer": "/cad/d1/layer/0", + "linePatternScale": 1.0 + }, + "ifccad::geom::placement": { + "origin": [ + 10000.0, + 5000.0, + 0.0 + ], + "xAxis": [ + 0.0, + 1.0, + 0.0 + ], + "yAxis": [ + -1.0, + 0.0, + 0.0 + ] + }, + "ifccad::xref": { + "source": "/cad/d1/externalSource/1", + "scale": 500.0 + } + } + }, + { + "path": "/cad/d1/e1001", + "attributes": { + "ifccad::entity": { + "appearance": { + "color": { + "mode": "ByLayer" + }, + "linePattern": { + "mode": "ByLayer" + }, + "lineWeight": { + "mode": "ByLayer" + }, + "opacity": { + "mode": "ByLayer" + } + }, + "layer": "/cad/d1/layer/0", + "linePatternScale": 1.0, + "visible": true + }, + "ifccad::viewport": { + "frame": { + "center": [ + 100.0, + 75.0 + ], + "height": 100.0, + "width": 160.0 + }, + "model": "/cad/d1/layout/1", + "paperClip": { + "boundary": "/cad/d1/e1002", + "enabled": true + }, + "renderMode": "Wireframe", + "view": { + "backClip": { + "distance": 0.0, + "mode": "Disabled" + }, + "center": [ + 0.0, + 0.0 + ], + "direction": [ + 0.0, + 0.0, + 100.0 + ], + "frontClip": { + "distance": 0.0, + "mode": "Disabled" + }, + "height": 200.0, + "lensLengthMm": 50.0, + "projection": "Perspective", + "target": [ + 0.0, + 0.0, + 0.0 + ], + "twist": 0.0 + }, + "viewEnabled": true, + "viewLocked": true, + "layerOverrides": [ + { + "layer": "/cad/d1/layer/4", + "frozen": true + } + ] + } + } + }, + { + "path": "/cad/d1/e1002", + "attributes": { + "ifccad::entity": { + "appearance": { + "color": { + "mode": "ByLayer" + }, + "linePattern": { + "mode": "ByLayer" + }, + "lineWeight": { + "mode": "ByLayer" + }, + "opacity": { + "mode": "ByLayer" + } + }, + "layer": "/cad/d1/layer/0", + "linePatternScale": 1.0 + }, + "ifccad::geom::circle": { + "radius": 50.0 + }, + "ifccad::geom::placement": { + "origin": [ + 100.0, + 75.0, + 0.0 + ], + "xAxis": [ + 1.0, + 0.0, + 0.0 + ], + "yAxis": [ + 0.0, + 1.0, + 0.0 + ] + } + } + }, + { + "path": "/cad/d1/externalSource/1", + "attributes": { + "ifccad::externalSource": { + "name": "grondplan", + "location": { + "kind": "uriReference", + "uri": "../Referenties/grondplan.dwg" + }, + "source": { + "format": "dwg", + "basePoint": [ + 10.0, + 20.0, + 0.0 + ], + "insertionUnit": "m", + "fingerprintGuid": "e5b4a9af-cf20-4fc9-a30f-ffb20fd987e1" + } + } + } + } + ] +} diff --git a/crates/ocs_save/tests/ifccad_xref.rs b/crates/ocs_save/tests/ifccad_xref.rs new file mode 100644 index 0000000000..a9d0961e16 --- /dev/null +++ b/crates/ocs_save/tests/ifccad_xref.rs @@ -0,0 +1,134 @@ +use ::document::{entities, ifccad::*, EntityType}; + +fn drawing() -> IfccadDocument { + load_ifccad_bytes(include_bytes!("fixtures/xref.ifcx"), Default::default()) + .unwrap() + .into_document() +} + +#[test] +fn native_source_guid_observations_do_not_leak_between_identical_tabs() { + let (a, first) = ocs_save::read_ifccad_for_edit(include_bytes!("fixtures/xref.ifcx")).unwrap(); + let (b, second) = ocs_save::read_ifccad_for_edit(include_bytes!("fixtures/xref.ifcx")).unwrap(); + let first = first.unwrap(); + let second = second.unwrap(); + let ah = a.document.block_records.get("grondplan").unwrap().handle; + let bh = b.document.block_records.get("grondplan").unwrap().handle; + assert_eq!(ah, bh); + let original = "{E5B4A9AF-CF20-4FC9-A30F-FFB20FD987E1}"; + let other = "{11111111-2222-3333-4444-555555555555}"; + assert_eq!( + first.observe_external_source_guid(ah, original), + Some(false) + ); + assert_eq!(second.observe_external_source_guid(bh, other), Some(true)); + assert_eq!( + first.observe_external_source_guid(ah, original), + Some(false) + ); + assert_eq!(second.observe_external_source_guid(bh, other), Some(false)); + assert_eq!( + second.observe_external_source_guid(bh, original), + Some(true) + ); +} + +#[test] +fn native_xref_missing_save_reopen_keeps_identity() { + let original = drawing(); + let encoded = encode_ifccad_document(&original).unwrap(); + let (mut loaded, session) = ocs_save::read_ifccad_for_edit(encoded.bytes()).unwrap(); + let handle = loaded + .document + .block_records + .get("grondplan") + .unwrap() + .handle; + let mut line = entities::Line::from_coords(0., 0., 0., 2., 0., 0.); + line.common.owner_handle = handle; + let temporary = loaded.document.add_entity(EntityType::Line(line)).unwrap(); + // The external body can disappear; local editing remains possible. + loaded.document.remove_entity(temporary); + loaded + .document + .add_entity(EntityType::Line(entities::Line::from_coords( + 0., 0., 0., 3., 0., 0., + ))) + .unwrap(); + let bytes = ocs_save::write_external_for_edit( + &loaded.document, + ocs_save::external_format("ifccad").unwrap(), + true, + session.as_ref(), + ) + .unwrap(); + let read = load_ifccad_bytes(&bytes, Default::default()).unwrap(); + assert_eq!(read.document().external_sources, original.external_sources); + assert!(read.document().blocks.is_empty()); + assert_eq!( + read.document().model.entities[0].id(), + original.model.entities[0].id() + ); + let (reopened, session) = ocs_save::read_ifccad_for_edit(&bytes).unwrap(); + let again = ocs_save::write_external_for_edit( + &reopened.document, + ocs_save::external_format("ifccad").unwrap(), + true, + session.as_ref(), + ) + .unwrap(); + assert_eq!( + load_ifccad_bytes(&again, Default::default()) + .unwrap() + .document() + .external_sources, + original.external_sources + ); +} + +#[test] +fn native_session_refuses_unqualified_cad_locator() { + let mut d = drawing(); + d.external_sources[0].location = IfccadExternalSourceLocation::UriReference { + uri: "custom:opaque".into(), + }; + let bytes = encode_ifccad_document(&d).unwrap(); + let (loaded, session) = ocs_save::read_ifccad_for_edit(bytes.bytes()).unwrap(); + assert!(session + .unwrap() + .check_destination(&loaded.document, "dwg") + .is_err()); +} + +#[test] +fn reload_checks_basis_and_unit_but_guid_mismatch_keeps_loading_policy() { + let d = drawing(); + let bytes = encode_ifccad_document(&d).unwrap(); + let (loaded, session) = ocs_save::read_ifccad_for_edit(bytes.bytes()).unwrap(); + let session = session.unwrap(); + let handle = loaded + .document + .block_records + .get("grondplan") + .unwrap() + .handle; + let mut changed = d.external_sources[0].source.clone(); + let IfccadExternalSourceContent::Dwg { + fingerprint_guid, .. + } = &mut changed; + *fingerprint_guid = Some("11111111-2222-3333-4444-555555555555".into()); + assert!(session + .check_external_source_reload(handle, &changed) + .is_ok()); + let IfccadExternalSourceContent::Dwg { base_point, .. } = &mut changed; + base_point[0] += 1.; + assert!(session + .check_external_source_reload(handle, &changed) + .is_err()); + let mut changed = d.external_sources[0].source.clone(); + let IfccadExternalSourceContent::Dwg { insertion_unit, .. } = &mut changed; + *insertion_unit = Some("mm".into()); + assert!(session + .check_external_source_reload(handle, &changed) + .is_err()); +} diff --git a/src/app/commands/blocks.rs b/src/app/commands/blocks.rs index 014305d7b1..00d7eb94d6 100644 --- a/src/app/commands/blocks.rs +++ b/src/app/commands/blocks.rs @@ -9,9 +9,7 @@ fn xref_source_path( base_dir: &std::path::Path, ) -> Result { let Some(record) = doc.block_records.get(name) else { - return Err(format!( - "XOPEN: no definition for \"{name}\"." - )); + return Err(format!("XOPEN: no definition for \"{name}\".")); }; if !record.flags.is_xref && !record.flags.is_xref_overlay { return Err("XOPEN: select an external reference (xref) to open.".to_string()); @@ -1468,10 +1466,12 @@ impl OpenCADStudio { .filter(|br| reload_keys.contains(&br.handle.value())) .map(|br| br.handle) .collect(); - let infos = crate::io::xref::resolve_xrefs_for_keys( + let xref_session = self.tabs[i].ifccad_session.clone(); + let infos = crate::io::xref::resolve_xrefs_for_keys_in_session( &mut self.tabs[i].scene.document, base_dir, &handles, + xref_session.as_ref(), ); // Targeted reload updates only the selected rows. { @@ -2078,22 +2078,24 @@ impl OpenCADStudio { .into_iter() .find(|(_, e)| matches!(e, document::EntityType::Insert(_))) { - return Some(match xref_source_path( - &self.tabs[i].scene.document, - &insert.block_name, - &base_dir, - ) { - Ok(path) => { - self.command_line.push_output( - crate::tf!("XOPEN: opening \"{}\".", path.display()).as_ref(), - ); - Task::done(Message::OpenRecent(path)) - } - Err(message) => { - self.command_line.push_error(&message); - self.finish_dispatch(cmd) - } - }); + return Some( + match xref_source_path( + &self.tabs[i].scene.document, + &insert.block_name, + &base_dir, + ) { + Ok(path) => { + self.command_line.push_output( + crate::tf!("XOPEN: opening \"{}\".", path.display()).as_ref(), + ); + Task::done(Message::OpenRecent(path)) + } + Err(message) => { + self.command_line.push_error(&message); + self.finish_dispatch(cmd) + } + }, + ); } if had_selection { self.command_line.push_error( @@ -2117,8 +2119,7 @@ impl OpenCADStudio { }) .collect(); use crate::command::CadCommand; - let command = - crate::modules::insert::xref_cmd::XOpenPickCommand::new(references); + let command = crate::modules::insert::xref_cmd::XOpenPickCommand::new(references); self.command_line.push_info(&command.prompt()); self.tabs[i].active_cmd = Some(Box::new(command)); return Some(Task::none()); @@ -2145,22 +2146,24 @@ impl OpenCADStudio { return Some(self.finish_dispatch(cmd)); } }; - return Some(match xref_source_path( - &self.tabs[i].scene.document, - &insert.block_name, - &base_dir, - ) { - Ok(path) => { - self.command_line.push_output( - crate::tf!("XOPEN: opening \"{}\".", path.display()).as_ref(), - ); - Task::done(Message::OpenRecent(path)) - } - Err(message) => { - self.command_line.push_error(&message); - self.finish_dispatch(cmd) - } - }); + return Some( + match xref_source_path( + &self.tabs[i].scene.document, + &insert.block_name, + &base_dir, + ) { + Ok(path) => { + self.command_line.push_output( + crate::tf!("XOPEN: opening \"{}\".", path.display()).as_ref(), + ); + Task::done(Message::OpenRecent(path)) + } + Err(message) => { + self.command_line.push_error(&message); + self.finish_dispatch(cmd) + } + }, + ); } "NCOPY" | "NCOPYALL" => { diff --git a/src/app/commands/refedit.rs b/src/app/commands/refedit.rs index 602231b323..7751917fe9 100644 --- a/src/app/commands/refedit.rs +++ b/src/app/commands/refedit.rs @@ -743,10 +743,12 @@ impl OpenCADStudio { .xref_stat_cache .0 .remove(&session.br_handle.value()); - let _ = crate::io::xref::resolve_xrefs_for_keys( + let xref_session = self.tabs[i].ifccad_session.clone(); + let _ = crate::io::xref::resolve_xrefs_for_keys_in_session( &mut self.tabs[i].scene.document, &base_dir, &keys, + xref_session.as_ref(), ); Ok(()) } diff --git a/src/app/commands/xref_attach.rs b/src/app/commands/xref_attach.rs index 5b85bef51e..12e4369e94 100644 --- a/src/app/commands/xref_attach.rs +++ b/src/app/commands/xref_attach.rs @@ -194,9 +194,7 @@ impl OpenCADStudio { let entries = self.refresh_xref_report(i); let rows: Vec<(String, String, String, String)> = entries .iter() - .filter(|e| { - e.parent_key.is_none() && e.kind == crate::io::xref_model::RefKind::DwgXref - }) + .filter(|e| e.parent_key.is_none() && e.kind == crate::io::xref_model::RefKind::DwgXref) .filter(|e| pattern == "*" || crate::io::xref_model::wildcard_match(&e.name, pattern)) .map(|e| { let kind = match e.ref_type { @@ -480,6 +478,12 @@ impl OpenCADStudio { ) { let pending = self.begin_undo(i, "XATTACH", 1, false); let host = self.tabs[i].current_path.clone(); + let read = read.or_else(|| { + let (path, base) = + crate::modules::insert::xattach::xref_read_inputs(&request, host.as_deref()); + Some(crate::io::xref::read_xref_file(&path, &base?, None)) + }); + let source_content = read.as_ref().and_then(|r| r.source_content()); let stem = path_to_block_name(&request.path); let name = crate::modules::insert::xattach::prepare_named_xref_definition_with( &mut self.tabs[i].scene, @@ -492,7 +496,56 @@ impl OpenCADStudio { self.tabs[i].xref_relative_on_save.insert(name.clone()); } if let document::EntityType::Insert(insert) = &mut entity { - insert.block_name = name; + let doc = &self.tabs[i].scene.document; + let source_units = doc.block_records.get(&name).map(|r| r.units).unwrap_or(0); + let factor = + crate::app::properties::insert_unit_scale(doc.header.insertion_units, source_units) + .unwrap_or(1.0); + insert.set_x_scale(insert.x_scale() * factor); + insert.set_y_scale(insert.y_scale() * factor); + insert.set_z_scale(insert.z_scale() * factor); + insert.block_name = name.clone(); + } + if let Some(content) = source_content { + let doc = &mut self.tabs[i].scene.document; + if let Some(record) = doc.block_records.get(&name) { + let handle = record.handle; + let path = record.xref_path.clone(); + let document::ifccad::IfccadExternalSourceContent::Dwg { + fingerprint_guid, .. + } = &content; + if let Some(guid) = fingerprint_guid.as_ref().filter(|_| { + !doc.file_dependencies + .iter() + .any(|d| d.feature.eq_ignore_ascii_case("Acad:XRef") && d.file_name == path) + }) { + doc.file_dependencies + .push(document::acadrust::document::FileDependency { + feature: "Acad:XRef".into(), + file_name: path, + found_path: String::new(), + fingerprint_guid: Some(format!("{{{}}}", guid.to_ascii_uppercase())), + version_guid: None, + timestamp: 0, + file_size: 0, + affects_graphics: true, + reference_count: 1, + }); + } + if let Some(session) = self.tabs[i] + .ifccad_session + .as_ref() + .filter(|s| s.external_source(handle).is_none()) + { + if let Err(error) = session.register_external_source( + &self.tabs[i].scene.document, + handle, + content, + ) { + log::error!("{error}"); + } + } + } } // Resolving merged the reference's layers and linetypes — mirror // them into the Layers panel and ribbon dropdowns now (#407). diff --git a/src/app/control/mod.rs b/src/app/control/mod.rs index b151cb1356..613e54805d 100644 --- a/src/app/control/mod.rs +++ b/src/app/control/mod.rs @@ -1474,6 +1474,7 @@ impl OpenCADStudio { "plot" => self.control_plot(req)?, "entities_create" => self.control_entities_create(req)?, "entities_set" => self.control_entities_set(req)?, + "xref_source_register" => self.control_xref_source_register(req)?, "xref_reload" => self.control_xref_reload(req)?, "xref_unload" => self.control_xref_unload(req)?, "xref_detach" => self.control_xref_detach(req)?, @@ -1574,7 +1575,7 @@ impl OpenCADStudio { true, require_new_destination, ) - .map_err(|e| failure("save_failed", e))?; + .map_err(|e| failure("save_failed", e))?; Task::none() } else { self.prepare_native_save(i); @@ -4660,7 +4661,11 @@ mod tests { let measured = app.control_measure(&json!({"handles":[handle_text]})); let mesh = &measured["measurements"][0]["mesh"]; - assert!((mesh["volume"].as_f64().unwrap() - 50.0).abs() < 1e-9, "{}", mesh["volume"]); + assert!( + (mesh["volume"].as_f64().unwrap() - 50.0).abs() < 1e-9, + "{}", + mesh["volume"] + ); assert_eq!(mesh["principal_moments"].as_array().unwrap().len(), 3); assert!(matches!( app.tabs[app.active_tab] @@ -5011,7 +5016,10 @@ mod tests { fn block_definition_dialog_fields_are_automatable() { use crate::app::ModalKind; let mut app = OpenCADStudio::new_for_test(); - assert_eq!(request(&mut app, json!({"op":"new"}))["status"], "completed"); + assert_eq!( + request(&mut app, json!({"op":"new"}))["status"], + "completed" + ); let drawn = request(&mut app, json!({"op":"run","cmd":"LINE 0,0 10,0"})); assert_eq!(drawn["ok"], true, "{drawn}"); let selected = request(&mut app, json!({"op":"run","cmd":"SELECTALL"})); @@ -5898,11 +5906,8 @@ mod tests { .header .insertion_units = 6; let crs = crate::io::crs::CrsDefinition::from_epsg(5514).unwrap(); - crate::io::crs::set_document_crs( - &mut app.tabs[app.active_tab].scene.document, - &crs, - ) - .unwrap(); + crate::io::crs::set_document_crs(&mut app.tabs[app.active_tab].scene.document, &crs) + .unwrap(); app.plot_dialog.geopdf = true; // The destination extension, not this stale device selection, decides // whether the output is PDF and needs GeoPDF validation. @@ -5930,8 +5935,7 @@ mod tests { std::process::id() )); let _ = std::fs::remove_file(&path); - let mut plot = - json!({"op":"plot","layout":layout,"path":path.to_string_lossy()}); + let mut plot = json!({"op":"plot","layout":layout,"path":path.to_string_lossy()}); if kind == "mixed" { // Paper-space non-Layout areas are deliberately plain. They // must not inherit the model page's GeoPDF eligibility check. @@ -5946,9 +5950,10 @@ mod tests { } else { assert!(flags.len() > 1); assert!(flags[model_index]); - assert!(flags.iter().enumerate().all(|(index, vp)| { - index == model_index || !vp - })); + assert!(flags + .iter() + .enumerate() + .all(|(index, vp)| { index == model_index || !vp })); } let _ = std::fs::remove_file(&path); } @@ -5999,23 +6004,20 @@ mod tests { // A drawing without a CRS exports as an ordinary plain PDF; the // GeoPDF opt-in neither fails the plot nor writes geospatial metadata. - let response = request( - &mut app, - json!({"op":"plot","path":pdf.to_string_lossy()}), - ); + let response = request(&mut app, json!({"op":"plot","path":pdf.to_string_lossy()})); assert_eq!(response["status"], "completed", "{response}"); assert!(pdf.exists(), "{response}"); - assert_eq!(vp_by_page(std::fs::read(&pdf).expect("fallback PDF")), [false]); + assert_eq!( + vp_by_page(std::fs::read(&pdf).expect("fallback PDF")), + [false] + ); let _ = std::fs::remove_file(&pdf); let svg = std::env::temp_dir().join(format!( "ocs-geopdf-control-missing-crs-{}.svg", std::process::id() )); - let response = request( - &mut app, - json!({"op":"plot","path":svg.to_string_lossy()}), - ); + let response = request(&mut app, json!({"op":"plot","path":svg.to_string_lossy()})); assert_eq!(response["status"], "completed", "{response}"); roxmltree::Document::parse(&std::fs::read_to_string(&svg).unwrap()).unwrap(); let _ = std::fs::remove_file(&svg); @@ -6920,47 +6922,60 @@ mod tests { let before = app.tabs[0].scene.document.clone(); let before_undo = app.tabs[0].history.undo_stack.len(); - let response = request(&mut app, json!({ - "op": "panel_input", - "panel_id": panel_id, - "control_id": "SegmentLength", - "text": "101.5", - })); + let response = request( + &mut app, + json!({ + "op": "panel_input", + "panel_id": panel_id, + "control_id": "SegmentLength", + "text": "101.5", + }), + ); assert_eq!(response["ok"], true, "{response}"); assert_eq!( - app.plugin_panels[panel_id].text_values.get("SegmentLength").map(String::as_str), + app.plugin_panels[panel_id] + .text_values + .get("SegmentLength") + .map(String::as_str), Some("101.5"), ); assert_eq!(app.tabs[0].scene.document, before); assert_eq!(app.tabs[0].history.undo_stack.len(), before_undo); - let response = request(&mut app, json!({ - "op": "panel_button", - "panel_id": panel_id, - "control_id": "reset", - })); + let response = request( + &mut app, + json!({ + "op": "panel_button", + "panel_id": panel_id, + "control_id": "reset", + }), + ); assert_eq!(response["ok"], true, "{response}"); assert_eq!( - app.plugin_panels[panel_id].text_values.get("SegmentLength").map(String::as_str), + app.plugin_panels[panel_id] + .text_values + .get("SegmentLength") + .map(String::as_str), Some("100"), ); assert_eq!( app.plugin_panels[panel_id].owner_plugin_id.as_deref(), Some("opencad.civil_ifc"), ); - let declared_action = OpenCADStudio::panel_button_action( - &app.plugin_panels[panel_id].def.controls, - "apply", - ); + let declared_action = + OpenCADStudio::panel_button_action(&app.plugin_panels[panel_id].def.controls, "apply"); assert_eq!(declared_action.as_deref(), Some("CVI_IFC_PANEL_APPLY")); assert_eq!(app.tabs[0].scene.document, before); assert_eq!(app.tabs[0].history.undo_stack.len(), before_undo); - let response = request(&mut app, json!({ - "op": "panel_button", - "panel_id": panel_id, - "control_id": "apply", - })); + let response = request( + &mut app, + json!({ + "op": "panel_button", + "panel_id": panel_id, + "control_id": "apply", + }), + ); assert_eq!(response["ok"], true, "{response}"); assert_eq!(app.tabs[0].scene.document, before); assert_eq!(app.tabs[0].history.undo_stack.len(), before_undo); diff --git a/src/app/control/p1_tests.rs b/src/app/control/p1_tests.rs index b446972e50..242042c587 100644 --- a/src/app/control/p1_tests.rs +++ b/src/app/control/p1_tests.rs @@ -469,8 +469,7 @@ fn layout_lifecycle_is_case_insensitive_undoable_and_passive() { assert_eq!(app.tabs[i].scene.document, before_doc); assert_eq!(app.tabs[i].history.undo_stack.len(), before_undo); assert_eq!(app.tabs[i].edit_revision, before_revision); - let setup_before_activation = - app.automation_op(r#"{"op":"page_setup_get","layout":"PLAN"}"#); + let setup_before_activation = app.automation_op(r#"{"op":"page_setup_get","layout":"PLAN"}"#); let entities_before_activation = app.tabs[i].scene.document.entities().count(); assert!(!app.tabs[i].dirty); @@ -4296,11 +4295,110 @@ fn ifccad_undo_does_not_reissue_a_saved_linetype_handle() { cmd(&mut app, "-LINETYPE CREATE FIRST 1,-1"); let first_id = saved_pattern_id(&app, "FIRST"); assert_eq!(request(&mut app, json!({"op":"undo"}))["ok"], true); - assert!(app.tabs[tab].scene.document.line_types.get("FIRST").is_none()); + assert!(app.tabs[tab] + .scene + .document + .line_types + .get("FIRST") + .is_none()); cmd(&mut app, "-LINETYPE CREATE SECOND 2,-2"); assert_ne!(saved_pattern_id(&app, "SECOND"), first_id); } +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn native_xref_host_source_edit_grip_undo_and_offline_save() { + use base64::Engine; + use document::{EntityType, Vector3}; + let input = include_bytes!("../../../crates/ocs_save/tests/fixtures/xref.ifcx"); + let original = document::ifccad::load_ifccad_bytes(input, Default::default()) + .unwrap() + .into_document(); + let (loaded, session) = ocs_save::read_ifccad_for_edit(input).unwrap(); + let session = session.unwrap(); + let mut app = OpenCADStudio::new_for_test(); + app.automation_op(r#"{"op":"new"}"#); + let i = app.active_tab; + app.tabs[i].scene.document = loaded.document; + crate::io::normalize_block_origins(&mut app.tabs[i].scene.document); + app.tabs[i].ifccad_session = Some(session.clone()); + let handle = app.tabs[i] + .scene + .document + .model_space_entities() + .find_map(|e| matches!(e, EntityType::Insert(_)).then_some(e.common().handle)) + .unwrap(); + for endpoint in [12., 13.] { + let mut source = document::Document::new(); + source.header.insertion_units = 6; + source.header.model_space_insertion_base = Vector3::new(10., 20., 0.); + source.header.fingerprint_guid = "{E5B4A9AF-CF20-4FC9-A30F-FFB20FD987E1}".into(); + source + .add_entity(EntityType::Line(document::entities::Line::from_coords( + 10., 20., 0., endpoint, 20., 0., + ))) + .unwrap(); + let data = base64::engine::general_purpose::STANDARD + .encode(document::DwgWriter::write_to_vec(&source).unwrap()); + let reply = control( + &mut app, + json!({"op":"xref_source_register","source_id":original.external_sources[0].id.0.to_string(),"file_name":"grondplan.dwg","data_base64":data}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + let doc = &app.tabs[i].scene.document; + let owner = doc.block_records.get("grondplan").unwrap().handle; + let line = doc + .entities() + .find_map(|e| match e { + EntityType::Line(l) if l.common.owner_handle == owner => Some(l), + _ => None, + }) + .unwrap(); + assert_eq!(line.start, Vector3::ZERO); + assert_eq!(line.end, Vector3::new(endpoint - 10., 0., 0.)); + } + let reply = control( + &mut app, + json!({"op":"grip_drag","handle":handle.to_string(),"grip_id":0,"point":[11000,5000,0]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + for op in ["undo", "redo"] { + let reply = control(&mut app, json!({"op":op})); + assert_eq!(reply["ok"], true, "{reply}"); + } + let prepared = app.tabs[i].scene.document_for_save(); + let bytes = ocs_save::write_external_for_edit( + &prepared, + ocs_save::external_format("ifccad").unwrap(), + false, + Some(&session), + ) + .unwrap(); + let saved = document::ifccad::load_ifccad_bytes(&bytes, Default::default()) + .unwrap() + .into_document(); + assert_eq!(saved.external_sources, original.external_sources); + assert_eq!(saved.model.entities.len(), original.model.entities.len()); + let native = saved + .model + .entities + .iter() + .filter_map(|e| e.as_native()) + .find_map(|e| match &e.kind { + document::ifccad::IfccadEntityKind::Xref(x) => Some(x), + _ => None, + }) + .unwrap(); + for (actual, expected) in native.placement.origin.iter().zip([11000., 5000., 0.]) { + assert!( + (actual - expected).abs() <= 0.001, + "grip placement {actual} vs {expected}" + ); + } + assert_eq!(native.scale, 500.); + assert!(saved.blocks.is_empty()); +} + #[test] #[cfg(not(target_arch = "wasm32"))] fn ifccad_blocked_mline_survives_studio_edit_save_and_reopen() { diff --git a/src/app/control/xrefs.rs b/src/app/control/xrefs.rs index f86215b20c..ba59f117c6 100644 --- a/src/app/control/xrefs.rs +++ b/src/app/control/xrefs.rs @@ -243,7 +243,7 @@ impl OpenCADStudio { .as_deref() .and_then(Path::parent) .unwrap_or_else(|| Path::new(".")); - let entry = crate::io::xref::collect_direct_entry_with_prev( + let mut entry = crate::io::xref::collect_direct_entry_with_prev( &self.tabs[i].scene.document, base_dir, self.tabs[i].xref_unloaded.as_set(), @@ -256,6 +256,10 @@ impl OpenCADStudio { "The reference disappeared during the operation", ) })?; + crate::io::xref::apply_native_source_status( + std::slice::from_mut(&mut entry), + self.tabs[i].ifccad_session.as_ref(), + ); Ok(reference_json(&self.tabs[i].scene.document, &entry)) } @@ -295,6 +299,81 @@ impl OpenCADStudio { json!({"ok":true, "count":xrefs.len(), "xrefs":xrefs}) } + /// Bind explicitly selected DWG bytes to one source in the active native tab. + pub(super) fn control_xref_source_register( + &mut self, + req: &Value, + ) -> Result, Value> { + use base64::Engine; + validate_fields(req, &["source_id", "file_name", "data_base64"])?; + let id = req["source_id"] + .as_str() + .and_then(|s| s.parse::().ok().filter(|id| id.to_string() == s)) + .ok_or_else(|| { + failure( + "invalid_source", + "source_id must be an exact decimal string", + ) + })?; + let file_name = req["file_name"] + .as_str() + .filter(|s| { + !s.is_empty() + && !s.contains(['/', '\\', '\0', ':']) + && s.to_ascii_lowercase().ends_with(".dwg") + }) + .ok_or_else(|| failure("invalid_source", "Choose a DWG filename"))?; + let bytes = base64::engine::general_purpose::STANDARD + .decode(req["data_base64"].as_str().unwrap_or_default()) + .map_err(|e| failure("invalid_source", e))?; + if bytes.is_empty() { + return Err(failure("invalid_source", "The DWG is empty")); + } + let i = self.active_tab; + let session = self.tabs[i] + .ifccad_session + .clone() + .ok_or_else(|| failure("invalid_source", "This tab has no native source context"))?; + let (handle, name, path) = self.tabs[i] + .scene + .document + .block_records + .iter() + .find_map(|r| { + session + .external_source(r.handle) + .filter(|s| s.id.0 == id) + .map(|_| (r.handle, r.name.clone(), r.xref_path.clone())) + }) + .ok_or_else(|| failure("invalid_source", "Source does not belong to this drawing"))?; + let read = crate::io::xref::read_source_bytes(file_name, &bytes); + let mut infos = Vec::new(); + crate::io::xref::merge_xref_reads_in_session( + &mut self.tabs[i].scene.document, + vec![(name, path.clone(), handle, read)], + &mut infos, + None, + Some(&session), + ); + let info = infos + .pop() + .ok_or_else(|| failure("xref_load_failed", "No source result"))?; + if info.status != crate::io::xref::XrefStatus::Loaded { + return Err(load_failed(&info)); + } + session + .bind_external_source_bytes( + handle, + &path, + file_name.to_owned(), + std::sync::Arc::new(bytes), + ) + .map_err(|e| failure("invalid_source", e))?; + self.post_ref_op(i); + self.set_control_result(json!({"source_id":id.to_string(),"source_status":"loaded","found_at":file_name,"other_drawing":info.other_drawing,"diagnostics":info.diagnostics})); + Ok(Task::none()) + } + pub(super) fn control_xref_reload(&mut self, req: &Value) -> Result, Value> { validate_fields(req, &["id"])?; let target = self.direct_reference(req)?; @@ -303,18 +382,33 @@ impl OpenCADStudio { if target.kind == RefKind::Image { return Err(kind_unsupported("xref_reload", &target)); } - let base_dir = self.saved_host_dir(i)?; - if target.found_at.is_none() { + let selected_bytes = self.tabs[i] + .ifccad_session + .as_ref() + .and_then(|s| s.external_source_bytes(Handle::new(id), &target.saved_path)); + let base_dir = if selected_bytes.is_some() { + self.tabs[i] + .current_path + .as_deref() + .and_then(Path::parent) + .unwrap_or_else(|| Path::new(".")) + .to_path_buf() + } else { + self.saved_host_dir(i)? + }; + if target.found_at.is_none() && selected_bytes.is_none() { return Err(source_missing(target.saved_path, Vec::new())); } match target.kind { RefKind::DwgXref => { self.push_undo_snapshot(i, "XREF-RELOAD"); let handles = [Handle::new(id)].into_iter().collect(); - let infos = crate::io::xref::resolve_xrefs_for_keys( + let xref_session = self.tabs[i].ifccad_session.clone(); + let infos = crate::io::xref::resolve_xrefs_for_keys_in_session( &mut self.tabs[i].scene.document, &base_dir, &handles, + xref_session.as_ref(), ); let Some(info) = infos .iter() diff --git a/src/app/find_replace.rs b/src/app/find_replace.rs index 2c0418e7c7..8784965662 100644 --- a/src/app/find_replace.rs +++ b/src/app/find_replace.rs @@ -256,7 +256,10 @@ impl OpenCADStudio { fn visit_find_result(&mut self, result: &FindResult) -> Task { let i = self.active_tab; let mut task = Task::none(); - if !result.location.eq_ignore_ascii_case(&self.tabs[i].scene.current_layout) { + if !result + .location + .eq_ignore_ascii_case(&self.tabs[i].scene.current_layout) + { task = self.on_layout_switch(result.location.clone()); } let zoom = if result.height > 0.0 { @@ -311,7 +314,10 @@ impl OpenCADStudio { return Task::none(); } let first = picked[0].location.clone(); - if picked.iter().any(|r| !r.location.eq_ignore_ascii_case(&first)) { + if picked + .iter() + .any(|r| !r.location.eq_ignore_ascii_case(&first)) + { self.find_replace.notice = Some(FindNotice::CannotSelect); return Task::none(); } @@ -445,10 +451,7 @@ impl OpenCADStudio { let doc = &self.tabs[i].scene.document; layer .iter() - .chain( - doc.get_entity(key.owner) - .map(|e| &e.common().layer), - ) + .chain(doc.get_entity(key.owner).map(|e| &e.common().layer)) .cloned() .collect() }; @@ -538,7 +541,10 @@ impl OpenCADStudio { } if result.kind == FindKind::Xref { if let Some(name) = definition { - if !xref_writes.iter().any(|n: &String| n.eq_ignore_ascii_case(&name)) { + if !xref_writes + .iter() + .any(|n: &String| n.eq_ignore_ascii_case(&name)) + { xref_writes.push(name); } } @@ -711,10 +717,12 @@ impl OpenCADStudio { for key in &insert_keys { self.tabs[i].xref_stat_cache.0.remove(&key.value()); } - let _ = crate::io::xref::resolve_xrefs_for_keys( + let xref_session = self.tabs[i].ifccad_session.clone(); + let _ = crate::io::xref::resolve_xrefs_for_keys_in_session( &mut self.tabs[i].scene.document, &base_dir, &insert_keys, + xref_session.as_ref(), ); } } @@ -882,7 +890,16 @@ impl Walk<'_> { .is_some_and(|l| l.flags.off || l.flags.frozen) } - fn push(&mut self, owner: Handle, target: Handle, part: FindPart, kind: FindKind, location: &str, value: &str, height: f64) { + fn push( + &mut self, + owner: Handle, + target: Handle, + part: FindPart, + kind: FindKind, + location: &str, + value: &str, + height: f64, + ) { // Formatted texts are searched and listed as they read. let value = &shown_text(self.doc, target, part, value); if crate::app::text_match::str_ranges(value, self.pattern, &self.matching).is_empty() { @@ -920,17 +937,37 @@ impl Walk<'_> { None => kind, }; match entity { - EntityType::Text(t) if self.opts.texts => { - self.push(owner, target, FindPart::Text, inner(FindKind::Text), location, &t.value, t.height) - } - EntityType::MText(t) if self.opts.texts => { - self.push(owner, target, FindPart::Text, inner(FindKind::MText), location, &t.value, t.height) - } + EntityType::Text(t) if self.opts.texts => self.push( + owner, + target, + FindPart::Text, + inner(FindKind::Text), + location, + &t.value, + t.height, + ), + EntityType::MText(t) if self.opts.texts => self.push( + owner, + target, + FindPart::Text, + inner(FindKind::MText), + location, + &t.value, + t.height, + ), EntityType::Dimension(d) if self.opts.dimensions => { if let Some(text) = d.base().text_override() { if !text.trim().is_empty() && text.trim() != "<>" { let height = dim_text_height(self.doc, &d.base().style_name); - self.push(owner, target, FindPart::Text, inner(FindKind::Dimension), location, text, height); + self.push( + owner, + target, + FindPart::Text, + inner(FindKind::Dimension), + location, + text, + height, + ); } } } @@ -951,7 +988,15 @@ impl Walk<'_> { for col in 0..table.column_count() { if let Some(text) = table.cell_text(row, col) { let text = text.to_string(); - self.push(owner, target, FindPart::Cell(row, col), inner(FindKind::Table), location, &text, height); + self.push( + owner, + target, + FindPart::Cell(row, col), + inner(FindKind::Table), + location, + &text, + height, + ); } } } @@ -961,10 +1006,26 @@ impl Walk<'_> { if within.is_none() { if let Some(link) = crate::scene::hyperlink::Link::of(entity) { if self.opts.link_texts && !link.text.is_empty() { - self.push(owner, target, FindPart::LinkText, FindKind::LinkText, location, &link.text, 0.0); + self.push( + owner, + target, + FindPart::LinkText, + FindKind::LinkText, + location, + &link.text, + 0.0, + ); } if self.opts.links && !link.url.is_empty() { - self.push(owner, target, FindPart::LinkUrl, FindKind::Link, location, &link.url, 0.0); + self.push( + owner, + target, + FindPart::LinkUrl, + FindKind::Link, + location, + &link.url, + 0.0, + ); } } } @@ -994,7 +1055,11 @@ impl Walk<'_> { return; }; let xref = record.flags.is_xref || record.flags.is_xref_overlay; - let go = if xref { self.opts.xrefs } else { self.opts.blocks }; + let go = if xref { + self.opts.xrefs + } else { + self.opts.blocks + }; if !go || depth > 16 { return; } @@ -1049,7 +1114,9 @@ fn field_text(doc: &document::Document, key: FindMatchKey) -> Option { /// Write a match's text back. fn set_field_text(doc: &mut document::Document, key: FindMatchKey, value: String) -> bool { if let FindPart::LinkText | FindPart::LinkUrl = key.part { - let Some(mut link) = doc.get_entity(key.target).and_then(crate::scene::hyperlink::Link::of) + let Some(mut link) = doc + .get_entity(key.target) + .and_then(crate::scene::hyperlink::Link::of) else { return false; }; @@ -1114,7 +1181,14 @@ fn match_quads( // (cells of one line share their bottom). let runs = |cells: &[(usize, [f64; 4])], visible: &str| -> Vec<[f64; 4]> { let chars: Vec> = visible.chars().map(Some).collect(); - let join = |a: [f64; 4], c: [f64; 4]| [a[0].min(c[0]), a[1].min(c[1]), a[2].max(c[2]), a[3].max(c[3])]; + let join = |a: [f64; 4], c: [f64; 4]| { + [ + a[0].min(c[0]), + a[1].min(c[1]), + a[2].max(c[2]), + a[3].max(c[3]), + ] + }; let frame = cells.iter().map(|(_, c)| *c).reduce(join); let mut out: Vec<[f64; 4]> = frame.into_iter().collect(); for (start, end) in crate::app::text_match::find_ranges(&chars, pattern, opts) { @@ -1222,7 +1296,9 @@ fn highlight( .chain(matched.iter().map(|q| (q, FIND_MATCH_FILL))) .map(|(q, color)| { let origin = q[0]; - let ring = q.iter().map(|p| [(p[0] - origin[0]) as f32, (p[1] - origin[1]) as f32]); + let ring = q + .iter() + .map(|p| [(p[0] - origin[0]) as f32, (p[1] - origin[1]) as f32]); crate::scene::HatchModel { entity: None, effective_layer: None, @@ -1282,8 +1358,10 @@ const FIND_FRAME_FILL: [f32; 4] = [0.0, 0.0, 0.0, 0.28]; fn shown_text(doc: &document::Document, target: Handle, part: FindPart, value: &str) -> String { let formatted = matches!( (part, doc.get_entity(target)), - (FindPart::Text, Some(EntityType::MText(_) | EntityType::MultiLeader(_) | EntityType::Dimension(_))) - | (FindPart::Cell(..), Some(EntityType::Table(_))) + ( + FindPart::Text, + Some(EntityType::MText(_) | EntityType::MultiLeader(_) | EntityType::Dimension(_)) + ) | (FindPart::Cell(..), Some(EntityType::Table(_))) ); if formatted { document::entities::mtext_format::parse_mtext(value, true).to_plain_text() diff --git a/src/app/update/dialog.rs b/src/app/update/dialog.rs index e191bb5ab9..e986a7d12a 100644 --- a/src/app/update/dialog.rs +++ b/src/app/update/dialog.rs @@ -719,6 +719,10 @@ impl OpenCADStudio { ) }; let tab = &mut self.tabs[i]; + crate::io::xref::apply_native_source_status( + &mut self.xref_manager.entries, + tab.ifccad_session.as_ref(), + ); for (key, mtime) in baselines { tab.xref_stat_cache.insert(key, mtime); } @@ -766,12 +770,16 @@ impl OpenCADStudio { .as_ref() .and_then(|p| p.parent().map(|p| p.to_path_buf())) .unwrap_or_else(|| std::path::PathBuf::from(".")); - let entries = crate::io::xref::collect_entries_with_prev( + let mut entries = crate::io::xref::collect_entries_with_prev( &self.tabs[i].scene.document, &base_dir, self.tabs[i].xref_unloaded.as_set(), &self.tabs[i].xref_stat_cache.0, ); + crate::io::xref::apply_native_source_status( + &mut entries, + self.tabs[i].ifccad_session.as_ref(), + ); self.tabs[i].xref_report = entries .iter() .map(|e| { @@ -1041,10 +1049,12 @@ impl OpenCADStudio { .filter(|br| dwg_picked.iter().any(|(key, _)| *key == br.handle.value())) .map(|br| br.handle) .collect(); - let infos = crate::io::xref::resolve_xrefs_for_keys( + let xref_session = self.tabs[i].ifccad_session.clone(); + let infos = crate::io::xref::resolve_xrefs_for_keys_in_session( &mut self.tabs[i].scene.document, &base_dir, &handles, + xref_session.as_ref(), ); // Targeted reload updates baselines only for selected rows. { @@ -2085,8 +2095,10 @@ mod tests { #[test] fn interactive_dialog_action_pick_updates_table() { - use ocs_plugin_api::dialog::{DialogActionResponse, DialogControl, DialogDef, DialogEvent, DialogValue}; use crate::command::{CadCommand, CmdResult}; + use ocs_plugin_api::dialog::{ + DialogActionResponse, DialogControl, DialogDef, DialogEvent, DialogValue, + }; use std::collections::HashMap; struct MockStartupCommand { @@ -2113,9 +2125,14 @@ mod tests { let mut updates = HashMap::new(); updates.insert( "scripts_table".to_string(), - DialogValue::Table(self.scripts.iter().map(|s| vec![s.clone()]).collect()), + DialogValue::Table( + self.scripts.iter().map(|s| vec![s.clone()]).collect(), + ), + ); + updates.insert( + "file_input".to_string(), + DialogValue::FilePath(String::new()), ); - updates.insert("file_input".to_string(), DialogValue::FilePath(String::new())); return DialogActionResponse::UpdateValues(updates); } } @@ -2125,7 +2142,9 @@ mod tests { let mut app = fresh(); let i = app.active_tab; - app.tabs[i].active_cmd = Some(Box::new(MockStartupCommand { scripts: Vec::new() })); + app.tabs[i].active_cmd = Some(Box::new(MockStartupCommand { + scripts: Vec::new(), + })); let def = DialogDef::new("Startup Test") .with_control(DialogControl::FilePicker { @@ -2147,7 +2166,13 @@ mod tests { app.open_plugin_dialog(def); - let initial_table = app.plugin_dialog_state.as_ref().unwrap().table_values.get("scripts_table").unwrap(); + let initial_table = app + .plugin_dialog_state + .as_ref() + .unwrap() + .table_values + .get("scripts_table") + .unwrap(); assert_eq!(initial_table.len(), 0); // Simulate typing into the file input (should send "change", not "pick") @@ -2158,7 +2183,10 @@ mod tests { { let state = app.plugin_dialog_state.as_ref().unwrap(); assert_eq!(state.table_values.get("scripts_table").unwrap().len(), 0); - assert_eq!(state.file_values.get("file_input").unwrap(), "C:/AutoLISP/partial"); + assert_eq!( + state.file_values.get("file_input").unwrap(), + "C:/AutoLISP/partial" + ); } // Simulate picking a file via Browse dialog (sends "pick") @@ -2176,8 +2204,10 @@ mod tests { #[test] fn interactive_dialog_choice_static_and_dynamic_text_and_tab_routing() { - use ocs_plugin_api::dialog::{DialogActionResponse, DialogControl, DialogDef, DialogEvent, DialogValue}; use crate::command::{CadCommand, CmdResult}; + use ocs_plugin_api::dialog::{ + DialogActionResponse, DialogControl, DialogDef, DialogEvent, DialogValue, + }; use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -2212,11 +2242,14 @@ mod tests { selected_index: 1, }, ); - self.pending_updates.push(("Choice Test".to_string(), updates)); + self.pending_updates + .push(("Choice Test".to_string(), updates)); } DialogActionResponse::None } - fn take_pending_panel_updates(&mut self) -> Vec<(String, HashMap)> { + fn take_pending_panel_updates( + &mut self, + ) -> Vec<(String, HashMap)> { std::mem::take(&mut self.pending_updates) } } @@ -2335,25 +2368,69 @@ mod tests { app.open_plugin_dialog(def); // Mutate text value, then test "clear" button fallback - let _ = app.update(Message::PluginDialogTextChange("txt".to_string(), "modified".to_string())); - let _ = app.update(Message::PluginDialogButtonClick("btn_clear".to_string(), Some("clear".to_string()))); - assert!(app.plugin_dialog_state.as_ref().unwrap().table_values.get("tbl").unwrap().is_empty()); - assert_eq!(app.plugin_dialog_state.as_ref().unwrap().text_values.get("txt").unwrap(), "modified"); + let _ = app.update(Message::PluginDialogTextChange( + "txt".to_string(), + "modified".to_string(), + )); + let _ = app.update(Message::PluginDialogButtonClick( + "btn_clear".to_string(), + Some("clear".to_string()), + )); + assert!(app + .plugin_dialog_state + .as_ref() + .unwrap() + .table_values + .get("tbl") + .unwrap() + .is_empty()); + assert_eq!( + app.plugin_dialog_state + .as_ref() + .unwrap() + .text_values + .get("txt") + .unwrap(), + "modified" + ); // Test "reset" button fallback restores initial defaults - let _ = app.update(Message::PluginDialogButtonClick("btn_reset".to_string(), Some("reset".to_string()))); - assert_eq!(app.plugin_dialog_state.as_ref().unwrap().text_values.get("txt").unwrap(), "initial"); - assert_eq!(app.plugin_dialog_state.as_ref().unwrap().table_values.get("tbl").unwrap().len(), 1); + let _ = app.update(Message::PluginDialogButtonClick( + "btn_reset".to_string(), + Some("reset".to_string()), + )); + assert_eq!( + app.plugin_dialog_state + .as_ref() + .unwrap() + .text_values + .get("txt") + .unwrap(), + "initial" + ); + assert_eq!( + app.plugin_dialog_state + .as_ref() + .unwrap() + .table_values + .get("tbl") + .unwrap() + .len(), + 1 + ); // Test "close" button fallback closes the dialog - let _ = app.update(Message::PluginDialogButtonClick("btn_close".to_string(), Some("close".to_string()))); + let _ = app.update(Message::PluginDialogButtonClick( + "btn_close".to_string(), + Some("close".to_string()), + )); assert!(app.plugin_dialog_state.is_none()); } #[test] fn interactive_dialog_autolisp_exact_flow() { - use ocs_plugin_api::dialog::*; use crate::command::CadCommand; + use ocs_plugin_api::dialog::*; let mut app = fresh(); let opening_tab = app.active_tab; @@ -2383,37 +2460,66 @@ mod tests { // Like interactive_dialog_test.lsp: // (setq picked (oca-get "picker" values)) // (setq current-tbl (oca-get "tbl_files" values)) - let picked = event.current_values.get("picker").and_then(|v| match v { - DialogValue::FilePath(p) => Some(p.clone()), - _ => None, - }).unwrap_or_default(); - let mut tbl = event.current_values.get("tbl_files").and_then(|v| match v { - DialogValue::Table(rows) => Some(rows.clone()), - _ => None, - }).unwrap_or_default(); + let picked = event + .current_values + .get("picker") + .and_then(|v| match v { + DialogValue::FilePath(p) => Some(p.clone()), + _ => None, + }) + .unwrap_or_default(); + let mut tbl = event + .current_values + .get("tbl_files") + .and_then(|v| match v { + DialogValue::Table(rows) => Some(rows.clone()), + _ => None, + }) + .unwrap_or_default(); if !picked.is_empty() { tbl.push(vec![picked, "Active".to_string()]); updates.insert("tbl_files".to_string(), DialogValue::Table(tbl.clone())); updates.insert("picker".to_string(), DialogValue::FilePath(String::new())); - updates.insert("lbl_status".to_string(), DialogValue::Text(format!("Added file. Total in list: {}", tbl.len()))); + updates.insert( + "lbl_status".to_string(), + DialogValue::Text(format!("Added file. Total in list: {}", tbl.len())), + ); return DialogActionResponse::UpdateValues(updates); } } else if event.control_id == "btn_clear" { // Empty list clears table: updates.insert("tbl_files".to_string(), DialogValue::Table(Vec::new())); - updates.insert("lbl_status".to_string(), DialogValue::Text("List cleared. 0 items in table.".to_string())); + updates.insert( + "lbl_status".to_string(), + DialogValue::Text("List cleared. 0 items in table.".to_string()), + ); return DialogActionResponse::UpdateValues(updates); } else if event.control_id == "btn_inspect" { - let mode = event.current_values.get("cmb_mode").and_then(|v| match v { - DialogValue::Choice { text, .. } => Some(text.clone()), - _ => None, - }).unwrap_or_default(); - let log = event.current_values.get("chk_log").and_then(|v| match v { - DialogValue::Bool(b) => Some(*b), - _ => None, - }).unwrap_or(false); - updates.insert("lbl_status".to_string(), DialogValue::Text(format!("Active Mode: \"{}\" | Console Log: {}", mode, if log { "ON" } else { "OFF" }))); + let mode = event + .current_values + .get("cmb_mode") + .and_then(|v| match v { + DialogValue::Choice { text, .. } => Some(text.clone()), + _ => None, + }) + .unwrap_or_default(); + let log = event + .current_values + .get("chk_log") + .and_then(|v| match v { + DialogValue::Bool(b) => Some(*b), + _ => None, + }) + .unwrap_or(false); + updates.insert( + "lbl_status".to_string(), + DialogValue::Text(format!( + "Active Mode: \"{}\" | Console Log: {}", + mode, + if log { "ON" } else { "OFF" } + )), + ); return DialogActionResponse::UpdateValues(updates); } @@ -2460,7 +2566,11 @@ mod tests { .with_control(DialogControl::Choice { id: "cmb_mode".to_string(), label: "Execution Mode".to_string(), - options: vec!["Standard".to_string(), "Fast".to_string(), "Debug".to_string()], + options: vec![ + "Standard".to_string(), + "Fast".to_string(), + "Debug".to_string(), + ], default_index: 0, }) .with_control(DialogControl::Checkbox { @@ -2480,7 +2590,12 @@ mod tests { // 1. Verify initial status text assert_eq!( - app.plugin_dialog_state.as_ref().unwrap().text_values.get("lbl_status").unwrap(), + app.plugin_dialog_state + .as_ref() + .unwrap() + .text_values + .get("lbl_status") + .unwrap(), "Ready - Pick a file or click buttons to test reactivity" ); @@ -2571,7 +2686,12 @@ fn xref_dimension_targets( _ => None, }) .flat_map(|association| association.references.iter().flatten()) - .flat_map(|reference| reference.xrefs.iter().chain(&reference.intersection_objects)) + .flat_map(|reference| { + reference + .xrefs + .iter() + .chain(&reference.intersection_objects) + }) .filter(|handle| { doc.get_entity(**handle) .is_some_and(|entity| xref_blocks.contains(&entity.common().owner_handle)) diff --git a/src/app/update/file/open.rs b/src/app/update/file/open.rs index 4073a1b23e..9fe7ee2211 100644 --- a/src/app/update/file/open.rs +++ b/src/app/update/file/open.rs @@ -1,5 +1,5 @@ -use super::*; use super::super::util::*; +use super::*; impl OpenCADStudio { pub(in crate::app) fn on_open_file(&mut self) -> Task { @@ -290,10 +290,12 @@ impl OpenCADStudio { .as_deref() .and_then(|p| p.parent().map(|p| p.to_path_buf())) .unwrap_or_else(|| std::path::PathBuf::from(".")); - let infos = crate::io::xref::resolve_xrefs_for_keys( + let xref_session = self.tabs[j].ifccad_session.clone(); + let infos = crate::io::xref::resolve_xrefs_for_keys_in_session( &mut self.tabs[j].scene.document, &base_dir, &keys, + xref_session.as_ref(), ); if infos.is_empty() { continue; @@ -450,7 +452,11 @@ impl OpenCADStudio { } #[cfg(not(target_arch = "wasm32"))] - pub(in crate::app) fn retry_native_edit_guard(&mut self, i: usize, path: &std::path::Path) -> Result<(), String> { + pub(in crate::app) fn retry_native_edit_guard( + &mut self, + i: usize, + path: &std::path::Path, + ) -> Result<(), String> { if let Some(lease) = self.tabs[i].edit_lease.as_mut() { match lease.refresh_drawing_lock(path) { Ok(()) => { @@ -998,5 +1004,4 @@ impl OpenCADStudio { enter_viewport_task, ]) } - } diff --git a/src/app/update/file/plot_paper_tests/geopdf.rs b/src/app/update/file/plot_paper_tests/geopdf.rs index 145056d9fb..9488290a77 100644 --- a/src/app/update/file/plot_paper_tests/geopdf.rs +++ b/src/app/update/file/plot_paper_tests/geopdf.rs @@ -354,4 +354,3 @@ fn svg_only_plot_preferences_are_stored_but_ignored_by_pdf() { assert!(app.plot_dialog.non_scaling_stroke); assert!(app.plot_dialog.text_as_outlines); } - diff --git a/src/io/mod.rs b/src/io/mod.rs index 052f496149..0b4bd2398c 100644 --- a/src/io/mod.rs +++ b/src/io/mod.rs @@ -3,10 +3,10 @@ // All file reading/writing goes through document. // Default save format: DWG (AC1032 / R2018+). -#[cfg(not(target_arch = "wasm32"))] -pub mod edit_lock; #[cfg(not(target_arch = "wasm32"))] pub(crate) mod connection_workers; +#[cfg(not(target_arch = "wasm32"))] +pub mod edit_lock; // Same split as web_session/web_autosave: the save-routing decision (and // its tests) is pure and compiles everywhere; the showSaveFilePicker half // inside is wasm-only. @@ -566,10 +566,11 @@ async fn open_path_with_phase_attempt( callback }; crate::io::xref::register_underlay_sources(&doc, base_dir); - crate::io::xref::resolve_xrefs_with_progress( + crate::io::xref::resolve_xrefs_with_progress_in_session( &mut doc, base_dir, Some(xref_progress), + ifccad_session.as_ref(), ) } else { Vec::new() @@ -908,7 +909,7 @@ async fn load_web_bytes( // registry (see `resolve_web_xrefs`) before the caches snapshot the // document, so merged xref geometry is part of the caches — the same // phase order the native open uses. - let xref_infos = resolve_web_xrefs(&mut doc, progress.clone()).await; + let xref_infos = resolve_web_xrefs(&mut doc, progress.clone(), ifccad_session.as_ref()).await; let mut caches = crate::scene::build_derived_caches(&doc); caches.read_stats = Some(outcome.stats); caches.xrefs = xref_infos; @@ -986,6 +987,7 @@ pub async fn parse_drawing_bytes_web(name: &str, bytes: &[u8]) -> Result, + session: Option<&ocs_save::IfccadSession>, ) -> Vec { let pending: Vec = doc .block_records @@ -1018,7 +1020,12 @@ async fn resolve_web_xrefs( progress.set(crate::app::OPEN_PHASE_XREF, 5900, completed, total); }) }; - crate::io::xref::resolve_xrefs_with_progress(doc, Path::new(""), Some(xref_progress)) + crate::io::xref::resolve_xrefs_with_progress_in_session( + doc, + Path::new(""), + Some(xref_progress), + session, + ) } /// Web XATTACH pick: read the chosen drawing's bytes, keep them in the xref @@ -1556,7 +1563,7 @@ fn read_dxf_path(path: &Path, failsafe: bool) -> Result Result "Current-file alias has a different destination extension; save to a new matching path", )); } - match (std::fs::canonicalize(logical), std::fs::canonicalize(physical)) { + match ( + std::fs::canonicalize(logical), + std::fs::canonicalize(physical), + ) { (Ok(logical), Ok(physical)) if logical == physical => Ok(()), _ => Err(SaveFailure::externally_modified(logical)), } @@ -2725,6 +2738,13 @@ where .check_destination(&doc, &ext) .map_err(SaveFailure::other)?; } + if !ocs_save::is_ifccad_extension(&ext) { + if let Some(session) = ifccad_session { + session + .prepare_cad_external_sources(&mut doc) + .map_err(SaveFailure::other)?; + } + } let write_started = iced::time::Instant::now(); if ext == "dxf" { crate::entities::spline::complete_nurbs_for_dxf(&mut doc); @@ -2869,8 +2889,13 @@ fn replace_save_file_inner( // Omitting MOVEFILE_REPLACE_EXISTING makes the final placement // reject a name that appeared after the control request. return if unsafe { - MoveFileExW(source.as_ptr(), destination.as_ptr(), MOVEFILE_WRITE_THROUGH) - } == 0 { + MoveFileExW( + source.as_ptr(), + destination.as_ptr(), + MOVEFILE_WRITE_THROUGH, + ) + } == 0 + { Err(std::io::Error::last_os_error()) } else { Ok(()) @@ -3146,6 +3171,14 @@ pub async fn serialize_prepared_document( ifccad_session, ); } + let mut cad_copy; + let prepared = if let Some(session) = ifccad_session { + cad_copy = prepared.clone(); + session.prepare_cad_external_sources(&mut cad_copy)?; + &cad_copy + } else { + prepared + }; let encoded = match ocs_save::encode_request(prepared, ext) { Ok(encoded) => encoded, // The worker cannot help if the document cannot even be encoded — diff --git a/src/io/web_worker.rs b/src/io/web_worker.rs index fd427c1764..ee376bd287 100644 --- a/src/io/web_worker.rs +++ b/src/io/web_worker.rs @@ -10,7 +10,7 @@ const HASH_MARKER: &str = "\nreport-source-sha256:"; /// Version of the shared worker wire format (`ocs_save`); the `?v=` on the /// worker URL cache-busts to match. v5 adds the `serialize` action. const PROTOCOL_VERSION: u16 = ocs_save::PROTOCOL_VERSION; -const WORKER_URL: &str = "ocs-parse-worker.js?v=6"; +const WORKER_URL: &str = "ocs-parse-worker.js?v=7"; pub(super) async fn parse_document( name: &str, diff --git a/src/io/xref.rs b/src/io/xref.rs index dac4c08fa9..5352e807f3 100644 --- a/src/io/xref.rs +++ b/src/io/xref.rs @@ -10,6 +10,232 @@ use std::collections::VecDeque; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; +#[cfg(all(test, not(target_arch = "wasm32")))] +mod native_attachment_tests { + use super::*; + fn fixture(guid: &str) -> (Document, PathBuf, ocs_save::IfccadSession) { + let root = std::env::temp_dir().join(format!( + "ocs-native-xref-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(root.join("Tekeningen")).unwrap(); + std::fs::create_dir_all(root.join("Referenties")).unwrap(); + let mut source = Document::new(); + source.header.insertion_units = 6; + source.header.model_space_insertion_base = Vector3::new(10., 20., 0.); + source.header.fingerprint_guid = guid.into(); + source + .add_entity(EntityType::Line(document::entities::Line::from_coords( + 10., 20., 0., 12., 20., 0., + ))) + .unwrap(); + std::fs::write( + root.join("Referenties/grondplan.dwg"), + document::DwgWriter::write_to_vec(&source).unwrap(), + ) + .unwrap(); + let (loaded, session) = ocs_save::read_ifccad_for_edit(include_bytes!( + "../../crates/ocs_save/tests/fixtures/xref.ifcx" + )) + .unwrap(); + let mut host = loaded.document; + host.source_path = Some( + root.join("Tekeningen/hoofd.ifcx") + .to_string_lossy() + .into_owned(), + ); + host.header.fingerprint_guid = format!("native-host-{}", root.display()); + crate::io::normalize_block_origins(&mut host); + (host, root, session.unwrap()) + } + + #[test] + fn native_xref_source_base_is_subtracted_once_before_effective_scale() { + let (mut host, root, _session) = fixture("{E5B4A9AF-CF20-4FC9-A30F-FFB20FD987E1}"); + let infos = resolve_xrefs(&mut host, &root.join("Tekeningen")); + assert_eq!(infos[0].status, XrefStatus::Loaded); + let owner = host.block_records.get("grondplan").unwrap().handle; + let line = host + .entities() + .find_map(|e| match e { + EntityType::Line(l) if l.common.owner_handle == owner => Some(l), + _ => None, + }) + .unwrap(); + assert_eq!(line.start, Vector3::ZERO); + assert_eq!(line.end, Vector3::new(2., 0., 0.)); + let insert = host + .model_space_entities() + .find_map(|e| match e { + EntityType::Insert(i) => Some(i), + _ => None, + }) + .unwrap(); + assert_eq!(insert.x_scale(), 500.); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn native_and_dwg_file_dependency_guid_seed_the_same_warning() { + let (mut host, root, _session) = fixture("{11111111-2222-3333-4444-555555555555}"); + let infos = resolve_xrefs(&mut host, &root.join("Tekeningen")); + assert_eq!(infos[0].status, XrefStatus::Loaded); + assert!(infos[0].other_drawing); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn native_source_bytes_are_scoped_and_failed_reload_keeps_body() { + let (mut first, root, session) = fixture("{E5B4A9AF-CF20-4FC9-A30F-FFB20FD987E1}"); + let (second, other_root, other_session) = fixture("{E5B4A9AF-CF20-4FC9-A30F-FFB20FD987E1}"); + let record = first.block_records.get("grondplan").unwrap().clone(); + let bytes = Arc::new(std::fs::read(root.join("Referenties/grondplan.dwg")).unwrap()); + session + .bind_external_source_bytes( + record.handle, + &record.xref_path, + "grondplan.dwg".into(), + bytes, + ) + .unwrap(); + let other_record = second.block_records.get("grondplan").unwrap(); + assert!(other_session + .external_source_bytes(other_record.handle, &other_record.xref_path) + .is_none()); + let keys = [record.handle].into_iter().collect(); + let infos = resolve_xrefs_for_keys_in_session(&mut first, &root, &keys, Some(&session)); + assert_eq!(infos[0].status, XrefStatus::Loaded); + let before = first + .entities() + .filter(|e| e.common().owner_handle == record.handle) + .count(); + let mut changed = Document::new(); + changed.header.insertion_units = 6; + changed.header.model_space_insertion_base = Vector3::new(11., 20., 0.); + changed + .add_entity(EntityType::Line(document::entities::Line::from_coords( + 11., 20., 0., 14., 20., 0., + ))) + .unwrap(); + let bytes = document::DwgWriter::write_to_vec(&changed).unwrap(); + let mut infos = Vec::new(); + merge_xref_reads_in_session( + &mut first, + vec![( + record.name.clone(), + record.xref_path.clone(), + record.handle, + read_source_bytes("grondplan.dwg", &bytes), + )], + &mut infos, + None, + Some(&session), + ); + assert_eq!(infos[0].status, XrefStatus::Failed); + assert!(infos[0] + .diagnostics + .iter() + .any(|d| d.contains("base point"))); + assert_eq!( + first + .entities() + .filter(|e| e.common().owner_handle == record.handle) + .count(), + before + ); + std::fs::remove_dir_all(root).unwrap(); + std::fs::remove_dir_all(other_root).unwrap(); + } + + #[test] + fn native_xref_search_order_is_direct_host_structured_then_configured() { + let (_, root, _) = fixture("{E5B4A9AF-CF20-4FC9-A30F-FFB20FD987E1}"); + let host = root.join("Tekeningen"); + std::fs::create_dir_all(host.join("xref")).unwrap(); + let configured = root.join("search"); + std::fs::create_dir_all(&configured).unwrap(); + let name = "ground.dwg"; + for path in [ + configured.join(name), + host.join("xref").join(name), + host.join(name), + ] { + std::fs::write(&path, b"chosen").unwrap(); + } + let dirs = [configured.clone()]; + assert_eq!( + resolve_path_in("../missing/ground.dwg", &host, &dirs), + Some(host.join(name)) + ); + std::fs::remove_file(host.join(name)).unwrap(); + assert_eq!( + resolve_path_in("../missing/ground.dwg", &host, &dirs), + Some(host.join("xref").join(name)) + ); + std::fs::remove_file(host.join("xref").join(name)).unwrap(); + assert_eq!( + resolve_path_in("../missing/ground.dwg", &host, &dirs), + Some(configured.join(name)) + ); + assert_eq!( + resolve_path_in("../Referenties/grondplan.dwg", &host, &dirs), + Some(host.join("../Referenties/grondplan.dwg")) + ); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn native_guid_warning_is_scoped_to_same_named_open_documents() { + let (mut first, first_root, first_session) = + fixture("{E5B4A9AF-CF20-4FC9-A30F-FFB20FD987E1}"); + let (mut second, second_root, second_session) = + fixture("{11111111-2222-3333-4444-555555555555}"); + for (doc, root, session) in [ + (&mut first, &first_root, &first_session), + (&mut second, &second_root, &second_session), + ] { + doc.header.fingerprint_guid.clear(); + doc.source_path = Some("same.ifcx".into()); + let record = doc.block_records.get("grondplan").unwrap(); + session + .bind_external_source_bytes( + record.handle, + &record.xref_path, + "grondplan.dwg".into(), + Arc::new(std::fs::read(root.join("Referenties/grondplan.dwg")).unwrap()), + ) + .unwrap(); + } + let keys = [first.block_records.get("grondplan").unwrap().handle] + .into_iter() + .collect(); + let first_info = + resolve_xrefs_for_keys_in_session(&mut first, &first_root, &keys, Some(&first_session)); + assert_eq!(first_info[0].status, XrefStatus::Loaded, "{first_info:?}"); + assert!(!first_info[0].other_drawing); + let second_info = resolve_xrefs_for_keys_in_session( + &mut second, + &second_root, + &keys, + Some(&second_session), + ); + assert_eq!(second_info[0].status, XrefStatus::Loaded, "{second_info:?}"); + assert!(second_info[0].other_drawing); + let first_reload = + resolve_xrefs_for_keys_in_session(&mut first, &first_root, &keys, Some(&first_session)); + assert!( + !first_reload[0].other_drawing, + "the second tab must not change the first tab's GUID baseline" + ); + std::fs::remove_dir_all(first_root).unwrap(); + std::fs::remove_dir_all(second_root).unwrap(); + } +} + /// Status of an external reference block. #[derive(Debug, Clone, PartialEq, Eq)] pub enum XrefStatus { @@ -121,16 +347,15 @@ fn source_cache() -> &'static Mutex<(HashMap>>, VecDeque &'static Mutex>> { - static MERGED: OnceLock>>> = - OnceLock::new(); + static MERGED: OnceLock>>> = OnceLock::new(); MERGED.get_or_init(|| Mutex::new(HashMap::default())) } /// FingerprintGUID of the drawing each xref block last loaded, keyed by the /// host's own GUID and the block, so a reload can tell a revision (same /// GUID) from another drawing that took the file's place. -// ponytail: session-only; a reopened host has no expected GUID until the -// file's dependency list (AcDb:FileDepList) records it. +// Observations are session-only; the first load also uses the stored +// AcDb:FileDepList expectation (native import populates that same list). fn loaded_identities() -> &'static Mutex> { static IDS: OnceLock>> = OnceLock::new(); IDS.get_or_init(|| Mutex::new(HashMap::default())) @@ -138,6 +363,7 @@ fn loaded_identities() -> &'static Mutex> { /// Record `loaded` as the drawing behind `br_handle`; true when the block /// held a different known drawing before. +#[cfg(test)] fn replaced_by_other_drawing(host_guid: &str, br_handle: Handle, loaded: &str) -> bool { if host_guid.is_empty() || loaded.is_empty() { return false; @@ -477,7 +703,6 @@ pub(crate) fn registered_document(key: &str) -> Result { /// Apply the same post-parse fixups the file-open tail applies, so merged /// xref content behaves like natively loaded content. -#[cfg(target_arch = "wasm32")] fn finalize_xref_outcome(outcome: &mut document::ReadOutcome) { let doc = &mut outcome.document; super::normalize_block_origins(doc); @@ -537,7 +762,7 @@ fn read_outcome_from_bytes( /// /// Returns a list of [`XrefInfo`] describing each xref block found. pub fn resolve_xrefs(doc: &mut Document, base_dir: &Path) -> Vec { - resolve_xrefs_with_filter(doc, base_dir, None, None, false) + resolve_xrefs_with_filter(doc, base_dir, None, None, false, None) } /// Reload only the direct xref block records identified by `keys`. @@ -550,7 +775,16 @@ pub fn resolve_xrefs_for_keys( base_dir: &Path, keys: &HashSet, ) -> Vec { - resolve_xrefs_with_filter(doc, base_dir, None, Some(keys), false) + resolve_xrefs_with_filter(doc, base_dir, None, Some(keys), false, None) +} + +pub fn resolve_xrefs_for_keys_in_session( + doc: &mut Document, + base_dir: &Path, + keys: &HashSet, + session: Option<&ocs_save::IfccadSession>, +) -> Vec { + resolve_xrefs_with_filter(doc, base_dir, None, Some(keys), false, session) } /// Resolve XREFs while reporting completed work units. This is the open @@ -564,7 +798,16 @@ pub fn resolve_xrefs_with_progress( base_dir: &Path, progress: Option>, ) -> Vec { - resolve_xrefs_with_filter(doc, base_dir, progress, None, true) + resolve_xrefs_with_filter(doc, base_dir, progress, None, true, None) +} + +pub fn resolve_xrefs_with_progress_in_session( + doc: &mut Document, + base_dir: &Path, + progress: Option>, + session: Option<&ocs_save::IfccadSession>, +) -> Vec { + resolve_xrefs_with_filter(doc, base_dir, progress, None, true, session) } fn resolve_xrefs_with_filter( @@ -573,6 +816,7 @@ fn resolve_xrefs_with_filter( progress: Option>, only: Option<&HashSet>, honor_unloaded: bool, + session: Option<&ocs_save::IfccadSession>, ) -> Vec { let mut result = Vec::new(); // Auto-resolve every xref — frustum + LOD culling keep GPU cost bounded. @@ -634,7 +878,21 @@ fn resolve_xrefs_with_filter( }); callback }); - let read = read_xref_file(&raw_path, base_dir, nested_progress); + let read = if let Some(bytes) = + session.and_then(|s| s.external_source_bytes(br_handle, &raw_path)) + { + read_source_bytes(&bytes.file_name, &bytes.bytes) + } else if cfg!(target_arch = "wasm32") + && session.and_then(|s| s.external_source(br_handle)).is_some() + { + XrefRead { + resolved: None, + outcome: None, + source_sha256: None, + } + } else { + read_xref_file(&raw_path, base_dir, nested_progress) + }; parse_units[xref_index].store(1000, std::sync::atomic::Ordering::Relaxed); if let Some(progress) = &progress { let completed = parse_units @@ -647,7 +905,7 @@ fn resolve_xrefs_with_filter( }) .collect(); - merge_xref_reads(doc, parsed, &mut result, progress.as_ref()); + merge_xref_reads_in_session(doc, parsed, &mut result, progress.as_ref(), session); result } @@ -661,6 +919,29 @@ pub struct XrefRead { source_sha256: Option, } +impl XrefRead { + pub fn source_content(&self) -> Option { + let outcome = self.outcome.as_ref()?.as_ref().ok()?; + (outcome.stats.source_format == Some(document::SourceFormat::Dwg)) + .then(|| document::dwg_external_source_content(&outcome.document)) + } +} + +pub fn read_source_bytes(name: &str, bytes: &[u8]) -> XrefRead { + let outcome = document::DwgReader::from_stream(std::io::Cursor::new(bytes.to_vec())) + .read_with_stats() + .map_err(|error| error.to_string()) + .map(|mut outcome| { + finalize_xref_outcome(&mut outcome); + outcome + }); + XrefRead { + resolved: Some(PathBuf::from(name)), + outcome: Some(outcome), + source_sha256: None, + } +} + /// Read and parse the drawing that a reference stored as `raw_path` names, /// resolved against `base_dir`. It touches no host document, so it can run /// on any thread; [`merge_xref_reads`] merges the result. @@ -669,6 +950,18 @@ pub fn read_xref_file( base_dir: &Path, progress: Option>, ) -> XrefRead { + // Native unknown schemes are retained, but must never reach filename fallback. + if let Err(error) = document::external_source_location_from_cad_path(raw_path) + .and_then(|location| document::external_source_location_to_cad_path(&location)) + { + return XrefRead { + resolved: None, + outcome: Some(Err(format!( + "Unsupported source location {raw_path}: {error}" + ))), + source_sha256: None, + }; + } let resolved = resolve_path(raw_path, base_dir); #[cfg(not(target_arch = "wasm32"))] let initial_fingerprint = resolved @@ -721,6 +1014,16 @@ pub fn merge_xref_reads( parsed: Vec<(String, String, Handle, XrefRead)>, result: &mut Vec, progress: Option<&std::sync::Arc>, +) { + merge_xref_reads_in_session(doc, parsed, result, progress, None) +} + +pub fn merge_xref_reads_in_session( + doc: &mut Document, + parsed: Vec<(String, String, Handle, XrefRead)>, + result: &mut Vec, + progress: Option<&Arc>, + session: Option<&ocs_save::IfccadSession>, ) { let xref_count = parsed.len(); let total_units = xref_count.saturating_mul(2000); @@ -731,6 +1034,23 @@ pub fn merge_xref_reads( outcome: xref_outcome, source_sha256, } = read; + let xref_outcome = xref_outcome.map(|outcome| outcome.and_then(|outcome| { + if let Some(record) = doc.block_records.iter().find(|r| r.handle == br_handle) { + document::dwg_xref_fingerprint_guid(doc, record).map_err(|e| e.to_string())?; + } + if let (Some(found), Some(host)) = (&resolved, &doc.source_path) { + if std::fs::canonicalize(found).ok().zip(std::fs::canonicalize(host).ok()).is_some_and(|(a,b)| a == b) { + return Err("Direct self-reference is unsupported".into()); + } + } + if let Some(session) = session { + if session.external_source(br_handle).is_some() && outcome.stats.source_format != Some(document::SourceFormat::Dwg) { + return Err("This native XREF requires a DWG source; other source formats are deferred".into()); + } + session.check_external_source_reload(br_handle, &document::dwg_external_source_content(&outcome.document))?; + } + Ok(outcome) + })); let mut other_drawing = false; let (status, diagnostics, read_stats) = match xref_outcome { Some(Ok(outcome)) => { @@ -766,11 +1086,43 @@ pub fn merge_xref_reads( // re-apply onto the freshly merged layers below. Without this // every reload silently reset frozen/off/color tweaks the // user made on `name|*` layers back to file defaults. - other_drawing = replaced_by_other_drawing( - &doc.header.fingerprint_guid, - br_handle, + let expected = doc + .block_records + .iter() + .find(|r| r.handle == br_handle) + .and_then(|r| document::dwg_xref_fingerprint_guid(doc, r).ok().flatten()); + let observed = session.and_then(|session| { + session.observe_external_source_guid( + br_handle, + &outcome.document.header.fingerprint_guid, + ) + }); + if let Some(changed) = observed { + other_drawing = changed; + } else if let Some(loaded) = document::ifccad::normalize_ifccad_fingerprint_guid( &outcome.document.header.fingerprint_guid, - ); + ) { + let has_host_identity = + !doc.header.fingerprint_guid.is_empty() || doc.source_path.is_some(); + let previous = if has_host_identity { + let host_key = format!( + "{}|{}", + doc.header.fingerprint_guid, + doc.source_path.as_deref().unwrap_or_default() + ); + loaded_identities() + .lock() + .ok() + .and_then(|mut ids| { + ids.insert((host_key, br_handle), loaded.clone()) + }) + .or(expected) + } else { + expected + }; + other_drawing = previous + .is_some_and(|previous| !previous.eq_ignore_ascii_case(&loaded)); + } let visretain = doc.header.retain_xref_visibility; let kept_layers = if visretain { snapshot_dependent_layers(doc, &block_name) @@ -951,49 +1303,29 @@ pub(crate) fn resolve_path(raw: &str, _base_dir: &Path) -> Option { /// Handles absolute paths, relative paths, and Windows-style separators. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn resolve_path(raw: &str, base_dir: &Path) -> Option { - let normalised = raw.replace('\\', "/"); - let p = PathBuf::from(&normalised); - - if p.is_absolute() { - if p.exists() { - return Some(p); - } - // Fallback: try the filename in base_dir. - if let Some(fname) = p.file_name() { - let c = base_dir.join(fname); - if c.exists() { - return Some(c); - } - let structured = base_dir.join("xref").join(fname); - if structured.is_file() { - return Some(structured); - } - } - return None; - } - - // Relative path against base_dir. - let candidate = base_dir.join(&p); - if candidate.exists() { - return Some(candidate); - } - - // Last resort: just the filename. - if let Some(fname) = p.file_name() { - let c = base_dir.join(fname); - if c.exists() { - return Some(c); - } - // Flat references from older packages also resolve into the structured - // AutoCAD-style xref/ folder. The reverse (an xref/ path with a flat - // package) is covered by the bare-name fallback above. - let structured = base_dir.join("xref").join(fname); - if structured.is_file() { - return Some(structured); - } - } + let dirs = std::env::var_os("OCS_XREF_PATH") + .map(|v| std::env::split_paths(&v).collect::>()) + .unwrap_or_default(); + resolve_path_in(raw, base_dir, &dirs) +} - None +#[cfg(not(target_arch = "wasm32"))] +fn resolve_path_in(raw: &str, base_dir: &Path, search_dirs: &[PathBuf]) -> Option { + let p = PathBuf::from(raw.replace('\\', "/")); + let direct = if p.is_absolute() { + p.clone() + } else { + base_dir.join(&p) + }; + if direct.is_file() { + return Some(direct); + } + let name = p.file_name()?; + std::iter::once(base_dir.to_path_buf()) + .chain(std::iter::once(base_dir.join("xref"))) + .chain(search_dirs.iter().cloned()) + .map(|dir| dir.join(name)) + .find(|candidate| candidate.is_file()) } /// Give a block record its BLOCK / ENDBLK markers, linked through the @@ -1635,6 +1967,8 @@ fn merge_source_entities( // Paper-space / unknown owners are skipped. let old_owner = entity.common().owner_handle; let new_owner = if old_owner == source_ms_handle { + let base = source.header.model_space_insertion_base; + entity.translate(Vector3::new(-base.x, -base.y, -base.z)); target_br } else if let Some(&h) = maps.br_handles.get(&old_owner) { h @@ -1714,6 +2048,39 @@ pub fn collect_entries_with_prev( collect_entries_impl(doc, base_dir, unloaded, prev, true) } +/// Apply explicit per-tab source choices to the existing manager/report rows. +pub fn apply_native_source_status( + entries: &mut [crate::io::xref_model::ReferenceEntry], + session: Option<&ocs_save::IfccadSession>, +) { + use crate::io::xref_model::{RefKind, RefStatus}; + let Some(session) = session else { + return; + }; + for entry in entries { + if entry.kind != RefKind::DwgXref || entry.parent_key.is_some() { + continue; + } + if let Some(source) = + session.external_source_bytes(Handle::new(entry.key), &entry.saved_path) + { + entry.found_at = Some(source.file_name); + entry.size_bytes = Some(source.bytes.len() as u64); + if entry.status != RefStatus::Unloaded { + entry.status = RefStatus::Loaded; + } + } else if cfg!(target_arch = "wasm32") + && session.external_source(Handle::new(entry.key)).is_some() + { + entry.found_at = None; + entry.size_bytes = None; + if entry.status != RefStatus::Unloaded { + entry.status = RefStatus::NotFound; + } + } + } +} + /// Resolve one host-owned row without applying the manager's nested-row /// deduplication filter. A direct, uninserted record can intentionally be /// hidden by that filter immediately after a path edit; lifecycle responses @@ -3950,8 +4317,8 @@ mod tests { #[test] fn a_reload_relinks_dimension_references_to_the_new_copies() { use document::objects::{ - AssocDimensionAssociation, AssocDimensionReference, AssociativeData, - AssociativeObject, ObjectType, + AssocDimensionAssociation, AssocDimensionReference, AssociativeData, AssociativeObject, + ObjectType, }; let dir = xref_tmpdir("relink"); let mut source = document::Document::new(); @@ -3961,8 +4328,11 @@ mod tests { let source_line = source.add_entity(document::EntityType::Line(line)).unwrap(); let path = dir.join("walls.dwg"); let write = |doc: &document::Document| { - std::fs::write(&path, crate::io::save_to_bytes(doc, "dwg", doc.version).unwrap()) - .unwrap(); + std::fs::write( + &path, + crate::io::save_to_bytes(doc, "dwg", doc.version).unwrap(), + ) + .unwrap(); }; write(&source); @@ -5258,4 +5628,3 @@ mod web_registry_tests { assert!(unresolved_xref_names(&[]).is_empty()); } } - diff --git a/web/ocs-parse-worker.js b/web/ocs-parse-worker.js index 6590e76ba6..c931d0c74a 100644 --- a/web/ocs-parse-worker.js +++ b/web/ocs-parse-worker.js @@ -1,7 +1,7 @@ -import init, { parse_document, serialize_document, sha256_document } from "./worker_pkg/ocs_web_worker.js?v=6"; +import init, { parse_document, serialize_document, sha256_document } from "./worker_pkg/ocs_web_worker.js?v=7"; const ready = init( - new URL("./worker_pkg/ocs_web_worker_bg.wasm?v=6", import.meta.url), + new URL("./worker_pkg/ocs_web_worker_bg.wasm?v=7", import.meta.url), ); self.onmessage = async ({ data }) => {