Merge pull request #8667 from storytold/train/carry7668

Shortcuts: add Switch Selection Tools (#7668)
This commit is contained in:
BFlat
2026-11-19 15:21:47 +07:00
committed by GitHub
7 changed files with 261 additions and 2 deletions
+6
View File
@@ -930,6 +930,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"Cmd+~",
"{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool), keeping the active tool when it is that tool; choosing Magic Wand, Lasso or any other tool does not change which one it chooses → {tool}. Default shortcut Ctrl+` on Windows and Linux, none on macOS, where Cmd+` switches windows",
),
(
"tool.switchSelectionTools",
"Switch Selection Tools",
"",
"{} choose Direct Selection while Selection is active, otherwise choose Selection; this is a persistent explicit tool choice, as selecting the tool from the toolbar, and can be assigned a key in Keyboard Shortcuts with no default key. Normal tool deactivation finishes pending work; returns the actual active {tool}",
),
(
"tool.setOption",
"Tool Option",
+4
View File
@@ -716,6 +716,10 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
let switched = if app.session.tool_id() == id { Ok(()) } else { app.try_select_tool(id) };
switched.map(|()| json!({"tool": app.session.tool_id()}))
}
"tool.switchSelectionTools" => {
let tool = if app.session.tool_id() == "selection" { "directSelection" } else { "selection" };
app.try_select_tool(tool).map(|()| json!({"tool": app.session.tool_id()}))
}
crate::touch::TOGGLE_MODE => crate::touch::toggle_mode(app),
crate::addons::pathtools::corner::COMMAND => crate::addons::pathtools::corner::open(app),
crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app),
+39
View File
@@ -1706,3 +1706,42 @@ fn window_menu_panels_are_sorted_alphabetically_in_active_language() {
set_current(prev);
}
/// A command reports the same failed valid tool choice as `tool.select`, rather than success
/// with the old tool. The existing failure hook exercises the activation error boundary.
#[test]
fn selection_tools_toggle_propagates_a_failed_valid_choice() {
let failure = "selection tool choice failed";
let mut failures = Vec::new();
for (from, to) in [("selection", "directSelection"), ("directSelection", "selection")] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
assert!(vectorcraft_tools::tool_info(from).is_some() && vectorcraft_tools::tool_info(to).is_some());
app.run("tool.select", json!({"tool": from})).unwrap();
// The real successful command chooses the other valid selection tool.
assert_eq!(app.run("tool.switchSelectionTools", json!({})).unwrap(), json!({"tool": to}));
app.run("tool.select", json!({"tool": from})).unwrap();
app.ui.touch_drawing_tool = Some("paintbrush".into());
let snapshot = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
(serde_json::to_value(st.doc.as_ref()).unwrap(), st.selection.clone(), st.history.undo.len(), st.history.redo.len())
};
let before = snapshot(&app);
let groups = app.ui.group_tool.clone();
let drawing = app.ui.touch_drawing_tool.clone();
app.fail_next_tool_choice = Some(failure.into());
let result = app.run("tool.switchSelectionTools", json!({}));
assert!(app.fail_next_tool_choice.is_none(), "the valid activation consumed the failure hook");
assert_eq!(app.session.tool_id(), from, "a failed choice keeps the current tool");
assert_eq!(snapshot(&app), before, "failed choice preserves document, selection and history");
assert_eq!(app.ui.group_tool, groups, "failed choice does not remember the requested tool");
assert_eq!(app.ui.touch_drawing_tool, drawing);
// The hook is one-shot: ordinary success and the return direction still work afterwards.
assert_eq!(app.run("tool.switchSelectionTools", json!({})).unwrap(), json!({"tool": to}));
assert_eq!(app.run("tool.switchSelectionTools", json!({})).unwrap(), json!({"tool": from}));
assert_eq!(snapshot(&app), before, "successful selection toggles do not edit the artwork");
failures.push(result);
}
assert_eq!(failures, vec![Err(failure.to_string()), Err(failure.to_string())], "both failed valid choices must reach the command caller");
}
+6
View File
@@ -931,6 +931,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"Cmd+~",
"{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool), keeping the active tool when it is that tool; choosing Magic Wand, Lasso or any other tool does not change which one it chooses → {tool}. Default shortcut Ctrl+` on Windows and Linux, none on macOS, where Cmd+` switches windows",
),
(
"tool.switchSelectionTools",
"Switch Selection Tools",
"",
"{} choose Direct Selection while Selection is active, otherwise choose Selection; this is a persistent explicit tool choice, as selecting the tool from the toolbar, and can be assigned a key in Keyboard Shortcuts with no default key. Normal tool deactivation finishes pending work; returns the actual active {tool}",
),
(
"tool.setOption",
"Tool Option",
@@ -0,0 +1,200 @@
//! User-configurable persistent Selection / Direct Selection switching.
// Tests may unwrap/panic (AGENTS.md, Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::{Mutex, MutexGuard};
use egui::{Event, Key, Modifiers};
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_engine::Session;
use vectorcraft_geom::PathData;
use vectorcraft_ui_egui::{UiState, VectorcraftApp, i18n, shortcut_editor, shortcuts};
const SWITCH: &str = "tool.switchSelectionTools";
static CASE: Mutex<()> = Mutex::new(());
// Integration binaries use process-wide locale/keymap mirrors. Every case owns the guard,
// starts from the same neutral keymap, and restores that keymap even if an assertion fails.
struct Globals {
_lock: MutexGuard<'static, ()>,
language: i18n::Lang,
neutral: UiState,
}
impl Globals {
fn new() -> Self {
let lock = CASE.lock().unwrap_or_else(|e| e.into_inner());
let language = i18n::current();
let neutral = UiState::default();
i18n::set_current(i18n::Lang::EN);
shortcut_editor::sync(&neutral);
Self { _lock: lock, language, neutral }
}
}
impl Drop for Globals {
fn drop(&mut self) {
shortcut_editor::sync(&self.neutral);
i18n::set_current(self.language);
}
}
fn app() -> (VectorcraftApp, NodeId) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300, "profile": null})).unwrap();
let shape = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap();
let id = NodeId(shape["id"].as_u64().unwrap());
app.select_tool("selection");
shortcut_editor::sync(&app.ui);
(app, id)
}
fn path_state(app: &VectorcraftApp, id: NodeId) -> (PathData, Vec<NodeId>, usize) {
let state = app.session.doc().unwrap();
(state.doc.node(id).unwrap().path_data().unwrap().clone(), state.selection.objects.clone(), state.history.undo.len())
}
struct Keyboard {
ctx: egui::Context,
time: f64,
}
impl Keyboard {
fn new() -> Self {
Self { ctx: egui::Context::default(), time: 0.0 }
}
fn frame(&mut self, app: &mut VectorcraftApp, events: Vec<Event>) {
self.time += 0.05;
let mut out = self.ctx.run_ui(
egui::RawInput {
events,
time: Some(self.time),
focused: true,
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))),
..Default::default()
},
|ui| {
app.logic(ui.ctx());
shortcuts::handle(app, ui.ctx());
},
);
out.textures_delta.clear();
}
fn key(&mut self, app: &mut VectorcraftApp, key: Key, pressed: bool, modifiers: Modifiers) {
let mut events = vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }];
// Plain letter shortcuts read the text the native host pairs with the key press.
// Modified command chords and releases produce no text.
if pressed && modifiers == Modifiers::NONE {
match key {
Key::V => events.push(Event::Text("v".into())),
Key::A => events.push(Event::Text("a".into())),
_ => {}
}
}
self.frame(app, events);
}
fn tap(&mut self, app: &mut VectorcraftApp, key: Key, modifiers: Modifiers) {
self.key(app, key, true, modifiers);
self.key(app, key, false, modifiers);
self.frame(app, vec![Event::ModifiersChanged(Modifiers::NONE)]);
}
}
fn control() -> Modifiers {
// Physical Control is the requested chord. On Windows/Linux egui also calls it command.
Modifiers { ctrl: true, command: !cfg!(target_os = "macos"), ..Modifiers::NONE }
}
fn configure_control_backtick(app: &mut VectorcraftApp) {
// Main assigns this chord to Select Last Selection Tool. Free that binding explicitly,
// as a user does in Keyboard Shortcuts, before assigning the configurable toggle.
app.run("shortcuts.set", json!({"id": "tool.selectLastSelection", "shortcut": ""})).unwrap();
app.run("shortcuts.set", json!({"id": SWITCH, "shortcut": "Ctrl+~"})).unwrap();
}
#[test]
fn selection_tools_existing_v_and_a_defaults_keep_their_choices() {
let _globals = Globals::new();
let (mut app, id) = app();
let before = path_state(&app, id);
app.select_tool("pen");
let mut keys = Keyboard::new();
keys.tap(&mut app, Key::V, Modifiers::NONE);
assert_eq!(app.session.tool_id(), "selection");
keys.tap(&mut app, Key::A, Modifiers::NONE);
assert_eq!(app.session.tool_id(), "directSelection");
assert_eq!(path_state(&app, id), before);
}
#[test]
fn selection_tools_configured_control_backtick_toggles_both_arrows() {
let _globals = Globals::new();
let (mut app, id) = app();
let before = path_state(&app, id);
let rows = app.run("shortcuts.list", json!({"query": SWITCH})).unwrap();
let rows = rows.as_array().unwrap();
assert_eq!(rows.len(), 1, "the configurable command is missing: {rows:?}");
assert_eq!(rows[0]["id"], SWITCH);
assert_eq!(rows[0]["label"], "Switch Selection Tools");
assert!(rows[0]["default"].is_null());
assert!(rows[0]["shortcut"].is_null());
configure_control_backtick(&mut app);
let mut keys = Keyboard::new();
keys.tap(&mut app, Key::Backtick, control());
assert_eq!(app.session.tool_id(), "directSelection");
keys.tap(&mut app, Key::Backtick, control());
assert_eq!(app.session.tool_id(), "selection");
assert_eq!(path_state(&app, id), before, "idle tool choices preserve path, selection and history");
}
#[test]
fn selection_tools_saved_binding_runs_and_reset_removes_it() {
let _globals = Globals::new();
let (mut original, _) = app();
configure_control_backtick(&mut original);
let saved = serde_json::to_string(&original.ui).unwrap();
let (mut restored, id) = app();
restored.ui = serde_json::from_str::<UiState>(&saved).unwrap();
shortcut_editor::sync(&restored.ui);
let before = path_state(&restored, id);
let mut keys = Keyboard::new();
keys.tap(&mut restored, Key::Backtick, control());
assert_eq!(restored.session.tool_id(), "directSelection");
restored.run("shortcuts.set", json!({"id": SWITCH, "shortcut": null})).unwrap();
let rows = restored.run("shortcuts.list", json!({"query": SWITCH})).unwrap();
assert!(rows[0]["shortcut"].is_null());
assert_eq!(rows[0]["overridden"], false);
keys.tap(&mut restored, Key::Backtick, control());
assert_eq!(restored.session.tool_id(), "directSelection", "reset leaves this chord unbound");
assert_eq!(path_state(&restored, id), before);
}
#[test]
fn selection_tools_other_tools_enter_selection_and_explicit_choice_survives_release() {
let _globals = Globals::new();
let (mut app, id) = app();
let before = path_state(&app, id);
for third in ["pen", "groupSelection"] {
app.select_tool(third);
assert_eq!(app.run(SWITCH, json!({})).unwrap()["tool"], "selection");
assert_eq!(app.session.tool_id(), "selection");
assert_eq!(app.run(SWITCH, json!({})).unwrap()["tool"], "directSelection");
assert_eq!(app.session.tool_id(), "directSelection");
}
configure_control_backtick(&mut app);
app.select_tool("pen");
let mut keys = Keyboard::new();
keys.key(&mut app, Key::V, true, Modifiers::NONE);
assert_eq!(app.session.tool_id(), "selection");
keys.tap(&mut app, Key::Backtick, control());
assert_eq!(app.session.tool_id(), "directSelection");
// Keep V down longer than the existing 0.25s temporary-tool threshold. Without clearing
// the held choice, its release would restore Pen instead of respecting this command.
for _ in 0..6 {
keys.frame(&mut app, vec![]);
}
keys.key(&mut app, Key::V, false, Modifiers::NONE);
assert_eq!(app.session.tool_id(), "directSelection");
assert_eq!(path_state(&app, id), before);
}
+2 -1
View File
@@ -6,7 +6,7 @@
> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged.
> Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged.
> Blend redraw update (#5179; previously: Keyboard Shortcuts: user-bindable Switch Selection Tools (#7645), with no default key; scores and estimates unchanged): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged.
## Feature submission evidence
@@ -504,6 +504,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Implemented and tested (2026-11-15):** Swatches list rows and thumbnail cells have item context menus with Swatch Options…, Duplicate Swatch and Delete Swatch. Right-click selects the target without painting art; actions use that item's name and are disabled for reserved or missing swatches. All 39 Swatches tests pass, covering all five views, command dispatch, selection and Undo; the regression fails with the menu hooks removed. Rendered list and thumbnail menus were inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Other panels without context menus remain in G12; estimate unchanged.
- **Done (2026-11-14, #7645):** Edit › Keyboard Shortcuts lists Switch Selection Tools (`tool.switchSelectionTools`) with no default key. Selection goes to Direct Selection; Direct Selection and other tools go to Selection through the existing explicit tool-choice path. The choice remains after key release; V/A defaults and Touch mode are unchanged. Estimate unchanged.
- **Done (2026-11-14):** Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu with Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of the symbol), and Select All Instances, selecting the symbol if unselected. Estimate unchanged.
- **Done (2026-10-29, #4522):** the Pathfinder panel menu's Make, Release and Expand Compound Shape, which were dimmed placeholders, and the panel's Expand button act on live compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html)): Alt-clicking a Shape Mode makes one in that mode, a Shape Mode sets the mode of the members selected, and the compound shape draws, exports and saves as the area its members' modes make (`object.compoundShape.*`, `crates/engine/src/tests/compound_shape.rs`). Left: blends, envelopes and warps as members, clicks that hit the area rather than the members. Estimate unchanged.
- **Done (2026-10-25, #3426):** Pathfinder panel › Pathfinder Options… ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): Precision (0.001–10 pt; results are refit to within it and pieces thinner than it are dropped), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (pieces of objects with no fill), kept in the preferences (`object.pathfinder.options`, group `pathfinder`) and used by every Shape Mode and Pathfinder button and Repeat; the page gives no defaults, so ours (0.01 pt, both off) keep the earlier results byte for byte. Trap is left as it was. Estimate unchanged.
+4 -1
View File
@@ -158,7 +158,7 @@ forbids launching or measuring Illustrator, so there has been **no side-by-side
| Transform handles, bounding box, Free Transform | 80% | 5–8 | estimated |
| Nudging, numeric entry, precision, units | 85% | 3–5 | estimated |
| Modifier keys and temporary tools | 80% | 5–8 | estimated |
| Keyboard shortcuts (default set) | 70% | 6–10 | estimated |
| Keyboard shortcuts (default set) | 70% | 6–10 | estimated; optional Switch Selection Tools is user-bindable with no default key (#7645), so default-set coverage is unchanged |
| Cursors | 75% | 3–5 | estimated |
| Panels, Control bar, Properties, context menus | 70% | 15–25 | estimated |
| Look and feel (layout, theme, metrics) | 80% | 5–10 | measured once against public screenshots on 2026-10-02; panels added since not re-measured |
@@ -389,6 +389,8 @@ tools, never checked side by side) isn't captured row by row.
## Keyboard shortcuts
Switch Selection Tools (`tool.switchSelectionTools`, #7645) appears in Edit › Keyboard Shortcuts with no default key. Its assigned key chooses Direct Selection from Selection, and Selection from Direct Selection or another tool. This is the normal persistent explicit tool choice; V/A shortcuts and Touch mode stay unchanged.
Cmd/Ctrl+/ (`appearance.addFill`) and Cmd/Ctrl+Alt+/ (`appearance.addStroke`) add a new fill and a new stroke to the
selected objects, as the Appearance panel's Add New Fill and Add New Stroke buttons do.
@@ -617,6 +619,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra
| 2026-11-16 | minor | Eraser review (#6582): ordinary Group/Layer own paints and reproducible evaluated gradient placements are preserved as members are cut. Replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot reproduce the original appearance keep existing fitting. Scores and estimates unchanged. |
| 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. |
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
| 2026-11-14 | minor | Keyboard Shortcuts lists Switch Selection Tools (`tool.switchSelectionTools`, #7645), with no default key: Selection goes to Direct Selection, and other tools go to Selection through the normal explicit tool-choice path. Existing V/A and Touch behavior stay unchanged. Scores and estimates unchanged. |
| 2026-11-12 | minor | Floating panels: the app counts as inactive only once none of its windows has had focus for 0.25 s, so focus moving between its own windows (a press on a panel's bar) leaves the panels' OS windows at their level; with two floating panels, a press on one panel's bar no longer hands the keyboard to the other or leaves both behind the main window (#6986). `focus_moving_between_the_apps_windows_leaves_the_palettes_on_top`; scores and estimates unchanged. |
| 2026-11-14 | minor | Direct Selection: Space during an ordinary path's direction-handle drag moves its anchor and both handles; releasing Space resumes handle adjustment, and a Cmd/Ctrl loan preserves Pen continuation (#7237, request 3 only). Handle-hover labels remain open; scores and estimates unchanged. |
| 2026-11-12 | minor | Numeric fields: a focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326). Scores and estimates unchanged. |