diff --git a/Cargo.lock b/Cargo.lock index 8cd78c9..78427e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -260,6 +260,12 @@ dependencies = [ "serde", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.2.0" @@ -443,8 +449,8 @@ dependencies = [ [[package]] name = "ifccad" -version = "2026.46.1" -source = "git+https://github.com/OpenAEC-Foundation/ifccad.git?rev=9ca1cf1ff4c71dad8d380677e9eb657818b03d80#9ca1cf1ff4c71dad8d380677e9eb657818b03d80" +version = "2026.47.0" +source = "git+https://github.com/OpenAEC-Foundation/ifccad.git?rev=96895aea607e3f2a54f9b286115844554f59df77#96895aea607e3f2a54f9b286115844554f59df77" dependencies = [ "base64", "fpmath", @@ -456,6 +462,7 @@ dependencies = [ "serde", "serde_json", "thiserror 1.0.69", + "uriparse", ] [[package]] @@ -1150,6 +1157,16 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "uriparse" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0200d0fc04d809396c2ad43f3c95da3582a2556eba8d453c1087f4120ee352ff" +dependencies = [ + "fnv", + "lazy_static", +] + [[package]] name = "utf8_iter" version = "1.0.4" diff --git a/Cargo.toml b/Cargo.toml index 5848aaa..187d075 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ acadrust = { git = "https://github.com/hakanaktt/acadrust.git", rev = "a7d378502 rmp-serde = { version = "=1.3.0", optional = true } serde = { version = "1", features = ["derive"], optional = true } # ifccad only reads and writes IFCX; the mapping to `Document` lives here. -ifccad = { git = "https://github.com/OpenAEC-Foundation/ifccad.git", rev = "9ca1cf1ff4c71dad8d380677e9eb657818b03d80", optional = true } +ifccad = { git = "https://github.com/OpenAEC-Foundation/ifccad.git", rev = "96895aea607e3f2a54f9b286115844554f59df77", optional = true } web-time = { version = "1", optional = true } [dev-dependencies] @@ -27,6 +27,10 @@ serde_json = { version = "1", features = ["float_roundtrip"] } [workspace] +[[example]] +name = "xref_review" +required-features = ["ifcx", "mline-pilot"] + [[example]] name = "annotation_gallery" required-features = ["ifcx"] diff --git a/README.md b/README.md index a8f5bbc..b0e0933 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,9 @@ With the `ifcx` feature, the `Ifcx` format reads and writes IFCX through [ifccad](https://github.com/OpenAEC-Foundation/ifccad): - ifccad only reads and writes the files; the mapping to `Document` lives here, so neither library depends on the other. +- The XREF development mapping pairs with profile 0.12.0 / CBOR 12. It retains + external DWG sources and Model attachments, with URI/search locations and + optional FileDepList identity. See [XREF scope and evidence](docs/ifcx-xrefs.md). - The IFCX mapping covers layers, line patterns with their SHX and text symbols, text styles, dimension styles, UCSs, the point display, block definitions, paper layouts with their sheet and plot diff --git a/docs/ifcx-xrefs.md b/docs/ifcx-xrefs.md new file mode 100644 index 0000000..86be455 --- /dev/null +++ b/docs/ifcx-xrefs.md @@ -0,0 +1,53 @@ +# External sources and Model XREF attachments + +The development mapping pairs with IFCCAD profile 0.12.0 / CBOR 12. The core +owns native source/location validation. Document maps DWG XREF definitions to +drawing-local external sources and INSERTs to native XREF placements. +`import_ifccad_preserving` and `export_ifccad_preserving` retain native source +and entity IDs, original URI spelling and optional expected FingerprintGUID. +Context history retains earlier authored locators for undo after a native save. +Resolving a file at another location does not implicitly rewrite its locator. + +Supported placements are Model attachments with Z rotation and positive uniform +effective scale. The scale already includes any insertion-unit conversion. +Neither direction multiplies the unit factor again. Source base points belong +to the external source; placement is stored once as O/X/Y. Unknown offline +source units remain absent. A source definition without an INSERT is retained. +Loaded external bodies are not emitted as native blocks or Model entities. + +The pure location helpers distinguish a direct URI-reference from a search +filename. Relative CAD paths map to escaped relative URI-references; drive +absolute and UNC paths map to `file:` URIs. A literal filename percent sign is +escaped once, and URI escapes are decoded once. A direct one-component relative +URI exports with `./`, keeping its direct lookup meaning on reimport. Native +URI spellings are retained in context. URI schemes without a qualified CAD +mapping, queries and fragments remain unresolved editing references; DWG/DXF +file export reports an error rather than silently changing their meaning. + +DWG expected identity comes from the typed codec FileDepList using its +`Acad:XRef` feature and stored filename. Multiple matching records are an +explicit ambiguity error. The main drawing header GUID is independent. +The native expected GUID is optional and canonicalized from a valid stored +DWG GUID. `dwg_external_source_content` reads actual opened-source header +metadata; it never generates an identity. + +Physical DWG tests cover AC1018, AC1021 and AC1032 dependency identity. +Physical DXF return currently has no FileDepList GUID. This matches the existing +Document/OCS DWG-to-DXF policy and adds no special GUID-loss message. This +local writer/reader evidence does not replace independent AutoCAD/ODA fixture +qualification, which remains pending in the first-slice working record. + +The matched host has also been checked with LibreDWG geometry/header readback +and an independent literal FileDepList section parser. The latter is necessary +for empty fields and the legacy feature list because of identified LibreDWG +decoder limitations. An AutoCAD-authored dependency identity fixture remains +separate qualification. Extra physical dependency metadata and unbound records +produce native conversion loss diagnostics; the first native source model +retains only the qualified expected FingerprintGUID. + +Overlay, arrays, Paper ownership, XREF inside a local block, nonuniform or +reflected scaling and INSERT attributes produce explicit conversion losses. +Native core validation enforces the same placement/ownership boundary. +Nested reference graphs, binding, packaging, remote download and additional +source formats remain outside this slice. The core stays independent of CAD +runtimes; Document owns CAD conversion, and the host owns resolution and I/O. diff --git a/examples/xref_review.rs b/examples/xref_review.rs new file mode 100644 index 0000000..32f5874 --- /dev/null +++ b/examples/xref_review.rs @@ -0,0 +1,170 @@ +//! Small XREF review project; all files pass their production reader. +use opencaddocument::{ifccad::*, *}; +use std::path::PathBuf; + +fn main() -> std::result::Result<(), Error> { + let root = std::env::args_os() + .nth(1) + .map(PathBuf::from) + .ok_or("output directory required")?; + let drawings = root.join("Tekeningen"); + let references = root.join("Referenties"); + std::fs::create_dir_all(&drawings)?; + std::fs::create_dir_all(&references)?; + let mut d = load_ifccad_bytes( + include_bytes!("../tests/fixtures/xref/attachment.ifcx"), + Default::default(), + )? + .into_document(); + d.paper_layouts.clear(); + let workspace = load_ifccad_bytes( + include_bytes!("../tests/fixtures/workspace-state.ifcx"), + Default::default(), + )? + .into_document(); + let mut window = workspace.model_windows[0].clone(); + window.id = d.id_counters.allocate_model_window_id()?; + window.view.target = ifccad::geometry_kernel::Point3::new(10000., 5500., 0.); + window.view.height = 2500.; + window.stored_ucs = IfccadUcsSelection::World; + window.use_stored_ucs = false; + window.grid.enabled = false; + d.model_view_state = Some(IfccadModelViewState { + current_model_ucs: Some(IfccadUcsSelection::World), + active_model_window_id: Some(window.id), + }); + d.model_windows.push(window); + 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 = "{E5B4A9AF-CF20-4FC9-A30F-FFB20FD987E1}".into(); + source.add_entity(EntityType::Line(entities::Line::from_coords( + 10., 20., 0., 12., 20., 0., + )))?; + let (bytes, losses) = Dwg.write(&source)?; + assert!(losses.is_empty()); + let (read, _) = Dwg.read(&bytes)?; + assert_eq!( + read.header.model_space_insertion_base, + source.header.model_space_insertion_base + ); + std::fs::write(references.join("grondplan.dwg"), &bytes)?; + let variants = root.join("Variants"); + std::fs::create_dir_all(&variants)?; + let mut other_identity = source.clone(); + other_identity.header.fingerprint_guid = "{11111111-2222-3333-4444-555555555555}".into(); + let (variant, losses) = Dwg.write(&other_identity)?; + assert!(losses.is_empty()); + assert_eq!( + Dwg.read(&variant)?.0.header.fingerprint_guid, + other_identity.header.fingerprint_guid + ); + std::fs::write(variants.join("other-guid.dwg"), variant)?; + if let Some(public) = std::env::args_os().nth(2).map(PathBuf::from) { + std::fs::create_dir_all(&public)?; + std::fs::write(public.join("xref-source.dwg"), &bytes)?; + let mut gallery = d.clone(); + gallery.model_windows[0].view.target = + ifccad::geometry_kernel::Point3::new(13000., 5500., 0.); + gallery.model_windows[0].view.height = 6000.; + let prototype = gallery.model.entities[0].clone(); + gallery.external_sources.clear(); + gallery.model.entities.clear(); + // This is a newly authored public drawing, independent of fixture history. + gallery.id_counters.next_entity_id = 1; + gallery.id_counters.next_external_source_id = 1; + gallery.id_counters.next_layout_id = gallery.model.id + 1; + let mut layers = std::collections::BTreeMap::new(); + let mut next_layer = 1; + for layer in &mut gallery.layers { + let id = if layer.id == 0 { + 0 + } else { + let id = next_layer; + next_layer += 1; + id + }; + layers.insert(layer.id, id); + layer.id = id; + } + gallery.id_counters.next_layer_id = next_layer; + if let Some(workspace) = &mut gallery.workspace_state { + workspace.current_layer_id = workspace.current_layer_id.map(|id| layers[&id]); + } + for (index, location) in [ + IfccadExternalSourceLocation::UriReference { + uri: "./xref-source.dwg".into(), + }, + IfccadExternalSourceLocation::SearchFileName { + file_name: "xref-source.dwg".into(), + }, + IfccadExternalSourceLocation::UriReference { + uri: "file:///C:/CAD/xref-source.dwg".into(), + }, + IfccadExternalSourceLocation::UriReference { + uri: "example:offline-xref".into(), + }, + ] + .into_iter() + .enumerate() + { + let mut definition = d.external_sources[0].clone(); + definition.id = gallery.id_counters.allocate_external_source_id()?; + definition.name = [ + "Relative", + "Search filename", + "Absolute file URI", + "Unresolved URI", + ][index] + .into(); + definition.location = location; + let mut entity = prototype.clone(); + let IfccadEntity::Native(native) = &mut entity else { + unreachable!() + }; + native.id = gallery.id_counters.allocate_entity_id()?; + native.layer_id = layers[&native.layer_id]; + let IfccadEntityKind::Xref(xref) = &mut native.kind else { + unreachable!() + }; + xref.source_id = definition.id; + xref.placement.origin[0] += index as f64 * 2000.; + gallery.external_sources.push(definition); + gallery.model.entities.push(entity); + } + validate_ifccad_document(&gallery)?; + let encoded = encode_ifccad_document(&gallery)?; + load_ifccad_bytes(encoded.bytes(), Default::default())?; + std::fs::write(public.join("xrefs.ifcx"), encoded.bytes())?; + } + let (native, mut context) = Ifcx.import_ifccad_preserving(&d)?; + assert!(native.losses.is_empty()); + let back = Ifcx.export_ifccad_preserving(&native.document, &mut context)?; + assert_eq!(back.drawing.external_sources, d.external_sources); + std::fs::write( + drawings.join("hoofd.ifcx"), + encode_ifccad_document(&d)?.bytes(), + )?; + std::fs::write( + drawings.join("hoofd.ifccad.cbor"), + encode_ifccad_cbor_document(&d)?.bytes(), + )?; + for (name, format, guid) in [ + ("hoofd-retour.dwg", &Dwg as &dyn Format, true), + ("hoofd-retour.dxf", &Dxf as &dyn Format, false), + ] { + let (bytes, losses) = format.write(&native.document)?; + assert!(losses.is_empty()); + let (read, _) = format.read(&bytes)?; + let back = Ifcx.export_ifccad(&read)?; + validate_ifccad_document(&back.drawing)?; + assert_eq!(back.drawing.external_sources.len(), 1); + let IfccadExternalSourceContent::Dwg { + fingerprint_guid, .. + } = &back.drawing.external_sources[0].source; + assert_eq!(fingerprint_guid.is_some(), guid); + std::fs::write(drawings.join(name), bytes)?; + } + println!("{}", root.display()); + Ok(()) +} diff --git a/src/format.rs b/src/format.rs index 33f09f3..d4cd238 100644 --- a/src/format.rs +++ b/src/format.rs @@ -52,6 +52,8 @@ impl Format for Dwg { } fn write(&self, document: &Document) -> Result<(Vec, Vec), Error> { + #[cfg(feature = "ifcx")] + crate::validate_cad_external_sources(document)?; Ok((DwgWriter::write_to_vec(document)?, Vec::new())) } } @@ -74,6 +76,8 @@ impl Format for Dxf { } fn write(&self, document: &Document) -> Result<(Vec, Vec), Error> { + #[cfg(feature = "ifcx")] + crate::validate_cad_external_sources(document)?; Ok((DxfWriter::new(document).write_to_vec()?, Vec::new())) } } diff --git a/src/ifcx/dimension_graphics.rs b/src/ifcx/dimension_graphics.rs index a3f44f0..8d21b20 100644 --- a/src/ifcx/dimension_graphics.rs +++ b/src/ifcx/dimension_graphics.rs @@ -278,6 +278,7 @@ fn canonical( /// Resource-only conversion context: never clone the drawing's entity graph. fn resources(d: &IfccadDocument) -> IfccadDocument { IfccadDocument { + external_sources: Vec::new(), table_styles: Vec::new(), table_data_links: Vec::new(), data_tables: Vec::new(), @@ -319,6 +320,7 @@ fn resources(d: &IfccadDocument) -> IfccadDocument { } fn context<'a>(document: &'a Document, drawing: &IfccadDocument) -> Writer<'a> { Writer { + external_sources: HashMap::new(), #[cfg(feature = "mline-pilot")] roundtrip: None, table_data_links: HashMap::new(), diff --git a/src/ifcx/external_sources.rs b/src/ifcx/external_sources.rs new file mode 100644 index 0000000..3687300 --- /dev/null +++ b/src/ifcx/external_sources.rs @@ -0,0 +1,208 @@ +//! Pure CAD path / native URI-reference conversion. Resolution belongs to hosts. +use crate::Error; +use ifccad::IfccadExternalSourceLocation as Location; + +fn error(message: &str) -> Error { + format!("external source location: {message}").into() +} +fn encode(path: &str) -> String { + let mut out = String::new(); + for b in path.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/') { + out.push(b as char); + } else { + use std::fmt::Write; + write!(&mut out, "%{b:02X}").unwrap(); + } + } + out +} +fn decode(uri: &str) -> Result { + let bytes = uri.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + let pair = uri + .get(i + 1..i + 3) + .ok_or_else(|| error("invalid URI escape"))?; + out.push(u8::from_str_radix(pair, 16).map_err(|_| error("invalid URI escape"))?); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + let path = String::from_utf8(out).map_err(|_| error("file URI must encode UTF-8"))?; + if path.contains('\0') { + return Err(error("file path contains NUL")); + } + Ok(path) +} + +/// Convert a literal CAD path, escaping filename bytes exactly once. +pub fn external_source_location_from_cad_path(path: &str) -> Result { + if path.is_empty() || path.contains('\0') { + return Err(error("empty or invalid CAD path")); + } + let path = path.replace('\\', "/"); + let bytes = path.as_bytes(); + let location = if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' { + if bytes.get(2) != Some(&b'/') { + return Err(error("drive-relative paths have no portable basis")); + } + Location::UriReference { + uri: format!("file:///{}:{}", &path[..1], encode(&path[2..])), + } + } else if path + .split('/') + .next() + .is_some_and(|first| first.contains(':')) + { + Location::UriReference { uri: path } + } else if let Some(rest) = path.strip_prefix("//") { + let (host, tail) = rest + .split_once('/') + .ok_or_else(|| error("UNC path requires a share"))?; + if host.is_empty() || tail.is_empty() { + return Err(error("UNC path requires a server and share")); + } + Location::UriReference { + uri: format!("file://{}/{}", encode(host), encode(tail)), + } + } else if path.starts_with('/') { + Location::UriReference { + uri: format!("file://{}", encode(&path)), + } + } else if path.contains('/') { + Location::UriReference { uri: encode(&path) } + } else { + Location::SearchFileName { file_name: path } + }; + location.validate()?; + Ok(location) +} + +/// Map a directly representable native source to CAD path text. +/// Unsupported URI schemes, queries and fragments produce an explicit error. +pub fn external_source_location_to_cad_path(location: &Location) -> Result { + location.validate()?; + let Location::UriReference { uri } = location else { + let Location::SearchFileName { file_name } = location else { + unreachable!() + }; + return Ok(file_name.clone()); + }; + if uri.contains(['?', '#']) { + return Err(error( + "URI query or fragment cannot identify a whole CAD file", + )); + } + let scheme = uri + .split('/') + .next() + .and_then(|first| first.split_once(':').map(|(s, _)| s)); + let path = if let Some(scheme) = scheme { + if !scheme.eq_ignore_ascii_case("file") { + return Err(error("URI scheme has no qualified DWG/DXF path mapping")); + } + let rest = &uri[scheme.len() + 1..]; + let path = if let Some(rest) = rest.strip_prefix("//") { + let (host, path) = rest + .split_once('/') + .ok_or_else(|| error("file URI requires an absolute path"))?; + if host.contains(['@', ':']) { + return Err(error("file URI authority is not a file server")); + } + if host.is_empty() || host.eq_ignore_ascii_case("localhost") { + format!("/{path}") + } else { + format!("//{host}/{path}") + } + } else { + if !rest.starts_with('/') { + return Err(error("file URI requires an absolute path")); + } + rest.into() + }; + let path = decode(&path)?; + if path.as_bytes().get(2) == Some(&b':') && path.starts_with('/') { + path[1..].to_owned() + } else { + path + } + } else { + let path = decode(uri)?; + // Decoded colons/backslashes must not create a drive or UNC path. + if path.contains('\\') || path.split('/').next().is_some_and(|s| s.contains(':')) { + return Err(error( + "relative URI cannot map to a drive or backslash path", + )); + } + if path.starts_with('/') { + return Err(error("absolute native paths require file URI")); + } + if path.contains('/') { + path + } else { + format!("./{path}") + } + }; + if path.is_empty() { + return Err(error("file URI has no filename")); + } + Ok(path) +} + +/// Check that every CAD XREF locator has a qualified whole-file mapping. +/// Native editing can retain unsupported URIs as unresolved references. +pub fn validate_cad_external_sources(document: &crate::Document) -> Result<(), Error> { + for record in document + .block_records + .iter() + .filter(|r| r.flags.is_xref || r.flags.is_xref_overlay) + { + let location = external_source_location_from_cad_path(&record.xref_path)?; + external_source_location_to_cad_path(&location) + .map_err(|e| error(&format!("XREF {}: {e}", record.name)))?; + } + Ok(()) +} + +/// Metadata of an actually opened DWG. This never invents a source UUID. +pub fn dwg_external_source_content( + document: &crate::Document, +) -> ifccad::IfccadExternalSourceContent { + let code = document.header.insertion_units; + ifccad::IfccadExternalSourceContent::Dwg { + base_point: super::array(document.header.model_space_insertion_base), + insertion_unit: usize::try_from(code) + .ok() + .and_then(|i| super::UNITS.get(i)) + .map(|v| (*v).to_owned()), + fingerprint_guid: ifccad::normalize_ifccad_fingerprint_guid( + &document.header.fingerprint_guid, + ), + } +} + +/// Expected XREF identity from the physical feature/filename key, independently +/// of the main drawing header and of the source's last-loaded session identity. +pub fn dwg_xref_fingerprint_guid( + document: &crate::Document, + record: &acadrust::tables::BlockRecord, +) -> Result, Error> { + let mut candidates = document.file_dependencies.iter().filter(|d| { + d.feature.eq_ignore_ascii_case("Acad:XRef") + && d.file_name + .replace('\\', "/") + .eq_ignore_ascii_case(&record.xref_path.replace('\\', "/")) + }); + let dependency = candidates.next(); + if candidates.next().is_some() { + return Err(format!("ambiguous FileDepList identity for XREF {}", record.name).into()); + } + Ok(dependency + .and_then(|d| d.fingerprint_guid.as_deref()) + .and_then(ifccad::normalize_ifccad_fingerprint_guid)) +} diff --git a/src/ifcx/mline_pilot/retention.rs b/src/ifcx/mline_pilot/retention.rs index c52f09d..806559d 100644 --- a/src/ifcx/mline_pilot/retention.rs +++ b/src/ifcx/mline_pilot/retention.rs @@ -16,6 +16,8 @@ use std::collections::{BTreeMap, HashMap}; /// CAD handles inside it refer to that session and are rebuilt on reopen. #[derive(Clone, Debug)] pub struct IfccadRoundtripContext { + external_source_history: HashMap<(Handle, String), ifccad::IfccadExternalSource>, + external_sources: HashMap, header_id: String, drawing_id: u64, counters: IfccadIdCounters, @@ -149,6 +151,8 @@ fn exported_pattern(writer: &Writer<'_>, handle: Handle) -> Option Self { Self { + external_source_history: HashMap::new(), + external_sources: HashMap::new(), header_id: drawing.header.id.clone(), drawing_id: drawing.drawing_id, counters: drawing.id_counters, @@ -164,6 +168,76 @@ impl IfccadRoundtripContext { } } + /// Native source metadata for this CAD block, independent of resolved bytes. + pub fn external_source(&self, handle: Handle) -> Option<&ifccad::IfccadExternalSource> { + self.external_sources.get(&handle) + } + + /// Recover the authored source for a live CAD locator, including earlier + /// locator spellings retained for undo after a native save. + pub fn external_source_for_path( + &self, + handle: Handle, + path: &str, + ) -> Result, Error> { + if let Some(source) = self.external_source_history.get(&(handle, path.to_owned())) { + return Ok(Some(source.clone())); + } + let Some(mut source) = self.external_sources.get(&handle).cloned() else { + return Ok(None); + }; + source.location = crate::external_source_location_from_cad_path(path)?; + Ok(Some(source)) + } + + /// Register an explicitly attached source. Deleting/undoing its CAD block + /// does not lower allocation history; redo reuses the same source identity. + pub fn register_external_source( + &mut self, + handle: Handle, + name: String, + cad_path: String, + content: ifccad::IfccadExternalSourceContent, + ) -> Result { + let existing = self.external_sources.get(&handle).map(|s| s.id); + let id = existing.unwrap_or(ifccad::IfccadExternalSourceId( + self.counters.next_external_source_id, + )); + let source = ifccad::IfccadExternalSource { + id, + name, + location: crate::external_source_location_from_cad_path(&cad_path)?, + source: content, + }; + source.validate()?; + if existing.is_none() { + self.counters.allocate_external_source_id()?; + } + self.external_source_history + .insert((handle, cad_path), source.clone()); + self.external_sources.insert(handle, source); + Ok(id) + } + + pub(in crate::ifcx) fn remember_external_sources( + &mut self, + drawing: &IfccadDocument, + document: &Document, + names: &Names, + ) { + for source in &drawing.external_sources { + if let Some(record) = names + .external_sources + .get(&source.id) + .and_then(|name| document.block_records.get(name)) + { + self.external_source_history + .insert((record.handle, record.xref_path.clone()), source.clone()); + self.external_sources.insert(record.handle, source.clone()); + } + } + } + /// IFCCAD identities and diagnostic reasons for live roots without CAD geometry. pub fn blocked_entities(&self) -> impl Iterator { self.blocked @@ -306,6 +380,9 @@ impl IfccadRoundtripContext { pub(in crate::ifcx) fn remember_export(&mut self, saved: SavedIdentities) { self.counters = saved.counters; + self.external_sources.extend(saved.external_sources); + self.external_source_history + .extend(saved.external_source_history); self.entities.extend(saved.entities); self.layers.extend(saved.layers); self.layouts.extend(saved.layouts); @@ -393,6 +470,8 @@ impl IfccadRoundtripContext { } pub(in crate::ifcx) struct SavedIdentities { + external_source_history: HashMap<(Handle, String), ifccad::IfccadExternalSource>, + external_sources: HashMap, counters: IfccadIdCounters, entities: HashMap, layers: HashMap, @@ -440,6 +519,35 @@ impl SavedIdentities { }) .collect(); Self { + external_source_history: writer + .external_sources + .iter() + .filter_map(|(&h, id)| { + let source = writer + .drawing + .external_sources + .iter() + .find(|s| s.id == *id)?; + let record = writer + .document + .block_records + .iter() + .find(|b| b.handle == h)?; + Some(((h, record.xref_path.clone()), source.clone())) + }) + .collect(), + external_sources: writer + .external_sources + .iter() + .filter_map(|(&h, id)| { + writer + .drawing + .external_sources + .iter() + .find(|s| s.id == *id) + .map(|s| (h, s.clone())) + }) + .collect(), counters: writer.drawing.id_counters, entities, layers, diff --git a/src/ifcx/mod.rs b/src/ifcx/mod.rs index 2e22e3c..7971e4f 100644 --- a/src/ifcx/mod.rs +++ b/src/ifcx/mod.rs @@ -45,6 +45,12 @@ mod attributes; mod dimension; mod dimension_graphics; mod dimension_kinds; +mod external_sources; +mod xref; +pub use external_sources::{ + dwg_external_source_content, dwg_xref_fingerprint_guid, external_source_location_from_cad_path, + external_source_location_to_cad_path, validate_cad_external_sources, +}; mod font; mod hatch; mod layout; @@ -77,7 +83,7 @@ const TEMPLATE: &str = r#"{ "author": "OpenCAD", "timestamp": "1970-01-01T00:00:00Z" }, - "imports": [{ "uri": "urn:example:ifccad:0.11.0" }], + "imports": [{ "uri": "urn:example:ifccad:0.12.0" }], "schemas": {}, "data": [ { @@ -96,7 +102,7 @@ const TEMPLATE: &str = r#"{ "nextLayoutId": 2, "nextLinePatternId": 1, "nextSymbolSourceId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextUcsId": 1, "nextModelWindowId": 1 } @@ -253,7 +259,7 @@ impl Ifcx { fn import_ifccad_inner( &self, drawing: &IfccadDocument, - #[cfg(feature = "mline-pilot")] context: Option<&mut IfccadRoundtripContext>, + #[cfg(feature = "mline-pilot")] mut context: Option<&mut IfccadRoundtripContext>, ) -> Result { ifccad::validate_ifccad_document(drawing)?; #[cfg(feature = "mline-pilot")] @@ -290,6 +296,11 @@ impl Ifcx { } let mut names = Names::default(); + xref::sources_in(drawing, &mut document, &mut names, &mut losses)?; + #[cfg(feature = "mline-pilot")] + if let Some(context) = context.as_deref_mut() { + context.remember_external_sources(drawing, &document, &names); + } annotation::read_scales(drawing, &mut document, &mut names); annotation_views::import(drawing, &mut document, &mut names)?; tables::read(drawing, &mut document, &mut names, &mut losses)?; @@ -532,6 +543,7 @@ impl Ifcx { _ => return Err(annotation::invalid("invalid ATTMODE")), }; let mut writer = Writer { + external_sources: HashMap::new(), #[cfg(feature = "mline-pilot")] roundtrip: context.as_deref(), table_data_links: HashMap::new(), @@ -624,6 +636,7 @@ impl Ifcx { context.emit(&mut writer)?; } plot_styles::assignments_out(&mut writer); + xref::diagnose_dependency_losses(&mut writer); ifccad::validate_ifccad_document(&writer.drawing)?; #[cfg(feature = "mline-pilot")] let saved = context @@ -680,6 +693,7 @@ fn link_hatches( /// Names of what IFCX refers to by id. #[derive(Default)] struct Names { + external_sources: HashMap, table_data_links: HashMap, table_styles: HashMap, multi_leader_styles: HashMap, @@ -717,6 +731,7 @@ fn add_in( return Ok(None); }; let converted = match &entity.kind { + IfccadEntityKind::Xref(source) => xref::insert_in(source, names), IfccadEntityKind::Dimension(source) => { dimension::dimension_in(source, document, names, losses) } @@ -808,6 +823,7 @@ fn add_in( } struct Writer<'a> { + external_sources: HashMap, #[cfg(feature = "mline-pilot")] roundtrip: Option<&'a IfccadRoundtripContext>, table_data_links: HashMap, @@ -954,7 +970,23 @@ impl Writer<'_> { let common = entity.common(); let layer_id = match self.layers.get(&common.layer.to_ascii_lowercase()) { Some(id) => *id, - None => self.layers.get("0").copied().unwrap_or(0), + None => { + if self + .document + .layers + .get(&common.layer) + .is_some_and(|layer| layer.flags.xref_dependent) + { + self.losses.located_loss( + common.handle, + format!( + "local entity uses external dependent layer {}", + common.layer + ), + ); + } + self.layers.get("0").copied().unwrap_or(0) + } }; let id = self.entity_id(common.handle)?; if let EntityType::Hatch(hatch) = entity { @@ -987,6 +1019,11 @@ impl Writer<'_> { let Some(record) = document.block_records.get(name) else { return Ok(None); }; + if record.flags.is_xref || record.flags.is_xref_overlay { + self.external_source(record)?; + self.blocks.insert(key, None); + return Ok(None); + } if record.is_layout() || record.is_model_space() || record.is_paper_space() @@ -1342,6 +1379,11 @@ impl Writer<'_> { return Ok(dimension::dimension_out(self, dimension)) } EntityType::Insert(insert) => { + if let Some(record) = self.document.block_records.get(&insert.block_name) { + if record.flags.is_xref || record.flags.is_xref_overlay { + return self.xref_kind(insert, record); + } + } if insert.is_array() { return Ok(None); } @@ -1433,6 +1475,7 @@ impl Losses { fn entity_in(kind: &IfccadEntityKind, names: &Names, losses: &mut Losses) -> Option { Some(match kind { + IfccadEntityKind::Xref(source) => return xref::insert_in(source, names), IfccadEntityKind::AttributeDefinition(a) => { return attributes::definition_in(a, names, losses) } @@ -1962,6 +2005,7 @@ fn array(v: Vector3) -> [f64; 3] { fn kind_name(kind: &IfccadEntityKind) -> &'static str { match kind { + IfccadEntityKind::Xref(_) => "XREF", IfccadEntityKind::Solid(_) => "Solid", IfccadEntityKind::Trace(_) => "Trace", IfccadEntityKind::Table(_) => "Table", diff --git a/src/ifcx/tables.rs b/src/ifcx/tables.rs index ec3ab21..4d65340 100644 --- a/src/ifcx/tables.rs +++ b/src/ifcx/tables.rs @@ -224,7 +224,7 @@ pub(super) fn write(writer: &mut Writer) -> Result<(), Error> { for style in document .text_styles .iter() - .filter(|style| style.is_shape_file) + .filter(|style| style.is_shape_file && !style.xref_dependent) { let file_name = ifccad::line_pattern::shx_file_name_from_cad_request(&style.font_file) .map_err(|error| format!("invalid SHX STYLE {:?}: {error}", style.handle))?; @@ -241,7 +241,7 @@ pub(super) fn write(writer: &mut Writer) -> Result<(), Error> { } for style in document.text_styles.iter() { - if style.is_shape_file || style.name.is_empty() { + if style.is_shape_file || style.name.is_empty() || style.xref_dependent { continue; } let font = font::font_from_cad_style( @@ -281,6 +281,9 @@ pub(super) fn write(writer: &mut Writer) -> Result<(), Error> { // The template's continuous pattern (id 0) stands for the document's. for linetype in document.line_types.iter() { + if linetype.xref_dependent { + continue; + } let key = linetype.name.to_ascii_lowercase(); if key == "bylayer" || key == "byblock" { continue; @@ -377,6 +380,9 @@ pub(super) fn write(writer: &mut Writer) -> Result<(), Error> { } for layer in document.layers.iter() { + if layer.flags.xref_dependent { + continue; + } let line_pattern = match writer .line_patterns .get(&layer.line_type.to_ascii_lowercase()) diff --git a/src/ifcx/xref.rs b/src/ifcx/xref.rs new file mode 100644 index 0000000..dbb7dc2 --- /dev/null +++ b/src/ifcx/xref.rs @@ -0,0 +1,300 @@ +//! XREF definitions remain external even when the CAD host has resolved bodies. +use super::*; +use ifccad::{ + IfccadExternalSource, IfccadExternalSourceContent, IfccadExternalSourceId, IfccadXref, +}; + +pub(super) fn diagnose_dependency_losses(writer: &mut Writer<'_>) { + for dependency in &writer.document.file_dependencies { + let binding = writer.document.block_records.iter().find(|record| { + if !writer.external_sources.contains_key(&record.handle) + || !dependency.feature.eq_ignore_ascii_case("Acad:XRef") + { + return false; + } + let matches = dependency + .file_name + .replace('\\', "/") + .eq_ignore_ascii_case(&record.xref_path.replace('\\', "/")); + #[cfg(feature = "mline-pilot")] + let matches = matches + || writer + .roundtrip + .and_then(|context| context.external_source(record.handle)) + .is_some_and(|source| { + external_sources::external_source_location_to_cad_path(&source.location) + .is_ok_and(|path| { + dependency + .file_name + .replace('\\', "/") + .eq_ignore_ascii_case(&path.replace('\\', "/")) + }) + }); + matches + }); + let Some(binding) = binding else { + writer.losses.note(format!( + "unbound FileDepList record {}: {}", + dependency.feature, dependency.file_name + )); + continue; + }; + let source_id = writer.external_sources[&binding.handle]; + let expected = writer + .drawing + .external_sources + .iter() + .find(|source| source.id == source_id) + .and_then(|source| { + let IfccadExternalSourceContent::Dwg { + fingerprint_guid, .. + } = &source.source; + fingerprint_guid.as_deref() + }); + if dependency + .fingerprint_guid + .as_deref() + .and_then(ifccad::normalize_ifccad_fingerprint_guid) + .as_deref() + != expected + { + writer.losses.note(format!( + "FileDepList identity differs from retained native source {}", + dependency.file_name + )); + } + let references = writer + .drawing + .model + .entities + .iter() + .filter_map(IfccadEntity::as_native) + .filter(|e| matches!(&e.kind, IfccadEntityKind::Xref(x) if x.source_id == source_id)) + .count(); + if dependency + .fingerprint_guid + .as_deref() + .is_some_and(|g| ifccad::normalize_ifccad_fingerprint_guid(g).is_none()) + { + writer.losses.note(format!( + "invalid FileDepList FingerprintGUID for {}", + dependency.file_name + )); + } + if !dependency.found_path.is_empty() + || dependency.version_guid.is_some() + || dependency.timestamp != 0 + || dependency.file_size != 0 + || !dependency.affects_graphics + || dependency.reference_count as usize != references + { + writer.losses.note(format!( + "FileDepList metadata beyond native source identity for {}", + dependency.file_name + )); + } + } +} + +pub(super) fn sources_in( + drawing: &IfccadDocument, + document: &mut Document, + names: &mut Names, + losses: &mut Losses, +) -> Result<(), Error> { + for source in &drawing.external_sources { + if document.block_records.get(&source.name).is_some() + || drawing + .blocks + .iter() + .any(|b| b.name.eq_ignore_ascii_case(&source.name)) + { + losses.note(format!( + "XREF source {} conflicts with a CAD block name", + source.name + )); + continue; + } + let path = match external_sources::external_source_location_to_cad_path(&source.location) { + Ok(path) => path, + Err(error) => { + // Keep an unresolved editing representation. CAD file export + // separately diagnoses this unqualified locator. + losses.retained.push(Loss { + handle: None, + message: format!( + "XREF location retained unresolved; CAD export unavailable: {error}" + ), + }); + match &source.location { + ifccad::IfccadExternalSourceLocation::UriReference { uri } => uri.clone(), + _ => return Err(error), + } + } + }; + let IfccadExternalSourceContent::Dwg { + base_point, + insertion_unit, + fingerprint_guid, + } = &source.source; + let mut record = BlockRecord::new(source.name.clone()); + record.handle = document.allocate_handle(); + record.block_entity_handle = document.allocate_handle(); + record.block_end_handle = document.allocate_handle(); + record.flags.is_xref = true; + record.xref_path = path.clone(); + record.base_point = vector(*base_point); + record.units = insertion_unit.as_deref().map(unit_code).unwrap_or(0); + let mut block = Block::new(record.name.clone(), record.base_point); + block.common.handle = record.block_entity_handle; + block.common.owner_handle = record.handle; + let mut end = BlockEnd::new(); + end.common.handle = record.block_end_handle; + end.common.owner_handle = record.handle; + names + .external_sources + .insert(source.id, source.name.clone()); + document.block_records.add(record)?; + document.add_entity(EntityType::Block(block))?; + document.add_entity(EntityType::BlockEnd(end))?; + if let Some(guid) = fingerprint_guid { + document + .file_dependencies + .push(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: drawing + .model + .entities + .iter() + .filter_map(IfccadEntity::as_native) + .filter( + |e| matches!(&e.kind,IfccadEntityKind::Xref(x) if x.source_id==source.id), + ) + .count() + .try_into()?, + }); + } + } + Ok(()) +} + +pub(super) fn insert_in(xref: &IfccadXref, names: &Names) -> Option { + let name = names.external_sources.get(&xref.source_id)?; + let (origin, normal, rotation) = placement_in(&xref.placement); + let mut insert = Insert::new(name.clone(), origin); + insert.normal = normal; + insert.rotation = rotation; + insert.set_x_scale(xref.scale); + insert.set_y_scale(xref.scale); + insert.set_z_scale(xref.scale); + (insert.x_scale().to_bits() == xref.scale.to_bits()).then_some(EntityType::Insert(insert)) +} + +impl Writer<'_> { + pub(super) fn external_source( + &mut self, + record: &BlockRecord, + ) -> Result, Error> { + if record.flags.is_xref_overlay { + self.losses.note(format!( + "XREF {} overlay is outside the Model attachment slice", + record.name + )); + return Ok(None); + } + if let Some(id) = self.external_sources.get(&record.handle) { + return Ok(Some(*id)); + } + #[cfg(feature = "mline-pilot")] + let retained = self + .roundtrip + .map(|c| c.external_source_for_path(record.handle, &record.xref_path)) + .transpose()? + .flatten(); + #[cfg(not(feature = "mline-pilot"))] + let retained: Option = None; + let source = if let Some(mut source) = retained { + source.name = record.name.clone(); + source + } else { + if record.xref_path.to_ascii_lowercase().ends_with(".dxf") { + self.losses.note(format!( + "XREF {} uses a DXF source outside the first DWG attachment slice", + record.name + )); + return Ok(None); + } + let location = + match external_sources::external_source_location_from_cad_path(&record.xref_path) { + Ok(v) => v, + Err(e) => { + self.losses + .note(format!("XREF {} location: {e}", record.name)); + return Ok(None); + } + }; + let fingerprint_guid = + external_sources::dwg_xref_fingerprint_guid(self.document, record)?; + IfccadExternalSource { + id: self.drawing.id_counters.allocate_external_source_id()?, + name: record.name.clone(), + location, + source: IfccadExternalSourceContent::Dwg { + base_point: array(record.base_point), + insertion_unit: (record.units != 0).then(|| unit_name(record.units)), + fingerprint_guid, + }, + } + }; + let id = source.id; + self.drawing.external_sources.push(source); + self.external_sources.insert(record.handle, id); + Ok(Some(id)) + } + + pub(super) fn xref_kind( + &mut self, + insert: &Insert, + record: &BlockRecord, + ) -> Result, Error> { + let owner = insert.common.owner_handle; + let model = owner.is_null() + || self + .document + .block_records + .iter() + .any(|b| b.handle == owner && b.is_model_space()); + let scales = [insert.x_scale(), insert.y_scale(), insert.z_scale()]; + let placement = placement_out(insert.insert_point, insert.normal, insert.rotation); + if !model + || insert.row_count != 1 + || insert.column_count != 1 + || !insert.attributes.is_empty() + || !scales[0].is_finite() + || scales[0] <= 0. + || scales.iter().any(|s| *s != scales[0]) + || placement.x_axis[2].abs() > 1e-12 + || placement.y_axis[2].abs() > 1e-12 + || placement.x_axis[0] * placement.y_axis[1] - placement.x_axis[1] * placement.y_axis[0] + <= 0. + { + self.losses.note(format!("XREF {} requires Model ownership, one attachment, no attributes, Z rotation and positive uniform scale",record.name)); + return Ok(None); + } + let Some(source_id) = self.external_source(record)? else { + return Ok(None); + }; + Ok(Some(IfccadEntityKind::Xref(IfccadXref { + source_id, + placement, + scale: scales[0], + }))) + } +} diff --git a/src/lib.rs b/src/lib.rs index 66811ef..4485563 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -126,3 +126,12 @@ impl From for ReadOutcome { } } } + +#[cfg(feature = "ifcx")] +pub use ifcx::dwg_external_source_content; +#[cfg(feature = "ifcx")] +pub use ifcx::dwg_xref_fingerprint_guid; +#[cfg(feature = "ifcx")] +pub use ifcx::validate_cad_external_sources; +#[cfg(feature = "ifcx")] +pub use ifcx::{external_source_location_from_cad_path, external_source_location_to_cad_path}; diff --git a/tests/fixtures/annotation-blocks.ifcx b/tests/fixtures/annotation-blocks.ifcx index 9df9ef3..9ecf127 100644 --- a/tests/fixtures/annotation-blocks.ifcx +++ b/tests/fixtures/annotation-blocks.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -33,7 +33,7 @@ "nextLayoutId": 2, "nextLinePatternId": 1, "nextSymbolSourceId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextUcsId": 1, "nextModelWindowId": 1, "nextAnnotationScaleId": 1 diff --git a/tests/fixtures/annotation-hatch.ifcx b/tests/fixtures/annotation-hatch.ifcx index a2be73e..0326006 100644 --- a/tests/fixtures/annotation-hatch.ifcx +++ b/tests/fixtures/annotation-hatch.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -35,7 +35,7 @@ "nextSymbolSourceId": 1, "nextModelWindowId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextAnnotationScaleId": 2 } } diff --git a/tests/fixtures/annotation-workspace.ifcx b/tests/fixtures/annotation-workspace.ifcx index 4f33562..0e99fb3 100644 --- a/tests/fixtures/annotation-workspace.ifcx +++ b/tests/fixtures/annotation-workspace.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -39,7 +39,7 @@ "nextSymbolSourceId": 1, "nextModelWindowId": 9007199254740994, "nextUcsId": 9007199254740994, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextAnnotationScaleId": 1 }, "ifccad::drawingWorkspace": { diff --git a/tests/fixtures/complex-line-patterns.ifcx b/tests/fixtures/complex-line-patterns.ifcx index 56b966c..8b2fffd 100644 --- a/tests/fixtures/complex-line-patterns.ifcx +++ b/tests/fixtures/complex-line-patterns.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -44,7 +44,7 @@ "nextSymbolSourceId": 4, "nextTextStyleId": 2, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextAnnotationScaleId": 1 } } diff --git a/tests/fixtures/dimension-fraction-diagonal.ifcx b/tests/fixtures/dimension-fraction-diagonal.ifcx index c9545cc..51885a1 100644 --- a/tests/fixtures/dimension-fraction-diagonal.ifcx +++ b/tests/fixtures/dimension-fraction-diagonal.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -37,7 +37,7 @@ "nextModelWindowId": 1, "nextTextStyleId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextSymbolSourceId": 1, "nextAnnotationScaleId": 1 } diff --git a/tests/fixtures/dimension-graphics.ifcx b/tests/fixtures/dimension-graphics.ifcx index a0a23b3..c13f037 100644 --- a/tests/fixtures/dimension-graphics.ifcx +++ b/tests/fixtures/dimension-graphics.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -37,7 +37,7 @@ "nextModelWindowId": 1, "nextTextStyleId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextSymbolSourceId": 1, "nextAnnotationScaleId": 1 } diff --git a/tests/fixtures/dimension-linear-aligned.ifcx b/tests/fixtures/dimension-linear-aligned.ifcx index da28c38..7224f04 100644 --- a/tests/fixtures/dimension-linear-aligned.ifcx +++ b/tests/fixtures/dimension-linear-aligned.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -37,7 +37,7 @@ "nextModelWindowId": 1, "nextTextStyleId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextSymbolSourceId": 1, "nextAnnotationScaleId": 1 } diff --git a/tests/fixtures/dimension-spatial-references.ifcx b/tests/fixtures/dimension-spatial-references.ifcx index c1c09f8..d885f96 100644 --- a/tests/fixtures/dimension-spatial-references.ifcx +++ b/tests/fixtures/dimension-spatial-references.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -37,7 +37,7 @@ "nextModelWindowId": 1, "nextTextStyleId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextSymbolSourceId": 1, "nextAnnotationScaleId": 1 } diff --git a/tests/fixtures/font-symbol-base.ifcx b/tests/fixtures/font-symbol-base.ifcx index ee31f75..47100df 100644 --- a/tests/fixtures/font-symbol-base.ifcx +++ b/tests/fixtures/font-symbol-base.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -32,7 +32,7 @@ "nextLayoutId": 2, "nextLinePatternId": 1, "nextSymbolSourceId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextUcsId": 1, "nextModelWindowId": 1, "nextAnnotationScaleId": 1 diff --git a/tests/fixtures/hatch-associations-disabled.ifcx b/tests/fixtures/hatch-associations-disabled.ifcx index b3e56db..62e687a 100644 --- a/tests/fixtures/hatch-associations-disabled.ifcx +++ b/tests/fixtures/hatch-associations-disabled.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -34,7 +34,7 @@ "nextSymbolSourceId": 1, "nextModelWindowId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextAnnotationScaleId": 1 } } diff --git a/tests/fixtures/hatch-editing.ifcx b/tests/fixtures/hatch-editing.ifcx index 07a345d..8375a7d 100644 --- a/tests/fixtures/hatch-editing.ifcx +++ b/tests/fixtures/hatch-editing.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -34,7 +34,7 @@ "nextSymbolSourceId": 1, "nextModelWindowId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextAnnotationScaleId": 1 } } diff --git a/tests/fixtures/hatch-gradient-inactive.ifcx b/tests/fixtures/hatch-gradient-inactive.ifcx index 0519587..4cad5bf 100644 --- a/tests/fixtures/hatch-gradient-inactive.ifcx +++ b/tests/fixtures/hatch-gradient-inactive.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -33,7 +33,7 @@ "nextLinePatternId": 1, "nextModelWindowId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextSymbolSourceId": 1, "nextAnnotationScaleId": 1 } diff --git a/tests/fixtures/hatch-gradient.ifcx b/tests/fixtures/hatch-gradient.ifcx index 686038a..3355e70 100644 --- a/tests/fixtures/hatch-gradient.ifcx +++ b/tests/fixtures/hatch-gradient.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -33,7 +33,7 @@ "nextLinePatternId": 1, "nextModelWindowId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextSymbolSourceId": 1, "nextAnnotationScaleId": 1 } diff --git a/tests/fixtures/hatch-pattern.ifcx b/tests/fixtures/hatch-pattern.ifcx index 3fb1099..770530d 100644 --- a/tests/fixtures/hatch-pattern.ifcx +++ b/tests/fixtures/hatch-pattern.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -34,7 +34,7 @@ "nextSymbolSourceId": 1, "nextModelWindowId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextAnnotationScaleId": 1 } } diff --git a/tests/fixtures/hello-cad.ifcx b/tests/fixtures/hello-cad.ifcx index ee31f75..47100df 100644 --- a/tests/fixtures/hello-cad.ifcx +++ b/tests/fixtures/hello-cad.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -32,7 +32,7 @@ "nextLayoutId": 2, "nextLinePatternId": 1, "nextSymbolSourceId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextUcsId": 1, "nextModelWindowId": 1, "nextAnnotationScaleId": 1 diff --git a/tests/fixtures/hello-nested-blocks.ifcx b/tests/fixtures/hello-nested-blocks.ifcx index 9df9ef3..9ecf127 100644 --- a/tests/fixtures/hello-nested-blocks.ifcx +++ b/tests/fixtures/hello-nested-blocks.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -33,7 +33,7 @@ "nextLayoutId": 2, "nextLinePatternId": 1, "nextSymbolSourceId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextUcsId": 1, "nextModelWindowId": 1, "nextAnnotationScaleId": 1 diff --git a/tests/fixtures/hello-paper-layouts.ifcx b/tests/fixtures/hello-paper-layouts.ifcx index 5a500f3..47accef 100644 --- a/tests/fixtures/hello-paper-layouts.ifcx +++ b/tests/fixtures/hello-paper-layouts.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -35,7 +35,7 @@ "nextLayoutId": 4, "nextLinePatternId": 1, "nextSymbolSourceId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextUcsId": 1, "nextModelWindowId": 1, "nextAnnotationScaleId": 1 diff --git a/tests/fixtures/hello-viewports.ifcx b/tests/fixtures/hello-viewports.ifcx index 077c4c5..eb00b60 100644 --- a/tests/fixtures/hello-viewports.ifcx +++ b/tests/fixtures/hello-viewports.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -32,7 +32,7 @@ "nextLayoutId": 3, "nextLinePatternId": 1, "nextSymbolSourceId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextUcsId": 1, "nextModelWindowId": 1, "nextAnnotationScaleId": 1 diff --git a/tests/fixtures/layout-linetype-scaling.ifcx b/tests/fixtures/layout-linetype-scaling.ifcx index 99764dd..97de9db 100644 --- a/tests/fixtures/layout-linetype-scaling.ifcx +++ b/tests/fixtures/layout-linetype-scaling.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -27,7 +27,7 @@ "attributes": { "ifccad::drawing": { "lengthUnit": "cm", - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextEntityId": 101, "nextLayerId": 3, "nextLayoutId": 3, diff --git a/tests/fixtures/layout-plot-inch.ifcx b/tests/fixtures/layout-plot-inch.ifcx index 3575374..0c41b88 100644 --- a/tests/fixtures/layout-plot-inch.ifcx +++ b/tests/fixtures/layout-plot-inch.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -27,7 +27,7 @@ "attributes": { "ifccad::drawing": { "lengthUnit": "cm", - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextEntityId": 101, "nextLayerId": 3, "nextLayoutId": 3, diff --git a/tests/fixtures/layouts-viewports.ifcx b/tests/fixtures/layouts-viewports.ifcx index 0abeac3..0efa990 100644 --- a/tests/fixtures/layouts-viewports.ifcx +++ b/tests/fixtures/layouts-viewports.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -38,7 +38,7 @@ "nextSymbolSourceId": 1, "nextModelWindowId": 1, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextAnnotationScaleId": 1 } } diff --git a/tests/fixtures/text-rich.ifcx b/tests/fixtures/text-rich.ifcx index fe4c070..7e6e28c 100644 --- a/tests/fixtures/text-rich.ifcx +++ b/tests/fixtures/text-rich.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -36,7 +36,7 @@ "nextModelWindowId": 1, "nextTextStyleId": 2, "nextUcsId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextAnnotationScaleId": 1 } } diff --git a/tests/fixtures/viewport-bulged-clip.ifcx b/tests/fixtures/viewport-bulged-clip.ifcx index b4314c4..5059e3e 100644 --- a/tests/fixtures/viewport-bulged-clip.ifcx +++ b/tests/fixtures/viewport-bulged-clip.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -32,7 +32,7 @@ "nextLayoutId": 43, "nextLinePatternId": 1, "nextSymbolSourceId": 1, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextUcsId": 1, "nextModelWindowId": 1, "nextAnnotationScaleId": 1 diff --git a/tests/fixtures/workspace-state.ifcx b/tests/fixtures/workspace-state.ifcx index aecf780..74cead9 100644 --- a/tests/fixtures/workspace-state.ifcx +++ b/tests/fixtures/workspace-state.ifcx @@ -8,7 +8,7 @@ }, "imports": [ { - "uri": "urn:example:ifccad:0.11.0" + "uri": "urn:example:ifccad:0.12.0" } ], "schemas": {}, @@ -39,7 +39,7 @@ "nextSymbolSourceId": 1, "nextModelWindowId": 9007199254740994, "nextUcsId": 9007199254740994, - "profileVersion": "0.11.0", + "profileVersion": "0.12.0", "nextAnnotationScaleId": 1 }, "ifccad::drawingWorkspace": { diff --git a/tests/fixtures/xref/attachment.ifcx b/tests/fixtures/xref/attachment.ifcx new file mode 100644 index 0000000..ef335de --- /dev/null +++ b/tests/fixtures/xref/attachment.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/tests/ifcx_external_source_locations.rs b/tests/ifcx_external_source_locations.rs new file mode 100644 index 0000000..159449c --- /dev/null +++ b/tests/ifcx_external_source_locations.rs @@ -0,0 +1,63 @@ +#![cfg(feature = "ifcx")] +use opencaddocument::ifccad::IfccadExternalSourceLocation as Location; +use opencaddocument::{ + external_source_location_from_cad_path as from_cad, + external_source_location_to_cad_path as to_cad, +}; + +#[test] +fn paths_keep_direct_and_search_meaning_and_decode_only_once() { + for (cad, uri) in [ + (r"..\Refs\grond plan.dwg", "../Refs/grond%20plan.dwg"), + (r"C:\CAD\grondplan.dwg", "file:///C:/CAD/grondplan.dwg"), + ( + r"\\server\share\grondplan.dwg", + "file://server/share/grondplan.dwg", + ), + ("./grondplan.dwg", "./grondplan.dwg"), + ("../Refs/a%20#é.dwg", "../Refs/a%2520%23%C3%A9.dwg"), + ] { + let expected = Location::UriReference { uri: uri.into() }; + assert_eq!(from_cad(cad).unwrap(), expected); + assert_eq!(from_cad(&to_cad(&expected).unwrap()).unwrap(), expected); + } + assert_eq!( + from_cad("grondplan.dwg").unwrap(), + Location::SearchFileName { + file_name: "grondplan.dwg".into() + } + ); + assert_eq!( + to_cad(&Location::UriReference { + uri: "grondplan.dwg".into() + }) + .unwrap(), + "./grondplan.dwg" + ); + assert_eq!( + to_cad(&Location::UriReference { + uri: "../a%2520.dwg".into() + }) + .unwrap(), + "../a%20.dwg" + ); +} + +#[test] +fn valid_native_uris_without_cad_equivalent_have_explicit_errors() { + for uri in [ + "https://example.org/a.dwg", + "urn:uuid:e5b4a9af-cf20-4fc9-a30f-ffb20fd987e1", + "a.dwg?version=2", + "a.dwg#part", + "file:///a%00.dwg", + ] { + assert!( + to_cad(&Location::UriReference { uri: uri.into() }).is_err(), + "{uri}" + ); + } + for path in ["", "C:relative.dwg", "bad\0.dwg"] { + assert!(from_cad(path).is_err()); + } +} diff --git a/tests/ifcx_xrefs.rs b/tests/ifcx_xrefs.rs new file mode 100644 index 0000000..e4c0768 --- /dev/null +++ b/tests/ifcx_xrefs.rs @@ -0,0 +1,265 @@ +#![cfg(all(feature = "ifcx", feature = "mline-pilot"))] +use opencaddocument::{ifccad::*, *}; + +fn drawing() -> IfccadDocument { + load_ifccad_bytes( + include_bytes!("fixtures/xref/attachment.ifcx"), + Default::default(), + ) + .unwrap() + .into_document() +} + +#[test] +fn offline_xref_roundtrip_keeps_source_and_effective_placement() { + let d = drawing(); + let (imported, mut context) = Ifcx.import_ifccad_preserving(&d).unwrap(); + assert!(imported.losses.is_empty(), "{:?}", imported.losses); + let source = imported + .document + .block_records + .get("grondplan") + .expect("XREF definition"); + assert!(source.flags.is_xref); + assert_eq!(source.base_point, Vector3::new(10., 20., 0.)); + assert_eq!(source.xref_path, "../Referenties/grondplan.dwg"); + let x = imported + .document + .model_space_entities() + .find_map(|e| match e { + EntityType::Insert(i) => Some(i), + _ => None, + }) + .unwrap(); + assert_eq!(x.insert_point, Vector3::new(10000., 5000., 0.)); + assert_eq!([x.x_scale(), x.y_scale(), x.z_scale()], [500.; 3]); + let saved = Ifcx + .export_ifccad_preserving(&imported.document, &mut context) + .unwrap(); + assert_eq!(saved.drawing.external_sources, d.external_sources); + assert_eq!( + saved.drawing.model.entities[0].id(), + d.model.entities[0].id() + ); + let IfccadEntityKind::Xref(saved) = &saved.drawing.model.entities[0].as_native().unwrap().kind + else { + panic!() + }; + assert_eq!(saved.scale, 500.); + for (format, keep_guid) in [(&Dwg as &dyn Format, true), (&Dxf as &dyn Format, false)] { + let (bytes, losses) = format.write(&imported.document).unwrap(); + assert!(losses.is_empty(), "{losses:?}"); + let (cad, _) = format.read(&bytes).unwrap(); + let back = Ifcx.export_ifccad(&cad).unwrap(); + assert_eq!(back.drawing.external_sources.len(), 1); + let IfccadExternalSourceContent::Dwg { + base_point, + fingerprint_guid, + .. + } = &back.drawing.external_sources[0].source; + assert_eq!(*base_point, [10., 20., 0.]); + assert_eq!(fingerprint_guid.is_some(), keep_guid); + let IfccadEntityKind::Xref(x) = &back.drawing.model.entities[0].as_native().unwrap().kind + else { + panic!() + }; + assert_eq!(x.scale, 500.); + assert!((x.placement.x_axis[1] - 1.).abs() < 1e-12); + validate_ifccad_document(&back.drawing).unwrap(); + } +} + +#[test] +fn loaded_xref_is_never_flattened_into_native_model() { + let d = drawing(); + let (mut imported, mut context) = Ifcx.import_ifccad_preserving(&d).unwrap(); + let handle = imported + .document + .block_records + .get("grondplan") + .unwrap() + .handle; + let mut line = entities::Line::from_coords(10., 20., 0., 12., 20., 0.); + line.common.owner_handle = handle; + let mut generated = tables::Layer::new("grondplan|SOURCE"); + generated.handle = imported.document.allocate_handle(); + generated.flags.xref_dependent = true; + generated.xref_block_record_handle = handle; + imported.document.layers.add(generated).unwrap(); + imported + .document + .add_entity(EntityType::Line(line)) + .unwrap(); + let back = Ifcx + .export_ifccad_preserving(&imported.document, &mut context) + .unwrap(); + assert!(back.drawing.blocks.is_empty()); + assert!(!back.drawing.layers.iter().any(|l| l.name.contains('|'))); + assert_eq!(back.drawing.model.entities.len(), 1); + assert_eq!(back.drawing.external_sources, d.external_sources); + let mut local = entities::Line::from_coords(0., 0., 0., 1., 0., 0.); + local.common.layer = "grondplan|SOURCE".into(); + imported + .document + .add_entity(EntityType::Line(local)) + .unwrap(); + let with_local = Ifcx + .export_ifccad_preserving(&imported.document, &mut context) + .unwrap(); + assert!(with_local + .losses + .iter() + .any(|loss| loss.message.contains("external dependent layer"))); +} + +#[test] +fn source_without_insert_is_retained_and_deletion_does_not_reuse_id() { + let mut d = drawing(); + d.model.entities.clear(); + let (imported, mut context) = Ifcx.import_ifccad_preserving(&d).unwrap(); + let mut back = Ifcx + .export_ifccad_preserving(&imported.document, &mut context) + .unwrap() + .drawing; + assert_eq!(back.external_sources, d.external_sources); + back.external_sources.clear(); + assert_eq!(back.id_counters.allocate_external_source_id().unwrap().0, 2); +} + +#[test] +fn unsupported_cad_attachment_variants_are_explicit_losses() { + for variant in ["overlay", "array", "paper", "block", "dxf-source"] { + let imported = Ifcx.import_ifccad(&drawing()).unwrap(); + let mut cad = imported.document; + let handle = *imported.entity_handles.get(&1000).unwrap(); + if variant == "dxf-source" { + cad.block_records.get_mut("grondplan").unwrap().xref_path = "source.dxf".into(); + } + if variant == "overlay" { + cad.block_records + .get_mut("grondplan") + .unwrap() + .flags + .is_xref_overlay = true; + } + if variant == "array" { + let EntityType::Insert(i) = cad.get_entity_mut(handle).unwrap() else { + panic!() + }; + i.row_count = 2; + } + if variant == "paper" { + let owner = cad + .block_records + .iter() + .find(|b| b.is_paper_space()) + .unwrap() + .handle; + cad.get_entity_mut(handle) + .unwrap() + .common_mut() + .owner_handle = owner; + } + if variant == "block" { + let mut record = tables::BlockRecord::new("LOCAL"); + record.handle = cad.allocate_handle(); + let owner = record.handle; + cad.block_records.add(record).unwrap(); + cad.get_entity_mut(handle) + .unwrap() + .common_mut() + .owner_handle = owner; + } + let out = Ifcx.export_ifccad(&cad).unwrap(); + assert!( + out.losses.iter().any(|l| l.message.contains("XREF")), + "{variant}: {:?}", + out.losses + ); + assert!(!out + .drawing + .model + .entities + .iter() + .filter_map(IfccadEntity::as_native) + .any(|e| matches!(e.kind, IfccadEntityKind::Xref(_)))); + } +} + +#[test] +fn unknown_uri_is_retained_in_editing_but_has_no_silent_cad_export() { + let mut d = drawing(); + d.external_sources[0].location = IfccadExternalSourceLocation::UriReference { + uri: "custom:opaque".into(), + }; + let (imported, mut context) = Ifcx.import_ifccad_preserving(&d).unwrap(); + let back = Ifcx + .export_ifccad_preserving(&imported.document, &mut context) + .unwrap(); + assert_eq!(back.drawing.external_sources, d.external_sources); + assert!(Dwg.write(&imported.document).is_err()); + assert!(Dxf.write(&imported.document).is_err()); +} + +#[test] +fn explicit_path_edit_and_undo_keep_source_id_and_original_uri_spelling() { + let mut d = drawing(); + d.external_sources[0].location = IfccadExternalSourceLocation::UriReference { + uri: "../Referenties/%67rondplan.dwg".into(), + }; + let (mut imported, mut context) = Ifcx.import_ifccad_preserving(&d).unwrap(); + let original = imported + .document + .block_records + .get("grondplan") + .unwrap() + .xref_path + .clone(); + imported + .document + .block_records + .get_mut("grondplan") + .unwrap() + .xref_path = "../Andere/new.dwg".into(); + let outcome = Ifcx + .export_ifccad_preserving(&imported.document, &mut context) + .unwrap(); + assert!(outcome.losses.is_empty(), "{:?}", outcome.losses); + let saved = outcome.drawing; + assert_eq!(saved.external_sources[0].id, d.external_sources[0].id); + assert_eq!( + saved.external_sources[0].location, + IfccadExternalSourceLocation::UriReference { + uri: "../Andere/new.dwg".into() + } + ); + imported + .document + .block_records + .get_mut("grondplan") + .unwrap() + .xref_path = original; + let undone = Ifcx + .export_ifccad_preserving(&imported.document, &mut context) + .unwrap() + .drawing; + assert_eq!(undone.external_sources, d.external_sources); +} + +#[test] +fn physical_dependency_metadata_has_explicit_native_loss_diagnostics() { + let mut cad = Ifcx.import_ifccad(&drawing()).unwrap().document; + cad.file_dependencies[0].version_guid = Some("{11111111-2222-3333-4444-555555555555}".into()); + let out = Ifcx.export_ifccad(&cad).unwrap(); + assert!(out + .losses + .iter() + .any(|l| l.message.contains("FileDepList metadata"))); + cad.file_dependencies[0].version_guid = None; + cad.file_dependencies[0].file_name = "unbound.dwg".into(); + let out = Ifcx.export_ifccad(&cad).unwrap(); + assert!(out + .losses + .iter() + .any(|l| l.message.contains("unbound FileDepList"))); +}