mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 10:46:46 +00:00
Command Palette: a small search index ranks the best match first
Results are ordered by how well they match instead of by registration
order. A query equal to a result's id lists it first; then come results
whose name is the query, whose name starts with it, and whose initials
it is ("ea" finds Export As…). Within those, a whole word of the name
ranks above a word it starts, then a word of the menu that holds the
result, of its id, and text inside a word. At equal grades a tool ranks
above a menu command, panel, effect or filter plug-in, and a shorter
name above a longer one.
The words of the menu bar item that runs a result, its own label
included, also find it, read from the native menu bar when the app uses
it. The index is built when the palette first opens after the language,
plug-ins, shortcuts or menu bar change, and the last query's ranking is
kept. Every result the earlier search found is still found, an empty
query keeps the old order, and the highlight stays on its result when
the results change while the palette is open.
This commit is contained in:
+143
-31
@@ -8,6 +8,8 @@ use serde_json::json;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{VectorcraftApp, menus};
|
||||
|
||||
mod search;
|
||||
|
||||
/// Engine commands the palette leaves out, each with the UI command of the same name that runs it
|
||||
/// the way the panels and menus do: (engine id, UI command id). The Layers panel's Delete
|
||||
/// Selection asks before deleting a layer that holds art, and the other UI commands open the
|
||||
@@ -275,35 +277,82 @@ pub(crate) struct Entry {
|
||||
/// label and the id (and the id of the engine command a UI command wraps), lowercased, one per
|
||||
/// line: a query word (which has no line break) matches within one of them.
|
||||
haystack: String,
|
||||
/// The English menu path of the first item of the menu bar shown that runs the entry
|
||||
/// ([`search::menu_homes`]), if one does.
|
||||
home: Option<String>,
|
||||
/// The English label of that item of the menu bar, which may differ from the entry's (File ›
|
||||
/// Exit runs Quit VectorCraft), or empty.
|
||||
menu_item: &'static str,
|
||||
/// The entry's kind, in the order [`search::kind`] ranks kinds.
|
||||
kind: u8,
|
||||
}
|
||||
|
||||
/// The palette's entries, the index a query is looked up in, and the last query's ranked results.
|
||||
pub(crate) struct Catalog {
|
||||
list: Vec<Entry>,
|
||||
index: search::Index,
|
||||
ranked: std::sync::Mutex<Option<(String, Arc<[u32]>)>>,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Catalog {
|
||||
type Target = [Entry];
|
||||
|
||||
fn deref(&self) -> &[Entry] {
|
||||
&self.list
|
||||
}
|
||||
}
|
||||
|
||||
/// The palette's entries in `lang`. They are built when the language, the installed plug-ins or
|
||||
/// the keyboard shortcuts (shown beside each entry) change, not on every frame while a query is
|
||||
/// typed.
|
||||
/// What the entries depend on: the language, the installed plug-ins and the shortcuts.
|
||||
fn cache_key(lang: crate::i18n::Lang) -> (&'static str, u64, u64) {
|
||||
(lang.code(), menus::plugin_revision(), crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
fn entries(ctx: &egui::Context, lang: crate::i18n::Lang) -> Arc<Vec<Entry>> {
|
||||
type Cached = ((&'static str, u64, u64), Arc<Vec<Entry>>);
|
||||
/// The palette's entries in `lang` with the in-window menu bar.
|
||||
#[cfg(test)]
|
||||
fn entries(ctx: &egui::Context, lang: crate::i18n::Lang) -> Arc<Catalog> {
|
||||
entries_in(ctx, lang, false)
|
||||
}
|
||||
|
||||
/// The palette's entries in `lang`, with the native menu bar when `native`. They and their index
|
||||
/// are built the first time the palette opens after the language, the installed plug-ins, the
|
||||
/// keyboard shortcuts (shown beside each entry) or the menu bar change, not at start and not on
|
||||
/// every frame while a query is typed.
|
||||
fn entries_in(ctx: &egui::Context, lang: crate::i18n::Lang, native: bool) -> Arc<Catalog> {
|
||||
type Cached = ((&'static str, u64, u64), bool, Arc<Catalog>);
|
||||
let key = cache_key(lang);
|
||||
let id = egui::Id::unique("palette-entries");
|
||||
if let Some((k, v)) = ctx.data(|d| d.get_temp::<Cached>(id))
|
||||
if let Some((k, n, v)) = ctx.data(|d| d.get_temp::<Cached>(id))
|
||||
&& k == key
|
||||
&& n == native
|
||||
{
|
||||
return v;
|
||||
}
|
||||
let built: Arc<Vec<Entry>> = Arc::new(build(lang));
|
||||
ctx.data_mut(|d| d.insert_temp::<Cached>(id, (key, built.clone())));
|
||||
let built = Arc::new(catalog(lang, native));
|
||||
ctx.data_mut(|d| d.insert_temp::<Cached>(id, (key, native, built.clone())));
|
||||
built
|
||||
}
|
||||
|
||||
/// The entries of [`build_in`] and their index.
|
||||
fn catalog(lang: crate::i18n::Lang, native: bool) -> Catalog {
|
||||
let list = build_in(lang, native);
|
||||
let shown_homes: Vec<Option<String>> =
|
||||
list.iter().map(|e| e.home.as_deref().map(|h| format!("{} › {}", shown_label(lang, h), crate::i18n::tr(lang, e.menu_item)))).collect();
|
||||
let index = search::Index::build(&list, &shown_homes);
|
||||
Catalog { list, index, ranked: std::sync::Mutex::new(None) }
|
||||
}
|
||||
|
||||
/// The palette's entries in `lang` with the in-window menu bar.
|
||||
#[cfg(test)]
|
||||
fn build(lang: crate::i18n::Lang) -> Vec<Entry> {
|
||||
build_in(lang, false)
|
||||
}
|
||||
|
||||
/// The palette's entries in `lang`: [`items`], then one per filter plug-in's Object › Plug-ins
|
||||
/// item (`plugin:<id>`), whose name is not translated, each with a name no result for another id
|
||||
/// shows, in English and in `lang` ([`distinct_names`]). A query still matches the name before
|
||||
/// it was made distinct.
|
||||
fn build(lang: crate::i18n::Lang) -> Vec<Entry> {
|
||||
/// it was made distinct. Each entry's menu home is read from the native menu bar when `native`.
|
||||
fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec<Entry> {
|
||||
let homes = search::menu_homes(native);
|
||||
let mut drafts = drafts();
|
||||
drafts.extend(crate::shortcut_editor::filter_items().iter().map(|f| Draft {
|
||||
translates: false,
|
||||
@@ -322,7 +371,9 @@ fn build(lang: crate::i18n::Lang) -> Vec<Entry> {
|
||||
haystack.push('\n');
|
||||
haystack.push_str(&engine.to_lowercase());
|
||||
}
|
||||
Entry { id: d.id, shortcut: d.shortcut, shown, haystack }
|
||||
let (home, menu_item) = homes.get(&d.id).map_or((None, ""), |(path, item)| (Some(path.clone()), *item));
|
||||
let kind = search::kind(&d.id, home.as_deref());
|
||||
Entry { id: d.id, shortcut: d.shortcut, shown, haystack, home, menu_item, kind }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -362,19 +413,21 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every entry that holds every word of the lowercased query `q`, the ones whose name without its
|
||||
/// menu path is the query (the Layers panel for "layers") first, each group in catalog order.
|
||||
/// [`show`] lists the first [`MAX_RESULTS`] and counts the rest.
|
||||
fn matching<'a>(entries: &'a [Entry], q: &str) -> Vec<&'a Entry> {
|
||||
let words: Vec<&str> = q.split_whitespace().collect();
|
||||
let whole = words.join(" ");
|
||||
// The plain, English and shown names are the haystack's first three lines.
|
||||
let named = |e: &Entry| e.haystack.lines().take(3).any(|l| l.rsplit(" › ").next().is_some_and(|n| n.trim_end_matches('…') == whole));
|
||||
let mut found: Vec<&Entry> = entries.iter().filter(|e| words.iter().all(|w| e.haystack.contains(w))).collect();
|
||||
if !whole.is_empty() {
|
||||
found.sort_by_key(|e| !named(e));
|
||||
}
|
||||
found
|
||||
/// The entries the query `q` matches, best first ([`search::rank`]). The ranking of the last query
|
||||
/// is kept, so a frame that draws the same query does not rank again. [`show`] lists the first
|
||||
/// [`MAX_RESULTS`] and counts the rest.
|
||||
fn matching<'a>(catalog: &'a Catalog, q: &str) -> Vec<&'a Entry> {
|
||||
let q = search::normalize(q);
|
||||
let kept = catalog.ranked.lock().ok().and_then(|last| last.as_ref().filter(|(k, _)| *k == q).map(|(_, r)| r.clone()));
|
||||
let ranked = kept.unwrap_or_else(|| {
|
||||
let ranked: Arc<[u32]> = search::rank(&catalog.list, &catalog.index, &q).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, ranked.clone()));
|
||||
}
|
||||
ranked
|
||||
});
|
||||
ranked.iter().filter_map(|&i| catalog.list.get(i as usize)).collect()
|
||||
}
|
||||
|
||||
/// The height of a result row, in points: one line of 13-point body text.
|
||||
@@ -461,8 +514,9 @@ fn nearest_in_view(sel: usize, offset: f32, view: f32, n: usize) -> usize {
|
||||
sel.clamp(first, last)
|
||||
}
|
||||
|
||||
/// The highlighted result, the query it belongs to, the list's scroll offset and the list's height.
|
||||
type Highlight = (usize, String, f32, f32);
|
||||
/// The highlighted result, the query it belongs to, the list's scroll offset, the list's height
|
||||
/// and the highlighted result's id.
|
||||
type Highlight = (usize, String, f32, f32, String);
|
||||
|
||||
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
// The widget that had the keyboard focus when the palette opened takes it back when the palette
|
||||
@@ -492,7 +546,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
crate::shortcuts::hold_back_keys(app, ctx);
|
||||
let t = Tokens::get(ctx);
|
||||
let q = app.ui.palette_query.to_lowercase();
|
||||
let entries = entries(ctx, crate::i18n::current());
|
||||
let entries = entries_in(ctx, crate::i18n::current(), app.services.native_menu.is_some());
|
||||
let mut matches = matching(&entries, &q);
|
||||
let total = matches.len();
|
||||
matches.truncate(MAX_RESULTS);
|
||||
@@ -500,12 +554,19 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
// 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.
|
||||
let sel_id = egui::Id::unique("palette-selected");
|
||||
let (mut sel, last_q, mut offset, last_view) = ctx.data(|d| d.get_temp::<Highlight>(sel_id)).unwrap_or_default();
|
||||
let (mut sel, last_q, mut offset, last_view, last_id) = ctx.data(|d| d.get_temp::<Highlight>(sel_id)).unwrap_or_default();
|
||||
let mut view = last_view;
|
||||
let new_query = last_q != q;
|
||||
// The highlight stays on its result when the results change under the same query, as when a
|
||||
// plug-in is installed, a shortcut changes or the language changes; it goes to the first
|
||||
// result when its result is gone.
|
||||
let held = sel;
|
||||
if new_query {
|
||||
sel = 0;
|
||||
} else if matches.get(sel).is_none_or(|e| e.id != last_id) {
|
||||
sel = matches.iter().position(|e| e.id == last_id).unwrap_or(0);
|
||||
}
|
||||
let moved = sel != held;
|
||||
let n = matches.len();
|
||||
let mut moves = Moves::default();
|
||||
if n > 0 {
|
||||
@@ -569,7 +630,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
// `show_rows` adds the item spacing to each row, and rows touch.
|
||||
ui.spacing_mut().item_spacing = egui::Vec2::ZERO;
|
||||
let mut area = egui::ScrollArea::vertical().id_salt("palette-results").max_height(view).auto_shrink([false, true]);
|
||||
if new_query || moves.any() || resized {
|
||||
if new_query || moves.any() || resized || moved {
|
||||
offset = offset_showing(sel, if new_query { 0.0 } else { offset }, view);
|
||||
area = area.vertical_scroll_offset(offset);
|
||||
}
|
||||
@@ -639,7 +700,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if sel != drawn {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
ctx.data_mut(|d| d.insert_temp::<Highlight>(sel_id, (sel, q, offset, view)));
|
||||
let sel_key = matches.get(sel).map(|e| e.id.clone()).unwrap_or_default();
|
||||
ctx.data_mut(|d| d.insert_temp::<Highlight>(sel_id, (sel, q, offset, view, sel_key)));
|
||||
if let Some(id) = run {
|
||||
app.ui.palette_open = false;
|
||||
run_pick(app, &id);
|
||||
@@ -1312,7 +1374,7 @@ mod tests {
|
||||
/// leaves it showing rather than hiding it as the Window menu item does.
|
||||
#[test]
|
||||
fn a_panel_is_a_result_whose_pick_shows_it() {
|
||||
let entries = build(Lang::EN);
|
||||
let entries = catalog(Lang::EN, false);
|
||||
let panels: Vec<&Entry> = entries.iter().filter(|e| e.id.starts_with("panel:")).collect();
|
||||
assert_eq!(panels.len(), crate::state::all_panels().count());
|
||||
// Many results hold "layers" in their menu path; the panel, named Layers, is shown first, and "color guide" shows the Color Guide panel first too.
|
||||
@@ -2078,4 +2140,54 @@ mod tests {
|
||||
assert!(!window.app.ui.palette_open);
|
||||
assert!(crate::panel_docking::showing(&window.app.ui, &panel), "{panel}: {}", window.app.ui.status);
|
||||
}
|
||||
|
||||
/// The entries and their index are built when the palette first opens, not before.
|
||||
#[test]
|
||||
fn the_search_index_is_built_when_the_palette_opens() {
|
||||
type Cached = ((&'static str, u64, u64), bool, Arc<Catalog>);
|
||||
let built = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<Cached>(egui::Id::unique("palette-entries"))).is_some();
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
let frame = |app: &mut VectorcraftApp| {
|
||||
ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui.ctx())).textures_delta.clear();
|
||||
};
|
||||
frame(&mut app);
|
||||
assert!(!built(&ctx), "nothing is built while the palette is closed");
|
||||
app.ui.palette_open = true;
|
||||
frame(&mut app);
|
||||
assert!(built(&ctx));
|
||||
}
|
||||
|
||||
/// The highlight stays on its result when the results change under the same query: when a
|
||||
/// plug-in whose name ranks above it is installed, a shortcut changes, or the language
|
||||
/// changes.
|
||||
#[test]
|
||||
fn the_highlight_stays_on_its_result_when_the_results_change() {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let mut open = Open::new("group", WINDOW);
|
||||
open.press(egui::Key::ArrowDown, 3);
|
||||
let held = |open: &Open| open.ctx.data(|d| d.get_temp::<Highlight>(egui::Id::unique("palette-selected"))).unwrap();
|
||||
let id = held(&open).4;
|
||||
assert_eq!(open.listed().get(3), Some(&id));
|
||||
let filter = "test.UI.palette_highlight-group";
|
||||
let manifest = format!(r#"{{"id":"{filter}","name":"Group","version":"1","kind":"filter","params":{{}}}}"#);
|
||||
vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
open.frame(vec![]);
|
||||
let listed = open.listed();
|
||||
let plugin = listed.iter().position(|r| *r == format!("plugin:{filter}"));
|
||||
vectorcraft_plugins::registry::remove(filter);
|
||||
assert!(plugin.is_some_and(|p| p < 3), "the plug-in ranks above the highlight: {listed:?}");
|
||||
let (sel, .., now) = held(&open);
|
||||
assert_eq!((listed.get(sel), &now), (Some(&id), &id), "after the plug-in was installed");
|
||||
crate::shortcut_editor::GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
open.frame(vec![]);
|
||||
assert_eq!(held(&open).4, id, "after a shortcut changed");
|
||||
crate::i18n::set_current(Lang::from_code("de").unwrap());
|
||||
open.frame(vec![]);
|
||||
let (sel, .., now) = held(&open);
|
||||
let de = entries(&open.ctx, Lang::from_code("de").unwrap());
|
||||
let de_listed: Vec<String> = matching(&de, "group").iter().map(|e| e.id.clone()).collect();
|
||||
crate::i18n::set_current(Lang::EN);
|
||||
assert_eq!((de_listed.get(sel), &now), (Some(&id), &id), "after the language changed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,705 @@
|
||||
//! The command palette's search: a small index of the words in each result's label, menu path and
|
||||
//! id, the menu bar's home of each result, and the ranking of the results a query matches.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{Entry, WRAPPED};
|
||||
use crate::menus;
|
||||
|
||||
/// The most characters of a query the index reads (VectorCraft's own limit). The substring rule
|
||||
/// and the exact tiers read the whole query.
|
||||
const INDEX_CHARS: usize = 200;
|
||||
|
||||
/// The field of a result a word comes from, best first.
|
||||
const LABEL: u8 = 0;
|
||||
const PATH: u8 = 1;
|
||||
const ID: u8 = 2;
|
||||
|
||||
/// A word's grade in a result, best first: a whole word of the label, a word of the label it
|
||||
/// starts, a word of the menu path it is or starts, a word of the id it is or starts, or text
|
||||
/// inside a word of any field ([`super::matching`]'s substring rule).
|
||||
const LABEL_WORD: u8 = 1;
|
||||
const LABEL_PREFIX: u8 = 2;
|
||||
const PATH_WORD: u8 = 3;
|
||||
const ID_WORD: u8 = 4;
|
||||
const SUBSTRING: u8 = 5;
|
||||
const NONE: u8 = u8::MAX;
|
||||
|
||||
/// How a whole query matches a result, best first: it is the result's id, it is a label, a label
|
||||
/// starts with it, or it is the initials of a label.
|
||||
const EXACT_ID: u8 = 0;
|
||||
const EXACT_LABEL: u8 = 1;
|
||||
const PREFIX: u8 = 2;
|
||||
const INITIALS: u8 = 3;
|
||||
const NO_PHRASE: u8 = 4;
|
||||
|
||||
/// One result in the list of a term: the result's place in the catalog and the field the term is
|
||||
/// a word of.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Posting {
|
||||
entry: u16,
|
||||
field: u8,
|
||||
}
|
||||
|
||||
/// The words of every result, each distinct word stored once.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Index {
|
||||
/// Every distinct word, one after another.
|
||||
term_text: String,
|
||||
/// Each word's offset and length in `term_text`, sorted by the word's text.
|
||||
terms: Vec<(u32, u32)>,
|
||||
/// Each word's first posting and number of postings in `postings`, in the order of `terms`.
|
||||
spans: Vec<(u32, u32)>,
|
||||
postings: Vec<Posting>,
|
||||
/// The initials of each result's labels, one line per label.
|
||||
initials_text: String,
|
||||
/// Each result's offset and length in `initials_text`.
|
||||
initials: Vec<(u32, u16)>,
|
||||
}
|
||||
|
||||
/// Splits `text` into lowercase words at whitespace and at `.`, `-`, `/`, `(`, `)`, `…`, `›`, `,`
|
||||
/// and `:`.
|
||||
fn words(text: &str) -> impl Iterator<Item = &str> {
|
||||
text.split(|c: char| c.is_whitespace() || matches!(c, '.' | '-' | '/' | '(' | ')' | '…' | '›' | ',' | ':')).filter(|w| !w.is_empty())
|
||||
}
|
||||
|
||||
/// The first letter of each word of `label`, words split at whitespace and at `-`, `/`, `(` and
|
||||
/// `›`, lowercased.
|
||||
fn initials_of(label: &str) -> String {
|
||||
label
|
||||
.split(|c: char| c.is_whitespace() || matches!(c, '-' | '/' | '(' | '›'))
|
||||
.filter_map(|w| w.chars().find(|c| c.is_alphanumeric()))
|
||||
.flat_map(char::to_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A name's last `›`-separated part (the label) and the parts before it (the menu path).
|
||||
fn split_name(name: &str) -> (&str, &str) {
|
||||
match name.rsplit_once(" › ") {
|
||||
Some((path, label)) => (label, path),
|
||||
None => (name, ""),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` without the id that follows it when the result shows its id.
|
||||
fn without_id<'a>(name: &'a str, id: &str) -> &'a str {
|
||||
name.strip_suffix(')').and_then(|n| n.strip_suffix(id)).and_then(|n| n.strip_suffix(" (")).unwrap_or(name)
|
||||
}
|
||||
|
||||
/// The lowercased names a result is found by: the plain English name, the English name and the
|
||||
/// shown name ([`super::build`]'s haystack lines).
|
||||
fn names(e: &Entry) -> impl Iterator<Item = &str> {
|
||||
e.haystack.lines().take(3)
|
||||
}
|
||||
|
||||
/// The lowercased ids a result is found by: its own, and the engine command's a UI command wraps.
|
||||
fn ids(e: &Entry) -> impl Iterator<Item = &str> {
|
||||
e.haystack.lines().skip(3)
|
||||
}
|
||||
|
||||
impl Index {
|
||||
/// The index of `entries`, whose menu homes and menu items read `homes` in the UI language. The
|
||||
/// words of a result's menu home and of its menu item's label count as menu path words. A
|
||||
/// catalog with more results than a posting can name gets an empty index, and queries match by
|
||||
/// the substring rule alone.
|
||||
pub(crate) fn build(entries: &[Entry], homes: &[Option<String>]) -> Index {
|
||||
if entries.len() > usize::from(u16::MAX) {
|
||||
return Index::default();
|
||||
}
|
||||
let mut found: Vec<(String, u16, u8)> = vec![];
|
||||
let mut initials_text = String::new();
|
||||
let mut initials = Vec::with_capacity(entries.len());
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
let Ok(entry) = u16::try_from(i) else { break };
|
||||
let id = ids(e).next().unwrap_or_default();
|
||||
let start = initials_text.len();
|
||||
let mut seen_initials: Vec<String> = vec![];
|
||||
for name in names(e) {
|
||||
let (label, path) = split_name(without_id(name, id));
|
||||
found.extend(words(label).map(|w| (w.to_string(), entry, LABEL)));
|
||||
found.extend(words(path).map(|w| (w.to_string(), entry, PATH)));
|
||||
let ini = initials_of(label);
|
||||
if ini.chars().count() >= 2 && !seen_initials.contains(&ini) {
|
||||
if !seen_initials.is_empty() {
|
||||
initials_text.push('\n');
|
||||
}
|
||||
initials_text.push_str(&ini);
|
||||
seen_initials.push(ini);
|
||||
}
|
||||
}
|
||||
for home in [e.home.as_deref(), Some(e.menu_item), homes.get(i).and_then(Option::as_deref)].into_iter().flatten() {
|
||||
found.extend(words(&home.to_lowercase()).map(|w| (w.to_string(), entry, PATH)));
|
||||
}
|
||||
for id in ids(e) {
|
||||
found.extend(words(id).map(|w| (w.to_string(), entry, ID)));
|
||||
}
|
||||
let len = u16::try_from(initials_text.len() - start).unwrap_or(0);
|
||||
initials.push((u32::try_from(start).unwrap_or(0), len));
|
||||
}
|
||||
found.sort_unstable();
|
||||
found.dedup();
|
||||
let mut index = Index { initials_text, initials, ..Index::default() };
|
||||
let mut last: Option<&str> = None;
|
||||
for (word, entry, field) in &found {
|
||||
if last != Some(word.as_str()) {
|
||||
let (Ok(offset), Ok(len), Ok(start)) =
|
||||
(u32::try_from(index.term_text.len()), u32::try_from(word.len()), u32::try_from(index.postings.len()))
|
||||
else {
|
||||
return Index::default();
|
||||
};
|
||||
index.term_text.push_str(word);
|
||||
index.terms.push((offset, len));
|
||||
index.spans.push((start, 0));
|
||||
last = Some(word.as_str());
|
||||
}
|
||||
index.postings.push(Posting { entry: *entry, field: *field });
|
||||
if let Some(span) = index.spans.last_mut() {
|
||||
span.1 += 1;
|
||||
}
|
||||
}
|
||||
index.term_text.shrink_to_fit();
|
||||
index.terms.shrink_to_fit();
|
||||
index.spans.shrink_to_fit();
|
||||
index.postings.shrink_to_fit();
|
||||
index.initials_text.shrink_to_fit();
|
||||
index.initials.shrink_to_fit();
|
||||
index
|
||||
}
|
||||
|
||||
/// The bytes the index holds.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
self.term_text.capacity()
|
||||
+ self.terms.capacity() * std::mem::size_of::<(u32, u32)>()
|
||||
+ self.spans.capacity() * std::mem::size_of::<(u32, u32)>()
|
||||
+ self.postings.capacity() * std::mem::size_of::<Posting>()
|
||||
+ self.initials_text.capacity()
|
||||
+ self.initials.capacity() * std::mem::size_of::<(u32, u16)>()
|
||||
}
|
||||
|
||||
/// The text of the word at `(offset, len)` in `term_text`.
|
||||
fn text(&self, &(offset, len): &(u32, u32)) -> &str {
|
||||
let offset = offset as usize;
|
||||
self.term_text.get(offset..offset + len as usize).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The best grade (1 to 4) `word` gets in each result, [`NONE`] where it is no word and starts
|
||||
/// no word of the result. The words it starts are found by a binary search of the sorted words.
|
||||
fn grades(&self, word: &str, n: usize) -> Vec<u8> {
|
||||
let mut out = vec![NONE; n];
|
||||
let start = self.terms.partition_point(|t| self.text(t) < word);
|
||||
for (t, at) in self.terms.iter().enumerate().skip(start) {
|
||||
let term = self.text(at);
|
||||
if !term.starts_with(word) {
|
||||
break;
|
||||
}
|
||||
let whole = term == word;
|
||||
let Some(&(begin, len)) = self.spans.get(t) else { continue };
|
||||
let (begin, len) = (begin as usize, len as usize);
|
||||
for p in self.postings.get(begin..begin + len).unwrap_or_default() {
|
||||
let grade = match p.field {
|
||||
LABEL if whole => LABEL_WORD,
|
||||
LABEL => LABEL_PREFIX,
|
||||
PATH => PATH_WORD,
|
||||
_ => ID_WORD,
|
||||
};
|
||||
if let Some(g) = out.get_mut(usize::from(p.entry)) {
|
||||
*g = (*g).min(grade);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Is `query` (no spaces) the initials of one of result `i`'s labels?
|
||||
fn initials_are(&self, i: usize, query: &str) -> bool {
|
||||
let Some(&(offset, len)) = self.initials.get(i) else { return false };
|
||||
let (offset, len) = (offset as usize, usize::from(len));
|
||||
self.initials_text.get(offset..offset + len).is_some_and(|text| text.lines().any(|l| l == query))
|
||||
}
|
||||
}
|
||||
|
||||
/// `query` trimmed, lowercased, with each run of whitespace made one space.
|
||||
pub(crate) fn normalize(query: &str) -> String {
|
||||
query.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()
|
||||
}
|
||||
|
||||
/// The order of a result's kind when everything else ties: a tool, a command of the menu bar, a
|
||||
/// panel, an effect, a filter plug-in, then a command with no item in the menu bar.
|
||||
pub(crate) fn kind(id: &str, home: Option<&str>) -> u8 {
|
||||
match id.split_once(':').map(|(k, _)| k) {
|
||||
Some("tool") => 0,
|
||||
Some("panel") => 2,
|
||||
Some("effect") => 3,
|
||||
Some("plugin") => 4,
|
||||
_ if home.is_some() => 1,
|
||||
_ => 5,
|
||||
}
|
||||
}
|
||||
|
||||
/// How the whole lowercased `query` matches result `e` ([`EXACT_ID`] to [`NO_PHRASE`]), where
|
||||
/// `initials` says whether the query is the initials of one of its labels.
|
||||
fn phrase(e: &Entry, query: &str, initials: bool) -> u8 {
|
||||
if ids(e).any(|id| id == query) {
|
||||
return EXACT_ID;
|
||||
}
|
||||
let trimmed = query.trim_end_matches('…');
|
||||
let labels = || names(e).flat_map(|n| [n, split_name(n).0]);
|
||||
if labels().any(|l| l == query || l.trim_end_matches('…') == trimmed) {
|
||||
return EXACT_LABEL;
|
||||
}
|
||||
if labels().any(|l| l.starts_with(query)) {
|
||||
return PREFIX;
|
||||
}
|
||||
if initials {
|
||||
return INITIALS;
|
||||
}
|
||||
NO_PHRASE
|
||||
}
|
||||
|
||||
/// What results are ordered by, compared field by field: how the whole query matches, the worst
|
||||
/// grade a word gets, the sum of the grades, the kind of result and the label's length.
|
||||
type RankKey = (u8, u8, u32, 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
|
||||
/// (the rule the palette always had, so nothing it found is lost), when every word of the query is
|
||||
/// or starts a word of its label, menu path or id, or when the query is the initials of a label
|
||||
/// ("ea" for Export As…). Results are ordered by how the whole query matches ([`phrase`]), then by
|
||||
/// the worst grade a word gets, the sum of the grades, the kind of result ([`kind`]), the label's
|
||||
/// length and the catalog order. An empty query lists every result in catalog order.
|
||||
pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec<u32> {
|
||||
let query = normalize(query);
|
||||
if query.is_empty() {
|
||||
return (0..entries.len()).filter_map(|i| u32::try_from(i).ok()).collect();
|
||||
}
|
||||
let spaced: Vec<&str> = query.split(' ').collect();
|
||||
let head: String = query.chars().take(INDEX_CHARS).collect();
|
||||
let tokens: Vec<&str> = words(&head).collect();
|
||||
let n = entries.len();
|
||||
let indexed: Vec<Vec<u8>> = tokens.iter().map(|t| index.grades(t, n)).collect();
|
||||
// The index reads only the start of a longer query, so such a query matches by the substring
|
||||
// rule, which reads all of it.
|
||||
let fits = query.chars().count() <= INDEX_CHARS;
|
||||
let packed: String = query.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
let packed = Some(packed).filter(|p| (2..=6).contains(&p.chars().count()) && p.chars().all(char::is_alphabetic));
|
||||
let mut ranked: Vec<(RankKey, u32)> = vec![];
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
let Ok(place) = u32::try_from(i) else { break };
|
||||
let substring = spaced.iter().all(|w| e.haystack.contains(w));
|
||||
let initials = packed.as_deref().is_some_and(|p| index.initials_are(i, p));
|
||||
// Each word's grade, the worst and their sum; with initials, every word counts as a word
|
||||
// the label starts, as the initials stand for every word of the label.
|
||||
let (mut all_indexed, mut worst, mut sum) = (fits && !tokens.is_empty(), 0u8, 0u32);
|
||||
for (grades, token) in indexed.iter().zip(&tokens) {
|
||||
let mut g = grades.get(i).copied().unwrap_or(NONE);
|
||||
if g == NONE {
|
||||
all_indexed = false;
|
||||
if e.haystack.contains(token) {
|
||||
g = SUBSTRING;
|
||||
}
|
||||
}
|
||||
let g = if initials { g.min(LABEL_PREFIX) } else { g.min(SUBSTRING) };
|
||||
worst = worst.max(g);
|
||||
sum += u32::from(g);
|
||||
}
|
||||
if !(substring || all_indexed || initials) {
|
||||
continue;
|
||||
}
|
||||
let tier = phrase(e, &query, initials);
|
||||
let length = split_name(&e.shown).0.chars().count();
|
||||
ranked.push(((tier, worst, sum, e.kind, length), place));
|
||||
}
|
||||
ranked.sort_by_key(|&(key, place)| (key, place));
|
||||
ranked.into_iter().map(|(_, place)| place).collect()
|
||||
}
|
||||
|
||||
/// The first place in the menu bar of each item a result runs, as an English `›`-separated path
|
||||
/// of the menus that hold it: by command id, `panel:<id>` for a Window menu panel (Learn too),
|
||||
/// `effect:<id>` for an Effect menu item and `plugin:<id>` for an Object › Plug-ins filter. With
|
||||
/// the native Mac menu bar (`native`), About, Preferences (under Settings), Language, Appearance
|
||||
/// and Quit are in the application menu, which comes first, as `native_menu::mac_layout` puts
|
||||
/// them. The in-window menu bar shows no application menu. Each home comes with the English label
|
||||
/// of its item (File › Exit for Quit VectorCraft), empty for the application menu's items.
|
||||
pub(crate) fn menu_homes(native: bool) -> HashMap<String, (String, &'static str)> {
|
||||
fn key(id: &str, p: &serde_json::Value) -> String {
|
||||
let field = |k: &str| p.get(k).and_then(serde_json::Value::as_str);
|
||||
match (id, field("panel"), field("effect"), field("id")) {
|
||||
("window.panel", Some(panel), ..) => format!("panel:{panel}"),
|
||||
("window.learn", ..) => format!("panel:{}", crate::panels::learn::ID),
|
||||
("effect.dialog" | "effect.apply", _, Some(effect), _) => format!("effect:{effect}"),
|
||||
("plugin.dialog", _, _, Some(filter)) => format!("plugin:{filter}"),
|
||||
_ => WRAPPED.iter().find(|(engine, _)| *engine == id).map_or(id, |(_, ui)| ui).to_string(),
|
||||
}
|
||||
}
|
||||
fn walk(items: &[menus::Item], path: &mut Vec<&'static str>, skip: &[&str], out: &mut HashMap<String, (String, &'static str)>) {
|
||||
for it in items {
|
||||
match it {
|
||||
menus::Item::Cmd(label, id, p) if !skip.contains(id) => {
|
||||
out.entry(key(id, p)).or_insert_with(|| (path.join(" › "), *label));
|
||||
}
|
||||
menus::Item::Sub(name, children) => {
|
||||
path.push(name);
|
||||
walk(children, path, skip, out);
|
||||
path.pop();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = HashMap::new();
|
||||
let app_menu: &[(&str, &str)] =
|
||||
&[("help.about", ""), ("edit.preferences", "Settings"), ("app.language", "Language"), ("window.brightness", "Appearance"), ("app.quit", "")];
|
||||
let skip: Vec<&str> = if native { app_menu.iter().map(|(id, _)| *id).collect() } else { vec![] };
|
||||
if native {
|
||||
for (id, sub) in app_menu {
|
||||
let path = if sub.is_empty() { crate::native_menu::APP_NAME.to_string() } else { format!("{} › {sub}", crate::native_menu::APP_NAME) };
|
||||
out.insert((*id).to_string(), (path, ""));
|
||||
}
|
||||
}
|
||||
// The tree's first menu is the application menu, which the in-window bar never shows and
|
||||
// the native bar builds itself.
|
||||
for (name, items) in menus::menu_tree().into_iter().skip(1) {
|
||||
walk(&items, &mut vec![name], &skip, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::{Catalog, catalog};
|
||||
use super::*;
|
||||
use crate::i18n::Lang;
|
||||
|
||||
/// The ids of the results `query` lists, best first.
|
||||
fn ranked(c: &Catalog, query: &str) -> Vec<String> {
|
||||
rank(&c.list, &c.index, query).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`.
|
||||
fn entry(name: &str, id: &str) -> Entry {
|
||||
let home = None;
|
||||
Entry {
|
||||
id: id.to_string(),
|
||||
shortcut: String::new(),
|
||||
shown: name.to_string(),
|
||||
haystack: [name, name, name, id].map(str::to_lowercase).join("\n"),
|
||||
kind: kind(id, home.as_deref()),
|
||||
home,
|
||||
menu_item: "",
|
||||
}
|
||||
}
|
||||
|
||||
/// `entries` with their index.
|
||||
fn synthetic(entries: Vec<Entry>) -> Catalog {
|
||||
let index = Index::build(&entries, &[]);
|
||||
Catalog { list: entries, index, ranked: std::sync::Mutex::new(None) }
|
||||
}
|
||||
|
||||
/// Where `id` is among the results of `query`.
|
||||
fn place(c: &Catalog, query: &str, id: &str) -> Option<usize> {
|
||||
ranked(c, query).iter().position(|r| r == id)
|
||||
}
|
||||
|
||||
/// For each pair of adjacent word grades, a result where the word gets the better grade ranks
|
||||
/// above one where it gets the worse, and both are listed. The second word of each query is a
|
||||
/// whole word of every label, so no whole-query tier applies.
|
||||
#[test]
|
||||
fn a_better_word_grade_ranks_first() {
|
||||
for (query, better, worse) in [
|
||||
// A whole word of the label, then a word of the label it starts.
|
||||
("cut zz", entry("Zz Cut", "a.one"), entry("Zz Cutter", "b.two")),
|
||||
// A word of the label it starts, then a word of the menu path.
|
||||
("fill zz", entry("Zz Filling", "a.one"), entry("Fill › Zz Other", "b.two")),
|
||||
// A word of the menu path, then a word of the id.
|
||||
("zap zz", entry("Zap › Zz One", "a.one"), entry("Zz Two", "zap.two")),
|
||||
// A word of the id, then text inside a word.
|
||||
("zip zz", entry("Zz Three", "zip.three"), entry("Zz Unzipped", "b.two")),
|
||||
] {
|
||||
let (b, w) = (better.id.clone(), worse.id.clone());
|
||||
// The worse one comes first in the catalog, so only the grade puts the better first.
|
||||
let c = synthetic(vec![worse, better]);
|
||||
assert_eq!(ranked(&c, query), [b, w], "{query}");
|
||||
}
|
||||
}
|
||||
|
||||
/// For each pair of adjacent whole-query tiers, a result in the better tier ranks above one in
|
||||
/// the worse.
|
||||
#[test]
|
||||
fn a_better_whole_query_tier_ranks_first() {
|
||||
for (query, better, worse) in [
|
||||
// The query is the result's id, then it is a label.
|
||||
("zz.one", entry("Alpha", "zz.one"), entry("zz.one", "b.two")),
|
||||
// The query is a label, then a label starts with it.
|
||||
("snap", entry("Snap", "a.one"), entry("Snapshot", "b.two")),
|
||||
// A label starts with the query, then the query is a label's initials.
|
||||
("ab", entry("Abacus", "a.one"), entry("Alpha Beta", "b.two")),
|
||||
// The query is a label's initials, then a whole word of a label that it does not start.
|
||||
("gb", entry("Green Blue", "a.one"), entry("Zz Gb", "b.two")),
|
||||
] {
|
||||
let (b, w) = (better.id.clone(), worse.id.clone());
|
||||
let c = synthetic(vec![worse, better]);
|
||||
assert_eq!(ranked(&c, query), [b, w], "{query}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of result and the label's length order results only when the grades tie: a tool
|
||||
/// with a short label stays below a command whose label holds the word whole. Ties keep the
|
||||
/// catalog order, the same on every ranking.
|
||||
#[test]
|
||||
fn kind_and_length_never_lift_a_worse_grade() {
|
||||
let c = synthetic(vec![entry("Zz Cutx", "tool:cutx"), entry("Zz Cut With a Much Longer Label", "a.one")]);
|
||||
assert_eq!(ranked(&c, "cut zz"), ["a.one", "tool:cutx"]);
|
||||
let c = synthetic(vec![entry("Zz Cut Long Label", "a.one"), entry("Zz Cut Long", "b.two"), entry("Zz Cut", "tool:cut")]);
|
||||
assert_eq!(ranked(&c, "cut zz"), ["tool:cut", "b.two", "a.one"], "the tool first, then the shorter label");
|
||||
let c = synthetic(vec![entry("Zz Same", "a.one"), entry("Zz Same", "b.two"), entry("Zz Same", "c.three")]);
|
||||
assert_eq!(ranked(&c, "same zz"), ["a.one", "b.two", "c.three"]);
|
||||
assert_eq!(ranked(&c, "same zz"), ranked(&c, "same zz"));
|
||||
}
|
||||
|
||||
/// Queries from the list of things people type, on the English results.
|
||||
#[test]
|
||||
fn common_queries_list_the_command_first() {
|
||||
let c = catalog(Lang::EN, false);
|
||||
let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default();
|
||||
let within = |q: &str, id: &str, n: usize| place(&c, q, id).is_some_and(|p| p < n);
|
||||
assert_eq!(first("ea"), "file.exportAs", "the initials of Export As…");
|
||||
assert_eq!(first("save"), "file.save");
|
||||
assert!(within("export", "file.exportAs", 3));
|
||||
assert_eq!(first("rect"), "tool:rectangle");
|
||||
let (tool, effect) = (place(&c, "rect", "tool:rectangle"), place(&c, "rect", "effect:convertToShape.rectangle"));
|
||||
assert!(effect.is_some() && tool < effect, "{tool:?} {effect:?}");
|
||||
assert!(within("type", "tool:type", 2));
|
||||
assert!(within("layers", "panel:layers", 3));
|
||||
assert!(first("drop shadow").starts_with("effect:"), "{}", first("drop shadow"));
|
||||
assert_eq!(first("view.goto1"), "view.goto1", "the whole id, above Saved View 10");
|
||||
assert_eq!(first("bring front"), "object.arrange.bringToFront");
|
||||
assert!(within("ruler", "view.rulers", 4));
|
||||
assert!(place(&c, "ruler", "perspective.grid.rulers").is_some());
|
||||
assert_eq!(first("deselect"), "select.none");
|
||||
let mut blurs: Vec<String> = ranked(&c, "blur").into_iter().take(3).collect();
|
||||
blurs.sort();
|
||||
assert_eq!(blurs, ["effect:blur.gaussian", "effect:blur.radial", "effect:blur.smart"]);
|
||||
assert!(ranked(&c, "zzzz").is_empty());
|
||||
// English names are searched in every language.
|
||||
let zh = catalog(Lang::from_code("zh-hant").unwrap(), false);
|
||||
for q in ["save", "rect"] {
|
||||
assert_eq!(ranked(&zh, q).first(), ranked(&c, q).first(), "{q}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What the palette always matched: every word of the query is text in one of the result's
|
||||
/// names or ids.
|
||||
fn substring_rule<'a>(c: &'a Catalog, query: &str) -> Vec<&'a str> {
|
||||
let q = normalize(query);
|
||||
c.list.iter().filter(|e| q.split_whitespace().all(|w| e.haystack.contains(w))).map(|e| e.id.as_str()).collect()
|
||||
}
|
||||
|
||||
/// Each result's English name, shown name (in English, German and Chinese, Traditional) and id
|
||||
/// find it, first unless another result has that name; its id always lists it first.
|
||||
#[test]
|
||||
fn every_result_is_found_first_by_its_name_and_its_id() {
|
||||
for code in ["en", "de", "zh-hant"] {
|
||||
let c = catalog(Lang::from_code(code).unwrap(), false);
|
||||
let label = |n: &str| split_name(n).0.trim_end_matches('…').to_string();
|
||||
for e in &c.list {
|
||||
let english = e.haystack.lines().nth(1).unwrap_or_default();
|
||||
for query in [english, &e.shown] {
|
||||
let results = ranked(&c, query);
|
||||
assert!(results.contains(&e.id), "{code}: {query} finds {}", e.id);
|
||||
let q = normalize(query);
|
||||
let named = c.list.iter().filter(|o| names(o).any(|n| n == q || label(n) == label(&q))).count();
|
||||
if named <= 1 {
|
||||
assert_eq!(results.first(), Some(&e.id), "{code}: {query}");
|
||||
}
|
||||
}
|
||||
assert_eq!(ranked(&c, &e.id).first(), Some(&e.id), "{code}: {}", e.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The queries the palette's tests use and a list of things people type.
|
||||
const QUERIES: &[&str] = &[
|
||||
"select",
|
||||
"zoom",
|
||||
"zoom in",
|
||||
"show panel",
|
||||
"group",
|
||||
"layers",
|
||||
"color guide",
|
||||
"drop shadow",
|
||||
"use precise cursors",
|
||||
"continue in background",
|
||||
"export continue in background",
|
||||
"show rulers",
|
||||
"delete selection",
|
||||
"cancel key object",
|
||||
"fit headline",
|
||||
"batch",
|
||||
"flattener preview",
|
||||
"panel options",
|
||||
"close path",
|
||||
"knife",
|
||||
"play action",
|
||||
"reset panel",
|
||||
"other library",
|
||||
"ellipse",
|
||||
"blur",
|
||||
"save",
|
||||
"export",
|
||||
"rect",
|
||||
"type",
|
||||
"ea",
|
||||
"bring front",
|
||||
"ruler",
|
||||
"deselect",
|
||||
"view.goto1",
|
||||
"zzzz",
|
||||
"pen",
|
||||
"outlines",
|
||||
"join paths",
|
||||
"rounded corners",
|
||||
"scaling",
|
||||
"rotated",
|
||||
"eyedroper",
|
||||
"rectange",
|
||||
"elipse",
|
||||
"gruop",
|
||||
"remove bg",
|
||||
"outline text",
|
||||
"flip",
|
||||
"combine",
|
||||
"vectorize",
|
||||
"colour",
|
||||
"transparent background",
|
||||
"png",
|
||||
"object.group",
|
||||
"file.exportinbackground",
|
||||
"window",
|
||||
"s",
|
||||
"e",
|
||||
"…",
|
||||
"› ",
|
||||
];
|
||||
|
||||
/// For each query, every result the palette found before is still found, and when it found 50
|
||||
/// or fewer, each of them is among the first 50 results, so the list still shows it.
|
||||
#[test]
|
||||
fn every_result_found_before_is_still_found_and_shown() {
|
||||
assert_eq!(QUERIES.len(), 60);
|
||||
let c = catalog(Lang::EN, false);
|
||||
for q in QUERIES {
|
||||
let before = substring_rule(&c, q);
|
||||
let now = ranked(&c, q);
|
||||
for id in &before {
|
||||
let at = now.iter().position(|r| r == id);
|
||||
assert!(at.is_some(), "{q}: {id} is still found");
|
||||
if before.len() <= super::super::MAX_RESULTS {
|
||||
assert!(at < Some(super::super::MAX_RESULTS), "{q}: {id} is shown at {at:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A query longer than the index reads still has to match in full: two labels that share their
|
||||
/// first 200 characters are told apart by the rest.
|
||||
#[test]
|
||||
fn a_long_query_matches_in_full() {
|
||||
let shared = "a".repeat(200);
|
||||
let c = synthetic(vec![entry(&format!("{shared}b tail"), "a.one"), entry(&format!("{shared}c tail"), "b.two")]);
|
||||
let query = format!("{shared}b");
|
||||
assert_eq!(substring_rule(&c, &query), ["a.one"]);
|
||||
assert_eq!(ranked(&c, &query), ["a.one"]);
|
||||
}
|
||||
|
||||
/// Text in scripts without spaces, right-to-left text, combining characters, a very long pasted
|
||||
/// query, punctuation alone and names that differ only in the id they show.
|
||||
#[test]
|
||||
fn unusual_text_is_searched_safely() {
|
||||
let c = synthetic(vec![entry("物件 › 群組", "a.one"), entry("مرحبا عالم", "b.two"), entry("Cafe\u{301} Tool", "c.three")]);
|
||||
assert_eq!(ranked(&c, "群組"), ["a.one"]);
|
||||
assert_eq!(ranked(&c, "عالم"), ["b.two"]);
|
||||
assert_eq!(ranked(&c, "cafe\u{301}"), ["c.three"]);
|
||||
assert!(ranked(&c, &"x".repeat(5000)).is_empty());
|
||||
assert!(ranked(&c, &"群".repeat(5000)).is_empty());
|
||||
assert_eq!(ranked(&c, "›"), ["a.one"]);
|
||||
assert!(ranked(&c, "…,.-").is_empty());
|
||||
let en = catalog(Lang::EN, false);
|
||||
let both = ranked(&en, "fit headline");
|
||||
assert!(both.contains(&"type.fitHeadline".to_string()) && both.contains(&"text.fitHeadline".to_string()), "{both:?}");
|
||||
for id in ["type.fitHeadline", "text.fitHeadline"] {
|
||||
assert_eq!(ranked(&en, &format!("Type › Fit Headline ({id})")).first().map(String::as_str), Some(id));
|
||||
}
|
||||
let zh = Lang::from_code("zh-hant").unwrap();
|
||||
let zh_catalog = catalog(zh, false);
|
||||
let group = crate::i18n::tr(zh, "Group");
|
||||
assert!(place(&zh_catalog, group, "object.group").is_some_and(|p| p < 3), "{group}");
|
||||
}
|
||||
|
||||
/// Each result's home is the first item of the menu bar that runs it: an Effect menu item's
|
||||
/// submenu, the Window menu for a panel whose item shows and hides it, Learn's own item, and
|
||||
/// with the native Mac menu bar Preferences under the application menu's Settings.
|
||||
#[test]
|
||||
fn results_know_their_place_in_the_menu_bar() {
|
||||
let homes = menu_homes(false);
|
||||
let home = |id: &str| homes.get(id).map(|(path, _)| path.as_str());
|
||||
assert_eq!(home("effect:stylize.roundCorners"), Some("Effect › Stylize"));
|
||||
assert_eq!(home("panel:layers"), Some("Window"), "matched by the panel, although the item also asks to toggle it");
|
||||
assert_eq!(home("panel:learn"), Some("Window"));
|
||||
assert_eq!(home("panel:character"), Some("Window › Type"));
|
||||
assert_eq!(home("edit.preferences"), Some("Edit"));
|
||||
assert_eq!(home("help.about"), Some("Help"), "the in-window bar shows no application menu");
|
||||
assert_eq!(home("ui.layersPanelOptions"), None);
|
||||
assert_eq!(homes.get("app.quit"), Some(&("File".to_string(), "Exit")), "with its item's own label");
|
||||
let native = menu_homes(true);
|
||||
let native_home = |id: &str| native.get(id).map(|(path, _)| path.as_str());
|
||||
assert_eq!(native_home("edit.preferences"), Some("VectorCraft › Settings"));
|
||||
assert_eq!(native_home("help.about"), Some("VectorCraft"));
|
||||
assert_eq!(native_home("help.discord"), Some("Help"));
|
||||
let c = catalog(Lang::EN, false);
|
||||
let of = |id: &str| c.list.iter().find(|e| e.id == id).and_then(|e| e.home.clone());
|
||||
assert_eq!(of("effect:stylize.roundCorners").as_deref(), Some("Effect › Stylize"));
|
||||
assert_eq!(of("tool:pen"), None);
|
||||
// The home's words find the result: Preferences… under the native bar's Settings.
|
||||
let native_catalog = catalog(Lang::EN, true);
|
||||
assert!(place(&native_catalog, "settings pref", "edit.preferences").is_some());
|
||||
assert!(place(&c, "settings pref", "edit.preferences").is_none());
|
||||
// The menu item's own label finds the result too: File › Exit runs Quit VectorCraft.
|
||||
assert!(place(&c, "exit", "app.quit").is_some());
|
||||
}
|
||||
|
||||
/// The index of the real results takes at most 512 KiB, homes included.
|
||||
#[test]
|
||||
fn the_index_stays_small() {
|
||||
let c = catalog(Lang::EN, false);
|
||||
let homes: usize = c.list.iter().filter_map(|e| e.home.as_ref()).map(String::capacity).sum();
|
||||
let bytes = c.index.bytes() + homes;
|
||||
println!("{} results, index {} bytes, homes {homes} bytes", c.list.len(), c.index.bytes());
|
||||
assert!(bytes <= 512 * 1024, "{bytes}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "times the index and sample queries; run in a release build"]
|
||||
fn time_the_index_and_queries() {
|
||||
let started = std::time::Instant::now();
|
||||
let c = catalog(Lang::EN, false);
|
||||
let built = started.elapsed();
|
||||
let started = std::time::Instant::now();
|
||||
let index = Index::build(&c.list, &[]);
|
||||
println!("catalog {built:?}, index alone {:?}, {} results, {} bytes", started.elapsed(), c.list.len(), index.bytes());
|
||||
let long = "q".repeat(200);
|
||||
for q in ["e", "ea", "select", "bring front", "zzzz", long.as_str()] {
|
||||
let started = std::time::Instant::now();
|
||||
let runs = 100;
|
||||
for _ in 0..runs {
|
||||
std::hint::black_box(rank(&c.list, &c.index, q));
|
||||
}
|
||||
println!("{:>12}: {:?} per query", q.get(..12).unwrap_or(q), started.elapsed() / runs);
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
for _ in 0..100 {
|
||||
std::hint::black_box(substring_rule(&c, "bring front"));
|
||||
}
|
||||
println!("substring rule alone: {:?} per query", started.elapsed() / 100);
|
||||
}
|
||||
}
|
||||
@@ -1256,6 +1256,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. Results whose name without its menu path is the whole query come first, so "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`).
|
||||
The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`).
|
||||
A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`).
|
||||
The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, and a shorter name above a longer one, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs), read from the native menu bar when the app uses it. Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `common_queries_list_the_command_first`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`).
|
||||
`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.
|
||||
Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`).
|
||||
Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list.
|
||||
|
||||
Reference in New Issue
Block a user