Compare commits

..
29 Commits
Author SHA1 Message Date
Tanish Manku d1cb40332b Stack u2: #3077: collapse the nested if (clippy) 2026-11-19 15:42:50 -07:00
Tanish Mankuandgraficaeusebio-cloud b7d5ed3401 Stack u2: #1279: test that Options reset also brings back the status bar and command line
Carried over from #1283's test, which also covered the status bar.

Co-authored-by: graficaeusebio-cloud <224763601+graficaeusebio-cloud@users.noreply.github.com>
2026-11-19 15:19:53 -07:00
Tanish Manku 6b767073d8 Stack u2: #1279: Options reset keeps the user's shortcuts and remembered folders
The reset now rebuilds the whole interface state so hidden bars come back (#1240), but that
also dropped the user's keyboard shortcuts and the APPLOAD and .pgp folders, which the old
reset and Window > Reset Palettes keep.
2026-11-19 15:18:53 -07:00
Tanish Manku 7bcfe25938 Stack u2: #1452: a Chinese label for MENUBAR's Menu Bar
main requires a Chinese label for every command (chinese_menus_and_commands_are_fully_translated);
the new MENUBAR command's label had none.
2026-11-19 15:18:13 -07:00
Tanish Manku 3886fb952d Merge #3077 2026-11-19 15:17:16 -07:00
Tanish Manku 6c9eedd7e1 Merge #2443 2026-11-19 15:17:16 -07:00
Tanish Manku 6411c1a4ab Merge #1867 2026-11-19 15:17:15 -07:00
Tanish Manku 6f203fb64b Merge #1452 2026-11-19 15:17:15 -07:00
Tanish Manku a2d209e10b Merge #1279 2026-11-19 15:17:15 -07:00
midasmatterhorn cd226cdf0f ui: keep the in-window menu where the host has no native one 2026-11-14 17:18:20 +03:00
assamaralandClaude Opus 5.5 8d2c9d1a26 fix(app): a saved main window below the minimum size opens at the default size
On Windows app.ron can hold a 64x64 window (e.g. saved while minimized).
eframe restores it as is, so the next launch shows an unusable tiny window.
Such an entry is now dropped from app.ron before launch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:19:42 -03:00
Nicholas Gower 0156fd9b9f docking: follow the shared surface's stock tab menu and non-exhaustive node
The dock area's tab menu item is "Close Panel" in the pinned craft-ui, and
Node is non-exhaustive, so the accordion scan needs a catch-all arm.
2026-11-02 08:26:29 -08:00
Nicholas Gower df2a5131af i18n: the panel close button's accessible name translates as a whole
The header close button built its name by joining an English "Close" to
the translated panel label, so Spanish screen readers heard "Close Capas".
A single translatable "Close {panel}" template now carries both parts, and
the tooltip's "Close panel" joins the catalogs too. Spanish gets both
rows, Ukrainian (the reference catalog) is required to have them, and
docking.rs joins the scanned sources so future marked strings stay covered.

Regression test: a Spanish harness finds "Cerrar Capas" and "Cerrar
Propiedades" by accessible name, proves "Close Capas" is gone, and closes
Layers through the localized button.
2026-11-02 08:24:52 -08:00
Nicholas Gower 5644c6c946 docs: document the functions touched by #1838 2026-11-02 08:24:04 -08:00
Nicholas Gower 0fa45daf25 UI: a visible close button on every panel header (fixes #1838)
Every dockable panel header now carries an X beside its title, so closing
a palette no longer has to be discovered in the tab context menu. The
button queues the same Close action as that menu item.

Tab and floating group headers use the docking surface's header callback;
accordion title bars place the same button left of the stock collapse
control. The accessible name includes the panel ("Close Layers"), the
tooltip says "Close panel", and the drawing canvas stays unclosable.

Regression test: crates/ui-egui/tests/docking_workflows.rs. It opens the
External References tab and checks its button does not cover the title,
closes the default Layers accordion entry, closes a floating Properties
group, and still closes Layers through the context menu.
2026-11-02 08:23:33 -08:00
austin62jake a92fb047d8 Merge remote-tracking branch 'upstream/main' into fix/refmanager-menu-closes 2026-11-01 07:07:28 -06:00
midasmatterhorn 33dc795c5f ui: the options reset brings a hidden menu bar and tool bar back 2026-11-01 05:26:41 +03:00
Aldo Zarate 4255108429 Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds
# Conflicts:
#	crates/ui-egui/src/lib.rs
2026-10-31 14:08:28 -06:00
Aldo Zarate 0b585fa8cb Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds
# Conflicts:
#	crates/engine/src/lib.rs
2026-10-30 13:52:46 -06:00
austin62jakeandClaude Opus 5.5 21d9627840 fix(ui): Window > Reference Manager closes the open palette
Once the External References palette was open, Window > Reference
Manager only opened it again, so there was no obvious way to close it
(the tab's right-click Close Panel works but is easy to miss). The menu
item now closes the palette when it is open, as Window > QuickCalc does
for QuickCalc (#2001). Typed XREF still only opens it, as in AutoCAD,
and XREF with JSON parameters still only lists the references.

Fixes #2273.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 22:33:23 -05:00
Aldo ZarateandClaude Opus 5.5 1c611d610d Control API: the bars are synced after every request
A command a control request runs (MENUBAR, TOOLBAR, also through cmdline.key) may ask for a bar;
control::handle now applies that before the next request, so a later query or ui.set sees the
bars as they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:29:46 -06:00
Aldo Zarate 076b7761a3 Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds 2026-10-28 10:26:55 -06:00
Aldo ZarateandClaude Opus 5.5 71a0ef2260 MENUBAR started from the interface offers the bar as shown now
CadApp::start syncs the bars before starting the command, as run and cmdline do, so MENUBAR's
default is the menu bar as the interface shows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:12:50 -06:00
Aldo ZarateandClaude Opus 5.5 4fadc54dbe MENUBAR/TOOLBAR: control-API calls see the bars as shown now
CadApp::run now syncs the bars before and after the engine runs, as the command line does,
so a bar query right after a ui.set reports the interface's current bars and a MENUBAR or
TOOLBAR request is applied at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:46:12 -06:00
Aldo ZarateandClaude Opus 5.5 9c2ebc0e12 MENUBAR/TOOLBAR: request each bar on its own
The request was both bars as one snapshot, so a tool bar change made between MENUBAR and the
UI applying it was undone. Each command now asks only for its own bar, and the UI applies only
the bars asked for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:25:10 -06:00
Aldo ZarateandClaude Opus 5.5 98240d82d0 MENUBAR/TOOLBAR: explicit imports for the wildcard-imports lint
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:03:36 -06:00
Aldo Zarate 1e1cf10a1c Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds 2026-10-28 08:02:57 -06:00
Aldo Zarate af460caac6 Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds 2026-10-26 19:34:20 -06:00
Aldo ZarateandClaude Opus 5.5 ad072e6cb0 MENUBAR and TOOLBAR at the command line bring hidden bars back (#1341)
On Windows and Linux the in-window menu bar is the only menu, so once it
was hidden there was no way back from the keyboard: MENUBAR and TOOLBAR,
which AutoCAD users type for this, were unknown commands.

MENUBAR asks "Enter new value for MENUBAR <1>:" (1 shows, 0 hides), and
TOOLBAR (alias -TOOLBAR) asks for Show or Hide, Show by default. The JSON
forms report or set the bars. The engine records the change and the UI
applies it, reporting what it shows every frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:54:43 -06:00
37 changed files with 836 additions and 1212 deletions
+45 -4
View File
@@ -233,11 +233,38 @@ fn saved_window(app_ron: &str) -> bool {
ron::from_str::<std::collections::HashMap<String, String>>(app_ron).is_ok_and(|kv| kv.contains_key(WINDOW_KEY))
}
/// The window state from the last session is saved and will be restored (#2595).
/// The window state from the last session is saved and will be restored (#2595). A saved size
/// below the minimum (seen on Windows: 64×64 points, which eframe restores un-maximized and
/// unusable) is dropped first, so the window opens at its default size.
fn restores_window() -> bool {
eframe::storage_dir(APP_ID).and_then(|dir| std::fs::read_to_string(dir.join("app.ron")).ok()).is_some_and(|ron| saved_window(&ron))
let Some(path) = eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron")) else { return false };
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
if let Some(fixed) = without_tiny_window(&ron)
&& std::fs::write(&path, &fixed).is_ok()
{
ron = fixed;
}
saved_window(&ron)
}
/// `app_ron` without its window entry when that entry's inner size is below `MIN_INNER_SIZE`;
/// `None` when there is nothing to drop (no entry, a usable size, or an unreadable file).
fn without_tiny_window(app_ron: &str) -> Option<String> {
let mut kv = ron::from_str::<std::collections::BTreeMap<String, String>>(app_ron).ok()?;
let w = kv.get(WINDOW_KEY)?;
let size = &w[w.find("inner_size_points:")?..];
let num = |k: &str| size[size.find(k)? + k.len()..].split([',', ')']).next()?.trim().parse::<f32>().ok();
let (x, y) = (num("x:")?, num("y:")?);
if x >= MIN_INNER_SIZE[0] && y >= MIN_INNER_SIZE[1] {
return None;
}
kv.remove(WINDOW_KEY);
ron::ser::to_string_pretty(&kv, ron::ser::PrettyConfig::default()).ok()
}
/// The smallest main window, in points.
const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred.
fn window_options(restoring: bool) -> eframe::NativeOptions {
@@ -245,7 +272,7 @@ fn window_options(restoring: bool) -> eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("CADCraft")
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size([900.0, 560.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
@@ -403,6 +430,9 @@ fn main() -> eframe::Result {
app.ui = ui;
}
app.set_system_cursor_default(vars.system_cursor == Switch::On);
// macOS: CADCRAFT_NO_NATIVE_MENU=1 keeps the menus inside the window.
#[cfg(target_os = "macos")]
app.set_native_menus(vars.no_native_menu != Switch::On);
if let Some(error) = &workspace_error {
eprintln!("CADCraft workspace: {error}");
app.set_status(error);
@@ -481,7 +511,7 @@ fn main() -> eframe::Result {
#[cfg(test)]
mod tests {
use super::{filters_for_save, follow_desktop, saved_window, window_options};
use super::{filters_for_save, follow_desktop, saved_window, window_options, without_tiny_window};
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
@@ -525,6 +555,17 @@ mod tests {
assert!(!saved_window("not ron at all"));
}
/// A saved 64×64 window (below the minimum) is dropped; a usable one is kept.
#[test]
fn a_tiny_saved_window_is_dropped() {
let tiny = r#"{"window": "(normal_geometry:(outer_position_pixels:Some((x:0.0,y:0.0)),scale_factor:1.25,inner_size_points:(x:64.0,y:64.0)),fullscreen:false,maximized:true)", "cadcraft.prefs": "{}"}"#;
let fixed = without_tiny_window(tiny).expect("dropped");
assert!(!saved_window(&fixed) && fixed.contains("cadcraft.prefs"));
let ok = tiny.replace("x:64.0,y:64.0)),", "x:1600.0,y:1000.0)),");
assert_eq!(without_tiny_window(&ok), None);
assert_eq!(without_tiny_window("not ron"), None);
}
/// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in;
/// without one (or where winit answers and the desktop doesn't) the input is left alone.
#[test]
-5
View File
@@ -128,8 +128,3 @@ sync_github_name = true
[people.tyrel]
real_name = "Tyrel Haveman"
[people.Sladrian]
real_name = "Sladrian Pedroso"
display_name = "Sladrian Pedroso"
sync_github_name = false
+2
View File
@@ -22,6 +22,7 @@ pub(crate) mod groups;
pub(crate) mod hatch;
mod image;
mod inquiry;
pub mod interface;
mod layer;
mod layout;
mod lisp;
@@ -212,6 +213,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(inquiry::specs());
v.extend(settings::specs());
v.extend(options::specs());
v.extend(interface::specs());
v.extend(utility::specs());
v.extend(table::specs());
v.extend(tolerance::specs());
+134
View File
@@ -0,0 +1,134 @@
//! MENUBAR and TOOLBAR: show or hide the window's menu bar and tool bar from the command line, as
//! in AutoCAD. With the menu bar hidden on Windows and Linux (where it is the only menu), typing
//! these is the way back.
//!
//! The UI owns the bars: it reports what it shows in [`Session::bars_shown`] and applies
//! [`Session::bars_request`], which these commands set.
use serde_json::{Value, json};
use super::{CommandSpec, always, bad};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
/// The interface bars MENUBAR and TOOLBAR control.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InterfaceBars {
pub menubar: bool,
pub toolbar: bool,
}
impl Default for InterfaceBars {
fn default() -> Self {
InterfaceBars { menubar: true, toolbar: true }
}
}
/// A change MENUBAR or TOOLBAR asked for: only the bars a command set, so the UI leaves the other
/// as it is (it may have been changed since).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BarsRequest {
pub menubar: Option<bool>,
pub toolbar: Option<bool>,
}
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("menubar", "Menu Bar", run_menubar)
.params("{value?: 0|1} (1 shows the in-window menu bar, 0 hides it; without it, reports it)")
.enabled(always)
.noundo()
.interactive(|s| Ok(Box::new(MenubarM { current: s.bars_shown.menubar }))),
CommandSpec::new("toolbar", "Tool Bar", run_toolbar)
.alias(&["-toolbar"])
.params("{show?: bool} (without it, reports it)")
.enabled(always)
.noundo()
.interactive(|_| Ok(Box::new(ToolbarM))),
]
}
fn set_menubar(s: &mut Session, on: bool) {
s.bars_shown.menubar = on;
s.bars_request.menubar = Some(on);
}
fn set_toolbar(s: &mut Session, show: bool) {
s.bars_shown.toolbar = show;
s.bars_request.toolbar = Some(show);
}
fn run_menubar(s: &mut Session, p: &Value) -> Result<Value> {
let v = match p.get("value") {
None | Some(Value::Null) => return Ok(json!({ "value": u8::from(s.bars_shown.menubar) })),
Some(v) => v
.as_u64()
.or_else(|| v.as_str().and_then(|t| t.trim().parse().ok()))
.filter(|v| *v <= 1)
.ok_or_else(|| bad("menubar", "`value` must be 0 or 1"))?,
};
set_menubar(s, v == 1);
Ok(json!({ "value": v }))
}
fn run_toolbar(s: &mut Session, p: &Value) -> Result<Value> {
let Some(show) = p.get("show").filter(|v| !v.is_null()) else { return Ok(json!({ "show": s.bars_shown.toolbar })) };
let show = show.as_bool().ok_or_else(|| bad("toolbar", "`show` must be true or false"))?;
set_toolbar(s, show);
Ok(json!({ "show": show }))
}
/// Typed MENUBAR: "Enter new value for MENUBAR <1>:".
struct MenubarM {
current: bool,
}
impl Interactive for MenubarM {
fn name(&self) -> &'static str {
"MENUBAR"
}
fn prompt(&self, _s: &Session) -> Prompt {
Prompt::new("Enter new value for MENUBAR", Accept::NUMBER).default(u8::from(self.current).to_string())
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Enter => Ok(Step::Done),
Input::Text(t) => match run_menubar(s, &json!({ "value": t })) {
Ok(_) => Ok(Step::Done),
Err(_) => {
s.echo("Requires 0 or 1.");
Ok(Step::Continue)
}
},
_ => Ok(Step::Continue),
}
}
}
/// Typed TOOLBAR: "Enter tool bar option [Show/Hide] <Show>:" (CADCraft has one tool bar).
struct ToolbarM;
impl Interactive for ToolbarM {
fn name(&self) -> &'static str {
"TOOLBAR"
}
fn prompt(&self, _s: &Session) -> Prompt {
Prompt::new("Enter tool bar option", Accept::TEXT).kw(&["Show", "Hide"]).default("Show")
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let word = match &i {
Input::Enter => "show".to_string(),
Input::Keyword(k) | Input::Text(k) => k.trim().to_ascii_lowercase(),
_ => return Ok(Step::Continue),
};
let show = if !word.is_empty() && "show".starts_with(&word) {
true
} else if !word.is_empty() && "hide".starts_with(&word) {
false
} else {
s.echo("Invalid option keyword.");
return Ok(Step::Continue);
};
run_toolbar(s, &json!({ "show": show }))?;
Ok(Step::Done)
}
}
+1 -4
View File
@@ -323,16 +323,13 @@ 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 { picks_one: self.removing, ..Prompt::new(if self.removing { "Remove objects" } else { "Select objects" }, Accept::POINT) }
}
(StretchPhase::Select, None) => 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),
+3 -4
View File
@@ -8,7 +8,6 @@ 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};
@@ -361,7 +360,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, KW).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
Prompt::new(msg, Accept::TEXT).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
}
Stage::Project => {
let cur = match proj_mode(s) {
@@ -369,9 +368,9 @@ impl Interactive for TrimM {
2 => "View",
_ => "Ucs",
};
Prompt::new("Enter a projection option", KW).kw(&["None", "Ucs", "View"]).default(cur)
Prompt::new("Enter a projection option", Accept::TEXT).kw(&["None", "Ucs", "View"]).default(cur)
}
Stage::Edge => Prompt::new("Enter an implied edge extension mode", KW).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
Stage::Edge => Prompt::new("Enter an implied edge extension mode", Accept::TEXT).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
"Extend"
} else {
"No extend"
+6
View File
@@ -156,6 +156,10 @@ pub struct Session {
lisp_last: Option<std::result::Result<lisp::value::Value, String>>,
/// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks).
pub hatch_picks: Option<cmd::hatch::HatchPicks>,
/// The window's menu bar and tool bar as the UI shows them (it reports them every frame).
pub bars_shown: cmd::interface::InterfaceBars,
/// The bars MENUBAR or TOOLBAR asked to change, for the UI to apply.
pub bars_request: cmd::interface::BarsRequest,
/// The object named with a point for the input a prompt picking one object is taking
/// ([`Session::input_object`]): a pick at exactly that point picks that object
/// ([`Session::pick_object`]).
@@ -215,6 +219,8 @@ impl Session {
lisp: lisp::LispState::default(),
lisp_last: None,
hatch_picks: None,
bars_shown: Default::default(),
bars_request: Default::default(),
pick_hint: None,
}
}
+143 -207
View File
@@ -20,7 +20,6 @@ mod grid;
mod grips;
mod list;
mod pick;
mod press;
mod viewport;
mod widgets;
@@ -165,7 +164,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.
pub(crate) grip_menu: Option<(Handle, usize)>,
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,
@@ -182,8 +181,8 @@ pub struct CanvasState {
hover_frozen: Vec<String>,
/// Constraint glyphs for the parametric overlay (cached per drawing revision).
pub param: crate::parametric::Cache,
/// The primary-button press being held, when it was acted on (see [`press`]).
press: Option<press::Press>,
/// A selection window opened by a press-and-drag, to close where the button is let go.
drag_window: bool,
/// 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,
@@ -514,7 +513,13 @@ fn paint_content_highlights(frame: &mut CanvasPaint<'_>, bg: Rgb, sel: &[Handle]
}
}
fn paint_pointer_overlay(frame: &mut CanvasPaint<'_>, paper_rect: Option<Rect>, surround: Color32, sheet: Option<cadcraft_render::Sheet>) {
fn paint_pointer_overlay(
frame: &mut CanvasPaint<'_>,
paper_rect: Option<Rect>,
surround: Color32,
selecting: bool,
sheet: Option<cadcraft_render::Sheet>,
) {
let app = &mut *frame.app;
let ui = &mut *frame.ui;
let painter = frame.painter;
@@ -558,8 +563,7 @@ fn paint_pointer_overlay(frame: &mut CanvasPaint<'_>, paper_rect: Option<Rect>,
// 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 }));
let picking = app.session.picking_objects() && app.session.pending_window.is_none();
draw_crosshair(app, painter, rect, hp, picking, ink);
draw_crosshair(app, painter, rect, hp, selecting, ink);
if app.canvas.cycle_badge && app.canvas.cycle.is_none() {
cycle_badge(painter, hp);
}
@@ -607,12 +611,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.press = None;
app.canvas.drag_window = false;
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.press = None;
app.canvas.drag_window = false;
app.canvas.list = None;
return None;
}
@@ -653,7 +657,43 @@ 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);
track_cursor(app, raw_world, xf, ui.ctx(), dyn_frame);
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;
}
(raw_world, dyn_frame)
}
@@ -703,91 +743,48 @@ fn update_hover(app: &mut CadApp, ui: &egui::Ui, inside: bool, hover_pos: Option
}
}
struct PressContext {
struct PromptClickContext<'a> {
rect: Rect,
xf: Xf,
inside: bool,
middle_down: bool,
mods: egui::Modifiers,
primary_clicked: bool,
response: &'a egui::Response,
}
/// 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());
}
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());
}
}
}
}
if !primary_down {
// The button came up where we didn't see it (outside the window, say).
app.canvas.press = None;
}
click_used
pressed_primary
}
/// Whether a quick right-click cancels the running command instead of acting as Enter: it asks for
@@ -875,21 +872,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
return;
};
// 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 pressed_primary =
collect_prompt_clicks(app, ui, PromptClickContext { rect, xf, inside, middle_down, primary_clicked: pressed_primary, response: &resp });
let (raw_world, dyn_frame) = update_canvas_cursor(app, ui, &xf, inside, hover_pos);
@@ -909,14 +893,26 @@ 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.press = None;
app.canvas.drag_window = false;
}
let pressed_primary = pressed_primary && !picked && !hatch_dialog && !idle_dbl;
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.
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.
if inside
&& pressed_primary
&& !click_used
&& !middle_down
&& !cycled
&& let Some(p) = app.canvas.cursor
@@ -948,31 +944,58 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
app.session.echo(e.to_string());
}
}
// 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.
// 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.
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 && !enter) || app.canvas.snap_menu {
} else if idle || app.canvas.snap_menu {
crate::context_menu::show(app, &resp);
}
@@ -998,95 +1021,6 @@ 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,
@@ -1107,6 +1041,7 @@ 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)];
@@ -1288,6 +1223,7 @@ fn paint_canvas(frame: CanvasPaint<'_>) {
},
paper_rect,
surround,
selecting,
sheet,
);
}
+12 -21
View File
@@ -212,37 +212,28 @@ 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 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 pb = if pickbox { pickbox_half(app.session.settings.pickbox) } else { None };
let gap = pb.unwrap_or(0.0);
// 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);
// 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);
}
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
@@ -1,167 +0,0 @@
//! 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,66 +249,6 @@ 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) {
+14 -26
View File
@@ -1,7 +1,6 @@
//! The canvas's right-click menus, after AutoCAD's shortcut menus:
//!
//! - **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
//! - **No command running** ([`entries`]): 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.
@@ -11,8 +10,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).
//! With it off, `rightClickDefault` and `rightClickEdit` can make a right-click with no command
//! running repeat the last command instead of opening the menu.
//! `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.
//!
@@ -388,16 +387,13 @@ 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 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.
// 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.
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()
{
@@ -421,15 +417,13 @@ pub fn show(app: &mut CadApp, resp: &egui::Response) {
#[derive(Clone, Copy, Default)]
struct Press(f64, egui::Pos2);
/// 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.
/// 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.
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");
@@ -454,21 +448,15 @@ 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 {
// 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;
return false;
}
let mut clicked = None;
let popup = egui::Popup::new(popup_id, ctx, egui::PopupAnchor::PointerFixed, ui.layer_id())
+8
View File
@@ -308,6 +308,14 @@ fn key_from(name: &str) -> Option<egui::Key> {
}
pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
let out = handle_request(app, ctx, req);
// A command the request ran may have asked for a bar (MENUBAR, TOOLBAR): apply it before
// the next request, so a later query or `ui.set` sees the bars as they are now.
app.sync_bars();
out
}
fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
let p = &req.params;
let s = |k: &str| p.get(k).and_then(Value::as_str);
let f = |k: &str| p.get(k).and_then(Value::as_f64);
+94 -1
View File
@@ -316,6 +316,10 @@ pub fn command(app: &mut crate::CadApp, reset: bool, params: &Value) -> Result<V
}
/// Validate and repair the stored workspace, sync it with the app, and render the dock panels; a failed restore falls back to the default layout with a status message.
/// Draw the docked workspace: restore or fall back from the persisted layout, render every
/// panel body plus the header close buttons, and apply the resulting actions through
/// [`command`]. Bodies may dispatch commands, so the canonical workspace is published before
/// rendering while the layout snapshot stays immutable.
pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) {
let t = crate::theme::Tokens::get();
let mut workspace = app.ui.docking.clone();
@@ -348,7 +352,33 @@ pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) {
if let Some(panel) = app.raise_panel.take() {
area = area.raise_panel(panel);
}
let mut output = area.show_content(ui, &workspace.layout, &style, &mut Panels { app });
let (mut output, header_close) = {
let mut panels = Panels { app, close: None };
let output = area.show_content(ui, &workspace.layout, &style, &mut panels);
(output, panels.close)
};
// Accordion title bars are rendered by the shared surface without a header callback, so
// place the same close button over their title bar, left of the stock collapse control.
let mut close = header_close;
for panel in stack_panels(&workspace.layout) {
if !permissions(&panel).closable {
continue;
}
let Some(title) = ui.ctx().read_response(egui::Id::unique("cadcraft-docking").with(("tab", panel))) else { continue };
if !title.rect.is_positive() {
continue;
}
let rect = egui::Rect::from_center_size(
egui::pos2(title.rect.right() - 18.0 - CLOSE_BUTTON * 0.5 - 4.0, title.rect.center().y),
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
);
if close_button(ui, panel, rect) {
close = Some(panel);
}
}
if let Some(panel) = close {
output.actions.push(Action::Close { panel });
}
// Keys typed in a floating panel's own OS window run the main window's shortcuts and
// command line; files dropped on one open like files dropped on the main window.
app.forward_native_input(ui.ctx(), std::mem::take(&mut output.forwarded_events), output.forwarded_modifiers);
@@ -393,9 +423,55 @@ pub fn native_input_blocked(app: &crate::CadApp, ctx: &egui::Context) -> bool {
/// The panels' contents, names, size limits and icons for the dock area.
pub struct Panels<'a> {
pub app: &'a mut crate::CadApp,
/// The panel whose header close button was clicked this frame.
pub close: Option<Panel>,
}
/// Size of a panel header's close button, in points.
const CLOSE_BUTTON: f32 = 16.0;
/// The accessible name of a header's close button. One translated template carries both the
/// verb and the panel name, so a catalog translates the whole name instead of leaving an
/// English verb in front of a translated panel label.
fn close_label(panel: Panel) -> String {
crate::tf!("Close {panel}", panel = crate::i18n::t(panel.label()))
}
/// A visible close button for a panel header. It runs the same action as the tab context
/// menu's "Close panel"; the accessible name includes the panel so the headers stay distinct.
fn close_button(ui: &mut egui::Ui, panel: Panel, rect: egui::Rect) -> bool {
let t = crate::theme::Tokens::get();
let response = ui.interact(rect, egui::Id::unique("cadcraft-docking").with(("close", panel.id())), egui::Sense::click());
let label = close_label(panel);
crate::icons::describe_control(ui, &response, &label, None, false);
if response.hovered() {
ui.painter().rect_filled(rect.expand(2.0), 2.0, t.control_hover.gamma_multiply(0.6));
}
crate::icons::paint(ui.painter(), rect, crate::icons::Icon::Close, false);
response.on_hover_text(crate::tl!("Close panel")).clicked()
}
/// Panels whose title bar is an accordion entry rather than a tab group header.
fn stack_panels(layout: &Layout<Panel>) -> Vec<Panel> {
let mut panels = Vec::new();
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
while let Some(node) = nodes.pop() {
match node {
Node::Split { first, second, .. } => {
nodes.push(first);
nodes.push(second);
}
Node::Stack { entries } => panels.extend(entries.iter().map(|entry| entry.panel)),
// Tab groups draw their own header; nothing else stacks an accordion entry.
_ => {}
}
}
panels
}
impl DockContent<Panel> for Panels<'_> {
/// Render `panel`'s existing view; Layers, Properties and External References scroll
/// independently, and the drawing canvas paints its own background before the view.
fn body(&mut self, ui: &mut egui::Ui, panel: &Panel) {
let app = &mut *self.app;
match panel {
@@ -445,6 +521,23 @@ impl DockContent<Panel> for Panels<'_> {
crate::icons::paint(painter, rect, icon, false);
true
}
/// Reserve header space for the close button only when `active` may be closed, so the
/// drawing view's title gets no empty gap.
fn group_header_width(&self, _panels: &[Panel], active: &Panel, _floating: bool, _strip_width: f32) -> f32 {
if permissions(active).closable { CLOSE_BUTTON + 8.0 } else { 0.0 }
}
/// Draw the close button at the right edge of a tab-group header and remember the panel
/// to close once the docking surface has returned, so layout changes stay outside rendering.
fn group_header(&mut self, ui: &mut egui::Ui, _panels: &[Panel], active: &Panel, _floating: bool) {
let header = ui.max_rect();
let rect = egui::Rect::from_center_size(
egui::pos2(header.right() - CLOSE_BUTTON * 0.5 - 4.0, header.center().y),
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
);
if close_button(ui, *active, rect) {
self.close = Some(*active);
}
}
}
fn panel_limits(panel: &Panel) -> PanelLimits {
+3
View File
@@ -139,11 +139,13 @@
Clip Viewport Delimitar ventana gráfica
Clipboard Portapapeles
Close Cerrar
Close {panel} Cerrar {panel}
Close All Cerrar todo
Close All Other Drawings Cerrar todos los demás dibujos
Close Array Editing Cerrar la edición de matriz
Close Comparison Cerrar comparación
Export Comparison Exportar comparación
Close panel Cerrar panel
Closed Cerrada
Coincident Coincidente
Collapse Palettes Contraer paletas
@@ -542,6 +544,7 @@
Measure Medir
Measure Distance Medir distancia
Measure Geometry Medir geometría
Menu Bar Barra de menús
Merge Cells Combinar celdas
Merged PRs PR integradas
Mid Between 2 Points Punto medio entre 2 puntos
1 # CADCraft Spanish interface catalog — original translations.
139
140
141
142
143
144
145
146
147
148
149
150
151
544
545
546
547
548
549
550
+1
View File
@@ -146,6 +146,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet<String> {
"chrome",
"cmdline",
"credits",
"docking",
"dialogs",
"hatchdlg",
"aliasdlg",
+3
View File
@@ -143,11 +143,13 @@
Xref Clip Frame Рамка обрізки зовнішнього посилання
Clipboard Буфер обміну
Close Закрити
Close {panel} Закрити {panel}
Close All Закрити всі
Close All Other Drawings Закрити всі інші креслення
Closed Замкнений
Close Comparison Закрити порівняння
Export Comparison Експортувати порівняння
Close panel Закрити панель
Coincident Збіг
Collapse Palettes Згорнути палітри
Collapse Tool Sets Згорнути набори інструментів
@@ -534,6 +536,7 @@
Measure Розмітити
Measure Distance Виміряти відстань
Measure Geometry Виміряти геометрію
Menu Bar Рядок меню
Merge Cells Об'єднати комірки
Merged PRs Об'єднані PR
Mid Between 2 Points Середина між 2 точками
1 # CADCraft Ukrainian interface catalog — original translations by @dmatviichuk.
143
144
145
146
147
148
149
150
151
152
153
154
155
536
537
538
539
540
541
542
+1
View File
@@ -928,6 +928,7 @@
Time 时间
To get started, create or open a drawing. 若要开始,请创建或打开一个图形。
Tool Bar 工具栏
Menu Bar 菜单栏
Tool Sets 工具集
Tools 工具
Torus 圆环体
1 # CADCraft Simplified Chinese interface catalog — original translations.
928
929
930
931
932
933
934
+85 -1
View File
@@ -283,6 +283,9 @@ pub struct CadApp {
pub system_animations: Option<bool>,
/// What `ui.system_cursor` goes back to when the interface is reset ([`Self::set_system_cursor_default`]).
pub system_cursor_default: bool,
/// Whether the host has a native menu bar: off where the menus stay in the window
/// ([`Self::set_native_menus`]).
pub native_menus: bool,
pub session: Session,
pub ui: UiState,
/// The interface's own preferences from the Options dialog ([`options`]).
@@ -381,6 +384,7 @@ impl CadApp {
system_languages: Vec::new(),
system_animations: None,
system_cursor_default: false,
native_menus: cfg!(target_os = "macos"),
session,
ui: UiState::default(),
options: options::UiOptions::default(),
@@ -588,7 +592,11 @@ impl CadApp {
if let Some(r) = menus::run_ui_command(self, id, &params) {
return r;
}
// The bars as the interface shows them now (a `ui.set` may have just changed one), and any
// MENUBAR or TOOLBAR request applied at once.
self.sync_bars();
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
self.sync_bars();
if let Ok(v) = &r
&& let Some(m) = v.get("message").and_then(Value::as_str)
{
@@ -607,6 +615,7 @@ impl CadApp {
if menus::run_ui_command(self, name, &Value::Null).is_some() {
return;
}
self.sync_bars();
if let Err(e) = self.session.start(name) {
self.session.echo(e.to_string());
}
@@ -622,6 +631,7 @@ impl CadApp {
/// command or system variable) runs `fallback` instead: Enter on a partly typed name accepts
/// the highlighted AutoComplete suggestion.
pub fn cmdline_or(&mut self, text: &str, fallback: Option<&str>) -> Option<String> {
self.sync_bars();
if !self.session.prompting() {
let first = text.split_whitespace().next().unwrap_or("");
// `cmd {json}` is a programmatic call: the engine runs it with those parameters.
@@ -636,7 +646,9 @@ impl CadApp {
return None;
}
}
let e = match (self.session.cmdline(text), fallback) {
let r = self.session.cmdline(text);
self.sync_bars();
let e = match (r, fallback) {
(Ok(()), _) => return None,
(Err(cadcraft_engine::EngineError::UnknownCommand(_)), Some(f)) => return self.cmdline(f),
(Err(e), _) => e.to_string(),
@@ -645,6 +657,18 @@ impl CadApp {
Some(e)
}
/// Apply a menu bar / tool bar change MENUBAR or TOOLBAR asked for, and report the bars shown.
fn sync_bars(&mut self) {
let b = std::mem::take(&mut self.session.bars_request);
if let Some(on) = b.menubar {
self.ui.in_window_menu = on;
}
if let Some(show) = b.toolbar {
self.ui.show_toolbar = show;
}
self.session.bars_shown = cadcraft_engine::cmd::interface::InterfaceBars { menubar: self.ui.in_window_menu, toolbar: self.ui.show_toolbar };
}
/// The theme the interface shows now (the choice resolved against the OS appearance).
pub fn shown_theme(&self) -> egui::Theme {
self.shown_theme.unwrap_or_else(|| self.ui.theme.resolve(None))
@@ -731,6 +755,15 @@ impl CadApp {
}
}
/// Tell the interface whether the host has a native menu bar. Where it has none, the
/// in-window menu is the only menu, so it is shown and a reset keeps it.
pub fn set_native_menus(&mut self, on: bool) {
self.native_menus = on;
if !on {
self.ui.in_window_menu = true;
}
}
pub fn set_status(&mut self, s: impl Into<String>) {
self.status = Some((s.into(), now_ms()));
}
@@ -1087,6 +1120,7 @@ impl CadApp {
/// Draw one UI pass: title/toolbar, optional menu/status bar/file tabs, the standalone tool-set strip when a drawing is shown but Tool Sets is not docked, docking or the start page, and the floating overlays; record `frame_ms`. Runs on every pass, including one egui later discards.
fn draw(&mut self, ui: &mut egui::Ui) {
let t0 = now_ms();
self.sync_bars();
control::begin_frame(ui.ctx());
let t = theme::Tokens::get();
chrome::title_and_toolbar(self, ui);
@@ -1408,4 +1442,54 @@ mod tests {
let ui: UiState = serde_json::from_value(json!({ "saveFormat": "dwg" })).unwrap_or_default();
assert_eq!(ui.save_format, SaveFormat::Dwg);
}
#[test]
fn options_reset_brings_the_interface_back() {
// Hiding the interface (View/Window toggles) can leave no way back — on Windows the
// in-window menu bar is the only menu there is. Options > Reset must restore it (#1240).
let mut a = app();
a.run("ui.toggle.toolbar", json!({ "on": false })).unwrap();
a.run("ui.toggle.menubar", json!({ "on": cfg!(target_os = "macos") })).unwrap();
a.start("ui.hidepalettes");
assert!(!a.ui.show_toolbar && !a.ui.show_palettes && !a.ui.show_toolsets);
assert_eq!(a.ui.in_window_menu, cfg!(target_os = "macos"), "the test did not hide the menu bar");
a.run("options", json!({ "reset": true })).unwrap();
assert!(a.ui.show_toolbar, "the tool bar is still hidden");
assert!(a.ui.show_palettes, "the palettes are still hidden");
assert!(a.ui.show_toolsets);
assert_eq!(a.ui.in_window_menu, !cfg!(target_os = "macos"), "the menu bar did not come back");
}
#[test]
fn options_reset_keeps_the_menu_where_the_host_has_no_native_one() {
// With CADCRAFT_NO_NATIVE_MENU=1 the menus stay in the window: the host reports no native
// menu bar, so the in-window one is the only menu and the reset must leave it (#1240).
let mut a = app();
a.set_native_menus(false);
assert!(a.ui.in_window_menu, "the host's setting did not show the in-window menu");
a.run("ui.toggle.menubar", json!({ "on": false })).unwrap();
a.run("options", json!({ "reset": true })).unwrap();
assert!(a.ui.in_window_menu, "the only menu bar did not come back");
// Beside a native menu bar, the reset returns to the platform default.
a.set_native_menus(true);
a.run("ui.toggle.menubar", json!({ "on": true })).unwrap();
a.run("options", json!({ "reset": true })).unwrap();
assert!(!a.ui.in_window_menu, "the in-window menu is not the default beside a native one");
}
#[test]
fn options_reset_keeps_the_users_shortcuts_and_folders() {
// The reset brings hidden bars back (#1240); it must not also lose the user's own
// keyboard shortcuts or the folders the file pickers remember.
let mut a = app();
a.ui.shortcuts.insert("line".into(), "Ctrl+Shift+L".into());
a.ui.last_lisp_dir = Some("lisp-folder".into());
a.ui.last_pgp_dir = Some("pgp-folder".into());
a.run("ui.toggle.toolbar", json!({ "on": false })).unwrap();
a.run("options", json!({ "reset": true })).unwrap();
assert!(a.ui.show_toolbar, "the tool bar is still hidden");
assert_eq!(a.ui.shortcuts.get("line").map(String::as_str), Some("Ctrl+Shift+L"), "the reset lost a user shortcut");
assert_eq!(a.ui.last_lisp_dir.as_deref(), Some("lisp-folder"));
assert_eq!(a.ui.last_pgp_dir.as_deref(), Some("pgp-folder"));
}
}
+9 -2
View File
@@ -797,13 +797,20 @@ fn switch_on_hover(ctx: &egui::Context, titles: &[egui::Response]) {
}
}
/// Activate a menu command. QuickCalc toggles transparently; other items clear pending
/// command-line text and start their command interactively.
/// Activate a menu command. QuickCalc toggles transparently, and Reference Manager closes its
/// palette when it is open (typed XREF only opens it); other items clear pending command-line
/// text and start their command interactively.
pub fn activate(app: &mut CadApp, id: &str) {
if id == "ui.toggle.quickcalc" {
run_transparent(app, id);
return;
}
if id == "xref" && app.ui.docking.layout.contains(&crate::docking::Panel::ExternalRefs) {
if let Err(e) = crate::xrefs::close_palette(app) {
app.set_status(e);
}
return;
}
app.cmd.buffer.clear();
app.start(id);
}
+28 -14
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` | 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 |
//! | `timeSensitiveRightClick` | while a command runs, a quick right-click is Enter and holding the button opens the shortcut menu (default); `false`: `rightClickCommand` decides |
//! | `rightClickDuration` | how long the right button is held to open the menu while a command runs, 100–2000 ms (250) |
//! | `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) |
//! | `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) |
//! | `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,16 +139,13 @@ pub struct UiOptions {
pub snap_marker_size: f32,
/// The selection highlight colour; `None` keeps the theme's.
pub selection_color: Option<Color32>,
/// 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.
/// 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.
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), with the time-sensitive right-click off.
/// (Edit mode).
pub right_click_default: IdleClick,
pub right_click_edit: IdleClick,
/// A right-click while a command runs, with the time-sensitive right-click off.
@@ -437,13 +434,30 @@ fn apply_right_click(o: &mut UiOptions, c: &UiChanges) {
/// The interface preferences back to their defaults (the interface language stays).
fn reset_ui(app: &mut CadApp) {
let d = crate::UiState::default();
app.ui.theme = d.theme;
app.ui.animations = d.animations;
app.ui.save_format = d.save_format;
app.ui.save_version = d.save_version;
// Everything interface, back to its defaults: a hidden menu bar, tool bar, palettes or
// panels and a rearranged panel layout come back — once the menu bar is hidden there may be
// no other way to reach the toggles (#1240). The interface language stays; the open dialog,
// the start tab, the recent files and the remembered folders are state, not preferences, and
// stay too. The user's keyboard shortcuts are their own customisation, which Window > Reset
// Palettes keeps as well: a reset meant to bring a bar back must not lose them.
let (language, dialog, start_tab) = (app.ui.interface_language, app.ui.dialog.take(), app.ui.start_tab);
let recent_files = std::mem::take(&mut app.ui.recent_files);
let shortcuts = std::mem::take(&mut app.ui.shortcuts);
let (last_lisp_dir, last_pgp_dir) = (app.ui.last_lisp_dir.take(), app.ui.last_pgp_dir.take());
app.ui = crate::UiState {
interface_language: language,
dialog,
start_tab,
recent_files,
shortcuts,
last_lisp_dir,
last_pgp_dir,
..Default::default()
};
// Where the host has no native menu bar the in-window one is the only menu: the reset must
// leave it in place (#1240).
app.ui.in_window_menu = !app.native_menus;
app.ui.system_cursor = app.system_cursor_default;
app.ui.history_lines = d.history_lines;
app.options = UiOptions::default();
}
+14 -26
View File
@@ -615,35 +615,23 @@ 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);
// 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()));
}
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| {
+6
View File
@@ -42,6 +42,12 @@ fn open_palette(app: &mut CadApp) -> Result<Value, String> {
crate::docking::command(app, false, &json!({ "operation": "open", "panel": Panel::ExternalRefs.id() }))
}
/// Close the palette: Window ▸ Reference Manager while it is open, as Window ▸ QuickCalc closes
/// QuickCalc (#2273).
pub(crate) fn close_palette(app: &mut CadApp) -> Result<Value, String> {
crate::docking::command(app, false, &json!({ "operation": "close", "panel": Panel::ExternalRefs.id() }))
}
/// A picked file inside the host drawing's folder is attached by its relative path, so the
/// project folder can move.
fn relative_to_host(app: &CadApp, picked: &str) -> String {
-38
View File
@@ -240,42 +240,4 @@ 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());
}
+60 -1
View File
@@ -123,7 +123,7 @@ fn palette_icons_are_painted_in_code_and_shown_in_an_iconic_column() {
let ctx = egui::Context::default();
let mut paint = |panel: Panel| {
let mut painted = false;
let mut content = Panels { app: &mut app };
let mut content = Panels { app: &mut app, close: None };
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.ctx().layer_painter(egui::LayerId::background());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(20.0, 20.0));
@@ -593,3 +593,62 @@ fn group_drag_bar_moves_the_whole_group_into_the_other_dock() {
assert_eq!(frames(layout), [[Panel::Canvas]]);
assert_eq!(h.state().session.doc().unwrap(), &document);
}
/// Guard that every closable panel header offers a visible close button: a docked tab group,
/// the default accordion stack, and a floating group. Each click must remove the panel, the
/// button must not cover the title, and the tab context menu must still close the same panel.
#[test]
fn every_panel_header_has_a_close_button_that_closes_like_the_context_menu() {
let mut h = harness(None, 1280.0, 1.0);
assert!(h.query_by_label("Close Tool Sets").is_some(), "docked tab headers show a close button");
assert!(h.query_by_label("Close Drawing").is_none(), "the drawing view is not a closable panel");
// External References opens as a tabbed pane; its button sits beside the title, not over it.
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"externalReferences"})).unwrap();
h.run_steps(4);
assert!(h.state().ui.docking.layout.contains(&Panel::ExternalRefs));
let close = h.get_by_label("Close External References").rect();
let title = h.get_by_role_and_label(egui::accesskit::Role::Tab, "External References").rect();
assert!(!close.intersects(title), "the close button does not cover the panel title");
h.get_by_label("Close External References").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::ExternalRefs));
// Accordion headers (the default Layers/Properties stack) get one too.
assert!(h.state().ui.docking.layout.contains(&Panel::Layers));
h.get_by_label("Close Layers").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::Layers));
// The context menu still closes the same panel after it is reopened.
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"layers"})).unwrap();
h.run_steps(4);
assert!(h.state().ui.docking.layout.contains(&Panel::Layers));
h.get_by_role_and_label(egui::accesskit::Role::Tab, "Layers").click_button(PointerButton::Secondary);
h.run_steps(3);
// The docking surface's stock tab menu item ("Close Panel"), not our tooltip.
h.get_by_label("Close Panel").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::Layers));
// Floating panels get the same button in their group header.
h.state_mut().run("ui.dock", json!({"operation":"float","panel":"properties","rect":[400,250,300,350]})).unwrap();
h.run_steps(4);
h.get_by_label("Close Properties").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::Properties));
}
/// The accessible name is one translated string, not an English verb glued to a translated
/// panel label: Spanish readers must hear "Cerrar Capas", never "Close Capas".
#[test]
fn spanish_close_button_accessible_name_is_localized_as_a_whole() {
let mut h = harness(None, 1280.0, 1.0);
h.state_mut().run("ui.language", json!({"lang": "es"})).unwrap();
h.run_steps(4);
assert!(h.query_by_label("Cerrar Capas").is_some(), "the accordion close button is named in Spanish");
assert!(h.query_by_label("Cerrar Propiedades").is_some(), "every panel's close button follows the language");
assert!(h.query_by_label("Close Capas").is_none(), "no English verb survives the translation");
h.get_by_label("Cerrar Capas").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::Layers), "the localized name still closes its panel");
}
-4
View File
@@ -21,7 +21,6 @@ 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;
@@ -30,7 +29,6 @@ mod options_dialog;
mod options_right_click;
mod parameters_rename;
mod pickdrag;
mod press_first_clicks;
mod properties_described;
mod properties_units;
mod rapid_clicks;
@@ -38,8 +36,6 @@ 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
@@ -1,183 +0,0 @@
//! 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");
}
+19
View File
@@ -252,3 +252,22 @@ fn selection_highlight_settings_set_save_and_show_in_the_selection_tab() {
assert!(text.contains(label), "{label} missing from:\n{text}");
}
}
#[test]
fn reset_brings_back_hidden_menu_bar_toolbar_and_status_bar() {
// #1240: with the in-window menu bar, the toolbar and the status bar hidden, OPTIONS ▸ Reset
// to Defaults (typed, or from the right-click menu) is the way back.
let mut a = app();
let d = cadcraft_ui_egui::UiState::default();
a.ui.in_window_menu = !d.in_window_menu;
a.ui.show_toolbar = false;
a.ui.show_status_bar = false;
a.ui.show_command_line = false;
a.ui.show_palettes = false;
a.run("options", json!({"reset": true})).unwrap();
assert_eq!(a.ui.in_window_menu, d.in_window_menu);
assert_eq!(a.ui.show_toolbar, d.show_toolbar);
assert_eq!(a.ui.show_status_bar, d.show_status_bar);
assert_eq!(a.ui.show_command_line, d.show_command_line);
assert_eq!(a.ui.show_palettes, d.show_palettes);
}
+5 -28
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!({"timeSensitiveRightClick": false, "rightClickDefault": "repeat"})).unwrap();
a.run("options", json!({"rightClickDefault": "repeat"})).unwrap();
a.cmdline("circle 0,0 5");
assert!(!a.session.prompting());
let ctx = egui::Context::default();
@@ -116,22 +116,6 @@ 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();
@@ -198,17 +182,6 @@ 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();
@@ -217,6 +190,10 @@ 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);
+7 -5
View File
@@ -83,11 +83,13 @@ 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());
// 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);
// 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);
assert!(h.state().session.pending_window.is_none());
assert_eq!(h.state().session.selection().len(), 1);
}
@@ -1,189 +0,0 @@
//! 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");
}
+2 -3
View File
@@ -88,12 +88,11 @@ 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 point is
// where the button went down (#1001), not where the hand got to.
// The hand is already on its way to the next point when the button comes up.
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(down), 1e-4), "{got:?}");
assert!(got[0].1.near(h.state().canvas.xf.unwrap().to_world(up), 1e-4), "{got:?}");
}
-159
View File
@@ -1,159 +0,0 @@
//! 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}");
}
@@ -1,59 +0,0 @@
//! 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");
}
+107
View File
@@ -0,0 +1,107 @@
//! MENUBAR and TOOLBAR at the command line bring a hidden menu bar and tool bar back (#1341):
//! on Windows and Linux the in-window menu bar is the only menu, so with it hidden typing these
//! is the way back, as in AutoCAD.
use cadcraft_engine::Session;
use cadcraft_ui_egui::{CadApp, Services};
use serde_json::json;
fn app() -> CadApp {
CadApp::new(Session::new(), Services::default())
}
#[test]
fn typed_menubar_shows_and_hides_the_menu_bar() {
let mut app = app();
app.ui.in_window_menu = false;
app.cmdline("MENUBAR");
assert_eq!(app.session.prompt_text(), "MENUBAR Enter new value for MENUBAR <0>:");
app.cmdline("1");
assert!(app.session.running.is_none());
assert!(app.ui.in_window_menu);
// 0 hides it again; anything else is refused and asked again.
app.cmdline("MENUBAR");
app.cmdline("2");
assert!(app.session.running.is_some(), "still asking");
app.cmdline("0");
assert!(!app.ui.in_window_menu);
}
#[test]
fn typed_toolbar_shows_the_tool_bar_by_default() {
let mut app = app();
app.ui.show_toolbar = false;
app.cmdline("TOOLBAR");
assert_eq!(app.session.prompt_text(), "TOOLBAR Enter tool bar option or [Show/Hide] <Show>:");
app.cmdline("");
assert!(app.ui.show_toolbar);
app.cmdline("TOOLBAR");
app.cmdline("H");
assert!(!app.ui.show_toolbar);
}
#[test]
fn the_json_forms_report_and_set_the_bars() {
let mut app = app();
app.ui.in_window_menu = true;
app.ui.show_toolbar = false;
app.cmdline("MENUBAR");
app.cmdline("");
assert_eq!(app.session.execute("menubar", &json!({})).unwrap(), json!({ "value": 1 }));
assert_eq!(app.session.execute("toolbar", &json!({})).unwrap(), json!({ "show": false }));
app.session.execute("toolbar", &json!({ "show": true })).unwrap();
app.cmdline("MENUBAR");
app.cmdline("");
assert!(app.ui.show_toolbar && app.ui.in_window_menu);
assert!(app.session.execute("menubar", &json!({ "value": 3 })).is_err());
}
/// MENUBAR changes only the menu bar: a tool bar change made before the request is applied
/// stays (a control-API `ui.set` can come between them).
#[test]
fn menubar_leaves_a_later_tool_bar_change() {
let mut app = app();
app.ui.in_window_menu = true;
app.ui.show_toolbar = true;
app.session.execute("menubar", &json!({ "value": 0 })).unwrap();
app.ui.show_toolbar = false;
app.cmdline("'REDRAW");
assert!(!app.ui.in_window_menu, "MENUBAR applied");
assert!(!app.ui.show_toolbar, "the tool bar keeps its later change");
}
/// A bar query through `CadApp::run` reports the bars as the interface shows them now, even when
/// a UI change came just before it with no frame drawn in between.
#[test]
fn a_bar_query_sees_a_ui_change_just_made() {
let mut app = app();
app.ui.show_toolbar = true;
assert_eq!(app.run("toolbar", json!({})).unwrap(), json!({ "show": true }));
app.ui.show_toolbar = false;
assert_eq!(app.run("toolbar", json!({})).unwrap(), json!({ "show": false }));
app.run("toolbar", json!({ "show": true })).unwrap();
assert!(app.ui.show_toolbar, "the request is applied at once");
}
#[test]
fn menubar_started_from_the_ui_offers_the_bar_as_shown_now() {
let mut app = app();
app.ui.in_window_menu = true;
app.cmdline("");
app.ui.in_window_menu = false;
app.start("menubar");
let prompt = app.session.prompt_text();
assert!(prompt.contains("<0>"), "{prompt}");
}
#[test]
fn enter_through_the_control_api_applies_the_bar_before_the_next_request() {
let mut app = app();
let ctx = egui::Context::default();
app.ui.show_toolbar = false;
app.start("toolbar");
let (req, _pending) = cadcraft_ui_egui::control::ControlRequest::new("cmdline.key", serde_json::json!({ "key": "enter" }));
cadcraft_ui_egui::control::handle(&mut app, &ctx, &req);
assert!(app.session.running.is_none());
assert!(app.ui.show_toolbar, "TOOLBAR's default Show is applied before the next request");
}
+18 -1
View File
@@ -5,7 +5,7 @@ use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use cadcraft_engine::doc::geom::Vec3;
use cadcraft_engine::doc::{Drawing, Entity, EntityKind, Handle, Layer, Line, XrefStatus};
use cadcraft_ui_egui::{CadApp, Services, docking::Panel};
use cadcraft_ui_egui::{CadApp, Services, docking::Panel, menus};
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
@@ -71,6 +71,23 @@ fn xref_opens_the_palette_and_its_buttons_manage_the_xref() {
h.get_by_label("site");
}
/// Window ▸ Reference Manager closes the palette when it is open, like Window ▸ QuickCalc; typed,
/// XREF only ever opens it (#2273).
#[test]
fn the_window_menu_item_closes_an_open_palette() {
let mut app = CadApp::new(Session::default(), Services::default());
let open = |app: &CadApp| app.ui.docking.layout.contains(&Panel::ExternalRefs);
menus::activate(&mut app, "xref");
assert!(open(&app), "the menu item opens the palette");
menus::activate(&mut app, "xref");
assert!(!open(&app), "the menu item closes the open palette");
menus::activate(&mut app, "xref");
assert!(open(&app), "and opens it again");
assert!(app.cmdline("XREF").is_none());
assert!(app.cmdline("XR").is_none());
assert!(open(&app), "typed XREF keeps it open");
}
#[test]
fn json_xref_lists_and_never_opens_the_palette() {
let mut app = CadApp::new(Session::default(), Services::default());
+6
View File
@@ -144,6 +144,12 @@ The shortcut also works with text-field focus. Toggling preserves the running dr
and pending command-line input. The expression, history and calculator variables survive
closing/reopening within the same session; they are not saved across application restarts.
The External References palette (`externalReferences`) is not part of the default arrangement
either. Typed `XREF`/`XR` opens and activates it. **Window > Reference Manager** (also
`ui.menu.invoke` with `xref`) opens it too, but closes it when it is present, as Window >
QuickCalc does; closing leaves the running command and command-line input alone. `xref` with
JSON parameters lists the references and never opens or closes the palette.
Invoke these UI commands through `engine.execute`, for example `{"command":"ui.dock","params":{"operation":"float","panel":"layers","rect":[100,100,320,440]}}`.
Advanced `ui.dock` operations use the same validated transaction as pointer gestures: