Merge pull request #8209 from dotCooCoo/feat/palette-use-counts

Command Palette: commands picked often rank first within their grades
This commit is contained in:
BFlat authored and GitHub committed 2026-11-20 03:11:53 +07:00
commit e9a62670a7
4 files changed
+443 -39

No files matched your search

+374 -17
View File
@@ -319,8 +319,8 @@ pub(crate) struct Entry {
names_item: bool,
}
/// The last query, the recent picks it was ranked with, and its ranked results.
type Ranked = (String, Vec<u32>, Arc<[u32]>);
/// The last query, the recent picks and the pick counts it was ranked with, and its ranked results.
type Ranked = (String, Vec<u32>, CommandUses, Arc<[u32]>);
/// The palette's entries, the index a query is looked up in, and the last query's ranked results.
pub(crate) struct Catalog {
@@ -522,19 +522,24 @@ pub(crate) enum Picked {
Refused,
}
/// The entries the query `q` matches, best first ([`search::rank`]), with the picks that Recent
/// Commands lists for the ids `recent_ids` ([`recent`]) first among the entries that match as well.
/// The ranking of the last query is kept, so a frame that draws the same query with the same recent
/// picks does not rank again. [`show`] lists the first [`MAX_RESULTS`] and counts the rest.
fn matching<'a>(catalog: &'a Catalog, q: &str, recent_ids: &[String]) -> Vec<&'a Entry> {
/// 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
/// a frame that draws the same query with the same counts and recent picks does not rank again.
/// [`show`] lists the first [`MAX_RESULTS`] and counts the rest.
fn matching<'a>(catalog: &'a Catalog, q: &str, recent_ids: &[String], uses: &CommandUses) -> Vec<&'a Entry> {
let q = search::normalize(q);
let picks: Vec<u32> = recent_places(&catalog.list, recent_ids).into_iter().filter_map(|i| u32::try_from(i).ok()).collect();
let kept = catalog.ranked.lock().ok().and_then(|last| last.as_ref().filter(|(k, p, _)| *k == q && *p == picks).map(|(_, _, r)| r.clone()));
let kept = catalog
.ranked
.lock()
.ok()
.and_then(|last| last.as_ref().filter(|(k, p, c, _)| *k == q && *p == picks && c == uses).map(|(_, _, _, r)| r.clone()));
let ranked = kept.unwrap_or_else(|| {
let ranked: Arc<[u32]> = search::rank(&catalog.list, &catalog.index, &q, &picks).into();
let ranked: Arc<[u32]> = search::rank(&catalog.list, &catalog.index, &q, &picks, &uses.grades(&catalog.list)).into();
// A poisoned lock only loses the kept ranking: the next frame ranks again.
if let Ok(mut last) = catalog.ranked.lock() {
*last = Some((q, picks, ranked.clone()));
*last = Some((q, picks, uses.clone(), ranked.clone()));
}
ranked
});
@@ -1065,6 +1070,127 @@ fn recent_places(entries: &[Entry], ids: &[String]) -> Vec<usize> {
.collect()
}
/// How many command ids [`CommandUses`] counts at most.
const MAX_COUNTED_COMMANDS: usize = 200;
/// The count at which [`CommandUses::count`] halves every count.
const HALVING_COUNT: u32 = 1_000;
/// How many times each command was picked in the palette: commands picked often rank first among
/// the results that match a query as well ([`matching`]). It counts at most
/// [`MAX_COUNTED_COMMANDS`] ids. When a count reaches [`HALVING_COUNT`], every count is halved, so
/// a count is at most 999.
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)]
pub struct CommandUses {
/// The number of the last pick; each pick takes the next one.
pick: u32,
/// For each command id, its count and the number of its last pick.
uses: std::collections::BTreeMap<String, (u32, u32)>,
}
impl CommandUses {
/// Counts a pick of `id`. A new id when [`MAX_COUNTED_COMMANDS`] are counted first removes
/// one id from the half of the ids picked longest ago: the one with the lowest count, of those
/// the one picked longest ago. It then counts once. When the pick number is at its limit, the
/// counted ids' pick numbers are first renumbered from 1 in their order ([`renumbered`]), so
/// the pick still takes a number above all of them.
pub(crate) fn count(&mut self, id: &str) {
if self.pick == u32::MAX {
let lasts: Vec<u64> = self.uses.values().map(|&(_, last)| u64::from(last)).collect();
for ((_, last), number) in self.uses.values_mut().zip(renumbered(&lasts)) {
*last = number;
}
self.pick = self.uses.values().map(|&(_, last)| last).max().unwrap_or(0);
}
self.pick = self.pick.saturating_add(1);
let pick = self.pick;
if let Some((n, last)) = self.uses.get_mut(id) {
*n = n.saturating_add(1);
*last = pick;
} else {
if self.uses.len() >= MAX_COUNTED_COMMANDS {
let mut by_age: Vec<(u32, u32, &String)> = self.uses.iter().map(|(k, &(n, last))| (last, n, k)).collect();
by_age.sort_unstable();
let older = by_age.len().div_ceil(2);
if let Some(least) = by_age.iter().take(older).min_by_key(|&&(last, n, _)| (n, last)).map(|&(_, _, k)| k.clone()) {
self.uses.remove(&least);
}
}
self.uses.insert(id.to_string(), (1, pick));
}
if self.uses.get(id).is_some_and(|&(n, _)| n >= HALVING_COUNT) {
for (n, _) in self.uses.values_mut() {
*n /= 2;
}
self.uses.retain(|_, (n, _)| *n > 0);
}
}
/// The count of `id`'s picks as a grade from 0 (never picked) to 9: the base-2 logarithm of
/// the count plus one, so 1 pick gives 1, 3 give 2, 7 give 3, and so on.
fn grade(&self, id: &str) -> u8 {
self.uses.get(id).map_or(0, |&(n, _)| u8::try_from(n.min(HALVING_COUNT - 1).saturating_add(1).ilog2()).unwrap_or(u8::MAX))
}
/// The grade ([`CommandUses::grade`]) of each of `entries`, in their order, or none when no
/// command was picked.
fn grades(&self, entries: &[Entry]) -> Vec<u8> {
if self.uses.is_empty() {
return vec![];
}
entries.iter().map(|e| self.grade(&e.id)).collect()
}
}
/// The pick numbers `lasts` renumbered from 1 in their order, in the order of `lasts`: equal
/// numbers stay equal, and the lowest becomes 1.
fn renumbered(lasts: &[u64]) -> Vec<u32> {
let mut distinct = lasts.to_vec();
distinct.sort_unstable();
distinct.dedup();
lasts.iter().map(|last| u32::try_from(distinct.partition_point(|d| d < last) + 1).unwrap_or(u32::MAX)).collect()
}
/// Serde reader for the saved pick counts ([`crate::UiState::command_uses`]): an entry that is not
/// a pair of counts is dropped, a count above 999 reads as 999, and of more than
/// [`MAX_COUNTED_COMMANDS`] ids the ones picked most recently are kept. When a kept pick number or
/// the last pick number is above the largest the counts hold, the kept pick numbers are
/// renumbered from 1 in their order ([`renumbered`]). Anything else reads as no picks, so an
/// unknown value doesn't lose the rest of the preferences.
pub fn deserialize_command_uses<'de, D: serde::Deserializer<'de>>(d: D) -> Result<CommandUses, D::Error> {
use std::cmp::Reverse;
let v = <serde_json::Value as serde::Deserialize>::deserialize(d)?;
let number = |v: Option<&serde_json::Value>| v.and_then(serde_json::Value::as_u64);
// The heap holds at most MAX_COUNTED_COMMANDS + 1 entries, the least recent pick on top (of
// equal picks, the id that sorts last), so a long saved list is not collected whole. Pick
// numbers are compared as saved, before any is renumbered.
let mut kept: std::collections::BinaryHeap<Reverse<(u64, Reverse<&String>, u32)>> = std::collections::BinaryHeap::new();
for (id, u) in v.get("uses").and_then(serde_json::Value::as_object).into_iter().flatten() {
let (Some(n), Some(last)) = (number(u.get(0)), number(u.get(1))) else { continue };
if n == 0 || !u.as_array().is_some_and(|a| a.len() == 2) {
continue;
}
let n = u32::try_from(n.min(u64::from(HALVING_COUNT - 1))).unwrap_or(HALVING_COUNT - 1);
kept.push(Reverse((last, Reverse(id), n)));
if kept.len() > MAX_COUNTED_COMMANDS {
kept.pop();
}
}
let kept: Vec<(&String, u32, u64)> = kept.into_iter().map(|Reverse((last, Reverse(id), n))| (id, n, last)).collect();
// The pick number stays above every saved last pick, so the next pick is the most recent.
let newest = kept.iter().map(|&(_, _, last)| last).max().unwrap_or(0);
let pick = number(v.get("pick")).unwrap_or(0).max(newest);
if let Ok(pick) = u32::try_from(pick) {
let uses = kept.into_iter().map(|(id, n, last)| (id.clone(), (n, u32::try_from(last).unwrap_or(pick)))).collect();
return Ok(CommandUses { pick, uses });
}
let lasts: Vec<u64> = kept.iter().map(|&(_, _, last)| last).collect();
let uses: std::collections::BTreeMap<String, (u32, u32)> =
kept.into_iter().zip(renumbered(&lasts)).map(|((id, n, _), last)| (id.clone(), (n, last))).collect();
let pick = uses.values().map(|&(_, last)| last).max().unwrap_or(0);
Ok(CommandUses { pick, uses })
}
/// The id of the Recent Commands list's popup.
fn recent_list_id() -> egui::Id {
egui::Id::unique("palette-recent-commands")
@@ -1129,7 +1255,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let recent = recent(&entries.list, &app.ui.recent_commands);
// An empty search lists the recent picks, most recent first, so Enter runs the last pick again.
let empty = app.ui.palette_query.trim().is_empty();
let mut matches = if empty { recent.clone() } else { matching(&entries, &q, &app.ui.recent_commands) };
let mut matches = if empty { recent.clone() } else { matching(&entries, &q, &app.ui.recent_commands, &app.ui.command_uses) };
let total = matches.len();
// The highlighted result (#1757): Up and Down move it (wrapping), Page Up and Page Down move it
// by a page, the pointer over a result takes it, and a new query starts again from the first.
@@ -1461,15 +1587,18 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
app.ui.palette_open = false;
// A pick goes first in Recent Commands before it runs, and stays there when it ran or
// opened a dialog, even when the dialog is then canceled. A refused pick puts the list
// back as it was.
// back as it was. Only a pick that stays in the list is counted.
let before = (id != PALETTE_TOGGLE).then(|| app.ui.recent_commands.clone());
if before.is_some() {
remember(&mut app.ui.recent_commands, &id, |c| entries.list.iter().any(|e| e.id == c));
}
if run_pick(app, &id) == Picked::Refused
&& let Some(before) = before
{
app.ui.recent_commands = before;
let picked = run_pick(app, &id);
if let Some(before) = before {
if picked == Picked::Refused {
app.ui.recent_commands = before;
} else {
app.ui.command_uses.count(&id);
}
}
} else if outside {
app.ui.palette_open = false;
@@ -1486,6 +1615,11 @@ mod tests {
use super::*;
use crate::i18n::Lang;
/// The entries `q` matches, best first, with the recent picks `recent_ids` and no pick counts.
fn matching<'a>(catalog: &'a Catalog, q: &str, recent_ids: &[String]) -> Vec<&'a Entry> {
super::matching(catalog, q, recent_ids, &CommandUses::default())
}
#[test]
fn entries_are_built_once_per_language_and_match_english_shown_text_and_ids() {
let ctx = egui::Context::default();
@@ -2104,6 +2238,229 @@ mod tests {
assert_eq!(ids(&["plugin:test.UI.palette_removed".to_string(), effect.clone()]).first(), Some(&effect));
}
/// Pick counts for the ids `counts`, picked in that order.
fn counted(counts: &[(&str, u32)]) -> CommandUses {
let uses = counts.iter().zip(1..).map(|(&(id, n), last)| (id.to_string(), (n, last))).collect();
CommandUses { pick: u32::try_from(counts.len()).unwrap(), uses }
}
/// A command picked often ranks first among the results that match the query as well as it
/// does, also when it is no longer a recent pick, and the count is saved with the other
/// interface settings.
#[test]
fn a_command_picked_often_ranks_first_among_results_that_match_as_well() {
let (tool, effect) = ("tool:rectangle", "effect:convertToShape.rectangle");
let mut open = Open::new("rect", egui::vec2(1200.0, 900.0));
// The fixture has art selected, so the effect is not dimmed and its pick is counted.
open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default());
open.app.ui.palette_open = true;
open.app.ui.palette_query = "rect".into();
open.frame(vec![]);
let before = open.listed();
assert_eq!(before.first().map(String::as_str), Some(tool));
let at = before.iter().position(|id| id == effect).unwrap();
open.press(egui::Key::ArrowDown, at);
open.press(egui::Key::Enter, 1);
assert_eq!(open.app.ui.command_uses.grade(effect), 1);
assert_eq!(open.app.ui.command_uses.grade(tool), 0);
open.app.ui.recent_commands.clear();
open.app.ui.dialog = None;
open.app.ui.palette_open = true;
open.app.ui.palette_query = "rect".into();
open.frame(vec![]);
let after = open.listed();
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 restored: crate::state::UiState = serde_json::from_str(&serde_json::to_string(&open.app.ui).unwrap()).unwrap();
assert_eq!(restored.command_uses, open.app.ui.command_uses);
}
/// The kept ranking of a query is ranked again when a pick count changes.
#[test]
fn the_kept_ranking_follows_the_pick_counts() {
let ctx = egui::Context::default();
let entries = entries(&ctx, Lang::EN);
let first = |uses: &CommandUses| super::matching(&entries, "rect", &[], uses).first().map(|e| e.id.clone());
let effect = "effect:convertToShape.rectangle";
assert_eq!(first(&CommandUses::default()).as_deref(), Some("tool:rectangle"));
let mut uses = counted(&[("tool:rectangle", 1)]);
assert_eq!(first(&uses).as_deref(), Some("tool:rectangle"));
uses.count(effect);
assert_eq!(first(&uses).as_deref(), Some("tool:rectangle"), "the same grade: the catalog order");
uses.count(effect);
uses.count(effect);
assert_eq!(first(&uses).as_deref(), Some(effect), "three picks reach grade 2");
assert_eq!(first(&CommandUses::default()).as_deref(), Some("tool:rectangle"));
}
/// A count does not lift a result above one that matches the query better: the exact id
/// `view.goto1` lists Saved View 1 before Saved View 10, however often that was picked.
#[test]
fn a_count_does_not_pass_a_better_match() {
let ctx = egui::Context::default();
let entries = entries(&ctx, Lang::EN);
let uses = counted(&[("view.goto10", 999)]);
let ids: Vec<&str> = super::matching(&entries, "view.goto1", &[], &uses).into_iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids.first(), Some(&"view.goto1"), "{ids:?}");
assert!(ids.contains(&"view.goto10"), "{ids:?}");
}
/// Counts grow in grades that double: 1 pick gives grade 1, 3 give 2, 7 give 3, and 999 give 9.
#[test]
fn pick_counts_rank_in_grades_that_double() {
let mut uses = CommandUses::default();
let grades: Vec<u8> = (0..8)
.map(|_| {
let g = uses.grade("a");
uses.count("a");
g
})
.collect();
assert_eq!(grades, [0, 1, 1, 2, 2, 2, 2, 3]);
assert_eq!(counted(&[("a", 999)]).grade("a"), 9);
assert_eq!(counted(&[("a", u32::MAX)]).grade("a"), 9);
assert!(CommandUses::default().grades(&[]).is_empty(), "no grades without counts");
}
/// A new id when 200 are counted removes, of the 100 ids picked longest ago, the id with the
/// lowest count, of those the one picked longest ago, and keeps the new one.
#[test]
fn the_201st_command_removes_the_least_used_and_keeps_itself() {
let ids: Vec<String> = (0..MAX_COUNTED_COMMANDS).map(|i| format!("c{i}")).collect();
let counts: Vec<(&str, u32)> = ids.iter().enumerate().map(|(i, id)| (id.as_str(), if i == 5 || i == 9 { 1 } else { 2 })).collect();
let mut uses = counted(&counts);
uses.count("new");
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
assert!(!uses.uses.contains_key("c5") && uses.uses.contains_key("c9"));
assert_eq!(uses.uses.get("new"), Some(&(1, 201)));
uses.count("newer");
assert!(!uses.uses.contains_key("c9"), "c9 was picked before new");
assert!(uses.uses.contains_key("new") && uses.uses.contains_key("newer"));
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
}
/// When all 200 counted ids have 2 picks or more, new ids picked in turn keep their places and
/// their counts grow; the ids removed are the ones picked longest ago.
#[test]
fn new_commands_build_up_counts_when_every_counted_one_has_more_picks() {
let ids: Vec<String> = (0..MAX_COUNTED_COMMANDS).map(|i| format!("c{i}")).collect();
let counts: Vec<(&str, u32)> = ids.iter().map(|id| (id.as_str(), 2)).collect();
let mut uses = counted(&counts);
for _ in 0..3 {
for id in ["a", "b", "c"] {
uses.count(id);
}
}
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
for id in ["a", "b", "c"] {
assert_eq!(uses.uses.get(id).map(|&(n, _)| n), Some(3), "{id}");
}
assert!(!uses.uses.contains_key("c0") && !uses.uses.contains_key("c2") && uses.uses.contains_key("c3"));
assert!(uses.uses.contains_key("c199"));
}
/// When a count reaches 1,000, every count is halved and ids left at 0 are removed.
#[test]
fn counts_are_halved_at_one_thousand() {
let mut uses = counted(&[("a", 999), ("b", 1), ("c", 5)]);
uses.count("a");
assert_eq!(uses.uses.get("a"), Some(&(500, 4)));
assert_eq!(uses.uses.get("c"), Some(&(2, 3)));
assert!(!uses.uses.contains_key("b"));
}
/// At the pick number's limit, the counted ids' pick numbers are renumbered from 1 in their
/// order, so a pick still takes a number above all of them and a command picked again leaves
/// the half of the ids picked longest ago.
#[test]
fn picks_keep_their_order_at_the_pick_number_limit() {
let ids: Vec<String> = (0..MAX_COUNTED_COMMANDS).map(|i| format!("c{i:03}")).collect();
let mut uses = CommandUses { pick: u32::MAX, uses: ids.iter().map(|id| (id.clone(), (2, u32::MAX))).collect() };
uses.uses.insert("c000".into(), (1, u32::MAX));
uses.count("c000");
assert_eq!(uses.uses.get("c000"), Some(&(2, 2)));
assert_eq!(uses.uses.get("c001"), Some(&(2, 1)));
uses.count("new");
assert!(uses.uses.contains_key("c000"), "c000 was picked last: {:?}", uses.uses.get("c000"));
assert!(!uses.uses.contains_key("c001"));
assert_eq!(uses.uses.get("new"), Some(&(1, 3)));
// Equal pick numbers stay equal, and the order of the others is kept.
let mut uses =
CommandUses { pick: u32::MAX, uses: [("a", (1, 7)), ("b", (1, u32::MAX)), ("c", (1, 7))].map(|(k, v)| (k.to_string(), v)).into() };
uses.count("d");
assert_eq!(
uses,
CommandUses { pick: 3, uses: [("a", (1, 1)), ("b", (1, 2)), ("c", (1, 1)), ("d", (1, 3))].map(|(k, v)| (k.to_string(), v)).into() }
);
}
/// Saved counts load what is readable: a count above 999 reads as 999, entries that are not a
/// pair of counts are dropped, of more than 200 ids the most recent picks are kept, and a value
/// of the wrong kind, or none (an older settings file), reads as no picks.
#[test]
fn saved_pick_counts_load_what_is_readable() {
let load = |v: serde_json::Value| serde_json::from_value::<crate::state::UiState>(json!({ "command_uses": v })).unwrap().command_uses;
let uses = load(json!({
"pick": 3,
"uses": {"a": [5000, 2], "b": "x", "c": [1], "d": [0, 1], "e": [2, 3, 4], "f": [-1, 2], "g": [4, 1], "h": [1.5, 1], "i": [3, 9]}
}));
assert_eq!(uses, CommandUses { pick: 9, uses: [("a", (999, 2)), ("g", (4, 1)), ("i", (3, 9))].map(|(k, v)| (k.to_string(), v)).into() });
for wrong in [json!("x"), json!(null), json!([1, 2]), json!({"uses": [1]}), json!({"pick": "x", "uses": {}})] {
assert_eq!(load(wrong.clone()), CommandUses::default(), "{wrong}");
}
let older: crate::state::UiState = serde_json::from_value(json!({})).unwrap();
assert_eq!(older.command_uses, CommandUses::default());
let many: serde_json::Map<String, serde_json::Value> = (1..=250).map(|i| (format!("c{i}"), json!([1, i]))).collect();
let uses = load(json!({ "pick": 250, "uses": many }));
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
assert!(uses.uses.contains_key("c51") && !uses.uses.contains_key("c50"));
// The next pick is the most recent, also when the saved pick number is behind.
let mut uses = load(json!({ "pick": 1, "uses": {"a": [1, 9]} }));
uses.count("b");
assert_eq!(uses.uses.get("b"), Some(&(1, 10)));
// Saved pick numbers above the largest the counts hold are compared as saved, and the kept
// ones are renumbered from 1 in their order.
let big = u64::from(u32::MAX) + 1;
let mut many: serde_json::Map<String, serde_json::Value> = (0..MAX_COUNTED_COMMANDS).map(|i| (format!("c{i:03}"), json!([1, big]))).collect();
many.insert("z".into(), json!([1, big + 1]));
let uses = load(json!({ "pick": big + 1, "uses": many }));
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
assert_eq!(uses.uses.get("z"), Some(&(1, 2)), "the newest pick is kept");
assert_eq!(uses.uses.get("c000"), Some(&(1, 1)));
assert_eq!(uses.pick, 2);
let uses = load(json!({ "pick": big, "uses": {"a": [1, 5], "b": [1, 3]} }));
assert_eq!(uses, CommandUses { pick: 2, uses: [("a", (1, 2)), ("b", (1, 1))].map(|(k, v)| (k.to_string(), v)).into() });
}
/// A pick is counted only when Recent Commands records it: a refused pick and a pick of the
/// palette's own toggle are not counted, and a pick that opens a dialog is.
#[test]
fn only_a_pick_recorded_in_recent_commands_is_counted() {
for (query, id) in [("find and replace", "edit.findReplace"), ("search commands", PALETTE_TOGGLE)] {
let mut open = Open::new(query, WINDOW);
let k = open.listed().iter().position(|c| c == id).unwrap_or_else(|| panic!("{query:?} finds {id}"));
open.frame(vec![]);
open.press(egui::Key::ArrowDown, k);
assert_eq!(open.highlighted(), k, "{id}");
open.press(egui::Key::Enter, 1);
assert!(open.app.ui.recent_commands.is_empty(), "{id}");
assert_eq!(open.app.ui.command_uses, CommandUses::default(), "{id}");
}
let id = "object.path.cleanUp";
let mut open = Open::new("clean up", WINDOW);
open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default());
open.app.ui.palette_open = true;
open.app.ui.palette_query = "clean up".into();
let k = open.listed().iter().position(|c| c == id).expect("the search finds Clean Up…");
open.frame(vec![]);
open.press(egui::Key::ArrowDown, k);
open.press(egui::Key::Enter, 1);
assert!(open.app.ui.dialog.is_some());
assert_eq!(open.app.ui.recent_commands, [id]);
assert_eq!(open.app.ui.command_uses.grade(id), 1);
}
/// #6376: with nothing picked yet, Recent Commands shows a dimmed No recent commands row.
#[test]
fn recent_commands_without_picks_show_a_dimmed_row() {
@@ -2904,7 +3261,7 @@ mod tests {
let listed = if self.app.ui.palette_query.trim().is_empty() {
recent(&entries.list, &self.app.ui.recent_commands)
} else {
matching(&entries, &self.app.ui.palette_query.to_lowercase(), &self.app.ui.recent_commands)
super::matching(&entries, &self.app.ui.palette_query.to_lowercase(), &self.app.ui.recent_commands, &self.app.ui.command_uses)
};
listed.iter().take(MAX_RESULTS).map(|e| e.id.clone()).collect()
}
+62 -21
View File
@@ -682,9 +682,9 @@ fn phrase(e: &Entry, query: &str, initials: bool) -> u8 {
/// What results are ordered by, compared field by field: whether a word matched only through a
/// description, whether a word matched only through a typo, how the whole query matches, the worst
/// grade a word gets, the sum of the grades, how the whole query matches when read with the words
/// of the same meaning it matched through, the result's place among the recent picks, the kind of
/// result and the label's length.
type RankKey = (bool, bool, u8, u8, u32, u8, usize, u8, usize);
/// of the same meaning it matched through, how often the result was picked (higher first), the
/// result's place among the recent picks, the kind of result and the label's length.
type RankKey = (bool, bool, u8, u8, u32, u8, std::cmp::Reverse<u8>, usize, u8, usize);
/// The results of `entries` that the lowercased `query` matches, best first, as places in
/// `entries`. A result matches when every word of the query is text in one of its names or ids
@@ -705,12 +705,14 @@ type RankKey = (bool, bool, u8, u8, u32, u8, usize, u8, usize);
/// worst grade a word gets, the sum of the grades, how the whole query matches when read with each
/// word matched through a word of the same meaning replaced by that word ("colour" as "color"; of
/// several such words the result holds, the ones that match the whole query best),
/// then by the result's place in `recent`, the places in `entries` of the recent picks, most
/// recent first (a result not in it comes after every result in it), then the kind of result
/// ([`kind`]), the label's length and the catalog order. So a recent pick ranks above the results
/// that match the query as well as it does and below every result that matches it better. An
/// empty query lists every result in catalog order.
pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32]) -> Vec<u32> {
/// then by the grade in `uses` of how often the result was picked, highest first (`uses` holds one
/// grade per entry of `entries`, in their order; a missing grade is 0), then by the result's place
/// in `recent`, the places in `entries` of the recent picks, most recent first (a result not in it
/// comes after every result in it), then the kind of result ([`kind`]), the label's length and the
/// catalog order. So a result picked often, or recently, ranks above the results that match the
/// query as well as it does and below every result that matches it better. An empty query lists
/// every result in catalog order.
pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32], uses: &[u8]) -> Vec<u32> {
let query = normalize(query);
if query.is_empty() {
return (0..entries.len()).filter_map(|i| u32::try_from(i).ok()).collect();
@@ -858,7 +860,8 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32]
let meant_tier = if synonym { best_reading(&query, &starts, &tokens, &meant, |read| phrase(e, read, false)) } else { tier };
let length = split_name(&e.shown).0.chars().count();
let picked = recent.iter().position(|&r| r == place).unwrap_or(recent.len());
ranked.push(((described, typo, tier, worst, sum, meant_tier, picked, e.kind, length), place));
let used = std::cmp::Reverse(uses.get(i).copied().unwrap_or(0));
ranked.push(((described, typo, tier, worst, sum, meant_tier, used, picked, e.kind, length), place));
}
ranked.sort_by_key(|&(key, place)| (key, place));
ranked.into_iter().map(|(_, place)| place).collect()
@@ -966,8 +969,15 @@ mod tests {
/// The ids of the results `query` lists, best first, with the results of ids `picked` as the
/// recent picks, most recent first.
fn recently(c: &Catalog, query: &str, picked: &[&str]) -> Vec<String> {
used(c, query, picked, &[])
}
/// The ids of the results `query` lists, best first, with the results of ids `picked` as the
/// recent picks, most recent first, and the results of ids `counted` given those use grades.
fn used(c: &Catalog, query: &str, picked: &[&str], counted: &[(&str, u8)]) -> Vec<String> {
let recent: Vec<u32> = picked.iter().filter_map(|id| c.list.iter().position(|e| e.id == *id)).filter_map(|i| u32::try_from(i).ok()).collect();
rank(&c.list, &c.index, query, &recent).iter().filter_map(|&i| c.list.get(i as usize)).map(|e| e.id.clone()).collect()
let uses: Vec<u8> = c.list.iter().map(|e| counted.iter().find(|(id, _)| e.id == *id).map_or(0, |&(_, g)| g)).collect();
rank(&c.list, &c.index, query, &recent, &uses).iter().filter_map(|&i| c.list.get(i as usize)).map(|e| e.id.clone()).collect()
}
/// A result named `name` (`›`-separated, its last part the label) with id `id`.
@@ -1095,13 +1105,11 @@ mod tests {
assert_eq!(ranked(&c, "same zz"), ranked(&c, "same zz"));
}
/// For each pair of adjacent grades and whole-query tiers, a recent pick ranks above a result
/// that matches the query as well as it does and comes earlier in the catalog, and below the
/// result that matches better; of two such recent picks, the more recent ranks first.
#[test]
fn a_recent_pick_ranks_first_within_its_grades() {
/// For each pair of adjacent grades and whole-query tiers: a query, a result that matches it
/// better, one that matches it as the next grade or tier, and the description of the latter.
fn adjacent_grades() -> [(&'static str, Entry, Entry, &'static str); 14] {
let description = "{} keeps the art central on the page";
for (query, better, worse, said) in [
[
("cut zz", entry("Zz Cut", "a.one"), entry("Zz Cutter", "b.two"), ""),
("scale zz", entry("Zz Scale", "a.one"), entry("Zz Scaling", "b.two"), ""),
("scale zz", entry("Zz Scaling", "a.one"), entry("Zz Scalers", "scale.two"), ""),
@@ -1120,7 +1128,15 @@ mod tests {
("remove", entry("Zz Remove", "a.one"), entry("Zz Delete", "b.two"), ""),
// Matches through a word of the same meaning: the whole label, then a word of it.
("colour", entry("Color", "a.one"), entry("Zz Color", "b.two"), ""),
] {
]
}
/// For each pair of adjacent grades and whole-query tiers, a recent pick ranks above a result
/// that matches the query as well as it does and comes earlier in the catalog, and below the
/// result that matches better; of two such recent picks, the more recent ranks first.
#[test]
fn a_recent_pick_ranks_first_within_its_grades() {
for (query, better, worse, said) in adjacent_grades() {
let (b, w) = (better.id.clone(), worse.id.clone());
// A second result that matches as the worse one does and comes before it.
let twin = entry(&worse.shown, &format!("{w}x"));
@@ -1137,6 +1153,31 @@ mod tests {
assert_eq!(recently(&c, "", &["b.two"]), ["a.one", "b.two"]);
}
/// For each pair of adjacent grades and whole-query tiers, a result picked often ranks above a
/// result that matches the query as well as it does and comes earlier in the catalog, and below
/// the result that matches better, which was never picked. Of two such results, the
/// one with the higher use grade ranks first, and a recent pick ranks first only among results
/// of the same use grade.
#[test]
fn a_command_picked_often_ranks_first_within_its_grades() {
for (query, better, worse, said) in adjacent_grades() {
let (b, w) = (better.id.clone(), worse.id.clone());
// A second result that matches as the worse one does and comes before it.
let twin = entry(&worse.shown, &format!("{w}x"));
let t = twin.id.clone();
let c = described(vec![twin, worse, better], &[said, said, ""]);
let (b, w, t) = (b.as_str(), w.as_str(), t.as_str());
assert_eq!(used(&c, query, &[], &[(w, 1)]), [b, w, t], "{query}: one pick ranks above none");
assert_eq!(used(&c, query, &[], &[(w, 9), (t, 3)]), [b, w, t], "{query}: the higher grade first");
assert_eq!(used(&c, query, &[], &[(w, 1), (t, 3)]), [b, t, w], "{query}: the higher grade first");
assert_eq!(used(&c, query, &[w], &[(t, 1)]), [b, t, w], "{query}: a recent pick within its use grade");
assert_eq!(used(&c, query, &[w], &[(w, 1), (t, 1)]), [b, w, t], "{query}: a recent pick within its use grade");
}
// An empty query lists every result in catalog order.
let c = synthetic(vec![entry("Zz One", "a.one"), entry("Zz Two", "b.two")]);
assert_eq!(used(&c, "", &[], &[("b.two", 9)]), ["a.one", "b.two"]);
}
/// A query that is a menu's title ranks a result whose label holds it as a word above the items
/// of that menu, which match only by their menu path. A query that names the menu with `›`
/// still starts the item's name.
@@ -1147,7 +1188,7 @@ mod tests {
assert_eq!(ranked(&c, "object › pa"), ["a.one"]);
let en = catalog(Lang::EN, false);
for q in ["object", "effect", "select", "view", "type", "edit"] {
let first = rank(&en.list, &en.index, q, &[]).first().and_then(|&i| en.list.get(i as usize)).map(|e| e.shown.to_lowercase());
let first = rank(&en.list, &en.index, q, &[], &[]).first().and_then(|&i| en.list.get(i as usize)).map(|e| e.shown.to_lowercase());
let label = first.as_deref().map(|n| split_name(n).0.to_string()).unwrap_or_default();
assert!(words(&label).any(|w| w.starts_with(q)), "{q}: {first:?}");
}
@@ -1362,7 +1403,7 @@ mod tests {
] {
assert!(substring_rule(&c, typo).is_empty(), "{typo} matched nothing before");
let top = |q: &str| ranked(&c, q).into_iter().take(4).collect::<Vec<_>>();
let spelled_right: Vec<String> = rank(&c.list, &plain, word, &[]).iter().take(4).map(id).collect();
let spelled_right: Vec<String> = rank(&c.list, &plain, word, &[], &[]).iter().take(4).map(id).collect();
assert_eq!(top(typo), spelled_right, "{typo}");
assert!(place(&c, typo, tool).is_some_and(|p| p < 4), "{typo}: {:?}", ranked(&c, typo));
}
@@ -1923,7 +1964,7 @@ mod tests {
let started = std::time::Instant::now();
let runs = 100;
for _ in 0..runs {
std::hint::black_box(rank(&c.list, &c.index, q, &[]));
std::hint::black_box(rank(&c.list, &c.index, q, &[], &[]));
}
println!("{:>12}: {:?} per query", q.get(..12).unwrap_or(q), started.elapsed() / runs);
}
+5
View File
@@ -762,6 +762,10 @@ pub struct UiState {
/// Help › Search Commands' Recent Commands list: the ids of the last picks, most recent first.
#[serde(default)]
pub recent_commands: Vec<String>,
/// How many times each command was picked in Help › Search Commands, which ranks the commands
/// picked most often first among results that match as well.
#[serde(default, deserialize_with = "crate::palette::deserialize_command_uses")]
pub command_uses: crate::palette::CommandUses,
/// Families starred in the font menus (the ★ filter shows only these).
#[serde(default)]
pub favorite_fonts: Vec<String>,
@@ -1348,6 +1352,7 @@ impl Default for UiState {
recent_files: vec![],
recent_fonts: vec![],
recent_commands: vec![],
command_uses: Default::default(),
favorite_fonts: vec![],
engine_prefs: Value::Null,
original_editor: Default::default(),
+2 -1
View File
@@ -1567,7 +1567,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`).
A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`).
A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`).
The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do, 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, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades and the matches through a typo, a description or a word with the same meaning, 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 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`).
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`).