M2: add localized menu access keys (#6596)

This commit is contained in:
yoriswind committed 2026-11-15 10:12:47 -08:00
1 parent 4dfb91fdc7
commit ba2654072b
6 files changed
+2017 -31

No files matched your search

+3 -1
View File
@@ -17,7 +17,9 @@ impl VectorcraftApp {
if self.fonts_ready {
tools_float::cancel_move_on_escape(self, ctx);
crate::custom_toolbars::cancel_move_on_escape(self, ctx);
shortcuts::handle(self, ctx);
if !crate::menus::handle_keyboard_input(self, ctx) {
shortcuts::handle(self, ctx);
}
}
// A Copy taken in this UI phase (an egui copy event, or a command it runs) is published in
// this same pass: waiting for the next `tick` can leave the command unissued when an idle
+4
View File
@@ -49,6 +49,7 @@ mod bar;
mod context;
mod entries;
mod invoke;
mod keyboard;
mod labels;
mod run;
mod slots;
@@ -71,6 +72,9 @@ pub(crate) use invoke::graph_dialog;
#[cfg(test)]
pub(crate) use invoke::with_held_keys;
pub use invoke::{click_target, invoke, invoke_from_system_menu};
pub(crate) use keyboard::handle_input as handle_keyboard_input;
// Shared numeric fields preserve their caret when a transient menu returns their focus.
pub(crate) use keyboard::restoring_field_focus;
pub(crate) use labels::lists_plugin;
pub(crate) use labels::shows_a_name;
pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings};
+106 -29
View File
@@ -1,33 +1,37 @@
use super::entries::{Row, entry, shown_shortcut};
use super::invoke::{field_event, focused_text_field, invoke, to_field, with_held_keys};
use super::keyboard::{self, AccessRow, SourcePath};
use super::tree::menu_tree_named;
use super::{Entry, Item, Tokens, Value, VectorcraftApp, widgets};
/// Render the menu bar.
/// The in-window menu bar. Returns where its titles end (x): the bar itself takes the full width.
pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 {
let t = Tokens::get(ui.ctx());
let ctx = ui.ctx().clone();
// The press that opens a menu takes the keyboard from a focused text field: the field and its
// selection are kept while the menus are open, so their Select All, Cut, Copy and Paste act on
// its text (#516), the frame after the click that chose them (that click takes the keyboard
// from it again).
type Field = (egui::Id, egui::text_edit::TextEditState);
let (field_key, chosen_key) = (egui::Id::unique("menu-bar-field"), egui::Id::unique("menu-bar-field-event"));
let chosen_key = egui::Id::unique("menu-bar-field-event").with(ctx.viewport_id());
if let Some(((field, state), e)) = ctx.data(|d| d.get_temp::<(Field, egui::Event)>(chosen_key)) {
ctx.data_mut(|d| d.remove::<(Field, egui::Event)>(chosen_key));
state.store(&ctx, field);
keyboard::restore_field(&ctx, field, state);
to_field(&ctx, field, e);
}
if let Some(field) = focused_text_field(&ctx).and_then(|id| Some((id, egui::TextEdit::load_state(&ctx, id)?))) {
ctx.data_mut(|d| d.insert_temp::<Field>(field_key, field));
}
let mut clicked: Option<(String, Value)> = None;
let mut file_open = false;
keyboard::remember_field(&ctx);
keyboard::begin_bar(&ctx);
let tree = menu_tree_named(app.session.prefs.font_names_in_english);
// No application menu in the window (as in Illustrator): the bar starts at File on every
// platform. The VectorCraft menu stays in the tree: the native Mac bar takes it from there.
let tree: Vec<(&str, Vec<Item>)> = tree.into_iter().filter(|(title, _)| *title != "VectorCraft").collect();
let root_rows = keyboard::root_rows(&tree);
let show_cues = keyboard::cues(&ctx);
// Only the bar temporarily sees no resting pointer while keyboard navigation owns it.
// Real movement/clicks keep normal pointer menus; restore before refresh/invoke/other UI.
let pointer = keyboard::suppress_stationary_hover(&ctx).then(|| ctx.input_mut(|i| std::mem::take(&mut i.pointer)));
let mut clicked: Option<(String, Value)> = None;
let mut file_open = false;
// A menu bar for its layout and menu-button style, but the titles use `Popup::menu` directly:
// egui 0.37's `MenuButton` opens the title under a resting pointer while another menu is open,
// and the app switches titles on movement only (`switch_on_hover`, the native behaviour).
@@ -35,9 +39,11 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 {
.ui(ui, |ui| {
let mut titles = Vec::with_capacity(tree.len());
for (title, items) in tree.iter() {
let text = egui::RichText::new(tl!(title)).size(13.0).color(t.text);
let resp = ui.add(egui::Button::new(text));
egui::Popup::menu(&resp).show(|ui| menu_body(app, ui, items, &mut clicked));
let cue = root_rows.iter().find(|r| r.label == crate::i18n::t(title)).and_then(|r| r.cue.as_ref()).filter(|_| show_cues);
let text = keyboard::text(ui, crate::i18n::t(title), "", cue, Some(13.0));
let resp = ui.push_id(("menu-bar-root", *title), |ui| ui.add(egui::Button::new(text))).inner;
keyboard::bind_root(&ctx, title, &resp);
egui::Popup::menu(&resp).show(|ui| bar_menu_body(app, ui, items, &keyboard::root_path(title), &mut clicked));
if *title == "File" {
file_open = egui::Popup::is_id_open(ui.ctx(), egui::Popup::default_response_id(&resp));
}
@@ -46,6 +52,10 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 {
(ui.cursor().min.x, switch_on_hover(ui.ctx(), &titles))
})
.inner;
if let Some(pointer) = pointer {
ctx.input_mut(|i| i.pointer = pointer);
}
keyboard::finish_bar(&ctx, open, clicked.is_some());
// The File menu opening reads the Scripts folder again, for File › Scripts.
let file_key = egui::Id::unique("menu-bar-file-open");
let file_was_open = ctx.data(|d| d.get_temp::<bool>(file_key)).unwrap_or(false);
@@ -57,9 +67,9 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 {
// while one is, or the menu would open under them.
ctx.data_mut(|d| d.insert_temp(menu_open_id(), open));
let field = ctx.data(|d| d.get_temp::<Field>(field_key));
if !open && focused_text_field(&ctx).is_none() {
ctx.data_mut(|d| d.remove::<Field>(field_key));
let field = keyboard::field(&ctx);
if !open && !keyboard::active(&ctx) && focused_text_field(&ctx).is_none() {
keyboard::forget_field(&ctx);
}
if let Some((id, p)) = clicked {
match field.and_then(|f| Some((f, field_event(app, &id)?))) {
@@ -122,10 +132,37 @@ pub(super) fn menu_body(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Item],
});
}
fn bar_menu_body(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Item], path: &SourcePath, clicked: &mut Option<(String, Value)>) {
if !keyboard::active(ui.ctx()) && !keyboard::cues(ui.ctx()) {
menu_body(app, ui, items, clicked);
return;
}
widgets::menu_scroll(ui, |ui| {
widgets::menu_min_width(ui, 230.0);
render_items_scoped(app, ui, items, true, Some(path), clicked);
});
}
/// `items` as menu buttons; with `checks`, items that can be on or off show a check mark (or the
/// room for one).
pub(super) fn render_items(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Item], checks: bool, clicked: &mut Option<(String, Value)>) {
render_items_scoped(app, ui, items, checks, None, clicked);
}
fn render_items_scoped(
app: &VectorcraftApp,
ui: &mut egui::Ui,
items: &[Item],
checks: bool,
path: Option<&SourcePath>,
clicked: &mut Option<(String, Value)>,
) {
let t = Tokens::get(ui.ctx());
let rows = path.map(|p| keyboard::level(app, p, items)).unwrap_or_default();
let mut rows = rows.iter();
if let Some(path) = path {
keyboard::note_level(ui.ctx(), path);
}
for e in items.iter().filter_map(|it| entry(app, it)) {
match e {
Entry::Sep => {
@@ -135,14 +172,40 @@ pub(super) fn render_items(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Ite
ui.label(egui::RichText::new(h).size(11.0).color(t.text_dim));
}
Entry::Sub(label, children) => {
ui.menu_button(label, |ui| {
widgets::menu_scroll(ui, |ui| {
widgets::menu_min_width(ui, 200.0);
render_items(app, ui, children, checks || only_toggles(app, children), clicked);
if let Some(access) = rows.next() {
ui.push_id(access.key.salt(), |ui| {
let cue = access.cue.as_ref().filter(|_| keyboard::cues(ui.ctx()));
let text = keyboard::text(ui, label, "", cue, None);
if !ui.is_sizing_pass() {
keyboard::prepare_submenu(ui.ctx(), access, ui.next_auto_id());
}
let (response, _) = egui::menu::SubMenuButton::new(text).ui(ui, |ui| {
widgets::menu_scroll(ui, |ui| {
widgets::menu_min_width(ui, 200.0);
render_items_scoped(
app,
ui,
children,
checks || only_toggles(app, children),
Some(&keyboard::child_path(&access.key)),
clicked,
);
});
});
if !ui.is_sizing_pass() {
keyboard::bind_response(ui.ctx(), access, &response);
}
});
});
} else {
ui.menu_button(label, |ui| {
widgets::menu_scroll(ui, |ui| {
widgets::menu_min_width(ui, 200.0);
render_items(app, ui, children, checks || only_toggles(app, children), clicked);
});
});
}
}
Entry::Item(row) => render_row(app, ui, &row, checks, clicked),
Entry::Item(row) => render_row(app, ui, &row, checks, rows.next(), clicked),
}
}
}
@@ -156,24 +219,28 @@ fn only_toggles(app: &VectorcraftApp, items: &[Item]) -> bool {
/// One menu item: its label (with a check mark, or the room for one, under `checks`), its shortcut,
/// and Type › Font's samples.
fn render_row(app: &VectorcraftApp, ui: &mut egui::Ui, row: &Row, checks: bool, clicked: &mut Option<(String, Value)>) {
fn render_row(app: &VectorcraftApp, ui: &mut egui::Ui, row: &Row, checks: bool, access: Option<&AccessRow>, clicked: &mut Option<(String, Value)>) {
let sc = row.shortcut.map(shown_shortcut).unwrap_or_default();
let Some((id, p)) = row.command else {
ui.add_enabled_ui(false, |ui| {
ui.add(egui::Button::new(row.label.as_ref()).shortcut_text(sc));
let cue = access.and_then(|r| r.cue.as_ref()).filter(|_| keyboard::cues(ui.ctx()));
let text = keyboard::text(ui, row.label.as_ref(), "", cue, None);
ui.add(egui::Button::new(text).shortcut_text(sc));
})
.response
.on_disabled_hover_text(tl!("Coming soon — tracked in the parity plan"));
return;
};
let text = match row.checked.filter(|_| checks) {
Some(true) => format!("✓ {}", row.label),
Some(false) => format!(" {}", row.label),
None => row.label.to_string(),
let prefix = match row.checked.filter(|_| checks) {
Some(true) => "✓ ",
Some(false) => " ",
None => "",
};
let cue = access.and_then(|r| r.cue.as_ref()).filter(|_| keyboard::cues(ui.ctx()));
let text = keyboard::text(ui, row.label.as_ref(), prefix, cue, None);
// Type → Font: each family's sample after its name (Enable in-menu font previews).
let sampled = p.get("font").and_then(Value::as_str).filter(|_| id == "text.setStyle" && app.session.prefs.font_preview);
let r = match sampled {
let draw = |ui: &mut egui::Ui| match sampled {
Some(family) => {
let slot = egui::IdSalt::new(("font-sample", family));
let button = egui::Button::new(text).right_text(egui::Atom::custom(slot, crate::font_menu::MENU_SAMPLE_SIZE));
@@ -185,12 +252,22 @@ fn render_row(app: &VectorcraftApp, ui: &mut egui::Ui, row: &Row, checks: bool,
}
None => ui.add_enabled(row.enabled, egui::Button::new(text).shortcut_text(sc)),
};
let r = match access {
Some(access) => ui.push_id(access.key.salt(), draw).inner,
None => draw(ui),
};
let keyboard_chosen = !ui.is_sizing_pass() && access.is_some_and(|access| keyboard::bind_response(ui.ctx(), access, &r));
let r = match (row.enabled, disabled_hint(app, id)) {
(false, Some(why)) => r.on_disabled_hover_text(why),
_ => r,
};
if r.clicked() {
*clicked = row.target().map(|target| with_held_keys(target, ui.input(|i| i.modifiers)));
if r.clicked() || keyboard_chosen {
*clicked = row.target().map(|target| {
if access.is_none() || r.clicked_by(egui::PointerButton::Primary) { with_held_keys(target, ui.input(|i| i.modifiers)) } else { target } // access-key Alt is not an Alt-click alternate action
});
if access.is_some() {
keyboard::chosen(ui.ctx());
}
ui.close();
}
}
+933
View File
@@ -0,0 +1,933 @@
//! Access keys for the in-window menu bar. Native menu labels and command shortcuts stay separate.
use std::collections::HashSet;
use std::ops::Range;
use egui::{Context, Event, Id, Key, Modifiers, Response};
use serde_json::Value;
use super::{Entry, Item, VectorcraftApp, entry};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct SubKey {
source: String,
contents: Id,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct SourcePath {
root: String,
parents: Vec<SubKey>,
}
#[derive(Clone, Debug, PartialEq)]
enum Kind {
Sub(SubKey),
Command(String, Value),
Unavailable(String),
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct TargetKey {
path: SourcePath,
kind: Kind,
// Dynamic slots can keep their command id while naming a different saved item.
binding: Id,
}
impl TargetKey {
pub(super) fn salt(&self) -> String {
format!("menu-access:{self:?}")
}
}
#[derive(Clone)]
pub(super) struct Cue {
folded: String,
range: Range<usize>,
}
#[derive(Clone)]
pub(super) struct AccessRow {
pub key: TargetKey,
pub label: String,
pub cue: Option<Cue>,
pub enabled: bool,
preferred: Option<char>,
}
type Field = (Id, egui::text_edit::TextEditState);
#[derive(Clone, Default)]
struct State {
active: bool,
root: Option<String>,
open: bool,
path: Vec<SubKey>,
focus: Option<TargetKey>,
focus_request: Option<TargetKey>,
scroll_request: Option<TargetKey>,
first_request: Option<SourcePath>,
root_request: bool,
activate: Option<TargetKey>,
collision: Option<(String, Vec<TargetKey>, usize)>,
invalidated: bool,
alt_down: bool,
alt_armed: bool,
alt_used: bool,
composing: bool,
modifiers: Modifiers,
keyboard_pointer: bool,
origin: Option<Id>,
document: Option<u64>,
titles: Vec<(String, Id, Id)>,
registry: Vec<(Id, TargetKey)>,
shown: Vec<SourcePath>,
}
fn state_id(ctx: &Context) -> Id {
Id::unique("menu-bar-access").with(ctx.viewport_id())
}
fn read(ctx: &Context) -> State {
let id = state_id(ctx);
ctx.data(|d| d.get_temp(id)).unwrap_or_default()
}
fn write(ctx: &Context, state: State) {
let id = state_id(ctx);
ctx.data_mut(|d| d.insert_temp(id, state));
}
// Row rendering borrows the stored state in place: never clone its whole growing registry.
// Context/focus/scroll calls belong outside this data lock.
fn with_state<R>(ctx: &Context, f: impl FnOnce(&mut State) -> R) -> R {
let id = state_id(ctx);
ctx.data_mut(|d| f(d.get_temp_mut_or_default::<State>(id)))
}
fn field_id(ctx: &Context) -> Id {
Id::unique("menu-bar-field").with(ctx.viewport_id())
}
pub(super) fn remember_field(ctx: &Context) {
if let Some(id) = super::invoke::focused_text_field(ctx)
&& let Some(state) = egui::TextEdit::load_state(ctx, id)
{
let key = field_id(ctx);
ctx.data_mut(|d| d.insert_temp(key, (id, state)));
}
}
pub(super) fn field(ctx: &Context) -> Option<Field> {
let id = field_id(ctx);
ctx.data(|d| d.get_temp(id))
}
// A menu's focus return resumes the same edit, rather than beginning a new numeric edit.
// Keep the marker for every pass of this frame; a sizing/discard pass must not reselect all.
fn restoration_id(ctx: &Context, field: Id) -> Id {
field.with(("menu-bar-resume-selection", ctx.viewport_id()))
}
pub(super) fn restore_field(ctx: &Context, id: Id, saved: egui::text_edit::TextEditState) {
let marker = restoration_id(ctx, id);
let frame = ctx.cumulative_frame_nr();
ctx.data_mut(|d| d.insert_temp(marker, frame));
saved.store(ctx, id);
ctx.memory_mut(|m| m.request_focus(id));
}
pub(crate) fn restoring_field_focus(ctx: &Context, field: Id) -> bool {
let marker = restoration_id(ctx, field);
let frame = ctx.cumulative_frame_nr();
ctx.data_mut(|d| {
let restoring = d.get_temp::<u64>(marker) == Some(frame);
if !restoring {
d.remove_temp::<u64>(marker);
}
restoring
})
}
pub(super) fn forget_field(ctx: &Context) {
let id = field_id(ctx);
ctx.data_mut(|d| d.remove::<Field>(id));
}
fn supported(ctx: &Context) -> bool {
matches!(ctx.os(), egui::os::OperatingSystem::Windows | egui::os::OperatingSystem::Nix)
}
pub(super) fn active(ctx: &Context) -> bool {
with_state(ctx, |state| state.active)
}
fn cancel(ctx: &Context, state: &mut State, restore: bool) {
for (_, _, popup) in &state.titles {
egui::Popup::close_id(ctx, *popup);
}
state.active = false;
state.open = false;
state.root_request = false;
state.focus_request = None;
state.scroll_request = None;
state.first_request = None;
state.activate = None;
state.collision = None;
state.path.clear();
if restore {
if let Some((id, saved)) = field(ctx) {
restore_field(ctx, id, saved);
} else if let Some(id) = state.origin {
ctx.memory_mut(|m| m.request_focus(id));
} else if let Some(id) = ctx.memory(|m| m.focused()) {
ctx.memory_mut(|m| m.surrender_focus(id));
}
}
if !restore
&& let Some(focused) = ctx.memory(|m| m.focused())
&& (state.titles.iter().any(|(_, id, _)| *id == focused) || state.registry.iter().any(|(id, _)| *id == focused))
{
ctx.memory_mut(|m| m.surrender_focus(focused));
}
state.origin = None;
ctx.request_repaint();
}
fn enter(app: &VectorcraftApp, ctx: &Context, state: &mut State) {
if !state.active {
remember_field(ctx);
state.origin = ctx.memory(|m| m.focused());
state.document = app.session.active().map(|d| d.uid);
state.active = true;
}
state.keyboard_pointer = true;
}
fn choose_root(app: &VectorcraftApp, ctx: &Context, state: &mut State, root: String, open: bool) {
enter(app, ctx, state);
for (_, _, popup) in &state.titles {
egui::Popup::close_id(ctx, *popup);
}
state.root = Some(root.clone());
state.invalidated = false;
state.open = open;
state.path.clear();
state.focus = None;
state.focus_request = None;
state.scroll_request = None;
state.activate = None;
state.collision = None;
state.root_request = true;
state.first_request = open.then_some(SourcePath { root, parents: vec![] });
ctx.request_repaint();
}
fn folded(text: &str) -> String {
text.chars().flat_map(char::to_lowercase).collect()
}
fn characters(label: &str) -> Vec<Cue> {
let mut out = vec![];
let mut seen = HashSet::new();
let mut push = |at: usize, ch: char| {
let key = folded(&ch.to_string());
if seen.insert(key.clone()) {
out.push(Cue { folded: key, range: at..at + ch.len_utf8() });
}
};
// Word initials first, then all letters/digits. Literal punctuation is a last resort for a
// user-named row containing no other character; it is never interpreted as markup.
let mut initial = true;
for (at, ch) in label.char_indices() {
if ch.is_alphanumeric() && initial {
push(at, ch);
}
initial = !ch.is_alphanumeric();
}
for (at, ch) in label.char_indices().filter(|(_, c)| c.is_alphanumeric()) {
push(at, ch);
}
for (at, ch) in label.char_indices().filter(|(_, c)| !c.is_whitespace() && !c.is_control()) {
push(at, ch);
}
out
}
fn assign(rows: &mut [AccessRow]) {
let mut occupied = HashSet::new();
// Reserve the reported paths before earlier siblings take their letters.
for row in rows.iter_mut() {
if let Some(wanted) = row.preferred.map(|c| folded(&c.to_string()))
&& let Some(cue) = characters(&row.label).into_iter().find(|c| c.folded == wanted)
{
occupied.insert(cue.folded.clone());
row.cue = Some(cue);
}
}
for row in rows.iter_mut().filter(|r| r.cue.is_none()) {
let choices = characters(&row.label);
row.cue = choices.iter().find(|c| !occupied.contains(&c.folded)).or_else(|| choices.first()).cloned();
if let Some(cue) = &row.cue {
occupied.insert(cue.folded.clone());
}
}
}
fn roots(app: &VectorcraftApp) -> Vec<(&'static str, Vec<Item>)> {
super::menu_tree_named(app.session.prefs.font_names_in_english).into_iter().filter(|(name, _)| *name != "VectorCraft").collect()
}
pub(super) fn root_rows(tree: &[(&str, Vec<Item>)]) -> Vec<AccessRow> {
let mut rows: Vec<_> = tree
.iter()
.map(|(source, _)| AccessRow {
key: TargetKey {
path: SourcePath { root: (*source).into(), parents: vec![] },
kind: Kind::Unavailable((*source).into()),
binding: Id::unique(("menu-root-binding", source, crate::i18n::t(source))),
},
label: crate::i18n::t(source).into(),
cue: None,
enabled: true,
preferred: match *source {
"File" => Some('f'),
"Edit" => Some('e'),
"Object" => Some('o'),
"Type" => Some('t'),
"Select" => Some('s'),
"Effect" => Some('c'),
"View" => Some('v'),
"Window" => Some('w'),
"Help" => Some('h'),
_ => None,
},
})
.collect();
assign(&mut rows);
rows
}
fn sub_key(source: &str, items: &[Item]) -> SubKey {
// Source names, command ids and params (not translated labels or visible row positions).
// A changed dynamic folder definition invalidates its old selection rather than retargeting it.
SubKey { source: source.into(), contents: Id::unique(("menu-submenu-definition", format!("{items:?}"))) }
}
pub(super) fn root_path(source: &str) -> SourcePath {
SourcePath { root: source.into(), parents: vec![] }
}
pub(super) fn child_path(key: &TargetKey) -> SourcePath {
let mut path = key.path.clone();
if let Kind::Sub(sub) = &key.kind {
path.parents.push(sub.clone());
}
path
}
pub(super) fn level(app: &VectorcraftApp, path: &SourcePath, items: &[Item]) -> Vec<AccessRow> {
let mut rows = vec![];
for item in items {
match entry(app, item) {
Some(Entry::Sub(label, children)) => {
let Item::Sub(source, _) = item else { continue };
rows.push(AccessRow {
key: TargetKey {
path: path.clone(),
kind: Kind::Sub(sub_key(source, children)),
binding: Id::unique(("menu-submenu-binding", source, label)),
},
label: label.into(),
cue: None,
enabled: true,
preferred: (path.root == "Object" && path.parents.is_empty() && *source == "Path").then_some('p'),
});
}
Some(Entry::Item(row)) => {
let target = row.target();
let preferred = row.command.and_then(|(id, _)| match id {
"object.path.offsetPath" => Some('o'),
"select.save" if path.root == "Select" && path.parents.is_empty() => Some('s'),
"select.editSaved" if path.root == "Select" && path.parents.is_empty() => Some('e'),
_ => None,
});
rows.push(AccessRow {
key: TargetKey {
path: path.clone(),
kind: target.map_or_else(|| Kind::Unavailable(row.source.into()), |(id, params)| Kind::Command(id, params)),
binding: Id::unique(("menu-row-binding", row.source, row.label.as_ref())),
},
label: row.label.into_owned(),
cue: None,
enabled: row.enabled && row.command.is_some(),
preferred,
});
}
_ => {}
}
}
assign(&mut rows);
rows
}
fn current_rows(app: &VectorcraftApp, state: &State) -> Option<Vec<AccessRow>> {
let root = state.root.as_deref()?;
let tree = roots(app);
let (_, items) = tree.iter().find(|(name, _)| *name == root)?;
let mut items = items.as_slice();
for wanted in &state.path {
items = items.iter().find_map(|item| match item {
Item::Sub(source, children) if *source == wanted.source.as_str() && sub_key(source, children) == *wanted => Some(children.as_slice()),
_ => None,
})?;
}
Some(level(app, &SourcePath { root: root.into(), parents: state.path.clone() }, items))
}
fn mnemonic(rows: &[AccessRow], text: &str) -> Vec<TargetKey> {
let folded = folded(text);
rows.iter().filter(|r| r.enabled && r.cue.as_ref().is_some_and(|c| c.folded == folded)).map(|r| r.key.clone()).collect()
}
fn letter(app: &VectorcraftApp, ctx: &Context, state: &mut State, text: &str, fallback: Option<&str>) -> bool {
let rows = if state.active && state.open { current_rows(app, state) } else { Some(root_rows(&roots(app))) };
let Some(rows) = rows else {
cancel(ctx, state, true);
return true;
};
let mut matches = mnemonic(&rows, text);
if matches.is_empty()
&& let Some(fallback) = fallback
{
matches = mnemonic(&rows, fallback);
}
if matches.is_empty() {
return state.active;
}
if !state.active || !state.open {
if let Some(target) = matches.first() {
choose_root(app, ctx, state, target.path.root.clone(), true);
}
return true;
}
let chosen = if matches.len() == 1 {
state.collision = None;
matches.first().cloned()
} else {
let token = folded(text);
let index = match &state.collision {
Some((old, keys, at)) if old == &token && keys == &matches => (at + 1) % matches.len(),
_ => 0,
};
let chosen = matches.get(index).cloned();
state.collision = Some((token, matches, index));
chosen
};
if let Some(chosen) = chosen {
state.invalidated = false;
state.focus_request = Some(chosen.clone());
state.focus = Some(chosen.clone());
// A submenu mnemonic focuses its genuine button; real Right/Enter enters it through
// egui, including its RTL and stationary-pointer handling. Collisions require Enter.
if matches!(chosen.kind, Kind::Command(..)) && state.collision.is_none() {
state.activate = Some(chosen);
}
state.keyboard_pointer = true;
ctx.request_repaint();
}
true
}
fn owner_blocks(app: &VectorcraftApp, ctx: &Context, state: &State) -> bool {
!supported(ctx)
|| !ctx.input(|i| i.focused)
|| app.file_dialog_open()
|| app.ui.dialog.is_some()
|| app.ui.palette_open
|| app.ui.screen_mode == 3
|| app.ui.tools_drawer
|| crate::updates_ui::blocks_input(app)
|| !app.held_tool.is_empty()
|| app.session.tool_busy()
|| app.session.tool_composing()
|| state.composing
|| crate::scrub::phase(ctx) != crate::scrub::Phase::Idle
|| crate::canvas::dragging(ctx)
|| ctx.dragged_id().is_some()
}
fn update_composition(ctx: &Context, state: &mut State, events: &[Event]) -> bool {
if !events.iter().any(|e| matches!(e, Event::ModifiersChanged(_) | Event::Key { .. })) {
state.modifiers = ctx.input(|i| i.modifiers);
}
let mut ime = false;
for event in events {
match event {
Event::Ime(egui::ImeEvent::Preedit { text, .. }) => {
state.composing = !text.is_empty();
ime = true;
}
Event::Ime(egui::ImeEvent::Commit(_)) => {
state.composing = false;
ime = true;
}
#[allow(deprecated)]
Event::Ime(egui::ImeEvent::Disabled) => {
state.composing = false;
ime = true;
}
Event::Ime(_) => ime = true,
Event::WindowFocused(false) => {
state.alt_down = false;
state.alt_armed = false;
state.composing = false;
}
_ => {}
}
}
ime
}
fn prepare_input(app: &VectorcraftApp, ctx: &Context, state: &mut State, events: &[Event]) -> Option<bool> {
let ime = update_composition(ctx, state, events);
if ime || owner_blocks(app, ctx, state) {
if state.active {
cancel(ctx, state, ime && app.ui.dialog.is_none());
}
state.alt_armed = false;
return None;
}
if !state.active && egui::Popup::is_any_open(ctx) {
if let Some((source, _, _)) = state.titles.iter().find(|(_, _, id)| egui::Popup::is_id_open(ctx, *id)).cloned() {
enter(app, ctx, state);
state.root = Some(source);
state.open = true;
state.keyboard_pointer = false;
} else {
state.alt_armed = false;
return None; // context menu/popover owns its own keys
}
}
refresh_targets(app, ctx, state);
let pointer_activity = ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO || i.pointer.any_click() || i.pointer.any_down());
if pointer_activity {
state.invalidated = false;
state.keyboard_pointer = false;
state.alt_armed = false;
}
Some(pointer_activity)
}
fn refresh_targets(app: &VectorcraftApp, ctx: &Context, state: &mut State) {
if state.active && state.document != app.session.active().map(|d| d.uid) {
cancel(ctx, state, false);
}
if !state.root_request
&& !state.invalidated
&& let Some(focused) = ctx.memory(|m| m.focused())
&& let Some((_, key)) = state.registry.iter().find(|(id, _)| *id == focused)
{
state.focus = Some(key.clone());
state.path = key.path.parents.clone();
}
// Re-resolve current labels/targets; a vanished dynamic target never invokes its replacement.
if state.active && state.open {
match current_rows(app, state) {
Some(rows) => {
if state.focus.as_ref().is_some_and(|key| !rows.iter().any(|r| &r.key == key)) {
if let Some(id) = ctx.memory(|m| m.focused()) {
ctx.memory_mut(|m| m.surrender_focus(id));
}
state.invalidated = true;
state.first_request = None;
state.scroll_request = None;
state.focus = None;
state.focus_request = None;
state.activate = None;
state.collision = None;
}
}
None => {
if let Some(id) = ctx.memory(|m| m.focused()) {
ctx.memory_mut(|m| m.surrender_focus(id));
}
state.invalidated = true;
state.first_request = None;
state.scroll_request = None;
state.path.clear();
state.focus = None;
state.focus_request = None;
state.activate = None;
state.collision = None;
}
}
}
}
fn modifiers_changed(app: &VectorcraftApp, ctx: &Context, state: &mut State, m: &Modifiers, pointer_activity: bool, owned: &mut bool) {
let plain_alt = m.alt && !m.ctrl && !m.command && !m.mac_cmd;
if plain_alt && !state.alt_down {
state.alt_armed = !pointer_activity;
state.alt_used = false;
}
if !m.alt && state.alt_down {
if state.alt_armed && !state.alt_used {
*owned = true;
if state.active {
cancel(ctx, state, true);
} else {
choose_root(app, ctx, state, "File".into(), false);
}
}
state.alt_armed = false;
}
if m.ctrl || m.command || m.mac_cmd {
state.alt_armed = false;
state.alt_used = true;
if state.active {
cancel(ctx, state, true);
}
*owned = false;
}
state.alt_down = m.alt;
}
fn consume_event(consumed: &mut [bool], at: usize) {
if let Some(c) = consumed.get_mut(at) {
*c = true;
}
}
fn horizontal_navigation(app: &VectorcraftApp, ctx: &Context, state: &mut State, key: Key) -> bool {
let towards = if ctx.global_style().right_to_left { Key::ArrowLeft } else { Key::ArrowRight };
let submenu = state.focus.as_ref().is_some_and(|f| matches!(f.kind, Kind::Sub(_)));
if key != towards || !submenu {
let roots = roots(app);
if let Some(index) = roots.iter().position(|(s, _)| Some(*s) == state.root.as_deref()) {
let forward = (key == Key::ArrowRight) != ctx.global_style().right_to_left;
let next = if forward { (index + 1) % roots.len() } else { (index + roots.len() - 1) % roots.len() };
if let Some((root, _)) = roots.get(next) {
let was_open = state.open;
choose_root(app, ctx, state, (*root).into(), was_open);
}
}
return true;
}
false
}
fn navigation_key(app: &VectorcraftApp, ctx: &Context, state: &mut State, key: Key, consumed: &mut [bool], at: usize, owned: &mut bool) -> bool {
match key {
Key::Enter | Key::Space if state.invalidated => {
// A disappeared item is not permission to activate the next slot,
// including when egui gives that replacement its default focus.
consume_event(consumed, at);
*owned = true;
true
}
Key::Escape if state.path.is_empty() => {
cancel(ctx, state, true);
*owned = true;
consume_event(consumed, at);
true
}
Key::Escape | Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight | Key::Enter | Key::Space => {
if matches!(key, Key::ArrowLeft | Key::ArrowRight) && state.path.is_empty() {
if horizontal_navigation(app, ctx, state, key) {
consume_event(consumed, at);
}
} else if !state.open && matches!(key, Key::ArrowDown | Key::Enter | Key::Space) {
if let Some(root) = state.root.clone() {
choose_root(app, ctx, state, root, true);
}
consume_event(consumed, at);
}
*owned = true;
true // egui owns the remaining navigation keys
}
_ => false,
}
}
fn pressed_key(app: &VectorcraftApp, ctx: &Context, state: &mut State, events: &[Event], at: usize, consumed: &mut [bool], owned: &mut bool) {
let Event::Key { key, physical_key, pressed: true, repeat, modifiers } = &events[at] else {
return;
};
if modifiers.ctrl || modifiers.command || modifiers.mac_cmd || (modifiers.alt && matches!(key, Key::Tab | Key::Space)) {
state.alt_armed = false;
state.alt_used = true;
if state.active {
cancel(ctx, state, true);
*owned = false;
}
return;
}
let access = state.active || modifiers.alt;
if !access {
return;
}
if modifiers.alt && crate::shortcuts::runs_a_shortcut(key.name(), physical_key.unwrap_or(*key).name(), *modifiers) {
state.alt_armed = false;
state.alt_used = true;
if state.active {
cancel(ctx, state, true);
*owned = false;
}
return;
}
if state.active {
state.keyboard_pointer = true;
if matches!(key, Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight) {
state.invalidated = false;
}
if navigation_key(app, ctx, state, *key, consumed, at, owned) {
return;
}
}
state.alt_used = true;
state.alt_armed = false;
// Native input is Key then Text. Prefer its delivered Unicode text, while keeping
// the logical/Latin key as fallback. The pair is consumed together, exactly once.
let text_at = events
.iter()
.enumerate()
.skip(at + 1)
.take_while(|(_, e)| !matches!(e, Event::Key { pressed: true, .. } | Event::Ime(_)))
.find_map(|(i, e)| matches!(e, Event::Text(_)).then_some(i));
let text = text_at.and_then(|i| events.get(i)).and_then(|e| if let Event::Text(t) = e { Some(t.as_str()) } else { None });
let fallback = key.name();
if !*repeat && letter(app, ctx, state, text.unwrap_or(fallback), Some(fallback)) || state.active {
*owned = true;
consume_event(consumed, at);
if let Some(i) = text_at {
consume_event(consumed, i);
}
}
}
fn text_event(app: &VectorcraftApp, ctx: &Context, state: &mut State, text: &str, consumed: &mut [bool], at: usize, owned: &mut bool) {
if state.modifiers.ctrl || state.modifiers.command || state.modifiers.mac_cmd {
state.alt_armed = false;
state.alt_used = true;
if state.active {
cancel(ctx, state, true);
}
*owned = false;
// AltGr/Ctrl text belongs downstream, even without a Key event.
} else if state.active || state.alt_down && state.alt_armed {
state.alt_used = true;
state.alt_armed = false;
if letter(app, ctx, state, text, None) || state.active {
*owned = true;
consume_event(consumed, at);
}
}
}
/// Called only by App's existing once-per-frame gate, BEFORE ordinary shortcuts.
pub(crate) fn handle_input(app: &mut VectorcraftApp, ctx: &Context) -> bool {
let mut state = read(ctx);
let events = ctx.input(|i| i.events.clone());
let Some(pointer_activity) = prepare_input(app, ctx, &mut state, &events) else {
write(ctx, state);
return false;
};
let mut owned = state.active;
let mut consumed = vec![false; events.len()];
for (at, event) in events.iter().enumerate() {
if consumed.get(at).copied().unwrap_or(false) {
continue;
}
match event {
Event::ModifiersChanged(m)
| Event::Key { modifiers: m, .. }
| Event::PointerButton { modifiers: m, .. }
| Event::MouseWheel { modifiers: m, .. } => state.modifiers = *m,
_ => {}
}
match event {
Event::ModifiersChanged(m) => modifiers_changed(app, ctx, &mut state, m, pointer_activity, &mut owned),
Event::Key { pressed: true, .. } => pressed_key(app, ctx, &mut state, &events, at, &mut consumed, &mut owned),
Event::Text(text) => text_event(app, ctx, &mut state, text, &mut consumed, at, &mut owned),
Event::PointerButton { .. } | Event::MouseWheel { .. } => {
// Preserve event order: wheel hands scrolling to the real pointer, but a later
// navigation key owns it again. Smoothed wheel tails must not undo that choice.
state.keyboard_pointer = false;
state.alt_armed = false;
state.alt_used = true;
}
_ => {}
}
}
ctx.input_mut(|i| {
let mut at = 0;
i.events.retain(|_| {
let keep = !consumed.get(at).copied().unwrap_or(false);
at += 1;
keep
});
});
write(ctx, state);
owned
}
pub(super) fn begin_bar(ctx: &Context) {
with_state(ctx, |state| {
state.registry.clear();
state.shown.clear();
});
}
pub(super) fn cues(ctx: &Context) -> bool {
supported(ctx) && with_state(ctx, |state| state.active || state.alt_down && state.alt_armed)
}
pub(super) fn suppress_stationary_hover(ctx: &Context) -> bool {
let keyboard = with_state(ctx, |state| state.active && state.keyboard_pointer);
keyboard && ctx.input(|i| i.pointer.delta() == egui::Vec2::ZERO && !i.pointer.any_click() && !i.pointer.any_down())
}
pub(super) fn bind_root(ctx: &Context, source: &str, response: &Response) {
let popup = egui::Popup::default_response_id(response);
let requested = with_state(ctx, |state| {
if let Some(root) = state.titles.iter_mut().find(|(name, _, _)| name == source) {
*root = (source.into(), response.id, popup);
} else {
state.titles.push((source.into(), response.id, popup));
}
if state.active && state.root_request && state.root.as_deref() == Some(source) {
state.root_request = false;
Some(state.open)
} else {
None
}
});
if let Some(open) = requested {
response.request_focus();
if open {
egui::Popup::open_id(ctx, popup);
} else {
egui::Popup::close_id(ctx, popup);
}
}
}
pub(super) fn note_level(ctx: &Context, path: &SourcePath) {
with_state(ctx, |state| state.shown.push(path.clone()));
}
// The public SubMenuButton uses this same next_auto_id for its genuine button. Let its own
// Right/Enter/RTL path open it. Only request focus after releasing the data lock.
pub(super) fn prepare_submenu(ctx: &Context, row: &AccessRow, id: Id) {
let request = with_state(ctx, |state| {
let focus_here = match &state.focus_request {
Some(wanted) => wanted == &row.key,
None => state.first_request.as_ref() == Some(&row.key.path),
};
if state.active && row.enabled && focus_here {
state.focus = Some(row.key.clone());
state.focus_request = None;
state.first_request = None;
state.scroll_request = Some(row.key.clone());
true
} else {
false
}
});
if request {
ctx.memory_mut(|m| m.request_focus(id));
}
}
pub(super) fn bind_response(ctx: &Context, row: &AccessRow, response: &Response) -> bool {
let has_focus = response.has_focus();
let (request_focus, scroll, activate) = with_state(ctx, |state| {
state.registry.push((response.id, row.key.clone()));
let scroll = state.scroll_request.as_ref() == Some(&row.key);
if scroll {
state.scroll_request = None;
}
let focus_here = match &state.focus_request {
Some(wanted) => wanted == &row.key,
None => state.first_request.as_ref() == Some(&row.key.path),
};
let request_focus = state.active && row.enabled && focus_here;
if request_focus {
state.focus_request = None;
state.first_request = None;
state.focus = Some(row.key.clone());
}
if has_focus && !state.invalidated {
state.focus = Some(row.key.clone());
}
// Real egui arrow navigation changes focus without a helper focus_request.
// Keep that keyboard row visible, while pointer/wheel scrolling keeps its own position.
let focused_keyboard_row = state.active && state.keyboard_pointer && !state.invalidated && row.enabled && has_focus;
let activate = state.active && row.enabled && state.activate.as_ref() == Some(&row.key);
if activate {
state.activate = None;
state.active = false;
state.open = false;
state.root_request = false;
}
(request_focus, scroll || request_focus || focused_keyboard_row, activate)
});
if request_focus {
response.request_focus();
}
if scroll {
response.scroll_to_me(None);
}
activate
}
pub(super) fn chosen(ctx: &Context) {
with_state(ctx, |state| {
state.active = false;
state.open = false;
state.activate = None;
state.root_request = false;
state.collision = None;
});
}
pub(super) fn finish_bar(ctx: &Context, open: bool, command_chosen: bool) {
let mut state = read(ctx);
if state.active {
if let Some((source, _, _)) = state.titles.iter().find(|(_, _, id)| egui::Popup::is_id_open(ctx, *id)).cloned() {
state.root = Some(source.clone());
state.open = true;
state.path =
state.shown.iter().filter(|p| p.root == source).max_by_key(|p| p.parents.len()).map(|p| p.parents.clone()).unwrap_or_default();
} else if state.open && !open {
let restore = !command_chosen && !ctx.input(|i| i.pointer.any_click());
cancel(ctx, &mut state, restore);
}
}
write(ctx, state);
}
/// A layout job changes only presentation; literal '&'/'_' and all native/shared labels survive.
pub(super) fn text(ui: &egui::Ui, label: &str, prefix: &str, cue: Option<&Cue>, size: Option<f32>) -> egui::WidgetText {
let Some(cue) = cue else {
let text = format!("{prefix}{label}");
return match size {
Some(size) => egui::RichText::new(text).size(size).color(super::Tokens::get(ui.ctx()).text).into(),
None => text.into(),
};
};
let Some((before, rest)) = label.split_at_checked(cue.range.start) else { return format!("{prefix}{label}").into() };
let Some((letter, after)) = rest.split_at_checked(cue.range.len()) else { return format!("{prefix}{label}").into() };
let mut font = egui::TextStyle::Button.resolve(ui.style());
if let Some(size) = size {
font.size = size;
}
let format = egui::TextFormat { font_id: font, color: ui.visuals().text_color(), ..Default::default() };
let mut job = egui::text::LayoutJob::default();
job.append(&format!("{prefix}{before}"), 0.0, format.clone());
job.append(letter, 0.0, egui::TextFormat { underline: egui::Stroke::new(1.0, format.color), ..format.clone() });
job.append(after, 0.0, format);
job.into()
}
+5 -1
View File
@@ -200,7 +200,11 @@ pub(super) fn select_all_on_focus(ui: &Ui, resp: &Response, text: &str) {
d.remove_temp::<egui::Pos2>(press_pos);
});
}
if !(resp.gained_focus() && !pressed || resp.double_clicked() || clicked_focus && !dragged) {
// Returning from a transient menu resumes its saved caret/selection. This is not the
// keyboard focus that starts a new numeric edit; pointer taps/double-clicks still select all.
// The menu helper's data borrow ends here, before TextEdit's state is loaded below.
let restored_focus = crate::menus::restoring_field_focus(ui.ctx(), resp.id);
if !(resp.gained_focus() && !pressed && !restored_focus || resp.double_clicked() || clicked_focus && !dragged) {
return;
}
if let Some(st) = egui::TextEdit::load_state(ui.ctx(), resp.id) {
+966
View File
@@ -0,0 +1,966 @@
//! Main-menu access keys use the real App input and existing dialog routes.
#![cfg(not(target_os = "macos"))]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::{Mutex, MutexGuard};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, Shape, vec2};
use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_ui_egui::{VectorcraftApp, i18n};
// These cases share the library's process-global locale. A failing baseline must not poison
// the passing pointer control, and Drop restores the previous locale even after an assertion.
static UI_STATE: Mutex<()> = Mutex::new(());
struct GlobalState {
language: i18n::Lang,
_lock: MutexGuard<'static, ()>,
}
impl GlobalState {
fn new() -> Self {
let lock = UI_STATE.lock().unwrap_or_else(|e| e.into_inner());
let language = i18n::current();
i18n::set_current(i18n::Lang::EN);
Self { language, _lock: lock }
}
}
impl Drop for GlobalState {
fn drop(&mut self) {
i18n::set_current(self.language);
}
}
fn key(key: Key, pressed: bool, modifiers: Modifiers) -> Event {
Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }
}
fn text_points(shape: &Shape, clip: Rect, out: &mut Vec<(String, Pos2)>) {
match shape {
Shape::Text(t) => {
let point = t.pos + vec2(4.0, 6.0);
if clip.contains(point) {
out.push((t.galley.text().to_string(), point));
}
}
Shape::Vec(children) => children.iter().for_each(|shape| text_points(shape, clip, out)),
_ => {}
}
}
struct Scene {
app: VectorcraftApp,
ctx: egui::Context,
time: f64,
shown: Vec<(String, Pos2)>,
}
impl Scene {
fn new() -> Self {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("app.language", json!({"lang": "en"})).unwrap();
i18n::set_current(i18n::Lang::EN);
app.run("file.new", json!({"width": 500, "height": 350})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 70, "y": 60, "width": 120, "height": 80})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [id]})).unwrap();
app.select_tool("selection");
let ctx = egui::Context::default();
vectorcraft_ui_egui::theme::install_fonts(&ctx);
vectorcraft_ui_egui::theme::apply(&ctx, Default::default());
let mut s = Self { app, ctx, time: 0.0, shown: vec![] };
for _ in 0..4 {
s.frame(vec![]);
}
assert!(s.app.ui.dialog.is_none());
assert!(!s.ctx.egui_wants_keyboard_input(), "the initial idle canvas owns input");
s
}
fn frame(&mut self, events: Vec<Event>) {
self.time += 1.0 / 30.0;
let mut raw = RawInput {
events,
time: Some(self.time),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 1000.0))),
..Default::default()
};
self.app.raw_input_hook(&self.ctx, &mut raw);
let mut out = self.ctx.run_ui(raw, |ui| self.app.ui(ui));
self.shown.clear();
for clipped in &out.shapes {
text_points(&clipped.shape, clipped.clip_rect, &mut self.shown);
}
out.textures_delta.clear();
}
fn settle(&mut self) {
for _ in 0..3 {
self.frame(vec![]);
}
}
fn letter(&mut self, key_id: Key, text: &str, modifiers: Modifiers) {
self.frame(vec![Event::ModifiersChanged(modifiers), key(key_id, true, modifiers), Event::Text(text.into())]);
self.frame(vec![key(key_id, false, modifiers)]);
}
fn arrow(&mut self, key_id: Key) {
self.frame(vec![key(key_id, true, Modifiers::NONE)]);
self.frame(vec![key(key_id, false, Modifiers::NONE)]);
}
fn point(&self, label: &str, popup: bool) -> Pos2 {
let points: Vec<_> = self
.shown
.iter()
.filter(|(text, point)| {
text.trim() == label && (!popup || self.ctx.layer_id_at(*point).is_some_and(|layer| layer.order == egui::Order::Foreground))
})
.map(|(_, point)| *point)
.collect();
assert_eq!(points.len(), 1, "one visible {label:?} label required; found {points:?}");
points[0]
}
fn click(&mut self, pos: Pos2) {
self.frame(vec![Event::ModifiersChanged(Modifiers::NONE), Event::PointerMoved(pos)]);
self.frame(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]);
self.frame(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]);
self.settle();
}
fn assert_offset_dialog(&self) {
let d = self.app.ui.dialog.as_ref().expect("menu navigation must open a dialog");
assert_eq!(d.kind, "offsetPath", "must invoke the existing Offset Path dialog, not another command");
assert!(!d.bool("preview"), "a fresh Offset Path dialog opens with Preview off");
assert!(self.shown.iter().any(|(text, _)| text == "Offset Path"), "the actual existing dialog must be drawn");
}
}
#[test]
fn menu_access_baseline_alt_sequence_opens_offset_path_without_editing() {
let _global = GlobalState::new();
let mut s = Scene::new();
let state = s.app.session.active().unwrap();
let (document, selection) = (state.doc.clone(), state.selection.clone());
let history = (state.history.undo.len(), state.history.redo.len());
s.frame(vec![Event::ModifiersChanged(Modifiers::ALT)]);
s.letter(Key::O, "o", Modifiers::ALT);
s.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]);
s.letter(Key::P, "p", Modifiers::NONE);
s.arrow(Key::ArrowRight);
s.letter(Key::O, "o", Modifiers::NONE);
s.settle();
s.assert_offset_dialog();
let state = s.app.session.active().unwrap();
assert_eq!(state.doc, document, "opening the menu's dialog must not edit the art");
assert_eq!(state.selection, selection);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
}
#[test]
fn menu_access_baseline_pointer_route_opens_same_offset_path_dialog() {
let _global = GlobalState::new();
let mut s = Scene::new();
let state = s.app.session.active().unwrap();
let (document, selection) = (state.doc.clone(), state.selection.clone());
let history = (state.history.undo.len(), state.history.redo.len());
s.click(s.point("Object", false));
let path = s.point("Path", true);
s.frame(vec![Event::PointerMoved(path)]);
s.settle();
s.click(s.point("Offset Path\u{2026}", true));
s.assert_offset_dialog();
let state = s.app.session.active().unwrap();
assert_eq!(state.doc, document);
assert_eq!(state.selection, selection);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
}
// Prospective full-contract cases. The baseline above stays byte-for-byte unchanged.
#[derive(Debug)]
struct Cue {
label: String,
character: char,
popup: bool,
}
fn clean_label(text: &str) -> &str {
text.trim().trim_start_matches('\u{2713}').trim_start()
}
fn painted_cues(shape: &Shape, clip: Rect, ctx: &egui::Context, out: &mut Vec<Cue>) {
match shape {
Shape::Text(t) => {
let point = t.pos + vec2(4.0, 6.0);
if !clip.contains(point) {
return;
}
for section in &t.galley.job.sections {
if section.format.underline.width <= 0.0 {
continue;
}
let marked =
t.galley.job.text.get(section.byte_range.start.0..section.byte_range.end.0).expect("underline uses valid UTF-8 boundaries");
let mut chars = marked.chars();
let Some(character) = chars.next() else { continue };
// Other widgets may underline whole strings. Only a single-character menu cue
// satisfies the assertions below; do not mistake unrelated styling for a cue.
if chars.next().is_some() {
continue;
}
out.push(Cue {
label: clean_label(t.galley.text()).into(),
character,
popup: ctx.layer_id_at(point).is_some_and(|layer| layer.order == egui::Order::Foreground),
});
}
}
Shape::Vec(children) => children.iter().for_each(|shape| painted_cues(shape, clip, ctx, out)),
_ => {}
}
}
impl Scene {
fn cues(&mut self) -> Vec<Cue> {
self.at_size(vec![], vec2(1440.0, 1000.0))
}
fn at_size(&mut self, events: Vec<Event>, size: egui::Vec2) -> Vec<Cue> {
self.at_size_focused(events, size, true)
}
fn at_size_focused(&mut self, events: Vec<Event>, size: egui::Vec2, focused: bool) -> Vec<Cue> {
self.time += 1.0 / 30.0;
let mut raw =
RawInput { events, focused, time: Some(self.time), screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size)), ..Default::default() };
self.app.raw_input_hook(&self.ctx, &mut raw);
let mut out = self.ctx.run_ui(raw, |ui| self.app.ui(ui));
self.shown.clear();
let mut cues = vec![];
for clipped in &out.shapes {
text_points(&clipped.shape, clipped.clip_rect, &mut self.shown);
painted_cues(&clipped.shape, clipped.clip_rect, &self.ctx, &mut cues);
}
out.textures_delta.clear();
cues
}
fn window_focus(&mut self, focused: bool) {
// egui-winit supplies both the RawInput field and the event on native focus changes.
self.at_size_focused(vec![Event::WindowFocused(focused)], vec2(1440.0, 1000.0), focused);
}
fn menu_diagnostic(&self) -> String {
let shown: Vec<_> = self
.shown
.iter()
.filter(|(_, point)| point.y < 40.0 || self.ctx.layer_id_at(*point).is_some_and(|layer| layer.order == egui::Order::Foreground))
.take(36)
.collect();
let focus = self.ctx.memory(|m| m.focused()).and_then(|id| self.ctx.read_response(id)).map(|r| r.rect);
format!(
"pref={} ui={} global={} input_focused={} focus_rect={focus:?} shown={shown:?}",
self.app.session.prefs.interface_language,
self.app.ui_language().code(),
i18n::current().code(),
self.ctx.input(|i| i.focused)
)
}
fn bare_alt(&mut self) {
self.frame(vec![Event::ModifiersChanged(Modifiers::ALT)]);
self.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]);
self.settle();
}
fn root(&mut self, title: &str) {
let (key, text) = match title {
"File" => (Key::F, "f"),
"Edit" => (Key::E, "e"),
"Object" => (Key::O, "o"),
"Type" => (Key::T, "t"),
"Select" => (Key::S, "s"),
"Effect" => (Key::C, "c"),
"View" => (Key::V, "v"),
"Window" => (Key::W, "w"),
"Help" => (Key::H, "h"),
_ => panic!("unexpected root {title}"),
};
self.frame(vec![Event::ModifiersChanged(Modifiers::ALT)]);
self.letter(key, text, Modifiers::ALT);
self.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]);
self.settle();
}
fn end_access(&mut self) {
for _ in 0..12 {
let active = egui::Popup::is_any_open(&self.ctx)
|| self.cues().iter().any(|c| {
!c.popup && ["File", "Edit", "Object", "Type", "Select", "Effect", "View", "Window", "Help"].contains(&c.label.as_str())
});
if !active {
return;
}
self.arrow(Key::Escape);
self.settle();
}
panic!("menu navigation did not close after bounded Escape presses");
}
fn advertised(&mut self, label: &str, invoke: bool) {
let cues = self.cues();
let matches: Vec<_> = cues.iter().filter(|c| c.popup && c.label == label).collect();
assert_eq!(matches.len(), 1, "one painted access cue for {label:?}: {cues:?}; {}", self.menu_diagnostic());
let c = matches[0].character;
let text = c.to_lowercase().collect::<String>();
let key = Key::from_name(&c.to_uppercase().collect::<String>()).expect("this English menu has a native letter key");
// A painted letter need not be unique. Follow the advertised collision interaction,
// checking the real focused row, instead of assuming the first press names this label.
let bound = cues.iter().filter(|cue| cue.popup && cue.character.to_lowercase().eq(c.to_lowercase())).count() + 1;
for _ in 0..bound {
self.letter(key, &text, Modifiers::NONE);
self.settle();
if !egui::Popup::is_any_open(&self.ctx) {
assert!(invoke, "submenu {label:?} must focus rather than invoke another command; {}", self.menu_diagnostic());
return;
}
if focused_label(self, &[label]).as_deref() == Some(label) {
if invoke {
self.arrow(Key::Enter);
self.settle();
}
return;
}
}
panic!("painted access key could not focus {label:?}; {}", self.menu_diagnostic());
}
fn command_from_menu(&mut self, id: &str) {
let entries = vectorcraft_ui_egui::menus::menu_entries(&self.app);
let matches: Vec<_> = entries.iter().filter(|e| e.command.as_deref() == Some(id)).collect();
assert_eq!(matches.len(), 1, "unambiguous existing menu command {id}");
let row = matches[0];
let (path, label) = (row.path.clone(), row.label.clone());
assert!(row.enabled);
self.root(&path[0]);
for submenu in path.iter().skip(1) {
self.advertised(submenu, false);
self.arrow(Key::ArrowRight);
self.settle();
}
self.advertised(&label, true);
}
fn assert_root_contents(&self, root: &str) {
use vectorcraft_ui_egui::menus::{self, Entry};
let tree = menus::menu_tree_named(self.app.session.prefs.font_names_in_english);
let (_, items) = tree.iter().find(|(title, _)| *title == root).unwrap();
let labels: Vec<_> = items
.iter()
.filter_map(|item| match menus::entry(&self.app, item)? {
Entry::Sub(label, _) => Some(label.to_string()),
Entry::Item(row) => Some(row.label.to_string()),
_ => None,
})
.take(3)
.collect();
assert!(!labels.is_empty());
for label in labels {
assert!(
self.shown.iter().any(|(text, point)| clean_label(text) == label
&& self.ctx.layer_id_at(*point).is_some_and(|layer| layer.order == egui::Order::Foreground)),
"visible {root} popup must contain {label:?}"
);
}
}
}
#[test]
fn menu_access_all_roots_bare_alt_and_one_existing_command() {
let _global = GlobalState::new();
let mut s = Scene::new();
let before = s.app.session.active().unwrap();
let (doc, selection, undo) = (before.doc.clone(), before.selection.clone(), before.history.undo.len());
s.bare_alt();
let roots = [
("File", 'F'),
("Edit", 'E'),
("Object", 'O'),
("Type", 'T'),
("Select", 'S'),
("Effect", 'C'),
("View", 'V'),
("Window", 'W'),
("Help", 'H'),
];
let cues = s.cues();
for (label, letter) in roots {
assert!(cues.iter().any(|c| !c.popup && c.label == label && c.character.eq_ignore_ascii_case(&letter)), "painted root cue {label}/{letter}");
}
s.bare_alt();
assert!(!s.cues().iter().any(|c| roots.iter().any(|(title, _)| c.label == *title)));
for (title, _) in roots {
s.root(title);
s.assert_root_contents(title);
s.end_access();
}
let rulers = s.app.ui.view.rulers;
s.command_from_menu("view.rulers");
assert_eq!(s.app.ui.view.rulers, !rulers, "one menu activation toggles once");
s.settle();
assert_eq!(s.app.ui.view.rulers, !rulers, "idle passes cannot repeat the command");
let after = s.app.session.active().unwrap();
assert_eq!(after.doc, doc);
assert_eq!(after.selection, selection);
assert_eq!(after.history.undo.len(), undo);
}
#[test]
fn menu_access_localized_latin_and_cyrillic_painted_text_pairs() {
let _global = GlobalState::new();
let mut s = Scene::new();
for (locale, expected) in [("fr", "Fichier"), ("ru", "Файл")] {
s.app.run("app.language", json!({"lang": locale})).unwrap();
i18n::set_current(i18n::Lang::from_code(locale).unwrap());
s.settle();
assert_eq!(s.app.session.prefs.interface_language, locale);
assert_eq!(s.app.ui_language().code(), locale);
s.bare_alt();
let cues = s.cues();
let cue = cues
.iter()
.find(|c| !c.popup && c.label == expected)
.unwrap_or_else(|| panic!("translated {locale} File root {expected:?} has no visible cue: {cues:?}; {}", s.menu_diagnostic()));
assert!(expected.chars().any(|c| c.to_lowercase().eq(cue.character.to_lowercase())), "cue is an actual translated character");
let text = cue.character.to_lowercase().collect::<String>();
// Standard Russian physical positions send these Latin Key values with Cyrillic Text.
// Inter's bundled cmap contains every glyph of Файл; no substituted ASCII label is used.
let key = if locale == "ru" {
match text.as_str() {
"ф" => Key::A,
"а" => Key::F,
"й" => Key::Q,
"л" => Key::K,
_ => panic!("unexpected File cue {text}"),
}
} else {
Key::from_name(&text.to_uppercase()).unwrap()
};
s.letter(key, &text, Modifiers::NONE);
s.settle();
s.assert_root_contents("File");
// Escape must end localized navigation too, independently of English labels.
for _ in 0..3 {
s.arrow(Key::Escape);
}
s.settle();
assert!(!egui::Popup::is_any_open(&s.ctx));
assert!(s.app.ui.dialog.is_none(), "one Text/Key pair opens only the root");
}
}
fn focused_label(s: &Scene, labels: &[&str]) -> Option<String> {
let focused = s.ctx.memory(|m| m.focused())?;
let response = s.ctx.read_response(focused)?;
s.shown
.iter()
.find(|(text, point)| labels.contains(&clean_label(text)) && response.rect.contains(*point))
.map(|(text, _)| clean_label(text).into())
}
#[test]
fn menu_access_disabled_rows_dynamic_collisions_and_deleted_focus() {
let _global = GlobalState::new();
let mut s = Scene::new();
s.app.run("select.set", json!({"ids": []})).unwrap();
let doc = s.app.session.active().unwrap().doc.clone();
s.root("Object");
s.letter(Key::P, "p", Modifiers::NONE);
s.arrow(Key::ArrowRight);
s.letter(Key::O, "o", Modifiers::NONE);
s.settle();
assert!(s.app.ui.dialog.is_none(), "disabled Offset Path cannot be invoked by its access key");
assert_eq!(s.app.session.active().unwrap().doc, doc);
s.end_access();
let first = s.app.run("shape.rectangle", json!({"x": 220, "y": 70, "width": 30, "height": 40})).unwrap()["id"].clone();
s.app.run("select.set", json!({"ids": [first]})).unwrap();
let selection_a = s.app.session.active().unwrap().selection.clone();
s.app.run("select.save", json!({"name": "QQQQ"})).unwrap();
let second = s.app.run("shape.rectangle", json!({"x": 290, "y": 90, "width": 40, "height": 30})).unwrap()["id"].clone();
s.app.run("select.set", json!({"ids": [second]})).unwrap();
let selection_b = s.app.session.active().unwrap().selection.clone();
s.app.run("select.save", json!({"name": "QQQ"})).unwrap();
s.app.run("select.set", json!({"ids": []})).unwrap();
let empty = s.app.session.active().unwrap().selection.clone();
s.root("Select");
let cues = s.cues();
for label in ["QQQQ", "QQQ"] {
assert!(
cues.iter().any(|c| c.popup && c.label == label && c.character.eq_ignore_ascii_case(&'Q')),
"the unavoidable {label} collision is visibly advertised"
);
}
s.letter(Key::Q, "q", Modifiers::NONE);
s.settle();
let first_focus = focused_label(&s, &["QQQQ", "QQQ"]).expect("collision focuses one saved selection");
assert_eq!(s.app.session.active().unwrap().selection, empty, "a collision letter does not execute");
s.letter(Key::Q, "q", Modifiers::NONE);
s.settle();
let next_focus = focused_label(&s, &["QQQQ", "QQQ"]).unwrap();
assert_ne!(first_focus, next_focus, "repeated letter cycles the two real dynamic rows");
s.arrow(Key::Enter);
s.settle();
assert_eq!(s.app.session.active().unwrap().selection, if next_focus == "QQQQ" { selection_a } else { selection_b });
s.app.run("select.set", json!({"ids": []})).unwrap();
s.root("Select");
for _ in 0..2 {
s.letter(Key::Q, "q", Modifiers::NONE);
s.settle();
if focused_label(&s, &["QQQQ", "QQQ"]).as_deref() == Some("QQQQ") {
break;
}
}
assert_eq!(focused_label(&s, &["QQQQ", "QQQ"]).as_deref(), Some("QQQQ"));
s.app.run("select.editSaved", json!({"name": "QQQQ", "delete": true})).unwrap();
s.settle();
assert!(!s.shown.iter().any(|(text, _)| clean_label(text) == "QQQQ"));
s.arrow(Key::Enter);
s.settle();
assert_eq!(s.app.session.active().unwrap().selection, empty, "deleting the focused row cannot invoke the next saved-selection slot");
assert!(s.app.ui.dialog.is_none());
}
fn field_range(s: &Scene, id: egui::Id) -> egui::text::CCursorRange {
egui::TextEdit::load_state(&s.ctx, id).unwrap().cursor.char_range().unwrap()
}
impl Scene {
fn focus_numeric(&mut self) -> egui::Id {
// Unit::format includes its suffix; choose an actual original rectangle field by its number.
let mut candidates: Vec<_> = self
.shown
.iter()
.filter(|(text, _)| text.split_whitespace().next().is_some_and(|number| ["70", "60", "120", "80"].contains(&number)))
.map(|(_, p)| *p)
.collect();
candidates.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)));
candidates.dedup();
for point in candidates {
self.click(point);
if let Some(field) = self.ctx.memory(|m| m.focused()).filter(|id| egui::TextEdit::load_state(&self.ctx, *id).is_some()) {
return field;
}
}
panic!("an actual selected-rectangle numeric field must be focusable");
}
}
#[test]
#[allow(deprecated)] // ImeEvent::Disabled is a supported host cancellation event in this regression.
fn menu_access_real_numeric_field_cancel_and_edit_cut_keep_art_unchanged() {
let _global = GlobalState::new();
{
let mut ime = Scene::new();
ime.focus_numeric();
ime.frame(vec![Event::Ime(egui::ImeEvent::Preedit { text: "ф".into(), active_range_chars: Some(0..1) })]);
ime.bare_alt();
assert!(!ime.cues().iter().any(|c| !c.popup && c.label == "File"), "active composition keeps Alt ownership");
ime.frame(vec![Event::Ime(egui::ImeEvent::Disabled)]);
ime.settle();
ime.root("Object");
ime.letter(Key::P, "p", Modifiers::NONE);
ime.arrow(Key::ArrowRight);
ime.letter(Key::O, "o", Modifiers::NONE);
ime.settle();
ime.assert_offset_dialog(); // No Commit was sent: terminal cancellation really releases the latch.
}
let mut s = Scene::new();
// These are the original rectangle's actual Transform/Control numeric fields, not a test UI.
let field = s.focus_numeric();
s.arrow(Key::Home);
s.arrow(Key::ArrowRight);
let caret = field_range(&s, field);
assert!(caret.is_empty());
let state = s.app.session.active().unwrap();
let (doc, selection, undo) = (state.doc.clone(), state.selection.clone(), state.history.undo.len());
s.bare_alt();
s.arrow(Key::Escape);
s.settle();
assert_eq!(s.ctx.memory(|m| m.focused()), Some(field), "cancelling access mode restores the former field");
assert_eq!(field_range(&s, field), caret, "the original caret is restored too");
s.bare_alt();
let altgr = Modifiers { ctrl: true, alt: true, ..Modifiers::NONE };
s.frame(vec![Event::ModifiersChanged(altgr), Event::Text("ø".into())]);
s.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]);
s.settle();
assert_eq!(s.ctx.memory(|m| m.focused()), Some(field), "Text-only AltGr restores the original field before delivery");
assert_eq!(field_range(&s, field).primary.index, caret.primary.index + 1, "the actual field receives the Unicode Text event without a Key event");
assert!(!s.cues().iter().any(|c| !c.popup && c.label == "File"), "AltGr cancels active menu mode");
s.arrow(Key::Home);
s.frame(vec![Event::ModifiersChanged(Modifiers::SHIFT), key(Key::End, true, Modifiers::SHIFT)]);
s.frame(vec![key(Key::End, false, Modifiers::SHIFT), Event::ModifiersChanged(Modifiers::NONE)]);
assert!(!field_range(&s, field).is_empty());
s.command_from_menu("edit.cut");
s.settle();
assert_eq!(s.ctx.memory(|m| m.focused()), Some(field), "Edit Cut is delivered to the original field");
let cut = field_range(&s, field);
assert_eq!(
(cut.primary.index, cut.secondary.index),
(egui::text::CharIndex::ZERO, egui::text::CharIndex::ZERO),
"the selected numeric text was cut"
);
let state = s.app.session.active().unwrap();
assert_eq!(state.doc, doc, "cutting uncommitted field text must not cut selected artwork");
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
s.letter(Key::Num9, "9", Modifiers::NONE);
s.letter(Key::Num5, "5", Modifiers::NONE);
assert_eq!(field_range(&s, field).primary.index, egui::text::CharIndex(2), "normal Text/Key input resumes in the same field after menu editing");
}
struct KeymapRestore(vectorcraft_ui_egui::UiState);
impl Drop for KeymapRestore {
fn drop(&mut self) {
vectorcraft_ui_egui::shortcut_editor::sync(&self.0);
}
}
#[test]
fn menu_access_custom_shortcut_typing_tool_altgr_and_cancel_ownership() {
let _global = GlobalState::new();
let mut s = Scene::new();
let _restore = KeymapRestore(s.app.ui.clone());
let rulers = s.app.ui.view.rulers;
s.app.run("shortcuts.set", json!({"id": "view.rulers", "shortcut": "Alt+O"})).unwrap();
s.root("Object");
let once = s.app.ui.view.rulers;
let open = egui::Popup::is_any_open(&s.ctx);
s.app.run("shortcuts.set", json!({"id": "view.rulers", "shortcut": null})).unwrap();
assert_eq!(once, !rulers, "the user's existing Alt+O shortcut wins");
assert!(!open, "the same chord must not also arm Object");
s.letter(Key::P, "p", Modifiers::NONE);
assert_eq!(s.app.session.tool_id(), "pen", "ordinary typing tool shortcut still works");
s.app.select_tool("selection");
let altgr = Modifiers { ctrl: true, alt: true, ..Modifiers::NONE };
s.frame(vec![Event::ModifiersChanged(altgr)]);
s.letter(Key::O, "ø", altgr);
s.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]);
s.settle();
assert!(!egui::Popup::is_any_open(&s.ctx));
assert!(!s.cues().iter().any(|c| !c.popup && c.label == "Object"), "Ctrl+Alt/AltGr does not become bare Alt navigation");
s.bare_alt();
s.window_focus(false);
s.window_focus(true);
s.settle();
assert!(!s.cues().iter().any(|c| !c.popup && c.label == "File"), "window focus loss cancels access mode");
s.bare_alt();
s.click(Pos2::new(1000.0, 850.0));
assert!(!s.cues().iter().any(|c| !c.popup && c.label == "File"), "an outside pointer click cancels access mode");
for key_id in [Key::Tab, Key::Space] {
s.frame(vec![Event::ModifiersChanged(Modifiers::ALT), key(key_id, true, Modifiers::ALT)]);
s.frame(vec![key(key_id, false, Modifiers::ALT), Event::ModifiersChanged(Modifiers::NONE)]);
s.settle();
assert!(!s.cues().iter().any(|c| !c.popup && c.label == "File"), "Alt+Tab/Space does not become an unused Alt release");
}
s.app.select_tool("rectangle");
// Ordinary points inside the wide fixture's real central canvas: use the actual App pointer
// route, with a busy-tool precondition, rather than merely selecting an idle tool.
let (start, end) = (Pos2::new(600.0, 500.0), Pos2::new(650.0, 540.0));
s.frame(vec![
Event::ModifiersChanged(Modifiers::ALT),
Event::PointerMoved(start),
Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT },
]);
s.frame(vec![Event::PointerMoved(end)]);
assert!(s.app.session.tool_busy(), "the actual rectangle drag must have started");
s.bare_alt();
assert_eq!(s.app.session.tool_id(), "rectangle");
assert!(s.app.session.tool_busy(), "Alt access cannot finish or replace the active gesture");
assert!(!s.cues().iter().any(|c| !c.popup && c.label == "File"));
s.frame(vec![Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]);
s.settle();
assert!(!s.app.session.tool_busy(), "normal pointer release completes the same gesture");
assert!(!s.cues().iter().any(|c| !c.popup && c.label == "File"), "using Alt with the pointer cannot arm a later unused-Alt release");
s.app.select_tool("selection");
s.app.run("select.all", json!({})).unwrap();
s.command_from_menu("object.path.offsetPath");
s.assert_offset_dialog();
s.root("Edit");
assert_eq!(s.app.ui.dialog.as_ref().unwrap().kind, "offsetPath", "an existing modal dialog keeps keyboard ownership");
assert!(!s.cues().iter().any(|c| !c.popup && c.label == "Edit"));
}
#[test]
fn menu_access_stationary_pointer_repeat_and_rerun_do_not_retarget_or_double_invoke() {
let _global = GlobalState::new();
let mut s = Scene::new();
let object = s.point("Object", false);
s.frame(vec![Event::PointerMoved(object)]);
s.root("File");
s.assert_root_contents("File");
s.settle();
s.assert_root_contents("File");
s.frame(vec![Event::PointerMoved(s.point("Edit", false))]);
s.settle();
s.assert_root_contents("Edit");
s.end_access();
s.frame(vec![Event::PointerGone]);
s.root("Object");
s.frame(vec![
Event::ModifiersChanged(Modifiers::ALT),
Event::Key { key: Key::O, physical_key: Some(Key::O), pressed: true, repeat: true, modifiers: Modifiers::ALT },
Event::Text("o".into()),
]);
s.frame(vec![key(Key::O, false, Modifiers::ALT), Event::ModifiersChanged(Modifiers::NONE)]);
s.settle();
s.assert_root_contents("Object");
s.end_access();
let entries = vectorcraft_ui_egui::menus::menu_entries(&s.app);
let row = entries.iter().find(|e| e.command.as_deref() == Some("view.rulers")).unwrap();
let (path, label) = (row.path.clone(), row.label.clone());
s.root(&path[0]);
for submenu in path.iter().skip(1) {
s.advertised(submenu, false);
s.arrow(Key::ArrowRight);
s.settle();
}
let cues = s.cues();
let cue = cues
.iter()
.find(|c| c.popup && c.label == label)
.unwrap_or_else(|| panic!("rerun command {label:?} has no painted cue: {cues:?}; {}", s.menu_diagnostic()));
let text = cue.character.to_lowercase().collect::<String>();
let key_id = Key::from_name(&text.to_uppercase()).unwrap();
let before = s.app.ui.view.rulers;
s.time += 1.0 / 30.0;
let mut raw = RawInput {
time: Some(s.time),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 1000.0))),
events: vec![Event::ModifiersChanged(Modifiers::NONE), key(key_id, true, Modifiers::NONE), Event::Text(text)],
..Default::default()
};
s.app.raw_input_hook(&s.ctx, &mut raw);
let mut passes = 0;
let mut out = s.ctx.run_ui(raw, |ui| {
passes += 1;
s.app.ui(ui);
if passes == 1 {
ui.ctx().request_discard("exercise the real App's once-per-frame menu input");
}
});
out.textures_delta.clear();
s.frame(vec![key(key_id, false, Modifiers::NONE)]);
s.settle();
assert!(passes >= 2, "the test must actually exercise a UI rerun");
assert_eq!(s.app.ui.view.rulers, !before, "one Text/Key pair invokes exactly once across passes");
s.end_access();
let text = s.app.run("text.create", json!({"x": 250, "y": 200, "text": "Menu", "font": "Inter", "size": 12})).unwrap()["id"].clone();
s.app.run("select.set", json!({"ids": [text]})).unwrap();
let size = vec2(640.0, 420.0);
for _ in 0..4 {
s.at_size(vec![], size);
}
s.at_size(vec![Event::ModifiersChanged(Modifiers::ALT), key(Key::T, true, Modifiers::ALT), Event::Text("t".into())], size);
s.at_size(vec![key(Key::T, false, Modifiers::ALT), Event::ModifiersChanged(Modifiers::NONE)], size);
let cues = s.at_size(vec![], size);
let font = cues.iter().find(|c| c.popup && c.label == "Font").expect("narrow Type menu exposes its Font submenu");
let letter = font.character.to_lowercase().collect::<String>();
let font_key = Key::from_name(&letter.to_uppercase()).unwrap();
s.at_size(vec![key(font_key, true, Modifiers::NONE), Event::Text(letter)], size);
s.at_size(vec![key(font_key, false, Modifiers::NONE)], size);
s.at_size(vec![key(Key::ArrowRight, true, Modifiers::NONE)], size);
s.at_size(vec![key(Key::ArrowRight, false, Modifiers::NONE)], size);
let entries = vectorcraft_ui_egui::menus::menu_entries(&s.app);
let font_labels: Vec<_> = entries
.iter()
.filter(|e| {
e.path.first().is_some_and(|p| p == "Type") && e.path.iter().any(|p| p == "Font") && e.command.as_deref() == Some("text.setStyle")
})
.map(|e| e.label.clone())
.collect();
assert!(font_labels.len() > 20, "the inherited bundled font fixture must produce a genuinely long submenu");
let first = s.ctx.memory(|m| m.focused()).expect("Font navigation has a genuine focused menu response");
let viewport = Rect::from_min_size(Pos2::ZERO, size);
// Right can leave global focus on the Font parent until native Down navigation enters its
// children. Locate the pointer from an actually painted family cue instead of that parent.
let family_cues = s.at_size(vec![], size);
let (pointer_family, pointer, wheel_layer) = s
.shown
.iter()
.filter_map(|(text, point)| {
let label = clean_label(text);
if !font_labels.iter().any(|family| family == label) || !family_cues.iter().any(|cue| cue.popup && cue.label == label) {
return None;
}
let layer = s.ctx.layer_id_at(*point)?;
(layer.order == egui::Order::Foreground).then_some((label.to_owned(), *point, layer))
})
.min_by(|a, b| a.1.y.total_cmp(&b.1.y).then(a.1.x.total_cmp(&b.1.x)))
.unwrap_or_else(|| panic!("wheel precondition requires an actual painted Font family: {family_cues:?}; {}", s.menu_diagnostic()));
assert!(
viewport.contains(pointer) && s.ctx.layer_id_at(pointer) == Some(wheel_layer),
"wheel point for {pointer_family:?} is inside the actual visible Font popup"
);
s.at_size(vec![Event::PointerMoved(pointer)], size);
let focus_before_rearm = s.ctx.memory(|m| m.focused());
// Movement alone already gives the old implementation pointer ownership. A real navigation
// key must re-arm keyboard ownership with that pointer stationary INSIDE the same popup.
s.at_size(vec![key(Key::ArrowDown, true, Modifiers::NONE)], size);
s.at_size(vec![key(Key::ArrowDown, false, Modifiers::NONE)], size);
s.at_size(vec![], size);
let rearmed_focus = s.ctx.memory(|m| m.focused()).expect("real Down navigation retains menu focus");
assert_ne!(Some(rearmed_focus), focus_before_rearm, "the real re-arming Down press advances Font focus before the wheel");
let rearmed_row = s.ctx.read_response(rearmed_focus).unwrap();
assert!(
s.shown.iter().any(|(text, point)| font_labels.contains(&clean_label(text).to_owned())
&& rearmed_row.rect.contains(*point)
&& s.ctx.layer_id_at(*point) == Some(wheel_layer)),
"re-armed keyboard focus remains on a visible Font family in the same popup"
);
assert_eq!(s.ctx.pointer_hover_pos(), Some(pointer));
assert_eq!(s.ctx.layer_id_at(pointer), Some(wheel_layer));
let top_family = |scene: &Scene, labels: &[String]| {
scene
.shown
.iter()
.filter(|(text, point)| labels.contains(&clean_label(text).to_owned()) && scene.ctx.layer_id_at(*point) == Some(wheel_layer))
.map(|(text, point)| (clean_label(text).to_owned(), *point))
.min_by(|a, b| a.1.y.total_cmp(&b.1.y).then(a.1.x.total_cmp(&b.1.x)))
.expect("the real Font popup has a visible top family")
};
let wheel_top_before = top_family(&s, &font_labels);
let wheel_state = s.app.session.active().unwrap();
let (wheel_doc, wheel_selection, wheel_history) =
(wheel_state.doc.clone(), wheel_state.selection.clone(), (wheel_state.history.undo.len(), wheel_state.history.redo.len()));
s.at_size(
vec![Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: vec2(0.0, -80.0),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
modifiers: Modifiers::NONE,
}],
size,
);
for _ in 0..10 {
s.at_size(vec![], size);
}
let wheel_top_after = top_family(&s, &font_labels);
let before_index = font_labels.iter().position(|label| label == &wheel_top_before.0).unwrap();
let after_index = font_labels.iter().position(|label| label == &wheel_top_after.0).unwrap();
assert!(
after_index > before_index || (wheel_top_after.0 == wheel_top_before.0 && wheel_top_after.1.y < wheel_top_before.1.y - 1.0),
"stationary raw wheel must scroll the real Font list after keyboard navigation: before={wheel_top_before:?}, after={wheel_top_after:?}"
);
assert!(s.app.ui.dialog.is_none(), "wheel scroll cannot invoke a menu command");
let wheel_state = s.app.session.active().unwrap();
assert_eq!(wheel_state.doc, wheel_doc);
assert_eq!(wheel_state.selection, wheel_selection);
assert_eq!((wheel_state.history.undo.len(), wheel_state.history.redo.len()), wheel_history);
for _ in 0..20 {
s.at_size(vec![key(Key::ArrowDown, true, Modifiers::NONE)], size);
s.at_size(vec![key(Key::ArrowDown, false, Modifiers::NONE)], size);
}
let focus_before_settle = s.ctx.memory(|m| m.focused()).unwrap();
// The normal scroll animation can take 0.3s. Keep the actual narrow viewport while it settles.
for _ in 0..10 {
s.at_size(vec![], size);
}
let cues = s.at_size(vec![], size);
let focus = s.ctx.memory(|m| m.focused()).unwrap();
assert_eq!(focus, focus_before_settle, "settling scrolling must not change the chosen Font row");
assert_ne!(focus, first, "normal Down navigation advances through the long submenu");
// An installed-font scan can finish while the menu is open; compare with its current rows.
let entries = vectorcraft_ui_egui::menus::menu_entries(&s.app);
let font_labels: Vec<_> = entries
.iter()
.filter(|e| {
e.path.first().is_some_and(|p| p == "Type") && e.path.iter().any(|p| p == "Font") && e.command.as_deref() == Some("text.setStyle")
})
.map(|e| e.label.clone())
.collect();
let response = s.ctx.read_response(focus).unwrap();
let viewport = Rect::from_min_size(Pos2::ZERO, size);
assert!(
viewport.contains(response.rect.center()),
"the focused row must scroll into the actual narrow viewport: focus={focus:?}, rect={:?}, viewport={viewport:?}, visible_fonts={:?}",
response.rect,
s.shown.iter().filter(|(text, _)| font_labels.contains(&clean_label(text).to_owned())).take(8).collect::<Vec<_>>()
);
assert!(
cues.iter().any(|c| c.popup
&& font_labels.contains(&c.label)
&& s.shown.iter().any(|(text, point)| clean_label(text) == c.label && response.rect.contains(*point))),
"the scrolled focused Font row retains a visible painted access cue"
);
}
/// The reported Select menu letters use the actual name/list dialog routes,
/// with no document edit before a normal dialog confirmation.
#[test]
fn menu_access_select_save_and_edit_use_reported_letters() {
let _global = GlobalState::new();
let mut s = Scene::new();
let before = s.app.session.active().unwrap();
let (doc, selection) = (before.doc.clone(), before.selection.clone());
let history = (before.history.undo.len(), before.history.redo.len());
s.root("Select");
s.letter(Key::S, "s", Modifiers::NONE);
s.settle();
let dialog = s.app.ui.dialog.as_ref().expect("Alt+S then S must open Save Selection, not focus Same");
assert_eq!(dialog.kind, "command");
assert_eq!(dialog.str("__command"), "select.save");
assert_eq!(dialog.str("__label"), "Save Selection");
assert_eq!(dialog.str("name"), "Selection 1");
assert!(s.shown.iter().any(|(text, _)| text == "Save Selection"), "the real naming dialog must be drawn");
let after = s.app.session.active().unwrap();
assert_eq!(after.doc, doc, "opening Save Selection does not edit art or saved selections");
assert_eq!(after.selection, selection);
assert_eq!((after.history.undo.len(), after.history.redo.len()), history);
vectorcraft_ui_egui::dialogs::cancel(&mut s.app);
s.settle();
s.end_access();
assert!(s.app.ui.dialog.is_none());
let after_cancel = s.app.session.active().unwrap();
assert_eq!(after_cancel.doc, doc);
assert_eq!(after_cancel.selection, selection);
assert_eq!((after_cancel.history.undo.len(), after_cancel.history.redo.len()), history);
// Edit Selection is enabled only after a real saved selection exists.
// This command is setup, never a substitute for the observed E invocation.
s.app.run("select.save", json!({"name": "Access Keys Selection"})).unwrap();
s.settle();
let before = s.app.session.active().unwrap();
let (doc, selection) = (before.doc.clone(), before.selection.clone());
let history = (before.history.undo.len(), before.history.redo.len());
s.root("Select");
s.letter(Key::E, "e", Modifiers::NONE);
s.settle();
let dialog = s.app.ui.dialog.as_ref().expect("Alt+S then E must open Edit Selection");
assert_eq!(dialog.kind, "editSelection");
assert_eq!(dialog.fields["count"].as_u64(), Some(1));
assert_eq!(dialog.str("orig0"), "Access Keys Selection");
assert!(s.shown.iter().any(|(text, _)| text == "Edit Selection"), "the real saved-selection list must be drawn");
let after = s.app.session.active().unwrap();
assert_eq!(after.doc, doc, "opening Edit Selection does not rename or delete a saved selection");
assert_eq!(after.selection, selection);
assert_eq!((after.history.undo.len(), after.history.redo.len()), history);
vectorcraft_ui_egui::dialogs::cancel(&mut s.app);
s.settle();
s.end_access();
assert!(s.app.ui.dialog.is_none());
let after_cancel = s.app.session.active().unwrap();
assert_eq!(after_cancel.doc, doc);
assert_eq!(after_cancel.selection, selection);
assert_eq!((after_cancel.history.undo.len(), after_cancel.history.redo.len()), history);
}