mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-30 22:10:12 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23f60b50aa | ||
|
|
022b9644be | ||
|
|
78b40d3593 | ||
|
|
461be33ea8 | ||
|
|
489f143341 | ||
|
|
5c26eef628 | ||
|
|
a22473f3e4 | ||
|
|
d1fbec9473 | ||
|
|
9cedb46d53 | ||
|
|
ed759dda38 | ||
|
|
b8131c6b42 | ||
|
|
fcca921719 | ||
|
|
4cbdfc1600 | ||
|
|
e7c907b690 | ||
|
|
e58cd4ccc4 | ||
|
|
be85a3eb16 | ||
|
|
241719d5ea | ||
|
|
b15f0b7158 | ||
|
|
5820753676 | ||
|
|
8df3d9a241 | ||
|
|
6318e09325 | ||
|
|
8c0f7658a3 | ||
|
|
fc19d899eb | ||
|
|
b9fb71535a | ||
|
|
26196a7418 | ||
|
|
e4e48426f2 | ||
|
|
5b460a6061 | ||
|
|
e5d3fe6a0b | ||
|
|
b273a72307 | ||
|
|
456cecd2f7 | ||
|
|
87fb3f2ddb | ||
|
|
54d1be50ba | ||
|
|
1ba86d461b | ||
|
|
7526dc62c1 | ||
|
|
161af2a8da | ||
|
|
28241abb8f | ||
|
|
51f5bbcc21 | ||
|
|
227e3c385b |
@@ -53,7 +53,7 @@ pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyface
|
|||||||
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
|
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
|
||||||
pub use fill::{Gradient, Hatch, HatchLoop};
|
pub use fill::{Gradient, Hatch, HatchLoop};
|
||||||
pub use layout::{Image, Table, TableCell, Viewport};
|
pub use layout::{Image, Table, TableCell, Viewport};
|
||||||
pub use proxy::{ProxyTables, proxy_entities};
|
pub use proxy::{ProxyTables, TableOrder, proxy_entities};
|
||||||
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
|
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
|
||||||
pub use wipeout::Wipeout;
|
pub use wipeout::Wipeout;
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
|||||||
@@ -7,8 +7,9 @@ pub struct HatchLoop {
|
|||||||
pub vertices: Vec<PolyVertex>,
|
pub vertices: Vec<PolyVertex>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub outer: bool,
|
pub outer: bool,
|
||||||
/// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and
|
/// Original DXF group 92 bits. Writing keeps only Textbox (8) and Outermost (16), derives
|
||||||
/// Outermost (16), derives External (1) from `outer`, and sets Polyline (2).
|
/// External (1) from `outer`, and sets Polyline (2). Derived (4) stays here but is not
|
||||||
|
/// written: the pixel size (group 47) it needs is not kept (#3664).
|
||||||
/// None uses the flags of a locally created loop.
|
/// None uses the flags of a locally created loop.
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub boundary_flags: Option<i64>,
|
pub boundary_flags: Option<i64>,
|
||||||
|
|||||||
+388
-82
@@ -35,6 +35,36 @@ pub struct ProxyTables {
|
|||||||
pub styles: Vec<(String, String)>,
|
pub styles: Vec<(String, String)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The LAYER and LTYPE names the indices of proxy graphics count in, in table order (the
|
||||||
|
/// linetypes without ByBlock and ByLayer, as in [`ProxyTables`]).
|
||||||
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
|
pub struct TableOrder<'a> {
|
||||||
|
pub layers: &'a [String],
|
||||||
|
pub linetypes: &'a [String],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The chunk that sets the layer by its index (ATTRIBUTE_LAYER).
|
||||||
|
const LAYER_CHUNK: u32 = 16;
|
||||||
|
/// The chunk that sets the linetype by its index (ATTRIBUTE_LINETYPE).
|
||||||
|
const LINETYPE_CHUNK: u32 = 18;
|
||||||
|
/// The linetype indices that stand for ByBlock and ByLayer.
|
||||||
|
const LINETYPE_BYBLOCK: u32 = 32766;
|
||||||
|
const LINETYPE_BYLAYER: u32 = 32767;
|
||||||
|
|
||||||
|
/// The names a record's own graphics show for its table indices (`Unknown::names_by_index`).
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Learned {
|
||||||
|
layers: std::collections::HashMap<u32, Option<String>>,
|
||||||
|
linetypes: std::collections::HashMap<u32, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The names that stand for the table indices a record uses while it is decoded again to learn
|
||||||
|
/// them; an index without one leaves the layer, or gives ByLayer, as one past a table does.
|
||||||
|
struct Marks {
|
||||||
|
layers: std::collections::HashMap<u32, String>,
|
||||||
|
linetypes: std::collections::HashMap<u32, String>,
|
||||||
|
}
|
||||||
|
|
||||||
impl Unknown {
|
impl Unknown {
|
||||||
/// The proxy graphics bytes of an entity: the 310 groups after its size group (92, or 160 in
|
/// The proxy graphics bytes of an entity: the 310 groups after its size group (92, or 160 in
|
||||||
/// newer files), cut to that size. An ACAD_PROXY_ENTITY holds them in its proxy data: the size
|
/// newer files), cut to that size. An ACAD_PROXY_ENTITY holds them in its proxy data: the size
|
||||||
@@ -92,21 +122,22 @@ impl Unknown {
|
|||||||
Some((at, size))
|
Some((at, size))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The record's groups with the layer indices of its proxy graphics (ATTRIBUTE_LAYER) turned
|
/// The record's groups with the table indices of its proxy graphics (ATTRIBUTE_LAYER and
|
||||||
/// into the written LAYER table `written`, by name; everything else as read. The name of an
|
/// ATTRIBUTE_LINETYPE) turned into the written tables `written`, by name; everything else as
|
||||||
/// index is the one the record's own decoded graphics draw on after it (so a proxy copied from
|
/// read. The name of an index is the one the record's own decoded graphics use after it (so a
|
||||||
/// another drawing, or one whose layer was renamed, keeps the layer it shows); an index no
|
/// proxy copied from another drawing, or one whose layer was renamed, keeps what it shows);
|
||||||
/// drawn entity follows takes the name from the file's table `read` (see
|
/// an index no drawn entity follows takes the name from the file's tables `read` (see
|
||||||
/// [`crate::Drawing::proxy_layers`]). A layer that is gone becomes layer 0 (the proxy's own
|
/// [`crate::Drawing::proxy_layers`] and [`crate::Drawing::proxy_linetypes`]).
|
||||||
/// layer, as in a block); an index past the table, or one of a record without a name, stays
|
///
|
||||||
/// past the written one, which keeps the layer before it as AutoCAD does. Only the 310 groups
|
/// A layer that is gone becomes layer 0 (the proxy's own layer, as in a block); a layer index
|
||||||
/// that hold the declared size are read and rewritten. `None` when no index changes, or the
|
/// past the table, or one of a record without a name, stays past the written one, which keeps
|
||||||
/// graphics aren't readable.
|
/// the layer before it as AutoCAD does. A linetype that is gone, or an index that names none,
|
||||||
pub fn with_proxy_layers(&self, read: &[String], written: &[String]) -> Option<Vec<RawTag>> {
|
/// becomes ByLayer (32767, what an index past the table means too); ByBlock (32766) and
|
||||||
// Only a proxy entity's own graphics: a kept dimension draws from its block instead.
|
/// ByLayer stay. The picture of a kept dimension (#3438) is rewritten too: by the tables alone
|
||||||
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
|
/// when the dimension draws its block instead. Only the 310 groups that hold the declared size
|
||||||
return None;
|
/// are read and rewritten. `None` when no index changes, or the graphics aren't readable.
|
||||||
}
|
pub fn with_proxy_tables(&self, read: TableOrder<'_>, written: TableOrder<'_>) -> Option<Vec<RawTag>> {
|
||||||
|
use std::collections::HashMap;
|
||||||
let (at, size) = self.graphics_size_group()?;
|
let (at, size) = self.graphics_size_group()?;
|
||||||
let (mut bytes, mut groups) = (Vec::new(), Vec::new());
|
let (mut bytes, mut groups) = (Vec::new(), Vec::new());
|
||||||
for i in (at + 1..self.tags.len()).take_while(|&i| self.tags[i].code == 310) {
|
for i in (at + 1..self.tags.len()).take_while(|&i| self.tags[i].code == 310) {
|
||||||
@@ -120,49 +151,72 @@ impl Unknown {
|
|||||||
groups.push((i, bytes.len() - before));
|
groups.push((i, bytes.len() - before));
|
||||||
}
|
}
|
||||||
let end = size.min(bytes.len());
|
let end = size.min(bytes.len());
|
||||||
// The ATTRIBUTE_LAYER chunks: where each index sits.
|
// The ATTRIBUTE_LAYER (16) and ATTRIBUTE_LINETYPE (18) chunks: where each index sits.
|
||||||
let mut refs: Vec<(usize, u32)> = Vec::new();
|
let mut refs: Vec<(usize, u32, u32)> = Vec::new();
|
||||||
let mut chunk = 8usize;
|
let mut chunk = 8usize;
|
||||||
while let (Some(len), Some(kind)) = (u32_at(&bytes[..end], chunk), u32_at(&bytes[..end], chunk + 4)) {
|
while let (Some(len), Some(kind)) = (u32_at(&bytes[..end], chunk), u32_at(&bytes[..end], chunk + 4)) {
|
||||||
let len = len as usize;
|
let len = len as usize;
|
||||||
if len < 8 || chunk.saturating_add(len) > end {
|
if len < 8 || chunk.saturating_add(len) > end {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if kind == 16
|
if (kind == LAYER_CHUNK || kind == LINETYPE_CHUNK)
|
||||||
&& let Some(i) = u32_at(&bytes[..chunk + len], chunk + 8)
|
&& let Some(i) = u32_at(&bytes[..chunk + len], chunk + 8)
|
||||||
{
|
{
|
||||||
refs.push((chunk + 8, i));
|
refs.push((chunk + 8, kind, i));
|
||||||
}
|
}
|
||||||
chunk += len;
|
chunk += len;
|
||||||
}
|
}
|
||||||
if refs.is_empty() {
|
if refs.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let indices: Vec<u32> = refs.iter().map(|r| r.1).collect();
|
let of = |k: u32| -> Vec<u32> { refs.iter().filter(|r| r.1 == k).map(|r| r.2).collect() };
|
||||||
let learned = self.layers_by_index(&bytes[..end], &indices);
|
let learned = self.names_by_index(&bytes[..end], &of(LAYER_CHUNK), &of(LINETYPE_CHUNK), read.layers);
|
||||||
if read.is_empty() && learned.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
// Each written name's first place, found once.
|
// Each written name's first place, found once.
|
||||||
let mut place: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
|
let places = |names: &[String]| {
|
||||||
for (p, n) in written.iter().enumerate() {
|
let mut place: HashMap<String, u32> = HashMap::new();
|
||||||
place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX));
|
for (p, n) in names.iter().enumerate() {
|
||||||
}
|
place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX));
|
||||||
let zero = place.get("0").copied();
|
}
|
||||||
let past = u32::try_from(written.len()).unwrap_or(u32::MAX).max(u32::try_from(read.len()).unwrap_or(u32::MAX));
|
place
|
||||||
let mut resolved: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
|
};
|
||||||
|
let (layer_at, linetype_at) = (places(written.layers), places(written.linetypes));
|
||||||
|
let zero = layer_at.get("0").copied();
|
||||||
|
let len = |names: &[String]| u32::try_from(names.len()).unwrap_or(u32::MAX);
|
||||||
|
let layers_past = len(written.layers).max(len(read.layers));
|
||||||
|
let linetypes_past = len(written.linetypes).max(len(read.linetypes));
|
||||||
|
// Without the file's table or names from the graphics, an index can't be placed.
|
||||||
|
let known_layers = !read.layers.is_empty() || !learned.layers.is_empty();
|
||||||
|
let known_linetypes = !read.linetypes.is_empty() || !learned.linetypes.is_empty();
|
||||||
|
let layer = |i: u32| {
|
||||||
|
let name = match learned.layers.get(&i) {
|
||||||
|
Some(name) => name.as_deref(),
|
||||||
|
None => read.layers.get(i as usize).map(String::as_str),
|
||||||
|
};
|
||||||
|
match name.filter(|n| !n.is_empty()) {
|
||||||
|
Some(name) => layer_at.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i),
|
||||||
|
None if i >= layers_past => i,
|
||||||
|
None => layers_past,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let linetype = |i: u32| {
|
||||||
|
if i == LINETYPE_BYBLOCK || i == LINETYPE_BYLAYER {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
let name = learned.linetypes.get(&i).or_else(|| read.linetypes.get(i as usize)).map(String::as_str);
|
||||||
|
let by = |n: &str| n.eq_ignore_ascii_case("ByLayer") || n.eq_ignore_ascii_case("ByBlock");
|
||||||
|
match name.filter(|n| !n.is_empty() && !by(n)) {
|
||||||
|
Some(name) => linetype_at.get(&name.to_ascii_lowercase()).copied().unwrap_or(LINETYPE_BYLAYER),
|
||||||
|
None if i >= linetypes_past => i,
|
||||||
|
None => LINETYPE_BYLAYER,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut resolved: HashMap<(u32, u32), u32> = HashMap::new();
|
||||||
let mut changed = false;
|
let mut changed = false;
|
||||||
for (offset, i) in refs {
|
for (offset, kind, i) in refs {
|
||||||
let j = *resolved.entry(i).or_insert_with(|| {
|
let j = *resolved.entry((kind, i)).or_insert_with(|| match kind {
|
||||||
let name = match learned.get(&i) {
|
LAYER_CHUNK if known_layers => layer(i),
|
||||||
Some(name) => name.as_deref(),
|
LINETYPE_CHUNK if known_linetypes => linetype(i),
|
||||||
None => read.get(i as usize).map(String::as_str),
|
_ => i,
|
||||||
};
|
|
||||||
match name.filter(|n| !n.is_empty()) {
|
|
||||||
Some(name) => place.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i),
|
|
||||||
None if i >= past => i,
|
|
||||||
None => past,
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
if j != i {
|
if j != i {
|
||||||
bytes[offset..offset + 4].copy_from_slice(&j.to_le_bytes());
|
bytes[offset..offset + 4].copy_from_slice(&j.to_le_bytes());
|
||||||
@@ -181,15 +235,20 @@ impl Unknown {
|
|||||||
Some(tags)
|
Some(tags)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The layer each ATTRIBUTE_LAYER index of `bytes` (the record's `indices`) stands for in
|
/// The layer and linetype each index of `bytes` (the record's ATTRIBUTE_LAYER indices
|
||||||
/// this record's decoded graphics: the bytes decoded again with index `i` named `#i` give the
|
/// `layers` and ATTRIBUTE_LINETYPE indices `linetypes`) stands for in this record's decoded
|
||||||
/// same entities in the same order, so each one's marker meets its real layer. `None` for an
|
/// graphics: the bytes decoded again with each index `i` named `#i` give the same entities in
|
||||||
/// index after which the graphics stay on the layer before (one past the table it was read
|
/// the same order, so each one's marker meets its real name. Only the indices the record uses
|
||||||
/// with). An index above 65,535 isn't named here (it resolves through the file's table, like
|
/// get a marker, so the work follows the chunks, not the largest index.
|
||||||
/// one no entity follows). Empty when the graphics don't match
|
///
|
||||||
/// (not decoded from these bytes); an index whose entities disagree is left out.
|
/// A layer is `None` for an index after which the graphics stay on the layer before (one past
|
||||||
fn layers_by_index(&self, bytes: &[u8], indices: &[u32]) -> std::collections::HashMap<u32, Option<String>> {
|
/// the table it was read with). When the entities after an index stay on the layer before but
|
||||||
/// What the entities after an index say about it.
|
/// the file's LAYER table `read` names that layer at the index, it names it. An index whose
|
||||||
|
/// entities disagree is left out. Empty when the graphics don't match (not decoded from these
|
||||||
|
/// bytes, such as a kept dimension's reference to its block).
|
||||||
|
fn names_by_index(&self, bytes: &[u8], layers: &[u32], linetypes: &[u32], read: &[String]) -> Learned {
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
/// What the entities after a layer index say about it.
|
||||||
enum Seen {
|
enum Seen {
|
||||||
/// They are on this layer, and the ones before them weren't.
|
/// They are on this layer, and the ones before them weren't.
|
||||||
Named(String),
|
Named(String),
|
||||||
@@ -199,27 +258,42 @@ impl Unknown {
|
|||||||
/// It keeps the layer before (two kept observations on different layers).
|
/// It keeps the layer before (two kept observations on different layers).
|
||||||
Keeps,
|
Keeps,
|
||||||
}
|
}
|
||||||
const MAX: u32 = 65_535;
|
let mut out = Learned::default();
|
||||||
let mut out: std::collections::HashMap<u32, Option<String>> = std::collections::HashMap::new();
|
if self.graphics.is_empty() || self.graphics.iter().any(|g| matches!(g.kind, EntityKind::Insert(_))) {
|
||||||
if self.graphics.is_empty() {
|
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
let max = indices.iter().copied().filter(|&i| i <= MAX).max().unwrap_or(0);
|
let mark = |i: &u32| (*i, format!("\u{1}{i}"));
|
||||||
let markers = ProxyTables { layers: (0..=max).map(|i| format!("\u{1}{i}")).collect(), ..ProxyTables::default() };
|
let marks = Marks {
|
||||||
let marked = proxy_entities(bytes, &markers, Handle(0));
|
layers: layers.iter().map(mark).collect(),
|
||||||
|
linetypes: linetypes.iter().filter(|&&i| i != LINETYPE_BYBLOCK && i != LINETYPE_BYLAYER).map(mark).collect(),
|
||||||
|
};
|
||||||
|
let marked = decode(bytes, &ProxyTables::default(), Handle(0), Some(&marks));
|
||||||
if marked.len() != self.graphics.len() {
|
if marked.len() != self.graphics.len() {
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
|
let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
|
||||||
let mut seen: std::collections::HashMap<u32, Seen> = std::collections::HashMap::new();
|
let index = |name: &str| name.strip_prefix('\u{1}').and_then(|i| i.parse::<u32>().ok());
|
||||||
let mut conflict = std::collections::HashSet::new();
|
let mut seen: HashMap<u32, Seen> = HashMap::new();
|
||||||
|
let mut conflict = HashSet::new();
|
||||||
|
let mut linetype_conflict = HashSet::new();
|
||||||
let mut before: Option<(&str, &str)> = None;
|
let mut before: Option<(&str, &str)> = None;
|
||||||
for (m, g) in marked.iter().zip(&self.graphics) {
|
for (m, g) in marked.iter().zip(&self.graphics) {
|
||||||
|
if let Some(i) = index(&m.common.linetype) {
|
||||||
|
match out.linetypes.get(&i) {
|
||||||
|
Some(a) if !same(a, &g.common.linetype) => {
|
||||||
|
linetype_conflict.insert(i);
|
||||||
|
}
|
||||||
|
Some(_) => {}
|
||||||
|
None => {
|
||||||
|
out.linetypes.insert(i, g.common.linetype.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
let (mark, real) = (m.common.layer.as_str(), g.common.layer.as_str());
|
let (mark, real) = (m.common.layer.as_str(), g.common.layer.as_str());
|
||||||
let changed_here = before.is_none_or(|(prev_mark, _)| prev_mark != mark);
|
let changed_here = before.is_none_or(|(prev_mark, _)| prev_mark != mark);
|
||||||
let kept = before.is_some_and(|(_, prev_real)| same(prev_real, real));
|
let kept = before.is_some_and(|(_, prev_real)| same(prev_real, real));
|
||||||
before = Some((mark, real));
|
before = Some((mark, real));
|
||||||
let Some(i) = mark.strip_prefix('\u{1}').and_then(|i| i.parse::<u32>().ok()) else { continue };
|
let Some(i) = index(mark) else { continue };
|
||||||
if !changed_here {
|
if !changed_here {
|
||||||
// The same marker on another real layer: an index in between (one past the table
|
// The same marker on another real layer: an index in between (one past the table
|
||||||
// the marker decoding doesn't see as such) changed it, so this one can't be named.
|
// the marker decoding doesn't see as such) changed it, so this one can't be named.
|
||||||
@@ -247,10 +321,19 @@ impl Unknown {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (i, s) in seen {
|
for (i, s) in seen {
|
||||||
if !conflict.contains(&i) {
|
if conflict.contains(&i) {
|
||||||
out.insert(i, if let Seen::Named(n) = s { Some(n) } else { None });
|
continue;
|
||||||
}
|
}
|
||||||
|
let name = match s {
|
||||||
|
Seen::Named(n) => Some(n),
|
||||||
|
// Staying on the layer before says nothing when the table names that layer here:
|
||||||
|
// the index sets it again.
|
||||||
|
Seen::Kept(n) => read.get(i as usize).filter(|r| !r.is_empty() && same(r, &n)).map(|_| n),
|
||||||
|
Seen::Keeps => None,
|
||||||
|
};
|
||||||
|
out.layers.insert(i, name);
|
||||||
}
|
}
|
||||||
|
out.linetypes.retain(|i, _| !linetype_conflict.contains(i));
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -261,16 +344,27 @@ impl crate::Drawing {
|
|||||||
/// it at once. RENAME calls it, LAYMRG for each merged layer (its graphics move to the
|
/// it at once. RENAME calls it, LAYMRG for each merged layer (its graphics move to the
|
||||||
/// target, as its objects do) and LAYDEL with layer 0.
|
/// target, as its objects do) and LAYDEL with layer 0.
|
||||||
pub fn rename_proxy_layer(&mut self, old: &str, new: &str) {
|
pub fn rename_proxy_layer(&mut self, old: &str, new: &str) {
|
||||||
for n in &mut self.proxy_layers {
|
rename_in(&mut self.proxy_layers, old, new);
|
||||||
if n.eq_ignore_ascii_case(old) {
|
self.rename_in_graphics(old, new, TableName::Layer);
|
||||||
*n = new.to_string();
|
}
|
||||||
}
|
|
||||||
}
|
/// Rename linetype `old` to `new` where proxy graphics use it, as
|
||||||
let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| g.common.layer.eq_ignore_ascii_case(old)));
|
/// [`crate::Drawing::rename_proxy_layer`] does for a layer: RENAME calls it.
|
||||||
|
pub fn rename_proxy_linetype(&mut self, old: &str, new: &str) {
|
||||||
|
rename_in(&mut self.proxy_linetypes, old, new);
|
||||||
|
self.rename_in_graphics(old, new, TableName::Linetype);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rename the graphics' `field` from `old` to `new`.
|
||||||
|
fn rename_in_graphics(&mut self, old: &str, new: &str, field: TableName) {
|
||||||
|
let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| field.of(&g.common).eq_ignore_ascii_case(old)));
|
||||||
let fix = |e: &mut Entity| {
|
let fix = |e: &mut Entity| {
|
||||||
if let EntityKind::Unknown(u) = &mut e.kind {
|
if let EntityKind::Unknown(u) = &mut e.kind {
|
||||||
for g in u.graphics.iter_mut().filter(|g| g.common.layer.eq_ignore_ascii_case(old)) {
|
for g in &mut u.graphics {
|
||||||
g.common.layer = new.to_string();
|
let n = field.of_mut(&mut g.common);
|
||||||
|
if n.eq_ignore_ascii_case(old) {
|
||||||
|
*n = new.to_string();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -290,6 +384,36 @@ impl crate::Drawing {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The table name of an entity's properties that proxy graphics set by index.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
enum TableName {
|
||||||
|
Layer,
|
||||||
|
Linetype,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TableName {
|
||||||
|
fn of(self, c: &Common) -> &str {
|
||||||
|
match self {
|
||||||
|
TableName::Layer => &c.layer,
|
||||||
|
TableName::Linetype => &c.linetype,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn of_mut(self, c: &mut Common) -> &mut String {
|
||||||
|
match self {
|
||||||
|
TableName::Layer => &mut c.layer,
|
||||||
|
TableName::Linetype => &mut c.linetype,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rename `old` to `new` in the table order `names`.
|
||||||
|
fn rename_in(names: &mut [String], old: &str, new: &str) {
|
||||||
|
for n in names.iter_mut().filter(|n| n.eq_ignore_ascii_case(old)) {
|
||||||
|
*n = new.to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
|
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
|
||||||
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
|
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
|
||||||
let digits: Vec<u8> = s.trim().bytes().collect();
|
let digits: Vec<u8> = s.trim().bytes().collect();
|
||||||
@@ -304,8 +428,14 @@ fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
|
|||||||
/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one
|
/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one
|
||||||
/// selects the proxy.
|
/// selects the proxy.
|
||||||
pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec<Entity> {
|
pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec<Entity> {
|
||||||
|
decode(bytes, tables, handle, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`proxy_entities`], with the indices in `marks` named by them instead of `tables`.
|
||||||
|
fn decode(bytes: &[u8], tables: &ProxyTables, handle: Handle, marks: Option<&Marks>) -> Vec<Entity> {
|
||||||
let mut r = Decoder {
|
let mut r = Decoder {
|
||||||
tables,
|
tables,
|
||||||
|
marks,
|
||||||
handle,
|
handle,
|
||||||
pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() },
|
pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() },
|
||||||
fill: false,
|
fill: false,
|
||||||
@@ -327,6 +457,8 @@ pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec
|
|||||||
|
|
||||||
struct Decoder<'a> {
|
struct Decoder<'a> {
|
||||||
tables: &'a ProxyTables,
|
tables: &'a ProxyTables,
|
||||||
|
/// Names standing for the indices while a record is decoded again (`Unknown::names_by_index`).
|
||||||
|
marks: Option<&'a Marks>,
|
||||||
handle: Handle,
|
handle: Handle,
|
||||||
/// Layer, colour, linetype and lineweight for the entities that follow.
|
/// Layer, colour, linetype and lineweight for the entities that follow.
|
||||||
pen: Common,
|
pen: Common,
|
||||||
@@ -427,18 +559,26 @@ impl Decoder<'_> {
|
|||||||
}
|
}
|
||||||
// ATTRIBUTE_LAYER: index into the layer table; an index past it, or one of a record
|
// ATTRIBUTE_LAYER: index into the layer table; an index past it, or one of a record
|
||||||
// without a name, leaves the layer.
|
// without a name, leaves the layer.
|
||||||
16 => {
|
LAYER_CHUNK => {
|
||||||
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)).filter(|n| !n.is_empty()) {
|
let name = b.u32().and_then(|i| match self.marks {
|
||||||
|
Some(m) => m.layers.get(&i),
|
||||||
|
None => self.tables.layers.get(i as usize),
|
||||||
|
});
|
||||||
|
if let Some(name) = name.filter(|n| !n.is_empty()) {
|
||||||
self.pen.layer = name.clone();
|
self.pen.layer = name.clone();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer;
|
// ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer;
|
||||||
// 32766 is ByBlock, 32767 and anything past the table ByLayer.
|
// 32766 is ByBlock, 32767 and anything past the table ByLayer.
|
||||||
18 => {
|
LINETYPE_CHUNK => {
|
||||||
if let Some(i) = b.u32() {
|
if let Some(i) = b.u32() {
|
||||||
|
let name = match self.marks {
|
||||||
|
Some(m) => m.linetypes.get(&i),
|
||||||
|
None => self.tables.linetypes.get(i as usize),
|
||||||
|
};
|
||||||
self.pen.linetype = match i {
|
self.pen.linetype = match i {
|
||||||
32766 => "ByBlock".into(),
|
LINETYPE_BYBLOCK => "ByBlock".into(),
|
||||||
_ => self.tables.linetypes.get(i as usize).filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()),
|
_ => name.filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -596,6 +736,15 @@ impl Decoder<'_> {
|
|||||||
fn arc_between(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3, a0: f64, a1: f64) {
|
fn arc_between(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3, a0: f64, a1: f64) {
|
||||||
let (at, u, v) = self.axes(c, e1, e2);
|
let (at, u, v) = self.axes(c, e1, e2);
|
||||||
let on = |a: f64| at + u * (r * a.cos()) + v * (r * a.sin());
|
let on = |a: f64| at + u * (r * a.cos()) + v * (r * a.sin());
|
||||||
|
// A sweep too short for an arc or an elliptical arc to hold (it would read as a full
|
||||||
|
// turn): the chord between its ends.
|
||||||
|
if (a1 - a0).abs() <= cadcraft_geom::EPS {
|
||||||
|
let (p, q) = (on(a0), on(a1));
|
||||||
|
if p != q && p.is_finite() && q.is_finite() {
|
||||||
|
self.push(EntityKind::Line(Line { a: p.to3(0.0), b: q.to3(0.0) }));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
if round(u * r, v * r).is_some() {
|
if round(u * r, v * r).is_some() {
|
||||||
return self.arc_3p(on(a0), on((a0 + a1) / 2.0), on(a1));
|
return self.arc_3p(on(a0), on((a0 + a1) / 2.0), on(a1));
|
||||||
}
|
}
|
||||||
@@ -767,6 +916,13 @@ fn round(u: Vec2, v: Vec2) -> Option<f64> {
|
|||||||
/// ellipse's own parameter (counter-clockwise from its major axis).
|
/// ellipse's own parameter (counter-clockwise from its major axis).
|
||||||
fn ellipse(c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) -> Option<Ellipse> {
|
fn ellipse(c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) -> Option<Ellipse> {
|
||||||
use std::f64::consts::{FRAC_PI_2, TAU};
|
use std::f64::consts::{FRAC_PI_2, TAU};
|
||||||
|
// Conjugate radii on one line (a plane seen edge-on, also through an exact quarter turn,
|
||||||
|
// whose cosine leaves a tiny minor axis), relative to the longer: no ellipse, the caller
|
||||||
|
// draws the line it covers.
|
||||||
|
let longer = u.len().max(v.len());
|
||||||
|
if u.cross(v).abs() <= 1e-9 * longer * longer {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
// c + u·cos a + v·sin a = c + p·cos(a − t) + q·sin(a − t): p and q at right angles.
|
// c + u·cos a + v·sin a = c + p·cos(a − t) + q·sin(a − t): p and q at right angles.
|
||||||
let t = 0.5 * (2.0 * u.dot(v)).atan2(u.len2() - v.len2());
|
let t = 0.5 * (2.0 * u.dot(v)).atan2(u.len2() - v.len2());
|
||||||
let p = u * t.cos() + v * t.sin();
|
let p = u * t.cos() + v * t.sin();
|
||||||
@@ -1299,6 +1455,155 @@ mod tests {
|
|||||||
assert!(own.proxy_graphics_bytes().is_empty());
|
assert!(own.proxy_graphics_bytes().is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The layer order `names` with no linetypes.
|
||||||
|
fn layers(names: &[String]) -> TableOrder<'_> {
|
||||||
|
TableOrder { layers: names, linetypes: &[] }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A record with the graphics `g`: in its proxy data for an ACAD_PROXY_ENTITY, else in its
|
||||||
|
/// `AcDbEntity` part (a kept dimension naming block `*D1`).
|
||||||
|
fn record(dxf_type: &str, g: &[u8], graphics: Vec<Entity>) -> Unknown {
|
||||||
|
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||||
|
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
|
||||||
|
let tags = if dxf_type == "ACAD_PROXY_ENTITY" {
|
||||||
|
vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex)]
|
||||||
|
} else {
|
||||||
|
vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(92, &g.len().to_string()), tag(310, &hex), tag(100, "AcDbDimension"), tag(2, "*D1")]
|
||||||
|
};
|
||||||
|
Unknown { dxf_type: dxf_type.into(), tags, graphics }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unit_circle() -> Vec<u8> {
|
||||||
|
let mut circle = pt(0.0, 0.0);
|
||||||
|
circle.extend(1.0f64.to_le_bytes());
|
||||||
|
circle.extend(pt(0.0, 0.0));
|
||||||
|
circle
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Graphics that stay on the layer before after an index don't hide that the table names the
|
||||||
|
/// index: with layers 1, then 2 and 99, then 2, then 1 and 99 before four circles (A, B, B,
|
||||||
|
/// A), the second 2 sets B again, and saving keeps all four where they are.
|
||||||
|
#[test]
|
||||||
|
fn an_index_staying_on_the_layer_its_table_names_keeps_it() {
|
||||||
|
let circle = unit_circle();
|
||||||
|
let layer = |i: u32| chunk(16, &i.to_le_bytes());
|
||||||
|
let g = graphics(&[
|
||||||
|
layer(1),
|
||||||
|
chunk(2, &circle),
|
||||||
|
layer(2),
|
||||||
|
layer(99),
|
||||||
|
chunk(2, &circle),
|
||||||
|
layer(2),
|
||||||
|
chunk(2, &circle),
|
||||||
|
layer(1),
|
||||||
|
layer(99),
|
||||||
|
chunk(2, &circle),
|
||||||
|
]);
|
||||||
|
let read: Vec<String> = ["0", "A", "B"].map(String::from).to_vec();
|
||||||
|
let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() };
|
||||||
|
let u = record("ACAD_PROXY_ENTITY", &g, proxy_entities(&g, &tables, Handle(1)));
|
||||||
|
let on = |es: &[Entity]| es.iter().map(|e| e.common.layer.clone()).collect::<Vec<_>>();
|
||||||
|
assert_eq!(on(&u.graphics), ["A", "B", "B", "A"]);
|
||||||
|
assert!(u.with_proxy_tables(layers(&read), layers(&read)).is_none(), "nothing changes for the same table");
|
||||||
|
let written: Vec<String> = ["0", "X", "A", "B"].map(String::from).to_vec();
|
||||||
|
let again = Unknown { tags: u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped"), ..u.clone() };
|
||||||
|
let w = ProxyTables { layers: written, ..ProxyTables::default() };
|
||||||
|
assert_eq!(on(&proxy_entities(&again.proxy_graphics_bytes(), &w, Handle(1))), ["A", "B", "B", "A"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Linetype indices follow the written LTYPE table by name, as layer indices do: a linetype
|
||||||
|
/// that is gone becomes ByLayer, and ByBlock, ByLayer and an index past the table stay.
|
||||||
|
#[test]
|
||||||
|
fn linetype_indices_follow_the_written_table() {
|
||||||
|
let circle = unit_circle();
|
||||||
|
let linetype = |i: u32| chunk(18, &i.to_le_bytes());
|
||||||
|
let g = graphics(&[
|
||||||
|
linetype(2),
|
||||||
|
chunk(2, &circle),
|
||||||
|
linetype(32766),
|
||||||
|
chunk(2, &circle),
|
||||||
|
linetype(1),
|
||||||
|
chunk(2, &circle),
|
||||||
|
linetype(9),
|
||||||
|
chunk(2, &circle),
|
||||||
|
]);
|
||||||
|
let read: Vec<String> = ["Continuous", "DASHED", "HIDDEN"].map(String::from).to_vec();
|
||||||
|
let tables = ProxyTables { linetypes: read.clone(), ..ProxyTables::default() };
|
||||||
|
let u = record("ACAD_PROXY_ENTITY", &g, proxy_entities(&g, &tables, Handle(1)));
|
||||||
|
let drawn = |es: &[Entity]| es.iter().map(|e| e.common.linetype.clone()).collect::<Vec<_>>();
|
||||||
|
assert_eq!(drawn(&u.graphics), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]);
|
||||||
|
let saved = |written: &[String]| {
|
||||||
|
let tags = u.with_proxy_tables(TableOrder { layers: &[], linetypes: &read }, TableOrder { layers: &[], linetypes: written });
|
||||||
|
let again = Unknown { tags: tags.unwrap_or_else(|| u.tags.clone()), ..u.clone() };
|
||||||
|
drawn(&proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { linetypes: written.to_vec(), ..ProxyTables::default() }, Handle(1)))
|
||||||
|
};
|
||||||
|
let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||||
|
assert_eq!(saved(&read), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]);
|
||||||
|
assert_eq!(saved(&names(&["Continuous", "CENTER", "DASHED", "HIDDEN"])), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]);
|
||||||
|
assert_eq!(saved(&names(&["Continuous", "HIDDEN"])), ["HIDDEN", "ByBlock", "ByLayer", "ByLayer"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A kept dimension's picture (#3438) follows the written LAYER table too: by its decoded
|
||||||
|
/// graphics when it draws them, by the file's table when it draws its block instead.
|
||||||
|
#[test]
|
||||||
|
fn a_kept_dimensions_picture_follows_the_written_table() {
|
||||||
|
let circle = unit_circle();
|
||||||
|
let g = graphics(&[chunk(16, &2u32.to_le_bytes()), chunk(2, &circle)]);
|
||||||
|
let read: Vec<String> = ["0", "UNUSED", "A"].map(String::from).to_vec();
|
||||||
|
let written: Vec<String> = ["0", "A", "Defpoints"].map(String::from).to_vec();
|
||||||
|
let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() };
|
||||||
|
let w = ProxyTables { layers: written.clone(), ..ProxyTables::default() };
|
||||||
|
for graphics in [proxy_entities(&g, &tables, Handle(1)), vec![block_ref()]] {
|
||||||
|
let u = record("LARGE_RADIAL_DIMENSION", &g, graphics);
|
||||||
|
let again = Unknown { tags: u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped"), ..u.clone() };
|
||||||
|
assert_eq!(proxy_entities(&again.proxy_graphics_bytes(), &w, Handle(1))[0].common.layer, "A");
|
||||||
|
}
|
||||||
|
// A reference to the block on another layer isn't taken for the picture (one entity as
|
||||||
|
// well): the file's table names index 2.
|
||||||
|
let elsewhere = Entity { common: Common { layer: "Defpoints".into(), ..Common::default() }, ..block_ref() };
|
||||||
|
let u = record("LARGE_RADIAL_DIMENSION", &g, vec![elsewhere]);
|
||||||
|
assert!(u.names_by_index(&g, &[2], &[], &read).layers.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn block_ref() -> Entity {
|
||||||
|
Entity {
|
||||||
|
handle: Handle(1),
|
||||||
|
common: Common::default(),
|
||||||
|
kind: EntityKind::Insert(super::super::Insert { block: "*D1".into(), ..super::super::Insert::default() }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An exact quarter turn about Y shows a circle edge-on: it draws as the line it covers, not
|
||||||
|
/// as an ellipse with the minor axis the turn's cosine leaves. An arc too short for its sweep
|
||||||
|
/// to be held draws as its chord, not as a full turn, round or under an uneven matrix.
|
||||||
|
#[test]
|
||||||
|
fn quarter_turns_and_tiny_sweeps_draw_lines() {
|
||||||
|
let matrix = |m: [f64; 16]| chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
|
||||||
|
let (s, c) = std::f64::consts::FRAC_PI_2.sin_cos();
|
||||||
|
let turn = matrix([c, 0.0, s, 0.0, 0.0, 1.0, 0.0, 0.0, -s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0]);
|
||||||
|
let line = |es: &[Entity]| match es {
|
||||||
|
[e] => match &e.kind {
|
||||||
|
EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
},
|
||||||
|
_ => panic!("{es:?}"),
|
||||||
|
};
|
||||||
|
let near = |p: Vec2, x: f64, y: f64| (p - Vec2::new(x, y)).len() < 1e-12;
|
||||||
|
let (a, b) = line(&proxy_entities(&graphics(&[turn, chunk(2, &unit_circle())]), &tables(), Handle(1)));
|
||||||
|
assert!(near(a, 0.0, -1.0) && near(b, 0.0, 1.0), "{a:?} {b:?}");
|
||||||
|
let sweep = 5e-10f64;
|
||||||
|
let mut tiny = pt(0.0, 0.0);
|
||||||
|
tiny.extend(1.0f64.to_le_bytes());
|
||||||
|
tiny.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||||
|
tiny.extend(pt(1.0, 0.0));
|
||||||
|
tiny.extend(sweep.to_le_bytes());
|
||||||
|
let stretch = matrix([2.0, 0.0, 0.0, 10.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
|
||||||
|
for (chunks, x) in [(vec![chunk(4, &tiny)], 1.0), (vec![stretch, chunk(4, &tiny)], 12.0)] {
|
||||||
|
let (a, b) = line(&proxy_entities(&graphics(&chunks), &tables(), Handle(1)));
|
||||||
|
assert!(near(a, x, 0.0) && (b - Vec2::new(x, sweep)).len() < 1e-15, "{a:?} {b:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Saving renames the layer indices by name into the written table, reading only the 310
|
/// Saving renames the layer indices by name into the written table, reading only the 310
|
||||||
/// groups the declared size needs: a damaged group after them doesn't stop it.
|
/// groups the declared size needs: a damaged group after them doesn't stop it.
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1318,7 +1623,7 @@ mod tests {
|
|||||||
};
|
};
|
||||||
assert_eq!(u.graphics[0].common.layer, "B");
|
assert_eq!(u.graphics[0].common.layer, "B");
|
||||||
let written: Vec<String> = ["0", "B", "C"].map(String::from).to_vec();
|
let written: Vec<String> = ["0", "B", "C"].map(String::from).to_vec();
|
||||||
let tags = u.with_proxy_layers(&read, &written).expect("remapped");
|
let tags = u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped");
|
||||||
let again = Unknown { tags, ..u.clone() };
|
let again = Unknown { tags, ..u.clone() };
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { layers: written, ..ProxyTables::default() }, Handle(1))[0].common.layer,
|
proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { layers: written, ..ProxyTables::default() }, Handle(1))[0].common.layer,
|
||||||
@@ -1328,8 +1633,8 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// An index whose graphics stay on the layer before (99 here, past the table) doesn't make
|
/// An index whose graphics stay on the layer before (99 here, past the table) doesn't make
|
||||||
/// the index before it (3) look contradictory when that one comes again; an index above
|
/// the index before it (3) look contradictory when that one comes again, and a large index
|
||||||
/// 65,535 isn't named (it resolves through the file's table), and the others still are.
|
/// is found like any other.
|
||||||
#[test]
|
#[test]
|
||||||
fn indices_are_named_around_kept_layers_and_huge_indices() {
|
fn indices_are_named_around_kept_layers_and_huge_indices() {
|
||||||
let mut circle = pt(0.0, 0.0);
|
let mut circle = pt(0.0, 0.0);
|
||||||
@@ -1345,12 +1650,13 @@ mod tests {
|
|||||||
}
|
}
|
||||||
let g = graphics(&chunks);
|
let g = graphics(&chunks);
|
||||||
let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: proxy_entities(&g, &tables, Handle(1)) };
|
let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: proxy_entities(&g, &tables, Handle(1)) };
|
||||||
let mut learned: Vec<(u32, Option<String>)> = u.layers_by_index(&g, indices).into_iter().collect();
|
let mut learned: Vec<(u32, Option<String>)> = u.names_by_index(&g, indices, &[], &tables.layers).layers.into_iter().collect();
|
||||||
learned.sort();
|
learned.sort();
|
||||||
learned
|
learned
|
||||||
};
|
};
|
||||||
assert_eq!(named(&[0, 3, 99, 3]), [(0, Some("0".into())), (3, Some("B".into())), (99, None)]);
|
assert_eq!(named(&[0, 3, 99, 3]), [(0, Some("0".into())), (3, Some("B".into())), (99, None)]);
|
||||||
assert_eq!(named(&[2, 70_000]), [(2, Some("C".into()))]);
|
// Only the indices used get a marker: 70,000 keeps the layer before, as past the table.
|
||||||
|
assert_eq!(named(&[2, 70_000]), [(2, Some("C".into())), (70_000, None)]);
|
||||||
// Layer 4 (past the table, so it keeps layer 0), a circle, then layers 1 and 4 at once (4
|
// Layer 4 (past the table, so it keeps layer 0), a circle, then layers 1 and 4 at once (4
|
||||||
// keeps A): both circles follow index 4 in the marker decoding, on different layers.
|
// keeps A): both circles follow index 4 in the marker decoding, on different layers.
|
||||||
let g = graphics(&[
|
let g = graphics(&[
|
||||||
@@ -1368,9 +1674,9 @@ mod tests {
|
|||||||
graphics: proxy_entities(&g, &tables, Handle(1)),
|
graphics: proxy_entities(&g, &tables, Handle(1)),
|
||||||
};
|
};
|
||||||
assert_eq!(u.graphics.iter().map(|e| e.common.layer.as_str()).collect::<Vec<_>>(), ["0", "A"]);
|
assert_eq!(u.graphics.iter().map(|e| e.common.layer.as_str()).collect::<Vec<_>>(), ["0", "A"]);
|
||||||
assert!(!u.layers_by_index(&g, &[4, 1, 4]).contains_key(&4), "index 4 isn't named");
|
assert!(!u.names_by_index(&g, &[4, 1, 4], &[], &tables.layers).layers.contains_key(&4), "index 4 isn't named");
|
||||||
// Saved with the same table, nothing changes, so both circles stay where they are.
|
// Saved with the same table, nothing changes, so both circles stay where they are.
|
||||||
assert!(u.with_proxy_layers(&tables.layers, &tables.layers).is_none());
|
assert!(u.with_proxy_tables(layers(&tables.layers), layers(&tables.layers)).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
|
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
|
||||||
|
|||||||
@@ -121,6 +121,9 @@ pub struct Drawing {
|
|||||||
pub model: EntityStore,
|
pub model: EntityStore,
|
||||||
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
|
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
|
||||||
pub model_page: Option<PageSetup>,
|
pub model_page: Option<PageSetup>,
|
||||||
|
/// The Model layout's own flags as the file had them (see [`Layout::flags`]); `None` for a
|
||||||
|
/// new drawing.
|
||||||
|
pub model_layout_flags: Option<i64>,
|
||||||
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
|
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
|
||||||
pub layouts: NamedList<Layout>,
|
pub layouts: NamedList<Layout>,
|
||||||
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
|
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
|
||||||
@@ -174,6 +177,9 @@ pub struct Drawing {
|
|||||||
/// turns those indices into the written table's (#3094). An empty name stands for a record
|
/// turns those indices into the written table's (#3094). An empty name stands for a record
|
||||||
/// without one. Empty for a drawing not read from a file.
|
/// without one. Empty for a drawing not read from a file.
|
||||||
pub proxy_layers: Vec<String>,
|
pub proxy_layers: Vec<String>,
|
||||||
|
/// The LTYPE table of that file in the same way, without ByBlock and ByLayer (proxy graphics
|
||||||
|
/// count the others).
|
||||||
|
pub proxy_linetypes: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Drawing {
|
impl Default for Drawing {
|
||||||
@@ -219,6 +225,7 @@ impl Drawing {
|
|||||||
blocks: NamedMap::default(),
|
blocks: NamedMap::default(),
|
||||||
model: EntityStore::new(),
|
model: EntityStore::new(),
|
||||||
model_page: None,
|
model_page: None,
|
||||||
|
model_layout_flags: None,
|
||||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
|
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
|
||||||
active_layout: None,
|
active_layout: None,
|
||||||
views: Vec::new(),
|
views: Vec::new(),
|
||||||
@@ -240,6 +247,7 @@ impl Drawing {
|
|||||||
portable_fonts: false,
|
portable_fonts: false,
|
||||||
rasters: Rasters::default(),
|
rasters: Rasters::default(),
|
||||||
proxy_layers: Vec::new(),
|
proxy_layers: Vec::new(),
|
||||||
|
proxy_linetypes: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -905,6 +905,11 @@ pub struct Layout {
|
|||||||
/// them; `None` for a layout CADCraft made, written as 0,0 to 12,9 (#2109).
|
/// them; `None` for a layout CADCraft made, written as 0,0 to 12,9 (#2109).
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub limits: Option<(Vec2, Vec2)>,
|
pub limits: Option<(Vec2, Vec2)>,
|
||||||
|
/// The layout's own flags (LAYOUT group 70 after the AcDbLayout marker; DXF Reference: 1 is
|
||||||
|
/// its PSLTSCALE and 2 its LIMCHECK, each the value while the layout is current) as the file
|
||||||
|
/// had them; `None` for a layout CADCraft made, saved with the drawing's PSLTSCALE.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub flags: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Layout {
|
impl Layout {
|
||||||
@@ -918,6 +923,7 @@ impl Layout {
|
|||||||
ucs: None,
|
ucs: None,
|
||||||
ucs_previous: Vec::new(),
|
ucs_previous: Vec::new(),
|
||||||
limits: None,
|
limits: None,
|
||||||
|
flags: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -480,6 +480,31 @@ fn table_create_edit_merge() {
|
|||||||
assert!(dl.prims.len() > 10);
|
assert!(dl.prims.len() > 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn covered_text_survives_save_and_unmerge() {
|
||||||
|
let text = "CoveredText".repeat(30);
|
||||||
|
let table = cadcraft_doc::Table {
|
||||||
|
col_widths: vec![2.0, 2.0],
|
||||||
|
row_heights: vec![0.5],
|
||||||
|
cells: vec![vec![
|
||||||
|
cadcraft_doc::TableCell { text: "Title".into(), merged: Some((1, 2)), ..Default::default() },
|
||||||
|
cadcraft_doc::TableCell { text: text.clone(), ..Default::default() },
|
||||||
|
]],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut drawing = cadcraft_doc::Drawing::new_imperial();
|
||||||
|
drawing.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Table(table)).unwrap();
|
||||||
|
let bytes = cadcraft_io::write(&drawing, "table.dxf").unwrap();
|
||||||
|
let drawing = cadcraft_io::read(&bytes, "table.dxf").unwrap();
|
||||||
|
let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Table(_))).unwrap().handle;
|
||||||
|
let mut session = Session::new();
|
||||||
|
session.open_drawing(drawing, "table.dxf", None);
|
||||||
|
session.execute("table.unmerge", &json!({ "handle": handle.hex(), "row": 0, "col": 1 })).unwrap();
|
||||||
|
let EntityKind::Table(table) = &session.doc().unwrap().entity(handle).unwrap().kind else { panic!("expected table") };
|
||||||
|
assert_eq!(table.cells[0][0].merged, None);
|
||||||
|
assert_eq!(table.cells[0][1].text, text);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn table_interactive() {
|
fn table_interactive() {
|
||||||
let mut s = Session::new();
|
let mut s = Session::new();
|
||||||
|
|||||||
@@ -220,7 +220,7 @@ fn modify_attrib(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut c
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The layer and colour attribute `k` of block reference `h` is drawn with: its own, else its
|
/// The layer and colour attribute `k` of block reference `h` is drawn with: its own, else its
|
||||||
/// definition's (layer 0 is the reference's layer).
|
/// definition's (layer 0 from the definition is the reference's layer).
|
||||||
fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)> {
|
fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)> {
|
||||||
let d = s.doc().ok()?;
|
let d = s.doc().ok()?;
|
||||||
let e = d.entity(h)?;
|
let e = d.entity(h)?;
|
||||||
@@ -230,7 +230,7 @@ fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)
|
|||||||
.block(&ins.block)
|
.block(&ins.block)
|
||||||
.and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))));
|
.and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))));
|
||||||
let c = a.props.over(&def.map(|de| de.common.clone()).unwrap_or_else(Common::default));
|
let c = a.props.over(&def.map(|de| de.common.clone()).unwrap_or_else(Common::default));
|
||||||
let layer = if c.layer == "0" { e.common.layer.clone() } else { c.layer };
|
let layer = if a.props.layer.is_none() && c.layer == "0" { e.common.layer.clone() } else { c.layer };
|
||||||
Some((layer, c.color))
|
Some((layer, c.color))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,13 +41,13 @@ fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
|
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
|
||||||
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
|
/// 0 from the definition is the reference's layer (an attribute set on layer 0 itself stays there)
|
||||||
/// block's objects.
|
/// and ByBlock colour the reference's colour, as EXPLODE gives the block's objects.
|
||||||
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
|
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
|
||||||
// An attribute without a definition follows the reference.
|
// An attribute without a definition follows the reference.
|
||||||
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
|
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
|
||||||
let mut c = props.over(&base);
|
let mut c = props.over(&base);
|
||||||
if c.layer == "0" {
|
if props.layer.is_none() && c.layer == "0" {
|
||||||
c.layer.clone_from(&e.common.layer);
|
c.layer.clone_from(&e.common.layer);
|
||||||
}
|
}
|
||||||
if c.color == Color::ByBlock {
|
if c.color == Color::ByBlock {
|
||||||
|
|||||||
@@ -115,7 +115,13 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
|
|||||||
let defs = b.attdefs_by_tag();
|
let defs = b.attdefs_by_tag();
|
||||||
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
|
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
|
||||||
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
|
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
|
||||||
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
|
let own = a.props.over(def.unwrap_or(&by_block));
|
||||||
|
let mut common = under(&own, r);
|
||||||
|
// An attribute set on layer 0 itself stays there; only layer 0 from its definition is
|
||||||
|
// the reference's layer.
|
||||||
|
if a.props.layer.is_some() {
|
||||||
|
common.layer.clone_from(&own.layer);
|
||||||
|
}
|
||||||
let kind = match a.multiline_text() {
|
let kind = match a.multiline_text() {
|
||||||
Some(m) => EntityKind::MText(m),
|
Some(m) => EntityKind::MText(m),
|
||||||
None => EntityKind::Text(a.text.clone()),
|
None => EntityKind::Text(a.text.clone()),
|
||||||
|
|||||||
@@ -220,14 +220,19 @@ fn linetypes_inside(e: &cadcraft_doc::Entity) -> Vec<String> {
|
|||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The linetypes named by objects, layers, dimension styles and multiline styles.
|
/// The linetypes named by objects, layers, dimension styles and multiline styles, and the ones
|
||||||
|
/// proxy graphics draw with (as for layers: saving names them by their index in the table).
|
||||||
fn linetypes_in_use(d: &Drawing) -> impl Iterator<Item = String> + '_ {
|
fn linetypes_in_use(d: &Drawing) -> impl Iterator<Item = String> + '_ {
|
||||||
let objects = entities(d).map(|e| e.common.linetype.clone());
|
let objects = entities(d).map(|e| e.common.linetype.clone());
|
||||||
|
let graphics = entities(d).flat_map(|e| match &e.kind {
|
||||||
|
EntityKind::Unknown(u) => u.graphics.iter().map(|g| g.common.linetype.clone()).collect(),
|
||||||
|
_ => Vec::new(),
|
||||||
|
});
|
||||||
let inside = entities(d).flat_map(|e| linetypes_inside(e));
|
let inside = entities(d).flat_map(|e| linetypes_inside(e));
|
||||||
let layers = d.layers.iter().map(|l| l.linetype.clone());
|
let layers = d.layers.iter().map(|l| l.linetype.clone());
|
||||||
let dims = d.dim_styles.iter().flat_map(|t| [t.dim_linetype.clone(), t.ext_linetype1.clone(), t.ext_linetype2.clone()]);
|
let dims = d.dim_styles.iter().flat_map(|t| [t.dim_linetype.clone(), t.ext_linetype1.clone(), t.ext_linetype2.clone()]);
|
||||||
let mlines = d.mline_styles.iter().flat_map(|t| t.elements.iter().map(|e| e.linetype.clone()));
|
let mlines = d.mline_styles.iter().flat_map(|t| t.elements.iter().map(|e| e.linetype.clone()));
|
||||||
objects.chain(inside).chain(layers).chain(dims).chain(mlines)
|
objects.chain(graphics).chain(inside).chain(layers).chain(dims).chain(mlines)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Names of the unused objects of a named kind, in table order. This is PURGE's scan; `USAGE`
|
/// Names of the unused objects of a named kind, in table order. This is PURGE's scan; `USAGE`
|
||||||
|
|||||||
@@ -836,6 +836,36 @@ mod tests {
|
|||||||
assert_eq!(graphics_layer(&s), "0");
|
assert_eq!(graphics_layer(&s), "0");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The same for linetypes: PURGE keeps one only proxy graphics draw with, and RENAME takes
|
||||||
|
/// the graphics and the file's LTYPE order with it.
|
||||||
|
#[test]
|
||||||
|
fn linetypes_proxy_graphics_draw_with_are_in_use_and_renamed() {
|
||||||
|
let mut s = proxy_on_b();
|
||||||
|
for name in ["DASHED", "HIDDEN"] {
|
||||||
|
s.execute("linetype", &json!({ "load": name })).unwrap();
|
||||||
|
}
|
||||||
|
let d = s.doc_mut().unwrap();
|
||||||
|
d.proxy_linetypes = vec!["Continuous".into(), "DASHED".into(), "HIDDEN".into()];
|
||||||
|
let h = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_))).unwrap().handle;
|
||||||
|
d.modify_entity(h, |e| {
|
||||||
|
if let cadcraft_doc::EntityKind::Unknown(u) = &mut e.kind {
|
||||||
|
u.graphics[0].common.linetype = "DASHED".into();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
s.execute("purge", &json!({})).unwrap();
|
||||||
|
let d = s.doc().unwrap();
|
||||||
|
assert!(d.linetype("DASHED").is_some() && d.linetype("HIDDEN").is_none());
|
||||||
|
s.execute("rename", &json!({ "table": "linetype", "from": "DASHED", "to": "DASH2" })).unwrap();
|
||||||
|
let d = s.doc().unwrap();
|
||||||
|
let linetype = d.model.iter().find_map(|e| match &e.kind {
|
||||||
|
cadcraft_doc::EntityKind::Unknown(u) => Some(u.graphics[0].common.linetype.clone()),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
assert_eq!(linetype.as_deref(), Some("DASH2"));
|
||||||
|
assert_eq!(d.proxy_linetypes, ["Continuous", "DASH2", "HIDDEN"]);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rename_repoints_paper_space_and_block_entities() {
|
fn rename_repoints_paper_space_and_block_entities() {
|
||||||
let mut s = Session::new();
|
let mut s = Session::new();
|
||||||
|
|||||||
@@ -466,6 +466,7 @@ fn run_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
|||||||
ucs: src.ucs,
|
ucs: src.ucs,
|
||||||
ucs_previous: Vec::new(),
|
ucs_previous: Vec::new(),
|
||||||
limits: src.limits,
|
limits: src.limits,
|
||||||
|
flags: src.flags,
|
||||||
});
|
});
|
||||||
Ok(json!({ "name": to }))
|
Ok(json!({ "name": to }))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1047,6 +1047,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
d.rename_proxy_linetype(&from, &to);
|
||||||
}
|
}
|
||||||
_ => return Err(bad("rename", "unsupported table")),
|
_ => return Err(bad("rename", "unsupported table")),
|
||||||
}
|
}
|
||||||
|
|||||||
+86
-20
@@ -582,7 +582,10 @@ fn gather_in(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut sink = Sink { osmode, aperture, probe, cands: &mut cands, near: &mut near_prims };
|
let mut sink = Sink { osmode, aperture, probe, cands: &mut cands, near: &mut near_prims };
|
||||||
sink.object(&e.kind, None);
|
// A record kept as read snaps to its graphics one by one, below.
|
||||||
|
if !matches!(e.kind, EntityKind::Unknown(_)) {
|
||||||
|
sink.object(&e.kind, None);
|
||||||
|
}
|
||||||
// A block reference snaps to the objects inside it, placed by its transform.
|
// A block reference snaps to the objects inside it, placed by its transform.
|
||||||
if let EntityKind::Insert(ins) = &e.kind {
|
if let EntityKind::Insert(ins) = &e.kind {
|
||||||
block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
|
block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
|
||||||
@@ -590,14 +593,10 @@ fn gather_in(
|
|||||||
if let EntityKind::Dimension(dm) = &e.kind {
|
if let EntityKind::Dimension(dm) = &e.kind {
|
||||||
sink.dimension(d, dm, &mut budget, frozen);
|
sink.dimension(d, dm, &mut budget, frozen);
|
||||||
}
|
}
|
||||||
// A dimension kept as read draws its block through a reference in its graphics (#3438),
|
// A proxy snaps to what its graphics draw, and a dimension kept as read to the objects of
|
||||||
// and snaps to the objects inside it the same way.
|
// the block it draws through a reference in them (#3438).
|
||||||
if let EntityKind::Unknown(u) = &e.kind {
|
if let EntityKind::Unknown(u) = &e.kind {
|
||||||
for g in &u.graphics {
|
graphics_leaves(d, u, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
|
||||||
if let EntityKind::Insert(ins) = &g.kind {
|
|
||||||
block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some((cands, near_prims))
|
Some((cands, near_prims))
|
||||||
@@ -908,10 +907,7 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
*budget -= 1;
|
*budget -= 1;
|
||||||
// Objects on layer 0 take the reference's layer, which is visible.
|
if !drawn_inside(d, be, frozen) {
|
||||||
if !be.common.visible
|
|
||||||
|| (be.common.layer != "0" && (!d.is_visible(be) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&be.common.layer))))
|
|
||||||
{
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
match &be.kind {
|
match &be.kind {
|
||||||
@@ -921,14 +917,7 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
|
|||||||
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
|
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
|
||||||
block_leaves(d, &dimension_reference(blk, dm), &mm, depth + 1, budget, frozen, f);
|
block_leaves(d, &dimension_reference(blk, dm), &mm, depth + 1, budget, frozen, f);
|
||||||
}
|
}
|
||||||
k @ EntityKind::Unknown(u) => {
|
EntityKind::Unknown(u) => graphics_leaves(d, u, &mm, depth + 1, budget, frozen, f),
|
||||||
f(k, &mm);
|
|
||||||
for g in &u.graphics {
|
|
||||||
if let EntityKind::Insert(inner) = &g.kind {
|
|
||||||
block_leaves(d, inner, &mm, depth + 1, budget, frozen, f);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
k => f(k, &mm),
|
k => f(k, &mm),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -936,6 +925,37 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether `e`, inside a block reference or a record's graphics, is drawn: not hidden, and on
|
||||||
|
/// layer 0 (which takes the visible layer of what holds it) or a layer that is on and not frozen.
|
||||||
|
fn drawn_inside(d: &Drawing, e: &cadcraft_doc::Entity, frozen: &[String]) -> bool {
|
||||||
|
e.common.visible && (e.common.layer == "0" || (d.is_visible(e) && !frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Calls `f` with each object the graphics of a record kept as read draw (a proxy's, #2697, or a
|
||||||
|
/// kept dimension's reference to its block, #3438) and the transform `m` placing it, as the
|
||||||
|
/// renderer draws them: like a block's contents, so graphics on a layer that is off or frozen
|
||||||
|
/// are left out. The fill hatches are too: each filled shape's outline is drawn as well, and the
|
||||||
|
/// hatch's sides would offer snaps inside it.
|
||||||
|
fn graphics_leaves(
|
||||||
|
d: &Drawing,
|
||||||
|
u: &cadcraft_doc::Unknown,
|
||||||
|
m: &Mat3,
|
||||||
|
depth: usize,
|
||||||
|
budget: &mut usize,
|
||||||
|
frozen: &[String],
|
||||||
|
f: &mut dyn FnMut(&EntityKind, &Mat3),
|
||||||
|
) {
|
||||||
|
for g in &u.graphics {
|
||||||
|
if matches!(g.kind, EntityKind::Hatch(_)) || !drawn_inside(d, g, frozen) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match &g.kind {
|
||||||
|
EntityKind::Insert(inner) => block_leaves(d, inner, m, depth, budget, frozen, f),
|
||||||
|
k => f(k, m),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The reference that places a dimension's block as the renderer draws it: the block holds world
|
/// The reference that places a dimension's block as the renderer draws it: the block holds world
|
||||||
/// geometry, moved by the insertion point (DXF group 12, which an older AutoCAD sets for a moved
|
/// geometry, moved by the insertion point (DXF group 12, which an older AutoCAD sets for a moved
|
||||||
/// dimension; #2634).
|
/// dimension; #2634).
|
||||||
@@ -1277,6 +1297,52 @@ mod tests {
|
|||||||
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &["HIDDEN".to_string()], Handle(0)), None);
|
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &["HIDDEN".to_string()], Handle(0)), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A proxy snaps to its graphics as the renderer draws them: not to those on a layer that is
|
||||||
|
/// off or frozen (in the drawing or the viewport), though the proxy's own layer is visible;
|
||||||
|
/// those on layer 0 take the proxy's. Inside a block the same, beside a visible line that keeps
|
||||||
|
/// the block in reach.
|
||||||
|
#[test]
|
||||||
|
fn proxy_graphics_on_hidden_layers_offer_no_snaps() {
|
||||||
|
let mut d = drawing();
|
||||||
|
for (name, on, frozen) in [("OFF", false, false), ("ICE", true, true), ("VP", true, false)] {
|
||||||
|
d.ensure_layer(name);
|
||||||
|
let l = d.layer_mut(name).unwrap();
|
||||||
|
(l.on, l.frozen) = (on, frozen);
|
||||||
|
}
|
||||||
|
let line = |layer: &str, y: f64| cadcraft_doc::Entity {
|
||||||
|
common: Common { layer: layer.into(), ..Common::default() },
|
||||||
|
..cadcraft_doc::Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }))
|
||||||
|
};
|
||||||
|
let graphics = vec![line("OFF", 20.0), line("0", 25.0), line("ICE", 30.0), line("VP", 35.0)];
|
||||||
|
let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
|
||||||
|
d.add(&Space::Model, Common::default(), proxy.clone()).unwrap();
|
||||||
|
let mut blk = cadcraft_doc::Block::new("PROXIES");
|
||||||
|
blk.entities.push(cadcraft_doc::Entity::new(Handle(1), proxy));
|
||||||
|
blk.entities.push(line("0", 21.0));
|
||||||
|
d.blocks.insert("PROXIES".into(), std::sync::Arc::new(blk));
|
||||||
|
let ins = cadcraft_doc::Insert {
|
||||||
|
block: "PROXIES".into(),
|
||||||
|
insert: Vec3::new(100.0, 0.0, 0.0),
|
||||||
|
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||||
|
let frozen = ["vp".to_string()];
|
||||||
|
let end = |x: f64, y: f64| {
|
||||||
|
let at = Vec2::new(x, y);
|
||||||
|
osnap_in(&d, &Space::Model, &None, at + Vec2::new(0.02, -0.01), 0.5, mode::END, None, false, &frozen, None)
|
||||||
|
.into_iter()
|
||||||
|
.any(|h| h.point.dist(at) < 1e-9)
|
||||||
|
};
|
||||||
|
for x in [10.0, 110.0] {
|
||||||
|
assert!(end(x, 25.0), "layer 0 at {x}");
|
||||||
|
for y in [20.0, 30.0, 35.0] {
|
||||||
|
assert!(!end(x, y), "hidden at ({x}, {y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(end(110.0, 21.0), "the block's own line");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn endpoint_and_mid() {
|
fn endpoint_and_mid() {
|
||||||
let d = drawing();
|
let d = drawing();
|
||||||
|
|||||||
@@ -38,6 +38,16 @@ pub(crate) const MLEADER_STYLE_KEY: &str = "CADCRAFT_MLEADERSTYLE";
|
|||||||
/// Named-object-dictionary key of the XRECORD holding model space's current UCS name ($UCSNAME,
|
/// Named-object-dictionary key of the XRECORD holding model space's current UCS name ($UCSNAME,
|
||||||
/// which the DWG bridge drops).
|
/// which the DWG bridge drops).
|
||||||
pub(crate) const UCS_NAME_KEY: &str = "CADCRAFT_UCSNAME";
|
pub(crate) const UCS_NAME_KEY: &str = "CADCRAFT_UCSNAME";
|
||||||
|
/// Header-value key of the `*Active` VPORT records' group 72 ("Circle sides" in the DXF
|
||||||
|
/// Reference, VPORT), kept as the file has it so that a save writes it back. CADCraft gives it no
|
||||||
|
/// meaning of its own, and a drawing that stores none is written without it.
|
||||||
|
pub(crate) const VPORT_CIRCLE_SIDES_KEY: &str = "CADCRAFT_VPORT_CIRCLE_SIDES";
|
||||||
|
|
||||||
|
/// `v` when a VPORT group 72 can hold it: a 16-bit integer, the type of groups 60-79 (DXF
|
||||||
|
/// Reference, Group Code Value Types).
|
||||||
|
pub(crate) fn circle_sides(v: i64) -> Option<i64> {
|
||||||
|
i16::try_from(v).ok().map(i64::from)
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether the UCS at `origin` with axes `x`, `y` is exactly the named UCS `u` (to rounding):
|
/// Whether the UCS at `origin` with axes `x`, `y` is exactly the named UCS `u` (to rounding):
|
||||||
/// only then is the current UCS still that named one, read or written. The origin may differ by
|
/// only then is the current UCS still that named one, read or written. The origin may differ by
|
||||||
|
|||||||
@@ -1529,8 +1529,14 @@ fn plan_unknown(
|
|||||||
};
|
};
|
||||||
let br = |name: &str| roles.get(&("BLOCK_RECORD".to_string(), up(name))).cloned();
|
let br = |name: &str| roles.get(&("BLOCK_RECORD".to_string(), up(name))).cloned();
|
||||||
let first_at = |s: &cadcraft_doc::EntityStore| s.iter().find_map(|e| at.get(&e.handle.hex()).copied());
|
let first_at = |s: &cadcraft_doc::EntityStore| s.iter().find_map(|e| at.get(&e.handle.hex()).copied());
|
||||||
// The LAYER table as written: proxy graphics name layers by their index in it (#3094).
|
// The LAYER and LTYPE tables as written: proxy graphics name layers and linetypes by their
|
||||||
let written_layers: Vec<String> = recs.iter().filter(|r| r.sec == "TABLES" && r.kind == "LAYER").filter_map(|r| val(body(r), 2)).collect();
|
// index in them (#3094), linetypes without ByBlock and ByLayer.
|
||||||
|
let table = |kind: &str| -> Vec<String> { recs.iter().filter(|r| r.sec == "TABLES" && r.kind == kind).filter_map(|r| val(body(r), 2)).collect() };
|
||||||
|
let written_layers = table("LAYER");
|
||||||
|
let mut written_linetypes = table("LTYPE");
|
||||||
|
written_linetypes.retain(|n| !n.eq_ignore_ascii_case("ByBlock") && !n.eq_ignore_ascii_case("ByLayer"));
|
||||||
|
let read_order = cadcraft_doc::TableOrder { layers: &d.proxy_layers, linetypes: &d.proxy_linetypes };
|
||||||
|
let written_order = cadcraft_doc::TableOrder { layers: &written_layers, linetypes: &written_linetypes };
|
||||||
let layouts = d.paper_space_layouts();
|
let layouts = d.paper_space_layouts();
|
||||||
// (entities, owner, paper space, end of the space, section)
|
// (entities, owner, paper space, end of the space, section)
|
||||||
let mut stores: Vec<(&cadcraft_doc::EntityStore, Option<String>, bool, Option<usize>, &str)> = Vec::new();
|
let mut stores: Vec<(&cadcraft_doc::EntityStore, Option<String>, bool, Option<usize>, &str)> = Vec::new();
|
||||||
@@ -1558,7 +1564,7 @@ fn plan_unknown(
|
|||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let remapped = u.with_proxy_layers(&d.proxy_layers, &written_layers).map(|tags| Unknown { tags, ..u.clone() });
|
let remapped = u.with_proxy_tables(read_order, written_order).map(|tags| Unknown { tags, ..u.clone() });
|
||||||
let t = unknown_entity(remapped.as_ref().unwrap_or(u), e, &owner, paper);
|
let t = unknown_entity(remapped.as_ref().unwrap_or(u), e, &owner, paper);
|
||||||
if !t.is_empty() {
|
if !t.is_empty() {
|
||||||
pending.push((sec.to_string(), t));
|
pending.push((sec.to_string(), t));
|
||||||
|
|||||||
+129
-24
@@ -24,8 +24,8 @@ mod tables;
|
|||||||
mod text;
|
mod text;
|
||||||
|
|
||||||
use document::{
|
use document::{
|
||||||
HandlePolicy, apply_sortents, count_skipped, dropped_paper_views, outside_sections, parse_entities, place_blocks, place_entities, read_blocks,
|
HandlePolicy, append, apply_sortents, count_skipped, dropped_paper_views, out_of_memory, outside_sections, parse_entities, place_blocks,
|
||||||
read_objects, setup_layouts,
|
place_entities, read_blocks, read_objects, setup_layouts,
|
||||||
};
|
};
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
use entities::acad_table;
|
use entities::acad_table;
|
||||||
@@ -78,6 +78,10 @@ struct Rx {
|
|||||||
linetypes_cut: usize,
|
linetypes_cut: usize,
|
||||||
/// IMAGE entity handle, as read (a repeated one reassigned) → its IMAGEDEF handle (upper case).
|
/// IMAGE entity handle, as read (a repeated one reassigned) → its IMAGEDEF handle (upper case).
|
||||||
image_defs: HashMap<Handle, String>,
|
image_defs: HashMap<Handle, String>,
|
||||||
|
/// Tests: refuse room for more than this many entities in one list, to grow it or to move it
|
||||||
|
/// into the drawing, as an allocator out of memory refuses, so the error paths run without
|
||||||
|
/// exhausting memory. `None` when reading.
|
||||||
|
entities_refused_past: Option<usize>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Order `items` as the file's table lists them (`order`, names in any case), after the `pinned`
|
/// Order `items` as the file's table lists them (`order`, names in any case), after the `pinned`
|
||||||
@@ -160,7 +164,7 @@ fn draw_kept_dimensions_from_their_blocks(d: &mut Drawing) {
|
|||||||
|
|
||||||
/// Read a DXF file into a drawing.
|
/// Read a DXF file into a drawing.
|
||||||
pub fn read(bytes: &[u8]) -> Result<Drawing> {
|
pub fn read(bytes: &[u8]) -> Result<Drawing> {
|
||||||
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS)
|
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS, None)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A block definition read from BLOCKS: name, base point, description, entities (owner, paper
|
/// A block definition read from BLOCKS: name, base point, description, entities (owner, paper
|
||||||
@@ -168,12 +172,13 @@ pub fn read(bytes: &[u8]) -> Result<Drawing> {
|
|||||||
type BlockDef = (String, Vec3, String, Vec<(Option<String>, bool, Entity)>, i64);
|
type BlockDef = (String, Vec3, String, Vec<(Option<String>, bool, Entity)>, i64);
|
||||||
|
|
||||||
/// A layout read from OBJECTS: name, tab order, paper block handle and page setup.
|
/// A layout read from OBJECTS: name, tab order, paper block handle and page setup.
|
||||||
/// A LAYOUT object: name, tab order, block record, page setup and its limits (groups 10/11).
|
/// A LAYOUT object: name, tab order, block record, page setup, its limits (groups 10/11) and
|
||||||
type LayoutDef = (String, u32, String, PageSetup, Option<(Vec2, Vec2)>);
|
/// its own flags (group 70 after the AcDbLayout marker).
|
||||||
|
type LayoutDef = (String, u32, String, PageSetup, Option<(Vec2, Vec2)>, Option<i64>);
|
||||||
|
|
||||||
/// Import DXF sections while sharing one materialized-table-cell budget and one hatch curve-point
|
/// Import DXF sections while sharing one materialized-table-cell budget and one hatch curve-point
|
||||||
/// budget across blocks and entity sections.
|
/// budget across blocks and entity sections. `entities_refused_past` is for tests (see `Rx`).
|
||||||
fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) -> Result<Drawing> {
|
fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize, entities_refused_past: Option<usize>) -> Result<Drawing> {
|
||||||
let tags = craft_dxf::parse(bytes).map_err(|e| IoError::Format(e.to_string()))?;
|
let tags = craft_dxf::parse(bytes).map_err(|e| IoError::Format(e.to_string()))?;
|
||||||
let secs = section_slices(&tags);
|
let secs = section_slices(&tags);
|
||||||
if secs.is_empty() {
|
if secs.is_empty() {
|
||||||
@@ -183,7 +188,8 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
|||||||
d.layouts.clear();
|
d.layouts.clear();
|
||||||
// A file without $INSUNITS declares no units (#1209); only new drawings take the template's.
|
// A file without $INSUNITS declares no units (#1209); only new drawings take the template's.
|
||||||
d.header.set_i64("INSUNITS", 0);
|
d.header.set_i64("INSUNITS", 0);
|
||||||
let mut rx = Rx { pstyles: plot_style_names(&secs), curves: hatch::CurvePoints { left: curve_points, cut: 0 }, ..Rx::default() };
|
let mut rx =
|
||||||
|
Rx { pstyles: plot_style_names(&secs), curves: hatch::CurvePoints { left: curve_points, cut: 0 }, entities_refused_past, ..Rx::default() };
|
||||||
let mut blocks: Vec<BlockDef> = Vec::new();
|
let mut blocks: Vec<BlockDef> = Vec::new();
|
||||||
let mut layout_objs: Vec<LayoutDef> = Vec::new();
|
let mut layout_objs: Vec<LayoutDef> = Vec::new();
|
||||||
let mut entities = Vec::new();
|
let mut entities = Vec::new();
|
||||||
@@ -193,12 +199,12 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
|||||||
// Model/paper-space handles retain priority if an in-memory drawing or damaged DXF also
|
// Model/paper-space handles retain priority if an in-memory drawing or damaged DXF also
|
||||||
// assigns one to a block entity. This preserves top-level references while letting block
|
// assigns one to a block entity. This preserves top-level references while letting block
|
||||||
// handles be repaired before their deferred fixups are recorded.
|
// handles be repaired before their deferred fixups are recorded.
|
||||||
let reserved_entity_handles: HashSet<Handle> = secs
|
let mut reserved_entity_handles: HashSet<Handle> = HashSet::new();
|
||||||
.iter()
|
let entity_records = secs.iter().filter(|s| s.name == "ENTITIES").flat_map(|s| record_slices(s.tags));
|
||||||
.filter(|s| s.name == "ENTITIES")
|
for h in entity_records.filter_map(|(_, tags)| tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex)) {
|
||||||
.flat_map(|s| record_slices(s.tags))
|
reserved_entity_handles.try_reserve(1).map_err(|_| out_of_memory(reserved_entity_handles.len().saturating_add(1), "entity handles"))?;
|
||||||
.filter_map(|(_, tags)| tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex))
|
reserved_entity_handles.insert(h);
|
||||||
.collect();
|
}
|
||||||
let mut objs = Objects::default();
|
let mut objs = Objects::default();
|
||||||
// Every handle another program's file already uses is taken before anything gets a new one:
|
// Every handle another program's file already uses is taken before anything gets a new one:
|
||||||
// its $HANDSEED can be lower than its handles, and entities made while reading (the faces of
|
// its $HANDSEED can be lower than its handles, and entities made while reading (the faces of
|
||||||
@@ -242,20 +248,23 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
|||||||
match s.name {
|
match s.name {
|
||||||
"HEADER" => header(s.tags, &mut d),
|
"HEADER" => header(s.tags, &mut d),
|
||||||
"TABLES" => tables(s.tags, &mut d, &mut rx),
|
"TABLES" => tables(s.tags, &mut d, &mut rx),
|
||||||
"BLOCKS" => {
|
"BLOCKS" => append(
|
||||||
blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles)?)
|
&mut blocks,
|
||||||
}
|
read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles)?,
|
||||||
|
"block definitions",
|
||||||
|
)?,
|
||||||
// A damaged file may split its entities over several ENTITIES sections (#865).
|
// A damaged file may split its entities over several ENTITIES sections (#865).
|
||||||
"ENTITIES" => {
|
"ENTITIES" => {
|
||||||
let mut n = 0;
|
let mut n = 0;
|
||||||
entities.extend(parse_entities(
|
let list = parse_entities(
|
||||||
&record_slices(s.tags),
|
&record_slices(s.tags),
|
||||||
&mut d,
|
&mut d,
|
||||||
&mut rx,
|
&mut rx,
|
||||||
&mut n,
|
&mut n,
|
||||||
&mut table_cells_left,
|
&mut table_cells_left,
|
||||||
&mut HandlePolicy { seen: &mut seen_handles, reserved: &reserved_entity_handles, source_wins: true },
|
&mut HandlePolicy { seen: &mut seen_handles, reserved: &reserved_entity_handles, source_wins: true },
|
||||||
)?);
|
)?;
|
||||||
|
append(&mut entities, list, "entities")?;
|
||||||
count_skipped(&mut skipped, "ENTITIES", n);
|
count_skipped(&mut skipped, "ENTITIES", n);
|
||||||
}
|
}
|
||||||
"OBJECTS" => read_objects(s.tags, &mut objs, &mut layout_objs),
|
"OBJECTS" => read_objects(s.tags, &mut objs, &mut layout_objs),
|
||||||
@@ -269,6 +278,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
|||||||
// removing or adding layers doesn't move them (#3094).
|
// removing or adding layers doesn't move them (#3094).
|
||||||
d.proxy_layers.clone_from(&rx.proxy_tables.layers);
|
d.proxy_layers.clone_from(&rx.proxy_tables.layers);
|
||||||
keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]);
|
keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]);
|
||||||
|
d.proxy_linetypes.clone_from(&rx.proxy_tables.linetypes);
|
||||||
// A proxy text takes the first style on its font, so the styles keep the file's order too.
|
// A proxy text takes the first style on its font, so the styles keep the file's order too.
|
||||||
let styles: Vec<String> = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect();
|
let styles: Vec<String> = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect();
|
||||||
keep_file_order(&mut d.text_styles, |s| &s.name, &styles, &[]);
|
keep_file_order(&mut d.text_styles, |s| &s.name, &styles, &[]);
|
||||||
@@ -276,8 +286,8 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
|||||||
// are numbered above it and rebuilt on save, so following $HANDSEED would drift every save.
|
// are numbered above it and rebuilt on save, so following $HANDSEED would drift every save.
|
||||||
let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim()));
|
let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim()));
|
||||||
let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx);
|
let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx);
|
||||||
place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout);
|
place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout)?;
|
||||||
place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout);
|
place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout)?;
|
||||||
draw_kept_dimensions_from_their_blocks(&mut d);
|
draw_kept_dimensions_from_their_blocks(&mut d);
|
||||||
number_unknown_viewport_ids(&mut d, &dropped_paper_views(&rx, &paper_block_for, &first_layout));
|
number_unknown_viewport_ids(&mut d, &dropped_paper_views(&rx, &paper_block_for, &first_layout));
|
||||||
apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout);
|
apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout);
|
||||||
@@ -399,7 +409,7 @@ mod table_budget_tests {
|
|||||||
let dxf = format!(
|
let dxf = format!(
|
||||||
"0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\nTEST\n10\n0\n20\n0\n{table}0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nEOF\n"
|
"0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\nTEST\n10\n0\n20\n0\n{table}0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nEOF\n"
|
||||||
);
|
);
|
||||||
let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS).unwrap();
|
let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS, None).unwrap();
|
||||||
let block = d.block("TEST").unwrap();
|
let block = d.block("TEST").unwrap();
|
||||||
let count = |e: &Entity| match &e.kind {
|
let count = |e: &Entity| match &e.kind {
|
||||||
EntityKind::Table(t) => t.cells.iter().map(Vec::len).sum::<usize>(),
|
EntityKind::Table(t) => t.cells.iter().map(Vec::len).sum::<usize>(),
|
||||||
@@ -443,10 +453,10 @@ mod hatch_budget_tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn hatch_curves_stop_at_the_read_budget_and_say_so() {
|
fn hatch_curves_stop_at_the_read_budget_and_say_so() {
|
||||||
let dxf = format!("0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n0\nEOF\n", spline_hatch(10), spline_hatch(10));
|
let dxf = format!("0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n0\nEOF\n", spline_hatch(10), spline_hatch(10));
|
||||||
let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS).unwrap();
|
let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, None).unwrap();
|
||||||
assert!(full.read_notes.is_empty(), "{:?}", full.read_notes);
|
assert!(full.read_notes.is_empty(), "{:?}", full.read_notes);
|
||||||
assert!(hatch_points(&full) > 20_000, "{}", hatch_points(&full));
|
assert!(hatch_points(&full) > 20_000, "{}", hatch_points(&full));
|
||||||
let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000).unwrap();
|
let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000, None).unwrap();
|
||||||
// The budget is checked before each edge: the last one sampled may pass it by its own
|
// The budget is checked before each edge: the last one sampled may pass it by its own
|
||||||
// points (at most about 4,000); every edge after it is its four control points.
|
// points (at most about 4,000); every edge after it is its four control points.
|
||||||
assert!(hatch_points(&d) <= 1000 + 4001 + 20 * 4, "{}", hatch_points(&d));
|
assert!(hatch_points(&d) <= 1000 + 4001 + 20 * 4, "{}", hatch_points(&d));
|
||||||
@@ -489,4 +499,99 @@ mod entity_list_tests {
|
|||||||
assert!(matches!(entity_list(usize::MAX / 2, usize::MAX), Err(IoError::Format(m)) if m.contains("out of memory")));
|
assert!(matches!(entity_list(usize::MAX / 2, usize::MAX), Err(IoError::Format(m)) if m.contains("out of memory")));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Past the reservation cap a list grows as entities come, but no further than its records
|
||||||
|
/// can fill: a last doubling would leave up to half of it spare, memory a drawing near the
|
||||||
|
/// limit doesn't have.
|
||||||
|
#[test]
|
||||||
|
fn a_long_entity_list_ends_within_its_record_count() -> Result<()> {
|
||||||
|
let n = document::MAX_RESERVED_ENTITIES + 100;
|
||||||
|
let line = vec![Tag::s(8, "0"), Tag::f(11, 1.0)];
|
||||||
|
let recs: Vec<(String, &[Tag])> = (0..n).map(|_| ("LINE".to_string(), line.as_slice())).collect();
|
||||||
|
let mut d = Drawing::new_imperial();
|
||||||
|
let (mut rx, mut skipped, mut cells) = (Rx::default(), 0, 100);
|
||||||
|
let (mut seen, reserved) = (HashSet::new(), HashSet::new());
|
||||||
|
let mut hp = HandlePolicy { seen: &mut seen, reserved: &reserved, source_wins: true };
|
||||||
|
let out = parse_entities(&recs, &mut d, &mut rx, &mut skipped, &mut cells, &mut hp)?;
|
||||||
|
assert_eq!(out.len(), n);
|
||||||
|
assert!(out.capacity() <= recs.len(), "room for {} entities from {} records", out.capacity(), recs.len());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A full list doubles below its record count, stops at the count, and doubles again past it
|
||||||
|
/// (a mesh's faces); room for many at once is room for all of them. A reservation that can't
|
||||||
|
/// be had, or one past the test ceiling, is an error rather than an abort.
|
||||||
|
#[test]
|
||||||
|
fn entity_room_doubles_up_to_the_record_count() -> Result<()> {
|
||||||
|
use document::{entity_list, entity_room};
|
||||||
|
let (common, kind) = entity("LINE", &[Tag::s(8, "0")]).expect("a line");
|
||||||
|
let full = |n: usize| -> Result<Vec<(Option<String>, bool, Entity)>> {
|
||||||
|
let mut v = entity_list(n, n)?;
|
||||||
|
v.extend((1..=n as u64).map(|h| (None, false, Entity { handle: Handle(h), common: common.clone(), kind: kind.clone() })));
|
||||||
|
Ok(v)
|
||||||
|
};
|
||||||
|
let room = |n: usize, records: usize, more: usize| -> Result<usize> {
|
||||||
|
let mut v = full(n)?;
|
||||||
|
entity_room(&mut v, records, more, None)?;
|
||||||
|
Ok(v.capacity())
|
||||||
|
};
|
||||||
|
assert!(room(4, 100, 1)? >= 8, "below the count a full list doubles");
|
||||||
|
assert_eq!(room(64, 100, 1)?, 100, "and stops at the count");
|
||||||
|
assert!(room(100, 100, 1)? >= 200, "past the count it doubles again");
|
||||||
|
assert!(room(4, 100, 300)? >= 304, "room for a mesh's faces comes at once");
|
||||||
|
let mut v = full(4)?;
|
||||||
|
entity_room(&mut v, 100, 4, None)?;
|
||||||
|
let (cap, free) = (v.capacity(), v.capacity() - v.len());
|
||||||
|
entity_room(&mut v, 100, free, None)?;
|
||||||
|
assert_eq!(v.capacity(), cap, "room already there asks for nothing more");
|
||||||
|
let mut v = full(1)?;
|
||||||
|
assert!(matches!(entity_room(&mut v, usize::MAX, usize::MAX / 2, None), Err(IoError::Format(m)) if m.contains("out of memory")));
|
||||||
|
let mut v = full(4)?;
|
||||||
|
assert!(matches!(entity_room(&mut v, 100, 1, Some(7)), Err(IoError::Format(m)) if m.contains("out of memory")));
|
||||||
|
entity_room(&mut v, 100, 1, Some(8))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A polygon mesh's faces join the list together, so room for all of them is asked for at
|
||||||
|
/// once: faces past a refused reservation are an error, not grown into by a push.
|
||||||
|
#[test]
|
||||||
|
fn a_mesh_asks_room_for_all_its_faces() -> Result<()> {
|
||||||
|
let rec = |kind: &str, tags: Vec<Tag>| (kind.to_string(), tags);
|
||||||
|
let mut recs = vec![rec("POLYLINE", vec![Tag::s(8, "0"), Tag::i(66, 1), Tag::i(70, 16), Tag::i(71, 3), Tag::i(72, 3)])];
|
||||||
|
for i in 0..9 {
|
||||||
|
recs.push(rec(
|
||||||
|
"VERTEX",
|
||||||
|
vec![Tag::s(8, "0"), Tag::i(70, 64), Tag::f(10, f64::from(i % 3)), Tag::f(20, f64::from(i / 3)), Tag::f(30, 0.0)],
|
||||||
|
));
|
||||||
|
}
|
||||||
|
recs.push(rec("SEQEND", vec![Tag::s(8, "0")]));
|
||||||
|
let recs: Vec<(String, &[Tag])> = recs.iter().map(|(kind, tags)| (kind.clone(), tags.as_slice())).collect();
|
||||||
|
let parse = |refused_past| {
|
||||||
|
let mut d = Drawing::new_imperial();
|
||||||
|
let (mut rx, mut skipped, mut cells) = (Rx { entities_refused_past: refused_past, ..Rx::default() }, 0, 100);
|
||||||
|
let (mut seen, reserved) = (HashSet::new(), HashSet::new());
|
||||||
|
let mut hp = HandlePolicy { seen: &mut seen, reserved: &reserved, source_wins: true };
|
||||||
|
parse_entities(&recs, &mut d, &mut rx, &mut skipped, &mut cells, &mut hp)
|
||||||
|
};
|
||||||
|
assert_eq!(parse(None)?.len(), 4, "a 3 by 3 mesh has 4 faces");
|
||||||
|
assert_eq!(parse(Some(4))?.len(), 4);
|
||||||
|
assert!(matches!(parse(Some(3)), Err(IoError::Format(m)) if m.contains("out of memory")));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each list checks the drawing has room for it before it moves in: ENTITIES, and model
|
||||||
|
/// space, paper space and other blocks alike. A refused check stops the read with an error.
|
||||||
|
#[test]
|
||||||
|
fn each_list_checks_its_room_before_it_moves_into_the_drawing() {
|
||||||
|
let lines = "0\nLINE\n8\n0\n11\n1\n".repeat(3);
|
||||||
|
let block = |name: &str| format!("0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\n{name}\n10\n0\n20\n0\n{lines}0\nENDBLK\n0\nENDSEC\n0\nEOF\n");
|
||||||
|
let files = [format!("0\nSECTION\n2\nENTITIES\n{lines}0\nENDSEC\n0\nEOF\n"), block("*Model_Space"), block("*Paper_Space"), block("B")];
|
||||||
|
for dxf in &files {
|
||||||
|
let open = |refused_past| read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, refused_past);
|
||||||
|
let d = open(Some(3)).unwrap();
|
||||||
|
let in_layouts: usize = d.layouts.iter().map(|l| l.entities.len()).sum();
|
||||||
|
assert_eq!(d.model.len() + in_layouts + d.block("B").map_or(0, |b| b.entities.len()), 3, "{dxf}");
|
||||||
|
assert!(matches!(open(Some(2)), Err(IoError::Format(m)) if m.contains("out of memory")), "{dxf}");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,19 +49,77 @@ pub(super) struct HandlePolicy<'a> {
|
|||||||
/// Most entities an entity list reserves room for before its records are read. The record count
|
/// Most entities an entity list reserves room for before its records are read. The record count
|
||||||
/// is bounded by the tag limit, but a file of tiny records could still ask for gigabytes (an
|
/// is bounded by the tag limit, but a file of tiny records could still ask for gigabytes (an
|
||||||
/// entry takes several hundred bytes) before any record is admitted. Drawings of up to this many
|
/// entry takes several hundred bytes) before any record is admitted. Drawings of up to this many
|
||||||
/// entities are sized in one step; larger ones grow as usual. At the cap the reservation is
|
/// entities are sized in one step; larger ones grow as entities are admitted ([`entity_room`]).
|
||||||
/// about 46 MiB (728 bytes an entry on 64-bit targets).
|
/// At the cap the reservation is about 46 MiB (728 bytes an entry on 64-bit targets).
|
||||||
pub(super) const MAX_RESERVED_ENTITIES: usize = 1 << 16;
|
pub(super) const MAX_RESERVED_ENTITIES: usize = 1 << 16;
|
||||||
|
|
||||||
|
/// The error for memory the allocator refused: the read stops with it, where an ordinary push
|
||||||
|
/// would abort the process.
|
||||||
|
pub(super) fn out_of_memory(n: usize, what: &str) -> IoError {
|
||||||
|
IoError::Format(format!("DXF: out of memory reserving {n} {what}"))
|
||||||
|
}
|
||||||
|
|
||||||
/// An empty entity list with room for `records` entities, or `cap` if that is fewer. A refused
|
/// An empty entity list with room for `records` entities, or `cap` if that is fewer. A refused
|
||||||
/// reservation is an error rather than an abort.
|
/// reservation is an error rather than an abort.
|
||||||
pub(super) fn entity_list(records: usize, cap: usize) -> Result<Vec<(Option<String>, bool, Entity)>> {
|
pub(super) fn entity_list(records: usize, cap: usize) -> Result<Vec<(Option<String>, bool, Entity)>> {
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
let n = records.min(cap);
|
let n = records.min(cap);
|
||||||
out.try_reserve_exact(n).map_err(|_| IoError::Format(format!("DXF: out of memory reserving {n} entities")))?;
|
out.try_reserve_exact(n).map_err(|_| out_of_memory(n, "entities"))?;
|
||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Make room for `n` more entities in `out`, a list read from `records` records (followers not
|
||||||
|
/// counted). A full list doubles, as a push would, but no further than its records can fill, so
|
||||||
|
/// it ends at about its final length rather than with a last doubling's spare half; only the
|
||||||
|
/// faces of a polygon mesh take it past that count, and from there it doubles as usual. A
|
||||||
|
/// reservation the allocator refuses, or one past `refused_past` (set only by tests), is an
|
||||||
|
/// error rather than an abort.
|
||||||
|
pub(super) fn entity_room(out: &mut Vec<(Option<String>, bool, Entity)>, records: usize, n: usize, refused_past: Option<usize>) -> Result<()> {
|
||||||
|
let needed = out.len().saturating_add(n);
|
||||||
|
if needed <= out.capacity() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let fill = if records > out.len() { records } else { usize::MAX };
|
||||||
|
let target = out.capacity().saturating_mul(2).min(fill).max(needed);
|
||||||
|
if refused_past.is_some_and(|most| target > most) {
|
||||||
|
return Err(out_of_memory(target, "entities"));
|
||||||
|
}
|
||||||
|
out.try_reserve_exact(target - out.len()).map_err(|_| out_of_memory(target, "entities"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add the list a section gives to those read before it (a damaged file may repeat a section,
|
||||||
|
/// #865). The first list is taken as it is, not copied; a later one is added in a fallible
|
||||||
|
/// reservation.
|
||||||
|
pub(super) fn append<T>(all: &mut Vec<T>, more: Vec<T>, what: &str) -> Result<()> {
|
||||||
|
if all.is_empty() {
|
||||||
|
*all = more;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
all.try_reserve(more.len()).map_err(|_| out_of_memory(all.len().saturating_add(more.len()), what))?;
|
||||||
|
all.extend(more);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check, before entities read into a list move into the drawing, that the drawing has room for
|
||||||
|
/// `n` of them as it keeps them: each in a shared allocation of its own, with a slot in its
|
||||||
|
/// space's draw order and an entry in that space's handle index. Those allocations are small and
|
||||||
|
/// can't report failure, and the list holds its copy until the last one is made, so their memory
|
||||||
|
/// is asked for here in one fallible reservation and given back at once for them to use. It is a
|
||||||
|
/// check, not a guarantee (the sizes below are estimates), but a drawing whose entities clearly
|
||||||
|
/// don't fit stops with an error rather than aborting part way through. Past `refused_past` (set
|
||||||
|
/// only by tests) the room is refused too.
|
||||||
|
fn room_to_place(n: usize, refused_past: Option<usize>) -> Result<()> {
|
||||||
|
if refused_past.is_some_and(|most| n > most) {
|
||||||
|
return Err(out_of_memory(n, "entities in the drawing"));
|
||||||
|
}
|
||||||
|
// The shared allocation (its two counts and the entity) and about what an allocator adds to
|
||||||
|
// each allocation, the draw-order slot, and an index entry with the spare room a hash table
|
||||||
|
// keeps.
|
||||||
|
const PER_ENTITY: usize = size_of::<Entity>() + 4 * size_of::<usize>() + size_of::<std::sync::Arc<Entity>>() + 2 * size_of::<(Handle, u32)>();
|
||||||
|
let mut probe: Vec<u8> = Vec::new();
|
||||||
|
probe.try_reserve_exact(n.saturating_mul(PER_ENTITY)).map_err(|_| out_of_memory(n, "entities in the drawing"))
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn parse_entities(
|
pub(super) fn parse_entities(
|
||||||
recs: &[(String, &[Tag])],
|
recs: &[(String, &[Tag])],
|
||||||
d: &mut Drawing,
|
d: &mut Drawing,
|
||||||
@@ -73,9 +131,9 @@ pub(super) fn parse_entities(
|
|||||||
// Every record but a polyline's vertices, a reference's attributes and their SEQEND becomes
|
// Every record but a polyline's vertices, a reference's attributes and their SEQEND becomes
|
||||||
// at most one entity (`recs` is already in memory, bounded by the tag limit), so the list is
|
// at most one entity (`recs` is already in memory, bounded by the tag limit), so the list is
|
||||||
// sized once rather than moved at every doubling, up to MAX_RESERVED_ENTITIES; past that, and
|
// sized once rather than moved at every doubling, up to MAX_RESERVED_ENTITIES; past that, and
|
||||||
// for mesh faces past the count, it grows as usual.
|
// for mesh faces past the count, it grows fallibly as entities are admitted (`entity_room`).
|
||||||
let mut out =
|
let records = recs.iter().filter(|(kind, _)| !matches!(kind.as_str(), "VERTEX" | "ATTRIB" | "SEQEND")).count();
|
||||||
entity_list(recs.iter().filter(|(kind, _)| !matches!(kind.as_str(), "VERTEX" | "ATTRIB" | "SEQEND")).count(), MAX_RESERVED_ENTITIES)?;
|
let mut out = entity_list(records, MAX_RESERVED_ENTITIES)?;
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
while let Some((kind, tags)) = recs.get(i) {
|
while let Some((kind, tags)) = recs.get(i) {
|
||||||
let t = T(tags);
|
let t = T(tags);
|
||||||
@@ -120,6 +178,11 @@ pub(super) fn parse_entities(
|
|||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
if let Some((c, mut k)) = kindent {
|
if let Some((c, mut k)) = kindent {
|
||||||
|
// Room for the entity and a mesh's faces, in the list and among the handles seen,
|
||||||
|
// before either grows: a drawing too large for memory is an error, not an abort.
|
||||||
|
let n = 1 + extra.len();
|
||||||
|
entity_room(&mut out, records, n, rx.entities_refused_past)?;
|
||||||
|
hp.seen.try_reserve(n).map_err(|_| out_of_memory(hp.seen.len().saturating_add(n), "entity handles"))?;
|
||||||
let h = match handle {
|
let h = match handle {
|
||||||
// A file's handles keep their identity, however high they are (#913, #939).
|
// A file's handles keep their identity, however high they are (#913, #939).
|
||||||
Some(h) => {
|
Some(h) => {
|
||||||
@@ -132,12 +195,16 @@ pub(super) fn parse_entities(
|
|||||||
None => fresh_entity_handle(d, hp.seen, hp.reserved),
|
None => fresh_entity_handle(d, hp.seen, hp.reserved),
|
||||||
};
|
};
|
||||||
entity_extras(kind, tags, h, &mut k, rx);
|
entity_extras(kind, tags, h, &mut k, rx);
|
||||||
let more: Vec<_> = extra
|
// The faces go straight into the room reserved for them, after the entity, with fresh
|
||||||
.into_iter()
|
// handles in face order.
|
||||||
.map(|f| (owner.clone(), paper, Entity { handle: fresh_entity_handle(d, hp.seen, hp.reserved), common: c.clone(), kind: f }))
|
let faces = (!extra.is_empty()).then(|| (owner.clone(), c.clone()));
|
||||||
.collect();
|
|
||||||
out.push((owner, paper, Entity { handle: h, common: c, kind: k }));
|
out.push((owner, paper, Entity { handle: h, common: c, kind: k }));
|
||||||
out.extend(more);
|
if let Some((owner, c)) = faces {
|
||||||
|
for f in extra {
|
||||||
|
let handle = fresh_entity_handle(d, hp.seen, hp.reserved);
|
||||||
|
out.push((owner.clone(), paper, Entity { handle, common: c.clone(), kind: f }));
|
||||||
|
}
|
||||||
|
}
|
||||||
} else if kind == "HATCH" {
|
} else if kind == "HATCH" {
|
||||||
// Without boundary data. The other records `entity` returns nothing for are read
|
// Without boundary data. The other records `entity` returns nothing for are read
|
||||||
// elsewhere (the writer's paper viewport, the loops of a region).
|
// elsewhere (the writer's paper viewport, the loops of a region).
|
||||||
@@ -190,6 +257,7 @@ pub(super) fn read_blocks(
|
|||||||
&mut HandlePolicy { seen: seen_handles, reserved: reserved_handles, source_wins: false },
|
&mut HandlePolicy { seen: seen_handles, reserved: reserved_handles, source_wins: false },
|
||||||
)?;
|
)?;
|
||||||
rx.block = None;
|
rx.block = None;
|
||||||
|
blocks.try_reserve(1).map_err(|_| out_of_memory(blocks.len().saturating_add(1), "block definitions"))?;
|
||||||
blocks.push((name, base, description, ents, xref));
|
blocks.push((name, base, description, ents, xref));
|
||||||
i = j + 1;
|
i = j + 1;
|
||||||
} else {
|
} else {
|
||||||
@@ -205,18 +273,27 @@ pub(super) fn read_blocks(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Read the OBJECTS section into `objs`, and each LAYOUT into `layout_objs`.
|
/// Read the OBJECTS section into `objs`, and each LAYOUT into `layout_objs`.
|
||||||
pub(super) fn read_objects(tags: &[Tag], objs: &mut Objects, layout_objs: &mut Vec<LayoutDef>) {
|
pub(super) fn read_objects<'a>(tags: &'a [Tag], objs: &mut Objects<'a>, layout_objs: &mut Vec<LayoutDef>) {
|
||||||
for (k, tg) in record_slices(tags) {
|
for (k, tg) in record_slices(tags) {
|
||||||
objs.add(&k, tg);
|
objs.add(&k, tg);
|
||||||
if k == "LAYOUT" {
|
if k == "LAYOUT" {
|
||||||
// Fields after the AcDbLayout marker (AcDbPlotSettings also has a code 1).
|
// Fields after the AcDbLayout marker (AcDbPlotSettings also has a code 1).
|
||||||
let start = tg.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout").unwrap_or(0);
|
let marker = tg.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout");
|
||||||
|
let start = marker.unwrap_or(0);
|
||||||
let tail = tg.get(start..).unwrap_or(&[]);
|
let tail = tg.get(start..).unwrap_or(&[]);
|
||||||
let t = T(tail);
|
let t = T(tail);
|
||||||
// LAYOUT has two 330s: owner dict and the block record; take the last.
|
// LAYOUT has two 330s: owner dict and the block record; take the last.
|
||||||
let br = tg.iter().rfind(|x| x.code == 330).map(Tag::str).unwrap_or_default();
|
let br = tg.iter().rfind(|x| x.code == 330).map(Tag::str).unwrap_or_default();
|
||||||
let plot = T(tg.get(..start).unwrap_or(&[]));
|
let plot = T(tg.get(..start).unwrap_or(&[]));
|
||||||
layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot, tg), limits(&t)));
|
layout_objs.push((
|
||||||
|
t.s(1).unwrap_or_default(),
|
||||||
|
t.i(71).unwrap_or(0) as u32,
|
||||||
|
br.to_ascii_uppercase(),
|
||||||
|
page_setup(&plot, tg),
|
||||||
|
limits(&t),
|
||||||
|
// Its own flags only after the marker: without it, the first 70 is the plot flags.
|
||||||
|
marker.and_then(|_| t.i(70)),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -234,12 +311,13 @@ fn limits(t: &T) -> Option<(Vec2, Vec2)> {
|
|||||||
pub(super) fn setup_layouts(d: &mut Drawing, layout_objs: &mut [LayoutDef], rx: &Rx) -> (HashMap<String, String>, String) {
|
pub(super) fn setup_layouts(d: &mut Drawing, layout_objs: &mut [LayoutDef], rx: &Rx) -> (HashMap<String, String>, String) {
|
||||||
let mut paper_block_for: HashMap<String, String> = HashMap::new();
|
let mut paper_block_for: HashMap<String, String> = HashMap::new();
|
||||||
layout_objs.sort_by_key(|l| l.1);
|
layout_objs.sort_by_key(|l| l.1);
|
||||||
for (name, order, br, page, limits) in layout_objs.iter() {
|
for (name, order, br, page, limits, flags) in layout_objs.iter() {
|
||||||
if name.eq_ignore_ascii_case("Model") {
|
if name.eq_ignore_ascii_case("Model") {
|
||||||
d.model_page = Some(page.clone());
|
d.model_page = Some(page.clone());
|
||||||
|
d.model_layout_flags = *flags;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
d.layouts.push(Layout { page: page.clone(), limits: *limits, ..Layout::new(name, *order) });
|
d.layouts.push(Layout { page: page.clone(), limits: *limits, flags: *flags, ..Layout::new(name, *order) });
|
||||||
if let Some(bname) = rx.brs.get(br) {
|
if let Some(bname) = rx.brs.get(br) {
|
||||||
paper_block_for.insert(bname.to_ascii_uppercase(), name.clone());
|
paper_block_for.insert(bname.to_ascii_uppercase(), name.clone());
|
||||||
}
|
}
|
||||||
@@ -288,12 +366,19 @@ pub(super) fn layout_positions(d: &Drawing) -> std::collections::BTreeMap<String
|
|||||||
|
|
||||||
/// Place the BLOCKS entities: model and paper space blocks go to their space, the rest become
|
/// Place the BLOCKS entities: model and paper space blocks go to their space, the rest become
|
||||||
/// block definitions.
|
/// block definitions.
|
||||||
pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx, paper_block_for: &HashMap<String, String>, first_layout: &str) {
|
pub(super) fn place_blocks(
|
||||||
|
d: &mut Drawing,
|
||||||
|
blocks: Vec<BlockDef>,
|
||||||
|
rx: &mut Rx,
|
||||||
|
paper_block_for: &HashMap<String, String>,
|
||||||
|
first_layout: &str,
|
||||||
|
) -> Result<()> {
|
||||||
let mut layers = LayerSet::new(d);
|
let mut layers = LayerSet::new(d);
|
||||||
let layout_at = layout_positions(d);
|
let layout_at = layout_positions(d);
|
||||||
for (name, base, description, ents, xref) in blocks {
|
for (name, base, description, ents, xref) in blocks {
|
||||||
let up = name.to_ascii_uppercase();
|
let up = name.to_ascii_uppercase();
|
||||||
if up == "*MODEL_SPACE" {
|
if up == "*MODEL_SPACE" {
|
||||||
|
room_to_place(ents.len(), rx.entities_refused_past)?;
|
||||||
for (_, _, e) in ents {
|
for (_, _, e) in ents {
|
||||||
layers.ensure(d, &e.common.layer);
|
layers.ensure(d, &e.common.layer);
|
||||||
d.model.push(e);
|
d.model.push(e);
|
||||||
@@ -303,6 +388,7 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx,
|
|||||||
if up.starts_with("*PAPER_SPACE") {
|
if up.starts_with("*PAPER_SPACE") {
|
||||||
let lname = paper_block_for.get(&up).map_or(first_layout, String::as_str);
|
let lname = paper_block_for.get(&up).map_or(first_layout, String::as_str);
|
||||||
if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
|
if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
|
||||||
|
room_to_place(ents.len(), rx.entities_refused_past)?;
|
||||||
for (_, _, e) in ents {
|
for (_, _, e) in ents {
|
||||||
l.entities.push(e);
|
l.entities.push(e);
|
||||||
}
|
}
|
||||||
@@ -329,6 +415,7 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx,
|
|||||||
b.xref_path = Some(String::new());
|
b.xref_path = Some(String::new());
|
||||||
b.xref_overlay = xref & 8 != 0;
|
b.xref_overlay = xref & 8 != 0;
|
||||||
} else {
|
} else {
|
||||||
|
room_to_place(ents.len(), rx.entities_refused_past)?;
|
||||||
for (_, _, e) in ents {
|
for (_, _, e) in ents {
|
||||||
b.entities.push(e);
|
b.entities.push(e);
|
||||||
}
|
}
|
||||||
@@ -341,6 +428,7 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx,
|
|||||||
}
|
}
|
||||||
d.blocks.insert(name, std::sync::Arc::new(b));
|
d.blocks.insert(name, std::sync::Arc::new(b));
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The layout an entity record belongs to: paper space when flagged (67=1) or owned by a
|
/// The layout an entity record belongs to: paper space when flagged (67=1) or owned by a
|
||||||
@@ -358,7 +446,8 @@ pub(super) fn place_entities(
|
|||||||
rx: &Rx,
|
rx: &Rx,
|
||||||
paper_block_for: &HashMap<String, String>,
|
paper_block_for: &HashMap<String, String>,
|
||||||
first_layout: &str,
|
first_layout: &str,
|
||||||
) {
|
) -> Result<()> {
|
||||||
|
room_to_place(entities.len(), rx.entities_refused_past)?;
|
||||||
let mut layers = LayerSet::new(d);
|
let mut layers = LayerSet::new(d);
|
||||||
let layout_at = layout_positions(d);
|
let layout_at = layout_positions(d);
|
||||||
for (owner, paper, e) in entities {
|
for (owner, paper, e) in entities {
|
||||||
@@ -372,6 +461,7 @@ pub(super) fn place_entities(
|
|||||||
None => d.model.push(e),
|
None => d.model.push(e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Layouts whose generated sheet viewport (PAPERVIEW) the reader dropped: their viewports keep
|
/// Layouts whose generated sheet viewport (PAPERVIEW) the reader dropped: their viewports keep
|
||||||
|
|||||||
@@ -5,8 +5,12 @@ use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup
|
|||||||
use crate::dxf_ext::ByName;
|
use crate::dxf_ext::ByName;
|
||||||
|
|
||||||
/// Non-graphical objects applied once every entity is placed.
|
/// Non-graphical objects applied once every entity is placed.
|
||||||
|
///
|
||||||
|
/// The records it keeps until then are slices of the file's tag list, which the reader holds
|
||||||
|
/// for as long as this lives, not copies of it: a file of large records would otherwise hold
|
||||||
|
/// their groups twice while it opens (#1922).
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub(super) struct Objects {
|
pub(super) struct Objects<'a> {
|
||||||
/// Dictionary entry handle (upper case) → entry name.
|
/// Dictionary entry handle (upper case) → entry name.
|
||||||
names: HashMap<String, String>,
|
names: HashMap<String, String>,
|
||||||
/// (dictionary handle, entry handle), both upper case, in the order the dictionaries list them.
|
/// (dictionary handle, entry handle), both upper case, in the order the dictionaries list them.
|
||||||
@@ -14,17 +18,17 @@ pub(super) struct Objects {
|
|||||||
/// SCALE objects (the annotation scale list), in file order.
|
/// SCALE objects (the annotation scale list), in file order.
|
||||||
scales: Vec<cadcraft_doc::AnnoScale>,
|
scales: Vec<cadcraft_doc::AnnoScale>,
|
||||||
/// XRECORD handle (upper case) → its groups.
|
/// XRECORD handle (upper case) → its groups.
|
||||||
xrecords: HashMap<String, Vec<Tag>>,
|
xrecords: HashMap<String, &'a [Tag]>,
|
||||||
/// XRECORD handles in file order.
|
/// XRECORD handles in file order.
|
||||||
xrecord_order: Vec<String>,
|
xrecord_order: Vec<String>,
|
||||||
/// TABLESTYLE objects: (handle, groups).
|
/// TABLESTYLE objects: (handle, groups).
|
||||||
table_styles: Vec<(String, Vec<Tag>)>,
|
table_styles: Vec<(String, &'a [Tag])>,
|
||||||
/// DIMASSOC objects.
|
/// DIMASSOC objects.
|
||||||
dimassocs: Vec<Vec<Tag>>,
|
dimassocs: Vec<&'a [Tag]>,
|
||||||
/// MLEADERSTYLE objects: (handle, groups).
|
/// MLEADERSTYLE objects: (handle, groups).
|
||||||
mleader_styles: Vec<(String, Vec<Tag>)>,
|
mleader_styles: Vec<(String, &'a [Tag])>,
|
||||||
/// GROUP objects: (handle, groups).
|
/// GROUP objects: (handle, groups).
|
||||||
groups: Vec<(String, Vec<Tag>)>,
|
groups: Vec<(String, &'a [Tag])>,
|
||||||
/// Saved paper-space views of layouts: (layout name, view).
|
/// Saved paper-space views of layouts: (layout name, view).
|
||||||
layout_views: Vec<(String, (Vec2, f64))>,
|
layout_views: Vec<(String, (Vec2, f64))>,
|
||||||
/// Layouts' current UCSs: (layout name, origin, X axis, Y axis, named UCS record handle).
|
/// Layouts' current UCSs: (layout name, origin, X axis, Y axis, named UCS record handle).
|
||||||
@@ -37,8 +41,8 @@ pub(super) struct Objects {
|
|||||||
|
|
||||||
pub(super) const MAX_OBJECTS: usize = 1_000_000;
|
pub(super) const MAX_OBJECTS: usize = 1_000_000;
|
||||||
|
|
||||||
impl Objects {
|
impl<'a> Objects<'a> {
|
||||||
pub(super) fn add(&mut self, kind: &str, tags: &[Tag]) {
|
pub(super) fn add(&mut self, kind: &str, tags: &'a [Tag]) {
|
||||||
let h = T(tags).s(5).map(|h| h.trim().to_ascii_uppercase()).unwrap_or_default();
|
let h = T(tags).s(5).map(|h| h.trim().to_ascii_uppercase()).unwrap_or_default();
|
||||||
match kind {
|
match kind {
|
||||||
"SCALE" if self.scales.len() < cadcraft_doc::MAX_SCALES => {
|
"SCALE" if self.scales.len() < cadcraft_doc::MAX_SCALES => {
|
||||||
@@ -69,14 +73,14 @@ impl Objects {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
"XRECORD" if self.xrecords.len() < MAX_OBJECTS => {
|
"XRECORD" if self.xrecords.len() < MAX_OBJECTS => {
|
||||||
if self.xrecords.insert(h.clone(), tags.to_vec()).is_none() {
|
if self.xrecords.insert(h.clone(), tags).is_none() {
|
||||||
self.xrecord_order.push(h);
|
self.xrecord_order.push(h);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"TABLESTYLE" if self.table_styles.len() < MAX_OBJECTS => self.table_styles.push((h, tags.to_vec())),
|
"TABLESTYLE" if self.table_styles.len() < MAX_OBJECTS => self.table_styles.push((h, tags)),
|
||||||
"DIMASSOC" if self.dimassocs.len() < MAX_OBJECTS => self.dimassocs.push(tags.to_vec()),
|
"DIMASSOC" if self.dimassocs.len() < MAX_OBJECTS => self.dimassocs.push(tags),
|
||||||
"MLEADERSTYLE" if self.mleader_styles.len() < MAX_OBJECTS => self.mleader_styles.push((h, tags.to_vec())),
|
"MLEADERSTYLE" if self.mleader_styles.len() < MAX_OBJECTS => self.mleader_styles.push((h, tags)),
|
||||||
"GROUP" if self.groups.len() < MAX_OBJECTS => self.groups.push((h, tags.to_vec())),
|
"GROUP" if self.groups.len() < MAX_OBJECTS => self.groups.push((h, tags)),
|
||||||
"WIPEOUTVARIABLES" => self.wipeout_frame = T(tags).i(70).filter(|v| (0..=2).contains(v)),
|
"WIPEOUTVARIABLES" => self.wipeout_frame = T(tags).i(70).filter(|v| (0..=2).contains(v)),
|
||||||
"SORTENTSTABLE" if self.sortents.len() < MAX_OBJECTS => {
|
"SORTENTSTABLE" if self.sortents.len() < MAX_OBJECTS => {
|
||||||
if let Some(t) = sortents_table(tags) {
|
if let Some(t) = sortents_table(tags) {
|
||||||
@@ -128,10 +132,10 @@ impl Objects {
|
|||||||
let ours = |tags: &[Tag]| owner(tags).is_some_and(|o| dicts.contains(o.as_str()));
|
let ours = |tags: &[Tag]| owner(tags).is_some_and(|o| dicts.contains(o.as_str()));
|
||||||
// By lower-case name: the first entry's name and the last entry's record, in dictionary order.
|
// By lower-case name: the first entry's name and the last entry's record, in dictionary order.
|
||||||
let mut first: HashMap<String, &String> = HashMap::new();
|
let mut first: HashMap<String, &String> = HashMap::new();
|
||||||
let mut last: HashMap<String, &Vec<Tag>> = HashMap::new();
|
let mut last: HashMap<String, &[Tag]> = HashMap::new();
|
||||||
for (dict, h) in &self.entry_order {
|
for (dict, h) in &self.entry_order {
|
||||||
if dicts.contains(dict.as_str())
|
if dicts.contains(dict.as_str())
|
||||||
&& let (Some(name), Some(tags)) = (self.names.get(h), self.xrecords.get(h))
|
&& let (Some(name), Some(tags)) = (self.names.get(h), self.xrecords.get(h).copied())
|
||||||
&& ours(tags)
|
&& ours(tags)
|
||||||
{
|
{
|
||||||
first.entry(name.to_ascii_lowercase()).or_insert(name);
|
first.entry(name.to_ascii_lowercase()).or_insert(name);
|
||||||
@@ -142,7 +146,7 @@ impl Objects {
|
|||||||
let mut taken = std::collections::HashSet::new();
|
let mut taken = std::collections::HashSet::new();
|
||||||
let mut budget = crate::dxf_layer_states::MAX_COPIED_BYTES;
|
let mut budget = crate::dxf_layer_states::MAX_COPIED_BYTES;
|
||||||
for h in &self.xrecord_order {
|
for h in &self.xrecord_order {
|
||||||
let (Some(tags), Some(name)) = (self.xrecords.get(h), self.names.get(h)) else { continue };
|
let (Some(tags), Some(name)) = (self.xrecords.get(h).copied(), self.names.get(h)) else { continue };
|
||||||
if out.len() >= crate::dxf_ext::MAX_LAYER_STATES {
|
if out.len() >= crate::dxf_ext::MAX_LAYER_STATES {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -467,3 +471,61 @@ fn layout_view(tags: &[Tag]) -> Option<(Vec2, f64)> {
|
|||||||
let g = |c: i32| list.iter().find(|t| t.code == c).map(Tag::f64).filter(|v| v.is_finite());
|
let g = |c: i32| list.iter().find(|t| t.code == c).map(Tag::f64).filter(|v| v.is_finite());
|
||||||
Some((Vec2::new(g(1010)?, g(1020)?), g(1040)?))
|
Some((Vec2::new(g(1010)?, g(1020)?), g(1040)?))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// A file from another writer with one record of each kind [`Objects`] keeps until the drawing
|
||||||
|
/// is built: a LINE, a linear DIMENSION whose DIMASSOC ties its first point to the line's
|
||||||
|
/// start, and, named in the root dictionary, CADCraft's current multileader style record (an
|
||||||
|
/// XRECORD), a table style, a multileader style and a group holding the line.
|
||||||
|
const DXF: &str = "0\nSECTION\n2\nENTITIES\n\
|
||||||
|
0\nLINE\n5\n1F\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\
|
||||||
|
0\nDIMENSION\n5\n2A\n8\n0\n100\nAcDbDimension\n10\n10\n20\n5\n30\n0\n70\n0\n\
|
||||||
|
100\nAcDbAlignedDimension\n13\n0\n23\n0\n33\n0\n14\n10\n24\n0\n34\n0\n100\nAcDbRotatedDimension\n\
|
||||||
|
0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n\
|
||||||
|
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n\
|
||||||
|
3\nCADCRAFT_MLEADERSTYLE\n350\nA1\n3\nMine\n350\nA2\n3\nArrows\n350\nA4\n3\nPair\n350\nA5\n\
|
||||||
|
0\nXRECORD\n5\nA1\n330\nC\n100\nAcDbXrecord\n280\n1\n1\nArrows\n\
|
||||||
|
0\nTABLESTYLE\n5\nA2\n330\nC\n100\nAcDbTableStyle\n3\nmine\n\
|
||||||
|
0\nDIMASSOC\n5\nA3\n330\n0\n100\nAcDbDimAssoc\n330\n2A\n90\n1\n1\nAcDbOsnapPointRef\n72\n13\n331\n1F\n\
|
||||||
|
0\nMLEADERSTYLE\n5\nA4\n330\nC\n100\nAcDbMLeaderStyle\n44\n2.5\n\
|
||||||
|
0\nGROUP\n5\nA5\n330\nC\n100\nAcDbGroup\n300\nnote\n70\n0\n71\n1\n340\n1F\n\
|
||||||
|
0\nENDSEC\n0\nEOF\n";
|
||||||
|
|
||||||
|
/// The kept records are slices of the file's tag list, not copies of it (#1922): a file of
|
||||||
|
/// large records would otherwise hold their groups twice while it opens.
|
||||||
|
#[test]
|
||||||
|
fn kept_records_are_slices_of_the_tag_list() {
|
||||||
|
let tags = craft_dxf::parse(DXF.as_bytes()).unwrap();
|
||||||
|
let section = craft_dxf::section_slices(&tags).into_iter().find(|s| s.name == "OBJECTS").unwrap();
|
||||||
|
let mut objs = Objects::default();
|
||||||
|
crate::dxf_read::document::read_objects(section.tags, &mut objs, &mut Vec::new());
|
||||||
|
let list = tags.as_ptr_range();
|
||||||
|
let kept: [(&str, &[Tag]); 5] = [
|
||||||
|
("XRECORD", objs.xrecords["A1"]),
|
||||||
|
("TABLESTYLE", objs.table_styles[0].1),
|
||||||
|
("DIMASSOC", objs.dimassocs[0]),
|
||||||
|
("MLEADERSTYLE", objs.mleader_styles[0].1),
|
||||||
|
("GROUP", objs.groups[0].1),
|
||||||
|
];
|
||||||
|
for (kind, record) in kept {
|
||||||
|
assert!(record.first().is_some_and(|t| t.code == 5), "{kind}: the whole record, from its handle");
|
||||||
|
assert!(list.contains(&record.as_ptr()), "{kind} is a copy of the tag list");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each kind of kept record still reaches the drawing.
|
||||||
|
#[test]
|
||||||
|
fn each_kept_record_kind_reaches_the_drawing() {
|
||||||
|
let d = crate::dxf_read::read(DXF.as_bytes()).unwrap();
|
||||||
|
let line = Handle::parse_hex("1F").unwrap();
|
||||||
|
assert_eq!(d.header.str("CMLEADERSTYLE", ""), "Arrows", "XRECORD");
|
||||||
|
assert!(d.table_styles.iter().any(|s| s.name == "Mine"), "TABLESTYLE");
|
||||||
|
let dim = d.entity(Handle::parse_hex("2A").unwrap()).map(|e| &e.kind);
|
||||||
|
assert!(matches!(dim, Some(EntityKind::Dimension(dm)) if dm.assoc.iter().any(|a| a.handle == line && a.point == "p13")), "DIMASSOC: {dim:?}");
|
||||||
|
assert!(d.mleader_styles.iter().any(|s| s.name == "Arrows" && (s.arrow_size - 2.5).abs() < 1e-9), "MLEADERSTYLE");
|
||||||
|
assert!(d.groups.iter().any(|g| g.name == "Pair" && g.description == "note" && g.members == [line]), "GROUP");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -224,6 +224,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
|||||||
d.header.set("SNAPBASE", HVal::Point(Vec3::new(x, y, 0.0)));
|
d.header.set("SNAPBASE", HVal::Point(Vec3::new(x, y, 0.0)));
|
||||||
}
|
}
|
||||||
ucsicon(d, &t);
|
ucsicon(d, &t);
|
||||||
|
circle_sides(d, &t);
|
||||||
if let Some(a) = t.f(50).filter(|a| a.is_finite()) {
|
if let Some(a) = t.f(50).filter(|a| a.is_finite()) {
|
||||||
d.header.set_f64("SNAPANG", a);
|
d.header.set_f64("SNAPANG", a);
|
||||||
}
|
}
|
||||||
@@ -347,6 +348,14 @@ fn ucsicon(d: &mut Drawing, t: &T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The `*ACTIVE` VPORT's group 72 ("Circle sides"), kept so that a save writes it back
|
||||||
|
/// ([`crate::dxf_ext::VPORT_CIRCLE_SIDES_KEY`]); one that is not a 16-bit integer is left out.
|
||||||
|
fn circle_sides(d: &mut Drawing, t: &T) {
|
||||||
|
if let Some(v) = t.i(72).and_then(crate::dxf_ext::circle_sides) {
|
||||||
|
d.header.set_i64(crate::dxf_ext::VPORT_CIRCLE_SIDES_KEY, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Most tiles a viewport configuration keeps.
|
/// Most tiles a viewport configuration keeps.
|
||||||
const MAX_VPORT_TILES: usize = 64;
|
const MAX_VPORT_TILES: usize = 64;
|
||||||
|
|
||||||
|
|||||||
@@ -146,13 +146,14 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The properties attribute `a` of block reference `e` is drawn with: its own, else its
|
/// The properties attribute `a` of block reference `e` is drawn with: its own, else its
|
||||||
/// definition's, from the block's definitions by tag `defs`; an attribute defined on layer 0 is on
|
/// definition's, from the block's definitions by tag `defs`; an attribute that takes layer 0 from
|
||||||
/// the reference's layer. Also the definition's properties.
|
/// its definition is on the reference's layer, one set on layer 0 itself stays there. Also the
|
||||||
|
/// definition's properties.
|
||||||
pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap<cadcraft_doc::TagKey<'_>, &Entity>, a: &Attrib) -> (Common, Common) {
|
pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap<cadcraft_doc::TagKey<'_>, &Entity>, a: &Attrib) -> (Common, Common) {
|
||||||
let def = defs.get(&cadcraft_doc::TagKey(&a.tag));
|
let def = defs.get(&cadcraft_doc::TagKey(&a.tag));
|
||||||
let base = def.map(|de| de.common.clone()).unwrap_or_default();
|
let base = def.map(|de| de.common.clone()).unwrap_or_default();
|
||||||
let mut c = a.props.over(&base);
|
let mut c = a.props.over(&base);
|
||||||
if c.layer == "0" {
|
if a.props.layer.is_none() && c.layer == "0" {
|
||||||
c.layer.clone_from(&e.common.layer);
|
c.layer.clone_from(&e.common.layer);
|
||||||
}
|
}
|
||||||
(c, base)
|
(c, base)
|
||||||
|
|||||||
@@ -557,7 +557,7 @@ fn write_table_entity(w: &mut W, _d: &Drawing, e: &Entity, owner: &str, paper: b
|
|||||||
w.i(93, 4);
|
w.i(93, 4);
|
||||||
w.i(90, 4);
|
w.i(90, 4);
|
||||||
}
|
}
|
||||||
let chars: Vec<char> = cell.filter(|_| !cx.modern_table_values || !covered).map(|x| x.text.chars().collect()).unwrap_or_default();
|
let chars: Vec<char> = cell.map(|x| x.text.chars().collect()).unwrap_or_default();
|
||||||
let chunks: Vec<String> = chars.chunks(250).map(|c| c.iter().collect()).collect();
|
let chunks: Vec<String> = chars.chunks(250).map(|c| c.iter().collect()).collect();
|
||||||
let n = chunks.len();
|
let n = chunks.len();
|
||||||
for (i, ch) in chunks.iter().enumerate() {
|
for (i, ch) in chunks.iter().enumerate() {
|
||||||
@@ -662,7 +662,11 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
|||||||
w.i(71, i64::from(h.associative));
|
w.i(71, i64::from(h.associative));
|
||||||
w.i(91, h.loops.len() as i64);
|
w.i(91, h.loops.len() as i64);
|
||||||
for l in &h.loops {
|
for l in &h.loops {
|
||||||
w.i(92, 2 | i64::from(l.outer) | (l.boundary_flags.unwrap_or(0) & (4 | 8 | 16)));
|
// Polyline (2), External (1) from `outer`, and Textbox (8) and Outermost (16) as read.
|
||||||
|
// Not Derived (4): a derived path needs the hatch's pixel size (group 47) before its
|
||||||
|
// seed points, and a hatch does not keep one. As reported in #3664, AutoCAD refuses a
|
||||||
|
// file with the bit and no size, and draws pattern fills solid with a stand-in size.
|
||||||
|
w.i(92, 2 | i64::from(l.outer) | (l.boundary_flags.unwrap_or(0) & (8 | 16)));
|
||||||
let has_bulge = l.vertices.iter().any(|v| v.bulge != 0.0);
|
let has_bulge = l.vertices.iter().any(|v| v.bulge != 0.0);
|
||||||
w.i(72, i64::from(has_bulge));
|
w.i(72, i64::from(has_bulge));
|
||||||
w.i(73, 1);
|
w.i(73, 1);
|
||||||
|
|||||||
@@ -120,6 +120,8 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) {
|
|||||||
records.extend(d.vports.iter().filter(|c| !c.is_active() && !c.name.is_empty()).flat_map(|c| c.tiles.iter().map(|t| (c.name.as_str(), t))));
|
records.extend(d.vports.iter().filter(|c| !c.is_active() && !c.name.is_empty()).flat_map(|c| c.tiles.iter().map(|t| (c.name.as_str(), t))));
|
||||||
let th = table_head(w, "VPORT", records.len());
|
let th = table_head(w, "VPORT", records.len());
|
||||||
let finite = |p: Vec2, or: Vec2| if p.is_finite() { p } else { or };
|
let finite = |p: Vec2, or: Vec2| if p.is_finite() { p } else { or };
|
||||||
|
// The `*Active` records' group 72 as the drawing was read with it, if it was.
|
||||||
|
let circle_sides = d.header.get(dxf_ext::VPORT_CIRCLE_SIDES_KEY).and_then(|v| v.as_i64()).and_then(dxf_ext::circle_sides);
|
||||||
for (name, t) in records {
|
for (name, t) in records {
|
||||||
record_head(w, "VPORT", &th, "AcDbViewportTableRecord");
|
record_head(w, "VPORT", &th, "AcDbViewportTableRecord");
|
||||||
w.s(2, name);
|
w.s(2, name);
|
||||||
@@ -139,6 +141,10 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) {
|
|||||||
w.f(42, 50.0);
|
w.f(42, 50.0);
|
||||||
w.f(50, d.header.f64("SNAPANG", 0.0));
|
w.f(50, d.header.f64("SNAPANG", 0.0));
|
||||||
w.f(51, twist.to_degrees());
|
w.f(51, twist.to_degrees());
|
||||||
|
// Circle sides ([`dxf_ext::VPORT_CIRCLE_SIDES_KEY`]), carried as read on the `*Active` records.
|
||||||
|
if let Some(v) = circle_sides.filter(|_| name == VportConfig::ACTIVE) {
|
||||||
|
w.i(72, v);
|
||||||
|
}
|
||||||
// UCSICON: bit 1 shows the icon, bit 2 puts it at the UCS origin. A setting of the shown
|
// UCSICON: bit 1 shows the icon, bit 2 puts it at the UCS origin. A setting of the shown
|
||||||
// configuration (there is no header variable for it).
|
// configuration (there is no header variable for it).
|
||||||
if name == VportConfig::ACTIVE {
|
if name == VportConfig::ACTIVE {
|
||||||
|
|||||||
@@ -347,7 +347,7 @@ fn write_header(w: &mut W, d: &Drawing, version: Version) -> usize {
|
|||||||
seed_pos
|
seed_pos
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity]) {
|
fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity], wipeout_vars: bool) {
|
||||||
w.s(0, "SECTION");
|
w.s(0, "SECTION");
|
||||||
w.s(2, "CLASSES");
|
w.s(2, "CLASSES");
|
||||||
let mut classes = vec![
|
let mut classes = vec![
|
||||||
@@ -371,6 +371,9 @@ fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity]) {
|
|||||||
if every.iter().any(|e| matches!(e.kind, EntityKind::Wipeout(_))) {
|
if every.iter().any(|e| matches!(e.kind, EntityKind::Wipeout(_))) {
|
||||||
classes.push(("WIPEOUT", "AcDbWipeout", 127, true));
|
classes.push(("WIPEOUT", "AcDbWipeout", 127, true));
|
||||||
}
|
}
|
||||||
|
if wipeout_vars {
|
||||||
|
classes.push(("WIPEOUTVARIABLES", "AcDbWipeoutVariables", 0, false));
|
||||||
|
}
|
||||||
if !cx.images.is_empty() {
|
if !cx.images.is_empty() {
|
||||||
classes.push(("IMAGE", "AcDbRasterImage", 127, true));
|
classes.push(("IMAGE", "AcDbRasterImage", 127, true));
|
||||||
classes.push(("IMAGEDEF", "AcDbRasterImageDef", 0, false));
|
classes.push(("IMAGEDEF", "AcDbRasterImageDef", 0, false));
|
||||||
@@ -448,6 +451,16 @@ fn plot_layout_flags(page: &PageSetup, standard: bool, model: bool) -> i64 {
|
|||||||
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
|
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A LAYOUT object's own flags (group 70 after AcDbLayout; DXF Reference, LAYOUT: 1 is the
|
||||||
|
/// layout's PSLTSCALE and 2 its LIMCHECK, each the value while it is current): the bits the file
|
||||||
|
/// had, else the drawing's PSLTSCALE, which CADCraft draws every layout with, and LIMCHECK off, as
|
||||||
|
/// CADCraft has no limits check. Other bits have no meaning in the Reference and are not written.
|
||||||
|
fn layout_flags(d: &Drawing, kept: Option<i64>) -> i64 {
|
||||||
|
const PSLTSCALE: i64 = 1;
|
||||||
|
const LIMCHECK: i64 = 2;
|
||||||
|
kept.unwrap_or_else(|| if d.header.i64("PSLTSCALE", 1) != 0 { PSLTSCALE } else { 0 }) & (PSLTSCALE | LIMCHECK)
|
||||||
|
}
|
||||||
|
|
||||||
fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<'_>) {
|
fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<'_>) {
|
||||||
let d = context.drawing;
|
let d = context.drawing;
|
||||||
let layout_dict = context.dictionary;
|
let layout_dict = context.dictionary;
|
||||||
@@ -625,6 +638,8 @@ struct ObjectWritePlan<'a> {
|
|||||||
table_style_dict: &'a String,
|
table_style_dict: &'a String,
|
||||||
pstyle_dict: &'a String,
|
pstyle_dict: &'a String,
|
||||||
scale_dict: &'a String,
|
scale_dict: &'a String,
|
||||||
|
/// The WIPEOUTVARIABLES object's handle and its frame flag (0 or 1), when the drawing sets WIPEOUTFRAME.
|
||||||
|
wipeout_vars: Option<(&'a String, i64)>,
|
||||||
model_layout: &'a String,
|
model_layout: &'a String,
|
||||||
ms_br: &'a String,
|
ms_br: &'a String,
|
||||||
ps_brs: &'a [(String, String, &'a Layout)],
|
ps_brs: &'a [(String, String, &'a Layout)],
|
||||||
@@ -670,7 +685,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
|||||||
name: "Model",
|
name: "Model",
|
||||||
tab: 0,
|
tab: 0,
|
||||||
block_record: ms_br,
|
block_record: ms_br,
|
||||||
flags: 1,
|
flags: layout_flags(d, d.model_layout_flags),
|
||||||
page: d.model_page.as_ref().unwrap_or(&model_page),
|
page: d.model_page.as_ref().unwrap_or(&model_page),
|
||||||
view: None,
|
view: None,
|
||||||
ucs: None,
|
ucs: None,
|
||||||
@@ -688,7 +703,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
|||||||
name: &l.name,
|
name: &l.name,
|
||||||
tab: i64::from(l.tab_order.max(1)),
|
tab: i64::from(l.tab_order.max(1)),
|
||||||
block_record: brh,
|
block_record: brh,
|
||||||
flags: 1,
|
flags: layout_flags(d, l.flags),
|
||||||
page: &l.page,
|
page: &l.page,
|
||||||
view: l.view,
|
view: l.view,
|
||||||
ucs: l.ucs.as_ref(),
|
ucs: l.ucs.as_ref(),
|
||||||
@@ -715,6 +730,7 @@ fn write_root_group_objects(
|
|||||||
let pstyle_dict = plan.pstyle_dict;
|
let pstyle_dict = plan.pstyle_dict;
|
||||||
let scale_dict = plan.scale_dict;
|
let scale_dict = plan.scale_dict;
|
||||||
let xrecords = plan.xrecords;
|
let xrecords = plan.xrecords;
|
||||||
|
let wipeout_vars = plan.wipeout_vars;
|
||||||
w.s(0, "SECTION");
|
w.s(0, "SECTION");
|
||||||
w.s(2, "OBJECTS");
|
w.s(2, "OBJECTS");
|
||||||
w.s(0, "DICTIONARY");
|
w.s(0, "DICTIONARY");
|
||||||
@@ -746,6 +762,10 @@ fn write_root_group_objects(
|
|||||||
}
|
}
|
||||||
w.s(3, "ACAD_SCALELIST");
|
w.s(3, "ACAD_SCALELIST");
|
||||||
w.s(350, scale_dict.clone());
|
w.s(350, scale_dict.clone());
|
||||||
|
if let Some((h, _)) = wipeout_vars {
|
||||||
|
w.s(3, "ACAD_WIPEOUT_VARS");
|
||||||
|
w.s(350, h.clone());
|
||||||
|
}
|
||||||
w.s(0, "DICTIONARY");
|
w.s(0, "DICTIONARY");
|
||||||
w.s(5, group_dict);
|
w.s(5, group_dict);
|
||||||
w.s(330, root_dict.clone());
|
w.s(330, root_dict.clone());
|
||||||
@@ -839,6 +859,15 @@ fn write_named_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
scale_list(w, scales, scale_dict, root_dict);
|
scale_list(w, scales, scale_dict, root_dict);
|
||||||
|
// The wipeout frame flag (#3440): 0 no frame, 1 display frame.
|
||||||
|
if let Some((h, frame)) = plan.wipeout_vars {
|
||||||
|
w.s(0, "WIPEOUTVARIABLES");
|
||||||
|
w.s(5, h.clone());
|
||||||
|
w.group("ACAD_REACTORS", 330, &[root_dict]);
|
||||||
|
w.s(330, root_dict.clone());
|
||||||
|
w.s(100, "AcDbWipeoutVariables");
|
||||||
|
w.i(70, frame);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_associative_objects(w: &mut W, cx: &Ctx) {
|
fn write_associative_objects(w: &mut W, cx: &Ctx) {
|
||||||
@@ -1172,6 +1201,28 @@ pub(super) fn tags_kept_for(
|
|||||||
}
|
}
|
||||||
// The annotation scale list: the ACAD_SCALELIST dictionary of SCALE objects.
|
// The annotation scale list: the ACAD_SCALELIST dictionary of SCALE objects.
|
||||||
let scale_dict = w.h();
|
let scale_dict = w.h();
|
||||||
|
// Only a drawing that holds WIPEOUTFRAME (set, or read from a file) gets the object. The DXF
|
||||||
|
// Reference gives its flag two values, 0 (no frame) and 1 (display frame). "Shown but not
|
||||||
|
// plotted" (2) displays the frames, so it is written as 1: where a file keeps the third state
|
||||||
|
// is not documented. A file whose own object already says what the drawing holds, or what
|
||||||
|
// would be written for it, keeps that object instead (the kept objects are written back as
|
||||||
|
// read, with what other applications hung on them), so opening and saving it changes nothing.
|
||||||
|
let file_flag = d
|
||||||
|
.foreign
|
||||||
|
.objects
|
||||||
|
.iter()
|
||||||
|
.find(|o| o.kind == "WIPEOUTVARIABLES")
|
||||||
|
.and_then(|o| o.tags.iter().find(|t| t.code == 70))
|
||||||
|
.and_then(|t| t.value.trim().parse::<i64>().ok());
|
||||||
|
let wipeout_frame = d
|
||||||
|
.header
|
||||||
|
.get("WIPEOUTFRAME")
|
||||||
|
.and_then(HVal::as_i64)
|
||||||
|
.filter(|v| (0..=2).contains(v))
|
||||||
|
.filter(|v| file_flag != Some(*v))
|
||||||
|
.map(|v| v.min(1))
|
||||||
|
.filter(|flag| file_flag != Some(*flag));
|
||||||
|
let wipeout_handle = wipeout_frame.map(|_| w.h());
|
||||||
let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = d.scales.iter().filter(|s| s.is_valid()).map(|s| (s, w.h())).collect();
|
let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = d.scales.iter().filter(|s| s.is_valid()).map(|s| (s, w.h())).collect();
|
||||||
// Plot style names used by layers and objects (Normal always), each a placeholder object; in
|
// Plot style names used by layers and objects (Normal always), each a placeholder object; in
|
||||||
// a drawing of named plot styles also those of the layers of saved layer states, which name
|
// a drawing of named plot styles also those of the layers of saved layer states, which name
|
||||||
@@ -1196,7 +1247,7 @@ pub(super) fn tags_kept_for(
|
|||||||
|
|
||||||
let seed_pos = write_header(&mut w, d, version);
|
let seed_pos = write_header(&mut w, d, version);
|
||||||
|
|
||||||
write_classes(&mut w, &cx, &every);
|
write_classes(&mut w, &cx, &every, wipeout_frame.is_some());
|
||||||
|
|
||||||
let max_dashes = bridge.then_some(super::DWG_MAX_LINETYPE_ELEMENTS);
|
let max_dashes = bridge.then_some(super::DWG_MAX_LINETYPE_ELEMENTS);
|
||||||
let (ltype_handles, linetypes_cut) = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model), max_dashes });
|
let (ltype_handles, linetypes_cut) = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model), max_dashes });
|
||||||
@@ -1325,6 +1376,7 @@ pub(super) fn tags_kept_for(
|
|||||||
table_style_dict: &table_style_dict,
|
table_style_dict: &table_style_dict,
|
||||||
pstyle_dict: &pstyle_dict,
|
pstyle_dict: &pstyle_dict,
|
||||||
scale_dict: &scale_dict,
|
scale_dict: &scale_dict,
|
||||||
|
wipeout_vars: wipeout_handle.as_ref().zip(wipeout_frame),
|
||||||
model_layout: &model_layout,
|
model_layout: &model_layout,
|
||||||
ms_br: &ms_br,
|
ms_br: &ms_br,
|
||||||
ps_brs: &ps_brs,
|
ps_brs: &ps_brs,
|
||||||
|
|||||||
@@ -167,3 +167,40 @@ fn hostile_attrib_groups_do_not_panic() {
|
|||||||
assert_eq!((p.layer.as_deref(), p.linetype.as_deref()), (None, None), "empty names are not properties");
|
assert_eq!((p.layer.as_deref(), p.linetype.as_deref()), (None, None), "empty names are not properties");
|
||||||
let _ = write_dxf(&d);
|
let _ = write_dxf(&d);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The layer and colour of each attribute of each block reference in `d`, in file order.
|
||||||
|
fn layers_and_colors(d: &Drawing) -> Vec<(Option<String>, Option<Color>)> {
|
||||||
|
let attribs = d.model.iter().filter_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.attribs.clone()) } else { None });
|
||||||
|
attribs.flatten().map(|a| (a.props.layer, a.props.color)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #3492: an ATTRIB on layer 0 of a reference on layer A stays on layer 0 when the drawing is read
|
||||||
|
/// and saved again, as DXF and as DWG; layer 0 means the reference's layer only for a definition.
|
||||||
|
#[test]
|
||||||
|
fn attribute_on_layer_zero_stays_on_layer_zero() {
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let attrib = |layer: &str, color: &str| format!("0\nATTRIB\n8\n{layer}\n{color}10\n0\n20\n1\n30\n0\n40\n1\n1\nv\n2\nT1\n70\n0\n");
|
||||||
|
let insert = |x: u32, attrib: String| format!("0\nINSERT\n8\nA\n66\n1\n2\nBLK\n10\n{x}\n20\n0\n30\n0\n{attrib}0\nSEQEND\n8\nA\n");
|
||||||
|
let dxf = format!(
|
||||||
|
"0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n70\n2\n0\nLAYER\n2\nA\n70\n0\n62\n3\n6\nCONTINUOUS\n\
|
||||||
|
0\nLAYER\n2\nB\n70\n0\n62\n5\n6\nCONTINUOUS\n0\nENDTAB\n0\nENDSEC\n\
|
||||||
|
0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n8\n0\n2\nBLK\n70\n2\n10\n0\n20\n0\n30\n0\n3\nBLK\n\
|
||||||
|
0\nLINE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n0\n31\n0\n\
|
||||||
|
0\nATTDEF\n8\n0\n10\n0\n20\n1\n30\n0\n40\n1\n1\nx\n3\n\n2\nT1\n70\n0\n0\nENDBLK\n8\n0\n0\nENDSEC\n\
|
||||||
|
0\nSECTION\n2\nENTITIES\n{}{}{}0\nENDSEC\n0\nEOF\n",
|
||||||
|
insert(0, attrib("0", "")),
|
||||||
|
insert(10, attrib("B", "")),
|
||||||
|
insert(20, attrib("0", "62\n1\n")),
|
||||||
|
);
|
||||||
|
let d = cadcraft_io::read(dxf.as_bytes(), "t.dxf").expect("read");
|
||||||
|
let read = layers_and_colors(&d);
|
||||||
|
assert_eq!(read.len(), 3);
|
||||||
|
let layers: Vec<Option<&str>> = read.iter().map(|(l, _)| l.as_deref()).collect();
|
||||||
|
assert_eq!(layers, [Some("0"), Some("B"), Some("0")], "as the file says");
|
||||||
|
assert_eq!(read[2].1, Some(Color::Index(1)));
|
||||||
|
for name in ["t.dxf", "t.dwg"] {
|
||||||
|
let saved = cadcraft_io::write(&d, name).expect("write");
|
||||||
|
let back = cadcraft_io::read(&saved, name).expect("reopen");
|
||||||
|
assert_eq!(layers_and_colors(&back), read, "{name}: attribute layers or colours changed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -58,11 +58,17 @@ fn flags_written(drawing: &Drawing) -> Vec<i64> {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The group 92 of a path read with `flags`, as saved: Polyline set, and Derived cleared because
|
||||||
|
/// the pixel size it needs is not kept (#3664).
|
||||||
|
fn saved(flags: i64) -> i64 {
|
||||||
|
(flags | 2) & !4
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn boundary_flags_survive_dxf_open_and_save() {
|
fn boundary_flags_survive_dxf_open_and_save() {
|
||||||
for flags in [[7, 22, 7, 6], [7, 22, 6, 20], [0, 9, 16, 31]] {
|
for flags in [[7, 22, 7, 6], [7, 22, 6, 20], [0, 9, 16, 31]] {
|
||||||
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
|
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
|
||||||
let expected = flags.map(|flag| flag | 2);
|
let expected = flags.map(saved);
|
||||||
assert_eq!(flags_written(&drawing), expected);
|
assert_eq!(flags_written(&drawing), expected);
|
||||||
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
|
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
|
||||||
assert_eq!(flags_written(&back), expected);
|
assert_eq!(flags_written(&back), expected);
|
||||||
@@ -92,7 +98,7 @@ fn reclassified_loops_write_current_external_bit() {
|
|||||||
});
|
});
|
||||||
let written = flags_written(&drawing)[1];
|
let written = flags_written(&drawing)[1];
|
||||||
assert_eq!(written & 1, 0);
|
assert_eq!(written & 1, 0);
|
||||||
assert_eq!(written & (4 | 16), imported & (4 | 16));
|
assert_eq!(written & (4 | 16), imported & 16);
|
||||||
assert_ne!(written & 2, 0);
|
assert_ne!(written & 2, 0);
|
||||||
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
|
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
|
||||||
assert_eq!(flags_written(&back), flags_written(&drawing));
|
assert_eq!(flags_written(&back), flags_written(&drawing));
|
||||||
@@ -103,7 +109,7 @@ fn reclassified_loops_write_current_external_bit() {
|
|||||||
fn undocumented_boundary_bits_are_not_written_back() {
|
fn undocumented_boundary_bits_are_not_written_back() {
|
||||||
let flags = [i64::MAX, -1, 32 | 7, i64::MIN | 22];
|
let flags = [i64::MAX, -1, 32 | 7, i64::MIN | 22];
|
||||||
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
|
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
|
||||||
let expected = flags.map(|flag| (flag & 31) | 2);
|
let expected = flags.map(|flag| saved(flag & 31));
|
||||||
assert_eq!(flags_written(&drawing), expected);
|
assert_eq!(flags_written(&drawing), expected);
|
||||||
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
|
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
|
||||||
assert_eq!(flags_written(&back), expected);
|
assert_eq!(flags_written(&back), expected);
|
||||||
@@ -117,7 +123,7 @@ fn boundary_flags_survive_dwg_open_and_both_save_formats() {
|
|||||||
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
|
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
|
||||||
let bytes = cadcraft_io::write(&drawing, "logo.dwg").unwrap();
|
let bytes = cadcraft_io::write(&drawing, "logo.dwg").unwrap();
|
||||||
let back = cadcraft_io::read(&bytes, "logo.dwg").unwrap();
|
let back = cadcraft_io::read(&bytes, "logo.dwg").unwrap();
|
||||||
let expected = flags.map(|flag| flag | 2);
|
let expected = flags.map(saved);
|
||||||
assert_eq!(flags_written(&back), expected);
|
assert_eq!(flags_written(&back), expected);
|
||||||
let again = cadcraft_io::write(&back, "logo.dwg").unwrap();
|
let again = cadcraft_io::write(&back, "logo.dwg").unwrap();
|
||||||
assert_eq!(flags_written(&cadcraft_io::read(&again, "logo.dwg").unwrap()), expected);
|
assert_eq!(flags_written(&cadcraft_io::read(&again, "logo.dwg").unwrap()), expected);
|
||||||
@@ -143,3 +149,97 @@ fn old_serialized_loops_keep_locally_created_flags() {
|
|||||||
}
|
}
|
||||||
assert_eq!(flags_written(&drawing), expected);
|
assert_eq!(flags_written(&drawing), expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The first of the four LINEs in [`derived_hatches`].
|
||||||
|
const LINES: u64 = 0x1A0;
|
||||||
|
|
||||||
|
/// Invented geometry: a 30 by 20 rectangle drawn as four LINEs and two hatches on it. The first
|
||||||
|
/// is a NET pattern linked to the lines (71 = 1, 97 = 4), with a derived outer path (92 = 7), a
|
||||||
|
/// derived edge-path island (92 = 20) and its pixel size (47) after the pattern lines. The second
|
||||||
|
/// is solid and not linked, with one derived edge path (92 = 5) and a pixel size.
|
||||||
|
fn derived_hatches() -> String {
|
||||||
|
let corners = [(0.0, 0.0), (30.0, 0.0), (30.0, 20.0), (0.0, 20.0)];
|
||||||
|
let island = [(10.0, 5.0), (20.0, 5.0), (20.0, 15.0), (10.0, 15.0)];
|
||||||
|
let mut text = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n");
|
||||||
|
for (index, (start, end)) in (0..).zip(corners.iter().zip(corners.iter().cycle().skip(1))) {
|
||||||
|
text.push_str(&format!(
|
||||||
|
"0\nLINE\n5\n{:X}\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n{}\n20\n{}\n30\n0\n11\n{}\n21\n{}\n31\n0\n",
|
||||||
|
LINES + index,
|
||||||
|
start.0,
|
||||||
|
start.1,
|
||||||
|
end.0,
|
||||||
|
end.1
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let head = |handle: &str, pattern: &str, solid: i64, linked: i64, paths: usize| {
|
||||||
|
format!(
|
||||||
|
"0\nHATCH\n5\n{handle}\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\n{pattern}\n70\n{solid}\n71\n{linked}\n91\n{paths}\n"
|
||||||
|
)
|
||||||
|
};
|
||||||
|
text.push_str(&head("1A4", "NET", 0, 1, 2));
|
||||||
|
text.push_str(boundary(&corners, 7).strip_suffix("97\n0\n").unwrap());
|
||||||
|
text.push_str("97\n4\n");
|
||||||
|
for index in 0..4 {
|
||||||
|
text.push_str(&format!("330\n{:X}\n", LINES + index));
|
||||||
|
}
|
||||||
|
text.push_str(&boundary(&island, 20));
|
||||||
|
text.push_str("75\n0\n76\n1\n52\n0\n41\n2\n77\n0\n78\n2\n");
|
||||||
|
text.push_str("53\n0\n43\n0\n44\n0\n45\n0\n46\n2.5\n79\n0\n53\n90\n43\n0\n44\n0\n45\n-2.5\n46\n0\n79\n0\n47\n1.5\n98\n0\n");
|
||||||
|
text.push_str(&head("1A5", "SOLID", 1, 0, 1));
|
||||||
|
text.push_str(&boundary(&corners, 5));
|
||||||
|
text.push_str("75\n0\n76\n1\n47\n1.5\n98\n0\n0\nENDSEC\n0\nEOF\n");
|
||||||
|
text
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The (code, value) pairs of each HATCH record in a DXF text.
|
||||||
|
fn hatch_records(text: &str) -> Vec<Vec<(i32, String)>> {
|
||||||
|
let lines: Vec<_> = text.lines().collect();
|
||||||
|
let mut records: Vec<Vec<(i32, String)>> = Vec::new();
|
||||||
|
let mut hatch = false;
|
||||||
|
for pair in lines.as_chunks::<2>().0 {
|
||||||
|
let code: i32 = pair[0].trim().parse().unwrap();
|
||||||
|
let value = pair[1].trim().to_string();
|
||||||
|
if code == 0 {
|
||||||
|
hatch = value == "HATCH";
|
||||||
|
if hatch {
|
||||||
|
records.push(Vec::new());
|
||||||
|
}
|
||||||
|
} else if hatch && let Some(record) = records.last_mut() {
|
||||||
|
record.push((code, value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
records
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The values of `code` in a HATCH record, from its boundary paths (group 91) on.
|
||||||
|
fn path_values(record: &[(i32, String)], code: i32) -> Vec<String> {
|
||||||
|
record.iter().skip_while(|(group, _)| *group != 91).filter(|(group, _)| *group == code).map(|(_, value)| value.clone()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A derived path (92 bit 4) needs the hatch's pixel size (47), which is not kept (#3664). The
|
||||||
|
/// path is saved without the bit and no stand-in size is written; the hatch keeps its other path
|
||||||
|
/// bits, its pattern and its link to the lines, through a second save too.
|
||||||
|
#[test]
|
||||||
|
fn derived_paths_are_saved_without_the_bit_or_a_stand_in_pixel_size() {
|
||||||
|
let drawing = read_dxf(derived_hatches().as_bytes()).unwrap();
|
||||||
|
let first = write_dxf(&drawing);
|
||||||
|
let again = write_dxf(&read_dxf(first.as_bytes()).unwrap());
|
||||||
|
for text in [first, again] {
|
||||||
|
let hatches = hatch_records(&text);
|
||||||
|
assert_eq!(hatches.len(), 2);
|
||||||
|
for hatch in &hatches {
|
||||||
|
let derived = path_values(hatch, 92).iter().any(|flags| flags.parse::<i64>().unwrap() & 4 != 0);
|
||||||
|
assert!(!derived, "{hatch:?}");
|
||||||
|
assert!(!hatch.iter().any(|(code, _)| *code == 47), "{hatch:?}");
|
||||||
|
}
|
||||||
|
assert_eq!(path_values(&hatches[0], 92), [saved(7), saved(20)].map(|flags| flags.to_string()));
|
||||||
|
assert_eq!(path_values(&hatches[1], 92), [saved(5).to_string()]);
|
||||||
|
// Still a NET pattern fill with its two lines, and still linked to the lines it was made from.
|
||||||
|
assert!(hatches[0].contains(&(2, "NET".to_string())) && hatches[0].contains(&(70, "0".to_string())), "{:?}", hatches[0]);
|
||||||
|
assert_eq!(path_values(&hatches[0], 78), ["2"]);
|
||||||
|
assert!(hatches[0].contains(&(71, "1".to_string())), "{:?}", hatches[0]);
|
||||||
|
assert_eq!(path_values(&hatches[0], 97), ["4", "0"]);
|
||||||
|
let lines: Vec<String> = (0..4).map(|index| format!("{:X}", LINES + index)).collect();
|
||||||
|
assert_eq!(path_values(&hatches[0], 330), lines);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
//! Each LAYOUT object's own flags (group 70 after the AcDbLayout marker; DXF Reference, LAYOUT:
|
||||||
|
//! 1 is the layout's PSLTSCALE and 2 its LIMCHECK, each the value in effect while that layout is
|
||||||
|
//! current) are saved as the file had them. Saving wrote 1 for every layout, which turned
|
||||||
|
//! PSLTSCALE on in each paper-space layout whatever the source said.
|
||||||
|
|
||||||
|
use cadcraft_doc::Drawing;
|
||||||
|
use cadcraft_io::{read, read_dxf, write, write_dxf};
|
||||||
|
|
||||||
|
/// Each LAYOUT object's name and its own flags (the AcDbLayout groups 1 and 70) in DXF text.
|
||||||
|
fn layout_flags(text: &str) -> Vec<(String, i64)> {
|
||||||
|
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let (mut inside, mut subclass, mut name, mut flags) = (false, "", None, None);
|
||||||
|
for pair in lines.chunks(2) {
|
||||||
|
let [code, value] = pair else { break };
|
||||||
|
match *code {
|
||||||
|
"0" => {
|
||||||
|
if let (true, Some(n), Some(f)) = (inside, name.take(), flags.take()) {
|
||||||
|
out.push((n, f));
|
||||||
|
}
|
||||||
|
(inside, subclass, name, flags) = (*value == "LAYOUT", "", None, None);
|
||||||
|
}
|
||||||
|
"100" if inside => subclass = value,
|
||||||
|
"1" if inside && subclass == "AcDbLayout" => name = Some(value.to_string()),
|
||||||
|
"70" if inside && subclass == "AcDbLayout" => flags = value.parse().ok(),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `text` with the AcDbLayout group 70 of each layout named in `set` replaced by its value.
|
||||||
|
fn with_layout_flags(text: &str, set: &[(&str, i64)]) -> String {
|
||||||
|
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
|
||||||
|
let mut i = 0;
|
||||||
|
while i + 5 < lines.len() {
|
||||||
|
let at = |k: usize| lines[i + k].trim();
|
||||||
|
if at(0) == "100"
|
||||||
|
&& at(1) == "AcDbLayout"
|
||||||
|
&& at(2) == "1"
|
||||||
|
&& at(4) == "70"
|
||||||
|
&& let Some((_, f)) = set.iter().find(|(n, _)| *n == at(3))
|
||||||
|
{
|
||||||
|
lines[i + 5] = f.to_string();
|
||||||
|
}
|
||||||
|
i += 2;
|
||||||
|
}
|
||||||
|
lines.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The flags each layout of `text` has, sorted by name.
|
||||||
|
fn sorted(text: &str) -> Vec<(String, i64)> {
|
||||||
|
let mut v = layout_flags(text);
|
||||||
|
v.sort();
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A DXF whose layouts have their own flags: PSLTSCALE off (0), off with LIMCHECK on (2), both on
|
||||||
|
/// (3), and the Model layout with LIMCHECK on.
|
||||||
|
fn source() -> String {
|
||||||
|
let mut d = Drawing::new_imperial();
|
||||||
|
d.layouts = vec![cadcraft_doc::Layout::new("A", 1), cadcraft_doc::Layout::new("B", 2), cadcraft_doc::Layout::new("C", 3)].into();
|
||||||
|
let text = with_layout_flags(&write_dxf(&d), &[("Model", 2), ("A", 0), ("B", 2), ("C", 3)]);
|
||||||
|
assert_eq!(sorted(&text), [("A", 0), ("B", 2), ("C", 3), ("Model", 2)].map(|(n, f)| (n.to_string(), f)), "the source as made");
|
||||||
|
text
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The flags each layout of [`source`] has after it is read, saved as `name` and read back, and
|
||||||
|
/// the flags it was made with.
|
||||||
|
fn after_save(name: &str) -> (Vec<(String, i64)>, Vec<(String, i64)>) {
|
||||||
|
let text = source();
|
||||||
|
let d = read_dxf(text.as_bytes()).expect("read");
|
||||||
|
let back = read(&write(&d, name).expect("save"), name).expect("reopen");
|
||||||
|
(sorted(&write_dxf(&back)), sorted(&text))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn layout_flags_are_saved_as_read() {
|
||||||
|
let (saved, made) = after_save("sheet.dxf");
|
||||||
|
assert_eq!(saved, made);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DWG saving fails there.
|
||||||
|
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||||
|
#[test]
|
||||||
|
fn layout_flags_survive_a_dwg_save() {
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let (saved, made) = after_save("sheet.dwg");
|
||||||
|
assert_eq!(saved, made);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_bits_the_reference_defines_are_written() {
|
||||||
|
// 4 and above have no meaning in the DXF Reference: a damaged file's other bits are dropped,
|
||||||
|
// the two defined ones kept.
|
||||||
|
let text = with_layout_flags(&source(), &[("A", 4 | 2), ("B", -1)]);
|
||||||
|
let back = sorted(&write_dxf(&read_dxf(text.as_bytes()).expect("read")));
|
||||||
|
let flags = |name: &str| back.iter().find(|(n, _)| n == name).map(|&(_, f)| f);
|
||||||
|
assert_eq!((flags("A"), flags("B")), (Some(2), Some(3)), "{back:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_layout_record_without_its_marker_takes_no_plot_flags_as_its_own() {
|
||||||
|
// Before the AcDbLayout marker group 70 is the plot layout flags: a LAYOUT record without the
|
||||||
|
// marker is read with no flags of its own, not with those.
|
||||||
|
let text = source();
|
||||||
|
let lines: Vec<&str> = text.lines().collect();
|
||||||
|
let marker = lines.windows(4).position(|w| w[0].trim() == "100" && w[1].trim() == "AcDbLayout" && w[3].trim() == "A").expect("A's marker");
|
||||||
|
let cut = [&lines[..marker], &lines[marker + 2..]].concat().join("\n");
|
||||||
|
let d = read_dxf(cut.as_bytes()).expect("read");
|
||||||
|
let flags: Vec<(&str, Option<i64>)> = d.layouts.iter().map(|l| (l.name.as_str(), l.flags)).collect();
|
||||||
|
assert_eq!(flags.len(), 3, "{flags:?}");
|
||||||
|
for (name, f) in &flags {
|
||||||
|
let want = match *name {
|
||||||
|
"B" => Some(2),
|
||||||
|
"C" => Some(3),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
assert_eq!(*f, want, "{flags:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The DWG bridge carries a DWG's layout flags into the DXF CADCraft reads: a DWG another program
|
||||||
|
/// wrote with PSLTSCALE off and LIMCHECK on in its layout converts to a DXF that says so.
|
||||||
|
// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526).
|
||||||
|
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||||
|
#[test]
|
||||||
|
fn a_dwg_layouts_flags_reach_the_converted_dxf() {
|
||||||
|
let mut doc = acadrust::CadDocument::new();
|
||||||
|
let mut set = 0;
|
||||||
|
for o in doc.objects.values_mut() {
|
||||||
|
if let acadrust::objects::ObjectType::Layout(l) = o
|
||||||
|
&& l.name == "Layout1"
|
||||||
|
{
|
||||||
|
l.flags = 2;
|
||||||
|
set += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(set, 1, "the DWG has a paper-space layout");
|
||||||
|
let dwg = acadrust::DwgWriter::write_to_vec(&doc).expect("DWG");
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let d = read(&dwg, "sheet.dwg").expect("read the DWG");
|
||||||
|
let flags = layout_flags(&write_dxf(&d));
|
||||||
|
assert!(flags.contains(&("Layout1".to_string(), 2)), "{flags:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_layout_without_its_own_flags_takes_psltscale() {
|
||||||
|
// A layout made in CADCraft has no flags of its own: it gets the drawing's PSLTSCALE, the
|
||||||
|
// value CADCraft draws every layout with, and LIMCHECK off, as CADCraft has no limits check.
|
||||||
|
for psltscale in [0, 1] {
|
||||||
|
let mut d = Drawing::new_imperial();
|
||||||
|
d.header.set_i64("PSLTSCALE", psltscale);
|
||||||
|
let flags = layout_flags(&write_dxf(&d));
|
||||||
|
assert!(flags.len() > 1, "Model and the paper-space layouts: {flags:?}");
|
||||||
|
assert!(flags.iter().all(|(_, f)| *f == psltscale), "PSLTSCALE {psltscale}: {flags:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -45,6 +45,7 @@ mod hatch_pattern_def;
|
|||||||
mod helix_roundtrip;
|
mod helix_roundtrip;
|
||||||
mod large_radial_dimension;
|
mod large_radial_dimension;
|
||||||
mod layer_states_acad;
|
mod layer_states_acad;
|
||||||
|
mod layout_flags;
|
||||||
mod layout_limits_roundtrip;
|
mod layout_limits_roundtrip;
|
||||||
mod layout_paper_units;
|
mod layout_paper_units;
|
||||||
mod layout_plot_flags;
|
mod layout_plot_flags;
|
||||||
@@ -111,5 +112,6 @@ mod view_target;
|
|||||||
mod viewport_clip_roundtrip;
|
mod viewport_clip_roundtrip;
|
||||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||||
mod visualstyle_dwg;
|
mod visualstyle_dwg;
|
||||||
|
mod vport_circle_sides;
|
||||||
mod xclip_roundtrip;
|
mod xclip_roundtrip;
|
||||||
mod xref_roundtrip;
|
mod xref_roundtrip;
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
//! Proxy graphics name layers by their index in the file's LAYER table (#3094). AutoCAD keeps
|
//! Proxy graphics name layers by their index in the file's LAYER table (#3094). AutoCAD keeps
|
||||||
//! layers that only proxy graphics use, but saves the graphics with their old indices after
|
//! layers that only proxy graphics use, but saves the graphics with their old indices after
|
||||||
//! PURGE removed a layer before them, which moves the graphics to other layers; CADCraft turns the
|
//! PURGE removed a layer before them, which moves the graphics to other layers; CADCraft turns the
|
||||||
//! indices into the written table's on save.
|
//! indices into the written table's on save. Linetype indices (the LTYPE table without ByBlock
|
||||||
|
//! and ByLayer) follow it the same way.
|
||||||
|
|
||||||
use cadcraft_doc::{EntityKind, Unknown};
|
use cadcraft_doc::{EntityKind, Unknown};
|
||||||
use cadcraft_io::{read_dxf, write_dxf};
|
use cadcraft_io::{read_dxf, write_dxf};
|
||||||
@@ -148,3 +149,53 @@ fn a_proxy_copied_from_another_drawing_keeps_its_layers() {
|
|||||||
let again = read_dxf(write_dxf(&target).as_bytes()).expect("reopen");
|
let again = read_dxf(write_dxf(&target).as_bytes()).expect("reopen");
|
||||||
assert_eq!(circle_layers(&again), ["0", "B_NOTIZ", "C_EXTRA", "C_EXTRA"]);
|
assert_eq!(circle_layers(&again), ["0", "B_NOTIZ", "C_EXTRA", "C_EXTRA"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Linetype indices count the LTYPE records other than ByBlock and ByLayer, and follow the
|
||||||
|
/// written table the same way: removing an unused linetype before the one the graphics draw
|
||||||
|
/// with keeps them on it after a save. So does a record without a name there, which counts on
|
||||||
|
/// reading but isn't written.
|
||||||
|
#[test]
|
||||||
|
fn removing_a_linetype_before_the_one_the_graphics_use_keeps_it_on_save() {
|
||||||
|
let mut circle: Vec<u8> = [25.0f64, 70.0, 0.0, 15.0, 0.0, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||||
|
circle.truncate(56);
|
||||||
|
let chunks = [chunk(18, &2u32.to_le_bytes()), chunk(2, &circle)];
|
||||||
|
let body = chunks.concat();
|
||||||
|
let mut g = ((8 + body.len()) as u32).to_le_bytes().to_vec();
|
||||||
|
g.extend((chunks.len() as u32).to_le_bytes());
|
||||||
|
g.extend(body);
|
||||||
|
// The table ByBlock, ByLayer, Continuous, `unused` (no name for `None`), HIDDEN.
|
||||||
|
let file = |unused: Option<&str>| -> String {
|
||||||
|
let mut tags: Vec<(i32, String)> = Vec::new();
|
||||||
|
let mut push = |list: &[(i32, &str)]| tags.extend(list.iter().map(|(c, v)| (*c, v.to_string())));
|
||||||
|
push(&[(0, "SECTION"), (2, "CLASSES"), (0, "CLASS"), (1, "SYNLAYERTEST"), (2, "SynLayerTest"), (3, "SyntheticProxyApp")]);
|
||||||
|
push(&[(90, "0"), (280, "0"), (281, "1"), (0, "ENDSEC"), (0, "SECTION"), (2, "TABLES"), (0, "TABLE"), (2, "LTYPE")]);
|
||||||
|
for (handle, name) in [("14", Some("ByBlock")), ("15", Some("ByLayer")), ("16", Some("Continuous")), ("17", unused), ("18", Some("HIDDEN"))] {
|
||||||
|
let dashed = handle == "17" || handle == "18";
|
||||||
|
push(&[(0, "LTYPE"), (5, handle)]);
|
||||||
|
if let Some(name) = name {
|
||||||
|
push(&[(2, name)]);
|
||||||
|
}
|
||||||
|
push(&[(70, "0"), (3, "")]);
|
||||||
|
push(if dashed {
|
||||||
|
&[(72, "65"), (73, "2"), (40, "0.375"), (49, "0.25"), (74, "0"), (49, "-0.125"), (74, "0")]
|
||||||
|
} else {
|
||||||
|
&[(72, "65"), (73, "0"), (40, "0")]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
push(&[(0, "ENDTAB"), (0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES"), (0, "ACAD_PROXY_ENTITY"), (5, "21"), (100, "AcDbEntity"), (8, "0")]);
|
||||||
|
push(&[(100, "AcDbProxyEntity"), (90, "498"), (91, "500"), (95, "0"), (70, "0")]);
|
||||||
|
tags.push((92, g.len().to_string()));
|
||||||
|
tags.extend(g.chunks(127).map(|c| (310, c.iter().map(|b| format!("{b:02X}")).collect())));
|
||||||
|
tags.extend([(93, "0".to_string()), (94, "0".to_string()), (0, "ENDSEC".to_string()), (0, "EOF".to_string())]);
|
||||||
|
tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
|
||||||
|
};
|
||||||
|
let linetype = |d: &cadcraft_doc::Drawing| proxy(d).graphics[0].common.linetype.clone();
|
||||||
|
for unused in [Some("UNUSED"), None] {
|
||||||
|
let mut d = read_dxf(file(unused).as_bytes()).expect("read");
|
||||||
|
assert_eq!(linetype(&d), "HIDDEN", "{unused:?}");
|
||||||
|
d.linetypes.retain(|t| t.name != "UNUSED");
|
||||||
|
let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen");
|
||||||
|
assert!(again.linetype("UNUSED").is_none());
|
||||||
|
assert_eq!(linetype(&again), "HIDDEN", "{unused:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ fn modern_table_cell_values_have_reference_groups() {
|
|||||||
cells[0][0].text = "Title".into();
|
cells[0][0].text = "Title".into();
|
||||||
cells[0][0].merged = Some((1, cols as u32));
|
cells[0][0].merged = Some((1, cols as u32));
|
||||||
cells[0][1].text = "CoveredText".repeat(30);
|
cells[0][1].text = "CoveredText".repeat(30);
|
||||||
|
cells[0][2].text.clear();
|
||||||
}
|
}
|
||||||
let table = Table { col_widths: vec![2.0; cols], row_heights: vec![0.5; rows], cells, title: merged, ..Table::default() };
|
let table = Table { col_widths: vec![2.0; cols], row_heights: vec![0.5; rows], cells, title: merged, ..Table::default() };
|
||||||
d.add(&Space::Model, Common::default(), EntityKind::Table(table.clone())).unwrap();
|
d.add(&Space::Model, Common::default(), EntityKind::Table(table.clone())).unwrap();
|
||||||
@@ -32,16 +33,12 @@ fn modern_table_cell_values_have_reference_groups() {
|
|||||||
let pairs: Vec<_> = lines.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
|
let pairs: Vec<_> = lines.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
|
||||||
let start = pairs.iter().position(|p| *p == ("0", "ACAD_TABLE")).unwrap();
|
let start = pairs.iter().position(|p| *p == ("0", "ACAD_TABLE")).unwrap();
|
||||||
let end = start + 1 + pairs[start + 1..].iter().position(|p| p.0 == "0").unwrap();
|
let end = start + 1 + pairs[start + 1..].iter().position(|p| p.0 == "0").unwrap();
|
||||||
let values: Vec<_> = pairs[start..end].iter().filter(|p| p.0 == "302").map(|p| p.1).collect();
|
let values: Vec<String> = pairs[start..end]
|
||||||
let expected: Vec<_> = table
|
.split_inclusive(|p| *p == ("304", "ACVALUE_END"))
|
||||||
.cells
|
.filter(|block| block.contains(&("301", "CELL_VALUE")))
|
||||||
.iter()
|
.map(|block| block.iter().filter(|p| p.0 == "302" || p.0 == "303").map(|p| p.1).collect())
|
||||||
.enumerate()
|
|
||||||
.flat_map(|(row, cells)| {
|
|
||||||
cells.iter().enumerate().map(move |(col, cell)| if merged && row == 0 && col > 0 { "" } else { cell.text.as_str() })
|
|
||||||
})
|
|
||||||
.collect();
|
.collect();
|
||||||
assert_eq!(values, expected);
|
assert_eq!(values, table.cells.iter().flatten().map(|cell| cell.text.clone()).collect::<Vec<_>>());
|
||||||
assert_eq!(pairs[start..end].iter().filter(|p| **p == ("301", "CELL_VALUE")).count(), rows * cols);
|
assert_eq!(pairs[start..end].iter().filter(|p| **p == ("301", "CELL_VALUE")).count(), rows * cols);
|
||||||
assert_eq!(pairs[start..end].iter().filter(|p| **p == ("304", "ACVALUE_END")).count(), rows * cols);
|
assert_eq!(pairs[start..end].iter().filter(|p| **p == ("304", "ACVALUE_END")).count(), rows * cols);
|
||||||
let value_start = start + pairs[start..end].iter().position(|p| *p == ("301", "CELL_VALUE")).unwrap();
|
let value_start = start + pairs[start..end].iter().position(|p| *p == ("301", "CELL_VALUE")).unwrap();
|
||||||
@@ -88,37 +85,19 @@ fn modern_table_cell_values_have_reference_groups() {
|
|||||||
);
|
);
|
||||||
let covered_start = cell_start + 1 + pairs[cell_start + 1..end].iter().position(|pair| *pair == ("171", "1")).unwrap();
|
let covered_start = cell_start + 1 + pairs[cell_start + 1..end].iter().position(|pair| *pair == ("171", "1")).unwrap();
|
||||||
let covered_end = covered_start + pairs[covered_start..end].iter().position(|pair| *pair == ("304", "ACVALUE_END")).unwrap();
|
let covered_end = covered_start + pairs[covered_start..end].iter().position(|pair| *pair == ("304", "ACVALUE_END")).unwrap();
|
||||||
|
let covered = &pairs[covered_start..=covered_end];
|
||||||
|
assert!(covered.contains(&("173", "1")));
|
||||||
|
assert!(covered.iter().any(|p| p.0 == "303"));
|
||||||
|
assert_eq!(covered.iter().filter(|p| p.0 == "303" || p.0 == "302").map(|p| p.1).collect::<String>(), table.cells[0][1].text);
|
||||||
|
let empty_start = covered_end + 1 + pairs[covered_end + 1..end].iter().position(|p| *p == ("171", "1")).unwrap();
|
||||||
|
let empty_end = empty_start + pairs[empty_start..end].iter().position(|p| *p == ("304", "ACVALUE_END")).unwrap();
|
||||||
|
assert!(pairs[empty_start..=empty_end].contains(&("173", "1")));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
&pairs[covered_start..=covered_end],
|
pairs[empty_start..=empty_end].iter().filter(|p| p.0 == "302" || p.0 == "303").copied().collect::<Vec<_>>(),
|
||||||
&[
|
vec![("302", "")]
|
||||||
("171", "1"),
|
|
||||||
("172", "0"),
|
|
||||||
("173", "1"),
|
|
||||||
("174", "0"),
|
|
||||||
("175", "0"),
|
|
||||||
("176", "0"),
|
|
||||||
("91", "0"),
|
|
||||||
("92", "0"),
|
|
||||||
("178", "0"),
|
|
||||||
("145", "0.0"),
|
|
||||||
("301", "CELL_VALUE"),
|
|
||||||
("93", "4"),
|
|
||||||
("90", "4"),
|
|
||||||
("1", ""),
|
|
||||||
("94", "0"),
|
|
||||||
("300", ""),
|
|
||||||
("302", ""),
|
|
||||||
("304", "ACVALUE_END")
|
|
||||||
]
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
let mut expected_cells = table.cells.clone();
|
assert_eq!(first_table(&cadcraft_io::read(&bytes, "t.dxf").unwrap()).cells, table.cells);
|
||||||
if merged {
|
|
||||||
for cell in &mut expected_cells[0][1..] {
|
|
||||||
cell.text.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert_eq!(first_table(&cadcraft_io::read(&bytes, "t.dxf").unwrap()).cells, expected_cells);
|
|
||||||
}
|
}
|
||||||
if merged {
|
if merged {
|
||||||
let bytes = cadcraft_io::write_with(&d, "t.dxf", &SaveOptions { version: Some(Version::R2004), binary: false }).unwrap();
|
let bytes = cadcraft_io::write_with(&d, "t.dxf", &SaveOptions { version: Some(Version::R2004), binary: false }).unwrap();
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
//! Group 72 of the `*Active` VPORT records ("Circle sides" in the DXF Reference, VPORT) survives
|
||||||
|
//! opening and saving as DXF and as DWG. A drawing that stores none, or one that is not a 16-bit
|
||||||
|
//! integer (the type of groups 60-79, DXF Reference, Group Code Value Types), is written without
|
||||||
|
//! it, as before.
|
||||||
|
|
||||||
|
use cadcraft_doc::{Drawing, HVal};
|
||||||
|
use cadcraft_io::{read_dxf, write_dxf};
|
||||||
|
|
||||||
|
/// Where the value is kept with the drawing.
|
||||||
|
const KEY: &str = "CADCRAFT_VPORT_CIRCLE_SIDES";
|
||||||
|
|
||||||
|
/// The group 72 of each `*ACTIVE` VPORT record in DXF text, in order (`None`: the record has no
|
||||||
|
/// 72, or one that is not a number).
|
||||||
|
fn active_circle_sides(text: &str) -> Vec<Option<i64>> {
|
||||||
|
circle_sides_of(text, "*ACTIVE")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The group 72 of each VPORT record named `name` (any case) in DXF text, in order.
|
||||||
|
fn circle_sides_of(text: &str, name: &str) -> Vec<Option<i64>> {
|
||||||
|
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut record: Option<Vec<(&str, &str)>> = None;
|
||||||
|
let mut finish = |r: Option<Vec<(&str, &str)>>| {
|
||||||
|
if let Some(r) = r.filter(|r| r.iter().any(|(c, v)| *c == "2" && v.eq_ignore_ascii_case(name))) {
|
||||||
|
out.push(r.iter().find(|(c, _)| *c == "72").and_then(|(_, v)| v.parse().ok()));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for pair in lines.chunks(2) {
|
||||||
|
let [code, value] = pair else { break };
|
||||||
|
if *code == "0" {
|
||||||
|
finish(record.take());
|
||||||
|
record = (*value == "VPORT").then(Vec::new);
|
||||||
|
} else if let Some(r) = record.as_mut() {
|
||||||
|
r.push((*code, *value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finish(record);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A DXF whose VPORT table holds `records`, each `(name, group 72)` a usable tile, tiles side by
|
||||||
|
/// side in pairs.
|
||||||
|
fn vport_dxf(records: &[(&str, Option<&str>)]) -> String {
|
||||||
|
let mut tags: Vec<(i32, String)> = vec![(0, "SECTION".into()), (2, "TABLES".into()), (0, "TABLE".into()), (2, "VPORT".into())];
|
||||||
|
for (i, (name, sides)) in records.iter().enumerate() {
|
||||||
|
let x0 = if i % 2 == 0 { "0" } else { "0.5" };
|
||||||
|
let x1 = if i % 2 == 0 { "0.5" } else { "1" };
|
||||||
|
for (c, v) in [(0, "VPORT"), (2, name), (70, "0"), (10, x0), (20, "0"), (11, x1), (21, "1"), (12, "3"), (22, "4"), (40, "9"), (41, "1.5")] {
|
||||||
|
tags.push((c, v.to_string()));
|
||||||
|
}
|
||||||
|
if let Some(v) = sides {
|
||||||
|
tags.push((72, v.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tags.extend([(0, "ENDTAB".into()), (0, "ENDSEC".into()), (0, "EOF".into())]);
|
||||||
|
tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value the first `*ACTIVE` record holds is written back on every `*ACTIVE` record, and again
|
||||||
|
/// after a second save; it was read and dropped, so the file came back without it.
|
||||||
|
#[test]
|
||||||
|
fn circle_sides_of_the_active_vport_are_written_back() {
|
||||||
|
for sides in ["2500", "1", "0", "-7", "32767", "-32768"] {
|
||||||
|
let d = read_dxf(vport_dxf(&[("*ACTIVE", Some(sides)), ("*ACTIVE", Some(sides))]).as_bytes()).expect("read");
|
||||||
|
let want: i64 = sides.parse().expect("a number");
|
||||||
|
let text = write_dxf(&d);
|
||||||
|
let written = active_circle_sides(&text);
|
||||||
|
assert_eq!(written.len(), 2, "both tiles are written: {written:?}");
|
||||||
|
assert!(written.iter().all(|v| *v == Some(want)), "{sides}: {written:?}");
|
||||||
|
let again = write_dxf(&read_dxf(text.as_bytes()).expect("reopen"));
|
||||||
|
assert!(active_circle_sides(&again).iter().all(|v| *v == Some(want)), "{sides}: second save");
|
||||||
|
}
|
||||||
|
// Only the first `*ACTIVE` record's value is kept: a later one neither replaces it nor stands
|
||||||
|
// in for a first record that has none.
|
||||||
|
for (first, second, want) in [(Some("1"), Some("2"), Some(1)), (None, Some("2"), None)] {
|
||||||
|
let text = write_dxf(&read_dxf(vport_dxf(&[("*Active", first), ("*ACTIVE", second)]).as_bytes()).expect("read"));
|
||||||
|
assert_eq!(active_circle_sides(&text), [want, want], "{first:?}, {second:?}");
|
||||||
|
}
|
||||||
|
// An untiled drawing: its lone `*ACTIVE` record. A saved configuration that has none does
|
||||||
|
// not get the shown one's.
|
||||||
|
let d = read_dxf(vport_dxf(&[("*ACTIVE", Some("2500")), ("Saved", None), ("Saved", None)]).as_bytes()).expect("read");
|
||||||
|
let text = write_dxf(&d);
|
||||||
|
assert_eq!(active_circle_sides(&text), [Some(2500)]);
|
||||||
|
assert_eq!(circle_sides_of(&text, "Saved"), [None, None]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A drawing with no value, or one that is not a 16-bit integer (from a file or set on the
|
||||||
|
/// drawing), is written with no group 72, never the bad value.
|
||||||
|
#[test]
|
||||||
|
fn missing_or_unusable_circle_sides_are_not_written() {
|
||||||
|
let none = |text: &str| {
|
||||||
|
let written = active_circle_sides(text);
|
||||||
|
!written.is_empty() && written.iter().all(Option::is_none)
|
||||||
|
};
|
||||||
|
let new = write_dxf(&Drawing::new_metric());
|
||||||
|
assert!(none(&new), "a new drawing: {:?}", active_circle_sides(&new));
|
||||||
|
for sides in [None, Some("32768"), Some("-32769"), Some("99999999999")] {
|
||||||
|
let text = write_dxf(&read_dxf(vport_dxf(&[("*ACTIVE", sides)]).as_bytes()).expect("read"));
|
||||||
|
assert!(none(&text), "{sides:?}: {:?}", active_circle_sides(&text));
|
||||||
|
}
|
||||||
|
for bad in [HVal::Int(32_768), HVal::Int(i64::MIN), HVal::Real(f64::NAN), HVal::Real(1e300), HVal::Str("many".into())] {
|
||||||
|
let mut d = Drawing::new_metric();
|
||||||
|
d.header.set(KEY, bad.clone());
|
||||||
|
let text = write_dxf(&d);
|
||||||
|
assert!(none(&text), "{bad:?}: {:?}", active_circle_sides(&text));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saved as DWG and reopened, the drawing keeps the value: the DWG is written from the same VPORT
|
||||||
|
/// records, and a DWG is read through the DXF its decoder gives, by the same reader.
|
||||||
|
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||||
|
#[test]
|
||||||
|
fn circle_sides_survive_a_dwg_round_trip() {
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let d = read_dxf(vport_dxf(&[("*ACTIVE", Some("2500"))]).as_bytes()).expect("read");
|
||||||
|
let dwg = cadcraft_io::write(&d, "x.dwg").expect("write DWG");
|
||||||
|
let back = cadcraft_io::read(&dwg, "x.dwg").expect("read DWG");
|
||||||
|
assert_eq!(active_circle_sides(&write_dxf(&back)), [Some(2500)]);
|
||||||
|
}
|
||||||
@@ -19,3 +19,134 @@ fn wipeoutvariables_sets_the_frame_flag() {
|
|||||||
assert_eq!(frame(None), 1, "no object: the default shows frames");
|
assert_eq!(frame(None), 1, "no object: the default shows frames");
|
||||||
assert_eq!(frame(Some(7)), 1, "an out-of-range flag is ignored");
|
assert_eq!(frame(Some(7)), 1, "an out-of-range flag is ignored");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A drawing with `frame` set (or untouched for `None`), saved as `name` and read back.
|
||||||
|
fn saved(frame: Option<i64>, name: &str) -> cadcraft_doc::Drawing {
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let mut d = cadcraft_doc::Drawing::new_metric();
|
||||||
|
if let Some(f) = frame {
|
||||||
|
d.header.set_i64("WIPEOUTFRAME", f);
|
||||||
|
}
|
||||||
|
let bytes = cadcraft_io::write(&d, name).unwrap();
|
||||||
|
cadcraft_io::read(&bytes, name).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many records of the written DXF have `value` in group `code`.
|
||||||
|
fn count(dxf: &str, code: &str, value: &str) -> usize {
|
||||||
|
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||||
|
lines.chunks(2).filter(|pair| **pair == [code, value]).count()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The object is of a class a reader does not know by itself, so the file declares it; a drawing
|
||||||
|
/// that never set the frame gets neither the object nor the class.
|
||||||
|
#[test]
|
||||||
|
fn the_written_object_has_its_class_and_one_dictionary_entry() {
|
||||||
|
let mut d = cadcraft_doc::Drawing::new_metric();
|
||||||
|
let plain = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap();
|
||||||
|
d.header.set_i64("WIPEOUTFRAME", 0);
|
||||||
|
let set = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap();
|
||||||
|
for (code, value) in [("0", "WIPEOUTVARIABLES"), ("1", "WIPEOUTVARIABLES"), ("3", "ACAD_WIPEOUT_VARS")] {
|
||||||
|
assert_eq!(count(&set, code, value), 1, "set: group {code} {value}");
|
||||||
|
assert_eq!(count(&plain, code, value), 0, "not set: group {code} {value}");
|
||||||
|
}
|
||||||
|
// A file that already has the object is not given a second one when it is saved again.
|
||||||
|
let again = String::from_utf8(cadcraft_io::write(&cadcraft_io::read(set.as_bytes(), "a.dxf").unwrap(), "a.dxf").unwrap()).unwrap();
|
||||||
|
assert_eq!(count(&again, "0", "WIPEOUTVARIABLES"), 1, "saved twice");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wipeout_frame_setting_survives_a_save_in_dxf_and_dwg() {
|
||||||
|
// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works.
|
||||||
|
let mut names = vec!["a.dxf"];
|
||||||
|
if cfg!(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))) {
|
||||||
|
names.push("a.dwg");
|
||||||
|
}
|
||||||
|
for name in names {
|
||||||
|
for frame in [0, 1] {
|
||||||
|
let back = saved(Some(frame), name);
|
||||||
|
assert_eq!(back.header.i64("WIPEOUTFRAME", 1), frame, "{name}: frame {frame}");
|
||||||
|
}
|
||||||
|
// "Shown but not plotted" has no documented place in the object: the frames stay shown.
|
||||||
|
assert_ne!(saved(Some(2), name).header.i64("WIPEOUTFRAME", 1), 0, "{name}: frame 2 keeps the frames shown");
|
||||||
|
let untouched = saved(None, name);
|
||||||
|
assert_eq!(untouched.header.i64("WIPEOUTFRAME", 1), 1, "{name}: default");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Group 70 of the WIPEOUTVARIABLES object in a written DXF.
|
||||||
|
fn written_flag(dxf: &str) -> Option<i64> {
|
||||||
|
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||||
|
let mut pairs = lines.chunks(2).skip_while(|pair| **pair != ["0", "WIPEOUTVARIABLES"]).skip(1);
|
||||||
|
pairs.by_ref().take_while(|pair| pair.first() != Some(&"0")).find(|pair| pair.first() == Some(&"70")).and_then(|pair| pair.get(1)?.parse().ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The DXF Reference gives the object's group 70 two values, 0 (no frame) and 1 (display frame),
|
||||||
|
/// so no setting writes another one.
|
||||||
|
#[test]
|
||||||
|
fn the_written_flag_is_one_the_format_documents() {
|
||||||
|
for frame in [0, 1, 2] {
|
||||||
|
let mut d = cadcraft_doc::Drawing::new_metric();
|
||||||
|
d.header.set_i64("WIPEOUTFRAME", frame);
|
||||||
|
let dxf = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap();
|
||||||
|
let flag = written_flag(&dxf);
|
||||||
|
assert!(matches!(flag, Some(0 | 1)), "frame {frame} writes {flag:?}");
|
||||||
|
assert_eq!(flag == Some(0), frame == 0, "frame {frame}: only hidden frames write 0");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A file whose named object dictionary lists a WIPEOUTVARIABLES object with `flag` in group 70.
|
||||||
|
fn file_with(flag: i64) -> String {
|
||||||
|
format!(
|
||||||
|
" 0\nSECTION\n 2\nENTITIES\n 0\nENDSEC\n 0\nSECTION\n 2\nOBJECTS\n\
|
||||||
|
0\nDICTIONARY\n 5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n 3\nACAD_WIPEOUT_VARS\n350\nA1\n\
|
||||||
|
0\nWIPEOUTVARIABLES\n 5\nA1\n102\n{{ACAD_REACTORS\n330\nC\n102\n}}\n330\nC\n100\nAcDbWipeoutVariables\n 70\n{flag}\n\
|
||||||
|
0\nENDSEC\n 0\nEOF\n"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A file's own WIPEOUTVARIABLES object is replaced by the drawing's setting when the setting
|
||||||
|
/// changed: the saved file has one object, and it no longer hides the frames.
|
||||||
|
#[test]
|
||||||
|
fn a_changed_setting_replaces_the_objects_of_the_file() {
|
||||||
|
for shown in [1, 2] {
|
||||||
|
let mut d = cadcraft_io::read_dxf(file_with(0).as_bytes()).unwrap();
|
||||||
|
assert_eq!(d.header.i64("WIPEOUTFRAME", 1), 0, "as the file says");
|
||||||
|
d.header.set_i64("WIPEOUTFRAME", shown);
|
||||||
|
let saved = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap();
|
||||||
|
assert_eq!(count(&saved, "0", "WIPEOUTVARIABLES"), 1, "set to {shown}: one object");
|
||||||
|
assert_eq!(count(&saved, "3", "ACAD_WIPEOUT_VARS"), 1, "set to {shown}: one dictionary entry");
|
||||||
|
assert_ne!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.i64("WIPEOUTFRAME", 0), 0, "set to {shown}: the frames are shown");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A file's own object is written back as read while the setting is what the file said: what
|
||||||
|
/// another application hung on it (here an extension dictionary with one record) is still there.
|
||||||
|
#[test]
|
||||||
|
fn an_unchanged_setting_keeps_the_objects_of_the_file_as_read() {
|
||||||
|
for flag in [0, 1, 2] {
|
||||||
|
let extra = "102\n{ACAD_XDICTIONARY\n360\nB1\n102\n}\n102\n{ACAD_REACTORS";
|
||||||
|
let file = file_with(flag).replacen("102\n{ACAD_REACTORS", extra, 1).replacen(
|
||||||
|
"0\nENDSEC\n 0\nEOF\n",
|
||||||
|
"0\nDICTIONARY\n 5\nB1\n330\nA1\n100\nAcDbDictionary\n281\n1\n 3\nSOME_APP_DATA\n360\nB2\n\
|
||||||
|
0\nXRECORD\n 5\nB2\n330\nB1\n100\nAcDbXrecord\n280\n1\n 1\nkept\n 0\nENDSEC\n 0\nEOF\n",
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
assert_eq!(count(&file, "3", "SOME_APP_DATA"), 1, "the file has the record");
|
||||||
|
let d = cadcraft_io::read_dxf(file.as_bytes()).unwrap();
|
||||||
|
let saved = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap();
|
||||||
|
assert_eq!(count(&saved, "0", "WIPEOUTVARIABLES"), 1, "flag {flag}: one object");
|
||||||
|
assert_eq!(written_flag(&saved), Some(flag), "flag {flag}: as the file said");
|
||||||
|
assert_eq!(count(&saved, "3", "SOME_APP_DATA"), 1, "flag {flag}: its extension dictionary is kept");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A file that came with flag 2 in its object keeps it through a save, as every object CADCraft
|
||||||
|
/// does not write itself is kept: opening and saving a drawing does not change its setting.
|
||||||
|
#[test]
|
||||||
|
fn a_file_that_holds_flag_2_keeps_it() {
|
||||||
|
let d = cadcraft_io::read_dxf(file_with(2).as_bytes()).unwrap();
|
||||||
|
let saved = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap();
|
||||||
|
assert_eq!(count(&saved, "0", "WIPEOUTVARIABLES"), 1, "one object");
|
||||||
|
assert_eq!(written_flag(&saved), Some(2), "the file's own flag");
|
||||||
|
assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.i64("WIPEOUTFRAME", 1), d.header.i64("WIPEOUTFRAME", 1));
|
||||||
|
}
|
||||||
|
|||||||
@@ -209,13 +209,19 @@ fn attributes(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert
|
|||||||
let sh = if multiline.is_none() { Some(place_text_entity(ctx.d, &a.text, &a.text.value).0) } else { None };
|
let sh = if multiline.is_none() { Some(place_text_entity(ctx.d, &a.text, &a.text.value).0) } else { None };
|
||||||
// Properties of the attribute's definition (as AutoCAD copies them to the attribute
|
// Properties of the attribute's definition (as AutoCAD copies them to the attribute
|
||||||
// on insertion), except those set on the attribute itself: ByBlock = the reference's,
|
// on insertion), except those set on the attribute itself: ByBlock = the reference's,
|
||||||
// layer 0 = the reference's layer.
|
// layer 0 from the definition = the reference's layer.
|
||||||
let def = defs.get(&a.tag.to_ascii_lowercase()).copied();
|
let def = defs.get(&a.tag.to_ascii_lowercase()).copied();
|
||||||
let (ink, lw, shown, t) = match (def, a.props.is_empty()) {
|
let (ink, lw, shown, t) = match (def, a.props.is_empty()) {
|
||||||
(None, true) => (rgb, resolve(ctx, e, b.plotting).1, true, reference),
|
(None, true) => (rgb, resolve(ctx, e, b.plotting).1, true, reference),
|
||||||
(def, _) => {
|
(def, _) => {
|
||||||
let c = a.props.over(&def.map(|d| d.common.clone()).unwrap_or_else(by_block));
|
let c = a.props.over(&def.map(|d| d.common.clone()).unwrap_or_else(by_block));
|
||||||
let (ink, lw, _, _, shown, layer_t, fade) = resolve_common(&sub_ctx(ctx, e, Mat3::IDENTITY), &c, b.plotting);
|
let mut sub = sub_ctx(ctx, e, Mat3::IDENTITY);
|
||||||
|
// An attribute set on layer 0 itself is on layer 0 where its reference is,
|
||||||
|
// not on the reference's layer.
|
||||||
|
if a.props.layer.is_some() {
|
||||||
|
sub.block_layer.clone_from(&ctx.block_layer);
|
||||||
|
}
|
||||||
|
let (ink, lw, _, _, shown, layer_t, fade) = resolve_common(&sub, &c, b.plotting);
|
||||||
// ByBlock takes the reference's own transparency, not its locked-layer fade.
|
// ByBlock takes the reference's own transparency, not its locked-layer fade.
|
||||||
let t = if b.opts.transparency { transparency(c.transparency, layer_t, own) } else { 0 };
|
let t = if b.opts.transparency { transparency(c.transparency, layer_t, own) } else { 0 };
|
||||||
let t = if b.opts.on_screen { t.max(fade) } else { t };
|
let t = if b.opts.on_screen { t.max(fade) } else { t };
|
||||||
|
|||||||
@@ -1090,6 +1090,62 @@ fn attributes_follow_the_reference_layer_and_have_no_definition() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn attribute_set_on_layer_zero_does_not_take_the_reference_layer() {
|
||||||
|
// #3492: a layer-0 definition in a reference on a 40 % layer. An attribute that takes layer 0
|
||||||
|
// from its definition is drawn on the reference's layer, like the line; one set on layer 0
|
||||||
|
// itself is drawn on the opaque layer 0.
|
||||||
|
let drawn = |layer: Option<&str>| {
|
||||||
|
let mut d = Drawing::new_imperial();
|
||||||
|
let mut blk = cadcraft_doc::Block::new("B");
|
||||||
|
let (c, k) = line_common(Common::default());
|
||||||
|
blk.entities.push(block_entity(1, c, k));
|
||||||
|
blk.entities.push(block_entity(2, Common::default(), EntityKind::AttDef(attrib("TAG"))));
|
||||||
|
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||||
|
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||||||
|
let props = cadcraft_doc::AttribProps { layer: layer.map(Into::into), ..Default::default() };
|
||||||
|
ins.attribs.push(cadcraft_doc::Attrib { props, ..attrib("TAG") });
|
||||||
|
d.add(&Space::Model, Common { layer: "Glass".into(), ..Default::default() }, EntityKind::Insert(ins)).unwrap();
|
||||||
|
d.layer_mut("Glass").unwrap().transparency = 40;
|
||||||
|
line_and_text(&d)
|
||||||
|
};
|
||||||
|
let (inherited_line, inherited) = drawn(None);
|
||||||
|
let (line, own) = drawn(Some("0"));
|
||||||
|
assert_eq!(line, inherited_line, "the block's contents still take the reference's layer");
|
||||||
|
assert!(inherited.iter().all(|t| *t == line), "{inherited:?}");
|
||||||
|
assert!(own.iter().all(|t| *t < line), "{own:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn attribute_on_layer_zero_of_a_nested_reference_follows_the_outer_reference() {
|
||||||
|
// A reference on the opaque layer A, with an attribute set on layer 0, sits inside block
|
||||||
|
// Outer beside a layer-0 line; Outer is placed on a 40 % layer. In Outer the attribute is
|
||||||
|
// layer-0 content like that line, so both take the outer reference's layer: not layer 0
|
||||||
|
// itself, and not layer A, which only the inner block's own line takes.
|
||||||
|
let mut d = Drawing::new_imperial();
|
||||||
|
d.layers.push(cadcraft_doc::Layer { name: "A".into(), ..Default::default() });
|
||||||
|
let mut inner = cadcraft_doc::Block::new("B");
|
||||||
|
let (c, k) = line_common(Common::default());
|
||||||
|
inner.entities.push(block_entity(1, c, k));
|
||||||
|
inner.entities.push(block_entity(2, Common::default(), EntityKind::AttDef(attrib("TAG"))));
|
||||||
|
d.blocks.insert("B".into(), std::sync::Arc::new(inner));
|
||||||
|
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||||||
|
let props = cadcraft_doc::AttribProps { layer: Some("0".into()), ..Default::default() };
|
||||||
|
ins.attribs.push(cadcraft_doc::Attrib { props, ..attrib("TAG") });
|
||||||
|
let mut outer = cadcraft_doc::Block::new("Outer");
|
||||||
|
let (c, k) = line_common(Common::default());
|
||||||
|
outer.entities.push(block_entity(3, c, k));
|
||||||
|
outer.entities.push(block_entity(4, Common { layer: "A".into(), ..Default::default() }, EntityKind::Insert(ins)));
|
||||||
|
d.blocks.insert("Outer".into(), std::sync::Arc::new(outer));
|
||||||
|
d.add(&Space::Model, Common { layer: "Glass".into(), ..Default::default() }, insert_of("Outer")).unwrap();
|
||||||
|
d.layer_mut("Glass").unwrap().transparency = 40;
|
||||||
|
let l = build(&d, &Space::Model, &with_transparency());
|
||||||
|
let [outer_line, inner_line, text @ ..] = l.prims.as_slice() else { panic!("two lines and the attribute") };
|
||||||
|
assert!(!text.is_empty(), "the attribute is drawn");
|
||||||
|
assert!(inner_line.transparency < outer_line.transparency, "the inner block's line is on layer A");
|
||||||
|
assert!(text.iter().all(|p| p.transparency == outer_line.transparency), "the attribute follows the outer reference's layer");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn mtext_exact_spacing_ignores_taller_lines() {
|
fn mtext_exact_spacing_ignores_taller_lines() {
|
||||||
// #711: a doubled middle line pushes the next baseline down with At least, not with Exactly.
|
// #711: a doubled middle line pushes the next baseline down with At least, not with Exactly.
|
||||||
|
|||||||
Reference in New Issue
Block a user