Compare commits

..
Author SHA1 Message Date
FredApps 88f76a91f6 fix(ci): give each plotter test its own device name
The in-memory plotter store is shared by the whole test process. On
FreeBSD the tests run as threads of one process (cargo test), so the
three tests that each create a "Banner Printer" collide and the later
one fails with "plotter `Banner Printer` already exists". Each test now
creates a device with its own name.
2026-12-02 09:38:12 +01:00
21 changed files with 90 additions and 1125 deletions
Generated
+2 -25
View File
@@ -26,29 +26,6 @@ dependencies = [
"web-time",
]
[[package]]
name = "acadrust"
version = "0.6.6"
source = "git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436#5d5c482b3fcb3dc77e8281474461760f32959436"
dependencies = [
"anyhow",
"bitflags 2.13.2",
"byteorder",
"encoding_rs",
"flate2",
"foldhash 0.2.0",
"indexmap",
"itoa",
"memmap2",
"nom 7.1.3",
"oem_cp",
"once_cell",
"rayon",
"ryu",
"thiserror 2.0.21",
"web-time",
]
[[package]]
name = "accesskit"
version = "0.25.2"
@@ -878,7 +855,7 @@ dependencies = [
name = "cadcraft-io"
version = "0.21.0"
dependencies = [
"acadrust 0.6.6 (git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436)",
"acadrust",
"cadcraft-color",
"cadcraft-doc",
"cadcraft-fonts",
@@ -1457,7 +1434,7 @@ name = "craft-dwg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"acadrust 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)",
"acadrust",
"log",
]
+14 -17
View File
@@ -213,14 +213,16 @@ mod tests {
let path = directory.join("workspace.json");
let (mut first, restored, error) = Workspace::at(Some(path.clone()));
assert!(restored.is_none() && error.is_none());
let mut ui = UiState::default();
ui.show_palettes = false;
ui.show_command_line = false;
ui.toolset_tab = "Modeling".into();
ui.collapsed_groups = vec!["Solid".into()];
ui.history_lines = 5;
ui.dialog = Some("layers".into());
ui.start_tab = true;
let ui = UiState {
show_palettes: false,
show_command_line: false,
toolset_tab: "Modeling".into(),
collapsed_groups: vec!["Solid".into()],
history_lines: 5,
dialog: Some("layers".into()),
start_tab: true,
..Default::default()
};
first.save_if_changed(&ui, Instant::now()).unwrap();
let bytes = fs::read(&path).unwrap();
let value: Value = serde_json::from_slice(&bytes).unwrap();
@@ -311,9 +313,7 @@ mod tests {
let (mut store, ui, error) = Workspace::at(Some(path.clone()));
assert!(ui.is_none());
assert!(error.as_deref().is_some_and(|error| error.contains("left unchanged")));
let mut ui = UiState::default();
ui.show_palettes = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
store.save_if_changed(&UiState { show_palettes: false, ..Default::default() }, Instant::now()).unwrap();
assert_eq!(fs::read(&path).unwrap(), bytes);
}
fs::remove_dir_all(directory).unwrap();
@@ -351,8 +351,7 @@ mod tests {
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let start = Instant::now();
let mut ui = UiState::default();
ui.history_lines = 1;
let mut ui = UiState { history_lines: 1, ..Default::default() };
assert_eq!(store.save_if_changed(&ui, start).unwrap(), None);
// A drag: a new state every frame, none of them written until the interval ends.
for (frame, lines) in (2..=5).enumerate() {
@@ -376,8 +375,7 @@ mod tests {
let directory = temp_dir();
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let mut ui = UiState::default();
ui.show_palettes = false;
let mut ui = UiState { show_palettes: false, ..Default::default() };
store.save_if_changed(&ui, Instant::now()).unwrap();
let good = fs::read(&path).unwrap();
ui.collapsed_groups = vec!["x".repeat(257)];
@@ -393,8 +391,7 @@ mod tests {
let (mut store, _, _) = Workspace::at(Some(path.clone()));
// Simulate a destination becoming unavailable after startup.
fs::create_dir(&path).unwrap();
let mut ui = UiState::default();
ui.show_palettes = false;
let ui = UiState { show_palettes: false, ..Default::default() };
let first_error = store.save_if_changed(&ui, Instant::now()).unwrap_err();
fs::remove_dir(&path).unwrap();
assert_eq!(store.save_if_changed(&ui, Instant::now()).unwrap_err(), first_error);
-5
View File
@@ -261,11 +261,6 @@ pub fn is_user_pattern(name: &str) -> bool {
name.eq_ignore_ascii_case(USER_PATTERN)
}
/// Names owned by the standard library or the native user-defined hatch form.
pub fn is_reserved_pattern_name(name: &str) -> bool {
is_user_pattern(name) || pattern(name).is_some()
}
/// Hatch pattern scales must be greater than this limit. For a user-defined hatch, the scale is its line spacing.
pub const MIN_HATCH_PATTERN_SCALE: f64 = 1e-9;
+10 -26
View File
@@ -1,11 +1,10 @@
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
mod capture;
mod patfile;
pub(super) use edit::{set_pattern, takes_pattern};
pub use patfile::{PatternChoice, pattern_choices, pattern_choices_in, register_drawing_patterns};
pub(super) use patfile::{drawing_lines, run_patterns};
pub(super) use patfile::run_patterns;
pub use patfile::{PatternChoice, pattern_choices};
use cadcraft_color::Color;
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
@@ -57,10 +56,6 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
CommandSpec::new("hatch.capture", "Capture hatch tile", capture::run)
.params("{first:[x,y], second:[x,y], name?:string} → {pattern, patternText}; capture line segments inside the tile in the active space")
.enabled(has_doc)
.noundo(),
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
.enabled(has_doc)
@@ -345,7 +340,6 @@ pub(crate) fn gradient_name(t: &str) -> Option<&'static str> {
#[derive(Clone)]
struct HatchSettings {
lines: Vec<cadcraft_doc::library::PatternLine>,
pattern: String,
scale: f64,
/// HPSPACE for user-defined patterns. The entity stores it as its scale.
@@ -378,10 +372,8 @@ impl HatchSettings {
angle: f64_or(p, "angle", 0.0).to_radians(),
centered: bool_or(p, "centered", true),
});
let lines = s.doc().ok().and_then(|d| drawing_lines(d, &pattern)).unwrap_or_else(|| patfile::lines_for(&pattern));
let scale = f64_or(p, "scale", hdr.1).max(1e-9);
HatchSettings {
lines,
pattern,
scale,
user_spacing: scale,
@@ -425,12 +417,12 @@ impl HatchSettings {
background: None,
// A user-defined hatch's families come from its angle, spacing and double flag, not
// from a pattern definition; any other hatch takes the loaded pattern's, if any.
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { self.lines.clone() },
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { patfile::lines_for(&self.pattern) },
})
}
}
fn make(s: &mut Session, p: &Value, gradient: bool, loaded: &[String]) -> Result<Value> {
fn make(s: &mut Session, p: &Value, gradient: bool) -> Result<Value> {
// A zero or negative pattern scale would be clamped to a near-zero spacing.
size_param(if gradient { "gradient" } else { "hatch" }, p, "scale", false)?;
let cmd = if gradient { "gradient" } else { "hatch" };
@@ -443,10 +435,7 @@ fn make(s: &mut Session, p: &Value, gradient: bool, loaded: &[String]) -> Result
if gradient && str_param(p, "name").is_some_and(|t| gradient_name(t).is_none()) {
return Err(bad(cmd, format!("unknown gradient `name`; use one of {}", GRADIENT_NAMES.join(", "))));
}
let mut st = HatchSettings::from(s, p, gradient);
if loaded.iter().any(|n| n.eq_ignore_ascii_case(&st.pattern)) {
st.lines = patfile::lines_for(&st.pattern);
}
let st = HatchSettings::from(s, p, gradient);
// Loops by picked point or selected object: one hatch each when separate.
let mut groups: Vec<Vec<HatchLoop>> = Vec::new();
// Internal points and boundary objects can come together (the dialog's Pick points and
@@ -545,19 +534,18 @@ fn add_hatches(s: &mut Session, st: &HatchSettings, groups: Vec<Vec<HatchLoop>>)
}
fn run_hatch(s: &mut Session, p: &Value) -> Result<Value> {
let loaded = patfile::load_param(p)?;
patfile::load_param(p)?;
// Like the prompt: a name without a definition would be drawn as ANSI31.
if let Some(up) = str_param(p, "pattern").map(str::to_ascii_uppercase)
&& cadcraft_doc::library::pattern(&up).is_none()
&& patfile::user_pattern(&up).is_none()
&& drawing_lines(s.doc()?, &up).is_none()
{
return Err(bad("hatch", format!("unknown pattern {up}: not built in; load it with patternFile or patternText (a .pat file)")));
}
make(s, p, false, &loaded)
make(s, p, false)
}
fn run_gradient(s: &mut Session, p: &Value) -> Result<Value> {
make(s, p, true, &[])
make(s, p, true)
}
fn boundary_at(s: &mut Session, q: Vec2) -> Result<Vec<Handle>> {
@@ -718,17 +706,13 @@ impl HatchM {
self.settings.double = s.last_used.hatch_double;
return Ok(true);
}
let file = patfile::typed_file(s, t);
let explicit = file.is_some();
let up = match file {
let up = match patfile::typed_file(s, t) {
// Nothing loaded from it: the pattern is asked again.
Some(n) if n.is_empty() => return Ok(false),
Some(n) => n,
None => t.to_ascii_uppercase(),
};
let local = if explicit { None } else { drawing_lines(s.doc()?, &up) };
if local.is_some() || pattern_exists(&up) {
self.settings.lines = local.unwrap_or_else(|| patfile::lines_for(&up));
if pattern_exists(&up) {
self.settings.pattern = up.clone();
// A named pattern, SOLID included, is not the user-defined one.
self.settings.double = false;
-205
View File
@@ -1,205 +0,0 @@
//! Capture a rectangular tile from the active drawing space as reusable PAT text.
use cadcraft_doc::{Drawing, EntityKind, Space, library::PatternLine};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use crate::cmd::{bad, point_param};
use crate::{Result, Session};
const COMMAND: &str = "hatch.capture";
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let corner = |key| point_param(p, key).filter(|q| q.is_finite()).ok_or_else(|| bad(COMMAND, format!("give a finite {key} point [x,y]")));
let a = corner("first")?;
let b = corner("second")?;
let name = match p.get("name") {
None => "CAPTURED_TILE",
Some(v) => v.as_str().ok_or_else(|| bad(COMMAND, "name must be a string"))?,
}
.trim()
.to_ascii_uppercase();
if name.is_empty()
|| name.len() > 31
|| !name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
|| cadcraft_doc::library::is_reserved_pattern_name(&name)
{
return Err(bad(COMMAND, "use a custom pattern name of 1 to 31 letters, digits or underscores"));
}
let lines = capture_lines(s.doc()?, &s.space(), a, b).map_err(|e| bad(COMMAND, e))?;
let mut text = format!("*{name}, Custom pattern\n");
for line in lines {
text.push_str(&format!("{},{},{},{},{}", line.angle, line.origin.0, line.origin.1, line.delta.0, line.delta.1));
for dash in line.dashes {
text.push_str(&format!(",{dash}"));
}
text.push('\n');
}
Ok(json!({"pattern": name, "patternText": text}))
}
/// A PAT family repeats along an integer combination of the two tile edges.
/// The perpendicular neighbour is a second combination with determinant one.
fn captured_family(start: Vec2, end: Vec2, u: Vec2, v: Vec2, m: i32, n: i32) -> PatternLine {
let along = u * f64::from(m) + v * f64::from(n);
let period = along.len();
let dir = along / period;
// Extended Euclid: a*m + b*n = 1, so the neighbour is -b*u + a*v.
let (mut r, mut t) = (m, n);
let (mut a, mut b, mut c, mut d) = (1, 0, 0, 1);
while t != 0 {
let k = r / t;
(r, t) = (t, r % t);
(a, c) = (c, a - k * c);
(b, d) = (d, b - k * d);
}
let neighbour = (v * f64::from(a) - u * f64::from(b)) / f64::from(r);
let len = start.dist(end);
PatternLine {
origin: (start.x, start.y),
angle: dir.y.atan2(dir.x).to_degrees(),
delta: (neighbour.dot(dir), u.cross(v) / period),
dashes: if len >= period { Vec::new() } else { vec![len, len - period] },
}
}
fn capture_lines(d: &Drawing, space: &Space, a: Vec2, b: Vec2) -> std::result::Result<Vec<PatternLine>, &'static str> {
let low = Vec2::new(a.x.min(b.x), a.y.min(b.y));
let w = (a.x - b.x).abs();
let h = (a.y - b.y).abs();
if !w.is_finite() || !h.is_finite() || w < 1e-9 || h < 1e-9 {
return Err("Pick two opposite corners for the tile");
}
let entities = || d.space(space).into_iter().flat_map(|store| store.iter()).filter(|entity| d.is_visible(entity));
let (mut origin, mut u, mut v) = (low, Vec2::new(w, 0.), Vec2::new(0., h));
let mut guides = Vec::new();
for entity in entities() {
let EntityKind::LwPolyline(p) = &entity.kind else { continue };
if !p.closed || p.vertices.len() != 4 || p.vertices.iter().any(|q| q.bulge != 0.) {
continue;
}
let mut corners = [None; 4];
let mut order = [0usize; 4];
for (index, vertex) in p.vertices.iter().enumerate() {
let q = vertex.p;
let right = q.x > low.x + w / 2.;
let top = q.y > low.y + h / 2.;
let target = low + Vec2::new(if right { w } else { 0. }, if top { h } else { 0. });
if (q.x - target.x).abs() <= w * 0.002 && (q.y - target.y).abs() <= h * 0.002 {
order[index] = usize::from(right) + 2 * usize::from(top);
corners[order[index]] = Some(q);
}
}
if let [Some(bl), Some(br), Some(tl), Some(tr)] = corners
&& order.iter().zip(order.iter().cycle().skip(1)).all(|(a, b)| (a ^ b).count_ones() == 1)
&& (bl + (br - bl) + (tl - bl)).dist(tr) < w.min(h) * 1e-8
{
(origin, u, v) = (bl, br - bl, tl - bl);
guides.push(entity.handle);
}
}
let area = u.cross(v);
let coords = |p: Vec2| Vec2::new(p.cross(v) / area, u.cross(p) / area);
let world = |p: Vec2| u * p.x + v * p.y;
let mut families = Vec::new();
let mut add = |a: Vec2, b: Vec2, grid: bool| -> std::result::Result<(), &'static str> {
let (mut start, mut end) = (a - origin, b - origin);
let (s, e) = (coords(start), coords(end));
let inside = |q: Vec2| (-1e-8..=1.00000001).contains(&q.x) && (-1e-8..=1.00000001).contains(&q.y);
if !inside(s) || !inside(e) || start == end {
return Ok(());
}
let delta = e - s;
// Simple LINE geometry retains its original coordinates and short dash period.
let simple = if delta.x.abs() < 1e-14 {
Some((0, delta.y.signum() as i32))
} else {
(1..=128).find_map(|m| {
let m = m * delta.x.signum() as i32;
let n = f64::from(m) * delta.y / delta.x;
(n.abs() <= 128. && (n - n.round()).abs() < 1e-10).then_some((m, n.round() as i32))
})
};
let (mut m, mut n) = if let Some(dir) = simple.filter(|_| !grid) {
dir
} else {
// Shared vertices round identically, including on neighbouring tiles.
let snap = |p: Vec2| Vec2::new((p.x * 2048.).round(), (p.y * 2048.).round());
let (s, e) = (snap(s), snap(e));
if s == e {
return Err("A segment is too small for the tile capture precision.");
}
start = world(s / 2048.);
end = world(e / 2048.);
((e.x - s.x) as i32, (e.y - s.y) as i32)
};
if m < 0 || (m == 0 && n < 0) {
std::mem::swap(&mut start, &mut end);
(m, n) = (-m, -n);
}
let (mut gcd, mut k) = (m.abs(), n.abs());
while k != 0 {
(gcd, k) = (k, gcd % k);
}
if gcd != 0 {
families.push(captured_family(start, end, u, v, m / gcd, n / gcd));
}
Ok(())
};
for entity in entities() {
match &entity.kind {
EntityKind::Line(l) => add(l.a.xy(), l.b.xy(), false)?,
EntityKind::LwPolyline(p) if !guides.contains(&entity.handle) => {
for (i, vertex) in p.vertices.iter().enumerate() {
let next = p.vertices.get(i + 1).or_else(|| if p.closed { p.vertices.first() } else { None });
if let Some(next) = next
&& vertex.bulge == 0.
{
add(vertex.p, next.p, true)?;
}
}
}
_ => {}
}
}
if families.is_empty() {
return Err("No complete line segments in the selected tile.");
}
Ok(families)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capture_l_from_drawing_without_a_dialog() {
let mut s = Session::new();
s.execute("rectang", &json!({"p1":[30,40], "p2":[40,50]})).unwrap();
for (a, b) in [([32, 42], [35, 42]), ([32, 42], [32, 46]), ([50, 60], [57, 60])] {
s.execute("line", &json!({"points":[a,b]})).unwrap();
}
// An almost coincident hidden guide would shift the origin if it were used.
let guide = s.execute("rectang", &json!({"p1":[30.01,40.01],"p2":[40.01,50.01]})).unwrap();
s.execute("hideobjects", &json!({"handles":[guide["handle"]]})).unwrap();
s.execute("layer.new", &json!({"name":"Hidden detail","current":true})).unwrap();
s.execute("line", &json!({"points":[[33,43],[36,43]]})).unwrap();
let detail = s.doc().unwrap().model.iter().last().unwrap().handle.hex();
s.execute("layer.current", &json!({"name":"0"})).unwrap();
s.execute("layoff", &json!({"handles":[detail]})).unwrap();
let result = s.execute(COMMAND, &json!({"first":[40,50],"second":[30,40],"name":"HEADLESS_L"})).unwrap();
let dest = s.execute("rectang", &json!({"p1":[0,0],"p2":[30,20]})).unwrap();
let mut apply = result;
apply["handles"] = json!([dest["handle"]]);
s.execute("hatch", &apply).unwrap();
let drawing = s.doc().unwrap();
let hatch = drawing.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h) } else { None }).unwrap();
assert_eq!(hatch.pattern, "HEADLESS_L");
assert_eq!(hatch.pattern_lines.len(), 2, "frame and exterior segment excluded");
for (angle, ink) in [(0., 3.), (90., 4.)] {
let line = hatch.pattern_lines.iter().find(|l| (l.angle - angle).abs() < 1e-8).unwrap();
assert_eq!(line.origin, (2., 2.));
assert_eq!(line.dashes, vec![ink, ink - 10.]);
assert!((line.delta.1 - 10.).abs() < 1e-8);
}
}
}
+6 -16
View File
@@ -195,9 +195,9 @@ fn separate(s: &mut Session, handle: Handle) -> Result<Vec<Handle>> {
}
/// Pattern, scale and angle (degrees) from the parameters.
fn properties(h: &mut Hatch, p: &Value, local: Option<&[cadcraft_doc::library::PatternLine]>) {
fn properties(h: &mut Hatch, p: &Value) {
if let Some(v) = str_param(p, "pattern") {
set_pattern(h, v, local);
set_pattern(h, v);
}
if let Some(x) = p.get("scale").and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0) {
h.scale = x;
@@ -222,12 +222,11 @@ pub(crate) fn takes_pattern(h: &Hatch, name: &str) -> bool {
/// Give `h` the pattern called `name` (HATCHEDIT's and Properties' pattern edit); false, and
/// nothing changes, for a blank name or one the hatch can't take ([`takes_pattern`]).
pub(crate) fn set_pattern(h: &mut Hatch, name: &str, local: Option<&[cadcraft_doc::library::PatternLine]>) -> bool {
pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool {
let name = name.trim();
if name.is_empty() || (local.is_none() && !takes_pattern(h, name)) {
if name.is_empty() || !takes_pattern(h, name) {
return false;
}
let keep_lines = h.pattern.eq_ignore_ascii_case(name) && !h.pattern_lines.is_empty();
h.pattern = name.to_ascii_uppercase();
h.solid = h.pattern == "SOLID";
// A named pattern, SOLID included, replaces the gradient fill; the renderer draws the
@@ -238,10 +237,6 @@ pub(crate) fn set_pattern(h: &mut Hatch, name: &str, local: Option<&[cadcraft_do
// any other name is the hatch's own and keeps its definition.
if cadcraft_doc::library::pattern(&h.pattern).is_some() {
h.pattern_lines.clear();
} else if keep_lines {
return true;
} else if let Some(lines) = local {
h.pattern_lines = lines.to_vec();
} else if let Some(user) = super::patfile::user_pattern(&h.pattern) {
h.pattern_lines = user.lines;
}
@@ -484,9 +479,7 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
}
// Like the prompt: a pattern must be one CADCraft defines, SOLID, or the hatches' own (a
// pattern read from a file keeps its definition).
let local = str_param(p, "pattern").and_then(|n| super::drawing_lines(s.doc().ok()?, n.trim()));
if let Some(up) = str_param(p, "pattern").map(|v| v.trim().to_ascii_uppercase()).filter(|v| !v.is_empty())
&& local.is_none()
&& !defined_pattern(&up)
{
let d = s.doc()?;
@@ -514,7 +507,7 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
notes.push(format!("Hatch {}: {missing} new boundary loop(s) could not be linked; it is now non-associative.", handle.hex()));
}
}
properties(&mut h, p, local.as_deref());
properties(&mut h, p);
if let Some(g) = &grad {
g.apply(&mut h);
}
@@ -727,10 +720,7 @@ impl Interactive for HatchEditM {
(Ask::Pattern, _) => {
if let Some(t) = text.filter(|t| !t.is_empty()) {
let up = t.to_ascii_uppercase();
if cadcraft_doc::library::pattern(&up).is_none()
&& super::patfile::user_pattern(&up).is_none()
&& super::drawing_lines(s.doc()?, &up).is_none()
{
if cadcraft_doc::library::pattern(&up).is_none() && super::patfile::user_pattern(&up).is_none() {
s.echo(format!("Unknown pattern {up}."));
return Ok(Step::Continue);
}
+5 -54
View File
@@ -9,7 +9,7 @@
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
use cadcraft_doc::library::files::{UserPattern, parse_pat};
use cadcraft_doc::library::{PatternLine, is_reserved_pattern_name, standard_patterns};
use cadcraft_doc::library::{PatternLine, pattern, standard_patterns};
use serde_json::{Value, json};
use super::super::helpers::support_text;
@@ -38,7 +38,7 @@ pub(crate) fn user_pattern_name(name: &str) -> Option<String> {
/// The line families a new hatch of pattern `name` carries: a user pattern's, else none (the
/// library's patterns are drawn and saved from the library).
pub(crate) fn lines_for(name: &str) -> Vec<PatternLine> {
if is_reserved_pattern_name(name) {
if pattern(name).is_some() {
return Vec::new();
}
user_pattern(name).map(|p| p.lines).unwrap_or_default()
@@ -70,54 +70,6 @@ pub fn pattern_choices() -> Vec<PatternChoice> {
v
}
fn embedded(d: &cadcraft_doc::Drawing) -> impl Iterator<Item = &cadcraft_doc::Hatch> {
let stores = std::iter::once(&d.model)
.chain(d.layouts.iter().map(|l| &l.entities))
.chain(d.blocks.values().filter(|b| b.xref_path.is_none()).map(|b| &b.entities));
stores.flat_map(|s| s.iter()).filter_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Hatch(h) if !h.pattern_lines.is_empty() => Some(h),
_ => None,
})
}
pub(crate) fn drawing_lines(d: &cadcraft_doc::Drawing, name: &str) -> Option<Vec<PatternLine>> {
if is_reserved_pattern_name(name) {
return None;
}
embedded(d).find(|h| h.pattern.eq_ignore_ascii_case(name)).map(|h| h.pattern_lines.clone())
}
/// An embedded definition takes precedence over the session library in its own drawing.
pub fn pattern_choices_in(d: &cadcraft_doc::Drawing) -> Vec<PatternChoice> {
let mut choices = pattern_choices();
let mut seen = std::collections::HashSet::new();
for h in embedded(d) {
if !seen.insert(h.pattern.to_ascii_uppercase()) || is_reserved_pattern_name(&h.pattern) {
continue;
}
if let Some(c) = choices.iter_mut().find(|c| c.name.eq_ignore_ascii_case(&h.pattern)) {
c.lines.clone_from(&h.pattern_lines);
} else {
choices.push(PatternChoice { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
}
}
choices
}
/// Make embedded custom definitions available when opening the hatch manager in an older drawing.
pub fn register_drawing_patterns(d: &cadcraft_doc::Drawing) {
let mut user = store();
let mut known: std::collections::HashSet<_> = user.iter().map(|p| p.name.to_ascii_uppercase()).collect();
for h in embedded(d) {
if user.len() >= MAX_USER_PATTERNS {
break;
}
if !h.pattern_lines.is_empty() && known.insert(h.pattern.to_ascii_uppercase()) && !is_reserved_pattern_name(&h.pattern) {
user.push(UserPattern { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
}
}
}
/// Add the patterns of a `.pat` file's text (a pattern loaded before under the same name is
/// replaced). Returns the names added and the file's problems.
pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
@@ -126,7 +78,7 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
let mut added = Vec::new();
let mut user = store();
for p in parsed.items {
if is_reserved_pattern_name(&p.name) {
if pattern(&p.name).is_some() {
warnings.push(format!("{} is a built-in pattern; the built-in definition is kept", p.name));
continue;
}
@@ -145,15 +97,14 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
}
/// Load the pattern file a HATCH call names (`patternFile` path or `patternText` contents).
pub(super) fn load_param(p: &Value) -> Result<Vec<String>> {
pub(super) fn load_param(p: &Value) -> Result<()> {
if let Some((text, source)) = support_text("hatch", p, "patternFile", "patternText")? {
let (added, warnings) = load(&text);
if added.is_empty() {
return Err(bad("hatch", format!("no hatch pattern could be read from {source}: {}", warnings.join("; "))));
}
return Ok(added);
}
Ok(Vec::new())
Ok(())
}
/// A `.pat` file typed at HATCH's pattern prompt: load it and return the pattern to use (the
+2 -21
View File
@@ -14,7 +14,7 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(crate) const MAX_PICKS: usize = 1000;
/// The first prompt's keywords: what to pick.
const MODES: [&str; 5] = ["Points", "Objects", "oRigin", "Hatch", "TileRect"];
const MODES: [&str; 4] = ["Points", "Objects", "oRigin", "Hatch"];
/// What HATCHPICK picks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -22,8 +22,6 @@ pub enum PickMode {
/// Internal points, each inside a closed boundary.
#[default]
Points,
/// Two opposite corners of a rectangular custom-pattern tile.
TileRect,
/// Closed boundary objects.
Objects,
/// One point: the pattern origin.
@@ -46,7 +44,6 @@ pub struct HatchPicks {
fn mode_named(t: &str) -> Option<PickMode> {
Some(match t.trim().to_ascii_lowercase().as_str() {
"points" | "p" => PickMode::Points,
"tilerect" | "tile" => PickMode::TileRect,
"objects" | "o" => PickMode::Objects,
"origin" | "r" => PickMode::Origin,
"hatch" | "h" => PickMode::Hatch,
@@ -137,10 +134,6 @@ impl Interactive for HatchPickM {
match self.mode {
None => Prompt::new("Enter what to pick", Accept::TEXT).kw(&MODES),
Some(PickMode::Points) => Prompt::new("Pick internal point", Accept::POINT).kw(&["Undo"]),
Some(PickMode::TileRect) => {
Prompt::new(if self.picks.is_empty() { "Pick first corner of tile" } else { "Pick opposite corner of tile" }, Accept::POINT)
.kw(&["Undo"])
}
Some(PickMode::Objects) => Prompt::new("Select objects", Accept::SELECT).kw(&["Undo"]),
Some(PickMode::Origin) => Prompt::new("Specify the pattern origin", Accept::POINT),
Some(PickMode::Hatch) => Prompt::new("Select hatch object", Accept::SELECT),
@@ -157,13 +150,12 @@ impl Interactive for HatchPickM {
};
match (mode, i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(PickMode::Points | PickMode::TileRect | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
(PickMode::Points | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
if self.picks.pop().is_none() {
s.echo("Nothing to undo.");
}
Ok(Step::Continue)
}
(PickMode::TileRect, Input::Enter) => Ok(Step::Continue),
(PickMode::Points | PickMode::Objects, Input::Enter) => {
self.keep(s, mode);
Ok(Step::Done)
@@ -182,17 +174,6 @@ impl Interactive for HatchPickM {
}
Ok(Step::Continue)
}
(PickMode::TileRect, Input::Point(q)) => {
if self.count() < 2 {
self.picks.push(Pick::Point(q, Vec::new()));
}
if self.count() >= 2 {
self.keep(s, mode);
Ok(Step::Done)
} else {
Ok(Step::Continue)
}
}
(PickMode::Objects, Input::Pick(hs)) => {
let room = MAX_PICKS.saturating_sub(self.count());
let closed: Vec<Handle> = {
+2 -5
View File
@@ -204,7 +204,6 @@ fn set_override(dm: &mut cadcraft_doc::Dimension, field: &'static str, v: Value)
/// A `properties.set` call, checked before any object changes: the values every object takes,
/// and what the edits need to know beforehand.
struct Call<'a> {
hatch_lines: Option<Vec<cadcraft_doc::library::PatternLine>>,
p: &'a Value,
color: Option<Color>,
transparency: Option<Transparency>,
@@ -352,10 +351,8 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
let hatch_lines = str_param(p, "pattern").and_then(|n| crate::cmd::hatch::drawing_lines(d, n.trim()));
// A pattern must be one each hatch can take, as HATCHEDIT refuses others.
if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty())
&& hatch_lines.is_none()
&& hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v)))
{
return Err(bad("properties.set", format!("unknown pattern {}", v.trim().to_ascii_uppercase())));
@@ -366,7 +363,7 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
let prep = Prepared::new(d, p, &hs);
let anno_scale = d.current_anno_scale();
let c = Call { hatch_lines, p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
let c = Call { p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
// A failed call changes nothing (a command's error doesn't undo what it did), so the drawing
// is taken for writing, and the layer made, only after every check.
let d = s.doc_mut()?;
@@ -808,7 +805,7 @@ fn dimension_posts(dm: &mut Dimension, c: &Call<'_>, used: &mut Used<'_>) {
fn hatch(ha: &mut Hatch, c: &Call<'_>, used: &mut Used<'_>) {
// HATCHEDIT's pattern edit (a blank name changes nothing, so it's ignored).
if let Some(v) = str_param(c.p, "pattern")
&& crate::cmd::hatch::set_pattern(ha, v, c.hatch_lines.as_deref())
&& crate::cmd::hatch::set_pattern(ha, v)
{
used.insert("pattern");
}
@@ -241,7 +241,6 @@ pub const NO_FILES: &[&str] = &[
"gradient",
"boundary",
"region",
"hatch.capture",
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
+1 -1
View File
@@ -57,7 +57,7 @@ pub use cadcraft_geom as geom;
pub use cadcraft_render as render;
pub use cmd::blocks::WblockPicks;
pub use cmd::blocks::attedit::{AttributeRow, attributes};
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices, pattern_choices_in, register_drawing_patterns};
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
+1 -4
View File
@@ -35,8 +35,5 @@ craft-pdf = { workspace = true, features = ["read"] }
# Inspect DWG output only where craft-dwg builds its native bridge. An unconditional
# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526).
# The storytold/acadrust fork at tag `storytold/v0.6.6` (upstream v0.6.6), the source craft-dwg moves
# to in storytold/craft-libs#4762; until craft-libs is repinned, craft-dwg still takes the identical
# crates.io 0.6.6.
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies]
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "5d5c482b3fcb3dc77e8281474461760f32959436" }
acadrust = "0.6.6"
+9 -46
View File
@@ -553,29 +553,15 @@ const MAX_SWATCH_WORK: u64 = 2_000_000;
/// A preview of a pattern for a pattern picker: the runs of its line families `lines` inside the
/// `side` × `side` square with a corner at the origin, at a scale that shows a few repeats of the
/// pattern. For sparse, staggered tile edges the area per mark sets the preview scale. Empty for a pattern
/// pattern (each family's line spacing or dash repeat, whichever is longer). Empty for a pattern
/// with no lines (SOLID).
pub fn pattern_swatch(lines: &[PatternLine], side: f64) -> Vec<Vec<Vec2>> {
let estimate = |sparse: bool| {
lines
.iter()
.map(|l| {
let spacing = l.delta.1.abs();
let period = l.dashes.iter().map(|d| d.abs()).sum::<f64>();
if sparse && l.delta.0 != 0. && matches!(l.dashes.as_slice(), [ink, gap] if *ink > 0. && -*gap > 32. * spacing) {
(period * spacing).sqrt()
} else {
spacing.max(period)
}
})
.filter(|r| r.is_finite())
.fold(0.0, f64::max)
};
let repeat = estimate(true);
let repeat =
lines.iter().map(|l| l.delta.1.abs().max(l.dashes.iter().map(|d| d.abs()).sum::<f64>())).filter(|r| r.is_finite()).fold(0.0, f64::max);
if !side.is_finite() || side <= 0.0 || repeat < 1e-9 {
return Vec::new();
}
let mut h = Hatch {
let h = Hatch {
pattern: String::new(),
solid: false,
loops: Vec::new(),
@@ -592,16 +578,7 @@ pub fn pattern_swatch(lines: &[PatternLine], side: f64) -> Vec<Vec<Vec2>> {
let square = vec![Vec2::new(0.0, 0.0), Vec2::new(side, 0.0), Vec2::new(side, side), Vec2::new(0.0, side)];
// The generator stops at the swatch's own limits, so a compact pattern is never made in full
// (about a million runs) to keep a few thousand.
let loops = [square];
let render = |h: &Hatch| pattern_lines_within(&Drawing::default(), h, &loops, 0.0, None, None, MAX_SWATCH_RUNS, MAX_SWATCH_WORK);
let mut runs = render(&h);
if runs.is_empty() {
let full = estimate(false);
if full > repeat {
h.scale = side / (SWATCH_REPEATS * full);
runs = render(&h);
}
}
let mut runs = pattern_lines_within(&Drawing::default(), &h, &[square], 0.0, None, None, MAX_SWATCH_RUNS, MAX_SWATCH_WORK);
runs.truncate(MAX_SWATCH_RUNS);
runs.shrink_to_fit();
runs
@@ -667,18 +644,14 @@ impl Family<'_> {
let k0 = (lo.y / self.spacing).floor() as i64;
let k1 = (hi.y / self.spacing).ceil() as i64;
let max_lines = if view.is_some() { MAX_VIEW_FAMILY_LINES } else { MAX_FAMILY_LINES };
let many_rows = k1.saturating_sub(k0) > max_lines;
if k1.saturating_sub(k0) > max_lines {
return;
}
let pat_len: f64 = self.dashes.iter().map(|d| d.abs()).sum();
// Level of detail: a whole repeat under two pixels reads as a continuous line (when the
// family draws anything at all).
let draws = self.dashes.iter().any(|d| *d >= 0.0);
let solid_line = self.dashes.is_empty() || pat_len < 1e-12 || (px > 0.0 && pat_len < 2.0 * px && draws);
// Captured tile edges can have many tightly spaced rows, each with a long empty gap.
// Reject empty rows by dash phase before walking or sorting any boundary edges.
let sparse = matches!(self.dashes, [ink, gap] if *ink >= 0. && -*gap > hi.x - lo.x) && !solid_line;
if many_rows && (!sparse || k1.abs_diff(k0) >= *work) {
return;
}
// Each scanline visits every boundary edge and sorts the intersections. Charge both the
// traversal and an n*ceil(log2(n)) upper bound for sorting, scaled to one unit per eight
// operations, whether or not any dash is made.
@@ -689,20 +662,10 @@ impl Family<'_> {
if out.len() >= self.max_runs || crossings_charge > *work || is_set(cancel) {
return;
}
let offset = shift_per_line * k as f64;
if many_rows {
*work -= 1;
let phase = (lo.x - offset).rem_euclid(pat_len);
if phase > self.dashes[0] && pat_len - phase > hi.x - lo.x {
continue;
}
if crossings_charge > *work {
return;
}
}
*work -= crossings_charge;
let y = k as f64 * self.spacing;
let xs = crossings(&local, y);
let offset = shift_per_line * k as f64;
for span in xs.chunks(2) {
let [x0, x1] = span else { continue };
let (x0, x1) = match span_cut {
+4 -4
View File
@@ -84,7 +84,7 @@ enum Tab {
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum View {
enum View {
ExtraLarge,
Large,
#[default]
@@ -95,10 +95,10 @@ pub(crate) enum View {
}
impl View {
pub(crate) const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List];
const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List];
/// The name shown on the view's button.
pub(crate) fn label(self) -> &'static str {
fn label(self) -> &'static str {
match self {
View::ExtraLarge => crate::tl!("Extra Large Icons"),
View::Large => crate::tl!("Large Icons"),
@@ -110,7 +110,7 @@ impl View {
}
/// The side of a gallery tile, for the icon views.
pub(crate) fn tile(self) -> Option<f32> {
fn tile(self) -> Option<f32> {
match self {
View::ExtraLarge => Some(150.0),
View::Large => Some(104.0),
+12 -220
View File
@@ -46,10 +46,7 @@ pub struct Fill {
/// The dialog while open (and while a pick it started runs).
#[derive(Clone, Debug, PartialEq)]
pub struct HatchDlgState {
choices: Vec<cadcraft_engine::PatternChoice>,
pub fill: Fill,
custom: Option<CustomPattern>,
saved_source: Option<String>,
/// The fill as the dialog opened: edit mode sends only what changed.
pub opened: Fill,
/// The hatches being edited; empty in create mode.
@@ -64,8 +61,6 @@ pub struct HatchDlgState {
pub remove_loops: Vec<usize>,
/// A HATCHPICK the dialog started that hasn't ended yet.
pub picking: Option<PickMode>,
/// The next point pick defines a repeating tile for the custom pattern.
capture_tile: bool,
/// The last command error, shown in the dialog.
pub error: Option<String>,
/// The drawing the dialog belongs to (`DocState::uid`).
@@ -75,79 +70,9 @@ pub struct HatchDlgState {
pub space: Space,
}
#[derive(Clone, Debug, PartialEq)]
struct CustomPattern {
name: String,
families: Vec<PatternFamily>,
}
#[derive(Clone, Debug, PartialEq)]
struct PatternFamily {
origin: (f64, f64),
shift: f64,
angle: f64,
spacing: f64,
dashes: String,
}
impl Default for PatternFamily {
fn default() -> Self {
Self { origin: (0., 0.), shift: 0., angle: 45.0, spacing: 5.0, dashes: String::new() }
}
}
fn available_name(base: &str) -> String {
let choices = cadcraft_engine::pattern_choices();
let used = |name: &str| choices.iter().any(|p| p.name.eq_ignore_ascii_case(name));
let mut name = base.to_owned();
let mut suffix = 2;
while used(&name) {
name = format!("{base}_{suffix}");
suffix += 1;
}
name
}
impl Default for CustomPattern {
fn default() -> Self {
Self { name: available_name("MY_PATTERN"), families: vec![PatternFamily::default()] }
}
}
impl CustomPattern {
fn encode(&self) -> Option<(String, String)> {
let name = self.name.trim().to_ascii_uppercase();
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') || cadcraft_doc::library::is_reserved_pattern_name(&name)
{
return None;
}
let mut text = format!("*{name}, Custom pattern\n");
for family in &self.families {
if !family.angle.is_finite() || !family.spacing.is_finite() || family.spacing <= 0.0 {
return None;
}
text.push_str(&format!("{},{},{},{},{}", family.angle, family.origin.0, family.origin.1, family.shift, family.spacing));
if !family.dashes.trim().is_empty() {
let dashes: Vec<_> =
family.dashes.split_whitespace().map(|value| value.parse::<f64>().ok().filter(|v| v.is_finite())).collect::<Option<_>>()?;
if dashes.iter().all(|d| *d == 0.0) {
return None;
}
for dash in dashes {
text.push_str(&format!(",{dash}"));
}
}
text.push('\n');
}
let parsed = cadcraft_doc::library::files::parse_pat(&text);
(parsed.items.len() == 1 && parsed.warnings.is_empty()).then_some((name, text))
}
}
/// Create mode, from the drawing's HATCH settings (HPNAME, HPSCALE, HPANG, HPASSOC, HPSEPARATE,
/// HPORIGINMODE, HPISLANDDETECTION); values a file got wrong fall back to the defaults.
pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState {
cadcraft_engine::register_drawing_patterns(d);
let h = &d.header;
let scale = Some(h.f64("HPSCALE", 1.0)).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0);
let angle = Some(h.f64("HPANG", 0.0).to_degrees()).filter(|v| v.is_finite()).unwrap_or(0.0);
@@ -171,11 +96,8 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState {
style: u8::try_from(h.i64("HPISLANDDETECTION", 0).clamp(0, 2)).unwrap_or(0),
};
HatchDlgState {
choices: cadcraft_engine::pattern_choices_in(d),
opened: fill.clone(),
fill,
custom: None,
saved_source: None,
edit: Vec::new(),
separate: h.i64("HPSEPARATE", 0) != 0,
points: Vec::new(),
@@ -183,7 +105,6 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState {
loop_outer: Vec::new(),
remove_loops: Vec::new(),
picking: None,
capture_tile: false,
error: None,
uid,
space: Space::Model,
@@ -268,17 +189,7 @@ pub fn ok_call(st: &HatchDlgState) -> Option<(&'static str, Value)> {
p.insert("color2".into(), json!(f.color2.name()));
p.insert("centered".into(), json!(f.centered));
} else {
let pattern = if let Some(custom) = &st.custom {
let (name, text) = custom.encode()?;
p.insert("patternText".into(), json!(text));
name
} else {
if let Some(text) = &st.saved_source {
p.insert("patternText".into(), json!(text));
}
f.pattern.clone()
};
p.insert("pattern".into(), json!(pattern));
p.insert("pattern".into(), json!(f.pattern));
p.insert("scale".into(), json!(f.scale));
}
p.insert("angle".into(), json!(f.angle));
@@ -349,7 +260,7 @@ pub fn ok_call(st: &HatchDlgState) -> Option<(&'static str, Value)> {
/// Take a HATCHPICK's picks into the dialog (Hatch picks are taken by `resume`).
pub fn merge_picks(st: &mut HatchDlgState, picks: HatchPicks) {
match picks.mode {
PickMode::Points | PickMode::TileRect | PickMode::Objects => {
PickMode::Points | PickMode::Objects => {
st.points.extend(picks.points.iter().map(|q| [q.x, q.y]));
for h in picks.handles {
if !st.handles.contains(&h) {
@@ -413,7 +324,6 @@ pub fn start_pick(app: &mut CadApp, mode: PickMode) {
app.start("hatchpick");
let kw = match mode {
PickMode::Points => "Points",
PickMode::TileRect => "TileRect",
PickMode::Objects => "Objects",
PickMode::Origin => "oRigin",
PickMode::Hatch => "Hatch",
@@ -425,27 +335,6 @@ pub fn start_pick(app: &mut CadApp, mode: PickMode) {
}
}
/// Convert the engine's PAT result into editable fields in the dialog.
fn capture_draft(app: &mut CadApp, a: cadcraft_geom::Vec2, b: cadcraft_geom::Vec2) -> Result<CustomPattern, String> {
let params = json!({"first":[a.x,a.y], "second":[b.x,b.y], "name":available_name("CAPTURED_TILE")});
let result = app.run("hatch.capture", params)?;
let text = result["patternText"].as_str().ok_or_else(|| crate::tl!("Missing captured PAT definition").to_owned())?;
let parsed = cadcraft_doc::library::files::parse_pat(text);
let pattern = parsed.items.into_iter().next().ok_or_else(|| crate::tl!("Invalid captured PAT definition").to_owned())?;
let families = pattern
.lines
.into_iter()
.map(|line| PatternFamily {
origin: line.origin,
shift: line.delta.0,
angle: line.angle,
spacing: line.delta.1,
dashes: line.dashes.iter().map(ToString::to_string).collect::<Vec<_>>().join(" "),
})
.collect();
Ok(CustomPattern { name: pattern.name, families })
}
/// Every frame: once a HATCHPICK the dialog started has ended, take its picks and bring the
/// dialog back (unchanged when the pick was cancelled). A different drawing by then drops the
/// dialog and its picks; a Hatch pick that found none closes it.
@@ -467,17 +356,7 @@ pub fn resume(app: &mut CadApp) {
next.space = st.space.clone();
st = next;
} else if let Some(p) = picks {
if st.capture_tile && mode == PickMode::TileRect {
st.capture_tile = false;
if let [a, b] = p.points.as_slice() {
match capture_draft(app, *a, *b) {
Ok(pattern) => st.custom = Some(pattern),
Err(message) => st.error = Some(message),
}
}
} else {
merge_picks(&mut st, p);
}
merge_picks(&mut st, p);
}
app.hatch_dlg = Some(st);
app.ui.dialog = Some("hatch".into());
@@ -491,12 +370,8 @@ pub fn ok(app: &mut CadApp) -> bool {
app.hatch_dlg = None;
return true;
};
let authored = p["pattern"].as_str().zip(p["patternText"].as_str()).map(|(n, t)| (n.to_owned(), t.to_owned()));
match app.run(cmd, p) {
Ok(_) => {
if let Some((name, text)) = authored {
app.ui.hatch_patterns.insert(name, text);
}
app.hatch_dlg = None;
true
}
@@ -509,31 +384,7 @@ pub fn ok(app: &mut CadApp) -> bool {
}
}
/// Register a finished draft even when the user has not picked a surface to fill.
fn save_pattern(app: &mut CadApp) {
let Some((name, text)) = app.hatch_dlg.as_ref().and_then(|s| s.custom.as_ref()).and_then(CustomPattern::encode) else { return };
let result = app.run("hatch.patterns", json!({"text": text}));
let Some(st) = app.hatch_dlg.as_mut() else { return };
match result {
Ok(value) if value["added"].as_array().is_some_and(|a| a.iter().any(|n| n.as_str() == Some(&name))) => {
st.saved_source = Some(text.clone());
app.ui.hatch_patterns.insert(name.clone(), text);
st.fill.pattern = name;
if let Ok(d) = app.session.doc() {
st.choices = cadcraft_engine::pattern_choices_in(d);
}
st.custom = None;
st.error = None;
}
Ok(value) => {
st.error = Some(value["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>().join("\n"));
}
Err(error) => st.error = Some(error),
}
}
enum Action {
SavePattern,
None,
Ok,
Cancel,
@@ -578,16 +429,12 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
return;
};
let title = if st.edit.is_empty() { crate::tl!("Hatch and Gradient") } else { crate::tl!("Hatch Edit") };
// Esc cancels, as the Cancel button does.
let mut action = if crate::framework::escape_pressed(ctx) { Action::Cancel } else { Action::None };
let mut action = Action::None;
egui::Window::new(title).id(egui::Id::unique("hatch_dialog")).open(open).collapsible(false).resizable(false).show(ctx, |ui| {
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(340.0);
fill_ui(ui, &mut st.fill, &st.choices, &mut st.saved_source, &mut action);
if st.edit.is_empty() && !st.fill.gradient {
custom_pattern_ui(ui, &mut st.custom, &mut st.capture_tile, &mut action);
}
fill_ui(ui, &mut st.fill, &mut action);
});
// Space, not a vertical separator: a separator takes the height available, and the
// window grew by it every frame until the buttons left the screen.
@@ -602,8 +449,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
}
ui.separator();
ui.horizontal(|ui| {
let valid = st.fill.gradient || st.custom.as_ref().is_none_or(|draft| draft.encode().is_some());
let ready = valid && (!st.edit.is_empty() || !(st.points.is_empty() && st.handles.is_empty()));
let ready = !st.edit.is_empty() || !(st.points.is_empty() && st.handles.is_empty());
if ui.add_enabled(ready, egui::Button::new(crate::tl!("OK"))).clicked() {
action = Action::Ok;
}
@@ -623,7 +469,6 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
app.hatch_dlg = None;
*open = false;
}
Action::SavePattern => save_pattern(app),
Action::Pick(mode) => start_pick(app, mode),
Action::None => {
if !*open {
@@ -633,62 +478,8 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
}
}
fn custom_pattern_ui(ui: &mut egui::Ui, custom: &mut Option<CustomPattern>, capture_tile: &mut bool, action: &mut Action) {
let mut enabled = custom.is_some();
if ui.checkbox(&mut enabled, crate::tl!("Create a custom hatch pattern")).changed() {
*custom = enabled.then(CustomPattern::default);
}
let Some(draft) = custom else { return };
if ui
.button(crate::tl!("Capture square tile from drawing"))
.on_hover_text(crate::tl!("Pick two opposite corners to define the repeating tile"))
.clicked()
{
// The two corners become the horizontal and vertical repeat steps.
// The normal boundary picker remains available separately.
*capture_tile = true;
*action = Action::Pick(PickMode::TileRect);
}
let name = ui.label(crate::tl!("Pattern name"));
ui.add(egui::TextEdit::singleline(&mut draft.name).char_limit(31)).labelled_by(name.id);
ui.label(crate::tl!("Use spaces between dashes: positive draws, negative skips, zero marks a dot."));
let mut remove = None;
egui::ScrollArea::vertical().id_salt("custom-hatch-families").max_height(125.0).show(ui, |ui| {
for (index, family) in draft.families.iter_mut().enumerate() {
ui.push_id(index, |ui| {
ui.horizontal(|ui| {
let angle = ui.label(crate::tl!("Angle"));
ui.add(egui::DragValue::new(&mut family.angle).suffix("°")).labelled_by(angle.id);
let spacing = ui.label(crate::tl!("Spacing"));
ui.add(egui::DragValue::new(&mut family.spacing).range(0.0001..=1e6).clamp_existing_to_range(false)).labelled_by(spacing.id);
let dashes = ui.label(crate::tl!("Dashes"));
ui.add(egui::TextEdit::singleline(&mut family.dashes).char_limit(120).desired_width(70.0)).labelled_by(dashes.id);
if ui.small_button("×").on_hover_text(crate::tl!("Remove")).clicked() {
remove = Some(index);
}
})
});
}
});
if let Some(index) = remove
&& draft.families.len() > 1
{
draft.families.remove(index);
}
if ui.add_enabled(draft.families.len() < 16, egui::Button::new(crate::tl!("Add line family"))).clicked() {
draft.families.push(PatternFamily::default());
}
let valid = draft.encode().is_some();
if ui.add_enabled(valid, egui::Button::new(crate::tl!("Save pattern"))).clicked() {
*action = Action::SavePattern;
}
if !valid {
ui.colored_label(Tokens::get().warn, crate::tl!("Check the pattern name, spacing and dash values."));
}
}
/// Pattern/gradient fill selector and its controls; an origin pick is reported through `action`.
fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, choices: &[cadcraft_engine::PatternChoice], saved_source: &mut Option<String>, action: &mut Action) {
fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) {
ui.horizontal(|ui| {
ui.selectable_value(&mut f.gradient, false, crate::tl!("Pattern"));
ui.selectable_value(&mut f.gradient, true, crate::tl!("Gradient"));
@@ -724,10 +515,11 @@ fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, choices: &[cadcraft_engine::PatternC
ui.end_row();
});
} else {
if let Some(name) = crate::palettes::patterns::manager(ui, &f.pattern, choices) {
*saved_source = None;
f.pattern = name;
}
egui::ScrollArea::vertical().id_salt("hatch_swatches").max_height(220.0).show(ui, |ui| {
if let Some(name) = crate::palettes::patterns::grid(ui, &f.pattern, "") {
f.pattern = name;
}
});
egui::Grid::new("hatch_pattern").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| {
ui.label(crate::tl!("Angle"));
ui.add(egui::DragValue::new(&mut f.angle).speed(1.0).range(-360.0..=360.0).clamp_existing_to_range(false).suffix("°"));
-377
View File
@@ -19,13 +19,6 @@ fn app_with_rect() -> (CadApp, Handle) {
(CadApp::new(s, Services::default()), r)
}
#[test]
fn capture_errors_use_the_dialog_translation_keys() {
let mut app = CadApp::new(Session::new(), Services::default());
assert_eq!(capture_draft(&mut app, Vec2::ZERO, Vec2::ZERO).unwrap_err(), crate::tl!("Pick two opposite corners for the tile"));
assert_eq!(capture_draft(&mut app, Vec2::ZERO, Vec2::new(10., 10.)).unwrap_err(), crate::tl!("No complete line segments in the selected tile."));
}
#[test]
fn pick_points_hides_the_dialog_and_brings_it_back_with_the_points() {
let (mut app, _) = app_with_rect();
@@ -478,373 +471,3 @@ fn edit_mode_leaves_out_a_selected_hatch_the_viewport_does_not_draw() {
assert_eq!(app.hatch_dlg.as_ref().map(|d| d.edit.clone()), Some(Vec::new()), "a hatch the viewport does not draw must not be edited");
assert!(app.session.running.is_some(), "HATCHPICK must be asking for a hatch");
}
#[test]
fn captured_tile_keeps_l_segments_and_excludes_outside_line() {
use cadcraft_doc::{Common, Line};
use cadcraft_engine::geom::Vec3;
let mut app = CadApp::new(Session::new(), Services::default());
for (a, b) in [([32., 42.], [32., 46.]), ([35., 42.], [32., 42.]), ([50., 60.], [57., 60.])] {
app.session
.doc_mut()
.unwrap()
.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.), b: Vec3::new(b[0], b[1], 0.) }))
.unwrap();
}
open_create(&mut app, false);
app.hatch_dlg.as_mut().unwrap().capture_tile = true;
start_pick(&mut app, PickMode::TileRect);
for point in [Vec2::new(40., 50.), Vec2::new(30., 40.)] {
app.session.input(cadcraft_engine::Input::Point(point)).unwrap();
}
resume(&mut app);
let (_, text) = app.hatch_dlg.as_ref().unwrap().custom.as_ref().unwrap().encode().unwrap();
assert!(text.contains(",3,-7"), "horizontal L segment must repeat every 10 units: {text}");
assert!(text.contains(",4,-6"), "vertical L segment must repeat every 10 units: {text}");
assert!(!text.contains(",7,-3"), "outside segment must be excluded");
let rect = app.session.execute("rectang", &json!({"p1":[0,0],"p2":[30,20]})).unwrap();
app.hatch_dlg.as_mut().unwrap().handles.push(Handle::parse_hex(rect["handle"].as_str().unwrap()).unwrap());
assert!(ok(&mut app));
let d = app.session.doc().unwrap();
let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(d).as_bytes()).unwrap();
for drawing in [d, &reopened] {
let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let list = cadcraft_render::build(drawing, &Space::Model, &Default::default());
let segments: Vec<_> = list
.prims
.iter()
.filter(|p| p.handle == handle && p.kind == cadcraft_render::Kind::Polyline)
.map(|p| &list.verts[p.start as usize..(p.start + p.len) as usize])
.collect();
assert_eq!(segments.len(), 12, "two segments in each of six tiles: {segments:?}");
for x in [2., 12., 22.] {
for y in [2., 12.] {
let corner = Vec2::new(x, y);
for tip in [corner + Vec2::new(3., 0.), corner + Vec2::new(0., 4.)] {
assert!(
segments.iter().any(|s| s.len() == 2
&& ((s[0].dist(corner) < 1e-7 && s[1].dist(tip) < 1e-7) || (s[1].dist(corner) < 1e-7 && s[0].dist(tip) < 1e-7))),
"missing {corner:?} to {tip:?}: {segments:?}"
);
}
}
}
}
}
#[test]
fn tile_corners_do_not_require_closed_boundaries() {
let mut app = CadApp::new(Session::new(), Services::default());
open_create(&mut app, false);
start_pick(&mut app, PickMode::TileRect);
app.session.input(cadcraft_engine::Input::Enter).unwrap();
assert!(app.session.prompt_text().contains("first corner"));
app.session.input(cadcraft_engine::Input::Point(Vec2::new(20.0, 30.0))).unwrap();
app.session.input(cadcraft_engine::Input::Enter).unwrap();
assert!(app.session.prompt_text().contains("opposite corner"));
app.session.cmdline("Undo").unwrap();
assert!(app.session.prompt_text().contains("first corner"));
app.session.input(cadcraft_engine::Input::Point(Vec2::new(20.0, 30.0))).unwrap();
app.session.input(cadcraft_engine::Input::Point(Vec2::new(40.0, 50.0))).unwrap();
assert!(app.session.running.is_none());
assert_eq!(app.session.hatch_picks.as_ref().unwrap().points.len(), 2);
}
#[test]
fn a_custom_hatch_created_in_the_dialog_stores_its_line_families() {
let (mut app, boundary) = app_with_rect();
open_create(&mut app, false);
let state = app.hatch_dlg.as_mut().unwrap();
state.handles.push(boundary);
state.custom = Some(CustomPattern {
name: "DIEVART_TEST_HATCH".into(),
families: vec![PatternFamily::default(), PatternFamily { angle: 90.0, spacing: 3.0, dashes: "2 -1".into(), ..Default::default() }],
});
assert!(ok(&mut app));
let drawing = app.session.doc().unwrap();
let hatch = drawing.model.iter().find_map(|e| if let EntityKind::Hatch(hatch) = &e.kind { Some(hatch) } else { None }).unwrap();
assert_eq!(hatch.pattern, "DIEVART_TEST_HATCH");
assert_eq!(hatch.pattern_lines.len(), 2);
let expected = hatch.pattern_lines.clone();
let prefs = app.prefs_json();
let mut restarted = CadApp::new(Session::new(), Services::default());
// Replace the in-memory definition so success requires reading the saved families.
restarted.session.execute("hatch.patterns", &json!({"text":"*DIEVART_TEST_HATCH, temporary\n0,0,0,0,7\n"})).unwrap();
restarted.load_prefs(&prefs);
let restored = cadcraft_engine::pattern_choices().into_iter().find(|p| p.name == hatch.pattern).unwrap();
assert_eq!(restored.lines, expected);
assert_ne!(available_name(&hatch.pattern), hatch.pattern);
assert_eq!(restarted.ui.hatch_patterns, app.ui.hatch_patterns);
// An older DXF has an embedded definition, even on a machine without the author's preferences.
let dxf = cadcraft_io::write_dxf(drawing).replace("DIEVART_TEST_HATCH", "OLDER_EMBEDDED_TEST");
let reopened = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap();
create_state(&reopened, 99, false);
let embedded = cadcraft_engine::pattern_choices().into_iter().find(|p| p.name == "OLDER_EMBEDDED_TEST").unwrap();
assert_eq!(embedded.lines.len(), expected.len());
}
#[test]
fn escape_closes_the_dialog_as_cancel_does() {
let (mut app, _) = app_with_rect();
open_create(&mut app, false);
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut open = true;
let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let mut out = ctx.run_ui(egui::RawInput { events: vec![esc], ..Default::default() }, |ui| dialog(&mut app, ui.ctx(), &mut open));
out.textures_delta.clear();
assert!(!open && app.hatch_dlg.is_none());
}
#[test]
fn stone_tile_excludes_skewed_frame_and_repeats_open_and_closed_polylines() {
use cadcraft_doc::{Common, LwPolyline};
use cadcraft_geom::PolyVertex;
let mut app = CadApp::new(Session::new(), Services::default());
let u = Vec2::new(700., 0.35);
let v = Vec2::new(0., 700.);
let stone = [Vec2::new(111.23, 161.71), Vec2::new(132.01, 158.33), Vec2::new(120.57, 147.83)];
let joint = [Vec2::new(0., 611.31), Vec2::new(21.49, 621.15), Vec2::new(66.21, 615.19)];
for (points, closed) in [(&[Vec2::ZERO, u, u + v, v][..], true), (&stone[..], true), (&joint[..], false)] {
let poly =
LwPolyline { vertices: points.iter().copied().map(PolyVertex::new).collect(), closed, const_width: 0., elevation: 0., plinegen: false };
app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::LwPolyline(poly)).unwrap();
}
let custom = capture_draft(&mut app, u + v, Vec2::ZERO).unwrap();
assert_eq!(custom.families.len(), 5);
open_create(&mut app, false);
let rect = app.session.execute("rectang", &json!({"p1":[0,0],"p2":[1400,700]})).unwrap();
let state = app.hatch_dlg.as_mut().unwrap();
state.custom = Some(custom);
state.handles.push(Handle::parse_hex(rect["handle"].as_str().unwrap()).unwrap());
assert!(ok(&mut app));
let drawing = cadcraft_io::read_dxf(cadcraft_io::write_dxf(app.session.doc().unwrap()).as_bytes()).unwrap();
let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let list = cadcraft_render::build(&drawing, &Space::Model, &Default::default());
let runs: Vec<_> = list
.prims
.iter()
.filter(|p| p.handle == handle && p.kind == cadcraft_render::Kind::Polyline)
.map(|p| &list.verts[p.start as usize..(p.start + p.len) as usize])
.collect();
for offset in [Vec2::ZERO, u] {
for (a, b) in [(stone[0], stone[1]), (stone[1], stone[2]), (stone[2], stone[0]), (joint[0], joint[1]), (joint[1], joint[2])] {
let (a, b) = (a + offset, b + offset);
assert!(
runs.iter().any(|s| s.len() == 2 && ((s[0].dist(a) < 0.25 && s[1].dist(b) < 0.25) || (s[1].dist(a) < 0.25 && s[0].dist(b) < 0.25))),
"missing {a:?} to {b:?}"
);
}
}
}
#[test]
fn crossed_four_corner_polyline_is_part_of_the_motif() {
use cadcraft_doc::{Common, LwPolyline};
use cadcraft_geom::PolyVertex;
let mut app = CadApp::new(Session::new(), Services::default());
let corners = [Vec2::ZERO, Vec2::new(10., 10.), Vec2::new(0., 10.), Vec2::new(10., 0.)];
let poly =
LwPolyline { vertices: corners.into_iter().map(PolyVertex::new).collect(), closed: true, const_width: 0., elevation: 0., plinegen: false };
app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::LwPolyline(poly)).unwrap();
let custom = capture_draft(&mut app, Vec2::ZERO, corners[1]).unwrap();
assert_eq!(custom.families.len(), 4);
}
#[test]
fn shallow_captured_edge_repeats_over_a_hundred_by_a_hundred_tiles() {
let mut app = CadApp::new(Session::new(), Services::default());
let tile = 10.;
let a = Vec2::new(0., 2.);
let b = a + Vec2::new(2047., 1.) * (tile / 2048.);
app.session.execute("line", &json!({"points":[[a.x,a.y],[b.x,b.y]]})).unwrap();
let capture = app.session.execute("hatch.capture", &json!({"first":[0,0],"second":[tile,tile],"name":"SHALLOW_CAPTURE_TEST"})).unwrap();
let text = &capture["patternText"];
let r = app.session.execute("rectang", &json!({"p1":[0,0],"p2":[1000,1000]})).unwrap();
app.session.execute("hatch", &json!({"handles":[r["handle"]],"pattern":"SHALLOW_CAPTURE_TEST","patternText":text})).unwrap();
let d = app.session.doc().unwrap();
let h = d.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let list = cadcraft_render::build(d, &Space::Model, &Default::default());
let runs = list.prims.iter().filter(|p| p.handle == h && p.kind == cadcraft_render::Kind::Polyline);
let full = runs
.filter(|p| {
let seg = &list.verts[p.start as usize..(p.start + p.len) as usize];
seg.len() == 2 && (seg[0].dist(seg[1]) - a.dist(b)).abs() < 1e-6
})
.count();
assert_eq!(full, 10000);
}
#[test]
fn save_pattern_without_applying_it_then_use_it_in_a_new_drawing() {
let mut app = CadApp::new(Session::new(), Services::default());
open_create(&mut app, false);
app.hatch_dlg.as_mut().unwrap().custom = Some(CustomPattern { name: "UNAPPLIED_TILE_TEST".into(), families: vec![PatternFamily::default()] });
save_pattern(&mut app);
let st = app.hatch_dlg.as_ref().unwrap();
assert_eq!(st.fill.pattern, "UNAPPLIED_TILE_TEST");
assert!(st.custom.is_none() && st.error.is_none() && app.session.doc().unwrap().model.iter().next().is_none());
let (mut reopened, boundary) = app_with_rect();
reopened.load_prefs(&app.prefs_json());
open_create(&mut reopened, false);
let st = reopened.hatch_dlg.as_mut().unwrap();
st.fill.pattern = cadcraft_engine::pattern_choices().into_iter().find(|p| p.name == "UNAPPLIED_TILE_TEST").unwrap().name;
st.handles.push(boundary);
assert!(ok(&mut reopened));
assert!(
reopened
.session
.doc()
.unwrap()
.model
.iter()
.any(|e| matches!(&e.kind, EntityKind::Hatch(h) if h.pattern=="UNAPPLIED_TILE_TEST" && h.pattern_lines.len()==1))
);
}
#[test]
fn gallery_filters_by_description_and_selects_the_pattern_in_list_view() {
use egui_kittest::{Harness, kittest::Queryable};
let mut session = Session::new();
session.execute("hatch.patterns", &json!({"text":"*GALLERY_TEST, Quarry sample\n0,0,0,0,1\n"})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(360., 420.)).build_ui_state(
|ui, selected: &mut String| {
if let Some(name) = crate::palettes::patterns::manager(ui, selected, &cadcraft_engine::pattern_choices()) {
*selected = name;
}
},
String::new(),
);
h.get_by_label("Filter").click();
h.run_steps(3);
h.get_by_role(egui::accesskit::Role::TextInput).click();
h.run_steps(2);
h.get_by_role(egui::accesskit::Role::TextInput).type_text("quarry");
h.run_steps(3);
assert!(h.query_by_label("ANSI31").is_none());
h.get_by_role(egui::accesskit::Role::ComboBox).click();
h.run_steps(3);
h.get_by_label("List").click();
h.run_steps(3);
h.get_by_label("GALLERY_TEST").click();
h.run_steps(3);
assert_eq!(h.state(), "GALLERY_TEST");
}
#[test]
fn same_name_in_two_drawings_uses_the_active_drawings_geometry() {
let name = "SHARED_DXF_NAME_TEST";
let make = |spacing| {
let (mut app, boundary) = app_with_rect();
app.run("hatch", json!({"handles":[boundary.hex()],"pattern":name,"patternText":format!("*{name}, local\n0,0,0,0,{spacing}\n")})).unwrap();
let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(app.session.doc().unwrap()).as_bytes()).unwrap();
app.session.open_drawing(reopened, "Reopened", None);
(app, boundary, spacing)
};
let first = make(3);
let second = make(7);
for (mut app, boundary, spacing) in [first, second] {
open_create(&mut app, false);
let st = app.hatch_dlg.as_mut().unwrap();
let choice = st.choices.iter().find(|c| c.name == name).unwrap();
assert_eq!(choice.lines[0].delta.1, f64::from(spacing));
st.fill.pattern = name.into();
st.handles.push(boundary);
assert!(ok(&mut app));
let drawing = app.session.doc().unwrap();
let hatches: Vec<_> = drawing
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Hatch(h) => Some(h),
_ => None,
})
.collect();
assert_eq!(hatches.len(), 2);
assert!(hatches.iter().all(|h| h.pattern_lines[0].delta.1 == f64::from(spacing)));
}
}
#[test]
fn aligned_sparse_marks_still_get_a_visible_swatch() {
let family = cadcraft_doc::library::PatternLine { angle: 0., origin: (70., 0.), delta: (100., 1.), dashes: vec![1., -99.] };
assert!(!cadcraft_render::pattern_swatch(&[family], 1.).is_empty());
}
#[test]
fn capture_refuses_a_polyline_with_a_segment_lost_to_rounding() {
use cadcraft_doc::{Common, LwPolyline};
use cadcraft_geom::PolyVertex;
let mut app = CadApp::new(Session::new(), Services::default());
let vertices = [Vec2::new(1., 1.), Vec2::new(1.001, 1.), Vec2::new(8., 6.)].into_iter().map(PolyVertex::new).collect();
let poly = LwPolyline { vertices, closed: false, const_width: 0., elevation: 0., plinegen: false };
app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::LwPolyline(poly)).unwrap();
assert_eq!(
capture_draft(&mut app, Vec2::ZERO, Vec2::new(10., 10.)).unwrap_err(),
crate::tl!("A segment is too small for the tile capture precision.")
);
}
#[test]
fn applying_a_just_saved_pattern_uses_its_new_spacing() {
let (mut app, boundary) = app_with_rect();
let name = "SAVED_OVER_EMBEDDED_TEST";
let old = app.run("hatch", json!({"handles":[boundary.hex()], "pattern":name, "patternText":format!("*{name}, old\n0,0,0,0,3\n")})).unwrap();
let old = Handle::parse_hex(old["handle"].as_str().unwrap()).unwrap();
open_create(&mut app, false);
let st = app.hatch_dlg.as_mut().unwrap();
st.handles.push(boundary);
st.custom = Some(CustomPattern { name: name.into(), families: vec![PatternFamily { spacing: 7., ..Default::default() }] });
save_pattern(&mut app);
assert!(app.hatch_dlg.as_ref().unwrap().custom.is_none());
assert!(ok(&mut app));
let drawing = app.session.doc().unwrap();
let hatches: Vec<_> = drawing
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Hatch(h) if h.pattern == name => Some((e.handle, h.pattern_lines[0].delta.1)),
_ => None,
})
.collect();
assert_eq!(hatches.len(), 2);
assert!(hatches.contains(&(old, 3.)));
assert!(hatches.iter().any(|(handle, spacing)| *handle != old && *spacing == 7.));
}
#[test]
fn reserved_user_hatch_cannot_be_shadowed_by_a_custom_pattern() {
use cadcraft_doc::library::is_user_pattern;
let (mut app, boundary) = app_with_rect();
let reserved = "_uSeR";
let ordinary = "RESERVED_NAME_CONTROL";
let draft = CustomPattern { name: reserved.into(), families: vec![PatternFamily::default()] };
assert!(draft.encode().is_none());
assert!(app.run("hatch.capture", json!({"first":[0,0], "second":[10,10], "name":reserved})).is_err());
let source = format!("*{reserved}, collision\n0,0,0,0,13\n*{ordinary}, named\n30,0,0,0,7\n");
let registered = app.run("hatch.patterns", json!({"text":source})).unwrap();
assert_eq!(registered["added"], json!([ordinary]));
assert!(!registered["warnings"].as_array().unwrap().is_empty());
app.session.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap();
app.run("hatch", json!({"handles":[boundary.hex()], "pattern":ordinary})).unwrap();
let drawing = app.session.doc().unwrap();
let hatch = |name: &str| {
drawing
.model
.iter()
.find_map(|e| match &e.kind {
EntityKind::Hatch(h) if h.pattern.eq_ignore_ascii_case(name) => Some(h),
_ => None,
})
.unwrap()
};
let native = hatch(reserved);
assert_eq!(native.pattern_lines, cadcraft_doc::library::user_defined_lines(true));
assert_eq!(native.scale, 100.);
assert_eq!(hatch(ordinary).pattern_lines[0].delta.1, 7.);
cadcraft_engine::register_drawing_patterns(drawing);
assert!(!cadcraft_engine::pattern_choices_in(drawing).iter().any(|p| is_user_pattern(&p.name)));
assert!(!cadcraft_engine::pattern_choices().iter().any(|p| is_user_pattern(&p.name)));
}
-1
View File
@@ -1448,7 +1448,6 @@
B B
Backup copy 备份副本
Block to create or edit 要创建或编辑的块
Capture hatch tile 捕获图案填充单元
Choose the command the alias starts. 选择别名要启动的命令。
Click the ruler to add a tab stop, right-click to remove one 单击标尺可添加制表位,右键单击可将其删除
Command 命令
1 # CADCraft Simplified Chinese interface catalog — original translations.
1448
1449
1450
1451
1452
1453
+1 -29
View File
@@ -145,7 +145,6 @@ pub struct UiState {
pub save_version: String,
/// Drawings opened from a path, newest first (File ▸ Open Recent and the Start page).
pub recent_files: Vec<String>,
pub(crate) hatch_patterns: std::collections::BTreeMap<String, String>,
/// The folder the last APPLOAD file came from: the next pick starts there.
pub last_lisp_dir: Option<String>,
/// The folder the Command Aliases dialog last imported a `.pgp` file from.
@@ -227,7 +226,6 @@ impl Default for UiState {
save_format: SaveFormat::default(),
save_version: SaveVersion::default().year().to_string(),
recent_files: Vec::new(),
hatch_patterns: Default::default(),
last_lisp_dir: None,
last_pgp_dir: None,
}
@@ -636,17 +634,7 @@ impl CadApp {
// The bars as the interface shows them now (a `ui.set` may have just changed one), and any
// MENUBAR or TOOLBAR request applied at once.
self.sync_bars();
let r = self.session.execute(id, &params).map_err(|error| match &error {
cadcraft_engine::EngineError::BadParams { cmd, msg } if cmd == "hatch.capture" => match msg.as_str() {
"Pick two opposite corners for the tile" => crate::tl!("Pick two opposite corners for the tile").to_owned(),
"A segment is too small for the tile capture precision." => {
crate::tl!("A segment is too small for the tile capture precision.").to_owned()
}
"No complete line segments in the selected tile." => crate::tl!("No complete line segments in the selected tile.").to_owned(),
_ => error.to_string(),
},
_ => error.to_string(),
});
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
self.sync_bars();
if let Ok(v) = &r
&& let Some(m) = v.get("message").and_then(Value::as_str)
@@ -770,9 +758,6 @@ impl CadApp {
if self.spacemouse.settings != spacemouse::Settings::default() {
prefs["spacemouse"] = json!(self.spacemouse.settings);
}
if !self.ui.hatch_patterns.is_empty() {
prefs["hatchPatterns"] = json!(self.ui.hatch_patterns);
}
if !self.ui.recent_files.is_empty() {
prefs["recentFiles"] = json!(self.ui.recent_files);
}
@@ -791,19 +776,6 @@ impl CadApp {
/// Restore preferences saved by [`Self::prefs_json`]; unknown or malformed values are ignored.
pub fn load_prefs(&mut self, json: &str) {
let Ok(v) = serde_json::from_str::<Value>(json) else { return };
if let Some(patterns) = v["hatchPatterns"].as_object() {
for (name, text) in patterns {
if let Some(text) = text.as_str()
&& self
.session
.execute("hatch.patterns", &json!({"text":text}))
.ok()
.is_some_and(|v| v["added"].as_array().is_some_and(|a| a.iter().any(|n| n.as_str() == Some(name))))
{
self.ui.hatch_patterns.insert(name.clone(), text.to_owned());
}
}
}
if let Some(calculator) = v.get("quickcalc") {
self.quickcalc.load_prefs(calculator);
}
+2 -2
View File
@@ -1349,7 +1349,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) {
EntityKind::Hatch(hh) => {
prop_row(ui, "Pattern", |ui| {
ui.menu_button(hh.pattern.clone(), |ui| {
if let Some(name) = patterns::menu(ui, &hh.pattern, d) {
if let Some(name) = patterns::menu(ui, &hh.pattern) {
set = Some(json!({ "handles": ids, "pattern": name }));
ui.close();
}
@@ -1599,7 +1599,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) {
let pattern = shared("hatch.pattern", &|k| if let EntityKind::Hatch(h) = k { Some(h.pattern.clone()) } else { None });
prop_row(ui, "Pattern", |ui| {
ui.menu_button(pattern.clone(), |ui| {
if let Some(name) = patterns::menu(ui, &pattern, d) {
if let Some(name) = patterns::menu(ui, &pattern) {
set = Some(json!({ "handles": ids, "pattern": name }));
ui.close();
}
+18 -62
View File
@@ -6,7 +6,7 @@ use std::cell::RefCell;
use std::sync::Arc;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, PatternChoice, Picker, pattern_choices_in};
use cadcraft_engine::{Input, PatternChoice, Picker, pattern_choices};
use egui::{Align2, Rect, Sense, Stroke, pos2, vec2};
use crate::CadApp;
@@ -29,8 +29,8 @@ struct Swatch {
solid: bool,
}
/// The complete definitions used to build the cached swatches.
type Swatches = (Vec<PatternChoice>, Arc<Vec<Swatch>>);
/// The patterns' names and line family counts, and their swatches.
type Swatches = (Vec<(String, usize)>, Arc<Vec<Swatch>>);
thread_local! {
static SWATCHES: RefCell<Swatches> = RefCell::new((Vec::new(), Arc::new(Vec::new())));
@@ -38,26 +38,27 @@ thread_local! {
/// The swatches of the patterns offered now, made again only when the list changes (a `.pat`
/// file loaded more patterns).
fn swatches(choices: &[PatternChoice]) -> Arc<Vec<Swatch>> {
fn swatches() -> Arc<Vec<Swatch>> {
let choices = pattern_choices();
let key: Vec<(String, usize)> = choices.iter().map(|c| (c.name.clone(), c.lines.len())).collect();
SWATCHES.with(|cell| {
let mut cache = cell.borrow_mut();
if cache.0 != choices {
let previews = choices.iter().map(swatch).collect();
*cache = (choices.to_vec(), Arc::new(previews));
if cache.0 != key {
*cache = (key, Arc::new(choices.into_iter().map(swatch).collect()));
}
cache.1.clone()
})
}
fn swatch(c: &PatternChoice) -> Swatch {
fn swatch(c: PatternChoice) -> Swatch {
let solid = c.lines.is_empty();
Swatch { runs: cadcraft_engine::render::pattern_swatch(&c.lines, 1.0), name: c.name.clone(), description: c.description.clone(), solid }
Swatch { runs: cadcraft_engine::render::pattern_swatch(&c.lines, 1.0), name: c.name, description: c.description, solid }
}
/// Draw one swatch in `r` (the square and the name under it).
fn paint(p: &egui::Painter, r: Rect, s: &Swatch, selected: bool, hovered: bool) {
let t = Tokens::get();
let square = Rect::from_min_size(r.min, vec2(r.width(), r.width()));
let square = Rect::from_min_size(r.min, vec2(CELL, CELL));
p.rect_filled(square, 3.0, t.field);
let inner = square.shrink(3.0);
if s.solid {
@@ -90,61 +91,18 @@ fn paint(p: &egui::Painter, r: Rect, s: &Swatch, selected: bool, hovered: bool)
/// The swatches whose name or description holds `filter`, `current` marked; returns the
/// pattern clicked.
pub fn grid(ui: &mut egui::Ui, current: &str, filter: &str, choices: &[PatternChoice]) -> Option<String> {
gallery(ui, current, filter, Some(CELL), false, choices)
}
pub(crate) fn manager(ui: &mut egui::Ui, current: &str, choices: &[PatternChoice]) -> Option<String> {
use crate::blocks_palette::View;
let id = ui.make_persistent_id("hatch-gallery-settings");
let (mut view, mut filtering, mut filter): (View, bool, String) = ui.data_mut(|data| data.get_temp(id)).unwrap_or_default();
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("View"));
egui::ComboBox::from_id_salt("hatch-view")
.selected_text(view.label())
.show_ui(ui, |ui| {
for v in View::ALL {
ui.selectable_value(&mut view, v, v.label());
}
})
.response
.labelled_by(label.id);
ui.toggle_value(&mut filtering, crate::tl!("Filter"));
});
if filtering {
ui.add(egui::TextEdit::singleline(&mut filter).hint_text(crate::tl!("Search for pattern")));
}
let chosen = egui::ScrollArea::vertical()
.id_salt("hatch_swatches")
.max_height(220.0)
.show(ui, |ui| gallery(ui, current, if filtering { &filter } else { "" }, view.tile(), view == View::Details, choices))
.inner;
ui.data_mut(|data| data.insert_temp(id, (view, filtering, filter)));
chosen
}
fn gallery(ui: &mut egui::Ui, current: &str, filter: &str, side: Option<f32>, details: bool, choices: &[PatternChoice]) -> Option<String> {
pub fn grid(ui: &mut egui::Ui, current: &str, filter: &str) -> Option<String> {
let filter = filter.trim().to_lowercase();
let mut chosen = None;
let row_width = ui.available_width();
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(GAP, GAP);
let shown = swatches(choices);
let shown = swatches();
for s in
shown.iter().filter(|s| filter.is_empty() || s.name.to_lowercase().contains(&filter) || s.description.to_lowercase().contains(&filter))
{
let Some(side) = side else {
let label = if details { format!("{} {}", s.name, s.description) } else { s.name.clone() };
if ui.add_sized([row_width, LABEL_H + GAP], egui::Button::selectable(s.name.eq_ignore_ascii_case(current), label)).clicked() {
chosen = Some(s.name.clone());
}
continue;
};
let (r, resp) = ui.allocate_exact_size(vec2(side, side + LABEL_H), Sense::click());
let selected = s.name.eq_ignore_ascii_case(current);
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, resp.enabled(), selected, &s.name));
let (r, resp) = ui.allocate_exact_size(vec2(CELL, CELL + LABEL_H), Sense::click());
if ui.is_rect_visible(r) {
paint(ui.painter(), r, s, selected, resp.hovered() || resp.has_focus());
paint(ui.painter(), r, s, s.name.eq_ignore_ascii_case(current), resp.hovered());
}
let tip = if s.description.is_empty() { s.name.clone() } else { format!("{}\n{}", s.name, s.description) };
if resp.on_hover_text(tip).clicked() {
@@ -157,9 +115,9 @@ fn gallery(ui: &mut egui::Ui, current: &str, filter: &str, side: Option<f32>, de
/// The Properties palette's pattern menu: the swatch grid, scrolling; returns the pattern
/// clicked.
pub fn menu(ui: &mut egui::Ui, current: &str, d: &cadcraft_doc::Drawing) -> Option<String> {
pub fn menu(ui: &mut egui::Ui, current: &str) -> Option<String> {
ui.set_width(MENU_COLUMNS * (CELL + GAP));
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| grid(ui, current, "", &pattern_choices_in(d))).inner
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| grid(ui, current, "")).inner
}
/// The picker window while the prompt offers one (HATCH's boundary and pattern prompts,
@@ -181,9 +139,7 @@ pub fn prompt_picker(app: &mut CadApp, ctx: &egui::Context) {
.on_hover_text(crate::tl!("Search for pattern"));
ui.add_space(4.0);
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
if let Ok(d) = app.session.doc() {
chosen = grid(ui, &current, &filter, &pattern_choices_in(d));
}
chosen = grid(ui, &current, &filter);
});
});
ctx.data_mut(|d| d.insert_temp(filter_id, filter));
+1 -4
View File
@@ -23,8 +23,5 @@ fn dwg_test_dependency_matches_the_shared_bridge_targets() {
tests["target"], "cfg(not(any(target_arch = \"wasm32\", all(target_os = \"freebsd\", target_arch = \"aarch64\"))))",
"--all-targets must not add acadrust where the shared DWG bridge excludes it"
);
assert_eq!(
tests["source"], "git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436",
"tests inspect output from the decoder craft-dwg uses: the storytold/acadrust fork at storytold/v0.6.6"
);
assert_eq!(tests["req"], "^0.6.6", "tests inspect output from the decoder version used by craft-dwg");
}