Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 203 additions & 0 deletions crates/ocs_save/src/ifccad.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,213 @@ use serde_json::Value;
pub struct IfccadSession(
Option<Arc<Mutex<document::IfccadRoundtripContext>>>,
Arc<BTreeMap<document::Handle, document::ifccad::IfccadPlotStyleSource>>,
Arc<Mutex<BTreeMap<(document::ifccad::IfccadExternalSourceId, String), ExternalSourceBytes>>>,
Arc<Mutex<BTreeMap<document::ifccad::IfccadExternalSourceId, String>>>,
);

/// Explicit browser choice, scoped to one open drawing and stored locator.
#[derive(Clone, Debug)]
pub struct ExternalSourceBytes {
pub file_name: String,
pub bytes: Arc<Vec<u8>>,
}

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<bool> {
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<ExternalSourceBytes> {
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<Vec<u8>>,
) -> 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<document::ifccad::IfccadExternalSource> {
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::<Result<Vec<_>, _>>()
.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,
Expand Down Expand Up @@ -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(())
Expand Down Expand Up @@ -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),
Expand Down
3 changes: 2 additions & 1 deletion crates/ocs_save/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading