diff --git a/apps/cadcraft-cli/src/lib.rs b/apps/cadcraft-cli/src/lib.rs index 583c14c700..0c7a274f8a 100644 --- a/apps/cadcraft-cli/src/lib.rs +++ b/apps/cadcraft-cli/src/lib.rs @@ -56,6 +56,8 @@ fn install_io() { }); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records); + // What a DXF before 2007 leaves out for its proxies' string streams (#3229). + cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost); } /// `path` as text, for the engine and io calls that take a file name as a string. diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index bef6264d58..7a6a372f1c 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -130,6 +130,8 @@ mod web { }); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records); + // What a DXF before 2007 leaves out for its proxies' string streams (#3229). + cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost); let Some(canvas) = app_canvas() else { log::error!("missing "); return; diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index acd5b76df5..cfbf86d569 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -173,6 +173,8 @@ pub fn install_io() { }); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records); + // What a DXF before 2007 leaves out for its proxies' string streams (#3229). + cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost); } fn services() -> Services { diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 539982cb7e..6bbbe03227 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -131,17 +131,69 @@ pub fn sat_text_acis(u: &crate::Unknown, handle: Handle, stored: &std::collectio pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap { let stored = d.foreign.data_store_entities(); let mut out = BTreeMap::new(); - // The writer saves xrefs as references: their blocks (and `xref|` ones) hold nothing in the file. + for e in saved_entities(d) { + if let crate::EntityKind::Unknown(u) = &e.kind + && sat_text_acis(u, e.handle, &stored) + { + count(&mut out, &u.dxf_type); + } + } + out +} + +/// The entities a DXF file holds: model space, layouts and block definitions. The writer saves +/// xrefs as references: their blocks (and `xref|` ones) hold nothing in the file. +fn saved_entities(d: &crate::Drawing) -> impl Iterator> { let own_blocks = d.blocks.values().filter(|b| b.xref_path.is_none() && !xref_dependent(&b.name)); let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(own_blocks.map(|b| &b.entities)); - for e in stores.flat_map(|s| s.iter()) { + stores.flat_map(|s| s.iter()) +} + +/// Add one record of DXF type `kind` to `out`. +fn count(out: &mut BTreeMap, kind: &str) { + let n: &mut usize = out.entry(kind.to_ascii_uppercase()).or_default(); + *n = n.saturating_add(1); +} + +/// Whether a DXF type is a proxy (ACAD_PROXY_OBJECT, ACAD_PROXY_ENTITY). +pub fn is_proxy(kind: &str) -> bool { + let k = kind.trim(); + k.eq_ignore_ascii_case("ACAD_PROXY_OBJECT") || k.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") +} + +/// Whether a proxy's groups (after its type) give it a separate string stream: a size above 0 in +/// group 96 (2007) or 162 (2010 and later) after the `AcDbProxy…` marker. Before 2007 a proxy's +/// strings are part of its data, so a file of an earlier version has no form for one that keeps +/// them apart (#3229). +pub fn proxy_has_string_stream>(groups: impl IntoIterator) -> bool { + let mut own = false; + for (code, value) in groups { + let v = value.as_ref().trim(); + match code { + 100 => own = own || v.to_ascii_lowercase().starts_with("acdbproxy"), + 96 | 162 if own && v.parse::().is_ok_and(|n| n > 0) => return true, + _ => {} + } + } + false +} + +/// The proxies a DXF earlier than 2007 leaves out because they have a separate string stream +/// ([`proxy_has_string_stream`]), counted by DXF type. +pub fn proxies_dropped_before_2007(d: &crate::Drawing) -> BTreeMap { + let mut out = BTreeMap::new(); + let has_strings = |tags: &[RawTag]| proxy_has_string_stream(tags.iter().map(|t| (t.code, t.value.as_str()))); + for e in saved_entities(d) { if let crate::EntityKind::Unknown(u) = &e.kind - && sat_text_acis(u, e.handle, &stored) + && is_proxy(&u.dxf_type) + && has_strings(&u.tags) { - let n: &mut usize = out.entry(u.dxf_type.to_ascii_uppercase()).or_default(); - *n = n.saturating_add(1); + count(&mut out, &u.dxf_type); } } + for o in d.foreign.objects.iter().filter(|o| is_proxy(&o.kind) && has_strings(&o.tags)) { + count(&mut out, &o.kind); + } out } diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index 373e471bfe..b981e5fa69 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -8,7 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3}; use serde_json::{Value, json}; use super::super::curves::KW; -use super::super::file::{drops_unknown, new_folder, not_saved, not_saved_message, report_new_folder, report_not_saved}; +use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder}; use super::super::machines::{SelOutcome, SelectPhase}; use super::super::modify::erase_kept; use super::super::{CommandSpec, bad, point_param, str_param, targets}; @@ -44,13 +44,13 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string(); let base = point_param(p, "base"); let folder = new_folder(&path); - let (entities, bytes, lost) = match str_param(p, "name") { + let (entities, bytes, lost, version) = match str_param(p, "name") { Some(name) => write(s, "wblock", &path, Source::Block(name, base))?, None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?, }; let mut r = json!({ "path": path, "entities": entities, "bytes": bytes }); report_new_folder(s, &mut r, folder); - report_not_saved(s, &mut r, &lost); + report_lost(s, &mut r, &path, version, &lost); Ok(r) } @@ -61,7 +61,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string(); let base = point_param(p, "base"); let folder = new_folder(&path); - let (entities, bytes, lost) = match str_param(p, "name") { + let (entities, bytes, lost, version) = match str_param(p, "name") { Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?, None => { let hs = targets(s, p)?; @@ -76,16 +76,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result { }; let mut r = json!({ "path": path, "entities": entities, "bytes": bytes }); report_new_folder(s, &mut r, folder); - report_not_saved(s, &mut r, &lost); + report_lost(s, &mut r, &path, version, &lost); Ok(r) } -/// Write `what` to `path` through the io hooks; the objects written, the file's size and what a -/// DWG file left out, for the caller to report as a save does. The +/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the +/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and +/// the version it was written at, for the caller to report as a save does. The /// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units /// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and /// scaled on insert, and its defaults (text size, current styles, annotation scales). -fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap)> { +fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap, Version)> { let src = s.doc()?; // The base point becomes the written drawing's origin: by default 0,0 for objects and the // block's base point for a block. @@ -106,13 +107,15 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi // Through a temporary file, as SAVE writes, so a failed write keeps the file it replaces. #[cfg(not(target_arch = "wasm32"))] crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() }; - Ok((d.model.len(), bytes.len(), lost)) + // The written drawing's own version: the writer is given no other. + let version = own_version(&d, path); + let lost = lost_writing(&d, path, version); + Ok((d.model.len(), bytes.len(), lost, version)) } -/// Say on the command line what the written DWG file left out. -fn echo_not_saved(s: &mut Session, lost: &BTreeMap) { - if let Some(msg) = not_saved_message(lost) { +/// Say on the command line what the file written at `path` and `version` left out. +fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap) { + if let Some(msg) = lost_message(path, version, lost) { s.echo(msg); } } @@ -331,7 +334,7 @@ impl DashWblockM { fn write(&self, s: &mut Session, what: Source) -> Result { match write(s, "-wblock", &self.path, what) { - Ok((.., lost)) => echo_not_saved(s, &lost), + Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost), Err(e) => s.echo(e.to_string()), } Ok(Step::Done) @@ -342,8 +345,8 @@ impl DashWblockM { return Ok(Step::Done); } match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) { - Ok((.., lost)) => { - echo_not_saved(s, &lost); + Ok((.., lost, version)) => { + echo_not_saved(s, &self.path, version, &lost); erase(s, hs)?; } Err(e) => s.echo(e.to_string()), diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index cb28c2d45a..e0b1c7faeb 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -83,6 +83,31 @@ pub fn object_records() -> Option { OBJECT_RECORDS.get().copied() } +/// What a DXF of a version before 2007 leaves out of a drawing because it has no form for a +/// proxy's separate string stream, counted by DXF type (installed by the app with the DXF writer, +/// a lower layer, which finds it by writing; see `cadcraft_io::proxies_lost`). Without it the +/// proxies themselves are counted ([`cadcraft_doc::foreign::proxies_dropped_before_2007`]). +pub type ProxiesLost = fn(&Drawing, Version) -> std::collections::BTreeMap; + +static PROXIES_LOST: OnceLock = OnceLock::new(); + +pub fn set_proxies_lost(f: ProxiesLost) { + let _ = PROXIES_LOST.set(f); +} + +/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from +/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file). +fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap { + if version >= Version::R2007 { + return Default::default(); + } + let d = d.committed(); + match PROXIES_LOST.get() { + Some(f) => f(&d, version), + None => cadcraft_doc::foreign::proxies_dropped_before_2007(&d), + } +} + /// COMPARE (drawing comparison). pub mod compare; @@ -776,14 +801,22 @@ fn run_saveas(s: &mut Session, p: &Value) -> Result { /// The version a drawing is saved in at `path` when none is asked for: its `$ACADVER` (2018 by /// default), and for DWG at least 2004 (the io layer's rule: R2000 DWG has no true colours). fn drawing_version(s: &Session, path: &str) -> Version { - let v = s - .state() - .ok() - .and_then(|st| st.drawing().header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver)) - .unwrap_or_default(); + let v = s.state().ok().and_then(|st| acadver(st.drawing())).unwrap_or_default(); + if is_dxf(path) { v } else { v.max(Version::R2004) } +} + +/// The version `d` is saved in at `path` when none is asked for, as [`drawing_version`] says for +/// the active drawing. +pub(crate) fn own_version(d: &Drawing, path: &str) -> Version { + let v = acadver(d).unwrap_or_default(); if is_dxf(path) { v } else { v.max(Version::R2004) } } +/// The version `d`'s `$ACADVER` names. +fn acadver(d: &Drawing) -> Option { + d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver) +} + /// `document.switch index`: require the index, cancel the running command, activate that drawing and bump the epoch even if it was already active (screenshot identity). fn run_switch(s: &mut Session, p: &Value) -> Result { let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("document.switch", "`index` is required"))? as usize; @@ -810,7 +843,11 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result { if drops_unknown(format!("drawing.{fmt}")) { report_not_saved(s, &mut r, &lost); } else if version >= Version::R2013 && is_dxf_file(format!("drawing.{fmt}")) { - report_sat_text_dropped(s, &mut r); + let lost = host_sat_text_dropped(s); + report_sat_text_dropped(s, &mut r, &lost); + } else if version < Version::R2007 && is_dxf_file(format!("drawing.{fmt}")) { + let lost = host_proxies_lost(s, version); + report_proxies_dropped(s, &mut r, &lost); } Ok(r) } @@ -891,8 +928,11 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap) -> Op pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap { let version = drawing_version(s, path); if is_dxf_file(path) && version >= Version::R2013 { - // The drawing a file holds: the host while the Block Editor is open. - return s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default(); + return host_sat_text_dropped(s); + } + if is_dxf_file(path) && version < Version::R2007 { + // Proxies whose strings such a file can't hold, and what goes with them (#3229). + return host_proxies_lost(s, version); } if !drops_unknown(path) { return Default::default(); @@ -900,18 +940,70 @@ pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap std::collections::BTreeMap { + s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default() +} + +/// What a DXF of `version` before 2007 leaves out of the drawing a save writes (the host while +/// the Block Editor is open) for its proxies' string streams (#3229). +fn host_proxies_lost(s: &Session, version: Version) -> std::collections::BTreeMap { + s.state().map(|st| proxies_lost(st.drawing(), version)).unwrap_or_default() +} + +/// What a file at `path` leaves out of `d`, written at `version`: empty when it keeps everything. +pub(crate) fn lost_writing(d: &Drawing, path: &str, version: Version) -> std::collections::BTreeMap { + if !is_dxf_file(path) { + return if drops_unknown(path) { not_saved_as(d, version) } else { Default::default() }; + } + if version >= Version::R2013 { cadcraft_doc::foreign::sat_text_dropped(d) } else { proxies_lost(d, version) } +} + +/// Report what the file `path`, just written from the active document (what EXPORT writes: the +/// block while the Block Editor is open) at its own version, left out. pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) { - if is_dxf_file(path) { - if drawing_version(s, path) >= Version::R2013 { - report_sat_text_dropped(s, r); - } - } else { - let lost = loss_on_save(s, path); - report_not_saved(s, r, &lost); + let Ok(d) = s.doc() else { return }; + let version = own_version(d, path); + let lost = lost_writing(d, path, version); + report_lost(s, r, path, version, &lost); +} + +/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`), +/// in the words for that kind of file, and list it in the result's `notSaved`. +pub(crate) fn report_lost(s: &mut Session, r: &mut Value, path: &str, version: Version, lost: &std::collections::BTreeMap) { + match lost_message(path, version, lost) { + Some(msg) => s.echo(msg), + None => return, + } + if let Some(o) = r.as_object_mut() { + o.insert("notSaved".into(), json!(lost)); } } +/// The command-line warning for what a file at `path` written at `version` left out, or `None` +/// when it kept everything. +pub(crate) fn lost_message(path: &str, version: Version, lost: &std::collections::BTreeMap) -> Option { + if !is_dxf_file(path) { + return not_saved_message(lost); + } + if lost.is_empty() { + return None; + } + let list: Vec = lost.iter().map(|(t, n)| format!("{n} {t}")).collect(); + Some(if version >= Version::R2013 { + format!( + "Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}", + list.join(", ") + ) + } else { + format!( + "Not saved in the DXF file (proxies that keep their strings apart from their data, which DXF before 2007 can't hold, and the objects that go with them; save as 2007 or later to keep them): {}", + list.join(", ") + ) + }) +} + /// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG /// bridge drops types it doesn't know); DXF writes them back as read. pub fn drops_unknown(path: impl AsRef) -> bool { @@ -930,20 +1022,8 @@ fn is_dxf_file(path: impl AsRef) -> bool { /// Say on the command line which solid modeler entities a DXF of 2013 or later left out because /// they hold SAT-text ACIS data, which such files keep in a data store instead (#2334). -fn report_sat_text_dropped(s: &mut Session, r: &mut Value) { - // The drawing a file holds: the host while the Block Editor is open. - let lost = s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default(); - if lost.is_empty() { - return; - } - let list: Vec = lost.iter().map(|(t, n)| format!("{n} {t}")).collect(); - s.echo(format!( - "Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}", - list.join(", ") - )); - if let Some(o) = r.as_object_mut() { - o.insert("notSaved".into(), json!(lost)); - } +fn report_sat_text_dropped(s: &mut Session, r: &mut Value, lost: &std::collections::BTreeMap) { + report_lost(s, r, "drawing.dxf", Version::R2013, lost); } /// The folder a write to `path` has to create, asked before writing so it can be reported after. @@ -977,6 +1057,12 @@ pub(super) fn report_not_saved(s: &mut Session, r: &mut Value, lost: &std::colle } } +/// Say on the command line which proxies a DXF earlier than 2007 left out (`lost`) because their +/// strings are kept apart from their data, which those versions have no form for (#3229). +fn report_proxies_dropped(s: &mut Session, r: &mut Value, lost: &std::collections::BTreeMap) { + report_lost(s, r, "drawing.dxf", Version::R2000, lost); +} + /// Save, then report the entities the file couldn't keep (nothing is dropped silently). fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> Result, asked: Option) -> Result { // What the file will hold depends on the version it is saved as (the data store from 2013). @@ -990,7 +1076,11 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) { report_not_saved(s, &mut r, &lost); } else if version >= Version::R2013 && r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) { - report_sat_text_dropped(s, &mut r); + let lost = host_sat_text_dropped(s); + report_sat_text_dropped(s, &mut r, &lost); + } else if version < Version::R2007 && r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) { + let lost = host_proxies_lost(s, version); + report_proxies_dropped(s, &mut r, &lost); } if r.get("path").and_then(Value::as_str).is_some_and(is_drawing_file) { report_fonts(s, &mut r); diff --git a/crates/engine/tests/proxy_loss_real_writer.rs b/crates/engine/tests/proxy_loss_real_writer.rs new file mode 100644 index 0000000000..5ad1a03e9e --- /dev/null +++ b/crates/engine/tests/proxy_loss_real_writer.rs @@ -0,0 +1,149 @@ +//! What a DXF before 2007 leaves out for its proxies' string streams, counted by the real DXF +//! writer (#3229): only what 2007 would keep, from the drawing the command writes. In its own +//! test binary because it installs the real io hooks for the whole process. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_proxies_lost, set_write_as}; +use cadcraft_engine::doc::Drawing; +use serde_json::{Value, json}; +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + +/// The real reader and writer, and the real proxy-loss count. +fn install() { + set_io(IoHooks { + read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); + set_write_as(|d, name, o: &SaveAs| { + cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) + }); + set_proxies_lost(cadcraft_io::proxies_lost); +} + +/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes. +fn proxy(handle: &str, owner: &str, strings: &str, class: &str) -> Vec<(String, String)> { + let p = |c: &str, v: &str| (c.to_string(), v.to_string()); + vec![ + p("0", "ACAD_PROXY_ENTITY"), + p("5", handle), + p("330", owner), + p("100", "AcDbEntity"), + p("8", "0"), + p("100", "AcDbProxyEntity"), + p("90", "498"), + p("91", class), + p("95", "393245"), + p("70", "0"), + p("162", strings), + p("161", "16"), + p("310", "AABB"), + ] +} + +fn pairs(text: &str) -> Vec<(String, String)> { + let lines: Vec<&str> = text.lines().collect(); + lines.chunks(2).map(|c| (c[0].trim().to_string(), c.get(1).map_or(String::new(), |v| v.trim().to_string()))).collect() +} + +/// A drawing with `$ACADVER` `acadver` read from a DXF holding the class WIDGETX and, in model +/// space, the proxies `entities` gives (each from the model space block record's handle). +fn drawing(acadver: &str, entities: impl Fn(&str) -> Vec>) -> Drawing { + let mut d = Drawing::new_imperial(); + d.header.set_str("ACADVER", "AC1024"); + let text = String::from_utf8(cadcraft_io::write(&d, "p.dxf").unwrap()).unwrap(); + let mut p = pairs(&text); + let g = |c: &str, v: &str| (c.to_string(), v.to_string()); + let classes = p.iter().position(|q| q.0 == "2" && q.1 == "CLASSES").unwrap() + 1; + let class = + [g("0", "CLASS"), g("1", "WIDGETX"), g("2", "AcDbWidgetX"), g("3", "ObjectDBX Classes"), g("90", "4095"), g("280", "0"), g("281", "1")]; + p.splice(classes..classes, class); + // The model space block record: the owner of model space entities. + let record_end = |i: usize| i + 1 + p[i + 1..].iter().position(|q| q.0 == "0").unwrap_or(p.len() - i - 1); + let ms = (0..p.len()) + .filter(|&i| p[i].0 == "0" && p[i].1 == "BLOCK_RECORD") + .find(|&i| p[i..record_end(i)].iter().any(|q| q.0 == "2" && q.1.eq_ignore_ascii_case("*Model_Space"))) + .unwrap(); + let owner = p[ms..].iter().find(|q| q.0 == "5").unwrap().1.clone(); + let ents = p.iter().position(|q| q.0 == "2" && q.1 == "ENTITIES").unwrap(); + let end = ents + p[ents..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap(); + p.splice(end..end, entities(&owner).into_iter().flatten()); + let bytes: String = p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect(); + let mut d = cadcraft_io::read(bytes.as_bytes(), "p.dxf").unwrap(); + d.header.set_str("ACADVER", acadver); + d +} + +/// Two proxies with string streams, one whose class number names no class (no version writes +/// it), and one without: before 2007 only the first one is lost to the string stream. +fn three_proxies(owner: &str) -> Vec> { + vec![proxy("AAA1", owner, "8", "500"), proxy("AAA2", owner, "8", "777"), proxy("AAA3", owner, "0", "500")] +} + +fn not_saved(r: &Value) -> Value { + r.get("notSaved").cloned().unwrap_or(Value::Null) +} + +#[test] +fn a_proxy_no_version_writes_is_not_reported() { + install(); + let dir = TempDir::new("proxy-loss"); + let mut s = Session::empty(); + s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None); + let path = dir.path_str("out.dxf"); + let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap(); + assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "{:?}", s.log); + let r = s.execute("saveas", &json!({ "path": path, "version": 2007 })).unwrap(); + assert_eq!(not_saved(&r), Value::Null); +} + +#[test] +fn export_reports_the_drawing_it_writes() { + // In the Block Editor EXPORT writes the block, which holds no proxy: nothing is lost. + install(); + let mut s = Session::empty(); + s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None); + let r = s.execute("export", &json!({ "format": "dxf" })).unwrap(); + assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 })); + s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + let line = s.execute("entities", &json!({ "type": "LINE" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string(); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [line], "keep": "convert" })).unwrap(); + s.execute("bedit", &json!({ "name": "B" })).unwrap(); + let n = s.log.len(); + let r = s.execute("export", &json!({ "format": "dxf" })).unwrap(); + assert_eq!(not_saved(&r), Value::Null, "{:?}", &s.log[n..]); +} + +#[test] +fn a_reference_edit_working_copy_is_not_counted_twice() { + install(); + let dir = TempDir::new("proxy-loss"); + let mut s = Session::empty(); + s.open_drawing(drawing("AC1015", |o| vec![proxy("AAA1", o, "8", "500")]), "proxy.dxf", None); + s.execute("block", &json!({ "name": "W", "base": [0, 0], "handles": ["AAA1"], "keep": "convert" })).unwrap(); + let ins = s.execute("entities", &json!({ "type": "INSERT" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string(); + let path = dir.path_str("before.dxf"); + let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap(); + assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "in the block"); + s.execute("refedit", &json!({ "handle": ins })).unwrap(); + // Saves wait for REFCLOSE; the QSAVE question and `document.bytes` count the committed drawing. + let r = s.execute("document.bytes", &json!({ "format": "dxf", "version": 2000 })).unwrap(); + assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "the working copy isn't written"); + assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&s, "during.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect()); +} + +#[test] +fn dash_wblock_of_the_whole_drawing_reports_a_pre_2007_dxf() { + install(); + let dir = TempDir::new("proxy-loss"); + let mut s = Session::empty(); + s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None); + let path = dir.path_str("whole.dxf").replace('\\', "/"); + s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"\" \"*\")")).unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert!(std::path::Path::new(&path).exists()); + assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.ends_with("1 ACAD_PROXY_ENTITY")), "{:?}", s.log); +} diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 980f926760..57e8693a91 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -302,3 +302,74 @@ fn ole_objects_are_not_reported() { assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1), ("ole2frame".to_string(), 1)].into_iter().collect(), "{v:?}"); } } + +/// A proxy entity (as a 2010 file has it) whose string stream is `strings` long (group 162). +fn proxy_entity(strings: &str) -> EntityKind { + let tags = [(8, "0"), (100, "AcDbProxyEntity"), (90, "498"), (91, "500"), (162, strings), (161, "16"), (310, "AABB")]; + EntityKind::Unknown(Unknown { + dxf_type: "ACAD_PROXY_ENTITY".into(), + tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(), + }) +} + +/// A DXF before 2007 has no form for a proxy's separate string stream: the writer leaves such a +/// proxy out, and the save says so instead of dropping it silently (#3229). +#[test] +fn a_dxf_before_2007_reports_the_proxies_it_leaves_out() { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); + // SAVEAS at a chosen version goes through this hook (each test may run in its own process). + set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec())); + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap(); + d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "proxy.dxf", None); + let path = std::env::temp_dir().join(format!("cadcraft-proxy-r2000-{}.dxf", std::process::id())); + let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2000 })).unwrap(); + assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings"); + assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log); + let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2007 })).unwrap(); + let _ = std::fs::remove_file(&path); + assert!(r.get("notSaved").is_none(), "2007 keeps it"); +} + +/// The interactive QSAVE asks before a pre-2007 DXF replaces a file and leaves such proxies out, +/// with the same list (#3229). +#[test] +fn a_pre_2007_dxf_proxy_loss_is_known_before_saving() { + use cadcraft_engine::cmd::file::loss_on_save; + let drawing = |acadver: &str| { + let mut d = Drawing::new_imperial(); + d.header.set_str("ACADVER", acadver); + d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap(); + d + }; + let mut s = Session::empty(); + s.open_drawing(drawing("AC1015"), "proxy.dxf", None); + assert_eq!(loss_on_save(&s, "proxy.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect()); + s.open_drawing(drawing("AC1021"), "proxy.dxf", None); + assert!(loss_on_save(&s, "proxy.dxf").is_empty(), "2007 keeps it"); +} + +/// EXPORT writes a DXF at the drawing's own version: before 2007 it leaves the same proxies out +/// and says so, like a save (#3229). +#[test] +fn exporting_a_dxf_before_2007_reports_the_proxies_it_leaves_out() { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); + let drawing = |acadver: &str| { + let mut d = Drawing::new_imperial(); + d.header.set_str("ACADVER", acadver); + d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap(); + d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap(); + d + }; + let mut s = Session::empty(); + s.open_drawing(drawing("AC1015"), "proxy.dxf", None); + let r = s.execute("export", &json!({ "format": "dxf" })).unwrap(); + assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings"); + assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log); + let mut s = Session::empty(); + s.open_drawing(drawing("AC1021"), "proxy.dxf", None); + let r = s.execute("export", &json!({ "format": "dxf" })).unwrap(); + assert!(r.get("notSaved").is_none(), "2007 keeps it"); +} diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 6dd45b8459..f08d4d8618 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -16,7 +16,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; -use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number}; +use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream}; use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown}; use craft_dxf::{Section, Tag}; @@ -941,12 +941,15 @@ fn unknown_handles(d: &Drawing) -> HashSet { } /// Put the drawing's foreign data back into a written file's tags (see the module comment). -pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap>, modern: bool) { +/// `strings`: whether the file has a form for a proxy's separate string stream (a DXF of 2007 or +/// later, or the DWG bridge); without one such a proxy is left out (#3229). Returns the foreign +/// objects written, by their handles in the drawing (the file gives them new ones). +pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap>, modern: bool, strings: bool) -> HashSet { let f = d.foreign.as_ref(); let unknown = unknown_handles(d); let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect(); if f.is_empty() && unknown.is_empty() && xd.is_empty() { - return; + return HashSet::new(); } let recs = written_records(tags); let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); @@ -969,6 +972,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap, d: &Drawing, reactors: &HashMap = t.iter().map(|x| (x.code, x.str())).collect(); + let groups: Vec<(i32, &str)> = groups.iter().map(|(c, v)| (*c, v.as_str())).collect(); + if no_room(&groups) { + return false; + } + let Some(n) = renumber(class_number(groups.iter().copied())) else { return false }; set_class_number(t, n); true }); @@ -1027,8 +1037,11 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect(); let kept = |h: &str| kept.get(h) == Some(&true); - for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) - { + let dropped = |o: &ForeignObject| { + let groups: Vec<(i32, &str)> = o.tags.iter().map(|r| (r.code, r.value.as_str())).collect(); + no_room(&groups) || renumber(class_number(groups.iter().copied())).is_none() + }; + for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && dropped(o)) { alive_memo.insert(o.handle.hex(), false); } for o in &f.objects { @@ -1119,6 +1132,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap String { /// The drawing's DXF tags, declaring `version` in `$ACADVER`. pub fn tags(d: &Drawing, version: Version) -> Vec { - tags_for(d, version, version, version < Version::R2004) + tags_kept(d, version).0 +} + +/// [`tags`], with the foreign objects the file keeps, by their handles in the drawing. +fn tags_kept(d: &Drawing, version: Version) -> (Vec, std::collections::HashSet) { + let (mut tags, kept) = sections::tags_kept_for(d, version, version, version < Version::R2004); + // Kept proxies in this version's layout (#3229). Not for the DWG bridge, whose writer reads + // them in the layout of the DWG they came from. + proxy::proxy_layout(&mut tags, version); + (tags, kept) } /// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG diff --git a/crates/io/src/dxf_write/proxy.rs b/crates/io/src/dxf_write/proxy.rs new file mode 100644 index 0000000000..cece4fae63 --- /dev/null +++ b/crates/io/src/dxf_write/proxy.rs @@ -0,0 +1,268 @@ +//! Kept proxy records (ACAD_PROXY_OBJECT, ACAD_PROXY_ENTITY) in the group layout of the DXF version +//! written (#3229). Proxies are kept with the groups they were read with, and the DWG bridge +//! brings them in the DWG's own version's layout, so a 2010 drawing saved as an R2000 DXF wrote +//! 2010 groups that R2000 readers reject ("Out of range"). +//! +//! The layouts, after the `AcDbProxyObject` / `AcDbProxyEntity` marker: +//! - R2000 and R2004 (DXF Reference): 92 graphics size, 93 data size in bits, 95 the drawing +//! format (low word the DWG version, high word the maintenance release), 70 the data format. +//! - 2007: as R2000, with 96 for the size of the separate string stream. A proxy whose string +//! stream isn't empty has no earlier form: the raw writer leaves it out of an earlier file and +//! the save says so. +//! - 2010 and 2013: 160 graphics size, 161 data size, 162 string stream size. +//! - 2018 and later: as 2010, with the drawing format split into 71 (DWG version) and 97 +//! (maintenance release). + +use std::collections::{BTreeMap, HashSet}; + +use cadcraft_doc::foreign::is_proxy; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use craft_dxf::{Tag, Version}; + +/// What a DXF of `version` leaves out of `d` because a file earlier than 2007 has no form for a +/// proxy's separate string stream, counted by DXF type: those proxies, and the objects that go +/// with them (their extension dictionary and its records) because nothing written owns them any +/// more. Found by writing the drawing as 2007 and as `version` and comparing what each keeps, so a proxy that no version writes (its class isn't written, or no written block holds +/// it) is not counted, and nothing that stays in the file is. Empty from 2007 on (#3229). +pub fn proxies_lost(d: &Drawing, version: Version) -> BTreeMap { + // Writing twice only for a drawing that holds such a proxy at all. + if version >= Version::R2007 || cadcraft_doc::foreign::proxies_dropped_before_2007(d).is_empty() { + return BTreeMap::new(); + } + // Unknown entities keep their handles in the file; kept foreign objects get new ones, so + // the writer names those by their handles in the drawing. + let (tags_2007, objects_2007) = super::tags_kept(d, Version::R2007); + let (tags_here, objects_here) = super::tags_kept(d, version); + let (entities_2007, entities_here) = (written_handles(&tags_2007), written_handles(&tags_here)); + let lost = |h: Handle| entities_2007.contains(&h) && !entities_here.contains(&h); + let lost_object = |h: Handle| objects_2007.contains(&h) && !objects_here.contains(&h); + let mut out = BTreeMap::new(); + let mut count = |kind: &str| { + let n: &mut usize = out.entry(kind.trim().to_ascii_uppercase()).or_default(); + *n = n.saturating_add(1); + }; + let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities)); + for e in stores.flat_map(|s| s.iter()) { + if let EntityKind::Unknown(u) = &e.kind + && lost(e.handle) + { + count(&u.dxf_type); + } + } + for o in d.foreign.objects.iter().filter(|o| lost_object(o.handle)) { + count(&o.kind); + } + out +} + +/// The handles of the records in written `tags` (group 5, and 105 for a DIMSTYLE). +fn written_handles(tags: &[Tag]) -> HashSet { + tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(t.str().trim())).collect() +} + +/// What a proxy group holds, whatever version's code it was read with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Field { + /// Size of the graphics data in bytes (92, 160). + Graphics, + /// Size of the object or entity data in bits (93, 161). + Data, + /// Size of the separate string stream (96, 162), from the 2007 format. + Strings, +} + +fn field(code: i32) -> Option { + match code { + 92 | 160 => Some(Field::Graphics), + 93 | 161 => Some(Field::Data), + 96 | 162 => Some(Field::Strings), + _ => None, + } +} + +/// The code `version` writes `f` with; `None` when it has none (a string stream before 2007). +fn code_for(f: Field, version: Version) -> Option { + let late = version >= Version::R2010; + match f { + Field::Graphics => Some(if late { 160 } else { 92 }), + Field::Data => Some(if late { 161 } else { 93 }), + Field::Strings if late => Some(162), + Field::Strings => (version >= Version::R2007).then_some(96), + } +} + +/// Rewrite every proxy record in `tags` into `version`'s layout. Other records are untouched. +pub(super) fn proxy_layout(tags: &mut Vec, version: Version) { + if !tags.iter().any(|t| t.code == 0 && is_proxy(&t.str())) { + return; + } + let src = std::mem::take(tags); + let mut out = Vec::with_capacity(src.len()); + let mut rest = src.as_slice(); + while let Some((first, tail)) = rest.split_first() { + // One record: its type, and its groups up to the next record. + let end = tail.iter().position(|t| t.code == 0).unwrap_or(tail.len()); + let (body, next) = tail.split_at(end); + out.push(first.clone()); + if first.code == 0 && is_proxy(&first.str()) { + convert(body, version, &mut out); + } else { + out.extend_from_slice(body); + } + rest = next; + } + *tags = out; +} + +/// One proxy record's groups (after its type) in `version`'s layout. Only the groups after the +/// proxy subclass marker change: before it, an entity's common groups have a 92 and a 160 of +/// their own. +fn convert(body: &[Tag], version: Version, out: &mut Vec) { + let marker = body.iter().position(|t| t.code == 100 && t.str().trim().to_ascii_lowercase().starts_with("acdbproxy")); + let Some(marker) = marker else { + out.extend_from_slice(body); + return; + }; + let (common, own) = body.split_at(marker.saturating_add(1)); + out.extend_from_slice(common); + let format = drawing_format(own); + let mut format_written = false; + for t in own { + if matches!(t.code, 95 | 71 | 97) { + // The drawing format goes where the first of its groups was, in this version's form. + if !format_written && let Some(f) = format { + if version >= Version::R2018 { + out.push(Tag::i(71, f & 0xFFFF)); + out.push(Tag::i(97, (f >> 16) & 0xFFFF)); + } else { + out.push(Tag::i(95, f)); + } + } + format_written = true; + continue; + } + match field(t.code) { + Some(f) => { + if let Some(code) = code_for(f, version) { + out.push(Tag { code, value: t.value.clone() }); + } + } + None => out.push(t.clone()), + } + } +} + +/// The proxy's drawing format (DWG version in the low word, maintenance release in the high +/// word), from a 95 or from 71 and 97. +fn drawing_format(own: &[Tag]) -> Option { + let get = |code| own.iter().find(|t| t.code == code).map(|t| t.value.as_i64()); + get(95).map(|f| f & 0xFFFF_FFFF).or_else(|| get(71).map(|lo| ((get(97).unwrap_or(0) & 0xFFFF) << 16) | (lo & 0xFFFF))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record(groups: &[(i32, &str)]) -> Vec { + groups.iter().map(|(c, v)| Tag::s(*c, *v)).collect() + } + + fn codes(tags: &[Tag]) -> Vec<(i32, String)> { + tags.iter().map(|t| (t.code, t.str())).collect() + } + + /// A proxy object as a 2010 DWG brings it (the record in the report). + fn from_2010() -> Vec { + record(&[ + (0, "ACAD_PROXY_OBJECT"), + (5, "2CBA9C"), + (100, "AcDbProxyObject"), + (90, "499"), + (91, "521"), + (95, "393245"), + (70, "0"), + (162, "0"), + (161, "303"), + (310, "00FF"), + (340, "1F"), + (94, "0"), + (0, "ENDSEC"), + ]) + } + + fn own(tags: &[Tag]) -> Vec<(i32, String)> { + codes(tags).into_iter().skip(3).take_while(|(c, _)| *c != 0).collect() + } + + fn s(c: i32, v: &str) -> (i32, String) { + (c, v.to_string()) + } + + #[test] + fn a_2010_proxy_takes_each_versions_layout() { + // 393245 = 0x6001D: DWG version 29, maintenance release 6. + let mut t = from_2010(); + proxy_layout(&mut t, Version::R2000); + assert_eq!(own(&t), [s(90, "499"), s(91, "521"), s(95, "393245"), s(70, "0"), s(93, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]); + let mut t = from_2010(); + proxy_layout(&mut t, Version::R2007); + assert_eq!( + own(&t), + [s(90, "499"), s(91, "521"), s(95, "393245"), s(70, "0"), s(96, "0"), s(93, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")] + ); + let mut t = from_2010(); + proxy_layout(&mut t, Version::R2010); + assert_eq!(codes(&t), codes(&from_2010()), "already 2010"); + let mut t = from_2010(); + proxy_layout(&mut t, Version::R2018); + assert_eq!( + own(&t), + [s(90, "499"), s(91, "521"), s(71, "29"), s(97, "6"), s(70, "0"), s(162, "0"), s(161, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")] + ); + // And back from the 2018 form. + proxy_layout(&mut t, Version::R2004); + assert_eq!(own(&t), [s(90, "499"), s(91, "521"), s(95, "393245"), s(70, "0"), s(93, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]); + // The ENDSEC after it is untouched. + assert_eq!(t.last().map(Tag::str).as_deref(), Some("ENDSEC")); + } + + #[test] + fn an_entitys_common_groups_stay() { + // Before the subclass marker, 92 and 160 are the entity's own proxy graphics. + let mut t = record(&[ + (0, "ACAD_PROXY_ENTITY"), + (100, "AcDbEntity"), + (92, "4"), + (310, "AA"), + (100, "AcDbProxyEntity"), + (90, "498"), + (91, "500"), + (160, "8"), + (310, "BB"), + (161, "16"), + (310, "CC"), + (94, "0"), + (95, "393245"), + (70, "0"), + ]); + proxy_layout(&mut t, Version::R2000); + let c: Vec = t.iter().map(|x| x.code).collect(); + assert_eq!(c, [0, 100, 92, 310, 100, 90, 91, 92, 310, 93, 310, 94, 95, 70]); + } + + #[test] + fn other_records_and_hostile_values_are_safe() { + let mut t = record(&[(0, "LINE"), (95, "1"), (100, "AcDbProxyObject"), (93, "1")]); + let before = codes(&t); + proxy_layout(&mut t, Version::R2018); + assert_eq!(codes(&t), before, "not a proxy"); + // A huge or negative drawing format doesn't overflow. + let mut t = record(&[(0, "ACAD_PROXY_OBJECT"), (100, "AcDbProxyObject"), (95, "-1"), (71, "99999999999")]); + proxy_layout(&mut t, Version::R2018); + assert_eq!(codes(&t), [s(0, "ACAD_PROXY_OBJECT"), s(100, "AcDbProxyObject"), s(71, "65535"), s(97, "65535")]); + // No marker: left as it is. + let mut t = record(&[(0, "ACAD_PROXY_OBJECT"), (93, "1")]); + proxy_layout(&mut t, Version::R2018); + assert_eq!(codes(&t), [s(0, "ACAD_PROXY_OBJECT"), s(93, "1")]); + } +} diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 24c877b729..c51233ca9f 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -907,6 +907,11 @@ fn plan_dimension_associations(d: &Drawing, all_spaces: &[&EntityStore], w: &mut /// file ends up in: `version`, or the DWG version the bridge writes) has. /// `frozen_341`: see [`Ctx::frozen_341`]. pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_341: bool) -> Vec { + tags_kept_for(d, version, target, frozen_341).0 +} + +/// [`tags_for`], with the foreign objects the file keeps, by their handles in the drawing. +pub(super) fn tags_kept_for(d: &Drawing, version: Version, target: Version, frozen_341: bool) -> (Vec, std::collections::HashSet) { // An in-place block edit in progress is not written: the drawing as before it. let committed = d.committed(); let d: &Drawing = &committed; @@ -1144,11 +1149,13 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34 } // Only a DXF declares the version it is written for: the DWG bridge writes R2000 text for the // DWG writer, which keeps SAT-text solids (#2334). - crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013); + // The DWG bridge (`target` another version) keeps proxies in the DWG's own layout. + let strings = version != target || version >= Version::R2007; + let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, strings); crate::dxf_raw::data_store(&mut w.t, d, target >= Version::R2013); add_class_instance_counts(&mut w.t, target); mark_xrefs(&mut w.t, d); - w.t + (w.t, kept) } /// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index d13abca6d8..9194d3fcdd 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -34,7 +34,7 @@ pub use cadcraft_doc::Format; pub use craft_dxf::Version; pub use dxf_raw::{ObjectRecord, object_records}; pub use dxf_read::entity_from_groups; -pub use dxf_write::entity_groups; +pub use dxf_write::{entity_groups, proxies_lost}; pub use pdf::{PdfOptions, pdf, plot}; /// How a drawing is saved as DXF or DWG. diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 13d747b553..c961b50ced 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -3541,6 +3541,144 @@ fn proxy_file() -> Vec { pairs.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::().into_bytes() } +/// #3229: a file with a proxy object in the 2010 layout (as the DWG bridge brings it from a 2010 +/// DWG), with its class and a dictionary entry. +/// A 2010 DXF with one proxy object (dictionary entry WIDGETS) whose string stream is `strings` +/// long (group 162). +fn proxy_2010_file(strings: &str) -> Vec { + let text = String::from_utf8(write(&Drawing::new_metric(), "p.dxf").unwrap()).unwrap(); + let mut pairs = dxf_pairs(&text); + let p = |c: &str, v: &str| (c.to_string(), v.to_string()); + let classes = pairs.iter().position(|q| q.0 == "2" && q.1 == "CLASSES").unwrap() + 1; + pairs.splice( + classes..classes, + [p("0", "CLASS"), p("1", "WIDGETX"), p("2", "AcDbWidgetX"), p("3", "ObjectDBX Classes"), p("90", "4095"), p("280", "1"), p("281", "0")], + ); + let objects = pairs.iter().position(|q| q.0 == "2" && q.1 == "OBJECTS").unwrap(); + let nod = objects + 1; + let after = nod + pairs[nod..].iter().position(|q| q.0 == "281").unwrap() + 1; + pairs.splice(after..after, [p("3", "WIDGETS"), p("350", "AAA1")]); + let nod_handle = pairs[nod + 1].1.clone(); + let proxy = [ + p("0", "ACAD_PROXY_OBJECT"), + p("5", "AAA1"), + p("330", &nod_handle), + p("100", "AcDbProxyObject"), + p("90", "499"), + p("91", "500"), + p("95", "393245"), + p("70", "0"), + p("162", strings), + p("161", "303"), + p("310", "00FF"), + p("94", "0"), + ]; + let end = objects + pairs[objects..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap(); + pairs.splice(end..end, proxy); + pairs.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::().into_bytes() +} + +#[test] +fn proxies_take_the_layout_of_the_version_written() { + let d = read(&proxy_2010_file("0"), "p.dxf").unwrap(); + let own = |version: Version| { + let text = String::from_utf8(write_with(&d, "out.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap(); + let pairs = dxf_pairs(&text); + let recs = dxf_records(&pairs, "ACAD_PROXY_OBJECT"); + let r = recs.first().expect("the proxy is kept"); + r.iter().skip_while(|q| q.1 != "AcDbProxyObject").skip(1).map(|q| q.0.clone()).collect::>().join(" ") + }; + // R2000: no 161/162 (ODA and BricsCAD refused the file), the data size is 93. + assert_eq!(own(Version::R2000), "90 91 95 70 93 310 94"); + assert_eq!(own(Version::R2007), "90 91 95 70 96 93 310 94"); + assert_eq!(own(Version::R2010), "90 91 95 70 162 161 310 94"); + assert_eq!(own(Version::R2018), "90 91 71 97 70 162 161 310 94"); +} + +#[test] +fn a_proxy_with_a_string_stream_is_left_out_before_2007() { + // Before 2007 a proxy's strings are part of its data: a separate stream has no form there. + // The proxy and its dictionary entry are left out rather than written with half its data. + let d = read(&proxy_2010_file("10"), "p.dxf").unwrap(); + assert_eq!(cadcraft_doc::foreign::proxies_dropped_before_2007(&d), [("ACAD_PROXY_OBJECT".to_string(), 1)].into_iter().collect()); + let pairs = |version: Version| { + let text = String::from_utf8(write_with(&d, "out.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap(); + dxf_pairs(&text) + }; + let entry = |p: &[(String, String)]| p.iter().any(|q| q.0 == "3" && q.1 == "WIDGETS"); + for version in [Version::R2000, Version::R2004] { + let p = pairs(version); + assert!(dxf_records(&p, "ACAD_PROXY_OBJECT").is_empty(), "{version:?}"); + assert!(!entry(&p), "{version:?}: the dictionary entry goes with it"); + } + // From 2007 it is kept, with its string stream and its dictionary entry. + let p = pairs(Version::R2007); + let recs = dxf_records(&p, "ACAD_PROXY_OBJECT"); + assert_eq!(recs.first().and_then(|r| group(r, "96")), Some("10")); + assert!(entry(&p)); +} + +/// #3229 review: the loss a DXF before 2007 reports is what the writer leaves out for the string +/// stream alone. A proxy no version writes (its class number names no class) is not counted, and +/// the objects a dropped proxy owns (its extension dictionary and the XRECORD in it) are. +#[test] +fn proxies_lost_counts_what_the_string_stream_takes_with_it() { + let lost = |d: &Drawing, v| crate::proxies_lost(d, v); + // The records of the file written at `version` (the file gives kept objects new handles). + let written = |d: &Drawing, version: Version| { + let text = String::from_utf8(write_with(d, "out.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap(); + dxf_pairs(&text) + }; + // Its class isn't written: every version leaves it out, so 2007 would not keep it either. + let text = String::from_utf8(proxy_2010_file("10")).unwrap(); + assert_eq!(text.matches("\n91\n500\n").count(), 1, "the proxy's class number"); + let orphan = read(text.replacen("\n91\n500\n", "\n91\n777\n", 1).as_bytes(), "p.dxf").unwrap(); + assert!(!cadcraft_doc::foreign::proxies_dropped_before_2007(&orphan).is_empty(), "the proxy itself is counted"); + assert!(dxf_records(&written(&orphan, Version::R2007), "ACAD_PROXY_OBJECT").is_empty(), "no version writes it"); + assert_eq!(lost(&orphan, Version::R2000), std::collections::BTreeMap::new()); + // With an extension dictionary holding an XRECORD: all three go before 2007. + let mut p = dxf_pairs(&text); + let at = p.iter().position(|q| q.0 == "5" && q.1 == "AAA1").unwrap() + 1; + let g = |c: &str, v: &str| (c.to_string(), v.to_string()); + p.splice(at..at, [g("102", "{ACAD_XDICTIONARY"), g("360", "BBB1"), g("102", "}")]); + // The proxy is the last object: its owned objects go after it. + let objects_end = at + p[at..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap(); + p.splice( + objects_end..objects_end, + [ + g("0", "DICTIONARY"), + g("5", "BBB1"), + g("330", "AAA1"), + g("100", "AcDbDictionary"), + g("280", "1"), + g("281", "1"), + g("3", "WIDGETDATA"), + g("350", "CCC1"), + g("0", "XRECORD"), + g("5", "CCC1"), + g("330", "BBB1"), + g("100", "AcDbXrecord"), + g("280", "1"), + g("1", "kept with the widget"), + ], + ); + let bytes: Vec = p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::().into_bytes(); + let d = read(&bytes, "p.dxf").unwrap(); + let held = |version| { + let p = written(&d, version); + let xrecord = dxf_records(&p, "XRECORD").iter().any(|r| group(r, "1") == Some("kept with the widget")); + let dictionary = p.iter().any(|q| q.0 == "3" && q.1 == "WIDGETDATA"); + (dxf_records(&p, "ACAD_PROXY_OBJECT").len(), dictionary, xrecord) + }; + assert_eq!(held(Version::R2007), (1, true, true), "2007 keeps all three"); + assert_eq!(held(Version::R2000), (0, false, false), "R2000 keeps none"); + let want: std::collections::BTreeMap = + [("ACAD_PROXY_OBJECT", 1), ("DICTIONARY", 1), ("XRECORD", 1)].into_iter().map(|(k, n)| (k.to_string(), n)).collect(); + assert_eq!(lost(&d, Version::R2000), want); + assert_eq!(lost(&d, Version::R2004), want); + assert_eq!(lost(&d, Version::R2007), std::collections::BTreeMap::new()); +} + #[test] fn proxies_keep_their_class_when_classes_are_rewritten() { let d = read(&proxy_file(), "p.dxf").unwrap(); diff --git a/crates/ui-egui/src/save_loss.rs b/crates/ui-egui/src/save_loss.rs index 2b0a28c57f..7ebe1be9d4 100644 --- a/crates/ui-egui/src/save_loss.rs +++ b/crates/ui-egui/src/save_loss.rs @@ -108,6 +108,28 @@ impl CadApp { } } +/// Which files keep what a save would lose: the hint under the warning. +#[derive(Debug, PartialEq, Eq)] +enum Keeps { + /// A DXF before 2007 leaves out proxies whose strings it can't hold (#3229). + Dxf2007, + /// A DXF of 2013 or later leaves out a solid's SAT text. + Dxf2010, + /// Any other file: DXF keeps everything. + Dxf, +} + +/// The hint for saving to `path` and losing `lost`. A path names a DXF the way the save does +/// (`Format::from_path`), so a name without an extension is a DXF too. +fn keeps_hint(path: &std::path::Path, lost: &BTreeMap) -> Keeps { + if cadcraft_doc::Format::from_path(path) != Some(cadcraft_doc::Format::Dxf) { + return Keeps::Dxf; + } + // Before 2007 the proxies go with what they own (an XRECORD, a DICTIONARY); a 2013 or later + // file only leaves out solids. + if lost.keys().any(|k| cadcraft_doc::foreign::is_proxy(k)) { Keeps::Dxf2007 } else { Keeps::Dxf2010 } +} + /// The warning, while a save waits for an answer. Cancel is what Escape does. pub fn prompt(app: &mut CadApp, ctx: &egui::Context) { let Some(pending) = app.save_loss.clone() else { return }; @@ -121,10 +143,10 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) { ui.label(RichText::new(crate::tf!("Saving {name} will remove content", name = file)).strong()); ui.add_space(4.0); ui.label(crate::tf!("This format can't keep these objects yet: {objects}.", objects = pending.summary())); - let keeps = if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dxf")) { - crate::tl!("DXF 2010 and earlier keep them. Use Save As to keep them in the drawing.") - } else { - crate::tl!("DXF keeps them. Use Save As to keep them in the drawing.") + let keeps = match keeps_hint(path, &pending.loss.lost) { + Keeps::Dxf2007 => crate::tl!("DXF 2007 and later keep them. Use Save As to keep them in the drawing."), + Keeps::Dxf2010 => crate::tl!("DXF 2010 and earlier keep them. Use Save As to keep them in the drawing."), + Keeps::Dxf => crate::tl!("DXF keeps them. Use Save As to keep them in the drawing."), }; ui.label(RichText::new(keeps).color(t.text_dim)); let on_disk = if save_keeps_current(path) { @@ -158,3 +180,23 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) { ctx.request_repaint(); } } + +#[cfg(test)] +mod tests { + use super::*; + + fn lost(kind: &str) -> BTreeMap { + BTreeMap::from([(kind.to_string(), 1)]) + } + + #[test] + fn a_name_without_an_extension_is_a_dxf_for_the_hint() { + let path = std::path::Path::new("plans/site"); + assert_eq!(keeps_hint(path, &lost("ACAD_PROXY_ENTITY")), Keeps::Dxf2007); + assert_eq!(keeps_hint(path, &lost("3DSOLID")), Keeps::Dxf2010); + let with_owned = BTreeMap::from([("ACAD_PROXY_OBJECT".to_string(), 1), ("XRECORD".to_string(), 2)]); + assert_eq!(keeps_hint(path, &with_owned), Keeps::Dxf2007); + assert_eq!(keeps_hint(std::path::Path::new("plans/site.DXF"), &lost("ACAD_PROXY_ENTITY")), Keeps::Dxf2007); + assert_eq!(keeps_hint(std::path::Path::new("plans/site.dwg"), &lost("ACAD_PROXY_ENTITY")), Keeps::Dxf); + } +}