Merge pull request #8210 from dotCooCoo/feat/palette-dimmed-rows

Command Palette: commands that cannot run now are dimmed
This commit is contained in:
BFlat
2026-11-20 05:10:21 +07:00
committed by GitHub
5 changed files with 654 additions and 65 deletions
+1
View File
@@ -82,6 +82,7 @@ pub use run::{check_params, run_ui_command};
pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number};
#[cfg(test)]
use slots::RECENT_FONT_IDS;
pub(crate) use state::why_off;
pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state};
pub(crate) use submenus::PATH_EFFECTS;
pub(crate) use tree::arrange_documents_items;
+22 -5
View File
@@ -216,22 +216,39 @@ pub(super) fn has_subject(app: &VectorcraftApp) -> bool {
/// Can command `id` run now? An engine command asks the engine, a UI command the app's state;
/// none that would act on text an input method is still composing.
pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
why_off(app, id).is_none()
}
/// Why command `id` can't run now ([`enabled`]): `None` while it can, else `Some` with the
/// engine's reason when the engine's check of an engine command fails. The engine's check runs at
/// most once.
pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option<Option<String>> {
if waits_for_ime(app, id) {
return false;
return Some(None);
}
if SUBJECT_COMMANDS.contains(&id) {
return has_subject(app);
return (!has_subject(app)).then_some(None);
}
// The Artboard tool's canvas menu measured this when it opened.
if id == "artboard.deleteEmpty"
&& let Some(facts) = crate::panels::artboards::open_menu_facts(app)
{
return facts.any_empty;
return (!facts.any_empty).then_some(None);
}
if let Some(c) = vectorcraft_engine::find_command(id) {
// The system clipboard's contents can be pasted with an empty internal clipboard.
return (c.enabled)(&app.session).is_ok() || app.system_paste && id.starts_with("edit.paste");
return match (c.enabled)(&app.session) {
Ok(()) => None,
// The system clipboard's contents can be pasted into an open document with an empty
// internal clipboard.
Err(_) if app.system_paste && app.session.active().is_some() && id.starts_with("edit.paste") => None,
Err(why) => Some(Some(why)),
};
}
(!ui_enabled(app, id)).then_some(None)
}
/// Can UI command `id` run now?
fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
match id {
// Save is off for a clean document that already has its own file.
"file.save" => app.session.active().is_some_and(|d| d.path.is_none() || d.converted || d.is_dirty()),
+604 -50
View File
@@ -442,9 +442,10 @@ fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec<Entry> {
/// Runs the palette result `id`: selects a tool, or invokes a command with the params its entry
/// stands for. A command whose menu bar item gives params runs what a click on that item runs
/// ([`crate::shortcut_editor::menu_target_now`]), so Clean Up… and Find and Replace… open their
/// dialogs. While that item is dimmed, no dialog opens and the status line says why the command
/// can't run. A panel's result shows the panel, and an effect's result runs what its Effect menu
/// item runs ([`crate::keymap::command_of`]). Returns what the pick did.
/// dialogs. While a result is dimmed ([`unavailable`]), its pick runs nothing, opens no dialog or
/// panel, and the status line says why the command can't run. A panel's result shows the panel,
/// and an effect's result runs what its Effect menu item runs ([`crate::keymap::command_of`]).
/// Returns what the pick did.
pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) -> Picked {
let had_dialog = app.ui.dialog.is_some();
let ran = if let Some(tool) = id.strip_prefix("tool:") {
@@ -470,17 +471,15 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) -> Picked {
}
} else if id.starts_with("plugin:") || id.starts_with("effect:") {
let command = crate::keymap::command_of(id);
let on = menus::enabled(app, &command.id);
// While the Effect menu dims the item (nothing selected), no dialog opens and the status
// line says why.
if id.starts_with("effect:") && !on {
if let Err(why) = crate::shortcut_editor::dimmed(app, &command.id) {
app.status(why);
}
// While the item is dimmed (an effect with nothing selected), no dialog opens and the
// status line says why.
if let Some(why) = crate::shortcut_editor::dimmed(app, &command.id, &command.id) {
app.status(why);
false
} else {
menus::invoke(app, &command.id, command.params);
true
}
on
} else {
match crate::shortcut_editor::menu_target_now(app, id) {
Some(Ok((id, p))) => {
@@ -491,13 +490,18 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) -> Picked {
app.status(why);
false
}
None => {
// The command is invoked while its menu item is dimmed too, and its own check
// reports why it can't run.
let on = menus::enabled(app, id);
menus::invoke(app, id, json!({}));
on
}
// A dimmed result does not run: the Asset Export commands with no document open show
// no panel.
None => match crate::shortcut_editor::dimmed(app, id, id) {
Some(why) => {
app.status(why);
false
}
None => {
menus::invoke(app, id, json!({}));
true
}
},
}
};
// A dimmed command that still opens its dialog counts as opening it.
@@ -522,6 +526,79 @@ pub(crate) enum Picked {
Refused,
}
/// Why the result `id`, shown as `name`, can't run now, as an English status message, or `None`
/// while it can: the status line a pick of its dimmed menu item gives
/// ([`crate::shortcut_editor::dimmed`]), with the engine's reason when it gives one and `name` in
/// place of the command's id. A panel can't be shown in Presentation Mode, a tool can always be
/// chosen, and every other result asks about the command its pick runs.
fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option<String> {
if id.starts_with("tool:") {
return None;
}
if id.starts_with("panel:") && app.ui.screen_mode >= 3 {
return Some("panels can't be shown in Presentation Mode".to_string());
}
// The command the pick runs.
let id = if id.starts_with("panel:") || id.starts_with("plugin:") || id.starts_with("effect:") {
crate::keymap::command_of(id).id
} else {
id.to_string()
};
crate::shortcut_editor::dimmed(app, &id, name)
}
/// The drawn results' [`unavailable`] answers for the state `key` ([`availability_key`]) they were
/// read in. An engine check can take tens of milliseconds on a large selection, so each result is
/// asked once per state instead of on every frame.
#[derive(Clone, Default)]
struct Availability {
key: u64,
/// Each asked result's answer: why it can't run now, in English, or `None` while it can.
known: std::collections::HashMap<String, Option<String>>,
/// How many results were asked since the key was set.
#[cfg(test)]
asked: usize,
}
impl Availability {
/// Why the result `e` can't run now, in the interface language, or `None` while it can.
fn why(&mut self, app: &VectorcraftApp, e: &Entry) -> Option<String> {
let why = match self.known.get(&e.id) {
Some(why) => why.clone(),
None => {
#[cfg(test)]
{
self.asked += 1;
}
let why = unavailable(app, &e.id, &e.shown);
self.known.insert(e.id.clone(), why.clone());
why
}
};
why.map(|why| crate::i18n::msg(&why))
}
}
/// What the results' availability depends on: what the native menu bar's rows depend on
/// ([`crate::native_menu::state_hash`]: commands run, the document's revision, selection, history
/// and clipboard, the language and more), whether the document has unsaved changes, the screen
/// mode, an open dialog, and the background saves and exports, file reads, plug-in runs and traces
/// that run or show their progress. A click asks again for what it leaves out (a panel shown, a
/// tool chosen) without changing it ([`show`]); typing in the search field does not.
fn availability_key(app: &VectorcraftApp) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
crate::native_menu::state_hash(app, None).hash(&mut h);
let running = app.background.jobs.iter().filter(|j| j.progress.is_some() && !j.cancelled()).count();
(app.ui.screen_mode, app.ui.dialog.is_some(), app.background.jobs.len(), running).hash(&mut h);
(app.opening.pending.len(), crate::opening::any_shown(app)).hash(&mut h);
// A background save marks the document saved without a new revision.
app.session.active().map(|d| (d.path.is_some(), d.converted, d.is_dirty())).hash(&mut h);
let plugins = (crate::plugin_runs::any_running(app), crate::plugin_runs::any_shown(app));
(plugins, crate::trace_runs::any_running(app), crate::trace_runs::any_shown(app)).hash(&mut h);
h.finish()
}
/// The entries the query `q` matches, best first ([`search::rank`]), with the commands picked most
/// often (`uses`) first among the entries that match as well, and then the picks that Recent
/// Commands lists for the ids `recent_ids` ([`recent`]). The ranking of the last query is kept, so
@@ -1221,6 +1298,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let focus_id = egui::Id::unique("palette-focus-before");
let field_id = egui::Id::unique("palette-field");
let sel_id = egui::Id::unique("palette-selected");
let availability_id = egui::Id::unique("palette-availability");
// A toggle can close the palette and open it again before it is drawn closed, as two runs of its
// command in one step do, so the palette forgets its highlight after any toggle.
if std::mem::take(&mut app.ui.palette_toggled) {
@@ -1243,9 +1321,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
if !app.ui.palette_open {
// The palette opens again with its first row highlighted and its list scrolled to the top
// (a list height of 0 scrolls it to the highlighted row).
// (a list height of 0 scrolls it to the highlighted row), and asks its results again
// whether they can run.
let (field, rows) = ctx.data_mut(|d| {
d.remove::<Highlight>(sel_id);
d.remove::<Availability>(availability_id);
let field = d.get_temp::<egui::Id>(field_id);
d.remove::<egui::Id>(field_id);
let rows = d.get_temp::<Vec<egui::Id>>(rows_id).unwrap_or_default();
@@ -1348,6 +1428,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
});
}
let screen = ctx.content_rect();
// The drawn results' availability, kept while the state it was read in lasts. A frame with a
// pointer button release asks again, once, for what the state leaves out.
let key = availability_key(app);
let mut availability = ctx
.data_mut(|d| d.remove_temp::<Availability>(availability_id))
.filter(|a| a.key == key)
.unwrap_or_else(|| Availability { key, ..Default::default() });
if ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. }))) {
availability.known.clear();
}
// The highlighted result the rows and the field's description are drawn with.
let mut drawn = sel;
// The control that shows where the highlighted result lives, the callout's text, and how the
@@ -1394,7 +1484,25 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
ui.add_enabled(false, egui::Button::new(tl!("No recent commands")));
}
for (i, e) in recent.iter().enumerate() {
let row = ui.add(egui::Button::new(e.shown.as_str()).shortcut_text(menus::shown_shortcut(&e.shortcut)));
// A pick that can't run now is drawn dimmed, as in the results, and says
// why on hover and to screen readers; it can still be chosen.
let why = availability.why(app, e);
let (name, shortcut) = (egui::RichText::new(e.shown.as_str()), egui::RichText::new(menus::shown_shortcut(&e.shortcut)));
let (name, shortcut) = match why {
Some(_) => (name.color(t.text_disabled), shortcut.color(t.text_disabled)),
None => (name, shortcut),
};
let row = ui.add(egui::Button::new(name).shortcut_text(shortcut));
ui.ctx().accesskit_node_builder(row.id, |node| {
if let Some(why) = &why {
node.set_disabled();
node.set_description(why.clone());
}
});
let row = match why {
Some(why) => row.on_hover_text(why),
None => row,
};
rows.push(row.id);
if i == rsel {
row.request_focus();
@@ -1428,14 +1536,18 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
// keep the highlighted result in view.
let resized = (view - last_view).abs() > 0.5;
// Screen readers stay on the field: its description names the highlighted result and
// its place among every match, as the footer counts them.
// its place among every match, as the footer counts them, and on a second line why it
// can't run now when it can't.
let mut described = None;
if let Some(e) = matches.get(sel) {
let rank = if sel + 1 == matches.len() { kept.unwrap_or(sel) } else { sel };
let pos = (rank + 1).to_string();
let of = total.to_string();
let name = row_label(e, &home_text(app, e));
let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &name)]);
let mut said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &name)]);
if let Some(why) = availability.why(app, e) {
said = format!("{said}\n{why}");
}
described = Some(said.clone());
ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said));
}
@@ -1459,32 +1571,46 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
if on {
ui.painter().rect_filled(rect, 4.0, ui.visuals().selection.bg_fill);
}
// A result that can't run now stays in its place, drawn dimmed, and says
// why on hover and to screen readers.
let why = availability.why(app, e);
let (name_color, shortcut_color) = if why.is_some() { (t.text_disabled, t.text_disabled) } else { (t.text, t.text_dim) };
let font = egui::TextStyle::Body.resolve(ui.style());
let shortcut = menus::shown_shortcut(&e.shortcut);
let home = home_text(app, e);
let said = row_label(e, &home);
let p = ui.painter();
let shortcut_at = rect.right_center() - egui::vec2(8.0, 0.0);
let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), t.text_dim);
let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), shortcut_color);
let name_end = if shortcut.is_empty() { rect.right() - 8.0 } else { used.left() - 12.0 };
let icon = egui::Rect::from_center_size(
egui::pos2(rect.left() + 8.0 + KIND_ICON / 2.0, rect.center().y),
egui::Vec2::splat(KIND_ICON),
);
crate::icons::paint(ui, kind_of(e).0, icon, t.icon);
crate::icons::paint(ui, kind_of(e).0, icon, if why.is_some() { t.text_disabled } else { t.icon });
let name_at = icon.right() + 6.0;
let (label, home, cut) = row_galleys(p, e, &home, font, t.text, t.text_dim, name_end - name_at);
let home_color = if why.is_some() { t.text_disabled } else { t.text_dim };
let (label, home, cut) = row_galleys(p, e, &home, font, name_color, home_color, name_end - name_at);
let home_at = name_at + label.size().x + 10.0;
p.galley(egui::pos2(name_at, rect.center().y - label.size().y / 2.0), label, t.text);
p.galley(egui::pos2(name_at, rect.center().y - label.size().y / 2.0), label, name_color);
if let Some(home) = home {
p.galley(egui::pos2(home_at, rect.center().y - home.size().y / 2.0), home, t.text_dim);
p.galley(egui::pos2(home_at, rect.center().y - home.size().y / 2.0), home, home_color);
}
// A row whose text is cut short shows all of it while the pointer rests on it.
let resp = if cut { resp.on_hover_text(said.clone()) } else { resp };
// `WidgetInfo::selected` reaches screen readers as a toggled state, so the
// row sets the selected state on its node itself.
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, said.clone()));
ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(on));
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, why.is_none(), said.clone()));
ui.ctx().accesskit_node_builder(resp.id, |node| {
node.set_selected(on);
if let Some(why) = &why {
node.set_description(why.clone());
}
});
let resp = match why {
Some(why) => resp.on_hover_text(why),
None => resp,
};
if resp.clicked() {
run = Some(e.id.clone());
}
@@ -1499,6 +1625,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
});
}
// While the highlighted result can't run now, the footer also says why, so a keyboard
// user reads it too, in place of the line that names its home.
let why = matches.get(sel).and_then(|e| availability.why(app, e));
// The highlighted result's home, after a pointer or a scroll moved the highlight too. In
// the pass that opens the palette, the menu bar and the toolbars have noted nothing yet,
// and the next pass shows it.
@@ -1520,7 +1649,12 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
&& let Some(said) = &described
&& !said.contains(text.as_str())
{
let said = format!("{said}, {text}");
// The text goes on the first line, before the line that says why the
// result can't run now.
let said = match said.split_once('\n') {
Some((first, why)) => format!("{first}, {text}\n{why}"),
None => format!("{said}, {text}"),
};
ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said));
}
pointed = Some((place, text, how));
@@ -1528,9 +1662,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
Some(Pointer::Footer(text)) => hint = Some(text),
None => {}
}
// Under the recent picks no count is shown, only where the highlighted pick's home is when
// no callout shows it; with no picks, one dimmed line says what a search finds.
if !empty || (n > 0 && hint.is_some()) {
// Under the recent picks no count is shown, only why the highlighted pick can't run now,
// or where its home is when no callout shows it; with no picks, one dimmed line says
// what a search finds.
let line = why.or(hint);
if !empty || (n > 0 && line.is_some()) {
ui.add_space(6.0);
ui.scope(|ui| {
// The footer stays one line of text tall, as the list's height counts it.
@@ -1539,8 +1675,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
if !empty {
ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim));
}
if let Some(hint) = hint {
ui.add(egui::Label::new(egui::RichText::new(hint).color(t.text_dim)).truncate());
if let Some(line) = line {
ui.add(egui::Label::new(egui::RichText::new(line).color(t.text_dim)).truncate());
}
});
});
@@ -1548,12 +1684,20 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
ui.add_space(6.0);
ui.label(egui::RichText::new(tl!("Type to search commands, tools, panels and effects")).color(t.text_dim));
}
if !list_open
&& !history_focused
&& ui.input(|i| i.key_pressed(egui::Key::Enter))
&& let Some(e) = matches.get(sel)
{
run = Some(e.id.clone());
if !list_open && !history_focused && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
// Text typed in the frame that pressed Enter changed the query after the results
// were listed: Enter runs the first result of the new query.
let typed = app.ui.palette_query.to_lowercase();
let picked = if typed == q {
matches.get(sel).copied()
} else if typed.trim().is_empty() {
recent.first().copied()
} else {
matching(&entries, &typed, &app.ui.recent_commands, &app.ui.command_uses).first().copied()
};
if let Some(e) = picked {
run = Some(e.id.clone());
}
}
});
});
@@ -1596,8 +1740,17 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
ctx.request_repaint();
}
let sel_key = matches.get(sel).map(|e| e.id.clone()).unwrap_or_default();
// A palette that closes on this frame forgets its highlight and its answers here, as a closed
// frame does, so a command that opens it again before that frame starts it afresh.
let closing = run.is_some() || outside;
ctx.data_mut(|d| {
d.insert_temp::<Highlight>(sel_id, (sel, q, offset, view, sel_key));
if closing {
d.remove::<Highlight>(sel_id);
d.remove::<Availability>(availability_id);
} else {
d.insert_temp::<Highlight>(sel_id, (sel, q, offset, view, sel_key));
d.insert_temp(availability_id, availability);
}
d.insert_temp(rsel_id, rsel);
});
if let Some(id) = run {
@@ -1795,6 +1948,22 @@ mod tests {
}
}
/// With no document open, the Asset Export commands are dimmed, and a pick of one shows no panel
/// and says why it can't run, as the row's description does.
#[test]
fn a_dimmed_asset_export_command_does_not_open_its_panel() {
let ids = ["assets.export", "assets.remove", "assets.rename", "assets.settings.set", "assets.export3D", "assets.set3DFormat"];
for id in ids {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
let why = unavailable(&app, id, id);
assert!(why.is_some(), "{id} is dimmed with no document open");
app.ui.status.clear();
run_pick(&mut app, id);
assert!(!crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID), "{id}: {}", app.ui.status);
assert_eq!(Some(app.ui.status.clone()), why, "{id}");
}
}
/// The open dialog's kind and fields, the active document's undo depth and the status line.
type Outcome = (Option<(String, serde_json::Map<String, serde_json::Value>)>, Option<usize>, String);
@@ -2238,7 +2407,7 @@ mod tests {
assert_eq!(after.first().map(String::as_str), Some(effect));
assert_eq!(after.get(1).map(String::as_str), Some(tool), "only the pick moves");
let label = open.said(effect);
assert_eq!(field_description(&nodes), format!("1 of {}: {label}", after.len()));
assert_eq!(field_place(&nodes), format!("1 of {}: {label}", after.len()));
open.press(egui::Key::Enter, 1);
assert!(open.app.ui.dialog.is_some(), "Enter ran the effect again: {}", open.app.ui.status);
assert_eq!(open.app.ui.recent_commands, [effect]);
@@ -2568,6 +2737,25 @@ mod tests {
assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]);
}
/// Text typed into an empty search in the frame that presses Enter runs the first result of the
/// new query, not the last pick the empty search listed.
#[test]
fn enter_with_text_typed_in_its_frame_runs_the_new_querys_first_result() {
let mut open = Open::new("", WINDOW);
open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default());
open.app.ui.recent_commands = vec!["paint.swap".into()];
open.app.ui.palette_open = true;
open.frame(vec![]);
open.frame(vec![]);
let entries = entries(&open.ctx, Lang::EN);
let first = super::matching(&entries, "select all", &open.app.ui.recent_commands, &open.app.ui.command_uses)[0].id.clone();
assert_ne!(first, "paint.swap");
let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
open.frame(vec![egui::Event::Text("select all".into()), enter]);
assert!(!open.app.ui.palette_open, "the palette closes");
assert_eq!(open.app.ui.recent_commands.first(), Some(&first), "{}", open.app.ui.status);
}
/// A pick of Clear Recent Commands empties the recent picks without keeping itself, so the
/// empty search then says what to type, and the saved UI state holds an empty list.
#[test]
@@ -2850,6 +3038,27 @@ mod tests {
assert_eq!(open.app.ui.recent_commands, [id, "paint.swap"]);
}
/// A palette closed by a press outside it and opened again before a closed frame is drawn
/// starts with its first row highlighted and asks its results again whether they can run.
#[test]
fn the_palette_opened_again_at_once_after_closing_starts_afresh() {
let mut open = Open::new("", WINDOW);
open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into(), "view.zoomIn".into()];
open.frame(vec![]);
open.press(egui::Key::ArrowDown, 2);
assert_eq!(open.highlighted(), 2);
let at = egui::pos2(2.0, 2.0);
assert!(!open.popup().contains(at), "{at:?} is outside {:?}", open.popup());
let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE };
open.frame(vec![egui::Event::PointerMoved(at), press]);
assert!(!open.app.ui.palette_open, "the press outside closes the palette");
let availability = egui::Id::unique("palette-availability");
assert!(open.ctx.data(|d| d.get_temp::<Availability>(availability)).is_none(), "the answers go when the palette closes");
open.app.ui.palette_open = true;
open.frame(vec![]);
assert_eq!(open.highlighted(), 0, "the first row is highlighted");
}
/// #1757: Up and Down move the highlighted result, wrapping at the ends; a new query starts
/// from the first again.
#[test]
@@ -3333,6 +3542,8 @@ mod tests {
time: f64,
/// Whether the last frame asked for another one at once.
repaint: bool,
/// What the last frame drew.
shapes: Vec<egui::epaint::ClippedShape>,
}
impl Open {
@@ -3346,7 +3557,7 @@ mod tests {
ctx.enable_accesskit();
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx, Default::default());
let mut open = Open { app, ctx, size, time: 0.0, repaint: false };
let mut open = Open { app, ctx, size, time: 0.0, repaint: false, shapes: Vec::new() };
open.frame(vec![]);
open
}
@@ -3360,6 +3571,7 @@ mod tests {
let mut out = self.ctx.run_ui(input, |ui| show(app, ui.ctx()));
out.textures_delta.clear();
self.repaint = out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero());
self.shapes = std::mem::take(&mut out.shapes);
out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default()
}
@@ -3369,6 +3581,18 @@ mod tests {
self.frame(vec![key; times])
}
/// The color the last frame drew the text `text` in.
fn color_of(&self, text: &str) -> Option<egui::Color32> {
fn find(shape: &egui::Shape, text: &str) -> Option<egui::Color32> {
match shape {
egui::Shape::Text(t) if t.galley.text() == text => Some(t.fallback_color),
egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| find(s, text)),
_ => None,
}
}
self.shapes.iter().find_map(|s| find(&s.shape, text))
}
/// The highlighted result's index.
fn highlighted(&self) -> usize {
self.ctx.data(|d| d.get_temp::<Highlight>(egui::Id::unique("palette-selected"))).unwrap().0
@@ -3423,6 +3647,12 @@ mod tests {
field.description().unwrap_or_default().to_string()
}
/// The first line of the search field's description: the highlighted result's place and name,
/// without the reason a result that can't run now adds under it.
fn field_place(nodes: &[egui::accesskit::Node]) -> String {
field_description(nodes).lines().next().unwrap_or_default().to_string()
}
const WINDOW: egui::Vec2 = egui::vec2(1280.0, 900.0);
/// Each result is a 20-point row, rows touch, and 12 show at once; the popup is shorter than
@@ -3669,7 +3899,7 @@ mod tests {
let lit: Vec<String> = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect();
let label = open.said(&listed[3]);
assert_eq!(lit, std::slice::from_ref(&label));
assert_eq!(field_description(&nodes), format!("4 of {}: {label}", matching(&entries, "select", &[]).len()));
assert_eq!(field_place(&nodes), format!("4 of {}: {label}", matching(&entries, "select", &[]).len()));
}
/// A name too long for its row is cut short with "…" and stays inside the width it is given.
@@ -3879,7 +4109,8 @@ mod tests {
assert_eq!(said, "Effect, Round Corners…, Effect › Stylize");
let row = rows(&nodes).into_iter().find(|r| r.0 == said).expect("its row is drawn");
assert!((row.3 - row.2 - f64::from(ROW_HEIGHT)).abs() < 0.01, "{row:?}");
assert!(field_description(&nodes).ends_with(&said), "{}", field_description(&nodes));
// With no document, Round Corners can't run now, and the reason goes on a second line.
assert!(field_place(&nodes).ends_with(&said), "{}", field_description(&nodes));
let open = Open::new("group selection", WINDOW);
assert_eq!(open.said("tool:groupSelection"), "Tool, Group Selection Tool, Toolbar, in the Direct Selection Tool group");
let mut open = Open::new("layers", WINDOW);
@@ -3931,6 +4162,329 @@ mod tests {
assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status);
}
/// The open palette on `query` over the session `session`.
fn open_on(query: &str, session: vectorcraft_engine::Session) -> Open {
let mut open = Open::new(query, WINDOW);
open.app = VectorcraftApp::new(session, crate::Services::default());
open.app.ui.palette_open = true;
open.app.ui.palette_query = query.into();
open.frame(vec![]);
open
}
/// The screen-reader node of the result row named `name`.
fn row_named<'a>(nodes: &'a [egui::accesskit::Node], name: &str) -> &'a egui::accesskit::Node {
nodes
.iter()
.filter(|n| n.role() == egui::accesskit::Role::ListItem)
.find(|n| n.label().is_some_and(|l| l == name || l.starts_with(&format!("{name}, "))))
.unwrap_or_else(|| panic!("a row named {name}: {:?}", rows(nodes)))
}
/// Highlights the result `id` with the arrow keys: the frame's screen-reader tree.
fn highlight(open: &mut Open, id: &str) -> Vec<egui::accesskit::Node> {
let k = open.listed().iter().position(|e| e == id).unwrap_or_else(|| panic!("{id} is listed"));
assert!(k < VISIBLE_ROWS, "{:?}", open.listed());
let nodes = open.press(egui::Key::ArrowDown, k);
assert_eq!(open.highlighted(), k);
nodes
}
/// With nothing selected, Ungroup stays listed in its place, dimmed, with the engine's reason in
/// its screen-reader description and in the footer while it is highlighted. Selecting art while
/// the palette stays open shows it as available on the next frame, in the same order. (A query
/// other tests' plug-in names do not match, so the list stays the same between frames.)
#[test]
fn a_result_that_cannot_run_now_is_dimmed_and_says_why() {
let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session();
session.execute("select.none", &json!({})).unwrap();
let why = ungroup_reason(&session);
let mut open = open_on("ungroup", session);
let entries = entries(&open.ctx, Lang::EN);
let entry = entries.iter().find(|e| e.id == "object.ungroup").unwrap();
let name = open.said("object.ungroup");
let order = open.listed();
let nodes = highlight(&mut open, "object.ungroup");
let ungroup = row_named(&nodes, &name);
assert!(ungroup.is_disabled(), "{ungroup:?}");
assert_eq!(ungroup.description(), Some(why.as_str()));
let t = Tokens::get(&open.ctx);
// The row draws the name without the menu path its home shows.
assert_eq!(open.color_of(label_of(entry)), Some(t.text_disabled), "the name is drawn dimmed");
let footer_says = |nodes: &[egui::accesskit::Node]| labels(nodes).contains(&why);
assert!(footer_says(&nodes), "{:?}", labels(&nodes));
// The arrow keys leave screen readers on the search field, so its description says why too.
let place = format!("{} of {}: {name}", open.highlighted() + 1, order.len());
assert_eq!(field_description(&nodes), format!("{place}\n{why}"));
let dimmed_rows: Vec<String> = rows(&nodes).into_iter().map(|r| r.0).collect();
open.app.run("select.all", json!({})).unwrap();
let nodes = open.frame(vec![]);
let ungroup = row_named(&nodes, &name);
assert!(!ungroup.is_disabled() && ungroup.description().is_none(), "{ungroup:?}");
assert_eq!(open.color_of(label_of(entry)), Some(t.text));
assert!(!footer_says(&nodes), "{:?}", labels(&nodes));
assert_eq!(field_description(&nodes), place);
// Whether a result can run never moves it.
assert_eq!(open.listed(), order);
assert_eq!(rows(&nodes).into_iter().map(|r| r.0).collect::<Vec<_>>(), dimmed_rows);
}
/// Why Object › Ungroup can't run in `session`, as the palette shows it: the engine's reason,
/// with the result's name and no command id.
fn ungroup_reason(session: &vectorcraft_engine::Session) -> String {
let reason = (vectorcraft_engine::find_command("object.ungroup").unwrap().enabled)(session).unwrap_err();
let why = crate::i18n::msg(&format!("command `Object › Ungroup` is not available right now: {reason}"));
assert!(!why.contains("object.ungroup"), "{why}");
why
}
/// The pointer resting on a result that can't run now shows why in a tooltip, as well as in
/// the footer of the result it highlights.
#[test]
fn hovering_a_result_that_cannot_run_now_says_why() {
let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session();
session.execute("select.none", &json!({})).unwrap();
let why = ungroup_reason(&session);
let mut open = open_on("ungroup", session);
let name = open.said("object.ungroup");
let nodes = open.frame(vec![]);
let b = row_named(&nodes, &name).bounds().unwrap();
let at = egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32);
open.frame(vec![egui::Event::PointerMoved(at)]);
let says = |nodes: &[egui::accesskit::Node]| labels(nodes).iter().filter(|l| **l == why).count();
let shown = (0..30).map(|_| says(&open.frame(vec![]))).max().unwrap_or(0);
assert_eq!(shown, 2, "the footer and the tooltip");
}
/// Under an empty search, a highlighted recent pick that can't run now is dimmed and the line
/// under the picks says why.
#[test]
fn a_recent_pick_that_cannot_run_now_says_why() {
let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session();
session.execute("select.none", &json!({})).unwrap();
let why = ungroup_reason(&session);
let mut open = open_on("", session);
open.app.ui.recent_commands = vec!["object.ungroup".to_string(), "object.group".to_string()];
let nodes = open.frame(vec![]);
assert_eq!(open.highlighted(), 0);
let rows: Vec<_> = nodes.iter().filter(|n| n.role() == egui::accesskit::Role::ListItem).collect();
assert_eq!(rows.len(), 2, "{rows:?}");
assert!(rows.iter().all(|n| n.is_disabled()), "{rows:?}");
assert!(labels(&nodes).contains(&why), "{:?}", labels(&nodes));
let popup = open.popup();
assert!(popup.bottom() <= WINDOW.y, "{popup:?}");
}
/// The Recent Commands list beside the search field draws a pick that can't run now dimmed,
/// disabled for screen readers with the reason as its description, and says why on hover.
#[test]
fn a_recent_command_that_cannot_run_now_is_dimmed_in_the_list() {
use egui::accesskit::Role;
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default());
app.run("select.none", json!({})).unwrap();
let why = ungroup_reason(&app.session);
app.ui.recent_commands = vec!["object.ungroup".into(), "select.all".into()];
let mut h = palette_harness(app);
h.ctx.all_styles_mut(|s| s.interaction.tooltip_delay = 0.0);
h.get_by_label(tl!("Recent Commands")).click();
h.run_steps(2);
let shown = |id: &str| entries(&h.ctx, Lang::EN).iter().find(|e| e.id == id).map(|e| e.shown.clone()).unwrap();
let (ungroup, all) = (shown("object.ungroup"), shown("select.all"));
// A row's label also holds its shortcut.
let row = |name: &str| {
let name = name.to_string();
move |n: &egui_kittest::kittest::AccessKitNode<'_>| n.role() == Role::Button && n.label().is_some_and(|l| l.contains(&name))
};
let ungroup_row = h.get_by(row(&ungroup));
assert!(ungroup_row.accesskit_node().is_disabled());
assert_eq!(ungroup_row.accesskit_node().description().as_deref(), Some(why.as_str()));
let all_row = h.get_by(row(&all));
assert!(!all_row.accesskit_node().is_disabled() && all_row.accesskit_node().description().is_none());
h.get_by(row(&ungroup)).hover();
h.run_steps(3);
assert!(h.query_by_label(&why).is_some(), "the tooltip says why");
}
/// The palette drops its answers when it closes, so opening it again, with the keyboard too,
/// asks its results again.
#[test]
fn the_palette_asks_again_when_it_opens_again() {
let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session();
session.execute("select.none", &json!({})).unwrap();
let mut open = open_on("ungroup", session);
let id = egui::Id::unique("palette-availability");
let kept = |open: &Open| open.ctx.data(|d| d.get_temp::<Availability>(id));
assert!(kept(&open).is_some_and(|a| a.known.contains_key("object.ungroup")));
open.app.ui.palette_open = false;
open.frame(vec![]);
assert!(kept(&open).is_none(), "the answers go when the palette closes");
open.app.ui.palette_open = true;
open.frame(vec![]);
assert!(kept(&open).is_some_and(|a| a.asked > 0 && a.known.contains_key("object.ungroup")), "asked again");
}
/// What the results' availability depends on changes the key it is kept under: an open dialog,
/// the screen mode, a background job, and a save that marks the document saved without a new
/// revision.
#[test]
fn availability_is_asked_again_when_what_it_depends_on_changes() {
let write_shared: crate::background::SharedWriteFn = std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()));
let services = crate::Services { write_shared: Some(write_shared), ..Default::default() };
let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), services);
let mut key = availability_key(&app);
let mut changed = |app: &VectorcraftApp, what: &str| {
let now = availability_key(app);
assert_ne!(now, key, "{what}");
key = now;
};
app.ui.dialog = Some(crate::state::Dialog::new("about", json!({})));
changed(&app, "a dialog opens");
app.ui.dialog = None;
changed(&app, "the dialog closes");
app.ui.screen_mode = 3;
changed(&app, "Presentation Mode");
let started = crate::background::run(&mut app, true, "Saving".into(), None, |_| Ok(json!({})), |_, r| r).unwrap();
assert_eq!(started.get("background"), Some(&json!(true)), "{started}");
changed(&app, "a background job starts");
app.run("select.all", json!({})).unwrap();
app.run("object.group", json!({})).unwrap();
changed(&app, "an edit");
let revision = app.session.active().map(|d| d.revision);
app.session.active_mut().unwrap().mark_saved();
assert_eq!(app.session.active().map(|d| d.revision), revision);
changed(&app, "the document is saved");
}
/// The drawn results are asked whether they can run once per state: keys pressed in the palette
/// keep the answers, a command run asks again, and a frame with a click asks again once,
/// without changing the state the answers are kept for.
#[test]
fn availability_is_read_once_per_state() {
let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session();
session.execute("select.none", &json!({})).unwrap();
let mut open = open_on("ungroup", session);
let id = egui::Id::unique("palette-availability");
let read = |open: &Open| open.ctx.data(|d| d.get_temp::<Availability>(id)).expect("the availability is kept");
let first = read(&open);
assert!(first.known.get("object.ungroup").is_some_and(Option::is_some), "{:?}", first.known);
// The key also takes in state shared by every test (the language, the loaded fonts, the
// installed plug-ins), which other tests change at the same time, so the presses are tried
// again until one try keeps the key.
let kept = (0..20).any(|_| {
open.frame(vec![]);
let before = read(&open).key;
open.press(egui::Key::ArrowDown, 1);
open.press(egui::Key::X, 1);
read(&open).key == before
});
assert!(kept, "key presses keep the answers");
let first = read(&open);
open.app.run("select.all", json!({})).unwrap();
open.frame(vec![]);
let after = read(&open);
assert_ne!(after.key, first.key);
assert_eq!(after.known.get("object.ungroup"), Some(&None), "asked again: {:?}", after.known);
let release = egui::Event::PointerButton {
pos: egui::pos2(1.0, 1.0),
button: egui::PointerButton::Primary,
pressed: false,
modifiers: egui::Modifiers::NONE,
};
// The same retries as for the key presses.
let once = (0..20).any(|_| {
open.frame(vec![]);
let before = read(&open);
open.frame(vec![release.clone()]);
let clicked = read(&open);
open.frame(vec![]);
let next = read(&open);
let asked_again = clicked.key == before.key && clicked.asked > before.asked;
asked_again && (next.key, next.asked) == (clicked.key, clicked.asked)
});
assert!(once, "a click asks again on its own frame only");
}
/// Paste is dimmed while the clipboard is empty and nothing can be pasted from the system
/// clipboard, and not while the system clipboard can be pasted.
#[test]
fn paste_is_dimmed_only_while_nothing_can_be_pasted() {
let mut open = open_on("paste", vectorcraft_testkit::fixtures::Fixture::Multi.session());
open.app.system_paste = false;
let name = open.said("edit.paste");
let nodes = open.frame(vec![]);
let paste = row_named(&nodes, &name);
assert!(paste.is_disabled(), "{paste:?}");
assert_eq!(paste.description(), Some("command `Edit › Paste` is not available right now: clipboard is empty"));
open.app.system_paste = true;
let nodes = open.frame(vec![]);
assert!(!row_named(&nodes, &name).is_disabled());
}
/// With no document open, Paste is dimmed with the engine's reason, though the system
/// clipboard still reads as pasteable until its next check.
#[test]
fn paste_is_dimmed_with_no_document_open() {
let mut open = open_on("paste", vectorcraft_engine::Session::new());
open.app.system_paste = true;
let name = open.said("edit.paste");
let nodes = open.frame(vec![]);
let paste = row_named(&nodes, &name);
assert!(paste.is_disabled(), "{paste:?}");
let reason = (vectorcraft_engine::find_command("edit.paste").unwrap().enabled)(&open.app.session).unwrap_err();
let why = format!("command `Edit › Paste` is not available right now: {reason}");
assert_eq!(paste.description(), Some(why.as_str()));
assert!(!menus::enabled(&open.app, "edit.paste"));
}
/// A tool can always be chosen; a panel can't be shown in Presentation Mode, and says so.
#[test]
fn tools_are_never_dimmed_and_panels_are_in_presentation_mode() {
let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
let tools: Vec<String> = build(Lang::EN).into_iter().map(|e| e.id).filter(|id| id.starts_with("tool:")).collect();
assert!(!tools.is_empty());
assert!(tools.iter().all(|id| unavailable(&app, id, id).is_none()), "{tools:?}");
let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default());
assert_eq!(unavailable(&app, "panel:layers", "Window › Layers"), None);
app.ui.screen_mode = 3;
assert_eq!(unavailable(&app, "panel:layers", "Window › Layers").as_deref(), Some("panels can't be shown in Presentation Mode"));
}
/// A UI command without an engine reason says it is not available, and a filter plug-in or an
/// effect asks about the command its pick runs. The message names the result as the palette
/// shows it, never by the command's id.
#[test]
fn a_result_without_an_engine_reason_says_it_is_not_available() {
let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
assert!(vectorcraft_engine::find_command("ui.newBrush").is_none());
let brush = unavailable(&app, "ui.newBrush", "New Brush…");
assert_eq!(brush.as_deref(), Some("command `New Brush…` is not available right now"));
let filter = unavailable(&app, "plugin:any.filter", "Object › Plug-ins › Any Filter…");
assert_eq!(filter.as_deref(), Some("command `Object › Plug-ins › Any Filter…` is not available right now"));
let effect = crate::shortcut_editor::effect_items().first().map(|e| format!("effect:{}", e.effect)).expect("an Effect menu item");
let why = unavailable(&app, &effect, "Effect › Any").unwrap_or_else(|| panic!("{effect}"));
assert!(why.starts_with("command `Effect › Any` is not available right now"), "{why}");
let app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default());
assert_eq!(unavailable(&app, "ui.newBrush", "New Brush…"), None);
assert_eq!(unavailable(&app, "plugin:any.filter", "Any Filter…"), None);
assert_eq!(unavailable(&app, &effect, "Effect › Any"), None, "{effect}");
}
/// Every result's reason names it as the palette shows it: no command id appears in it.
#[test]
fn no_reason_shows_a_command_id() {
let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
let entries = build(Lang::EN);
let reasons: Vec<(String, String)> =
entries.iter().filter_map(|e| unavailable(&app, &e.id, &e.shown).map(|why| (e.id.clone(), why))).collect();
assert!(reasons.len() > 100, "with no document most results can't run: {}", reasons.len());
for (id, why) in &reasons {
let command = crate::keymap::command_of(id).id;
assert!(!why.contains(&format!("`{command}`")), "{id}: {why}");
}
}
/// Screen readers stay on the field: its description names the highlighted result and its
/// place, and follows the highlight; the rows are list items, the highlighted one selected, and
/// the footer's count is a label.
@@ -3945,19 +4499,19 @@ mod tests {
// More results match than the list holds: the place counts every match, as the footer does.
let total = matching(&entries, "show panel", &[]).len();
assert!(total > MAX_RESULTS && listed.len() == MAX_RESULTS, "{total}");
assert_eq!(field_description(&nodes), format!("1 of {total}: {}", label(0)));
assert_eq!(field_place(&nodes), format!("1 of {total}: {}", label(0)));
let lit: Vec<String> = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect();
assert_eq!(lit, [label(0)]);
assert!(labels(&nodes).contains(&format!("50 of {total} results. Keep typing to narrow them.")), "{:?}", labels(&nodes));
let nodes = open.press(egui::Key::ArrowDown, 1);
assert_eq!(field_description(&nodes), format!("2 of {total}: {}", label(1)));
assert_eq!(field_place(&nodes), format!("2 of {total}: {}", label(1)));
// Fewer results match than the list holds.
let mut open = Open::new("eyedropper", WINDOW);
let n = open.listed().len();
assert!((1..MAX_RESULTS).contains(&n), "{n}");
let first = open.said(&open.listed()[0]);
let nodes = open.frame(vec![]);
assert_eq!(field_description(&nodes), format!("1 of {n}: {first}"));
assert_eq!(field_place(&nodes), format!("1 of {n}: {first}"));
assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes));
}
@@ -4565,7 +5119,7 @@ mod tests {
assert_eq!((sel, &now), (MAX_RESULTS - 1, &id), "the highlight stays on its result, in the last row");
let label = row_label(ranked[MAX_RESULTS], &home_text(&open.app, ranked[MAX_RESULTS]));
assert!(rows(&nodes).iter().any(|r| r.1 && r.0 == label), "its row is drawn and highlighted");
assert_eq!(field_description(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len()));
assert_eq!(field_place(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len()));
}
impl Window {
+26 -10
View File
@@ -937,17 +937,27 @@ pub(crate) fn menu_target(id: &str) -> Option<(String, Value)> {
/// status line ([`dimmed`]), as for Remove Background… with no image selected.
pub(crate) fn menu_target_now(app: &VectorcraftApp, id: &str) -> Option<Result<(String, Value), String>> {
let target = menu_target(id)?;
Some(if menus::enabled(app, id) { Ok(target) } else { dimmed(app, id) })
Some(match dimmed(app, id, id) {
None => Ok(target),
Some(why) => Err(why),
})
}
/// What [`menu_target_now`] gives for command `id` while its menu bar item is dimmed: the status
/// line, with the engine's reason when it gives one. The app's own rules ([`menus::enabled`]) dim
/// UI commands, and some commands the engine would run, without giving a reason.
pub(crate) fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> {
let Some(why) = vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()) else {
return Err(format!("command `{id}` is not available right now"));
/// What [`menu_target_now`] gives for command `id` while its menu bar item is dimmed, or `None`
/// while the item is not dimmed: the status line, which calls the command `name` (its id on the
/// status line), with the engine's reason when it gives one. The app's own rules
/// ([`menus::enabled`]) dim UI commands, and some commands the engine would run, without giving a
/// reason. The engine's check runs at most once.
pub(crate) fn dimmed(app: &VectorcraftApp, id: &str, name: &str) -> Option<String> {
let why = match menus::why_off(app, id)? {
Some(why) => Some(why),
// Dimmed before the engine was asked (no Appearance subject, an input method composing).
None => vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()),
};
Err(vectorcraft_engine::EngineError::Disabled(id.to_string(), why).to_string())
Some(match why {
Some(why) => vectorcraft_engine::EngineError::Disabled(name.to_string(), why).to_string(),
None => format!("command `{name}` is not available right now"),
})
}
/// Is `key` a command with no default shortcut that a key press can't run: no item of the menu
@@ -3366,13 +3376,19 @@ mod tests {
use vectorcraft_testkit::fixtures::Fixture;
let none = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
assert!(!menus::enabled(&none, "edit.findReplace"));
assert_eq!(dimmed(&none, "edit.findReplace"), Err("command `edit.findReplace` is not available right now: no document open".into()));
let why = "command `edit.findReplace` is not available right now: no document open";
assert_eq!(dimmed(&none, "edit.findReplace", "edit.findReplace").as_deref(), Some(why));
// A name to show takes the id's place.
let shown = "command `Edit › Find and Replace…` is not available right now: no document open";
assert_eq!(dimmed(&none, "edit.findReplace", "Edit › Find and Replace…").as_deref(), Some(shown));
let empty = VectorcraftApp::new(Fixture::Empty.session(), crate::Services::default());
for id in ["appearance.addFill", "ui.cropImage"] {
assert!(!menus::enabled(&empty, id), "{id}");
assert!(vectorcraft_engine::find_command(id).is_none_or(|c| (c.enabled)(&empty.session).is_ok()), "{id}: the engine gives no reason");
assert_eq!(dimmed(&empty, id), Err(format!("command `{id}` is not available right now")));
assert_eq!(dimmed(&empty, id, id), Some(format!("command `{id}` is not available right now")));
}
assert!(menus::enabled(&empty, "edit.findReplace"));
assert_eq!(dimmed(&empty, "edit.findReplace", "edit.findReplace"), None, "not dimmed");
}
/// Every command the editor lists, run as a key press runs it on a document with one or with
+1
View File
@@ -1575,6 +1575,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`).
The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`).
A Command Palette query word also finds a command by what the command's description says: "transparent background" lists Remove Background… among the first 3 results, and "png" lists it after every result with "png" in its name or menu path. The description is the command's params text (an engine or plug-in command's, a UI command's, or an effect's) without each `{…}` group that is not inside a `{`, `[` or `(` group, without each such `[…]` or `(…)` group just after a `→`, and without the `→` before a removed group, cut to its first 300 characters at the end of a word. The words of a schema ("corners" for Remove Background…) and of a result written as a group do not find the command; a result written as words after a `→` stays in the description. Words of 2 characters or fewer, words with no letter, and "the", "and", "ids", "true", "false" and "null" are left out. A query word that is a word of a description, shares an English base word with one, starts one or has the same meaning as one finds the result, and such a result ranks below every result that the query matches in its name, menu path or id, as text inside a word or through a typo. Descriptions are English only, and a typo does not match them. Tools, panels and filter plug-ins have no description (`palette::search` tests `a_description_leaves_out_the_schema_and_the_result`, `a_word_of_the_description_finds_the_result`, `a_description_match_ranks_below_a_typo`, `words_of_a_description_find_the_command`).
A Command Palette result that cannot run now stays in its place in the list and is drawn dimmed: an engine command whose engine check fails (Ungroup with nothing selected, Paste with an empty clipboard and nothing to paste from the system clipboard), a UI command the menus dim, a filter plug-in or an effect whose menu item is dimmed, and a panel in Presentation Mode. Tools are never dimmed. The reason shows on hover, in the row's screen-reader description, on a second line of the search field's screen-reader description and in the footer while the row is highlighted, beside the count or, under the recent picks of an empty search, on a line of its own. The reason is the status line a pick of the dimmed menu item gives, with the result's name in place of the command's id: "command `Object › Ungroup` is not available right now: nothing selected", or without the engine's reason when it gives none. The Recent Commands list beside the search field draws such a pick dimmed too, with the same reason on hover and for screen readers. Only the drawn rows are checked, each once for as long as the state it was checked in lasts: a command run, an edit, a change of selection, document, history, clipboard, language, screen mode or open dialog, a save that marks the document saved, or a background save, export, file read, plug-in run or trace that starts, ends or shows its progress window checks them again on the next frame, and a frame with a click checks them again on that frame only. Typing in the search field does not check them again, and the palette checks them again each time it opens. The check never changes the ranking. A pick of a dimmed result does what it did before (`palette` tests `a_result_that_cannot_run_now_is_dimmed_and_says_why`, `hovering_a_result_that_cannot_run_now_says_why`, `paste_is_dimmed_only_while_nothing_can_be_pasted`, `tools_are_never_dimmed_and_panels_are_in_presentation_mode`, `a_result_without_an_engine_reason_says_it_is_not_available`, `no_reason_shows_a_command_id`, `a_recent_pick_that_cannot_run_now_says_why`, `a_recent_command_that_cannot_run_now_is_dimmed_in_the_list`, `availability_is_asked_again_when_what_it_depends_on_changes`, `availability_is_read_once_per_state`, `the_palette_asks_again_when_it_opens_again`).
Each Command Palette row starts with an icon for its kind (a tool's own icon, or one for a panel, an effect, a filter plug-in or a command) and shows where the result lives after its label, in smaller dim text: the menu path of the menu bar item that runs it, with that item's label when it differs from the result's ("File › Exit" for Quit VectorCraft), and "No menu item" for a command no item runs. A panel's row shows "Window". A row with a home shows its label without the menu path in front of it. A path that keeps two results' names apart stays in the label, unless the row's home shows the same path; a tool's row drops the "Tools" in front of its name. A tool's row names the toolbar it is on: "Toolbar" for its button on the Tools panel, or the name of a toolbar made with New Toolbar, followed by ", in the <tool> group" when the tool is hidden in the group of a slot whose button shows another tool ("Toolbar, in the Direct Selection Tool group" for the Group Selection Tool), and "All Tools" when no toolbar holds it. A toolbar shown now comes first (the Tools panel, then the toolbars made with New Toolbar), then a hidden Tools panel, then hidden toolbars made with New Toolbar; toolbars count as hidden in Presentation Mode and while Tab hides the panels. The Learn command (`window.learn`), which Window › Learn runs, takes the Window menu as its home, so a search reads its menu path like any other result's, and among results that tie on everything else it ranks as a command of the menu bar, before panels and after tools. The home is cut short with "…" before the label, and a label too long for the row keeps the id it shows after its name unless the id alone is wider than the row. A cut row shows all its text while the pointer rests on it, and screen readers read the kind, the label, the home and the shortcut. The row height is unchanged (`palette` tests `rows_show_where_each_result_lives`, `no_two_rows_read_alike`, `a_tool_row_names_its_toolbar_slot`, `a_narrow_row_cuts_the_home_first_and_keeps_the_id`, `screen_readers_hear_the_kind_and_home`, `catalogs_translate_the_kind_and_home_words`).
While the Command Palette is open, the highlighted result points to where it lives, in the same frame the arrow keys or the pointer move the highlight. A result with an item of the in-window menu bar has that menu's title outlined, with the item's whole path in a box under it ("Effect › Stylize › Round Corners…"); a panel points at the Window menu. A tool has its slot's button outlined on the toolbar the row names, or its own button on a strip torn off its group, with a box on the canvas side of the toolbar that names the tool, or says "In the Direct Selection Tool group: press and hold to open it" for a tool hidden in a group; screen readers hear that sentence with the search field's description. The box stays inside the window and off the button and the palette's popup: beside a button, its text wraps to up to three rows to fit before the popup or the window's edge, and where it still does not fit, the footer shows the text and only the outline is drawn; when the popup covers the control, nothing is drawn and the footer names the home. Nothing opens or shows: no menu, flyout, toolbar or All Tools drawer, and the chosen tool stays. With the system's menu bar, the footer reads "In the menu bar:" and the path instead; when no control in view shows the home (Presentation Mode, toolbars hidden by Window › Tools or Tab, a button scrolled out of view or under a floating panel or another toolbar) the footer names the home followed by "not shown now", and a command with no menu item reads "No menu item" with its shortcut. The menu bar and the toolbars note where they drew their controls only while the palette is open, and the palette uses only what this pass drew in its own window (`palette` tests `the_highlighted_result_outlines_its_menu_title`, `with_a_native_menu_bar_the_footer_names_the_path`, `a_tool_result_outlines_its_toolbar_slot`, `a_tool_on_a_toolbar_made_with_new_toolbar_is_outlined_there`, `a_strip_torn_off_the_tools_panel_is_pointed_at`, `a_box_beside_a_button_wraps_to_fit_beside_the_popup`, `the_box_keeps_off_its_button`, `the_callout_stays_off_the_palette`, `the_callout_keeps_off_a_popup_that_grew_in_the_same_pass`, `a_home_out_of_view_is_named_in_the_footer`, `the_pass_that_opens_the_palette_names_no_home_as_hidden`, `the_callout_follows_the_pointer`, `the_callout_follows_the_highlight_and_reveals_nothing`, `only_a_control_in_view_in_this_pass_is_pointed_at`, `a_control_under_a_window_is_not_pointed_at`, `the_noted_controls_hold_one_pass_per_viewport`, `catalogs_translate_the_callout_words`).
`object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do.