Compare commits

..
29 Commits
Author SHA1 Message Date
Tanish MankuandAldo Zarate d1d2e5788a Stack u1: #1555: tests for clicks made while moving in STRETCH, MOVE and TRIM
#1001 names STRETCH and TRIM; #1555's tests cover MOVE, idle picks,
window corners and CPOLYGON. These cases from #1059 check that a click
made while the mouse moves counts where the button went down in
STRETCH (pick and window), MOVE (pick, and a slow drag is a window),
TRIM, with no command running, with PICKDRAG off, at a click-click
window's second corner, and over overlapping objects with selection
cycling. #1059's fast-long-drag case is left out: under the press-first
model a quick release is a click however far the mouse went.

Co-authored-by: Aldo Zarate <azarate@azf.com.mx>
2026-11-19 15:25:16 -07:00
Tanish Mankuandaustin62jake fa4b6d136d Stack u1: #1555: a slow click on a grip makes it hot
#1555 acts on presses where the button goes down, but leaves grips (no
command running) to egui's click. egui calls a press held longer than
0.8 s a drag, and on a drawing that draws slowly an ordinary click lasts
that long, so the grip ignored it (#2813).

A press on a grip is now remembered and clicks the grip when the button
comes up within the press tolerance, however long it was held; a drag
from it still does nothing. #2853's slow-click tests come along: the
grip case fails without this change, the others pin press-first clicks
across slow frames.

Co-authored-by: austin62jake <340374338+austin62jake@users.noreply.github.com>
2026-11-19 15:25:16 -07:00
Tanish Manku 9787da7015 Stack u1: #1748: rustfmt the Right-Click Customization window's mode groups 2026-11-19 15:25:04 -07:00
Tanish Manku 6ff59c0ada Merge #3183: TRIM/EXTEND: Space enters an option at the mode, projection and edge prompts 2026-11-19 15:23:01 -07:00
Tanish Manku d49ea7e586 Stack u1: #1748: Default and Edit modes decide only with the time-sensitive right-click off
With #1748 a quick right-click between commands is Enter whenever the
time-sensitive right-click is on, and a longer click opens the shortcut
menu. Main's Right-Click Customization (#2371) still let Default and Edit
modes set to "Repeat last command" take every idle right-click, so a
longer click repeated the command instead of opening the menu.

As in AutoCAD, the modes now apply with the time-sensitive right-click
off, and the window greys them out with it on, as it does Command mode.
The Right-Click Customization tests set the option off where they test
the modes; a new test holds the button with both modes on repeat.
2026-11-19 15:22:58 -07:00
Tanish Manku 9a4347a08d Merge #1748: a quick right-click is Enter between commands too
# Conflicts:
#	contributors/people.toml
#	crates/ui-egui/src/canvas.rs
#	crates/ui-egui/src/context_menu.rs
#	crates/ui-egui/src/options.rs
#	docs/ui-parity.md
2026-11-19 15:21:49 -07:00
Tanish Manku 48a18c882b Merge #2070: show pickbox-only cursor at command object-selection prompts
# Conflicts:
#	crates/ui-egui/src/canvas.rs
2026-11-19 15:19:55 -07:00
Tanish Manku 1341b42127 Merge #1555: Canvas: clicks count when the button goes down, even while the mouse moves
# Conflicts:
#	crates/ui-egui/tests/it/main.rs
2026-11-19 15:19:39 -07:00
The old Dutch Guy 79784a62fe Merge branch 'main' into feat/pickbox-only-cursor 2026-11-18 18:03:45 +01:00
The old Dutch Guy 38888cd5d9 Merge branch 'main' into feat/pickbox-only-cursor 2026-11-18 11:28:53 +01:00
The old Dutch Guy 97e5c7ff37 Merge branch 'main' into feat/pickbox-only-cursor 2026-11-16 17:28:53 +01:00
The old Dutch Guy 54015120db fix(tests): restore missing closing brace in canvas tests 2026-11-16 17:17:10 +01:00
The old Dutch Guy 60b0f21edb feat(ui): show pickbox-only cursor at object selection prompts 2026-11-16 17:17:10 +01:00
jayzed80 8db82ebf7c TRIM/EXTEND: Space enters an option at the mode, projection and edge prompts (#3092) 2026-11-15 09:38:01 +00:00
filforce95andClaude Opus 5.5 60c4f0d439 docs: leave ui-parity.md to the maintainers
PRs no longer edit the progress docs (CLAUDE.md, Roadmap); the affected row is
named in the PR description instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:01:57 +01:00
filforce95andClaude Opus 5.5 a762140d4e Merge origin/main into feat/press-first-clicks-1001
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:06:47 +01:00
filforce95andClaude Opus 5.5 e7c3cf9223 Merge origin/main into feat/press-first-clicks-1001
main split canvas.rs into canvas/ modules and show() into helpers (#2187),
moved to egui 0.37 (#2119) and tightened Clippy (#2239). The press detector is
carried over to that structure: handle_presses replaces collect_prompt_clicks
(#835's release replay) and the egui drag-window block; selection cycling
(#1149) and PICKDRAG 0 (#1032) behave as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:08:52 +01:00
Sladrian PedrosoandClaude Opus 5.5 f8423bb44f Merge main into right-click-enter-between-commands
canvas.rs: main moved most of the canvas into canvas/ and documented
show(); the right-click change stays where it was, in show().
time_sensitive_right_click paints a frame after Escape before the next
quick click: with egui 0.37 the shortcut menu closes on the frame after.
people.toml and docs/ui-parity.md: both sides kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:14:58 -03:00
filforce95 0703ae91b4 Merge remote-tracking branch 'origin/main' into feat/press-first-clicks-1001
# Conflicts:
#	docs/ui-parity.md
2026-10-24 09:24:06 +02:00
filforce95andClaude Opus 5.5 d75e2a0ae0 test: press_first_clicks joins the ui-egui test binary (#1989)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 19:50:50 +02:00
filforce95 0c7b7ec469 Merge remote-tracking branch 'origin/main' into feat/press-first-clicks-1001 2026-10-23 19:45:42 +02:00
filforce95andClaude Opus 5.5 b5f6df8fec test(pickdrag): the second corner is set where the button goes down
With clicks counting on press (#1001), a press after the first corner
closes the window there even with PICKDRAG 0; letting go elsewhere after
a drag changes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 18:31:43 +02:00
filforce95andClaude Opus 5.5 5fa1352d82 Merge main into feat/press-first-clicks-1001
Resolve the canvas conflicts with selection cycling (#1149) and the
two-click preference (#1032): cycling opens and picks on the press, and
with PICKDRAG off a drag no longer closes the window its press opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 18:23:59 +02:00
Sladrian PedrosoandClaude Opus 5.5 25714cac28 docs/ui-parity.md: with the time-sensitive right-click off, a right-click opens the command menu while a command runs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:11:05 -03:00
Sladrian PedrosoandClaude Opus 5.5 8709920931 Document canvas::show, the drawing area for one frame
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:58:04 -03:00
Sladrian PedrosoandClaude Opus 5.5 77b9560729 contributors: add my real name for the About window credits
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 14:58:38 -03:00
Sladrian PedrosoandClaude Opus 5.5 80bbcb98ba A quick right-click is Enter between commands too: it runs the typed command or repeats the last one (fixes #1387)
With the time-sensitive right-click on (the default), a quick right-click
was Enter only while a command ran, and it sent a bare Enter even when
something was typed. Between commands every right-click opened the shortcut
menu, so typing `rec` and right-clicking opened the menu instead of starting
RECTANG, and at an empty prompt it didn't repeat the last command as AutoCAD
does.

A quick right-click now does what the Enter key does (cmdline::submit): it
enters what was typed (a command name, `@10,0`), ends the input of a running
command, and between commands repeats the last one. Held, it still opens the
command menu or the shortcut menu; a grip with options keeps its menu;
Shift/Ctrl+right-click is still the object snap menu; with the time-sensitive
right-click turned off, every right-click opens the menu. With nothing typed
and no command run yet, a quick click opens the shortcut menu (there is
nothing to enter).

time_sensitive_right_click now also checks that a quick click between
commands repeats LINE, a held one opens the menu with Repeat LINE and repeats
nothing, a typed `circle` starts CIRCLE and a typed `5,5` enters its centre;
these checks fail without the change. docs/ui-parity.md describes the new
behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 14:58:37 -03:00
filforce95andClaude Opus 5.5 023b833fd4 docs(ui-parity): a press on an object picks it; a drag from it opens no window (#1001)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:08:56 +02:00
filforce95andClaude Opus 5.5 06e53f3ee7 fix(canvas): clicks count when the button goes down, even while the mouse moves (fixes #1001, #1546)
Every click on the drawing used to be decided when the button came up: egui
calls a press that travels more than a few points a drag, so a click made
while the hand was still moving was lost (object picks, the second corner of a
click-click window) or taken where the hand had got to (points, #835).

Following the model agreed in #1001, a press now acts at once, where the button
went down: it places the point (snapped as the cursor would be there), picks
the object or sets a selection window's corner. Each press among a frame's
events counts, so a slow frame keeps all its clicks (#815). What the pointer
does while the button is held only decides whether the press becomes a drag:
once it leaves a 6-point tolerance a 0.25 s timer starts; a button still down
then is a drag and closes the window its press opened where it comes up, while
a button that comes up sooner was a click and the window waits for the next
press. Holding still never makes a drag.

The detector lives in canvas/press.rs. Grips with no command running, ZOOM
Realtime, the Dynamic Input options menu, model tiles and double-clicks keep
their release-based clicks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 11:55:23 +02:00
32 changed files with 1523 additions and 398 deletions
Generated
+3 -4
View File
@@ -717,7 +717,6 @@ version = "0.21.0"
dependencies = [
"cadcraft-color",
"cadcraft-geom",
"craft-dxf",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -1184,7 +1183,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
[[package]]
name = "craft-docpath"
@@ -1203,9 +1202,9 @@ dependencies = [
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
dependencies = [
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a)",
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9)",
"encoding_rs",
"kurbo",
"log",
+1 -1
View File
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "2f2d1d84e3a36b3f93e81507aeff3f0da97a7162" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
+5
View File
@@ -128,3 +128,8 @@ sync_github_name = true
[people.tyrel]
real_name = "Tyrel Haveman"
[people.Sladrian]
real_name = "Sladrian Pedroso"
display_name = "Sladrian Pedroso"
sync_github_name = false
-1
View File
@@ -11,7 +11,6 @@ workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
craft-dxf = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+314 -46
View File
@@ -1,14 +1,32 @@
//! Readers for the user's own linetype (`.lin`) and hatch pattern (`.pat`) files.
//!
//! Grammar and hostile-input capping live in [`craft_dxf::lin_pat`]; this module maps the
//! parsed definitions into CADCraft's [`Linetype`] and [`UserPattern`] document types.
use cadcraft_geom::Vec2;
pub use craft_dxf::lin_pat::{MAX_DEFINITIONS, MAX_LINE_CHARS, MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, MAX_VALUE, Parsed};
//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then
//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for
//! a pattern), with `;` starting a comment line. CADCraft ships no such file; these read the
//! files users bring. Everything here treats the text as hostile: lines, definitions, dashes,
//! families and warnings are capped, numbers must be finite and reasonable, and nothing panics.
//! Problems become warnings and the definitions that can be read are kept.
use super::PatternLine;
use crate::{DashElement, Linetype};
/// Longest line read; longer lines are skipped with a warning.
pub const MAX_LINE_CHARS: usize = 4096;
/// Most definitions (linetypes or patterns) read from one file.
pub const MAX_DEFINITIONS: usize = 4096;
/// Most elements in one linetype.
pub const MAX_LINETYPE_ELEMENTS: usize = 256;
/// Most line families in one hatch pattern (what the renderer draws, too).
pub const MAX_PATTERN_FAMILIES: usize = 1024;
/// Most dashes in one pattern line family (as for a pattern definition read from DXF).
pub const MAX_PATTERN_DASHES: usize = 256;
/// Largest magnitude accepted for a length, offset or scale.
pub const MAX_VALUE: f64 = 1.0e6;
/// Longest name or description kept.
const MAX_NAME_CHARS: usize = 255;
/// Most warnings collected; the rest are counted in a last line.
const MAX_WARNINGS: usize = 100;
/// A hatch pattern read from a user's `.pat` file.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct UserPattern {
@@ -17,57 +35,307 @@ pub struct UserPattern {
pub lines: Vec<PatternLine>,
}
/// What a file held: the definitions that could be read, and why anything else was skipped.
#[derive(Clone, Debug, PartialEq)]
pub struct Parsed<T> {
pub items: Vec<T>,
pub warnings: Vec<String>,
}
impl<T> Default for Parsed<T> {
fn default() -> Self {
Parsed { items: Vec::new(), warnings: Vec::new() }
}
}
impl<T> Parsed<T> {
fn warn(&mut self, line: usize, msg: impl Into<String>) {
match self.warnings.len() {
n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())),
MAX_WARNINGS => self.warnings.push("more problems not listed".into()),
_ => {}
}
}
}
/// A header line `*NAME[,description]`: the name and description, or why it can't be used.
fn header(rest: &str) -> std::result::Result<(String, String), String> {
let (name, desc) = rest.split_once(',').unwrap_or((rest, ""));
let name = name.trim();
if name.is_empty() {
return Err("a definition without a name".into());
}
if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
return Err("a definition name that is too long or has control characters".into());
}
let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
Ok((name.to_string(), desc))
}
/// A finite number within ±[`MAX_VALUE`].
fn number(t: &str) -> Option<f64> {
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE)
}
/// The file's text lines with 1-based numbers, without a leading byte-order mark.
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim()))
}
// ---------- LIN ----------
/// Read the linetypes of a `.lin` file. Simple linetypes and complex ones with embedded text
/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`)
/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept.
/// Lengths are in drawing units as written: a user's file is never rescaled.
pub fn parse_lin(text: &str) -> Parsed<Linetype> {
let parsed = craft_dxf::lin_pat::parse_lin(text);
Parsed {
items: parsed
.items
.into_iter()
.map(|d| Linetype {
name: d.name,
description: d.description,
pattern: d
.pattern
.into_iter()
.map(|e| DashElement {
length: e.length,
text: e.text,
shape: None,
style: e.style,
scale: e.scale,
rotation: e.rotation,
offset: Vec2::new(e.offset[0], e.offset[1]),
absolute: e.absolute,
})
.collect(),
})
.collect(),
warnings: parsed.warnings,
let mut out = Parsed::default();
// The definition being read: name, description, header line.
let mut pending: Option<(String, String, usize)> = None;
for (no, line) in lines(text) {
if line.is_empty() || line.starts_with(';') {
continue;
}
if line.chars().count() > MAX_LINE_CHARS {
out.warn(no, "line too long; skipped");
continue;
}
if let Some(rest) = line.strip_prefix('*') {
if let Some((name, _, at)) = pending.take() {
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
}
match header(rest) {
Ok((name, desc)) => pending = Some((name, desc, no)),
Err(e) => out.warn(no, format!("{e}; skipped")),
}
continue;
}
let Some((name, description, _)) = pending.take() else {
out.warn(no, "pattern line without a *NAME line before it; skipped");
continue;
};
if out.items.len() >= MAX_DEFINITIONS {
out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped"));
break;
}
if out.items.iter().any(|l: &Linetype| l.name.eq_ignore_ascii_case(&name)) {
out.warn(no, format!("linetype {name} is defined twice; the first definition is kept"));
continue;
}
match lin_pattern(line, no, &name, &mut out) {
Ok(pattern) => out.items.push(Linetype { name, description, pattern }),
Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")),
}
}
if let Some((name, _, at)) = pending {
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
}
out
}
/// Split a pattern line at commas outside `[…]` and `"…"`.
fn lin_fields(line: &str) -> std::result::Result<Vec<&str>, String> {
let mut out = Vec::new();
let (mut depth, mut quoted, mut start) = (0usize, false, 0usize);
for (i, c) in line.char_indices() {
match c {
'"' => quoted = !quoted,
'[' if !quoted => depth = depth.saturating_add(1),
']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?,
',' if !quoted && depth == 0 => {
out.push(line.get(start..i).unwrap_or("").trim());
start = i.saturating_add(1);
}
_ => {}
}
if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) {
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
}
}
if quoted || depth != 0 {
return Err("an unclosed [ or \"".into());
}
out.push(line.get(start..).unwrap_or("").trim());
Ok(out)
}
/// The elements of a pattern line `A,dash,gap,[…],…`.
fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed<Linetype>) -> std::result::Result<Vec<DashElement>, String> {
let mut fields = lin_fields(line)?;
// The alignment field ("A") comes first; a line of plain numbers is read as well.
if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) {
fields.remove(0);
} else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) {
return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or("")));
}
let mut pattern: Vec<DashElement> = Vec::new();
for f in fields.into_iter().filter(|f| !f.is_empty()) {
if pattern.len() >= MAX_LINETYPE_ELEMENTS {
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
}
let Some(inner) = f.strip_prefix('[') else {
let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?;
pattern.push(DashElement::dash(len));
continue;
};
let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?;
match lin_text(inner)? {
Some(text) => {
// The text sits at the end of the element before it (a zero-length one if none).
if pattern.last().is_none_or(|e| e.text.is_some()) {
pattern.push(DashElement::dash(0.0));
}
if let Some(last) = pattern.last_mut() {
*last = DashElement { length: last.length, ..text };
}
}
None => {
let shape = inner.split(',').next().unwrap_or("").trim();
out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which CADCraft can't read; left out"));
}
}
}
if pattern.is_empty() {
return Err("no dashes".into());
}
if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) {
return Err("every element has zero length".into());
}
Ok(pattern)
}
/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element.
fn lin_text(inner: &str) -> std::result::Result<Option<DashElement>, String> {
let inner = inner.trim();
let Some(after) = inner.strip_prefix('"') else { return Ok(None) };
let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?;
if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) {
return Err("embedded text that is too long or has control characters".into());
}
let mut parts = rest.split(',').map(str::trim);
if !parts.next().unwrap_or("").is_empty() {
return Err("text element: expected a comma after the text".into());
}
let style = parts.next().unwrap_or("").trim();
if style.is_empty() || style.contains('=') {
return Err("text element: the text style is missing".into());
}
let mut e = DashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..DashElement::dash(0.0) };
for kv in parts.filter(|p| !p.is_empty()) {
let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?;
match k.trim().to_ascii_uppercase().as_str() {
"S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?,
"X" => e.offset.x = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?,
"Y" => e.offset.y = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?,
// Upright text keeps a rotation relative to the line, like R.
k @ ("R" | "A" | "U") => {
e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?;
e.absolute = k == "A";
}
other => return Err(format!("text element: unknown option `{other}`")),
}
}
Ok(Some(e))
}
/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out.
fn angle(t: &str) -> Option<f64> {
let t = t.trim().to_ascii_lowercase();
let (num, unit) = match t.char_indices().last() {
Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c),
_ => (t.as_str(), 'd'),
};
let v = num.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?;
Some(match unit {
'r' => v,
'g' => v * std::f64::consts::PI / 200.0,
_ => v.to_radians(),
})
}
// ---------- PAT ----------
/// Read the hatch patterns of a `.pat` file. Values are used as written (an inch file for inch
/// drawings, a millimetre file for metric ones).
pub fn parse_pat(text: &str) -> Parsed<UserPattern> {
let parsed = craft_dxf::lin_pat::parse_pat(text);
Parsed {
items: parsed
.items
.into_iter()
.map(|p| UserPattern {
name: p.name,
description: p.description,
lines: p
.lines
.into_iter()
.map(|l| PatternLine { angle: l.angle, origin: (l.origin[0], l.origin[1]), delta: (l.delta[0], l.delta[1]), dashes: l.dashes })
.collect(),
})
.collect(),
warnings: parsed.warnings,
let mut out: Parsed<UserPattern> = Parsed::default();
// The pattern being read, its header line, and whether it already failed.
let mut cur: Option<(UserPattern, usize, bool)> = None;
let finish = |cur: Option<(UserPattern, usize, bool)>, out: &mut Parsed<UserPattern>| {
let Some((p, at, failed)) = cur else { return };
if failed {
return;
}
if p.lines.is_empty() {
out.warn(at, format!("pattern {} has no line families; skipped", p.name));
} else if out.items.len() >= MAX_DEFINITIONS {
out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name));
} else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) {
out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name));
} else {
out.items.push(p);
}
};
for (no, line) in lines(text) {
// A comment runs to the end of the line.
let line = line.split(';').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
if line.chars().count() > MAX_LINE_CHARS {
out.warn(no, "line too long; skipped");
continue;
}
if let Some(rest) = line.strip_prefix('*') {
finish(cur.take(), &mut out);
match header(rest) {
Ok((name, description)) => cur = Some((UserPattern { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)),
Err(e) => out.warn(no, format!("{e}; skipped")),
}
continue;
}
let Some((p, _, failed)) = cur.as_mut() else {
out.warn(no, "line family without a *NAME line before it; skipped");
continue;
};
if *failed {
continue;
}
if p.lines.len() >= MAX_PATTERN_FAMILIES {
out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name));
*failed = true;
continue;
}
match pat_family(line) {
Ok(l) => p.lines.push(l),
Err(e) => {
out.warn(no, format!("pattern {}: {e}; skipped", p.name));
*failed = true;
}
}
}
finish(cur, &mut out);
out
}
/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`.
fn pat_family(line: &str) -> std::result::Result<PatternLine, String> {
let mut v = Vec::new();
for f in line.split(',') {
if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) {
return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family"));
}
let f = f.trim();
if f.is_empty() && v.len() >= 5 {
continue;
}
v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?);
}
let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else {
return Err("a line family needs angle, x, y, delta-x and delta-y".into());
};
if dy.abs() < 1e-9 {
return Err("a line family with zero spacing (delta-y)".into());
}
Ok(PatternLine { angle, origin: (x, y), delta: (dx, dy), dashes: v.get(5..).unwrap_or(&[]).to_vec() })
}
+2 -7
View File
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(),
CommandSpec::new("loops", "Implied Loops", loops::run).params(loops::PARAMS).noundo(),
CommandSpec::new("texts", "Query Texts", run_texts)
.params("{contains?: text (any case; `query` is the same filter), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders")
.params("{contains?: text (any case), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders")
.noundo(),
CommandSpec::new("countlist", "Count List", count::run_countlist)
.params("{space?: all (default)|current|model|<layout>, nested?: bool} → per-block counts, as COUNT")
@@ -664,12 +664,7 @@ fn run_texts(s: &mut Session, p: &Value) -> Result<Value> {
v.as_u64().map(|n| usize::try_from(n).unwrap_or(usize::MAX)).ok_or_else(|| bad(CMD, format!("`{k}` must be a whole number, 0 or more")))
})
};
// `query` is what agents tend to call the filter; without this alias it was silently ignored
// and every text came back (#3011).
let contains = match text("contains")? {
Some(c) => Some(c),
None => text("query")?,
};
let contains = text("contains")?;
let layer = text("layer")?;
let window = given("window")
.map(|w| {
+2 -23
View File
@@ -264,23 +264,16 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("`{name}` has no style `{rm}`")));
}
}
let mut changed: Option<String> = None;
if let Some(v) = p.get("style") {
let sname = v.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty());
let sname = sname.ok_or_else(|| bad(cmd, "`style.name` is required"))?;
// The name as it is stored (at most 255 characters, as `sanitized` cuts it, and
// without a space the cut leaves at the end, which `sanitized` trims), so a long
// name finds the style it was stored as and the reply finds the edited style.
let cut: String = sname.chars().take(255).collect();
let sname = cut.trim_end();
changed = Some(sname.to_string());
let idx = match t.styles.iter().position(|x| x.name.eq_ignore_ascii_case(sname)) {
Some(i) => i,
None if t.kind == PlotStyleKind::Named => {
if t.styles.len() >= cadcraft_doc::MAX_NAMED_STYLES {
return Err(bad(cmd, "the table has too many styles"));
}
t.styles.push(PlotStyle::object(sname));
t.styles.push(PlotStyle::object(&sname.chars().take(255).collect::<String>()));
t.styles.len() - 1
}
None => return Err(bad(cmd, format!("`{name}` has no style `{sname}` (colour-dependent styles are Color_1 to Color_255)"))),
@@ -290,21 +283,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let t = t.sanitized();
// Only what changed, not the table (a colour-dependent one has 255 styles): the table's
// name, the description if given, the edited style and the removed style's name.
let mut out = json!({ "name": t.name });
if let Some(o) = out.as_object_mut() {
if str_param(p, "description").is_some() {
o.insert("description".into(), json!(t.description));
}
let edited = changed.and_then(|n| t.styles.iter().find(|x| x.name.eq_ignore_ascii_case(&n)));
if let Some(e) = edited.and_then(|x| serde_json::to_value(x).ok()) {
o.insert("style".into(), e);
}
if let Some(r) = str_param(p, "removeStyle") {
o.insert("removedStyle".into(), json!(r.trim()));
}
}
let out = serde_json::to_value(&t).unwrap_or(Value::Null);
store(s.doc_mut()?, t);
Ok(out)
}
+4 -1
View File
@@ -323,13 +323,16 @@ impl Interactive for StretchM {
s.echo("Select objects to stretch by crossing-window or crossing-polygon...");
Ok(Step::Continue)
}
/// Returns the active interactive prompt for the current `STRETCH` phase.
fn prompt(&self, _s: &Session) -> Prompt {
if let (StretchPhase::Select, Some(m)) = (self.phase, &self.mode) {
return m.prompt();
}
match (self.phase, self.corner) {
(StretchPhase::Select, Some(c)) => Prompt::new("Specify opposite corner", Accept::POINT).corner(c),
(StretchPhase::Select, None) => Prompt::new(if self.removing { "Remove objects" } else { "Select objects" }, Accept::POINT),
(StretchPhase::Select, None) => {
Prompt { picks_one: self.removing, ..Prompt::new(if self.removing { "Remove objects" } else { "Select objects" }, Accept::POINT) }
}
(StretchPhase::Base, _) => Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]).default("Displacement"),
(StretchPhase::Displacement, _) => Prompt::new("Specify displacement", Accept::POINT).default("0,0"),
(StretchPhase::Second, _) => Prompt::new("Specify second point or <use first point as displacement>", Accept::POINT).base_opt(self.base),
+4 -3
View File
@@ -8,6 +8,7 @@ use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_geom::{Bounds2, Line, Vec2, line_line};
use serde_json::{Value, json};
use super::curves::KW;
use super::helpers::{line, lwpoly, rect_vertices};
use super::modify::{Edges, extend, trim};
use super::{bad, point_param, points_param};
@@ -360,7 +361,7 @@ impl Interactive for TrimM {
Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT),
Stage::Mode => {
let msg = if self.extend { "Enter an extend mode option" } else { "Enter a trim mode option" };
Prompt::new(msg, Accept::TEXT).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
Prompt::new(msg, KW).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
}
Stage::Project => {
let cur = match proj_mode(s) {
@@ -368,9 +369,9 @@ impl Interactive for TrimM {
2 => "View",
_ => "Ucs",
};
Prompt::new("Enter a projection option", Accept::TEXT).kw(&["None", "Ucs", "View"]).default(cur)
Prompt::new("Enter a projection option", KW).kw(&["None", "Ucs", "View"]).default(cur)
}
Stage::Edge => Prompt::new("Enter an implied edge extension mode", Accept::TEXT).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
Stage::Edge => Prompt::new("Enter an implied edge extension mode", KW).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
"Extend"
} else {
"No extend"
-9
View File
@@ -213,19 +213,10 @@ pub fn getvar(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
let name = string(&a[0])?;
Ok(Flow::Value(match crate::sysvars::get(ctx.s, &name) {
Some(serde_json::Value::Number(n)) if in_radians(&name) => Value::Real(n.as_f64().unwrap_or(0.0).to_radians()),
Some(serde_json::Value::Object(o)) if o.contains_key("x") => point_list(&o, &name),
v => v.map(|v| from_json(&v)).unwrap_or_default(),
}))
}
/// Header point variables are stored as `{x, y, z}`; AutoLISP gives a point list. LIMMIN, LIMMAX,
/// SNAPBASE and HPORIGIN are 2D points, so they lose z; the rest (INSBASE, UCSORG, ...) keep all three.
fn point_list(o: &serde_json::Map<String, serde_json::Value>, name: &str) -> Value {
let coord = |k: &str| Value::Real(o.get(k).and_then(serde_json::Value::as_f64).unwrap_or(0.0));
let planar = ["LIMMIN", "LIMMAX", "SNAPBASE", "HPORIGIN"].iter().any(|v| v.eq_ignore_ascii_case(name.trim()));
if planar { Value::list(vec![coord("x"), coord("y")]) } else { Value::list(vec![coord("x"), coord("y"), coord("z")]) }
}
/// Set a system variable after bounded JSON conversion, reporting invalid or oversized values as LISP errors.
pub fn setvar(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 2, 2)?;
-11
View File
@@ -649,17 +649,6 @@ fn getvar_drawing_and_session_variables() {
assert_eq!(ok(&mut s, "(getvar \"DWGTITLED\")"), "1");
}
/// LIMMIN, LIMMAX, SNAPBASE and HPORIGIN read as 2D point lists and INSBASE as a 3D one, not as JSON text (#2988).
#[test]
fn getvar_point_variables_are_point_lists() {
let mut s = session();
assert_eq!(ok(&mut s, "(getvar \"LIMMIN\")"), "(0.0 0.0)");
assert_eq!(ok(&mut s, "(getvar \"LIMMAX\")"), "(12.0 9.0)");
assert_eq!(ok(&mut s, "(getvar \"SNAPBASE\")"), "(0.0 0.0)");
assert_eq!(ok(&mut s, "(getvar \"INSBASE\")"), "(0.0 0.0 0.0)");
assert_eq!(ok(&mut s, "(setvar \"HPORIGIN\" '(3.0 4.0)) (getvar \"HPORIGIN\")"), "(3.0 4.0)");
}
/// CECOLOR is a string in AutoCAD, whatever it was set from (#1999).
#[test]
fn getvar_cecolor_is_a_string() {
+1 -69
View File
@@ -62,10 +62,7 @@ fn stylesmanager_creates_edits_saves_and_loads_tables() {
&json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5", "color": "#00ff00", "screening": 40, "lineweight": 0.35, "linetype": "HIDDEN", "end": "round"}}),
)
.unwrap();
// `set` replies with the table's name and the edited style, not the table.
assert_eq!(r["name"], "office.stb");
let pen = r["style"].clone();
assert_eq!(pen["name"], "Pen 5");
let pen = r["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Pen 5").unwrap().clone();
assert_eq!(
(pen["color"].as_str(), pen["screening"].as_u64(), pen["lineweight"].as_u64(), pen["end"].as_str()),
(Some("#00ff00"), Some(40), Some(35), Some("round"))
@@ -134,68 +131,3 @@ fn plot_style_save_is_atomic_and_keeps_permissions() {
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let _ = std::fs::remove_dir_all(&dir);
}
/// #3011: `set` on a colour-dependent table (255 styles) replies with what changed, not the table.
#[test]
fn stylesmanager_set_replies_with_the_change_not_the_whole_table() {
let mut s = Session::new();
let set = json!({"action": "set", "name": "monochrome.ctb", "style": {"name": "Color_13", "lineweight": 0.3}});
let r = s.execute("stylesmanager", &set).unwrap();
assert_eq!(r["name"], "monochrome.ctb", "{r}");
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some("Color_13"), Some(30)), "{r}");
// Only the change: no table summary, no other style.
let keys: Vec<&str> = r.as_object().unwrap().keys().map(String::as_str).collect();
assert_eq!(keys, ["name", "style"], "{r}");
assert!(r.to_string().len() < 1000, "the reply is short, not the 255-style table: {} bytes", r.to_string().len());
// The edit is in the drawing.
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "monochrome.ctb"})).unwrap();
let c13 = got["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Color_13").unwrap();
assert_eq!(c13["lineweight"], 30);
// Removing a style of a named table names what went.
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5"}})).unwrap();
let r =
s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "removeStyle": "Pen 5", "description": "Office pens"})).unwrap();
assert_eq!((r["removedStyle"].as_str(), r["description"].as_str()), (Some("Pen 5"), Some("Office pens")), "{r}");
assert!(r.get("style").is_none() && r.get("styles").is_none(), "{r}");
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
assert_eq!(got["styles"].as_array().map(Vec::len), Some(1), "{got}");
}
/// A style name over 255 characters is stored cut to 255: the reply names the stored style, and
/// setting the same long name again edits that style instead of adding one.
#[test]
fn stylesmanager_set_with_a_long_style_name_replies_with_the_stored_style() {
let mut s = Session::new();
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
let long = "P".repeat(300);
let stored = "P".repeat(255);
let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}});
let r = s.execute("stylesmanager", &set(0.3)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}");
let r = s.execute("stylesmanager", &set(0.5)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}");
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
let styles = got["styles"].as_array().unwrap();
assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}");
assert_eq!(styles[1]["lineweight"], 50, "{got}");
}
/// A long name whose 255th character is a space is stored without it (`sanitized` trims the cut
/// name), so the reply still has the style and setting the same name again edits it.
#[test]
fn stylesmanager_set_with_a_long_name_cut_at_a_space_edits_one_style() {
let mut s = Session::new();
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
let long = format!("{} tail", "P".repeat(254));
let stored = "P".repeat(254);
let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}});
let r = s.execute("stylesmanager", &set(0.3)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}");
let r = s.execute("stylesmanager", &set(0.5)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}");
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
let styles = got["styles"].as_array().unwrap();
assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}");
assert_eq!(styles[1]["lineweight"], 50, "{got}");
}
-16
View File
@@ -226,22 +226,6 @@ fn find_text_reads_texts_and_render_shows_one_area() {
assert_eq!((w, h), (1600, 800));
}
/// Guards #3011: `find_text` filters by `query` as it does by `contains`, instead of ignoring it
/// and returning every text.
#[test]
fn find_text_filters_by_query() {
let mut s = Server::new(Box::new(Headless::default()));
call(&mut s, 1, "initialize", json!({"protocolVersion": "2025-06-18"}));
tool(&mut s, "execute", json!({"command": "text", "params": {"at": [1, 1], "height": 0.15, "text": "RECAMARA 1"}}));
tool(&mut s, "execute", json!({"command": "text", "params": {"at": [50, 1], "height": 0.15, "text": "COCINA"}}));
assert_eq!(tool(&mut s, "find_text", json!({}))["count"], 2);
let r = tool(&mut s, "find_text", json!({"query": "cocina"}));
assert_eq!((r["count"].as_u64(), r["texts"][0]["text"].as_str()), (Some(1), Some("COCINA")), "{r}");
assert_eq!(tool(&mut s, "find_text", json!({"query": "nada"}))["count"], 0);
// `contains` still works and wins when both are given.
assert_eq!(tool(&mut s, "find_text", json!({"contains": "recamara", "query": "cocina"}))["texts"][0]["text"], "RECAMARA 1");
}
/// Guards a lazy Remote bridge: it serves tools without the app, reports how to start it
/// (`--control`), and reaches the app once that app starts listening on the port.
#[test]
+2 -2
View File
@@ -28,8 +28,8 @@ pub fn tool_definitions(has_ui: bool) -> Value {
"background": {"type": "string", "description": "\"dark\" (default without plot_style), \"white\" (default with one), \"paper\" or \"#rrggbb\""},
"plot_style": {"type": "string", "description": "a plot style table: monochrome.ctb, grayscale.ctb, default.ctb, default.stb, monochrome.stb, or one the drawing holds; \"none\" or \"\" for the objects' own properties"},
"path": {"type": "string"}}}}),
json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case; `query` is the same filter), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.",
"inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "query": {"type": "string"}, "layer": {"type": "string"},
json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.",
"inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "layer": {"type": "string"},
"window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2},
"limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}),
json!({"name": "new_drawing", "description": "Create a new drawing (imperial by default, or metric).",
+207 -143
View File
@@ -20,6 +20,7 @@ mod grid;
mod grips;
mod list;
mod pick;
mod press;
mod viewport;
mod widgets;
@@ -164,7 +165,7 @@ pub struct CanvasState {
/// A GRIP edit was running last frame (its grips go cold when it ends).
grip_editing: bool,
/// The grip whose menu (Stretch, Add Vertex, Lengthen…) a right-click opened.
grip_menu: Option<(Handle, usize)>,
pub(crate) grip_menu: Option<(Handle, usize)>,
/// Dynamic block grips of the selection (cached), the one being dragged, and the list grip
/// whose choices are open (and whether it opened this frame).
pub(crate) dyn_grips: crate::dyngrips::Cache,
@@ -181,8 +182,8 @@ pub struct CanvasState {
hover_frozen: Vec<String>,
/// Constraint glyphs for the parametric overlay (cached per drawing revision).
pub param: crate::parametric::Cache,
/// A selection window opened by a press-and-drag, to close where the button is let go.
drag_window: bool,
/// The primary-button press being held, when it was acted on (see [`press`]).
press: Option<press::Press>,
/// The right-click that opened the shortcut menu held Shift or Ctrl: it is the object snap
/// menu ([`crate::context_menu`]).
pub snap_menu: bool,
@@ -513,13 +514,7 @@ fn paint_content_highlights(frame: &mut CanvasPaint<'_>, bg: Rgb, sel: &[Handle]
}
}
fn paint_pointer_overlay(
frame: &mut CanvasPaint<'_>,
paper_rect: Option<Rect>,
surround: Color32,
selecting: bool,
sheet: Option<cadcraft_render::Sheet>,
) {
fn paint_pointer_overlay(frame: &mut CanvasPaint<'_>, paper_rect: Option<Rect>, surround: Color32, sheet: Option<cadcraft_render::Sheet>) {
let app = &mut *frame.app;
let ui = &mut *frame.ui;
let painter = frame.painter;
@@ -563,7 +558,8 @@ fn paint_pointer_overlay(
// Use the painted sheet even in MSPACE, where the editing transform follows a
// model viewport. The whole cursor takes one colour from its centre.
let ink = paper_rect.map_or(t.crosshair, |paper| crate::theme::crosshair_color(if paper.contains(hp) { t.paper } else { surround }));
draw_crosshair(app, painter, rect, hp, selecting, ink);
let picking = app.session.picking_objects() && app.session.pending_window.is_none();
draw_crosshair(app, painter, rect, hp, picking, ink);
if app.canvas.cycle_badge && app.canvas.cycle.is_none() {
cycle_badge(painter, hp);
}
@@ -611,12 +607,12 @@ fn handle_double_click(app: &mut CadApp, ctx: DoubleClickContext<'_>) -> Option<
if !in_active {
app.canvas.hot_grips.clear();
app.session.pending_window = None;
app.canvas.drag_window = false;
app.canvas.press = None;
if app.run("mspace", serde_json::json!({"at": [pp.x, pp.y]})).is_err() && active_viewport.is_some() {
let _ = app.run("pspace", serde_json::json!({}));
}
app.session.pending_window = None;
app.canvas.drag_window = false;
app.canvas.press = None;
app.canvas.list = None;
return None;
}
@@ -657,43 +653,7 @@ fn update_canvas_cursor(
) -> (Option<Vec2>, Option<crate::dyninput::Frame>) {
let raw_world = hover.filter(|_| inside).map(|p| xf.to_world(p));
let dyn_frame = crate::cmdline::dyn_frame(app);
if let Some(w) = raw_world {
let mut eff = effective_point(app, w, xf, ui.ctx());
// A locked Dynamic Input value (`40,` or `40<` typed) holds the cursor and overrides snaps.
if let Some(f) = dyn_frame
&& let Some(e) = crate::dyninput::parse(&app.cmd.buffer, &f)
&& e.first_locked().is_some()
{
eff = crate::dyninput::constrain(&e, &f, eff, app.cmd.second_locked());
app.canvas.snap = None;
app.canvas.track = None;
}
// Grip dimensional input: typed lengths and angles hold the grip and override snaps.
let grip_held = crate::grip_dyn::constrain(app, eff);
if let Some(q) = grip_held {
eff = q;
app.canvas.snap = None;
app.canvas.track = None;
}
app.canvas.cursor = Some(eff);
app.session.cursor = eff;
app.session.cursor_deferred = app.canvas.snap.and_then(|h| h.deferred);
// Typed or menu snap overrides (END, NON…) and Tab cycling; a locked Dynamic Input value wins.
if dyn_frame.and_then(|f| crate::dyninput::parse(&app.cmd.buffer, &f)).is_none_or(|e| e.first_locked().is_none()) {
override_cursor(app, w, xf);
}
// Typed grip dimensions win over snap overrides too.
if let Some(q) = grip_held {
app.canvas.cursor = Some(q);
app.session.cursor = q;
app.canvas.snap = None;
app.session.cursor_deferred = None;
}
} else {
app.canvas.cursor = None;
app.canvas.snap = None;
app.session.cursor_deferred = None;
}
track_cursor(app, raw_world, xf, ui.ctx(), dyn_frame);
(raw_world, dyn_frame)
}
@@ -743,48 +703,91 @@ fn update_hover(app: &mut CadApp, ui: &egui::Ui, inside: bool, hover_pos: Option
}
}
struct PromptClickContext<'a> {
struct PressContext {
rect: Rect,
xf: Xf,
inside: bool,
middle_down: bool,
primary_clicked: bool,
response: &'a egui::Response,
mods: egui::Modifiers,
}
fn collect_prompt_clicks(app: &mut CadApp, ui: &egui::Ui, context: PromptClickContext<'_>) -> bool {
// egui drops a click whose button comes up a few pixels from where it went down (a drag to it),
// and eframe hands a slow frame's clicks over together, which egui reports as one.
let point_prompt = app.session.current_prompt().is_some_and(|p| cadcraft_engine::pointmod::accepts(&p))
&& app.session.pending_window.is_none()
&& !app.session.realtime_zoom_active();
let pressed_primary = context.primary_clicked || (point_prompt && context.response.drag_stopped_by(egui::PointerButton::Primary));
if point_prompt && context.inside && pressed_primary && !context.middle_down && app.cmd.options.is_none() && app.cmd.buffer.is_empty() {
let releases: Vec<egui::Pos2> = ui.input(|i| {
i.events
.iter()
.filter_map(|e| match e {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(*pos),
_ => None,
})
.collect()
});
// The last one is placed below, at the cursor, like any click.
if let Some((_, earlier)) = releases.split_last() {
for pos in earlier.iter().filter(|p| context.rect.contains(**p)) {
let w = effective_point(app, context.xf.to_world(*pos), &context.xf, ui.ctx());
let result = match app.canvas.snap {
Some(hit) => app.session.input_snapped(hit),
None => app.session.input(Input::Point(w)),
};
if let Err(e) = result {
app.session.echo(e.to_string());
/// Clicks count when the button goes down, where it went down, however fast the mouse moves
/// (#1001, #815): each press among this frame's events places its point, picks its object or sets a
/// selection window's corner at once. What the pointer does while the button is held only decides
/// whether the press becomes a drag ([`press`]): a drag closes the window its press opened where
/// the button comes up; after a click the window waits for the next press. A press on a grip
/// (idle) clicks the grip when the button comes up near it, however long it was held (#2813).
/// Presses while ZOOM Realtime runs are left to the clicks in [`show`]. Returns whether a press
/// handled here was released this frame (its click must not count again).
fn handle_presses(app: &mut CadApp, ui: &egui::Ui, context: &PressContext) -> bool {
let PressContext { rect, xf, inside, middle_down, mods } = *context;
let (steps, now, primary_down) = ui.input(|i| (press::steps(&i.events), i.time, i.pointer.primary_down()));
let mut click_used = false;
for step in steps {
match step {
press::Step::Down(pos, m) => {
app.canvas.press = None;
if !inside || !rect.contains(pos) || middle_down {
continue;
}
// A press on the Dynamic Input options menu is the menu's (picked on release);
// elsewhere it closes the menu and counts as usual.
if app.cmd.options.is_some() {
if app.cmd.option_at(pos).is_some() {
continue;
}
app.cmd.options = None;
}
// Selection cycling: the press picks a row of the open list, or opens the list over
// overlapping objects (#1149). Its release must not count again.
if cycle_click(app, &xf, Some(pos), Some(xf.to_world(pos)), m.shift) {
app.canvas.press = Some(press::Press::new(pos, false));
continue;
}
if press_takes(app, &xf, pos) {
let opened = press_at(app, &xf, ui.ctx(), pos, m);
app.canvas.press = Some(press::Press::new(pos, opened));
} else if !app.session.realtime_zoom_active() {
// A grip with no command running: clicked when the button comes up. egui
// calls a press held longer than 0.8 s a drag, and a slow drawing's frames
// can make an ordinary click that long (#2813).
app.canvas.press = Some(press::Press::on_grip(pos, m));
}
}
press::Step::Move(pos) => {
if let Some(p) = &mut app.canvas.press {
p.moved(pos, now);
}
}
press::Step::Up(pos) => {
let Some(mut p) = app.canvas.press.take() else { continue };
click_used = true;
if p.is_on_grip() {
if let Some((at, m)) = p.grip_click(pos) {
if let Some(g) = crate::dyngrips::at(app, &xf, Some(at)) {
crate::dyngrips::click(app, g);
} else if let Some(g) = grip_at(app, &xf, Some(at)) {
click_grip(app, g, m.shift);
}
}
continue;
}
// PICKDRAG off: a window takes two clicks, a drag doesn't close it (#1032).
if app.session.settings.pickdrag && p.released_as_drag(pos, now) && p.opened_window && app.session.pending_window.is_some() {
let end = xf.to_world(pos);
let done = if app.session.prompting() { app.session.input(Input::Point(end)) } else { app.session.idle_click(end, mods.shift) };
if let Err(e) = done {
app.session.echo(e.to_string());
}
}
}
}
}
pressed_primary
if !primary_down {
// The button came up where we didn't see it (outside the window, say).
app.canvas.press = None;
}
click_used
}
/// Whether a quick right-click cancels the running command instead of acting as Enter: it asks for
@@ -872,8 +875,21 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
return;
};
let pressed_primary =
collect_prompt_clicks(app, ui, PromptClickContext { rect, xf, inside, middle_down, primary_clicked: pressed_primary, response: &resp });
// Selection cycling's list closes when the prompt, the drawing or the view changes.
let key: CycleKey = (
app.session.running.as_ref().map(|r| r.id.clone()),
app.session.current_prompt().map(|p| p.message),
app.session.state().map_or(0, |st| st.uid),
app.session.state().map_or(0, |st| st.revision),
xf.center,
xf.scale,
);
if app.canvas.cycle_key.as_ref() != Some(&key) {
app.canvas.cycle = None;
app.canvas.hover_cycle = None;
app.canvas.cycle_key = Some(key);
}
let click_used = handle_presses(app, ui, &PressContext { rect, xf, inside, middle_down, mods });
let (raw_world, dyn_frame) = update_canvas_cursor(app, ui, &xf, inside, hover_pos);
@@ -893,26 +909,14 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
let idle_dbl = dbl_primary && app.session.running.is_none();
if idle_dbl {
app.session.pending_window = None;
app.canvas.drag_window = false;
app.canvas.press = None;
}
let pressed_primary = pressed_primary && !picked && !hatch_dialog && !idle_dbl;
let key: CycleKey = (
app.session.running.as_ref().map(|r| r.id.clone()),
app.session.current_prompt().map(|p| p.message),
app.session.state().map_or(0, |st| st.uid),
app.session.state().map_or(0, |st| st.revision),
xf.center,
xf.scale,
);
if app.canvas.cycle_key.as_ref() != Some(&key) {
app.canvas.cycle = None;
app.canvas.hover_cycle = None;
app.canvas.cycle_key = Some(key);
}
let cycled = pressed_primary && !middle_down && cycle_click(app, &xf, hover_pos, raw_world.filter(|_| inside), mods.shift);
// Clicks.
let cycled = pressed_primary && !click_used && !middle_down && cycle_click(app, &xf, hover_pos, raw_world.filter(|_| inside), mods.shift);
// Clicks the presses above left alone: on grips, and during ZOOM Realtime.
if inside
&& pressed_primary
&& !click_used
&& !middle_down
&& !cycled
&& let Some(p) = app.canvas.cursor
@@ -944,58 +948,31 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
app.session.echo(e.to_string());
}
}
// Press-and-drag selection window (PICKDRAG = 2; click-click still works): a drag
// that starts while objects are being selected opens a window where the button went down,
// and letting go closes it. Drags on grips and drags while drawing are left alone.
if !app.session.settings.pickdrag {
app.canvas.drag_window = false;
}
if app.session.settings.pickdrag
&& resp.drag_started_by(egui::PointerButton::Primary)
&& !middle_down
&& app.canvas.cycle.is_none()
&& app.session.pending_window.is_none()
&& let Some(origin) = ui.input(|i| i.pointer.press_origin())
&& rect.contains(origin)
&& grip_at(app, &xf, Some(origin)).is_none()
&& crate::dyngrips::at(app, &xf, Some(origin)).is_none()
{
app.canvas.drag_window = app.session.begin_window(xf.to_world(origin));
}
if app.canvas.drag_window && resp.drag_stopped_by(egui::PointerButton::Primary) {
app.canvas.drag_window = false;
if app.session.pending_window.is_some()
&& let Some(end) = ui.input(|i| i.pointer.interact_pos())
{
let end = xf.to_world(end);
let done = if app.session.prompting() { app.session.input(Input::Point(end)) } else { app.session.idle_click(end, mods.shift) };
if let Err(e) = done {
app.session.echo(e.to_string());
}
}
}
// Right-click acts as Enter while a command runs (the classic CAD default; held, it opens the
// command menu); otherwise it opens the shortcut menu (Repeat, Clipboard, …).
// Shift/Ctrl+right-click opens the object snap menu.
// A quick right-click is Enter (the classic CAD default): it enters what was typed, ends the
// input of a running command, and between commands repeats the last one. Held, it opens the
// command menu or the shortcut menu (Repeat, Clipboard, …). Shift/Ctrl+right-click opens the
// object snap menu.
let idle = !app.session.prompting();
if inside && pressed_secondary {
app.canvas.snap_menu = mods.shift || mods.ctrl;
}
if crate::context_menu::in_command(app, ui, inside, pressed_secondary) {
if right_click_cancels_placing(app) {
crate::cmdline::escape(app);
} else {
let _ = app.session.input(Input::Enter);
}
}
// Right-click on a grip with options (polyline vertex, line end…) opens the grip menu.
if inside && pressed_secondary && idle && !app.canvas.snap_menu {
app.canvas.grip_menu = grip_at(app, &xf, hover_pos).filter(|g| !grip_options(app, *g).is_empty());
}
let enter = crate::context_menu::in_command(app, ui, inside, pressed_secondary);
if enter {
if right_click_cancels_placing(app) {
crate::cmdline::escape(app);
} else {
// As the Enter key does: what was typed (`rec`, `@10,0`), or Enter when nothing was.
crate::cmdline::submit(app);
}
}
crate::dyngrips::menu(app, ui.ctx(), &xf);
if idle && !app.canvas.snap_menu && app.canvas.grip_menu.is_some() {
grip_menu(app, &resp);
} else if idle || app.canvas.snap_menu {
} else if (idle && !enter) || app.canvas.snap_menu {
crate::context_menu::show(app, &resp);
}
@@ -1021,6 +998,95 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
});
}
/// Put the cursor at `raw` (world, `None` off the canvas): snaps, ortho and polar, a locked
/// Dynamic Input value and typed grip dimensions applied (`app.canvas.cursor`, `.snap`, `.track`).
fn track_cursor(app: &mut CadApp, raw: Option<Vec2>, xf: &Xf, ctx: &egui::Context, dyn_frame: Option<crate::dyninput::Frame>) {
if let Some(w) = raw {
let mut eff = effective_point(app, w, xf, ctx);
// A locked Dynamic Input value (`40,` or `40<` typed) holds the cursor and overrides snaps.
if let Some(f) = dyn_frame
&& let Some(e) = crate::dyninput::parse(&app.cmd.buffer, &f)
&& e.first_locked().is_some()
{
eff = crate::dyninput::constrain(&e, &f, eff, app.cmd.second_locked());
app.canvas.snap = None;
app.canvas.track = None;
}
// Grip dimensional input: typed lengths and angles hold the grip and override snaps.
let grip_held = crate::grip_dyn::constrain(app, eff);
if let Some(q) = grip_held {
eff = q;
app.canvas.snap = None;
app.canvas.track = None;
}
app.canvas.cursor = Some(eff);
app.session.cursor = eff;
app.session.cursor_deferred = app.canvas.snap.and_then(|h| h.deferred);
// Typed or menu snap overrides (END, NON…) and Tab cycling; a locked Dynamic Input value wins.
if dyn_frame.and_then(|f| crate::dyninput::parse(&app.cmd.buffer, &f)).is_none_or(|e| e.first_locked().is_none()) {
override_cursor(app, w, xf);
}
// Typed grip dimensions win over snap overrides too.
if let Some(q) = grip_held {
app.canvas.cursor = Some(q);
app.session.cursor = q;
app.canvas.snap = None;
app.session.cursor_deferred = None;
}
} else {
app.canvas.cursor = None;
app.canvas.snap = None;
app.session.cursor_deferred = None;
}
}
/// Whether the press at `pos` is acted on when the button goes down ([`press_at`]): at any prompt
/// and on the drawing with no command running. Grips (with no command running) and ZOOM Realtime
/// keep their clicks.
fn press_takes(app: &mut CadApp, xf: &Xf, pos: Pos2) -> bool {
if app.session.realtime_zoom_active() {
return false;
}
if app.session.prompting() {
return true;
}
crate::dyngrips::at(app, xf, Some(pos)).is_none() && grip_at(app, xf, Some(pos)).is_none()
}
/// Act on a press at `pos`: at a prompt the point goes in (snapped as the cursor would be there);
/// with no command running it picks the object there or sets a selection window's corner.
/// Returns whether the press opened a selection window.
fn press_at(app: &mut CadApp, xf: &Xf, ctx: &egui::Context, pos: Pos2, mods: egui::Modifiers) -> bool {
let had_window = app.session.pending_window.is_some();
let raw = xf.to_world(pos);
let dyn_frame = crate::cmdline::dyn_frame(app);
track_cursor(app, Some(raw), xf, ctx, dyn_frame);
let Some(p) = app.canvas.cursor else { return false };
if app.session.prompting() {
// Ctrl held while picking the point of a grip edit makes copies (the Copy option).
if mods.ctrl && app.session.running.as_ref().is_some_and(|r| r.id == "grip") {
let _ = app.session.input(Input::Keyword("Copy".into()));
}
// Clicking places the point; a value typed into the Dynamic Input boxes is used up.
if let Some(f) = dyn_frame
&& crate::dyninput::parse(&app.cmd.buffer, &f).is_some()
{
app.cmd.buffer.clear();
}
// Preserve a snap's viewport origin for DIST, and its deferred curve where needed.
let result = match app.canvas.snap {
Some(hit) => app.session.input_snapped(hit),
None => app.session.input(Input::Point(p)),
};
if let Err(e) = result {
app.session.echo(e.to_string());
}
} else if let Err(e) = app.session.idle_click(raw, mods.shift) {
app.session.echo(e.to_string());
}
!had_window && app.session.pending_window.is_some()
}
fn paint_canvas(frame: CanvasPaint<'_>) {
let CanvasPaint {
app,
@@ -1041,7 +1107,6 @@ fn paint_canvas(frame: CanvasPaint<'_>) {
raw_world,
} = frame;
let scale = xf.scale;
let selecting = app.session.previews_selection();
painter.rect_filled(rect, 0.0, t.canvas);
let t0 = crate::now_ms();
let mut views = vec![(xf_paper.world_bounds(), 1.0 / xf_paper.scale)];
@@ -1223,7 +1288,6 @@ fn paint_canvas(frame: CanvasPaint<'_>) {
},
paper_rect,
surround,
selecting,
sheet,
);
}
+21 -12
View File
@@ -212,28 +212,37 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
app.session.cursor_deferred = app.canvas.snap.and_then(|h| h.deferred);
}
/// Half the side of the pick box (`PICKBOX * 1.5` screen points), or `None` when `PICKBOX` is 0.
fn pickbox_half(pickbox: f64) -> Option<f32> {
let half = (pickbox * 1.5) as f32;
(half.is_finite() && half >= 1.0).then_some(half)
}
/// Draws the canvas cursor at `at`: the full crosshair with pickbox when idle, crosshair lines
/// only at point prompts, and the pickbox square alone at command object-selection prompts.
pub(super) fn draw_crosshair(app: &CadApp, p: &egui::Painter, rect: Rect, at: Pos2, pickbox: bool, ink: Color32) {
let st = Stroke::new(1.0, ink);
let len = (rect.height() * app.session.settings.cursorsize as f32 / 100.0).max(12.0);
let pb = if pickbox { pickbox_half(app.session.settings.pickbox) } else { None };
let picking_in_cmd = pickbox && app.session.current_prompt().is_some_and(|pr| pr.picks_objects());
let pb = if pickbox { pickbox_half(app.session.settings.pickbox).or(picking_in_cmd.then_some(1.5)) } else { None };
let gap = pb.unwrap_or(0.0);
// Along the isometric plane's axes in isometric drafting.
if app.session.settings.isodraft {
for a in cadcraft_engine::snap::iso::cursor_axes(&app.session.settings) {
let dir = vec2(a.cos() as f32, -(a.sin() as f32));
p.line_segment([at - dir * len, at - dir * gap], st);
p.line_segment([at + dir * gap, at + dir * len], st);
// At a command prompt that selects objects, AutoCAD shows only the pickbox square (no
// crosshair lines); when idle or once a selection window corner is picked, the crosshair
// lines are drawn.
if !picking_in_cmd {
// Along the isometric plane's axes in isometric drafting.
if app.session.settings.isodraft {
for a in cadcraft_engine::snap::iso::cursor_axes(&app.session.settings) {
let dir = vec2(a.cos() as f32, -(a.sin() as f32));
p.line_segment([at - dir * len, at - dir * gap], st);
p.line_segment([at + dir * gap, at + dir * len], st);
}
} else {
p.line_segment([pos2(at.x - len, at.y), pos2(at.x - gap, at.y)], st);
p.line_segment([pos2(at.x + gap, at.y), pos2(at.x + len, at.y)], st);
p.line_segment([pos2(at.x, at.y - len), pos2(at.x, at.y - gap)], st);
p.line_segment([pos2(at.x, at.y + gap), pos2(at.x, at.y + len)], st);
}
} else {
p.line_segment([pos2(at.x - len, at.y), pos2(at.x - gap, at.y)], st);
p.line_segment([pos2(at.x + gap, at.y), pos2(at.x + len, at.y)], st);
p.line_segment([pos2(at.x, at.y - len), pos2(at.x, at.y - gap)], st);
p.line_segment([pos2(at.x, at.y + gap), pos2(at.x, at.y + len)], st);
}
if let Some(pb) = pb {
p.rect_stroke(Rect::from_center_size(at, vec2(pb * 2.0, pb * 2.0)), 0.0, st, egui::StrokeKind::Middle);
+167
View File
@@ -0,0 +1,167 @@
//! Press-first clicks (#1001): a click on the canvas counts when the primary button goes down, at
//! the spot where it went down, however fast the mouse is moving. Where the pointer goes while the
//! button is held only decides whether the press also becomes a drag:
//!
//! - holding still, or staying within [`TOLERANCE`] of the press, never makes a drag;
//! - once the pointer leaves the tolerance a timer starts; a button still down [`DRAG_DELAY`]
//! later is a drag (a selection window the press opened closes where the button comes up);
//! - a button that comes up sooner was a click (the window waits for the next press).
//!
//! The timer starts on leaving the tolerance, not on the press: pressing, holding still and then
//! moving and letting go quickly is still a click, as in AutoCAD.
//!
//! A press on a grip with no command running ([`Press::on_grip`]) is the exception: the grip is
//! clicked when the button comes up within [`TOLERANCE`] of the press, however long it was held
//! (#2813), and a drag from it does nothing.
use egui::{Modifiers, Pos2};
/// How far (points) the pointer may wander from the press before the timer starts.
pub(crate) const TOLERANCE: f32 = 6.0;
/// How long (seconds) the button must stay down after the pointer left [`TOLERANCE`] for the
/// press to be a drag.
pub(crate) const DRAG_DELAY: f64 = 0.25;
/// A primary-button press being held.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Press {
origin: Pos2,
/// When the pointer first went further than [`TOLERANCE`] from `origin` (seconds).
left_at: Option<f64>,
/// The press opened a selection window (set its first corner).
pub(crate) opened_window: bool,
/// The press went down on a grip with no command running, with these modifiers: it is a click
/// on the grip if the button comes up near it ([`Self::grip_click`]).
on_grip: Option<Modifiers>,
}
impl Press {
pub(crate) fn new(origin: Pos2, opened_window: bool) -> Self {
Self { origin, left_at: None, opened_window, on_grip: None }
}
/// A press on a grip with no command running, acted on when the button comes up.
pub(crate) fn on_grip(origin: Pos2, modifiers: Modifiers) -> Self {
Self { origin, left_at: None, opened_window: false, on_grip: Some(modifiers) }
}
/// For a press on a grip ([`Self::on_grip`]) whose button came up at `pos`: `Some` (where it
/// went down, the modifiers then) when that is a click on the grip, within [`TOLERANCE`] of the
/// press however long the button was held; `None` for a drag from it or a press elsewhere.
pub(crate) fn grip_click(&self, pos: Pos2) -> Option<(Pos2, Modifiers)> {
let modifiers = self.on_grip?;
(pos.distance(self.origin) <= TOLERANCE).then_some((self.origin, modifiers))
}
/// Whether the press went down on a grip ([`Self::on_grip`]).
pub(crate) fn is_on_grip(&self) -> bool {
self.on_grip.is_some()
}
/// The pointer is at `pos` at time `now`.
pub(crate) fn moved(&mut self, pos: Pos2, now: f64) {
if self.left_at.is_none() && pos.distance(self.origin) > TOLERANCE {
self.left_at = Some(now);
}
}
/// Whether the button coming up at `pos` at time `now` ends a drag rather than a click.
pub(crate) fn released_as_drag(&mut self, pos: Pos2, now: f64) -> bool {
self.moved(pos, now);
self.left_at.is_some_and(|t| now - t >= DRAG_DELAY)
}
}
/// A primary-button event of the frame, in order.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Step {
Down(Pos2, Modifiers),
Move(Pos2),
Up(Pos2),
}
/// The primary-button presses, pointer moves and releases among a frame's events, in order. A slow
/// frame can hold several clicks; each press is its own step (#815).
pub(crate) fn steps(events: &[egui::Event]) -> Vec<Step> {
events
.iter()
.filter_map(|e| match *e {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers } => Some(Step::Down(pos, modifiers)),
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(Step::Up(pos)),
egui::Event::PointerMoved(pos) => Some(Step::Move(pos)),
_ => None,
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use egui::pos2;
#[test]
fn staying_within_the_tolerance_is_a_click_however_long_the_button_is_held() {
let mut p = Press::new(pos2(100.0, 100.0), true);
p.moved(pos2(104.0, 103.0), 0.5);
assert!(!p.released_as_drag(pos2(105.0, 100.0), 5.0));
}
#[test]
fn letting_go_soon_after_leaving_the_tolerance_is_a_click() {
let mut p = Press::new(pos2(100.0, 100.0), true);
p.moved(pos2(112.0, 100.0), 1.0);
assert!(!p.released_as_drag(pos2(130.0, 100.0), 1.0 + DRAG_DELAY / 2.0));
}
#[test]
fn holding_still_then_moving_and_letting_go_quickly_is_a_click() {
// The timer starts when the pointer leaves the tolerance, not when the button goes down.
let mut p = Press::new(pos2(100.0, 100.0), true);
p.moved(pos2(101.0, 100.0), 2.0);
assert!(!p.released_as_drag(pos2(140.0, 100.0), 2.05));
}
#[test]
fn a_button_still_down_after_the_delay_is_a_drag() {
let mut p = Press::new(pos2(100.0, 100.0), true);
p.moved(pos2(110.0, 100.0), 1.0);
p.moved(pos2(200.0, 150.0), 1.1);
assert!(p.released_as_drag(pos2(250.0, 160.0), 1.0 + DRAG_DELAY));
}
#[test]
fn a_grip_press_is_a_click_where_it_went_down_only_when_let_go_near_it() {
let p = Press::on_grip(pos2(100.0, 100.0), Modifiers::SHIFT);
assert!(p.is_on_grip());
assert_eq!(p.grip_click(pos2(103.0, 104.0)), Some((pos2(100.0, 100.0), Modifiers::SHIFT)));
assert_eq!(p.grip_click(pos2(120.0, 100.0)), None, "a drag from the grip is no click");
let elsewhere = Press::new(pos2(100.0, 100.0), false);
assert!(!elsewhere.is_on_grip());
assert_eq!(elsewhere.grip_click(pos2(100.0, 100.0)), None);
}
#[test]
fn steps_keep_every_press_of_a_slow_frame_in_order() {
let at = |x| pos2(x, 10.0);
let button =
|x, pressed| egui::Event::PointerButton { pos: at(x), button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
let events = vec![
egui::Event::PointerMoved(at(1.0)),
button(1.0, true),
button(1.0, false),
egui::Event::PointerButton { pos: at(2.0), button: egui::PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
button(3.0, true),
button(3.0, false),
];
assert_eq!(
steps(&events),
vec![
Step::Move(at(1.0)),
Step::Down(at(1.0), Modifiers::NONE),
Step::Up(at(1.0)),
Step::Down(at(3.0), Modifiers::NONE),
Step::Up(at(3.0))
]
);
}
}
+60
View File
@@ -249,6 +249,66 @@ fn clicking_a_hot_grip_leaves_hidden_objects_out_of_the_stretch() {
assert_eq!(app.canvas.hot_grips, vec![(shown, 0)], "the hidden object's grip must leave the hot set");
}
/// Verifies that command object-selection prompts draw only the pickbox square while idle and
/// point prompts draw the crosshair lines.
#[test]
fn cursor_shows_pickbox_only_at_command_object_selection_prompts() {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
let at = pos2(400.0, 300.0);
let paint = |app: &CadApp| {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.painter_at(rect);
let picking = app.session.picking_objects() && app.session.pending_window.is_none();
draw_crosshair(app, &painter, rect, at, picking, Color32::WHITE);
});
out.textures_delta.clear();
let mut lines = 0usize;
let mut rects = 0usize;
for clipped in &out.shapes {
match &clipped.shape {
Shape::LineSegment { .. } => lines += 1,
Shape::Rect(r) if r.rect.center() == at => rects += 1,
_ => {}
}
}
(lines, rects)
};
// 1. Idle with PICKFIRST on: crosshair lines (4 segments) + pickbox square (1 rect).
assert_eq!(paint(&app), (4, 1), "idle with PICKFIRST on");
// 2. Idle with SELECTIONPREVIEW = 0: pickbox still drawn while PICKFIRST is on.
app.session.settings.selectionpreview = 0;
assert_eq!(paint(&app), (4, 1), "idle with SELECTIONPREVIEW = 0");
app.session.settings.selectionpreview = 3;
// 3. Command asking for points (LINE): crosshair lines only (4 segments, 0 rects).
app.session.cmdline("line").unwrap();
assert_eq!(paint(&app), (4, 0), "point prompt (LINE)");
app.session.cancel();
// 4. Command asking to select objects (ERASE): pickbox square only (0 segments, 1 rect).
app.session.cmdline("erase").unwrap();
assert_eq!(paint(&app), (0, 1), "object selection prompt (ERASE)");
// 5. Even when PICKBOX = 0, a command object-selection prompt keeps a minimal visible pickbox.
app.session.settings.pickbox = 0.0;
assert_eq!(paint(&app), (0, 1), "object selection prompt with PICKBOX = 0");
app.session.settings.pickbox = 3.0;
// 6. While picking the second corner of a selection window, the crosshair lines return.
app.session.pending_window = Some(cadcraft_engine::PendingWindow { corner: Vec2::ZERO, during_command: true });
assert_eq!(paint(&app), (4, 0), "selection window second corner");
app.session.pending_window = None;
app.session.cancel();
// 7. STRETCH's "Remove objects" prompt also draws the pickbox-only cursor.
app.session.cmdline("stretch r").unwrap();
assert_eq!(paint(&app), (0, 1), "STRETCH Remove objects prompt");
}
/// Makes the layer "Hidden" and, on Layout1, two viewports over the model: the first freezes
/// "Hidden", the second freezes nothing. The app is left in paper space.
fn viewports_freezing_hidden(app: &mut CadApp) -> (String, String) {
+26 -14
View File
@@ -1,6 +1,7 @@
//! The canvas's right-click menus, after AutoCAD's shortcut menus:
//!
//! - **No command running** ([`entries`]): Repeat the last command, Recent Commands, the
//! - **No command running** ([`entries`], opened by holding the button: a quick right-click is
//! Enter, which repeats the last command): Repeat the last command, Recent Commands, the
//! Clipboard and Isolate; with a selection the editing commands, Draw Order, Group, the edit
//! commands of the selected object type, Select Similar and Deselect All; then Undo/Redo,
//! Pan/Zoom, Quick Select, Find, Properties and Options.
@@ -10,8 +11,8 @@
//! Preferences ▸ Right-Click Customization sets how long, `rightClickDuration`). With that turned
//! off (`timeSensitiveRightClick`), Command mode says what a right-click does
//! (`rightClickCommand`: the menu, Enter, or the menu only when the prompt has options).
//! `rightClickDefault` and `rightClickEdit` can make a right-click with no command running
//! repeat the last command instead of opening the menu.
//! With it off, `rightClickDefault` and `rightClickEdit` can make a right-click with no command
//! running repeat the last command instead of opening the menu.
//! - **Shift/Ctrl+right-click** ([`snap_entries`]): the object snap menu. Its items type the point
//! modifiers and snap overrides (`_from`, `_endp`, `_non`…) at the current point prompt.
//!
@@ -387,13 +388,16 @@ pub fn groups_ui(ui: &mut egui::Ui, groups: &[Vec<Entry>], clicked: &mut Option<
pub fn show(app: &mut CadApp, resp: &egui::Response) {
let mut clicked = None;
let snap = app.canvas.snap_menu;
// Right-Click Customization: with nothing selected (Default mode) or a selection (Edit mode),
// a right-click may repeat the last command instead of opening the menu. With no last command
// yet, it opens the menu.
// Right-Click Customization: with the time-sensitive right-click off and nothing selected
// (Default mode) or a selection (Edit mode), a right-click may repeat the last command instead
// of opening the menu. With no last command yet, it opens the menu. With the time-sensitive
// right-click on, a quick click is already Enter ([`in_command`]) and a longer one is this
// menu, as in AutoCAD.
let o = &app.options;
let mode =
if o.right_click_default == o.right_click_edit || app.session.selection().is_empty() { o.right_click_default } else { o.right_click_edit };
if !snap
&& !o.time_sensitive_right_click
&& mode == crate::options::IdleClick::Repeat
&& let Some(last) = app.session.last_command.clone()
{
@@ -417,13 +421,15 @@ pub fn show(app: &mut CadApp, resp: &egui::Response) {
#[derive(Clone, Copy, Default)]
struct Press(f64, egui::Pos2);
/// The canvas's right button while a command runs (Shift/Ctrl+right-click is the snap menu's): a
/// quick click is Enter — returns `true` when the caller should send it — and a click held for
/// OPTIONS `rightClickDuration` opens the command menu ([`command_entries`]) at the pointer. With
/// the time-sensitive right-click turned off, `rightClickCommand` says whether a click opens the
/// menu or is Enter. Call it every frame
/// with whether the pointer is on the canvas and whether a right-click ended there; it also shows
/// the menu while it is open.
/// The canvas's right button (Shift/Ctrl+right-click is the snap menu's). With the time-sensitive
/// right-click on, a quick click is Enter — returns `true` when the caller should send it; between
/// commands that runs what was typed or repeats the last command — and while a command runs a
/// click held for OPTIONS `rightClickDuration` opens the command menu ([`command_entries`]) at the
/// pointer (between commands a held click is left to the caller's shortcut menu). With it turned
/// off, `rightClickCommand` says whether a click while a command runs opens the menu or is Enter,
/// and between commands the caller follows `rightClickDefault` and `rightClickEdit`. Call it every
/// frame with whether the pointer is on the canvas and whether a right-click ended there; it also
/// shows the menu while it is open.
pub fn in_command(app: &mut CadApp, ui: &egui::Ui, inside: bool, right_clicked: bool) -> bool {
let ctx = ui.ctx().clone();
let press_id = egui::Id::unique("cc_command_menu_press");
@@ -448,15 +454,21 @@ pub fn in_command(app: &mut CadApp, ui: &egui::Ui, inside: bool, right_clicked:
};
let hold = f64::from(o.right_click_hold_ms) / 1000.0;
let mut open = false;
let mut quick = false;
if released && let Some(Press(t0, p0)) = ctx.data_mut(|d| d.remove_temp::<Press>(press_id)) {
// A drag isn't a click; a click held long enough asks for the menu.
let still = pos.is_some_and(|p| p.distance(p0) <= 6.0);
let held = if timed { now - t0 >= hold } else { menu };
open = running && still && held;
quick = !held;
}
let enter = running && inside && right_clicked && !open && (timed || !menu);
if !running {
return false;
// Between commands a quick click is Enter too (as in AutoCAD): it runs the typed command,
// or repeats the last one; held, it opens the shortcut menu. A grip with options keeps
// its menu.
let something = !app.cmd.buffer.trim().is_empty() || app.session.last_command.is_some();
return timed && quick && inside && right_clicked && !app.canvas.snap_menu && app.canvas.grip_menu.is_none() && something;
}
let mut clicked = None;
let popup = egui::Popup::new(popup_id, ctx, egui::PopupAnchor::PointerFixed, ui.layer_id())
+8 -5
View File
@@ -16,9 +16,9 @@
//! | `SAVETIME` | minutes between automatic saves, 0–600 (0: off) |
//! | `SAVEFILEPATH` | the folder automatic saves go to |
//! | `ISAVEBAK` | 1: saving over a drawing keeps the previous file as `<name>.bak` (default); 0: no backup |
//! | `timeSensitiveRightClick` | while a command runs, a quick right-click is Enter and holding the button opens the shortcut menu (default); `false`: `rightClickCommand` decides |
//! | `timeSensitiveRightClick` | a quick right-click is Enter (between commands it runs what was typed, or repeats the last command) and holding the button opens the shortcut menu (default); `false`: `rightClickCommand` decides while a command runs, `rightClickDefault` and `rightClickEdit` between commands |
//! | `rightClickDuration` | how long the right button is held to open the menu while a command runs, 100–2000 ms (250) |
//! | `rightClickDefault`, `rightClickEdit` | a right-click with no command running and nothing (`Default`) or something (`Edit`) selected: `"menu"` (the shortcut menu, default) or `"repeat"` (the last command) |
//! | `rightClickDefault`, `rightClickEdit` | with the time-sensitive right-click off, a right-click with no command running and nothing (`Default`) or something (`Edit`) selected: `"menu"` (the shortcut menu, default) or `"repeat"` (the last command) |
//! | `rightClickCommand` | a right-click while a command runs, with the time-sensitive right-click off: `"menu"` (default), `"enter"`, or `"menuWithOptions"` (the menu when the prompt has options, else Enter) |
//! | `systemCursor` | keep the system cursor visible over the drawing area |
//! | `historyLines` | command-line history lines, 0–12 |
@@ -139,13 +139,16 @@ pub struct UiOptions {
pub snap_marker_size: f32,
/// The selection highlight colour; `None` keeps the theme's.
pub selection_color: Option<Color32>,
/// While a command runs: a quick right-click is Enter and a held one opens the shortcut menu
/// (AutoCAD's time-sensitive right-click). Off: [`Self::right_click_command`] decides.
/// A quick right-click is Enter and a held one opens the shortcut menu (AutoCAD's
/// time-sensitive right-click). Between commands that Enter runs what was typed, or repeats
/// the last command; with neither, the click opens the shortcut menu. Off:
/// [`Self::right_click_command`] decides while a command runs, and [`Self::right_click_default`]
/// and [`Self::right_click_edit`] between commands.
pub time_sensitive_right_click: bool,
/// How long the right button is held to open the menu while a command runs, in milliseconds.
pub right_click_hold_ms: u32,
/// A right-click with no command running and nothing selected (Default mode) or a selection
/// (Edit mode).
/// (Edit mode), with the time-sensitive right-click off.
pub right_click_default: IdleClick,
pub right_click_edit: IdleClick,
/// A right-click while a command runs, with the time-sensitive right-click off.
+26 -14
View File
@@ -615,23 +615,35 @@ fn right_click_window(o: &super::UiOptions, ctx: &egui::Context, open: &mut bool
ui.label(crate::tl!("milliseconds"));
});
hint(ui, crate::tl!("While a command runs, a quick click is Enter and a longer click opens the shortcut menu."));
hint(ui, crate::tl!("With no command running, a quick click repeats the last command or runs what was typed."));
});
ui.add_space(6.0);
for (title, note, key, current) in [
(crate::tl!("Default Mode"), crate::tl!("No objects selected and no command running:"), "rightClickDefault", o.right_click_default),
(crate::tl!("Edit Mode"), crate::tl!("Objects selected and no command running:"), "rightClickEdit", o.right_click_edit),
] {
heading(ui, title);
ui.group(|ui| {
ui.set_width(ui.available_width());
hint(ui, note);
for (choice, label) in [(IdleClick::Repeat, crate::tl!("Repeat last command")), (IdleClick::Menu, crate::tl!("Shortcut Menu"))] {
if ui.radio(current == choice, label).clicked() && current != choice {
changes.insert(key.into(), json!(choice.as_str()));
// Like Command mode, Default and Edit modes decide only with the time-sensitive
// right-click off: with it on, a quick click is Enter and a longer one the menu.
ui.add_enabled_ui(!o.time_sensitive_right_click, |ui| {
for (title, note, key, current) in [
(
crate::tl!("Default Mode"),
crate::tl!("No objects selected and no command running:"),
"rightClickDefault",
o.right_click_default,
),
(crate::tl!("Edit Mode"), crate::tl!("Objects selected and no command running:"), "rightClickEdit", o.right_click_edit),
] {
heading(ui, title);
ui.group(|ui| {
ui.set_width(ui.available_width());
hint(ui, note);
for (choice, label) in
[(IdleClick::Repeat, crate::tl!("Repeat last command")), (IdleClick::Menu, crate::tl!("Shortcut Menu"))]
{
if ui.radio(current == choice, label).clicked() && current != choice {
changes.insert(key.into(), json!(choice.as_str()));
}
}
}
});
}
});
}
});
ui.add_enabled_ui(!o.time_sensitive_right_click, |ui| {
heading(ui, crate::tl!("Command Mode"));
ui.group(|ui| {
+38
View File
@@ -240,4 +240,42 @@ fn time_sensitive_right_click() {
painted(&mut app, &ctx, Vec::new(), 3.1);
assert!(app.session.running.is_none(), "a quick right-click is Enter: {}", app.session.prompt_text());
assert_eq!(app.session.doc().unwrap().model.handles().len(), 1);
// Between commands a quick right-click is Enter too: it repeats LINE (it opened the shortcut
// menu instead).
painted(&mut app, &ctx, vec![quick(true)], 4.0);
painted(&mut app, &ctx, vec![quick(false)], 4.05);
let text = painted(&mut app, &ctx, Vec::new(), 4.1);
assert!(app.session.running.is_some(), "a quick right-click repeats LINE: {}", app.session.prompt_text());
assert!(!text.contains("Repeat LINE"), "no shortcut menu on a quick click:\n{text}");
app.session.input(cadcraft_engine::Input::Cancel).unwrap();
// Held, it opens the shortcut menu and repeats nothing.
painted(&mut app, &ctx, vec![quick(true)], 5.0);
painted(&mut app, &ctx, Vec::new(), 5.2);
painted(&mut app, &ctx, vec![quick(false)], 5.0 + context_menu::HOLD_SECS + 0.1);
let text = painted(&mut app, &ctx, Vec::new(), 5.5);
assert!(text.contains("Repeat LINE"), "Repeat LINE missing from the painted menu:\n{text}");
assert!(app.session.running.is_none(), "held, no repeat: {}", app.session.prompt_text());
// A quick click enters what was typed, as the Enter key does (#1387): a command name between
// commands (not a repeat of LINE)…
painted(
&mut app,
&ctx,
vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],
5.6,
);
// The menu closes on the frame after Escape.
painted(&mut app, &ctx, Vec::new(), 5.7);
app.cmd.buffer = "circle".into();
painted(&mut app, &ctx, vec![quick(true)], 6.0);
painted(&mut app, &ctx, vec![quick(false)], 6.05);
painted(&mut app, &ctx, Vec::new(), 6.1);
assert!(app.session.prompt_text().contains("center point"), "the typed CIRCLE starts: {}", app.session.prompt_text());
// …and a point while a command runs.
app.cmd.buffer = "5,5".into();
painted(&mut app, &ctx, vec![quick(true)], 7.0);
painted(&mut app, &ctx, vec![quick(false)], 7.05);
painted(&mut app, &ctx, Vec::new(), 7.1);
assert!(app.session.prompt_text().contains("radius"), "the typed center is entered: {}", app.session.prompt_text());
}
+4
View File
@@ -21,6 +21,7 @@ mod instant_modals;
mod lisp_files;
mod measure_distance_snapping;
mod menubar_hover;
mod moving_clicks;
mod mspace_viewport_view;
mod named_viewports_dialog;
mod native_menu_text_keys;
@@ -29,6 +30,7 @@ mod options_dialog;
mod options_right_click;
mod parameters_rename;
mod pickdrag;
mod press_first_clicks;
mod properties_described;
mod properties_units;
mod rapid_clicks;
@@ -36,6 +38,8 @@ mod selection_cycling;
mod shared_controls;
mod shortcut_menus;
mod shortcuts_checked;
mod slow_clicks;
mod space_at_options;
mod status_bar_toggles;
mod style_dialogs;
mod system_cursor;
+183
View File
@@ -0,0 +1,183 @@
//! A click made while the mouse moves counts where the button went down, in the commands #1001
//! names (STRETCH, MOVE, TRIM), with no command running, with PICKDRAG off, at a click-click
//! window's second corner and over overlapping objects (selection cycling).
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Drawing, EntityKind, Space};
use cadcraft_engine::geom::Vec2;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
fn screen(h: &Harness<'_, CadApp>, p: Vec2) -> Pos2 {
h.state().canvas.xf.unwrap().to_screen(p)
}
fn button(h: &mut Harness<'_, CadApp>, pos: Pos2, pressed: bool) {
h.event(Event::PointerMoved(pos));
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
}
fn lines(h: &Harness<'_, CadApp>) -> Vec<(Vec2, Vec2)> {
let st = h.state().session.state().unwrap();
st.doc
.space(&Space::Model)
.unwrap()
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some((l.a.xy(), l.b.xy())),
_ => None,
})
.collect()
}
/// A harness at 60 frames a second, with two lines to select: a horizontal one through (20, 50)
/// and (40, 50), and a vertical one at x = 80.
fn select_harness() -> Harness<'static, CadApp> {
let mut session = Session::empty();
session.open_drawing(Drawing::new_imperial(), "Moving clicks", None);
session.execute("view.set", &json!({"center":[50,50],"height":100})).unwrap();
session.settings.osmode = 0;
session.execute("line", &json!({"points": [[20, 50], [40, 50]]})).unwrap();
session.execute("line", &json!({"points": [[80, 30], [80, 70]]})).unwrap();
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h
}
/// Press at `down`, move on (the hand is already going somewhere) and let go at `up`, `frames`
/// frames later.
fn press_moving(h: &mut Harness<'_, CadApp>, down: Vec2, up: Vec2, frames: usize) {
let (d, u) = (screen(h, down), screen(h, up));
button(h, d, true);
h.run_steps(1);
for i in 1..=frames {
let t = i as f32 / frames as f32;
h.event(Event::PointerMoved(d + (u - d) * t));
h.run_steps(1);
}
button(h, u, false);
h.run_steps(2);
}
fn handles(h: &Harness<'_, CadApp>) -> Vec<cadcraft_engine::doc::Handle> {
let st = h.state().session.state().unwrap();
st.doc.space(&Space::Model).unwrap().iter().map(|e| e.handle).collect()
}
/// #1001: in STRETCH (whose "Select objects" takes points), a click made while the mouse moves
/// picks the object where the button went down; on empty space it starts STRETCH's window.
#[test]
fn a_click_made_while_moving_selects_in_stretch() {
let mut h = select_harness();
let ids = handles(&h);
h.state_mut().start("stretch");
h.run_steps(2);
// Down on the horizontal line, up a few units off it, a few frames later.
press_moving(&mut h, Vec2::new(30.0, 50.0), Vec2::new(32.0, 54.0), 4);
assert_eq!(h.state().session.selection(), vec![ids[0]], "the line under the button is picked");
// Down on empty space while moving: the window starts where the button went down.
press_moving(&mut h, Vec2::new(70.0, 20.0), Vec2::new(72.0, 22.0), 4);
assert_eq!(h.state().session.current_prompt().unwrap().message, "Specify opposite corner");
let corner = screen(&h, Vec2::new(90.0, 80.0));
button(&mut h, corner, true);
h.run_steps(1);
button(&mut h, corner, false);
h.run_steps(2);
assert_eq!(h.state().session.selection(), vec![ids[0], ids[1]], "the window took the vertical line");
}
/// At a generic "Select objects" (MOVE), a moving click picks the object where the button went
/// down instead of closing a tiny window; a slow press-and-drag is still a window.
#[test]
fn a_click_made_while_moving_selects_in_move_and_a_slow_drag_is_a_window() {
let mut h = select_harness();
let ids = handles(&h);
h.state_mut().start("move");
h.run_steps(2);
press_moving(&mut h, Vec2::new(30.0, 50.0), Vec2::new(32.0, 54.0), 4);
assert_eq!(h.state().session.selection(), vec![ids[0]]);
assert!(h.state().session.pending_window.is_none());
// Half a second from (70, 20) to (90, 80): a window around the vertical line.
press_moving(&mut h, Vec2::new(70.0, 20.0), Vec2::new(90.0, 80.0), 30);
assert!(h.state().session.pending_window.is_none(), "closed where the drag ended");
assert_eq!(h.state().session.selection(), vec![ids[0], ids[1]]);
}
/// With no command running, the same moving click picks the object.
#[test]
fn a_click_made_while_moving_picks_with_no_command() {
let mut h = select_harness();
let ids = handles(&h);
press_moving(&mut h, Vec2::new(80.0, 40.0), Vec2::new(83.0, 41.0), 4);
assert_eq!(h.state().session.selection(), vec![ids[1]]);
}
/// A click-click window already open: its second corner, clicked while moving, closes it where the
/// button went down instead of being lost to the drag egui saw.
#[test]
fn a_click_made_while_moving_closes_a_click_click_window() {
let mut h = select_harness();
let ids = handles(&h);
let corner = screen(&h, Vec2::new(70.0, 20.0));
button(&mut h, corner, true);
h.run_steps(1);
button(&mut h, corner, false);
h.run_steps(2);
assert!(h.state().session.pending_window.is_some(), "the click on empty space opened a window");
press_moving(&mut h, Vec2::new(90.0, 80.0), Vec2::new(92.0, 82.0), 4);
assert!(h.state().session.pending_window.is_none(), "the moving click closed the window");
assert_eq!(h.state().session.selection(), vec![ids[1]], "the window took the vertical line");
}
/// With PICKDRAG 0 no drag opens a window, and a click made while moving still picks the object.
#[test]
fn a_click_made_while_moving_picks_with_pickdrag_off() {
let mut h = select_harness();
let ids = handles(&h);
h.state_mut().session.settings.pickdrag = false;
press_moving(&mut h, Vec2::new(80.0, 40.0), Vec2::new(83.0, 41.0), 4);
assert_eq!(h.state().session.selection(), vec![ids[1]]);
assert!(h.state().session.pending_window.is_none());
}
/// TRIM's "Select object to trim": a click made while moving trims the part the button went down
/// on.
#[test]
fn a_click_made_while_moving_trims_in_trim() {
let mut h = select_harness();
// A vertical cutting edge through the horizontal line, at x = 30.
h.state_mut().session.execute("line", &json!({"points": [[30, 40], [30, 60]]})).unwrap();
h.state_mut().start("trim");
h.run_steps(2);
press_moving(&mut h, Vec2::new(36.0, 50.0), Vec2::new(39.0, 56.0), 4);
let got = lines(&h);
assert!(
got.iter().any(|(a, b)| a.near(Vec2::new(20.0, 50.0), 1e-6) && b.near(Vec2::new(30.0, 50.0), 1e-6)),
"the right part of the horizontal line was trimmed: {got:?}"
);
}
/// With SELECTIONCYCLING 2, a click made while moving over overlapping objects opens selection
/// cycling's list, as a still click does, instead of picking one of them.
#[test]
fn a_click_made_while_moving_over_overlapping_objects_lists_them() {
let mut h = select_harness();
h.state_mut().session.execute("line", &json!({"points": [[20, 50], [60, 50]]})).unwrap();
h.state_mut().session.execute("setvar", &json!({ "name": "SELECTIONCYCLING", "value": 2 })).unwrap();
h.state_mut().session.set_selection(Vec::new());
h.run_steps(2);
press_moving(&mut h, Vec2::new(30.0, 50.0), Vec2::new(32.0, 54.0), 4);
assert_eq!(h.state().canvas.cycle_rows().len(), 2, "both lines are listed");
assert!(h.state().session.selection().is_empty(), "nothing is picked until a row is chosen");
}
+28 -5
View File
@@ -99,7 +99,7 @@ fn right_click_settings_are_checked_and_survive_a_restart() {
#[test]
fn an_idle_right_click_can_repeat_the_last_command() {
let mut a = app();
a.run("options", json!({"rightClickDefault": "repeat"})).unwrap();
a.run("options", json!({"timeSensitiveRightClick": false, "rightClickDefault": "repeat"})).unwrap();
a.cmdline("circle 0,0 5");
assert!(!a.session.prompting());
let ctx = egui::Context::default();
@@ -116,6 +116,22 @@ fn an_idle_right_click_can_repeat_the_last_command() {
assert!(text.contains("Erase"), "the shortcut menu opens:\n{text}");
}
/// With the time-sensitive right-click on (the default), Default and Edit modes don't decide, as
/// in AutoCAD: a quick click is Enter (#1387) and a longer one opens the shortcut menu, even with
/// both set to repeat the last command.
#[test]
fn the_time_sensitive_right_click_decides_between_commands_too() {
let mut a = app();
a.run("options", json!({"rightClickDefault": "repeat", "rightClickEdit": "repeat"})).unwrap();
a.cmdline("circle 0,0 5");
assert!(!a.session.prompting());
let ctx = egui::Context::default();
frame(&mut a, &ctx, Vec::new(), 0.0);
let text = right_click(&mut a, &ctx, 0.1, 0.4);
assert!(!a.session.prompting(), "a longer click repeats nothing: {}", a.session.prompt_text());
assert!(text.contains("Repeat CIRCLE"), "the shortcut menu opens:\n{text}");
}
#[test]
fn command_mode_and_click_duration_decide_enter_or_the_menu() {
let ctx = egui::Context::default();
@@ -182,6 +198,17 @@ fn the_customization_window_sets_every_mode() {
h.get_by_label("Longer click duration:");
shot(&mut h, "options-right-click.png");
// Default, Edit and Command modes apply once the time-sensitive right-click is off; with it
// on, Default mode's choice can't be made.
if let Some(n) = h.get_all_by_label("Repeat last command").next() {
n.click();
}
h.run_steps(3);
assert_eq!(h.state().options.right_click_default, IdleClick::Menu);
h.get_by_label("Turn on time-sensitive right-click").click();
h.run_steps(3);
assert!(!h.state().options.time_sensitive_right_click);
// Default mode's "Repeat last command" comes first, Edit mode's second.
if let Some(n) = h.get_all_by_label("Repeat last command").next() {
n.click();
@@ -190,10 +217,6 @@ fn the_customization_window_sets_every_mode() {
assert_eq!(h.state().options.right_click_default, IdleClick::Repeat);
assert_eq!(h.state().options.right_click_edit, IdleClick::Menu);
// Command mode applies once the time-sensitive right-click is off.
h.get_by_label("Turn on time-sensitive right-click").click();
h.run_steps(3);
assert!(!h.state().options.time_sensitive_right_click);
h.get_by_label("Shortcut Menu: enabled when command options are present").click();
h.run_steps(3);
assert_eq!(h.state().options.right_click_command, CommandClick::MenuWithOptions);
+5 -7
View File
@@ -83,13 +83,11 @@ fn drag_is_disabled_but_two_clicks_still_complete_the_window() {
button(&mut h, a, true);
button(&mut h, a, false);
assert!(h.state().session.pending_window.is_some());
// A held-button movement after the first click must not consume the second corner.
drag(&mut h, a, b);
assert!(h.state().session.pending_window.is_some());
assert!(h.state().session.selection().is_empty());
h.run_steps(30); // Separate deliberate clicks from egui's double-click interval.
button(&mut h, b, true);
button(&mut h, b, false);
// The second corner is where the button goes down (#1001): a drag on from there, let go
// elsewhere, changes nothing.
h.run_steps(30); // Separate deliberate clicks from the double-click interval.
let away = xf.to_screen(Vec2::new(30.0, 8.0));
drag(&mut h, b, away);
assert!(h.state().session.pending_window.is_none());
assert_eq!(h.state().session.selection().len(), 1);
}
@@ -0,0 +1,189 @@
//! Press-first clicks (#1001): a click counts when the button goes down, where it went down, even
//! while the mouse is moving; holding the button after the pointer left a small tolerance makes a
//! drag. The harness runs at 60 frames a second and each queued event is one frame, so the number
//! of moves between press and release is how long the button was held.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Drawing, EntityKind, Space};
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::prompt::Input;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
fn harness() -> Harness<'static, CadApp> {
let mut session = Session::empty();
session.open_drawing(Drawing::new_imperial(), "Press first", None);
session.execute("view.set", &json!({"center":[50,50],"height":100})).unwrap();
session.settings.osmode = 0;
session.settings.snapmode = false;
session.settings.orthomode = false;
session.execute("line", &json!({"points": [[20, 20], [60, 20]]})).unwrap();
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h
}
fn screen(h: &Harness<'_, CadApp>, p: Vec2) -> Pos2 {
h.state().canvas.xf.unwrap().to_screen(p)
}
fn button(h: &mut Harness<'_, CadApp>, pos: Pos2, pressed: bool) {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
}
/// Press at `at`, then move `dx` points to the right over `frames` frames and let go there.
fn moving_click(h: &mut Harness<'_, CadApp>, at: Pos2, dx: f32, frames: usize) {
h.event(Event::PointerMoved(at));
button(h, at, true);
for i in 1..=frames {
h.event(Event::PointerMoved(at + vec2(dx * i as f32 / frames as f32, 0.0)));
}
button(h, at + vec2(dx, 0.0), false);
h.run_steps(2);
}
/// A click that moves 15 points while the button is down, let go within two frames.
fn quick_moving_click(h: &mut Harness<'_, CadApp>, at: Vec2) {
let pos = screen(h, at);
moving_click(h, pos, 15.0, 2);
}
fn start(h: &mut Harness<'_, CadApp>, id: &str) {
h.state_mut().start(id);
h.run_steps(2);
assert_eq!(h.state().session.running.as_ref().map(|r| r.id.as_str()), Some(id));
}
fn enter(h: &mut Harness<'_, CadApp>) {
h.state_mut().session.input(Input::Enter).unwrap();
h.run_steps(2);
}
fn lines(h: &Harness<'_, CadApp>) -> Vec<(Vec2, Vec2)> {
let st = h.state().session.state().unwrap();
st.doc
.space(&Space::Model)
.unwrap()
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some((l.a.xy(), l.b.xy())),
_ => None,
})
.collect()
}
#[test]
fn move_takes_the_base_and_second_point_where_the_button_went_down() {
let mut h = harness();
start(&mut h, "move");
quick_moving_click(&mut h, Vec2::new(40.0, 20.0));
enter(&mut h);
// Base point and second point, both clicked on the move: 15 points is 1.5 drawing units here.
quick_moving_click(&mut h, Vec2::new(30.0, 40.0));
quick_moving_click(&mut h, Vec2::new(50.0, 40.0));
let got = lines(&h);
assert_eq!(got.len(), 1, "{got:?}");
assert!(got[0].0.near(Vec2::new(40.0, 20.0), 1e-3) && got[0].1.near(Vec2::new(80.0, 20.0), 1e-3), "moved by (20, 0): {got:?}");
}
#[test]
fn an_object_clicked_on_the_move_is_picked_with_no_command_running() {
let mut h = harness();
quick_moving_click(&mut h, Vec2::new(40.0, 20.0));
assert_eq!(h.state().session.selection().len(), 1);
assert!(h.state().session.pending_window.is_none());
}
#[test]
fn an_object_clicked_on_the_move_is_picked_at_select_objects() {
let mut h = harness();
start(&mut h, "erase");
quick_moving_click(&mut h, Vec2::new(40.0, 20.0));
enter(&mut h);
assert!(lines(&h).is_empty(), "the line was picked and erased");
}
#[test]
fn both_corners_of_a_click_click_window_count_while_the_mouse_moves() {
let mut h = harness();
// Lower left, then upper right: a window around the whole line.
quick_moving_click(&mut h, Vec2::new(10.0, 10.0));
assert!(h.state().session.pending_window.is_some(), "a quick click leaves the window open for the second corner");
quick_moving_click(&mut h, Vec2::new(70.0, 30.0));
assert!(h.state().session.pending_window.is_none());
assert_eq!(h.state().session.selection().len(), 1);
}
#[test]
fn holding_the_button_while_moving_drags_a_window() {
let mut h = harness();
// Half a second of dragging from lower left to upper right of the line.
let from = screen(&h, Vec2::new(10.0, 10.0));
let to = screen(&h, Vec2::new(70.0, 30.0));
h.event(Event::PointerMoved(from));
button(&mut h, from, true);
for i in 1..=30 {
h.event(Event::PointerMoved(from + (to - from) * (i as f32 / 30.0)));
}
button(&mut h, to, false);
h.run_steps(2);
assert!(h.state().session.pending_window.is_none(), "letting go closes the dragged window");
assert_eq!(h.state().session.selection().len(), 1);
}
#[test]
fn holding_still_then_moving_and_letting_go_quickly_is_a_click() {
let mut h = harness();
let at = screen(&h, Vec2::new(10.0, 10.0));
h.event(Event::PointerMoved(at));
button(&mut h, at, true);
// Held in place for half a second: no drag yet.
h.run_steps(30);
h.event(Event::PointerMoved(at + vec2(40.0, 0.0)));
button(&mut h, at + vec2(40.0, 0.0), false);
h.run_steps(2);
assert!(h.state().session.pending_window.is_some(), "still waiting for the second corner");
}
#[test]
fn two_window_corners_clicked_within_one_frame_both_count() {
let mut h = harness();
let (a, b) = (screen(&h, Vec2::new(10.0, 10.0)), screen(&h, Vec2::new(70.0, 30.0)));
// A slow frame: both clicks arrive before the next one is drawn.
for pos in [a, b] {
h.input_mut().events.push(Event::PointerMoved(pos));
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
}
}
h.run_steps(2);
assert!(h.state().session.pending_window.is_none());
assert_eq!(h.state().session.selection().len(), 1);
}
#[test]
fn cpolygon_points_clicked_on_the_move_all_count() {
// #1546: a narrow crossing polygon over the line's right end (x 58.6–59.9, the line ends at
// 60), each point clicked while moving. Taken where the buttons came up (1.5 units further
// right) it would miss the line.
let mut h = harness();
start(&mut h, "erase");
h.state_mut().session.input(Input::Keyword("CP".into())).unwrap();
h.run_steps(2);
for p in [Vec2::new(58.6, 15.0), Vec2::new(59.9, 15.0), Vec2::new(59.9, 25.0), Vec2::new(58.6, 25.0)] {
quick_moving_click(&mut h, p);
}
enter(&mut h);
enter(&mut h);
assert!(lines(&h).is_empty(), "the polygon crossed the line and ERASE removed it");
}
+3 -2
View File
@@ -88,11 +88,12 @@ fn a_click_made_while_the_mouse_moves_still_places_the_point() {
let down = screen(&h, Vec2::new(40.0, 10.0));
button(&mut h, down, true);
h.run_steps(1);
// The hand is already on its way to the next point when the button comes up.
// The hand is already on its way to the next point when the button comes up; the point is
// where the button went down (#1001), not where the hand got to.
let up = down + vec2(12.0, 0.0);
button(&mut h, up, false);
h.run_steps(2);
let got = lines(&h);
assert_eq!(got.len(), 1, "{got:?}");
assert!(got[0].1.near(h.state().canvas.xf.unwrap().to_world(up), 1e-4), "{got:?}");
assert!(got[0].1.near(h.state().canvas.xf.unwrap().to_world(down), 1e-4), "{got:?}");
}
+159
View File
@@ -0,0 +1,159 @@
//! A click on an object selects it, however long the frames around it take (#2813).
//!
//! egui calls a press that lasts longer than `max_click_duration` (0.8 s) a drag, and it times the
//! press by frames. On a large drawing that draws slowly, an ordinary click can come down in one
//! frame and up in the next, more than 0.8 s later. The canvas took that "drag" for a press-and-drag
//! selection window that never left the click, a window of no size, and nothing was selected; when
//! no frame ran while the button was down, egui reported nothing at all.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Drawing, Handle, Space};
use cadcraft_engine::geom::Vec2;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
/// Seconds each harness step advances egui's clock: two steps between press and release make a
/// press longer than egui's 0.8 s click limit.
const STEP: f32 = 0.5;
/// A drawing with one line from (10, 10) to (30, 10), no object snaps, nothing selected; each frame
/// advances egui's clock by [`STEP`].
fn harness() -> (Harness<'static, CadApp>, Handle) {
harness_stepping(STEP)
}
/// [`harness`] with each frame advancing egui's clock by `step` seconds.
fn harness_stepping(step: f32) -> (Harness<'static, CadApp>, Handle) {
let mut session = Session::empty();
session.open_drawing(Drawing::new_imperial(), "Slow clicks", None);
session.execute("view.set", &json!({"center": [50, 50], "height": 100})).unwrap();
session.settings.osmode = 0;
session.execute("line", &json!({"points": [[10, 10], [30, 10]]})).unwrap();
let line = session.doc().unwrap().space(&Space::Model).unwrap().iter().next().unwrap().handle;
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(step).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
(h, line)
}
fn screen(h: &Harness<'_, CadApp>, p: Vec2) -> Pos2 {
h.state().canvas.xf.unwrap().to_screen(p)
}
fn button(h: &mut Harness<'_, CadApp>, pos: Pos2, pressed: bool) {
h.event(Event::PointerMoved(pos));
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
}
/// Press at `down`, let `frames` slow frames pass, release at `up`.
fn slow_click(h: &mut Harness<'_, CadApp>, down: Pos2, up: Pos2, frames: usize) {
button(h, down, true);
h.run_steps(frames);
button(h, up, false);
h.run_steps(2);
}
#[test]
fn a_click_spanning_slow_frames_selects_the_object() {
let (mut h, line) = harness();
let at = screen(&h, Vec2::new(20.0, 10.0));
slow_click(&mut h, at, at, 2);
assert_eq!(h.state().session.selection(), vec![line]);
assert!(h.state().session.pending_window.is_none(), "no window is left open");
}
/// The slowest case: the frame the button went down in took a second, and the next frame already
/// has it up. No frame ran with the button down, so egui reports neither a click nor a drag.
#[test]
fn a_click_across_one_slow_frame_selects_the_object() {
let (mut h, line) = harness_stepping(1.0);
let at = screen(&h, Vec2::new(20.0, 10.0));
slow_click(&mut h, at, at, 1);
assert_eq!(h.state().session.selection(), vec![line]);
}
/// A slow click on a grip of a selected object makes it hot, as a quick one does.
#[test]
fn a_slow_click_on_a_grip_starts_a_grip_edit() {
let (mut h, line) = harness();
h.state_mut().session.set_selection(vec![line]);
h.run_steps(2);
let grip = screen(&h, Vec2::new(30.0, 10.0));
slow_click(&mut h, grip, grip, 2);
assert_eq!(h.state().session.running.as_ref().map(|r| r.id.as_str()), Some("grip"));
}
/// The hand drifts a pixel or two while the button is down: still a click.
#[test]
fn a_slow_click_that_drifts_within_the_click_distance_selects_the_object() {
let (mut h, line) = harness();
let at = screen(&h, Vec2::new(20.0, 10.0));
slow_click(&mut h, at, at + vec2(2.0, 1.0), 2);
assert_eq!(h.state().session.selection(), vec![line]);
}
/// In empty space a slow click does what a quick one does there: it starts a click-click window.
#[test]
fn a_slow_click_in_empty_space_starts_a_window_as_a_click_does() {
let (mut h, _) = harness();
let at = screen(&h, Vec2::new(20.0, 40.0));
slow_click(&mut h, at, at, 2);
assert!(h.state().session.selection().is_empty());
let corner = h.state().session.pending_window.map(|w| w.corner);
assert!(corner.is_some_and(|c| c.near(Vec2::new(20.0, 40.0), 0.5)), "{corner:?}");
}
/// A real press-and-drag still opens and closes a selection window, slow or not.
#[test]
fn a_press_and_drag_still_selects_by_window() {
let (mut h, line) = harness();
let (from, to) = (screen(&h, Vec2::new(5.0, 15.0)), screen(&h, Vec2::new(35.0, 5.0)));
button(&mut h, from, true);
h.run_steps(1);
h.event(Event::PointerMoved(from + (to - from) / 2.0));
h.run_steps(2);
button(&mut h, to, false);
h.run_steps(2);
assert_eq!(h.state().session.selection(), vec![line]);
assert!(h.state().session.pending_window.is_none());
}
/// While a command asks for objects, a slow click on one picks it.
#[test]
fn a_slow_click_picks_at_select_objects() {
let (mut h, line) = harness();
h.state_mut().start("erase");
h.run_steps(2);
let at = screen(&h, Vec2::new(20.0, 10.0));
slow_click(&mut h, at, at, 2);
h.state_mut().session.input(cadcraft_engine::Input::Enter).unwrap();
h.run_steps(2);
let d = h.state().session.doc().unwrap();
assert!(d.entity(line).is_none(), "the line was picked and erased");
}
/// At a point prompt, a click across one slow frame places one point. This already worked (a drag
/// that stops at a point prompt counts as a click, #815). The test keeps it so, and shows the click
/// isn't counted twice (CIRCLE would take the second as the radius).
#[test]
fn a_click_across_one_slow_frame_places_a_point() {
let (mut h, _) = harness_stepping(1.0);
h.state_mut().start("circle");
h.run_steps(1);
let prompt = |h: &Harness<'_, CadApp>| h.state().session.current_prompt().map(|p| p.message).unwrap_or_default();
let center_prompt = prompt(&h);
let at = screen(&h, Vec2::new(60.0, 60.0));
slow_click(&mut h, at, at, 1);
let next = prompt(&h);
assert_ne!(next, center_prompt, "the center was taken");
assert!(next.to_ascii_lowercase().starts_with("specify radius"), "{next}");
}
@@ -0,0 +1,59 @@
//! Space is Enter at TRIM's and EXTEND's option prompts, as at AutoCAD's (#3092): typing `O`,
//! Space, `S`, Space switches to Standard mode instead of typing a space into the command line.
use cadcraft_engine::Session;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Key, Modifiers, vec2};
use egui_kittest::Harness;
fn harness() -> Harness<'static, CadApp> {
let app = CadApp::new(Session::new(), Services::default());
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
/// Type `text` at the keyboard: a space arrives as the Space key and as text, like a real press.
fn type_keys(h: &mut Harness<'static, CadApp>, text: &str) {
for c in text.chars() {
if c == ' ' {
h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
}
h.event(egui::Event::Text(c.to_string()));
h.run_steps(1);
}
h.run_steps(1);
}
fn header(h: &Harness<'static, CadApp>, name: &str) -> i64 {
h.state().session.doc().unwrap().header.i64(name, -1)
}
fn prompt(h: &Harness<'static, CadApp>) -> String {
h.state().session.current_prompt().map(|p| p.message).unwrap_or_default()
}
#[test]
fn space_answers_trim_and_extend_option_prompts() {
let mut h = harness();
type_keys(&mut h, "trim o s ");
assert_eq!(h.state().cmd.buffer, "", "Space typed a space instead of entering the option");
assert_eq!(header(&h, "TRIMEXTENDMODE"), 0, "S chose Standard mode");
// Standard mode asks for cutting edges; Enter selects all, then Project and Edge.
type_keys(&mut h, " p n e e ");
assert_eq!(h.state().cmd.buffer, "");
assert_eq!(header(&h, "PROJMODE"), 0, "N chose no projection");
assert_eq!(header(&h, "EDGEMODE"), 1, "E chose Extend");
assert!(prompt(&h).starts_with("Select object to trim"), "back at the trim prompt: {}", prompt(&h));
h.key_press(Key::Escape);
h.run_steps(2);
type_keys(&mut h, "extend o q ");
assert_eq!(h.state().cmd.buffer, "");
assert_eq!(header(&h, "TRIMEXTENDMODE"), 1, "Q chose Quick mode in EXTEND");
}
+1 -1
View File
@@ -48,7 +48,7 @@ Example client configuration (Claude Code / Claude Desktop):
| `execute {"command": "loops", "params": {tolerance?, maxPairs?, limit?, offset?}}` | Implied closed loops from loose LINE and ARC chains: each closed loop with its member handles, perimeter, area and winding, exact with arcs; each open chain with the endpoint gap, its location (`at`, `ends`) and length; and branch junctions (three or more ends meeting), reported but not resolved. `tolerance` defaults to 1e-9 × the extents diagonal; the quadratic endpoint pairing stops at `maxPairs` (default 1,000,000) and reports `capped` with `pairTestsNeeded` instead of guessing from a partial pairing. |
| `query_entities {type?, layer?, selected?, window?, crossing?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `count` is every match, `returned` the page (`offset`, `limit`, default 500). |
| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. |
| `find_text {contains?, query?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (`contains`, or `query` as an alias; any case), layer and a window around the insertion points. Read-only (the `texts` command). |
| `find_text {contains?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (any case), layer and a window around the insertion points. Read-only (the `texts` command). |
| `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. |
| `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. |
+1 -2
View File
@@ -81,8 +81,7 @@ prints as `Normal`. A colour-dependent table ignores the property.
style and the named styles.
- `layer.set {name, plotStyle}` sets a layer's plot style.
- `stylesmanager {action, …}` manages the tables: `list`, `get`, `new` (`kind`, `from`), `set`
(`style: {name, …fields}`, `removeStyle`, `description`; it replies with the table's name and
only what changed), `delete`, `load` (`path` or `text`)
(`style: {name, …fields}`, `removeStyle`, `description`), `delete`, `load` (`path` or `text`)
and `save` (`path`, or returns `text`). Typed or chosen from **File ▸ Plot Styles...**, it
opens the Plot Style Manager dialog.