mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-19 20:30:42 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23a599dcd6 | ||
|
|
a1f5481cf9 | ||
|
|
e072b680d6 | ||
|
|
7c98bb2617 | ||
|
|
865ecbd071 | ||
|
|
2423f45e49 | ||
|
|
b4c76bb796 | ||
|
|
39a2e4da07 | ||
|
|
4750d67331 | ||
|
|
152e3b560c |
Generated
+4
-3
@@ -717,6 +717,7 @@ version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-geom",
|
||||
"craft-dxf",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1183,7 +1184,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=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
@@ -1202,9 +1203,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
|
||||
dependencies = [
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9)",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a)",
|
||||
"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 = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
|
||||
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,6 +11,7 @@ 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 }
|
||||
|
||||
+46
-314
@@ -1,32 +1,14 @@
|
||||
//! Readers for the user's own linetype (`.lin`) and hatch pattern (`.pat`) files.
|
||||
//!
|
||||
//! 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.
|
||||
//! 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};
|
||||
|
||||
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 {
|
||||
@@ -35,307 +17,57 @@ 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 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")),
|
||||
}
|
||||
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,
|
||||
}
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
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,
|
||||
}
|
||||
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() })
|
||||
}
|
||||
|
||||
@@ -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), 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; `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")
|
||||
.noundo(),
|
||||
CommandSpec::new("countlist", "Count List", count::run_countlist)
|
||||
.params("{space?: all (default)|current|model|<layout>, nested?: bool} → per-block counts, as COUNT")
|
||||
@@ -664,7 +664,12 @@ 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")))
|
||||
})
|
||||
};
|
||||
let contains = text("contains")?;
|
||||
// `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 layer = text("layer")?;
|
||||
let window = given("window")
|
||||
.map(|w| {
|
||||
|
||||
@@ -264,16 +264,23 @@ 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.chars().take(255).collect::<String>()));
|
||||
t.styles.push(PlotStyle::object(sname));
|
||||
t.styles.len() - 1
|
||||
}
|
||||
None => return Err(bad(cmd, format!("`{name}` has no style `{sname}` (colour-dependent styles are Color_1 to Color_255)"))),
|
||||
@@ -283,7 +290,21 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let t = t.sanitized();
|
||||
let out = serde_json::to_value(&t).unwrap_or(Value::Null);
|
||||
// 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()));
|
||||
}
|
||||
}
|
||||
store(s.doc_mut()?, t);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -213,10 +213,19 @@ 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,6 +649,17 @@ 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,7 +62,10 @@ 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();
|
||||
let pen = r["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Pen 5").unwrap().clone();
|
||||
// `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");
|
||||
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"))
|
||||
@@ -131,3 +134,68 @@ 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}");
|
||||
}
|
||||
|
||||
@@ -226,6 +226,22 @@ 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), `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"},
|
||||
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"},
|
||||
"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).",
|
||||
|
||||
+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?, 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). |
|
||||
| `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). |
|
||||
| `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. |
|
||||
|
||||
|
||||
+2
-1
@@ -81,7 +81,8 @@ 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`), `delete`, `load` (`path` or `text`)
|
||||
(`style: {name, …fields}`, `removeStyle`, `description`; it replies with the table's name and
|
||||
only what changed), `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