//! DWG support through a DXF bridge. //! //! DWG files are read with the `acadrust` crate (MPL-2.0, used unmodified as a dependency) and //! converted to DXF bytes for the caller's DXF reader; saving goes the other way. Keeping the //! dependency behind this byte-level API prevents its document types from leaking to consumers. //! Native targets only (the dependency memory-maps files). //! //! # Guardrails around the third-party decoder //! //! The decoder allocates tables and section buffers from sizes a (possibly damaged or hostile) //! file declares, and once it starts it cannot be interrupted (an allocation failure aborts the //! process, which `catch_unwind` cannot recover). Because the dependency is used unmodified, this //! crate guards it from the outside: //! //! - Both directions reject oversized input *before* the decoder runs ([`Limits::max_dwg_bytes`] //! for DWG→DXF, [`Limits::max_dxf_bytes`] for DXF→DWG), and the DWG→DXF output is capped while //! it is written (`CappedWriter`). //! - The reader and writer run inside `catch_unwind`, so a decode failure is reported instead of //! crashing. //! //! These bound the input- and output-size variants. A small file that declares a huge internal //! table or section can still make the dependency allocate before any size is known, so the app //! runs both directions in a child process ([`worker`]): what that kills is the child. //! //! Isolation is not optional for untrusted input. With no worker configured the conversion is //! refused rather than run here, and a worker that cannot start is an error, so a missing worker //! never turns into decoding a hostile file in the caller's process. [`worker::allow_in_process`] //! is the explicit exception, for input the caller knows is trusted. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] /// DWG version codes we can write. pub const VERSIONS: &[(&str, &str)] = &[("AC1015", "2000"), ("AC1018", "2004"), ("AC1021", "2007"), ("AC1024", "2010"), ("AC1027", "2013"), ("AC1032", "2018")]; /// True when the bytes look like a DWG file (`AC10xx` magic). pub fn is_dwg(bytes: &[u8]) -> bool { bytes.len() > 6 && bytes.starts_with(b"AC10") && bytes.get(4..6).is_some_and(|v| v.iter().all(u8::is_ascii_digit)) } /// The DWG version code of a file (e.g. "AC1032"). pub fn version(bytes: &[u8]) -> Option { is_dwg(bytes).then(|| String::from_utf8_lossy(bytes.get(0..6).unwrap_or_default()).to_string()) } /// Size limits for reading a DWG file. DWG is compressed and the DXF text it converts to is /// several times larger (about 6x in our tests: a 10 MB DWG becomes about 60 MB of DXF), so /// the limits are generous for real drawings. They exist because a damaged file, or one the reader /// misreads, can make the DWG reader produce a drawing thousands of times larger than the file. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Limits { /// Largest DWG file read at all (checked before reading starts). pub max_dwg_bytes: usize, /// Largest DXF rendition of a DWG (checked while it is written). pub max_dxf_bytes: usize, } impl Limits { /// 512 MB of DWG, 1 GB of DXF (more than the DXF reader's group-code limit fills). pub const DEFAULT: Limits = Limits { max_dwg_bytes: 512 << 20, max_dxf_bytes: 1 << 30 }; } /// A byte count in megabytes for messages ("9.9 MB", "1024 MB"). #[cfg_attr(no_dwg_bridge, allow(dead_code))] #[expect( clippy::cast_precision_loss, reason = "Megabyte formatting is rounded for display; exact integer precision beyond 2^53 bytes is not meaningful." )] fn mb(n: u64) -> String { let m = n as f64 / f64::from(1u32 << 20); if m >= 100.0 { format!("{m:.0} MB") } else { format!("{m:.1} MB") } } #[cfg(not(no_dwg_bridge))] pub mod worker; #[cfg(not(no_dwg_bridge))] pub use worker::{ WORKER_ARG, allow_in_process, crash_worker_for_test, decode, encode_as, encode_kept_noted, encode_noted, serve_if_asked, use_own_worker, use_worker, }; #[cfg(not(no_dwg_bridge))] mod proxy_transport; #[cfg(not(no_dwg_bridge))] mod native { use std::fmt::Write as _; use std::io::{Cursor, Write}; use std::panic::AssertUnwindSafe; use super::{Limits, mb}; /// Read DWG bytes and return an ASCII DXF rendition, within [`Limits::DEFAULT`]. /// /// # Errors /// /// Returns an error when the DWG cannot be read or post-processed, or its DXF rendition exceeds the default limits. pub fn dwg_to_dxf(bytes: &[u8]) -> Result, String> { dwg_to_dxf_with(bytes, Limits::DEFAULT) } /// [`dwg_to_dxf`] with explicit limits. Both are checked before the expensive step they /// guard: the input size before the DWG reader runs, the DXF size while it is written, so a /// runaway conversion stops at the limit instead of filling memory first. /// /// # Errors /// /// Returns an error when the input exceeds `limits`, decoding fails, or the DXF output exceeds `limits`. pub fn dwg_to_dxf_with(bytes: &[u8], limits: Limits) -> Result, String> { dwg_to_dxf_noted(bytes, limits).map(|(dxf, _)| dxf) } /// [`dwg_to_dxf_with`], also returning notes on what the read left out. The reader runs in /// failsafe mode: an object record it can't decode is skipped instead of failing the whole /// file, and the notes say how many were skipped and of which types, so a partial read never /// passes for a complete one. /// /// # Errors /// /// Returns an error when the input exceeds `limits`, decoding fails, or the DXF output exceeds `limits`. pub fn dwg_to_dxf_noted(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { if bytes.len() > limits.max_dwg_bytes { return Err(format!( "DWG: the file is {}, larger than the {} accepted by this bridge", mb(bytes.len() as u64), mb(limits.max_dwg_bytes as u64) )); } let outcome = std::panic::catch_unwind(|| { acadrust::DwgReader::from_stream_with_options(Cursor::new(bytes), acadrust::DwgReadOptions::failsafe()).read_with_stats() }) .map_err(|_| "the DWG reader failed on this file".to_string())? .map_err(|e| format!("DWG: {e}"))?; // Failsafe skips records, not whole files: when the objects stream itself couldn't be // read (a damaged header or section map, or not a DWG at all), nothing was read. if !outcome.stats.record_stream_read { let why = outcome.stats.diagnostics.first().map(|d| d.message.trim_start_matches("Failsafe: ").to_string()); return Err(format!("DWG: {}", why.unwrap_or_else(|| "the file's objects couldn't be read".to_string()))); } let mut notes = read_notes(&outcome.stats); let mut doc = outcome.document; notes.extend( guarded(AssertUnwindSafe(|| application_objects(&mut doc))).map_err(|()| "the DWG application object conversion failed".to_string())?, ); // After application_objects, so the proxy objects it makes are numbered as the DXF's. notes.extend( guarded(AssertUnwindSafe(|| super::proxy_transport::prepare(&mut doc))).map_err(|()| "the DWG proxy conversion failed".to_string())?, ); let orphans = guarded(AssertUnwindSafe(|| post_process(&mut doc))).map_err(|()| "the DWG post-processing failed on this file".to_string())?; if orphans > 0 { let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") }; notes.push(format!("DWG: {orphans} DGN line style component{s} that no line style definition uses {were} left out")); } let mut out = CappedWriter { buf: Vec::new(), limit: limits.max_dxf_bytes, exceeded: false }; let written = std::panic::catch_unwind(AssertUnwindSafe(|| { acadrust::DxfWriter::new(&doc).write_to_writer(&mut out)?; mtext_contents(&doc, &mut out) })) .map_err(|_| "the DWG→DXF conversion failed on this file".to_string())?; if out.exceeded { return Err(format!( "DWG: converting this {} file produced more than {} of drawing data (the limit); \ the file is probably damaged, or uses objects the DWG reader misreads", mb(bytes.len() as u64), mb(limits.max_dxf_bytes as u64) )); } written.map_err(|e| format!("DWG→DXF: {e}"))?; Ok((add_header_vars(out.buf, &doc.header), notes)) } /// acadrust 0.6.6's ASCII writer treats a caret followed by a literal space as already /// escaped, and turns line feeds into paragraph codes. Serialize affected MTEXT contents /// from the native values instead, using its lossless string writer. All other groups, /// including embedded-object data, remain byte-for-byte as the DXF writer emitted them. fn mtext_contents(doc: &acadrust::CadDocument, out: &mut CappedWriter) -> acadrust::Result<()> { use acadrust::io::dxf::{DxfStreamWriter, DxfTextWriter}; let contents: std::collections::HashMap<_, _> = doc .entities() .filter_map(|e| match e { acadrust::EntityType::MText(t) if t.value.contains(['^', '\t', '\n']) => Some((t.common.handle.value(), t.value.as_str())), _ => None, }) .collect(); if contents.is_empty() { return Ok(()); } let dxf = std::mem::take(&mut out.buf); let mut lines = dxf.split_inclusive(|b| *b == b'\n'); let (mut mtext, mut text, mut written) = (false, None, false); while let Some(code) = lines.next() { let value = lines.next().ok_or_else(|| std::io::Error::other("incomplete DWG bridge DXF pair"))?; match code.trim_ascii() { b"0" => { mtext = value.trim_ascii() == b"MTEXT"; text = None; written = false; } b"5" if mtext => { text = std::str::from_utf8(value.trim_ascii()).ok().and_then(|s| u64::from_str_radix(s, 16).ok()).and_then(|h| contents.get(&h)); } b"101" => mtext = false, b"1" | b"3" if mtext && text.is_some() => { if let Some(&text) = text && !written { let mut writer = DxfTextWriter::new(&mut *out); if doc.version < acadrust::DxfVersion::AC1021 && let Some(encoding) = acadrust::io::dxf::code_page::encoding_from_code_page(&doc.header.code_page) { writer.set_encoding(encoding); } // Each character can expand to two caret-escape characters. Keep // those pairs together and each group within 250 characters. let mut rest = text; while let Some((end, _)) = rest.char_indices().nth(125) { let (chunk, tail) = rest.split_at(end); writer.write_xrecord_string(3, chunk)?; rest = tail; } writer.write_xrecord_string(1, rest)?; written = true; } continue; } _ => {} } out.write_all(code)?; out.write_all(value)?; } Ok(()) } #[cfg(test)] #[test] fn mtext_contents_keeps_other_groups_and_the_output_limit() -> acadrust::Result<()> { for version in [acadrust::DxfVersion::AC1015, acadrust::DxfVersion::AC1032] { let mut doc = acadrust::CadDocument::new(); doc.version = version; doc.header.code_page = "ANSI_1252".into(); let mut t = acadrust::MText::with_value("é ^ C", acadrust::Vector3::ZERO); t.common.handle = acadrust::Handle::new(0x10); doc.add_entity(acadrust::EntityType::MText(Box::new(t)))?; // Only the MTEXT's own 1/3 groups change. The embedded object's groups and the // following TEXT record must survive byte-for-byte, including their spaces. let prefix = b" 0\r\nMTEXT\r\n 5\r\n10\r\n 8\r\n0\r\n"; let suffix = b"101\r\nEmbedded Object\r\n 1\r\n^ embedded\r\n 3\r\n^ tail\r\n 0\r\nTEXT\r\n 1\r\n^ plain\r\n"; let raw = [prefix.as_slice(), b" 3\r\nold\r\n 1\r\ntext\r\n", suffix.as_slice()].concat(); let mut out = CappedWriter { buf: raw.clone(), limit: 4096, exceeded: false }; mtext_contents(&doc, &mut out)?; let value: &[u8] = if version == acadrust::DxfVersion::AC1015 { b"\xe9 ^ C" } else { "é ^ C".as_bytes() }; assert_eq!(out.buf, [prefix.as_slice(), b" 1\r\n", value, b"\r\n", suffix.as_slice()].concat()); let mut limited = CappedWriter { buf: raw, limit: 1, exceeded: false }; assert!(mtext_contents(&doc, &mut limited).is_err()); assert!(limited.exceeded); } Ok(()) } /// Most record types named in the skipped-records note. const NOTE_TYPES: usize = 6; /// The note on object records a failsafe read skipped: how many, and how many of each type /// (most first), or nothing when the read was complete. pub(crate) fn read_notes(stats: &acadrust::ReadStats) -> Vec { let skipped = stats.skipped_source_records; if skipped == 0 { return Vec::new(); } let label = |t: Option<&str>| match t.map(str::parse::) { Some(Ok(code)) => type_name(code).map_or_else(|| format!("type {code}"), str::to_string), Some(Err(_)) => t.unwrap_or_default().to_string(), None => "unknown".to_string(), }; let mut by_type: std::collections::BTreeMap = std::collections::BTreeMap::new(); for d in stats.diagnostics.iter().filter(|d| d.record_handle.is_some()) { *by_type.entry(label(d.record_type.as_deref())).or_default() += 1; } let mut types: Vec<(String, usize)> = by_type.into_iter().collect(); types.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); let mut list: Vec = types.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t} × {n}")).collect(); if types.len() > NOTE_TYPES { list.push(format!("{} more types", types.len() - NOTE_TYPES)); } let of = if stats.source_records > 0 { format!(" of {}", stats.source_records) } else { String::new() }; let records = if skipped == 1 && of.is_empty() { "object record" } else { "object records" }; let (were, them) = if skipped == 1 { ("was", "it") } else { ("were", "them") }; let which = if list.is_empty() { String::new() } else { format!(" ({})", list.join(", ")) }; vec![format!( "DWG: {skipped}{of} {records} couldn't be read and {were} left out{which}; \ saving over the original file would lose {them}" )] } /// The DXF name of a DWG object type code with a fixed number (classes, 500 and up, are /// numbered per file). fn type_name(code: i16) -> Option<&'static str> { Some(match code { 1 => "TEXT", 2 => "ATTRIB", 3 => "ATTDEF", 4 => "BLOCK", 5 => "ENDBLK", 6 => "SEQEND", 7 => "INSERT", 8 => "MINSERT", 10..=14 => "VERTEX", 15 | 16 | 29 | 30 => "POLYLINE", 17 => "ARC", 18 => "CIRCLE", 19 => "LINE", 20..=26 => "DIMENSION", 27 => "POINT", 28 => "3DFACE", 31 => "SOLID", 32 => "TRACE", 33 => "SHAPE", 34 => "VIEWPORT", 35 => "ELLIPSE", 36 => "SPLINE", 37 => "REGION", 38 => "3DSOLID", 39 => "BODY", 40 => "RAY", 41 => "XLINE", 42 => "DICTIONARY", 43 => "OLEFRAME", 44 => "MTEXT", 45 => "LEADER", 46 => "TOLERANCE", 47 => "MLINE", 48 => "BLOCK_CONTROL", 49 => "BLOCK_RECORD", 50 => "LAYER_CONTROL", 51 => "LAYER", 52 => "STYLE_CONTROL", 53 => "STYLE", 56 => "LTYPE_CONTROL", 57 => "LTYPE", 60 => "VIEW_CONTROL", 61 => "VIEW", 62 => "UCS_CONTROL", 63 => "UCS", 64 => "VPORT_CONTROL", 65 => "VPORT", 66 => "APPID_CONTROL", 67 => "APPID", 68 => "DIMSTYLE_CONTROL", 69 => "DIMSTYLE", 70 => "VX_CONTROL", 71 => "VX_TABLE_RECORD", 72 => "GROUP", 73 => "MLINESTYLE", 74 => "OLE2FRAME", 77 => "LWPOLYLINE", 78 => "HATCH", 79 => "XRECORD", 80 => "ACDBPLACEHOLDER", 82 => "LAYOUT", _ => return None, }) } /// Merged table cells onto the cells. acadrust 0.6.3 reads a 2010+ (AC1024+) DWG table's /// merged cells into the table's `merged_ranges` only, while its DXF writer writes each cell's /// own merge groups (173, 175, 176), so without this the merges would be lost. Tables whose /// cells already carry merges are left alone. Each range's first cell gets the span; the /// cells it covers are marked merged with no span of their own, as CADCraft's DXF writer does. fn table_merges(doc: &mut acadrust::CadDocument) { table_merges_within(doc, MAX_MERGE_CELLS); } /// The most table cells [`table_merges`] visits in one document: each range is capped, but /// can cover rows × cols cells, so the total is bounded too. const MAX_MERGE_CELLS: usize = 1 << 24; /// A table cell's own text height only when the file says it overrides the table style's. /// acadrust's DXF writer writes a cell style's height (group 140) whenever the cell has a /// style record, even a default 0.18 with no override flag, and CADCraft reads a 140 as an /// override (#2501). The override is the cell style's TEXT_HEIGHT property flag or the /// content's format override bit 128; without either the height is cleared (0 is no /// override), so the table style's height applies. fn table_cell_heights(doc: &mut acadrust::CadDocument) { use acadrust::entities::table::CellStylePropertyFlags; const CONTENT_TEXT_HEIGHT: i32 = 128; for e in doc.entities_mut() { let acadrust::entities::EntityType::Table(t) = e else { continue }; for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { // The first content's own height (group 144) when its format override sets bit 128. // CADCraft keeps one height for the cell's text, so a later content's override // must not stand in for the first content's. let content_height = cell .contents .first() .filter(|c| c.format_override_flags & CONTENT_TEXT_HEIGHT != 0) .map(|c| c.text_height) .filter(|h| h.is_finite() && *h > 0.0); if let Some(h) = content_height { // CADCraft reads only the style's height (group 140), so carry it there. cell.style.get_or_insert_with(acadrust::entities::table::CellStyle::new).text_height = h; continue; } // A style overrides through its property flags or, in newer files, its override // flags; anything else is the writer's default and is cleared. if let Some(style) = cell.style.as_mut() && !style.property_flags.contains(CellStylePropertyFlags::TEXT_HEIGHT) && style.override_flags & CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32 == 0 { style.text_height = 0.0; } } } } /// The fix-ups made to a document after the DWG read, returning how many orphaned DGN /// components were dropped. The document comes from a third-party reader and is hostile. fn post_process(doc: &mut acadrust::CadDocument) -> usize { super::fail_in_test("post_process"); current_style_names(doc); table_merges(doc); table_cell_heights(doc); table_style_rows(doc, false); keep_sort_handles(doc); drop_orphaned_dgn_components(doc) } /// Runs `f`, turning a panic into an error (the reader and writer are guarded the same way). fn guarded(f: impl FnOnce() -> R + std::panic::UnwindSafe) -> Result { std::panic::catch_unwind(f).map_err(|_| ()) } /// The version a proxy record of a DWG of `version` names its format by (Open Design /// Specification for .dwg, proxy objects): 19 for R13, 21 for R14, 23 for 2000, 25 for 2004, /// 27 for 2007, 29 for 2010, 31 for 2013 and 33 for 2018; `None` for any other version. pub(super) fn proxy_dwg_version(version: acadrust::DxfVersion) -> Option { Some(match version.version_code() { 1012 => 19, 1014 => 21, 1015 => 23, 1018 => 25, 1021 => 27, 1024 => 29, 1027 => 31, 1032 => 33, _ => return None, }) } /// Objects of another application's class that acadrust keeps only as their DWG record /// (`ObjectType::Unknown`, which has no DXF form): its DXF writer left them out, and the /// references to them went with them (a dimension's extension dictionary entry naming its /// application data, say), with no note. Each is carried as a proxy object of its class instead /// (DXF Reference, ACAD_PROXY_OBJECT), so the DXF keeps it and a DWG written from that DXF has it /// again: its common object data (owner, reactors, extension dictionary) and the streams after /// it (data bits, R2007+ strings, object references), as the Open Design Specification for .dwg /// splits an object record. Objects of the drawing database's own classes are not turned into /// another application's proxies. What is still without a DXF form is named in the notes, so a /// save over the original is not mistaken for a complete one. fn application_objects(doc: &mut acadrust::CadDocument) -> Vec { use acadrust::objects::{ObjectType, ProxyObject}; let classes: Vec = doc.classes.iter().cloned().collect(); let source = doc.dwg_source_version.unwrap_or(doc.version); if let Some(dwg_version) = proxy_dwg_version(source) { let maintenance = i32::from(doc.maintenance_version); for object in doc.objects.values_mut() { let ObjectType::Unknown { handle, raw_dwg_data: Some(data), raw_dwg_handle_bits, raw_dwg_version: Some(version), type_name, .. } = &*object else { continue; }; if !application_class(&classes, type_name) { continue; } let raw = acadrust::entities::RawRecord { data: data.clone(), handle_bits: *raw_dwg_handle_bits, version: *version }; let handle = *handle; // A record that doesn't split stays as it was, and is named below. let Ok(Ok(record)) = std::panic::catch_unwind(AssertUnwindSafe(|| object_record(&raw, handle.value()))) else { continue }; let Some(class) = classes.iter().find(|c| c.class_number == record.kind && !c.is_an_entity) else { continue }; *object = ObjectType::ProxyObject(ProxyObject { handle, owner: record.owner, reactors: record.reactors, xdictionary_handle: record.xdictionary, proxy_id: 499, class_id: i32::from(class.class_number), dwg_version, maintenance_version: maintenance, version: (maintenance << 16) | dwg_version, payload: record.payload, text_payload: record.text_payload, object_ids: record.object_ids, ..Default::default() }); } } let mut left: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); for object in doc.objects.values() { if let ObjectType::Unknown { type_name, raw_dxf_codes: None, .. } = object { let n = left.entry(type_name.as_str()).or_insert(0); *n = n.saturating_add(1); } } if left.is_empty() { return Vec::new(); } let total = left.values().fold(0usize, |a, n| a.saturating_add(*n)); let mut list: Vec = left.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t:.60} × {n}")).collect(); if left.len() > NOTE_TYPES { list.push(format!("{} more types", left.len() - NOTE_TYPES)); } vec![format!( "DWG: {total} objects of types this bridge can't preserve were left out ({}); saving over the original file would lose them", list.join(", ") )] } /// Whether `name` is an object class of another application, which only that application /// rebuilds: not one of the drawing database's own classes (`AcDb…`/`ACDB…`/`ACAD_…`), whose /// leftovers the database regenerates itself. fn application_class(classes: &[acadrust::classes::DxfClass], name: &str) -> bool { classes.iter().any(|c| { !c.is_an_entity && c.dxf_name.eq_ignore_ascii_case(name) && !c.cpp_class_name.starts_with("AcDb") && !["ACDB", "ACAD_", "ACAD"].iter().any(|p| c.dxf_name.to_ascii_uppercase().starts_with(p)) }) } /// An application object acadrust kept only as its record: the parts a proxy object carries. struct ObjectRecord { kind: i16, owner: acadrust::types::Handle, reactors: Vec, xdictionary: Option, payload: acadrust::objects::ProxyPayload, text_payload: acadrust::objects::ProxyPayload, object_ids: Vec, } /// Split an object record into its common object data and the uninterpreted streams after it /// (data bits, R2007+ strings and object references), as an application object's proxy holds /// them (Open Design Specification for .dwg, common object data and proxy objects). The record /// is hostile: sizes are checked against it, and acadrust's checked stream reader does the rest. fn object_record(raw: &acadrust::entities::RawRecord, handle: u64) -> Result { use acadrust::io::dwg::{ DwgVersion, dwg_reference_type::DwgReferenceType, dwg_stream_readers::object_reader::DwgObjectReader, dwg_stream_writers::bit_writer::DwgBitWriter, }; use acadrust::objects::{ProxyObjectReference, ProxyPayload, ProxyReferenceKind}; use acadrust::types::{DxfVersion, Handle}; if raw.data.len() > 32 << 20 { return Err("object record exceeds the transport limit".into()); } let handle_bits = usize::try_from(raw.handle_bits).map_err(|_| "object has a negative handle stream size")?; let total_bits = raw.data.len().checked_mul(8).ok_or("object record is too large")?; if handle_bits > total_bits { return Err("object handle stream exceeds its record".into()); } let version = DwgVersion::from_dxf_version(raw.version).map_err(|e| e.to_string())?; let mut frame = DwgBitWriter::new(version, raw.version); frame.write_modular_short(raw.data.len()); if raw.version >= DxfVersion::AC1024 { frame.write_modular_char(handle_bits); } frame.write_bytes(&raw.data); let reader = DwgObjectReader::new(frame.into_bytes(), raw.version, std::collections::HashMap::new()).map_err(|e| e.to_string())?; let (kind, mut streams) = reader.read_record_at(0).map_err(|e| e.to_string())?; if kind < 500 { return Err("object has no application class".into()); } let common = reader.read_common_non_entity_data(&mut streams, kind); streams.check_error().map_err(|e| e.to_string())?; if common.common.handle != handle { return Err("object record names another handle".into()); } let read_bits = |count: usize, bit: &mut dyn FnMut() -> bool| -> Result { if count > total_bits { return Err("object stream exceeds its record".into()); } let n = u32::try_from(count).map_err(|_| "object stream is too large")?; let mut bytes = vec![0u8; count.div_ceil(8)]; for index in 0..count { if bit() && let Some(b) = bytes.get_mut(index / 8) { *b |= 0x80 >> (index % 8); } } Ok(ProxyPayload::from_bits(&bytes, n)) }; let main = usize::try_from(streams.main_remaining_bits()).map_err(|_| "object body has an invalid size")?; let payload = read_bits(main, &mut || streams.read_bit())?; let text_payload = if raw.version >= DxfVersion::AC1021 { let bits = usize::try_from(streams.text_remaining_bits()).map_err(|_| "object has a negative string stream size")?; read_bits(bits, &mut || streams.read_text_bit())? } else { ProxyPayload::default() }; // Every reference to the end of the handle stream, null ones too: an object keeps a null pointer in its // field's place, and the references after it are the next fields' (as acadrust reads a proxy's own). R2010+ // records give the stream's exact length; the bits of its last byte past it are padding. let mut object_ids = Vec::new(); let mut left = if raw.version >= DxfVersion::AC1024 { streams.get_handle_bits().max(0).min(streams.handle_remaining_bits()) } else { streams.handle_remaining_bits() }; while left >= 8 { if object_ids.len() >= 100_000 { return Err("object has too many references".into()); } let before = streams.handle_remaining_bits(); let (target, reference) = streams.read_handle_reference(handle); let used = before.saturating_sub(streams.handle_remaining_bits()); if used <= 0 || used > left { break; } left -= used; let kind = match reference { DwgReferenceType::SoftOwnership => ProxyReferenceKind::SoftOwnership, DwgReferenceType::HardOwnership => ProxyReferenceKind::HardOwnership, DwgReferenceType::SoftPointer => ProxyReferenceKind::SoftPointer, DwgReferenceType::HardPointer => ProxyReferenceKind::HardPointer, DwgReferenceType::Undefined => ProxyReferenceKind::Undefined, }; object_ids.push(ProxyObjectReference { handle: Handle::from(target), kind }); } streams.check_error().map_err(|e| e.to_string())?; Ok(ObjectRecord { kind, owner: Handle::from(common.owner_handle), reactors: common.reactors.into_iter().map(Handle::from).collect(), xdictionary: common.xdictionary_handle.map(Handle::from), payload, text_payload, object_ids, }) } /// [`table_merges`] visiting at most `budget` cells in all; a range that would pass it is /// left unmerged. Returns the cells visited. fn table_merges_within(doc: &mut acadrust::CadDocument, budget: usize) -> usize { let mut left = budget; for e in doc.entities_mut() { let acadrust::entities::EntityType::Table(t) = e else { continue }; if t.merged_ranges.is_empty() || t.rows.iter().flat_map(|r| &r.cells).any(|c| c.merge_width > 1 || c.merge_height > 1) { continue; } let (rows, cols) = (t.rows.len(), t.columns.len()); // A real table has at most one merge per cell; more ranges than that come from a // damaged file and would only make this rows × cols × ranges. let max_ranges = rows.saturating_mul(cols).min(1 << 16); for r in t.merged_ranges.iter().take(max_ranges).copied().collect::>() { // Clamp to the table: the ranges come from the file. let (bottom, right) = (r.bottom_row.min(rows.saturating_sub(1)), r.right_col.min(cols.saturating_sub(1))); if r.top_row > bottom || r.left_col > right || rows == 0 || cols == 0 || (r.top_row, r.left_col) == (bottom, right) { continue; } let area = (bottom - r.top_row + 1).saturating_mul(right - r.left_col + 1); if area > left { continue; } left -= area; let span = |n: usize| i32::try_from(n + 1).unwrap_or(i32::MAX); for (ri, row) in t.rows.iter_mut().enumerate().take(bottom + 1).skip(r.top_row) { for (ci, cell) in row.cells.iter_mut().enumerate().take(right + 1).skip(r.left_col) { cell.merged = 1; let first = (ri, ci) == (r.top_row, r.left_col); cell.merge_width = if first { span(right - r.left_col) } else { 0 }; cell.merge_height = if first { span(bottom - r.top_row) } else { 0 }; } } } } budget - left } /// Draw-order tables (SORTENTSTABLE) keep the sort handles the file gave them. acadrust's DXF /// writer renumbers them past every entity handle, but an entity left out of a table sorts by /// its own handle, so after renumbering it would draw below every listed entity (#2410). Giving /// the table its codes verbatim makes the writer emit them unchanged. fn keep_sort_handles(doc: &mut acadrust::CadDocument) { use acadrust::objects::ObjectType; let version = doc.version; for o in doc.objects.values_mut() { let ObjectType::SortEntitiesTable(t) = o else { continue }; let hex = |h: acadrust::types::Handle| format!("{:X}", h.value()); let mut codes = vec![(5, hex(t.handle)), (330, hex(t.owner_handle)), (100, "AcDbSortentsTable".to_string()), (330, hex(t.block_owner_handle))]; for e in t.entries() { codes.push((331, hex(e.entity_handle))); codes.push((5, hex(e.sort_handle))); } t.raw_dxf_codes = Some(codes); t.raw_dxf_version = Some(version); } } /// Table styles' title and header suppression between the two places acadrust 0.6.3 keeps /// it. 2010+ (AC1024+) DWG stores it only in the style's flags (title 1, header 2), while /// acadrust's DXF reader and writer use the `title_suppressed`/`header_suppressed` fields /// (groups 280, 281). `to_flags` copies the fields into the flags before a DWG is written; /// otherwise the flags are copied into the fields after one is read. Older versions store /// both and are left alone. fn table_style_rows(doc: &mut acadrust::CadDocument, to_flags: bool) { use acadrust::objects::{ObjectType, TableStyleFlags}; if doc.version < acadrust::DxfVersion::AC1024 { return; } for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; for (bit, suppressed) in [(TableStyleFlags::TITLE_SUPPRESSED, &mut s.title_suppressed), (TableStyleFlags::HEADER_SUPPRESSED, &mut s.header_suppressed)] { if to_flags { s.flags.set(bit, *suppressed); } else { *suppressed = s.flags.contains(bit); } } } } /// A FIELD's format string between the two places acadrust 0.6.6 keeps it. Its DXF reader /// puts a pre-2007 field's format (group 4) only in `Field::format`, and its DWG writer /// writes that one only for versions before 2007; from 2007 it writes `value.format`. A field /// read from an older drawing and written as DWG 2007 or later would lose its format /// (`dd/MM/yyyy`, `%lu2`). The child values hold no format of their own in the old DXF. /// /// `legacy`: the group 4 formats of a DXF that was read as a newer version than it declares /// ([`legacy_field_formats`]), which the reader then skipped. They go back into an empty /// `Field::format` first, as the reader puts them there under the DXF's own version, so a /// DWG before 2007 keeps them too. fn field_formats(doc: &mut acadrust::CadDocument, legacy: &[(acadrust::Handle, String)]) { for (handle, format) in legacy { if let Some(acadrust::objects::ObjectType::Field(f)) = doc.objects.get_mut(handle) && f.format.is_empty() { f.format.clone_from(format); } } if doc.version < acadrust::DxfVersion::AC1021 { return; } for o in doc.objects.values_mut() { let acadrust::objects::ObjectType::Field(f) = o else { continue }; if f.value.format.is_empty() && !f.format.is_empty() { f.value.format = f.format.clone(); } } } /// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification, /// common dimension data), which acadrust keeps no copy of from DXF: it is set here as /// CADCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128, /// acadrust 0.6.6 reads and writes itself. fn dimension_flags(doc: &mut acadrust::CadDocument) { for e in doc.entities_mut() { let acadrust::entities::EntityType::Dimension(d) = e else { continue }; d.base_mut().dwg_flags_byte |= 0x02; } } /// Leave out DGN line style components (`LS*COMPONENT`) that no line style definition uses /// (#1482). A drawing that once came from `MicroStation` can carry hundreds of thousands of /// them, orphaned copies piled up by earlier DGN imports and copy-pastes (`AutoCAD`'s PURGE /// removes them as orphaned data): in a real 83 MB site plan they were 888,483 of 889,053 /// components and made its DXF rendition 1.2 GB, over [`Limits::DEFAULT`], so the file /// didn't open at all. No definition that was read refers to them (a definition the reader /// skipped can't use them either) and CADCraft doesn't draw DGN line styles, so nothing /// visible is lost. /// Every component a definition reaches (directly, or through compound and point /// components) is kept, as are the definitions; dictionary entries that named a dropped /// component go with it. Returns how many were left out. fn drop_orphaned_dgn_components(doc: &mut acadrust::CadDocument) -> usize { use acadrust::objects::{DgnLineStyleData, ObjectType}; use std::collections::{HashMap, HashSet}; // Each component's references, and the definitions' root components to start from. let mut refs: HashMap> = HashMap::new(); let mut stack: Vec = Vec::new(); for (h, o) in &doc.objects { let ObjectType::DgnLineStyle(ls) = o else { continue }; match &ls.data { DgnLineStyleData::Definition { root_component, .. } => stack.push(*root_component), DgnLineStyleData::Component { component, .. } => { refs.insert(*h, component.references()); } DgnLineStyleData::Registered { .. } => {} } } if refs.is_empty() { return 0; } // Each component is visited once, so cycles and shared subtrees end. let mut used: HashSet = HashSet::new(); while let Some(h) = stack.pop() { if let Some(r) = refs.get(&h) && used.insert(h) { stack.extend(r.iter().copied()); } } let orphans: HashSet = refs.into_keys().filter(|h| !used.contains(h)).collect(); if orphans.is_empty() { return 0; } doc.objects.retain(|h, _| !orphans.contains(h)); doc.dgn_ls_components.retain(|h, _| !orphans.contains(h)); for o in doc.objects.values_mut() { let ObjectType::Dictionary(d) = o else { continue }; if d.entries.iter().any(|(_, e)| orphans.contains(e)) { d.entries.retain(|(_, e)| !orphans.contains(e)); let keys: HashSet<&str> = d.entries.iter().map(|(k, _)| k.as_str()).collect(); d.hard_owner_entries.retain(|k| keys.contains(k.as_str())); } } orphans.len() } /// Leave out what acadrust can't write as this DWG version: other programs' custom entities /// and objects without raw DWG data of that version. acadrust 0.6.4 refuses the whole file /// for one of them (0.6.3 left them out); CADCraft already tells the user which entity types /// a DWG doesn't keep (`not_saved`), so the rest of the drawing is written. Returns how many /// records of each DXF type were left out, so a save can say so. fn drop_unwritable(doc: &mut acadrust::CadDocument) -> super::Unwritten { let version = doc.version; let mut dropped = super::Unwritten::new(); let mut count = |name: &str| { let n = dropped.entry(name.trim().to_ascii_uppercase()).or_insert(0); *n = n.saturating_add(1); }; let unwritable: Vec = doc .entities() .filter_map(|e| match e { acadrust::entities::EntityType::Unknown(u) if u.raw_dwg_data.is_none() || u.dwg_source_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => { count(&u.dxf_name); Some(u.common.handle) } _ => None, }) .collect(); for h in &unwritable { doc.remove_entity(*h); } let objects: Vec = doc .objects .iter() .filter_map(|(h, o)| match o { acadrust::objects::ObjectType::Unknown { type_name, raw_dwg_data, raw_dwg_version, .. } if raw_dwg_data.is_none() || raw_dwg_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => { count(type_name); Some(*h) } _ => None, }) .collect(); for h in &objects { doc.objects.remove(h); } dropped } /// Header variables the DWG reader fills in but acadrust's DXF writer (0.6.3) leaves out of /// the HEADER section: (name, group code, value). fn unwritten_header_vars(h: &acadrust::document::HeaderVariables) -> [(&'static str, i32, String); 7] { [ // DWG holds radians; `$ANGBASE` is in degrees. ("$ANGBASE", 50, h.angle_base.to_degrees().to_string()), ("$ANGDIR", 70, h.angle_direction.to_string()), ("$FILLETRAD", 40, h.fillet_radius.to_string()), ("$CHAMFERA", 40, h.chamfer_distance_a.to_string()), ("$CHAMFERB", 40, h.chamfer_distance_b.to_string()), ("$ELEVATION", 40, h.elevation.to_string()), ("$THICKNESS", 40, h.thickness.to_string()), ] } /// Add the [`unwritten_header_vars`] to the HEADER section of acadrust's DXF text, before its /// ENDSEC; a variable the writer already wrote is left alone. Text of another layout than /// acadrust's (` 0\r\nSECTION\r\n 2\r\nHEADER\r\n` … ` 0\r\nENDSEC\r\n`) is returned unchanged. fn add_header_vars(mut dxf: Vec, h: &acadrust::document::HeaderVariables) -> Vec { const START: &[u8] = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n"; const END: &[u8] = b"\r\n 0\r\nENDSEC\r\n"; if !dxf.starts_with(START) { return dxf; } let Some(end) = dxf.windows(END.len()).position(|w| w == END).map(|p| p + 2) else { return dxf }; let section = dxf.get(..end).unwrap_or_default(); let mut add = String::new(); for (name, code, value) in unwritten_header_vars(h) { let written = section.windows(name.len() + 2).any(|w| w.starts_with(name.as_bytes()) && w.ends_with(b"\r\n")); if !written && value.parse::().is_ok_and(f64::is_finite) { let _ = write!(add, " 9\r\n{name}\r\n{code:>3}\r\n{value}\r\n"); } } dxf.splice(end..end, add.into_bytes()); dxf } /// Collects the DXF text and fails the write once it would grow past `limit`. struct CappedWriter { buf: Vec, limit: usize, exceeded: bool, } impl Write for CappedWriter { fn write(&mut self, b: &[u8]) -> std::io::Result { // Sticky: once over, every later write fails too. if self.exceeded || self.buf.len().saturating_add(b.len()) > self.limit { self.exceeded = true; return Err(std::io::Error::other("DXF size limit reached")); } self.buf.extend_from_slice(b); Ok(b.len()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } /// Oldest DWG version written; older DXF input is written as this version. const MIN_DWG_VERSION: acadrust::DxfVersion = acadrust::DxfVersion::AC1018; /// Convert DXF bytes into a DWG file of the DXF's version, and at least `AutoCAD` 2004 /// (AC1018). /// /// # Errors /// /// Returns an error when the DXF cannot be decoded or the DWG cannot be written, including oversized input. pub fn dxf_to_dwg(dxf: &[u8]) -> Result, String> { convert(dxf, None, None).map(|(dwg, _)| dwg) } /// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"), /// whatever version the DXF declares. /// /// # Errors /// /// Returns an error for an unsupported version, invalid DXF, oversized input, or a DWG write failure. pub fn dxf_to_dwg_as(dxf: &[u8], version: &str) -> Result, String> { dxf_to_dwg_noted(dxf, version).map(|(dwg, _)| dwg) } /// [`dxf_to_dwg_as`], also returning what the DWG writer left out: how many records of each /// DXF type it can't write (other programs' custom entities and objects that the DWG reader /// didn't read from a DWG of this version), empty when the DWG keeps everything. pub fn dxf_to_dwg_noted(dxf: &[u8], version: &str) -> Result<(Vec, super::Unwritten), String> { convert(dxf, Some(writable(version)?), None) } /// Like [`dxf_to_dwg_as`], for a DXF that declares an older version than the groups it carries /// over from another file. CADCraft's R2000 DWG bridge holds the objects it keeps without /// modelling them (render settings, fields, associative and dynamic block data) as they were /// read from a file of version `kept` ("AC1032"), and acadrust reads several of those /// differently by version: read as R2000, an AC1032 file's mental ray render settings came out /// a class version too high, for which the ODA rejects the whole DWG, and a field lost its /// cached value. So the DXF is read as `kept` declares; the formats of the DXF's own pre-2007 /// fields, which the reader skips then, are restored. A `kept` /// version that is unknown, or not newer than the DXF's own, changes nothing. pub fn dxf_to_dwg_kept_as(dxf: &[u8], version: &str, kept: &str) -> Result, String> { dxf_to_dwg_kept_noted(dxf, version, kept).map(|(dwg, _)| dwg) } /// [`dxf_to_dwg_kept_as`], also returning what the DWG writer left out, as /// [`dxf_to_dwg_noted`] does. pub fn dxf_to_dwg_kept_noted(dxf: &[u8], version: &str, kept: &str) -> Result<(Vec, super::Unwritten), String> { let kept = acadrust::DxfVersion::from_version_string(kept.trim().to_ascii_uppercase().as_str()); let kept = (kept != acadrust::DxfVersion::Unknown).then_some(kept); convert(dxf, Some(writable(version)?), kept) } /// The DWG version for a code from [`super::VERSIONS`]. fn writable(version: &str) -> Result { Ok(match version.trim().to_ascii_uppercase().as_str() { "AC1015" => acadrust::DxfVersion::AC1015, "AC1018" => acadrust::DxfVersion::AC1018, "AC1021" => acadrust::DxfVersion::AC1021, "AC1024" => acadrust::DxfVersion::AC1024, "AC1027" => acadrust::DxfVersion::AC1027, "AC1032" => acadrust::DxfVersion::AC1032, _ => return Err(super::unsupported(version)), }) } /// The ASCII DXF with its `$ACADVER` set to `kept` when that is newer than the version it /// declares, or `None` to read it as it is (binary, no `$ACADVER`, or non-ASCII text without a /// `$DWGCODEPAGE` to decode it by). From AutoCAD 2007 (AC1021) a DXF is UTF-8, so other bytes /// are first decoded with the code page the DXF declares; `\U+XXXX` escapes read the same in /// every version, and CADCraft's R2000 DXF is ASCII with such escapes. pub(super) fn declare_version(dxf: &[u8], kept: acadrust::DxfVersion) -> Option> { if dxf.starts_with(b"AutoCAD Binary DXF") { return None; } let (_, declared) = header_value(dxf, b"$ACADVER")?; let declared = acadrust::DxfVersion::from_version_string(std::str::from_utf8(declared).ok()?); if declared >= kept { return None; } let text: std::borrow::Cow<'_, [u8]> = if dxf.is_ascii() || kept < acadrust::DxfVersion::AC1021 { std::borrow::Cow::Borrowed(dxf) } else { // As acadrust decodes an older DXF: by its code page, Windows-1252 for one it doesn't // know; a code page that names UTF-8 needs no decoding. let (_, code_page) = header_value(dxf, b"$DWGCODEPAGE")?; match acadrust::io::dxf::code_page::encoding_from_code_page(std::str::from_utf8(code_page).ok()?) { Some(encoding) => { let (text, errors) = encoding.decode_without_bom_handling(dxf); if errors { return None; } std::borrow::Cow::Owned(text.into_owned().into_bytes()) } None => std::borrow::Cow::Borrowed(std::str::from_utf8(dxf).ok()?.as_bytes()), } }; let (at, value) = header_value(&text, b"$ACADVER")?; let code = kept.to_string(); let mut out = Vec::with_capacity(text.len().saturating_add(code.len())); out.extend_from_slice(text.get(..at)?); out.extend_from_slice(code.as_bytes()); out.extend_from_slice(text.get(at.checked_add(value.len())?..)?); Some(out) } /// The format (group 4) of each FIELD record in an ASCII DXF, by handle. acadrust 0.6.6 reads /// it only from a DXF that declares a version before 2007 (AC1021), where it follows the /// field code or the object handles, before group 91 (`read_field_object_dxf`). When /// [`declare_version`] made an older DXF read as 2007 or later, a field the DXF wrote itself /// would lose its format; a field carried over from a 2007+ file has none and keeps its own /// `value.format`. fn legacy_field_formats(dxf: &[u8]) -> Vec<(acadrust::Handle, String)> { let Some(pairs) = super::proxy_transport::text_pairs(dxf) else { return Vec::new() }; let mut formats = Vec::new(); let (mut in_field, mut handle, mut format, mut past) = (false, None, None, false); for pair in pairs { let Some((code, value)) = pair else { break }; match code { 0 => { if let (Some(h), Some(f)) = (handle.take(), format.take()) { formats.push((h, f)); } in_field = value == "FIELD" || value == "ACDBFIELD"; (handle, format, past) = (None, None, false); } 5 if in_field && handle.is_none() => handle = u64::from_str_radix(value.trim(), 16).ok().map(acadrust::Handle::new), 4 if in_field && !past && format.is_none() => format = Some(value), 91 if in_field => past = true, _ => {} } } formats } /// The byte offset and the trimmed value of header variable `name` in an ASCII DXF: the value /// of the group that follows the `9` group naming it. The file is read as (group code, /// value) line pairs, in one pass with no buffering, up to the first `0`/`ENDSEC`, the end /// of the HEADER section: a large input without one costs time, not memory (a line index of /// a 32 MiB file used 0.8 GB). Lines may end in `\r\n`. pub(super) fn header_value<'a>(dxf: &'a [u8], name: &[u8]) -> Option<(usize, &'a [u8])> { let mut offset = 0usize; let mut lines = dxf.split(|b| *b == b'\n').map(|line| { let at = offset.saturating_add(line.len() - line.trim_ascii_start().len()); offset = offset.saturating_add(line.len()).saturating_add(1); (at, line.trim_ascii()) }); while let (Some((_, code)), Some((_, value))) = (lines.next(), lines.next()) { if code == b"0" && value == b"ENDSEC" { return None; } if code == b"9" && value == name { let (_, code) = lines.next()?; let (at, value) = lines.next()?; return (code != b"0" && code != b"9").then_some((at, value)); } } None } /// The current dimension and text styles' names from their handles: a DWG stores the /// handles, and the reader leaves the names at "Standard", so a drawing reopened from DWG /// lost its current dimension style (#1051). fn current_style_names(doc: &mut acadrust::CadDocument) { let h = doc.header.current_dimstyle_handle; if let Some(n) = doc.dim_styles.iter().find(|ds| ds.handle == h && !h.is_null()).map(|ds| ds.name.clone()) { doc.header.current_dimstyle_name = n; } let h = doc.header.current_text_style_handle; if let Some(n) = doc.text_styles.iter().find(|ts| ts.handle == h && !h.is_null()).map(|ts| ts.name.clone()) { doc.header.current_text_style_name = n; } } /// The current dimension style (`$DIMSTYLE`) by its name: the DXF gives the name, and the /// handle read with it needn't be the style's in the document, in which case the DWG writer /// fell back to Standard and `AutoCAD` opened the drawing with Standard current (#1051). fn current_dimstyle(doc: &mut acadrust::CadDocument) { let name = doc.header.current_dimstyle_name.clone(); if let Some(h) = doc.dim_styles.iter().find(|ds| ds.name.eq_ignore_ascii_case(&name)).map(|ds| ds.handle) { doc.header.current_dimstyle_handle = h; } } /// The current text style (`$TEXTSTYLE`) by its name, the same way as [`current_dimstyle`]: /// the handle read with the DXF needn't be the style's in the document, in which case the DWG /// writer fell back to Standard and `AutoCAD` opened the drawing with Standard current (#1650). fn current_text_style(doc: &mut acadrust::CadDocument) { let name = doc.header.current_text_style_name.clone(); if let Some(h) = doc.text_styles.iter().find(|ts| ts.name.eq_ignore_ascii_case(&name)).map(|ts| ts.handle) { doc.header.current_text_style_handle = h; } } /// The R2010+ row cell styles of a table style, in their order. const ROW_NAMES: [&str; 3] = ["_TITLE", "_HEADER", "_DATA"]; /// Whether a table style carries no cell style named `name` (cell style names ignore case). fn missing(s: &acadrust::objects::TableStyle, name: &str) -> bool { !s.modern_overrides.iter().any(|(_, o)| o.name.eq_ignore_ascii_case(name)) } /// Whether a table style gets row cell styles: it lacks some and they all fit. The DWG reader /// keeps only 64 cell styles per table style, so a style with no room for every missing row gets /// none (nothing added, nothing dropped; the rows it has still get their margins, see /// [`table_style_row_margins`]) and the drawing still converts. fn gets_rows(s: &acadrust::objects::TableStyle) -> bool { let missing_rows = ROW_NAMES.iter().filter(|n| missing(s, n)).count(); missing_rows > 0 && s.modern_overrides.len().saturating_add(missing_rows) <= 64 } /// The spacing between cells of the base cell style the DWG writer builds for a table style /// that has none of its own (`modern_style` `None`): the fallback when the style has no base. const ROW_SPACING: f64 = 0.18; /// The margins and spacing of a table style's cell styles: vertical, horizontal, bottom and /// right margin, horizontal and vertical spacing. #[derive(Clone, Copy, Debug, PartialEq)] struct Margins { vertical: f64, horizontal: f64, bottom: f64, right: f64, horizontal_spacing: f64, vertical_spacing: f64, } /// What the DWG writer's own default base cell style carries for the style: its margins, and /// [`ROW_SPACING`]. Rows added to a style whose base carries no margins get these. fn default_base(s: &acadrust::objects::TableStyle) -> Margins { Margins { vertical: s.vertical_margin, horizontal: s.horizontal_margin, bottom: s.vertical_margin, right: s.horizontal_margin, horizontal_spacing: ROW_SPACING, vertical_spacing: ROW_SPACING, } } /// The margins and spacing of the base cell style the writer actually emits for the style, if /// that carries any: the style's own `modern_style` when it has cell style data with margin /// overrides (the writer writes nothing past the data flags otherwise, as after reading a DWG /// whose base has none), or the writer's default base ([`default_base`]) when it has none. /// `None` when the base it emits has no margins: there is nothing to copy to a row then. fn base_margins(s: &acadrust::objects::TableStyle) -> Option { let Some(m) = &s.modern_style else { return Some(default_base(s)) }; let c = &m.cell_style; (c.data_flags != 0 && c.margin_override_flags != 0).then_some(Margins { vertical: c.vertical_margin, horizontal: c.horizontal_margin, bottom: c.bottom_margin, right: c.right_margin, horizontal_spacing: c.horizontal_spacing, vertical_spacing: c.vertical_spacing, }) } /// The cell styles of the table style a built-in row name stands for: every one spelled /// exactly so (the DWG reader applies each in turn, so the last decides), else the first one /// spelled in another case (cell style names ignore case; the reader only takes the exact /// spelling for the row). fn row_indices(s: &acadrust::objects::TableStyle, name: &str) -> Vec { let at = |exact: bool| -> Vec { let same = |n: &str| if exact { n == name } else { n.eq_ignore_ascii_case(name) }; s.modern_overrides.iter().enumerate().filter(|(_, (_, o))| same(&o.name)).map(|(i, _)| i).collect() }; let exact = at(true); if exact.is_empty() { at(false).into_iter().take(1).collect() } else { exact } } /// Whether a row cell style needs no margins of its own: it carries margin overrides, judged as /// the DWG writer and reader judge them (any nonzero `margin_override_flags`), or has no cell /// style data at all (`data_flags` 0: the writer leaves everything past the flag out, so the /// row sets nothing and the base cell style, which carries the style's margins, applies). fn has_margins(c: &acadrust::objects::TableCellStyleData) -> bool { c.data_flags == 0 || c.margin_override_flags != 0 } /// Whether any of the three built-in rows a table style carries needs work: the row is not /// spelled as the DWG reader knows it (`_title`, which it would take for a custom cell style, /// not the title row), or it has no margins ([`has_margins`]; the writer then reads the style's /// margins as 0.06) and the style's base has margins to give it ([`base_margins`]). Every row /// of a name is looked at, not only the first. fn rows_need_work(s: &acadrust::objects::TableStyle) -> bool { let fillable = base_margins(s).is_some(); ROW_NAMES.iter().any(|n| { row_indices(s, n) .into_iter() .filter_map(|i| s.modern_overrides.get(i)) .any(|(_, o)| o.name != *n || (fillable && !has_margins(&o.cell_style))) }) } /// The lowest cell style id from 101 up to `max` that nothing in `held` holds; `None` when /// they are all held. fn free_id(held: &std::collections::HashSet, max: i32) -> Option { (101..=max).find(|n| !held.contains(n)) } /// Table styles' R2010+ row cell styles (`_TITLE`, `_HEADER`, `_DATA`) with the style's cell /// margins (#2920). Without row cell styles of its own (as after reading a DXF), acadrust /// 0.6.6's DWG writer builds them with no margin override, and the reference app then reads /// the style's margins as 0.06 where the drawing has another value. They are built here the /// way that writer builds them, with the margins the writer gives the base `Table` cell /// style. Only missing rows are added, so every style ends with all three (when they fit): a /// row a style carries already keeps its values, except that one with no margin overrides /// gets the margins and spacing of the base cell style the writer emits (the style's own /// `modern_style` when it carries margins, else the writer's default base; none when its base /// has none, and then nothing is copied), and one spelled `_title` takes /// the reader's spelling `_TITLE` only when the style has no exact `_TITLE` (with one, `_title` /// is left as it is); a row whose id another cell style holds gets a free one. /// /// Versions before 2010 return at once, as does a drawing none of whose styles is missing a /// row or has a row that needs work (see above): it is left exactly as it is. Otherwise the /// one thing changed besides the rows is the /// handle of a text style that an added row names and that was read without one (R12, /// HANDLING 0): it is numbered here, as the writer would number it later, so the row finds /// its style as it would there rather than falling to Standard. Other table entries without /// a handle are left for the writer, so the drawing's handle numbering stays the writer's /// own. A style with no room for all its missing rows (64 cell styles at most) gets none, and /// is otherwise changed only as above. An `Err` means a style has no free cell style id (not /// possible short of two billion cell styles). fn table_style_row_margins(doc: &mut acadrust::CadDocument) -> Result<(), String> { table_style_row_margins_up_to(doc, i32::MAX) } /// [`table_style_row_margins`] with cell style ids numbered up to `max_id` at most. fn table_style_row_margins_up_to(doc: &mut acadrust::CadDocument, max_id: i32) -> Result<(), String> { use acadrust::objects::{ NamedTableCellStyle, ObjectType, RowCellStyle, TableCellBorder, TableCellStyleData, TableContentFormat, TableGridFormat, }; use acadrust::types::{Color, Handle}; if doc.version < acadrust::DxfVersion::AC1024 { return Ok(()); } // The text styles the added rows name that have no handle: the writer gives them one // before it looks rows up, so they get it here, and nothing else is numbered. let mut unnumbered: Vec = Vec::new(); for o in doc.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; if !gets_rows(s) { continue; } let rows = [&s.title_row_style, &s.header_row_style, &s.data_row_style]; for (name, row) in ROW_NAMES.iter().zip(rows) { if !missing(s, name) { continue; } let by_handle = row.text_style_handle.is_some_and(|h| !h.is_null() && doc.text_styles.iter().any(|ts| ts.handle == h)); if !by_handle && doc.text_styles.get(&row.text_style_name).is_some_and(|ts| ts.handle.is_null()) { unnumbered.push(row.text_style_name.clone()); } } } for name in unnumbered { if doc.text_styles.get(&name).is_some_and(|ts| ts.handle.is_null()) { let handle = doc.allocate_handle(); if let Some(ts) = doc.text_styles.get_mut(&name) { ts.handle = handle; } } } // A row's text style as the writer finds it: its handle when it is a text style's, else // its name's; a null handle is left for the writer, which gives such a row Standard. let text_styles = &doc.text_styles; let handles: std::collections::HashSet = text_styles.iter().map(|ts| ts.handle).filter(|h| !h.is_null()).collect(); let text_style = |row: &RowCellStyle| { row.text_style_handle .filter(|h| handles.contains(h)) .or_else(|| text_styles.get(&row.text_style_name).map(|ts| ts.handle)) .unwrap_or(Handle::NULL) }; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; let adds_rows = gets_rows(s); if !adds_rows && !rows_need_work(s) { continue; } let base = base_margins(s); // Added rows get the base's margins, or when it has none the default base's ones. let m = base.unwrap_or_else(|| default_base(s)); // The rows the style carries already. A built-in row spelled in another case (and // with no exact spelling in the style) takes the DWG reader's spelling, keeping its id // and formatting, so the reader takes it for the row. One with no margin overrides gets // the base's margins and spacing (nothing when the base the writer emits has none); an // override it has, in any of its flags, is its own and stays. When the style holds the exact spelling too, only that // row is the row (all of them, if it holds it more than once): the other spelling is // left as it is. for name in ROW_NAMES { for i in row_indices(s, name) { let Some((_, o)) = s.modern_overrides.get_mut(i) else { continue }; o.name = name.to_string(); let c = &mut o.cell_style; if let Some(b) = base.filter(|_| !has_margins(c)) { c.margin_override_flags |= 1; (c.vertical_margin, c.bottom_margin) = (b.vertical, b.bottom); (c.horizontal_margin, c.right_margin) = (b.horizontal, b.right); (c.horizontal_spacing, c.vertical_spacing) = (b.horizontal_spacing, b.vertical_spacing); } } } if !adds_rows { continue; } let row_style = |row: &RowCellStyle, id: i32, style_type: i32, name: &str, merge_flags: i32| { // R2010+ edge order; the grid flag is set for a hidden edge, the reverse of the // row border's `is_invisible`. let borders = [ (1, &row.top_border), (2, &row.horizontal_inside_border), (4, &row.bottom_border), (8, &row.left_border), (16, &row.vertical_inside_border), (32, &row.right_border), ] .into_iter() .map(|(index_mask, border)| TableGridFormat { index_mask, border: TableCellBorder { is_invisible: !border.is_invisible, ..border.clone() }, line_type: Handle::NULL, }) .collect(); NamedTableCellStyle { cell_style: TableCellStyleData { style_type: 5, data_flags: 1, merge_flags, background_color: if row.fill_enabled { row.fill_color } else { Color::None }, content_layout: 1, content_format: TableContentFormat { value_data_type: row.data_type, value_unit_type: row.unit_type, value_format_string: row.format_string.clone(), block_scale: 1.0, cell_alignment: row.alignment as i32, content_color: row.text_color, text_style: text_style(row), text_height: row.text_height, ..TableContentFormat::default() }, margin_override_flags: 1, vertical_margin: m.vertical, horizontal_margin: m.horizontal, bottom_margin: m.bottom, right_margin: m.right, horizontal_spacing: m.horizontal_spacing, vertical_spacing: m.vertical_spacing, borders, ..TableCellStyleData::default() }, id, style_type, name: name.to_string(), } }; // Only the rows the style doesn't already carry (a DXF's CELLSTYLEMAP may hold some of // them); the ones it has are dealt with above. A row's id held already by another cell // style (as key or id) gives the row a free id instead, so no two styles share one. An // added row goes right after the last row that comes before it (or first), so the rows // keep _TITLE, _HEADER, _DATA order. let rank = |name: &str| ROW_NAMES.iter().position(|r| r.eq_ignore_ascii_case(name)).unwrap_or(ROW_NAMES.len()); let rows = [(1, 1, 0x8000, s.title_row_style.clone()), (2, 1, 0, s.header_row_style.clone()), (3, 2, 0, s.data_row_style.clone())]; // A set of the numbers held, kept up to date as rows go in, keeps the search linear. let mut held: std::collections::HashSet = s.modern_overrides.iter().flat_map(|(k, o)| [*k, o.id]).collect(); for (name, (id, style_type, merge_flags, row)) in ROW_NAMES.iter().zip(rows) { if !missing(s, name) { continue; } let id = if held.contains(&id) { free_id(&held, max_id).ok_or_else(|| format!("table style {}: no free cell style id for {name}", s.name))? } else { id }; let at = s.modern_overrides.iter().rposition(|(_, o)| rank(&o.name) < rank(name)).map_or(0, |j| j + 1); let row = row_style(&row, id, style_type, name, merge_flags); held.insert(id); s.modern_overrides.insert(at, (id, row)); } } Ok(()) } /// The DXF names of an ASCII DXF's CLASS records, in CLASSES order: a proxy's class number /// (group 91) is 500 plus its class's place here (DXF Reference, ACAD_PROXY_OBJECT). Empty for /// one without a CLASSES section. `None` for a binary DXF, whose classes this doesn't read: /// CADCraft's own bridge DXF is always ASCII, and only a binary DXF given to the public /// conversion functions comes here. pub(super) fn dxf_class_names(dxf: &[u8]) -> Option> { let pairs = super::proxy_transport::text_pairs(dxf)?; let mut names = Vec::new(); let (mut section, mut in_classes, mut in_class) = (false, false, false); for pair in pairs { let (code, value) = pair?; match (code, value.as_str()) { (0, "ENDSEC") if in_classes => break, (0, "SECTION") => section = true, (2, name) if section => { in_classes = name == "CLASSES"; section = false; } (0, kind) if in_classes => { in_class = kind == "CLASS"; // Even an unnamed record keeps its place in the source class table. if in_class { names.push(String::new()); } } (1, value) if in_class => { if let Some(last) = names.last_mut() { *last = value.to_string(); } in_class = false; } _ => section = false, } } Some(names) } /// Proxy objects' and entities' class numbers as the DWG numbers its classes. A DXF proxy /// names its class by its place in the DXF's CLASSES (`classes`, from 500), but acadrust's /// reader puts its own default classes first and numbers the DXF's after them, so the DXF /// number named another class in the DWG: a 2018 drawing's piping proxies became /// LARGE_RADIAL_DIMENSION and SECTIONOBJECT, and the ODA File Converter refused the file. A /// proxy whose number names no class of the DXF is left out: kept as it is, its number would /// name some other class of the DWG, for the same reason. /// /// Before 2013 (AC1027) acadrust writes only the classes it knows a pre-2013 DWG needs, and a /// proxy's class is not one of them: the proxy would name a missing class (the ODA refuses /// the file: "No ClassId") or, by its old number, some other class. Such a DWG leaves the /// proxies out instead, as it does other programs' data it can't write (`not_saved` reports /// the entities). So does a DXF whose classes are unknown (`classes` is `None`, a binary /// DXF): its proxies' numbers can't be mapped, and kept as they are they would name the /// wrong classes and the ODA would refuse the file. Returns the proxies left out, by DXF type, for /// what the DWG writer left out ([`super::Unwritten`]). fn proxy_classes(doc: &mut acadrust::CadDocument, classes: Option<&[String]>) -> super::Unwritten { let classes = match classes { Some(c) if doc.version >= acadrust::DxfVersion::AC1027 => c, _ => { let entities: Vec = doc .entities() .filter_map(|e| match e { acadrust::entities::EntityType::Extended(x) if matches!(x.data, acadrust::entities::ExtendedEntityData::Proxy(_)) => { Some(x.common.handle) } _ => None, }) .collect(); let objects: Vec = doc.objects.iter().filter_map(|(h, o)| matches!(o, acadrust::objects::ObjectType::ProxyObject(_)).then_some(*h)).collect(); for h in &entities { doc.remove_entity(*h); } for h in &objects { doc.objects.remove(h); } return left_out(objects.len(), entities.len()); } }; // Name matching cannot choose between different source classes with the same name. // Count those proxies as unwritten rather than silently changing their class identity. let mut unique = std::collections::HashMap::new(); for name in classes { unique.entry(name.to_uppercase()).and_modify(|value| *value = false).or_insert(true); } let number = |id: i32| -> Option { let name = classes.get(usize::try_from(id.checked_sub(500)?).ok()?)?; if unique.get(&name.to_uppercase()) != Some(&true) { return None; } doc.classes.get_by_name(name).map(|c| i32::from(c.class_number)) }; let objects: Vec<(acadrust::Handle, Option)> = doc .objects .iter() .filter_map(|(h, o)| match o { acadrust::objects::ObjectType::ProxyObject(p) => Some((*h, number(p.class_id))), _ => None, }) .collect(); let entities: Vec<(acadrust::Handle, Option)> = doc .entities() .filter_map(|e| match e { acadrust::entities::EntityType::Extended(x) => match &x.data { acadrust::entities::ExtendedEntityData::Proxy(p) => Some((x.common.handle, number(p.class_id))), _ => None, }, _ => None, }) .collect(); let unmapped = |list: &[(acadrust::Handle, Option)]| list.iter().filter(|(_, n)| n.is_none()).map(|(h, _)| *h).collect::>(); let (gone_objects, gone_entities) = (unmapped(&objects), unmapped(&entities)); for h in &gone_objects { doc.objects.remove(h); } for h in &gone_entities { doc.remove_entity(*h); } let objects = objects.into_iter().filter_map(|(h, n)| Some((h, n?))); let entities = entities.into_iter().filter_map(|(h, n)| Some((h, n?))); for (h, n) in objects { if let Some(acadrust::objects::ObjectType::ProxyObject(p)) = doc.objects.get_mut(&h) { p.class_id = n; } } let entities: std::collections::HashMap = entities.into_iter().collect(); for e in doc.entities_mut() { if let acadrust::entities::EntityType::Extended(x) = e { let Some(n) = entities.get(&x.common.handle).copied() else { continue }; if let acadrust::entities::ExtendedEntityData::Proxy(p) = &mut x.data { p.class_id = n; } } } left_out(gone_objects.len(), gone_entities.len()) } /// Proxy objects and entities left out of the DWG, by their DXF types. fn left_out(objects: usize, entities: usize) -> super::Unwritten { [("ACAD_PROXY_OBJECT", objects), ("ACAD_PROXY_ENTITY", entities)] .into_iter() .filter(|(_, n)| *n > 0) .map(|(t, n)| (t.to_string(), n)) .collect() } /// The current layer (`$CLAYER`) by its name, the same way as [`current_dimstyle`]: a DWG /// stores the handle of the layer, and the one read with the DXF needn't be the layer's in /// the document, so the drawing reopened with layer "0" current (#2252). fn current_layer(doc: &mut acadrust::CadDocument) { let name = doc.header.current_layer_name.clone(); // The table's own lookup compares Unicode case-insensitively ("Survey_Ä" = "Survey_ä"). if let Some(layer) = doc.layers.get(&name) { doc.header.current_layer_handle = layer.handle; } } /// `kept`: the version the DXF's carried-over groups were read from ([`dxf_to_dwg_kept_as`]). fn convert(dxf: &[u8], version: Option, kept: Option) -> Result<(Vec, super::Unwritten), String> { // Reject a pathologically large DXF before handing it to the third-party decoder, which // allocates tables and section buffers from the input's declared sizes and cannot be // interrupted once it starts (CWE-789). This bounds the large-input variant; the decoder // runs inside `catch_unwind` so a decode failure is reported rather than crashing. if dxf.len() > Limits::DEFAULT.max_dxf_bytes { return Err(format!( "DXF: the input is {}, larger than the {} accepted for DWG conversion", mb(dxf.len() as u64), mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } // Decoding a code page to UTF-8 can grow the text, so the limit applies again. let (data, legacy) = match kept.and_then(|k| declare_version(dxf, k).map(|d| (k, d))) { Some((_, d)) if d.len() > Limits::DEFAULT.max_dxf_bytes => { return Err(format!( "DXF: the input is {} as UTF-8, larger than the {} accepted for DWG conversion", mb(d.len() as u64), mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } // Read as 2007 or later, the DXF's own fields lose their formats: restored after. Some((k, d)) => (d, k >= acadrust::DxfVersion::AC1021), None => (dxf.to_vec(), false), }; let (classes, source, legacy) = guarded(AssertUnwindSafe(|| { let legacy = if legacy { legacy_field_formats(&data) } else { Vec::new() }; (dxf_class_names(&data), super::proxy_transport::source_classes(&data), legacy) })) .map_err(|_| "the DXF proxy class conversion failed".to_string())?; let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(acadrust::DxfReader::read)) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; match version { Some(v) => doc.version = v, // Without a version asked for, write at least AutoCAD 2004 (AC1018) DWG: R2000 DWG // has no true colours, transparency, table styles or gradients. The DXF stays R2000; // only the DWG is newer. None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION, None => {} } // The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash. let mut margin_error: Option = None; let unwritten = guarded(AssertUnwindSafe(|| { super::fail_in_test("convert"); // From 2013 the DWG takes the source classes as they are, duplicates and metadata // included; otherwise (before 2013, a binary DXF, classes that can't be written back) // proxies are matched to classes by name or left out. let restored = match source { Some(source) if doc.version >= acadrust::DxfVersion::AC1027 => super::proxy_transport::restore_classes(&mut doc, source), _ => None, }; let proxies = match restored { Some((objects, entities)) => left_out(objects, entities), None => proxy_classes(&mut doc, classes.as_deref()), }; other_layout_owners(&mut doc); table_style_rows(&mut doc, true); field_formats(&mut doc, &legacy); margin_error = table_style_row_margins(&mut doc).err(); dimension_flags(&mut doc); let mut unwritten = drop_unwritable(&mut doc); for (kind, n) in proxies { let total = unwritten.entry(kind).or_insert(0); *total = total.saturating_add(n); } current_dimstyle(&mut doc); add_variable_dictionary(&mut doc); current_text_style(&mut doc); current_layer(&mut doc); unwritten })) .map_err(|()| "the DXF to DWG conversion failed on this file".to_string())?; if let Some(e) = margin_error { return Err(e); } let dwg = std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc))) .map_err(|_| "the DWG writer failed on this drawing".to_string())? .map_err(|e| format!("DWG write: {e}"))?; Ok((dwg, unwritten)) } /// `AutoCAD`'s entry name for the drawing variables dictionary (the DXF Reference calls it the /// ACDBVARIABLEDICTIONARY; dictionary keys are case-insensitive). const VARIABLE_DICTIONARY: &str = "AcDbVariableDictionary"; /// A style or scale name, or `default` when the drawing has none. fn name_or_default(name: &str, default: &str) -> String { let name = name.trim(); if name.is_empty() { default.to_string() } else { name.to_string() } } /// A drawing variable's value as text, or `default` when the header holds a value the /// variable doesn't accept (a hostile file can put any integer in it). fn variable_value(value: i16, valid: &[i16], default: i16) -> String { if valid.contains(&value) { value.to_string() } else { default.to_string() } } /// Add the drawing variables dictionary `AutoCAD` always writes into the named object /// dictionary, with the variables it keeps there, when the drawing has none (#1813). /// Vectric Aspire 10.5 reads a 2004 (AC1018) DWG without it as empty ("No data was imported /// from the DXF / DWG file"), though it reads the same drawing as DXF — which has no such /// dictionary either, as CADCraft's and ezdxf's writers don't make one. `AutoCAD`'s AC1032 DWGs /// read there without it, so newer output is left as it was, and a dictionary the drawing /// does have keeps its own entries and values. fn add_variable_dictionary(doc: &mut acadrust::CadDocument) { use acadrust::objects::{Dictionary, DictionaryVariable, ObjectType}; if doc.version >= acadrust::DxfVersion::AC1032 { return; } let root_handle = doc.header.named_objects_dict_handle; match doc.objects.get(&root_handle) { Some(ObjectType::Dictionary(root)) => { if root.get(VARIABLE_DICTIONARY).is_some() { return; } } _ => return, } // The variables AutoCAD writes for a drawing with default styles and a 1:1 annotation // scale. DIMASSOC and HIDETEXT keep the drawing's own header values; LAYEREVAL and // LAYERNOTIFY have no DXF header variable. let variables = [ ("CMLEADERSTYLE", name_or_default(&doc.header.current_mleader_style_name, "Standard")), ("CTABLESTYLE", name_or_default(&doc.header.current_table_style_name, "Standard")), ("CANNOSCALE", name_or_default(&doc.header.current_annotation_scale, "1:1")), ("DIMASSOC", variable_value(doc.header.dimension_associativity, &[0, 1, 2], 2)), ("HIDETEXT", variable_value(doc.header.hide_text, &[0, 1], 1)), ("LAYEREVAL", "0".to_string()), ("LAYERNOTIFY", "0".to_string()), ]; let dictionary_handle = doc.allocate_handle(); let mut dictionary = Dictionary::new(); dictionary.handle = dictionary_handle; dictionary.owner = root_handle; for (name, value) in variables { let handle = doc.allocate_handle(); let mut variable = DictionaryVariable::new(name, &value); variable.handle = handle; variable.owner_handle = dictionary_handle; dictionary.add_entry(name, handle); doc.objects.insert(handle, ObjectType::DictionaryVariable(variable)); } doc.objects.insert(dictionary_handle, ObjectType::Dictionary(dictionary)); if let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&root_handle) { root.add_entry(VARIABLE_DICTIONARY, dictionary_handle); } } /// Entities of a layout other than the one in `*Paper_Space` are written owned by their block /// (entity mode 0, with its handle). acadrust writes every paper-space entity with mode 1, /// "paper space", which `AutoCAD` reads as the `*Paper_Space` block's: everything drawn on a /// second layout landed on the first one, and the second stayed empty (#1057). fn other_layout_owners(doc: &mut acadrust::CadDocument) { let others: std::collections::HashSet = doc .block_records .iter() .filter(|br| { let n = br.name.to_ascii_uppercase(); n.len() > 12 && n.starts_with("*PAPER_SPACE") && n[12..].bytes().all(|b| b.is_ascii_digit()) }) .map(|br| br.handle) .collect(); if others.is_empty() { return; } for e in doc.entities_mut() { let c = e.common_mut(); if others.contains(&c.owner_handle) { c.entity_mode = Some(0); } } } #[cfg(test)] mod post_tests { use super::*; use acadrust::entities::{CellRange, EntityType, Table}; fn doc_with_table(rows: usize, cols: usize, ranges: usize) -> acadrust::CadDocument { let mut t = Table::new(acadrust::types::Vector3::new(0.0, 0.0, 0.0), rows, cols); t.merged_ranges = (0..ranges).map(|_| CellRange::new(0, 0, rows - 1, cols - 1)).collect(); let mut doc = acadrust::CadDocument::new(); assert!(doc.add_entity(EntityType::Table(Box::new(t))).is_ok()); doc } /// Overlapping whole-table ranges can't make the merge pass visit more than its budget (#1934). #[test] fn merge_work_is_bounded_by_the_cell_budget() { let mut doc = doc_with_table(10, 10, 50); assert_eq!(table_merges_within(&mut doc, 250), 200, "two whole-table ranges fit, the rest are skipped"); let mut doc = doc_with_table(10, 10, 1); assert_eq!(table_merges_within(&mut doc, usize::MAX), 100); } /// A style that carries some row cell styles already (a DXF's partial CELLSTYLEMAP) gets /// the missing rows, and the ones it has keep their values: a margin of its own is not /// replaced (review on #2921). #[test] fn partial_row_cell_styles_get_the_missing_rows() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; let mut styles = 0; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.horizontal_margin = 1.0; s.vertical_margin = 0.25; // A _DATA row of its own, seeded here rather than taken from the default style, // under a key lower than the rows that go before it. let mut data = NamedTableCellStyle { id: 3, name: "_DATA".into(), ..NamedTableCellStyle::default() }; data.cell_style.horizontal_margin = 9.0; s.modern_overrides = vec![(0, data)]; let custom = NamedTableCellStyle { id: 101, name: "Highlight".into(), ..NamedTableCellStyle::default() }; s.modern_overrides.push((101, custom)); styles += 1; } assert!(styles > 0, "the drawing has no table style"); table_style_row_margins(&mut doc).expect("row ids"); for o in doc.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let rows: Vec<_> = s.modern_overrides.iter().map(|(k, row)| (*k, row.name.as_str())).collect(); assert_eq!(rows, [(1, "_TITLE"), (2, "_HEADER"), (0, "_DATA"), (101, "Highlight")], "rows in order, custom one kept"); for (_, row) in &s.modern_overrides { let c = &row.cell_style; let margins = (c.margin_override_flags, c.horizontal_margin, c.vertical_margin, c.right_margin, c.bottom_margin); match row.name.as_str() { "_TITLE" | "_HEADER" => assert_eq!(margins, (1, 1.0, 0.25, 1.0, 0.25), "{} gets the style's margins", row.name), "_DATA" => assert_eq!(c.horizontal_margin, 9.0, "the _DATA row keeps its value"), _ => {} } } } } /// A drawing none of whose styles needs a row keeps its table entries' handles as they /// are: the writer gives them their own later, in its own order (review on #2921). #[test] fn a_drawing_needing_no_rows_keeps_its_unnumbered_entries() { use acadrust::objects::ObjectType; let layer_handle = |doc: &acadrust::CadDocument| doc.layers.get("NoHandle").map(|l| l.handle); for no_styles in [true, false] { let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; if no_styles { doc.objects.retain(|_, o| !matches!(o, ObjectType::TableStyle(_))); } else { table_style_row_margins(&mut doc).expect("row ids"); } assert!(doc.layers.add(acadrust::tables::Layer::new("NoHandle")).is_ok()); assert!(layer_handle(&doc).is_some_and(|h| h.is_null())); table_style_row_margins(&mut doc).expect("row ids"); assert!(layer_handle(&doc).is_some_and(|h| h.is_null()), "no_styles {no_styles}: the layer was numbered"); } // A style that does need rows numbers only the text style its row names, not the // layer (the writer numbers that one in its own order). let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; assert!(doc.layers.add(acadrust::tables::Layer::new("NoHandle")).is_ok()); table_style_row_margins(&mut doc).expect("row ids"); assert!(layer_handle(&doc).is_some_and(|h| h.is_null()), "the layer was numbered"); } /// With no free cell style id the conversion is an error, not a row silently left out. #[test] fn no_free_cell_style_id_is_an_error() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; let held = NamedTableCellStyle { id: 1, name: "Highlight".into(), ..NamedTableCellStyle::default() }; s.modern_overrides = vec![(101, held)]; } assert!(table_style_row_margins_up_to(&mut doc, 100).is_err()); assert!(table_style_row_margins_up_to(&mut doc, 102).is_ok()); } /// The DWG reader keeps only 64 cell styles per table style, so a style with no room for /// every missing row is left exactly as it is (no error, nothing added or dropped) and the /// drawing still converts; one with room gets its rows. The decoded cell styles (ids and /// names) are those expected, not only as many. #[test] fn a_style_with_no_room_for_its_rows_is_left_as_it_is() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; // `names` as the style's cell styles, ids as given. let doc_with = |names: &[(i32, String)]| { let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.modern_overrides = names .iter() .map(|(id, name)| (*id, NamedTableCellStyle { id: *id, name: name.clone(), ..NamedTableCellStyle::default() })) .collect(); } doc }; // Every table style's cell styles as (id, name), sorted by id. let styles = |doc: &acadrust::CadDocument| -> Vec> { let mut all: Vec> = doc .objects .values() .filter_map(|o| if let ObjectType::TableStyle(s) = o { Some(s) } else { None }) .map(|s| { let mut v: Vec<(i32, String)> = s.modern_overrides.iter().map(|(_, o)| (o.id, o.name.clone())).collect(); v.sort(); v }) .collect(); all.sort(); all }; // _TITLE and _HEADER, then custom styles up to `count`; no _DATA. let names = |count: i32| -> Vec<(i32, String)> { let mut v = vec![(1, "_TITLE".to_string()), (2, "_HEADER".to_string())]; v.extend((0..count - 2).map(|i| (101 + i, format!("Custom{i}")))); v }; for (given, gets_data) in [(names(64), false), (names(63), true)] { let mut doc = doc_with(&given); let before = styles(&doc); assert!(!before.is_empty(), "the drawing has a table style"); table_style_row_margins(&mut doc).expect("converts"); let mut expected = given.clone(); if gets_data { expected.push((3, "_DATA".to_string())); } expected.sort(); let after = styles(&doc); assert!(after.iter().all(|s| *s == expected), "{} cell styles in: {after:?}", given.len()); if !gets_data { assert_eq!(after, before, "left as it is"); } // The DWG keeps the same cell styles. let decoded = styles(&through_dwg(&doc)); assert!(!decoded.is_empty() && decoded.iter().all(|s| *s == expected), "{} cell styles round trip: {decoded:?}", given.len()); } // Two missing rows and room for one: all or nothing. let mut given = names(64); given.remove(1); let mut doc = doc_with(&given); table_style_row_margins(&mut doc).expect("converts"); let mut expected = given.clone(); expected.sort(); assert!(styles(&doc).iter().all(|s| *s == expected)); } /// The DWG as the writer makes it from `doc`, read back. fn through_dwg(doc: &acadrust::CadDocument) -> acadrust::CadDocument { let dwg = acadrust::DwgWriter::write_to_vec(doc).expect("the DWG writes"); acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().expect("the DWG reads") } /// A row whose text style names nothing is written with the Standard style, not a null /// handle: the writer resolves a row built as a finished cell style the same way (review /// on #2921, finding 1). #[test] fn a_row_with_an_unknown_text_style_is_written_with_standard() { use acadrust::objects::ObjectType; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.data_row_style.text_style_name = "NoSuchStyle".into(); s.data_row_style.text_style_handle = None; } table_style_row_margins(&mut doc).expect("row ids"); let back = through_dwg(&doc); let standard = back.text_styles.get("Standard").map(|t| t.handle); assert!(standard.is_some_and(|h| !h.is_null())); let mut rows = 0; for o in back.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; for (_, row) in s.modern_overrides.iter().filter(|(_, r)| r.name == "_DATA") { assert_eq!(Some(row.cell_style.content_format.text_style), standard); rows += 1; } } assert!(rows > 0); } /// A row a style carries already gets the style's margins and spacing when it has no margin /// override, and keeps the ones it has (review on #1960). After a DWG save and reopen the /// cases are told apart: `_TITLE` (no override) carries the style's margins and the base /// spacing, `_HEADER` (flags 2, which the writer and reader also take for margins) its own /// margins and spacing, `_DATA` (no cell style data at all) nothing, so it inherits the /// base cell style, which carries the style's margins. #[test] fn an_existing_row_gets_the_style_margins_only_where_it_has_no_override() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.horizontal_margin = 1.0; s.vertical_margin = 0.25; let mut title = NamedTableCellStyle { id: 1, style_type: 1, name: "_TITLE".into(), ..NamedTableCellStyle::default() }; title.cell_style.data_flags = 1; assert_eq!(title.cell_style.margin_override_flags, 0); let mut header = NamedTableCellStyle { id: 2, style_type: 1, name: "_HEADER".into(), ..NamedTableCellStyle::default() }; header.cell_style.data_flags = 1; header.cell_style.margin_override_flags = 2; (header.cell_style.horizontal_margin, header.cell_style.right_margin) = (9.0, 9.0); (header.cell_style.vertical_margin, header.cell_style.bottom_margin) = (7.0, 7.0); (header.cell_style.horizontal_spacing, header.cell_style.vertical_spacing) = (5.0, 4.0); let data = NamedTableCellStyle { id: 3, style_type: 2, name: "_DATA".into(), ..NamedTableCellStyle::default() }; s.modern_overrides = vec![(1, title), (2, header), (3, data)]; } table_style_row_margins(&mut doc).expect("row ids"); let back = through_dwg(&doc); let mut styles = 0; for o in back.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let rows: Vec<_> = s .modern_overrides .iter() .map(|(_, r)| { let c = &r.cell_style; let margins = (c.margin_override_flags, c.horizontal_margin, c.vertical_margin, c.right_margin, c.bottom_margin); (r.name.as_str(), margins, (c.horizontal_spacing, c.vertical_spacing)) }) .collect(); assert_eq!( rows, [ ("_TITLE", (1, 1.0, 0.25, 1.0, 0.25), (0.18, 0.18)), ("_HEADER", (2, 9.0, 7.0, 9.0, 7.0), (5.0, 4.0)), ("_DATA", (0, 0.0, 0.0, 0.0, 0.0), (0.0, 0.0)), ], "an existing row without margins takes the style's margins and spacing, one with its own keeps them" ); let base = s .modern_style .as_ref() .map(|b| (b.cell_style.margin_override_flags, b.cell_style.horizontal_margin, b.cell_style.vertical_margin)); assert_eq!(base, Some((1, 1.0, 0.25)), "the base cell style carries the margins the _DATA row inherits"); styles += 1; } assert!(styles > 0); } /// With both spellings in a style only the exact one (`_TITLE`) is the row, as the DWG reader /// takes it: it gets the margins, and `_title` (a custom cell style to the reader) is left /// as it is, name and values. #[test] fn with_both_spellings_only_the_exact_row_is_filled() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.horizontal_margin = 1.0; s.vertical_margin = 0.25; s.modern_overrides = [(5, "_title"), (1, "_TITLE")] .map(|(k, n)| { let mut row = NamedTableCellStyle { id: k, name: n.into(), ..NamedTableCellStyle::default() }; row.cell_style.data_flags = 1; (k, row) }) .into(); } table_style_row_margins(&mut doc).expect("row ids"); let mut styles = 0; for o in doc.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let rows: Vec<_> = s.modern_overrides.iter().map(|(_, r)| (r.name.as_str(), r.cell_style.margin_override_flags != 0)).collect(); assert_eq!(rows, [("_title", false), ("_TITLE", true), ("_HEADER", true), ("_DATA", true)]); let filled: Vec<_> = s.modern_overrides.iter().filter(|(_, r)| r.cell_style.margin_override_flags != 0).collect(); assert!( filled.iter().all(|(_, r)| r.cell_style.horizontal_margin == s.horizontal_margin), "the filled rows carry the style's margins" ); styles += 1; } assert!(styles > 0); } /// The margins and spacing of a cell style, to compare as relations. fn margins_of(c: &acadrust::objects::TableCellStyleData) -> Margins { Margins { vertical: c.vertical_margin, horizontal: c.horizontal_margin, bottom: c.bottom_margin, right: c.right_margin, horizontal_spacing: c.horizontal_spacing, vertical_spacing: c.vertical_spacing, } } /// A style whose base cell style (`modern_style`) is as given, with a `_TITLE` row that has /// cell style data but no margin override. fn style_with_base(base: acadrust::objects::NamedTableCellStyle) -> acadrust::CadDocument { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.horizontal_margin = 1.0; s.vertical_margin = 0.25; s.modern_style = Some(base.clone()); let mut title = NamedTableCellStyle { id: 1, style_type: 1, name: "_TITLE".into(), ..NamedTableCellStyle::default() }; title.cell_style.data_flags = 1; s.modern_overrides = vec![(1, title)]; } doc } /// A style read from a DWG has a base cell style of its own, which the writer emits as it /// is: the rows filled and added here carry its margins and spacing, not the style's own /// margin fields or the default 0.18, so rows and base agree. #[test] fn filled_and_added_rows_equal_the_base_cell_style_the_writer_emits() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut base = NamedTableCellStyle { id: 4, style_type: 5, name: "Table".into(), ..NamedTableCellStyle::default() }; base.cell_style.data_flags = 1; base.cell_style.margin_override_flags = 1; base.cell_style.vertical_margin = 0.5; base.cell_style.horizontal_margin = 0.7; base.cell_style.bottom_margin = 0.6; base.cell_style.right_margin = 0.8; (base.cell_style.horizontal_spacing, base.cell_style.vertical_spacing) = (0.45, 0.35); let mut doc = style_with_base(base); table_style_row_margins(&mut doc).expect("row ids"); let mut rows = 0; for o in doc.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let Some(base) = s.modern_style.as_ref() else { continue }; assert!(margins_of(&base.cell_style) != default_base(s), "the base differs from the style's own fields"); for (_, r) in &s.modern_overrides { assert_eq!(margins_of(&r.cell_style), margins_of(&base.cell_style), "{} takes the base's margins and spacing", r.name); assert!(r.cell_style.margin_override_flags != 0); rows += 1; } } assert_eq!(rows, 3, "the existing row and the two added ones"); } /// A base cell style that carries no margins (no cell style data, or no margin override) is /// emitted by the writer without any, so there is nothing to copy: the existing row is left /// as it is and the added rows get what they got before, the style's margins and 0.18. #[test] fn a_base_without_margins_leaves_existing_rows_unfilled() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; for (data_flags, margin_flags) in [(1, 0), (0, 1)] { let mut base = NamedTableCellStyle { id: 4, style_type: 5, name: "Table".into(), ..NamedTableCellStyle::default() }; base.cell_style.data_flags = data_flags; base.cell_style.margin_override_flags = margin_flags; let mut doc = style_with_base(base); table_style_row_margins(&mut doc).expect("row ids"); let mut styles = 0; for o in doc.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let rows: Vec<_> = s.modern_overrides.iter().map(|(_, r)| r).collect(); assert_eq!(rows.iter().map(|r| r.name.as_str()).collect::>(), ["_TITLE", "_HEADER", "_DATA"]); assert_eq!(rows[0].cell_style.margin_override_flags, 0, "{data_flags}/{margin_flags}: the existing row stays unfilled"); for r in &rows[1..] { assert_eq!(margins_of(&r.cell_style), default_base(s), "{data_flags}/{margin_flags}: {} gets the style's margins", r.name); } styles += 1; } assert!(styles > 0); } } /// With all three rows present and the first `_TITLE` carrying margins, the style still /// needs work when a second `_TITLE` has none: every row of the name is looked at. #[test] fn a_second_exact_row_without_margins_is_found_and_filled() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.horizontal_margin = 1.0; s.vertical_margin = 0.25; s.modern_overrides = [(1, "_TITLE", true), (2, "_HEADER", true), (3, "_DATA", true), (7, "_TITLE", false)] .map(|(id, n, margins)| { let mut row = NamedTableCellStyle { id, name: n.into(), ..NamedTableCellStyle::default() }; row.cell_style.data_flags = 1; row.cell_style.margin_override_flags = i16::from(margins); (id, row) }) .into(); assert!(!gets_rows(s), "every row is there"); assert!(rows_need_work(s)); } table_style_row_margins(&mut doc).expect("row ids"); let mut styles = 0; for o in doc.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let second = s.modern_overrides.iter().find(|(k, _)| *k == 7).map(|(_, r)| r); assert!(second.is_some_and(|r| r.cell_style.margin_override_flags != 0 && r.cell_style.horizontal_margin == s.horizontal_margin)); assert!(!rows_need_work(s)); styles += 1; } assert!(styles > 0); } /// A style holding the exact spelling twice: the reader applies each in turn, so the last one /// decides, and every one of them gets the margins. #[test] fn every_row_of_the_exact_spelling_is_filled() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.horizontal_margin = 1.0; s.vertical_margin = 0.25; s.modern_overrides = [(1, 1), (7, 7)] .map(|(k, id)| { let mut row = NamedTableCellStyle { id, name: "_TITLE".into(), ..NamedTableCellStyle::default() }; row.cell_style.data_flags = 1; (k, row) }) .into(); } table_style_row_margins(&mut doc).expect("row ids"); let mut styles = 0; for o in doc.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let titles: Vec<_> = s.modern_overrides.iter().filter(|(_, r)| r.name == "_TITLE").collect(); assert_eq!(titles.len(), 2); assert!(titles.iter().all(|(_, r)| r.cell_style.margin_override_flags != 0 && r.cell_style.horizontal_margin == s.horizontal_margin)); styles += 1; } assert!(styles > 0); } /// A built-in row in another case (`_title`) is written under the spelling the DWG reader /// knows, with its id and formatting, so its formatting survives a reopen; a style holding /// both spellings keeps both as they are. #[test] fn a_title_row_in_lower_case_keeps_its_formatting_through_a_dwg() { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; let mut title = NamedTableCellStyle { id: 5, style_type: 1, name: "_title".into(), ..NamedTableCellStyle::default() }; title.cell_style.data_flags = 1; title.cell_style.content_format.text_height = 2.5; s.modern_overrides = vec![(5, title)]; } table_style_row_margins(&mut doc).expect("row ids"); let back = through_dwg(&doc); let mut styles = 0; for o in back.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let title: Vec<_> = s.modern_overrides.iter().filter(|(_, r)| r.name.eq_ignore_ascii_case("_TITLE")).collect(); assert_eq!(title.len(), 1); assert_eq!((title[0].1.name.as_str(), title[0].1.id, title[0].1.cell_style.content_format.text_height), ("_TITLE", 5, 2.5)); assert_eq!(s.title_row_style.text_height, 2.5, "the reader applies the title height"); styles += 1; } assert!(styles > 0); // Both spellings are left alone. for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.modern_overrides = [(5, "_title"), (1, "_TITLE")] .map(|(k, n)| (k, NamedTableCellStyle { id: k, name: n.into(), ..NamedTableCellStyle::default() })) .into(); } table_style_row_margins(&mut doc).expect("row ids"); for o in doc.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let names: Vec<_> = s.modern_overrides.iter().map(|(_, r)| r.name.as_str()).collect(); assert_eq!(names, ["_title", "_TITLE", "_HEADER", "_DATA"]); } } /// `(key, id, name)` of each cell style a table style ends with when it starts with `start`. fn rows_after(start: &[(i32, i32, &str)]) -> Vec> { use acadrust::objects::{NamedTableCellStyle, ObjectType}; let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; s.horizontal_margin = 1.0; s.modern_overrides = start.iter().map(|&(k, id, name)| (k, NamedTableCellStyle { id, name: name.into(), ..NamedTableCellStyle::default() })).collect(); } table_style_row_margins(&mut doc).expect("row ids"); let mut out = Vec::new(); for o in doc.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; for (_, row) in s.modern_overrides.iter().filter(|(_, r)| !start.iter().any(|&(_, _, n)| n.eq_ignore_ascii_case(&r.name))) { assert_eq!((row.cell_style.margin_override_flags, row.cell_style.horizontal_margin), (1, 1.0), "{} has the margins", row.name); } out.push(s.modern_overrides.iter().map(|(k, row)| (*k, row.id, row.name.clone())).collect()); } assert!(!out.is_empty(), "the drawing has no table style"); out } fn owned(rows: &[(i32, i32, &str)]) -> Vec<(i32, i32, String)> { rows.iter().map(|&(k, id, n)| (k, id, n.to_string())).collect() } /// A row whose id another cell style holds already (as key or as id) is still added, with /// its margins, under a free id: no two styles share one, and no row goes without. #[test] fn a_row_takes_a_free_id_when_another_cell_style_holds_its_own() { for rows in rows_after(&[(101, 1, "Highlight"), (2, 102, "Note")]) { let want = [(103, 103, "_TITLE"), (104, 104, "_HEADER"), (3, 3, "_DATA"), (101, 1, "Highlight"), (2, 102, "Note")]; assert_eq!(rows, owned(&want)); } // An id at the top of the range leaves a free one all the same. for rows in rows_after(&[(1, i32::MAX, "Huge")]) { assert_eq!(rows, owned(&[(101, 101, "_TITLE"), (2, 2, "_HEADER"), (3, 3, "_DATA"), (1, i32::MAX, "Huge")])); } // Keys and ids together can fill more than len + 1 numbers above 100. for rows in rows_after(&[(1, 101, "A"), (102, 103, "B")]) { let want = [(104, 104, "_TITLE"), (2, 2, "_HEADER"), (3, 3, "_DATA"), (1, 101, "A"), (102, 103, "B")]; assert_eq!(rows, owned(&want)); } // Every row needs a free id, and each one added takes a number from the next search. for rows in rows_after(&[(1, 101, "A"), (2, 102, "B"), (3, 103, "C"), (104, 105, "D")]) { let want = [(106, 106, "_TITLE"), (107, 107, "_HEADER"), (108, 108, "_DATA"), (1, 101, "A"), (2, 102, "B"), (3, 103, "C"), (104, 105, "D")]; assert_eq!(rows, owned(&want)); } } /// A row present under another case is the row (cell style names ignore case), and added /// rows go after the rows before them, whatever the keys: _TITLE, _HEADER, _DATA stay in order. #[test] fn rows_are_found_in_any_case_and_added_in_row_order() { for rows in rows_after(&[(5, 5, "_title")]) { assert_eq!(rows, owned(&[(5, 5, "_TITLE"), (2, 2, "_HEADER"), (3, 3, "_DATA")])); } for rows in rows_after(&[(101, 101, "Custom"), (2, 2, "_HEADER")]) { assert_eq!(rows, owned(&[(1, 1, "_TITLE"), (101, 101, "Custom"), (2, 2, "_HEADER"), (3, 3, "_DATA")])); } } /// Before 2010 a DWG has no row cell styles: the style is left as it is. #[test] fn pre_2010_table_styles_get_no_row_cell_styles() { for version in [acadrust::DxfVersion::AC1018, acadrust::DxfVersion::AC1021] { let mut doc = acadrust::CadDocument::new(); doc.version = version; table_style_row_margins(&mut doc).expect("row ids"); for o in doc.objects.values() { let acadrust::objects::ObjectType::TableStyle(s) = o else { continue }; assert!(s.modern_overrides.is_empty(), "{version:?}"); } } } /// A row whose text style was read without a handle (R12, HANDLING 0) still finds it by /// name, as the writer would after giving it a handle, rather than falling to Standard. #[test] fn a_row_finds_a_text_style_read_without_a_handle() { let mut doc = acadrust::CadDocument::new(); doc.version = acadrust::DxfVersion::AC1032; let romans = acadrust::tables::TextStyle::new("ROMANS"); assert!(romans.handle.is_null()); assert!(doc.text_styles.add(romans).is_ok()); for o in doc.objects.values_mut() { let acadrust::objects::ObjectType::TableStyle(s) = o else { continue }; s.data_row_style.text_style_name = "ROMANS".into(); s.data_row_style.text_style_handle = None; } table_style_row_margins(&mut doc).expect("row ids"); let romans = doc.text_styles.get("ROMANS").map(|ts| ts.handle); assert!(romans.is_some_and(|h| !h.is_null()), "ROMANS has a handle now"); let mut rows = 0; for o in doc.objects.values() { let acadrust::objects::ObjectType::TableStyle(s) = o else { continue }; for (_, row) in s.modern_overrides.iter().filter(|(_, r)| r.name == "_DATA") { assert_eq!(Some(row.cell_style.content_format.text_style), romans); rows += 1; } } assert!(rows > 0); } /// A height marked only in the style's override flags (as newer files store it) is kept, /// and the same height with no flag at all is cleared (review on #2588). Tested on the /// read document because acadrust's DWG writer doesn't write the override flags. #[test] fn a_style_override_flag_keeps_the_cell_height() { use acadrust::entities::table::{CellStyle, CellStylePropertyFlags}; let height = |override_flags: i32| { let mut doc = doc_with_table(1, 1, 0); for e in doc.entities_mut() { if let EntityType::Table(t) = e { for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { let mut s = CellStyle::new(); s.text_height = 0.5; s.override_flags = override_flags; cell.style = Some(s); } } } table_cell_heights(&mut doc); doc.entities().find_map(|e| match e { EntityType::Table(t) => t.rows.first()?.cells.first()?.style.as_ref().map(|s| s.text_height), _ => None, }) }; assert_eq!(height(CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32), Some(0.5)); assert_eq!(height(0), Some(0.0)); } /// A panic in the post-read fix-ups is an error, not a crash (#1934). #[test] fn a_panic_in_post_processing_is_an_error() { #[allow(clippy::panic)] let r = guarded(AssertUnwindSafe(|| -> usize { panic!("boom") })); assert!(r.is_err()); assert_eq!(guarded(|| 3), Ok(3)); } } #[cfg(test)] mod application_object_tests { use super::*; use acadrust::CadDocument; use acadrust::classes::DxfClass; use acadrust::objects::{ObjectType, ProxyObjectReference, ProxyPayload, ProxyReferenceKind, RegisteredClassObject}; use acadrust::types::{DxfVersion, Handle}; /// An object of another application's class that acadrust keeps only as its record (a /// vertical product's dimension data, say) is carried as that class's proxy object, with its /// data bits, references, owner and extension dictionary, through DXF and back to DWG, twice. #[test] fn undecoded_application_object_is_kept_as_its_proxy() { for version in [DxfVersion::AC1027, DxfVersion::AC1032] { let mut source = CadDocument::new(); source.version = version; source.classes.add_or_update(DxfClass::new("TESTCONTAINER", "xyzDbTestContainer")); let handle = Handle::from(0x2Bu64); let target = Handle::from(0x2Cu64); let payload = ProxyPayload::from_bits(&[0x5A, 0x3C, 0xC0], 18); // A null pointer between two references: it keeps its place, the one after it is not lost. let references = vec![ ProxyObjectReference { handle: target, kind: ProxyReferenceKind::HardPointer }, ProxyObjectReference { handle: Handle::from(0u64), kind: ProxyReferenceKind::SoftPointer }, ProxyObjectReference { handle: Handle::from(0x0Cu64), kind: ProxyReferenceKind::HardPointer }, ]; source.objects.insert( handle, ObjectType::RegisteredClass(RegisteredClassObject { handle, owner: Handle::from(0x0Cu64), dxf_name: "TESTCONTAINER".into(), cpp_class_name: "xyzDbTestContainer".into(), payload: payload.clone(), object_ids: references.clone(), ..Default::default() }), ); let mut dwg = acadrust::DwgWriter::write_to_vec(&source).unwrap(); // acadrust has no model of it: read back, it is only its record. let decoded = acadrust::DwgReader::from_stream(Cursor::new(dwg.clone())).read().unwrap(); assert!(matches!(decoded.objects.get(&handle), Some(ObjectType::Unknown { .. })), "{:?}", decoded.objects.get(&handle)); for generation in 0..2 { let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap(); assert!(notes.is_empty(), "{version:?} {generation}: {notes:?}"); // The DXF has the object, by its handle, as a proxy record. let text = String::from_utf8_lossy(&dxf); let lines: Vec<&str> = text.lines().map(str::trim).collect(); let record = lines.windows(4).any(|w| w == ["0", "ACAD_PROXY_OBJECT", "5", "2B"]); assert!(record, "{version:?} {generation}: no proxy record for the object"); dwg = dxf_to_dwg_as(&dxf, "AC1032").unwrap(); let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.clone())).read().unwrap(); let Some(ObjectType::ProxyObject(proxy)) = doc.objects.get(&handle) else { panic!("{version:?} {generation}: proxy object") }; assert_eq!(proxy.payload.bit_count, payload.bit_count); assert_eq!(proxy.payload.data(), payload.data()); assert_eq!(proxy.object_ids, references); let class = doc.classes.iter().find(|c| i32::from(c.class_number) == proxy.class_id).unwrap(); assert_eq!(class.dxf_name, "TESTCONTAINER"); assert!(!class.is_an_entity); } } } /// The database's own classes are not turned into another application's proxies; what is /// left without a DXF form is said, not dropped silently. #[test] fn database_objects_without_a_form_are_reported() { let mut doc = CadDocument::new(); doc.classes.add_or_update(DxfClass::new("BLOCKPROPERTIESTABLE", "AcDbBlockPropertiesTable")); let handle = Handle::from(0x40u64); doc.objects.insert( handle, ObjectType::Unknown { type_name: "BLOCKPROPERTIESTABLE".into(), handle, owner: Handle::from(0x0Cu64), raw_dxf_codes: None, raw_dwg_data: Some(vec![0; 8]), raw_dwg_handle_bits: 0, raw_dwg_version: Some(DxfVersion::AC1032), }, ); let notes = application_objects(&mut doc); assert!(matches!(doc.objects.get(&handle), Some(ObjectType::Unknown { .. }))); assert_eq!( notes, [ "DWG: 1 objects of types this bridge can't preserve were left out (BLOCKPROPERTIESTABLE × 1); saving over the original file would lose them" ] ); } /// A record that doesn't split stays as it was and is named, never guessed at. #[test] fn invalid_object_records_are_rejected() { for handle_bits in [-1, 1000] { let raw = acadrust::entities::RawRecord { data: vec![0; 8], handle_bits, version: DxfVersion::AC1032 }; assert!(object_record(&raw, 42).is_err()); } let mut doc = CadDocument::new(); doc.classes.add_or_update(DxfClass::new("TESTCONTAINER", "xyzDbTestContainer")); let handle = Handle::from(0x41u64); doc.objects.insert( handle, ObjectType::Unknown { type_name: "TESTCONTAINER".into(), handle, owner: Handle::from(0x0Cu64), raw_dxf_codes: None, raw_dwg_data: Some(vec![0xFF; 4]), raw_dwg_handle_bits: 1000, raw_dwg_version: Some(DxfVersion::AC1032), }, ); let notes = application_objects(&mut doc); assert!(matches!(doc.objects.get(&handle), Some(ObjectType::Unknown { .. }))); assert!(notes.iter().any(|n| n.contains("(TESTCONTAINER × 1)")), "{notes:?}"); } } } #[cfg(not(no_dwg_bridge))] pub use native::{ dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as, dxf_to_dwg_kept_as, dxf_to_dwg_kept_noted, dxf_to_dwg_noted, }; /// What saving as DWG left out: how many records of each DXF type (upper case) the DWG writer /// can't write. pub type Unwritten = std::collections::BTreeMap; // Test-only: the stage ("post_process" or "convert") whose guard the current test checks. The // stage then panics on entry, so a test through the public API shows whether it is guarded. #[cfg(all(test, not(no_dwg_bridge)))] thread_local! { static PANIC_IN: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// Panics when a test asked for `stage` to fail (see [`PANIC_IN`]); does nothing otherwise. #[cfg(not(no_dwg_bridge))] #[allow(clippy::panic)] fn fail_in_test(stage: &str) { #[cfg(not(test))] let _ = stage; #[cfg(test)] assert!(PANIC_IN.with(std::cell::Cell::get) != Some(stage), "test-forced panic in {stage}"); } /// The error for a DWG version this writer can't create. #[cfg_attr(no_dwg_bridge, allow(dead_code))] fn unsupported(version: &str) -> String { let list: Vec<&str> = VERSIONS.iter().map(|(_, year)| *year).collect(); format!("DWG version `{version}` can't be written (this bridge writes {})", list.join(", ")) } /// Which build has no DWG bridge, for the stubs' errors. #[cfg(no_dwg_bridge)] const NO_BRIDGE_BUILD: &str = if cfg!(target_arch = "wasm32") { "web" } else { "FreeBSD aarch64" }; /// There's no worker without a bridge. #[cfg(no_dwg_bridge)] pub const WORKER_ARG: &str = "--dwg-worker"; #[cfg(no_dwg_bridge)] pub fn serve_if_asked() -> Option { None } #[cfg(no_dwg_bridge)] pub fn use_own_worker() {} #[cfg(no_dwg_bridge)] pub fn allow_in_process() {} #[cfg(no_dwg_bridge)] pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { dwg_to_dxf_noted(bytes, limits) } #[cfg(no_dwg_bridge)] pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { dxf_to_dwg_as(dxf, version) } #[cfg(no_dwg_bridge)] pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec, Unwritten), String> { dxf_to_dwg_noted(dxf, version) } #[cfg(no_dwg_bridge)] pub fn encode_kept_noted(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec, Unwritten), String> { match kept { Some(kept) => dxf_to_dwg_kept_noted(dxf, version, kept), None => dxf_to_dwg_noted(dxf, version), } } #[cfg(no_dwg_bridge)] pub fn dwg_to_dxf(_bytes: &[u8]) -> Result, String> { Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } #[cfg(no_dwg_bridge)] pub fn dwg_to_dxf_noted(_bytes: &[u8], _limits: Limits) -> Result<(Vec, Vec), String> { Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } #[cfg(no_dwg_bridge)] pub fn dwg_to_dxf_with(_bytes: &[u8], _limits: Limits) -> Result, String> { Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } #[cfg(no_dwg_bridge)] pub fn dxf_to_dwg(_dxf: &[u8]) -> Result, String> { Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } #[cfg(no_dwg_bridge)] pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result, String> { Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } #[cfg(no_dwg_bridge)] pub fn dxf_to_dwg_noted(_dxf: &[u8], _version: &str) -> Result<(Vec, Unwritten), String> { Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } #[cfg(no_dwg_bridge)] pub fn dxf_to_dwg_kept_as(_dxf: &[u8], _version: &str, _kept: &str) -> Result, String> { Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } #[cfg(no_dwg_bridge)] pub fn dxf_to_dwg_kept_noted(_dxf: &[u8], _version: &str, _kept: &str) -> Result<(Vec, Unwritten), String> { Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } #[cfg(test)] mod tests { use std::fmt::Write as _; use super::*; /// The DXF of an empty drawing, enough for the bridge to make a small DWG. #[cfg(not(no_dwg_bridge))] const MINIMAL_DXF: &str = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nEOF\n"; /// Makes `stage` panic on the current thread until dropped. #[cfg(not(no_dwg_bridge))] struct PanicIn; #[cfg(not(no_dwg_bridge))] impl PanicIn { fn at(stage: &'static str) -> Self { PANIC_IN.with(|p| p.set(Some(stage))); Self } } #[cfg(not(no_dwg_bridge))] impl Drop for PanicIn { fn drop(&mut self) { PANIC_IN.with(|p| p.set(None)); } } /// The public read reports a panic in the post-read fix-ups as an error: this fails if the /// `guarded` call around `post_process` is taken out (#2402). #[cfg(not(no_dwg_bridge))] #[test] fn reading_a_dwg_survives_a_panic_in_post_processing() { let dwg = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap(); assert!(dwg_to_dxf(&dwg).is_ok(), "the DWG reads without the forced panic"); let _panic = PanicIn::at("post_process"); let err = dwg_to_dxf(&dwg).unwrap_err(); assert!(err.contains("the DWG post-processing failed on this file"), "{err}"); } /// The DXF to DWG conversion reports a panic in its fix-ups as an error, not a crash (#2402). #[cfg(not(no_dwg_bridge))] #[test] fn converting_to_dwg_survives_a_panic_in_the_fix_ups() { let _panic = PanicIn::at("convert"); let err = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap_err(); assert!(err.contains("the DXF to DWG conversion failed on this file"), "{err}"); } #[test] fn detects_magic() { assert!(is_dwg(b"AC1032\0\0\0\0")); assert!(!is_dwg(b" 0\r\nSECTION")); assert_eq!(version(b"AC1018xxxx").as_deref(), Some("AC1018")); } /// A DXF with ROMANS as `$TEXTSTYLE` gives a DWG whose current text style is ROMANS, not /// Standard: the DXF names the style, and the handle read with it was Standard's (#1650). #[cfg(not(no_dwg_bridge))] #[test] fn current_text_style_reaches_the_dwg() { let header = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 9\n$TEXTSTYLE\n 7\nROMANS\n 0\nENDSEC\n"; let style = " 0\nSTYLE\n 5\n1F0\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nROMANS\n 70\n0\n"; let style = format!("{style} 40\n0\n 41\n1\n 50\n0\n 71\n0\n 42\n2.5\n 3\nromans.shx\n 4\n\n"); let dxf = format!("{header} 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nSTYLE\n 70\n1\n{style} 0\nENDTAB\n 0\nENDSEC\n 0\nEOF\n"); let dwg = dxf_to_dwg(dxf.as_bytes()).unwrap(); let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); let romans = doc.text_styles.iter().find(|ts| ts.name == "ROMANS").map(|ts| ts.handle); assert!(romans.is_some(), "ROMANS is missing from the DWG"); assert_eq!(Some(doc.header.current_text_style_handle), romans); } /// What a table style gives one of its rows, written out by hand for /// `table_style_row_cell_styles_keep_the_style`: the six edges as (grid mask, hidden in the /// source, line weight, colour index) in the order top, horizontal inside, bottom, left, /// vertical inside, right; the fill (enabled, colour index), text style, alignment, height and /// text colour index; and what the DWG row carries besides. #[cfg(not(no_dwg_bridge))] struct StyleRow { name: &'static str, edges: [(i32, bool, i16, i16); 6], fill: (bool, i16), text_style: &'static str, alignment: acadrust::objects::CellAlignment, height: f64, text_colour: i16, merge_flags: i32, style_type: i32, } /// The three rows' values; every edge differs from every other, in the rows and between them. #[cfg(not(no_dwg_bridge))] fn style_rows() -> [StyleRow; 3] { use acadrust::objects::CellAlignment; [ StyleRow { name: "_TITLE", edges: [(1, false, 5, 11), (2, true, 9, 12), (4, false, 13, 13), (8, true, 15, 14), (16, false, 18, 15), (32, true, 20, 16)], fill: (true, 30), text_style: "Standard", alignment: CellAlignment::TopCenter, height: 0.5, text_colour: 1, merge_flags: 0x8000, style_type: 1, }, StyleRow { name: "_HEADER", edges: [(1, true, 25, 21), (2, false, 30, 22), (4, true, 35, 23), (8, false, 40, 24), (16, true, 50, 25), (32, false, 53, 26)], fill: (false, 40), text_style: "ROMANS", alignment: CellAlignment::MiddleRight, height: 0.3, text_colour: 3, merge_flags: 0, style_type: 1, }, StyleRow { name: "_DATA", edges: [(1, false, 60, 31), (2, true, 70, 32), (4, true, 80, 33), (8, false, 90, 34), (16, true, 100, 35), (32, false, 106, 36)], fill: (true, 50), text_style: "Standard", alignment: CellAlignment::BottomLeft, height: 0.2, text_colour: 5, merge_flags: 0, style_type: 2, }, ] } /// Gives a table style the margins and the three rows' values. #[cfg(not(no_dwg_bridge))] fn give_style_rows(s: &mut acadrust::objects::TableStyle, rows: &[StyleRow]) { use acadrust::types::{Color, LineWeight}; // Different margins each way, so a swapped pair shows. s.horizontal_margin = 1.0; s.vertical_margin = 0.25; for r in rows { let row = match r.name { "_TITLE" => &mut s.title_row_style, "_HEADER" => &mut s.header_row_style, _ => &mut s.data_row_style, }; for &(mask, hidden, weight, colour) in &r.edges { let b = match mask { 1 => &mut row.top_border, 2 => &mut row.horizontal_inside_border, 4 => &mut row.bottom_border, 8 => &mut row.left_border, 16 => &mut row.vertical_inside_border, _ => &mut row.right_border, }; b.is_invisible = hidden; b.line_weight = LineWeight::Value(weight); b.color = Color::from_index(colour); } row.fill_enabled = r.fill.0; row.fill_color = Color::from_index(r.fill.1); row.text_style_name = r.text_style.to_string(); row.alignment = r.alignment; row.text_height = r.height; row.text_color = Color::from_index(r.text_colour); } } /// Asserts a DWG table style row has what `want` says; `tag` names it in a failure. #[cfg(not(no_dwg_bridge))] fn assert_style_row( tag: &str, row: &acadrust::objects::NamedTableCellStyle, want: &StyleRow, text_styles: &acadrust::tables::Table, ) { use acadrust::objects::TableBorderType; use acadrust::types::{Color, LineWeight}; let c = &row.cell_style; assert_eq!( (c.margin_override_flags, c.horizontal_margin, c.vertical_margin, c.right_margin, c.bottom_margin), (1, 1.0, 0.25, 1.0, 0.25), "{tag}: margins" ); assert_eq!(c.merge_flags, want.merge_flags, "{tag}: merge flags"); assert_eq!(row.style_type, want.style_type, "{tag}: style type"); // The grid flag is set for a hidden edge: the reverse of `is_invisible`. A DXF table style // holds no border type or double spacing, so those stay the default. assert_eq!(c.borders.len(), 6, "{tag}: borders"); for (got, &(mask, hidden, weight, colour)) in c.borders.iter().zip(&want.edges) { assert_eq!(got.index_mask, mask, "{tag}: border order"); let b = &got.border; assert_eq!(b.is_invisible, !hidden, "{tag}: border {mask} visibility"); assert_eq!(b.border_type, TableBorderType::Single, "{tag}: border {mask} type"); assert_eq!(b.line_weight, LineWeight::Value(weight), "{tag}: border {mask} weight"); assert_eq!(b.color, Color::from_index(colour), "{tag}: border {mask} colour"); assert_eq!(b.double_line_spacing, 0.0, "{tag}: border {mask} spacing"); } let fill = if want.fill.0 { Color::from_index(want.fill.1) } else { Color::None }; assert_eq!(c.background_color, fill, "{tag}: fill"); let f = &c.content_format; assert_eq!(f.cell_alignment, want.alignment as i32, "{tag}: alignment"); assert_eq!(f.text_height, want.height, "{tag}: text height"); assert_eq!(f.content_color, Color::from_index(want.text_colour), "{tag}: text colour"); // Handles are the DWG's own: compare the style they name. let got = text_styles.iter().find(|t| t.handle == f.text_style).map(|t| t.name.as_str()); assert_eq!(got.map(str::to_ascii_lowercase), Some(want.text_style.to_ascii_lowercase()), "{tag}: text style"); } /// A 2010+ DWG's table style row cell styles carry the style's margins, as the reference app /// writes them: without them it reads the margins as 0.06 where the drawing has 1.0 (#2920). /// DWG 2004 has no row cell styles and keeps the margins in the style itself. The rows also /// keep the attributes the style gives them: borders, fill, text style, alignment, height and /// colour. The style is given a value of its own for each of them, differing between the six /// edges and between the rows, and the expected values are written out by hand, so a swapped /// edge, a swapped row or a broken lookup fails. #[cfg(not(no_dwg_bridge))] #[test] fn table_style_row_cell_styles_keep_the_style() { use acadrust::objects::ObjectType; // A drawing with a ROMANS text style, for one row to use. let style = " 0\nSTYLE\n 5\n1F0\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nROMANS\n 70\n0\n"; let style = format!("{style} 40\n0\n 41\n1\n 50\n0\n 71\n0\n 42\n2.5\n 3\nromans.shx\n 4\n\n"); let head = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n"; let dxf = format!("{head} 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nSTYLE\n 70\n1\n{style} 0\nENDTAB\n 0\nENDSEC\n 0\nEOF\n"); let rows = style_rows(); // Parsed once; the DWG is made from the DXF it is written to at each version. let mut doc = acadrust::DxfReader::from_reader(std::io::Cursor::new(dxf.into_bytes())).unwrap().read().unwrap(); let mut styles = 0; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; give_style_rows(s, &rows); styles += 1; } assert!(styles > 0, "the drawing has no table style"); let dxf = acadrust::DxfWriter::new(&doc).write_to_vec().unwrap(); for version in ["AC1024", "AC1027", "AC1032"] { let dwg = dxf_to_dwg_as(&dxf, version).unwrap(); let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); let mut checked = 0; for o in back.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; assert_eq!((s.horizontal_margin, s.vertical_margin), (1.0, 0.25), "{version} {}", s.name); let names: Vec<_> = s.modern_overrides.iter().map(|(_, r)| r.name.as_str()).collect(); assert_eq!(names, ["_TITLE", "_HEADER", "_DATA"], "{version} {}: rows", s.name); for (_, row) in &s.modern_overrides { let want = rows.iter().find(|r| r.name == row.name).expect("a row of the three"); assert_style_row(&format!("{version} {} {}", s.name, row.name), row, want, &back.text_styles); checked += 1; } } assert_eq!(checked, 3 * styles, "{version}: rows checked"); } } /// A 2010+ DWG written from a DXF whose table styles carry the rows' values, and the DXF it /// reads back as: the style's margins and the rows' values survive both ways, and the rows /// added for the DWG (which a DWG 2010+ keeps in the style, not as a CELLSTYLEMAP) don't add /// cell style entries to the DXF (review on #2921). #[cfg(not(no_dwg_bridge))] #[test] fn table_style_survives_dxf_to_dwg_to_dxf() { use acadrust::objects::ObjectType; let rows = style_rows(); let head = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nEOF\n"; let mut doc = acadrust::DxfReader::from_reader(std::io::Cursor::new(head.as_bytes().to_vec())).unwrap().read().unwrap(); let mut styles = 0; for o in doc.objects.values_mut() { let ObjectType::TableStyle(s) = o else { continue }; give_style_rows(s, &rows); styles += 1; } assert!(styles > 0, "the drawing has no table style"); let dxf = acadrust::DxfWriter::new(&doc).write_to_vec().unwrap(); let dwg = dxf_to_dwg_as(&dxf, "AC1032").unwrap(); // The DWG itself carries the three rows with the style's margins as an override: without // them the reference app reads the margins as 0.06 (#2920). let in_dwg = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); let mut in_dwg_styles = 0; for o in in_dwg.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; let got: Vec<_> = s .modern_overrides .iter() .map(|(_, r)| { let c = &r.cell_style; (r.name.as_str(), c.margin_override_flags, c.horizontal_margin, c.vertical_margin) }) .collect(); assert_eq!(got, [("_TITLE", 1, 1.0, 0.25), ("_HEADER", 1, 1.0, 0.25), ("_DATA", 1, 1.0, 0.25)], "{}: rows in the DWG", s.name); in_dwg_styles += 1; } assert_eq!(in_dwg_styles, styles); let out = dwg_to_dxf(&dwg).unwrap(); let text = String::from_utf8_lossy(&out); assert_eq!(text.matches("CELLSTYLEMAP").count(), String::from_utf8_lossy(&dxf).matches("CELLSTYLEMAP").count(), "cell style maps"); for name in ["_TITLE", "_HEADER", "_DATA"] { assert_eq!(text.matches(name).count(), String::from_utf8_lossy(&dxf).matches(name).count(), "{name} entries"); } // Read back, the style has the margins and the rows' values, as before. let back = acadrust::DxfReader::from_reader(std::io::Cursor::new(out)).unwrap().read().unwrap(); let mut checked = 0; for o in back.objects.values() { let ObjectType::TableStyle(s) = o else { continue }; assert_eq!((s.horizontal_margin, s.vertical_margin), (1.0, 0.25), "{}", s.name); for r in &rows { let row = match r.name { "_TITLE" => &s.title_row_style, "_HEADER" => &s.header_row_style, _ => &s.data_row_style, }; let got: Vec<_> = [ &row.top_border, &row.horizontal_inside_border, &row.bottom_border, &row.left_border, &row.vertical_inside_border, &row.right_border, ] .iter() .map(|b| b.is_invisible) .collect(); let want: Vec<_> = r.edges.iter().map(|e| e.1).collect(); assert_eq!(got, want, "{} {}: edges hidden", s.name, r.name); assert_eq!(row.text_height, r.height, "{} {}: height", s.name, r.name); } checked += 1; } assert_eq!(checked, styles); } #[test] fn garbage_is_an_error_not_a_crash() { assert!(dwg_to_dxf(b"AC1032 this is not a dwg file at all").is_err()); assert!(dwg_to_dxf(b"").is_err()); } #[cfg(not(no_dwg_bridge))] #[test] fn dxf_to_dwg_rejects_garbage_without_crashing() { // The DXF→DWG path runs the third-party reader inside catch_unwind and reports failures // rather than crashing (and rejects oversized input before decoding). assert!(dxf_to_dwg(b"not a dxf file").is_err()); assert!(dxf_to_dwg(b"").is_err()); } /// A DXF with one DIMENSION per (text, group 70, subclass, points) row. #[cfg(not(no_dwg_bridge))] type DimensionSpec<'a> = (&'a str, i64, &'a str, &'a [(i32, [f64; 2])]); #[cfg(not(no_dwg_bridge))] fn dims_dxf(dims: &[DimensionSpec<'_>]) -> String { let mut s = String::from(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n"); for (text, flags, sub, pts) in dims { s += " 0\nDIMENSION\n 8\n0\n100\nAcDbEntity\n100\nAcDbDimension\n 10\n0\n 20\n0\n 30\n0\n"; let _ = write!(s, " 11\n50\n 21\n-20\n 31\n0\n 70\n{flags}\n 1\n{text}\n 3\nStandard\n100\n{sub}\n"); for (code, [x, y]) in *pts { let _ = write!(s, "{code:>3}\n{x}\n{:>3}\n{y}\n{:>3}\n0\n", code + 10, code + 20); } } s + " 0\nENDSEC\n 0\nEOF\n" } /// DWG stores DXF group 70's bit 128 inverted, in bit 0 of the dimension flags byte (set: /// the text is at its default position), and bit 32 in bit 1 (ODA DWG specification, common /// dimension data). The bytes are read back raw, so a reader that inverts bit 0 the same way /// as the writer can't hide a wrong byte. #[cfg(not(no_dwg_bridge))] #[test] fn dimension_text_position_flags_reach_the_dwg_as_autocad_reads_them() { let linear: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [100.0, 0.0])]; let radius: &[(i32, [f64; 2])] = &[(15, [10.0, 0.0])]; let angular: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [10.0, 0.0]), (15, [0.0, 0.0]), (16, [0.0, 10.0])]; let kinds = [ (0, "AcDbAlignedDimension", linear), (1, "AcDbAlignedDimension", linear), (4, "AcDbRadialDimension", radius), (2, "AcDb2LineAngularDimension", angular), ]; let mut dims = Vec::new(); for (ty, sub, pts) in kinds { dims.push(("HOME", ty | 32, sub, pts)); dims.push(("MOVED", ty | 32 | 128, sub, pts)); } let dwg = dxf_to_dwg(dims_dxf(&dims).as_bytes()).unwrap(); let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); let mut seen = Vec::new(); for e in doc.entities() { let acadrust::entities::EntityType::Dimension(d) = e else { continue }; let (text, byte) = (d.base().text_override().unwrap_or_default(), d.base().dwg_flags_byte); seen.push((text.to_string(), byte & 0x03)); assert_eq!(byte & 0x02, 0x02, "{text} {:?}: bit 32 of group 70 is lost (flags byte {byte:#04x})", d.base().dimension_type); let default_pos = text == "HOME"; assert_eq!(byte & 0x01 != 0, default_pos, "{text} {:?}: flags byte {byte:#04x}", d.base().dimension_type); } for text in ["HOME", "MOVED"] { assert_eq!(seen.iter().filter(|(t, _)| t == text).count(), 4, "{seen:?}"); } // And CADCraft reads its own DWG back as it wrote it: 128 only on the moved texts. let dxf = String::from_utf8(dwg_to_dxf(&dwg).unwrap()).unwrap(); let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); let mut flags = Vec::new(); for rec in lines.chunks(2).collect::>().split(|p| p.first() == Some(&"0")) { let value = |code: &str| rec.iter().find(|p| p.first() == Some(&code)).and_then(|p| p.get(1).copied()); if let (Some(text @ ("HOME" | "MOVED")), Some(v)) = (value("1"), value("70")) { flags.push((text, v.parse::().unwrap_or(-1) & 128)); } } assert_eq!(flags.len(), 8, "{flags:?}"); assert!(flags.iter().all(|(l, f)| (*f == 128) == (*l == "MOVED")), "{flags:?}"); } /// The handles a DXF text refers to or gives its records (groups 5, 105 and 330–369). #[cfg(not(no_dwg_bridge))] fn dxf_handles(dxf: &str) -> std::collections::HashSet { let lines: Vec<&str> = dxf.lines().collect(); lines .chunks(2) .filter_map(|p| match p { [c, v] if matches!(c.trim().parse::(), Ok(5 | 105 | 330..=369)) => u64::from_str_radix(v.trim(), 16).ok(), _ => None, }) .collect() } /// Issue #1482: a DWG that once came from `MicroStation` can carry hundreds of thousands of DGN /// line style components no definition uses (a real 83 MB site plan: 888,483 of 889,053, a /// 1.2 GB DXF rendition over the limit, so it didn't open). They're left out with a note, and /// their dictionary entries with them; the definition and every component it reaches — /// through compound and point components, around a cycle — are kept. #[cfg(not(no_dwg_bridge))] #[test] #[expect( clippy::too_many_lines, reason = "This integration test builds and verifies one complete DGN component graph; splitting the fixture would obscure reachability." )] fn orphaned_dgn_line_style_components_are_left_out() { use acadrust::objects::*; let mut doc = acadrust::CadDocument::new(); let container = doc.allocate_handle(); let nod = doc.header.named_objects_dict_handle; let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&nod) else { panic!("no named object dictionary") }; root.entries.push(("ACAD_DGNLINESTYLECOMP".into(), container)); let pattern = || DgnLsStrokePattern { has_iteration_limit: false, is_single_segment: false, iteration_limit: 0, auto_phase: 0.0, phase: 0.0, phase_mode: DgnLsPhaseMode::Distance, strokes: vec![DgnLsStroke { is_dash: true, bypass_corner: false, can_be_scaled: true, invert_at_origin: false, invert_at_end: false, length: 2.5, start_width: 0.0, end_width: 0.0, width_mode: 0, cap_mode: 0, }], }; let kind = |c: &DgnLsComponentData| match c { DgnLsComponentData::Symbol(_) => DgnLsComponentType::Symbol, DgnLsComponentData::Compound(_) => DgnLsComponentType::Compound, DgnLsComponentData::Stroke(_) => DgnLsComponentType::Stroke, DgnLsComponentData::Point(_) => DgnLsComponentType::Point, DgnLsComponentData::Internal(_) => DgnLsComponentType::Internal, }; let compound = |of: &[acadrust::Handle]| { DgnLsComponentData::Compound(DgnLsCompoundComponent { entries: of.iter().map(|&component| DgnLsCompoundEntry { component, offset: 0.0 }).collect(), }) }; let mut entries = Vec::new(); let mut put = |doc: &mut acadrust::CadDocument, h: acadrust::Handle, data: DgnLineStyleData| { entries.push((format!("{:X}", h.value()), h)); let reactors = vec![container]; doc.objects .insert(h, ObjectType::DgnLineStyle(DgnLineStyleObject { handle: h, owner: container, reactors, xdictionary_handle: None, data })); }; let component = |c: DgnLsComponentData| DgnLineStyleData::Component { kind: kind(&c), description: "dash".into(), version: 1, component_uid: [7; 16], scale: 1.0, property_flags: 0, component: c, properties: vec![], }; let h: Vec = (0..9).map(|_| doc.allocate_handle()).collect(); let [def, root, stroke, point, back, orphan, orphan_cycle, internal, shared] = h[..] else { panic!("nine handles") }; put( &mut doc, def, DgnLineStyleData::Definition { description: "{ dash }".into(), version: 1, style_number: 1, component_uid: [1; 16], is_continuous: false, unit_definition: 1.0, unit_scale: 1.0, units_type: 0, is_element: false, is_physical: false, is_scale_independent: false, is_snappable: false, root_component: root, properties: vec![], }, ); // Used: def → root → {stroke, point → shared, back → root (a cycle)}. put(&mut doc, root, component(compound(&[stroke, point, back]))); put(&mut doc, stroke, component(DgnLsComponentData::Stroke(pattern()))); put(&mut doc, point, component(DgnLsComponentData::Point(DgnLsPointComponent { stroke_component: shared, symbols: vec![] }))); put(&mut doc, back, component(compound(&[root]))); put(&mut doc, shared, component(DgnLsComponentData::Stroke(pattern()))); // Orphans: an internal component, and two compounds that refer to each other and to a // used component (which stays). let pattern_internal = DgnLsInternalComponent { pattern: pattern(), internal_version: 0, hardware_style: 0, is_hardware_style: false, line_code: 0 }; put(&mut doc, internal, component(DgnLsComponentData::Internal(pattern_internal))); put(&mut doc, orphan, component(compound(&[orphan_cycle, shared]))); put(&mut doc, orphan_cycle, component(compound(&[orphan]))); let mut dict = Dictionary::new(); dict.handle = container; dict.owner = nod; dict.entries = entries; doc.objects.insert(container, ObjectType::Dictionary(dict)); let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap(); let dxf = String::from_utf8(dxf).unwrap(); let handles = dxf_handles(&dxf); for kept in [def, root, stroke, point, back, shared] { assert!(handles.contains(&kept.value()), "{:X} was left out", kept.value()); } for gone in [internal, orphan, orphan_cycle] { assert!(!handles.contains(&gone.value()), "{:X} was kept or is still referred to", gone.value()); } let lines: Vec<&str> = dxf.lines().collect(); let ls: Vec<&str> = lines.chunks(2).filter_map(|p| p.get(1).filter(|_| p[0].trim() == "0" && p[1].starts_with("LS")).copied()).collect(); assert_eq!(ls.iter().filter(|t| t.ends_with("COMPONENT")).count(), 5, "{ls:?}"); assert!(ls.contains(&"LSDEFINITION") && !ls.contains(&"LSINTERNALCOMPONENT"), "{ls:?}"); assert_eq!(notes, ["DWG: 3 DGN line style components that no line style definition uses were left out"]); } /// An R2000 DXF header (`\r\n` lines, as CADCraft writes them) with `extra` after `$ACADVER`. #[cfg(not(no_dwg_bridge))] fn r2000(extra: &[u8]) -> Vec { let mut dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n 9\r\n$DWGCODEPAGE\r\n 3\r\nANSI_1252\r\n".to_vec(); dxf.extend_from_slice(b" 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\n"); dxf.extend_from_slice(extra); dxf.extend_from_slice(b"\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"); dxf } /// The kept version replaces only the `$ACADVER` value; everything else stays byte for byte. #[cfg(not(no_dwg_bridge))] #[test] fn declare_version_changes_only_acadver() { let dxf = r2000(b"A\\U+00E7\\U+00E3o"); let out = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap(); assert_eq!(String::from_utf8(out).unwrap(), String::from_utf8(dxf).unwrap().replacen("AC1015", "AC1032", 1)); } /// A kept version not newer than the declared one, a binary DXF and a DXF without `$ACADVER` /// are read as they are. #[cfg(not(no_dwg_bridge))] #[test] fn declare_version_leaves_what_it_need_not_change() { let dxf = r2000(b"x"); assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1015), None); assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1009), None); assert_eq!(native::declare_version(b"AutoCAD Binary DXF\r\n\x1a\0", acadrust::DxfVersion::AC1032), None); let no_version = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; assert_eq!(native::declare_version(no_version, acadrust::DxfVersion::AC1032), None); // A `$ACADVER` outside the HEADER section is not the file's version. let late = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n"; assert_eq!(native::declare_version(late, acadrust::DxfVersion::AC1032), None); } /// The header is read as group code and value pairs up to the first `0`/`ENDSEC`: a `$ACADVER` /// name whose value would come after it, or a file that never ends its HEADER, is no version /// to replace, and `\r\n` lines keep the value's offset right. #[cfg(not(no_dwg_bridge))] #[test] fn declare_version_reads_the_header_in_pairs_up_to_endsec() { let cut = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 0\r\nENDSEC\r\n 1\r\nAC1015\r\n"; assert_eq!(native::declare_version(cut, acadrust::DxfVersion::AC1032), None); let endless = vec![b'\n'; 1 << 20]; assert_eq!(native::declare_version(&endless, acadrust::DxfVersion::AC1032), None); let crlf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1015\r\n 0\r\nENDSEC\r\n"; let out = native::declare_version(crlf, acadrust::DxfVersion::AC1032).unwrap(); assert_eq!(out, b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1032\r\n 0\r\nENDSEC\r\n"); } /// Declared as 2007 or later, a DXF is UTF-8: code page text is decoded first. Declared as an /// older version, the code page bytes stay as they are. #[cfg(not(no_dwg_bridge))] #[test] fn declare_version_decodes_a_code_page_for_utf8_versions() { let dxf = r2000(b"A\xe7\xe3o"); let utf8 = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap(); let text = String::from_utf8(utf8).unwrap(); assert!(text.contains("\r\nAção\r\n") && text.contains("$ACADVER\r\n 1\r\nAC1032\r\n"), "{text}"); let legacy = native::declare_version(&dxf, acadrust::DxfVersion::AC1018).unwrap(); assert!(legacy.windows(4).any(|w| w == b"A\xe7\xe3o"), "the code page bytes stay"); assert!(legacy.windows(6).any(|w| w == b"AC1018")); // A code page it doesn't know is read as Windows-1252, as acadrust reads an older DXF. let at = dxf.windows(9).position(|w| w == b"ANSI_1252").unwrap(); let unknown = [&dxf[..at], b"NO_SUCH_CP".as_slice(), &dxf[at + 9..]].concat(); let text = String::from_utf8(native::declare_version(&unknown, acadrust::DxfVersion::AC1032).unwrap()).unwrap(); assert!(text.contains("\r\nAção\r\n"), "{text}"); // Without a `$DWGCODEPAGE` there is nothing to decode it by: it is read as it is. let none = [&dxf[..at - 21], &dxf[at + 11..]].concat(); assert!(!none.windows(12).any(|w| w == b"$DWGCODEPAGE"), "{}", String::from_utf8_lossy(&none)); assert_eq!(native::declare_version(&none, acadrust::DxfVersion::AC1032), None); } /// An unknown kept version converts as [`dxf_to_dwg_as`] does. #[cfg(not(no_dwg_bridge))] #[test] fn unknown_kept_version_converts_as_before() { let dxf = r2000(b"x"); assert_eq!(dxf_to_dwg_kept_as(&dxf, "AC1032", "AC9999"), dxf_to_dwg_as(&dxf, "AC1032")); assert!(dxf_to_dwg_kept_as(&dxf, "AC0000", "AC1032").is_err(), "an unwritable version is still an error"); } /// The CLASS names in CLASSES order; nothing for a binary DXF or one without CLASSES. #[cfg(not(no_dwg_bridge))] #[test] fn dxf_class_names_in_classes_order() { let dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nWIDGETA\r\n 2\r\nAcDbWidgetA\r\n 3\r\nApp\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 2\r\nAcDbWidgetB\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\nNOT_A_CLASS\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; assert_eq!(native::dxf_class_names(dxf).unwrap(), ["WIDGETA", "WIDGETB"]); // A CLASS record without a name keeps its place, so the classes after it keep theirs // (#2837 review). let unnamed = b" 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 2\r\nAcDbNoName\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; assert_eq!(native::dxf_class_names(unnamed).unwrap(), ["", "WIDGETB"]); assert_eq!(native::dxf_class_names(b" 0\nSECTION\n 2\nHEADER\n 0\nENDSEC\n 0\nEOF\n"), Some(Vec::new())); assert_eq!(native::dxf_class_names(b"AutoCAD Binary DXF\r\n\x1a\0"), None); } /// AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with a byte after its three /// connections that DXF doesn't carry. acadrust 0.6.4 neither read nor wrote it, so AutoCAD /// read past the object and refused every DWG CADCraft wrote with a dynamic block that scales /// ("Error Decrypting Data"); 0.6.5 added it and 0.6.6, which this uses, still keeps it (0.6.6 also /// fixes multi-layout DWGs, #1463). The byte reaches the DWG, and a scale action /// from DXF is written whole, with the byte AutoCAD writes (0). #[cfg(not(no_dwg_bridge))] #[test] fn scale_actions_keep_the_byte_autocad_reads_after_their_connections() { use acadrust::objects::*; let scale_action = |doc: &acadrust::CadDocument| { doc.objects.values().find_map(|o| match o { ObjectType::DynamicBlock(DynamicBlockObject { data: DynamicBlockData::ScaleAction(s), .. }) => Some(s.clone()), _ => None, }) }; let mut doc = acadrust::CadDocument::new(); let h = doc.allocate_handle(); let conn = |code, name: &str| BlockConnection { code, name: name.into() }; let mut action = DynamicBlockObject::new("BLOCKSCALEACTION", "AcDbBlockScaleAction"); action.handle = h; action.owner = doc.header.named_objects_dict_handle; let mut a = BlockBasePointAction::default(); a.action.action.element.name = "Scale".into(); a.action.connections = vec![conn(2, "UpdatedBaseX"), conn(2, "UpdatedBaseY")]; a.action.dependent = true; a.connections = vec![conn(2, "Scale"), conn(2, "XScale"), conn(2, "YScale")]; a.dwg_tail_byte = 7; action.data = DynamicBlockData::ScaleAction(a.clone()); doc.objects.insert(h, ObjectType::DynamicBlock(action)); let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); assert_eq!(scale_action(&back).map(|s| s.dwg_tail_byte), Some(7), "the byte isn't written"); let mut dxf = Vec::new(); acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); for version in ["AC1018", "AC1032"] { let dwg = dxf_to_dwg_as(&dxf, version).unwrap(); let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); let read = scale_action(&back).unwrap_or_else(|| panic!("{version}: the scale action wasn't written")); assert_eq!(read.connections, a.connections, "{version}"); assert_eq!(read.action.connections, a.action.connections, "{version}"); assert_eq!(read.dwg_tail_byte, 0, "{version}"); } } /// Saving says what the DWG writer left out, per type: entities of types acadrust's DXF /// reader doesn't model (another program's custom entity) can't be written; a drawing the DWG /// keeps whole reports nothing. #[cfg(not(no_dwg_bridge))] #[test] fn saving_lists_the_types_the_dwg_writer_leaves_out() { let line = " 0\nLINE\n 8\n0\n100\nAcDbEntity\n100\nAcDbLine\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 11\n10.0\n 21\n0.0\n 31\n0.0\n"; let widget = " 0\nACME_WIDGET\n 8\n0\n100\nAcDbEntity\n100\nAcmeWidget\n 10\n1.0\n 20\n2.0\n 30\n0.0\n"; let dxf = |body: &str| { format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{body} 0\nENDSEC\n 0\nEOF\n") }; for version in ["AC1015", "AC1018", "AC1032"] { let (dwg, unwritten) = dxf_to_dwg_noted(dxf(&format!("{line}{widget}{widget}")).as_bytes(), version).unwrap(); assert!(is_dwg(&dwg), "{version}"); assert_eq!(unwritten, [("ACME_WIDGET".to_string(), 2)].into_iter().collect::(), "{version}"); } let (_, unwritten) = dxf_to_dwg_noted(dxf(line).as_bytes(), "AC1032").unwrap(); assert!(unwritten.is_empty(), "{unwritten:?}"); } /// An OLE2FRAME, which CADCraft keeps as its DXF groups without modelling it, is written to /// the DWG with its data: it isn't in the list of what the writer left out. #[cfg(not(no_dwg_bridge))] #[test] fn ole_frames_are_written_with_their_data() { let ole = " 0\nOLE2FRAME\n 8\n0\n100\nAcDbEntity\n100\nAcDbOle2Frame\n 70\n2\n 10\n1.0\n 20\n9.0\n 30\n0.0\n 11\n8.0\n 21\n2.0\n 31\n0.0\n 71\n2\n 72\n0\n 73\n1\n 90\n4\n310\nDEADBEEF\n 1\nOLE\n"; let dxf = format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{ole} 0\nENDSEC\n 0\nEOF\n"); for version in ["AC1015", "AC1018", "AC1032"] { let (dwg, unwritten) = dxf_to_dwg_noted(dxf.as_bytes(), version).unwrap(); assert!(unwritten.is_empty(), "{version} {unwritten:?}"); let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); let frames: Vec> = back .entities() .filter_map(|e| match e { acadrust::entities::EntityType::Ole2Frame(o) => Some(o.encoded_payload()), _ => None, }) .collect(); assert_eq!(frames, [vec![0xDE, 0xAD, 0xBE, 0xEF]], "{version}"); } } /// A FIELD read from a pre-2007 DXF keeps its format (group 4) only in `Field::format`, which /// acadrust's DWG writer writes just for versions before 2007: saved as DWG 2007 or later the /// format (`dd/MM/yyyy`) was lost. A 2007+ field with its own format is written as it is. #[cfg(not(no_dwg_bridge))] #[test] fn field_formats_survive_saving_an_older_drawing_as_dwg_2007_or_later() { let formats = |dwg: Vec| -> Vec { let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); back.objects .values() .filter_map(|o| match o { acadrust::objects::ObjectType::Field(f) => Some(f.value.format.clone()), _ => None, }) .collect() }; for source in ["AC1015", "AC1018"] { let dxf = format!( " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\n{source}\n 0\nENDSEC\n 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nFIELD\n 2\nAcDbField\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n 0\nENDSEC\n 0\nSECTION\n 2\nOBJECTS\n 0\nFIELD\n 5\nA1F\n330\n1F\n 1\nAcVar\n 2\n\\AcVar Date\n 4\ndd/MM/yyyy\n 90\n0\n 97\n0\n 91\n0\n 92\n0\n 94\n0\n 95\n0\n 96\n0\n300\n\n 0\nENDSEC\n 0\nEOF\n" ); assert_eq!(formats(dxf_to_dwg_as(dxf.as_bytes(), "AC1032").unwrap()), ["dd/MM/yyyy"], "{source}"); } let mut doc = acadrust::CadDocument::new(); doc.classes.add_or_update(acadrust::classes::DxfClass::new("FIELD", "AcDbField")); let handle = doc.allocate_handle(); let field = acadrust::objects::Field { handle, owner: doc.header.named_objects_dict_handle, evaluator_id: "AcVar".into(), code: "\\AcVar Date".into(), value: acadrust::entities::CellValue { format: "%lu2".into(), ..Default::default() }, ..Default::default() }; doc.objects.insert(handle, acadrust::objects::ObjectType::Field(field)); let mut dxf = Vec::new(); acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); assert_eq!(formats(dxf_to_dwg_as(&dxf, "AC1032").unwrap()), ["%lu2"]); } /// A FIELD record as an AC1015/AC1018 DXF writes it, its format `dd/MM/yyyy` in group 4. #[cfg(not(no_dwg_bridge))] fn legacy_field(handle: acadrust::Handle, owner: acadrust::Handle) -> String { format!( " 0\r\nFIELD\r\n 5\r\n{handle:X}\r\n330\r\n{owner:X}\r\n 1\r\nAcVar\r\n 2\r\n\\AcVar Date\r\n 4\r\ndd/MM/yyyy\r\n 90\r\n0\r\n 97\r\n0\r\n 91\r\n0\r\n 92\r\n0\r\n 94\r\n0\r\n 95\r\n0\r\n 96\r\n0\r\n300\r\n\r\n" ) } /// The FIELD formats of a DWG by handle: `value.format` from 2007, `Field::format` before. #[cfg(not(no_dwg_bridge))] fn dwg_field_formats(dwg: Vec) -> Vec<(u64, String)> { let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); let mut formats: Vec<(u64, String)> = back .objects .values() .filter_map(|o| match o { acadrust::objects::ObjectType::Field(f) => Some((f.handle.into(), f.pre2007_format().to_string())), _ => None, }) .collect(); formats.sort(); formats } /// CADCraft's R2000 DXF of a drawing with fields declares AC1015 (or the drawing's AC1018) /// and is read as the `kept` version, for which acadrust skips group 4: an older drawing's own /// field lost its format (`dd/MM/yyyy`) in the DWG (#1580 review). #[cfg(not(no_dwg_bridge))] #[test] fn field_formats_survive_a_kept_version_newer_than_the_drawing() { for source in ["AC1015", "AC1018"] { for kept in ["AC1024", "AC1032"] { let owner = acadrust::Handle::new(0x1F); let legacy = legacy_field(acadrust::Handle::new(0xA1F), owner); let dxf = format!( " 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n{source}\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nFIELD\r\n 2\r\nAcDbField\r\n 3\r\nObjectDBX Classes\r\n 90\r\n0\r\n 91\r\n0\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nOBJECTS\r\n{legacy} 0\r\nENDSEC\r\n 0\r\nEOF\r\n" ); for version in ["AC1032", "AC1018"] { let got = dwg_field_formats(dxf_to_dwg_kept_as(dxf.as_bytes(), version, kept).unwrap()); assert_eq!(got, [(0xA1F, "dd/MM/yyyy".to_string())], "{source} kept {kept} as {version}"); } } } } /// The same DXF with a field carried over from a 2007+ file next to the drawing's own: the /// carried-over one keeps its own `value.format` (`%lu2`), the drawing's own its group 4 /// format (`dd/MM/yyyy`). #[cfg(not(no_dwg_bridge))] #[test] fn field_formats_survive_a_kept_version_with_carried_over_and_own_fields() { for source in ["AC1015", "AC1018"] { for kept in ["AC1024", "AC1032"] { // The carried-over field as acadrust writes 2007+ DXF, the drawing's own field in // the old layout, under the older version. let mut doc = acadrust::CadDocument::new(); doc.classes.add_or_update(acadrust::classes::DxfClass::new("FIELD", "AcDbField")); let (carried, own) = (doc.allocate_handle(), doc.allocate_handle()); let field = acadrust::objects::Field { handle: carried, owner: doc.header.named_objects_dict_handle, evaluator_id: "AcVar".into(), code: "\\AcVar Date".into(), value: acadrust::entities::CellValue { format: "%lu2".into(), ..Default::default() }, ..Default::default() }; doc.objects.insert(carried, acadrust::objects::ObjectType::Field(field)); let mut dxf = Vec::new(); acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); let dxf = String::from_utf8(dxf).unwrap(); let dxf = dxf.replacen("$ACADVER\r\n 1\r\nAC1032\r\n", &format!("$ACADVER\r\n 1\r\n{source}\r\n"), 1); let at = dxf.find(" 0\r\nFIELD\r\n").unwrap(); let dxf = format!("{}{}{}", &dxf[..at], legacy_field(own, doc.header.named_objects_dict_handle), &dxf[at..]); assert!(dxf.contains(&format!("$ACADVER\r\n 1\r\n{source}\r\n"))); for version in ["AC1032", "AC1018"] { let got = dwg_field_formats(dxf_to_dwg_kept_as(dxf.as_bytes(), version, kept).unwrap()); let mut want = vec![(carried.into(), "%lu2".to_string()), (own.into(), "dd/MM/yyyy".to_string())]; want.sort(); assert_eq!(got, want, "mixed {source} kept {kept} as {version}"); } } } } }