mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-21 20:40:02 +00:00
Compare commits
96
Commits
d3af2d5077
...
a70b9b02e4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a70b9b02e4 | ||
|
|
b206eab39b | ||
|
|
8d3236c5a3 | ||
|
|
f4d4a6e4e1 | ||
|
|
80e9a97164 | ||
|
|
97dccaf9e7 | ||
|
|
b39170aded | ||
|
|
20d489f059 | ||
|
|
318d8d9de1 | ||
|
|
4076a71dee | ||
|
|
e5a7d38a67 | ||
|
|
46053d43c1 | ||
|
|
6aa64fb5ae | ||
|
|
543285778b | ||
|
|
fed8b0f4e4 | ||
|
|
50baa3cfae | ||
|
|
ef6df4dffa | ||
|
|
97c5670a0a | ||
|
|
ed294b3fb3 | ||
|
|
40ddd7baca | ||
|
|
ea4a59b662 | ||
|
|
9e645ba17a | ||
|
|
8da04230af | ||
|
|
af5c658a4b | ||
|
|
5d76e47342 | ||
|
|
3caad662a4 | ||
|
|
615fee3e12 | ||
|
|
92fe0a655d | ||
|
|
a62dd047a4 | ||
|
|
b4c325a36b | ||
|
|
1ad4fc7c91 | ||
|
|
8178a68f3e | ||
|
|
29a22f7955 | ||
|
|
48f0a590ab | ||
|
|
80f2b6838d | ||
|
|
70e55f21cc | ||
|
|
2dc136781b | ||
|
|
5c00b66572 | ||
|
|
0e0344be94 | ||
|
|
3ec1e1b210 | ||
|
|
3165d2735e | ||
|
|
d04d67f8c3 | ||
|
|
67cc9a28c3 | ||
|
|
73d1b65f3e | ||
|
|
dab89a38ed | ||
|
|
3c956c4ccf | ||
|
|
3ee12a8c62 | ||
|
|
b8f60e1e60 | ||
|
|
984596fead | ||
|
|
5869cf91f9 | ||
|
|
8e2aa822f7 | ||
|
|
a34cf69439 | ||
|
|
6ec0f2400a | ||
|
|
203865064a | ||
|
|
18effe68b4 | ||
|
|
b325046f76 | ||
|
|
48bcb817ed | ||
|
|
467ab20ace | ||
|
|
275f989aa5 | ||
|
|
fd17a05b95 | ||
|
|
f7b3b68952 | ||
|
|
ad6d3d12ca | ||
|
|
6412e9c99a | ||
|
|
f7c4c148a3 | ||
|
|
0bd4d54f4a | ||
|
|
11ee9f1f64 | ||
|
|
e928316c4d | ||
|
|
1a3d2f6015 | ||
|
|
a801739ea7 | ||
|
|
41f9e394b9 | ||
|
|
2bd916661d | ||
|
|
b3a1e1af40 | ||
|
|
dc59a8e33c | ||
|
|
b17880ca89 | ||
|
|
72e82c59d0 | ||
|
|
72f8dd8076 | ||
|
|
cc74fe32ed | ||
|
|
9a5f26d5aa | ||
|
|
f646452065 | ||
|
|
5ab29b4090 | ||
|
|
b6cc1c29ee | ||
|
|
015fe2a18d | ||
|
|
bb95044b19 | ||
|
|
bee69e6f24 | ||
|
|
0bf230b14a | ||
|
|
0a23281d45 | ||
|
|
3f3ac1ded9 | ||
|
|
7f2e4bb817 | ||
|
|
c667151667 | ||
|
|
d2a1090357 | ||
|
|
24e5687c3d | ||
|
|
a35817eaea | ||
|
|
b49137f6dd | ||
|
|
5147aae2c2 | ||
|
|
b551acec8d | ||
|
|
fa4f997eed |
+15
-10
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet)
|
||||
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-19 · **Change:** major (alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-20 · **Change:** minor (Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
|
||||
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
|
||||
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
|
||||
@@ -115,21 +115,23 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
|
||||
- The open findings of the security audit (#1919–#1935): check each against the input limits that
|
||||
landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities
|
||||
overwrite existing ones (#1921) is fixed by #1276.
|
||||
- Hostile-input fixes waiting in pull requests (#2820, #2821, #2765).
|
||||
- A saved file that crashes AutoCAD 2021 (#3303) and dimension text lost on save (#3299).
|
||||
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content
|
||||
(#2174), startup on older graphics hardware (#1724, #1631, #3222).
|
||||
|
||||
**2. Parity with AutoCAD: the alpha gate rows, then the beta checklist (apart from its items named under tier 3).**
|
||||
- It starts on common hardware (#1596, then an automatic fallback renderer).
|
||||
- It starts on common hardware: an automatic fallback renderer (`CADCRAFT_STENCIL=0` is the manual
|
||||
switch since #3336).
|
||||
- It opens the DWG and DXF files people already have: large files (#3102, #2633, #1088), layouts and
|
||||
paper units (#1672, #2836), and a corpus of real files run in CI.
|
||||
- Saving loses nothing and other CAD programs open the result (#2904, #1687, #3234, #2632).
|
||||
- Input feels like AutoCAD for Windows: clicks while the mouse moves (#1001, #2092), right-click and
|
||||
Space as Enter (#1387), double-click to edit text (#842).
|
||||
- The prompt options that still say "not available yet", and TRIM/EXTEND depth.
|
||||
- Layouts print at scale on a system printer, and the menu bar and panels can always be restored
|
||||
(#3216, #1240).
|
||||
- 714 pull requests are open (2026-11-19). About 230 are mergeable, pass CI and are small; they are
|
||||
- Input feels like AutoCAD for Windows: the fixes for clicks while the mouse moves, right-click and
|
||||
Space as Enter, and double-click text editing landed (#3307, #3345); waiting for the reporters to
|
||||
confirm, and table cells are left (#842).
|
||||
- The prompt options that still say "not available yet" (gaps F1).
|
||||
- Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since
|
||||
#3308.
|
||||
- 661 pull requests are open (2026-11-20; 714 the day before). About 230 were mergeable, passed CI and were small; they are
|
||||
reviewed and landed in this order, the longest-waiting authors first within a row.
|
||||
|
||||
**3. Lower priority: affects fewer people and nothing breaks without it.**
|
||||
@@ -139,7 +141,9 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
|
||||
but a file with 3D content must open safely (tier 1).
|
||||
- Menu breadth against AutoCAD for Mac as a headline number.
|
||||
|
||||
Done since the last ranking: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
|
||||
Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345).
|
||||
|
||||
Done before that: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
|
||||
OFFSET, ROTATE, PLINE, SPLINE, MTEXT and MLEADER (#397, #408, #547), autosave, recovery, AUDIT and
|
||||
RECOVER on the desktop (#406, #416), xrefs (#525), groups (#417), the Block Editor (#824, #833, #885),
|
||||
REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the Dimension Style Manager
|
||||
@@ -166,6 +170,7 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored |
|
||||
| 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored |
|
||||
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: language table, CI gate and open-PR count re-checked against main 41d9b5e95 |
|
||||
| 2026-10-21 | trivial | Progress log: proxy objects keep their class through a save (#1812) |
|
||||
|
||||
@@ -56,6 +56,8 @@ fn install_io() {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
|
||||
@@ -130,6 +130,8 @@ mod web {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
let Some(canvas) = app_canvas() else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
|
||||
@@ -174,6 +174,8 @@ pub fn install_io() {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
|
||||
@@ -331,16 +331,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, and its socket path.
|
||||
/// A fresh folder for one test, and its socket path. Both names stay short: a Windows socket path
|
||||
/// holds at most 107 bytes, and a long `%TEMP%` already uses most of them.
|
||||
#[cfg(windows)]
|
||||
fn socket_dir(test: &str) -> (Cleanup, PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-single-instance-{}-{test}", std::process::id()));
|
||||
let dir = std::env::temp_dir().join(format!("cc-si-{}-{test}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("instance-test.sock");
|
||||
let path = dir.join("t.sock");
|
||||
(Cleanup(dir), path)
|
||||
}
|
||||
|
||||
/// Whether a socket can be bound at `path` here. It can't when `%TEMP%` is too long or lives
|
||||
/// under a redirected `%LOCALAPPDATA%`; the socket tests then skip instead of failing.
|
||||
#[cfg(windows)]
|
||||
fn can_bind(path: &std::path::Path) -> bool {
|
||||
let bound = uds_windows::UnixListener::bind(path)
|
||||
.map(drop)
|
||||
.map_err(|e| {
|
||||
// Straight to stderr: the test harness hides `eprintln!` from a test that passes.
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr(), "skipping: no AF_UNIX socket at {}: {e}", path.display());
|
||||
})
|
||||
.is_ok();
|
||||
let _ = std::fs::remove_file(path);
|
||||
bound
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_test_socket_path_stays_far_below_the_limit() {
|
||||
// Its own folder, with a name as long as the longest one used here: `socket_dir` empties the
|
||||
// folder, and the launches test may be using "together" at the same moment.
|
||||
let (_dir, path) = socket_dir("lengthck");
|
||||
let added = path.as_os_str().len() - std::env::temp_dir().as_os_str().len();
|
||||
assert!(added <= 40, "{added} bytes on top of %TEMP%");
|
||||
}
|
||||
|
||||
/// The whole exchange over a real socket: a stale socket file is taken over, a later launch
|
||||
/// hands its files to that listener, one that asked for its own window gets it, and a request
|
||||
/// naming a relative path is refused.
|
||||
@@ -348,6 +375,9 @@ mod tests {
|
||||
#[test]
|
||||
fn a_later_launch_hands_its_files_to_the_first() {
|
||||
let (dir, path) = socket_dir("handoff");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
drop(uds_windows::UnixListener::bind(&path).unwrap());
|
||||
assert!(path.exists(), "the stale socket file stays behind");
|
||||
|
||||
@@ -369,6 +399,9 @@ mod tests {
|
||||
fn launches_at_once_open_one_window() {
|
||||
const LAUNCHES: usize = 6;
|
||||
let (dir, path) = socket_dir("together");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
let start = Arc::new(std::sync::Barrier::new(LAUNCHES));
|
||||
let launches: Vec<_> = (0..LAUNCHES)
|
||||
.map(|i| {
|
||||
|
||||
@@ -85,6 +85,9 @@ pub struct Foreign {
|
||||
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
|
||||
/// later save must not take it for this one (#2471).
|
||||
pub version: Option<String>,
|
||||
/// The file's registered applications (APPID names as read, in file order). Saving writes
|
||||
/// them all back, whether or not any xdata still names them.
|
||||
pub appids: Vec<String>,
|
||||
}
|
||||
|
||||
impl Foreign {
|
||||
@@ -103,6 +106,7 @@ impl Foreign {
|
||||
&& self.targets.is_empty()
|
||||
&& self.class_order.is_empty()
|
||||
&& self.data_store.is_empty()
|
||||
&& self.appids.is_empty()
|
||||
}
|
||||
|
||||
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
|
||||
@@ -126,22 +130,89 @@ pub fn sat_text_acis(u: &crate::Unknown, handle: Handle, stored: &std::collectio
|
||||
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && !stored.contains(&handle) && has_sat_text(&u.tags)
|
||||
}
|
||||
|
||||
/// Whether a solid modeler entity can't be written to a DXF of 2013 and later (`modern`: SAT text
|
||||
/// with no data store record, [`sat_text_acis`]) or of 2010 and earlier (geometry only in the data
|
||||
/// store, which those files don't have, and no SAT text to write instead) (#2334).
|
||||
pub fn acis_left_out(u: &crate::Unknown, handle: Handle, stored: &std::collections::BTreeSet<Handle>, modern: bool) -> bool {
|
||||
if modern {
|
||||
return sat_text_acis(u, handle, stored);
|
||||
}
|
||||
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && stored.contains(&handle) && !has_sat_text(&u.tags)
|
||||
}
|
||||
|
||||
/// The entities a DXF of 2013 or later leaves out because they hold SAT-text ACIS data
|
||||
/// ([`sat_text_acis`]), counted by DXF type, across model space, layouts and block definitions.
|
||||
pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap<String, usize> {
|
||||
acis_dropped(d, true)
|
||||
}
|
||||
|
||||
/// The entities a DXF leaves out by [`acis_left_out`], counted like [`sat_text_dropped`].
|
||||
pub fn acis_dropped(d: &crate::Drawing, modern: bool) -> BTreeMap<String, usize> {
|
||||
let stored = d.foreign.data_store_entities();
|
||||
let mut out = BTreeMap::new();
|
||||
// The writer saves xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
|
||||
for e in saved_entities(d) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& acis_left_out(u, e.handle, &stored, modern)
|
||||
{
|
||||
count(&mut out, &u.dxf_type);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The entities a DXF file holds: model space, layouts and block definitions. The writer saves
|
||||
/// xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
|
||||
fn saved_entities(d: &crate::Drawing) -> impl Iterator<Item = &std::sync::Arc<crate::Entity>> {
|
||||
let own_blocks = d.blocks.values().filter(|b| b.xref_path.is_none() && !xref_dependent(&b.name));
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(own_blocks.map(|b| &b.entities));
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& sat_text_acis(u, e.handle, &stored)
|
||||
{
|
||||
let n: &mut usize = out.entry(u.dxf_type.to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
stores.flat_map(|s| s.iter())
|
||||
}
|
||||
|
||||
/// Add one record of DXF type `kind` to `out`.
|
||||
fn count(out: &mut BTreeMap<String, usize>, kind: &str) {
|
||||
let n: &mut usize = out.entry(kind.to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
|
||||
/// Whether a DXF type is a proxy (ACAD_PROXY_OBJECT, ACAD_PROXY_ENTITY).
|
||||
pub fn is_proxy(kind: &str) -> bool {
|
||||
let k = kind.trim();
|
||||
k.eq_ignore_ascii_case("ACAD_PROXY_OBJECT") || k.eq_ignore_ascii_case("ACAD_PROXY_ENTITY")
|
||||
}
|
||||
|
||||
/// Whether a proxy's groups (after its type) give it a separate string stream: a size above 0 in
|
||||
/// group 96 (2007) or 162 (2010 and later) after the `AcDbProxy…` marker. Before 2007 a proxy's
|
||||
/// strings are part of its data, so a file of an earlier version has no form for one that keeps
|
||||
/// them apart (#3229).
|
||||
pub fn proxy_has_string_stream<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)>) -> bool {
|
||||
let mut own = false;
|
||||
for (code, value) in groups {
|
||||
let v = value.as_ref().trim();
|
||||
match code {
|
||||
100 => own = own || v.to_ascii_lowercase().starts_with("acdbproxy"),
|
||||
96 | 162 if own && v.parse::<i64>().is_ok_and(|n| n > 0) => return true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The proxies a DXF earlier than 2007 leaves out because they have a separate string stream
|
||||
/// ([`proxy_has_string_stream`]), counted by DXF type.
|
||||
pub fn proxies_dropped_before_2007(d: &crate::Drawing) -> BTreeMap<String, usize> {
|
||||
let mut out = BTreeMap::new();
|
||||
let has_strings = |tags: &[RawTag]| proxy_has_string_stream(tags.iter().map(|t| (t.code, t.value.as_str())));
|
||||
for e in saved_entities(d) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& is_proxy(&u.dxf_type)
|
||||
&& has_strings(&u.tags)
|
||||
{
|
||||
count(&mut out, &u.dxf_type);
|
||||
}
|
||||
}
|
||||
for o in d.foreign.objects.iter().filter(|o| is_proxy(&o.kind) && has_strings(&o.tags)) {
|
||||
count(&mut out, &o.kind);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -164,6 +235,23 @@ pub fn data_store_records(tags: &[RawTag]) -> Vec<&[RawTag]> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The ACIS version a modeler entity's SAT text declares (the first number of its first line:
|
||||
/// 400, 700, 21800…), if it has SAT text.
|
||||
pub fn sat_version(tags: &[RawTag]) -> Option<u32> {
|
||||
let marked = tags.iter().take_while(|r| r.code < 1000).any(|r| r.code == 100);
|
||||
let mut in_modeler = !marked;
|
||||
for r in tags.iter().take_while(|r| r.code < 1000) {
|
||||
if r.code == 100 {
|
||||
in_modeler = r.value.trim().eq_ignore_ascii_case("AcDbModelerGeometry");
|
||||
} else if in_modeler && r.code == 1 {
|
||||
let first = r.value.split_whitespace().next()?;
|
||||
// DXF before 2013 encodes SAT text: each character but a space is 159 minus it ("hoo" is 700).
|
||||
return first.parse().ok().or_else(|| first.bytes().map(|b| char::from(159u8.wrapping_sub(b))).collect::<String>().parse().ok());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether an entity's groups hold SAT text: groups 1 and 3 inside its `AcDbModelerGeometry`
|
||||
/// subclass. A file of a version before the subclass markers has no `100` groups: all of its
|
||||
/// groups (before the extended data) are the entity's.
|
||||
|
||||
@@ -821,6 +821,18 @@ pub struct PageSetup {
|
||||
/// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub image_origin: Option<Vec2>,
|
||||
/// The plot layout flags (DXF group 70 of AcDbPlotSettings) as the file had them. Saving keeps
|
||||
/// the bits CADCraft doesn't model (plot paper space last, plot with plot styles, standard
|
||||
/// scale and the rest) as read instead of forcing its defaults (#3227); `None` for page setups
|
||||
/// made in CADCraft.
|
||||
#[serde(skip)]
|
||||
pub file_plot_flags: Option<i64>,
|
||||
/// The standard scale the file chose (DXF group 75, such as 25 for 1:50) and the plot scale it
|
||||
/// was read with. While the scale is unchanged, saving keeps that choice and the standard scale
|
||||
/// flag instead of writing the scale as a custom one; `None` for a custom scale, scaled to
|
||||
/// fit, or a page setup made in CADCraft.
|
||||
#[serde(skip)]
|
||||
pub file_standard_scale: Option<(i64, f64)>,
|
||||
}
|
||||
|
||||
impl Default for PageSetup {
|
||||
@@ -844,6 +856,8 @@ impl Default for PageSetup {
|
||||
paper_mm: None,
|
||||
file_paper: None,
|
||||
image_origin: None,
|
||||
file_plot_flags: None,
|
||||
file_standard_scale: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::curves::KW;
|
||||
use super::super::file::{drops_unknown, new_folder, not_saved, not_saved_message, report_new_folder, report_not_saved};
|
||||
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
|
||||
use super::super::machines::{SelOutcome, SelectPhase};
|
||||
use super::super::modify::erase_kept;
|
||||
use super::super::{CommandSpec, bad, point_param, str_param, targets};
|
||||
@@ -44,13 +44,13 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
|
||||
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
|
||||
};
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
|
||||
None => {
|
||||
let hs = targets(s, p)?;
|
||||
@@ -76,16 +76,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size and what a
|
||||
/// DWG file left out, for the caller to report as a save does. The
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
|
||||
/// the version it was written at, for the caller to report as a save does. The
|
||||
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
|
||||
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
|
||||
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>)> {
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
|
||||
let src = s.doc()?;
|
||||
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
|
||||
// block's base point for a block.
|
||||
@@ -108,13 +109,15 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
|
||||
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() };
|
||||
Ok((d.model.len(), bytes.len(), lost))
|
||||
// The written drawing's own version: the writer is given no other.
|
||||
let version = own_version(&d, path);
|
||||
let lost = lost_writing(&d, path, version);
|
||||
Ok((d.model.len(), bytes.len(), lost, version))
|
||||
}
|
||||
|
||||
/// Say on the command line what the written DWG file left out.
|
||||
fn echo_not_saved(s: &mut Session, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = not_saved_message(lost) {
|
||||
/// Say on the command line what the file written at `path` and `version` left out.
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = lost_message(path, version, lost) {
|
||||
s.echo(msg);
|
||||
}
|
||||
}
|
||||
@@ -335,7 +338,7 @@ impl DashWblockM {
|
||||
|
||||
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
|
||||
match write(s, "-wblock", &self.path, what) {
|
||||
Ok((.., lost)) => echo_not_saved(s, &lost),
|
||||
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
}
|
||||
Ok(Step::Done)
|
||||
@@ -346,8 +349,8 @@ impl DashWblockM {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
|
||||
Ok((.., lost)) => {
|
||||
echo_not_saved(s, &lost);
|
||||
Ok((.., lost, version)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost);
|
||||
erase(s, hs)?;
|
||||
}
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
|
||||
+130
-43
@@ -83,6 +83,31 @@ pub fn object_records() -> Option<ObjectRecords> {
|
||||
OBJECT_RECORDS.get().copied()
|
||||
}
|
||||
|
||||
/// What a DXF of a version before 2007 leaves out of a drawing because it has no form for a
|
||||
/// proxy's separate string stream, counted by DXF type (installed by the app with the DXF writer,
|
||||
/// a lower layer, which finds it by writing; see `cadcraft_io::proxies_lost`). Without it the
|
||||
/// proxies themselves are counted ([`cadcraft_doc::foreign::proxies_dropped_before_2007`]).
|
||||
pub type ProxiesLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
|
||||
|
||||
static PROXIES_LOST: OnceLock<ProxiesLost> = OnceLock::new();
|
||||
|
||||
pub fn set_proxies_lost(f: ProxiesLost) {
|
||||
let _ = PROXIES_LOST.set(f);
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
|
||||
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
|
||||
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
if version >= Version::R2007 {
|
||||
return Default::default();
|
||||
}
|
||||
let d = d.committed();
|
||||
match PROXIES_LOST.get() {
|
||||
Some(f) => f(&d, version),
|
||||
None => cadcraft_doc::foreign::proxies_dropped_before_2007(&d),
|
||||
}
|
||||
}
|
||||
|
||||
/// COMPARE (drawing comparison).
|
||||
pub mod compare;
|
||||
|
||||
@@ -792,15 +817,23 @@ fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The version a drawing is saved in at `path` when none is asked for: its `$ACADVER` (2018 by
|
||||
/// default), and for DWG at least 2004 (the io layer's rule: R2000 DWG has no true colours).
|
||||
fn drawing_version(s: &Session, path: &str) -> Version {
|
||||
let v = s
|
||||
.state()
|
||||
.ok()
|
||||
.and_then(|st| st.drawing().header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver))
|
||||
.unwrap_or_default();
|
||||
pub fn drawing_version(s: &Session, path: &str) -> Version {
|
||||
let v = s.state().ok().and_then(|st| acadver(st.drawing())).unwrap_or_default();
|
||||
if is_dxf(path) { v } else { v.max(Version::R2004) }
|
||||
}
|
||||
|
||||
/// The version `d` is saved in at `path` when none is asked for, as [`drawing_version`] says for
|
||||
/// the active drawing.
|
||||
pub(crate) fn own_version(d: &Drawing, path: &str) -> Version {
|
||||
let v = acadver(d).unwrap_or_default();
|
||||
if is_dxf(path) { v } else { v.max(Version::R2004) }
|
||||
}
|
||||
|
||||
/// The version `d`'s `$ACADVER` names.
|
||||
fn acadver(d: &Drawing) -> Option<Version> {
|
||||
d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver)
|
||||
}
|
||||
|
||||
/// `document.switch index`: require the index, cancel the running command, activate that drawing and bump the epoch even if it was already active (screenshot identity).
|
||||
fn run_switch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("document.switch", "`index` is required"))? as usize;
|
||||
@@ -826,8 +859,9 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
|
||||
if drops_unknown(format!("drawing.{fmt}")) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
} else if version >= Version::R2013 && is_dxf_file(format!("drawing.{fmt}")) {
|
||||
report_sat_text_dropped(s, &mut r);
|
||||
} else if is_dxf_file(format!("drawing.{fmt}")) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
@@ -862,10 +896,12 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities));
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let cadcraft_doc::EntityKind::Unknown(u) = &e.kind {
|
||||
// A DWG before 2013 writes a solid's SAT text as it is; from 2013 the geometry has to be
|
||||
// in the data store, and SAT text alone is lost (#2334).
|
||||
// A DWG before 2013 keeps a solid's SAT text of ACIS 7.0 and later; from 2013 the geometry
|
||||
// has to be in the data store, and SAT text alone is lost. Older SAT (ACIS 4.0, as ZWCAD
|
||||
// writes to DXF 2000) reaches the DWG without usable geometry: ZWCAD 2025 opens such a
|
||||
// solid as a proxy or an empty body (#2334).
|
||||
if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t))
|
||||
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::has_sat_text(&u.tags)))
|
||||
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::sat_version(&u.tags).is_some_and(|v| v >= 700)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -907,9 +943,8 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap<String, usize>) -> Op
|
||||
/// reports the same list afterwards to callers that never get a dialog.
|
||||
pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<String, usize> {
|
||||
let version = drawing_version(s, path);
|
||||
if is_dxf_file(path) && version >= Version::R2013 {
|
||||
// The drawing a file holds: the host while the Block Editor is open.
|
||||
return s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
|
||||
if is_dxf_file(path) {
|
||||
return host_dxf_lost(s, version);
|
||||
}
|
||||
if !drops_unknown(path) {
|
||||
return Default::default();
|
||||
@@ -917,16 +952,85 @@ pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<Strin
|
||||
s.doc().map(|d| not_saved_as(d, version)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Report what the file `path`, just written at the drawing's own version, left out.
|
||||
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
|
||||
if is_dxf_file(path) {
|
||||
if drawing_version(s, path) >= Version::R2013 {
|
||||
report_sat_text_dropped(s, r);
|
||||
}
|
||||
} else {
|
||||
let lost = loss_on_save(s, path);
|
||||
report_not_saved(s, r, &lost);
|
||||
/// What a DXF of `version` leaves out of the drawing a save writes: the host while the Block
|
||||
/// Editor is open ([`dxf_lost`]).
|
||||
fn host_dxf_lost(s: &Session, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
s.state().map(|st| dxf_lost(st.drawing(), version)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d`: solid modeler entities whose ACIS geometry that
|
||||
/// version has no place for (#2334: SAT text alone from 2013, data store geometry alone before),
|
||||
/// and before 2007 proxies whose strings it can't hold, with the objects that go with them
|
||||
/// (#3229). The two never name the same record: a solid lost before 2013 is lost in 2007 too.
|
||||
fn dxf_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
let mut lost = cadcraft_doc::foreign::acis_dropped(d, version >= Version::R2013);
|
||||
for (kind, n) in proxies_lost(d, version) {
|
||||
let m = lost.entry(kind).or_insert(0);
|
||||
*m = m.saturating_add(n);
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// What a file at `path` leaves out of `d`, written at `version`: empty when it keeps everything.
|
||||
pub(crate) fn lost_writing(d: &Drawing, path: &str, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
if !is_dxf_file(path) {
|
||||
return if drops_unknown(path) { not_saved_as(d, version) } else { Default::default() };
|
||||
}
|
||||
dxf_lost(d, version)
|
||||
}
|
||||
|
||||
/// Report what the file `path`, just written from the active document (what EXPORT writes: the
|
||||
/// block while the Block Editor is open) at its own version, left out.
|
||||
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
|
||||
let Ok(d) = s.doc() else { return };
|
||||
let version = own_version(d, path);
|
||||
let lost = lost_writing(d, path, version);
|
||||
report_lost(s, r, path, version, &lost);
|
||||
}
|
||||
|
||||
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
|
||||
/// in the words for that kind of file, and list it in the result's `notSaved`.
|
||||
pub(crate) fn report_lost(s: &mut Session, r: &mut Value, path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) {
|
||||
match lost_message(path, version, lost) {
|
||||
Some(msg) => s.echo(msg),
|
||||
None => return,
|
||||
}
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
|
||||
/// The command-line warning for what a file at `path` written at `version` left out, or `None`
|
||||
/// when it kept everything.
|
||||
pub(crate) fn lost_message(path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) -> Option<String> {
|
||||
if !is_dxf_file(path) {
|
||||
return not_saved_message(lost);
|
||||
}
|
||||
if lost.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Solids (#2334) and, before 2007, proxies and what goes with them (#3229), each with its reason.
|
||||
let list = |solids: bool| -> Vec<String> {
|
||||
lost.iter().filter(|(t, _)| MODELER_TYPES.iter().any(|m| t.eq_ignore_ascii_case(m)) == solids).map(|(t, n)| format!("{n} {t}")).collect()
|
||||
};
|
||||
let mut parts = Vec::new();
|
||||
let solids = list(true);
|
||||
if !solids.is_empty() {
|
||||
let why = if version >= Version::R2013 {
|
||||
"2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them"
|
||||
} else {
|
||||
"2010 and earlier have no data store, where these entities keep their ACIS geometry; save as 2013 or later to keep them"
|
||||
};
|
||||
parts.push(format!("Not saved in the DXF file ({why}): {}", solids.join(", ")));
|
||||
}
|
||||
let others = list(false);
|
||||
if !others.is_empty() {
|
||||
parts.push(format!(
|
||||
"Not saved in the DXF file (proxies that keep their strings apart from their data, which DXF before 2007 can't hold, and the objects that go with them; save as 2007 or later to keep them): {}",
|
||||
others.join(", ")
|
||||
));
|
||||
}
|
||||
Some(parts.join(" "))
|
||||
}
|
||||
|
||||
/// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG
|
||||
@@ -945,24 +1049,6 @@ fn is_dxf_file(path: impl AsRef<std::path::Path>) -> bool {
|
||||
Format::from_path(path) == Some(Format::Dxf)
|
||||
}
|
||||
|
||||
/// Say on the command line which solid modeler entities a DXF of 2013 or later left out because
|
||||
/// they hold SAT-text ACIS data, which such files keep in a data store instead (#2334).
|
||||
fn report_sat_text_dropped(s: &mut Session, r: &mut Value) {
|
||||
// The drawing a file holds: the host while the Block Editor is open.
|
||||
let lost = s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
|
||||
if lost.is_empty() {
|
||||
return;
|
||||
}
|
||||
let list: Vec<String> = lost.iter().map(|(t, n)| format!("{n} {t}")).collect();
|
||||
s.echo(format!(
|
||||
"Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}",
|
||||
list.join(", ")
|
||||
));
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder a write to `path` has to create, asked before writing so it can be reported after.
|
||||
/// The web has no folders.
|
||||
pub(super) fn new_folder(path: &str) -> Option<String> {
|
||||
@@ -1006,8 +1092,9 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
|
||||
report_new_folder(s, &mut r, folder);
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
} else if version >= Version::R2013 && r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
report_sat_text_dropped(s, &mut r);
|
||||
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
}
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(is_drawing_file) {
|
||||
report_fonts(s, &mut r);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
|
||||
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
|
||||
|
||||
mod patfile;
|
||||
pub(super) use edit::{set_pattern, takes_pattern};
|
||||
@@ -36,6 +37,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// Typed with nothing selected it asks for objects, as in AutoCAD, rather than converting none.
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("region", "REGION")))),
|
||||
CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))),
|
||||
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
|
||||
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
|
||||
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
|
||||
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
|
||||
.enabled(has_doc)
|
||||
|
||||
@@ -29,6 +29,59 @@ fn hatches(s: &Session, p: &Value) -> Result<Vec<Handle>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Most polylines one HATCHGENERATEBOUNDARY call creates.
|
||||
const MAX_GENERATED: usize = 10_000;
|
||||
|
||||
/// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of
|
||||
/// the selected hatches, at each hatch's height. The hatches are not changed: an associative
|
||||
/// hatch stays linked to its own boundary objects and is not linked to the new polylines.
|
||||
pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selected = targets(s, p)?;
|
||||
// The polylines go to the current space, so every hatch must be there too.
|
||||
let space = s.space();
|
||||
let mut loops = Vec::new();
|
||||
let mut found = false;
|
||||
// A hatch named twice gets its boundary once.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
{
|
||||
let d = s.doc()?;
|
||||
for h in selected {
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let EntityKind::Hatch(x) = &e.kind else { continue };
|
||||
if !seen.insert(h) {
|
||||
continue;
|
||||
}
|
||||
found = true;
|
||||
if d.space_of(h).as_ref() != Some(&space) {
|
||||
return Err(bad("hatchgenerateboundary", format!("hatch {} is not in the current space; switch to its layout first", h.hex())));
|
||||
}
|
||||
// Every selected hatch counts: none is left out of a call that succeeds. Compared
|
||||
// against the room left, so a hostile loop count can't overflow the sum.
|
||||
if x.loops.len() > MAX_GENERATED.saturating_sub(loops.len()) {
|
||||
return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches")));
|
||||
}
|
||||
// The elevation runs along the hatch's normal: one facing down Z (mirrored) lies at its
|
||||
// negative, where the polyline, facing up, goes.
|
||||
let z = if e.common.extrusion.z < 0.0 { -x.elevation } else { x.elevation };
|
||||
loops.extend(x.loops.iter().map(|l| (l.vertices.clone(), z)));
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Err(bad("hatchgenerateboundary", "select one or more hatches"));
|
||||
}
|
||||
// Everything is checked before anything is added, so a refused call leaves nothing behind.
|
||||
let mut created = Vec::new();
|
||||
for (vs, elevation) in loops {
|
||||
let mut kind = lwpoly(vs, true);
|
||||
if let EntityKind::LwPolyline(pl) = &mut kind {
|
||||
pl.elevation = elevation;
|
||||
}
|
||||
created.push(s.add_entity(kind)?.hex());
|
||||
}
|
||||
let n = created.len();
|
||||
Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") }))
|
||||
}
|
||||
|
||||
fn outline(l: &HatchLoop) -> Vec<Vec2> {
|
||||
Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e-3)
|
||||
}
|
||||
|
||||
@@ -235,6 +235,7 @@ pub const NO_FILES: &[&str] = &[
|
||||
"boundary",
|
||||
"region",
|
||||
"hatchedit",
|
||||
"hatchgenerateboundary",
|
||||
"hatchpick",
|
||||
"overkill",
|
||||
"block",
|
||||
|
||||
@@ -126,23 +126,14 @@ pub fn snap_name(m: u32) -> &'static str {
|
||||
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
|
||||
}
|
||||
|
||||
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
|
||||
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
|
||||
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
|
||||
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
|
||||
/// first, then deferred snaps, then Nearest), without repeats.
|
||||
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred);
|
||||
let extra = osmode & mode::HATCH;
|
||||
let mut per_mode: Vec<SnapHit> = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect();
|
||||
per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor)));
|
||||
let mut out: Vec<SnapHit> = osnap(osmode).into_iter().collect();
|
||||
for h in per_mode {
|
||||
if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) {
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
out
|
||||
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
|
||||
}
|
||||
|
||||
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
|
||||
|
||||
+143
-59
@@ -72,6 +72,33 @@ impl SnapHit {
|
||||
None => crate::Input::Point(self.point),
|
||||
}
|
||||
}
|
||||
|
||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
|
||||
}
|
||||
|
||||
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
|
||||
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
|
||||
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
|
||||
let class = if self.deferred.is_some() {
|
||||
1
|
||||
} else if self.mode == mode::NEA {
|
||||
2
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(class, snap_score(self.mode, self.point, cursor, aperture))
|
||||
}
|
||||
|
||||
/// The same snap as `o`: mode and point, from the same source (paper space, or one
|
||||
/// viewport). Overlapping viewports can show different model points at one paper point;
|
||||
/// each stays a candidate, since DIST measures in the model units of the viewport picked.
|
||||
fn same(&self, o: &SnapHit) -> bool {
|
||||
self.mode == o.mode
|
||||
&& self.deferred.is_some() == o.deferred.is_some()
|
||||
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
||||
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The curve a deferred snap refers to.
|
||||
@@ -211,6 +238,14 @@ pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u3
|
||||
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
|
||||
}
|
||||
|
||||
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
|
||||
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
|
||||
/// Snaps seen through layout viewports are included.
|
||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn osnap_with(
|
||||
d: &Drawing,
|
||||
@@ -237,19 +272,39 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
|
||||
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
|
||||
(all.into_iter().next(), prims)
|
||||
}
|
||||
|
||||
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_all_with_neighborhood(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
|
||||
return (None, None);
|
||||
return (Vec::new(), None);
|
||||
}
|
||||
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hit, prims)) => (hit, Some(prims)),
|
||||
None => (None, None),
|
||||
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hits, prims)) => (hits, Some(prims)),
|
||||
None => (Vec::new(), None),
|
||||
};
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if views.is_empty() {
|
||||
return (best, near_prims);
|
||||
return (all, near_prims);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
|
||||
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
|
||||
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
|
||||
let mut pick = all.first().copied();
|
||||
for view in views {
|
||||
let model_cursor = view.to_model(cursor);
|
||||
let model_aperture = aperture / view.scale;
|
||||
@@ -257,7 +312,7 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let hit = osnap_in(
|
||||
let hits = osnap_in(
|
||||
d,
|
||||
&model,
|
||||
&model_ix,
|
||||
@@ -268,15 +323,36 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
deferred,
|
||||
&view.viewport.frozen_layers,
|
||||
Some(view.model_clip),
|
||||
)
|
||||
.and_then(|h| view.hit(h));
|
||||
if let Some(hit) = hit
|
||||
&& best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
);
|
||||
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
|
||||
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
{
|
||||
best = Some(hit);
|
||||
pick = Some(hit);
|
||||
}
|
||||
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
|
||||
}
|
||||
let mut out = ranked(all, cursor, aperture);
|
||||
if let Some(pick) = pick {
|
||||
out.retain(|h| !h.same(&pick));
|
||||
out.insert(0, pick);
|
||||
}
|
||||
(out, near_prims)
|
||||
}
|
||||
|
||||
/// `hits` best first ([`SnapHit::rank`]), without repeats.
|
||||
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
|
||||
hits.sort_by(|a, b| {
|
||||
let (ca, sa) = a.rank(cursor, aperture);
|
||||
let (cb, sb) = b.rank(cursor, aperture);
|
||||
ca.cmp(&cb).then(sa.total_cmp(&sb))
|
||||
});
|
||||
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
|
||||
for h in hits {
|
||||
if !out.iter().any(|o| o.same(&h)) {
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
(best, near_prims)
|
||||
out
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -291,10 +367,11 @@ fn osnap_in(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
|
||||
) -> Vec<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_in_with_prims(
|
||||
d: &Drawing,
|
||||
@@ -307,7 +384,7 @@ fn osnap_in_with_prims(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
|
||||
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
|
||||
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
|
||||
// Intersections between nearby primitives; Apparent Intersection also where their extensions
|
||||
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
|
||||
@@ -345,8 +422,8 @@ fn osnap_in_with_prims(
|
||||
}
|
||||
}
|
||||
}
|
||||
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hit, near_prims))
|
||||
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hits, near_prims))
|
||||
}
|
||||
|
||||
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
||||
@@ -458,7 +535,8 @@ fn gather_in(
|
||||
Some((cands, near_prims))
|
||||
}
|
||||
|
||||
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
|
||||
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
|
||||
/// snaps, the deferred snaps and Nearest.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
@@ -469,7 +547,7 @@ fn finish(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<SnapHit> {
|
||||
) -> Vec<SnapHit> {
|
||||
// Perpendicular / tangent from the base point.
|
||||
if let Some(bp) = base {
|
||||
for p in near_prims {
|
||||
@@ -507,20 +585,10 @@ fn finish(
|
||||
}
|
||||
}
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| {
|
||||
// Prefer more specific modes when nearly equidistant.
|
||||
let da = snap_score(a.0, a.1, cursor, aperture);
|
||||
let db = snap_score(b.0, b.1, cursor, aperture);
|
||||
da.total_cmp(&db)
|
||||
});
|
||||
if let Some((m, p)) = best {
|
||||
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None });
|
||||
}
|
||||
if base.is_none()
|
||||
&& deferred
|
||||
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
|
||||
{
|
||||
return Some(h);
|
||||
let mut hits: Vec<SnapHit> =
|
||||
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect();
|
||||
if base.is_none() && deferred {
|
||||
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip));
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
// The closest point of all nearby objects, whatever their drawing order.
|
||||
@@ -540,12 +608,13 @@ fn finish(
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = nb {
|
||||
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
}
|
||||
}
|
||||
None
|
||||
ranked(hits, cursor, aperture)
|
||||
}
|
||||
|
||||
/// Prefer more specific modes when nearly equidistant.
|
||||
fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
|
||||
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
|
||||
}
|
||||
@@ -848,9 +917,11 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
|
||||
fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
|
||||
let mut best: Option<(f64, SnapHit)> = None;
|
||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
|
||||
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
|
||||
/// perpendicular on the same circle.
|
||||
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
|
||||
let mut hits = Vec::new();
|
||||
for p in prims {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
@@ -859,32 +930,28 @@ fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
|
||||
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
|
||||
_ => continue,
|
||||
};
|
||||
let (m, name, at) = match curve {
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
|
||||
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
|
||||
// Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray
|
||||
// anywhere.
|
||||
let at = match curve {
|
||||
SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor),
|
||||
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor),
|
||||
SnapCurve::Line { a, b } => {
|
||||
let l = cadcraft_geom::Line::new(a, b);
|
||||
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
|
||||
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
|
||||
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }));
|
||||
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
|
||||
continue;
|
||||
}
|
||||
let modes: &[(u32, &'static str)] = match curve {
|
||||
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
|
||||
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
|
||||
};
|
||||
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
|
||||
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
|
||||
}
|
||||
}
|
||||
best.map(|(_, h)| h)
|
||||
hits
|
||||
}
|
||||
|
||||
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
|
||||
@@ -1121,6 +1188,23 @@ mod tests {
|
||||
assert_eq!(h.name, "Intersection");
|
||||
}
|
||||
|
||||
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
|
||||
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
|
||||
/// picks.
|
||||
#[test]
|
||||
fn osnap_all_ranks_every_candidate() {
|
||||
let d = drawing();
|
||||
let modes = mode::END | mode::MID | mode::INT | mode::NEA;
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
|
||||
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
|
||||
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
|
||||
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
|
||||
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
|
||||
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
|
||||
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_quadrant_tangent() {
|
||||
let d = drawing();
|
||||
|
||||
@@ -317,6 +317,23 @@ fn tolerance_justification_angular_zeros_and_arc_symbol() {
|
||||
assert_eq!(dim_lines(&g1).len(), dim_lines(&g2).len() + 1, "the symbol drawn over the text");
|
||||
}
|
||||
|
||||
/// DIMPOST frames the angle too, as AutoCAD 2026 does to its own angular dimensions (#1653).
|
||||
#[test]
|
||||
fn dimpost_applies_to_angular_dimensions() {
|
||||
let mut s = Session::new();
|
||||
set(&mut s, "DIMPOST", json!("<> m"));
|
||||
set(&mut s, "DIMADEC", json!(1));
|
||||
// Vertex and two points.
|
||||
s.execute("dimangular", &json!({ "vertex": [0, 0], "p1": [10, 0], "p2": [0, 10], "at": [3, 3] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "90.0° m");
|
||||
// Two lines picked: the same suffix.
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [5, 8.660254037844387]] })).unwrap();
|
||||
let h: Vec<String> = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).map(|e| e.handle.hex()).collect();
|
||||
s.execute("dimangular", &json!({ "lines": h, "at": [4, 1] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "60.0° m");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linetypes_and_lineweights_of_dimension_and_extension_lines() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! HATCHGENERATEBOUNDARY (#2801): closed polylines around existing hatches, which stay as they are.
|
||||
|
||||
use cadcraft_engine::doc::{EntityKind, Handle, Hatch, LwPolyline};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn hatch(s: &Session, h: &str) -> Hatch {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::Hatch(x) => x.clone(),
|
||||
k => panic!("not a hatch: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn poly(s: &Session, h: &str) -> LwPolyline {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::LwPolyline(p) => p.clone(),
|
||||
k => panic!("not a polyline: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(v: &Value) -> String {
|
||||
v["handle"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn handles(v: &Value) -> Vec<String> {
|
||||
v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String {
|
||||
handle(&s.execute("rectang", &json!({ "p1": a, "p2": b })).unwrap())
|
||||
}
|
||||
|
||||
fn count(s: &Session) -> usize {
|
||||
s.doc().unwrap().model.iter().count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generates_a_closed_polyline_around_a_hatch_without_its_outline() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()] })).unwrap());
|
||||
s.execute("erase", &json!({ "handles": [r] })).unwrap();
|
||||
let before = hatch(&s, &h);
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
|
||||
let new = handles(&v);
|
||||
assert_eq!(new.len(), 1);
|
||||
let p = poly(&s, &new[0]);
|
||||
assert!(p.closed);
|
||||
assert_eq!(p.vertices, before.loops[0].vertices);
|
||||
assert_eq!(hatch(&s, &h), before, "the hatch is not changed");
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert_eq!(count(&s), 1, "one undo step removes what was generated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn islands_get_their_own_polylines() {
|
||||
let mut s = Session::new();
|
||||
rect(&mut s, [0.0, 0.0], [20.0, 20.0]);
|
||||
rect(&mut s, [5.0, 5.0], [10.0, 10.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "points": [[2, 2]] })).unwrap());
|
||||
assert_eq!(hatch(&s, &h).loops.len(), 2);
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_selected_hatch_gets_its_boundary() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let b = rect(&mut s, [10.0, 0.0], [14.0, 2.0]);
|
||||
let ha = handle(&s.execute("hatch", &json!({ "handles": [a] })).unwrap());
|
||||
let hb = handle(&s.execute("hatch", &json!({ "handles": [b] })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [ha, hb] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hatch_named_twice_gets_one_boundary() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone(), h] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_associative_hatch_stays_linked_to_its_own_boundary() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()], "associative": true })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
|
||||
let p = handles(&v)[0].clone();
|
||||
// Moving the generated polyline leaves the hatch where it is.
|
||||
s.execute("move", &json!({ "handles": [p], "delta": [0, 10] })).unwrap();
|
||||
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.y, 0.0);
|
||||
// Moving the original rectangle still moves the hatch.
|
||||
s.execute("move", &json!({ "handles": [r], "delta": [10, 0] })).unwrap();
|
||||
assert!(hatch(&s, &h).associative);
|
||||
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boundaries_keep_the_hatch_elevation() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
x.elevation = 300.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
assert_eq!(poly(&s, &handles(&v)[0]).elevation, 300.0);
|
||||
}
|
||||
|
||||
/// A mirrored hatch (normal 0,0,-1, as exploding a mirrored block makes) at elevation 300 lies at
|
||||
/// world Z -300; its boundary, facing up, goes there too, not to +300.
|
||||
#[test]
|
||||
fn a_mirrored_hatchs_boundary_keeps_its_world_height() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
e.common.extrusion = cadcraft_engine::geom::Vec3::new(0.0, 0.0, -1.0);
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
x.elevation = 300.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
let new = Handle::parse_hex(&handles(&v)[0]).unwrap();
|
||||
let e = s.doc().unwrap().entity(new).unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
|
||||
assert_eq!(e.common.extrusion.z.signum() * p.elevation, -300.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_hatch_in_another_space_and_adds_nothing() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
let before = s.doc().unwrap().entity_count();
|
||||
let e = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap_err();
|
||||
assert!(e.to_string().contains("not in the current space"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().entity_count(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_more_boundaries_than_the_limit_and_adds_nothing() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
// One hatch with more loops than one call may turn into polylines.
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
let l = x.loops[0].clone();
|
||||
x.loops = vec![l; 10_001];
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let before = count(&s);
|
||||
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).is_err());
|
||||
assert_eq!(count(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_a_hatch() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [r] })).is_err());
|
||||
assert_eq!(count(&s), 1, "nothing is added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_at_once_on_selected_hatches() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.set_selection(vec![Handle::parse_hex(&h).unwrap()]);
|
||||
s.start("hatchgenerateboundary").unwrap();
|
||||
assert!(s.current_prompt().is_none(), "a pickfirst selection needs no prompt");
|
||||
assert_eq!(count(&s), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asks_for_hatches_without_a_selection() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.set_selection(Vec::new());
|
||||
s.start("hatchgenerateboundary").unwrap();
|
||||
assert!(s.current_prompt().is_some());
|
||||
s.input(Input::Pick(vec![Handle::parse_hex(&h).unwrap()])).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert_eq!(count(&s), 3);
|
||||
}
|
||||
@@ -68,6 +68,7 @@ mod group_selection;
|
||||
mod groups;
|
||||
mod hatch_assoc;
|
||||
mod hatch_dialog_helpers;
|
||||
mod hatch_generate_boundary;
|
||||
mod hatch_numeric_validation;
|
||||
mod hatch_options;
|
||||
mod helix;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -278,6 +278,46 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
|
||||
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
|
||||
}
|
||||
|
||||
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
|
||||
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
|
||||
#[test]
|
||||
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
|
||||
let (mut d, paper) = drawing();
|
||||
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
|
||||
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
|
||||
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
|
||||
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
|
||||
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
|
||||
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
|
||||
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
|
||||
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
|
||||
assert!(
|
||||
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
|
||||
"Tab reaches the viewport's endpoint: {all:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Overlapping viewports can show different model points at one paper point; Tab offers each,
|
||||
/// since DIST measures in the model units of the viewport picked.
|
||||
#[test]
|
||||
fn overlapping_viewports_each_offer_their_model_point() {
|
||||
let (mut d, paper) = drawing();
|
||||
// This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0).
|
||||
edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0));
|
||||
let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind {
|
||||
EntityKind::Viewport(vp) => vp.clone(),
|
||||
_ => panic!("viewport fixture"),
|
||||
};
|
||||
vp.view_center = Vec2::new(0.0, 0.0);
|
||||
vp.id = 3;
|
||||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false);
|
||||
let mut models: Vec<Vec2> =
|
||||
all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect();
|
||||
models.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewport_frozen_layers_do_not_hide_paper_space_geometry() {
|
||||
let (mut d, paper) = drawing();
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! What a DXF before 2007 leaves out for its proxies' string streams, counted by the real DXF
|
||||
//! writer (#3229): only what 2007 would keep, from the drawing the command writes. In its own
|
||||
//! test binary because it installs the real io hooks for the whole process.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_proxies_lost, set_write_as};
|
||||
use cadcraft_engine::doc::Drawing;
|
||||
use serde_json::{Value, json};
|
||||
#[path = "support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
/// The real reader and writer, and the real proxy-loss count.
|
||||
fn install() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
set_write_as(|d, name, o: &SaveAs| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
}
|
||||
|
||||
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
|
||||
fn proxy(handle: &str, owner: &str, strings: &str, class: &str) -> Vec<(String, String)> {
|
||||
let p = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
vec![
|
||||
p("0", "ACAD_PROXY_ENTITY"),
|
||||
p("5", handle),
|
||||
p("330", owner),
|
||||
p("100", "AcDbEntity"),
|
||||
p("8", "0"),
|
||||
p("100", "AcDbProxyEntity"),
|
||||
p("90", "498"),
|
||||
p("91", class),
|
||||
p("95", "393245"),
|
||||
p("70", "0"),
|
||||
p("162", strings),
|
||||
p("161", "16"),
|
||||
p("310", "AABB"),
|
||||
]
|
||||
}
|
||||
|
||||
fn pairs(text: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines.chunks(2).map(|c| (c[0].trim().to_string(), c.get(1).map_or(String::new(), |v| v.trim().to_string()))).collect()
|
||||
}
|
||||
|
||||
/// A drawing with `$ACADVER` `acadver` read from a DXF holding the class WIDGETX and, in model
|
||||
/// space, the proxies `entities` gives (each from the model space block record's handle).
|
||||
fn drawing(acadver: &str, entities: impl Fn(&str) -> Vec<Vec<(String, String)>>) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", "AC1024");
|
||||
let text = String::from_utf8(cadcraft_io::write(&d, "p.dxf").unwrap()).unwrap();
|
||||
let mut p = pairs(&text);
|
||||
let g = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
let classes = p.iter().position(|q| q.0 == "2" && q.1 == "CLASSES").unwrap() + 1;
|
||||
let class =
|
||||
[g("0", "CLASS"), g("1", "WIDGETX"), g("2", "AcDbWidgetX"), g("3", "ObjectDBX Classes"), g("90", "4095"), g("280", "0"), g("281", "1")];
|
||||
p.splice(classes..classes, class);
|
||||
// The model space block record: the owner of model space entities.
|
||||
let record_end = |i: usize| i + 1 + p[i + 1..].iter().position(|q| q.0 == "0").unwrap_or(p.len() - i - 1);
|
||||
let ms = (0..p.len())
|
||||
.filter(|&i| p[i].0 == "0" && p[i].1 == "BLOCK_RECORD")
|
||||
.find(|&i| p[i..record_end(i)].iter().any(|q| q.0 == "2" && q.1.eq_ignore_ascii_case("*Model_Space")))
|
||||
.unwrap();
|
||||
let owner = p[ms..].iter().find(|q| q.0 == "5").unwrap().1.clone();
|
||||
let ents = p.iter().position(|q| q.0 == "2" && q.1 == "ENTITIES").unwrap();
|
||||
let end = ents + p[ents..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap();
|
||||
p.splice(end..end, entities(&owner).into_iter().flatten());
|
||||
let bytes: String = p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect();
|
||||
let mut d = cadcraft_io::read(bytes.as_bytes(), "p.dxf").unwrap();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d
|
||||
}
|
||||
|
||||
/// Two proxies with string streams, one whose class number names no class (no version writes
|
||||
/// it), and one without: before 2007 only the first one is lost to the string stream.
|
||||
fn three_proxies(owner: &str) -> Vec<Vec<(String, String)>> {
|
||||
vec![proxy("AAA1", owner, "8", "500"), proxy("AAA2", owner, "8", "777"), proxy("AAA3", owner, "0", "500")]
|
||||
}
|
||||
|
||||
fn not_saved(r: &Value) -> Value {
|
||||
r.get("notSaved").cloned().unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_no_version_writes_is_not_reported() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let path = dir.path_str("out.dxf");
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "{:?}", s.log);
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2007 })).unwrap();
|
||||
assert_eq!(not_saved(&r), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_reports_the_drawing_it_writes() {
|
||||
// In the Block Editor EXPORT writes the block, which holds no proxy: nothing is lost.
|
||||
install();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }));
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let line = s.execute("entities", &json!({ "type": "LINE" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
|
||||
s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [line], "keep": "convert" })).unwrap();
|
||||
s.execute("bedit", &json!({ "name": "B" })).unwrap();
|
||||
let n = s.log.len();
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(not_saved(&r), Value::Null, "{:?}", &s.log[n..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reference_edit_working_copy_is_not_counted_twice() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", |o| vec![proxy("AAA1", o, "8", "500")]), "proxy.dxf", None);
|
||||
s.execute("block", &json!({ "name": "W", "base": [0, 0], "handles": ["AAA1"], "keep": "convert" })).unwrap();
|
||||
let ins = s.execute("entities", &json!({ "type": "INSERT" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
|
||||
let path = dir.path_str("before.dxf");
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "in the block");
|
||||
s.execute("refedit", &json!({ "handle": ins })).unwrap();
|
||||
// Saves wait for REFCLOSE; the QSAVE question and `document.bytes` count the committed drawing.
|
||||
let r = s.execute("document.bytes", &json!({ "format": "dxf", "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "the working copy isn't written");
|
||||
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&s, "during.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_wblock_of_the_whole_drawing_reports_a_pre_2007_dxf() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let path = dir.path_str("whole.dxf").replace('\\', "/");
|
||||
s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"\" \"*\")")).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(std::path::Path::new(&path).exists());
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.ends_with("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Kept render settings are in the form of the file they were read from, whatever the drawing's
|
||||
//! `$ACADVER` says after a SAVEAS to another version: saving a 2018 drawing down to 2000 and back
|
||||
//! up to 2018 writes the class version the 2018 file had, not one higher (which BricsCAD refuses,
|
||||
//! #907).
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as};
|
||||
use serde_json::json;
|
||||
|
||||
/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the
|
||||
/// 2013+ form).
|
||||
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
|
||||
0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\
|
||||
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
/// The `AcDbRenderSettings` class version in a written DXF.
|
||||
fn class_version(path: &std::path::Path) -> Option<i64> {
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?;
|
||||
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
|
||||
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saveas_down_and_back_up_keeps_the_render_settings_class_version() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-render-settings-saveas-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "render.dxf", None);
|
||||
let save = |s: &mut Session, name: &str, version: &str| {
|
||||
let path = dir.join(name);
|
||||
s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": version })).unwrap();
|
||||
class_version(&path)
|
||||
};
|
||||
|
||||
assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read");
|
||||
assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower");
|
||||
s.execute("qsave", &json!({})).unwrap();
|
||||
assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form");
|
||||
assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -268,19 +268,27 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
|
||||
assert_eq!(r["notSaved"], json!({ "REGION": 1 }));
|
||||
}
|
||||
|
||||
/// A DWG before 2013 writes a solid's SAT text as it is, so a save there doesn't list a solid that
|
||||
/// holds it; from 2013 the geometry must be in the data store and SAT text alone is lost, so the
|
||||
/// save lists it. A solid with neither is always listed (#2334).
|
||||
/// A DWG before 2013 writes a solid's SAT text of ACIS 7.0 and later, so a save there doesn't list
|
||||
/// a solid that holds it; from 2013 the geometry must be in the data store and SAT text alone is
|
||||
/// lost, so the save lists it. Older SAT (ACIS 4.0) and a solid with neither are always listed
|
||||
/// (#2334).
|
||||
#[test]
|
||||
fn a_dwg_keeps_sat_text_solids_only_before_2013() {
|
||||
use cadcraft_engine::cmd::file::{Version, not_saved_as};
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags });
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 1 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "700 0 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 1)].into_iter().collect(), "2010 keeps the SAT-text solid");
|
||||
assert_eq!(not_saved_as(&d, Version::R2018), [("3DSOLID".to_string(), 2)].into_iter().collect(), "2018 loses it");
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 85 1 0")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "ACIS 4.0 SAT is listed");
|
||||
// The same versions encoded, as a DXF before 2013 holds them: 700 is kept, 400 is listed.
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "hoo o n o")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "encoded ACIS 7.0 SAT is kept");
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "koo gj n o")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 3)].into_iter().collect(), "encoded ACIS 4.0 SAT is listed");
|
||||
}
|
||||
|
||||
/// The DWG bridge writes OLE objects (`ole2frame_roundtrip` in the io tests), so saving one as
|
||||
@@ -302,3 +310,109 @@ fn ole_objects_are_not_reported() {
|
||||
assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1), ("ole2frame".to_string(), 1)].into_iter().collect(), "{v:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A solid whose geometry only the data store keeps (read from a 2013+ file) has nothing to write
|
||||
/// to a DXF of 2010 or earlier, which has no data store: the save leaves it out and says so, and
|
||||
/// the interactive save knows it beforehand; 2013 and later keep it (#2334).
|
||||
#[test]
|
||||
fn saving_data_store_solids_as_dxf_2010_reports_them() {
|
||||
use cadcraft_engine::cmd::file::loss_on_save;
|
||||
use cadcraft_engine::doc::foreign::Foreign;
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", "AC1032");
|
||||
let h = d.add(&Space::Model, Common::default(), unknown("3DSOLID")).unwrap();
|
||||
let record = vec![
|
||||
RawTag { code: 0, value: "ACDSRECORD".into() },
|
||||
RawTag { code: 320, value: h.hex() },
|
||||
RawTag { code: 2, value: "ASM_Data".into() },
|
||||
RawTag { code: 310, value: "00".into() },
|
||||
];
|
||||
d.foreign = std::sync::Arc::new(Foreign { data_store: record, ..Foreign::default() });
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "solid.dxf", None);
|
||||
assert!(loss_on_save(&s, "solid.dxf").is_empty(), "2018 keeps it");
|
||||
|
||||
let path = std::env::temp_dir().join(format!("cadcraft-ds-note-{}.dxf", std::process::id()));
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2010 })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "3DSOLID": 1 }));
|
||||
assert!(s.log.iter().any(|l| l.contains("2010 and earlier have no data store") && l.contains("1 3DSOLID")), "{:?}", s.log);
|
||||
assert_eq!(loss_on_save(&s, "solid.dxf"), [("3DSOLID".to_string(), 1)].into_iter().collect(), "now a 2010 drawing");
|
||||
|
||||
let n = s.log.len();
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2018 })).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(r.get("notSaved").is_none() && s.log.len() == n);
|
||||
}
|
||||
|
||||
/// A proxy entity (as a 2010 file has it) whose string stream is `strings` long (group 162).
|
||||
fn proxy_entity(strings: &str) -> EntityKind {
|
||||
let tags = [(8, "0"), (100, "AcDbProxyEntity"), (90, "498"), (91, "500"), (162, strings), (161, "16"), (310, "AABB")];
|
||||
EntityKind::Unknown(Unknown {
|
||||
dxf_type: "ACAD_PROXY_ENTITY".into(),
|
||||
tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A DXF before 2007 has no form for a proxy's separate string stream: the writer leaves such a
|
||||
/// proxy out, and the save says so instead of dropping it silently (#3229).
|
||||
#[test]
|
||||
fn a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
// SAVEAS at a chosen version goes through this hook (each test may run in its own process).
|
||||
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "proxy.dxf", None);
|
||||
let path = std::env::temp_dir().join(format!("cadcraft-proxy-r2000-{}.dxf", std::process::id()));
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2000 })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2007 })).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(r.get("notSaved").is_none(), "2007 keeps it");
|
||||
}
|
||||
|
||||
/// The interactive QSAVE asks before a pre-2007 DXF replaces a file and leaves such proxies out,
|
||||
/// with the same list (#3229).
|
||||
#[test]
|
||||
fn a_pre_2007_dxf_proxy_loss_is_known_before_saving() {
|
||||
use cadcraft_engine::cmd::file::loss_on_save;
|
||||
let drawing = |acadver: &str| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d
|
||||
};
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
|
||||
assert_eq!(loss_on_save(&s, "proxy.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
|
||||
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
|
||||
assert!(loss_on_save(&s, "proxy.dxf").is_empty(), "2007 keeps it");
|
||||
}
|
||||
|
||||
/// EXPORT writes a DXF at the drawing's own version: before 2007 it leaves the same proxies out
|
||||
/// and says so, like a save (#3229).
|
||||
#[test]
|
||||
fn exporting_a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
let drawing = |acadver: &str| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
|
||||
d
|
||||
};
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert!(r.get("notSaved").is_none(), "2007 keeps it");
|
||||
}
|
||||
|
||||
@@ -477,6 +477,18 @@ mod tests {
|
||||
ttf::fallback_for('\u{0E01}').filter(|f| ['\u{0E14}', '\u{0E34}', '\u{0E4C}', '\u{0E33}', '\u{0E10}'].iter().all(|c| f.has_glyph(*c)))
|
||||
}
|
||||
|
||||
/// A Thai face's letters are measured in ems: ก has neither ascender nor descender, ไ rises
|
||||
/// above it, and a space or an unmapped character has no height.
|
||||
#[test]
|
||||
fn thai_glyph_heights_are_measured_in_ems() {
|
||||
let Some(face) = thai_face() else { return };
|
||||
let ko = face.glyph_height('ก').unwrap_or_default();
|
||||
assert!((0.2..1.0).contains(&ko), "ก is {ko} em");
|
||||
assert!(face.glyph_height('ไ').is_some_and(|h| h > ko), "ไ is taller than ก");
|
||||
assert_eq!(face.glyph_height(' '), None);
|
||||
assert_eq!(face.glyph_height('\u{10fffd}'), None);
|
||||
}
|
||||
|
||||
/// Lowest point of the glyph that shows `c`.
|
||||
fn bottom_of(sh: &Shaped, c: char) -> Option<f64> {
|
||||
let t = sh.text.iter().find(|t| t.ch == c)?;
|
||||
|
||||
@@ -95,6 +95,17 @@ impl Face {
|
||||
Some(s.chars().filter(|c| !c.is_control()).take(80).collect::<String>()).filter(|s| !s.trim().is_empty())
|
||||
})
|
||||
}
|
||||
/// How tall the glyph of `c` is, from its lowest to its highest point, in ems: `None` when the
|
||||
/// face doesn't map `c` or its glyph has no outline (a space, or one too big to keep).
|
||||
pub fn glyph_height(&self, c: char) -> Option<f64> {
|
||||
let g = glyph(self, c);
|
||||
if !g.mapped {
|
||||
return None;
|
||||
}
|
||||
let (low, high) = g.contours.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), p| (low.min(p.y), high.max(p.y)));
|
||||
let height = (high - low) / f64::from(UPEM);
|
||||
(height.is_finite() && height > 0.0).then_some(height)
|
||||
}
|
||||
|
||||
/// The glyph ids the face's character map gives `chars` (`None` for an unmapped one).
|
||||
pub(crate) fn glyph_ids(&self, chars: &[char]) -> Vec<Option<u32>> {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//! The angles of a hatch's elliptic boundary edges in the DXF a DWG is read through.
|
||||
//!
|
||||
//! A DWG holds an elliptic edge's start and end angles in radians, and so does the DXF the DWG
|
||||
//! decoder writes (groups 50 and 51 of an edge of type 3). DXF itself keeps them in degrees, which
|
||||
//! is how [`crate::dxf_read`] reads them: a circle stored as an elliptic edge with the end angle
|
||||
//! 6.2832 became an arc of 6.28 degrees, and the hatch covered the hole it should have left open.
|
||||
//! Only the DWG path needs this; a DXF file is read as written.
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
/// `dxf` with the start and end angles (groups 50 and 51) of every elliptic hatch edge (edge type
|
||||
/// 3, group 72) turned from radians to degrees. The text is handled as bytes: a drawing from
|
||||
/// before 2007 is written in its code page, which is not UTF-8, and every other byte is kept as it
|
||||
/// was. Binary DXF, and text with no such edge, come back as they were.
|
||||
pub(crate) fn elliptic_edge_degrees(dxf: Vec<u8>) -> Vec<u8> {
|
||||
if dxf.starts_with(b"AutoCAD Binary DXF") || !dxf.windows(5).any(|w| w == b"HATCH") {
|
||||
return dxf;
|
||||
}
|
||||
let mut out = Vec::with_capacity(dxf.len());
|
||||
let mut lines = dxf.split_inclusive(|b| *b == b'\n');
|
||||
let mut in_hatch = false;
|
||||
// After an elliptic edge's type, until the next edge or loop: the angles still to convert.
|
||||
let mut ellipse = false;
|
||||
let mut changed = false;
|
||||
while let Some(code_line) = lines.next() {
|
||||
let Some(value_line) = lines.next() else {
|
||||
out.extend_from_slice(code_line);
|
||||
break;
|
||||
};
|
||||
let code = code_line.trim_ascii();
|
||||
let value = value_line.trim_ascii();
|
||||
match code {
|
||||
b"0" => {
|
||||
in_hatch = value == b"HATCH";
|
||||
ellipse = false;
|
||||
}
|
||||
b"72" if in_hatch => ellipse = value == b"3",
|
||||
b"92" | b"97" if in_hatch => ellipse = false,
|
||||
b"50" | b"51" if in_hatch && ellipse => {
|
||||
if let Some(radians) = std::str::from_utf8(value).ok().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
|
||||
let ending = &value_line[value_line.trim_ascii_end().len()..];
|
||||
out.extend_from_slice(code_line);
|
||||
out.extend_from_slice(format!("{}", radians * 180.0 / PI).as_bytes());
|
||||
out.extend_from_slice(ending);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out.extend_from_slice(code_line);
|
||||
out.extend_from_slice(value_line);
|
||||
}
|
||||
if changed { out } else { dxf }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pairs(text: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
|
||||
}
|
||||
|
||||
const HATCH: &str = "0\r\nHATCH\r\n91\r\n1\r\n92\r\n1\r\n93\r\n2\r\n72\r\n3\r\n10\r\n5.0\r\n20\r\n6.0\r\n11\r\n-55.5\r\n21\r\n0.0\r\n40\r\n1.0\r\n50\r\n0.0\r\n51\r\n6.283185307179586\r\n73\r\n1\r\n72\r\n1\r\n10\r\n1.0\r\n20\r\n2.0\r\n11\r\n3.0\r\n21\r\n4.0\r\n50\r\n7.0\r\n0\r\nLINE\r\n50\r\n9.0\r\n";
|
||||
|
||||
#[test]
|
||||
fn an_elliptic_edge_gets_its_angles_in_degrees_and_nothing_else_changes() {
|
||||
let out = String::from_utf8(elliptic_edge_degrees(HATCH.as_bytes().to_vec())).unwrap();
|
||||
let p = pairs(&out.replace("\r\n", "\n"));
|
||||
let value = |code: &str, n: usize| p.iter().filter(|(c, _)| c == code).nth(n).map(|(_, v)| v.parse::<f64>().unwrap());
|
||||
assert!((value("51", 0).unwrap() - 360.0).abs() < 1e-9);
|
||||
assert_eq!(value("50", 0), Some(0.0));
|
||||
// A line edge's 50 and another entity's are left alone, as is the line ending.
|
||||
assert_eq!(value("50", 1), Some(7.0));
|
||||
assert_eq!(value("50", 2), Some(9.0));
|
||||
assert!(out.contains("\r\n") && !out.replace("\r\n", "").contains('\r'));
|
||||
}
|
||||
|
||||
/// A drawing from before 2007 is written in its code page: an accented letter is one byte that
|
||||
/// is not valid UTF-8, and it must not stop the angles being converted or change.
|
||||
#[test]
|
||||
fn a_code_page_drawing_still_has_its_angles_converted() {
|
||||
let mut dxf = b"0\r\nTEXT\r\n1\r\ncaf".to_vec();
|
||||
dxf.push(0xE9);
|
||||
dxf.extend_from_slice(b"\r\n");
|
||||
dxf.extend_from_slice(HATCH.as_bytes());
|
||||
let out = elliptic_edge_degrees(dxf.clone());
|
||||
assert!(std::str::from_utf8(&dxf).is_err(), "the input is not UTF-8");
|
||||
assert!(out.windows(4).any(|w| w == b"caf\xE9"), "the accented byte is kept");
|
||||
let text: String = out.iter().map(|b| char::from(*b)).collect();
|
||||
assert!(text.contains("51\r\n360"), "the end angle is 360 degrees: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_without_a_hatch_ellipse_comes_back_untouched() {
|
||||
let dxf = b"0\nLINE\n50\n1.5\n".to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(dxf.clone()), dxf);
|
||||
let binary = b"AutoCAD Binary DXF\r\n\x1a\x00HATCH".to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(binary.clone()), binary);
|
||||
// A hatch with no elliptic edge is left as it is.
|
||||
let plain = "0\nHATCH\n72\n1\n50\n2.0\n".as_bytes().to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(plain.clone()), plain);
|
||||
}
|
||||
}
|
||||
+179
-13
@@ -16,9 +16,9 @@ use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number};
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
||||
use craft_dxf::{SectionRef, Tag};
|
||||
use craft_dxf::{SectionRef, Tag, Version};
|
||||
|
||||
/// Named object dictionary entries CADCraft writes itself from its model (plus every key that
|
||||
/// starts with `CADCRAFT`): they are read into the model, not kept raw. A change that starts
|
||||
@@ -457,6 +457,10 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
if !f.is_empty() {
|
||||
f.version = file_version(secs);
|
||||
}
|
||||
// Added after the version: registered applications alone are no kept objects whose groups
|
||||
// the DWG writer must read as the file's version, and nearly every file has some (ACAD).
|
||||
let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string());
|
||||
f.appids = appids.take(MAX_OBJECTS).collect();
|
||||
// The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`).
|
||||
f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect();
|
||||
if !f.is_empty() || !f.handles.is_empty() {
|
||||
@@ -686,6 +690,102 @@ pub(crate) fn data_store(tags: &mut Vec<Tag>, d: &Drawing, modern: bool) {
|
||||
tags.splice(at..at, out);
|
||||
}
|
||||
|
||||
/// Most constraint nodes, and connections per node, looked at in one constraint group.
|
||||
const MAX_CONSTRAINT_NODES: usize = 100_000;
|
||||
|
||||
/// Put the status of every node of the kept 2D constraint groups (`ACDBASSOC2DCONSTRAINTGROUP`)
|
||||
/// where a reader of the version the text is read as expects it: AutoCAD 2013 and later
|
||||
/// (`modern`) write it after the node's connections, earlier versions right after its id. The
|
||||
/// groups are kept as read, so a 2013+ drawing written in an older version's form had them in the
|
||||
/// wrong order, and its reader took every node's status from somewhere else: AutoCAD refused the
|
||||
/// DWG the bridge made from it ("Error Decrypting Data"). A group whose nodes can't all be found
|
||||
/// is left as it is.
|
||||
pub(crate) fn constraint_node_order(tags: &mut [Tag], modern: bool) {
|
||||
let mut i = 0;
|
||||
while i < tags.len() {
|
||||
let end = tags.iter().skip(i + 1).position(|t| t.code == 0).map_or(tags.len(), |k| i + 1 + k);
|
||||
if tags.get(i).is_some_and(|t| t.code == 0 && t.str().trim().eq_ignore_ascii_case("ACDBASSOC2DCONSTRAINTGROUP"))
|
||||
&& let Some(rec) = tags.get_mut(i + 1..end)
|
||||
{
|
||||
constraint_group_order(rec, modern);
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
}
|
||||
|
||||
/// [`constraint_node_order`] for one group's groups after its type.
|
||||
fn constraint_group_order(rec: &mut [Tag], modern: bool) {
|
||||
let Some(start) = rec.iter().position(|t| t.code == 100 && t.str().trim().eq_ignore_ascii_case("AcDbAssoc2dConstraintGroup")) else {
|
||||
return;
|
||||
};
|
||||
let end = rec.iter().skip(start + 1).position(|t| t.code == 100 || t.code >= 1000).map_or(rec.len(), |k| start + 1 + k);
|
||||
let Some(sec) = rec.get_mut(start + 1..end) else { return };
|
||||
let Some(nodes) = constraint_nodes(sec) else { return };
|
||||
for (at, len, old) in nodes {
|
||||
// Old order: id, status, count, connections; modern: id, count, connections, status.
|
||||
if let Some(head) = sec.get_mut(at + 1..at + len) {
|
||||
match (old, modern) {
|
||||
(true, true) => head.rotate_left(1),
|
||||
(false, false) => head.rotate_right(1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where each non-root node of a constraint group section starts: (index of its id, length of its
|
||||
/// id, status and connections, whether its status comes right after the id). `None` unless every
|
||||
/// node the group lists is found.
|
||||
fn constraint_nodes(sec: &[Tag]) -> Option<Vec<(usize, usize, bool)>> {
|
||||
let int = |p: usize, code: i32| sec.get(p).filter(|t| t.code == code).and_then(|t| t.str().trim().parse::<i64>().ok());
|
||||
let count = |p: usize| int(p, 90).and_then(|n| usize::try_from(n).ok()).filter(|n| *n <= MAX_CONSTRAINT_NODES);
|
||||
// Version, flag and work plane, then the dependency and the actions.
|
||||
let mut p = sec.iter().position(|t| t.code == 360)? + 1;
|
||||
p += count(p)? + 1;
|
||||
// The next node id, then the root node: id, connections, status (290).
|
||||
int(p, 90)?;
|
||||
int(p + 1, 90)?;
|
||||
p += count(p + 2)? + 3;
|
||||
int(p, 290)?;
|
||||
p += 1;
|
||||
// The registry: class name and id of each node.
|
||||
let n = count(p)?;
|
||||
p += 1;
|
||||
let mut ids = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
sec.get(p).filter(|t| t.code == 1)?;
|
||||
ids.push(int(p + 1, 90)?);
|
||||
p += 2;
|
||||
}
|
||||
let known: HashSet<i64> = ids.iter().copied().collect();
|
||||
// Groups looked at while searching for headers, capped so a hostile group can't take long.
|
||||
let budget = std::cell::Cell::new(MAX_CONSTRAINT_NODES.saturating_mul(100));
|
||||
// A node header at `q`: its length and whether it is in the old order. Connections are ids of
|
||||
// nodes (or of the root, 0), which keeps a node's data from passing for the next header.
|
||||
let header = |q: usize, id: i64| -> Option<(usize, bool)> {
|
||||
int(q, 90).filter(|v| *v == id)?;
|
||||
let old = sec.get(q + 1)?.code == 70;
|
||||
let c = q + 1 + usize::from(old);
|
||||
let n = count(c).filter(|n| *n <= known.len())?;
|
||||
budget.set(budget.get().checked_sub(n + 1)?);
|
||||
for k in 0..n {
|
||||
int(c + 1 + k, 90).filter(|v| *v == 0 || known.contains(v))?;
|
||||
}
|
||||
if !old {
|
||||
int(c + 1 + n, 70)?;
|
||||
}
|
||||
Some((n + 3, old))
|
||||
};
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
let at = (p..sec.len()).find(|q| header(*q, id).is_some())?;
|
||||
let (len, old) = header(at, id)?;
|
||||
out.push((at, len, old));
|
||||
p = at + len;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Drop a dictionary's modelled entries (key and handle) from its groups.
|
||||
fn strip_entries(tags: &mut Vec<RawTag>) {
|
||||
let mut out = Vec::with_capacity(tags.len());
|
||||
@@ -941,13 +1041,61 @@ fn unknown_handles(d: &Drawing) -> HashSet<String> {
|
||||
all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect()
|
||||
}
|
||||
|
||||
/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store
|
||||
/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of
|
||||
/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one
|
||||
/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's
|
||||
/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test
|
||||
/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A
|
||||
/// kept object carries the form of the file it was read from ([`Foreign::version`], not the
|
||||
/// drawing's `$ACADVER`, which SAVEAS changes); written into a file read as another version, it
|
||||
/// takes that version's form. The DWG bridge's R2000 text is read as the version the kept objects
|
||||
/// came from (craft-dwg's `encode_kept_noted`), so there they stay as read (#907, #2471).
|
||||
///
|
||||
/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own
|
||||
/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version,
|
||||
/// stored the same in every file version, and is left as read.
|
||||
pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option<Version>, declared: Version) {
|
||||
let Some(source) = source.filter(|s| *s != declared) else { return };
|
||||
let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) };
|
||||
let (mut kind, mut in_base) = (String::new(), false);
|
||||
for t in tags.iter_mut() {
|
||||
match t.code {
|
||||
0 => {
|
||||
kind = up(&t.str());
|
||||
in_base = false;
|
||||
}
|
||||
100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => {
|
||||
in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings");
|
||||
}
|
||||
90 if in_base => {
|
||||
let rapid = kind == "RAPIDRTRENDERSETTINGS";
|
||||
let logical = t.i64().saturating_sub(shift(rapid, source));
|
||||
*t = Tag::i(90, logical.saturating_add(shift(rapid, declared)));
|
||||
in_base = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the drawing's foreign data back into a written file's tags (see the module comment).
|
||||
pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle, Vec<String>>, modern: bool) {
|
||||
/// `strings`: whether the file has a form for a proxy's separate string stream (a DXF of 2007 or
|
||||
/// later, or the DWG bridge); without one such a proxy is left out (#3229). Returns the foreign
|
||||
/// objects written, by their handles in the drawing (the file gives them new ones).
|
||||
pub(crate) fn finish(
|
||||
tags: &mut Vec<Tag>,
|
||||
d: &Drawing,
|
||||
reactors: &HashMap<Handle, Vec<String>>,
|
||||
modern: bool,
|
||||
target_modern: bool,
|
||||
strings: bool,
|
||||
) -> HashSet<Handle> {
|
||||
let f = d.foreign.as_ref();
|
||||
let unknown = unknown_handles(d);
|
||||
let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect();
|
||||
if f.is_empty() && unknown.is_empty() && xd.is_empty() {
|
||||
return;
|
||||
return HashSet::new();
|
||||
}
|
||||
let recs = written_records(tags);
|
||||
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
|
||||
@@ -970,14 +1118,21 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
numbers.entry(n).or_insert(500_i64.saturating_add(i64::try_from(i).unwrap_or(i64::MAX)));
|
||||
}
|
||||
let renumber = |old| proxy_class_number(f, &numbers, old);
|
||||
// A proxy is dropped when its class isn't written, or when its strings have no place here.
|
||||
let no_room = |t: &[(i32, &str)]| !strings && proxy_has_string_stream(t.iter().copied());
|
||||
// Entities of types CADCraft doesn't model, placed among the written ones.
|
||||
let mut planned = plan_unknown(d, &recs, tags, &roles, modern);
|
||||
let mut planned = plan_unknown(d, &recs, tags, &roles, modern, target_modern);
|
||||
for list in planned.values_mut() {
|
||||
list.retain_mut(|(_, t)| {
|
||||
if !t.first().is_some_and(|z| is_proxy(&z.str())) {
|
||||
return true;
|
||||
}
|
||||
let Some(n) = renumber(class_number(t.iter().map(|x| (x.code, x.str())))) else { return false };
|
||||
let groups: Vec<(i32, String)> = t.iter().map(|x| (x.code, x.str())).collect();
|
||||
let groups: Vec<(i32, &str)> = groups.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
if no_room(&groups) {
|
||||
return false;
|
||||
}
|
||||
let Some(n) = renumber(class_number(groups.iter().copied())) else { return false };
|
||||
set_class_number(t, n);
|
||||
true
|
||||
});
|
||||
@@ -1015,8 +1170,11 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
// Keep established live paths available to descendants during this pass as well.
|
||||
let mut alive_memo: HashMap<String, bool> = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect();
|
||||
let kept = |h: &str| kept.get(h) == Some(&true);
|
||||
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none())
|
||||
{
|
||||
let dropped = |o: &ForeignObject| {
|
||||
let groups: Vec<(i32, &str)> = o.tags.iter().map(|r| (r.code, r.value.as_str())).collect();
|
||||
no_room(&groups) || renumber(class_number(groups.iter().copied())).is_none()
|
||||
};
|
||||
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && dropped(o)) {
|
||||
alive_memo.insert(o.handle.hex(), false);
|
||||
}
|
||||
for o in &f.objects {
|
||||
@@ -1113,7 +1271,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
join_entries(&map, b, kept, &mut out);
|
||||
}
|
||||
}
|
||||
add_appids(&mut out);
|
||||
add_appids(&mut out, &f.appids);
|
||||
let top = max_handle(&out).saturating_add(1);
|
||||
if let Some(t) = seed_index(&out).and_then(|i| out.get_mut(i))
|
||||
&& Handle::parse_hex(&t.str()).is_none_or(|h| h.0 < top)
|
||||
@@ -1121,6 +1279,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
*t = Tag::s(5, format!("{top:X}"));
|
||||
}
|
||||
*tags = out;
|
||||
map.alive.keys().filter_map(|h| handle(h)).collect()
|
||||
}
|
||||
|
||||
/// Kept extension dictionaries of written records: those that go on a record without its own,
|
||||
@@ -1202,6 +1361,7 @@ fn plan_unknown(
|
||||
tags: &[Tag],
|
||||
roles: &HashMap<ForeignKey, String>,
|
||||
modern: bool,
|
||||
target_modern: bool,
|
||||
) -> HashMap<usize, Vec<(String, Vec<Tag>)>> {
|
||||
let stored = d.foreign.data_store_entities();
|
||||
let mut out: HashMap<usize, Vec<(String, Vec<Tag>)>> = HashMap::new();
|
||||
@@ -1241,7 +1401,9 @@ fn plan_unknown(
|
||||
for e in store.iter() {
|
||||
match &e.kind {
|
||||
EntityKind::Unknown(u) => {
|
||||
if modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored) {
|
||||
if (modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored))
|
||||
|| (!target_modern && cadcraft_doc::foreign::acis_left_out(u, e.handle, &stored, false))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let t = unknown_entity(u, e, &owner, paper);
|
||||
@@ -1435,9 +1597,13 @@ fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>)
|
||||
}
|
||||
}
|
||||
|
||||
/// APPID records for every application with xdata in the file, added to the APPID table.
|
||||
fn add_appids(out: &mut Vec<Tag>) {
|
||||
let used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
|
||||
/// APPID records for every application with xdata in the file and every one the file read had
|
||||
/// (`kept`), added to the APPID table.
|
||||
fn add_appids(out: &mut Vec<Tag>, kept: &[String]) {
|
||||
let mut used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
|
||||
for name in kept.iter().filter(|n| !n.is_empty()) {
|
||||
used.entry(up(name)).or_insert_with(|| name.clone());
|
||||
}
|
||||
let recs = written_records(out);
|
||||
let Some(table) = recs.iter().position(|r| {
|
||||
r.sec == "TABLES" && r.kind == "TABLE" && val(out.get(r.start + 1..r.end).unwrap_or(&[]), 2).is_some_and(|n| up(&n) == "APPID")
|
||||
|
||||
@@ -88,6 +88,7 @@ fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option<EntityKind> {
|
||||
// In a tilted plane: drawn as seen from above, at the vertices' mean height, its
|
||||
// vertices now plan coordinates.
|
||||
(verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0);
|
||||
thickness_along_z(c);
|
||||
c.extrusion = Vec3::Z;
|
||||
} else if c.extrusion.z < 0.0 {
|
||||
for v in &mut verts {
|
||||
@@ -577,7 +578,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
|
||||
break;
|
||||
}
|
||||
}
|
||||
let c = common(t);
|
||||
let mut c = common(t);
|
||||
let mut extra: Vec<EntityKind> = Vec::new();
|
||||
let k = if flags & 64 != 0 {
|
||||
// Face records that name a missing vertex (or fewer than three) are dropped: they draw
|
||||
@@ -599,13 +600,26 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
|
||||
} else if flags & 8 != 0 {
|
||||
EntityKind::Polyline3d(Polyline3d { points: pts.iter().map(|p| p.0).collect(), closed: flags & 1 != 0 })
|
||||
} else {
|
||||
// A 2D polyline's vertices are in its OCS: mirrored like LWPOLYLINE.
|
||||
let m = if c.extrusion.z < 0.0 { -1.0 } else { 1.0 };
|
||||
// A 2D polyline's vertices are in its OCS, at the elevation of the POLYLINE's own point:
|
||||
// in a tilted plane drawn as seen from above like LWPOLYLINE, else mirrored like it.
|
||||
let closed = flags & 1 != 0;
|
||||
let mut vertices: Vec<PolyVertex> = pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect();
|
||||
let mut elevation = t.p(10).z;
|
||||
if tilted(c.extrusion, run_points(&vertices, elevation, closed)) {
|
||||
(vertices, elevation) = plan_of_tilted(c.extrusion, elevation, &vertices, closed);
|
||||
thickness_along_z(&mut c);
|
||||
c.extrusion = Vec3::Z;
|
||||
} else if c.extrusion.z < 0.0 {
|
||||
for v in &mut vertices {
|
||||
v.p.x = -v.p.x;
|
||||
v.bulge = -v.bulge;
|
||||
}
|
||||
}
|
||||
EntityKind::LwPolyline(LwPolyline {
|
||||
vertices: pts.iter().map(|p| PolyVertex { p: Vec2::new(m * p.0.x, p.0.y), bulge: m * p.1, start_width: p.2, end_width: p.3 }).collect(),
|
||||
closed: flags & 1 != 0,
|
||||
vertices,
|
||||
closed,
|
||||
const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0),
|
||||
elevation: t.p(10).z,
|
||||
elevation,
|
||||
plinegen: flags & 128 != 0,
|
||||
})
|
||||
};
|
||||
@@ -714,3 +728,11 @@ fn helix(tags: &[Tag]) -> Helix {
|
||||
}
|
||||
.sanitized()
|
||||
}
|
||||
|
||||
/// A polyline drawn as seen from above gets the normal +Z: its thickness keeps the side of Z it
|
||||
/// extruded toward, which the normal it is losing said.
|
||||
fn thickness_along_z(c: &mut Common) {
|
||||
if c.extrusion.z < 0.0 {
|
||||
c.thickness = -c.thickness;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,6 +421,8 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
// Plot layout flags: 2 display plot styles, 4 centred, 16 standard scale (75 = 0: scaled
|
||||
// to fit), 128 lineweights.
|
||||
if let Some(flags) = t.i(70) {
|
||||
// Kept to be written back (a 16-bit group: only those bits).
|
||||
p.file_plot_flags = Some(flags & 0xFFFF);
|
||||
p.show_plot_styles = flags & 2 != 0;
|
||||
p.center = flags & 4 != 0;
|
||||
p.lineweights = flags & 128 != 0;
|
||||
@@ -432,6 +434,13 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
if let Some(s) = pos(ratio).or_else(|| pos(t.f(147))) {
|
||||
p.scale = s;
|
||||
}
|
||||
// A standard scale (flag 16, group 75 above 0: 0 is scaled to fit, the DXF Reference lists
|
||||
// 1 to 32), kept with the scale it stands for so a save can tell it was not changed.
|
||||
if t.i(70).is_some_and(|f| f & 16 != 0)
|
||||
&& let Some(code) = t.i(75).filter(|c| (1..=32).contains(c))
|
||||
{
|
||||
p.file_standard_scale = Some((code, p.scale));
|
||||
}
|
||||
p.plot_area = match t.i(74) {
|
||||
Some(0) => "display",
|
||||
Some(1) => "extents",
|
||||
|
||||
@@ -24,6 +24,8 @@ mod entity;
|
||||
mod header;
|
||||
mod layout;
|
||||
mod objects;
|
||||
mod proxy;
|
||||
pub use proxy::proxies_lost;
|
||||
mod sections;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -149,7 +151,16 @@ pub fn write(d: &Drawing) -> String {
|
||||
|
||||
/// The drawing's DXF tags, declaring `version` in `$ACADVER`.
|
||||
pub fn tags(d: &Drawing, version: Version) -> Vec<Tag> {
|
||||
tags_for(d, version, version, version < Version::R2004)
|
||||
tags_kept(d, version).0
|
||||
}
|
||||
|
||||
/// [`tags`], with the foreign objects the file keeps, by their handles in the drawing.
|
||||
fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::HashSet<cadcraft_doc::Handle>) {
|
||||
let (mut tags, kept) = sections::tags_kept_for(d, version, version, version < Version::R2004, false);
|
||||
// Kept proxies in this version's layout (#3229). Not for the DWG bridge, whose writer reads
|
||||
// them in the layout of the DWG they came from.
|
||||
proxy::proxy_layout(&mut tags, version);
|
||||
(tags, kept)
|
||||
}
|
||||
|
||||
/// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG
|
||||
|
||||
@@ -2,13 +2,15 @@ use super::{
|
||||
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
|
||||
};
|
||||
|
||||
/// What happens to the anonymous `*D` blocks read from a file (#495): a dimension that still
|
||||
/// names its block regenerates its geometry under that name, keeping the block's entity
|
||||
/// handles, and `*D` blocks nothing else references are not written again.
|
||||
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
|
||||
/// its block is written with that block, under its name, and `*D` blocks nothing else
|
||||
/// references are not written again. The block a dimension names may have any name: other
|
||||
/// programs don't always use `*D` (#3299).
|
||||
pub(super) struct DimBlockPlan {
|
||||
/// Dimension (model or paper space) → the read block whose name and handles it reuses.
|
||||
pub(super) reuse: HashMap<Handle, std::sync::Arc<Block>>,
|
||||
/// Upper-case names of `*D` blocks not written as ordinary blocks.
|
||||
/// Upper-case names of blocks not written as ordinary blocks: `*D` blocks and the blocks
|
||||
/// dimensions name, when nothing else uses them.
|
||||
pub(super) skip: std::collections::HashSet<String>,
|
||||
}
|
||||
|
||||
@@ -16,6 +18,12 @@ fn is_dim_block(name: &str) -> bool {
|
||||
name.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("*D"))
|
||||
}
|
||||
|
||||
/// The read block, not named `*D`, that a dimension block definition named `name` is written
|
||||
/// from (#3299): its record and block properties are written as read.
|
||||
pub(super) fn kept_named_dim_block<'a>(d: &'a Drawing, name: &str) -> Option<&'a Block> {
|
||||
d.block(name).filter(|_| !is_dim_block(name)).map(|b| b.as_ref())
|
||||
}
|
||||
|
||||
pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
|
||||
let spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect();
|
||||
// Block names other objects use: inserts and multileader contents anywhere, and dimensions
|
||||
@@ -35,12 +43,19 @@ pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
|
||||
for e in d.blocks.values().flat_map(|b| b.entities.iter()) {
|
||||
note(e, true, &mut used);
|
||||
}
|
||||
let skip = d.blocks.keys().filter(|n| is_dim_block(n)).map(|n| n.to_ascii_uppercase()).filter(|n| !used.contains(n)).collect();
|
||||
// Blocks the dimensions of model and paper space still name, whatever their names.
|
||||
let named: std::collections::HashSet<String> = spaces
|
||||
.iter()
|
||||
.flat_map(|s| s.iter())
|
||||
.filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { dm.block.as_ref().map(|n| n.to_ascii_uppercase()) } else { None })
|
||||
.collect();
|
||||
let skip =
|
||||
d.blocks.keys().map(|n| n.to_ascii_uppercase()).filter(|n| is_dim_block(n) || named.contains(n)).filter(|n| !used.contains(n)).collect();
|
||||
let mut plan = DimBlockPlan { reuse: HashMap::new(), skip };
|
||||
let mut claimed = std::collections::HashSet::new();
|
||||
for e in spaces.iter().flat_map(|s| s.iter()) {
|
||||
let EntityKind::Dimension(dm) = &e.kind else { continue };
|
||||
let Some(b) = dm.block.as_deref().filter(|n| is_dim_block(n)).and_then(|n| d.block(n)) else { continue };
|
||||
let Some(b) = dm.block.as_deref().and_then(|n| d.block(n)) else { continue };
|
||||
let key = b.name.to_ascii_uppercase();
|
||||
if plan.skip.contains(&key) && claimed.insert(key) {
|
||||
plan.reuse.insert(e.handle, b.clone());
|
||||
|
||||
@@ -108,7 +108,10 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
EntityKind::Line(l) => {
|
||||
w.s(0, "LINE");
|
||||
common(w, e, owner, paper, "AcDbLine");
|
||||
thickness(w, e);
|
||||
// Along the normal written with it (210 below), as read.
|
||||
if e.common.thickness != 0.0 {
|
||||
w.f(39, e.common.thickness);
|
||||
}
|
||||
w.p(10, l.a);
|
||||
w.p(11, l.b);
|
||||
extrusion(w, e);
|
||||
@@ -156,8 +159,13 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
if p.const_width > 0.0 {
|
||||
w.f(43, p.const_width);
|
||||
}
|
||||
if p.elevation != 0.0 {
|
||||
w.f(38, p.elevation);
|
||||
// The elevation runs along the polyline's normal, which isn't written: one facing down
|
||||
// Z is at the elevation's negative. That is exact for a normal of 0,0,-1 only; a tilted
|
||||
// one pointing partly down is flipped the same way (the reader brings tilted polylines
|
||||
// into plan with normal Z, so only other sources make one).
|
||||
let elevation = if e.common.extrusion.z < 0.0 { -p.elevation } else { p.elevation };
|
||||
if elevation != 0.0 {
|
||||
w.f(38, elevation);
|
||||
}
|
||||
thickness(w, e);
|
||||
for v in &p.vertices {
|
||||
@@ -603,14 +611,16 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a HATCH: its pattern name, solid and associative flags, its boundary loops, and the
|
||||
/// pattern angle, scale and double flag (written for solid hatches too). Pattern lines are written
|
||||
/// only for non-solid hatches.
|
||||
/// Writes a HATCH: its pattern name, solid and associative flags, its boundary loops, and for a
|
||||
/// pattern fill its angle, scale, double flag and pattern lines.
|
||||
fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, _cx: &Ctx) {
|
||||
if let EntityKind::Hatch(h) = &e.kind {
|
||||
w.s(0, "HATCH");
|
||||
common(w, e, owner, paper, "AcDbHatch");
|
||||
w.p(10, Vec3::new(0.0, 0.0, h.elevation));
|
||||
// Its elevation runs along its normal, written as Z: one facing down is at the negative.
|
||||
// Exact for a normal of 0,0,-1; the reader brings a tilted hatch into plan with normal Z.
|
||||
let elevation = if e.common.extrusion.z < 0.0 { -h.elevation } else { h.elevation };
|
||||
w.p(10, Vec3::new(0.0, 0.0, elevation));
|
||||
w.p(210, Vec3::Z);
|
||||
w.s(2, &h.pattern);
|
||||
w.i(70, i64::from(h.solid));
|
||||
@@ -640,12 +650,13 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
}
|
||||
w.i(75, i64::from(h.style));
|
||||
w.i(76, 1);
|
||||
// Angle, scale and double flag are written for solid fills too, as read (AutoCAD and
|
||||
// other writers keep them on SOLID hatches; readers ignore them there).
|
||||
w.f(52, h.angle.to_degrees());
|
||||
w.f(41, h.scale);
|
||||
w.i(77, 0);
|
||||
// Angle, scale and double flag are a pattern fill's: AutoCAD 2024 writes none of them on a
|
||||
// solid or gradient fill, and refuses a file whose solid HATCH has any of them ("Error:
|
||||
// expected group code 98", the whole drawing discarded; measured).
|
||||
if !h.solid {
|
||||
w.f(52, h.angle.to_degrees());
|
||||
w.f(41, h.scale);
|
||||
w.i(77, 0);
|
||||
// The lines read from the file, else the library's pattern of that name.
|
||||
let lines = if h.pattern_lines.is_empty() {
|
||||
cadcraft_doc::library::pattern_for(d, &h.pattern).map(|p| p.lines).unwrap_or_default()
|
||||
@@ -829,10 +840,14 @@ fn gradient(w: &mut W, g: &Gradient) {
|
||||
w.s(1000, g.color2.name());
|
||||
}
|
||||
|
||||
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set.
|
||||
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set. They
|
||||
/// are written with no normal, so they extrude along Z: one whose normal points down Z extrudes
|
||||
/// the other way, and its thickness changes sign. That is exact for a normal of 0,0,-1; a tilted
|
||||
/// one pointing partly down only gets the closer of the two directions.
|
||||
fn thickness(w: &mut W, e: &Entity) {
|
||||
if e.common.thickness != 0.0 {
|
||||
w.f(39, e.common.thickness);
|
||||
let t = if e.common.extrusion.z < 0.0 { -e.common.thickness } else { e.common.thickness };
|
||||
if t != 0.0 {
|
||||
w.f(39, t);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
//! Kept proxy records (ACAD_PROXY_OBJECT, ACAD_PROXY_ENTITY) in the group layout of the DXF version
|
||||
//! written (#3229). Proxies are kept with the groups they were read with, and the DWG bridge
|
||||
//! brings them in the DWG's own version's layout, so a 2010 drawing saved as an R2000 DXF wrote
|
||||
//! 2010 groups that R2000 readers reject ("Out of range").
|
||||
//!
|
||||
//! The layouts, after the `AcDbProxyObject` / `AcDbProxyEntity` marker:
|
||||
//! - R2000 and R2004 (DXF Reference): 92 graphics size, 93 data size in bits, 95 the drawing
|
||||
//! format (low word the DWG version, high word the maintenance release), 70 the data format.
|
||||
//! - 2007: as R2000, with 96 for the size of the separate string stream. A proxy whose string
|
||||
//! stream isn't empty has no earlier form: the raw writer leaves it out of an earlier file and
|
||||
//! the save says so.
|
||||
//! - 2010 and 2013: 160 graphics size, 161 data size, 162 string stream size.
|
||||
//! - 2018 and later: as 2010, with the drawing format split into 71 (DWG version) and 97
|
||||
//! (maintenance release).
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use cadcraft_doc::foreign::is_proxy;
|
||||
use cadcraft_doc::{Drawing, EntityKind, Handle};
|
||||
use craft_dxf::{Tag, Version};
|
||||
|
||||
/// What a DXF of `version` leaves out of `d` because a file earlier than 2007 has no form for a
|
||||
/// proxy's separate string stream, counted by DXF type: those proxies, and the objects that go
|
||||
/// with them (their extension dictionary and its records) because nothing written owns them any
|
||||
/// more. Found by writing the drawing as 2007 and as `version` and comparing what each keeps, so a proxy that no version writes (its class isn't written, or no written block holds
|
||||
/// it) is not counted, and nothing that stays in the file is. Empty from 2007 on (#3229).
|
||||
pub fn proxies_lost(d: &Drawing, version: Version) -> BTreeMap<String, usize> {
|
||||
// Writing twice only for a drawing that holds such a proxy at all.
|
||||
if version >= Version::R2007 || cadcraft_doc::foreign::proxies_dropped_before_2007(d).is_empty() {
|
||||
return BTreeMap::new();
|
||||
}
|
||||
// Unknown entities keep their handles in the file; kept foreign objects get new ones, so
|
||||
// the writer names those by their handles in the drawing.
|
||||
let (tags_2007, objects_2007) = super::tags_kept(d, Version::R2007);
|
||||
let (tags_here, objects_here) = super::tags_kept(d, version);
|
||||
let (entities_2007, entities_here) = (written_handles(&tags_2007), written_handles(&tags_here));
|
||||
let lost = |h: Handle| entities_2007.contains(&h) && !entities_here.contains(&h);
|
||||
let lost_object = |h: Handle| objects_2007.contains(&h) && !objects_here.contains(&h);
|
||||
let mut out = BTreeMap::new();
|
||||
let mut count = |kind: &str| {
|
||||
let n: &mut usize = out.entry(kind.trim().to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
};
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities));
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let EntityKind::Unknown(u) = &e.kind
|
||||
&& lost(e.handle)
|
||||
{
|
||||
count(&u.dxf_type);
|
||||
}
|
||||
}
|
||||
for o in d.foreign.objects.iter().filter(|o| lost_object(o.handle)) {
|
||||
count(&o.kind);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The handles of the records in written `tags` (group 5, and 105 for a DIMSTYLE).
|
||||
fn written_handles(tags: &[Tag]) -> HashSet<Handle> {
|
||||
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(t.str().trim())).collect()
|
||||
}
|
||||
|
||||
/// What a proxy group holds, whatever version's code it was read with.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Field {
|
||||
/// Size of the graphics data in bytes (92, 160).
|
||||
Graphics,
|
||||
/// Size of the object or entity data in bits (93, 161).
|
||||
Data,
|
||||
/// Size of the separate string stream (96, 162), from the 2007 format.
|
||||
Strings,
|
||||
}
|
||||
|
||||
fn field(code: i32) -> Option<Field> {
|
||||
match code {
|
||||
92 | 160 => Some(Field::Graphics),
|
||||
93 | 161 => Some(Field::Data),
|
||||
96 | 162 => Some(Field::Strings),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The code `version` writes `f` with; `None` when it has none (a string stream before 2007).
|
||||
fn code_for(f: Field, version: Version) -> Option<i32> {
|
||||
let late = version >= Version::R2010;
|
||||
match f {
|
||||
Field::Graphics => Some(if late { 160 } else { 92 }),
|
||||
Field::Data => Some(if late { 161 } else { 93 }),
|
||||
Field::Strings if late => Some(162),
|
||||
Field::Strings => (version >= Version::R2007).then_some(96),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrite every proxy record in `tags` into `version`'s layout. Other records are untouched.
|
||||
pub(super) fn proxy_layout(tags: &mut Vec<Tag>, version: Version) {
|
||||
if !tags.iter().any(|t| t.code == 0 && is_proxy(&t.str())) {
|
||||
return;
|
||||
}
|
||||
let src = std::mem::take(tags);
|
||||
let mut out = Vec::with_capacity(src.len());
|
||||
let mut rest = src.as_slice();
|
||||
while let Some((first, tail)) = rest.split_first() {
|
||||
// One record: its type, and its groups up to the next record.
|
||||
let end = tail.iter().position(|t| t.code == 0).unwrap_or(tail.len());
|
||||
let (body, next) = tail.split_at(end);
|
||||
out.push(first.clone());
|
||||
if first.code == 0 && is_proxy(&first.str()) {
|
||||
convert(body, version, &mut out);
|
||||
} else {
|
||||
out.extend_from_slice(body);
|
||||
}
|
||||
rest = next;
|
||||
}
|
||||
*tags = out;
|
||||
}
|
||||
|
||||
/// One proxy record's groups (after its type) in `version`'s layout. Only the groups after the
|
||||
/// proxy subclass marker change: before it, an entity's common groups have a 92 and a 160 of
|
||||
/// their own.
|
||||
fn convert(body: &[Tag], version: Version, out: &mut Vec<Tag>) {
|
||||
let marker = body.iter().position(|t| t.code == 100 && t.str().trim().to_ascii_lowercase().starts_with("acdbproxy"));
|
||||
let Some(marker) = marker else {
|
||||
out.extend_from_slice(body);
|
||||
return;
|
||||
};
|
||||
let (common, own) = body.split_at(marker.saturating_add(1));
|
||||
out.extend_from_slice(common);
|
||||
let format = drawing_format(own);
|
||||
let mut format_written = false;
|
||||
for t in own {
|
||||
if matches!(t.code, 95 | 71 | 97) {
|
||||
// The drawing format goes where the first of its groups was, in this version's form.
|
||||
if !format_written && let Some(f) = format {
|
||||
if version >= Version::R2018 {
|
||||
out.push(Tag::i(71, f & 0xFFFF));
|
||||
out.push(Tag::i(97, (f >> 16) & 0xFFFF));
|
||||
} else {
|
||||
out.push(Tag::i(95, f));
|
||||
}
|
||||
}
|
||||
format_written = true;
|
||||
continue;
|
||||
}
|
||||
match field(t.code) {
|
||||
Some(f) => {
|
||||
if let Some(code) = code_for(f, version) {
|
||||
out.push(Tag { code, value: t.value.clone() });
|
||||
}
|
||||
}
|
||||
None => out.push(t.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The proxy's drawing format (DWG version in the low word, maintenance release in the high
|
||||
/// word), from a 95 or from 71 and 97.
|
||||
fn drawing_format(own: &[Tag]) -> Option<i64> {
|
||||
let get = |code| own.iter().find(|t| t.code == code).map(|t| t.value.as_i64());
|
||||
get(95).map(|f| f & 0xFFFF_FFFF).or_else(|| get(71).map(|lo| ((get(97).unwrap_or(0) & 0xFFFF) << 16) | (lo & 0xFFFF)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn record(groups: &[(i32, &str)]) -> Vec<Tag> {
|
||||
groups.iter().map(|(c, v)| Tag::s(*c, *v)).collect()
|
||||
}
|
||||
|
||||
fn codes(tags: &[Tag]) -> Vec<(i32, String)> {
|
||||
tags.iter().map(|t| (t.code, t.str())).collect()
|
||||
}
|
||||
|
||||
/// A proxy object as a 2010 DWG brings it (the record in the report).
|
||||
fn from_2010() -> Vec<Tag> {
|
||||
record(&[
|
||||
(0, "ACAD_PROXY_OBJECT"),
|
||||
(5, "2CBA9C"),
|
||||
(100, "AcDbProxyObject"),
|
||||
(90, "499"),
|
||||
(91, "521"),
|
||||
(95, "393245"),
|
||||
(70, "0"),
|
||||
(162, "0"),
|
||||
(161, "303"),
|
||||
(310, "00FF"),
|
||||
(340, "1F"),
|
||||
(94, "0"),
|
||||
(0, "ENDSEC"),
|
||||
])
|
||||
}
|
||||
|
||||
fn own(tags: &[Tag]) -> Vec<(i32, String)> {
|
||||
codes(tags).into_iter().skip(3).take_while(|(c, _)| *c != 0).collect()
|
||||
}
|
||||
|
||||
fn s(c: i32, v: &str) -> (i32, String) {
|
||||
(c, v.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2010_proxy_takes_each_versions_layout() {
|
||||
// 393245 = 0x6001D: DWG version 29, maintenance release 6.
|
||||
let mut t = from_2010();
|
||||
proxy_layout(&mut t, Version::R2000);
|
||||
assert_eq!(own(&t), [s(90, "499"), s(91, "521"), s(95, "393245"), s(70, "0"), s(93, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]);
|
||||
let mut t = from_2010();
|
||||
proxy_layout(&mut t, Version::R2007);
|
||||
assert_eq!(
|
||||
own(&t),
|
||||
[s(90, "499"), s(91, "521"), s(95, "393245"), s(70, "0"), s(96, "0"), s(93, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]
|
||||
);
|
||||
let mut t = from_2010();
|
||||
proxy_layout(&mut t, Version::R2010);
|
||||
assert_eq!(codes(&t), codes(&from_2010()), "already 2010");
|
||||
let mut t = from_2010();
|
||||
proxy_layout(&mut t, Version::R2018);
|
||||
assert_eq!(
|
||||
own(&t),
|
||||
[s(90, "499"), s(91, "521"), s(71, "29"), s(97, "6"), s(70, "0"), s(162, "0"), s(161, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]
|
||||
);
|
||||
// And back from the 2018 form.
|
||||
proxy_layout(&mut t, Version::R2004);
|
||||
assert_eq!(own(&t), [s(90, "499"), s(91, "521"), s(95, "393245"), s(70, "0"), s(93, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]);
|
||||
// The ENDSEC after it is untouched.
|
||||
assert_eq!(t.last().map(Tag::str).as_deref(), Some("ENDSEC"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entitys_common_groups_stay() {
|
||||
// Before the subclass marker, 92 and 160 are the entity's own proxy graphics.
|
||||
let mut t = record(&[
|
||||
(0, "ACAD_PROXY_ENTITY"),
|
||||
(100, "AcDbEntity"),
|
||||
(92, "4"),
|
||||
(310, "AA"),
|
||||
(100, "AcDbProxyEntity"),
|
||||
(90, "498"),
|
||||
(91, "500"),
|
||||
(160, "8"),
|
||||
(310, "BB"),
|
||||
(161, "16"),
|
||||
(310, "CC"),
|
||||
(94, "0"),
|
||||
(95, "393245"),
|
||||
(70, "0"),
|
||||
]);
|
||||
proxy_layout(&mut t, Version::R2000);
|
||||
let c: Vec<i32> = t.iter().map(|x| x.code).collect();
|
||||
assert_eq!(c, [0, 100, 92, 310, 100, 90, 91, 92, 310, 93, 310, 94, 95, 70]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_records_and_hostile_values_are_safe() {
|
||||
let mut t = record(&[(0, "LINE"), (95, "1"), (100, "AcDbProxyObject"), (93, "1")]);
|
||||
let before = codes(&t);
|
||||
proxy_layout(&mut t, Version::R2018);
|
||||
assert_eq!(codes(&t), before, "not a proxy");
|
||||
// A huge or negative drawing format doesn't overflow.
|
||||
let mut t = record(&[(0, "ACAD_PROXY_OBJECT"), (100, "AcDbProxyObject"), (95, "-1"), (71, "99999999999")]);
|
||||
proxy_layout(&mut t, Version::R2018);
|
||||
assert_eq!(codes(&t), [s(0, "ACAD_PROXY_OBJECT"), s(100, "AcDbProxyObject"), s(71, "65535"), s(97, "65535")]);
|
||||
// No marker: left as it is.
|
||||
let mut t = record(&[(0, "ACAD_PROXY_OBJECT"), (93, "1")]);
|
||||
proxy_layout(&mut t, Version::R2018);
|
||||
assert_eq!(codes(&t), [s(0, "ACAD_PROXY_OBJECT"), s(93, "1")]);
|
||||
}
|
||||
}
|
||||
@@ -413,6 +413,23 @@ struct LayoutWriteData<'a> {
|
||||
limits: Option<(Vec2, Vec2)>,
|
||||
}
|
||||
|
||||
/// The plot layout flags (AcDbPlotSettings group 70) for `page`. The bits CADCraft models come
|
||||
/// from the page: 2 display plot styles, 4 centred, 128 lineweights, and 16 standard scale where
|
||||
/// the scale decides it (scaled to fit: set; a custom scale: clear). The rest are kept as the file
|
||||
/// had them (#3227); a page CADCraft made gets 512 (plot paper space last) and 32 (plot with plot
|
||||
/// styles), and 16 when its scale is standard.
|
||||
fn plot_layout_flags(page: &PageSetup, standard: bool) -> i64 {
|
||||
const MODELED: i64 = 2 | 4 | 128;
|
||||
const STANDARD_SCALE: i64 = 16;
|
||||
let kept = match page.file_plot_flags {
|
||||
Some(f) if page.scale_to_fit => (f & !MODELED) | STANDARD_SCALE,
|
||||
Some(f) if !standard => f & !MODELED & !STANDARD_SCALE,
|
||||
Some(f) => f & !MODELED,
|
||||
None => 512 | 32 | if standard { STANDARD_SCALE } else { 0 },
|
||||
};
|
||||
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
|
||||
}
|
||||
|
||||
fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<'_>) {
|
||||
let d = context.drawing;
|
||||
let layout_dict = context.dictionary;
|
||||
@@ -426,13 +443,10 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
// Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units
|
||||
// per 143 drawing units).
|
||||
let scale = if page.scale.is_finite() && page.scale > 0.0 { page.scale } else { 1.0 };
|
||||
let standard = page.scale_to_fit || scale == 1.0;
|
||||
let plot_flags = 512
|
||||
| 32
|
||||
| if standard { 16 } else { 0 }
|
||||
| if page.lineweights { 128 } else { 0 }
|
||||
| if page.center { 4 } else { 0 }
|
||||
| if page.show_plot_styles { 2 } else { 0 };
|
||||
// The file's standard scale (such as 1:50) while the scale is still the one read with it.
|
||||
let file_standard = page.file_standard_scale.filter(|&(_, s)| !page.scale_to_fit && s == scale).map(|(code, _)| code);
|
||||
let standard = page.scale_to_fit || scale == 1.0 || file_standard.is_some();
|
||||
let plot_flags = plot_layout_flags(page, standard);
|
||||
let plot_type = match page.plot_area.as_str() {
|
||||
"display" => 0,
|
||||
"extents" => 1,
|
||||
@@ -474,7 +488,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
w.i(73, rotation);
|
||||
w.i(74, plot_type);
|
||||
w.s(7, &page.plot_style_table);
|
||||
w.i(75, if page.scale_to_fit { 0 } else { 16 });
|
||||
w.i(75, if page.scale_to_fit { 0 } else { file_standard.unwrap_or(16) });
|
||||
w.f(147, scale);
|
||||
// The paper image origin the file had (#2109), else 0,0.
|
||||
let origin = page.image_origin.filter(|o| o.is_finite()).unwrap_or(Vec2::ZERO);
|
||||
@@ -978,10 +992,24 @@ fn plan_dimension_associations(d: &Drawing, all_spaces: &[&EntityStore], w: &mut
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the version the
|
||||
/// file ends up in: `version`, or the DWG version the bridge writes) has.
|
||||
/// The DWG bridge's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the DWG
|
||||
/// version the bridge writes) has.
|
||||
/// `frozen_341`: see [`Ctx::frozen_341`].
|
||||
pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_341: bool) -> Vec<Tag> {
|
||||
tags_kept_for(d, version, target, frozen_341, true).0
|
||||
}
|
||||
|
||||
/// The drawing's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the version the
|
||||
/// file ends up in) has, and the foreign objects the file keeps, by their handles in the drawing.
|
||||
/// `bridge`: the text is for the DWG bridge, not a DXF file. The versions alone can't say so: an
|
||||
/// R2000 DWG is bridged from R2000 text.
|
||||
pub(super) fn tags_kept_for(
|
||||
d: &Drawing,
|
||||
version: Version,
|
||||
target: Version,
|
||||
frozen_341: bool,
|
||||
bridge: bool,
|
||||
) -> (Vec<Tag>, std::collections::HashSet<Handle>) {
|
||||
// An in-place block edit in progress is not written: the drawing as before it.
|
||||
let committed = d.committed();
|
||||
let d: &Drawing = &committed;
|
||||
@@ -1129,7 +1157,12 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
for (n, h, b) in &user_blocks {
|
||||
br_rec(&mut w, h, n, None, Some(b));
|
||||
}
|
||||
for (n, h, _) in dim_defs.iter().chain(arrow_defs.iter()).chain(table_defs.iter()) {
|
||||
// A block with another name that a dimension was read with keeps its record's properties
|
||||
// (insertion units, explodability) as read (#3299).
|
||||
for (n, h, _) in &dim_defs {
|
||||
br_rec(&mut w, h, n, None, super::blocks::kept_named_dim_block(d, n));
|
||||
}
|
||||
for (n, h, _) in arrow_defs.iter().chain(table_defs.iter()) {
|
||||
br_rec(&mut w, h, n, None, None);
|
||||
}
|
||||
w.s(0, "ENDTAB");
|
||||
@@ -1190,7 +1223,15 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
}
|
||||
}
|
||||
for (n, h, ents) in &dim_defs {
|
||||
block(&mut w, (n, ""), h, Vec3::ZERO, 1, &mut ents.iter(), false);
|
||||
// A block with another name that a dimension was read with keeps its description, flags
|
||||
// and base point as read (#3299); `*D` blocks are anonymous at the origin. A picture
|
||||
// regenerated into an empty read block is drawn in world coordinates, so it is at the
|
||||
// origin too.
|
||||
let (desc, base, flags) = match super::blocks::kept_named_dim_block(d, n) {
|
||||
Some(b) => (b.description.as_str(), if b.entities.is_empty() { Vec3::ZERO } else { b.base }, i64::from(b.anonymous)),
|
||||
None => ("", Vec3::ZERO, 1),
|
||||
};
|
||||
block(&mut w, (n, desc), h, base, flags, &mut ents.iter(), false);
|
||||
}
|
||||
for (n, h, ents) in &arrow_defs {
|
||||
block(&mut w, (n, ""), h, Vec3::ZERO, 0, &mut ents.iter(), false);
|
||||
@@ -1232,12 +1273,23 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
*t = Tag::s(5, seed);
|
||||
}
|
||||
// Only a DXF declares the version it is written for: the DWG bridge writes R2000 text for the
|
||||
// DWG writer, which keeps SAT-text solids (#2334).
|
||||
crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013);
|
||||
// DWG writer, which keeps SAT-text solids (#2334). A file of 2010 or earlier, DXF or DWG, has
|
||||
// no data store, so a solid whose geometry is only there is left out of it.
|
||||
// The DWG bridge keeps proxies in the DWG's own layout.
|
||||
let strings = bridge || version >= Version::R2007;
|
||||
let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings);
|
||||
// Kept constraint groups go in the order their reader expects: a DXF's own version. The
|
||||
// bridge's R2000 text is read as the version its kept groups came from when that is newer
|
||||
// (craft-dwg's `encode_kept_noted` declares it), so there they stay as read.
|
||||
let read_as =
|
||||
if !bridge { version } else { d.foreign.version.as_deref().and_then(Version::for_acadver).filter(|from| *from > version).unwrap_or(version) };
|
||||
crate::dxf_raw::constraint_node_order(&mut w.t, read_as >= Version::R2013);
|
||||
// Kept render settings take the class-version form of the version the text is read as (#907).
|
||||
crate::dxf_raw::render_settings_versions(&mut w.t, d.foreign.version.as_deref().and_then(Version::for_acadver), read_as);
|
||||
crate::dxf_raw::data_store(&mut w.t, d, target >= Version::R2013);
|
||||
add_class_instance_counts(&mut w.t, target);
|
||||
mark_xrefs(&mut w.t, d);
|
||||
w.t
|
||||
(w.t, kept)
|
||||
}
|
||||
|
||||
/// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
/// A DWG hatch's elliptic boundary edge angles, in degrees in the DXF the DWG is read through (#3332).
|
||||
mod dwg_hatch;
|
||||
/// What a DXF file holds that CADCraft doesn't model, kept and written back (#528).
|
||||
mod dxf_raw;
|
||||
|
||||
@@ -35,7 +37,7 @@ pub use cadcraft_doc::Format;
|
||||
pub use craft_dxf::Version;
|
||||
pub use dxf_raw::{ObjectRecord, object_records};
|
||||
pub use dxf_read::entity_from_groups;
|
||||
pub use dxf_write::entity_groups;
|
||||
pub use dxf_write::{entity_groups, proxies_lost};
|
||||
pub use pdf::{PdfOptions, pdf, plot};
|
||||
|
||||
/// How a drawing is saved as DXF or DWG.
|
||||
@@ -98,6 +100,8 @@ pub fn read(bytes: &[u8], name: impl AsRef<Path>) -> Result<Drawing> {
|
||||
pub(crate) fn read_source(bytes: &[u8], name: &Path) -> Result<(Drawing, Option<Vec<u8>>)> {
|
||||
if craft_dwg::is_dwg(bytes) {
|
||||
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(dwg_error)?;
|
||||
// The decoder writes an elliptic hatch edge's angles in radians; DXF keeps degrees.
|
||||
let dxf = dwg_hatch::elliptic_edge_degrees(dxf);
|
||||
let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
|
||||
d.read_notes = notes.into_iter().map(|note| cadcraft_dwg_message(¬e)).collect();
|
||||
return Ok((d, Some(dxf)));
|
||||
|
||||
+344
-5
@@ -2683,6 +2683,84 @@ fn mirrored_2d_polyline_extrusion_flips_x_and_bulge() {
|
||||
assert_eq!(got, vec![(-1.0, 0.0, -1.0), (-3.0, 0.0, 0.0)]);
|
||||
}
|
||||
|
||||
/// Objects whose normal is 0,0,-1, at OCS height 5 and most of them 2 thick, keep their world height
|
||||
/// and the side they extrude to through a save. They are written with no normal (along Z), so an
|
||||
/// elevation or a thickness written as read put a polyline or a hatch at Z +5 instead of -5, and
|
||||
/// extruded a circle, point, solid or text up instead of down (AutoCAD 2024 opening the saved file,
|
||||
/// measured). A line writes its normal, and keeps its thickness as read. The same objects facing up
|
||||
/// (no normal, and 0,0,1) keep +5 and +2: only a normal pointing down Z changes the sign.
|
||||
#[test]
|
||||
fn mirrored_objects_keep_their_world_height_and_thickness_side() {
|
||||
let records = |normal: &str| {
|
||||
format!(
|
||||
"0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n38\n5\n39\n2\n{normal}10\n0\n20\n0\n42\n0.5\n10\n-10\n20\n0\n\
|
||||
0\nPOLYLINE\n8\n0\n66\n1\n70\n0\n10\n0\n20\n0\n30\n5\n{normal}0\nVERTEX\n8\n0\n10\n0\n20\n10\n0\nVERTEX\n8\n0\n10\n-10\n20\n10\n0\nSEQEND\n\
|
||||
0\nCIRCLE\n8\n0\n10\n-10\n20\n5\n30\n5\n40\n5\n39\n2\n{normal}\
|
||||
0\nARC\n8\n0\n10\n-30\n20\n5\n30\n5\n40\n5\n50\n180\n51\n270\n{normal}\
|
||||
0\nPOINT\n8\n0\n10\n-40\n20\n0\n30\n5\n39\n2\n{normal}\
|
||||
0\nSOLID\n8\n0\n10\n50\n20\n0\n30\n5\n11\n60\n21\n0\n31\n5\n12\n50\n22\n5\n32\n5\n13\n60\n23\n5\n33\n5\n39\n2\n{normal}\
|
||||
0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n5\n{normal}2\nSOLID\n70\n1\n71\n0\n91\n1\n92\n2\n72\n0\n73\n1\n93\n4\n\
|
||||
10\n70\n20\n0\n10\n80\n20\n0\n10\n80\n20\n5\n10\n70\n20\n5\n97\n0\n75\n0\n76\n1\n98\n0\n\
|
||||
0\nTEXT\n8\n0\n10\n-90\n20\n0\n30\n5\n40\n2\n1\nA\n39\n2\n{normal}\
|
||||
0\nLINE\n8\n0\n39\n2\n10\n0\n20\n20\n30\n3\n11\n10\n21\n20\n31\n3\n{normal}"
|
||||
)
|
||||
};
|
||||
let (down, up) = ("210\n0\n220\n0\n230\n-1\n", "210\n0\n220\n0\n230\n1\n");
|
||||
let text = format!("0\nSECTION\n2\nENTITIES\n{}{}{}0\nENDSEC\n0\nEOF\n", records(down), records(""), records(up));
|
||||
// Each object's kind, world height and thickness along world Z.
|
||||
let place = |d: &Drawing| -> Vec<(&'static str, f64, f64)> {
|
||||
d.model
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let n = e.common.extrusion.z.signum();
|
||||
let (kind, z) = match &e.kind {
|
||||
EntityKind::LwPolyline(p) => ("polyline", n * p.elevation),
|
||||
EntityKind::Circle(c) => ("circle", c.center.z),
|
||||
EntityKind::Arc(a) => ("arc", a.center.z),
|
||||
EntityKind::Point(p) => ("point", p.p.z),
|
||||
EntityKind::Solid(s) => ("solid", s.corners[0].z),
|
||||
EntityKind::Hatch(h) => ("hatch", n * h.elevation),
|
||||
EntityKind::Text(t) => ("text", t.insert.z),
|
||||
EntityKind::Line(l) => ("line", l.a.z),
|
||||
_ => ("other", f64::NAN),
|
||||
};
|
||||
(kind, z, n * e.common.thickness)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let d = read(text.as_bytes(), "m.dxf").unwrap();
|
||||
let mut want = vec![
|
||||
("polyline", -5.0, -2.0),
|
||||
("polyline", -5.0, 0.0),
|
||||
("circle", -5.0, -2.0),
|
||||
("arc", -5.0, 0.0),
|
||||
("point", 5.0, -2.0),
|
||||
("solid", -5.0, -2.0),
|
||||
("hatch", -5.0, 0.0),
|
||||
("text", -5.0, -2.0),
|
||||
("line", 3.0, -2.0),
|
||||
];
|
||||
let facing_up = [
|
||||
("polyline", 5.0, 2.0),
|
||||
("polyline", 5.0, 0.0),
|
||||
("circle", 5.0, 2.0),
|
||||
("arc", 5.0, 0.0),
|
||||
("point", 5.0, 2.0),
|
||||
("solid", 5.0, 2.0),
|
||||
("hatch", 5.0, 0.0),
|
||||
("text", 5.0, 2.0),
|
||||
("line", 3.0, 2.0),
|
||||
];
|
||||
want.extend(facing_up);
|
||||
want.extend(facing_up);
|
||||
assert_eq!(place(&d), want, "as read");
|
||||
let out = write(&d, "m.dxf").unwrap();
|
||||
assert_eq!(place(&read(&out, "m.dxf").unwrap()), want, "after a save");
|
||||
let pairs = dxf_pairs(std::str::from_utf8(&out).unwrap());
|
||||
let lines: Vec<_> = dxf_records(&pairs, "LINE").into_iter().map(|l| (group(l, "39"), group(l, "230"))).collect();
|
||||
assert_eq!(lines, [(Some("2.0"), Some("-1.0")), (Some("2.0"), None), (Some("2.0"), None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirrored_hatch_extrusion_flips_boundary() {
|
||||
// HATCH boundaries are OCS: the square (1,0)..(3,2) under extrusion (0,0,-1) lies at (-3,0)..(-1,2).
|
||||
@@ -2727,6 +2805,20 @@ fn tilted_hatch_turns_its_gradient() {
|
||||
assert!((g.angle - std::f64::consts::PI).abs() < 1e-9, "gradient angle {}", g.angle);
|
||||
}
|
||||
|
||||
/// A tilted polyline with a thickness, its normal pointing partly down Z, still extrudes toward -Z
|
||||
/// once it is drawn as seen from above and saved with no normal.
|
||||
#[test]
|
||||
fn tilted_thick_polyline_keeps_its_extrusion_side() {
|
||||
let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n39\n5\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
|
||||
10\n1\n20\n0\n10\n3\n20\n2\n0\nENDSEC\n0\nEOF\n";
|
||||
let d = read(text.as_bytes(), "p.dxf").unwrap();
|
||||
let e = d.model.iter().next().unwrap();
|
||||
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z));
|
||||
let back = roundtrip(&d);
|
||||
let e = back.model.iter().next().unwrap();
|
||||
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z), "saved with no normal, it still extrudes toward -Z");
|
||||
}
|
||||
|
||||
/// A straight tilted LWPOLYLINE keeps its vertex widths (groups 40/41) on the projected vertices.
|
||||
#[test]
|
||||
fn tilted_straight_lwpolyline_keeps_its_widths() {
|
||||
@@ -2841,6 +2933,57 @@ fn tilted_lwpolyline_is_drawn_as_seen_from_above() {
|
||||
assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::<Vec<_>>(), vec![1.0, 1.0]);
|
||||
}
|
||||
|
||||
/// A 2D POLYLINE (heavy polyline) in a tilted plane is drawn as seen from above, like a
|
||||
/// LWPOLYLINE: before, its OCS points were taken for world coordinates. With extrusion
|
||||
/// (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and y = (0, √3/2, 1/2), and the elevation of 2
|
||||
/// moves the plane by twice the normal, (0, 1, -√3): the square (1,0)..(3,2) lies over
|
||||
/// (-3,1)..(-1,1+√3), its corners at a mean height of 1/2 - √3.
|
||||
#[test]
|
||||
fn tilted_2d_polyline_is_drawn_as_seen_from_above() {
|
||||
let square = |n: &str| {
|
||||
format!(
|
||||
"0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n2\n70\n1\n{n}\
|
||||
0\nVERTEX\n8\n0\n10\n1\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n2\n\
|
||||
0\nVERTEX\n8\n0\n10\n1\n20\n2\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n"
|
||||
)
|
||||
};
|
||||
let d = read(square("210\n0\n220\n0.5\n230\n-0.8660254037844386\n").as_bytes(), "p.dxf").unwrap();
|
||||
let b = d.extents(&Space::Model);
|
||||
let r3 = 3f64.sqrt();
|
||||
for (got, want) in [(b.min.x, -3.0), (b.min.y, 1.0), (b.max.x, -1.0), (b.max.y, 1.0 + r3)] {
|
||||
assert!((got - want).abs() < 1e-9, "extents {b:?}");
|
||||
}
|
||||
let e = d.model.iter().next().unwrap();
|
||||
assert_eq!(e.common.extrusion, Vec3::Z, "its points are plan coordinates now");
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
|
||||
assert!((p.elevation - (0.5 - r3)).abs() < 1e-9, "the mean height of its corners: {}", p.elevation);
|
||||
// In plan and in the mirrored plane the polyline stays as it was: mirrored only in x.
|
||||
let plain = read(square("").as_bytes(), "p.dxf").unwrap();
|
||||
let b = plain.extents(&Space::Model);
|
||||
assert!((b.min.x - 1.0).abs() < 1e-9 && (b.max.y - 2.0).abs() < 1e-9, "extents {b:?}");
|
||||
let mirrored = read(square("210\n0\n220\n0\n230\n-1\n").as_bytes(), "p.dxf").unwrap();
|
||||
let b = mirrored.extents(&Space::Model);
|
||||
assert!((b.min.x + 3.0).abs() < 1e-9 && (b.max.x + 1.0).abs() < 1e-9, "extents {b:?}");
|
||||
assert_eq!(mirrored.model.iter().next().unwrap().common.extrusion, Vec3::new(0.0, 0.0, -1.0));
|
||||
}
|
||||
|
||||
/// A tilted 2D POLYLINE with an arc keeps its shape as seen from above: the half circle from
|
||||
/// (0,0) to (2,0) is flattened into its half ellipse, in plan x from -2 to 0 and reaching √3/2.
|
||||
#[test]
|
||||
fn tilted_2d_polyline_arc_is_flattened() {
|
||||
let text = "0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n0\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
|
||||
0\nVERTEX\n8\n0\n10\n0\n20\n0\n42\n1\n0\nVERTEX\n8\n0\n10\n2\n20\n0\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n";
|
||||
let d = read(text.as_bytes(), "p.dxf").unwrap();
|
||||
let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None });
|
||||
assert!(p.vertices.len() > 8 && p.vertices.iter().all(|v| v.bulge == 0.0), "{} vertices", p.vertices.len());
|
||||
let b = d.extents(&Space::Model);
|
||||
// Bulge 1 turns counter-clockwise from (0,0) to (2,0), so the arc runs below its chord, down
|
||||
// to OCS y -1: plan y -√3/2.
|
||||
for (got, want) in [(b.min.x, -2.0), (b.max.x, 0.0), (b.min.y, -(3f64.sqrt()) / 2.0), (b.max.y, 0.0)] {
|
||||
assert!((got - want).abs() < 5e-3, "extents {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The model extents of a one-loop solid HATCH whose edge boundary is `edges` (group 72 onwards).
|
||||
fn hatch_edge_extents(edges: &str) -> Bounds2 {
|
||||
let n = edges.matches("72\n").count();
|
||||
@@ -3552,6 +3695,44 @@ fn drawing_without_insunits_stays_unitless() {
|
||||
assert_eq!(insunits(&write_dxf(&Drawing::new_imperial())), Some("1".into()));
|
||||
}
|
||||
|
||||
/// Constraint groups with hostile node counts, truncated nodes and a registry that doesn't match
|
||||
/// the nodes are left as they are; nothing panics or loops for long.
|
||||
#[test]
|
||||
fn hostile_constraint_groups_never_panic() {
|
||||
use craft_dxf::Tag;
|
||||
let group = |rest: &[(i32, &str)]| {
|
||||
let mut t = vec![Tag::s(0, "ACDBASSOC2DCONSTRAINTGROUP"), Tag::s(100, "AcDbAssoc2dConstraintGroup"), Tag::s(360, "0"), Tag::s(90, "0")];
|
||||
t.extend(rest.iter().map(|(c, v)| Tag::s(*c, *v)));
|
||||
t
|
||||
};
|
||||
let many: Vec<(i32, &str)> = std::iter::repeat_n((90, "1"), 200_000).collect();
|
||||
let cases: Vec<Vec<Tag>> = vec![
|
||||
group(&[]),
|
||||
group(&[(90, "3"), (90, "0"), (90, "99999999999"), (290, "0")]),
|
||||
group(&[(90, "3"), (90, "0"), (90, "0"), (290, "0"), (90, "-5")]),
|
||||
group(&[(90, "3"), (90, "0"), (90, "0"), (290, "0"), (90, "100000"), (1, "AcFixedConstraint"), (90, "1")]),
|
||||
group(&[(90, "3"), (90, "0"), (90, "0"), (290, "0"), (90, "1"), (1, "AcFixedConstraint"), (90, "1"), (90, "1"), (90, "4")]),
|
||||
group(
|
||||
&[(90, "3"), (90, "0"), (90, "0"), (290, "0"), (90, "1"), (1, "AcFixedConstraint"), (90, "1")]
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(many)
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
vec![Tag::s(0, "ACDBASSOC2DCONSTRAINTGROUP")],
|
||||
];
|
||||
// Each group's content (code, value), unchanged after each mode: a rotation keeps the
|
||||
// length, and a second mode could rotate it back.
|
||||
let pairs = |t: &[Tag]| t.iter().map(|x| (x.code, x.str())).collect::<Vec<_>>();
|
||||
for mut tags in cases {
|
||||
let before = pairs(&tags);
|
||||
for modern in [false, true] {
|
||||
crate::dxf_raw::constraint_node_order(&mut tags, modern);
|
||||
assert_eq!(pairs(&tags), before, "modern: {modern}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_clips_a_primitive_beyond_the_coordinate_range() {
|
||||
let mut d = Drawing::new_metric();
|
||||
@@ -3711,6 +3892,144 @@ fn proxy_file() -> Vec<u8> {
|
||||
pairs.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::<String>().into_bytes()
|
||||
}
|
||||
|
||||
/// #3229: a file with a proxy object in the 2010 layout (as the DWG bridge brings it from a 2010
|
||||
/// DWG), with its class and a dictionary entry.
|
||||
/// A 2010 DXF with one proxy object (dictionary entry WIDGETS) whose string stream is `strings`
|
||||
/// long (group 162).
|
||||
fn proxy_2010_file(strings: &str) -> Vec<u8> {
|
||||
let text = String::from_utf8(write(&Drawing::new_metric(), "p.dxf").unwrap()).unwrap();
|
||||
let mut pairs = dxf_pairs(&text);
|
||||
let p = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
let classes = pairs.iter().position(|q| q.0 == "2" && q.1 == "CLASSES").unwrap() + 1;
|
||||
pairs.splice(
|
||||
classes..classes,
|
||||
[p("0", "CLASS"), p("1", "WIDGETX"), p("2", "AcDbWidgetX"), p("3", "ObjectDBX Classes"), p("90", "4095"), p("280", "1"), p("281", "0")],
|
||||
);
|
||||
let objects = pairs.iter().position(|q| q.0 == "2" && q.1 == "OBJECTS").unwrap();
|
||||
let nod = objects + 1;
|
||||
let after = nod + pairs[nod..].iter().position(|q| q.0 == "281").unwrap() + 1;
|
||||
pairs.splice(after..after, [p("3", "WIDGETS"), p("350", "AAA1")]);
|
||||
let nod_handle = pairs[nod + 1].1.clone();
|
||||
let proxy = [
|
||||
p("0", "ACAD_PROXY_OBJECT"),
|
||||
p("5", "AAA1"),
|
||||
p("330", &nod_handle),
|
||||
p("100", "AcDbProxyObject"),
|
||||
p("90", "499"),
|
||||
p("91", "500"),
|
||||
p("95", "393245"),
|
||||
p("70", "0"),
|
||||
p("162", strings),
|
||||
p("161", "303"),
|
||||
p("310", "00FF"),
|
||||
p("94", "0"),
|
||||
];
|
||||
let end = objects + pairs[objects..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap();
|
||||
pairs.splice(end..end, proxy);
|
||||
pairs.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::<String>().into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxies_take_the_layout_of_the_version_written() {
|
||||
let d = read(&proxy_2010_file("0"), "p.dxf").unwrap();
|
||||
let own = |version: Version| {
|
||||
let text = String::from_utf8(write_with(&d, "out.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap();
|
||||
let pairs = dxf_pairs(&text);
|
||||
let recs = dxf_records(&pairs, "ACAD_PROXY_OBJECT");
|
||||
let r = recs.first().expect("the proxy is kept");
|
||||
r.iter().skip_while(|q| q.1 != "AcDbProxyObject").skip(1).map(|q| q.0.clone()).collect::<Vec<_>>().join(" ")
|
||||
};
|
||||
// R2000: no 161/162 (ODA and BricsCAD refused the file), the data size is 93.
|
||||
assert_eq!(own(Version::R2000), "90 91 95 70 93 310 94");
|
||||
assert_eq!(own(Version::R2007), "90 91 95 70 96 93 310 94");
|
||||
assert_eq!(own(Version::R2010), "90 91 95 70 162 161 310 94");
|
||||
assert_eq!(own(Version::R2018), "90 91 71 97 70 162 161 310 94");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_with_a_string_stream_is_left_out_before_2007() {
|
||||
// Before 2007 a proxy's strings are part of its data: a separate stream has no form there.
|
||||
// The proxy and its dictionary entry are left out rather than written with half its data.
|
||||
let d = read(&proxy_2010_file("10"), "p.dxf").unwrap();
|
||||
assert_eq!(cadcraft_doc::foreign::proxies_dropped_before_2007(&d), [("ACAD_PROXY_OBJECT".to_string(), 1)].into_iter().collect());
|
||||
let pairs = |version: Version| {
|
||||
let text = String::from_utf8(write_with(&d, "out.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap();
|
||||
dxf_pairs(&text)
|
||||
};
|
||||
let entry = |p: &[(String, String)]| p.iter().any(|q| q.0 == "3" && q.1 == "WIDGETS");
|
||||
for version in [Version::R2000, Version::R2004] {
|
||||
let p = pairs(version);
|
||||
assert!(dxf_records(&p, "ACAD_PROXY_OBJECT").is_empty(), "{version:?}");
|
||||
assert!(!entry(&p), "{version:?}: the dictionary entry goes with it");
|
||||
}
|
||||
// From 2007 it is kept, with its string stream and its dictionary entry.
|
||||
let p = pairs(Version::R2007);
|
||||
let recs = dxf_records(&p, "ACAD_PROXY_OBJECT");
|
||||
assert_eq!(recs.first().and_then(|r| group(r, "96")), Some("10"));
|
||||
assert!(entry(&p));
|
||||
}
|
||||
|
||||
/// #3229 review: the loss a DXF before 2007 reports is what the writer leaves out for the string
|
||||
/// stream alone. A proxy no version writes (its class number names no class) is not counted, and
|
||||
/// the objects a dropped proxy owns (its extension dictionary and the XRECORD in it) are.
|
||||
#[test]
|
||||
fn proxies_lost_counts_what_the_string_stream_takes_with_it() {
|
||||
let lost = |d: &Drawing, v| crate::proxies_lost(d, v);
|
||||
// The records of the file written at `version` (the file gives kept objects new handles).
|
||||
let written = |d: &Drawing, version: Version| {
|
||||
let text = String::from_utf8(write_with(d, "out.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap();
|
||||
dxf_pairs(&text)
|
||||
};
|
||||
// Its class isn't written: every version leaves it out, so 2007 would not keep it either.
|
||||
let text = String::from_utf8(proxy_2010_file("10")).unwrap();
|
||||
assert_eq!(text.matches("\n91\n500\n").count(), 1, "the proxy's class number");
|
||||
let orphan = read(text.replacen("\n91\n500\n", "\n91\n777\n", 1).as_bytes(), "p.dxf").unwrap();
|
||||
assert!(!cadcraft_doc::foreign::proxies_dropped_before_2007(&orphan).is_empty(), "the proxy itself is counted");
|
||||
assert!(dxf_records(&written(&orphan, Version::R2007), "ACAD_PROXY_OBJECT").is_empty(), "no version writes it");
|
||||
assert_eq!(lost(&orphan, Version::R2000), std::collections::BTreeMap::new());
|
||||
// With an extension dictionary holding an XRECORD: all three go before 2007.
|
||||
let mut p = dxf_pairs(&text);
|
||||
let at = p.iter().position(|q| q.0 == "5" && q.1 == "AAA1").unwrap() + 1;
|
||||
let g = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
p.splice(at..at, [g("102", "{ACAD_XDICTIONARY"), g("360", "BBB1"), g("102", "}")]);
|
||||
// The proxy is the last object: its owned objects go after it.
|
||||
let objects_end = at + p[at..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap();
|
||||
p.splice(
|
||||
objects_end..objects_end,
|
||||
[
|
||||
g("0", "DICTIONARY"),
|
||||
g("5", "BBB1"),
|
||||
g("330", "AAA1"),
|
||||
g("100", "AcDbDictionary"),
|
||||
g("280", "1"),
|
||||
g("281", "1"),
|
||||
g("3", "WIDGETDATA"),
|
||||
g("350", "CCC1"),
|
||||
g("0", "XRECORD"),
|
||||
g("5", "CCC1"),
|
||||
g("330", "BBB1"),
|
||||
g("100", "AcDbXrecord"),
|
||||
g("280", "1"),
|
||||
g("1", "kept with the widget"),
|
||||
],
|
||||
);
|
||||
let bytes: Vec<u8> = p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::<String>().into_bytes();
|
||||
let d = read(&bytes, "p.dxf").unwrap();
|
||||
let held = |version| {
|
||||
let p = written(&d, version);
|
||||
let xrecord = dxf_records(&p, "XRECORD").iter().any(|r| group(r, "1") == Some("kept with the widget"));
|
||||
let dictionary = p.iter().any(|q| q.0 == "3" && q.1 == "WIDGETDATA");
|
||||
(dxf_records(&p, "ACAD_PROXY_OBJECT").len(), dictionary, xrecord)
|
||||
};
|
||||
assert_eq!(held(Version::R2007), (1, true, true), "2007 keeps all three");
|
||||
assert_eq!(held(Version::R2000), (0, false, false), "R2000 keeps none");
|
||||
let want: std::collections::BTreeMap<String, usize> =
|
||||
[("ACAD_PROXY_OBJECT", 1), ("DICTIONARY", 1), ("XRECORD", 1)].into_iter().map(|(k, n)| (k.to_string(), n)).collect();
|
||||
assert_eq!(lost(&d, Version::R2000), want);
|
||||
assert_eq!(lost(&d, Version::R2004), want);
|
||||
assert_eq!(lost(&d, Version::R2007), std::collections::BTreeMap::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxies_keep_their_class_when_classes_are_rewritten() {
|
||||
let d = read(&proxy_file(), "p.dxf").unwrap();
|
||||
@@ -3870,20 +4189,40 @@ fn non_unicode_names_pick_the_format_by_extension() {
|
||||
assert!(write(&d, name("dwt")).is_ok(), "a template is written as DWG");
|
||||
}
|
||||
|
||||
/// A SOLID hatch keeps its angle (52), scale (41) and double flag (77) through a save: the writer
|
||||
/// wrote them for pattern fills only.
|
||||
/// A solid or gradient HATCH goes from its pattern type (76) straight to its seed points (98), as
|
||||
/// AutoCAD 2024 writes it, even one read with an angle, scale and double flag: AutoCAD 2024 refuses
|
||||
/// a file whose solid HATCH has any of 52, 41 or 77 there ("Error: expected group code 98", the
|
||||
/// whole drawing discarded; measured). A pattern fill keeps all three.
|
||||
#[test]
|
||||
fn solid_hatch_keeps_angle_scale_and_double_flag() {
|
||||
fn solid_and_gradient_hatches_have_no_pattern_groups() {
|
||||
let src = "0\nSECTION\n2\nENTITIES\n0\nHATCH\n5\n40\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n2\nSOLID\n70\n1\n71\n0\n\
|
||||
91\n1\n92\n2\n72\n0\n73\n1\n93\n4\n10\n0\n20\n0\n10\n40\n20\n0\n10\n40\n20\n40\n10\n0\n20\n40\n97\n0\n\
|
||||
75\n0\n76\n1\n52\n30\n41\n2\n77\n0\n98\n0\n0\nENDSEC\n0\nEOF\n";
|
||||
let out = write_dxf(&read_dxf(src.as_bytes()).unwrap());
|
||||
let (mut d, _) = gradient_sample();
|
||||
for e in read_dxf(src.as_bytes()).unwrap().model.iter() {
|
||||
d.add(&Space::Model, e.common.clone(), e.kind.clone()).unwrap();
|
||||
}
|
||||
let mut pattern = hatches(&d)[0].clone();
|
||||
(pattern.pattern, pattern.solid, pattern.gradient, pattern.angle, pattern.scale) = ("ANSI31".into(), false, None, 30f64.to_radians(), 2.0);
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Hatch(pattern)).unwrap();
|
||||
let out = write_dxf(&d);
|
||||
let pairs = dxf_pairs(&out);
|
||||
let h = dxf_records(&pairs, "HATCH")[0];
|
||||
let records = dxf_records(&pairs, "HATCH");
|
||||
let (solid, pattern): (Vec<&[(String, String)]>, Vec<_>) = records.into_iter().partition(|h| group(h, "70") == Some("1"));
|
||||
assert_eq!((solid.len(), pattern.len()), (4, 1), "three from the sample, one read");
|
||||
for h in solid {
|
||||
let after = h.iter().position(|p| p.0 == "76").and_then(|k| h.get(k + 1)).map(|p| p.0.as_str());
|
||||
assert_eq!(after, Some("98"), "{h:?}");
|
||||
for code in ["52", "41", "77", "78"] {
|
||||
assert_eq!(group(h, code), None, "group {code}: {h:?}");
|
||||
}
|
||||
}
|
||||
let h = pattern[0];
|
||||
let f = |code: &str| group(h, code).and_then(|v| v.parse::<f64>().ok());
|
||||
assert!(f("52").is_some_and(|a| (a - 30.0).abs() < 1e-9), "{h:?}");
|
||||
assert!(f("41").is_some_and(|s| (s - 2.0).abs() < 1e-12), "{h:?}");
|
||||
assert_eq!(group(h, "77"), Some("0"), "{h:?}");
|
||||
assert!(group(h, "78").is_some(), "{h:?}");
|
||||
}
|
||||
|
||||
/// A layer state of CADCraft's own record from before states had a mask, a current layer and a
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! A kept 2D constraint group (`ACDBASSOC2DCONSTRAINTGROUP`, the geometric constraints of a
|
||||
//! parametric block) keeps its nodes through the DWG bridge and through DXF of another version.
|
||||
//! AutoCAD 2013 and later write a node's status after its connections, earlier versions right
|
||||
//! after its id; the group was written as read, so the bridge's R2000 DXF gave acadrust every
|
||||
//! node's status and connections from the wrong groups, and AutoCAD refused the DWG of a drawing
|
||||
//! with parametric blocks ("Error Decrypting Data").
|
||||
|
||||
// The DWG bridge and acadrust are unavailable on wasm and FreeBSD ARM64 (#2526).
|
||||
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use acadrust::objects::{AssociativeData, ObjectType};
|
||||
use cadcraft_io::{SaveOptions, Version, write_with};
|
||||
|
||||
/// A drawing of `acadver` whose named object dictionary holds a constraint group with two
|
||||
/// constraints: node 1 (status 1) connected to node 2, node 2 (status 2) connected to node 1.
|
||||
/// `modern` writes the nodes in the 2013+ order.
|
||||
fn dxf(acadver: &str, modern: bool) -> String {
|
||||
let node = |id: u32, status: u32, other: u32| {
|
||||
let (head, tail) = if modern { (String::new(), format!("70\n{status}\n")) } else { (format!("70\n{status}\n"), String::new()) };
|
||||
format!("90\n{id}\n{head}90\n1\n90\n{other}\n{tail}90\n0\n290\n0\n290\n1\n")
|
||||
};
|
||||
format!(
|
||||
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{acadver}\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nACDBASSOC2DCONSTRAINTGROUP\n2\nAcDbAssoc2dConstraintGroup\n3\nObjectDBX Classes\n90\n1025\n280\n0\n281\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n3\nTESTCG\n350\n20\n\
|
||||
0\nACDBASSOC2DCONSTRAINTGROUP\n5\n20\n330\nC\n100\nAcDbAssocAction\n90\n2\n90\n0\n330\n0\n360\n0\n90\n2\n90\n45\n90\n0\n90\n0\n90\n0\n90\n0\n90\n0\n\
|
||||
100\nAcDbAssoc2dConstraintGroup\n90\n2\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n10\n1.0\n20\n0.0\n30\n0.0\n10\n0.0\n20\n1.0\n30\n0.0\n360\n0\n90\n0\n\
|
||||
90\n3\n90\n0\n90\n2\n90\n1\n90\n2\n290\n0\n90\n2\n1\nAcPerpendicularConstraint\n90\n1\n1\nAcPointCoincidenceConstraint\n90\n2\n{}{}\
|
||||
0\nENDSEC\n0\nEOF\n",
|
||||
node(1, 1, 2),
|
||||
node(2, 2, 1)
|
||||
)
|
||||
}
|
||||
|
||||
/// The (id, status, connections) of every non-root node of the document's constraint group.
|
||||
fn nodes(doc: &acadrust::CadDocument) -> Vec<(i32, u8, Vec<i32>)> {
|
||||
let group = doc.objects.values().find_map(|o| match o {
|
||||
ObjectType::Associative(a) => match &a.data {
|
||||
AssociativeData::ConstraintGroup(g) => Some(g.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
});
|
||||
let group = group.expect("the constraint group is written");
|
||||
group.nodes.iter().skip(1).map(|n| (n.node_id, n.status, n.connections.clone())).collect()
|
||||
}
|
||||
|
||||
fn expected() -> Vec<(i32, u8, Vec<i32>)> {
|
||||
vec![(1, 1, vec![2]), (2, 2, vec![1])]
|
||||
}
|
||||
|
||||
fn save(src: &str, name: &str, version: Version) -> Vec<u8> {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = cadcraft_io::read(src.as_bytes(), "a.dxf").expect("read");
|
||||
write_with(&d, name, &SaveOptions { version: Some(version), binary: false }).expect("write")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constraint_group_nodes_survive_the_dwg_bridge() {
|
||||
for (acadver, modern) in [("AC1032", true), ("AC1024", false)] {
|
||||
for version in [Version::R2018, Version::R2010, Version::R2004, Version::R2000] {
|
||||
let dwg = save(&dxf(acadver, modern), "a.dwg", version);
|
||||
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().expect("acadrust reads the DWG");
|
||||
assert_eq!(nodes(&doc), expected(), "{acadver} drawing saved as {version:?} DWG");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constraint_group_nodes_follow_the_dxf_version() {
|
||||
for (acadver, modern) in [("AC1032", true), ("AC1024", false)] {
|
||||
for version in [Version::R2018, Version::R2013, Version::R2010, Version::R2000] {
|
||||
let out = save(&dxf(acadver, modern), "a.dxf", version);
|
||||
let doc = acadrust::DxfReader::from_reader(Cursor::new(out)).expect("dxf").read().expect("acadrust reads the DXF");
|
||||
assert_eq!(nodes(&doc), expected(), "{acadver} drawing saved as {version:?} DXF");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! A hatch boundary stored in a DWG as an elliptic edge keeps its sweep: a circle (0 to 2π) stays a
|
||||
//! circle, so the hatch leaves the hole open. The DWG decoder writes the edge's angles in radians
|
||||
//! and DXF reads degrees, so the circle used to come out as an arc of 6.28 degrees.
|
||||
|
||||
// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works.
|
||||
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
use acadrust::entities::{BoundaryEdge, BoundaryPath, BoundaryPathFlags, EllipticArcEdge, EntityType, Hatch, LineEdge};
|
||||
use acadrust::types::Vector2;
|
||||
use cadcraft_doc::EntityKind;
|
||||
|
||||
fn line(a: (f64, f64), b: (f64, f64)) -> BoundaryEdge {
|
||||
BoundaryEdge::Line(LineEdge { start: Vector2::new(a.0, a.1), end: Vector2::new(b.0, b.1) })
|
||||
}
|
||||
|
||||
/// A DWG with a pattern hatch over a 100 x 100 square with a round hole of radius 10 stored as an
|
||||
/// elliptic edge from `start` to `end` radians.
|
||||
fn dwg_with_hole(start: f64, end: f64) -> Vec<u8> {
|
||||
let mut hatch = Hatch::new();
|
||||
hatch.is_solid = false;
|
||||
let mut outer = BoundaryPath::new();
|
||||
outer.flags = BoundaryPathFlags::EXTERNAL;
|
||||
outer.edges =
|
||||
vec![line((0.0, 0.0), (100.0, 0.0)), line((100.0, 0.0), (100.0, 100.0)), line((100.0, 100.0), (0.0, 100.0)), line((0.0, 100.0), (0.0, 0.0))];
|
||||
let mut hole = BoundaryPath::new();
|
||||
hole.flags = BoundaryPathFlags::DEFAULT;
|
||||
hole.edges = vec![BoundaryEdge::EllipticArc(EllipticArcEdge {
|
||||
center: Vector2::new(50.0, 50.0),
|
||||
major_axis_endpoint: Vector2::new(-10.0, 0.0),
|
||||
minor_axis_ratio: 1.0,
|
||||
start_angle: start,
|
||||
end_angle: end,
|
||||
counter_clockwise: true,
|
||||
})];
|
||||
hatch.paths = vec![outer, hole];
|
||||
let mut doc = acadrust::CadDocument::new();
|
||||
doc.add_entity(EntityType::Hatch(Box::new(hatch))).unwrap();
|
||||
acadrust::DwgWriter::write_to_vec(&doc).unwrap()
|
||||
}
|
||||
|
||||
/// The x range of the hatch's hole, from the bulge polyline the drawing keeps for it.
|
||||
fn hole_extent(dwg: &[u8]) -> (f64, f64) {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = cadcraft_io::read(dwg, "hole.dwg").unwrap();
|
||||
let EntityKind::Hatch(h) = &d.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).expect("the hatch").kind else { panic!("hatch") };
|
||||
let hole = h.loops.iter().find(|l| !l.outer).expect("the hole's loop");
|
||||
let pl = cadcraft_geom::Polyline { vertices: hole.vertices.clone(), closed: true };
|
||||
let mut pts = Vec::new();
|
||||
for s in pl.segments() {
|
||||
s.tessellate(0.01, &mut pts);
|
||||
}
|
||||
let (min, max) = pts.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.x), hi.max(p.x)));
|
||||
(min, max)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_stored_as_an_elliptic_edge_stays_a_circle() {
|
||||
let (min, max) = hole_extent(&dwg_with_hole(0.0, std::f64::consts::TAU));
|
||||
// The hole spans its whole diameter: x from 40 to 60. Read as 6.28 degrees it spanned about 0.07.
|
||||
assert!(max - min > 19.9 && max - min < 20.1, "the hole spans {} in x", max - min);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quarter_arc_stored_as_an_elliptic_edge_keeps_its_quarter() {
|
||||
let (min, max) = hole_extent(&dwg_with_hole(0.0, std::f64::consts::FRAC_PI_2));
|
||||
// From the point at 0 degrees (60, 50) to the one at 90 degrees (50, 60), closed by a chord: x spans 10.
|
||||
assert!(max - min > 9.9 && max - min < 10.5, "the arc spans {} in x", max - min);
|
||||
}
|
||||
@@ -220,3 +220,25 @@ fn a_dwg_keeps_a_sat_text_region_only_before_2013() {
|
||||
assert!(holds_sat(cadcraft_io::Version::R2010), "2010 keeps the SAT text");
|
||||
assert!(!holds_sat(cadcraft_io::Version::R2018), "2018 comes back without it");
|
||||
}
|
||||
|
||||
/// The other way round: a solid whose geometry is only in the data store (a 2013+ file) has no
|
||||
/// SAT text to write to a DXF of 2010 or earlier, which has no data store. Writing it would leave
|
||||
/// an empty 2013-style record (290/2 groups) other programs reject, so it is left out and counted
|
||||
/// there, and kept in 2013 and later (#2334).
|
||||
#[test]
|
||||
fn data_store_solids_are_left_out_of_dxf_2010_and_earlier() {
|
||||
let d = cadcraft_io::read_dxf(dxf().as_bytes()).unwrap();
|
||||
let text = |v: cadcraft_io::Version| {
|
||||
let out = cadcraft_io::write_with(&d, "x.dxf", &cadcraft_io::SaveOptions { version: Some(v), binary: false }).unwrap();
|
||||
String::from_utf8(out).unwrap().replace("\r\n", "\n")
|
||||
};
|
||||
let solids = |t: &str| t.matches("\n0\n3DSOLID\n").count() + t.matches("\n 0\n3DSOLID\n").count();
|
||||
assert_eq!(cadcraft_doc::foreign::acis_dropped(&d, false), [("3DSOLID".to_string(), 2)].into());
|
||||
assert!(cadcraft_doc::foreign::acis_dropped(&d, true).is_empty());
|
||||
for v in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] {
|
||||
let t = text(v);
|
||||
assert_eq!(solids(&t), 0, "{v:?} leaves them out");
|
||||
assert!(!t.contains("AcDbModelerGeometry"), "{v:?} writes no empty modeler record");
|
||||
}
|
||||
assert_eq!(solids(&text(cadcraft_io::Version::R2018)), 2, "2018 keeps them");
|
||||
}
|
||||
|
||||
@@ -284,3 +284,104 @@ fn an_unedited_dimension_keeps_the_block_it_was_read_with() {
|
||||
let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&edited).as_bytes()).unwrap();
|
||||
assert_eq!(circles(&again).0, 0);
|
||||
}
|
||||
|
||||
/// Other programs name a dimension's picture block as they like (DXF group 2 may name any
|
||||
/// block; some exporters write `DIMBLOCK1-<view>`). An unedited dimension keeps that block as
|
||||
/// read, under its own name, as a `*D` one does; no `*D` copy is made next to it (#3299).
|
||||
#[test]
|
||||
fn an_unedited_dimension_keeps_a_block_with_any_name() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
use cadcraft_doc::{Circle, Text};
|
||||
const NAME: &str = "DIMBLOCK1-PLAN";
|
||||
let mut d = Drawing::new_metric();
|
||||
// The picture as the other program drew it: its own text format and a circle CADCraft never
|
||||
// generates for a linear dimension.
|
||||
let mut b = Block::new(NAME);
|
||||
for kind in [
|
||||
EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) }),
|
||||
EntityKind::Circle(Circle { center: Vec3::new(5.0, 3.0, 0.0), radius: 0.25 }),
|
||||
EntityKind::Text(Text {
|
||||
insert: Vec3::new(5.0, 3.5, 0.0),
|
||||
align_pt: None,
|
||||
height: 2.5,
|
||||
value: "10,00".into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
}),
|
||||
] {
|
||||
let h = d.new_handle();
|
||||
b.entities.push(Entity::new(h, kind));
|
||||
}
|
||||
b.base = Vec3::new(1.0, 2.0, 0.0);
|
||||
d.blocks.insert(NAME.into(), Arc::new(b));
|
||||
let mut dm = linear([0.0, 0.0], [10.0, 0.0], [5.0, 3.0]);
|
||||
dm.block = Some(NAME.into());
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap();
|
||||
|
||||
// (block the dimension names, anonymous, base point, its circles, its texts)
|
||||
let picture = |d: &Drawing| {
|
||||
let Some(EntityKind::Dimension(dm)) = d.entity(h).map(|e| &e.kind) else { panic!("dimension lost") };
|
||||
let name = dm.block.clone().unwrap_or_default();
|
||||
let blk = d.block(&name).unwrap();
|
||||
let circles = blk.entities.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
let texts: Vec<String> =
|
||||
blk.entities.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect();
|
||||
(name, blk.anonymous, blk.base, circles, texts)
|
||||
};
|
||||
let kept = (NAME.to_string(), false, Vec3::new(1.0, 2.0, 0.0), 1, vec!["10,00".to_string()]);
|
||||
let dxf = cadcraft_io::write_dxf(&d);
|
||||
assert_eq!(picture(&cadcraft_io::read_dxf(dxf.as_bytes()).unwrap()), kept, "DXF save");
|
||||
assert!(dim_blocks(&dxf).is_empty(), "no *D copy is written: {:?}", dim_blocks(&dxf));
|
||||
let dwg = cadcraft_io::read(&cadcraft_io::write(&d, "a.dwg").unwrap(), "a.dwg").unwrap();
|
||||
assert_eq!(picture(&dwg), kept, "DWG save");
|
||||
|
||||
// Edited (edits drop the link): regenerated from the dimension, as before.
|
||||
let mut edited = d.clone();
|
||||
edited
|
||||
.modify_entity(h, |e| {
|
||||
if let EntityKind::Dimension(dm) = &mut e.kind {
|
||||
dm.block = None;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&edited).as_bytes()).unwrap();
|
||||
let (name, _, _, circles, texts) = picture(&again);
|
||||
assert!(name.starts_with("*D") && circles == 0 && !texts.contains(&"10,00".to_string()), "edited: {name} {circles} {texts:?}");
|
||||
}
|
||||
|
||||
/// A block with another name that a dimension names keeps its record's properties and its
|
||||
/// description through a save; when it is empty the picture is regenerated in world coordinates,
|
||||
/// so the block is written at the origin, not at the read base point, which would shift it.
|
||||
#[test]
|
||||
fn a_kept_dimension_block_with_another_name_keeps_its_properties_and_an_empty_one_is_at_the_origin() {
|
||||
const NAME: &str = "DIMBLOCK2-PLAN";
|
||||
let build = |with_picture: bool| {
|
||||
let mut d = Drawing::new_metric();
|
||||
let mut b = Block::new(NAME);
|
||||
if with_picture {
|
||||
let h = d.new_handle();
|
||||
b.entities.push(Entity::new(h, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) })));
|
||||
}
|
||||
b.base = Vec3::new(1.0, 2.0, 0.0);
|
||||
b.description = "picture of a plan dimension".into();
|
||||
b.units = 4;
|
||||
b.explodable = false;
|
||||
d.blocks.insert(NAME.into(), Arc::new(b));
|
||||
let mut dm = linear([0.0, 0.0], [10.0, 0.0], [5.0, 3.0]);
|
||||
dm.block = Some(NAME.into());
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap();
|
||||
d
|
||||
};
|
||||
let back = |d: &Drawing| {
|
||||
let read = cadcraft_io::read_dxf(cadcraft_io::write_dxf(d).as_bytes()).unwrap();
|
||||
let b = read.block(NAME).expect("the named block is written").as_ref().clone();
|
||||
(b.base, b.description, b.units, b.explodable, b.entities.is_empty())
|
||||
};
|
||||
let props = |base: Vec3| (base, "picture of a plan dimension".to_string(), 4u8, false, false);
|
||||
assert_eq!(back(&build(true)), props(Vec3::new(1.0, 2.0, 0.0)), "kept picture");
|
||||
assert_eq!(back(&build(false)), props(Vec3::ZERO), "regenerated picture");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The anonymous `*D` block written for a dimension (what other programs draw) holds its text at
|
||||
//! the height it is drawn at: the dimension's overrides and DIMSCALE (0 = the drawing's) count
|
||||
//! (issue #367). Angular text also keeps its decimal separator in the stored block (#1646).
|
||||
//! (issue #367). Angular text also keeps its decimal separator in the stored block (#1646), and
|
||||
//! the style's DIMPOST reaches angular dimensions' blocks too (#1653).
|
||||
|
||||
use cadcraft_doc::{Common, DimKind, DimStyle, Dimension, Drawing, EntityKind, Space};
|
||||
use cadcraft_geom::Vec3;
|
||||
@@ -130,3 +131,98 @@ fn dwg_angular_block_text_keeps_the_decimal_separator() {
|
||||
assert_eq!(texts, [expected], "DIMDSEP override: {separator_override:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The group 1 (contents) values of every MTEXT in the BLOCKS section, in file order.
|
||||
fn block_mtext_contents(dxf: &str) -> Vec<String> {
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
let t: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect();
|
||||
let blocks = t.iter().position(|&(c, v)| c == "2" && v == "BLOCKS").unwrap();
|
||||
let end_blocks = blocks + t[blocks..].iter().position(|&(c, v)| c == "0" && v == "ENDSEC").unwrap();
|
||||
let mut out = Vec::new();
|
||||
let mut i = blocks;
|
||||
while let Some(k) = t[i..end_blocks].iter().position(|&(c, v)| c == "0" && v == "MTEXT") {
|
||||
let start = i + k;
|
||||
let end = t[start + 1..end_blocks].iter().position(|&(c, _)| c == "0").map_or(end_blocks, |n| start + 1 + n);
|
||||
// Contents are group 1 (the last chunk) after any 250-char group 3 chunks.
|
||||
out.push(t[start + 1..end].iter().filter(|&&(c, _)| c == "3" || c == "1").map(|&(_, v)| v).collect());
|
||||
i = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An angular dimension whose style sets DIMPOST `post` and one decimal place for angles.
|
||||
fn posted_angular_drawing(kind: DimKind, points: [Vec3; 5], post: &str) -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.dim_styles.iter_mut().for_each(|s| {
|
||||
s.post = post.into();
|
||||
s.angular_decimals = 1;
|
||||
});
|
||||
let [p13, p14, p15, p16, defpt] = points;
|
||||
let dm = Dimension {
|
||||
kind,
|
||||
defpt,
|
||||
text_mid: Vec3::ZERO,
|
||||
p13,
|
||||
p14,
|
||||
p15,
|
||||
p16,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 0.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: None,
|
||||
overrides: Default::default(),
|
||||
assoc: Vec::new(),
|
||||
marks: Default::default(),
|
||||
insertion_point: Vec3::ZERO,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The DXF text of the drawing's one dimension block.
|
||||
fn dxf_block_text(d: &Drawing) -> String {
|
||||
let mut texts = block_mtext_contents(&cadcraft_io::write_dxf(d));
|
||||
assert_eq!(texts.len(), 1, "{texts:?}");
|
||||
texts.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimpost_reaches_three_point_and_two_line_angular_dimension_blocks() {
|
||||
// Vertex p15 at the origin, legs through p13 (0°) and p14 (90°), the arc through defpt.
|
||||
let three_point = posted_angular_drawing(
|
||||
DimKind::Angular3P,
|
||||
[Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO, Vec3::ZERO, Vec3::new(3.0, 3.0, 0.0)],
|
||||
"<> m",
|
||||
);
|
||||
// The DXF is ASCII: the degree sign is its `\U+00B0` escape.
|
||||
assert_eq!(dxf_block_text(&three_point), "90.0\\U+00B0 m");
|
||||
// Lines p13-p14 (along +X) and defpt-p15 (45°), the arc through p16.
|
||||
let two_line = posted_angular_drawing(
|
||||
DimKind::Angular,
|
||||
[Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0), Vec3::new(15.0, 15.0, 0.0), Vec3::new(4.0, 1.5, 0.0), Vec3::new(-5.0, -5.0, 0.0)],
|
||||
"<> m",
|
||||
);
|
||||
assert_eq!(dxf_block_text(&two_line), "45.0\\U+00B0 m");
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn dwg_angular_block_text_keeps_dimpost() {
|
||||
use cadcraft_io::{SaveOptions, Version};
|
||||
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
|
||||
// Vertex p15 at the origin, legs through p13 (0°) and p14 (90°), the arc through defpt.
|
||||
let d = posted_angular_drawing(
|
||||
DimKind::Angular3P,
|
||||
[Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO, Vec3::ZERO, Vec3::new(3.0, 3.0, 0.0)],
|
||||
"<> m",
|
||||
);
|
||||
let dwg = cadcraft_io::write_with(&d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap();
|
||||
let from_dwg = String::from_utf8(craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let mut texts = block_mtext_contents(&from_dwg);
|
||||
assert_eq!(texts.len(), 1, "{texts:?}");
|
||||
assert_eq!(texts.remove(0), "90.0° m");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! #3227: saving kept the layout's plot flags only for the bits CADCraft models and forced 512
|
||||
//! (plot paper space last), 32 (plot with plot styles) and 16 (standard scale) on, so a layout
|
||||
//! with flags 0 came back as 560, in DXF and in DWG.
|
||||
|
||||
use cadcraft_doc::{Drawing, Layout, PageSetup};
|
||||
use cadcraft_io::{read, write};
|
||||
|
||||
/// A drawing with layout SHEET read with plot layout `flags` (lineweights, centring and display
|
||||
/// plot styles follow them, as the reader sets them).
|
||||
fn drawing(flags: i64) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut l = Layout::new("SHEET", 1);
|
||||
l.page = PageSetup {
|
||||
lineweights: flags & 128 != 0,
|
||||
center: flags & 4 != 0,
|
||||
show_plot_styles: flags & 2 != 0,
|
||||
file_plot_flags: Some(flags),
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
d
|
||||
}
|
||||
|
||||
/// The plot layout flags of SHEET after saving `d` as `name` and reading it back.
|
||||
fn flags_after_save(d: &Drawing, name: &str) -> Option<i64> {
|
||||
let bytes = write(d, name).unwrap();
|
||||
let back = read(&bytes, name).unwrap();
|
||||
back.layouts.iter().find(|l| l.name == "SHEET")?.page.file_plot_flags
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plot_layout_flags_are_saved_as_read() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for name in ["sheet.dxf", "sheet.dwg"] {
|
||||
for flags in [0, 176, 560, 688] {
|
||||
assert_eq!(flags_after_save(&drawing(flags), name), Some(flags), "{name}: flags {flags}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_standard_scale_keeps_its_flag_and_choice() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
// Flags 176 with standard scale 25 (1:50): the scale is 0.02, not 1:1, and still standard.
|
||||
let mut d = drawing(176);
|
||||
let page = &mut d.layouts.last_mut().unwrap().page;
|
||||
page.scale = 0.02;
|
||||
page.file_standard_scale = Some((25, 0.02));
|
||||
for name in ["sheet.dxf", "sheet.dwg"] {
|
||||
let back = read(&write(&d, name).unwrap(), name).unwrap();
|
||||
let page = &back.layouts.iter().find(|l| l.name == "SHEET").unwrap().page;
|
||||
assert_eq!(page.file_plot_flags, Some(176), "{name}");
|
||||
assert_eq!(page.file_standard_scale, Some((25, 0.02)), "{name}");
|
||||
}
|
||||
// A scale changed after reading is a custom one: 16 is cleared and the choice dropped.
|
||||
d.layouts.last_mut().unwrap().page.scale = 0.05;
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(160));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_still_decides_the_bits_cadcraft_models() {
|
||||
// Lineweights turned on and a custom scale chosen after reading flags 16: 128 is set and the
|
||||
// standard scale bit cleared, the rest kept.
|
||||
let mut d = drawing(16 | 512);
|
||||
let page = &mut d.layouts.last_mut().unwrap().page;
|
||||
page.lineweights = true;
|
||||
page.scale = 0.02;
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128));
|
||||
// A page made in CADCraft keeps the defaults (plot paper space last, plot with plot styles,
|
||||
// standard scale, lineweights).
|
||||
let mut d = drawing(0);
|
||||
d.layouts.last_mut().unwrap().page = PageSetup::default();
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16));
|
||||
}
|
||||
@@ -36,6 +36,7 @@ mod helix_roundtrip;
|
||||
mod layer_states_acad;
|
||||
mod layout_limits_roundtrip;
|
||||
mod layout_paper_units;
|
||||
mod layout_plot_flags;
|
||||
mod layout_plot_window;
|
||||
mod leader_vertex_elevation;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -68,6 +69,8 @@ mod plot_styles;
|
||||
mod polyface_roundtrip;
|
||||
mod portable_fonts;
|
||||
mod region_roundtrip;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod render_settings_version;
|
||||
mod roundtrip;
|
||||
mod roundtrip_audit;
|
||||
mod skipped_records;
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Render settings store their `AcDbRenderSettings` class version in the form of the file's
|
||||
//! version: a 2013+ file stores it one higher (a 2013 file stores a rapid RT one one lower), as
|
||||
//! acadrust reads and writes them. A kept object carries the form of the file it came from; written
|
||||
//! into a file declaring another version, it takes that version's form. The DWG bridge is an R2000
|
||||
//! DXF for a 2018 DWG: without this, a 2018 drawing's MENTALRAYRENDERSETTINGS went in with the 2018
|
||||
//! form, the DWG writer raised it once more, and BricsCAD refused the DWG ("Object improperly
|
||||
//! read", #907).
|
||||
|
||||
use cadcraft_io::{SaveOptions, Version};
|
||||
|
||||
/// A DXF of `version` with a named object dictionary, its render settings dictionary and one
|
||||
/// mental ray render settings object whose `AcDbRenderSettings` class version is `class_version`.
|
||||
fn dxf(version: &str, kind: &str, class_version: i64) -> String {
|
||||
let body = match kind {
|
||||
"MENTALRAYRENDERSETTINGS" => {
|
||||
"100\nAcDbMentalRayRenderSettings\n90\n2\n90\n0\n90\n1\n70\n2\n40\n3.0\n40\n3.0\n40\n0.05\n40\n0.05\n40\n0.05\n40\n0.05\n\
|
||||
70\n0\n290\n0\n290\n1\n90\n5\n90\n5\n90\n5\n290\n0\n90\n500\n290\n0\n40\n1.0\n90\n10000\n90\n5\n90\n5\n90\n5\n290\n0\n\
|
||||
90\n200\n290\n0\n290\n0\n290\n0\n40\n0.1\n40\n1.0\n40\n1500.0\n70\n0\n70\n0\n40\n10.0\n70\n0\n70\n0\n290\n0\n1\n\n\
|
||||
90\n128\n70\n0\n90\n1048\n290\n0\n40\n1.0\n"
|
||||
}
|
||||
_ => "",
|
||||
};
|
||||
let cpp = match kind {
|
||||
"MENTALRAYRENDERSETTINGS" => "AcDbMentalRayRenderSettings",
|
||||
"RAPIDRTRENDERSETTINGS" => "AcDbRapidRTRenderSettings",
|
||||
_ => "AcDbRenderSettings",
|
||||
};
|
||||
format!(
|
||||
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{version}\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\n{kind}\n2\n{cpp}\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
|
||||
0\n{kind}\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n{class_version}\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n{body}\
|
||||
0\nENDSEC\n0\nEOF\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// The `AcDbRenderSettings` class version of the `kind` object in DXF text.
|
||||
fn class_version(text: &str, kind: &str) -> Option<i64> {
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["0", kind])?;
|
||||
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
|
||||
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
|
||||
}
|
||||
|
||||
fn written(d: &cadcraft_doc::Drawing, version: Version) -> String {
|
||||
String::from_utf8(cadcraft_io::write_with(d, "x.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_settings_class_version_takes_the_declared_versions_form() {
|
||||
let kind = "MENTALRAYRENDERSETTINGS";
|
||||
// From a 2018 file (stored 2 = class version 1 in the 2013+ form).
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap();
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2), "same version: as read");
|
||||
assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(2));
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1), "2000 form: one lower");
|
||||
assert_eq!(class_version(&written(&d, Version::R2010), kind), Some(1));
|
||||
// From a 2000 file (stored 1), written as 2018: one higher.
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1015", kind, 1).as_bytes()).unwrap();
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
|
||||
// Rapid RT settings: the 2013 file alone stores one lower.
|
||||
let kind = "RAPIDRTRENDERSETTINGS";
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1027", kind, 1).as_bytes()).unwrap();
|
||||
assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(1));
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(2));
|
||||
}
|
||||
|
||||
/// A file that declares no `$ACADVER` gives no source form: its kept objects are written as read,
|
||||
/// not as if the new drawing's 2018 were their form.
|
||||
#[test]
|
||||
fn render_settings_without_a_declared_version_are_written_as_read() {
|
||||
let kind = "MENTALRAYRENDERSETTINGS";
|
||||
let text = dxf("AC1032", kind, 1).replace("9\n$ACADVER\n1\nAC1032\n", "");
|
||||
assert!(!text.contains("$ACADVER"));
|
||||
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
assert_eq!(d.foreign.version, None);
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(1));
|
||||
}
|
||||
|
||||
/// Through the DWG bridge (an R2000 DXF for a 2018 DWG) and back, the class version is what the
|
||||
/// 2018 file had: before, it came back one higher each time, and BricsCAD refused the DWG.
|
||||
#[test]
|
||||
fn render_settings_class_version_survives_the_dwg_bridge() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let kind = "MENTALRAYRENDERSETTINGS";
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap();
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
let back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
assert_eq!(class_version(&written(&back, Version::R2018), kind), Some(2), "{}", written(&back, Version::R2018));
|
||||
let dwg = cadcraft_io::write(&back, "x.dwg").unwrap();
|
||||
let again = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
assert_eq!(class_version(&written(&again, Version::R2018), kind), Some(2));
|
||||
}
|
||||
|
||||
/// The conversion mirrors how acadrust stores the value, so it is checked against acadrust itself:
|
||||
/// acadrust reads the fixture and writes it in each version, and CADCraft, reading any of those
|
||||
/// files and saving it in any version, stores what acadrust stores for that version. If acadrust
|
||||
/// changes the encoding, this fails before the DWG bridge drifts.
|
||||
#[test]
|
||||
fn render_settings_class_version_matches_what_acadrust_writes() {
|
||||
use acadrust::DxfVersion;
|
||||
let versions = [
|
||||
(DxfVersion::AC1015, Version::R2000),
|
||||
(DxfVersion::AC1024, Version::R2010),
|
||||
(DxfVersion::AC1027, Version::R2013),
|
||||
(DxfVersion::AC1032, Version::R2018),
|
||||
];
|
||||
// As a 2018 file stores them: mental ray one higher than its class version, rapid RT as is.
|
||||
for (kind, stored) in [("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
|
||||
let source = std::io::Cursor::new(dxf("AC1032", kind, stored).into_bytes());
|
||||
let mut doc = acadrust::DxfReader::from_reader(source).unwrap().read().unwrap();
|
||||
let by_acadrust: Vec<(Version, String)> = versions
|
||||
.iter()
|
||||
.map(|(theirs, ours)| {
|
||||
doc.version = *theirs;
|
||||
(*ours, String::from_utf8(acadrust::DxfWriter::new(&doc).write_to_vec().unwrap()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let forms: Vec<Option<i64>> = by_acadrust.iter().map(|(_, text)| class_version(text, kind)).collect();
|
||||
let expected = if kind == "RAPIDRTRENDERSETTINGS" { [2, 2, 1, 2] } else { [1, 1, 2, 2] };
|
||||
assert_eq!(forms, expected.map(Some), "{kind}: acadrust's own forms for 2000, 2010, 2013, 2018");
|
||||
for (read_from, text) in &by_acadrust {
|
||||
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
for ((declared, _), form) in by_acadrust.iter().zip(&forms) {
|
||||
assert_eq!(class_version(&written(&d, *declared), kind), *form, "{kind}: read from {read_from:?}, saved as {declared:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,7 +257,8 @@ pub(super) fn assert_layouts(a: &Drawing, b: &Drawing, context: &str) {
|
||||
let back = b.layouts.iter().find(|l| l.name == layout.name).expect("layout must survive");
|
||||
assert_eq!(back.tab_order, layout.tab_order, "{context}.{}.tab_order", layout.name);
|
||||
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
|
||||
let setting = |p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, ..p.clone() };
|
||||
let setting =
|
||||
|p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..p.clone() };
|
||||
assert_eq!(setting(&back.page), setting(&layout.page), "{context}.{}.page", layout.name);
|
||||
assert_eq!(back.view, layout.view, "{context}.{}.view", layout.name);
|
||||
compare::entities(a, b, &layout.entities, &back.entities, &format!("{context}.layout[{}]", layout.name));
|
||||
|
||||
@@ -112,7 +112,7 @@ fn layout_page_setup_and_paper_view_round_trip() {
|
||||
for (a, b) in d.layouts.iter().zip(&r.layouts) {
|
||||
assert_eq!(a.name, b.name);
|
||||
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
|
||||
let read = cadcraft_doc::PageSetup { file_paper: None, ..b.page.clone() };
|
||||
let read = cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..b.page.clone() };
|
||||
assert_eq!(a.page, read, "{}", a.name);
|
||||
assert_eq!(a.view, b.view, "{}", a.name);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! The registered applications (APPID) of a file are saved back, in DXF and in DWG, save after
|
||||
//! save, also those no xdata names.
|
||||
|
||||
use cadcraft_doc::Drawing;
|
||||
use cadcraft_io::{read, read_dxf, write, write_dxf};
|
||||
|
||||
/// The records of a DXF: each `(code, value)` from its `0` group on.
|
||||
fn records(text: &str) -> Vec<Vec<(i32, String)>> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut out: Vec<Vec<(i32, String)>> = Vec::new();
|
||||
for chunk in lines.chunks(2) {
|
||||
let [code, value] = chunk else { break };
|
||||
let Ok(c) = code.trim().parse::<i32>() else { continue };
|
||||
let pair = (c, value.trim().to_string());
|
||||
if c == 0 {
|
||||
out.push(vec![pair]);
|
||||
} else if let Some(r) = out.last_mut() {
|
||||
r.push(pair);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The value of the record's first group `code`.
|
||||
fn value(r: &[(i32, String)], code: i32) -> Option<&str> {
|
||||
r.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// A file whose APPID table has `Other_App` (handle 7A00), which no xdata names; with `xdata`,
|
||||
/// a line's xdata names it as `OTHER_APP`.
|
||||
fn source(xdata: bool) -> String {
|
||||
let mut out = String::new();
|
||||
let mut put = |c: i32, v: &str| out.push_str(&format!("{c:>3}\n{v}\n"));
|
||||
for r in records(&write_dxf(&Drawing::new_metric())) {
|
||||
for (c, v) in &r {
|
||||
put(*c, v);
|
||||
}
|
||||
if xdata && r[0].1 == "SECTION" && value(&r, 2) == Some("ENTITIES") {
|
||||
for (c, v) in [
|
||||
(0, "LINE"),
|
||||
(5, "7A01"),
|
||||
(100, "AcDbEntity"),
|
||||
(8, "0"),
|
||||
(100, "AcDbLine"),
|
||||
(10, "0"),
|
||||
(20, "0"),
|
||||
(30, "0"),
|
||||
(11, "10"),
|
||||
(21, "0"),
|
||||
(31, "0"),
|
||||
(1001, "OTHER_APP"),
|
||||
(1000, "x"),
|
||||
] {
|
||||
put(c, v);
|
||||
}
|
||||
}
|
||||
if r[0].1 == "TABLE" && value(&r, 2) == Some("APPID") {
|
||||
let table = value(&r, 5).unwrap_or("0").to_string();
|
||||
for (c, v) in [
|
||||
(0, "APPID"),
|
||||
(5, "7A00"),
|
||||
(330, table.as_str()),
|
||||
(100, "AcDbSymbolTableRecord"),
|
||||
(100, "AcDbRegAppTableRecord"),
|
||||
(2, "Other_App"),
|
||||
(70, "0"),
|
||||
] {
|
||||
put(c, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many APPID records of the DXF are named `Other_App`, in any case.
|
||||
fn appids(text: &str) -> usize {
|
||||
records(text).into_iter().filter(|r| r[0].1 == "APPID" && value(r, 2).is_some_and(|n| n.eq_ignore_ascii_case("Other_App"))).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_applications_no_xdata_names_are_kept() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read_dxf(source(false).as_bytes()).expect("read");
|
||||
for generation in 1..=2 {
|
||||
let text = write_dxf(&d);
|
||||
assert_eq!(appids(&text), 1, "DXF {generation}");
|
||||
d = read_dxf(text.as_bytes()).expect("reread");
|
||||
}
|
||||
for generation in 1..=2 {
|
||||
let dwg = write(&d, "kept.dwg").expect("DWG");
|
||||
d = read(&dwg, "kept.dwg").expect("DWG read");
|
||||
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An application both registered and named by xdata, in another case, gets one record.
|
||||
#[test]
|
||||
fn a_registered_application_xdata_names_gets_one_record() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read_dxf(source(true).as_bytes()).expect("read");
|
||||
for generation in 1..=2 {
|
||||
let text = write_dxf(&d);
|
||||
assert!(text.contains("OTHER_APP"), "DXF {generation}: the line's xdata is kept");
|
||||
assert_eq!(appids(&text), 1, "DXF {generation}");
|
||||
d = read_dxf(text.as_bytes()).expect("reread");
|
||||
}
|
||||
for generation in 1..=2 {
|
||||
let dwg = write(&d, "kept.dwg").expect("DWG");
|
||||
d = read(&dwg, "kept.dwg").expect("DWG read");
|
||||
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Registered applications alone are not kept objects: a file with nothing else to keep notes no
|
||||
/// version, so the DWG writer reads its R2000 text as before rather than as the file's version.
|
||||
#[test]
|
||||
fn registered_applications_alone_note_no_version() {
|
||||
let d = read_dxf(source(false).as_bytes()).expect("read");
|
||||
assert!(d.foreign.appids.iter().any(|n| n == "Other_App"), "{:?}", d.foreign.appids);
|
||||
assert_eq!(d.foreign.version, None);
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
//! fixed-length extension lines (DIMFXL/DIMFXLON), text placement (DIMTAD, DIMTVP, DIMJUST,
|
||||
//! DIMTIH/DIMTOH, DIMGAP, DIMTMOVE) and text formatting (DIMLUNIT, DIMDEC, DIMZIN, DIMRND,
|
||||
//! DIMPOST, DIMTOL/DIMLIM with DIMTZIN and DIMTOLJ, DIMALT with DIMALTU/DIMALTZ/DIMALTRND,
|
||||
//! DIMAZIN, DIMARCSYM) with its background (DIMTFILL).
|
||||
//! DIMAZIN, DIMARCSYM) with its background (DIMTFILL). DIMPOST wraps angles as well, as
|
||||
//! AutoCAD does (#1653).
|
||||
|
||||
use cadcraft_doc::{DimKind, DimStyle, Dimension};
|
||||
use cadcraft_fonts::{MTextParams, TextFont};
|
||||
|
||||
@@ -67,7 +67,7 @@ fn tol_height_code(st: &DimStyle) -> String {
|
||||
}
|
||||
|
||||
/// Apply measurement placeholders or append a dimension suffix, bounding the resulting UTF-8 text.
|
||||
fn post(template: &str, meas: &str) -> String {
|
||||
pub(super) fn post(template: &str, meas: &str) -> String {
|
||||
if template.contains("<>") {
|
||||
bounded_replace(template, meas)
|
||||
} else {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::text::{apply_override, inspected, linear_text};
|
||||
use super::text::{apply_override, inspected, linear_text, post};
|
||||
use super::{Arrowhead, DimConfig, DimGeometry, DimKind, Vec2, ext_line, readable};
|
||||
use crate::units::format_angle_with_separator;
|
||||
use cadcraft_geom::{Arc, ccw_sweep};
|
||||
@@ -178,8 +178,9 @@ pub(super) fn draw_angular(config: &DimConfig<'_>, g: &mut DimGeometry, text_ang
|
||||
g.measurement = sweep;
|
||||
// DIMAZIN 1 / 2 suppress leading / trailing zeros (DIMZIN's bits 4 / 8).
|
||||
let azin = (st.angular_zero_suppression & 3) * 4;
|
||||
let txt = format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator);
|
||||
// DIMPOST is a linear-dimension prefix/suffix; angles have their own format only.
|
||||
// DIMPOST wraps the angle too, as AutoCAD 2026 does to its own 2-line and 3-point
|
||||
// angular dimensions ("36.9° m" for a style with "<> m"; issue #1653, after #376).
|
||||
let txt = post(&st.post, &format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator));
|
||||
g.mtext = inspected(apply_override(&txt, d), d);
|
||||
let mut pts = Vec::new();
|
||||
arc.tessellate(r * 1e-3, &mut pts);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Dimension text formatting (issue #373): DIMRND rounds the measurement only, tolerances use
|
||||
//! DIMTZIN, alternate units DIMALTRND/DIMALTU/DIMALTZ, and DIMPOST is not added to angles.
|
||||
//! DIMTZIN, alternate units DIMALTRND/DIMALTU/DIMALTZ, and DIMPOST wraps angles too (#1653).
|
||||
|
||||
use cadcraft_doc::{DimKind, DimStyle, Dimension};
|
||||
use cadcraft_geom::Vec3;
|
||||
@@ -60,18 +60,23 @@ fn dimrnd_rounds_neither_tolerances_nor_alternate_units() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimpost_is_not_added_to_angular_dimensions() {
|
||||
fn dimpost_applies_to_angular_dimensions_too() {
|
||||
let mut a = linear(0.0);
|
||||
a.kind = DimKind::Angular3P;
|
||||
a.p15 = Vec3::ZERO;
|
||||
a.p13 = Vec3::new(10.0, 0.0, 0.0);
|
||||
a.p14 = Vec3::new(0.0, 10.0, 0.0);
|
||||
a.defpt = Vec3::new(3.0, 3.0, 0.0);
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°");
|
||||
// Linear dimensions keep it, and an angular text override still wraps the angle.
|
||||
// AutoCAD 2026 applies the style's DIMPOST to angular dimensions it builds: with "<> m"
|
||||
// its own 2-line and 3-point dimensions read "36.9° m" (#1653, follow-up to #373/#376).
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°mm");
|
||||
// A prefix before `<>` works as on a linear dimension.
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "A=<>"})), "A=90°");
|
||||
// Linear dimensions keep it, and an angular text override wraps the posted angle, as for
|
||||
// a linear dimension.
|
||||
assert_eq!(text(&linear(10.0), serde_json::json!({"DIMPOST": "<>mm", "DIMDEC": 1})), "10.0mm");
|
||||
a.text = "<> TYP".into();
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90° TYP");
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°mm TYP");
|
||||
}
|
||||
|
||||
fn angular(radians: f64) -> Dimension {
|
||||
|
||||
@@ -133,8 +133,8 @@ pub fn entries(app: &CadApp) -> Vec<Vec<Entry>> {
|
||||
}
|
||||
|
||||
/// The edit commands of the selected objects' type (when they are all of one type), with their
|
||||
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit,
|
||||
/// Polyline Edit, Spline Edit…
|
||||
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit
|
||||
/// and Generate Boundary for hatches, Polyline Edit, Spline Edit…
|
||||
fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
|
||||
let Ok(d) = app.session.doc() else { return Vec::new() };
|
||||
let sel = app.session.selection();
|
||||
@@ -153,7 +153,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
|
||||
}
|
||||
v
|
||||
}
|
||||
EntityKind::Hatch(_) => vec![("hatchedit", None)],
|
||||
EntityKind::Hatch(_) => vec![("hatchedit", None), ("hatchgenerateboundary", None)],
|
||||
EntityKind::LwPolyline(_) | EntityKind::Polyline3d(_) => vec![("pedit", Some("Polyline Edit"))],
|
||||
EntityKind::Spline(_) => vec![("splinedit", Some("Spline Edit"))],
|
||||
EntityKind::Dimension(_) => vec![("dimtedit", None)],
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Drawing text in the interface. egui's bundled faces and the fonts
|
||||
//! [`crate::theme::install_fonts`] loads cover the interface's own languages, but the interface
|
||||
//! also shows drawing text, which can be in any script the drawing uses: MTEXT contents in the
|
||||
//! in-place editor, layer, layout and block names, a prompt that quotes a text. A character none
|
||||
//! of those fonts has would be a box, while the canvas draws it from a fallback font.
|
||||
//!
|
||||
//! An egui font provider closes that gap: egui asks it once per family and character no
|
||||
//! installed font has, and it answers with the face drawing text takes for that character
|
||||
//! ([`cadcraft_fonts::ttf::fallback_for`]), so the interface shows what the canvas shows. The
|
||||
//! provider hands egui the font table's own bytes: nothing is bundled, read again or copied.
|
||||
//!
|
||||
//! A fallback face is sized to the interface text, not to its own em: the Thai faces drawings use
|
||||
//! (Cordia New, Angsana New) draw their letters small for their size, so their consonants are
|
||||
//! scaled up to the interface's x-height ([`scale`]). Its glyphs sit on the interface text's
|
||||
//! baseline, and a line with them grows to fit their stacked marks.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_fonts::ttf::Face;
|
||||
|
||||
/// Let egui ask the drawing-text fallback for characters no interface font has. Once per
|
||||
/// context: providers outlive the `set_fonts` of [`crate::theme::install_fonts`], so a second
|
||||
/// call (a language change) adds nothing.
|
||||
pub(crate) fn install(ctx: &egui::Context) {
|
||||
let id = egui::Id::unique("cadcraft::drawing_fonts");
|
||||
let installed = ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::<bool>(id), true));
|
||||
if !installed {
|
||||
ctx.add_font_provider(Arc::new(|request: &egui::FallbackRequest<'_>| font_for(request.cluster, cadcraft_fonts::ttf::fallback_for)));
|
||||
}
|
||||
}
|
||||
|
||||
/// How tall a lowercase x is in the interface faces, in ems (Ubuntu Light, egui's bundled face,
|
||||
/// 0.52; Segoe UI 0.50). A Thai consonant without ascender or descender (ก) is about as tall in
|
||||
/// the Thai faces made for screens (Leelawadee UI 0.51, Tahoma and Noto Sans Thai 0.56).
|
||||
const X_HEIGHT: f64 = 0.52;
|
||||
/// The most a fallback face is scaled up, so a face with an odd or tiny reference letter never
|
||||
/// draws huge text. Cordia New needs 1.28, Angsana New 1.30.
|
||||
const MAX_SCALE: f64 = 1.5;
|
||||
|
||||
/// The font for the first character of `cluster`: the face `fallback` finds for it, if any.
|
||||
fn font_for(cluster: &str, fallback: impl Fn(char) -> Option<Face>) -> Option<egui::FontInsert> {
|
||||
let c = cluster.chars().next()?;
|
||||
fallback(c).map(|face| font_insert(&face, c))
|
||||
}
|
||||
|
||||
/// The letter of `c`'s script that the interface's x-height measures: a Thai consonant without
|
||||
/// ascender or descender, else the face's own Latin x.
|
||||
fn reference_letter(c: char) -> char {
|
||||
if ('\u{0e00}'..='\u{0e7f}').contains(&c) { 'ก' } else { 'x' }
|
||||
}
|
||||
|
||||
/// How much a face is scaled up whose reference letter is `height` ems tall: to [`X_HEIGHT`],
|
||||
/// at most [`MAX_SCALE`]. A face that is already big enough, or whose letter has no height, keeps
|
||||
/// its size.
|
||||
fn scale(height: Option<f64>) -> f32 {
|
||||
height.filter(|h| h.is_finite() && *h > 0.0).map_or(1.0, |h| (X_HEIGHT / h).clamp(1.0, MAX_SCALE) as f32)
|
||||
}
|
||||
|
||||
/// `face`, found for character `c`, as an egui font: the font table's bytes, shared rather than
|
||||
/// copied, under a name that is the same for every character of the face, so egui loads the face
|
||||
/// once (sized by the first character's script); scaled to the interface text and on its baseline.
|
||||
fn font_insert(face: &Face, c: char) -> egui::FontInsert {
|
||||
let name = format!("drawing-text-{:p}-{}-{}", Arc::as_ptr(&face.bytes), face.bytes.len(), face.index);
|
||||
let tweak = egui::FontTweak {
|
||||
scale: scale(face.glyph_height(reference_letter(c))),
|
||||
fallback_align: egui::epaint::text::FallbackAlign::Baseline,
|
||||
..Default::default()
|
||||
};
|
||||
egui::FontInsert::new(&name, egui::FontData::from_blob(face.bytes.clone(), face.index).tweak(tweak), Vec::new())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A face from one of egui's bundled fonts (there are no font files in this repository).
|
||||
fn bundled_face() -> Face {
|
||||
let defs = egui::FontDefinitions::default();
|
||||
let bytes = defs.font_data.get("Hack").map(|d| d.bytes().to_vec()).unwrap_or_default();
|
||||
Face::new(Arc::new(bytes), 0).expect("egui bundles Hack")
|
||||
}
|
||||
|
||||
/// Every character of a face names the same font, whose bytes are the face's own (not a
|
||||
/// copy); a character without a fallback face, or no character, gets no font.
|
||||
#[test]
|
||||
fn a_fallback_face_is_one_shared_font() {
|
||||
let face = bundled_face();
|
||||
let fallback = |c: char| (c != '\u{e000}').then(|| face.clone());
|
||||
let a = font_for("ก", fallback).expect("a font");
|
||||
let b = font_for("ขั", fallback).expect("a font");
|
||||
assert_eq!(a.name, b.name);
|
||||
assert!(std::ptr::eq(a.data.bytes().as_ptr(), face.bytes.as_ptr()), "the font table's bytes, not a copy");
|
||||
assert_eq!(a.data.index, face.index);
|
||||
assert!(font_for("\u{e000}", fallback).is_none());
|
||||
assert!(font_for("", fallback).is_none());
|
||||
let other = Face::new(Arc::new(face.bytes.as_ref().clone()), 0).expect("a second copy parses");
|
||||
assert_ne!(font_insert(&other, 'ก').name, a.name, "another file is another font");
|
||||
assert_eq!(a.data.tweak.fallback_align, egui::epaint::text::FallbackAlign::Baseline, "on the interface text's baseline");
|
||||
}
|
||||
|
||||
/// A face whose reference letter is short is scaled up to the interface's x-height, at most
|
||||
/// by half; one that is tall enough, or can't be measured, keeps its size.
|
||||
#[test]
|
||||
fn short_faces_are_scaled_to_the_interface_x_height() {
|
||||
assert_eq!(reference_letter('ค'), 'ก');
|
||||
assert_eq!(reference_letter('\u{0e4c}'), 'ก', "a Thai mark measures by the consonant too");
|
||||
assert_eq!(reference_letter('א'), 'x');
|
||||
// Cordia New's ก is 0.405 em.
|
||||
assert!((f64::from(scale(Some(0.405))) * 0.405 - X_HEIGHT).abs() < 1e-6);
|
||||
assert_eq!(scale(Some(0.56)), 1.0, "never scaled down");
|
||||
assert_eq!(scale(Some(0.01)), MAX_SCALE as f32);
|
||||
for unmeasured in [None, Some(0.0), Some(-1.0), Some(f64::NAN), Some(f64::INFINITY)] {
|
||||
assert_eq!(scale(unmeasured), 1.0, "{unmeasured:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every Thai face found here (Cordia New, Angsana New on Windows; Noto Sans Thai from
|
||||
/// craft-fonts in CI) draws ก at least as tall as the interface's x-height, and is never shrunk.
|
||||
#[test]
|
||||
fn thai_faces_draw_their_consonants_at_the_interface_x_height() {
|
||||
let names = ["Cordia New", "Angsana New", "Browallia New", "Noto Sans Thai", "IBM Plex Sans Thai", "Leelawadee UI", "Tahoma"];
|
||||
let faces = names.iter().filter_map(|n| cadcraft_fonts::ttf::find(n)).chain(cadcraft_fonts::ttf::fallback_for('ก'));
|
||||
for face in faces.filter(|f| f.has_glyph('ก')) {
|
||||
let height = face.glyph_height('ก').unwrap_or_default();
|
||||
let drawn = height * f64::from(font_insert(&face, 'ก').data.tweak.scale);
|
||||
let family = face.family_name();
|
||||
assert!(drawn >= X_HEIGHT - 1e-6, "{family:?}: ก drawn {drawn} em");
|
||||
assert!(drawn <= height.max(X_HEIGHT) + 1e-6, "{family:?}: ก drawn {drawn} em, not shrunk or overshot");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -374,6 +374,7 @@
|
||||
From Desde
|
||||
From Template... Desde plantilla...
|
||||
General General
|
||||
Generate Boundary Generar contorno
|
||||
Geometric Center Centro geométrico
|
||||
Geometric Constraint Restricción geométrica
|
||||
Geometric Constraints Restricciones geométricas
|
||||
|
||||
|
@@ -296,6 +296,7 @@
|
||||
Freeze/Thaw in the current viewport 在当前视口中冻结/解冻
|
||||
From 自
|
||||
General 常规
|
||||
Generate Boundary 生成边界
|
||||
Geometric Center 几何中心
|
||||
Geometric Constraint 几何约束
|
||||
Geometric Constraints 几何约束
|
||||
|
||||
|
@@ -32,6 +32,7 @@ pub mod control;
|
||||
pub mod credits;
|
||||
pub mod dialogs;
|
||||
pub mod docking;
|
||||
mod drawing_fonts;
|
||||
pub mod fault;
|
||||
// The Find and Replace window behind the FIND command.
|
||||
pub mod finddlg;
|
||||
@@ -1065,6 +1066,7 @@ impl CadApp {
|
||||
let ctx = &ctx;
|
||||
let language = self.language();
|
||||
if self.fonts_language != Some(language) {
|
||||
drawing_fonts::install(ctx);
|
||||
theme::install_fonts(ctx, language);
|
||||
self.fonts_language = Some(language);
|
||||
}
|
||||
|
||||
@@ -658,6 +658,11 @@ fn fields(ui: &mut egui::Ui, d: &Drawing, st: &mut State) {
|
||||
combo(ui, egui::Id::unique(id), &cur, options)
|
||||
}
|
||||
});
|
||||
let new = new.map(|v| match (p.field, v.as_str()) {
|
||||
// An empty per-end name inherits DIMBLK.
|
||||
("arrowBlock1" | "arrowBlock2", Some("")) => json!("_CLOSEDFILLED"),
|
||||
_ => v,
|
||||
});
|
||||
if let Some(v) = new.filter(|v| *v != cur) {
|
||||
st.values.insert(p.field.into(), v);
|
||||
}
|
||||
|
||||
@@ -882,4 +882,40 @@ mod tests {
|
||||
assert!((big - 2.0 * height).abs() < 1e-9, "{big} for a {height} text");
|
||||
assert_eq!(st.fmt.fmt_at(5).height, None, "the rest keeps the text's height");
|
||||
}
|
||||
|
||||
/// A Thai MTEXT, which the canvas draws from a Thai fallback font, opens in the editor in
|
||||
/// letters, not boxes: the app's interface fonts take the face drawing text takes for a
|
||||
/// character they lack. Both interface families do, so Thai typed at the command line or in a
|
||||
/// layer name (proportional) and a FIND result (monospace) are letters too (#2949). Runs where
|
||||
/// a Thai face is found (CI embeds craft-fonts' Noto Sans Thai).
|
||||
#[test]
|
||||
fn thai_text_opens_in_the_editor_without_boxes() {
|
||||
let thai = "แบบขยายผนังห้องน้ำ ชั้นที่ ๒";
|
||||
let letters: Vec<char> = thai.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
if letters.iter().any(|c| cadcraft_fonts::ttf::fallback_for(*c).is_none()) {
|
||||
return;
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.run("mtext", serde_json::json!({ "at": [0, 20], "text": thai, "height": 2.5, "width": 40 })).unwrap();
|
||||
app.start("textedit");
|
||||
app.session.input(cadcraft_engine::Input::Point(cadcraft_geom::Vec2::new(1.0, 19.0))).unwrap();
|
||||
// Real app frames: the fonts are the ones the app installs.
|
||||
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() };
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(input.clone(), |ui| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
assert_eq!(ctx.data_mut(|d| d.get_temp::<State>(state_id())).expect("editor open").fmt.text(), thai);
|
||||
let mut missing = Vec::new();
|
||||
ctx.fonts_mut(|f| {
|
||||
for font in [FontId::proportional(MIN_PX), FontId::monospace(MIN_PX)] {
|
||||
missing.extend(letters.iter().filter(|c| !f.has_glyph(&font, **c)).map(|c| format!("{:?} {c}", font.family)));
|
||||
}
|
||||
});
|
||||
assert!(missing.is_empty(), "drawn as boxes: {missing:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Asking before a save throws content away. DWG can't yet hold everything a drawing read from
|
||||
//! another program keeps (`cadcraft_engine::cmd::file::not_saved`), a DXF of 2013 or later can't
|
||||
//! hold a solid's SAT text (`cadcraft_doc::foreign::sat_text_dropped`), and QSAVE replaces the file
|
||||
//! another program keeps (`cadcraft_engine::cmd::file::not_saved`), a DXF can't hold every solid
|
||||
//! or proxy of every version (`cadcraft_engine::cmd::file::loss_on_save`), and QSAVE replaces the file
|
||||
//! that still has it, so File ▸ Save, its shortcut or typing QSAVE says what would go first:
|
||||
//! Save Anyway / Save As... / Cancel. Agreeing lasts for that same loss on that same file, so
|
||||
//! later saves in the session don't ask again; the file no longer holds what was agreed to.
|
||||
@@ -14,7 +14,7 @@ use egui::{RichText, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use cadcraft_engine::autosave::isavebak;
|
||||
use cadcraft_engine::cmd::file::{backup_path, loss_on_save, save_keeps_current};
|
||||
use cadcraft_engine::cmd::file::{Version, backup_path, drawing_version, loss_on_save, save_keeps_current};
|
||||
|
||||
use crate::CadApp;
|
||||
use crate::theme::Tokens;
|
||||
@@ -44,6 +44,8 @@ pub struct Accepted {
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Pending {
|
||||
loss: Accepted,
|
||||
/// The version the file would be saved in: which DXF keeps what it loses depends on it.
|
||||
version: Version,
|
||||
}
|
||||
|
||||
impl Pending {
|
||||
@@ -78,13 +80,14 @@ impl CadApp {
|
||||
if self.save_loss_accepted.as_ref() == Some(&loss) {
|
||||
return false;
|
||||
}
|
||||
self.save_loss = Some(Pending { loss });
|
||||
let version = drawing_version(&self.session, &loss.path);
|
||||
self.save_loss = Some(Pending { loss, version });
|
||||
true
|
||||
}
|
||||
|
||||
/// Answer the open warning (no-op without one).
|
||||
pub fn answer_save_loss(&mut self, choice: Choice) {
|
||||
let Some(Pending { loss }) = self.save_loss.take() else { return };
|
||||
let Some(Pending { loss, .. }) = self.save_loss.take() else { return };
|
||||
// The drawing can go away, or stop being the active one, while the warning is up.
|
||||
let i = self.session.docs.iter().position(|d| d.uid == loss.uid);
|
||||
match (choice, i) {
|
||||
@@ -108,6 +111,38 @@ impl CadApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which files keep what a save would lose: the hint under the warning.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Keeps {
|
||||
/// A DXF before 2007 leaves out proxies whose strings it can't hold (#3229).
|
||||
Dxf2007,
|
||||
/// A DXF of 2013 or later leaves out a solid's SAT text.
|
||||
Dxf2010,
|
||||
/// A DXF before 2013 leaves out a solid whose geometry only the data store holds (#2334), and
|
||||
/// 2013 keeps the proxies a file before 2007 leaves out too.
|
||||
Dxf2013,
|
||||
/// Any other file: DXF keeps everything.
|
||||
Dxf,
|
||||
}
|
||||
|
||||
/// The hint for saving to `path` at `version` and losing `lost`. A path names a DXF the way the
|
||||
/// save does (`Format::from_path`), so a name without an extension is a DXF too.
|
||||
fn keeps_hint(path: &std::path::Path, lost: &BTreeMap<String, usize>, version: Version) -> Keeps {
|
||||
if cadcraft_doc::Format::from_path(path) != Some(cadcraft_doc::Format::Dxf) {
|
||||
return Keeps::Dxf;
|
||||
}
|
||||
// A 2013 or later file only leaves out solids with SAT text alone. Before 2013 it leaves out
|
||||
// solids whose geometry is in the data store, and before 2007 also proxies, with what they
|
||||
// own (an XRECORD, a DICTIONARY).
|
||||
if version >= Version::R2013 {
|
||||
Keeps::Dxf2010
|
||||
} else if lost.keys().any(|k| ["3DSOLID", "REGION", "BODY"].iter().any(|m| k.eq_ignore_ascii_case(m))) {
|
||||
Keeps::Dxf2013
|
||||
} else {
|
||||
Keeps::Dxf2007
|
||||
}
|
||||
}
|
||||
|
||||
/// The warning, while a save waits for an answer. Cancel is what Escape does.
|
||||
pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
|
||||
let Some(pending) = app.save_loss.clone() else { return };
|
||||
@@ -121,10 +156,11 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
|
||||
ui.label(RichText::new(crate::tf!("Saving {name} will remove content", name = file)).strong());
|
||||
ui.add_space(4.0);
|
||||
ui.label(crate::tf!("This format can't keep these objects yet: {objects}.", objects = pending.summary()));
|
||||
let keeps = if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dxf")) {
|
||||
crate::tl!("DXF 2010 and earlier keep them. Use Save As to keep them in the drawing.")
|
||||
} else {
|
||||
crate::tl!("DXF keeps them. Use Save As to keep them in the drawing.")
|
||||
let keeps = match keeps_hint(path, &pending.loss.lost, pending.version) {
|
||||
Keeps::Dxf2007 => crate::tl!("DXF 2007 and later keep them. Use Save As to keep them in the drawing."),
|
||||
Keeps::Dxf2013 => crate::tl!("DXF 2013 and later keep them. Use Save As to keep them in the drawing."),
|
||||
Keeps::Dxf2010 => crate::tl!("DXF 2010 and earlier keep them. Use Save As to keep them in the drawing."),
|
||||
Keeps::Dxf => crate::tl!("DXF keeps them. Use Save As to keep them in the drawing."),
|
||||
};
|
||||
ui.label(RichText::new(keeps).color(t.text_dim));
|
||||
let on_disk = if save_keeps_current(path) {
|
||||
@@ -158,3 +194,35 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn lost(kind: &str) -> BTreeMap<String, usize> {
|
||||
BTreeMap::from([(kind.to_string(), 1)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_without_an_extension_is_a_dxf_for_the_hint() {
|
||||
let path = std::path::Path::new("plans/site");
|
||||
let old = Version::R2000;
|
||||
assert_eq!(keeps_hint(path, &lost("ACAD_PROXY_ENTITY"), old), Keeps::Dxf2007);
|
||||
assert_eq!(keeps_hint(path, &lost("3DSOLID"), Version::R2018), Keeps::Dxf2010);
|
||||
let with_owned = BTreeMap::from([("ACAD_PROXY_OBJECT".to_string(), 1), ("XRECORD".to_string(), 2)]);
|
||||
assert_eq!(keeps_hint(path, &with_owned, old), Keeps::Dxf2007);
|
||||
assert_eq!(keeps_hint(std::path::Path::new("plans/site.DXF"), &lost("ACAD_PROXY_ENTITY"), old), Keeps::Dxf2007);
|
||||
assert_eq!(keeps_hint(std::path::Path::new("plans/site.dwg"), &lost("ACAD_PROXY_ENTITY"), old), Keeps::Dxf);
|
||||
}
|
||||
|
||||
/// A DXF before 2013 leaves out solids whose geometry only the data store holds (#2334): 2013
|
||||
/// and later keep them, so the hint doesn't send the user to 2010 or earlier, which would lose
|
||||
/// them again; with a proxy loss beside them, 2013 keeps both.
|
||||
#[test]
|
||||
fn a_solid_lost_before_2013_is_kept_from_2013() {
|
||||
let path = std::path::Path::new("plans/site.dxf");
|
||||
assert_eq!(keeps_hint(path, &lost("3DSOLID"), Version::R2010), Keeps::Dxf2013);
|
||||
let both = BTreeMap::from([("ACAD_PROXY_ENTITY".to_string(), 1), ("REGION".to_string(), 1)]);
|
||||
assert_eq!(keeps_hint(path, &both, Version::R2000), Keeps::Dxf2013);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +95,31 @@ fn modify_edits_the_style() {
|
||||
assert_eq!(h.state().ui.dialog.as_deref(), Some("dimstyle"), "back to the list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modify_keeps_closed_filled_per_end_arrowheads() {
|
||||
let mut h = manager(|app| {
|
||||
app.run("dimstyle", json!({ "name": "Standard", "DIMBLK": "_DOT" })).unwrap();
|
||||
});
|
||||
click(&mut h, "Modify...");
|
||||
click(&mut h, "Symbols and Arrows");
|
||||
for label in ["Arrow 1", "Arrow 2"] {
|
||||
h.get(by().label(label).role(egui::accesskit::Role::ComboBox)).click();
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Closed filled");
|
||||
}
|
||||
click(&mut h, "OK");
|
||||
let style = h.state().session.doc().unwrap().dim_style("Standard").unwrap();
|
||||
assert_eq!(style.arrow_block, "_DOT");
|
||||
assert_eq!(style.arrow_block1, "_CLOSEDFILLED");
|
||||
assert_eq!(style.arrow_block2, "_CLOSEDFILLED");
|
||||
|
||||
click(&mut h, "Modify...");
|
||||
click(&mut h, "Symbols and Arrows");
|
||||
for label in ["Arrow 1", "Arrow 2"] {
|
||||
h.get(by().label(label).role(egui::accesskit::Role::ComboBox).value("Closed filled"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_leaves_the_style_alone() {
|
||||
let mut h = manager(|_| {});
|
||||
|
||||
+16
-14
@@ -1,6 +1,6 @@
|
||||
# Where CADCraft falls short of AutoCAD
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (re-audit against main 7cee28580: file-test and catalog counts, REFEDIT, dynamic-block and QSAVE rows; previously: QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated; previously: BEDIT in the Block Editor switches blocks: F3 updated; previously: Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected; previously: DIMTFILL limits in the `*D` block, EXPLODE and DXF: F7 updated; re-audit against main 41d9b5e95: CI gate (#6, S1), MVIEW Restore (F15, U11), open-PR and catalog counts, file-test count; previously: Command Aliases dialog for ALIASEDIT: U12 and E5 narrowed) · **Target:** Autodesk AutoCAD 2027
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (alpha-blocker marks follow the six-row gate of 2026-11-19; rows updated for what merged on 2026-11-19 and 2026-11-20: the Dimension Style Manager, the UCS command, in-place TEXT editing, -ATTEDIT, -RENAME and -LAYER options, ARRAY Key point, right-click settings and the interface reset; new row P4 for startup on older graphics hardware; previously: re-audit against main 7cee28580: file-test and catalog counts, REFEDIT, dynamic-block and QSAVE rows; previously: QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated; previously: BEDIT in the Block Editor switches blocks: F3 updated; previously: Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected; previously: DIMTFILL limits in the `*D` block, EXPLODE and DXF: F7 updated; re-audit against main 41d9b5e95: CI gate (#6, S1), MVIEW Restore (F15, U11), open-PR and catalog counts, file-test count; previously: Command Aliases dialog for ALIASEDIT: U12 and E5 narrowed) · **Target:** Autodesk AutoCAD 2027
|
||||
|
||||
Every known shortfall, one row each, ranked within each section by user impact. This is the work
|
||||
list: agents pick from here (top of a section first). A PR names the rows it closes in its
|
||||
@@ -16,7 +16,7 @@ do them first.
|
||||
| 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors; the ACIS data of 3D solids, regions and bodies is kept, #781; a user's QSAVE now asks before replacing the file and keeps the previous one as `.bak`, which reduces the harm but does not close this row) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) |
|
||||
| 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | All 88 file tests (`crates/io/src/tests.rs`) use synthetic data (the real-file runs in PRs #781 and #859 were manual and are not committed); nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 10–15 + human | [file formats](file-format-parity.md#tests) |
|
||||
| 3 | **Ellipse and spline geometry is tessellated** (intersections, offsets, closest points; polyline offset recomputes arc bulges since #825 but has no loop cleanup) | Coordinates are subtly wrong; offsets of ellipses come out as polylines | 30–50 | [geometry](geometry-parity.md) |
|
||||
| 4 | **[alpha blocker]** **No dynamic-block authoring; xrefs can't be edited in place** (REFEDIT, REFSET and REFCLOSE edit block references in place, #818; XCLIP and XCLIPFRAME clip block and xref references, #2354; dynamic block references are read and edited, #838–#883; xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) |
|
||||
| 4 | **No dynamic-block authoring; xrefs can't be edited in place** (REFEDIT, REFSET and REFCLOSE edit block references in place, #818; XCLIP and XCLIPFRAME clip block and xref references, #2354; dynamic block references are read and edited, #838–#883; xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them; counted under beta since the gate revision of 2026-11-19 (few reports) | 55–90 | [features](#features) |
|
||||
| 5 | **No autosave in the web build** (the desktop app has SAVETIME autosave, Drawing Recovery, AUDIT and RECOVER since #406) | Browser users lose unsaved work when the tab or the browser goes down | 3–5 | [features](#features) |
|
||||
| 6 | ~~**No CI runs the Rust tests on pull requests**~~ fixed: `.github/workflows/ci.yml` runs `cargo xtask ci` on every pull request and push to main through the shared gate workflow (#1987); `cargo fmt` on main is fixed. | — | 0 | [stability](#stability) |
|
||||
|
||||
@@ -24,15 +24,15 @@ do them first.
|
||||
|
||||
| # | Gap | Evidence | User impact | Est. |
|
||||
|---|---|---|---|---|
|
||||
| F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations, DVIEW CAmera, TArget, Distance, POints, CLip and Hide (they need a 3D camera; TWist, PAn, Zoom, Off and Undo work). SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs`, `cmd/view/dview.rs` | Low: the most-used commands are done | 1–3 |
|
||||
| F1 | Prompt options that still print "not available yet": colour books in -ATTEDIT Color, -RENAME of materials and plot styles, -LAYER stAte Import and EXport, DVIEW CAmera, TArget, Distance, POints, CLip and Hide (they need a 3D camera; TWist, PAn, Zoom, Off and Undo work). -ATTEDIT one-at-a-time Position, Height, Angle and Style, -RENAME of viewport configurations and -LAYER stAte landed (#3311); the new -ATTEDIT prompt texts are not yet compared with AutoCAD's. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs`, `cmd/view/dview.rs` | Low: the most-used commands are done | 1–3 |
|
||||
| F2 | XREF editing in place: REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XCLIP clips a block or xref reference to a rectangular, polygonal or closed-polyline boundary (Invert clip, ON/OFF, Delete, generate Polyline; Clipdepth is ignored in 2D), drawn, plotted and framed as XCLIPFRAME says, with the extents cut to it, and kept through DXF and DWG as the reference's SPATIAL_FILTER (2026-10-27). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place | 12–20 |
|
||||
| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 |
|
||||
| F3 | No dynamic-block authoring (beta checklist): parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 |
|
||||
| F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 |
|
||||
| F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 |
|
||||
| F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 |
|
||||
| F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) (the Key point base point of ARRAY and ARRAYEDIT landed, #2368), levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 |
|
||||
| F7 | Dimensions: no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (the Dimension Style Manager, -DIMSTYLE and dimension properties landed, #1460; an edited dimension keeps its values on save, #3335; style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 |
|
||||
| F8 | TOLERANCE leftovers (feature control frames landed, #420: model, our own symbol drawing, DXF, command-line prompts, explode, grips): no Geometric Tolerance dialog, no LEADER/QLEADER tolerance annotation, no in-place editing of a frame's contents | `cmd/tolerance.rs` | Low-medium (mechanical) | 2–4 |
|
||||
| F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 6 settings (arrow size, text height, landing gap, dogleg, text style, annotative; block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `cmd/mleader_edit.rs`, `doc/src/tables.rs` | Medium | 8–12 |
|
||||
| F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, existing TEXT is edited as plain text on the command line with TEXTEDIT (alias DDEDIT; a double-click starts it, #868), while an existing MTEXT opens in the in-place editor with its contents (#1002, merged 2026-11-06); stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 |
|
||||
| F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, a double-click edits existing TEXT, an attribute definition or a dimension's text in a box on the canvas (#3345; table cells are not edited in place, and the box was not checked on a HiDPI screen or in a twisted view), and an existing MTEXT opens in the in-place editor with its contents (#1002); stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 |
|
||||
| F11 | Tables (cell styles, formulas, TABLEDIT, TABLEEXPORT, table breaking and CSV data links landed, #534): formulas aren't read from or written as AutoCAD FIELD objects (other programs see values); number formats apply to formula results only; cell text doesn't wrap; custom cell styles, breaks and data links travel as CADCraft xdata (not through DWG); data links read CSV only (no Excel ranges, no write-back, not on the web); no cell-style tab in the Table Style dialog | `cmd/table/*`, `io/dxf_table.rs` | Low-medium | 6–10 |
|
||||
| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, AutoCAD files' per-object scale contexts (read as not annotative) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 |
|
||||
| F14 | **[alpha blocker]** Plotting leftovers: binary `.ctb`/`.stb`/`.pc3` files can't be read; no system printers (H3); the page setup's "Plot transparency" is not saved in DXF/DWG (the public DXF Reference has no plot layout flag for it), so it lasts for the session and in JSON only. The Plot dialog (#160), Plot Preview and PUBLISH (#186), plot styles (CTB and STB, [plot-styles.md](plot-styles.md), #410) with their end, join and fill styles, plotter devices with paper sizes and printable areas ([plotters.md](plotters.md), #564), and plotted transparency (page setup and Plot dialog option, PLOTTRANSPARENCYOVERRIDE) landed | `io/src/plotter.rs`, `cmd/plotters.rs` | Medium | 4–8 |
|
||||
@@ -41,11 +41,11 @@ do them first.
|
||||
| F16 | Groups: no group bounding box or single grip when a group is selected (GROUPDISPLAYMODE), copying a whole group does not make a new group, no Object Grouping dialog (GROUP, GROUPEDIT, UNGROUP, -GROUP, PICKSTYLE group selection and the DXF/DWG round trip landed, #417); PICKSTYLE's associative-hatch bit is stored but unused | `cmd/groups.rs` | Low | 2–4 |
|
||||
| F17 | Attributes (ATTSYNC, global -ATTEDIT, BATTMAN editing and DATAEXTRACTION/EATTEXT landed, #433): the Verify, Preset and Lock position modes are kept in files and Lock position is applied by INSERT and ATTSYNC (#876), but INSERT doesn't act on Verify or Preset, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 |
|
||||
| F19 | MATCHPROP Settings is a keyword prompt (no dialog) and has no material, shadow or centre-object settings; TEXTTOFRONT and HATCHTOBACK act on the current space only; OVERKILL doesn't compare polyline segments with other objects (picker and Settings, DRAWORDER Above/Under, TEXTTOFRONT, HATCHTOBACK, OVERKILL tolerance/ignore/overlap/end-to-end options landed, #439) | `props/matchprop.rs`, `draworder.rs`, `overkill.rs` | Low | 2–4 |
|
||||
| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export Open and Save has the backup copy checkbox (ISAVEBAK). | `ui-egui/src/options/` | Low | 2–4 |
|
||||
| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Right-Click Customization and the time-sensitive right-click landed (#2371, #3307), and Reset restores the whole interface (#3308). Left: the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export Open and Save has the backup copy checkbox (ISAVEBAK). | `ui-egui/src/options/` | Low | 2–4 |
|
||||
| F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data) | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 |
|
||||
| F22 | Inquiry leftovers (COUNT across spaces and nested blocks, the QuickCalc palette and COMPARE landed, #563; MASSPROP on regions, #510): COMPARE compares the tab shown, not every layout at once (COMPAREEXPORT, the comparison as a new drawing, landed); COMPAREEXPORT puts the two sets of objects in model-space groups, where AutoCAD puts them in blocks; QuickCalc keeps its history and variables for the session only | `file/compare.rs`, `palettes/quickcalc.rs` | Low | 3–5 |
|
||||
| F23 | No Sheet Set Manager, eTransmit, Share, Traces, Markup Import, Activity Insights | menu items uncovered | Low-medium (team workflows) | 40–70 |
|
||||
| F24 | No 3D: UCS, 3D views, orbit, solids, surfaces, meshes, sections, visual styles, materials, lights, rendering (150 menu items) | [parity-checklist](parity-checklist.md) | Medium (3D users) | 300–450 |
|
||||
| F24 | No 3D: 3D views (the UCS command, named UCSs and the UCS icon work in the drawing plane since #3310), orbit, solids, surfaces, meshes, sections, visual styles, materials, lights, rendering (150 menu items) | [parity-checklist](parity-checklist.md) | Medium (3D users) | 300–450 |
|
||||
|
||||
## UI/UX
|
||||
|
||||
@@ -65,7 +65,7 @@ or allow clicks and drag (2, default), saved in the user profile. Drag-only mode
|
||||
| U10 | SETVAR covers about 150 of ~1,000 variables (UNDO options, MREDO and UNDOCTL, and header variables such as CIRCLERAD, OFFSETDIST, POLYSIDES, HPNAME and the dimension variables in SETVAR ? landed, #461; typing a bare variable name as a command runs SETVAR on it) | Low-medium | 3–5 |
|
||||
| U11 | VIEW Orthographic, UCS and background settings (view twist: DVIEW on the Model tab, each VPORTS tile and each layout viewport, VIEWTWIST, landed; Zoom Realtime and Dynamic, ZOOMFACTOR, named views (VIEW) and tiled model viewports with saved configurations (VPORTS) landed in #463, MVIEW Restore in #633, and the Named Viewports dialog, which restores or deletes a saved configuration) | Low | 1–2 |
|
||||
| U12 | Workspaces, navigation bar, CUI customisation, ViewCube drag (#7) (the Command Aliases dialog landed, #1381) | Low-medium | 13–23 |
|
||||
| U13 | `.dxf` from Finder fails to open on macOS (#158) (window controls fixed, #161) | Medium | 1–2 |
|
||||
| U13 | `.dxf` from Finder fails to open on macOS (#158; #3344, which lands #1347, is written but has never been built or run on a Mac and waits for someone to check it there) (window controls fixed, #161) | Medium | 1–2 |
|
||||
|
||||
## File formats
|
||||
|
||||
@@ -78,7 +78,7 @@ Detail: [file-format-parity.md](file-format-parity.md).
|
||||
| FF3 | Save-version leftovers (DXF/DWG 2000–2018, binary DXF, SAVEAS `version`/`binary` and the default save version landed, #421): no R14 DWG or R12 DXF output; the Save dialog can't pick the version per file (the file picker doesn't report the chosen type; File > Default Save Format sets it); no command-line SAVEAS format prompt | Low | 2–4 |
|
||||
| FF4 | Code-page leftovers (pre-2007 DXF read in their `$DWGCODEPAGE` landed, #505): Johab (ANSI_1361) and DOS 855/857/860–865/869 read as ANSI_1252; saving declares `ANSI_1252` instead of the file's code page (the text is pure ASCII, so still correct); acadrust approximates DOS code pages in pre-2007 DWG (DOS437 as 866, DOS850 as 1252) | Low | 1–2 |
|
||||
| FF5 | **[alpha blocker]** Real-file corpus (`storytold/cadcraft-corpus`), open → save → reopen tests, black-box check in AutoCAD | High | 10–15 + human |
|
||||
| FF6 | **[alpha blocker]** DWG throughput: a 10 MB DWG took ~2 min to fail (#57) | High for real projects | 6–10 |
|
||||
| FF6 | **[alpha blocker]** DWG throughput: a 10 MB DWG took ~2 min to fail (#57); large DWGs are refused at the size limits of the shared DWG library (512 MB of DWG, 1 GiB once converted, which a DWG of about 150 MB can reach; #3102, #2633, #1088). A typed `OPEN <path>` reads in the background (#3343); an open can't be cancelled and shows no progress | High for real projects | 6–10 |
|
||||
| FF7 | Table record and object handles from other programs' files are renumbered on the first save (entity handles are kept; `*D` blocks no longer duplicate and once reopened, CADCraft's own files keep every handle across saves, #495) | Low | 4–6 |
|
||||
| FF8 | SHX shape fonts, big fonts and unifonts are read and drawn (2026-10-22; looked up by file name beside the drawing, in `CADCRAFT_SHXPATH`, via a font map or registered by the web app; FONTALT). Left: no Options entry for the search path or font map; no desktop drag-drop of `.shx`; big-font code page guessed from the file name; vertical text not justified along its column; extended big font box scaling unverified against real files | Medium | 2–4 |
|
||||
| FF9 | `.pc3` plotter configuration files; shape elements in user `.lin` files are dropped on load (DXF/DWG linetype shape elements are drawn since 2026-10-22; templates and `.dwt`, user `.lin`/`.pat` and `.pgp` alias files landed, #552; `.ctb`/`.stb`, #410) | Low-medium | 4–8 |
|
||||
@@ -96,7 +96,7 @@ Detail: [hardware-parity.md](hardware-parity.md).
|
||||
|---|---|---|
|
||||
| H1 | 3Dconnexion SpaceMouse: 2D pan and zoom through raw HID on Windows and Linux landed (#650, Tools ▸ 3D Mouse; PR #983 open); none on macOS or the web, no 3D navigation (needs 3D views), not yet checked on a physical device in #650 | 6–10 + human |
|
||||
| H2 | Multi-monitor: floating palettes on other screens, per-monitor DPI (the Windows 11 DPI fix is in open PR #668, which replaced the closed PR #110) | 4–6 |
|
||||
| H3 | System printers (PC3 devices) beyond PDF, PNG and SVG plotter devices (CUPS printing on macOS and Linux is open PR #755) | 6–10 |
|
||||
| H3 | **[alpha blocker]** System printers (PC3 devices) beyond PDF, PNG and SVG plotter devices (CUPS printing on macOS and Linux is open PR #755) | 6–10 |
|
||||
| H4 | Pen tablets / digitizer (TABLET) | 3–5 + human |
|
||||
| H5 | Screen magnifier tracking: the system-cursor option landed (PR #187); issue #39 is still open | 1–2 |
|
||||
|
||||
@@ -117,7 +117,7 @@ Detail: [localization-parity.md](localization-parity.md).
|
||||
|---|---|---|---|
|
||||
| S1 | ~~No CI runs `cargo xtask ci` on pull requests~~ fixed: `ci.yml` runs it on every pull request and push to main (#1987) | `.github/workflows/ci.yml` | 0 |
|
||||
| S2 | ~~`cargo fmt --check` fails on main~~ fixed on main (8fceaaf) | — | 0 |
|
||||
| S3 | 450 open PRs (2026-10-24), many community bug fixes awaiting review | `gh pr list` | 10–20 |
|
||||
| S3 | 661 open PRs (2026-11-20; 714 the day before), many community bug fixes awaiting review | `gh pr list` | 10–20 |
|
||||
| S4 | Open correctness issues: extents union far-apart geometry (#166), lines not visible mid-command (#44), browser plot shows raw PDF bytes (#134) (closing a tab and browser saves fixed, #76, #133) | issues | 4–6 |
|
||||
| S5 | No smoke test of every command through the UI (open PR #42 proposes one) | — | 6–10 |
|
||||
|
||||
@@ -127,7 +127,8 @@ Detail: [localization-parity.md](localization-parity.md).
|
||||
|---|---|---|
|
||||
| P1 | Web build: plot shows raw PDF bytes (#134), no DWG (File > Open and save downloads fixed, #55, #133) | 3–5 |
|
||||
| P2 | Windows and Linux get little runtime testing; Linux Mint mouse delay (#25: the vsync fix landed, #183, the issue is open); Windows magnifier (#39: system-cursor option landed, #187, the issue is open) | 6–10 |
|
||||
| P3 | macOS file associations: opening `.dxf` from Finder fails (#158; open PRs #683 and #899) | 1–2 |
|
||||
| P3 | macOS file associations: opening `.dxf` from Finder fails (#158; #3344 lands #1347 and waits for a check on a Mac; #683 and #899 are open) | 1–2 |
|
||||
| P4 | **[alpha blocker]** Startup on older graphics hardware: a black window or a crash on older Intel graphics, older macOS and some virtual machines (#1724, #1631, #3222, #1780). `CADCRAFT_STENCIL=0` starts the app without a stencil buffer (#3336) but has to be set by hand; there is no automatic fallback renderer | not estimated |
|
||||
|
||||
## Ecosystem and automation
|
||||
|
||||
@@ -150,6 +151,7 @@ Detail: [localization-parity.md](localization-parity.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Batch for what merged on 2026-11-19 and 2026-11-20, and the six-row alpha gate: alpha-blocker marks removed from row 4, F1 and F3 (not gate rows any more) and added to H3 and the new P4 (startup on older graphics hardware, #3336); F1 narrowed (-ATTEDIT, -RENAME and -LAYER options, #3311); F5 (ARRAY Key point, #2368); F7 (Dimension Style Manager, #1460; dimension values kept on save, #3335); F9 (double-click edits TEXT, attribute definitions and dimension text in place, #3345); F20 (right-click settings, interface reset, #3308); F24 (UCS in the drawing plane, #3310); FF6 (size limits, typed OPEN in the background, #3343); U13 and P3 (#3344 waits for a Mac); S3 count. Hours not re-estimated |
|
||||
| 2026-11-03 | minor | XCLIP (rectangular, polygonal and polyline boundaries, Invert clip, ON/OFF, Delete, generate Polyline) and XCLIPFRAME: a boundary per block or xref reference (`Insert::clip`, block coordinates), drawn, plotted and framed clipped, the extents cut to it, and read and written as the reference's ACAD_FILTER/SPATIAL SPATIAL_FILTER in DXF and DWG: F2 and top-10 row 4 narrowed |
|
||||
| 2026-11-03 | minor | SHX fonts: shape fonts, big fonts and unifonts read (`cadcraft_fonts::shx`, every count and offset bounded) and drawn for TEXT, MTEXT, attributes, dimensions and tables, with the style's big font and vertical flag; found by file name beside the drawing, in `CADCRAFT_SHXPATH`, through a font map or from `.shx` files opened in the web app, never in another CAD program's folder; FONTALT may name a font and a big font; linetype shape elements drawn when their file is found: FF8 and FF9 narrowed |
|
||||
| 2026-10-30 | minor | QSAVE asks before replacing a file with content the DWG writer can't keep, and ISAVEBAK keeps the previous file as `.bak`: row 1 narrowed, FF1 and F20 updated |
|
||||
|
||||
+10
-9
@@ -1,6 +1,6 @@
|
||||
# CADCraft roadmap detail
|
||||
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-19 · **Change:** major (alpha gate revised from user reports: six rows, Windows first; current focus re-ranked into three tiers; percentages and hours not re-scored; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-20 · **Change:** minor (alpha gate evidence updated for what merged on 2026-11-19 and 2026-11-20; no row changes its verdict until the reporters confirm; previously major: alpha gate revised from user reports: six rows, Windows first; current focus re-ranked into three tiers; percentages and hours not re-scored; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
|
||||
Forward-looking plan: milestones with status, the current focus, and what comes next with
|
||||
estimates. The summary is [ROADMAP.md](../ROADMAP.md); the work items behind every line are in
|
||||
@@ -14,11 +14,11 @@ already written and waiting in a pull request lands before new work starts, firs
|
||||
|
||||
1. **Urgent: security fixes, leaks, crashes and lost work.** The open security-audit findings
|
||||
(#1919–#1935) are checked against the input limits that landed on 2026-11-11, then closed or
|
||||
fixed; #1276 fixes the crafted-handle overwrite (#1921). Hostile-input fixes are waiting in
|
||||
#2820, #2821 and #2765. Crashes and hangs with a reproduction come next: #1603 (web, large DXF),
|
||||
fixed; #1276 fixes the crafted-handle overwrite (#1921). The hostile-input fixes #2820, #2821 and #2765 landed on
|
||||
2026-11-20 (#3304, #3305). Crashes and hangs with a reproduction come next: #1603 (web, large DXF),
|
||||
#2174 (DWG with 3D content), #1724, #1631 and #3222 (startup).
|
||||
2. **Parity with AutoCAD.** The failing [alpha gate](#alpha-gate) rows in their order, then the
|
||||
[beta checklist](#beta-checklist), apart from the checklist items named under tier 3. 714 pull requests are open (2026-11-19); about 230 of them are
|
||||
[beta checklist](#beta-checklist), apart from the checklist items named under tier 3. 661 pull requests are open (2026-11-20; 714 the day before); about 230 of them were
|
||||
mergeable, pass CI and are small, and many already fix a gate row.
|
||||
3. **Lower priority.** Work that affects fewer people and that nothing breaks without: dynamic-block
|
||||
authoring, editing an xref in place, exact ellipse and spline geometry, prompt options that need
|
||||
@@ -40,12 +40,12 @@ evidence has limits: there is no telemetry, and someone whose copy never starts
|
||||
|
||||
| Row | Passes? | Evidence | Passes when |
|
||||
|---|---|---|---|
|
||||
| It starts on the hardware people have | **no** | Black window or a crash at startup on older Intel graphics, older macOS and some virtual machines (#1724, #1631, #3222, #1780); `CADCRAFT_STENCIL=0` is waiting in #1596; no automatic fallback renderer | It reaches a usable drawing area on Windows 10 and 11 with old integrated graphics, in a virtual machine, and on the supported macOS and Linux versions, choosing a fallback renderer by itself |
|
||||
| It opens the DWG and DXF files people already have, correctly and in reasonable time | **no** | Large DWGs are refused at a size limit or freeze the window (#3102, #2633, #1088); layouts come in at the wrong scale or in the wrong units (#1672, #2836); a DWG with 3D content crashes or opens empty (#2174); the corpus holds four files, all written by CADCraft, and CI does not run it | A corpus of files made by AutoCAD and other CAD programs opens in CI with its objects, layouts, viewports and units right, compared with what the program that wrote it shows; a large file opens or says clearly why not; content we don't model is kept and never crashes |
|
||||
| Saving loses nothing, and other CAD programs open the result | **no** | DXF keeps what we don't model (#528); other applications' objects are kept as proxies (#2917, #2919, #2654); through DWG, custom-class objects without data for the version written are still dropped; fixes for files AutoCAD or BricsCAD refuse are waiting (#2904, #1687, #3234); never checked against a corpus in AutoCAD | The corpus round-trips with every object kept and its geometry and properties unchanged, a save names anything it could not keep, and AutoCAD opens the saved files without a recovery prompt |
|
||||
| Input feels like AutoCAD for Windows | **partial, blocking** | Running snaps, polar, ortho, coordinate entry, tracking, FROM/M2P/TK and dynamic input work; a click while the mouse moves can be lost (#1001, #2092), right-click and Space don't always act as Enter (#1387), a double-click doesn't edit TEXT in place (#842); fixes are waiting in pull requests | A click counts while the pointer moves; right-click and Space repeat or confirm as set in Options; a double-click edits text, multiline text and dimension text in place |
|
||||
| It starts on the hardware people have | **no** | Black window or a crash at startup on older Intel graphics, older macOS and some virtual machines (#1724, #1631, #3222, #1780); `CADCRAFT_STENCIL=0` starts without a stencil buffer (#3336) but must be set by hand, and no reporter has confirmed it yet; no automatic fallback renderer | It reaches a usable drawing area on Windows 10 and 11 with old integrated graphics, in a virtual machine, and on the supported macOS and Linux versions, choosing a fallback renderer by itself |
|
||||
| It opens the DWG and DXF files people already have, correctly and in reasonable time | **no** | Large DWGs are refused at the shared DWG library's size limit (#3102, #2633, #1088); a typed OPEN reads in the background (#3343), but an open can't be cancelled and shows no progress; a layout's paper units are explicit and kept since #3309 (#2836 closed; #1672 open); a DWG with 3D content crashes or opens empty (#2174); the corpus holds four files, all written by CADCraft, and CI does not run it | A corpus of files made by AutoCAD and other CAD programs opens in CI with its objects, layouts, viewports and units right, compared with what the program that wrote it shows; a large file opens or says clearly why not; content we don't model is kept and never crashes |
|
||||
| Saving loses nothing, and other CAD programs open the result | **no** | DXF keeps what we don't model (#528); other applications' objects are kept as proxies (#2917, #2919, #2654); through DWG, custom-class objects without data for the version written are still dropped; an edited dimension keeps its values on save (#3335); fixes for files AutoCAD or BricsCAD refuse landed on 2026-11-20 (#2904, #1687, #3234, #1728, #2882), and a file saved from a Rhino drawing still crashes AutoCAD 2021 as DWG (#3303); never checked against a corpus in AutoCAD | The corpus round-trips with every object kept and its geometry and properties unchanged, a save names anything it could not keep, and AutoCAD opens the saved files without a recovery prompt |
|
||||
| Input feels like AutoCAD for Windows | **partial, blocking until confirmed** | Running snaps, polar, ortho, coordinate entry, tracking, FROM/M2P/TK and dynamic input work; landed on 2026-11-20 and not yet confirmed by the people who reported them: a click counts where the button goes down (#3307; #1001, #2092), a quick right-click and Space act as Enter (#3307; #1387), a double-click edits TEXT, attribute definitions and dimension text in place (#3345; #842 stays open for table cells) | A click counts while the pointer moves; right-click and Space repeat or confirm as set in Options; a double-click edits text, multiline text and dimension text in place |
|
||||
| Draft, dimension and annotate a sheet, with styles | partial, not blocking | All core DIM types, associativity, the Dimension Style Manager (#1460), TEXT/MTEXT, MLEADER, tables, the in-place MTEXT editor, blocks with attributes, xrefs, the Block Editor and REFEDIT work; a few prompt options still print "not available yet" ([gaps.md](gaps.md) F1); ellipse and spline intersections are approximate | No "not available yet" in the most-used draw, modify and annotate commands, apart from options that need 3D |
|
||||
| Lay out and print a sheet at scale, and the interface can always be restored | **partial, blocking** | Layers, layouts, viewports, page setups, PDF output, plot styles, the Plot dialog, preview and PUBLISH work; a print can come out off scale (#3216); printers are reached only through PDF, PNG and SVG files (F14, H3); a hidden menu bar or closed panels can't always be brought back (#1240) | A metric sheet prints 1:1 on a system printer, and one command or key restores the menu bar and default panels from any state |
|
||||
| Lay out and print a sheet at scale, and the interface can always be restored | **partial, blocking** | Layers, layouts, viewports, page setups, PDF output, plot styles, the Plot dialog, preview and PUBLISH work; a print can come out off scale (#3216); printers are reached only through PDF, PNG and SVG files (F14, H3); MENUBAR, TOOLBAR and Options ▸ Reset bring a hidden menu bar and closed panels back (#3308; #1240 closed), and metric sheets are in millimetres (#3309) | A metric sheet prints 1:1 on a system printer, and one command or key restores the menu bar and default panels from any state |
|
||||
|
||||
Moved to the beta checklist on 2026-11-19, with the reports behind each: dynamic-block authoring (none),
|
||||
editing an xref in place (one), exact ellipse and spline intersections (one).
|
||||
@@ -114,6 +114,7 @@ AutoLISP surface, AI features with openly licensed local models, and every remai
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Alpha gate evidence updated for what merged on 2026-11-19 and 2026-11-20: the stencil switch (#3336), typed OPEN in the background (#3343), paper units (#3309), dimension values kept on save (#3335), clicks while moving and right-click or Space as Enter (#3307), in-place text editing (#3345), the interface reset (#3308). No verdict changed: the input row waits for confirmation from the reporters; pull-request count 714 → 661 |
|
||||
| 2026-11-19 | major | Alpha gate revised from user reports: six rows (starts on common hardware; opens existing files; saves without loss; input feel; draft and annotate with styles; print at scale and a restorable interface), main platform Windows; dynamic-block authoring, xref editing in place and exact curve geometry counted under beta only; current focus re-ranked into three tiers; percentages and hours not re-scored |
|
||||
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: alpha-gate evidence, CI gate (#1987), beta-checklist states, open-PR and catalog counts re-checked against main 41d9b5e95; percentages and hours not re-scored |
|
||||
| 2026-10-13 | minor | Re-audit against main e707ab4d: alpha-gate evidence for drafting, annotation, blocks and DWG rows; beta-checklist states for DWG/DXF, blocks and languages; current-focus items 4–7; milestone notes M1, M12, M13; percentages and hours not re-scored |
|
||||
|
||||
Reference in New Issue
Block a user