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
42 changed files with 1273 additions and 1358 deletions
+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
+9 -76
View File
@@ -44,11 +44,6 @@ pub use store::EntityStore;
pub use tables::*;
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
/// Handles at or above this are not followed: a file may name one (an object's handle, or its
/// `$HANDSEED`), and the four billion handles above the limit stay free for the drawing's own
/// growth. A file's handles keep their identity, however high they are (#913, #939).
pub const HANDLE_LIMIT: u64 = u64::MAX - 0xFFFF_FFFF;
/// File data CADCraft doesn't model, kept for saving (#528).
pub mod dynblock;
pub mod foreign;
@@ -132,10 +127,6 @@ pub struct Drawing {
pub scales: Vec<AnnoScale>,
/// Next free handle.
pub handseed: u64,
/// Handles a file's records hold in the reserved band, recorded while reading before the
/// record is placed: [`Drawing::new_handle`] skips them meanwhile. [`Drawing::bump_handseed`]
/// does not follow them (#913). Emptied once the file is read; never written to a file.
pub reserved_handles: BTreeSet<u64>,
/// Objects hidden for this session by ISOLATEOBJECTS / HIDEOBJECTS. Never written to a file:
/// a drawing opens with everything shown again.
pub hidden_objects: BTreeSet<Handle>,
@@ -209,7 +200,6 @@ impl Drawing {
parametric: Parametric::default(),
scales: imperial_scales(),
handseed: 0x100,
reserved_handles: BTreeSet::new(),
hidden_objects: BTreeSet::new(),
read_notes: Vec::new(),
refedit: None,
@@ -219,83 +209,26 @@ impl Drawing {
}
}
/// Allocate a fresh handle: [`Drawing::next_handle`], with the seed moved past it. Past the
/// top of the range the drawing goes on growing in the reserved band (#913).
/// Allocate a fresh handle. It skips the handles the drawing's file gave the objects CADCraft
/// writes itself ([`foreign::Foreign::handles`]): AutoLISP names those objects by them, and a
/// file CADCraft wrote numbers them above its `$HANDSEED` (#495).
pub fn new_handle(&mut self) -> Handle {
let h = self.next_handle();
self.handseed = h.0.checked_add(1).unwrap_or(HANDLE_LIMIT);
self.handseed = h.0.saturating_add(1);
h
}
/// The handle [`Drawing::new_handle`] gives out next (AutoCAD's `HANDSEED`), without taking it:
/// the first one at or above the seed that nothing holds. It skips
/// - the handles the drawing's file gave the objects CADCraft writes itself
/// ([`foreign::Foreign::handles`]): AutoLISP names those objects by them, and a file
/// CADCraft wrote numbers them above its `$HANDSEED` (#495);
/// - handles an object or a file record being read holds in the reserved band above
/// [`HANDLE_LIMIT`]. A hostile or damaged file may name a `$HANDSEED` there, and a file
/// object may hold that same handle; the seed does not follow a file's handles in the band,
/// so taking it as-is would hand the file's object's handle to a new object and
/// `EntityStore` would replace it (#913, #1921);
/// - handle 0, which a file reads as "no handle".
///
/// Off the top of the range it goes on at the bottom of the band.
///
/// Cost: below the band the reader and [`Drawing::bump_handseed`] keep the seed above every
/// handle an object holds (AUDIT repairs a drawing where that fails), and reserved handles are
/// all in the band, so there only `foreign.handles` is looked up. The scan of every space and
/// block definition runs only for a candidate in the band. Every handle skipped is a distinct
/// one something holds, so the walk ends within one step more than the count of held handles.
/// The handle [`Drawing::new_handle`] gives out next (AutoCAD's `HANDSEED`), without taking it.
pub fn next_handle(&self) -> Handle {
let held = |h: u64| {
h == 0
|| self.foreign.handles.contains_key(&Handle(h))
|| (h >= HANDLE_LIMIT && (self.reserved_handles.contains(&h) || self.handle_in_use(Handle(h))))
};
let mut h = self.handseed;
// Counted only once a handle is skipped, so the usual first-try answer costs nothing.
let mut steps_left: Option<usize> = None;
while held(h) {
let left = steps_left.get_or_insert_with(|| self.held_handle_count());
let Some(rest) = left.checked_sub(1) else { break };
*left = rest;
h = h.checked_add(1).unwrap_or(HANDLE_LIMIT);
while self.foreign.handles.contains_key(&Handle(h)) && h < u64::MAX {
h = h.saturating_add(1);
}
Handle(h)
}
/// Whether an object in any space or block definition already holds `h`.
fn handle_in_use(&self, h: Handle) -> bool {
self.model.contains(h) || self.layouts.iter().any(|l| l.entities.contains(h)) || self.blocks.values().any(|b| b.entities.contains(h))
}
/// An upper bound on how many handles [`Drawing::next_handle`] can find held, plus handle 0.
fn held_handle_count(&self) -> usize {
let spaces = self.layouts.iter().map(|l| l.entities.len()).chain(self.blocks.values().map(|b| b.entities.len()));
spaces
.fold(self.model.len(), usize::saturating_add)
.saturating_add(self.foreign.handles.len())
.saturating_add(self.reserved_handles.len())
.saturating_add(1)
}
/// Record a handle a file's record holds in the reserved band, before the record is placed in
/// the drawing, so [`Drawing::new_handle`] does not hand it to an object read earlier (#1276).
///
/// Only handles at or above [`HANDLE_LIMIT`] are recorded: below it [`Drawing::bump_handseed`]
/// already moves the seed past them. The reservation stays separate from the seed because the
/// writer's growth lives above the limit and a file's handles there are not followed (#913).
pub fn reserve_handle(&mut self, h: Handle) {
if h.0 >= HANDLE_LIMIT {
self.reserved_handles.insert(h.0);
}
}
/// Make sure future handles don't collide with `h` (after loading a file).
///
/// A handle at or above [`HANDLE_LIMIT`] is the file's own and stays as it is: it is not
/// followed, so a new object is never given the top handle and the file's object is never
/// replaced (#913). The handles above the limit are the drawing's room to grow.
pub fn bump_handseed(&mut self, h: Handle) {
if h.0 >= self.handseed && h.0 < HANDLE_LIMIT {
self.handseed = h.0 + 1;
if h.0 >= self.handseed {
self.handseed = h.0.saturating_add(1);
}
}
-28
View File
@@ -726,34 +726,6 @@ fn new_handles_skip_the_files_object_handles() {
assert_eq!(d.new_handle(), Handle(next + 3));
}
/// In the reserved band a new handle skips the file's kept object handles (#2514) and the handles
/// objects hold in model space, a layout and a block definition, or that a file record reserved
/// (#913); off the top of the range it goes on at the bottom of the band. HANDSEED reports the
/// handle `new_handle` takes.
#[test]
fn new_handles_in_the_reserved_band_skip_every_held_handle_and_wrap() {
let mut d = Drawing::new_metric();
let top = u64::MAX;
d.model.push(Entity::new(Handle(top - 4), line((0.0, 0.0), (1.0, 0.0))));
let mut sheet = Layout::new("Sheet", 1);
sheet.entities.push(Entity::new(Handle(top - 3), line((0.0, 0.0), (1.0, 0.0))));
d.layouts.push(sheet);
let mut b = Block::new("B");
b.entities.push(Entity::new(Handle(top - 2), line((0.0, 0.0), (1.0, 0.0))));
d.blocks.insert("B".into(), std::sync::Arc::new(b));
std::sync::Arc::make_mut(&mut d.foreign).handles.insert(Handle(top - 1), ("LAYER".into(), "0".into()));
d.reserve_handle(Handle(top));
d.model.push(Entity::new(Handle(HANDLE_LIMIT), line((0.0, 0.0), (1.0, 0.0))));
d.handseed = top - 5;
assert_eq!(d.new_handle(), Handle(top - 5));
assert_eq!(d.next_handle(), Handle(HANDLE_LIMIT + 1), "a held handle was offered");
assert_eq!(d.new_handle(), Handle(HANDLE_LIMIT + 1));
assert_eq!(d.handseed, HANDLE_LIMIT + 2);
// Handle 0 means "no handle" in a file; a seed there moves on.
d.handseed = 0;
assert_eq!(d.new_handle(), Handle(1));
}
/// Several spellings of one DIM field apply once, the last in the map's order, and none is rejected.
#[test]
fn dim_style_spellings_of_one_field_apply_once() {
+1 -7
View File
@@ -319,14 +319,8 @@ fn all_handles(d: &Drawing) -> HashSet<Handle> {
}
/// The next handle is above every handle in use, so new objects never take an existing one.
///
/// A handle at or above [`cadcraft_doc::HANDLE_LIMIT`] is the file's own and is deliberately not
/// followed: the seed never moves past it, and new objects take free handles in the band above
/// the limit. Reporting it would repeat the same repair on every audit, so it is not an issue.
/// Such a handle is left out of the maximum too, or the largest handle would hide every ordinary
/// one behind it and the seed would never be repaired past them.
fn handseed(d: &mut Drawing, out: &mut Vec<Issue>) {
let Some(max) = each_entity(d).map(|e| e.handle).filter(|h| h.0 < cadcraft_doc::HANDLE_LIMIT).max() else { return };
let Some(max) = each_entity(d).map(|e| e.handle).max() else { return };
if max.0 >= d.handseed {
out.push(issue(
"handseed",
+3 -31
View File
@@ -18,13 +18,8 @@ use crate::{Result, Session};
/// Most image files loaded per drawing.
const MAX_IMAGE_FILES: usize = 1000;
/// Largest image file read (bytes).
#[cfg(not(target_arch = "wasm32"))]
const MAX_IMAGE_BYTES: u64 = 256 << 20;
/// Longest base64 text taken for `data`: what a file of [`MAX_IMAGE_BYTES`] encodes to.
const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4;
/// Longest `data` text with the line breaks and spaces base64 may carry (MIME breaks every 76
/// characters, under 3% more): the characters past [`MAX_IMAGE_BASE64`] are counted only up to
/// here, which also bounds what decoding sets aside.
const MAX_IMAGE_TEXT: u64 = MAX_IMAGE_BASE64 + MAX_IMAGE_BASE64 / 16;
/// Most decoded pixel bytes kept per drawing; images past it stay unloaded.
const MAX_LOADED_BYTES: u64 = 2 << 30;
/// Most image files decoded at the same time when a drawing opens.
@@ -75,22 +70,11 @@ fn paths(d: &Drawing) -> Vec<String> {
paths
}
/// Whether `path` is a full path here, or on Windows where a drawing may have been written (a
/// drive, `C:\maps\a.png`, or a share, `\\server\maps`), which other systems read as relative.
#[cfg(not(target_arch = "wasm32"))]
fn full_path(path: &str) -> bool {
let b = path.trim().as_bytes();
std::path::Path::new(path.trim()).is_absolute() || b.starts_with(b"\\\\") || matches!(b, [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic())
}
/// The contents of the image file saved as `path` in a drawing at `host`.
fn read_file(path: &str, host: Option<&str>) -> std::result::Result<Vec<u8>, String> {
#[cfg(not(target_arch = "wasm32"))]
{
let file = super::blocks::xref::find_file(path, host).ok_or_else(|| {
// An unsaved drawing has no folder for a relative path to be relative to.
if host.is_none() && !full_path(path) { "file not found (save the drawing first, or give a full path)" } else { "file not found" }
})?;
let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?;
let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len();
if len > MAX_IMAGE_BYTES {
return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20));
@@ -320,19 +304,7 @@ fn pixels(s: &Session, p: &Value, path: &str) -> Result<Arc<Raster>> {
let bytes = match p.get("data") {
Some(data) => {
let text = data.as_str().ok_or_else(|| bad(ID, "`data` must be base64 text"))?;
// Refused before decoding, which would hold all of it in memory. Line breaks and
// spaces, which decoding skips, don't count.
let len = u64::try_from(text.len()).unwrap_or(u64::MAX);
let digits = || u64::try_from(text.bytes().filter(|b| !matches!(b, b'\n' | b'\r' | b' ')).count()).unwrap_or(u64::MAX);
if len > MAX_IMAGE_TEXT || (len > MAX_IMAGE_BASE64 && digits() > MAX_IMAGE_BASE64) {
return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20)));
}
let bytes = base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?;
// The longest text allowed can still hold a byte or two more than the limit.
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_IMAGE_BYTES {
return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20)));
}
bytes
base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?
}
None => {
if let Some(loaded) = s.doc()?.rasters.get(path) {
+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"
+6 -11
View File
@@ -139,9 +139,6 @@ pub struct LispState {
/// Interpreter steps all synchronous callbacks have run, nested ones included. A callback's
/// allowance counts what ran since it started, so the callbacks it calls spend its steps.
pub(crate) callback_used: u64,
/// Work synchronous callbacks did inside the running step, already counted in `callback_used`:
/// the step is charged it without charging the enclosing callback a second time.
pub(crate) callback_work: u64,
/// The `callback_used` value the callback running now (and so every one it calls) must not
/// pass: the lowest of its own and its callers' allowances.
pub(crate) callback_ceiling: Option<u64>,
@@ -386,14 +383,6 @@ impl Session {
let uid = run.uid;
self.lisp_flush(&mut env, false);
self.lisp_env_put(uid, env);
// The work the slice did, which one step can take far past the slice. After a panic
// `used` is still the previous slice's; the run ends with the error anyway.
run.steps = run.steps.saturating_add(run.machine.used);
if run.blocking && run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_)) {
self.lisp.run = Some(run);
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
return;
}
match outcome {
Outcome::Done(v) => {
self.lisp.run = Some(run);
@@ -406,7 +395,13 @@ impl Session {
return;
}
Outcome::Wait(Need::Yield) => {
run.steps = run.steps.saturating_add(SLICE);
if run.blocking {
if run.steps > BLOCKING_CAP {
self.lisp.run = Some(run);
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
return;
}
self.lisp.run = Some(run);
continue;
}
+8 -41
View File
@@ -175,19 +175,17 @@ pub struct Machine {
stack: Vec<Frame>,
state: State,
need: Option<Need>,
/// Steps the last [`Machine::run`] took, with the work done inside them.
pub(crate) used: u64,
}
impl Machine {
/// A machine evaluating `forms` in turn.
pub fn forms(forms: Vec<Value>) -> Machine {
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None, used: 0 }
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None }
}
/// A machine calling `f` with `args`.
pub fn calling(f: Value, args: Vec<Value>) -> Machine {
Machine { stack: Vec::new(), state: State::Call(f, args), need: None, used: 0 }
Machine { stack: Vec::new(), state: State::Call(f, args), need: None }
}
/// Give the value a [`Need`] waited for, and carry on.
@@ -195,31 +193,12 @@ impl Machine {
self.state = State::Ret(v);
}
/// Run until done, waiting, or `budget` steps. A step that walks a long list (`length`) or
/// runs a synchronous callback counts that work too, so one slice stays short.
/// Run until done, waiting, or `budget` steps.
pub fn run(&mut self, ctx: &mut Ctx<'_>, budget: u64) -> Outcome {
let mut n = 0u64;
let outcome = self.run_counted(ctx, budget, &mut n);
// The last step's work too, so nothing is left for the next run.
self.used = n.saturating_add(Machine::take_step_work(ctx));
outcome
}
/// The work the last step did besides itself: the lists it walked, which count against a
/// callback's allowance too, and the callbacks it ran, which were counted there as they ran.
fn take_step_work(ctx: &mut Ctx<'_>) -> u64 {
let walked = super::value::take_work();
let callbacks = std::mem::take(&mut ctx.s.lisp.callback_work);
if ctx.depth > 0 {
ctx.s.lisp.callback_used = ctx.s.lisp.callback_used.saturating_add(walked);
}
walked.saturating_add(callbacks)
}
fn run_counted(&mut self, ctx: &mut Ctx<'_>, budget: u64, n: &mut u64) -> Outcome {
loop {
*n = n.saturating_add(1).saturating_add(Machine::take_step_work(ctx));
if *n > budget {
n += 1;
if n > budget {
return Outcome::Wait(Need::Yield);
}
// Charge a callback's step as it runs, so callbacks it calls see what it already spent.
@@ -672,10 +651,6 @@ impl Ctx<'_> {
return Ok(v);
}
let cap = self.s.lisp.limits.callback_steps;
// Work the caller queued before this call (its list walks, earlier callbacks of the same
// step) is not this callback's: set it aside and hand it back with this callback's.
let pending = super::value::take_work();
let pending_callbacks = std::mem::take(&mut self.s.lisp.callback_work);
let start = self.s.lisp.callback_used;
// This callback may run until `callback_used` reaches `ceiling`: `cap` steps from now, or
// sooner where a caller's allowance ends, so callbacks nested in callbacks share one
@@ -683,20 +658,13 @@ impl Ctx<'_> {
let outer = self.s.lisp.callback_ceiling;
let ceiling = start.saturating_add(cap).min(outer.unwrap_or(u64::MAX));
self.s.lisp.callback_ceiling = Some(ceiling);
let mut spent: u64 = 0;
let r = self.drive_callback(f, args, ceiling, &mut spent);
let r = self.drive_callback(f, args, ceiling);
self.s.lisp.callback_ceiling = outer;
super::value::charge_work(pending);
// Its steps, nested callbacks' included, are work done inside the caller's one step: they
// count against the caller's slice and every enclosing callback's. They are in
// `callback_used` already, so they reach the caller apart from its list walks.
self.s.lisp.callback_work = pending_callbacks.saturating_add(spent);
r
}
/// Run callback `f` in slices until it finishes or `callback_used` reaches `ceiling`, adding
/// the work each slice did to `spent`.
fn drive_callback(&mut self, f: &Value, args: Vec<Value>, ceiling: u64, spent: &mut u64) -> Result<Value, LispError> {
/// Run callback `f` in slices until it finishes or `callback_used` reaches `ceiling`.
fn drive_callback(&mut self, f: &Value, args: Vec<Value>, ceiling: u64) -> Result<Value, LispError> {
let cap = self.s.lisp.limits.callback_steps;
let mut m = Machine::calling(f.clone(), args);
let mut sub = Ctx { s: &mut *self.s, env: &mut *self.env, depth: self.depth + 1 };
@@ -712,7 +680,6 @@ impl Ctx<'_> {
}
let slice = remaining.min(SYNC_SLICE);
let outcome = m.run(&mut sub, slice);
*spent = spent.saturating_add(m.used);
match outcome {
// The steps were charged as they ran; finishing past the shared allowance is a failure too.
Outcome::Done(_) if sub.s.lisp.callback_used > ceiling => {
-106
View File
@@ -247,112 +247,6 @@ fn synchronous_callback_loop_is_an_error_not_a_hang() {
assert_eq!(ok(&mut s, "(vl-sort '(3 1 2) '<)"), "(1 2 3)");
}
/// A step that walks a long list counts its work: one `length` of 32768 cells is past a 1000-step
/// slice, so the slice yields after it.
#[test]
fn walking_a_long_list_counts_against_the_slice() {
use super::eval::{Ctx, Machine, Need, Outcome};
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut env = super::Env::default();
let mut ctx = Ctx { s: &mut s, env: &mut env, depth: 0 };
// Built before the measured run, so only the `length` is counted.
let mut build = Machine::forms(super::read::read_all("(setq l '(1)) (repeat 15 (setq l (append l l)))").unwrap());
assert!(matches!(build.run(&mut ctx, u64::MAX), Outcome::Done(_)));
let mut m = Machine::forms(super::read::read_all("(length l)").unwrap());
// Counted as one step, the walk left the few steps of `(length l)` well inside the slice.
assert!(matches!(m.run(&mut ctx, 1_000), Outcome::Wait(Need::Yield)), "the walk was not charged");
assert!(m.used > 32_768, "{}", m.used);
match m.run(&mut ctx, u64::MAX) {
Outcome::Done(v) => assert_eq!(to_text(&v, true), "32768"),
_ => panic!("the length did not finish"),
}
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}
/// A routine is charged the work its slice did, not the slice's length: one `length` of 2^19
/// cells is far past a 400000-step slice.
#[test]
fn a_routine_is_charged_the_work_of_its_slice() {
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
ok(&mut s, "(setq l '(1)) (repeat 19 (setq l (append l l))) nil");
let r = s.lisp_eval("(length l) (repeat 10 (setq x 1))", false, false, Vec::new()).unwrap();
assert!(r.is_none(), "the routine gave the interface a frame");
assert!(s.lisp_busy());
let steps = s.lisp.run.as_ref().map(|r| r.steps).unwrap_or(0);
assert!(steps >= 1 << 19, "{steps}");
for _ in 0..100 {
if !s.lisp_busy() {
break;
}
s.lisp_tick();
}
assert!(!s.lisp_running());
ok(&mut s, "(setq l nil)");
}
/// A run's last step walking a long list is charged to that run, not left for the next one: here
/// it fails after the walk (a list of numbers isn't a list of strings), so no step follows it.
#[test]
fn the_last_steps_list_walk_is_charged_to_its_run() {
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut env = super::Env::default();
env.globals.insert(super::value::Sym::new("L"), Value::list(vec![Value::Int(1); 100_000]));
let mut m = super::eval::Machine::forms(super::read::read_all("(acad_strlsort l)").unwrap());
let mut ctx = super::eval::Ctx { s: &mut s, env: &mut env, depth: 0 };
assert!(matches!(m.run(&mut ctx, u64::MAX), super::eval::Outcome::Error(_)));
assert!(m.used > 100_000, "{}", m.used);
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}
/// Nested callbacks share one cap: an inner endless callback retried by an outer one stops.
#[test]
fn nested_callback_steps_count_against_the_outer_callback() {
let mut s = session();
s.lisp.limits.callback_steps = 10_000;
// Each level retried the endless level inside it with a fresh cap: 10000^3 steps, a hang.
let code = "(defun g (a b) (while t)) \
(defun f (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'g)))) \
(defun h (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'f)))) \
(vl-sort '(1 2) 'h)";
assert_eq!(eval(&mut s, code), Err("callback stopped after 10000 steps".into()));
// A callback's own steps count once, however many slices it runs in: three slices do three
// times the work of one.
let counts: Vec<u64> = [400_000, 1_200_000]
.into_iter()
.map(|cap| {
s.lisp.limits.callback_steps = cap;
ok(&mut s, "(setq n 0)");
assert!(eval(&mut s, "(vl-remove-if '(lambda (x) (while t (setq n (1+ n)))) '(1))").is_err());
ok(&mut s, "n").parse().unwrap()
})
.collect();
assert!(counts[1] * 10 >= counts[0] * 29, "{counts:?}");
}
/// The callback cap holds for each callback: a sort's comparisons together take more steps than
/// it, and all their work still reaches the enclosing run.
#[test]
fn each_callback_has_its_own_cap_and_its_work_reaches_the_caller() {
let mut s = session();
s.lisp.limits.callback_steps = 1_000;
let mut env = super::Env::default();
env.globals.insert(super::value::Sym::new("L"), Value::list((0..300).rev().map(Value::Int)));
let mut m = super::eval::Machine::forms(super::read::read_all("(vl-sort l (function (lambda (a b) (< a b))))").unwrap());
let mut ctx = super::eval::Ctx { s: &mut s, env: &mut env, depth: 0 };
let v = match m.run(&mut ctx, u64::MAX) {
super::eval::Outcome::Done(v) => v,
super::eval::Outcome::Error(e) => panic!("the sort failed: {e:?}"),
super::eval::Outcome::Wait(_) => panic!("the sort waited"),
};
assert_eq!(to_text(&v, true), to_text(&Value::list((0..300).map(Value::Int)), true));
// Over a thousand comparisons of several steps each, together well past the cap.
assert!(m.used > 3_000, "{}", m.used);
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}
/// A zero-step callback limit prevents even the first callback side effect.
#[test]
fn a_zero_callback_budget_does_not_run_the_callback() {
+1 -17
View File
@@ -64,8 +64,6 @@ thread_local! {
static STRING_BYTES: Cell<(u64, u64)> = const { Cell::new((0, STRING_BUDGET)) };
/// The running slice's cap on live cons cells.
static CELL_LIMIT: Cell<usize> = const { Cell::new(MAX_CELLS) };
/// Work done inside the current machine step: list cells walked, steps of synchronous callbacks.
static WORK: Cell<u64> = const { Cell::new(0) };
}
/// Start a slice of a run on this thread: it fails when more than `limit` cells are alive.
@@ -78,16 +76,6 @@ pub fn check_cells() -> Result<(), LispError> {
if live_cells() > CELL_LIMIT.with(Cell::get) { Err(LispError::quit("out of memory: too many list cells")) } else { Ok(()) }
}
/// Count `n` units of work done inside one machine step ([`super::eval::Machine::run`] charges them as steps).
pub fn charge_work(n: u64) {
WORK.with(|c| c.set(c.get().saturating_add(n)));
}
/// The work counted since the last call.
pub fn take_work() -> u64 {
WORK.with(|c| c.replace(0))
}
/// Start a slice of a run on this thread: it has made `used` bytes of its `budget`.
pub fn set_string_budget(used: u64, budget: u64) {
STRING_BYTES.with(|c| c.set((used, budget)));
@@ -274,10 +262,7 @@ impl Value {
loop {
match v {
Value::Nil => return true,
Value::Cons(c) => {
charge_work(1);
v = c.cdr.clone();
}
Value::Cons(c) => v = c.cdr.clone(),
_ => return false,
}
}
@@ -333,7 +318,6 @@ impl Iterator for ListIter {
fn next(&mut self) -> Option<Value> {
match std::mem::take(&mut self.next) {
Value::Cons(c) => {
charge_work(1);
self.next = c.cdr.clone();
Some(c.car.clone())
}
-36
View File
@@ -329,39 +329,3 @@ fn auditctl_generates_adt_report_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_handle_in_the_reserved_band_is_not_repaired_on_every_audit() {
// A file object above HANDLE_LIMIT keeps its handle, and the seed deliberately does not move
// past it (#913). AUDIT must not report that policy as an error its own repair never fixes.
let band = Handle(cadcraft_engine::doc::HANDLE_LIMIT);
let mut d = Drawing::new_imperial();
d.space_mut(&Space::Model).unwrap().push(Entity { handle: band, common: Common::default(), kind: line((0.0, 0.0), (1.0, 0.0)) });
d.handseed = band.0;
for _ in 0..3 {
let r = cadcraft_engine::audit::check(&d);
assert!(r.issues.iter().all(|i| i.kind != "handseed"), "{}", r.message());
}
let mut repaired = d.clone();
let r = cadcraft_engine::audit::repair(&mut repaired);
assert!(r.iter().all(|i| i.kind != "handseed"), "{r:?}");
assert_eq!(repaired.handseed, band.0, "the seed moved past the file's own handle");
}
#[test]
fn an_ordinary_handle_behind_a_reserved_band_one_is_still_repaired() {
// The largest handle is in the reserved band, which the seed deliberately does not follow.
// An ordinary handle above the seed must still be found behind it: it is the one the seed
// has to move past, and skipping the check would leave AUDIT reporting a clean drawing.
let band = Handle(cadcraft_engine::doc::HANDLE_LIMIT);
let mut d = Drawing::new_imperial();
let store = d.space_mut(&Space::Model).unwrap();
store.push(Entity { handle: Handle(20), common: Common::default(), kind: line((0.0, 0.0), (1.0, 0.0)) });
store.push(Entity { handle: band, common: Common::default(), kind: line((2.0, 0.0), (3.0, 0.0)) });
d.handseed = 10;
let r = cadcraft_engine::audit::repair(&mut d);
assert!(r.iter().any(|i| i.kind == "handseed" && i.message.contains("(14)")), "the ordinary handle was hidden: {r:?}");
assert_eq!(d.handseed, 21, "the seed was not moved past the ordinary handle");
let r = cadcraft_engine::audit::repair(&mut d.clone());
assert!(r.iter().all(|i| i.kind != "handseed"), "the repair does not stick: {r:?}");
}
-45
View File
@@ -142,51 +142,6 @@ fn bad_input_is_refused_and_changes_nothing() {
assert_eq!(listed(&mut s), json!([]));
}
/// `data` longer than the largest image file encodes to is refused before it is decoded.
#[test]
fn oversized_data_is_refused_before_decoding() {
hooks();
const LIMIT: u64 = 256 << 20;
let mut s = Session::new();
// Not base64 at all: only the check before decoding tells it is too long ("not valid base64"
// otherwise), and nothing is decoded.
let too_long = "!".repeat(usize::try_from(LIMIT.div_ceil(3) * 4 + 1).unwrap());
let e = s.execute("imageattach", &json!({ "path": "a.png", "data": too_long })).unwrap_err().to_string();
assert!(e.contains("`data` is larger than 256 MB"), "{e}");
// Line breaks don't count: base64 wrapped as MIME writes it is taken.
let wrapped: String = base64_encode(&png()).as_bytes().chunks(76).map(|c| format!("{}\r\n", String::from_utf8_lossy(c))).collect();
s.execute("imageattach", &json!({ "path": "wrapped.png", "data": wrapped })).unwrap();
s.execute("undo", &json!({})).unwrap();
// The longest text allowed, holding one byte more than the limit, is refused once decoded.
let groups = usize::try_from(LIMIT / 3).unwrap();
let one_over = format!("{}AAA=", "AAAA".repeat(groups));
assert_eq!(u64::try_from(one_over.len()).unwrap(), LIMIT.div_ceil(3) * 4, "as long as the text for the limit itself");
let e = s.execute("imageattach", &json!({ "path": "a.png", "data": one_over })).unwrap_err().to_string();
assert!(e.contains("`data` is larger than 256 MB"), "{e}");
assert!(images(&s).is_empty());
}
/// A relative path in an unsaved drawing has nothing to be relative to, and the error says so.
#[test]
fn a_relative_path_in_an_unsaved_drawing_says_what_to_do() {
hooks();
let mut s = Session::new();
let e = s.execute("imageattach", &json!({ "path": "missing.png" })).unwrap_err().to_string();
assert!(e.contains("save the drawing first, or give a full path"), "{e}");
let dir = folder("unsaved");
let full = dir.join("missing.png");
let e = s.execute("imageattach", &json!({ "path": full.to_string_lossy() })).unwrap_err().to_string();
assert!(e.contains("file not found") && !e.contains("save the drawing"), "{e}");
// A full Windows path, read as relative elsewhere, is a full path all the same.
for windows in [r"C:\nowhere\a.png", "D:/nowhere/a.png", r"\\server\maps\a.png"] {
let e = s.execute("imageattach", &json!({ "path": windows })).unwrap_err().to_string();
assert!(e.contains("file not found") && !e.contains("save the drawing"), "{windows}: {e}");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_image_among_many_objects_keeps_its_pixels() {
// More objects than one build task takes: the display list is built in parts and joined,
+6 -19
View File
@@ -56,17 +56,11 @@ pub struct ShxGlyph {
pub advance: Vec2,
}
/// Glyphs cached per font, keyed by (shape, vertical), and their points in all.
#[derive(Default)]
struct GlyphCache {
glyphs: HashMap<(u16, bool), Option<Arc<ShxGlyph>>>,
points: usize,
}
/// Glyphs cached per font, keyed by (shape, vertical).
type GlyphCache = HashMap<(u16, bool), Option<Arc<ShxGlyph>>>;
/// Most glyphs cached per font (a big font has thousands; text uses a few hundred).
const MAX_CACHED_GLYPHS: usize = 16_384;
/// Most points cached per font (16 MB; a glyph may hold thousands of points).
const MAX_CACHED_POINTS: usize = 1 << 20;
/// A parsed SHX file.
pub struct ShxFont {
@@ -209,22 +203,15 @@ impl ShxFont {
}
let vertical = vertical && self.dual;
let key = (number, vertical);
if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).glyphs.get(&key) {
if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).get(&key) {
return g.clone();
}
let g = program::outline(self, number, vertical).ok().map(Arc::new);
let points = g.as_ref().map_or(0, |g| g.strokes.iter().map(Vec::len).sum::<usize>());
let mut c = self.cache.write().unwrap_or_else(PoisonError::into_inner);
// Another thread may have outlined it in the meantime: its points are counted already.
if let Some(g) = c.glyphs.get(&key) {
return g.clone();
if c.len() >= MAX_CACHED_GLYPHS {
c.clear();
}
if c.glyphs.len() >= MAX_CACHED_GLYPHS || c.points.saturating_add(points) > MAX_CACHED_POINTS {
c.glyphs.clear();
c.points = 0;
}
c.points = c.points.saturating_add(points);
c.glyphs.insert(key, g.clone());
c.insert(key, g.clone());
g
}
}
-16
View File
@@ -309,22 +309,6 @@ fn hostile_files_never_panic() {
assert!(compile("").is_err());
}
#[test]
fn the_glyph_cache_is_bounded_by_points() {
// Hostile: every glyph at the point bound, so 16,384 cached glyphs would hold 2 GB.
let mut src = format!("*2,1,HUNDRED\n{}0\n*3,3,V\n011,019,0\n", "7,3,".repeat(100));
for n in 10..=200 {
src.push_str(&format!("*{n},1,HEAVY\n{}0\n", "7,2,".repeat(40)));
}
let f = font(&src);
for n in 10..=200 {
assert!(f.glyph(n, false).is_some());
}
let c = f.cache.read().unwrap();
let cached: usize = c.glyphs.values().flatten().map(|g| g.strokes.iter().map(Vec::len).sum::<usize>()).sum();
assert!(cached <= MAX_CACHED_POINTS && cached == c.points, "{cached}");
}
/// Register a compiled test font under `name` (each test its own names: the table is shared).
fn reg(name: &str, src: &str) {
register(name, &compile(src).unwrap()).unwrap();
+6 -34
View File
@@ -1062,10 +1062,11 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
alive_memo
});
// New handles for the written kept objects, above every written handle and the seed.
let mut fresh = Fresh::new(tags);
let mut next = seed(tags).max(max_handle(tags).saturating_add(1));
let mut alive: HashMap<String, String> = HashMap::new();
for o in f.objects.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) {
alive.insert(o.handle.hex(), format!("{:X}", fresh.take()));
alive.insert(o.handle.hex(), format!("{next:X}"));
next = next.saturating_add(1);
}
let entities: HashSet<String> = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect();
let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities };
@@ -1388,18 +1389,19 @@ fn add_appids(out: &mut Vec<Tag>) {
return;
}
// New handles above the seed, which is then moved past them.
let mut fresh = Fresh::new(out);
let mut next = seed(out).max(max_handle(out).saturating_add(1));
let mut add = Vec::new();
for app in &missing {
add.extend([
Tag::s(0, "APPID"),
Tag::s(5, format!("{:X}", fresh.take())),
Tag::s(5, format!("{next:X}")),
Tag::s(330, table_h.clone()),
Tag::s(100, "AcDbSymbolTableRecord"),
Tag::s(100, "AcDbRegAppTableRecord"),
Tag::s(2, (*app).clone()),
Tag::i(70, 0),
]);
next = next.saturating_add(1);
}
let end_at = end.start;
if let Some(count) = out.get_mut(t.start + 1..t.end).and_then(|b| b.iter_mut().find(|x| x.code == 70)) {
@@ -1418,36 +1420,6 @@ fn seed(tags: &[Tag]) -> u64 {
seed_index(tags).and_then(|i| tags.get(i)).and_then(|t| Handle::parse_hex(&t.str())).map_or(0, |h| h.0)
}
/// New handles for records added to written tags: above the seed and every handle written, and
/// never one a record already holds. A file may hold the top handle (#913): then counting on from
/// it would give every added record that same handle, so past the top of the range the numbering
/// goes on in the reserved band above [`cadcraft_doc::HANDLE_LIMIT`], skipping the handles there.
struct Fresh {
next: u64,
used: HashSet<u64>,
}
impl Fresh {
fn new(tags: &[Tag]) -> Self {
let used: HashSet<u64> =
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).collect();
let above = used.iter().max().map_or(0, |h| h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT));
Fresh { next: seed(tags).max(above), used }
}
/// The next free handle. Each handle skipped is one a record holds, so the walk is bounded
/// by their count (and handle 0, which means "none").
fn take(&mut self) -> u64 {
for _ in 0..self.used.len().saturating_add(2) {
let h = self.next;
self.next = h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT);
if h != 0 && self.used.insert(h) {
return h;
}
}
self.next
}
}
/// The largest handle of a record (groups 5 and 105).
fn max_handle(tags: &[Tag]) -> u64 {
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).max().unwrap_or(0)
+4 -32
View File
@@ -102,36 +102,11 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
// its $HANDSEED can be lower than its handles, and entities made while reading (the faces of
// a polygon mesh) would otherwise get handles that records further on still have. A file
// CADCraft wrote names its own next handle, above which its rebuilt records are numbered
// (#495), so for it only the entity records are reserved. Handles in the reserved band are
// reserved for allocation rather than followed (#913): a handle-less entity read before the
// section that names one is placed would otherwise be given it and replace the record (#1276).
// (#495), so it is left to that.
let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str() == crate::dxf_ext::HANDSEED_KEY));
if ours {
// Its table and object records are numbered above its seed and rebuilt on save (#495),
// so only its entities are reserved. Reading is section by section: an entity that has
// no handle, or repeats one within its section, gets a fresh handle, and that must not
// be one an entity of a later section still names. `BLOCK` and `ENDBLK` are structural
// records, not entities, and are left out so they don't move the saved seed.
for (kind, tags) in secs.iter().filter(|s| s.name == "BLOCKS" || s.name == "ENTITIES").flat_map(|s| records(&s.tags)) {
if matches!(kind.as_str(), "BLOCK" | "ENDBLK") {
continue;
}
if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(t.str().trim())) {
d.bump_handseed(h);
d.reserve_handle(h);
}
}
} else {
for s in &secs {
let entity_section = s.name == "BLOCKS" || s.name == "ENTITIES";
for t in s.tags.iter().filter(|t| t.code == 5 || t.code == 105) {
if let Some(h) = Handle::parse_hex(t.str().trim()) {
d.bump_handseed(h);
if entity_section {
d.reserve_handle(h);
}
}
}
for t in secs.iter().filter(|_| !ours).flat_map(|s| s.tags.iter()).filter(|t| t.code == 5 || t.code == 105) {
if let Some(h) = Handle::parse_hex(t.str().trim()) {
d.bump_handseed(h);
}
}
let mut skipped = std::collections::BTreeMap::new();
@@ -173,9 +148,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
crate::dxf_raw::read(&secs, &mut d);
crate::dxf_clip::read(&mut d);
d.skipped_records = skipped;
// Every record is placed now, and an object holding a reserved handle keeps it from new
// objects by itself. Kept, the set would be copied with every undo step of the drawing.
d.reserved_handles.clear();
Ok(d)
}
-1
View File
@@ -55,7 +55,6 @@ pub(super) fn parse_entities(
}
if let Some((c, mut k)) = kindent {
let h = match handle {
// A file's handles keep their identity, however high they are (#913, #939).
Some(h) => {
d.bump_handseed(h);
h
+5 -34
View File
@@ -3,7 +3,7 @@
//! the newer DIMSTYLE groups, and from 2007 in UTF-8 text (the caller picks the text encoding) and
//! MULTILEADER entities (older files get LEADER + MTEXT).
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use cadcraft_color::Color;
use cadcraft_doc::{
@@ -39,9 +39,6 @@ use sections::tags_for;
struct W {
t: Vec<Tag>,
next: u64,
/// Handles the drawing's objects already hold: structural records skip them, so writing a
/// file whose own handles sit near the top of the range never repeats a handle (#913).
used: HashSet<u64>,
/// Upper-case plot style name → its `ACDBPLACEHOLDER` handle (group 390 of layers and objects).
pstyles: HashMap<String, String>,
/// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports).
@@ -51,21 +48,6 @@ struct W {
reactors: HashMap<Handle, Vec<String>>,
}
/// Where the writer's own records (tables, objects, dictionaries) start numbering: above every
/// object handle and the drawing's seed, with headroom for handles the drawing allocates next.
fn structural_start(d: &Drawing) -> u64 {
let highest = entity_handles(d).max().unwrap_or(0);
d.handseed.max(0x100).max(highest.saturating_add(1)).saturating_add(0x1000)
}
/// Every handle an object holds, plus the drawing's next one.
fn entity_handles(d: &Drawing) -> impl Iterator<Item = u64> + '_ {
let model = d.model.iter().map(|e| e.handle.0);
let layouts = d.layouts.iter().flat_map(|l| l.entities.iter()).map(|e| e.handle.0);
let blocks = d.blocks.values().flat_map(|b| b.entities.iter()).map(|e| e.handle.0);
model.chain(layouts).chain(blocks).chain(std::iter::once(d.handseed))
}
impl W {
fn s(&mut self, c: i32, v: impl Into<String>) {
self.t.push(Tag::s(c, v));
@@ -89,20 +71,10 @@ impl W {
format!("{:X}", self.next_handle())
}
/// A new handle for a record the drawing doesn't hold (as [`W::h`]).
///
/// Skips every handle in use, so a file object carrying a handle above the seed (the
/// reserved band) is not handed out again, and wraps into that band if the writer runs off
/// the top of the range. Each handle skipped is one in use, so the walk is bounded by their
/// count.
fn next_handle(&mut self) -> u64 {
for _ in 0..self.used.len().saturating_add(1) {
let h = self.next;
self.next = h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT);
if self.used.insert(h) {
return h;
}
}
self.next
let h = self.next;
self.next = self.next.saturating_add(1);
h
}
/// A `102 {NAME` … `102 }` group of handles.
fn group(&mut self, name: &str, code: i32, handles: &[&str]) {
@@ -180,8 +152,7 @@ fn bridge_markers(tags: &mut [Tag]) {
pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec<Tag>) {
let mut w = W {
t: Vec::new(),
next: structural_start(d),
used: entity_handles(d).collect(),
next: d.handseed.max(0x100).saturating_add(0x1000),
pstyles: HashMap::new(),
layers: HashMap::new(),
reactors: HashMap::new(),
+1 -8
View File
@@ -16,14 +16,7 @@ pub(super) fn annotative_xdata(w: &mut W) {
/// Override (`ACAD` DSTYLE) and associativity (`CADCRAFT` ASSOC) xdata of a dimension.
pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) {
let mut ov = W {
t: Vec::new(),
next: 0,
used: std::collections::HashSet::new(),
pstyles: HashMap::new(),
layers: HashMap::new(),
reactors: HashMap::new(),
};
let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
let mut sah = false;
for (k, v) in &dm.overrides {
let Some(field) = DimStyle::field_name(k) else { continue };
+7 -9
View File
@@ -7,10 +7,9 @@ use super::header::{code_page, header_vars};
use super::layout::{paper_views, record_head, sheet_first, table_head, vport_table};
use super::objects::{cadcraft_fonts_name, group_obj, mleader_style_obj, scale_list, table_style_obj};
use super::{
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, HashSet, Layout, MLeaderStyle, PageSetup,
Space, TableStyle, Tag, Vec2, Vec3, Version, W, dxf_ext,
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, Layout, MLeaderStyle, PageSetup, Space,
TableStyle, Tag, Vec2, Vec3, Version, W, dxf_ext,
};
use super::{entity_handles, structural_start};
struct TableWritePlan<'a> {
d: &'a Drawing,
@@ -246,7 +245,7 @@ fn write_dimstyles(w: &mut W, d: &Drawing, cx: &mut Ctx, version: Version) {
w.i(70, 0);
let v = serde_json::to_value(s).unwrap_or_default();
let defaults = serde_json::to_value(DimStyle::default()).unwrap_or_default();
let mut newer = W { t: Vec::new(), next: 0, used: HashSet::new(), pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
let mut newer = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
for (field, code, kind) in dxf_ext::DIM_CODES {
let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue };
// DIMPOST is written even when empty: a reader that defaults a missing one to "<>"
@@ -917,8 +916,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
// Structural handles start above every entity handle.
let mut w = W {
t: Vec::new(),
next: structural_start(d),
used: entity_handles(d).collect(),
next: d.handseed.max(0x100).saturating_add(0x1000),
pstyles: HashMap::new(),
layers: HashMap::new(),
reactors: hatch_reactors(d),
@@ -1095,11 +1093,11 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
for (n, h, b) in &user_blocks {
block(&mut w, (n, &b.description), h, b.base, if b.anonymous { 1 } else { 0 }, &mut b.entities.iter().map(|e| e.as_ref()), false);
}
// Generated geometry entities (dimension, arrowhead and table blocks) need handles; take
// them from the writer's allocator, which skips the drawing's own handles.
// Generated geometry entities (dimension, arrowhead and table blocks) need handles.
for (_, _, ents) in dim_defs.iter_mut().chain(arrow_defs.iter_mut()).chain(table_defs.iter_mut()) {
for e in ents.iter_mut().filter(|e| e.handle.0 == 0) {
e.handle = Handle(w.next_handle());
e.handle = Handle(w.next);
w.next = w.next.saturating_add(1);
}
}
for (n, h, ents) in &dim_defs {
+16 -122
View File
@@ -17,7 +17,7 @@ use std::collections::BTreeMap;
use cadcraft_color::Color;
use cadcraft_doc::{Circle, Common, Drawing, Ellipse, EntityKind, Layer, Line, LwPolyline, Space};
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3, bulge_to_arc};
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3};
use crate::{IoError, Result};
@@ -70,8 +70,6 @@ struct Parser {
verts_left: usize,
/// What was left out, by kind ([`LeftOut`]).
left_out: BTreeMap<LeftOut, usize>,
/// Shapes left out because their coordinates or extents overflow: invalid, not unsupported.
too_large: usize,
}
/// Drawn content the reader leaves out, named in the drawing's read note.
@@ -107,23 +105,16 @@ impl Parser {
elements: 0,
verts_left: MAX_TOTAL_VERTS,
left_out: BTreeMap::new(),
too_large: 0,
}
}
/// The read notes on what was left out: what isn't read yet, then what is invalid.
fn notes(&self) -> Vec<String> {
let mut notes = Vec::new();
if !self.left_out.is_empty() {
let list: Vec<String> = self.left_out.iter().map(|(k, n)| k.describe(*n)).collect();
notes.push(format!("SVG: CADCraft doesn't read these yet, so they were left out: {}", list.join(", ")));
/// The read note on what was left out, if anything was.
fn note(&self) -> Option<String> {
if self.left_out.is_empty() {
return None;
}
match self.too_large {
0 => {}
1 => notes.push("SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent".into()),
n => notes.push(format!("SVG: {n} shapes were left out as invalid: their coordinates or size are too large to represent")),
}
notes
let list: Vec<String> = self.left_out.iter().map(|(k, n)| k.describe(*n)).collect();
Some(format!("SVG: CADCraft doesn't read these yet, so they were left out: {}", list.join(", ")))
}
fn parse(&mut self, text: &str) -> Result<()> {
@@ -159,7 +150,7 @@ impl Parser {
};
self.left_out.insert(kind, count);
}
self.drawing.read_notes.extend(self.notes());
self.drawing.read_notes.extend(self.note());
Ok(())
}
@@ -227,18 +218,12 @@ impl Parser {
}
// Charge the vertices this entity retains against the shared document budget, so repeated
// flattened arcs/curves cannot amplify a compact path into unbounded geometry (CWE-400).
// A shape left out below was generated all the same, so it is charged too.
let verts = match &kind {
EntityKind::LwPolyline(p) => p.vertices.len(),
EntityKind::Spline(s) => s.control.len(),
_ => 1,
};
self.verts_left = self.verts_left.checked_sub(verts).ok_or_else(|| IoError::Format("SVG: too much generated geometry".into()))?;
// Finite numbers can still overflow through transforms and relative steps (`l1e308 0` twice).
if !finite(&kind) {
self.too_large += 1;
return Ok(());
}
let common = Common { layer: self.layer.clone(), ..Common::default() };
self.drawing.add(&Space::Model, common, kind).map(|_| ()).map_err(parse_err)
}
@@ -246,10 +231,7 @@ impl Parser {
/// A circle or ellipse through a transform. A circle stays a `CIRCLE` under rotations,
/// uniform scales and reflections; anything else becomes an `ELLIPSE` holding the axes
/// of the transformed shape — a linear map sends the unit circle to an ellipse whose
/// semi-axes are the square roots of the eigenvalues of `A·Aᵀ`. With `B = [bx by]` the
/// ellipse is `center + B·(cos t, sin t)`; `B·Bᵀ` lives in the drawing plane, so its leading
/// eigenvector is the major axis's direction. `major` is that axis from the centre, as
/// [`Ellipse::major`] is everywhere else.
/// semi-axes are the square roots of the eigenvalues of `A·Aᵀ`.
fn add_rounded(&mut self, center_user: Vec2, rx: f64, ry: f64) -> Result<()> {
let center = self.map(center_user);
let bx = self.map_vec(Vec2::new(rx, 0.0));
@@ -271,15 +253,18 @@ impl Parser {
if s_max <= f64::EPSILON {
return Ok(());
}
let axis = if xy.abs() <= 1e-12 * trace {
let axis = if xy.abs() <= 1e-12 * trace.max(1.0) {
if yy > xx { Vec2::new(0.0, 1.0) } else { Vec2::new(1.0, 0.0) }
} else {
let v = Vec2::new(xy, l_max - xx);
// |v| ≥ |xy| > 1e-12·trace ≥ 0 here, so the division is never by zero.
v / len(v)
let l = len(v);
if l <= f64::EPSILON {
return Ok(());
}
v / l
};
let ratio = (l_min.max(0.0).sqrt() / s_max).clamp(1e-9, 1.0);
let major = axis * s_max;
let major = center + axis * s_max;
self.add(EntityKind::Ellipse(Ellipse { center: v3(center), major: v3(major), ratio, start: 0.0, end: std::f64::consts::TAU }))
}
@@ -395,79 +380,6 @@ impl Parser {
}
}
/// Every coordinate of an entity the reader makes is finite, and so are its extents: a finite
/// centre and radius can still reach past the largest number.
fn finite(kind: &EntityKind) -> bool {
match kind {
EntityKind::Line(l) => l.a.is_finite() && l.b.is_finite(),
EntityKind::Circle(c) => {
c.center.is_finite()
&& c.radius.is_finite()
&& cadcraft_geom::Circle::new(c.center.xy(), c.radius).bounds().corners().iter().all(|p| p.is_finite())
}
EntityKind::Ellipse(e) => {
// Half the box is `hypot` of the major axis and the minor axis (`ratio` times it, turned).
let (m, r) = (e.major.xy(), e.ratio);
e.center.is_finite() && e.major.is_finite() && e.ratio.is_finite() && box_finite(e.center.xy(), m.x.hypot(r * m.y), m.y.hypot(r * m.x))
}
EntityKind::LwPolyline(p) => p.vertices.iter().all(|v| v.p.is_finite() && v.bulge.is_finite()) && bulges_finite(p),
EntityKind::Spline(s) => s.control.iter().all(|p| p.is_finite()),
// The SVG reader doesn't make these.
EntityKind::Point(_)
| EntityKind::Arc(_)
| EntityKind::Polyline3d(_)
| EntityKind::Helix(_)
| EntityKind::Ray(_)
| EntityKind::XLine(_)
| EntityKind::Text(_)
| EntityKind::MText(_)
| EntityKind::AttDef(_)
| EntityKind::Insert(_)
| EntityKind::Dimension(_)
| EntityKind::MLine(_)
| EntityKind::Leader(_)
| EntityKind::MLeader(_)
| EntityKind::Hatch(_)
| EntityKind::Solid(_)
| EntityKind::Trace(_)
| EntityKind::Face3d(_)
| EntityKind::PolyfaceMesh(_)
| EntityKind::Region(_)
| EntityKind::Viewport(_)
| EntityKind::Image(_)
| EntityKind::Wipeout(_)
| EntityKind::Table(_)
| EntityKind::Tolerance(_)
| EntityKind::Unknown(_) => true,
}
}
/// The box `centre ± (hx, hy)` is finite.
fn box_finite(c: Vec2, hx: f64, hy: f64) -> bool {
[c.x - hx, c.x + hx, c.y - hy, c.y + hy].iter().all(|v| v.is_finite())
}
/// Every arc segment of the polyline (a bulge between finite vertices) has a finite centre and
/// radius, and the quadrant points it passes through are finite.
fn bulges_finite(p: &LwPolyline) -> bool {
let n = p.vertices.len();
p.vertices.iter().enumerate().all(|(i, v)| {
let next = if i + 1 < n {
p.vertices.get(i + 1)
} else if p.closed {
p.vertices.first()
} else {
None
};
let Some((arc, _)) = next.and_then(|w| bulge_to_arc(v.p, w.p, v.bulge)) else { return true };
arc.center.is_finite()
&& arc.radius.is_finite()
&& (0..4)
.map(|k| f64::from(k) * std::f64::consts::FRAC_PI_2)
.all(|a| !arc.contains_angle(a) || Vec2::polar(arc.center, arc.radius, a).is_finite())
})
}
/// One `M …` run of a `d` attribute.
struct Subpath {
start: Vec2,
@@ -559,22 +471,4 @@ mod tests {
assert_eq!(arc_of("M10 10 a20 20 0 1 0 20 20"), (true, false, spaced.2));
assert!(arc_of("M10 10 a20 20 0 10-20 20").0);
}
#[test]
fn extents_past_the_largest_number_are_not_finite() {
let ellipse = |c: Vec2, major: Vec2| EntityKind::Ellipse(Ellipse { center: v3(c), major: v3(major), ratio: 1.0, start: 0.0, end: 0.0 });
assert!(!finite(&ellipse(Vec2::new(1e308, 0.0), Vec2::new(1e308, 0.0))));
assert!(finite(&ellipse(Vec2::new(5e307, 0.0), Vec2::new(5e307, 0.0))));
// Turned, its box is wider than its axis: `centre ± major` is finite, the box isn't.
assert!(!finite(&ellipse(Vec2::new(6e307, 0.0), Vec2::new(9e307, 9e307))));
assert!(finite(&ellipse(Vec2::ZERO, Vec2::new(9e307, 9e307))));
// Half circles between the same finite points: bulging up passes 1.8e308, down doesn't.
let half = |bulge: f64| {
let (a, b) = (Vec2::new(0.0, 1.5e308), Vec2::new(1e308, 1.5e308));
let vertices = vec![PolyVertex::with_bulge(a, bulge), PolyVertex::new(b)];
EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false })
};
assert!(!finite(&half(-1.0)));
assert!(finite(&half(1.0)));
}
}
+1 -117
View File
@@ -2915,75 +2915,12 @@ fn svg_shapes_become_entities_in_millimetres() {
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.radius - 2.0).abs() < 1e-9 && (c.center.x - 10.0).abs() < 1e-9 && (c.center.y - 5.0).abs() < 1e-9, "{c:?}");
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
let major = Vec2::new(e.major.x - e.center.x, e.major.y - e.center.y);
assert!((major.len() - 4.0).abs() < 1e-9 && (e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let l = first(&d, |k| if let EntityKind::Line(l) = k { Some(l.clone()) } else { None });
assert!((l.a.y - 10.0).abs() < 1e-9 && (l.b.y).abs() < 1e-9, "{l:?}");
}
#[test]
fn svg_ellipse_major_axis_is_relative_to_its_centre() {
// Away from the origin: the major axis was stored as the absolute point centre + axis.
let svg = format!("{SVG_PAGE}<ellipse cx=\"15\" cy=\"2\" rx=\"2\" ry=\"1\"/><circle cx=\"15\" cy=\"2\" r=\"1\"/></svg>");
let d = read(svg.as_bytes(), "ellipse.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse", "Circle"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
assert!((e.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9, "{e:?}");
assert!((e.major.x.abs() - 2.0).abs() < 1e-9 && e.major.y.abs() < 1e-9 && e.major.z == 0.0, "{e:?}");
assert!((e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9 && (c.radius - 1.0).abs() < 1e-9, "{c:?}");
}
#[test]
fn svg_rotated_ellipse_keeps_its_turn() {
// The page maps SVG (x, y) to (x, 10 - y); undo that, then rotate by -30°, to get back to the ellipse's own frame.
let svg = format!("{SVG_PAGE}<ellipse cx=\"0\" cy=\"0\" rx=\"20\" ry=\"10\" transform=\"rotate(30)\"/></svg>");
let d = read(svg.as_bytes(), "rotated.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
assert!((major.len() - 20.0).abs() < 1e-9 && (e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let (s, c) = 30f64.to_radians().sin_cos();
let want = Vec2::new(20.0 * c, -20.0 * s);
assert!((major - want).len() < 1e-9 || (major + want).len() < 1e-9, "{e:?}");
let (ux, uy) = (e.center.x + major.x, 10.0 - (e.center.y + major.y));
let (x, y) = (c * ux + s * uy, -s * ux + c * uy);
assert!(((x / 20.0).powi(2) + (y / 10.0).powi(2) - 1.0).abs() < 1e-9, "{e:?}");
}
#[test]
fn svg_sheared_circle_has_the_axes_of_its_image() {
// matrix(1 0 1 1 0 0) is B = [[1, 1], [0, 1]]; the page then flips Y at one millimetre per unit.
let svg = format!("{SVG_PAGE}<circle r=\"1\" transform=\"matrix(1 0 1 1 0 0)\"/></svg>");
let d = read(svg.as_bytes(), "sheared.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
let s_max = ((3.0 + 5f64.sqrt()) / 2.0).sqrt();
let s_min = ((3.0 - 5f64.sqrt()) / 2.0).sqrt();
assert!((major.len() - s_max).abs() < 1e-9 * s_max, "{e:?}");
assert!((e.ratio - s_min / s_max).abs() < 1e-9, "{e:?}");
let (ux, uy) = (major.x, -major.y);
let pre = Vec2::new(ux - uy, uy);
assert!((pre.len() - 1.0).abs() < 1e-9, "B⁻¹·major = {pre:?}, {e:?}");
assert!(major.x.abs() > 1e-3 && major.y.abs() > 1e-3, "{e:?}");
}
#[test]
fn svg_tiny_sheared_circle_has_the_axes_of_its_image() {
// Columns (1, 0.5)·1e-6 and (1, -0.5)·1e-6: far from orthogonal, though their dot product is tiny.
let svg = format!("{SVG_PAGE}<circle r=\"1\" transform=\"matrix(1e-6 0.5e-6 1e-6 -0.5e-6 0 0)\"/></svg>");
let d = read(svg.as_bytes(), "tiny.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
assert!(major.y.abs() <= 1e-9 * major.x.abs(), "{e:?}");
let want = 2f64.sqrt() * 1e-6;
assert!((major.len() - want).abs() < 1e-9 * want, "{e:?}");
assert!((e.ratio - 0.5).abs() < 1e-9, "{e:?}");
}
#[test]
fn svg_path_lines_curves_and_arcs() {
let svg = format!("{SVG_PAGE}<path d=\"M1 1 L5 1 C6 1 7 2 8 3\"/><path d=\"M0 0 A5 5 0 0 1 10 0 Z\"/></svg>");
@@ -3200,59 +3137,6 @@ fn svg_hostile_input_errors_without_panicking() {
assert!(deep.is_err(), "200 nested groups are refused, not walked");
}
#[test]
fn svg_coordinates_that_overflow_are_left_out() {
// Every number is finite; relative steps and transforms overflow them to infinity or NaN.
let svg = format!(
"{SVG_PAGE}<path d=\"M1e308 0 l1e308 0\"/><rect x=\"1e308\" width=\"1e308\" height=\"1\"/>\
<g transform=\"scale(1e308)\"><line x1=\"1e308\" y1=\"0\" x2=\"1\" y2=\"1\"/><circle r=\"1e308\"/></g>\
<g transform=\"scale(1e308,1)\"><ellipse rx=\"1e308\" ry=\"1\"/><path d=\"M0 0 C1e308 0 1 1 2 2\"/></g>\
<line x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"/></svg>"
);
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Line"]);
assert_eq!(d.read_notes, ["SVG: 6 shapes were left out as invalid: their coordinates or size are too large to represent"]);
}
#[test]
fn svg_shapes_whose_extents_overflow_are_left_out() {
// A finite centre and radius whose sum overflows; the same scale on smaller values stays
// representable.
let svg = format!("{SVG_PAGE}<g transform=\"scale(1e308)\"><circle cx=\"1\" cy=\"0\" r=\"1\"/><circle cx=\"0.5\" cy=\"0\" r=\"0.5\"/></g></svg>");
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Circle"]);
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.radius - 5e307).abs() < 1e293, "{}", c.radius);
assert_eq!(d.read_notes, ["SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent"]);
}
/// A shape too large to represent is invalid, not something CADCraft doesn't read yet: it gets a
/// note of its own.
#[test]
fn svg_too_large_shapes_are_noted_apart_from_unread_content() {
let svg = format!("{SVG_PAGE}<text x=\"0\" y=\"5\">one</text><path d=\"M1e308 0 l1e308 0\"/><line x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"/></svg>");
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Line"]);
assert_eq!(
d.read_notes,
[
"SVG: CADCraft doesn't read these yet, so they were left out: 1 text",
"SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent"
]
);
}
#[test]
fn svg_shapes_left_out_still_count_against_the_vertex_budget() {
// Each arc flattens to 10,000 chords under the non-uniform scale, and the doubled translation
// overflows to infinity, so each is left out; 820 of them make more than the 8,000,000 vertices
// a file may generate.
let arcs = "A1e9 1e9 0 0 1 2e9 0 A1e9 1e9 0 0 1 0 0 ".repeat(410);
let svg = format!("{SVG_PAGE}<g transform=\"translate(1e308 0) translate(1e308 0) scale(2 1)\"><path d=\"M0 0 {arcs}\"/></g></svg>");
let err = read(svg.as_bytes(), "huge.svg").err().map(|e| e.to_string()).unwrap_or_default();
assert!(err.contains("SVG: too much generated geometry"), "{err}");
}
#[test]
fn svg_no_geometry_yields_an_empty_drawing() {
let svg = format!("{SVG_PAGE}</svg>");
-360
View File
@@ -1,360 +0,0 @@
//! A hostile or damaged file can name a handle at the top of the range: an object's own handle,
//! or its `$HANDSEED`. A file's handles keep their identity, so a new object must take a free
//! handle instead of replacing the file's own object (#913).
#![cfg(not(target_arch = "wasm32"))]
use cadcraft_doc::{Common, DimKind, Dimension, Drawing, Entity, EntityKind, Handle, Line, Space};
use cadcraft_geom::Vec3;
const TOP: &str = "FFFFFFFFFFFFFFFF";
const NEAR_TOP: &str = "FFFFFFFFFFFEFFFF";
fn read(text: &str) -> Drawing {
cadcraft_io::read_dxf(text.as_bytes()).unwrap()
}
fn line(x: f64, y: f64) -> EntityKind {
EntityKind::Line(Line { a: Vec3::new(x, y, 0.0), b: Vec3::new(x + 1.0, y, 0.0) })
}
/// One line, with `entity_handle` when given, under a `$HANDSEED` of `seed`.
fn dxf(entity_handle: Option<&str>, seed: &str) -> String {
let handle = entity_handle.map(|h| format!("5\n{h}\n")).unwrap_or_default();
format!(
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n{seed}\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLINE\n{handle}8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n0\nENDSEC\n0\nEOF\n"
)
}
fn distinct(d: &Drawing) -> Vec<Handle> {
d.model.iter().map(|e| e.handle).collect()
}
#[test]
fn an_object_at_the_top_of_the_handle_range_is_not_replaced_by_a_new_one() {
let mut d = read(&dxf(Some(TOP), TOP));
assert_eq!(d.model.len(), 1);
// The file's handle is its own; the new object takes a free handle below it.
assert!(d.entity(Handle::parse_hex(TOP).unwrap()).is_some(), "the file's handle was renumbered");
d.add(&Space::Model, Common::default(), line(10.0, 10.0)).unwrap();
assert_eq!(d.model.len(), 2, "the file's line was replaced by the new one");
let handles = distinct(&d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the file's line is gone");
}
#[test]
fn a_seed_at_the_top_of_the_handle_range_cannot_be_followed_twice() {
let mut d = read(&dxf(None, TOP));
let a = d.add(&Space::Model, Common::default(), line(0.0, 10.0)).unwrap();
let b = d.add(&Space::Model, Common::default(), line(0.0, 20.0)).unwrap();
assert_ne!(a, b, "two objects were given the same handle");
assert_eq!(d.model.len(), 3, "the second line replaced the first");
}
#[test]
fn an_ordinary_high_handle_keeps_its_identity() {
// Far below the top of the range a file's handles are its own: they stay as they are.
let h = "FFFFFFFF";
let mut d = read(&dxf(Some(h), h));
assert!(d.entity(Handle::parse_hex(h).unwrap()).is_some(), "the file's handle was renumbered");
let n = d.add(&Space::Model, Common::default(), line(0.0, 5.0)).unwrap();
assert!(n.0 > Handle::parse_hex(h).unwrap().0, "a new handle below the file's own");
}
#[test]
fn a_handle_just_below_the_top_survives_a_save() {
// Main keeps a file's handles exactly as written, even near the top of the range: handles
// are how other objects and other programs refer to an entity (#939's round-trip tests).
let mut d = read(&dxf(Some(NEAR_TOP), NEAR_TOP));
let n = d.add(&Space::Model, Common::default(), line(0.0, 5.0)).unwrap();
let bytes = cadcraft_io::write(&d, "near-top.dxf").unwrap();
let r = cadcraft_io::read_dxf(&bytes).unwrap();
assert!(r.entity(Handle::parse_hex(NEAR_TOP).unwrap()).is_some(), "the file's handle did not survive the save");
assert!(r.entity(n).is_some(), "the new handle did not survive the save");
}
#[test]
fn nine_objects_drawn_after_a_saturated_seed_save_and_reopen_distinct() {
// The nine-entity case from #2237: a saturated $HANDSEED, ordinary entity handles. Drawing
// after the load gives every object its own handle, and a save/reopen keeps them apart.
let mut d = read(&dxf(None, TOP));
for i in 0..9 {
d.add(&Space::Model, Common::default(), line(f64::from(i), 40.0)).unwrap();
}
let bytes = cadcraft_io::write(&d, "nine.dxf").unwrap();
let r = cadcraft_io::read_dxf(&bytes).unwrap();
assert_eq!(r.model.len(), 10, "the file's line and the nine drawn ones");
let handles = distinct(&r);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "repeated handles on reopen: {handles:?}");
}
/// The first handle in the reserved band above [`HANDLE_LIMIT`].
const BAND: &str = "FFFFFFFF00000000";
#[test]
fn a_seed_in_the_reserved_band_does_not_hand_out_the_files_handle() {
// #913's remaining case: a file says its next handle is FFFFFFFF00000000 and an object holds
// that handle. Following the seed once would hand the object's handle to the new object, and
// `EntityStore` would replace the file's line.
let mut d = read(&dxf(Some(BAND), BAND));
assert_eq!(d.model.len(), 1);
let n = d.add(&Space::Model, Common::default(), line(10.0, 10.0)).unwrap();
assert_ne!(n, Handle::parse_hex(BAND).unwrap(), "the new object took the file object's handle");
assert_eq!(d.model.len(), 2, "the file's line was replaced");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the file's line is gone");
let bytes = cadcraft_io::write(&d, "band-seed.dxf").unwrap();
let r = cadcraft_io::read_dxf(&bytes).unwrap();
let handles = distinct(&r);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "repeated handles on reopen: {handles:?}");
assert_eq!(r.model.len(), 2, "a line did not survive the save");
}
#[test]
fn a_save_does_not_give_a_structural_record_an_objects_handle() {
// The writer numbers its own records from `seed + 0x1000`; with the seed at the bottom of the
// reserved band that lands on the file's own handle. The file must keep one record per handle.
let object = "FFFFFFFF00001000";
let d = read(&dxf(Some(object), "FFFFFFFEFFFFFFFF"));
let bytes = cadcraft_io::write(&d, "band-structural.dxf").unwrap();
let tags = craft_dxf::parse(&bytes).unwrap();
// Record handles start with the TABLES section; before it the HEADER's `$HANDSEED` is the
// next free handle, not a record's.
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
let unique: std::collections::HashSet<&String> = written.iter().collect();
assert_eq!(unique.len(), written.len(), "the save repeats a handle: {written:?}");
assert_eq!(written.iter().filter(|h| h.as_str() == object).count(), 1, "the object's handle was not written exactly once");
let r = cadcraft_io::read_dxf(&bytes).unwrap();
assert!(r.entity(Handle::parse_hex(object).unwrap()).is_some(), "the file's object is gone");
}
/// A CADCraft-marked file with a handle-less block entity and an `ENTITIES` record that names
/// the handle the reader would give it. The marker means the reader skips the handle pre-scan,
/// so the two sections must still reserve against each other.
fn marked_file_with_handle_less_block_entity() -> String {
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n1000\n0\nENDSEC\n\
0\nSECTION\n2\nBLOCKS\n\
0\nBLOCK\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n3\n*MODEL_SPACE\n1\n\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n\
0\nENDBLK\n8\n0\n\
0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n5\n100\n8\n0\n10\n10.0\n20\n0.0\n30\n0.0\n11\n11.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n\
0\nXRECORD\n5\n300\n100\nAcDbXrecord\n3\nCADCRAFT_HANDSEED\n1\n1000\n\
0\nENDSEC\n0\nEOF\n"
.to_string()
}
#[test]
fn a_marked_files_sections_reserve_handles_against_each_other() {
// The block entity has no handle of its own, so the reader gives it one; a later ENTITIES
// record must not be given the same handle, or one entity silently replaces the other.
let d = read(&marked_file_with_handle_less_block_entity());
assert_eq!(d.model.len(), 2, "one entity replaced the other");
let handles = distinct(&d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the block entity is gone");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 10.0)), "the ENTITIES line is gone");
}
/// A file whose BLOCKS holds a handle-less model-space entity and whose ENTITIES names the
/// last handle below the reserved band and the first handle in it. With `marked` the file names
/// CADCraft's own seed record, which narrows the reader's handle pre-scan to the entity sections.
fn file_with_reserved_band_entities(marked: bool) -> String {
let below = format!("{:X}", cadcraft_doc::HANDLE_LIMIT - 1);
let band = format!("{:X}", cadcraft_doc::HANDLE_LIMIT);
let objects = if marked {
"0\nSECTION\n2\nOBJECTS\n\
0\nXRECORD\n5\n300\n100\nAcDbXrecord\n3\nCADCRAFT_HANDSEED\n1\n1000\n\
0\nENDSEC\n"
} else {
""
};
format!(
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n1000\n0\nENDSEC\n\
0\nSECTION\n2\nBLOCKS\n\
0\nBLOCK\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n3\n*MODEL_SPACE\n1\n\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n\
0\nENDBLK\n8\n0\n\
0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n5\n{below}\n8\n0\n10\n10.0\n20\n0.0\n30\n0.0\n11\n11.0\n21\n0.0\n31\n0.0\n\
0\nLINE\n5\n{band}\n8\n0\n10\n20.0\n20\n0.0\n30\n0.0\n11\n21.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n{objects}0\nEOF\n"
)
}
/// All three lines survive with their own handles: the handle-less block entity could not take
/// the reserved-band handle of the file's own ENTITIES record.
fn assert_three_lines_survive(d: &Drawing) {
assert_eq!(d.model.len(), 3, "one entity replaced another");
let handles = distinct(d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the block entity is gone");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 10.0)), "the line below the band is gone");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 20.0)), "the line in the band is gone");
// The band's explicit handle stays with the record that names it.
let band = Handle(cadcraft_doc::HANDLE_LIMIT);
let owner = d.model.iter().find(|e| e.handle == band).expect("the band handle was renumbered");
assert!(matches!(&owner.kind, EntityKind::Line(l) if l.a.x == 20.0), "the band handle moved to another line");
// The handle just below the band is the file's too, and it stays with its own record.
let below = Handle(cadcraft_doc::HANDLE_LIMIT - 1);
let owner = d.model.iter().find(|e| e.handle == below).expect("the below-band handle was renumbered");
assert!(matches!(&owner.kind, EntityKind::Line(l) if l.a.x == 10.0), "the below-band handle moved to another line");
}
#[test]
fn reserved_band_handles_in_entities_are_not_handed_to_a_handle_less_block_entity() {
// The handle below the reserved band is the file's, so the reader's next handle is the first
// handle in the band, which an ENTITIES record already owns. The seed cannot follow it
// (#913), so the handle is reserved for allocation instead: the handle-less model-space
// block entity must not take it and replace the file's line.
assert_three_lines_survive(&read(&file_with_reserved_band_entities(true)));
}
#[test]
fn reserved_band_handles_are_reserved_without_the_cadcraft_seed_record() {
// The same reservation holds when the pre-scan reads every section's handles: a handle in
// the band is the file's own there too, and still must not be given away.
assert_three_lines_survive(&read(&file_with_reserved_band_entities(false)));
}
#[test]
fn reservations_end_with_the_read_and_placed_objects_still_keep_their_handles() {
// The reservations only bridge the gap until a record is placed; a drawing does not carry
// them on (every undo step copies the drawing). The placed objects keep new ones off.
let mut d = read(&file_with_reserved_band_entities(true));
assert!(d.reserved_handles.is_empty(), "the reader's reservations outlived the read");
for i in 0..3 {
d.add(&Space::Model, Common::default(), line(f64::from(i), 50.0)).unwrap();
}
assert_eq!(d.model.len(), 6, "a new object replaced one of the file's");
assert_three_lines_survive_among(&d);
}
fn assert_three_lines_survive_among(d: &Drawing) {
let band = Handle(cadcraft_doc::HANDLE_LIMIT);
assert!(d.model.iter().any(|e| e.handle == band && matches!(&e.kind, EntityKind::Line(l) if l.a.x == 20.0)), "the band line lost its handle");
let handles = distinct(d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
}
#[test]
fn generated_geometry_never_takes_a_handle_an_object_holds() {
// The drawing's own handles sit in the reserved band and the seed is at the top of the
// range, so the writer's structural numbering wraps into the band. Every other band handle
// is taken, so without a check the generated dimension block's entities land on an occupied
// one: the saved file would repeat a handle.
let mut d = Drawing::new_imperial();
d.handseed = u64::MAX - 1;
{
let model = d.space_mut(&Space::Model).unwrap();
for i in 0..200u64 {
let handle = Handle(cadcraft_doc::HANDLE_LIMIT + 1 + 2 * i);
model.push(Entity { handle, common: Common::default(), kind: line(i as f64, 0.0) });
}
model.push(Entity {
handle: Handle(0x200),
common: Common::default(),
kind: EntityKind::Dimension(Dimension {
kind: DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(0.0, 1.0, 0.0),
text_mid: Vec3::new(1.0, 1.0, 0.0),
p13: Vec3::ZERO,
p14: Vec3::new(2.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 2.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
insertion_point: Vec3::ZERO,
overrides: serde_json::Map::new(),
assoc: Vec::new(),
marks: Default::default(),
}),
});
}
let bytes = cadcraft_io::write(&d, "generated.dxf").unwrap();
let tags = craft_dxf::parse(&bytes).unwrap();
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
let unique: std::collections::HashSet<&String> = written.iter().collect();
assert_eq!(unique.len(), written.len(), "the save repeats a handle");
}
/// A line at the top handle with another application's xdata, and that application's object kept
/// from the file: a dictionary in the named object dictionary holding an XRECORD.
fn top_line_with_kept_objects() -> String {
let groups: &[(i32, &str)] = &[
(0, "SECTION"),
(2, "ENTITIES"),
(0, "LINE"),
(5, TOP),
(8, "0"),
(10, "0"),
(20, "0"),
(11, "10"),
(21, "0"),
(1001, "OTHER_APP"),
(1000, "tagged"),
(0, "ENDSEC"),
(0, "SECTION"),
(2, "OBJECTS"),
(0, "DICTIONARY"),
(5, "C"),
(330, "0"),
(100, "AcDbDictionary"),
(3, "OTHER_APP"),
(350, "50"),
(0, "DICTIONARY"),
(5, "50"),
(330, "C"),
(100, "AcDbDictionary"),
(281, "1"),
(3, "DATA"),
(360, "51"),
(0, "XRECORD"),
(5, "51"),
(330, "50"),
(100, "AcDbXrecord"),
(280, "1"),
(1, "kept"),
(0, "ENDSEC"),
(0, "EOF"),
];
groups.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
}
#[test]
fn records_added_on_save_after_the_top_handle_take_free_handles() {
// The writer adds the kept objects (and any application id the xdata needs) after its own
// records, numbered above the largest handle written. That is the file's line at the top of
// the range: counting on from it would give every added record the line's handle.
let d = read(&top_line_with_kept_objects());
let bytes = cadcraft_io::write(&d, "kept-top.dxf").unwrap();
let text = String::from_utf8_lossy(&bytes);
assert!(text.contains("\nkept"), "the kept XRECORD was not written");
let tags = craft_dxf::parse(&bytes).unwrap();
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
let unique: std::collections::HashSet<&String> = written.iter().collect();
assert_eq!(unique.len(), written.len(), "the save repeats a handle: {written:?}");
assert_eq!(written.iter().filter(|h| h.as_str() == TOP).count(), 1, "the line's handle was not written exactly once");
let r = read(&String::from_utf8_lossy(&bytes));
assert!(r.entity(Handle::parse_hex(TOP).unwrap()).is_some(), "the file's line is gone");
}
@@ -26,6 +26,7 @@ fn preserves_or_refuses(path: &str, binary: bool) {
}
#[test]
#[ignore = "Confirmed DXF data loss: exhausted generated handles produce a successful save that reopens with no model entities"]
fn dxf_exhausted_handles_are_preserved_or_refused() {
for binary in [false, true] {
preserves_or_refuses("memory.dxf", binary);
@@ -16,8 +16,8 @@ fn import(transform: &str) -> (f64, f64) {
_ => None,
})
.unwrap();
// `major` is the axis from the centre (#2821).
(e.major.y.atan2(e.major.x), e.ratio)
let (dx, dy) = (e.major.x - e.center.x, e.major.y - e.center.y);
(dy.atan2(dx), e.ratio)
}
/// Major-axis angle and ratio of the image of the ellipse under the 2x2 map `[a c; b d]`, with
+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");
}