From 9ee65fd00e7d0232a2e0afeab38ef70ab31deea8 Mon Sep 17 00:00:00 2001 From: BjornFidder Date: Tue, 1 Dec 2026 13:07:18 +0100 Subject: [PATCH 1/3] Map shared IFCCAD file sources through CAD consumers --- examples/font_symbol_review.rs | 38 +- src/ifcx/dimension_graphics.rs | 4 +- src/ifcx/file_fonts.rs | 189 +++ src/ifcx/file_sources.rs | 952 ++++++++++++++ src/ifcx/font.rs | 122 +- src/ifcx/layout.rs | 4 +- src/ifcx/leader_graphics/commands.rs | 17 +- src/ifcx/mline_pilot/retention.rs | 42 + src/ifcx/mod.rs | 58 +- src/ifcx/multi_leader/styles.rs | 19 +- src/ifcx/plot_styles.rs | 106 +- src/ifcx/table_resources.rs | 14 +- src/ifcx/tables.rs | 52 +- src/ifcx/text.rs | 3 + src/ifcx/xref.rs | 8 +- src/lib.rs | 2 + tests/fixtures/annotation-blocks.ifcx | 1 - tests/fixtures/annotation-hatch.ifcx | 1 - tests/fixtures/annotation-workspace.ifcx | 1 - tests/fixtures/complex-line-patterns.ifcx | 58 +- .../fixtures/dimension-fraction-diagonal.ifcx | 1 - tests/fixtures/dimension-graphics.ifcx | 1 - tests/fixtures/dimension-linear-aligned.ifcx | 1 - .../dimension-spatial-references.ifcx | 1 - tests/fixtures/font-symbol-base.ifcx | 1 - .../fixtures/hatch-associations-disabled.ifcx | 1 - tests/fixtures/hatch-editing.ifcx | 1 - tests/fixtures/hatch-gradient-inactive.ifcx | 1 - tests/fixtures/hatch-gradient.ifcx | 1 - tests/fixtures/hatch-pattern.ifcx | 1 - tests/fixtures/hello-cad.ifcx | 1 - tests/fixtures/hello-nested-blocks.ifcx | 1 - tests/fixtures/hello-paper-layouts.ifcx | 1 - tests/fixtures/hello-viewports.ifcx | 1 - tests/fixtures/layout-linetype-scaling.ifcx | 1 - tests/fixtures/layout-plot-inch.ifcx | 1 - tests/fixtures/layouts-viewports.ifcx | 1 - tests/fixtures/shared-file-sources/README.md | 7 + .../shared-file-sources/saved-font.ifcx | 1091 +++++++++++++++++ tests/fixtures/text-rich.ifcx | 1 - tests/fixtures/viewport-bulged-clip.ifcx | 1 - tests/fixtures/workspace-state.ifcx | 1 - tests/fixtures/xref/attachment.ifcx | 1 - tests/fixtures/xref/paper-layouts.ifcx | 1 - tests/ifccad_plot_styles.rs | 23 +- tests/ifcx_dimension_graphics.rs | 22 +- tests/ifcx_font_sources.rs | 146 ++- tests/ifcx_shared_file_sources.rs | 814 ++++++++++++ tests/ifcx_shared_file_sources_review.rs | 157 +++ tests/ifcx_xref_ifccad_sources.rs | 2 +- 50 files changed, 3701 insertions(+), 274 deletions(-) create mode 100644 src/ifcx/file_fonts.rs create mode 100644 src/ifcx/file_sources.rs create mode 100644 tests/fixtures/shared-file-sources/README.md create mode 100644 tests/fixtures/shared-file-sources/saved-font.ifcx create mode 100644 tests/ifcx_shared_file_sources.rs create mode 100644 tests/ifcx_shared_file_sources_review.rs diff --git a/examples/font_symbol_review.rs b/examples/font_symbol_review.rs index 0de35f4..99d24fc 100644 --- a/examples/font_symbol_review.rs +++ b/examples/font_symbol_review.rs @@ -6,8 +6,24 @@ use serde_json::{json, Value}; use std::{collections::BTreeMap, io::Cursor, path::Path}; type Error = Box; -fn font(font: &FontRequest) -> Value { +fn file_request(drawing: &IfccadDocument, id: Option) -> Value { + id.map_or(Value::Null, |id| { + match drawing + .external_sources + .iter() + .find(|source| source.id == id) + { + Some(source) => match opencaddocument::external_source_cad_path(source) { + Ok(path) => json!(path), + Err(error) => json!({"unsupported":error.to_string()}), + }, + None => json!({"missingSource":id.0}), + } + }) +} +fn font(drawing: &IfccadDocument, font: &FontRequest) -> Value { json!({"family":font.family,"cadFontName":font.cad_font_name,"bigFontName":font.big_font_name, + "primaryFile":file_request(drawing,font.primary_source),"bigFontFile":file_request(drawing,font.big_font_source), "bold":font.bold,"italic":font.italic,"charset":font.charset,"pitch":font.pitch}) } fn sort(rows: &mut [Value]) { @@ -17,10 +33,10 @@ fn projection(drawing: &IfccadDocument) -> Value { let mut styles = drawing .text_styles .iter() - .map(|s| json!({"name":s.name,"font":font(&s.properties.font)})) + .map(|s| json!({"name":s.name,"font":font(drawing, &s.properties.font)})) .collect::>(); sort(&mut styles); - let mut bindings: BTreeMap> = BTreeMap::new(); + let mut bindings: BTreeMap> = BTreeMap::new(); for pattern in &drawing.line_patterns { for (index, element) in pattern.pattern.iter().enumerate() { if let Some(IfccadLinePatternMarker::Symbol { @@ -38,12 +54,13 @@ fn projection(drawing: &IfccadDocument) -> Value { } } let mut sources = drawing - .symbol_sources + .external_sources .iter() + .filter(|s| matches!(s.source, IfccadExternalSourceContent::Shx {})) .map(|s| { let mut uses = bindings.remove(&s.id).unwrap_or_default(); sort(&mut uses); - json!({"request":s.source.effective_cad_file_name(),"bindings":uses}) + json!({"request":file_request(drawing,Some(s.id)),"bindings":uses}) }) .collect::>(); sort(&mut sources); @@ -79,13 +96,16 @@ fn projection(drawing: &IfccadDocument) -> Value { } => text.push(json!([ "run", value, - font(character_format.font.as_ref().unwrap_or(parent)) + font(drawing, character_format.font.as_ref().unwrap_or(parent)) ])), MTextInline::Stack(stack) => text.push(json!([ "stack", stack.upper, stack.lower, - font(stack.character_format.font.as_ref().unwrap_or(parent)) + font( + drawing, + stack.character_format.font.as_ref().unwrap_or(parent) + ) ])), _ => {} } @@ -130,7 +150,7 @@ fn main() -> Result<(), Error> { .and_then(|s| s.to_str()) .unwrap_or("") .to_ascii_lowercase(); - let (native, source_losses, source_reader) = if extension == "ifcx" { + let (native, source_losses, source_reader) = if extension == "ifcx" || extension == "ifccad" { ( load_ifccad_bytes(&bytes, Default::default())?.into_document(), Vec::new(), @@ -152,7 +172,7 @@ fn main() -> Result<(), Error> { std::fs::write(output.join("drawing.ifcx"), encoded.bytes())?; std::fs::write(output.join("drawing.ifccad.cbor"), cbor.bytes())?; let before = projection(&native); - let mut report = json!({"inputName":input.file_name().unwrap().to_string_lossy(),"profile":"0.6.0","cborRevision":6, + let mut report = json!({"inputName":input.file_name().unwrap().to_string_lossy(),"profile":"0.13.0","cborRevision":13, "sourceReader":source_reader,"sourceMappingDiagnostics":source_losses,"nativeToCadDiagnostics":losses(&converted.losses), "before":before,"targets":[],"scope":"Font/SHX requests and source bindings; ordinary geometry and rendering not certified by this projection"}); let mut equal = true; diff --git a/src/ifcx/dimension_graphics.rs b/src/ifcx/dimension_graphics.rs index 8d21b20..6bde5f3 100644 --- a/src/ifcx/dimension_graphics.rs +++ b/src/ifcx/dimension_graphics.rs @@ -278,7 +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(), + external_sources: d.external_sources.clone(), table_styles: Vec::new(), table_data_links: Vec::new(), data_tables: Vec::new(), @@ -286,7 +286,6 @@ fn resources(d: &IfccadDocument) -> IfccadDocument { annotation_settings: None, dimension_styles: d.dimension_styles.clone(), multi_leader_styles: d.multi_leader_styles.clone(), - symbol_sources: d.symbol_sources.clone(), plot_styles: Default::default(), point_display: d.point_display, text_styles: d.text_styles.clone(), @@ -320,6 +319,7 @@ fn resources(d: &IfccadDocument) -> IfccadDocument { } fn context<'a>(document: &'a Document, drawing: &IfccadDocument) -> Writer<'a> { Writer { + file_sources: super::file_sources::State::new(drawing), external_sources: HashMap::new(), #[cfg(feature = "mline-pilot")] roundtrip: None, diff --git a/src/ifcx/file_fonts.rs b/src/ifcx/file_fonts.rs new file mode 100644 index 0000000..af1debc --- /dev/null +++ b/src/ifcx/file_fonts.rs @@ -0,0 +1,189 @@ +//! Typed font consumers, including text embedded in saved pictures. +use super::*; +use ifccad::*; + +pub(super) fn may_have_fonts(kind: &IfccadEntityKind) -> bool { + matches!( + kind, + IfccadEntityKind::MText(_) + | IfccadEntityKind::Dimension(_) + | IfccadEntityKind::Table(_) + | IfccadEntityKind::MultiLeader(_) + | IfccadEntityKind::AttributeDefinition(_) + | IfccadEntityKind::BlockInstance { .. } + | IfccadEntityKind::Leader(_) + | IfccadEntityKind::Tolerance(_) + ) +} + +pub(super) fn has_file_bindings( + character: &ifccad::text::CharacterFormat, + content: &[ifccad::text::MTextParagraph], +) -> bool { + use ifccad::text::MTextInline; + let bound = |format: &ifccad::text::CharacterFormat| { + format + .font + .as_ref() + .is_some_and(|font| font.primary_source.is_some() || font.big_font_source.is_some()) + }; + bound(character) + || content.iter().any(|paragraph| { + bound(¶graph.character_format) + || paragraph.inlines.iter().any(|inline| match inline { + MTextInline::Run { + character_format, .. + } => bound(character_format), + MTextInline::Stack(stack) => bound(&stack.character_format), + _ => false, + }) + }) +} + +pub(super) fn formats( + character: &mut ifccad::text::CharacterFormat, + content: &mut [ifccad::text::MTextParagraph], + mut visit: impl FnMut(&mut FontRequest, &str) -> Result<(), Error>, +) -> Result<(), Error> { + use ifccad::text::MTextInline; + if let Some(font) = &mut character.font { + visit(font, "characterFormat/font")?; + } + for (p, paragraph) in content.iter_mut().enumerate() { + if let Some(font) = &mut paragraph.character_format.font { + visit(font, &format!("content/{p}/characterFormat/font"))?; + } + for (i, inline) in paragraph.inlines.iter_mut().enumerate() { + let format = match inline { + MTextInline::Run { + character_format, .. + } => character_format, + MTextInline::Stack(stack) => &mut stack.character_format, + _ => continue, + }; + if let Some(font) = &mut format.font { + visit( + font, + &format!("content/{p}/inlines/{i}/characterFormat/font"), + )?; + } + } + } + Ok(()) +} + +pub(super) fn texts( + kind: &mut IfccadEntityKind, + mut visit: impl FnMut(&mut IfccadMText, &str) -> Result<(), Error>, +) -> Result<(), Error> { + fn picture( + picture: &mut Option, + path: &str, + visit: &mut impl FnMut(&mut IfccadMText, &str) -> Result<(), Error>, + ) -> Result<(), Error> { + if let Some(picture) = picture { + for (i, part) in picture.parts.iter_mut().enumerate() { + if let IfccadDimensionGraphicsKind::MText(text) = &mut part.kind { + visit(text, &format!("{path}/parts/{i}/mText"))?; + } + } + } + Ok(()) + } + fn presentation( + p: &mut IfccadMultiLeaderPresentation, + path: &str, + visit: &mut impl FnMut(&mut IfccadMText, &str) -> Result<(), Error>, + ) -> Result<(), Error> { + if let Some(content) = &mut p.content.m_text { + visit(&mut content.text, &format!("{path}/content/mText"))?; + } + Ok(()) + } + match kind { + IfccadEntityKind::MText(text) => visit(text, "mText")?, + IfccadEntityKind::AttributeDefinition(a) => { + if let Some(m) = &mut a.m_text { + visit(&mut m.text, "attribute/mText")?; + } + } + IfccadEntityKind::BlockInstance { attributes, .. } => { + for a in attributes { + if let Some(m) = &mut a.value.m_text { + visit(&mut m.text, &format!("attribute/{}/mText", a.id))?; + } + } + } + IfccadEntityKind::Dimension(d) => { + picture(&mut d.graphics, "graphics", &mut visit)?; + if let Some(annotation) = &mut d.annotation { + for c in &mut annotation.contexts { + if let Some(p) = &mut c.presentation { + picture( + &mut p.graphics, + &format!("annotation/scale{}/graphics", c.key.scale_id.0), + &mut visit, + )?; + } + } + } + } + IfccadEntityKind::Table(t) => picture(&mut t.graphics, "graphics", &mut visit)?, + IfccadEntityKind::MultiLeader(m) => { + presentation(&mut m.presentation, "presentation", &mut visit)?; + if let Some(annotation) = &mut m.annotation { + for c in &mut annotation.contexts { + if let Some(p) = &mut c.presentation { + presentation( + p, + &format!("annotation/scale{}", c.key.scale_id.0), + &mut visit, + )?; + } + } + } + } + _ => {} + } + Ok(()) +} + +pub(super) fn graphic_fonts( + kind: &mut IfccadEntityKind, + mut visit: impl FnMut(&mut IfccadLeaderGraphicFont, &str) -> Result<(), Error>, +) -> Result<(), Error> { + let graphics = match kind { + IfccadEntityKind::Leader(v) => &mut v.graphics, + IfccadEntityKind::MultiLeader(v) => &mut v.graphics, + IfccadEntityKind::Tolerance(v) => &mut v.graphics, + _ => return Ok(()), + }; + if let Some(graphics) = graphics { + for (i, command) in graphics.commands.iter_mut().enumerate() { + if let IfccadLeaderGraphicCommand::Draw(IfccadLeaderGraphicPrimitive::Text(text)) = + command + { + if let Some(font) = &mut text.font { + visit(font, &format!("graphics/commands/{i}/font"))?; + } + } + } + } + Ok(()) +} + +pub(super) fn materialize_text(names: &Names, text: &IfccadMText) -> Result { + let mut result = text.clone(); + formats( + &mut result.character_format, + &mut result.content, + |font, _| { + *font = file_sources::materialize_font_sources(&names.file_sources, font)?; + if font.primary_source.is_some() { + font.cad_font_name = font.cad_font_name.take().map(|p| p.replace('\\', "/")); + } + Ok(()) + }, + )?; + Ok(result) +} diff --git a/src/ifcx/file_sources.rs b/src/ifcx/file_sources.rs new file mode 100644 index 0000000..3eadbd0 --- /dev/null +++ b/src/ifcx/file_sources.rs @@ -0,0 +1,952 @@ +//! File consumers share descriptors, but keep their own CAD object identities. +use super::*; +use ifccad::{ + IfccadExternalSource as Source, IfccadExternalSourceContent as Content, + IfccadExternalSourceFormat as Kind, IfccadExternalSourceId as Id, +}; + +type TextParts<'a> = ( + &'a ifccad::text::CharacterFormat, + &'a ifccad::text::ParagraphFormat, + &'a [ifccad::text::MTextParagraph], +); + +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +pub(super) enum Role { + Symbol, + PrimaryFont, + BigFont, + PlotStyle, + TableFile, +} + +#[derive(Clone, Debug, Hash, PartialEq, Eq)] +pub(super) struct Key { + pub owner: Handle, + pub role: Role, + pub slot: String, +} +impl Key { + pub fn new(owner: Handle, role: Role) -> Self { + Self { + owner, + role, + slot: String::new(), + } + } +} + +#[derive(Clone, Debug, Default)] +pub(super) struct State { + pub sources: BTreeMap, + pub bindings: HashMap, + pub history: HashMap>, + pub ambiguous_fonts: std::collections::HashSet<(Handle, String)>, + pub fonts: HashMap<(Handle, String), FontRequest>, + pub texts: HashMap<(Handle, String), TextSnapshot>, + pub defaults: HashMap< + Handle, + ( + ifccad::IfccadMultiLeaderDefaultText, + Vec>, + ), + >, +} + +#[derive(Clone, Debug)] +pub(super) struct TextSnapshot { + original: ifccad::IfccadMText, + projected: Vec>, +} +impl State { + pub fn new(drawing: &IfccadDocument) -> Self { + Self { + sources: drawing + .external_sources + .iter() + .filter(|s| s.source.base_point().is_none()) + .map(|s| (s.id, s.clone())) + .collect(), + ..Default::default() + } + } + pub fn remember( + &mut self, + drawing: &IfccadDocument, + names: &Names, + document: &Document, + handles: &HashMap, + ) -> Result<(), Error> { + for (id, handle) in &names.symbols { + self.bindings.insert(Key::new(*handle, Role::Symbol), *id); + } + for style in &drawing.text_styles { + let Some(handle) = names.style_handles.get(&style.id) else { + continue; + }; + let font = &style.properties.font; + self.fonts.insert((*handle, String::new()), font.clone()); + for (role, id) in [ + (Role::PrimaryFont, font.primary_source), + (Role::BigFont, font.big_font_source), + ] { + if let Some(id) = id { + self.bindings.insert(Key::new(*handle, role), id); + } + } + } + for object in document.objects.values() { + let acadrust::objects::ObjectType::Layout(layout) = object else { + continue; + }; + let id = if layout.name.eq_ignore_ascii_case("Model") { + Some(drawing.model.id) + } else { + drawing + .paper_layouts + .iter() + .find(|p| p.name.eq_ignore_ascii_case(&layout.name)) + .map(|p| p.id) + }; + if let Some(source) = id.and_then(|id| drawing.plot_styles.layout_sources.get(&id)) { + self.bindings + .insert(Key::new(layout.handle, Role::PlotStyle), *source); + } + } + for style in &drawing.multi_leader_styles { + let Some(owner) = names.multi_leader_styles.get(&style.id).copied() else { + continue; + }; + if !file_fonts::has_file_bindings( + &style.default_m_text.character_format, + &style.default_m_text.content, + ) { + continue; + } + let mut projected = style.default_m_text.clone(); + file_fonts::formats( + &mut projected.character_format, + &mut projected.content, + |font, _| { + *font = materialize_font(drawing, font)?; + if font.primary_source.is_some() { + font.cad_font_name = + font.cad_font_name.take().map(|p| p.replace('\\', "/")); + } + Ok(()) + }, + )?; + let encoded = text::emit_mtext( + &projected.character_format, + &projected.paragraph_format, + &projected.content, + ); + self.defaults.insert( + owner, + (style.default_m_text.clone(), text::parse_mtext(&encoded)), + ); + let mut original = style.default_m_text.clone(); + file_fonts::formats( + &mut original.character_format, + &mut original.content, + |font, slot| { + self.remember_font(owner, &format!("defaultMText/{slot}"), font); + Ok(()) + }, + )?; + self.remember_projected_fonts( + owner, + "defaultMText", + ( + &original.character_format, + &original.paragraph_format, + &original.content, + ), + ( + &projected.character_format, + &projected.paragraph_format, + &projected.content, + ), + )?; + } + for link in &drawing.table_data_links { + if let ifccad::IfccadTableDataLinkSource::File { source_id, .. } = &link.settings.source + { + if let Some(handle) = names.table_data_links.get(&link.id) { + self.bindings + .insert(Key::new(*handle, Role::TableFile), *source_id); + } + } + } + for entity in drawing + .model + .entities + .iter() + .chain(drawing.paper_layouts.iter().flat_map(|p| &p.entities)) + .chain(drawing.blocks.iter().flat_map(|b| &b.entities)) + { + let Some(entity) = entity.as_native() else { + continue; + }; + let Some(owner) = handles.get(&entity.id).copied() else { + continue; + }; + if !matches!( + entity.kind, + IfccadEntityKind::MText(_) + | IfccadEntityKind::Dimension(_) + | IfccadEntityKind::Table(_) + | IfccadEntityKind::MultiLeader(_) + | IfccadEntityKind::AttributeDefinition(_) + | IfccadEntityKind::BlockInstance { .. } + | IfccadEntityKind::Leader(_) + | IfccadEntityKind::Tolerance(_) + ) { + continue; + } + let mut kind = entity.kind.clone(); + file_fonts::texts(&mut kind, |text, path| { + if !file_fonts::has_file_bindings(&text.character_format, &text.content) { + return Ok(()); + } + let projected = file_fonts::materialize_text(names, text)?; + let encoded = text::emit_mtext( + &projected.character_format, + &projected.paragraph_format, + &projected.content, + ); + self.texts.insert( + (owner, path.into()), + TextSnapshot { + original: text.clone(), + projected: text::parse_mtext(&encoded), + }, + ); + file_fonts::formats( + &mut text.character_format, + &mut text.content, + |font, slot| { + self.remember_font(owner, &format!("{path}/{slot}"), font); + Ok(()) + }, + )?; + self.remember_projected_fonts( + owner, + path, + ( + &text.character_format, + &text.paragraph_format, + &text.content, + ), + ( + &projected.character_format, + &projected.paragraph_format, + &projected.content, + ), + ) + })?; + file_fonts::graphic_fonts(&mut kind, |font, slot| { + self.remember_font(owner, slot, &graphic_request(font)); + Ok(()) + })?; + } + for (key, id) in self.bindings.clone() { + self.bind(key, id); + } + Ok(()) + } + + fn bind(&mut self, key: Key, id: Id) { + let history = self.history.entry(key.clone()).or_default(); + if let Some(previous) = self.bindings.insert(key, id) { + if !history.contains(&previous) { + history.push(previous); + } + } + if !history.contains(&id) { + history.push(id); + } + } + + pub(super) fn select_plot_source( + &mut self, + owner: Handle, + selected: &Source, + counters: &mut ifccad::IfccadIdCounters, + ) -> Result { + if !matches!(selected.source, Content::Ctb { .. } | Content::Stb { .. }) { + return Err("plot-style binding requires CTB or STB content".into()); + } + selected.validate()?; + cad_path(selected)?; + let key = Key::new(owner, Role::PlotStyle); + let current = self.bindings.get(&key).copied(); + let known = current + .into_iter() + .chain(self.history.get(&key).into_iter().flatten().copied()) + .filter_map(|id| self.sources.get(&id)) + .find(|old| { + old.location == selected.location + && old.source == selected.source + && old.name == selected.name + && old.cad_path_spelling == selected.cad_path_spelling + }) + .map(|s| s.id); + let reusable = current.filter(|id| { + self.sources.get(id).is_some_and(|old| { + old.location == selected.location && old.source.format() == selected.source.format() + }) && self.bindings.values().filter(|value| *value == id).count() == 1 + }); + let id = match known.or(reusable) { + Some(id) => id, + None => counters.allocate_external_source_id()?, + }; + let mut source = selected.clone(); + source.id = id; + self.sources.insert(id, source); + self.bind(key, id); + Ok(id) + } + + fn remember_font(&mut self, owner: Handle, slot: &str, font: &FontRequest) { + self.fonts.insert((owner, slot.into()), font.clone()); + for (role, id) in [ + (Role::PrimaryFont, font.primary_source), + (Role::BigFont, font.big_font_source), + ] { + if let Some(id) = id { + self.bind( + Key { + owner, + role, + slot: slot.into(), + }, + id, + ); + } else { + let key = Key { + owner, + role, + slot: slot.into(), + }; + self.bindings.remove(&key); + self.history.remove(&key); + } + } + } + + fn remember_projected_fonts( + &mut self, + owner: Handle, + path: &str, + original: TextParts<'_>, + projected: TextParts<'_>, + ) -> Result<(), Error> { + let mut character = original.0.clone(); + let mut content = original.2.to_vec(); + let mut candidates = Vec::new(); + let sources = self.sources.values().cloned().collect::>(); + file_fonts::formats(&mut character, &mut content, |font, _| { + let projected = materialize_font_sources(&sources, font)?; + let signature = font_signature(&projected); + if !candidates.iter().any(|(old, _)| old == font) { + candidates.push((font.clone(), signature)); + } + Ok(()) + })?; + let encoded = text::emit_mtext(projected.0, projected.1, projected.2); + let mut parsed = text::parse_mtext(&encoded); + file_fonts::formats(&mut Default::default(), &mut parsed, |font, slot| { + let signature = font_signature(font); + let matches = candidates + .iter() + .filter(|(_, candidate)| *candidate == signature) + .collect::>(); + let slot = format!("{path}/{slot}"); + if let [candidate] = matches.as_slice() { + self.remember_font(owner, &slot, &candidate.0); + } else { + // A merged CAD scope cannot establish which original source ID + // was intended. Keep the descriptors, do not guess by filename. + for role in [Role::PrimaryFont, Role::BigFont] { + let key = Key { + owner, + role, + slot: slot.clone(), + }; + self.bindings.remove(&key); + self.history.remove(&key); + } + self.fonts.remove(&(owner, slot.clone())); + if matches.len() > 1 { + self.ambiguous_fonts.insert((owner, slot)); + } + } + Ok(()) + }) + } +} + +fn font_signature(font: &FontRequest) -> Option { + let mut font = font.clone(); + if font.primary_source.is_some() { + font.cad_font_name = font.cad_font_name.take().map(|p| p.replace('\\', "/")); + } + let character = ifccad::text::CharacterFormat { + font: Some(font), + ..Default::default() + }; + let content = [ifccad::text::MTextParagraph { + inlines: vec![ifccad::text::MTextInline::Run { + text: "x".into(), + character_format: Default::default(), + }], + ..Default::default() + }]; + let mut parsed = + text::parse_mtext(&text::emit_mtext(&character, &Default::default(), &content)); + let mut result = None; + let _ = file_fonts::formats(&mut Default::default(), &mut parsed, |font, _| { + result = Some(font.clone()); + Ok(()) + }); + result +} + +/// Qualify a whole-file CAD path, retaining a matching literal CAD spelling. +/// Unsupported URI schemes remain errors even when spelling metadata matches. +/// This conversion performs no resolution, filesystem access or download. +pub fn cad_path(source: &Source) -> Result { + let qualified = external_sources::external_source_location_to_cad_path(&source.location)?; + if let Some(spelling) = &source.cad_path_spelling { + let first = spelling.split(['/', '\\']).next().unwrap_or_default(); + let literal = !first.contains(':') + || (first.len() == 2 + && first.as_bytes()[0].is_ascii_alphabetic() + && first.as_bytes()[1] == b':'); + if literal + && external_sources::external_source_location_from_cad_path(spelling) + .is_ok_and(|location| location == source.location) + { + return Ok(spelling.clone()); + } + } + Ok(qualified) +} + +#[cfg(test)] +mod locator_tests { + use super::*; + + #[test] + fn spelling_cannot_qualify_an_unsupported_uri() { + let source = Source { + id: Id(1), + name: "Remote font".into(), + location: ifccad::IfccadExternalSourceLocation::UriReference { + uri: "https://example.invalid/font.shx".into(), + }, + cad_path_spelling: Some("https://example.invalid/font.shx".into()), + source: Content::Shx {}, + }; + assert!(cad_path(&source).is_err()); + } +} +pub(super) fn source(drawing: &IfccadDocument, id: Id) -> Result<&Source, Error> { + drawing + .external_sources + .iter() + .find(|s| s.id == id) + .ok_or_else(|| format!("missing external file source {}", id.0).into()) +} + +fn same_location(source: &Source, location: &ifccad::IfccadExternalSourceLocation) -> bool { + source.location == *location + || external_sources::external_source_location_to_cad_path(&source.location) + .and_then(|path| external_sources::external_source_location_from_cad_path(&path)) + .is_ok_and(|projected| projected == *location) +} + +pub(super) fn register( + writer: &mut Writer<'_>, + key: Key, + request: &str, + content: Content, +) -> Result { + let location = external_sources::external_source_location_from_cad_path(request)?; + let retained = writer + .file_sources + .bindings + .get(&key) + .into_iter() + .chain(writer.file_sources.history.get(&key).into_iter().flatten()) + .filter_map(|id| writer.file_sources.sources.get(id)) + .find(|old| old.source.format() == content.format() && same_location(old, &location)) + .cloned(); + let source = match retained { + Some(source) => source, + None => Source { + id: writer.drawing.id_counters.allocate_external_source_id()?, + name: request + .rsplit(['/', '\\']) + .next() + .unwrap_or(request) + .to_owned(), + location, + cad_path_spelling: Some(request.into()), + source: content, + }, + }; + source.validate()?; + if !writer + .drawing + .external_sources + .iter() + .any(|s| s.id == source.id) + { + writer.drawing.external_sources.push(source.clone()); + } + writer.file_sources.bind(key, source.id); + writer + .file_sources + .sources + .insert(source.id, source.clone()); + Ok(source.id) +} + +fn font_kind(writer: &Writer<'_>, key: &Key, request: &str) -> Option { + if let Ok(location) = external_sources::external_source_location_from_cad_path(request) { + if let Some(known) = writer + .file_sources + .bindings + .get(key) + .into_iter() + .chain(writer.file_sources.history.get(key).into_iter().flatten()) + .filter_map(|id| writer.file_sources.sources.get(id)) + .find(|source| { + matches!(source.source, Content::Shx {} | Content::Font {}) + && same_location(source, &location) + }) + { + return Some(known.source.clone()); + } + } + let extension = request.rsplit('.').next().unwrap_or(""); + if extension.eq_ignore_ascii_case("shx") { + return Some(Content::Shx {}); + } + if ["ttf", "otf", "ttc"] + .iter() + .any(|e| extension.eq_ignore_ascii_case(e)) + { + return Some(Content::Font {}); + } + writer + .file_sources + .bindings + .get(key) + .and_then(|id| writer.file_sources.sources.get(id)) + .and_then(|s| match s.source.format() { + Kind::Shx => Some(Content::Shx {}), + Kind::Font => Some(Content::Font {}), + _ => None, + }) +} +pub(super) fn bind_font( + writer: &mut Writer<'_>, + owner: Handle, + font: FontRequest, +) -> Result { + bind_font_at(writer, owner, "", font) +} +fn bind_font_at( + writer: &mut Writer<'_>, + owner: Handle, + slot: &str, + mut font: FontRequest, +) -> Result { + if font.primary_source.is_none() + && font.big_font_source.is_none() + && writer + .file_sources + .ambiguous_fonts + .contains(&(owner, slot.into())) + { + writer.losses.located_loss(owner, format!( + "{slot}: ambiguous merged font scope after editing; original file-source associations cannot be recovered, and their descriptors remain retained" + )); + } + for (role, id) in [ + (Role::PrimaryFont, font.primary_source), + (Role::BigFont, font.big_font_source), + ] { + if let Some(id) = id { + writer.file_sources.bindings.insert( + Key { + owner, + role, + slot: slot.into(), + }, + id, + ); + } + } + let original = writer + .file_sources + .fonts + .get(&(owner, slot.into())) + .cloned(); + if font.primary_source.is_some() || font.big_font_source.is_some() { + font = materialize_font(&writer.drawing, &font)?; + } + let key = Key { + owner, + role: Role::PrimaryFont, + slot: slot.into(), + }; + if let Some(request) = font.cad_font_name.clone().filter(|s| !s.is_empty()) { + if let Some(content) = font_kind(writer, &key, &request) { + font.primary_source = Some(register(writer, key, &request, content)?); + } + } + if let Some(request) = font.big_font_name.clone().filter(|s| !s.is_empty()) { + font.big_font_source = Some(register( + writer, + Key { + owner, + role: Role::BigFont, + slot: slot.into(), + }, + &request, + Content::Shx {}, + )?); + } + if let Some(original) = original { + if original.primary_source.is_some() && original.primary_source == font.primary_source { + font.cad_font_name = original.cad_font_name; + } + if original.big_font_source.is_some() && original.big_font_source == font.big_font_source { + font.big_font_name = original.big_font_name.clone(); + } + if !slot.is_empty() + && original.primary_source.is_some() + && original.primary_source == font.primary_source + { + // Inline CAD grammar has no second family or Big Font field. An + // unchanged primary scope still identifies those native requests. + if font.family.is_none() { + font.family = original.family; + } + if font.big_font_name.is_none() { + font.big_font_name = original.big_font_name; + font.big_font_source = original.big_font_source; + } + } + } + Ok(font) +} + +fn graphic_request(font: &ifccad::IfccadLeaderGraphicFont) -> FontRequest { + FontRequest { + cad_font_name: (!font.font_file.is_empty()).then(|| font.font_file.clone()), + big_font_name: (!font.big_font_file.is_empty()).then(|| font.big_font_file.clone()), + primary_source: font.primary_source, + big_font_source: font.big_font_source, + ..Default::default() + } +} + +pub(super) fn bind_entity_fonts( + writer: &mut Writer<'_>, + owner: Handle, + kind: &mut IfccadEntityKind, +) -> Result<(), Error> { + file_fonts::texts(kind, |text, path| { + if let Some(saved) = writer.file_sources.texts.get(&(owner, path.into())) { + if text::picture_native_content(text) == saved.projected { + text.character_format = saved.original.character_format.clone(); + text.content = saved.original.content.clone(); + } + } + file_fonts::formats( + &mut text.character_format, + &mut text.content, + |font, slot| { + *font = bind_font_at(writer, owner, &format!("{path}/{slot}"), font.clone())?; + Ok(()) + }, + ) + })?; + file_fonts::graphic_fonts(kind, |font, slot| { + let request = bind_font_at(writer, owner, slot, graphic_request(font))?; + font.primary_source = request.primary_source; + font.big_font_source = request.big_font_source; + font.font_file = request.cad_font_name.unwrap_or_default(); + font.big_font_file = request.big_font_name.unwrap_or_default(); + Ok(()) + }) +} + +pub(super) fn bind_default_fonts( + writer: &mut Writer<'_>, + owner: Handle, + value: &mut ifccad::IfccadMultiLeaderDefaultText, +) -> Result<(), Error> { + let encoded = text::emit_mtext( + &value.character_format, + &value.paragraph_format, + &value.content, + ); + if let Some((original, projected)) = writer.file_sources.defaults.get(&owner) { + if text::parse_mtext(&encoded) == *projected { + *value = original.clone(); + } + } + file_fonts::formats( + &mut value.character_format, + &mut value.content, + |font, slot| { + *font = bind_font_at(writer, owner, &format!("defaultMText/{slot}"), font.clone())?; + Ok(()) + }, + ) +} +pub(super) fn materialize_font( + drawing: &IfccadDocument, + font: &FontRequest, +) -> Result { + materialize_font_sources(&drawing.external_sources, font) +} +pub(super) fn materialize_font_sources( + sources: &[Source], + font: &FontRequest, +) -> Result { + let mut result = font.clone(); + if let Some(id) = font.primary_source { + result.cad_font_name = Some(cad_path( + sources + .iter() + .find(|s| s.id == id) + .ok_or("missing font source")?, + )?); + } + if let Some(id) = font.big_font_source { + result.big_font_name = Some(cad_path( + sources + .iter() + .find(|s| s.id == id) + .ok_or("missing Big Font source")?, + )?); + } + Ok(result) +} + +fn extraction_adapter(adapter: &str) -> bool { + adapter == "OpenCADStudio.DataExtraction.DataLinkAdapter" + || adapter.ends_with(".DataExtraction.DxDataLinkAdapter") +} + +fn table_path_has_basis(location: &ifccad::IfccadExternalSourceLocation, path_option: i16) -> bool { + path_option != 1 + || !matches!(location, + ifccad::IfccadExternalSourceLocation::UriReference { uri } + if !uri.get(..5).is_some_and(|scheme| scheme.eq_ignore_ascii_case("file:"))) +} + +pub(super) fn diagnose_cad_metadata_loss( + drawing: &IfccadDocument, + losses: &mut Losses, +) -> Result<(), Error> { + let mut used = std::collections::BTreeSet::new(); + let mut font = |font: &FontRequest| { + used.extend( + [font.primary_source, font.big_font_source] + .into_iter() + .flatten(), + ); + }; + for style in &drawing.text_styles { + font(&style.properties.font); + } + for style in &drawing.multi_leader_styles { + let mut value = style.default_m_text.clone(); + file_fonts::formats( + &mut value.character_format, + &mut value.content, + |value, _| { + font(value); + Ok(()) + }, + )?; + } + for entity in drawing + .model + .entities + .iter() + .chain(drawing.paper_layouts.iter().flat_map(|p| &p.entities)) + .chain(drawing.blocks.iter().flat_map(|b| &b.entities)) + { + let Some(entity) = entity.as_native() else { + continue; + }; + if !file_fonts::may_have_fonts(&entity.kind) { + continue; + } + let mut kind = entity.kind.clone(); + file_fonts::texts(&mut kind, |text, _| { + file_fonts::formats(&mut text.character_format, &mut text.content, |value, _| { + font(value); + Ok(()) + }) + })?; + file_fonts::graphic_fonts(&mut kind, |value, _| { + font(&graphic_request(value)); + Ok(()) + })?; + } + for pattern in &drawing.line_patterns { + for element in &pattern.pattern { + if let Some(ifccad::IfccadLinePatternMarker::Symbol { + symbol_source_id, .. + }) = element.marker + { + used.insert(symbol_source_id); + } + } + } + used.extend(drawing.plot_styles.layout_sources.values().copied()); + for link in &drawing.table_data_links { + if let ifccad::IfccadTableDataLinkSource::File { source_id, .. } = link.settings.source { + used.insert(source_id); + } + } + for source in drawing + .external_sources + .iter() + .filter(|s| s.source.base_point().is_none()) + { + let path = format!( + "/cad/d{}/externalSource/{}", + drawing.drawing_id, source.id.0 + ); + if !used.contains(&source.id) { + losses.note(format!("{path}: unused file-source descriptor has no CAD consumer; native context is required to retain it")); + continue; + } + if let Ok(request) = cad_path(source) { + let name = request.rsplit(['/', '\\']).next().unwrap_or(&request); + if source.name != name { + losses.note(format!( + "{path}/name: external file-source display name has no CAD file-request field" + )); + } + if source + .cad_path_spelling + .as_ref() + .is_some_and(|spelling| spelling != &request) + { + losses.note(format!("{path}/cadPathSpelling: stale spelling metadata is not written over the authoritative location")); + } + } + } + Ok(()) +} +pub(super) fn table_source_out( + writer: &mut Writer<'_>, + owner: Handle, + adapter: &str, + connection: &str, + path_option: i16, +) -> Result { + use ifccad::IfccadTableDataLinkSource as Link; + let raw = || Link::AdapterConnection { + connection: connection.into(), + }; + if connection.is_empty() { + return Ok(raw()); + } + let (path, selection) = if adapter == "AcExcel" { + let start = connection.rfind(['/', '\\']).map_or(0, |at| at + 1); + if let Some(at) = connection[start..].find('!') { + let at = start + at; + let path = &connection[..at]; + // A delimiter after a recognizable spreadsheet filename is qualified; + // an exclamation within a filename is not guessed into a selection. + if ![".xlsx", ".xls", ".xlsm", ".xlsb", ".csv"] + .iter() + .any(|ext| path.to_ascii_lowercase().ends_with(ext)) + { + return Ok(raw()); + } + (path, Some(connection[at + 1..].to_owned())) + } else { + (connection, None) + } + } else if extraction_adapter(adapter) { + (connection, None) + } else { + return Ok(raw()); + }; + let Ok(location) = external_sources::external_source_location_from_cad_path(path) else { + return Ok(raw()); + }; + if external_sources::external_source_location_to_cad_path(&location).is_err() { + return Ok(raw()); + } + if !table_path_has_basis(&location, path_option) { + return Ok(raw()); + } + let source_id = register( + writer, + Key::new(owner, Role::TableFile), + path, + Content::DataFile {}, + )?; + Ok(Link::File { + source_id, + selection, + }) +} +pub(super) fn table_connection( + drawing: &IfccadDocument, + settings: &ifccad::IfccadTableDataLinkSettings, +) -> Result { + use ifccad::IfccadTableDataLinkSource as Link; + match &settings.source { + Link::AdapterConnection { connection } => Ok(connection.clone()), + Link::File { + source_id, + selection, + } => { + if settings.adapter != "AcExcel" && !extraction_adapter(&settings.adapter) { + return Err("table adapter has no qualified CAD file-connection mapping".into()); + } + if extraction_adapter(&settings.adapter) && selection.is_some() { + return Err( + "data extraction settings files do not have a CAD source selection".into(), + ); + } + let source = source(drawing, *source_id)?; + let path = cad_path(source)?; + if !table_path_has_basis(&source.location, settings.path_option) { + return Err( + "table path mode has no qualified basis for this relative file URI".into(), + ); + } + if settings.adapter == "AcExcel" + && path + .rsplit(['/', '\\']) + .next() + .is_some_and(|p| p.contains('!')) + { + return Err( + "AcExcel cannot distinguish this filename from its selection delimiter".into(), + ); + } + Ok(match selection { + Some(selection) => format!("{path}!{selection}"), + None => path, + }) + } + } +} diff --git a/src/ifcx/font.rs b/src/ifcx/font.rs index d7b485e..67c15ee 100644 --- a/src/ifcx/font.rs +++ b/src/ifcx/font.rs @@ -12,15 +12,20 @@ pub(super) fn preflight_font_requests( losses: &mut Losses, ) -> Result<(), Error> { use ifccad::text::MTextInline; - use ifccad::{IfccadDimensionGraphics, IfccadDimensionGraphicsKind, IfccadMText}; - fn mtext(text: &IfccadMText, path: &str, losses: &mut Losses) -> Result<(), Error> { + fn mtext( + drawing: &IfccadDocument, + character: &ifccad::text::CharacterFormat, + content: &[ifccad::text::MTextParagraph], + path: &str, + losses: &mut Losses, + ) -> Result<(), Error> { let mut authored = Vec::new(); let mut emitted = Vec::new(); - let global = text.character_format.font.as_ref(); + let global = character.font.as_ref(); if let Some(font) = global { authored.push((font, format!("{path}/characterFormat/font"))); } - for (p, paragraph) in text.content.iter().enumerate() { + for (p, paragraph) in content.iter().enumerate() { let parent = paragraph.character_format.font.as_ref().or(global); if let Some(font) = paragraph.character_format.font.as_ref() { authored.push((font, format!("{path}/content/{p}/characterFormat/font"))); @@ -46,13 +51,27 @@ pub(super) fn preflight_font_requests( } for (font, location) in authored { let active = emitted.iter().any(|other| std::ptr::eq(*other, font)); - let (field, selected) = if let Some(family) = &font.family { + let projected = file_sources::materialize_font(drawing, font)?; + let (field, selected) = if projected.primary_source.is_some() { + ( + "primarySource", + projected + .cad_font_name + .as_ref() + .ok_or("missing materialized font path")?, + ) + } else if let Some(family) = &font.family { ("family", family) } else if let Some(name) = &font.cad_font_name { ("cadFontName", name) } else { continue; }; + let selected = if projected.primary_source.is_some() { + selected.replace('\\', "/") + } else { + selected.clone() + }; if active && selected.contains(['|', ';', '\\', '{', '}']) { return Err(format!("{location}/{field}: unsupported MText font request cannot be written without changing its name").into()); } @@ -61,69 +80,68 @@ pub(super) fn preflight_font_requests( "{location}: authored dormant font override has no emitted MText scope" )); } - if font.family.is_some() && font.cad_font_name.is_some() { + if font.primary_source.is_some() && font.family.is_some() { + losses.note(format!("{location}/family: additional family selector has no MText grammar field; bound file retained")); + } else if font.family.is_some() && font.cad_font_name.is_some() { losses.note(format!("{location}/cadFontName: additional selector has no MText grammar field; family retained")); } - if font.big_font_name.is_some() { + if font.big_font_name.is_some() || font.big_font_source.is_some() { + let field = if font.big_font_source.is_some() { + "bigFontSource" + } else { + "bigFontName" + }; losses.note(format!( - "{location}/bigFontName: selector has no MText grammar field" + "{location}/{field}: selector has no MText grammar field" )); } } Ok(()) } - fn graphics( - picture: &IfccadDimensionGraphics, - path: &str, - losses: &mut Losses, - ) -> Result<(), Error> { - for (index, part) in picture.parts.iter().enumerate() { - if let IfccadDimensionGraphicsKind::MText(text) = &part.kind { - mtext(text, &format!("{path}/parts/{index}/mText"), losses)?; - } - } - Ok(()) - } for entity in drawing .model .entities .iter() - .chain( - drawing - .paper_layouts - .iter() - .flat_map(|layout| &layout.entities), - ) - .chain(drawing.blocks.iter().flat_map(|block| &block.entities)) + .chain(drawing.paper_layouts.iter().flat_map(|p| &p.entities)) + .chain(drawing.blocks.iter().flat_map(|b| &b.entities)) { - let IfccadEntity::Native(entity) = entity else { + let Some(entity) = entity.as_native() else { continue; }; - let path = format!("/cad/d{}/e{}", drawing.drawing_id, entity.id); - match &entity.kind { - IfccadEntityKind::MText(text) => mtext(text, &format!("{path}/ifccad::mText"), losses)?, - IfccadEntityKind::Dimension(dimension) => { - if let Some(picture) = &dimension.graphics { - graphics(picture, &format!("{path}/graphics"), losses)?; - } - if let Some(annotation) = &dimension.annotation { - for (index, context) in annotation.contexts.iter().enumerate() { - if let Some(picture) = context - .presentation - .as_ref() - .and_then(|p| p.graphics.as_ref()) - { - graphics( - picture, - &format!("{path}/annotation/contexts/{index}/graphics"), - losses, - )?; - } - } - } - } - _ => {} + if !file_fonts::may_have_fonts(&entity.kind) { + continue; } + let mut kind = entity.kind.clone(); + file_fonts::texts(&mut kind, |text, slot| { + mtext( + drawing, + &text.character_format, + &text.content, + &format!("/cad/d{}/e{}/{slot}", drawing.drawing_id, entity.id), + losses, + ) + })?; + file_fonts::graphic_fonts(&mut kind, |font, _| { + for id in [font.primary_source, font.big_font_source] + .into_iter() + .flatten() + { + file_sources::cad_path(file_sources::source(drawing, id)?)?; + } + Ok(()) + })?; + } + for style in &drawing.multi_leader_styles { + mtext( + drawing, + &style.default_m_text.character_format, + &style.default_m_text.content, + &format!( + "/cad/d{}/multiLeaderStyle/{}/defaultMText", + drawing.drawing_id, style.id.0 + ), + losses, + )?; } Ok(()) } diff --git a/src/ifcx/layout.rs b/src/ifcx/layout.rs index aef5da9..4f758ab 100644 --- a/src/ifcx/layout.rs +++ b/src/ifcx/layout.rs @@ -591,7 +591,7 @@ pub(super) fn read( if let Some(model) = layout_handle(document, document.header.model_space_block_handle) { if let Some(ObjectType::Layout(layout)) = document.objects.get_mut(&model) { settings_in(layout, &drawing.model.settings, losses); - plot_styles::source_in(drawing, drawing.model.id, layout, losses); + plot_styles::source_in(drawing, drawing.model.id, layout, losses)?; } } let mut papers: Vec<&IfccadPaperLayout> = drawing.paper_layouts.iter().collect(); @@ -614,7 +614,7 @@ pub(super) fn read( }; layout.tab_order = i16::try_from(paper.tab_index).unwrap_or(i16::MAX); settings_in(layout, &paper.settings, losses); - plot_styles::source_in(drawing, paper.id, layout, losses); + plot_styles::source_in(drawing, paper.id, layout, losses)?; owners.push(layout.block_record); } // Every sheet, the untouched one of a new drawing too, gets its markers diff --git a/src/ifcx/leader_graphics/commands.rs b/src/ifcx/leader_graphics/commands.rs index 4eb8d2b..436a9b2 100644 --- a/src/ifcx/leader_graphics/commands.rs +++ b/src/ifcx/leader_graphics/commands.rs @@ -319,6 +319,8 @@ pub(super) fn decode( text.tracking = t.tracking; set_flags(&mut text, t.text_flags); text.font = Some(IfccadLeaderGraphicFont { + primary_source: None, + big_font_source: None, family: t.family, font_file: t.font_file, big_font_file: t.big_font_file, @@ -345,6 +347,8 @@ pub(super) fn decode( text.tracking = style.tracking; set_flags(&mut text, style.text_flags); text.font = Some(IfccadLeaderGraphicFont { + primary_source: None, + big_font_source: None, family: String::new(), font_file: decode_legacy(&style.font_file, bindings)?, big_font_file: decode_legacy(&style.big_font_file, bindings)?, @@ -366,7 +370,7 @@ fn encode_text( let position = vector(text.position); let normal = vector(text.normal); let direction = vector(text.direction); - let Some(font) = &text.font else { + let Some(mut font) = text.font.clone() else { if text.processing != Processing::Interpreted || flags(text).iter().any(|flag| *flag) || text.tracking != 1. @@ -386,6 +390,17 @@ fn encode_text( oblique_angle: text.oblique_angle, })); }; + if let Some(id) = font.primary_source { + font.font_file = super::super::file_sources::cad_path(super::super::file_sources::source( + bindings.drawing, + id, + )?)?; + } + if let Some(id) = font.big_font_source { + font.big_font_file = super::super::file_sources::cad_path( + super::super::file_sources::source(bindings.drawing, id)?, + )?; + } match (font.bold, font.italic, font.charset, font.pitch_family) { (Some(bold), Some(italic), Some(charset), Some(pitch_family)) => { Ok(CheckedProxyGraphicRecord::Command(Cad::StyledUnicodeText( diff --git a/src/ifcx/mline_pilot/retention.rs b/src/ifcx/mline_pilot/retention.rs index 3137835..31e4e08 100644 --- a/src/ifcx/mline_pilot/retention.rs +++ b/src/ifcx/mline_pilot/retention.rs @@ -16,6 +16,7 @@ use std::collections::{BTreeMap, HashMap}; /// CAD handles inside it refer to that session and are rebuilt on reopen. #[derive(Clone, Debug)] pub struct IfccadRoundtripContext { + file_sources: crate::ifcx::file_sources::State, external_source_definition_names: HashMap, external_source_history: HashMap<(Handle, String), ifccad::IfccadExternalSource>, external_sources: HashMap, @@ -152,6 +153,7 @@ fn exported_pattern(writer: &Writer<'_>, handle: Handle) -> Option Self { Self { + file_sources: crate::ifcx::file_sources::State::new(drawing), external_source_definition_names: HashMap::new(), external_source_history: HashMap::new(), external_sources: HashMap::new(), @@ -198,6 +200,7 @@ impl IfccadRoundtripContext { return Ok(None); }; source.location = crate::external_source_location_from_cad_path(path)?; + source.cad_path_spelling = Some(path.to_owned()); Ok(Some(source)) } @@ -227,6 +230,7 @@ impl IfccadRoundtripContext { id, name, location: crate::external_source_location_from_cad_path(&cad_path)?, + cad_path_spelling: Some(cad_path.clone()), source: content, }; source.validate()?; @@ -261,6 +265,38 @@ impl IfccadRoundtripContext { } } + pub(in crate::ifcx) fn file_source_state(&self) -> &crate::ifcx::file_sources::State { + &self.file_sources + } + + /// Bind selected CTB/STB metadata to one imported CAD layout. + /// + /// The descriptor's ID is not an allocation request. This context retains a + /// known consumer identity where possible and allocates from its own shared + /// source watermark otherwise. Replacing one use of a shared source forks + /// that binding, leaving the other layouts and unused descriptors intact. + /// File resolution and changing the CAD layout's requested path remain the + /// caller's responsibilities. No file is opened or hashed here. + pub fn bind_plot_style_source( + &mut self, + layout: Handle, + source: &ifccad::IfccadExternalSource, + ) -> Result { + self.file_sources + .select_plot_source(layout, source, &mut self.counters) + } + + pub(in crate::ifcx) fn remember_file_sources( + &mut self, + drawing: &IfccadDocument, + document: &Document, + names: &Names, + handles: &HashMap, + ) -> Result<(), Error> { + self.file_sources + .remember(drawing, names, document, handles) + } + /// IFCCAD identities and diagnostic reasons for live roots without CAD geometry. pub fn blocked_entities(&self) -> impl Iterator { self.blocked @@ -390,6 +426,9 @@ impl IfccadRoundtripContext { )); } drawing.id_counters = self.counters; + drawing + .external_sources + .extend(self.file_sources.sources.values().cloned()); drawing.model.id = self.model_id; if !document .line_types @@ -402,6 +441,7 @@ impl IfccadRoundtripContext { } pub(in crate::ifcx) fn remember_export(&mut self, saved: SavedIdentities) { + self.file_sources = saved.file_sources; self.counters = saved.counters; self.external_sources.extend(saved.external_sources); self.external_source_history @@ -493,6 +533,7 @@ impl IfccadRoundtripContext { } pub(in crate::ifcx) struct SavedIdentities { + file_sources: crate::ifcx::file_sources::State, external_source_history: HashMap<(Handle, String), ifccad::IfccadExternalSource>, external_sources: HashMap, counters: IfccadIdCounters, @@ -542,6 +583,7 @@ impl SavedIdentities { }) .collect(); Self { + file_sources: writer.file_sources.clone(), external_source_history: writer .external_sources .iter() diff --git a/src/ifcx/mod.rs b/src/ifcx/mod.rs index c63420c..21378b8 100644 --- a/src/ifcx/mod.rs +++ b/src/ifcx/mod.rs @@ -25,9 +25,9 @@ use ifccad::text::{ use ifccad::{ encode_ifccad_document, load_ifccad_bytes, IfccadBlockDefinition, IfccadBlockTransform, IfccadColor, IfccadDocument, IfccadEntity, IfccadEntityAppearance, IfccadEntityKind, - IfccadFilledQuadrilateral, IfccadHeader, IfccadLinePatternGeneration, IfccadLinePatternId, - IfccadMode, IfccadNativeEntity, IfccadPaperLayout, IfccadPlacement, IfccadPlanarPolylineWidths, - IfccadPlotStyleMode, IfccadSymbolSourceId, IfccadText, IfccadTextStyleId, IfccadUcsId, + IfccadExternalSourceId, IfccadFilledQuadrilateral, IfccadHeader, IfccadLinePatternGeneration, + IfccadLinePatternId, IfccadMode, IfccadNativeEntity, IfccadPaperLayout, IfccadPlacement, + IfccadPlanarPolylineWidths, IfccadPlotStyleMode, IfccadText, IfccadTextStyleId, IfccadUcsId, IfccadUcsSelection, }; @@ -46,6 +46,9 @@ mod dimension; mod dimension_graphics; mod dimension_kinds; mod external_sources; +mod file_fonts; +mod file_sources; +pub use file_sources::cad_path as external_source_cad_path; mod xref; pub use external_sources::{ dwg_external_source_content, dwg_xref_fingerprint_guid, dxf_external_source_content, @@ -102,7 +105,7 @@ const TEMPLATE: &str = r#"{ "nextLayerId": 1, "nextLayoutId": 2, "nextLinePatternId": 1, - "nextSymbolSourceId": 1, + "nextExternalSourceId": 1, "profileVersion": "0.13.0", "nextUcsId": 1, "nextModelWindowId": 1 @@ -220,7 +223,7 @@ impl Ifcx { /// Check existing CAD layouts carrying IFCCAD plot-source metadata. pub fn validate_cad_plot_style_sources<'a>( &self, - layouts: impl IntoIterator, + layouts: impl IntoIterator, ) -> Result<(), Error> { plot_styles::validate_cad_sources(layouts) } @@ -236,11 +239,10 @@ impl Ifcx { /// /// Returns an error if IFCCAD validation or CAD document construction fails. pub fn import_ifccad(&self, drawing: &IfccadDocument) -> Result { - if let Some(source) = drawing - .external_sources - .iter() - .find(|source| source.source.format() != ifccad::IfccadExternalSourceFormat::Dwg) - { + if let Some(source) = drawing.external_sources.iter().find(|source| { + source.source.base_point().is_some() + && source.source.format() != ifccad::IfccadExternalSourceFormat::Dwg + }) { return Err(format!( "XREF {}: convert the external source to DWG before CAD export", source.name @@ -278,6 +280,13 @@ impl Ifcx { mline_pilot::check_preservation_scope(drawing)?; let mut losses = Losses::default(); font::preflight_font_requests(drawing, &mut losses)?; + #[cfg(feature = "mline-pilot")] + let retains_file_metadata = context.is_some(); + #[cfg(not(feature = "mline-pilot"))] + let retains_file_metadata = false; + if !retains_file_metadata { + file_sources::diagnose_cad_metadata_loss(drawing, &mut losses)?; + } let mut document = Document::new(); document.header.insertion_units = unit_code(&drawing.length_unit); document.header.plotstyle_mode = @@ -307,7 +316,10 @@ impl Ifcx { info.author = drawing.header.author.clone(); } - let mut names = Names::default(); + let mut names = Names { + file_sources: drawing.external_sources.clone(), + ..Default::default() + }; xref::sources_in(drawing, &mut document, &mut names, &mut losses)?; #[cfg(feature = "mline-pilot")] if let Some(context) = context.as_deref_mut() { @@ -450,6 +462,10 @@ impl Ifcx { leader::link_import(drawing, &mut document, &handles)?; annotation_leader::import(drawing, &mut document, &names, &handles, &mut losses)?; #[cfg(feature = "mline-pilot")] + if let Some(context) = context.as_deref_mut() { + context.remember_file_sources(drawing, &document, &names, &handles)?; + } + #[cfg(feature = "mline-pilot")] mline_pilot::restore( drawing, &mut document, @@ -555,6 +571,19 @@ impl Ifcx { _ => return Err(annotation::invalid("invalid ATTMODE")), }; let mut writer = Writer { + file_sources: { + #[cfg(feature = "mline-pilot")] + { + context + .as_deref() + .map(|c| c.file_source_state().clone()) + .unwrap_or_default() + } + #[cfg(not(feature = "mline-pilot"))] + { + Default::default() + } + }, external_sources: HashMap::new(), #[cfg(feature = "mline-pilot")] roundtrip: context.as_deref(), @@ -705,6 +734,7 @@ fn link_hatches( /// Names of what IFCX refers to by id. #[derive(Default)] struct Names { + file_sources: Vec, external_sources: HashMap< ( ifccad::IfccadExternalSourceId, @@ -732,7 +762,7 @@ struct Names { line_patterns: HashMap, styles: HashMap, style_handles: HashMap, - symbols: HashMap, + symbols: HashMap, blocks: HashMap, } @@ -841,6 +871,7 @@ fn add_in( } struct Writer<'a> { + file_sources: file_sources::State, external_sources: HashMap, #[cfg(feature = "mline-pilot")] roundtrip: Option<&'a IfccadRoundtripContext>, @@ -860,7 +891,7 @@ struct Writer<'a> { styles: HashMap, style_handles: HashMap, /// Symbol sources by the handle of their shape-file style. - symbols: HashMap, + symbols: HashMap, /// Block ids by lower-case name; `None` for blocks IFCX cannot hold. blocks: HashMap>, #[cfg(feature = "mline-pilot")] @@ -985,6 +1016,7 @@ impl Writer<'_> { }; } annotation_dimension::export_entity(self, entity, &mut kind)?; + file_sources::bind_entity_fonts(self, entity.common().handle, &mut kind)?; let common = entity.common(); let layer_id = match self.layers.get(&common.layer.to_ascii_lowercase()) { Some(id) => *id, diff --git a/src/ifcx/multi_leader/styles.rs b/src/ifcx/multi_leader/styles.rs index 1bfd873..c5b0b0d 100644 --- a/src/ifcx/multi_leader/styles.rs +++ b/src/ifcx/multi_leader/styles.rs @@ -62,6 +62,7 @@ pub(in crate::ifcx) fn export(writer: &mut Writer) -> Result<(), Error> { .ok_or_else(|| { annotation::invalid("MLeader style default text contains unsupported formatting") })?; + file_sources::bind_default_fonts(writer, source.handle, &mut style.default_m_text)?; style.text_always_left = source.text_always_left; style.block_scale_enabled = source.enable_block_scale; style.block_rotation_enabled = source.enable_block_rotation; @@ -149,10 +150,22 @@ pub(in crate::ifcx) fn import( style.block_content_scale_y = common.block_scale.y; style.block_content_scale_z = common.block_scale.z; style.scale_factor = common.scale_factor; + let mut default_text = source.default_m_text.clone(); + file_fonts::formats( + &mut default_text.character_format, + &mut default_text.content, + |font, _| { + *font = file_sources::materialize_font(drawing, font)?; + if font.primary_source.is_some() { + font.cad_font_name = font.cad_font_name.take().map(|p| p.replace('\\', "/")); + } + Ok(()) + }, + )?; style.default_text = text::emit_mtext( - &source.default_m_text.character_format, - &source.default_m_text.paragraph_format, - &source.default_m_text.content, + &default_text.character_format, + &default_text.paragraph_format, + &default_text.content, ); style.text_always_left = source.text_always_left; style.enable_block_scale = source.block_scale_enabled; diff --git a/src/ifcx/plot_styles.rs b/src/ifcx/plot_styles.rs index d2e5d7f..a76f116 100644 --- a/src/ifcx/plot_styles.rs +++ b/src/ifcx/plot_styles.rs @@ -1,5 +1,7 @@ use acadrust::objects::{Layout, ObjectType, PlaceHolder}; -use ifccad::{IfccadPlotStyle as Style, IfccadPlotStyleSource, IfccadPlotStyleTableKind as Kind}; +use ifccad::{ + IfccadExternalSource, IfccadExternalSourceContent as Content, IfccadPlotStyle as Style, +}; use super::*; @@ -12,26 +14,28 @@ pub(super) fn validate_cad_bindings(drawing: &IfccadDocument) -> Result<(), Erro .map(|layout| (layout.id, layout.name.as_str())), ); validate_cad_sources(layouts.filter_map(|(id, layout)| { - let source = styles.sources.get(styles.layout_sources.get(&id)?)?; + let id = styles.layout_sources.get(&id)?; + let source = drawing.external_sources.iter().find(|s| s.id == *id)?; Some((layout, source)) })) } pub(super) fn validate_cad_sources<'a>( - layouts: impl IntoIterator, + layouts: impl IntoIterator, ) -> Result<(), Error> { let mut names = BTreeMap::new(); for (layout, source) in layouts { - let Some(hash) = source.sha256.as_deref() else { + let Some(hash) = source.source.sha256() else { continue; }; + let path = file_sources::cad_path(source)?; let (first_layout, first_hash) = names - .entry(source.file_name.to_ascii_lowercase()) + .entry(path.to_ascii_lowercase()) .or_insert((layout, hash)); if *first_hash != hash { return Err(annotation::invalid(&format!( "Layouts {first_layout:?} and {layout:?} bind different plot style tables named {:?}. CAD requires distinct file names for these tables.", - source.file_name, + path, ))); } } @@ -43,48 +47,38 @@ pub(super) fn source_out(writer: &mut Writer<'_>, layout: &Layout, id: u64) { if name.is_empty() || name.eq_ignore_ascii_case("None") { return; } - let (kind, extension) = if writer.document.header.plotstyle_mode { - (Kind::Ctb, "ctb") + let (content, extension) = if writer.document.header.plotstyle_mode { + (Content::Ctb { sha256: None }, "ctb") } else { - (Kind::Stb, "stb") + (Content::Stb { sha256: None }, "stb") }; - let valid_name = !name - .chars() - .any(|ch| ch.is_control() || matches!(ch, '/' | '\\' | ':')) - && name.rsplit_once('.').is_some_and(|(stem, ext)| { - !stem.trim().is_empty() - && !matches!(stem, "." | "..") - && ext.eq_ignore_ascii_case(extension) - }); - if !valid_name { + if name.chars().any(char::is_control) + || !name.rsplit_once('.').is_some_and(|(stem, ext)| { + !stem.trim().is_empty() && ext.eq_ignore_ascii_case(extension) + }) + { writer.losses.located_loss( layout.handle, format!( - "Layout {:?}: incompatible or invalid plot-style table {name:?} omitted.", + "Layout {:?}: incompatible plot-style file {name:?}", layout.name ), ); return; } - let styles = &mut writer.drawing.plot_styles; - let source = styles - .sources - .iter() - .find_map(|(&id, source)| (source.kind == kind && source.file_name == *name).then_some(id)); - let source = source.unwrap_or_else(|| { - let id = styles.next_source_id; - styles.next_source_id += 1; - styles.sources.insert( - id, - IfccadPlotStyleSource { - kind, - file_name: name.clone(), - sha256: None, - }, - ); - id - }); - styles.layout_sources.insert(id, source); + match file_sources::register( + writer, + file_sources::Key::new(layout.handle, file_sources::Role::PlotStyle), + name, + content, + ) { + Ok(source) => { + writer.drawing.plot_styles.layout_sources.insert(id, source); + } + Err(error) => writer + .losses + .located_loss(layout.handle, format!("Layout {:?}: {error}", layout.name)), + } } pub(super) fn source_in( @@ -92,24 +86,28 @@ pub(super) fn source_in( id: u64, layout: &mut Layout, losses: &mut Losses, -) { - let styles = &drawing.plot_styles; - if let Some(source) = styles - .layout_sources - .get(&id) - .and_then(|id| styles.sources.get(id)) +) -> Result<(), Error> { + let Some(id) = drawing.plot_styles.layout_sources.get(&id) else { + return Ok(()); + }; + layout.plot_style_sheet = file_sources::source(drawing, *id) + .and_then(file_sources::cad_path) + .map_err(|error| Error::from(format!("Layout {:?}: {error}", layout.name)))?; + if drawing + .external_sources + .iter() + .find(|s| s.id == *id) + .is_some_and(|s| s.source.sha256().is_some()) { - layout.plot_style_sheet.clone_from(&source.file_name); - if source.sha256.is_some() { - losses.located_loss( - layout.handle, - format!( - "Layout {:?}: CAD stores the table name {:?} without its SHA-256.", - layout.name, source.file_name, - ), - ); - } + losses.located_loss( + layout.handle, + format!( + "Layout {:?}: CAD stores the plot file location without its SHA-256.", + layout.name + ), + ); } + Ok(()) } fn named_out(document: &Document, handle: Handle) -> Option