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
35 changed files with 1258 additions and 861 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
+4 -6
View File
@@ -805,11 +805,9 @@ pub struct PageSetup {
/// Plot objects with their transparency ("Plot transparency"; PLOTTRANSPARENCYOVERRIDE can
/// override it). The DXF plot layout flags have no bit for it, so it is not saved in DXF.
pub plot_transparency: bool,
/// Explicit paper-space unit for the layout: `Some(true)` for millimetres (plot paper units 1
/// in DXF), `Some(false)` for inches, or `None` to follow the drawing's `MEASUREMENT` (#1058,
/// #3249).
#[serde(skip_serializing_if = "Option::is_none")]
pub paper_mm: Option<bool>,
/// The layout's paper units are millimetres (plot paper units 1 in DXF) whatever the
/// drawing's MEASUREMENT says; otherwise paper units follow MEASUREMENT (#1058).
pub paper_mm: bool,
/// Paper size (DXF groups 44, 45) and plot rotation (group 73) as the file stored them.
/// Saving writes them back while they still describe `width_mm`, `height_mm` and
/// `landscape`, so each program's convention for media defined wider than tall survives a
@@ -841,7 +839,7 @@ impl Default for PageSetup {
lineweights: true,
show_plot_styles: false,
plot_transparency: false,
paper_mm: None,
paper_mm: false,
file_paper: None,
image_origin: None,
}
+13 -7
View File
@@ -11,7 +11,7 @@ use std::collections::BTreeMap;
use std::sync::Arc;
use cadcraft_color::Rgb;
use cadcraft_doc::{Drawing, Entity, EntityKind, Space};
use cadcraft_doc::{Drawing, Entity, EntityKind, PageSetup, Space};
use cadcraft_geom::{Bounds2, Mat3, Vec2};
use cadcraft_render::paper::{self, Sheet};
use cadcraft_render::raster::{RasterOptions, View};
@@ -276,8 +276,18 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
let d = s.doc()?;
let mut page = match space.layout() {
Some(n) => d.layout(n).map(|l| l.page.clone()).unwrap_or_default(),
// Model space plots on ISO A4 (metric) or ANSI A, like the PDF plotter.
None => paper::model_page(d),
None => {
// Model space plots on A4 (metric) or ANSI A, like the PDF plotter.
let mut page = PageSetup::default();
if paper::paper_unit_mm(d) == 1.0
&& let Some(a4) = paper::paper_size("A4")
{
page.paper = a4.name.into();
page.width_mm = a4.width_mm;
page.height_mm = a4.height_mm;
}
page
}
};
if let Some(name) = str_param(p, "paper") {
let ps = paper::paper_size(name).ok_or_else(|| bad("preview", format!("unknown paper size `{name}`")))?;
@@ -285,10 +295,6 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
page.width_mm = ps.width_mm;
page.height_mm = ps.height_mm;
}
// A model-space plot takes its units from the paper it was given (a layout keeps its page setup's).
if matches!(space, Space::Model) {
paper::apply_model_paper_units(&mut page);
}
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
page.landscape = l;
}
+1 -27
View File
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
.menu(&["File", "Page Setup Manager..."])
.params(
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
),
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.menu(&["File", "Print..."])
@@ -641,7 +641,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
"width",
"height",
"landscape",
"paperUnits",
"margins",
"lineweights",
"plotArea",
@@ -683,22 +682,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
page.width_mm = ps.width_mm;
page.height_mm = ps.height_mm;
}
// The picked paper's own units become the layout's paper units: millimetres for a metric
// paper, else the drawing's MEASUREMENT. Otherwise ISO A0 in a new (imperial) drawing's
// layout is 33.11 x 46.81 units (#2836). This holds for a standard size from the page's
// device's list too (the built-in devices list every standard size), and a device's own
// paper that is not a standard size keeps the layout's units. Only a saved page setup changes
// units; a one-off plot's `paper` keeps the layout's, so its objects stay the size they were
// drawn. A custom `width` and `height` in the same call replace this paper below, and a
// custom size keeps the layout's units, with `paper` or without it. An explicit `paperUnits`
// in the same call wins (below).
if p.get("paper").is_some()
&& p.get("width").is_none()
&& p.get("height").is_none()
&& let Some(ps) = cadcraft_render::paper_size(&page.paper)
{
page.paper_mm = (!ps.imperial).then_some(true);
}
let mm = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0 && *v <= 5080.0);
match (mm("width"), mm("height")) {
(Some(w), Some(h)) => {
@@ -712,15 +695,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
page.landscape = l;
}
// Paper units: what one paper-space unit is on this layout, whatever the paper's own family
// (an ARCH D sheet can be drawn in millimetres, #3249).
if let Some(v) = p.get("paperUnits") {
page.paper_mm = Some(match v.as_str().map(str::to_ascii_lowercase).as_deref() {
Some("mm" | "millimeters" | "millimetres") => true,
Some("in" | "inch" | "inches") => false,
_ => return Err(bad(cmd, "`paperUnits` must be \"mm\" or \"inches\"")),
});
}
if let Some(m) = p.get("margins") {
let a: Vec<f64> = m.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
match a[..] {
+2 -79
View File
@@ -165,57 +165,14 @@ fn viewport_scale_lock_and_layers() {
}
}
/// #2836: picking a paper sets the layout's paper units from it. In a new drawing (imperial,
/// MEASUREMENT 0) ISO A0 was 46.81 x 33.11 units, the inch equivalent; now it is 1189 x 841.
/// An inch paper gives the layout back the drawing's units.
#[test]
fn pagesetup_paper_sets_the_layout_paper_units() {
let mut s = Session::new();
assert_eq!(cadcraft_render::paper::paper_unit_mm(s.doc().unwrap()), 25.4, "a new drawing is imperial");
let size = |s: &Session| {
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
((sheet.size.x * 100.0).round() / 100.0, (sheet.size.y * 100.0).round() / 100.0, sheet.unit_mm)
};
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A0", "landscape": true})).unwrap();
assert_eq!(r["page"]["paperMm"], true);
assert_eq!(size(&s), (1189.0, 841.0, 1.0), "ISO A0 in millimetres");
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ANSI D"})).unwrap();
assert_eq!(size(&s), (34.0, 22.0, 25.4), "ANSI D in the drawing's inches");
// A custom size replaces the named paper in the same call and keeps the layout's units.
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A4", "width": 254, "height": 508})).unwrap();
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, None, "the layout still follows MEASUREMENT");
assert_eq!(size(&s), (20.0, 10.0, 25.4), "the custom size in the layout's inches");
}
/// #2836 through a device: the built-in devices list every standard size, so a paper picked in
/// Page Setup with CADCraft PDF as the device comes from the device's list. It sets the layout's
/// paper units as a paper picked with no device does.
#[test]
fn pagesetup_device_paper_sets_the_layout_paper_units() {
let mut s = Session::new();
let size = |s: &Session| {
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
((sheet.size.x * 100.0).round() / 100.0, (sheet.size.y * 100.0).round() / 100.0, sheet.unit_mm)
};
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "CADCraft PDF", "landscape": true})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ISO A0 (841.00 x 1189.00 MM)"})).unwrap();
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.device, "CADCraft PDF");
assert_eq!(size(&s), (1189.0, 841.0, 1.0), "ISO A0 from the device's list in millimetres");
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ANSI D"})).unwrap();
assert_eq!(size(&s), (34.0, 22.0, 25.4), "ANSI D from the device's list in the drawing's inches");
// An explicit choice in the same call wins over the paper's own units (#3249).
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ARCH D", "paperUnits": "mm"})).unwrap();
assert_eq!(size(&s), (914.4, 609.6, 1.0));
}
#[test]
fn pagesetup_paper_table() {
let mut s = Session::new();
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A3", "landscape": true, "margins": [5, 5, 5, 5]})).unwrap();
assert_eq!(r["page"]["widthMm"], 297.0);
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
// An imperial drawing, but a metric paper: the layout's paper units are millimetres (#2836).
assert!((sheet.size.x - 420.0).abs() < 1e-9 && (sheet.size.y - 297.0).abs() < 1e-9);
// Imperial drawing: paper units are inches.
assert!((sheet.size.x - 420.0 / 25.4).abs() < 1e-9 && (sheet.size.y - 297.0 / 25.4).abs() < 1e-9);
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "Z12"})).is_err());
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "margins": [1, 2]})).is_err());
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "width": 1e308, "height": 5})).is_err());
@@ -233,40 +190,6 @@ fn pagesetup_paper_table() {
assert_eq!((p.width_mm, p.height_mm), (300.0, 500.0));
}
#[test]
fn pagesetup_paper_units_make_an_inch_sheet_metric() {
// An ARCH D sheet in a drawing that measures in millimetres (#3249): the page setup's paper
// units decide the paper-space unit, so the sheet can be 914.4 x 609.6 mm.
let mut s = Session::new();
s.execute("units", &json!({"insunits": 4})).unwrap();
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ARCH D", "landscape": true, "paperUnits": "mm"})).unwrap();
assert_eq!(r["page"]["paperMm"], true);
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
assert!((sheet.size.x - 914.4).abs() < 1e-9 && (sheet.size.y - 609.6).abs() < 1e-9, "{:?}", sheet.size);
s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "Inches"})).unwrap();
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
assert!((sheet.size.x - 36.0).abs() < 1e-9 && (sheet.size.y - 24.0).abs() < 1e-9, "{:?}", sheet.size);
s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "millimeters"})).unwrap();
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, Some(true));
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "feet"})).is_err());
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": 4})).is_err());
}
#[test]
fn pagesetup_paper_units_inches_overrides_metric_measurement() {
let mut s = Session::new();
s.execute("setvar", &json!({"name": "MEASUREMENT", "value": 1})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ARCH D", "landscape": true})).unwrap();
// Without an explicit paperUnits choice, MEASUREMENT = 1 keeps the sheet in millimetres.
let metric = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
assert!((metric.size.x - 914.4).abs() < 1e-9 && (metric.size.y - 609.6).abs() < 1e-9, "{:?}", metric.size);
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "inches"})).unwrap();
assert_eq!(r["page"]["paperMm"], false);
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, Some(false));
let inch = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
assert!((inch.size.x - 36.0).abs() < 1e-9 && (inch.size.y - 24.0).abs() < 1e-9, "{:?}", inch.size);
}
fn fake_plot(d: &Drawing, space: &Space, opts: &Value) -> std::result::Result<Vec<u8>, String> {
let _ = d;
Ok(format!("%PDF-1.4 fake {space:?} {opts}").into_bytes())
+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"
+1 -1
View File
@@ -143,7 +143,7 @@ pub(super) fn read_objects(tags: &[Tag], objs: &mut Objects, layout_objs: &mut V
// LAYOUT has two 330s: owner dict and the block record; take the last.
let br = tg.iter().rfind(|x| x.code == 330).map(Tag::str).unwrap_or_default();
let plot = T(tg.get(..start).unwrap_or(&[]));
layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot, &tg), limits(&t)));
layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot), limits(&t)));
}
}
}
+5 -14
View File
@@ -231,9 +231,8 @@ impl Objects {
}
}
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm), and its
/// CADCraft xdata in the record's `tags`.
pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm).
pub(super) fn page_setup(t: &T) -> PageSetup {
let mut p = PageSetup::default();
let mm = |code: i32, d: f64| {
let v = t.fd(code, d);
@@ -245,17 +244,9 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
p.height_mm = w.max(h);
}
p.margins_mm = [mm(40, p.margins_mm[0]), mm(41, p.margins_mm[1]), mm(42, p.margins_mm[2]), mm(43, p.margins_mm[3])];
// CADCraft's paper units come first (PSUNITS xdata: 0 inches, 1 millimetres, 2 follows
// MEASUREMENT), because plot paper units 0 cannot tell an explicit inch layout from an unset
// one: earlier CADCraft versions wrote 0 for every layout, so 0 alone is left to MEASUREMENT.
// Plot paper units 1 is millimetres (#3249).
let units = crate::dxf_ext::xdata_list(crate::dxf_ext::xdata(tags, crate::dxf_ext::APP), "PSUNITS");
p.paper_mm = match units.iter().find(|t| t.code == 1070).map(|t| t.i64()) {
Some(0) => Some(false),
Some(1) => Some(true),
Some(2) => None,
_ => (t.i(72) == Some(1)).then_some(true),
};
// Plot paper units 1: millimetres. 0 (inches) is left to MEASUREMENT: earlier CADCraft
// versions wrote 0 for every layout.
p.paper_mm = t.i(72) == Some(1);
// Plot rotation 1 or 3 turns the media a quarter turn; media defined wider than tall is
// already landscape.
let rotated = matches!(t.i(73), Some(1 | 3));
+7 -28
View File
@@ -473,35 +473,14 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
w.p(17, Vec3::new(0.0, 1.0, 0.0));
w.i(76, 0);
w.s(330, brh);
// CADCraft xdata: the saved paper-space view (centre, height), and the layout's paper units.
// Group 72 cannot carry the choice on its own: 0 means inches, but it is also what earlier
// CADCraft versions wrote for a layout that follows MEASUREMENT, and 1 is what a layout that
// inherits a metric MEASUREMENT writes too. PSUNITS keeps the three states apart: 0 inches,
// 1 millimetres, 2 follows MEASUREMENT (#3249).
let view = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite());
let unit_marker = match page.paper_mm {
Some(false) => Some(0),
Some(true) => Some(1),
// An inherited imperial layout writes group 72 = 0, which already reads back as
// inherited; only group 72 = 1 is ambiguous and needs the marker.
None if cadcraft_render::paper::page_unit_mm(d, page) == 1.0 => Some(2),
None => None,
};
if view.is_some() || unit_marker.is_some() {
// The saved paper-space view (centre, height) as CADCraft xdata.
if let Some((c, height)) = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite()) {
w.s(1001, dxf_ext::APP);
if let Some((c, height)) = view {
w.s(1000, "PSVIEW");
w.s(1002, "{");
w.p(1010, c.to3(0.0));
w.f(1040, height);
w.s(1002, "}");
}
if let Some(units) = unit_marker {
w.s(1000, "PSUNITS");
w.s(1002, "{");
w.i(1070, units);
w.s(1002, "}");
}
w.s(1000, "PSVIEW");
w.s(1002, "{");
w.p(1010, c.to3(0.0));
w.f(1040, height);
w.s(1002, "}");
}
}
+11 -6
View File
@@ -292,8 +292,17 @@ fn links_json(v: Option<&Value>) -> Vec<(Handle, String)> {
pub fn page_for(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<PageSetup> {
let mut page = match space.layout() {
Some(n) => d.layout(n).map(|l| l.page.clone()).ok_or_else(|| IoError::Format(format!("no layout `{n}`")))?,
// Model space has no stored page setup: ISO A4 in a metric drawing, ANSI A otherwise.
None => paper::model_page(d),
None => {
let mut p = PageSetup::default();
if paper::paper_unit_mm(d) == 1.0
&& let Some(a4) = paper::paper_size("A4")
{
p.paper = a4.name.into();
p.width_mm = a4.width_mm;
p.height_mm = a4.height_mm;
}
p
}
};
if let Some(name) = &o.paper {
let ps = paper::paper_size(name).ok_or_else(|| IoError::Format(format!("unknown paper size `{name}`")))?;
@@ -316,10 +325,6 @@ pub fn page_for(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<PageSetup>
if let (Space::Model, Some(m)) = (space, o.margins) {
page.margins_mm = m;
}
// A model-space plot takes its units from the paper it was given; a layout keeps its page setup's.
if matches!(space, Space::Model) {
paper::apply_model_paper_units(&mut page);
}
page.width_mm = page.width_mm.clamp(1.0, MAX_SHEET_MM);
page.height_mm = page.height_mm.clamp(1.0, MAX_SHEET_MM);
Ok(page)
+1 -1
View File
@@ -169,7 +169,7 @@ fn the_added_paper_viewport_follows_the_plot_scale() {
let sheet_width = |scale: f64, fit: bool| {
let mut d = Drawing::new_metric();
let page = &mut d.layouts[0].page;
(page.width_mm, page.height_mm, page.landscape, page.paper_mm) = (297.0, 420.0, true, Some(true));
(page.width_mm, page.height_mm, page.landscape, page.paper_mm) = (297.0, 420.0, true, true);
(page.scale, page.scale_to_fit) = (scale, fit);
let first = Space::Paper(d.layouts[0].name.clone());
d.add(&first, Common::default(), viewport(2)).unwrap();
+5 -70
View File
@@ -19,7 +19,7 @@ fn drawing() -> Drawing {
height_mm: 297.0,
margins_mm: [0.0; 4],
landscape: true,
paper_mm: Some(true),
paper_mm: true,
..PageSetup::default()
};
d.layouts.push(l);
@@ -57,81 +57,16 @@ fn plot_paper_units_round_trip_through_dxf() {
// Written as group 72 = 1 (millimetres) and read back as such.
let back = read(write_dxf(&drawing()).as_bytes(), "x.dxf").unwrap();
let page = &back.layouts.iter().find(|l| l.name == "SHEET").unwrap().page;
assert_eq!(page.paper_mm, Some(true));
assert!(page.paper_mm);
assert_eq!(cadcraft_render::sheet(&back, "SHEET").unwrap().unit_mm, 1.0);
// A metric drawing's layouts stay in millimetres even from files that say 72 = 0 and carry
// no PSUNITS xdata (what earlier CADCraft versions wrote for every layout).
// A metric drawing's layouts stay in millimetres even from files that say 72 = 0 (what
// earlier CADCraft versions wrote for every layout).
let mut metric = Drawing::new_metric();
metric.header.set_i64("MEASUREMENT", 1);
let written = write_dxf(&metric);
let text = written
.replace("1001\r\nCADCRAFT\r\n1000\r\nPSUNITS\r\n1002\r\n{\r\n1070\r\n2\r\n1002\r\n}\r\n", "")
.replace("\r\n 72\r\n1\r\n", "\r\n 72\r\n0\r\n");
let text = written.replace("\r\n 72\r\n1\r\n", "\r\n 72\r\n0\r\n");
assert_ne!(text, written, "the layouts' 72 = 1 became 0");
let back = read(text.as_bytes(), "old.dxf").unwrap();
let name = back.layouts.first().unwrap().name.clone();
assert_eq!(cadcraft_render::sheet(&back, &name).unwrap().unit_mm, 1.0);
}
#[test]
fn an_explicit_inch_layout_round_trips_on_a_metric_drawing() {
// #3249: group 72 = 0 is also what an unset layout writes, so the explicit inch choice
// travels in CADCraft xdata and must win over the group 72 fallback.
let mut d = Drawing::new_metric();
d.header.set_i64("MEASUREMENT", 1);
let mut l = Layout::new("INCHES", 3);
l.page = PageSetup {
paper: "ARCH D".into(),
width_mm: 609.6,
height_mm: 914.4,
margins_mm: [0.0; 4],
landscape: true,
paper_mm: Some(false),
..PageSetup::default()
};
d.layouts.push(l);
let back = read(write_dxf(&d).as_bytes(), "x.dxf").unwrap();
let page = &back.layouts.iter().find(|l| l.name == "INCHES").unwrap().page;
assert_eq!(page.paper_mm, Some(false));
let sheet = cadcraft_render::sheet(&back, "INCHES").unwrap();
assert_eq!(sheet.unit_mm, 25.4);
assert!((sheet.size.x - 36.0).abs() < 1e-9 && (sheet.size.y - 24.0).abs() < 1e-9, "{:?}", sheet.size);
}
#[test]
fn an_inherited_layout_keeps_following_measurement_after_a_dxf_round_trip() {
// #3249: a layout that never chose its paper units reads back as inherited, not fixed to the
// MEASUREMENT it had when saved. An ARCH D sheet on a metric drawing is 914.4 x 609.6; after
// MEASUREMENT changes to imperial it must be 36 x 24. The explicit choices do not move.
let mut d = Drawing::new_metric();
d.header.set_i64("MEASUREMENT", 1);
for (name, paper_mm) in [("INHERITED", None), ("INCHES", Some(false)), ("MILLIMETRES", Some(true))] {
let mut l = Layout::new(name, 3);
l.page = PageSetup {
paper: "ARCH D".into(),
width_mm: 609.6,
height_mm: 914.4,
margins_mm: [0.0; 4],
landscape: true,
paper_mm,
..PageSetup::default()
};
d.layouts.push(l);
}
let mut back = read(write_dxf(&d).as_bytes(), "x.dxf").unwrap();
let units = |d: &Drawing, name: &str| d.layouts.iter().find(|l| l.name == name).unwrap().page.paper_mm;
assert_eq!(units(&back, "INHERITED"), None);
assert_eq!(units(&back, "INCHES"), Some(false));
assert_eq!(units(&back, "MILLIMETRES"), Some(true));
back.header.set_i64("MEASUREMENT", 0);
let sheet = |name: &str| cadcraft_render::sheet(&back, name).unwrap();
let inherited = sheet("INHERITED");
assert_eq!(inherited.unit_mm, 25.4);
assert!((inherited.size.x - 36.0).abs() < 1e-9 && (inherited.size.y - 24.0).abs() < 1e-9, "{:?}", inherited.size);
assert_eq!(sheet("INCHES").unit_mm, 25.4);
let metric = sheet("MILLIMETRES");
assert_eq!(metric.unit_mm, 1.0);
assert!((metric.size.x - 914.4).abs() < 1e-9 && (metric.size.y - 609.6).abs() < 1e-9, "{:?}", metric.size);
}
-1
View File
@@ -60,7 +60,6 @@ mod pdf_layers;
#[path = "../support/pdf_read.rs"]
mod pdf_read;
mod plot_layout_scale;
mod plot_model_metric_units;
mod plot_model_png_scale;
mod plot_styles;
mod polyface_roundtrip;
@@ -1,130 +0,0 @@
//! #1828: a model-space plot at 1:1 in a drawing whose units are millimetres puts a 10 mm line
//! at 28.35 pt on an ISO A4 sheet, whatever MEASUREMENT says. A drawing made in millimetres by
//! changing the drawing units (UNITS sets INSUNITS, not MEASUREMENT) was plotted 25.4 times too
//! large, because model-space paper units were taken as inches.
//!
//! The model plot's units are the paper's, never the layouts' page setups': a layout whose page
//! setup is in inches still plots its paper space in inches (#1866).
use cadcraft_doc::{Common, Drawing, EntityKind, Layout, Line, PageSetup, Space};
use cadcraft_geom::Vec3;
use cadcraft_io::plot;
use serde_json::{Value, json};
use crate::pdf_read;
/// The page size in points.
fn media_box(pdf: &[u8]) -> (f64, f64) {
pdf_read::read(pdf).media()
}
/// The plotted length in points of the single horizontal line.
fn line_pt(pdf: &[u8]) -> f64 {
let doc = pdf_read::read(pdf);
let xs: Vec<f64> = pdf_read::drawn(doc.content()).iter().filter(|o| o.op == "m" || o.op == "l").filter_map(|o| o.nums.first().copied()).collect();
assert_eq!(xs.len(), 2, "one line, two ends: {xs:?}");
(xs[1] - xs[0]).abs()
}
/// A drawing with one 10-unit line in model space and the given drawing units.
fn drawing(insunits: i64, measurement: i64) -> Drawing {
let mut d = Drawing::new_imperial();
d.header.set_i64("INSUNITS", insunits);
d.header.set_i64("MEASUREMENT", measurement);
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) });
d.add(&Space::Model, Common::default(), line).unwrap();
d
}
/// Plot the model at 1:1 on the named paper, as the Plot dialog does.
fn plot_on(d: &Drawing, paper: &str) -> Vec<u8> {
let opts: Value = json!({
"paper": paper,
"landscape": false,
"fit": false,
"scale": 1,
"lineweights": false,
"compress": false,
});
plot(d, &Space::Model, &opts).unwrap()
}
const A4_PT: (f64, f64) = (595.28, 841.89);
const ANSI_A_PT: (f64, f64) = (612.0, 792.0);
const TEN_MM_PT: f64 = 28.3465;
const TEN_IN_PT: f64 = 720.0;
fn assert_pt(actual: f64, want: f64) {
assert!((actual - want).abs() < 0.01, "{actual} pt, want {want}");
}
/// The MediaBox is the sheet in points (A4 or ANSI A, portrait).
fn assert_media(pdf: &[u8], size: (f64, f64)) {
let (w, h) = media_box(pdf);
assert!((w - size.0).abs() < 0.01 && (h - size.1).abs() < 0.01, "{w} x {h} pt, want {size:?}");
}
#[test]
fn model_plot_in_a_metric_drawing_is_one_to_one() {
let pdf = plot_on(&drawing(4, 1), "ISO A4");
assert_media(&pdf, A4_PT);
assert_pt(line_pt(&pdf), TEN_MM_PT);
}
#[test]
fn model_plot_follows_the_length_unit_when_measurement_says_inches() {
// A drawing started imperial whose units the user changed to millimetres with UNITS:
// MEASUREMENT stays 0, the length unit is what says the drawing is in millimetres.
let pdf = plot_on(&drawing(4, 0), "ISO A4");
assert_media(&pdf, A4_PT);
assert_pt(line_pt(&pdf), TEN_MM_PT);
}
#[test]
fn model_plot_takes_units_from_the_paper() {
// A millimetre sheet at 1:1 prints one drawing unit per millimetre, whatever the drawing's
// length unit is.
let pdf = plot_on(&drawing(1, 0), "ISO A4");
assert_media(&pdf, A4_PT);
assert_pt(line_pt(&pdf), TEN_MM_PT);
// An inch sheet prints one drawing unit per inch, whatever the drawing's length unit is.
let pdf = plot_on(&drawing(4, 0), "ANSI A");
assert_media(&pdf, ANSI_A_PT);
assert_pt(line_pt(&pdf), TEN_IN_PT);
}
#[test]
fn model_plot_on_an_inch_sheet_is_in_inches_whatever_measurement_says() {
// MEASUREMENT 1 (an ISO-template drawing) must not turn an inch sheet's units into
// millimetres: a 10-unit line on ANSI A at 1:1 is 10 inches for every drawing unit.
for (insunits, measurement) in [(4, 1), (0, 1), (1, 1), (4, 0)] {
let pdf = plot_on(&drawing(insunits, measurement), "ANSI A");
assert_media(&pdf, ANSI_A_PT);
assert_pt(line_pt(&pdf), TEN_IN_PT);
}
}
#[test]
fn layout_plot_keeps_its_page_setup_units() {
// The @echelon regression: a metric drawing whose layout has a page setup in inches. The
// layout's paper space is in inches (25.4 mm per unit), not in the drawing's millimetres,
// and its A4 sheet is still A4.
let mut d = drawing(4, 0);
let mut l = Layout::new("SHEET", 3);
l.page = PageSetup {
paper: "ISO A4".into(),
width_mm: 210.0,
height_mm: 297.0,
margins_mm: [0.0; 4],
landscape: false,
paper_mm: Some(false),
..PageSetup::default()
};
d.layouts.push(l);
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) });
d.add(&Space::Paper("SHEET".into()), Common::default(), line).unwrap();
let opts = json!({"fit": false, "scale": 1, "lineweights": false, "compress": false});
let pdf = plot(&d, &Space::Paper("SHEET".into()), &opts).unwrap();
assert_media(&pdf, A4_PT);
assert_pt(line_pt(&pdf), TEN_IN_PT);
}
+1 -1
View File
@@ -197,7 +197,7 @@ pub(super) fn layouts() -> Case {
let mut drawing = cases::drawing();
drawing.layouts = vec![Layout::new("Sheet_A", 1), Layout::new("Sheet_B", 2)];
for (index, layout) in drawing.layouts.iter_mut().enumerate() {
layout.page.paper_mm = Some(true);
layout.page.paper_mm = true;
// PageSetup stores portrait dimensions; landscape is a separate orientation flag.
layout.page.width_mm = 297.0;
layout.page.height_mm = 420.0;
+6 -170
View File
@@ -1,9 +1,7 @@
//! Paper sizes and the layout sheet (paper rectangle, printable area) for paper space.
//!
//! Paper-space units follow a layout's explicit page-setup choice (millimetres or inches), and
//! otherwise `MEASUREMENT` (millimetres when 1, inches otherwise). The sheet's lower-left corner is the paper-space origin.
//! Model-space plots have no stored page setup, so they take their units from the paper itself
//! ([`model_page`], [`model_unit_mm`]).
//! Paper-space units are millimetres in metric drawings (`MEASUREMENT` = 1) and on layouts whose
//! page setup is in millimetres, and inches otherwise. The sheet's lower-left corner is the paper-space origin.
use cadcraft_doc::{Drawing, PageSetup};
use cadcraft_geom::{Bounds2, Vec2};
@@ -83,70 +81,11 @@ pub fn paper_unit_mm(d: &Drawing) -> f64 {
if d.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 25.4 }
}
/// Whether the drawing's length unit is metric: `INSUNITS` millimetres to kilometres and
/// angstroms to parsecs (4..=7, 11..=20) are metric, inches to US survey units (1, 2, 3, 8, 9,
/// 10, 21, 22, 23, 24) imperial. A unitless drawing (`INSUNITS` 0, absent or unknown, as files
/// without `$INSUNITS` are read, #1209) falls back to `MEASUREMENT` = 1.
///
/// `MEASUREMENT` only chooses the imperial or ISO hatch and linetype libraries (#1649, #1826),
/// so it is not what says a drawing is metric: a drawing whose units are millimetres but whose
/// MEASUREMENT is 0 — what UNITS leaves when the user picks millimetres, and what AutoCAD writes
/// for many metric drawings — is metric by this test (#1828).
pub fn metric_length_unit(d: &Drawing) -> bool {
match d.header.i64("INSUNITS", 0) {
// Inches, feet, miles, microinches, mils, yards and US survey units.
1 | 2 | 3 | 8 | 9 | 10 | 21 | 22 | 23 | 24 => false,
// Millimetres, centimetres, metres, kilometres, angstroms, nanometres, microns,
// decimetres to gigametres, astronomical units, light years and parsecs.
4..=7 | 11..=20 => true,
// Unitless: as MEASUREMENT says.
_ => d.header.i64("MEASUREMENT", 0) == 1,
}
}
/// Millimetres per paper unit of the paper named by `page`, from the paper itself: 1.0 for ISO
/// and user-defined millimetre sizes, 25.4 for the ANSI, ARCH and Legal sheets. A name that is
/// no known paper size is treated as a user millimetre size (1.0).
pub fn model_unit_mm(page: &PageSetup) -> f64 {
match paper_size(&page.paper) {
Some(p) if p.imperial => 25.4,
_ => 1.0,
}
}
/// The page a model-space plot starts from: ISO A4 in a drawing whose length unit is metric,
/// ANSI A otherwise. Model space has no stored page setup, so the plot takes its sheet (and its
/// units) from here unless the caller picks another paper.
pub fn model_page(d: &Drawing) -> PageSetup {
let mut page = PageSetup::default();
if let Some(p) = paper_size(if metric_length_unit(d) { "A4" } else { "ANSI A" }) {
page.paper = p.name.into();
page.width_mm = p.width_mm;
page.height_mm = p.height_mm;
}
apply_model_paper_units(&mut page);
page
}
/// Set a model-space plot's paper units once its paper is known: the paper's own units decide
/// (ISO and user millimetre sizes are millimetres, ANSI and ARCH sheets inches), as a model-space
/// page setup's "plot paper units" would. Layouts keep their stored page setup and go through
/// [`page_unit_mm`]; only model-space callers use this. The units are set explicitly either
/// way: an inch sheet left to follow `MEASUREMENT` would plot in millimetres in a drawing whose
/// `MEASUREMENT` is 1.
pub fn apply_model_paper_units(page: &mut PageSetup) {
page.paper_mm = Some(model_unit_mm(page) == 1.0);
}
/// Millimetres per paper-space unit on a layout with page setup `page`: `1.0` when the page
/// chooses millimetres, `25.4` when it chooses inches, else as the drawing's `MEASUREMENT`
/// says. Drawings from AutoCAD often have `MEASUREMENT` 0 with layouts in millimetres (#1058).
/// Millimetres per paper-space unit on a layout with page setup `page`: millimetres when the
/// page says so (plot paper units mm), else as the drawing's MEASUREMENT says. Drawings from
/// AutoCAD often have MEASUREMENT 0 with layouts in millimetres (#1058).
pub fn page_unit_mm(d: &Drawing, page: &PageSetup) -> f64 {
match page.paper_mm {
Some(true) => 1.0,
Some(false) => 25.4,
None => paper_unit_mm(d),
}
if page.paper_mm { 1.0 } else { paper_unit_mm(d) }
}
/// Millimetres per paper-space unit on the layout holding the paper-space entity `h` (the
@@ -200,92 +139,6 @@ pub fn sheet(d: &Drawing, layout: &str) -> Option<Sheet> {
mod tests {
use super::*;
#[test]
fn metric_length_unit_reads_the_length_unit() {
// Metric units, whatever MEASUREMENT says.
let mut d = Drawing::new_imperial();
d.header.set_i64("MEASUREMENT", 0);
for u in [4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] {
d.header.set_i64("INSUNITS", u);
assert!(metric_length_unit(&d), "INSUNITS {u} is metric");
}
// Imperial units, even with MEASUREMENT 1.
d.header.set_i64("MEASUREMENT", 1);
for u in [1, 2, 3, 8, 9, 10, 21, 22, 23, 24] {
d.header.set_i64("INSUNITS", u);
assert!(!metric_length_unit(&d), "INSUNITS {u} is imperial");
}
// Unitless: as MEASUREMENT says.
for u in [0, 25] {
d.header.set_i64("INSUNITS", u);
d.header.set_i64("MEASUREMENT", 1);
assert!(metric_length_unit(&d), "unitless with MEASUREMENT 1 is metric");
d.header.set_i64("MEASUREMENT", 0);
assert!(!metric_length_unit(&d), "unitless with MEASUREMENT 0 is imperial");
}
d.header.vars.remove("INSUNITS");
d.header.vars.remove("MEASUREMENT");
assert!(!metric_length_unit(&d), "no units at all is imperial, as before");
}
#[test]
fn paper_unit_mm_still_follows_measurement() {
let mut m = Drawing::new_metric();
assert_eq!(paper_unit_mm(&m), 1.0);
m.header.set_i64("MEASUREMENT", 0);
assert_eq!(paper_unit_mm(&m), 25.4, "layouts stay on MEASUREMENT (page setups in inches fit)");
let mut i = Drawing::new_imperial();
assert_eq!(paper_unit_mm(&i), 25.4);
i.header.set_i64("INSUNITS", 4);
assert_eq!(paper_unit_mm(&i), 25.4, "a metric length unit does not move layout paper units");
i.header.set_i64("MEASUREMENT", 1);
assert_eq!(paper_unit_mm(&i), 1.0);
}
#[test]
fn model_unit_mm_reads_the_paper() {
let page = |name: &str| PageSetup { paper: name.into(), ..PageSetup::default() };
assert_eq!(model_unit_mm(&page("ISO A4")), 1.0);
assert_eq!(model_unit_mm(&page("ISO A0")), 1.0);
assert_eq!(model_unit_mm(&page("ANSI A")), 25.4);
assert_eq!(model_unit_mm(&page("ARCH D")), 25.4);
assert_eq!(model_unit_mm(&page("User (300.00 x 400.00 MM)")), 1.0);
assert_eq!(model_unit_mm(&page("nope")), 1.0, "an unknown paper is a user millimetre size");
assert_eq!(model_unit_mm(&PageSetup::default()), 25.4, "the default page is ANSI A");
}
#[test]
fn model_page_is_a4_for_metric_drawings() {
let mut d = Drawing::new_metric();
let page = model_page(&d);
assert_eq!(page.paper, "ISO A4 (210.00 x 297.00 MM)");
assert_eq!((page.width_mm, page.height_mm), (210.0, 297.0));
assert_eq!(page.paper_mm, Some(true), "A4 in a metric drawing is in millimetres");
// The length unit decides, not MEASUREMENT.
d.header.set_i64("MEASUREMENT", 0);
assert_eq!(model_page(&d).paper, "ISO A4 (210.00 x 297.00 MM)");
// An imperial drawing starts on ANSI A.
let page = model_page(&Drawing::new_imperial());
assert_eq!(page.paper, "ANSI A (8.50 x 11.00 Inches)");
assert!((page.width_mm - 215.9).abs() < 1e-9 && (page.height_mm - 279.4).abs() < 1e-9);
assert_eq!(page.paper_mm, Some(false), "ANSI A in an imperial drawing is in inches");
}
#[test]
fn model_paper_units_follow_the_chosen_paper() {
// The sheet decides, whatever the drawing's length unit is.
let mut a4 = PageSetup { paper: "ISO A4 (210.00 x 297.00 MM)".into(), ..PageSetup::default() };
apply_model_paper_units(&mut a4);
assert_eq!(a4.paper_mm, Some(true), "ISO A4 is a millimetre sheet");
let mut ansi = PageSetup { paper: "ANSI A (8.50 x 11.00 Inches)".into(), ..PageSetup::default() };
apply_model_paper_units(&mut ansi);
assert_eq!(ansi.paper_mm, Some(false), "ANSI A is an inch sheet");
// A user size in millimetres is one to one.
let mut user = PageSetup { paper: "User (300.00 x 400.00 MM)".into(), ..PageSetup::default() };
apply_model_paper_units(&mut user);
assert_eq!(user.paper_mm, Some(true));
}
#[test]
fn lookup_and_sheet() {
assert_eq!(paper_size("a4").map(|p| p.width_mm), Some(210.0));
@@ -301,23 +154,6 @@ mod tests {
let s = Sheet::from_page(&hostile, 0.0);
assert!(s.size.x > 0.0 && s.printable == s.bounds());
}
#[test]
fn page_unit_mm_honours_explicit_choice_and_falls_back_to_measurement() {
let mut imperial = Drawing::new_imperial();
imperial.header.set_i64("MEASUREMENT", 0);
let mut metric = Drawing::new_metric();
metric.header.set_i64("MEASUREMENT", 1);
let unset = PageSetup::default();
let mm = PageSetup { paper_mm: Some(true), ..PageSetup::default() };
let inches = PageSetup { paper_mm: Some(false), ..PageSetup::default() };
assert_eq!(page_unit_mm(&imperial, &unset), 25.4);
assert_eq!(page_unit_mm(&imperial, &mm), 1.0);
assert_eq!(page_unit_mm(&imperial, &inches), 25.4);
assert_eq!(page_unit_mm(&metric, &unset), 1.0);
assert_eq!(page_unit_mm(&metric, &mm), 1.0);
assert_eq!(page_unit_mm(&metric, &inches), 25.4);
}
}
/// What a layout's saved page setup says about how to plot it, for a plot that was not given the
+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())
+5 -26
View File
@@ -584,8 +584,7 @@ fn page_setup(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action
let Some((_, name, page)) = layouts.iter().find(|l| l.1 == sel) else { return };
right.label(RichText::new(format!("Page setup of {name}")).strong());
// Layout plotting always prints the whole sheet, so only that area is offered.
let paper_mm = cadcraft_render::paper::page_unit_mm(d, page) == 1.0;
let rows = PageRows { areas: &["layout"], scale: true, center: true, paper_mm: Some(paper_mm) };
let rows = PageRows { areas: &["layout"], scale: true, center: true };
egui::Grid::new("pagesetup_grid").num_columns(2).spacing(vec2(10.0, 6.0)).show(right, |ui| {
if let Some((k, v)) = page_rows(ui, egui::Id::unique(("pagesetup", name)), page, &rows, &choices, None) {
action = Some(("pagesetup", json!({ "layout": name, k: v })));
@@ -605,9 +604,6 @@ struct PageRows {
areas: &'static [&'static str],
scale: bool,
center: bool,
/// Effective paper units (`Some(true)` = millimetres, `Some(false)` = inches) for the layout's
/// page setup, or `None` to hide the row (the Plot dialog).
paper_mm: Option<bool>,
}
/// The devices and plot style tables the page-setup rows offer.
@@ -670,7 +666,7 @@ fn parse_ratio(t: &str) -> Option<f64> {
/// The page-setup rows (device, paper, orientation, plot area, fit, scale, center, lineweights,
/// transparency, plot style table) shared by the Page Setup Manager and the Plot dialog, inside a
/// two-column grid. Returns the setting the user changed as a `pagesetup` parameter (`device`,
/// `paper`, `landscape`, `paperUnits`, `plotArea`, `scaleToFit`, `scale`, `center`, `lineweights`,
/// `paper`, `landscape`, `plotArea`, `scaleToFit`, `scale`, `center`, `lineweights`,
/// `plotTransparency` or `plotStyleTable`).
fn page_rows(
ui: &mut egui::Ui,
@@ -728,23 +724,6 @@ fn page_rows(
}
});
ui.end_row();
if let Some(mm) = rows.paper_mm {
ui.label(crate::tl!("Paper units"));
ui.horizontal(|ui| {
// Every click records the choice, even on the selected radio: while the layout has
// no explicit units it inherits MEASUREMENT, and clicking the value it currently
// inherits must lock that choice against a later MEASUREMENT change (#3249).
if ui.radio(!mm, crate::tl!("Inches")).clicked() {
change = Some(("paperUnits", json!("inches")));
}
if ui.radio(mm, crate::tl!("Millimeters")).clicked() {
change = Some(("paperUnits", json!("mm")));
}
})
.response
.on_hover_text(crate::tl!("What one paper-space unit is on this layout"));
ui.end_row();
}
ui.label("Plot area");
ui.add_enabled_ui(rows.areas.len() > 1, |ui| {
craft_ui::ComboBox::from_id_salt(salt.with("area")).selected_text(area_label(&page.plot_area)).show_ui(ui, |ui| {
@@ -930,7 +909,7 @@ fn plot_page(d: &cadcraft_doc::Drawing, target: &str) -> cadcraft_doc::PageSetup
return page;
}
let mut page = cadcraft_doc::PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..Default::default() };
if cadcraft_render::paper::metric_length_unit(d)
if cadcraft_render::paper::paper_unit_mm(d) == 1.0
&& let Some(a4) = cadcraft_render::paper_size("A4")
{
page.paper = a4.name.into();
@@ -1055,9 +1034,9 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
ui.horizontal_top(|ui| {
egui::Grid::new("plot_grid").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
let rows = if model {
PageRows { areas: MODEL_AREAS, scale: true, center: false, paper_mm: None }
PageRows { areas: MODEL_AREAS, scale: true, center: false }
} else {
PageRows { areas: &["layout"], scale: false, center: false, paper_mm: None }
PageRows { areas: &["layout"], scale: false, center: false }
};
let placement = model.then_some((&mut st.center, &mut st.offset_mm, offset_supported));
if let Some((k, v)) = page_rows(ui, egui::Id::unique(("plot", st.target.as_str())), &st.page, &rows, &choices, placement) {
+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 -1
View File
@@ -21,15 +21,16 @@ 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;
mod native_windows;
mod options_dialog;
mod options_right_click;
mod page_setup_paper_units;
mod parameters_rename;
mod pickdrag;
mod press_first_clicks;
mod properties_described;
mod properties_units;
mod rapid_clicks;
@@ -37,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);
@@ -1,87 +0,0 @@
//! File ▸ Page Setup Manager: a layout's paper units can be millimetres on an inch-family sheet
//! (an ARCH D sheet in a metric drawing, #3249), so the sheet measures 914.4 x 609.6 units.
use cadcraft_engine::Session;
use cadcraft_ui_egui::{CadApp, Services};
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
#[test]
fn page_setup_switches_an_arch_d_sheet_to_millimetres() {
let mut app = CadApp::new(Session::new(), Services::default());
app.run("units", json!({ "insunits": 4 })).unwrap();
app.run("pagesetup", json!({ "layout": "Layout1", "paper": "ARCH D", "landscape": true })).unwrap();
let inch = cadcraft_render::sheet(app.session.doc().unwrap(), "Layout1").unwrap();
assert!((inch.size.x - 36.0).abs() < 1e-9, "{:?}", inch.size);
app.start("pagesetup");
// The dialog's existing combo boxes (device, paper, plot area, plot style) have no
// accessible name yet; that check is not what this test is about.
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_accessibility_check(false).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.get_by_label("Millimeters").click();
h.run_steps(5);
let d = h.state().session.doc().unwrap();
assert_eq!(d.layout("Layout1").unwrap().page.paper_mm, Some(true));
let mm = cadcraft_render::sheet(d, "Layout1").unwrap();
assert!((mm.size.x - 914.4).abs() < 1e-9 && (mm.size.y - 609.6).abs() < 1e-9, "{:?}", mm.size);
}
#[test]
fn page_setup_switches_a_metric_drawing_sheet_to_inches() {
let mut app = CadApp::new(Session::new(), Services::default());
app.run("setvar", json!({ "name": "MEASUREMENT", "value": 1 })).unwrap();
app.run("pagesetup", json!({ "layout": "Layout1", "paper": "ARCH D", "landscape": true })).unwrap();
let mm = cadcraft_render::sheet(app.session.doc().unwrap(), "Layout1").unwrap();
assert!((mm.size.x - 914.4).abs() < 1e-9 && (mm.size.y - 609.6).abs() < 1e-9, "{:?}", mm.size);
app.start("pagesetup");
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_accessibility_check(false).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.get_by_label("Inches").click();
h.run_steps(5);
let d = h.state().session.doc().unwrap();
assert_eq!(d.layout("Layout1").unwrap().page.paper_mm, Some(false));
let inch = cadcraft_render::sheet(d, "Layout1").unwrap();
assert!((inch.size.x - 36.0).abs() < 1e-9 && (inch.size.y - 24.0).abs() < 1e-9, "{:?}", inch.size);
}
#[test]
fn clicking_the_inherited_paper_units_records_the_choice() {
// The layout starts with no explicit units and inherits MEASUREMENT 0 (inches). Clicking the
// selected Inches radio must record that choice, so a later MEASUREMENT change cannot flip
// the sheet to millimetres (#3249).
let mut app = CadApp::new(Session::new(), Services::default());
app.run("pagesetup", json!({ "layout": "Layout1", "paper": "ARCH D", "landscape": true })).unwrap();
assert_eq!(app.session.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, None);
app.start("pagesetup");
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_accessibility_check(false).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.get_by_label("Inches").click();
h.run_steps(5);
assert_eq!(h.state().session.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, Some(false));
h.state_mut().run("setvar", json!({ "name": "MEASUREMENT", "value": 1 })).unwrap();
let d = h.state().session.doc().unwrap();
assert_eq!(d.layout("Layout1").unwrap().page.paper_mm, Some(false));
let inch = cadcraft_render::sheet(d, "Layout1").unwrap();
assert_eq!(inch.unit_mm, 25.4);
assert!((inch.size.x - 36.0).abs() < 1e-9 && (inch.size.y - 24.0).abs() < 1e-9, "{:?}", inch.size);
}
+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");
}