mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-19 20:30:42 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b19ba1ff9 | ||
|
|
7001f74839 | ||
|
|
0b060ec96a | ||
|
|
c6bb366ad4 | ||
|
|
01a2f973c9 | ||
|
|
d4abea0df1 | ||
|
|
33cb596e38 | ||
|
|
4ac1a6a001 | ||
|
|
60e2c5cfba | ||
|
|
1df2b82955 | ||
|
|
9c2915c222 | ||
|
|
272e812e31 | ||
|
|
9a6396c090 | ||
|
|
a3e82dc9ce |
Generated
+3
-4
@@ -717,7 +717,6 @@ version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-geom",
|
||||
"craft-dxf",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1184,7 +1183,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
@@ -1203,9 +1202,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
|
||||
dependencies = [
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a)",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9)",
|
||||
"encoding_rs",
|
||||
"kurbo",
|
||||
"log",
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/cadcraft"
|
||||
# internal
|
||||
cadcraft-geom = { path = "crates/geom" }
|
||||
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "2f2d1d84e3a36b3f93e81507aeff3f0da97a7162" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
|
||||
|
||||
@@ -11,7 +11,6 @@ workspace = true
|
||||
[dependencies]
|
||||
cadcraft-geom = { workspace = true }
|
||||
cadcraft-color = { workspace = true }
|
||||
craft-dxf = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
+314
-46
@@ -1,14 +1,32 @@
|
||||
//! Readers for the user's own linetype (`.lin`) and hatch pattern (`.pat`) files.
|
||||
//!
|
||||
//! Grammar and hostile-input capping live in [`craft_dxf::lin_pat`]; this module maps the
|
||||
//! parsed definitions into CADCraft's [`Linetype`] and [`UserPattern`] document types.
|
||||
|
||||
use cadcraft_geom::Vec2;
|
||||
pub use craft_dxf::lin_pat::{MAX_DEFINITIONS, MAX_LINE_CHARS, MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, MAX_VALUE, Parsed};
|
||||
//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then
|
||||
//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for
|
||||
//! a pattern), with `;` starting a comment line. CADCraft ships no such file; these read the
|
||||
//! files users bring. Everything here treats the text as hostile: lines, definitions, dashes,
|
||||
//! families and warnings are capped, numbers must be finite and reasonable, and nothing panics.
|
||||
//! Problems become warnings and the definitions that can be read are kept.
|
||||
|
||||
use super::PatternLine;
|
||||
use crate::{DashElement, Linetype};
|
||||
|
||||
/// Longest line read; longer lines are skipped with a warning.
|
||||
pub const MAX_LINE_CHARS: usize = 4096;
|
||||
/// Most definitions (linetypes or patterns) read from one file.
|
||||
pub const MAX_DEFINITIONS: usize = 4096;
|
||||
/// Most elements in one linetype.
|
||||
pub const MAX_LINETYPE_ELEMENTS: usize = 256;
|
||||
/// Most line families in one hatch pattern (what the renderer draws, too).
|
||||
pub const MAX_PATTERN_FAMILIES: usize = 1024;
|
||||
/// Most dashes in one pattern line family (as for a pattern definition read from DXF).
|
||||
pub const MAX_PATTERN_DASHES: usize = 256;
|
||||
/// Largest magnitude accepted for a length, offset or scale.
|
||||
pub const MAX_VALUE: f64 = 1.0e6;
|
||||
/// Longest name or description kept.
|
||||
const MAX_NAME_CHARS: usize = 255;
|
||||
/// Most warnings collected; the rest are counted in a last line.
|
||||
const MAX_WARNINGS: usize = 100;
|
||||
|
||||
/// A hatch pattern read from a user's `.pat` file.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct UserPattern {
|
||||
@@ -17,57 +35,307 @@ pub struct UserPattern {
|
||||
pub lines: Vec<PatternLine>,
|
||||
}
|
||||
|
||||
/// What a file held: the definitions that could be read, and why anything else was skipped.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Parsed<T> {
|
||||
pub items: Vec<T>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T> Default for Parsed<T> {
|
||||
fn default() -> Self {
|
||||
Parsed { items: Vec::new(), warnings: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Parsed<T> {
|
||||
fn warn(&mut self, line: usize, msg: impl Into<String>) {
|
||||
match self.warnings.len() {
|
||||
n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())),
|
||||
MAX_WARNINGS => self.warnings.push("more problems not listed".into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A header line `*NAME[,description]`: the name and description, or why it can't be used.
|
||||
fn header(rest: &str) -> std::result::Result<(String, String), String> {
|
||||
let (name, desc) = rest.split_once(',').unwrap_or((rest, ""));
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("a definition without a name".into());
|
||||
}
|
||||
if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
|
||||
return Err("a definition name that is too long or has control characters".into());
|
||||
}
|
||||
let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
|
||||
Ok((name.to_string(), desc))
|
||||
}
|
||||
|
||||
/// A finite number within ±[`MAX_VALUE`].
|
||||
fn number(t: &str) -> Option<f64> {
|
||||
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE)
|
||||
}
|
||||
|
||||
/// The file's text lines with 1-based numbers, without a leading byte-order mark.
|
||||
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
|
||||
text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim()))
|
||||
}
|
||||
|
||||
// ---------- LIN ----------
|
||||
|
||||
/// Read the linetypes of a `.lin` file. Simple linetypes and complex ones with embedded text
|
||||
/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`)
|
||||
/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept.
|
||||
/// Lengths are in drawing units as written: a user's file is never rescaled.
|
||||
pub fn parse_lin(text: &str) -> Parsed<Linetype> {
|
||||
let parsed = craft_dxf::lin_pat::parse_lin(text);
|
||||
Parsed {
|
||||
items: parsed
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|d| Linetype {
|
||||
name: d.name,
|
||||
description: d.description,
|
||||
pattern: d
|
||||
.pattern
|
||||
.into_iter()
|
||||
.map(|e| DashElement {
|
||||
length: e.length,
|
||||
text: e.text,
|
||||
shape: None,
|
||||
style: e.style,
|
||||
scale: e.scale,
|
||||
rotation: e.rotation,
|
||||
offset: Vec2::new(e.offset[0], e.offset[1]),
|
||||
absolute: e.absolute,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect(),
|
||||
warnings: parsed.warnings,
|
||||
let mut out = Parsed::default();
|
||||
// The definition being read: name, description, header line.
|
||||
let mut pending: Option<(String, String, usize)> = None;
|
||||
for (no, line) in lines(text) {
|
||||
if line.is_empty() || line.starts_with(';') {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
if let Some((name, _, at)) = pending.take() {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
match header(rest) {
|
||||
Ok((name, desc)) => pending = Some((name, desc, no)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((name, description, _)) = pending.take() else {
|
||||
out.warn(no, "pattern line without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped"));
|
||||
break;
|
||||
}
|
||||
if out.items.iter().any(|l: &Linetype| l.name.eq_ignore_ascii_case(&name)) {
|
||||
out.warn(no, format!("linetype {name} is defined twice; the first definition is kept"));
|
||||
continue;
|
||||
}
|
||||
match lin_pattern(line, no, &name, &mut out) {
|
||||
Ok(pattern) => out.items.push(Linetype { name, description, pattern }),
|
||||
Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")),
|
||||
}
|
||||
}
|
||||
if let Some((name, _, at)) = pending {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Split a pattern line at commas outside `[…]` and `"…"`.
|
||||
fn lin_fields(line: &str) -> std::result::Result<Vec<&str>, String> {
|
||||
let mut out = Vec::new();
|
||||
let (mut depth, mut quoted, mut start) = (0usize, false, 0usize);
|
||||
for (i, c) in line.char_indices() {
|
||||
match c {
|
||||
'"' => quoted = !quoted,
|
||||
'[' if !quoted => depth = depth.saturating_add(1),
|
||||
']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?,
|
||||
',' if !quoted && depth == 0 => {
|
||||
out.push(line.get(start..i).unwrap_or("").trim());
|
||||
start = i.saturating_add(1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
}
|
||||
if quoted || depth != 0 {
|
||||
return Err("an unclosed [ or \"".into());
|
||||
}
|
||||
out.push(line.get(start..).unwrap_or("").trim());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The elements of a pattern line `A,dash,gap,[…],…`.
|
||||
fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed<Linetype>) -> std::result::Result<Vec<DashElement>, String> {
|
||||
let mut fields = lin_fields(line)?;
|
||||
// The alignment field ("A") comes first; a line of plain numbers is read as well.
|
||||
if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) {
|
||||
fields.remove(0);
|
||||
} else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) {
|
||||
return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or("")));
|
||||
}
|
||||
let mut pattern: Vec<DashElement> = Vec::new();
|
||||
for f in fields.into_iter().filter(|f| !f.is_empty()) {
|
||||
if pattern.len() >= MAX_LINETYPE_ELEMENTS {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
let Some(inner) = f.strip_prefix('[') else {
|
||||
let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?;
|
||||
pattern.push(DashElement::dash(len));
|
||||
continue;
|
||||
};
|
||||
let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?;
|
||||
match lin_text(inner)? {
|
||||
Some(text) => {
|
||||
// The text sits at the end of the element before it (a zero-length one if none).
|
||||
if pattern.last().is_none_or(|e| e.text.is_some()) {
|
||||
pattern.push(DashElement::dash(0.0));
|
||||
}
|
||||
if let Some(last) = pattern.last_mut() {
|
||||
*last = DashElement { length: last.length, ..text };
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let shape = inner.split(',').next().unwrap_or("").trim();
|
||||
out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which CADCraft can't read; left out"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if pattern.is_empty() {
|
||||
return Err("no dashes".into());
|
||||
}
|
||||
if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) {
|
||||
return Err("every element has zero length".into());
|
||||
}
|
||||
Ok(pattern)
|
||||
}
|
||||
|
||||
/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element.
|
||||
fn lin_text(inner: &str) -> std::result::Result<Option<DashElement>, String> {
|
||||
let inner = inner.trim();
|
||||
let Some(after) = inner.strip_prefix('"') else { return Ok(None) };
|
||||
let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?;
|
||||
if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) {
|
||||
return Err("embedded text that is too long or has control characters".into());
|
||||
}
|
||||
let mut parts = rest.split(',').map(str::trim);
|
||||
if !parts.next().unwrap_or("").is_empty() {
|
||||
return Err("text element: expected a comma after the text".into());
|
||||
}
|
||||
let style = parts.next().unwrap_or("").trim();
|
||||
if style.is_empty() || style.contains('=') {
|
||||
return Err("text element: the text style is missing".into());
|
||||
}
|
||||
let mut e = DashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..DashElement::dash(0.0) };
|
||||
for kv in parts.filter(|p| !p.is_empty()) {
|
||||
let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?;
|
||||
match k.trim().to_ascii_uppercase().as_str() {
|
||||
"S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?,
|
||||
"X" => e.offset.x = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?,
|
||||
"Y" => e.offset.y = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?,
|
||||
// Upright text keeps a rotation relative to the line, like R.
|
||||
k @ ("R" | "A" | "U") => {
|
||||
e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?;
|
||||
e.absolute = k == "A";
|
||||
}
|
||||
other => return Err(format!("text element: unknown option `{other}`")),
|
||||
}
|
||||
}
|
||||
Ok(Some(e))
|
||||
}
|
||||
|
||||
/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out.
|
||||
fn angle(t: &str) -> Option<f64> {
|
||||
let t = t.trim().to_ascii_lowercase();
|
||||
let (num, unit) = match t.char_indices().last() {
|
||||
Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c),
|
||||
_ => (t.as_str(), 'd'),
|
||||
};
|
||||
let v = num.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?;
|
||||
Some(match unit {
|
||||
'r' => v,
|
||||
'g' => v * std::f64::consts::PI / 200.0,
|
||||
_ => v.to_radians(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- PAT ----------
|
||||
|
||||
/// Read the hatch patterns of a `.pat` file. Values are used as written (an inch file for inch
|
||||
/// drawings, a millimetre file for metric ones).
|
||||
pub fn parse_pat(text: &str) -> Parsed<UserPattern> {
|
||||
let parsed = craft_dxf::lin_pat::parse_pat(text);
|
||||
Parsed {
|
||||
items: parsed
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|p| UserPattern {
|
||||
name: p.name,
|
||||
description: p.description,
|
||||
lines: p
|
||||
.lines
|
||||
.into_iter()
|
||||
.map(|l| PatternLine { angle: l.angle, origin: (l.origin[0], l.origin[1]), delta: (l.delta[0], l.delta[1]), dashes: l.dashes })
|
||||
.collect(),
|
||||
})
|
||||
.collect(),
|
||||
warnings: parsed.warnings,
|
||||
let mut out: Parsed<UserPattern> = Parsed::default();
|
||||
// The pattern being read, its header line, and whether it already failed.
|
||||
let mut cur: Option<(UserPattern, usize, bool)> = None;
|
||||
let finish = |cur: Option<(UserPattern, usize, bool)>, out: &mut Parsed<UserPattern>| {
|
||||
let Some((p, at, failed)) = cur else { return };
|
||||
if failed {
|
||||
return;
|
||||
}
|
||||
if p.lines.is_empty() {
|
||||
out.warn(at, format!("pattern {} has no line families; skipped", p.name));
|
||||
} else if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name));
|
||||
} else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) {
|
||||
out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name));
|
||||
} else {
|
||||
out.items.push(p);
|
||||
}
|
||||
};
|
||||
for (no, line) in lines(text) {
|
||||
// A comment runs to the end of the line.
|
||||
let line = line.split(';').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
finish(cur.take(), &mut out);
|
||||
match header(rest) {
|
||||
Ok((name, description)) => cur = Some((UserPattern { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((p, _, failed)) = cur.as_mut() else {
|
||||
out.warn(no, "line family without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if *failed {
|
||||
continue;
|
||||
}
|
||||
if p.lines.len() >= MAX_PATTERN_FAMILIES {
|
||||
out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name));
|
||||
*failed = true;
|
||||
continue;
|
||||
}
|
||||
match pat_family(line) {
|
||||
Ok(l) => p.lines.push(l),
|
||||
Err(e) => {
|
||||
out.warn(no, format!("pattern {}: {e}; skipped", p.name));
|
||||
*failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
finish(cur, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`.
|
||||
fn pat_family(line: &str) -> std::result::Result<PatternLine, String> {
|
||||
let mut v = Vec::new();
|
||||
for f in line.split(',') {
|
||||
if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) {
|
||||
return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family"));
|
||||
}
|
||||
let f = f.trim();
|
||||
if f.is_empty() && v.len() >= 5 {
|
||||
continue;
|
||||
}
|
||||
v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?);
|
||||
}
|
||||
let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else {
|
||||
return Err("a line family needs angle, x, y, delta-x and delta-y".into());
|
||||
};
|
||||
if dy.abs() < 1e-9 {
|
||||
return Err("a line family with zero spacing (delta-y)".into());
|
||||
}
|
||||
Ok(PatternLine { angle, origin: (x, y), delta: (dx, dy), dashes: v.get(5..).unwrap_or(&[]).to_vec() })
|
||||
}
|
||||
|
||||
@@ -805,9 +805,11 @@ pub struct PageSetup {
|
||||
/// Plot objects with their transparency ("Plot transparency"; PLOTTRANSPARENCYOVERRIDE can
|
||||
/// override it). The DXF plot layout flags have no bit for it, so it is not saved in DXF.
|
||||
pub plot_transparency: bool,
|
||||
/// The layout's paper units are millimetres (plot paper units 1 in DXF) whatever the
|
||||
/// drawing's MEASUREMENT says; otherwise paper units follow MEASUREMENT (#1058).
|
||||
pub paper_mm: bool,
|
||||
/// Explicit paper-space unit for the layout: `Some(true)` for millimetres (plot paper units 1
|
||||
/// in DXF), `Some(false)` for inches, or `None` to follow the drawing's `MEASUREMENT` (#1058,
|
||||
/// #3249).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub paper_mm: Option<bool>,
|
||||
/// Paper size (DXF groups 44, 45) and plot rotation (group 73) as the file stored them.
|
||||
/// Saving writes them back while they still describe `width_mm`, `height_mm` and
|
||||
/// `landscape`, so each program's convention for media defined wider than tall survives a
|
||||
@@ -839,7 +841,7 @@ impl Default for PageSetup {
|
||||
lineweights: true,
|
||||
show_plot_styles: false,
|
||||
plot_transparency: false,
|
||||
paper_mm: false,
|
||||
paper_mm: None,
|
||||
file_paper: None,
|
||||
image_origin: None,
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_color::Rgb;
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, PageSetup, Space};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Space};
|
||||
use cadcraft_geom::{Bounds2, Mat3, Vec2};
|
||||
use cadcraft_render::paper::{self, Sheet};
|
||||
use cadcraft_render::raster::{RasterOptions, View};
|
||||
@@ -276,18 +276,8 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = s.doc()?;
|
||||
let mut page = match space.layout() {
|
||||
Some(n) => d.layout(n).map(|l| l.page.clone()).unwrap_or_default(),
|
||||
None => {
|
||||
// Model space plots on A4 (metric) or ANSI A, like the PDF plotter.
|
||||
let mut page = PageSetup::default();
|
||||
if paper::paper_unit_mm(d) == 1.0
|
||||
&& let Some(a4) = paper::paper_size("A4")
|
||||
{
|
||||
page.paper = a4.name.into();
|
||||
page.width_mm = a4.width_mm;
|
||||
page.height_mm = a4.height_mm;
|
||||
}
|
||||
page
|
||||
}
|
||||
// Model space plots on ISO A4 (metric) or ANSI A, like the PDF plotter.
|
||||
None => paper::model_page(d),
|
||||
};
|
||||
if let Some(name) = str_param(p, "paper") {
|
||||
let ps = paper::paper_size(name).ok_or_else(|| bad("preview", format!("unknown paper size `{name}`")))?;
|
||||
@@ -295,6 +285,10 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
page.width_mm = ps.width_mm;
|
||||
page.height_mm = ps.height_mm;
|
||||
}
|
||||
// A model-space plot takes its units from the paper it was given (a layout keeps its page setup's).
|
||||
if matches!(space, Space::Model) {
|
||||
paper::apply_model_paper_units(&mut page);
|
||||
}
|
||||
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
|
||||
page.landscape = l;
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(),
|
||||
CommandSpec::new("loops", "Implied Loops", loops::run).params(loops::PARAMS).noundo(),
|
||||
CommandSpec::new("texts", "Query Texts", run_texts)
|
||||
.params("{contains?: text (any case; `query` is the same filter), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders")
|
||||
.params("{contains?: text (any case), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders")
|
||||
.noundo(),
|
||||
CommandSpec::new("countlist", "Count List", count::run_countlist)
|
||||
.params("{space?: all (default)|current|model|<layout>, nested?: bool} → per-block counts, as COUNT")
|
||||
@@ -664,12 +664,7 @@ fn run_texts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
v.as_u64().map(|n| usize::try_from(n).unwrap_or(usize::MAX)).ok_or_else(|| bad(CMD, format!("`{k}` must be a whole number, 0 or more")))
|
||||
})
|
||||
};
|
||||
// `query` is what agents tend to call the filter; without this alias it was silently ignored
|
||||
// and every text came back (#3011).
|
||||
let contains = match text("contains")? {
|
||||
Some(c) => Some(c),
|
||||
None => text("query")?,
|
||||
};
|
||||
let contains = text("contains")?;
|
||||
let layer = text("layer")?;
|
||||
let window = given("window")
|
||||
.map(|w| {
|
||||
|
||||
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
|
||||
.menu(&["File", "Page Setup Manager..."])
|
||||
.params(
|
||||
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
|
||||
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
|
||||
),
|
||||
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
|
||||
.menu(&["File", "Print..."])
|
||||
@@ -641,6 +641,7 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"width",
|
||||
"height",
|
||||
"landscape",
|
||||
"paperUnits",
|
||||
"margins",
|
||||
"lineweights",
|
||||
"plotArea",
|
||||
@@ -682,6 +683,22 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
page.width_mm = ps.width_mm;
|
||||
page.height_mm = ps.height_mm;
|
||||
}
|
||||
// The picked paper's own units become the layout's paper units: millimetres for a metric
|
||||
// paper, else the drawing's MEASUREMENT. Otherwise ISO A0 in a new (imperial) drawing's
|
||||
// layout is 33.11 x 46.81 units (#2836). This holds for a standard size from the page's
|
||||
// device's list too (the built-in devices list every standard size), and a device's own
|
||||
// paper that is not a standard size keeps the layout's units. Only a saved page setup changes
|
||||
// units; a one-off plot's `paper` keeps the layout's, so its objects stay the size they were
|
||||
// drawn. A custom `width` and `height` in the same call replace this paper below, and a
|
||||
// custom size keeps the layout's units, with `paper` or without it. An explicit `paperUnits`
|
||||
// in the same call wins (below).
|
||||
if p.get("paper").is_some()
|
||||
&& p.get("width").is_none()
|
||||
&& p.get("height").is_none()
|
||||
&& let Some(ps) = cadcraft_render::paper_size(&page.paper)
|
||||
{
|
||||
page.paper_mm = (!ps.imperial).then_some(true);
|
||||
}
|
||||
let mm = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0 && *v <= 5080.0);
|
||||
match (mm("width"), mm("height")) {
|
||||
(Some(w), Some(h)) => {
|
||||
@@ -695,6 +712,15 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
|
||||
page.landscape = l;
|
||||
}
|
||||
// Paper units: what one paper-space unit is on this layout, whatever the paper's own family
|
||||
// (an ARCH D sheet can be drawn in millimetres, #3249).
|
||||
if let Some(v) = p.get("paperUnits") {
|
||||
page.paper_mm = Some(match v.as_str().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("mm" | "millimeters" | "millimetres") => true,
|
||||
Some("in" | "inch" | "inches") => false,
|
||||
_ => return Err(bad(cmd, "`paperUnits` must be \"mm\" or \"inches\"")),
|
||||
});
|
||||
}
|
||||
if let Some(m) = p.get("margins") {
|
||||
let a: Vec<f64> = m.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
|
||||
match a[..] {
|
||||
|
||||
@@ -264,23 +264,16 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, format!("`{name}` has no style `{rm}`")));
|
||||
}
|
||||
}
|
||||
let mut changed: Option<String> = None;
|
||||
if let Some(v) = p.get("style") {
|
||||
let sname = v.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty());
|
||||
let sname = sname.ok_or_else(|| bad(cmd, "`style.name` is required"))?;
|
||||
// The name as it is stored (at most 255 characters, as `sanitized` cuts it, and
|
||||
// without a space the cut leaves at the end, which `sanitized` trims), so a long
|
||||
// name finds the style it was stored as and the reply finds the edited style.
|
||||
let cut: String = sname.chars().take(255).collect();
|
||||
let sname = cut.trim_end();
|
||||
changed = Some(sname.to_string());
|
||||
let idx = match t.styles.iter().position(|x| x.name.eq_ignore_ascii_case(sname)) {
|
||||
Some(i) => i,
|
||||
None if t.kind == PlotStyleKind::Named => {
|
||||
if t.styles.len() >= cadcraft_doc::MAX_NAMED_STYLES {
|
||||
return Err(bad(cmd, "the table has too many styles"));
|
||||
}
|
||||
t.styles.push(PlotStyle::object(sname));
|
||||
t.styles.push(PlotStyle::object(&sname.chars().take(255).collect::<String>()));
|
||||
t.styles.len() - 1
|
||||
}
|
||||
None => return Err(bad(cmd, format!("`{name}` has no style `{sname}` (colour-dependent styles are Color_1 to Color_255)"))),
|
||||
@@ -290,21 +283,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let t = t.sanitized();
|
||||
// Only what changed, not the table (a colour-dependent one has 255 styles): the table's
|
||||
// name, the description if given, the edited style and the removed style's name.
|
||||
let mut out = json!({ "name": t.name });
|
||||
if let Some(o) = out.as_object_mut() {
|
||||
if str_param(p, "description").is_some() {
|
||||
o.insert("description".into(), json!(t.description));
|
||||
}
|
||||
let edited = changed.and_then(|n| t.styles.iter().find(|x| x.name.eq_ignore_ascii_case(&n)));
|
||||
if let Some(e) = edited.and_then(|x| serde_json::to_value(x).ok()) {
|
||||
o.insert("style".into(), e);
|
||||
}
|
||||
if let Some(r) = str_param(p, "removeStyle") {
|
||||
o.insert("removedStyle".into(), json!(r.trim()));
|
||||
}
|
||||
}
|
||||
let out = serde_json::to_value(&t).unwrap_or(Value::Null);
|
||||
store(s.doc_mut()?, t);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -165,14 +165,57 @@ fn viewport_scale_lock_and_layers() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #2836: picking a paper sets the layout's paper units from it. In a new drawing (imperial,
|
||||
/// MEASUREMENT 0) ISO A0 was 46.81 x 33.11 units, the inch equivalent; now it is 1189 x 841.
|
||||
/// An inch paper gives the layout back the drawing's units.
|
||||
#[test]
|
||||
fn pagesetup_paper_sets_the_layout_paper_units() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(cadcraft_render::paper::paper_unit_mm(s.doc().unwrap()), 25.4, "a new drawing is imperial");
|
||||
let size = |s: &Session| {
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
((sheet.size.x * 100.0).round() / 100.0, (sheet.size.y * 100.0).round() / 100.0, sheet.unit_mm)
|
||||
};
|
||||
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A0", "landscape": true})).unwrap();
|
||||
assert_eq!(r["page"]["paperMm"], true);
|
||||
assert_eq!(size(&s), (1189.0, 841.0, 1.0), "ISO A0 in millimetres");
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ANSI D"})).unwrap();
|
||||
assert_eq!(size(&s), (34.0, 22.0, 25.4), "ANSI D in the drawing's inches");
|
||||
// A custom size replaces the named paper in the same call and keeps the layout's units.
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A4", "width": 254, "height": 508})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, None, "the layout still follows MEASUREMENT");
|
||||
assert_eq!(size(&s), (20.0, 10.0, 25.4), "the custom size in the layout's inches");
|
||||
}
|
||||
|
||||
/// #2836 through a device: the built-in devices list every standard size, so a paper picked in
|
||||
/// Page Setup with CADCraft PDF as the device comes from the device's list. It sets the layout's
|
||||
/// paper units as a paper picked with no device does.
|
||||
#[test]
|
||||
fn pagesetup_device_paper_sets_the_layout_paper_units() {
|
||||
let mut s = Session::new();
|
||||
let size = |s: &Session| {
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
((sheet.size.x * 100.0).round() / 100.0, (sheet.size.y * 100.0).round() / 100.0, sheet.unit_mm)
|
||||
};
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "CADCraft PDF", "landscape": true})).unwrap();
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ISO A0 (841.00 x 1189.00 MM)"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.device, "CADCraft PDF");
|
||||
assert_eq!(size(&s), (1189.0, 841.0, 1.0), "ISO A0 from the device's list in millimetres");
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ANSI D"})).unwrap();
|
||||
assert_eq!(size(&s), (34.0, 22.0, 25.4), "ANSI D from the device's list in the drawing's inches");
|
||||
// An explicit choice in the same call wins over the paper's own units (#3249).
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ARCH D", "paperUnits": "mm"})).unwrap();
|
||||
assert_eq!(size(&s), (914.4, 609.6, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagesetup_paper_table() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A3", "landscape": true, "margins": [5, 5, 5, 5]})).unwrap();
|
||||
assert_eq!(r["page"]["widthMm"], 297.0);
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
// Imperial drawing: paper units are inches.
|
||||
assert!((sheet.size.x - 420.0 / 25.4).abs() < 1e-9 && (sheet.size.y - 297.0 / 25.4).abs() < 1e-9);
|
||||
// An imperial drawing, but a metric paper: the layout's paper units are millimetres (#2836).
|
||||
assert!((sheet.size.x - 420.0).abs() < 1e-9 && (sheet.size.y - 297.0).abs() < 1e-9);
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "Z12"})).is_err());
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "margins": [1, 2]})).is_err());
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "width": 1e308, "height": 5})).is_err());
|
||||
@@ -190,6 +233,40 @@ fn pagesetup_paper_table() {
|
||||
assert_eq!((p.width_mm, p.height_mm), (300.0, 500.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagesetup_paper_units_make_an_inch_sheet_metric() {
|
||||
// An ARCH D sheet in a drawing that measures in millimetres (#3249): the page setup's paper
|
||||
// units decide the paper-space unit, so the sheet can be 914.4 x 609.6 mm.
|
||||
let mut s = Session::new();
|
||||
s.execute("units", &json!({"insunits": 4})).unwrap();
|
||||
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ARCH D", "landscape": true, "paperUnits": "mm"})).unwrap();
|
||||
assert_eq!(r["page"]["paperMm"], true);
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((sheet.size.x - 914.4).abs() < 1e-9 && (sheet.size.y - 609.6).abs() < 1e-9, "{:?}", sheet.size);
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "Inches"})).unwrap();
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((sheet.size.x - 36.0).abs() < 1e-9 && (sheet.size.y - 24.0).abs() < 1e-9, "{:?}", sheet.size);
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "millimeters"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, Some(true));
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "feet"})).is_err());
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": 4})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagesetup_paper_units_inches_overrides_metric_measurement() {
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({"name": "MEASUREMENT", "value": 1})).unwrap();
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ARCH D", "landscape": true})).unwrap();
|
||||
// Without an explicit paperUnits choice, MEASUREMENT = 1 keeps the sheet in millimetres.
|
||||
let metric = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((metric.size.x - 914.4).abs() < 1e-9 && (metric.size.y - 609.6).abs() < 1e-9, "{:?}", metric.size);
|
||||
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "inches"})).unwrap();
|
||||
assert_eq!(r["page"]["paperMm"], false);
|
||||
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, Some(false));
|
||||
let inch = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((inch.size.x - 36.0).abs() < 1e-9 && (inch.size.y - 24.0).abs() < 1e-9, "{:?}", inch.size);
|
||||
}
|
||||
|
||||
fn fake_plot(d: &Drawing, space: &Space, opts: &Value) -> std::result::Result<Vec<u8>, String> {
|
||||
let _ = d;
|
||||
Ok(format!("%PDF-1.4 fake {space:?} {opts}").into_bytes())
|
||||
|
||||
@@ -213,19 +213,10 @@ pub fn getvar(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let name = string(&a[0])?;
|
||||
Ok(Flow::Value(match crate::sysvars::get(ctx.s, &name) {
|
||||
Some(serde_json::Value::Number(n)) if in_radians(&name) => Value::Real(n.as_f64().unwrap_or(0.0).to_radians()),
|
||||
Some(serde_json::Value::Object(o)) if o.contains_key("x") => point_list(&o, &name),
|
||||
v => v.map(|v| from_json(&v)).unwrap_or_default(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Header point variables are stored as `{x, y, z}`; AutoLISP gives a point list. LIMMIN, LIMMAX,
|
||||
/// SNAPBASE and HPORIGIN are 2D points, so they lose z; the rest (INSBASE, UCSORG, ...) keep all three.
|
||||
fn point_list(o: &serde_json::Map<String, serde_json::Value>, name: &str) -> Value {
|
||||
let coord = |k: &str| Value::Real(o.get(k).and_then(serde_json::Value::as_f64).unwrap_or(0.0));
|
||||
let planar = ["LIMMIN", "LIMMAX", "SNAPBASE", "HPORIGIN"].iter().any(|v| v.eq_ignore_ascii_case(name.trim()));
|
||||
if planar { Value::list(vec![coord("x"), coord("y")]) } else { Value::list(vec![coord("x"), coord("y"), coord("z")]) }
|
||||
}
|
||||
|
||||
/// Set a system variable after bounded JSON conversion, reporting invalid or oversized values as LISP errors.
|
||||
pub fn setvar(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
|
||||
@@ -649,17 +649,6 @@ fn getvar_drawing_and_session_variables() {
|
||||
assert_eq!(ok(&mut s, "(getvar \"DWGTITLED\")"), "1");
|
||||
}
|
||||
|
||||
/// LIMMIN, LIMMAX, SNAPBASE and HPORIGIN read as 2D point lists and INSBASE as a 3D one, not as JSON text (#2988).
|
||||
#[test]
|
||||
fn getvar_point_variables_are_point_lists() {
|
||||
let mut s = session();
|
||||
assert_eq!(ok(&mut s, "(getvar \"LIMMIN\")"), "(0.0 0.0)");
|
||||
assert_eq!(ok(&mut s, "(getvar \"LIMMAX\")"), "(12.0 9.0)");
|
||||
assert_eq!(ok(&mut s, "(getvar \"SNAPBASE\")"), "(0.0 0.0)");
|
||||
assert_eq!(ok(&mut s, "(getvar \"INSBASE\")"), "(0.0 0.0 0.0)");
|
||||
assert_eq!(ok(&mut s, "(setvar \"HPORIGIN\" '(3.0 4.0)) (getvar \"HPORIGIN\")"), "(3.0 4.0)");
|
||||
}
|
||||
|
||||
/// CECOLOR is a string in AutoCAD, whatever it was set from (#1999).
|
||||
#[test]
|
||||
fn getvar_cecolor_is_a_string() {
|
||||
|
||||
@@ -62,10 +62,7 @@ fn stylesmanager_creates_edits_saves_and_loads_tables() {
|
||||
&json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5", "color": "#00ff00", "screening": 40, "lineweight": 0.35, "linetype": "HIDDEN", "end": "round"}}),
|
||||
)
|
||||
.unwrap();
|
||||
// `set` replies with the table's name and the edited style, not the table.
|
||||
assert_eq!(r["name"], "office.stb");
|
||||
let pen = r["style"].clone();
|
||||
assert_eq!(pen["name"], "Pen 5");
|
||||
let pen = r["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Pen 5").unwrap().clone();
|
||||
assert_eq!(
|
||||
(pen["color"].as_str(), pen["screening"].as_u64(), pen["lineweight"].as_u64(), pen["end"].as_str()),
|
||||
(Some("#00ff00"), Some(40), Some(35), Some("round"))
|
||||
@@ -134,68 +131,3 @@ fn plot_style_save_is_atomic_and_keeps_permissions() {
|
||||
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #3011: `set` on a colour-dependent table (255 styles) replies with what changed, not the table.
|
||||
#[test]
|
||||
fn stylesmanager_set_replies_with_the_change_not_the_whole_table() {
|
||||
let mut s = Session::new();
|
||||
let set = json!({"action": "set", "name": "monochrome.ctb", "style": {"name": "Color_13", "lineweight": 0.3}});
|
||||
let r = s.execute("stylesmanager", &set).unwrap();
|
||||
assert_eq!(r["name"], "monochrome.ctb", "{r}");
|
||||
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some("Color_13"), Some(30)), "{r}");
|
||||
// Only the change: no table summary, no other style.
|
||||
let keys: Vec<&str> = r.as_object().unwrap().keys().map(String::as_str).collect();
|
||||
assert_eq!(keys, ["name", "style"], "{r}");
|
||||
assert!(r.to_string().len() < 1000, "the reply is short, not the 255-style table: {} bytes", r.to_string().len());
|
||||
// The edit is in the drawing.
|
||||
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "monochrome.ctb"})).unwrap();
|
||||
let c13 = got["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Color_13").unwrap();
|
||||
assert_eq!(c13["lineweight"], 30);
|
||||
// Removing a style of a named table names what went.
|
||||
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
|
||||
s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5"}})).unwrap();
|
||||
let r =
|
||||
s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "removeStyle": "Pen 5", "description": "Office pens"})).unwrap();
|
||||
assert_eq!((r["removedStyle"].as_str(), r["description"].as_str()), (Some("Pen 5"), Some("Office pens")), "{r}");
|
||||
assert!(r.get("style").is_none() && r.get("styles").is_none(), "{r}");
|
||||
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
|
||||
assert_eq!(got["styles"].as_array().map(Vec::len), Some(1), "{got}");
|
||||
}
|
||||
|
||||
/// A style name over 255 characters is stored cut to 255: the reply names the stored style, and
|
||||
/// setting the same long name again edits that style instead of adding one.
|
||||
#[test]
|
||||
fn stylesmanager_set_with_a_long_style_name_replies_with_the_stored_style() {
|
||||
let mut s = Session::new();
|
||||
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
|
||||
let long = "P".repeat(300);
|
||||
let stored = "P".repeat(255);
|
||||
let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}});
|
||||
let r = s.execute("stylesmanager", &set(0.3)).unwrap();
|
||||
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}");
|
||||
let r = s.execute("stylesmanager", &set(0.5)).unwrap();
|
||||
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}");
|
||||
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
|
||||
let styles = got["styles"].as_array().unwrap();
|
||||
assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}");
|
||||
assert_eq!(styles[1]["lineweight"], 50, "{got}");
|
||||
}
|
||||
|
||||
/// A long name whose 255th character is a space is stored without it (`sanitized` trims the cut
|
||||
/// name), so the reply still has the style and setting the same name again edits it.
|
||||
#[test]
|
||||
fn stylesmanager_set_with_a_long_name_cut_at_a_space_edits_one_style() {
|
||||
let mut s = Session::new();
|
||||
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
|
||||
let long = format!("{} tail", "P".repeat(254));
|
||||
let stored = "P".repeat(254);
|
||||
let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}});
|
||||
let r = s.execute("stylesmanager", &set(0.3)).unwrap();
|
||||
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}");
|
||||
let r = s.execute("stylesmanager", &set(0.5)).unwrap();
|
||||
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}");
|
||||
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
|
||||
let styles = got["styles"].as_array().unwrap();
|
||||
assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}");
|
||||
assert_eq!(styles[1]["lineweight"], 50, "{got}");
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ pub(super) fn read_objects(tags: &[Tag], objs: &mut Objects, layout_objs: &mut V
|
||||
// LAYOUT has two 330s: owner dict and the block record; take the last.
|
||||
let br = tg.iter().rfind(|x| x.code == 330).map(Tag::str).unwrap_or_default();
|
||||
let plot = T(tg.get(..start).unwrap_or(&[]));
|
||||
layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot), limits(&t)));
|
||||
layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot, &tg), limits(&t)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,8 +231,9 @@ impl Objects {
|
||||
}
|
||||
}
|
||||
|
||||
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm).
|
||||
pub(super) fn page_setup(t: &T) -> PageSetup {
|
||||
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm), and its
|
||||
/// CADCraft xdata in the record's `tags`.
|
||||
pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
let mut p = PageSetup::default();
|
||||
let mm = |code: i32, d: f64| {
|
||||
let v = t.fd(code, d);
|
||||
@@ -244,9 +245,17 @@ pub(super) fn page_setup(t: &T) -> PageSetup {
|
||||
p.height_mm = w.max(h);
|
||||
}
|
||||
p.margins_mm = [mm(40, p.margins_mm[0]), mm(41, p.margins_mm[1]), mm(42, p.margins_mm[2]), mm(43, p.margins_mm[3])];
|
||||
// Plot paper units 1: millimetres. 0 (inches) is left to MEASUREMENT: earlier CADCraft
|
||||
// versions wrote 0 for every layout.
|
||||
p.paper_mm = t.i(72) == Some(1);
|
||||
// CADCraft's paper units come first (PSUNITS xdata: 0 inches, 1 millimetres, 2 follows
|
||||
// MEASUREMENT), because plot paper units 0 cannot tell an explicit inch layout from an unset
|
||||
// one: earlier CADCraft versions wrote 0 for every layout, so 0 alone is left to MEASUREMENT.
|
||||
// Plot paper units 1 is millimetres (#3249).
|
||||
let units = crate::dxf_ext::xdata_list(crate::dxf_ext::xdata(tags, crate::dxf_ext::APP), "PSUNITS");
|
||||
p.paper_mm = match units.iter().find(|t| t.code == 1070).map(|t| t.i64()) {
|
||||
Some(0) => Some(false),
|
||||
Some(1) => Some(true),
|
||||
Some(2) => None,
|
||||
_ => (t.i(72) == Some(1)).then_some(true),
|
||||
};
|
||||
// Plot rotation 1 or 3 turns the media a quarter turn; media defined wider than tall is
|
||||
// already landscape.
|
||||
let rotated = matches!(t.i(73), Some(1 | 3));
|
||||
|
||||
@@ -473,14 +473,35 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
w.p(17, Vec3::new(0.0, 1.0, 0.0));
|
||||
w.i(76, 0);
|
||||
w.s(330, brh);
|
||||
// The saved paper-space view (centre, height) as CADCraft xdata.
|
||||
if let Some((c, height)) = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite()) {
|
||||
// CADCraft xdata: the saved paper-space view (centre, height), and the layout's paper units.
|
||||
// Group 72 cannot carry the choice on its own: 0 means inches, but it is also what earlier
|
||||
// CADCraft versions wrote for a layout that follows MEASUREMENT, and 1 is what a layout that
|
||||
// inherits a metric MEASUREMENT writes too. PSUNITS keeps the three states apart: 0 inches,
|
||||
// 1 millimetres, 2 follows MEASUREMENT (#3249).
|
||||
let view = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite());
|
||||
let unit_marker = match page.paper_mm {
|
||||
Some(false) => Some(0),
|
||||
Some(true) => Some(1),
|
||||
// An inherited imperial layout writes group 72 = 0, which already reads back as
|
||||
// inherited; only group 72 = 1 is ambiguous and needs the marker.
|
||||
None if cadcraft_render::paper::page_unit_mm(d, page) == 1.0 => Some(2),
|
||||
None => None,
|
||||
};
|
||||
if view.is_some() || unit_marker.is_some() {
|
||||
w.s(1001, dxf_ext::APP);
|
||||
w.s(1000, "PSVIEW");
|
||||
w.s(1002, "{");
|
||||
w.p(1010, c.to3(0.0));
|
||||
w.f(1040, height);
|
||||
w.s(1002, "}");
|
||||
if let Some((c, height)) = view {
|
||||
w.s(1000, "PSVIEW");
|
||||
w.s(1002, "{");
|
||||
w.p(1010, c.to3(0.0));
|
||||
w.f(1040, height);
|
||||
w.s(1002, "}");
|
||||
}
|
||||
if let Some(units) = unit_marker {
|
||||
w.s(1000, "PSUNITS");
|
||||
w.s(1002, "{");
|
||||
w.i(1070, units);
|
||||
w.s(1002, "}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+6
-11
@@ -292,17 +292,8 @@ fn links_json(v: Option<&Value>) -> Vec<(Handle, String)> {
|
||||
pub fn page_for(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<PageSetup> {
|
||||
let mut page = match space.layout() {
|
||||
Some(n) => d.layout(n).map(|l| l.page.clone()).ok_or_else(|| IoError::Format(format!("no layout `{n}`")))?,
|
||||
None => {
|
||||
let mut p = PageSetup::default();
|
||||
if paper::paper_unit_mm(d) == 1.0
|
||||
&& let Some(a4) = paper::paper_size("A4")
|
||||
{
|
||||
p.paper = a4.name.into();
|
||||
p.width_mm = a4.width_mm;
|
||||
p.height_mm = a4.height_mm;
|
||||
}
|
||||
p
|
||||
}
|
||||
// Model space has no stored page setup: ISO A4 in a metric drawing, ANSI A otherwise.
|
||||
None => paper::model_page(d),
|
||||
};
|
||||
if let Some(name) = &o.paper {
|
||||
let ps = paper::paper_size(name).ok_or_else(|| IoError::Format(format!("unknown paper size `{name}`")))?;
|
||||
@@ -325,6 +316,10 @@ pub fn page_for(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<PageSetup>
|
||||
if let (Space::Model, Some(m)) = (space, o.margins) {
|
||||
page.margins_mm = m;
|
||||
}
|
||||
// A model-space plot takes its units from the paper it was given; a layout keeps its page setup's.
|
||||
if matches!(space, Space::Model) {
|
||||
paper::apply_model_paper_units(&mut page);
|
||||
}
|
||||
page.width_mm = page.width_mm.clamp(1.0, MAX_SHEET_MM);
|
||||
page.height_mm = page.height_mm.clamp(1.0, MAX_SHEET_MM);
|
||||
Ok(page)
|
||||
|
||||
@@ -169,7 +169,7 @@ fn the_added_paper_viewport_follows_the_plot_scale() {
|
||||
let sheet_width = |scale: f64, fit: bool| {
|
||||
let mut d = Drawing::new_metric();
|
||||
let page = &mut d.layouts[0].page;
|
||||
(page.width_mm, page.height_mm, page.landscape, page.paper_mm) = (297.0, 420.0, true, true);
|
||||
(page.width_mm, page.height_mm, page.landscape, page.paper_mm) = (297.0, 420.0, true, Some(true));
|
||||
(page.scale, page.scale_to_fit) = (scale, fit);
|
||||
let first = Space::Paper(d.layouts[0].name.clone());
|
||||
d.add(&first, Common::default(), viewport(2)).unwrap();
|
||||
|
||||
@@ -19,7 +19,7 @@ fn drawing() -> Drawing {
|
||||
height_mm: 297.0,
|
||||
margins_mm: [0.0; 4],
|
||||
landscape: true,
|
||||
paper_mm: true,
|
||||
paper_mm: Some(true),
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
@@ -57,16 +57,81 @@ fn plot_paper_units_round_trip_through_dxf() {
|
||||
// Written as group 72 = 1 (millimetres) and read back as such.
|
||||
let back = read(write_dxf(&drawing()).as_bytes(), "x.dxf").unwrap();
|
||||
let page = &back.layouts.iter().find(|l| l.name == "SHEET").unwrap().page;
|
||||
assert!(page.paper_mm);
|
||||
assert_eq!(page.paper_mm, Some(true));
|
||||
assert_eq!(cadcraft_render::sheet(&back, "SHEET").unwrap().unit_mm, 1.0);
|
||||
// A metric drawing's layouts stay in millimetres even from files that say 72 = 0 (what
|
||||
// earlier CADCraft versions wrote for every layout).
|
||||
// A metric drawing's layouts stay in millimetres even from files that say 72 = 0 and carry
|
||||
// no PSUNITS xdata (what earlier CADCraft versions wrote for every layout).
|
||||
let mut metric = Drawing::new_metric();
|
||||
metric.header.set_i64("MEASUREMENT", 1);
|
||||
let written = write_dxf(&metric);
|
||||
let text = written.replace("\r\n 72\r\n1\r\n", "\r\n 72\r\n0\r\n");
|
||||
let text = written
|
||||
.replace("1001\r\nCADCRAFT\r\n1000\r\nPSUNITS\r\n1002\r\n{\r\n1070\r\n2\r\n1002\r\n}\r\n", "")
|
||||
.replace("\r\n 72\r\n1\r\n", "\r\n 72\r\n0\r\n");
|
||||
assert_ne!(text, written, "the layouts' 72 = 1 became 0");
|
||||
let back = read(text.as_bytes(), "old.dxf").unwrap();
|
||||
let name = back.layouts.first().unwrap().name.clone();
|
||||
assert_eq!(cadcraft_render::sheet(&back, &name).unwrap().unit_mm, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_inch_layout_round_trips_on_a_metric_drawing() {
|
||||
// #3249: group 72 = 0 is also what an unset layout writes, so the explicit inch choice
|
||||
// travels in CADCraft xdata and must win over the group 72 fallback.
|
||||
let mut d = Drawing::new_metric();
|
||||
d.header.set_i64("MEASUREMENT", 1);
|
||||
let mut l = Layout::new("INCHES", 3);
|
||||
l.page = PageSetup {
|
||||
paper: "ARCH D".into(),
|
||||
width_mm: 609.6,
|
||||
height_mm: 914.4,
|
||||
margins_mm: [0.0; 4],
|
||||
landscape: true,
|
||||
paper_mm: Some(false),
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
let back = read(write_dxf(&d).as_bytes(), "x.dxf").unwrap();
|
||||
let page = &back.layouts.iter().find(|l| l.name == "INCHES").unwrap().page;
|
||||
assert_eq!(page.paper_mm, Some(false));
|
||||
let sheet = cadcraft_render::sheet(&back, "INCHES").unwrap();
|
||||
assert_eq!(sheet.unit_mm, 25.4);
|
||||
assert!((sheet.size.x - 36.0).abs() < 1e-9 && (sheet.size.y - 24.0).abs() < 1e-9, "{:?}", sheet.size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_layout_keeps_following_measurement_after_a_dxf_round_trip() {
|
||||
// #3249: a layout that never chose its paper units reads back as inherited, not fixed to the
|
||||
// MEASUREMENT it had when saved. An ARCH D sheet on a metric drawing is 914.4 x 609.6; after
|
||||
// MEASUREMENT changes to imperial it must be 36 x 24. The explicit choices do not move.
|
||||
let mut d = Drawing::new_metric();
|
||||
d.header.set_i64("MEASUREMENT", 1);
|
||||
for (name, paper_mm) in [("INHERITED", None), ("INCHES", Some(false)), ("MILLIMETRES", Some(true))] {
|
||||
let mut l = Layout::new(name, 3);
|
||||
l.page = PageSetup {
|
||||
paper: "ARCH D".into(),
|
||||
width_mm: 609.6,
|
||||
height_mm: 914.4,
|
||||
margins_mm: [0.0; 4],
|
||||
landscape: true,
|
||||
paper_mm,
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
}
|
||||
|
||||
let mut back = read(write_dxf(&d).as_bytes(), "x.dxf").unwrap();
|
||||
let units = |d: &Drawing, name: &str| d.layouts.iter().find(|l| l.name == name).unwrap().page.paper_mm;
|
||||
assert_eq!(units(&back, "INHERITED"), None);
|
||||
assert_eq!(units(&back, "INCHES"), Some(false));
|
||||
assert_eq!(units(&back, "MILLIMETRES"), Some(true));
|
||||
|
||||
back.header.set_i64("MEASUREMENT", 0);
|
||||
let sheet = |name: &str| cadcraft_render::sheet(&back, name).unwrap();
|
||||
let inherited = sheet("INHERITED");
|
||||
assert_eq!(inherited.unit_mm, 25.4);
|
||||
assert!((inherited.size.x - 36.0).abs() < 1e-9 && (inherited.size.y - 24.0).abs() < 1e-9, "{:?}", inherited.size);
|
||||
assert_eq!(sheet("INCHES").unit_mm, 25.4);
|
||||
let metric = sheet("MILLIMETRES");
|
||||
assert_eq!(metric.unit_mm, 1.0);
|
||||
assert!((metric.size.x - 914.4).abs() < 1e-9 && (metric.size.y - 609.6).abs() < 1e-9, "{:?}", metric.size);
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ mod pdf_layers;
|
||||
#[path = "../support/pdf_read.rs"]
|
||||
mod pdf_read;
|
||||
mod plot_layout_scale;
|
||||
mod plot_model_metric_units;
|
||||
mod plot_model_png_scale;
|
||||
mod plot_styles;
|
||||
mod polyface_roundtrip;
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! #1828: a model-space plot at 1:1 in a drawing whose units are millimetres puts a 10 mm line
|
||||
//! at 28.35 pt on an ISO A4 sheet, whatever MEASUREMENT says. A drawing made in millimetres by
|
||||
//! changing the drawing units (UNITS sets INSUNITS, not MEASUREMENT) was plotted 25.4 times too
|
||||
//! large, because model-space paper units were taken as inches.
|
||||
//!
|
||||
//! The model plot's units are the paper's, never the layouts' page setups': a layout whose page
|
||||
//! setup is in inches still plots its paper space in inches (#1866).
|
||||
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, Layout, Line, PageSetup, Space};
|
||||
use cadcraft_geom::Vec3;
|
||||
use cadcraft_io::plot;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::pdf_read;
|
||||
|
||||
/// The page size in points.
|
||||
fn media_box(pdf: &[u8]) -> (f64, f64) {
|
||||
pdf_read::read(pdf).media()
|
||||
}
|
||||
|
||||
/// The plotted length in points of the single horizontal line.
|
||||
fn line_pt(pdf: &[u8]) -> f64 {
|
||||
let doc = pdf_read::read(pdf);
|
||||
let xs: Vec<f64> = pdf_read::drawn(doc.content()).iter().filter(|o| o.op == "m" || o.op == "l").filter_map(|o| o.nums.first().copied()).collect();
|
||||
assert_eq!(xs.len(), 2, "one line, two ends: {xs:?}");
|
||||
(xs[1] - xs[0]).abs()
|
||||
}
|
||||
|
||||
/// A drawing with one 10-unit line in model space and the given drawing units.
|
||||
fn drawing(insunits: i64, measurement: i64) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_i64("INSUNITS", insunits);
|
||||
d.header.set_i64("MEASUREMENT", measurement);
|
||||
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) });
|
||||
d.add(&Space::Model, Common::default(), line).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// Plot the model at 1:1 on the named paper, as the Plot dialog does.
|
||||
fn plot_on(d: &Drawing, paper: &str) -> Vec<u8> {
|
||||
let opts: Value = json!({
|
||||
"paper": paper,
|
||||
"landscape": false,
|
||||
"fit": false,
|
||||
"scale": 1,
|
||||
"lineweights": false,
|
||||
"compress": false,
|
||||
});
|
||||
plot(d, &Space::Model, &opts).unwrap()
|
||||
}
|
||||
|
||||
const A4_PT: (f64, f64) = (595.28, 841.89);
|
||||
const ANSI_A_PT: (f64, f64) = (612.0, 792.0);
|
||||
const TEN_MM_PT: f64 = 28.3465;
|
||||
const TEN_IN_PT: f64 = 720.0;
|
||||
|
||||
fn assert_pt(actual: f64, want: f64) {
|
||||
assert!((actual - want).abs() < 0.01, "{actual} pt, want {want}");
|
||||
}
|
||||
|
||||
/// The MediaBox is the sheet in points (A4 or ANSI A, portrait).
|
||||
fn assert_media(pdf: &[u8], size: (f64, f64)) {
|
||||
let (w, h) = media_box(pdf);
|
||||
assert!((w - size.0).abs() < 0.01 && (h - size.1).abs() < 0.01, "{w} x {h} pt, want {size:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_plot_in_a_metric_drawing_is_one_to_one() {
|
||||
let pdf = plot_on(&drawing(4, 1), "ISO A4");
|
||||
assert_media(&pdf, A4_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_MM_PT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_plot_follows_the_length_unit_when_measurement_says_inches() {
|
||||
// A drawing started imperial whose units the user changed to millimetres with UNITS:
|
||||
// MEASUREMENT stays 0, the length unit is what says the drawing is in millimetres.
|
||||
let pdf = plot_on(&drawing(4, 0), "ISO A4");
|
||||
assert_media(&pdf, A4_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_MM_PT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_plot_takes_units_from_the_paper() {
|
||||
// A millimetre sheet at 1:1 prints one drawing unit per millimetre, whatever the drawing's
|
||||
// length unit is.
|
||||
let pdf = plot_on(&drawing(1, 0), "ISO A4");
|
||||
assert_media(&pdf, A4_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_MM_PT);
|
||||
// An inch sheet prints one drawing unit per inch, whatever the drawing's length unit is.
|
||||
let pdf = plot_on(&drawing(4, 0), "ANSI A");
|
||||
assert_media(&pdf, ANSI_A_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_IN_PT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_plot_on_an_inch_sheet_is_in_inches_whatever_measurement_says() {
|
||||
// MEASUREMENT 1 (an ISO-template drawing) must not turn an inch sheet's units into
|
||||
// millimetres: a 10-unit line on ANSI A at 1:1 is 10 inches for every drawing unit.
|
||||
for (insunits, measurement) in [(4, 1), (0, 1), (1, 1), (4, 0)] {
|
||||
let pdf = plot_on(&drawing(insunits, measurement), "ANSI A");
|
||||
assert_media(&pdf, ANSI_A_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_IN_PT);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_plot_keeps_its_page_setup_units() {
|
||||
// The @echelon regression: a metric drawing whose layout has a page setup in inches. The
|
||||
// layout's paper space is in inches (25.4 mm per unit), not in the drawing's millimetres,
|
||||
// and its A4 sheet is still A4.
|
||||
let mut d = drawing(4, 0);
|
||||
let mut l = Layout::new("SHEET", 3);
|
||||
l.page = PageSetup {
|
||||
paper: "ISO A4".into(),
|
||||
width_mm: 210.0,
|
||||
height_mm: 297.0,
|
||||
margins_mm: [0.0; 4],
|
||||
landscape: false,
|
||||
paper_mm: Some(false),
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) });
|
||||
d.add(&Space::Paper("SHEET".into()), Common::default(), line).unwrap();
|
||||
let opts = json!({"fit": false, "scale": 1, "lineweights": false, "compress": false});
|
||||
let pdf = plot(&d, &Space::Paper("SHEET".into()), &opts).unwrap();
|
||||
assert_media(&pdf, A4_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_IN_PT);
|
||||
}
|
||||
@@ -197,7 +197,7 @@ pub(super) fn layouts() -> Case {
|
||||
let mut drawing = cases::drawing();
|
||||
drawing.layouts = vec![Layout::new("Sheet_A", 1), Layout::new("Sheet_B", 2)];
|
||||
for (index, layout) in drawing.layouts.iter_mut().enumerate() {
|
||||
layout.page.paper_mm = true;
|
||||
layout.page.paper_mm = Some(true);
|
||||
// PageSetup stores portrait dimensions; landscape is a separate orientation flag.
|
||||
layout.page.width_mm = 297.0;
|
||||
layout.page.height_mm = 420.0;
|
||||
|
||||
@@ -226,22 +226,6 @@ fn find_text_reads_texts_and_render_shows_one_area() {
|
||||
assert_eq!((w, h), (1600, 800));
|
||||
}
|
||||
|
||||
/// Guards #3011: `find_text` filters by `query` as it does by `contains`, instead of ignoring it
|
||||
/// and returning every text.
|
||||
#[test]
|
||||
fn find_text_filters_by_query() {
|
||||
let mut s = Server::new(Box::new(Headless::default()));
|
||||
call(&mut s, 1, "initialize", json!({"protocolVersion": "2025-06-18"}));
|
||||
tool(&mut s, "execute", json!({"command": "text", "params": {"at": [1, 1], "height": 0.15, "text": "RECAMARA 1"}}));
|
||||
tool(&mut s, "execute", json!({"command": "text", "params": {"at": [50, 1], "height": 0.15, "text": "COCINA"}}));
|
||||
assert_eq!(tool(&mut s, "find_text", json!({}))["count"], 2);
|
||||
let r = tool(&mut s, "find_text", json!({"query": "cocina"}));
|
||||
assert_eq!((r["count"].as_u64(), r["texts"][0]["text"].as_str()), (Some(1), Some("COCINA")), "{r}");
|
||||
assert_eq!(tool(&mut s, "find_text", json!({"query": "nada"}))["count"], 0);
|
||||
// `contains` still works and wins when both are given.
|
||||
assert_eq!(tool(&mut s, "find_text", json!({"contains": "recamara", "query": "cocina"}))["texts"][0]["text"], "RECAMARA 1");
|
||||
}
|
||||
|
||||
/// Guards a lazy Remote bridge: it serves tools without the app, reports how to start it
|
||||
/// (`--control`), and reaches the app once that app starts listening on the port.
|
||||
#[test]
|
||||
|
||||
@@ -28,8 +28,8 @@ pub fn tool_definitions(has_ui: bool) -> Value {
|
||||
"background": {"type": "string", "description": "\"dark\" (default without plot_style), \"white\" (default with one), \"paper\" or \"#rrggbb\""},
|
||||
"plot_style": {"type": "string", "description": "a plot style table: monochrome.ctb, grayscale.ctb, default.ctb, default.stb, monochrome.stb, or one the drawing holds; \"none\" or \"\" for the objects' own properties"},
|
||||
"path": {"type": "string"}}}}),
|
||||
json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case; `query` is the same filter), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.",
|
||||
"inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "query": {"type": "string"}, "layer": {"type": "string"},
|
||||
json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.",
|
||||
"inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "layer": {"type": "string"},
|
||||
"window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2},
|
||||
"limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}),
|
||||
json!({"name": "new_drawing", "description": "Create a new drawing (imperial by default, or metric).",
|
||||
|
||||
+170
-6
@@ -1,7 +1,9 @@
|
||||
//! Paper sizes and the layout sheet (paper rectangle, printable area) for paper space.
|
||||
//!
|
||||
//! Paper-space units are millimetres in metric drawings (`MEASUREMENT` = 1) and on layouts whose
|
||||
//! page setup is in millimetres, and inches otherwise. The sheet's lower-left corner is the paper-space origin.
|
||||
//! Paper-space units follow a layout's explicit page-setup choice (millimetres or inches), and
|
||||
//! otherwise `MEASUREMENT` (millimetres when 1, inches otherwise). The sheet's lower-left corner is the paper-space origin.
|
||||
//! Model-space plots have no stored page setup, so they take their units from the paper itself
|
||||
//! ([`model_page`], [`model_unit_mm`]).
|
||||
|
||||
use cadcraft_doc::{Drawing, PageSetup};
|
||||
use cadcraft_geom::{Bounds2, Vec2};
|
||||
@@ -81,11 +83,70 @@ pub fn paper_unit_mm(d: &Drawing) -> f64 {
|
||||
if d.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 25.4 }
|
||||
}
|
||||
|
||||
/// Millimetres per paper-space unit on a layout with page setup `page`: millimetres when the
|
||||
/// page says so (plot paper units mm), else as the drawing's MEASUREMENT says. Drawings from
|
||||
/// AutoCAD often have MEASUREMENT 0 with layouts in millimetres (#1058).
|
||||
/// Whether the drawing's length unit is metric: `INSUNITS` millimetres to kilometres and
|
||||
/// angstroms to parsecs (4..=7, 11..=20) are metric, inches to US survey units (1, 2, 3, 8, 9,
|
||||
/// 10, 21, 22, 23, 24) imperial. A unitless drawing (`INSUNITS` 0, absent or unknown, as files
|
||||
/// without `$INSUNITS` are read, #1209) falls back to `MEASUREMENT` = 1.
|
||||
///
|
||||
/// `MEASUREMENT` only chooses the imperial or ISO hatch and linetype libraries (#1649, #1826),
|
||||
/// so it is not what says a drawing is metric: a drawing whose units are millimetres but whose
|
||||
/// MEASUREMENT is 0 — what UNITS leaves when the user picks millimetres, and what AutoCAD writes
|
||||
/// for many metric drawings — is metric by this test (#1828).
|
||||
pub fn metric_length_unit(d: &Drawing) -> bool {
|
||||
match d.header.i64("INSUNITS", 0) {
|
||||
// Inches, feet, miles, microinches, mils, yards and US survey units.
|
||||
1 | 2 | 3 | 8 | 9 | 10 | 21 | 22 | 23 | 24 => false,
|
||||
// Millimetres, centimetres, metres, kilometres, angstroms, nanometres, microns,
|
||||
// decimetres to gigametres, astronomical units, light years and parsecs.
|
||||
4..=7 | 11..=20 => true,
|
||||
// Unitless: as MEASUREMENT says.
|
||||
_ => d.header.i64("MEASUREMENT", 0) == 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Millimetres per paper unit of the paper named by `page`, from the paper itself: 1.0 for ISO
|
||||
/// and user-defined millimetre sizes, 25.4 for the ANSI, ARCH and Legal sheets. A name that is
|
||||
/// no known paper size is treated as a user millimetre size (1.0).
|
||||
pub fn model_unit_mm(page: &PageSetup) -> f64 {
|
||||
match paper_size(&page.paper) {
|
||||
Some(p) if p.imperial => 25.4,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The page a model-space plot starts from: ISO A4 in a drawing whose length unit is metric,
|
||||
/// ANSI A otherwise. Model space has no stored page setup, so the plot takes its sheet (and its
|
||||
/// units) from here unless the caller picks another paper.
|
||||
pub fn model_page(d: &Drawing) -> PageSetup {
|
||||
let mut page = PageSetup::default();
|
||||
if let Some(p) = paper_size(if metric_length_unit(d) { "A4" } else { "ANSI A" }) {
|
||||
page.paper = p.name.into();
|
||||
page.width_mm = p.width_mm;
|
||||
page.height_mm = p.height_mm;
|
||||
}
|
||||
apply_model_paper_units(&mut page);
|
||||
page
|
||||
}
|
||||
|
||||
/// Set a model-space plot's paper units once its paper is known: the paper's own units decide
|
||||
/// (ISO and user millimetre sizes are millimetres, ANSI and ARCH sheets inches), as a model-space
|
||||
/// page setup's "plot paper units" would. Layouts keep their stored page setup and go through
|
||||
/// [`page_unit_mm`]; only model-space callers use this. The units are set explicitly either
|
||||
/// way: an inch sheet left to follow `MEASUREMENT` would plot in millimetres in a drawing whose
|
||||
/// `MEASUREMENT` is 1.
|
||||
pub fn apply_model_paper_units(page: &mut PageSetup) {
|
||||
page.paper_mm = Some(model_unit_mm(page) == 1.0);
|
||||
}
|
||||
|
||||
/// Millimetres per paper-space unit on a layout with page setup `page`: `1.0` when the page
|
||||
/// chooses millimetres, `25.4` when it chooses inches, else as the drawing's `MEASUREMENT`
|
||||
/// says. Drawings from AutoCAD often have `MEASUREMENT` 0 with layouts in millimetres (#1058).
|
||||
pub fn page_unit_mm(d: &Drawing, page: &PageSetup) -> f64 {
|
||||
if page.paper_mm { 1.0 } else { paper_unit_mm(d) }
|
||||
match page.paper_mm {
|
||||
Some(true) => 1.0,
|
||||
Some(false) => 25.4,
|
||||
None => paper_unit_mm(d),
|
||||
}
|
||||
}
|
||||
|
||||
/// Millimetres per paper-space unit on the layout holding the paper-space entity `h` (the
|
||||
@@ -139,6 +200,92 @@ pub fn sheet(d: &Drawing, layout: &str) -> Option<Sheet> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn metric_length_unit_reads_the_length_unit() {
|
||||
// Metric units, whatever MEASUREMENT says.
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_i64("MEASUREMENT", 0);
|
||||
for u in [4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] {
|
||||
d.header.set_i64("INSUNITS", u);
|
||||
assert!(metric_length_unit(&d), "INSUNITS {u} is metric");
|
||||
}
|
||||
// Imperial units, even with MEASUREMENT 1.
|
||||
d.header.set_i64("MEASUREMENT", 1);
|
||||
for u in [1, 2, 3, 8, 9, 10, 21, 22, 23, 24] {
|
||||
d.header.set_i64("INSUNITS", u);
|
||||
assert!(!metric_length_unit(&d), "INSUNITS {u} is imperial");
|
||||
}
|
||||
// Unitless: as MEASUREMENT says.
|
||||
for u in [0, 25] {
|
||||
d.header.set_i64("INSUNITS", u);
|
||||
d.header.set_i64("MEASUREMENT", 1);
|
||||
assert!(metric_length_unit(&d), "unitless with MEASUREMENT 1 is metric");
|
||||
d.header.set_i64("MEASUREMENT", 0);
|
||||
assert!(!metric_length_unit(&d), "unitless with MEASUREMENT 0 is imperial");
|
||||
}
|
||||
d.header.vars.remove("INSUNITS");
|
||||
d.header.vars.remove("MEASUREMENT");
|
||||
assert!(!metric_length_unit(&d), "no units at all is imperial, as before");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paper_unit_mm_still_follows_measurement() {
|
||||
let mut m = Drawing::new_metric();
|
||||
assert_eq!(paper_unit_mm(&m), 1.0);
|
||||
m.header.set_i64("MEASUREMENT", 0);
|
||||
assert_eq!(paper_unit_mm(&m), 25.4, "layouts stay on MEASUREMENT (page setups in inches fit)");
|
||||
let mut i = Drawing::new_imperial();
|
||||
assert_eq!(paper_unit_mm(&i), 25.4);
|
||||
i.header.set_i64("INSUNITS", 4);
|
||||
assert_eq!(paper_unit_mm(&i), 25.4, "a metric length unit does not move layout paper units");
|
||||
i.header.set_i64("MEASUREMENT", 1);
|
||||
assert_eq!(paper_unit_mm(&i), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_unit_mm_reads_the_paper() {
|
||||
let page = |name: &str| PageSetup { paper: name.into(), ..PageSetup::default() };
|
||||
assert_eq!(model_unit_mm(&page("ISO A4")), 1.0);
|
||||
assert_eq!(model_unit_mm(&page("ISO A0")), 1.0);
|
||||
assert_eq!(model_unit_mm(&page("ANSI A")), 25.4);
|
||||
assert_eq!(model_unit_mm(&page("ARCH D")), 25.4);
|
||||
assert_eq!(model_unit_mm(&page("User (300.00 x 400.00 MM)")), 1.0);
|
||||
assert_eq!(model_unit_mm(&page("nope")), 1.0, "an unknown paper is a user millimetre size");
|
||||
assert_eq!(model_unit_mm(&PageSetup::default()), 25.4, "the default page is ANSI A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_page_is_a4_for_metric_drawings() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let page = model_page(&d);
|
||||
assert_eq!(page.paper, "ISO A4 (210.00 x 297.00 MM)");
|
||||
assert_eq!((page.width_mm, page.height_mm), (210.0, 297.0));
|
||||
assert_eq!(page.paper_mm, Some(true), "A4 in a metric drawing is in millimetres");
|
||||
// The length unit decides, not MEASUREMENT.
|
||||
d.header.set_i64("MEASUREMENT", 0);
|
||||
assert_eq!(model_page(&d).paper, "ISO A4 (210.00 x 297.00 MM)");
|
||||
// An imperial drawing starts on ANSI A.
|
||||
let page = model_page(&Drawing::new_imperial());
|
||||
assert_eq!(page.paper, "ANSI A (8.50 x 11.00 Inches)");
|
||||
assert!((page.width_mm - 215.9).abs() < 1e-9 && (page.height_mm - 279.4).abs() < 1e-9);
|
||||
assert_eq!(page.paper_mm, Some(false), "ANSI A in an imperial drawing is in inches");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_paper_units_follow_the_chosen_paper() {
|
||||
// The sheet decides, whatever the drawing's length unit is.
|
||||
let mut a4 = PageSetup { paper: "ISO A4 (210.00 x 297.00 MM)".into(), ..PageSetup::default() };
|
||||
apply_model_paper_units(&mut a4);
|
||||
assert_eq!(a4.paper_mm, Some(true), "ISO A4 is a millimetre sheet");
|
||||
let mut ansi = PageSetup { paper: "ANSI A (8.50 x 11.00 Inches)".into(), ..PageSetup::default() };
|
||||
apply_model_paper_units(&mut ansi);
|
||||
assert_eq!(ansi.paper_mm, Some(false), "ANSI A is an inch sheet");
|
||||
// A user size in millimetres is one to one.
|
||||
let mut user = PageSetup { paper: "User (300.00 x 400.00 MM)".into(), ..PageSetup::default() };
|
||||
apply_model_paper_units(&mut user);
|
||||
assert_eq!(user.paper_mm, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_and_sheet() {
|
||||
assert_eq!(paper_size("a4").map(|p| p.width_mm), Some(210.0));
|
||||
@@ -154,6 +301,23 @@ mod tests {
|
||||
let s = Sheet::from_page(&hostile, 0.0);
|
||||
assert!(s.size.x > 0.0 && s.printable == s.bounds());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_unit_mm_honours_explicit_choice_and_falls_back_to_measurement() {
|
||||
let mut imperial = Drawing::new_imperial();
|
||||
imperial.header.set_i64("MEASUREMENT", 0);
|
||||
let mut metric = Drawing::new_metric();
|
||||
metric.header.set_i64("MEASUREMENT", 1);
|
||||
let unset = PageSetup::default();
|
||||
let mm = PageSetup { paper_mm: Some(true), ..PageSetup::default() };
|
||||
let inches = PageSetup { paper_mm: Some(false), ..PageSetup::default() };
|
||||
assert_eq!(page_unit_mm(&imperial, &unset), 25.4);
|
||||
assert_eq!(page_unit_mm(&imperial, &mm), 1.0);
|
||||
assert_eq!(page_unit_mm(&imperial, &inches), 25.4);
|
||||
assert_eq!(page_unit_mm(&metric, &unset), 1.0);
|
||||
assert_eq!(page_unit_mm(&metric, &mm), 1.0);
|
||||
assert_eq!(page_unit_mm(&metric, &inches), 25.4);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a layout's saved page setup says about how to plot it, for a plot that was not given the
|
||||
|
||||
@@ -584,7 +584,8 @@ fn page_setup(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action
|
||||
let Some((_, name, page)) = layouts.iter().find(|l| l.1 == sel) else { return };
|
||||
right.label(RichText::new(format!("Page setup of {name}")).strong());
|
||||
// Layout plotting always prints the whole sheet, so only that area is offered.
|
||||
let rows = PageRows { areas: &["layout"], scale: true, center: true };
|
||||
let paper_mm = cadcraft_render::paper::page_unit_mm(d, page) == 1.0;
|
||||
let rows = PageRows { areas: &["layout"], scale: true, center: true, paper_mm: Some(paper_mm) };
|
||||
egui::Grid::new("pagesetup_grid").num_columns(2).spacing(vec2(10.0, 6.0)).show(right, |ui| {
|
||||
if let Some((k, v)) = page_rows(ui, egui::Id::unique(("pagesetup", name)), page, &rows, &choices, None) {
|
||||
action = Some(("pagesetup", json!({ "layout": name, k: v })));
|
||||
@@ -604,6 +605,9 @@ struct PageRows {
|
||||
areas: &'static [&'static str],
|
||||
scale: bool,
|
||||
center: bool,
|
||||
/// Effective paper units (`Some(true)` = millimetres, `Some(false)` = inches) for the layout's
|
||||
/// page setup, or `None` to hide the row (the Plot dialog).
|
||||
paper_mm: Option<bool>,
|
||||
}
|
||||
|
||||
/// The devices and plot style tables the page-setup rows offer.
|
||||
@@ -666,7 +670,7 @@ fn parse_ratio(t: &str) -> Option<f64> {
|
||||
/// The page-setup rows (device, paper, orientation, plot area, fit, scale, center, lineweights,
|
||||
/// transparency, plot style table) shared by the Page Setup Manager and the Plot dialog, inside a
|
||||
/// two-column grid. Returns the setting the user changed as a `pagesetup` parameter (`device`,
|
||||
/// `paper`, `landscape`, `plotArea`, `scaleToFit`, `scale`, `center`, `lineweights`,
|
||||
/// `paper`, `landscape`, `paperUnits`, `plotArea`, `scaleToFit`, `scale`, `center`, `lineweights`,
|
||||
/// `plotTransparency` or `plotStyleTable`).
|
||||
fn page_rows(
|
||||
ui: &mut egui::Ui,
|
||||
@@ -724,6 +728,23 @@ fn page_rows(
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
if let Some(mm) = rows.paper_mm {
|
||||
ui.label(crate::tl!("Paper units"));
|
||||
ui.horizontal(|ui| {
|
||||
// Every click records the choice, even on the selected radio: while the layout has
|
||||
// no explicit units it inherits MEASUREMENT, and clicking the value it currently
|
||||
// inherits must lock that choice against a later MEASUREMENT change (#3249).
|
||||
if ui.radio(!mm, crate::tl!("Inches")).clicked() {
|
||||
change = Some(("paperUnits", json!("inches")));
|
||||
}
|
||||
if ui.radio(mm, crate::tl!("Millimeters")).clicked() {
|
||||
change = Some(("paperUnits", json!("mm")));
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(crate::tl!("What one paper-space unit is on this layout"));
|
||||
ui.end_row();
|
||||
}
|
||||
ui.label("Plot area");
|
||||
ui.add_enabled_ui(rows.areas.len() > 1, |ui| {
|
||||
craft_ui::ComboBox::from_id_salt(salt.with("area")).selected_text(area_label(&page.plot_area)).show_ui(ui, |ui| {
|
||||
@@ -909,7 +930,7 @@ fn plot_page(d: &cadcraft_doc::Drawing, target: &str) -> cadcraft_doc::PageSetup
|
||||
return page;
|
||||
}
|
||||
let mut page = cadcraft_doc::PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..Default::default() };
|
||||
if cadcraft_render::paper::paper_unit_mm(d) == 1.0
|
||||
if cadcraft_render::paper::metric_length_unit(d)
|
||||
&& let Some(a4) = cadcraft_render::paper_size("A4")
|
||||
{
|
||||
page.paper = a4.name.into();
|
||||
@@ -1034,9 +1055,9 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
|
||||
ui.horizontal_top(|ui| {
|
||||
egui::Grid::new("plot_grid").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
|
||||
let rows = if model {
|
||||
PageRows { areas: MODEL_AREAS, scale: true, center: false }
|
||||
PageRows { areas: MODEL_AREAS, scale: true, center: false, paper_mm: None }
|
||||
} else {
|
||||
PageRows { areas: &["layout"], scale: false, center: false }
|
||||
PageRows { areas: &["layout"], scale: false, center: false, paper_mm: None }
|
||||
};
|
||||
let placement = model.then_some((&mut st.center, &mut st.offset_mm, offset_supported));
|
||||
if let Some((k, v)) = page_rows(ui, egui::Id::unique(("plot", st.target.as_str())), &st.page, &rows, &choices, placement) {
|
||||
|
||||
@@ -27,6 +27,7 @@ mod native_menu_text_keys;
|
||||
mod native_windows;
|
||||
mod options_dialog;
|
||||
mod options_right_click;
|
||||
mod page_setup_paper_units;
|
||||
mod parameters_rename;
|
||||
mod pickdrag;
|
||||
mod properties_described;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! File ▸ Page Setup Manager: a layout's paper units can be millimetres on an inch-family sheet
|
||||
//! (an ARCH D sheet in a metric drawing, #3249), so the sheet measures 914.4 x 609.6 units.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::vec2;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn page_setup_switches_an_arch_d_sheet_to_millimetres() {
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.run("units", json!({ "insunits": 4 })).unwrap();
|
||||
app.run("pagesetup", json!({ "layout": "Layout1", "paper": "ARCH D", "landscape": true })).unwrap();
|
||||
let inch = cadcraft_render::sheet(app.session.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((inch.size.x - 36.0).abs() < 1e-9, "{:?}", inch.size);
|
||||
app.start("pagesetup");
|
||||
// The dialog's existing combo boxes (device, paper, plot area, plot style) have no
|
||||
// accessible name yet; that check is not what this test is about.
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_accessibility_check(false).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.get_by_label("Millimeters").click();
|
||||
h.run_steps(5);
|
||||
let d = h.state().session.doc().unwrap();
|
||||
assert_eq!(d.layout("Layout1").unwrap().page.paper_mm, Some(true));
|
||||
let mm = cadcraft_render::sheet(d, "Layout1").unwrap();
|
||||
assert!((mm.size.x - 914.4).abs() < 1e-9 && (mm.size.y - 609.6).abs() < 1e-9, "{:?}", mm.size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_setup_switches_a_metric_drawing_sheet_to_inches() {
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.run("setvar", json!({ "name": "MEASUREMENT", "value": 1 })).unwrap();
|
||||
app.run("pagesetup", json!({ "layout": "Layout1", "paper": "ARCH D", "landscape": true })).unwrap();
|
||||
let mm = cadcraft_render::sheet(app.session.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((mm.size.x - 914.4).abs() < 1e-9 && (mm.size.y - 609.6).abs() < 1e-9, "{:?}", mm.size);
|
||||
app.start("pagesetup");
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_accessibility_check(false).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.get_by_label("Inches").click();
|
||||
h.run_steps(5);
|
||||
let d = h.state().session.doc().unwrap();
|
||||
assert_eq!(d.layout("Layout1").unwrap().page.paper_mm, Some(false));
|
||||
let inch = cadcraft_render::sheet(d, "Layout1").unwrap();
|
||||
assert!((inch.size.x - 36.0).abs() < 1e-9 && (inch.size.y - 24.0).abs() < 1e-9, "{:?}", inch.size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_the_inherited_paper_units_records_the_choice() {
|
||||
// The layout starts with no explicit units and inherits MEASUREMENT 0 (inches). Clicking the
|
||||
// selected Inches radio must record that choice, so a later MEASUREMENT change cannot flip
|
||||
// the sheet to millimetres (#3249).
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.run("pagesetup", json!({ "layout": "Layout1", "paper": "ARCH D", "landscape": true })).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, None);
|
||||
app.start("pagesetup");
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_accessibility_check(false).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.get_by_label("Inches").click();
|
||||
h.run_steps(5);
|
||||
assert_eq!(h.state().session.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, Some(false));
|
||||
h.state_mut().run("setvar", json!({ "name": "MEASUREMENT", "value": 1 })).unwrap();
|
||||
let d = h.state().session.doc().unwrap();
|
||||
assert_eq!(d.layout("Layout1").unwrap().page.paper_mm, Some(false));
|
||||
let inch = cadcraft_render::sheet(d, "Layout1").unwrap();
|
||||
assert_eq!(inch.unit_mm, 25.4);
|
||||
assert!((inch.size.x - 36.0).abs() < 1e-9 && (inch.size.y - 24.0).abs() < 1e-9, "{:?}", inch.size);
|
||||
}
|
||||
+1
-1
@@ -48,7 +48,7 @@ Example client configuration (Claude Code / Claude Desktop):
|
||||
| `execute {"command": "loops", "params": {tolerance?, maxPairs?, limit?, offset?}}` | Implied closed loops from loose LINE and ARC chains: each closed loop with its member handles, perimeter, area and winding, exact with arcs; each open chain with the endpoint gap, its location (`at`, `ends`) and length; and branch junctions (three or more ends meeting), reported but not resolved. `tolerance` defaults to 1e-9 × the extents diagonal; the quadratic endpoint pairing stops at `maxPairs` (default 1,000,000) and reports `capped` with `pairTestsNeeded` instead of guessing from a partial pairing. |
|
||||
| `query_entities {type?, layer?, selected?, window?, crossing?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `count` is every match, `returned` the page (`offset`, `limit`, default 500). |
|
||||
| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. |
|
||||
| `find_text {contains?, query?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (`contains`, or `query` as an alias; any case), layer and a window around the insertion points. Read-only (the `texts` command). |
|
||||
| `find_text {contains?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (any case), layer and a window around the insertion points. Read-only (the `texts` command). |
|
||||
| `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. |
|
||||
| `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. |
|
||||
|
||||
|
||||
+1
-2
@@ -81,8 +81,7 @@ prints as `Normal`. A colour-dependent table ignores the property.
|
||||
style and the named styles.
|
||||
- `layer.set {name, plotStyle}` sets a layer's plot style.
|
||||
- `stylesmanager {action, …}` manages the tables: `list`, `get`, `new` (`kind`, `from`), `set`
|
||||
(`style: {name, …fields}`, `removeStyle`, `description`; it replies with the table's name and
|
||||
only what changed), `delete`, `load` (`path` or `text`)
|
||||
(`style: {name, …fields}`, `removeStyle`, `description`), `delete`, `load` (`path` or `text`)
|
||||
and `save` (`path`, or returns `text`). Typed or chosen from **File ▸ Plot Styles...**, it
|
||||
opens the Plot Style Manager dialog.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user