From b861b6c0a5ace88c973274f7c1aa66b087a26680 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:07:14 +0700 Subject: [PATCH] DWG save: keep the first 255 dash elements of a linetype, and say so acadrust 0.6.6 writes and reads a DWG linetype's element count as one byte, so a linetype of 256 elements came back from a DWG save with none (continuous) and one of 300 with 44. The DXF read cap of #3482 lets 256 through, so every capped DXF linetype hit the 256 -> 0 case. The DWG bridge text now writes at most 255 elements per linetype (the first ones, with group 40 totalling them); DXF output is unchanged. cadcraft_io::dwg_notes gives one note counting the linetypes cut, counted by the writer so an xref linetype the file leaves out is not counted. An engine hook installed by the apps echoes it and returns it in `warnings` on every DWG write: QSAVE/SAVEAS, document.bytes, EXPORT, WBLOCK, -WBLOCK, LAYOUT SAVEAS; cadcraft-cli convert prints it. Part of #1923 (F-05). Co-Authored-By: Claude Opus 5.5 --- apps/cadcraft-cli/src/lib.rs | 1 + apps/cadcraft-cli/src/output.rs | 3 + apps/cadcraft-cli/tests/it/ltype_dwg_note.rs | 41 +++++++++++ apps/cadcraft-cli/tests/it/main.rs | 3 + apps/cadcraft-web/src/main.rs | 1 + apps/cadcraft/src/main.rs | 1 + crates/engine/src/cmd/blocks/wblock.rs | 39 ++++++---- crates/engine/src/cmd/file.rs | 36 ++++++++++ crates/engine/src/cmd/layout.rs | 2 +- crates/engine/src/cmd/layout/saveas.rs | 5 +- crates/engine/tests/proxy_loss_real_writer.rs | 55 ++++++++++++++ crates/io/src/dxf_write.rs | 32 +++++++-- crates/io/src/dxf_write/sections.rs | 30 +++++--- crates/io/src/lib.rs | 2 +- crates/io/tests/it/ltype_dwg_dash_count.rs | 71 +++++++++++++++++++ crates/io/tests/it/main.rs | 2 + 16 files changed, 293 insertions(+), 31 deletions(-) create mode 100644 apps/cadcraft-cli/tests/it/ltype_dwg_note.rs create mode 100644 crates/io/tests/it/ltype_dwg_dash_count.rs diff --git a/apps/cadcraft-cli/src/lib.rs b/apps/cadcraft-cli/src/lib.rs index 3c981421f..dc335b076 100644 --- a/apps/cadcraft-cli/src/lib.rs +++ b/apps/cadcraft-cli/src/lib.rs @@ -60,6 +60,7 @@ fn install_io() { // What a DXF before 2007 leaves out for its proxies' string streams (#3229). cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost); cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost); + cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes); } /// `path` as text, for the engine and io calls that take a file name as a string. diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs index 02f2a7341..f513ce0fb 100644 --- a/apps/cadcraft-cli/src/output.rs +++ b/apps/cadcraft-cli/src/output.rs @@ -154,6 +154,9 @@ pub(crate) fn export_framed(s: &Session, out: &Path, window: Option, io if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) { io.errln(format_args!("{m}")); } + for note in cadcraft_engine::cmd::file::dwg_notes(d) { + io.errln(format_args!("{note}")); + } } Ok(()) } diff --git a/apps/cadcraft-cli/tests/it/ltype_dwg_note.rs b/apps/cadcraft-cli/tests/it/ltype_dwg_note.rs new file mode 100644 index 000000000..2b16b12c5 --- /dev/null +++ b/apps/cadcraft-cli/tests/it/ltype_dwg_note.rs @@ -0,0 +1,41 @@ +//! `convert` to DWG says, in one warning, how many linetypes the DWG keeps with only their first +//! 255 dash elements (#1923, F-05); converting to DXF keeps them whole and says nothing. + +use std::process::{Command, Output}; + +fn cli(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap() +} + +/// A DXF with a 256-element linetype and a line drawn with it. +fn dxf() -> String { + let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n0\nLTYPE\n2\nLONG\n70\n0\n3\nLong\n72\n65\n73\n256\n40\n192\n"); + for i in 0..256 { + s.push_str(if i % 2 == 0 { "49\n1\n74\n0\n" } else { "49\n-0.5\n74\n0\n" }); + } + s.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n6\nLONG\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n"); + s +} + +#[test] +fn convert_to_dwg_notes_the_linetypes_it_cuts() { + let dir = std::env::temp_dir().join(format!("cc-cli-ltype-dwg-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let source = dir.join("long.dxf"); + std::fs::write(&source, dxf()).unwrap(); + let source = source.to_str().unwrap(); + let notes = + |out: &Output| String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("dash elements")).map(str::to_string).collect::>(); + + let out = cli(&["convert", source, dir.join("long.dwg").to_str().unwrap()]); + assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr)); + assert!( + matches!(notes(&out).as_slice(), [note] if note.contains("1 linetype") && note.contains("255")), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + + let out = cli(&["convert", source, dir.join("copy.dxf").to_str().unwrap()]); + assert!(out.status.success() && notes(&out).is_empty(), "{}", String::from_utf8_lossy(&out.stderr)); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/apps/cadcraft-cli/tests/it/main.rs b/apps/cadcraft-cli/tests/it/main.rs index 6c282f006..12e8a16ab 100644 --- a/apps/cadcraft-cli/tests/it/main.rs +++ b/apps/cadcraft-cli/tests/it/main.rs @@ -1,6 +1,9 @@ mod cli; mod drafting_spacing; mod help; +// DWG output needs craft-dwg's bridge. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +mod ltype_dwg_note; mod mcp_connect; mod pdf_import; mod skipped_records; diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index 03c041a93..11bae57e2 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -134,6 +134,7 @@ mod web { // What a DXF before 2007 leaves out for its proxies' string streams (#3229). cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost); cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost); + cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes); 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 9e812536c..f28f006e1 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -199,6 +199,7 @@ pub fn install_io() { // What a DXF before 2007 leaves out for its proxies' string streams (#3229). cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost); cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost); + cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes); } fn services() -> Services { diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index 22ff1dcb6..624d510de 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -8,7 +8,9 @@ use cadcraft_geom::{Mat3, Vec2, Vec3}; use serde_json::{Value, json}; use super::super::curves::KW; -use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder}; +use super::super::file::{ + Version, drops_unknown, dwg_notes, lost_message, lost_writing, new_folder, own_version, report_dwg_notes, 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}; @@ -46,7 +48,7 @@ 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, version) = match str_param(p, "name") { + let (entities, bytes, lost, version, notes) = match str_param(p, "name") { Some("*") => write(s, "wblock", &path, Source::Whole)?, 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)))?, @@ -54,6 +56,7 @@ fn run_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_lost(s, &mut r, &path, version, &lost); + report_dwg_notes(s, &mut r, notes); Ok(r) } @@ -64,7 +67,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, version) = match str_param(p, "name") { + let (entities, bytes, lost, version, notes) = match str_param(p, "name") { Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?, None => { let hs = targets(s, p)?; @@ -80,16 +83,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_lost(s, &mut r, &path, version, &lost); + report_dwg_notes(s, &mut r, notes); Ok(r) } /// 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, Version)> { +/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams), the +/// version it was written at and what a DWG keeps only in part, 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, Version, Vec)> { 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. @@ -115,14 +119,19 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi // 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)) + let notes = if drops_unknown(path) { dwg_notes(&d) } else { Vec::new() }; + Ok((d.model.len(), bytes.len(), lost, version, notes)) } -/// 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) { +/// Say on the command line what the file written at `path` and `version` left out, and what a +/// DWG keeps only in part (`notes`). +fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap, notes: Vec) { if let Some(msg) = lost_message(path, version, lost) { s.echo(msg); } + for note in notes { + s.echo(note); + } } /// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks @@ -341,7 +350,7 @@ impl DashWblockM { fn write(&self, s: &mut Session, what: Source) -> Result { match write(s, "-wblock", &self.path, what) { - Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost), + Ok((.., lost, version, notes)) => echo_not_saved(s, &self.path, version, &lost, notes), Err(e) => s.echo(e.to_string()), } Ok(Step::Done) @@ -352,8 +361,8 @@ impl DashWblockM { return Ok(Step::Done); } match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) { - Ok((.., lost, version)) => { - echo_not_saved(s, &self.path, version, &lost); + Ok((.., lost, version, notes)) => { + echo_not_saved(s, &self.path, version, &lost, notes); 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 6def828c3..8cb57ab24 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -104,6 +104,36 @@ pub fn set_dwg_compat_lost(f: DwgCompatLost) { let _ = DWG_COMPAT_LOST.set(f); } +/// Notes on what a DWG keeps of a drawing only in part, such as a linetype with more dash +/// elements than a DWG can count (installed by the app with the DWG writer, a lower layer; see +/// `cadcraft_io::dwg_notes`). +pub type DwgNotes = fn(&Drawing) -> Vec; + +static DWG_NOTES: OnceLock = OnceLock::new(); + +pub fn set_dwg_notes(f: DwgNotes) { + let _ = DWG_NOTES.set(f); +} + +/// The [`DwgNotes`] of `d`, the drawing a DWG save writes: none without the hook. +pub fn dwg_notes(d: &Drawing) -> Vec { + DWG_NOTES.get().map(|f| f(d)).unwrap_or_default() +} + +/// Say on the command line what the DWG just written keeps only in part (`notes`, from +/// [`dwg_notes`]), and list it in the result's `warnings`. +pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec) { + if notes.is_empty() { + return; + } + for note in ¬es { + s.echo(note.clone()); + } + if let Some(o) = r.as_object_mut() { + o.insert("warnings".into(), json!(notes)); + } +} + /// 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 { @@ -873,6 +903,8 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result { let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() }); if drops_unknown(format!("drawing.{fmt}")) { report_not_saved(s, &mut r, &lost); + let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default(); + report_dwg_notes(s, &mut r, notes); } else if is_dxf_file(format!("drawing.{fmt}")) { let lost = host_dxf_lost(s, version); report_lost(s, &mut r, "drawing.dxf", version, &lost); @@ -1005,7 +1037,9 @@ pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) { let Ok(d) = s.doc() else { return }; let version = own_version(d, path); let lost = lost_writing(d, path, version); + let notes = if drops_unknown(path) { dwg_notes(d) } else { Vec::new() }; report_lost(s, r, path, version, &lost); + report_dwg_notes(s, r, notes); } /// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`), @@ -1112,6 +1146,8 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R report_new_folder(s, &mut r, folder); if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) { report_not_saved(s, &mut r, &lost); + let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default(); + report_dwg_notes(s, &mut r, notes); } else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) { let lost = host_dxf_lost(s, version); report_lost(s, &mut r, "drawing.dxf", version, &lost); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 4417ba342..fc9f8a5bf 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { CommandSpec::new("layout.copy", "Copy Layout", run_copy).params("{from, to?}"), CommandSpec::new("layout.list", "List Layouts", run_list).params("→ [{name, tabOrder, page, viewports}]").noundo(), CommandSpec::new("layout.saveas", "Save Layout as Template", saveas::run_saveas) - .params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?}") + .params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?, warnings?}") .noundo(), CommandSpec::new("mview", "Viewports", run_mview) .alias(&["mv"]) diff --git a/crates/engine/src/cmd/layout/saveas.rs b/crates/engine/src/cmd/layout/saveas.rs index 170a610bd..32612acfd 100644 --- a/crates/engine/src/cmd/layout/saveas.rs +++ b/crates/engine/src/cmd/layout/saveas.rs @@ -12,7 +12,7 @@ use cadcraft_doc::{Common, Drawing, Entity, EntityKind, EntityStore, Point}; use cadcraft_geom::Vec3; use serde_json::{Value, json}; -use super::super::file::{drops_unknown, io, not_saved, not_saved_message}; +use super::super::file::{drops_unknown, dwg_notes, io, not_saved, not_saved_message, report_dwg_notes}; use super::super::{bad, str_param}; use super::layout_name; use super::prompts::current_layout; @@ -136,6 +136,9 @@ pub(super) fn run_saveas(s: &mut Session, p: &Value) -> Result { o.insert("notSaved".into(), json!(lost)); } } + if drops_unknown(&path) { + report_dwg_notes(s, &mut r, dwg_notes(&t)); + } Ok(r) } diff --git a/crates/engine/tests/proxy_loss_real_writer.rs b/crates/engine/tests/proxy_loss_real_writer.rs index 440d025fc..547ac72cd 100644 --- a/crates/engine/tests/proxy_loss_real_writer.rs +++ b/crates/engine/tests/proxy_loss_real_writer.rs @@ -23,6 +23,7 @@ fn install() { }); set_proxies_lost(cadcraft_io::proxies_lost); cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost); + cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes); } /// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes. @@ -117,6 +118,60 @@ fn legacy_visualstyles_warn_only_for_2007_dwg() { } } +/// A linetype with more dash elements than a DWG counts is saved with its first 255, and each +/// way of writing a DWG says so in one note (#1923, F-05); a DXF keeps it whole and says nothing. +#[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +fn a_dwg_save_notes_the_linetypes_it_cuts() { + use cadcraft_engine::doc::{Common, DashElement, EntityKind, Line, Linetype, Space}; + use cadcraft_engine::geom::Vec3; + install(); + cadcraft_io::dwg_worker::allow_in_process(); + let dir = TempDir::new("ltype-notes"); + let linetype = |name: &str, n: usize| Linetype { + name: name.into(), + description: String::new(), + pattern: (0..n).map(|i| DashElement::dash(if i % 2 == 0 { 1.0 } else { -0.5 })).collect(), + }; + let mut d = Drawing::new_metric(); + d.linetypes.extend([linetype("LONG", 256), linetype("FITS", 255)]); + // Lines drawn with it in model space and on a sheet, so WBLOCK and LAYOUT SAVEAS keep it. + let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) }); + let common = Common { linetype: "LONG".into(), ..Common::default() }; + let model_line = d.add(&Space::Model, common.clone(), line.clone()).unwrap(); + d.add(&Space::Paper("Layout1".into()), common, line).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "ltypes.dxf", None); + let one_note = |r: &Value| matches!(r["warnings"].as_array().map(Vec::as_slice), Some([note]) if note.as_str().is_some_and(|t| t.contains("1 linetype") && t.contains("255"))); + let notes_since = |s: &Session, n: usize| s.log[n..].iter().filter(|l| l.contains("dash elements")).count(); + let dwg = dir.path_str("out.dwg"); + let writes = [ + ("saveas", json!({ "path": dwg })), + ("document.bytes", json!({ "format": "dwg" })), + ("export", json!({ "format": "dwg" })), + ("wblock", json!({ "path": dir.path_str("all.dwg"), "name": "*" })), + ("layout.saveas", json!({ "name": "Layout1", "path": dir.path_str("sheet.dwg") })), + ("-wblock", json!({ "path": dir.path_str("line.dwg"), "handles": [model_line.0] })), + ]; + for (cmd, p) in writes { + let n = s.log.len(); + let r = s.execute(cmd, &p).unwrap(); + assert!(one_note(&r), "{cmd}: {r}"); + assert_eq!(notes_since(&s, n), 1, "{cmd}: {:?}", &s.log[n..]); + } + // -WBLOCK at the command line says it too (a DWG file has no precision prompt). + let n = s.log.len(); + let path = dir.path_str("typed.dwg").replace('\\', "/"); + s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"*\")")).unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(notes_since(&s, n), 1, "{:?}", &s.log[n..]); + let back = cadcraft_io::read(&std::fs::read(&dwg).unwrap(), "out.dwg").unwrap(); + assert_eq!(back.linetype("LONG").map(|l| l.pattern.len()), Some(255)); + let n = s.log.len(); + let r = s.execute("saveas", &json!({ "path": dir.path_str("out.dxf") })).unwrap(); + assert!(r.get("warnings").is_none() && !s.log[n..].iter().any(|l| l.contains("dash elements")), "{r} {:?}", &s.log[n..]); +} + #[test] fn a_proxy_no_version_writes_is_not_reported() { install(); diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index ee37b5f97..9b9ee8107 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -156,17 +156,23 @@ pub fn tags(d: &Drawing, version: Version) -> Vec { /// [`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, false); + let (mut tags, kept, _) = sections::tags_kept_for(d, version, version, version < Version::R2004, false); // 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 most dash elements a linetype keeps in a DWG. The DWG writer (acadrust) stores the count in +/// one byte, so a longer pattern would come back with its count modulo 256 (none at all for 256), +/// and a DWG save keeps the first 255 instead ([`dwg_notes`] says so). +pub const DWG_MAX_LINETYPE_ELEMENTS: usize = 255; + /// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG -/// version's (MULTILEADER from 2007). +/// version's (MULTILEADER from 2007), and its linetypes have at most +/// [`DWG_MAX_LINETYPE_ELEMENTS`] elements. pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwritten) { - let (mut tags, kept) = sections::tags_kept_for(d, Version::R2000, dwg, false, true); + let (mut tags, kept, _) = sections::tags_kept_for(d, Version::R2000, dwg, false, true); let mut unwritten = craft_dwg::Unwritten::new(); if dwg == Version::R2007 { let omitted = legacy_visualstyles_kept(d, &kept); @@ -186,7 +192,7 @@ pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwri pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten { let mut lost = craft_dwg::Unwritten::new(); if version == Version::R2007 && d.foreign.objects.iter().any(legacy_visual_style) { - let (_, kept) = sections::tags_kept_for(d, Version::R2000, version, false, true); + let (_, kept, _) = sections::tags_kept_for(d, Version::R2000, version, false, true); let omitted = legacy_visualstyles_kept(d, &kept); if omitted != 0 { lost.insert("VISUALSTYLE".into(), omitted); @@ -195,6 +201,24 @@ pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten { lost } +/// What a DWG keeps of `d` only in part, as notes for the user: one counting the linetypes with +/// more dash elements than a DWG counts, which it saves with their first +/// [`DWG_MAX_LINETYPE_ELEMENTS`]. Empty when the DWG keeps every linetype whole. +pub fn dwg_notes(d: &Drawing) -> Vec { + let max = DWG_MAX_LINETYPE_ELEMENTS; + if d.linetypes.iter().all(|l| l.pattern.len() <= max) { + return Vec::new(); + } + // The writer decides which linetypes the file holds (an xref's own only when a layer uses + // them), so it does the counting; the LTYPE table is the same in every DWG version. + let (_, _, cut) = sections::tags_kept_for(d, Version::R2000, Version::R2004, false, true); + match cut { + 0 => Vec::new(), + 1 => vec![format!("DWG: 1 linetype has more than {max} dash elements; only its first {max} were saved.")], + n => vec![format!("DWG: {n} linetypes have more than {max} dash elements; only the first {max} of each were saved.")], + } +} + fn legacy_visualstyles_kept(d: &Drawing, kept: &HashSet) -> usize { d.foreign.objects.iter().filter(|object| kept.contains(&object.handle) && legacy_visual_style(object)).count() } diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 4e18a88e2..e0459394b 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -17,9 +17,14 @@ struct TableWritePlan<'a> { version: Version, cx: &'a mut Ctx, ext: cadcraft_geom::Bounds2, + /// The most dash elements a linetype is written with (a DWG's count is one byte); `None` + /// writes every element. + max_dashes: Option, } -fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap { +/// The tables; the LTYPE handles by upper-case name, and how many linetypes were written with +/// only their first `plan.max_dashes` elements. +fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> (HashMap, usize) { let d = plan.d; let version = plan.version; let cx = plan.cx; @@ -32,8 +37,13 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap // in the STYLE table below: (tag position, style name, is a shape) are filled in there. let mut ltype_handles: HashMap = HashMap::new(); let mut ltype_style_refs: Vec<(usize, Option, bool)> = Vec::new(); + let mut linetypes_cut = 0usize; let th = table_head(w, "LTYPE", d.linetypes.len()); for lt in &d.linetypes { + let pattern = plan.max_dashes.and_then(|max| lt.pattern.get(..max)).unwrap_or(<.pattern); + if pattern.len() < lt.pattern.len() { + linetypes_cut = linetypes_cut.saturating_add(1); + } let h = record_head(w, "LTYPE", &th, "AcDbLinetypeTableRecord"); ltype_handles.entry(lt.name.to_ascii_uppercase()).or_insert(h.clone()); cx.ltypes.entry(lt.name.to_ascii_uppercase()).or_insert(h); @@ -41,9 +51,9 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap w.i(70, if crate::dxf_xref::dependent(<.name) { 48 } else { 0 }); w.s(3, <.description); w.i(72, 65); - w.i(73, lt.pattern.len() as i64); - w.f(40, lt.pattern_length()); - for el in <.pattern { + w.i(73, pattern.len() as i64); + w.f(40, pattern.iter().map(|el| el.length.abs()).sum()); + for el in pattern { w.f(49, el.length); // 74: 2 = text, 4 = shape, + 1 when the rotation is absolute (DXF Reference, LTYPE). let (kind, shape) = match (&el.text, el.shape) { @@ -191,7 +201,7 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap } w.s(0, "ENDTAB"); write_dimstyles(w, d, cx, version); - ltype_handles + (ltype_handles, linetypes_cut) } /// The LAYER table; when the drawing has layer states AutoCAD can hold, the table's extension @@ -1056,14 +1066,15 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34 /// The drawing's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the version the /// file ends up in) has, and the foreign objects the file keeps, by their handles in the drawing. /// `bridge`: the text is for the DWG bridge, not a DXF file. The versions alone can't say so: an -/// R2000 DWG is bridged from R2000 text. +/// R2000 DWG is bridged from R2000 text. The bridge's linetypes keep at most +/// [`super::DWG_MAX_LINETYPE_ELEMENTS`] elements; the last value counts those cut. pub(super) fn tags_kept_for( d: &Drawing, version: Version, target: Version, frozen_341: bool, bridge: bool, -) -> (Vec, std::collections::HashSet) { +) -> (Vec, std::collections::HashSet, usize) { // An in-place block edit in progress is not written: the drawing as before it. let committed = d.committed(); let d: &Drawing = &committed; @@ -1182,7 +1193,8 @@ pub(super) fn tags_kept_for( write_classes(&mut w, &cx, &every); - let ltype_handles = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model) }); + let max_dashes = bridge.then_some(super::DWG_MAX_LINETYPE_ELEMENTS); + let (ltype_handles, linetypes_cut) = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model), max_dashes }); // BLOCK_RECORD let th = table_head(&mut w, "BLOCK_RECORD", 1 + ps_brs.len() + user_blocks.len() + dim_defs.len() + arrow_defs.len() + table_defs.len()); @@ -1344,7 +1356,7 @@ pub(super) fn tags_kept_for( add_class_instance_counts(&mut w.t, target); mark_xrefs(&mut w.t, d); plot_settings_compatibility(&mut w.t, target); - (w.t, kept) + (w.t, kept, linetypes_cut) } fn plot_settings_compatibility(tags: &mut Vec, target: Version) { diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index cd787e3ac..7d868fbbc 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -38,7 +38,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::{dwg_compat_lost, entity_groups, proxies_lost}; +pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, proxies_lost}; pub use pdf::{PdfOptions, pdf, plot}; /// How a drawing is saved as DXF or DWG. diff --git a/crates/io/tests/it/ltype_dwg_dash_count.rs b/crates/io/tests/it/ltype_dwg_dash_count.rs new file mode 100644 index 000000000..7ddfc450a --- /dev/null +++ b/crates/io/tests/it/ltype_dwg_dash_count.rs @@ -0,0 +1,71 @@ +//! A DWG counts a linetype's dash elements in one byte (acadrust 0.6.6 writes and reads the +//! count with `write_byte` / `read_byte`), so a linetype saved as DWG keeps its first 255 +//! elements instead of a count that wrapped past 255, and one note says how many linetypes were +//! cut (#1923, F-05; the DXF cap of #3482 lets 256 through). + +use std::io::Cursor; + +use cadcraft_doc::{DashElement, Drawing, Layer, Linetype}; +use cadcraft_io::{DWG_MAX_LINETYPE_ELEMENTS as MAX, SaveOptions, Version, dwg_notes}; + +/// Element `i`: a dash `(i + 1) / 100` long for even `i`, a gap that long for odd `i`. +fn length(i: usize) -> f64 { + let l = (i + 1) as f64 / 100.0; + if i.is_multiple_of(2) { l } else { -l } +} + +/// A linetype `name` of `elements` elements. +fn linetype(name: &str, elements: usize) -> Linetype { + Linetype { name: name.into(), description: format!("{name} dashes"), pattern: (0..elements).map(|i| DashElement::dash(length(i))).collect() } +} + +/// A drawing with linetypes of these names and element counts. +fn drawing(linetypes: &[(&str, usize)]) -> Drawing { + let mut d = Drawing::new_metric(); + d.linetypes.extend(linetypes.iter().map(|(name, n)| linetype(name, *n))); + d +} + +/// The element lengths of linetype `name` in `d`. +fn lengths(d: &Drawing, name: &str) -> Option> { + d.linetype(name).map(|l| l.pattern.iter().map(|e| e.length).collect()) +} + +#[test] +fn a_dwg_keeps_the_first_255_dash_elements_of_a_longer_linetype() { + cadcraft_io::dwg_worker::allow_in_process(); + let d = drawing(&[("FULL", MAX), ("OVER", MAX + 1), ("LONG", 300)]); + let first = (0..MAX).map(length).collect::>(); + for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2010, Version::R2013, Version::R2018] { + let options = SaveOptions { version: Some(version), binary: false }; + let dwg = cadcraft_io::write_with(&d, "ltypes.dwg", &options).expect("save as DWG"); + let back = cadcraft_io::read(&dwg, "ltypes.dwg").expect("reopen"); + for name in ["FULL", "OVER", "LONG"] { + assert_eq!(lengths(&back, name).as_ref(), Some(&first), "{name} {version:?}"); + } + // The record's total length is that of the elements it keeps. + let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().expect("acadrust reads the DWG"); + let long = doc.line_types.iter().find(|l| l.name == "LONG").expect("LONG"); + let kept: f64 = first.iter().map(|l| l.abs()).sum(); + assert!((long.pattern_length - kept).abs() < 1e-9, "{version:?}: {} for {kept}", long.pattern_length); + } +} + +/// One note counts the linetypes a DWG cuts; linetypes that fit get none. +#[test] +fn one_note_counts_the_linetypes_a_dwg_cuts() { + assert_eq!(dwg_notes(&drawing(&[("FULL", MAX), ("SHORT", 4)])), Vec::::new()); + let one = dwg_notes(&drawing(&[("FULL", MAX), ("OVER", MAX + 1)])); + assert!(matches!(one.as_slice(), [note] if note.contains("1 linetype ") && note.contains(&MAX.to_string())), "{one:?}"); + let two = dwg_notes(&drawing(&[("OVER", MAX + 1), ("FULL", MAX), ("LONG", 300)])); + assert!(matches!(two.as_slice(), [note] if note.contains("2 linetypes")), "{two:?}"); +} + +/// An xref's own linetype is saved only when a layer uses it, so only then is it counted. +#[test] +fn an_xref_linetype_the_file_leaves_out_is_not_counted() { + let mut d = drawing(&[("SITE|LONG", 300)]); + assert_eq!(dwg_notes(&d), Vec::::new()); + d.layers.push(Layer { linetype: "SITE|LONG".into(), ..Layer::new("SITE|WALLS") }); + assert!(matches!(dwg_notes(&d).as_slice(), [note] if note.contains("1 linetype ")), "{:?}", dwg_notes(&d)); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index a604eff66..dc0bc0931 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -51,6 +51,8 @@ mod layout_plot_window; mod leader_vertex_elevation; #[cfg(not(target_arch = "wasm32"))] mod low_handseed; +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +mod ltype_dwg_dash_count; mod ltype_element_cap; mod minsert_marker; mod mleader_content;