diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 7e48fc244e..5b0d5a0d6c 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -133,8 +133,8 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // Search → command palette (its shortcut opens it too). if search { let tip = match menus::shortcut_of("help.commandPalette") { - Some(sc) => format!("{} ({})", tl!("Search commands and tools"), menus::shown_shortcut(sc)), - None => tl!("Search commands and tools").to_string(), + Some(sc) => format!("{} ({})", tl!("Search commands, tools, panels and effects"), menus::shown_shortcut(sc)), + None => tl!("Search commands, tools, panels and effects").to_string(), }; if widgets::icon_button(ui, "search", &tip, app.ui.palette_open, icon).clicked() { app.ui.palette_open = !app.ui.palette_open; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 0d124dacc4..b27a198fc1 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3188,8 +3188,12 @@ digits Malayalam Малаялам Scripts Скриптове Search Търсене Search All Търсене във всички - Search commands and tools Търсене на команди и инструменти - Search commands and tools… Търсене на команди и инструменти… + Search commands, tools, panels and effects Търсене на команди, инструменти, панели и ефекти + Search commands, tools, panels and effects… Търсене на команди, инструменти, панели и ефекти… + No commands match Няма съвпадащи команди + {pos} of {total}: {name} {pos} от {total}: {name} +@plural {n} result|{n} results {n} резултат|{n} резултата +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} от {n} резултат. Продължете да пишете, за да ги стесните.|{shown} от {n} резултата. Продължете да пишете, за да ги стесните. Recent Commands Последни команди No recent commands Няма последни команди Search Commands… Търсене на команди… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 571962db44..df8c34eeeb 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1301,7 +1301,7 @@ lighting Light Svjetlo Name* @ 66.67% (RGB/Preview) Naziv* @ 66,67% (RGB/pregled) No Document Nema dokumenta Press Pritisnite - Search commands and tools Pretraži naredbe i alate + Search commands, tools, panels and effects Pretraži naredbe, alate, panele i efekte Style: Stil: Switch workspace Promijeni radni prostor Show all open documents Prikaži sve otvorene dokumente @@ -4388,7 +4388,11 @@ font-technology Variable Varijabilni Saved {path} Sačuvano: {path} Saving Čuvanje Saving {} Čuvanje {} - Search commands and tools… Pretraži naredbe i alate… + Search commands, tools, panels and effects… Pretraži naredbe, alate, panele i efekte… + No commands match Nijedna naredba se ne podudara + {pos} of {total}: {name} {pos} od {total}: {name} +@plural {n} result|{n} results {n} rezultat|{n} rezultata|{n} rezultata +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite. Recent Commands Nedavne naredbe No recent commands Nema nedavnih naredbi Dashed Line Isprekidana linija diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9381aa96a7..a3f6252a3f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3983,42 +3983,42 @@ digits Malayalam Malaiàlam Saved Desat Saved recovery data for {title} S’han desat les dades de recuperació de {title} Saved Selection 1 Selecció desada 1 - Saved Selection 10 Selecció desada 2 - Saved Selection 11 Selecció desada 3 - Saved Selection 12 Selecció desada 4 - Saved Selection 13 Selecció desada 5 - Saved Selection 14 Selecció desada 6 - Saved Selection 15 Selecció desada 7 - Saved Selection 16 Selecció desada 8 - Saved Selection 17 Selecció desada 9 - Saved Selection 18 Selecció desada 10 - Saved Selection 19 Selecció desada 11 - Saved Selection 2 Selecció desada 12 - Saved Selection 20 Selecció desada 13 - Saved Selection 21 Selecció desada 14 - Saved Selection 22 Selecció desada 15 - Saved Selection 23 Selecció desada 16 - Saved Selection 24 Selecció desada 17 - Saved Selection 25 Selecció desada 18 - Saved Selection 3 Selecció desada 19 - Saved Selection 4 Selecció desada 20 - Saved Selection 5 Selecció desada 21 - Saved Selection 6 Selecció desada 22 - Saved Selection 7 Selecció desada 23 - Saved Selection 8 Selecció desada 24 - Saved Selection 9 Selecció desada 25 + Saved Selection 10 Selecció desada 10 + Saved Selection 11 Selecció desada 11 + Saved Selection 12 Selecció desada 12 + Saved Selection 13 Selecció desada 13 + Saved Selection 14 Selecció desada 14 + Saved Selection 15 Selecció desada 15 + Saved Selection 16 Selecció desada 16 + Saved Selection 17 Selecció desada 17 + Saved Selection 18 Selecció desada 18 + Saved Selection 19 Selecció desada 19 + Saved Selection 2 Selecció desada 2 + Saved Selection 20 Selecció desada 20 + Saved Selection 21 Selecció desada 21 + Saved Selection 22 Selecció desada 22 + Saved Selection 23 Selecció desada 23 + Saved Selection 24 Selecció desada 24 + Saved Selection 25 Selecció desada 25 + Saved Selection 3 Selecció desada 3 + Saved Selection 4 Selecció desada 4 + Saved Selection 5 Selecció desada 5 + Saved Selection 6 Selecció desada 6 + Saved Selection 7 Selecció desada 7 + Saved Selection 8 Selecció desada 8 + Saved Selection 9 Selecció desada 9 Saved Selections Seleccions desades Saved to User Defined: {} Desat a Definit per l’usuari: {} Saved View 1 Vista desada 1 - Saved View 10 Vista desada 2 - Saved View 11 Vista desada 3 - Saved View 12 Vista desada 4 - Saved View 13 Vista desada 5 - Saved View 14 Vista desada 6 - Saved View 15 Vista desada 7 - Saved View 16 Vista desada 8 - Saved View 17 Vista desada 9 - Saved View 18 Vista desada 10 + Saved View 10 Vista desada 10 + Saved View 11 Vista desada 11 + Saved View 12 Vista desada 12 + Saved View 13 Vista desada 13 + Saved View 14 Vista desada 14 + Saved View 15 Vista desada 15 + Saved View 16 Vista desada 16 + Saved View 17 Vista desada 17 + Saved View 18 Vista desada 18 Saved View 19 Vista desada 19 Saved View 2 Vista desada 2 Saved View 20 Vista desada 20 @@ -4117,8 +4117,12 @@ digits Malayalam Malaiàlam Scrub Numeric Fields by Dragging Canvia els camps numèrics arrossegant Search Cerca Search All Cerca a tot - Search commands and tools Cerca ordres i eines - Search commands and tools… Cerca ordres i eines… + Search commands, tools, panels and effects Cerca ordres, eines, panells i efectes + Search commands, tools, panels and effects… Cerca ordres, eines, panells i efectes… + No commands match Cap ordre coincideix + {pos} of {total}: {name} {pos} de {total}: {name} +@plural {n} result|{n} results {n} resultat|{n} resultats +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultat. Continueu escrivint per reduir-los.|{shown} de {n} resultats. Continueu escrivint per reduir-los. Recent Commands Ordres recents No recent commands No hi ha ordres recents Search Commands… Cerca ordres… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0b06ffe205..83662e4b5b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1325,7 +1325,7 @@ lighting Light Světlo Name* @ 66.67% (RGB/Preview) Název* @ 66,67 % (RGB/náhled) No Document Žádný dokument Press Klávesou - Search commands and tools Hledat příkazy a nástroje + Search commands, tools, panels and effects Hledat příkazy, nástroje, panely a efekty Style: Styl: Switch workspace Přepnout pracovní prostor Show all open documents Zobrazit všechny otevřené dokumenty @@ -4493,7 +4493,11 @@ font-technology Variable Variabilní Saved {path} Uloženo: {path} Saving Ukládání Saving {} Ukládání {} - Search commands and tools… Hledat příkazy a nástroje… + Search commands, tools, panels and effects… Hledat příkazy, nástroje, panely a efekty… + No commands match Žádný příkaz neodpovídá + {pos} of {total}: {name} {pos} z {total}: {name} +@plural {n} result|{n} results {n} výsledek|{n} výsledky|{n} výsledků +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} výsledku. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží. Recent Commands Nedávné příkazy No recent commands Žádné nedávné příkazy Dashed Line Čárkovaná čára diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f039593aaa..6a7c29cbce 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3902,7 +3902,7 @@ lighting Light Lys Name* @ 66.67% (RGB/Preview) Navn* @ 66.67% (RGB/forhåndsvisning) No Document Intet dokument Press Tryk på - Search commands and tools Søg i kommandoer og værktøjer + Search commands, tools, panels and effects Søg i kommandoer, værktøjer, paneler og effekter Style: Typografi: Switch workspace Skift arbejdsområde Show all open documents Vis alle åbne dokumenter @@ -6867,7 +6867,11 @@ font-technology Variable Variable Saved {path} Gemte {path} Saving Gemmer Saving {} Gemmer {} - Search commands and tools… Søg i kommandoer og værktøjer… + Search commands, tools, panels and effects… Søg i kommandoer, værktøjer, paneler og effekter… + No commands match Ingen kommandoer passer + {pos} of {total}: {name} {pos} af {total}: {name} +@plural {n} result|{n} results {n} resultat|{n} resultater +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} af {n} resultat. Skriv videre for at indsnævre dem.|{shown} af {n} resultater. Skriv videre for at indsnævre dem. Recent Commands Seneste kommandoer No recent commands Ingen seneste kommandoer Dashed Line Stiplet linje diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10f44a78b9..1b1ec46863 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3252,8 +3252,12 @@ digits Malayalam Malayalam Filter Layers Panel Rows Zeilen im Ebenenbedienfeld filtern @msg `Custom` stands for changed settings: save the preset under another name `Custom` steht für geänderte Einstellungen: Speichern Sie die Vorgabe unter einem anderen Namen @msg `{key}` must be an array of these names: {_1} `{key}` muss ein Array mit diesen Namen sein: {_1} - Search commands and tools Befehle und Werkzeuge suchen - Search commands and tools… Befehle und Werkzeuge suchen… + Search commands, tools, panels and effects Befehle, Werkzeuge, Bedienfelder und Effekte suchen + Search commands, tools, panels and effects… Befehle, Werkzeuge, Bedienfelder und Effekte suchen… + No commands match Keine passenden Befehle + {pos} of {total}: {name} {pos} von {total}: {name} +@plural {n} result|{n} results {n} Ergebnis|{n} Ergebnisse +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} von {n} Ergebnis. Tippen Sie weiter, um sie einzugrenzen.|{shown} von {n} Ergebnissen. Tippen Sie weiter, um sie einzugrenzen. Recent Commands Zuletzt verwendete Befehle No recent commands Keine zuletzt verwendeten Befehle Search Commands… Befehle suchen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 352c47f83a..618db0a6a8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3954,8 +3954,12 @@ digits Malayalam Μαλαγιάλαμ Scribble… Μουτζούρωμα… Script / Brush Σενάριο / Πινέλο Search All Αναζήτηση όλων - Search commands and tools Αναζήτηση εντολών και εργαλείων - Search commands and tools… Αναζήτηση εντολών και εργαλείων… + Search commands, tools, panels and effects Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ + Search commands, tools, panels and effects… Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ… + No commands match Καμία εντολή δεν ταιριάζει + {pos} of {total}: {name} {pos} από {total}: {name} +@plural {n} result|{n} results {n} αποτέλεσμα|{n} αποτελέσματα +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} από {n} αποτέλεσμα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε.|{shown} από {n} αποτελέσματα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε. Recent Commands Πρόσφατες εντολές No recent commands Δεν υπάρχουν πρόσφατες εντολές Search Commands… Αναζήτηση εντολών… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 55f561d6b1..3cf461791e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3290,8 +3290,12 @@ digits Malayalam Malayálam Filter Layers Panel Rows Filtrar filas del panel Capas @msg `Custom` stands for changed settings: save the preset under another name `Custom` representa ajustes modificados: guarda el preajuste con otro nombre @msg `{key}` must be an array of these names: {_1} `{key}` debe ser una lista de estos nombres: {_1} - Search commands and tools Buscar comandos y herramientas - Search commands and tools… Buscar comandos y herramientas… + Search commands, tools, panels and effects Buscar comandos, herramientas, paneles y efectos + Search commands, tools, panels and effects… Buscar comandos, herramientas, paneles y efectos… + No commands match Ningún comando coincide + {pos} of {total}: {name} {pos} de {total}: {name} +@plural {n} result|{n} results {n} resultado|{n} resultados +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Sigue escribiendo para acotarlos.|{shown} de {n} resultados. Sigue escribiendo para acotarlos. Recent Commands Comandos recientes No recent commands No hay comandos recientes Search Commands… Buscar comandos… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 08650843e3..0b1e3c881b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1303,7 +1303,7 @@ lighting Light Valo Name* @ 66.67% (RGB/Preview) Nimi* @ 66.67% (RGB/esikatselu) No Document Ei asiakirjaa Press Paina - Search commands and tools Hae komentoja ja työkaluja + Search commands, tools, panels and effects Hae komentoja, työkaluja, paneeleita ja tehosteita Style: Tyyli: Switch workspace Vaihda työtilaa Show all open documents Näytä kaikki avoimet asiakirjat @@ -4412,7 +4412,11 @@ font-technology Variable Muuttuvat Saved {path} Tallennettu {path} Saving Tallennetaan Saving {} Tallennetaan {} - Search commands and tools… Hae komentoja ja työkaluja… + Search commands, tools, panels and effects… Hae komentoja, työkaluja, paneeleita ja tehosteita… + No commands match Mikään komento ei vastaa hakua + {pos} of {total}: {name} {pos}/{total}: {name} +@plural {n} result|{n} results {n} tulos|{n} tulosta +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia.|{shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia. Recent Commands Viimeisimmät komennot No recent commands Ei viimeisimpiä komentoja Dashed Line Katkoviiva diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 397797d5e8..66d3c23c01 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3278,8 +3278,12 @@ digits Malayalam Malayalam Filter Layers Panel Rows Filtrer les lignes du panneau Calques @msg `Custom` stands for changed settings: save the preset under another name `Custom` désigne des réglages modifiés : enregistrez le paramètre prédéfini sous un autre nom @msg `{key}` must be an array of these names: {_1} `{key}` doit être un tableau de noms parmi {_1} - Search commands and tools Chercher commandes et outils - Search commands and tools… Chercher commandes et outils… + Search commands, tools, panels and effects Chercher commandes, outils, panneaux et effets + Search commands, tools, panels and effects… Chercher commandes, outils, panneaux et effets… + No commands match Aucune commande ne correspond + {pos} of {total}: {name} {pos} sur {total} : {name} +@plural {n} result|{n} results {n} résultat|{n} résultats +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} sur {n} résultat. Continuez à taper pour les affiner.|{shown} sur {n} résultats. Continuez à taper pour les affiner. Recent Commands Commandes récentes No recent commands Aucune commande récente Search Commands… Rechercher des commandes… diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 7959370e04..385fccc138 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3393,8 +3393,12 @@ Search Commands… આદેશો શોધો… Search Fonts Folder ફોન્ટ ફોલ્ડર શોધો Search Preferences પસંદગીઓ શોધો - Search commands and tools આદેશો અને ટૂલ્સ શોધો - Search commands and tools… આદેશો અને ટૂલ્સ શોધો… + Search commands, tools, panels and effects આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો + Search commands, tools, panels and effects… આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો… + No commands match કોઈ આદેશ મેળ ખાતો નથી + {pos} of {total}: {name} {total} માંથી {pos}: {name} +@plural {n} result|{n} results {n} પરિણામ|{n} પરિણામો +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} માંથી {shown} પરિણામ. તેમને સંકુચિત કરવા લખતા રહો.|{n} માંથી {shown} પરિણામો. તેમને સંકુચિત કરવા લખતા રહો. Recent Commands તાજેતરના આદેશો No recent commands કોઈ તાજેતરના આદેશો નથી Search images છબીઓ શોધો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 88ec0a8f19..e332f6be32 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4467,8 +4467,12 @@ antiAlias Sharp शार्प Search खोजें Search All सभी खोजें Search artboards खोज आर्टबोर्ड - Search commands and tools खोज आदेश और टूल - Search commands and tools… आदेश और टूल खोजें… + Search commands, tools, panels and effects आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें + Search commands, tools, panels and effects… आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें… + No commands match कोई आदेश मेल नहीं खाता + {pos} of {total}: {name} {total} में से {pos}: {name} +@plural {n} result|{n} results {n} परिणाम|{n} परिणाम +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें।|{n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें। Recent Commands हाल के आदेश No recent commands कोई हाल का आदेश नहीं Search Commands… कमांड खोजें… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e83fd78c1f..e4452cb211 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3911,8 +3911,12 @@ mark-style Japanese Japán Filter Layers Panel Rows Rétegek panel sorainak szűrése @msg `Custom` stands for changed settings: save the preset under another name a `Custom` a módosított beállításokat jelöli: mentsd az előbeállítást más néven @msg `{key}` must be an array of these names: {_1} `{key}`: ezen nevek tömbje kell: {_1} - Search commands and tools Parancsok és eszközök keresése - Search commands and tools… Parancsok és eszközök keresése… + Search commands, tools, panels and effects Parancsok, eszközök, panelek és effektusok keresése + Search commands, tools, panels and effects… Parancsok, eszközök, panelek és effektusok keresése… + No commands match Nincs egyező parancs + {pos} of {total}: {name} {pos}/{total}: {name} +@plural {n} result|{n} results {n} találat +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} találatból {shown} látható. Gépeljen tovább a szűkítéshez. Recent Commands Legutóbbi parancsok No recent commands Nincsenek legutóbbi parancsok Search Commands… Parancsok keresése… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7ce0201583..37ea827f3c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1228,7 +1228,7 @@ lighting Light Cahaya Name* @ 66.67% (RGB/Preview) Nama* @ 66.67% (RGB/Pratinjau) No Document Tidak ada dokumen Press Tekan - Search commands and tools Cari perintah dan alat + Search commands, tools, panels and effects Cari perintah, alat, panel, dan efek Style: Gaya: Switch workspace Ganti ruang kerja Show all open documents Tampilkan semua dokumen terbuka @@ -4144,7 +4144,11 @@ font-technology Variable Variabel Saved {path} Berhasil menyimpan {path} Saving Menyimpan Saving {} Menyimpan {} - Search commands and tools… Cari perintah dan alat… + Search commands, tools, panels and effects… Cari perintah, alat, panel, dan efek… + No commands match Tidak ada perintah yang cocok + {pos} of {total}: {name} {pos} dari {total}: {name} +@plural {n} result|{n} results {n} hasil +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} dari {n} hasil. Terus ketik untuk mempersempitnya. Recent Commands Perintah terbaru No recent commands Tidak ada perintah terbaru Dashed Line Garis putus-putus diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index feb39ff415..7005d218f7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3333,8 +3333,12 @@ digits Malayalam Malayalam Filter Layers Panel Rows Filtra righe del pannello Livelli @msg `Custom` stands for changed settings: save the preset under another name `Custom` indica impostazioni modificate: salva il preset con un altro nome @msg `{key}` must be an array of these names: {_1} `{key}` deve essere un array di questi nomi: {_1} - Search commands and tools Cerca comandi e strumenti - Search commands and tools… Cerca comandi e strumenti… + Search commands, tools, panels and effects Cerca comandi, strumenti, pannelli ed effetti + Search commands, tools, panels and effects… Cerca comandi, strumenti, pannelli ed effetti… + No commands match Nessun comando corrisponde + {pos} of {total}: {name} {pos} di {total}: {name} +@plural {n} result|{n} results {n} risultato|{n} risultati +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} di {n} risultato. Continua a digitare per restringerli.|{shown} di {n} risultati. Continua a digitare per restringerli. Recent Commands Comandi recenti No recent commands Nessun comando recente Search Commands… Cerca comandi… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ab94df078d..9b403f103c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3211,8 +3211,12 @@ mark-style Japanese 日本式 Filter Layers Panel Rows レイヤーパネルの行をフィルター @msg `Custom` stands for changed settings: save the preset under another name `Custom` は変更した設定を表します: プリセットを別の名前で保存してください @msg `{key}` must be an array of these names: {_1} `{key}` には {_1} の中の名前の配列を指定してください - Search commands and tools コマンドとツールを検索 - Search commands and tools… コマンドとツールを検索… + Search commands, tools, panels and effects コマンド、ツール、パネル、効果を検索 + Search commands, tools, panels and effects… コマンド、ツール、パネル、効果を検索… + No commands match 一致するコマンドはありません + {pos} of {total}: {name} {total} 件中 {pos} 件目: {name} +@plural {n} result|{n} results {n} 件 +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} 件中 {shown} 件。続けて入力すると絞り込めます。 Recent Commands 最近使ったコマンド No recent commands 最近使ったコマンドはありません Secondary セカンダリ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 1d3922373f..a069c9bac6 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3270,7 +3270,7 @@ lighting Light სინათლე Name* @ 66.67% (RGB/Preview) სახელი* @ 66.67% (RGB/წინასწარი ნახვა) No Document დოკუმენტი არ არის Press დააჭირეთ - Search commands and tools ბრძანებებისა და ხელსაწყოების ძიება + Search commands, tools, panels and effects ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება Style: სტილი: Switch workspace სამუშაო სივრცის გადართვა Show all open documents ყველა ღია დოკუმენტის ჩვენება @@ -6096,7 +6096,11 @@ font-technology Variable ცვლადი Saved {path} შენახულია: {path} Saving შენახვა Saving {} ინახება: {} - Search commands and tools… ბრძანებებისა და ხელსაწყოების ძიება… + Search commands, tools, panels and effects… ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება… + No commands match შესაბამისი ბრძანება არ არის + {pos} of {total}: {name} {pos} / {total}: {name} +@plural {n} result|{n} results {n} შედეგი +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} შედეგიდან {shown}. გააგრძელეთ აკრეფა მათ შესამცირებლად. Recent Commands ბოლო ბრძანებები No recent commands ბოლო ბრძანებები არ არის Dashed Line ტირეებიანი ხაზი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f59f64976e..e2de2a8d46 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3200,8 +3200,12 @@ mark-style Japanese 일본식 Filter Layers Panel Rows 레이어 패널 행 필터링 @msg `Custom` stands for changed settings: save the preset under another name `Custom`은 변경된 설정을 나타냅니다. 프리셋을 다른 이름으로 저장하세요 @msg `{key}` must be an array of these names: {_1} `{key}`은(는) 다음 이름의 배열이어야 합니다: {_1} - Search commands and tools 명령 및 도구 검색 - Search commands and tools… 명령 및 도구 검색… + Search commands, tools, panels and effects 명령, 도구, 패널 및 효과 검색 + Search commands, tools, panels and effects… 명령, 도구, 패널 및 효과 검색… + No commands match 일치하는 명령이 없습니다 + {pos} of {total}: {name} {total}개 중 {pos}번째: {name} +@plural {n} result|{n} results 결과 {n}개 +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 결과 {n}개 중 {shown}개. 계속 입력하여 범위를 좁히세요. Recent Commands 최근 명령 No recent commands 최근 명령 없음 Secondary 보조 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 8a78919fb9..aaa159876e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1796,7 +1796,7 @@ lighting Light Licht Name* @ 66.67% (RGB/Preview) Naam* @ 66.67% (RGB/Voorbeeld) No Document Geen document Press Druk op - Search commands and tools Opdrachten en gereedschappen zoeken + Search commands, tools, panels and effects Opdrachten, gereedschappen, panelen en effecten zoeken Style: Stijl: Switch workspace Werkruimte wisselen Show all open documents Alle geopende documenten tonen @@ -4761,7 +4761,11 @@ font-technology Variable Variabel Saved {path} {path} opgeslagen Saving Bezig met opslaan Saving {} {} wordt opgeslagen - Search commands and tools… Opdrachten en gereedschappen zoeken… + Search commands, tools, panels and effects… Opdrachten, gereedschappen, panelen en effecten zoeken… + No commands match Geen opdrachten gevonden + {pos} of {total}: {name} {pos} van {total}: {name} +@plural {n} result|{n} results {n} resultaat|{n} resultaten +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} van {n} resultaat. Typ verder om ze te beperken.|{shown} van {n} resultaten. Typ verder om ze te beperken. Recent Commands Recente opdrachten No recent commands Geen recente opdrachten Dashed Line Streepjeslijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7646357fb3..6f7c6eb49a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1255,7 +1255,7 @@ lighting Light Światło Name* @ 66.67% (RGB/Preview) Nazwa* @ 66,67% (RGB/Podgląd) No Document Brak dokumentu Press Naciśnij - Search commands and tools Szukaj poleceń i narzędzi + Search commands, tools, panels and effects Szukaj poleceń, narzędzi, paneli i efektów Style: Styl: Switch workspace Przełącz obszar roboczy Show all open documents Pokaż wszystkie otwarte dokumenty @@ -4334,7 +4334,11 @@ font-technology Variable Zmienne Saved {path} Zapisano {path} Saving Zapisywanie Saving {} Zapisywanie {} - Search commands and tools… Szukaj poleceń i narzędzi… + Search commands, tools, panels and effects… Szukaj poleceń, narzędzi, paneli i efektów… + No commands match Żadne polecenie nie pasuje + {pos} of {total}: {name} {pos} z {total}: {name} +@plural {n} result|{n} results {n} wynik|{n} wyniki|{n} wyników +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} wyniku. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić. Recent Commands Ostatnie polecenia No recent commands Brak ostatnich poleceń Dashed Line Linia przerywana diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e680cebdc6..4138d050c8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2749,8 +2749,12 @@ digits Malayalam Malaiala @msg `Custom` stands for changed settings: save the preset under another name `Custom` representa configurações alteradas: salve a predefinição com outro nome @msg `{key}` must be an array of these names: {_1} `{key}` deve ser uma matriz destes nomes: {_1} Search Commands… Pesquisar Comandos… - Search commands and tools Pesquisar comandos e ferramentas - Search commands and tools… Pesquisar comandos e ferramentas… + Search commands, tools, panels and effects Pesquisar comandos, ferramentas, painéis e efeitos + Search commands, tools, panels and effects… Pesquisar comandos, ferramentas, painéis e efeitos… + No commands match Nenhum comando corresponde + {pos} of {total}: {name} {pos} de {total}: {name} +@plural {n} result|{n} results {n} resultado|{n} resultados +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Continue digitando para filtrá-los.|{shown} de {n} resultados. Continue digitando para filtrá-los. Recent Commands Comandos recentes No recent commands Nenhum comando recente Secondary Secundária diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 1d79eece33..5f73b0dd78 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3322,8 +3322,12 @@ digits Malayalam Малаялам Filter Layers Panel Rows Фильтровать строки панели «Слои» @msg `Custom` stands for changed settings: save the preset under another name `Custom` обозначает изменённые параметры: сохраните набор под другим именем @msg `{key}` must be an array of these names: {_1} `{key}` должно быть массивом из этих имён: {_1} - Search commands and tools Поиск команд и инструментов - Search commands and tools… Поиск команд и инструментов… + Search commands, tools, panels and effects Поиск команд, инструментов, панелей и эффектов + Search commands, tools, panels and effects… Поиск команд, инструментов, панелей и эффектов… + No commands match Нет подходящих команд + {pos} of {total}: {name} {pos} из {total}: {name} +@plural {n} result|{n} results {n} результат|{n} результата|{n} результатов +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} из {n} результата. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их. Recent Commands Недавние команды No recent commands Нет недавних команд Search Commands… Поиск команд… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 49580ff0a1..769e5c7873 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3208,8 +3208,12 @@ digits Malayalam Malayalam Scripts Skript Search Sök Search All Sök i alla - Search commands and tools Sök kommandon och verktyg - Search commands and tools… Sök kommandon och verktyg… + Search commands, tools, panels and effects Sök kommandon, verktyg, paneler och effekter + Search commands, tools, panels and effects… Sök kommandon, verktyg, paneler och effekter… + No commands match Inga kommandon matchar + {pos} of {total}: {name} {pos} av {total}: {name} +@plural {n} result|{n} results {n} resultat|{n} resultat +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} av {n} resultat. Fortsätt skriva för att begränsa dem.|{shown} av {n} resultat. Fortsätt skriva för att begränsa dem. Recent Commands Senaste kommandon No recent commands Inga senaste kommandon Search Commands… Sök kommandon… diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0daefad24a..a540fdc463 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -434,6 +434,30 @@ fn font_height_reference_labels_are_in_complete_catalogs() { } } +/// Each catalog's Saved View N and Saved Selection N rows carry the number N, and no two of a +/// catalog's saved views or saved selections show one name, whatever digits the language uses. +#[test] +fn numbered_saved_views_and_selections_keep_their_number() { + let mut bad = vec![]; + for lang in LANGUAGES.iter().filter(|lang| !lang.source.is_empty()) { + for kind in ["Saved View", "Saved Selection"] { + let mut seen = std::collections::HashMap::new(); + for n in 1..=25 { + let source = format!("{kind} {n}"); + let Some(row) = lang.catalog().plain(&source) else { continue }; + let numbers: Vec<&str> = row.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).collect(); + if !numbers.is_empty() && numbers != [n.to_string().as_str()] { + bad.push(format!("{}: {source} -> {row}", lang.code)); + } + if let Some(earlier) = seen.insert(row, source.clone()) { + bad.push(format!("{}: {earlier} and {source} both show {row}", lang.code)); + } + } + } + } + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + /// The Objects on Path Options section's Detach button, its undo step and the message for a /// Detach with no object chosen. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 97b89af485..8937e9fe77 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3080,8 +3080,12 @@ digits Malayalam Malayalam Redefine {name} “{name}” Stilini Yeniden Tanımla @msg `Custom` stands for changed settings: save the preset under another name `Custom` değiştirilmiş ayarları ifade eder: ön ayarı başka bir adla kaydedin @msg `{key}` must be an array of these names: {_1} `{key}` şu adlardan oluşan bir dizi olmalıdır: {_1} - Search commands and tools Komutları ve araçları arayın - Search commands and tools… Komutları ve araçları arayın… + Search commands, tools, panels and effects Komutları, araçları, panelleri ve efektleri arayın + Search commands, tools, panels and effects… Komutları, araçları, panelleri ve efektleri arayın… + No commands match Eşleşen komut yok + {pos} of {total}: {name} {pos}/{total}: {name} +@plural {n} result|{n} results {n} sonuç +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} sonuçtan {shown} tanesi. Daraltmak için yazmaya devam edin. Recent Commands Son komutlar No recent commands Son komut yok Search Commands… Arama Komutları… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 2479f1c629..99f8038a30 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3325,8 +3325,12 @@ digits Malayalam Малаялам Filter Layers Panel Rows Фільтрувати рядки панелі «Шари» @msg `Custom` stands for changed settings: save the preset under another name `Custom` позначає змінені параметри: збережіть набір під іншим ім’ям @msg `{key}` must be an array of these names: {_1} `{key}` має бути масивом цих назв: {_1} - Search commands and tools Пошук команд та інструментів - Search commands and tools… Пошук команд та інструментів… + Search commands, tools, panels and effects Пошук команд, інструментів, панелей та ефектів + Search commands, tools, panels and effects… Пошук команд, інструментів, панелей та ефектів… + No commands match Немає відповідних команд + {pos} of {total}: {name} {pos} з {total}: {name} +@plural {n} result|{n} results {n} результат|{n} результати|{n} результатів +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} з {n} результату. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх. Recent Commands Нещодавні команди No recent commands Немає нещодавніх команд Search Commands… Пошук команд… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 850d4a890c..cece3dcf1b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3668,8 +3668,12 @@ mark-style Japanese Kiểu Nhật Filter Layers Panel Rows Lọc hàng bảng Lớp @msg `Custom` stands for changed settings: save the preset under another name `Custom` biểu thị các cài đặt đã thay đổi: hãy lưu thiết lập sẵn với tên khác @msg `{key}` must be an array of these names: {_1} `{key}` phải là một mảng gồm các tên sau: {_1} - Search commands and tools Tìm kiếm lệnh và công cụ - Search commands and tools… Tìm kiếm lệnh và công cụ… + Search commands, tools, panels and effects Tìm kiếm lệnh, công cụ, bảng và hiệu ứng + Search commands, tools, panels and effects… Tìm kiếm lệnh, công cụ, bảng và hiệu ứng… + No commands match Không có lệnh nào khớp + {pos} of {total}: {name} {pos} trên {total}: {name} +@plural {n} result|{n} results {n} kết quả +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} trên {n} kết quả. Tiếp tục gõ để thu hẹp. Recent Commands Lệnh gần đây No recent commands Không có lệnh gần đây Search Commands… Tìm kiếm lệnh… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9821a31331..677f7268b4 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3152,8 +3152,12 @@ digits Malayalam 马拉雅拉姆数字 Locked 已锁定 Hidden 已隐藏 Filter Layers Panel Rows 筛选图层面板行 - Search commands and tools 搜索命令和工具 - Search commands and tools… 搜索命令和工具… + Search commands, tools, panels and effects 搜索命令、工具、面板和效果 + Search commands, tools, panels and effects… 搜索命令、工具、面板和效果… + No commands match 没有匹配的命令 + {pos} of {total}: {name} 第 {pos} 个,共 {total} 个:{name} +@plural {n} result|{n} results {n} 个结果 +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 个结果,显示 {shown} 个。继续输入以缩小范围。 Recent Commands 最近使用的命令 No recent commands 没有最近使用的命令 Search Commands… 搜索命令… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0a6ddb0207..b50f0671b0 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4458,8 +4458,12 @@ digits Malayalam 馬來亞拉姆數字 Locked 已鎖定 Hidden 已隱藏 Filter Layers Panel Rows 篩選圖層面板列 - Search commands and tools 搜尋指令與工具 - Search commands and tools… 搜尋指令與工具… + Search commands, tools, panels and effects 搜尋指令、工具、面板與效果 + Search commands, tools, panels and effects… 搜尋指令、工具、面板與效果… + No commands match 沒有符合的指令 + {pos} of {total}: {name} 第 {pos} 個,共 {total} 個:{name} +@plural {n} result|{n} results {n} 個結果 +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 個結果,顯示 {shown} 個。繼續輸入以縮小範圍。 Recent Commands 最近使用的指令 No recent commands 沒有最近使用的指令 Search Commands… 搜尋指令… diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index da3d1052b4..544929a0e7 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1,4 +1,5 @@ -//! The command palette: fuzzy search over every command and tool. +//! The command palette: fuzzy search over the commands a pick runs, the tools, the panels and the +//! Effect menu's items. use std::sync::Arc; @@ -7,10 +8,14 @@ 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 -/// command's dialog or file chooser. Scripts and the control channel still run the engine ids. +/// command's dialog or file chooser (the four Other Library… commands ask for the library file). +/// Batch… and Flattener Preview open the dialog or panel that runs the engine command. Scripts and +/// the control channel still run the engine ids. const WRAPPED: &[(&str, &str)] = &[ ("layer.delete", "ui.layerDelete"), ("brush.new", "ui.newBrush"), @@ -18,34 +23,242 @@ const WRAPPED: &[(&str, &str)] = &[ ("symbol.options", "ui.symbolOptions"), ("svgFilter.import", "ui.importSvgFilter"), ("text.convertListToText", "type.convertListToText"), + ("action.batch", "ui.batchDialog"), + ("flattener.preview", "ui.flattenerPreview"), + ("swatch.library.load", "window.swatchLibrary.other"), + ("graphicStyle.loadLibrary", "window.graphicStyleLibrary.other"), + ("symbol.loadLibrary", "window.symbolLibrary.other"), + ("brush.loadLibrary", "window.brushLibrary.other"), ]; -/// Everything the palette searches: (label, command id or `tool:`, shortcut). -pub fn items() -> Vec<(String, String, String)> { - let mut items = vec![]; - // Aliases kept for older scripts run a command that is listed already, and a wrapped engine - // command is listed as its UI command. +/// Engine commands that [`crate::shortcut_editor::needs_a_value`] marks and that a pick, which +/// gives no params, still runs: Stop Script stops the running script, Clear Script Console empties +/// the Script Console, Clear Plug-in Cache deletes every plug-in's cache, Reset Preferences resets +/// every preference, Forget Import Matches forgets every saved match, Begin Undo Group and End +/// Undo Group begin and end a group, the six Save … Preset commands save a new preset (Save +/// Gradient Preset the selection's gradient), Delete Gradient Preset deletes the saved preset the +/// selection's gradient matches, Pixel Snapping Options… +/// opens its dialog, the three Asset Export commands open the Asset Export panel (#4864), New +/// Symbol makes a symbol of the selection, Gradient Vector gives the selection the default +/// gradient, Define Perspective Grid makes the document's grid, and Select Slice deselects the +/// slices. +const PICK_RUNS: &[&str] = &[ + "script.stop", + "script.console.clear", + "plugin.clearCache", + "prefs.reset", + "importMatches.reset", + "edit.undoGroup.begin", + "edit.undoGroup.end", + "imageTrace.presets.save", + "flattener.presets.save", + "pdf.preset.save", + "print.presets.save", + "perspective.presets.save", + "gradient.presets.save", + "gradient.presets.delete", + "view.snapToPixel.options", + "assets.export", + "assets.export3D", + "assets.settings.set", + "symbol.new", + "paint.setGradientGeom", + "perspective.grid.set", + "object.slice.select", +]; + +/// The menu path of a panel's result: a pick runs Show Panel (`window.panel`) for the panel. +const PANEL_PATH: &str = "Window › Show Panel"; + +/// The menu path ([`context`]) a result takes when another result has its name: (id, English +/// path), for commands that no item of the menu bar runs and whose id names no parent command. +const CONTEXTS: &[(&str, &str)] = &[ + ("addon.pen.close", "Pen"), + ("addon.pen.reshape", "Pen"), + ("addon.pen.togglePoint", "Pen"), + ("charStyle.setAttrs", "Character Styles"), + ("file.exportInBackground", "Export"), + ("file.openInBackground", "Open"), + ("imageTrace.hideRuns", "Image Trace"), + ("links.reveal", "Links"), + ("livePaint.fill", "Live Paint"), + ("object.blend.spine.convertAnchor", "Blend"), + ("paraStyle.setAttrs", "Paragraph Styles"), + ("path.close", "Path"), + ("path.convertAnchor", "Path"), + ("path.knife", "Path"), + ("path.reshapeSegment", "Path"), + ("plugin.hideRuns", "Plug-ins"), + ("text.editRange", "Text"), + ("ui.layersPanelOptions", "Layers"), + ("ui.navigatorPanelOptions", "Navigator"), +]; + +/// A palette result before its name is made distinct ([`distinct_names`]). +struct Draft { + /// The English menu path, `›`-separated; each segment translates. + path: String, + /// The English label. + label: String, + /// Does the label translate? An installed filter plug-in's name does not. + translates: bool, + id: String, + shortcut: String, + /// Has [`distinct_names`] given the result its [`context`]? + in_context: bool, + /// Does the result show its id after its name? + keyed: bool, +} + +impl Draft { + fn new(path: &str, label: &str, id: String, shortcut: &str) -> Draft { + Draft { + path: path.to_string(), + label: label.to_string(), + translates: true, + id, + shortcut: shortcut.to_string(), + in_context: false, + keyed: false, + } + } + + /// The name in `lang`: the path's segments and the label translate on their own, and the id + /// follows in parentheses when the result shows it. + fn name(&self, lang: crate::i18n::Lang) -> String { + // A built-in effect's label translates by its effect id first, as the Effect menu's does. + let label = match self.id.strip_prefix("effect:") { + _ if !self.translates => self.label.as_str(), + Some(effect) => crate::i18n::tr_id(lang, effect, &self.label), + None => crate::i18n::tr(lang, &self.label), + }; + let name = if self.path.is_empty() { label.to_string() } else { format!("{} › {label}", shown_label(lang, &self.path)) }; + if self.keyed { format!("{name} ({})", self.id) } else { name } + } +} + +/// The palette's results before their names are made distinct: every listed engine command and +/// plug-in command, UI command, tool, panel and Effect menu item. +fn drafts() -> Vec { + let mut out = vec![]; + // Aliases kept for older scripts run a command that is listed already, a wrapped engine + // command is listed as its UI command, and an engine command with a UI command of the same id + // (Place…, Print…) is listed once, as the UI command. An engine command that needs a value a + // pick doesn't give, or a query whose answer a pick drops ([`crate::shortcut_editor::needs_a_value`]), + // is left out unless it does something besides answering ([`PICK_RUNS`]). let plugin_commands = vectorcraft_engine::cmd::plugin::command_specs(); - let listed = |id: &str| !vectorcraft_engine::cmd::is_alias(id) && !WRAPPED.iter().any(|(engine, _)| *engine == id); - let labeled = |menu: &[&str], label: &str| { - let path = menu.join(" › "); - if path.is_empty() { label.to_string() } else { format!("{path} › {label}") } + let ui_ids: std::collections::HashSet<&str> = menus::UI_COMMANDS.iter().map(|c| c.0).collect(); + let listed = |c: &vectorcraft_engine::CommandSpec| { + !vectorcraft_engine::cmd::is_alias(c.id) + && !WRAPPED.iter().any(|(engine, _)| *engine == c.id) + && !ui_ids.contains(c.id) + && (!crate::shortcut_editor::needs_a_value(c.id) || PICK_RUNS.contains(&c.id)) }; - for c in vectorcraft_engine::command_specs().iter().filter(|c| listed(c.id)).chain(plugin_commands) { - items.push((labeled(c.menu, c.label), c.id.to_string(), menus::shortcut_of(c.id).unwrap_or("").to_string())); + for c in vectorcraft_engine::command_specs().iter().filter(|c| listed(c)).chain(plugin_commands) { + out.push(Draft::new(&c.menu.join(" › "), c.label, c.id.to_string(), menus::shortcut_of(c.id).unwrap_or(""))); } // `plugin.dialog` runs nothing without an id: [`build`] lists each filter instead. A script of // the Scripts folder runs from File › Scripts, by its path. A UI command that wraps an engine - // command takes that command's menu path, so a search for the path still finds it. + // command, or has an engine command's id, takes that command's menu path, so a search for the + // path still finds it. for c in menus::UI_COMMANDS.iter().filter(|c| c.0 != "plugin.dialog" && c.0 != crate::scripts_menu::COMMAND) { - let engine = WRAPPED.iter().find(|(_, ui)| *ui == c.0).and_then(|(engine, _)| vectorcraft_engine::find_command(engine)); - let label = engine.map_or_else(|| c.1.to_string(), |e| labeled(e.menu, c.1)); - items.push((label, c.0.to_string(), menus::shortcut_of(c.0).unwrap_or("").to_string())); + let engine = WRAPPED.iter().find(|(_, ui)| *ui == c.0).map_or(c.0, |(engine, _)| *engine); + let engine = vectorcraft_engine::find_command(engine); + let path = engine.map(|e| e.menu.join(" › ")).unwrap_or_default(); + out.push(Draft::new(&path, c.1, c.0.to_string(), menus::shortcut_of(c.0).unwrap_or(""))); } for tool in vectorcraft_tools::catalog::all_tools() { - items.push((tool.label.to_string(), format!("tool:{}", tool.id), crate::shortcut_editor::tool_shortcut(tool.id).unwrap_or("").to_string())); + out.push(Draft::new("", tool.label, format!("tool:{}", tool.id), crate::shortcut_editor::tool_shortcut(tool.id).unwrap_or(""))); + } + // A panel's result shows the panel, as `window.panel` does without `toggle`, under Window › + // Show Panel. + for (id, label) in crate::state::all_panels() { + out.push(Draft::new(PANEL_PATH, label, format!("panel:{id}"), crate::shortcut_editor::panel_shortcut(id).unwrap_or(""))); + } + // An Effect menu item runs what its item runs; a live-effect plug-in's name does not translate. + for e in crate::shortcut_editor::effect_items().iter() { + out.push(Draft { + translates: vectorcraft_plugins::effect::plugin_id(&e.effect).is_none(), + ..Draft::new(&e.group, &e.label, format!("effect:{}", e.effect), crate::shortcut_editor::effect_shortcut(&e.effect).unwrap_or("")) + }); + } + out +} + +/// Everything the palette searches: (label, command id or `tool:`, shortcut). Labels are the +/// English names before [`build`] makes them distinct. +pub fn items() -> Vec<(String, String, String)> { + drafts().into_iter().map(|d| (d.name(crate::i18n::Lang::EN), d.id, d.shortcut)).collect() +} + +/// The menu path a result shows when its name is another result's: its [`CONTEXTS`] path, Tools +/// for a tool, the menu path of the item of the menu bar that runs it (the four Other Library… +/// commands go under Window › Swatch Libraries, Brush Libraries, Graphic Style Libraries and Symbol +/// Libraries), or the label of the command whose id is its id without the last part (Reset Panel +/// goes under Character Style Options and Paragraph Style Options). +fn context(id: &str) -> Option { + if let Some((_, path)) = CONTEXTS.iter().find(|(c, _)| *c == id) { + return Some(path.to_string()); + } + if id.starts_with("tool:") { + return Some("Tools".to_string()); + } + // A plug-in's, panel's or effect's result already shows its menu path. + if ["plugin:", "panel:", "effect:"].iter().any(|p| id.starts_with(p)) { + return None; + } + if let Some(path) = crate::shortcut_editor::menu_bar_path(id) { + return Some(path.to_string()); + } + let (parent, _) = id.rsplit_once('.')?; + let label = + vectorcraft_engine::find_command(parent).map(|c| c.label).or_else(|| menus::UI_COMMANDS.iter().find(|c| c.0 == parent).map(|c| c.1))?; + Some(label.trim_end_matches('…').to_string()) +} + +/// Gives results for different ids different names in each of `langs`. Results that share a name +/// in one of them take their [`context`], when they have one, as their menu path; results that +/// still share one show their id after it. An installed plug-in whose name is another +/// result's name with its id ("Blur (plugin:a)") shows its id too. +fn distinct_names(drafts: &mut [Draft], langs: &[crate::i18n::Lang]) { + // The results whose name, in one of `langs`, a result with another id has. + let shared = |drafts: &[Draft]| -> Vec { + let mut out = std::collections::BTreeSet::new(); + for &lang in langs { + let mut by_name: std::collections::HashMap> = std::collections::HashMap::new(); + for (i, d) in drafts.iter().enumerate() { + by_name.entry(d.name(lang)).or_default().push(i); + } + let differ = |list: &Vec| { + let ids: Vec<&str> = list.iter().filter_map(|&i| drafts.get(i)).map(|d| d.id.as_str()).collect(); + ids.iter().any(|id| Some(id) != ids.first()) + }; + out.extend(by_name.into_values().filter(differ).flatten()); + } + out.into_iter().collect() + }; + for i in shared(drafts) { + if let Some(d) = drafts.get_mut(i).filter(|d| !d.in_context) + && let Some(path) = context(&d.id) + { + d.path = path; + d.in_context = true; + } + } + // A pass gives every result of a shared name its id, so a name is shared again only by a result + // whose label ends with another result's id; one pass per result is enough. + for _ in 0..drafts.len() { + let mut changed = false; + for i in shared(drafts) { + if let Some(d) = drafts.get_mut(i).filter(|d| !d.keyed) { + d.keyed = true; + changed = true; + } + } + if !changed { + break; + } } - items } /// A palette label in `lang`: each `›`-separated menu segment and the command label translate on @@ -60,73 +273,140 @@ pub(crate) struct Entry { shortcut: String, /// The label in the UI language. shown: String, - /// The English label (what agents document), the shown 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. + /// The English label before and after [`distinct_names`] (what agents document), the shown + /// 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, + /// 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, + index: search::Index, + ranked: std::sync::Mutex)>>, +} + +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> { - type Cached = ((&'static str, u64, u64), Arc>); +/// The palette's entries in `lang` with the in-window menu bar. +#[cfg(test)] +fn entries(ctx: &egui::Context, lang: crate::i18n::Lang) -> Arc { + 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 { + type Cached = ((&'static str, u64, u64), bool, Arc); let key = cache_key(lang); let id = egui::Id::unique("palette-entries"); - if let Some((k, v)) = ctx.data(|d| d.get_temp::(id)) + if let Some((k, n, v)) = ctx.data(|d| d.get_temp::(id)) && k == key + && n == native { return v; } - let built: Arc> = Arc::new(build(lang)); - ctx.data_mut(|d| d.insert_temp::(id, (key, built.clone()))); + let built = Arc::new(catalog(lang, native)); + ctx.data_mut(|d| d.insert_temp::(id, (key, native, built.clone()))); built } -/// The palette's entries in `lang`: [`items`], then one per filter plug-in's Object › Plug-ins -/// item (`plugin:`), whose name is not translated. +/// 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> = + 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 { - let entry = |label: String, shown: String, id: String, shortcut: String| { - let mut haystack = format!("{}\n{}\n{}", label.to_lowercase(), shown.to_lowercase(), id.to_lowercase()); - // A UI command that wraps an engine command is also found by the engine command's id. - if let Some((engine, _)) = WRAPPED.iter().find(|(_, ui)| *ui == id) { - haystack.push('\n'); - haystack.push_str(&engine.to_lowercase()); - } - Entry { id, shortcut, shown, haystack } - }; - let mut out: Vec = items() - .into_iter() - .map(|(label, id, shortcut)| { - let shown = shown_label(lang, &label); - entry(label, shown, id, shortcut) - }) - .collect(); - out.extend(crate::shortcut_editor::filter_items().iter().map(|f| { - let shortcut = crate::shortcut_editor::filter_shortcut(&f.id).unwrap_or("").to_string(); - let label = format!("{} › {}", f.group, f.label); - let shown = format!("{} › {}", shown_label(lang, &f.group), f.label); - entry(label, shown, format!("plugin:{}", f.id), shortcut) + build_in(lang, false) +} + +/// The palette's entries in `lang`: [`items`], then one per filter plug-in's Object › Plug-ins +/// item (`plugin:`), 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. Each entry's menu home is read from the native menu bar when `native`. +fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { + let homes = search::menu_homes(native); + let mut drafts = drafts(); + drafts.extend(crate::shortcut_editor::filter_items().iter().map(|f| Draft { + translates: false, + ..Draft::new(&f.group, &f.label, format!("plugin:{}", f.id), crate::shortcut_editor::filter_shortcut(&f.id).unwrap_or("")) })); - out + let plain: Vec = drafts.iter().map(|d| d.name(crate::i18n::Lang::EN)).collect(); + distinct_names(&mut drafts, &[crate::i18n::Lang::EN, lang]); + drafts + .into_iter() + .zip(plain) + .map(|(d, plain)| { + let (label, shown) = (d.name(crate::i18n::Lang::EN), d.name(lang)); + let mut haystack = [plain, label, shown.clone(), d.id.clone()].map(|s| s.to_lowercase()).join("\n"); + // A UI command that wraps an engine command is also found by the engine command's id. + if let Some((engine, _)) = WRAPPED.iter().find(|(_, ui)| *ui == d.id) { + haystack.push('\n'); + haystack.push_str(&engine.to_lowercase()); + } + 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() } /// Runs the palette result `id`: selects a tool, or invokes a command with the params its entry /// stands for. A command whose menu bar item gives params runs what a click on that item runs /// ([`crate::shortcut_editor::menu_target_now`]), so Clean Up… and Find and Replace… open their /// dialogs. While that item is dimmed, no dialog opens and the status line says why the command -/// can't run. +/// can't run. A panel's result shows the panel, and an effect's result runs what its Effect menu +/// item runs ([`crate::keymap::command_of`]). pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { if let Some(tool) = id.strip_prefix("tool:") { app.select_tool(tool); - } else if id.starts_with("plugin:") { + } else if let Some(panel) = id.strip_prefix("panel:") { + // A panel that can be seen stays as it is, where `window.panel` would put an open flyout or + // a floating panel away. In Presentation Mode the pick fails and changes nothing, as + // `window.panel` does. + if app.ui.screen_mode >= 3 { + app.status("panels can't be shown in Presentation Mode"); + } else if let Err(e) = crate::panel_docking::reveal_panel(app, panel) { + app.status(e); + } + } else if id.starts_with("plugin:") || id.starts_with("effect:") { let command = crate::keymap::command_of(id); - menus::invoke(app, &command.id, command.params); + // While the Effect menu dims the item (nothing selected), no dialog opens and the status + // line says why. + if id.starts_with("effect:") && !menus::enabled(app, &command.id) { + if let Err(why) = crate::shortcut_editor::dimmed(app, &command.id) { + app.status(why); + } + } else { + menus::invoke(app, &command.id, command.params); + } } else { match crate::shortcut_editor::menu_target_now(app, id) { Some(Ok((id, p))) => menus::invoke(app, &id, p), @@ -136,6 +416,111 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { } } +/// 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. +const ROW_HEIGHT: f32 = 20.0; +/// The most result rows the list shows at once; the others scroll into view. +const VISIBLE_ROWS: usize = 12; +/// The most results the list holds. The footer says how many matched in all. +const MAX_RESULTS: usize = 50; +/// The popup's distance from the top of the window, in points. +const TOP: f32 = 90.0; +/// The space kept between the popup and the bottom of the window, in points. +const BOTTOM_GAP: f32 = 8.0; + +/// What a result row shows and screen readers read: its name, and its shortcut after a comma. +fn row_label(e: &Entry) -> String { + let shortcut = menus::shown_shortcut(&e.shortcut); + if shortcut.is_empty() { e.shown.clone() } else { format!("{}, {shortcut}", e.shown) } +} + +/// The line under the results: how many results matched, how many of them the list holds when it +/// can't hold them all, or that none matched. +fn footer(listed: usize, total: usize) -> String { + if total == 0 { + tl!("No commands match").to_string() + } else if listed < total { + let line = crate::i18n::tn( + total as u64, + "{shown} of {n} result. Keep typing to narrow them.", + "{shown} of {n} results. Keep typing to narrow them.", + ); + crate::i18n::fmt(&line, &[("shown", &listed.to_string())]) + } else { + crate::i18n::tn(total as u64, "{n} result", "{n} results") + } +} + +/// How many times each key that moves the highlighted result was pressed this frame. +#[derive(Default)] +struct Moves { + down: usize, + up: usize, + page_down: usize, + page_up: usize, +} + +impl Moves { + fn any(&self) -> bool { + self.down + self.up + self.page_down + self.page_up > 0 + } + + /// The highlighted result of `n` after these moves from `sel`, a page being `page` rows: Up and + /// Down wrap at the ends, Page Up and Page Down stop at them. + fn apply(&self, sel: usize, n: usize, page: usize) -> usize { + let Some(last) = n.checked_sub(1) else { return 0 }; + let sel = sel.min(last); + let sel = (sel + self.down % n) % n; + let sel = (sel + n - self.up % n) % n; + let sel = sel.saturating_add(page.saturating_mul(self.page_down)).min(last); + sel.saturating_sub(page.saturating_mul(self.page_up)) + } +} + +/// `name` laid out on one line at most `width` points wide; a longer name ends with "…". +fn name_galley(painter: &egui::Painter, name: &str, font: egui::FontId, color: egui::Color32, width: f32) -> Arc { + let mut job = egui::text::LayoutJob::simple_singleline(name.to_owned(), font, color); + job.wrap = egui::text::TextWrapping { max_width: width.max(0.0), max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; + painter.layout_job(job) +} + +/// The scroll offset that keeps row `sel` in a list `view` points tall that was scrolled to `offset`. +fn offset_showing(sel: usize, offset: f32, view: f32) -> f32 { + let top = sel as f32 * ROW_HEIGHT; + offset.min(top).max(top + ROW_HEIGHT - view).max(0.0) +} + +/// The row nearest to `sel` among the rows of `n` wholly in view of a list `view` points tall +/// scrolled to `offset`. +fn nearest_in_view(sel: usize, offset: f32, view: f32, n: usize) -> usize { + let Some(last_row) = n.checked_sub(1) else { return 0 }; + // Half a point of leeway takes in rounding of the offset. + let first = (((offset - 0.5) / ROW_HEIGHT).ceil().max(0.0) as usize).min(last_row); + let end = ((offset + view + 0.5) / ROW_HEIGHT).floor().max(0.0) as usize; + let last = end.saturating_sub(1).clamp(first, last_row); + sel.clamp(first, last) +} + +/// 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); + /// How many picks the Recent Commands list beside the search field holds. pub(crate) const MAX_RECENT_COMMANDS: usize = 5; @@ -176,27 +561,72 @@ pub(crate) fn recent_list_open(ctx: &egui::Context) -> bool { } 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 + // closes, unless a pick opened a dialog, which focuses its own first field, or the press that + // closed it focused another widget, such as a field in a window above the backdrop. + let focus_id = egui::Id::unique("palette-focus-before"); + let field_id = egui::Id::unique("palette-field"); if !app.ui.palette_open { + let field = ctx.data_mut(|d| { + let field = d.get_temp::(field_id); + d.remove::(field_id); + field + }); + let now = ctx.memory(|m| m.focused()); + if let Some(Some(before)) = ctx.data_mut(|d| d.remove_temp::>(focus_id)) + && app.ui.dialog.is_none() + && (now.is_none() || now == field) + { + ctx.memory_mut(|m| m.request_focus(before)); + } return; } + if ctx.data(|d| d.get_temp::>(focus_id)).is_none() { + let before = ctx.memory(|m| m.focused()); + ctx.data_mut(|d| d.insert_temp(focus_id, before)); + } 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 matches: Vec<&Entry> = entries.iter().filter(|e| q.split_whitespace().all(|w| e.haystack.contains(w))).take(14).collect(); - let recent = recent(&entries, &app.ui.recent_commands); + let entries = entries_in(ctx, crate::i18n::current(), app.services.native_menu.is_some()); + let mut matches = matching(&entries, &q); + 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. + let sel_id = egui::Id::unique("palette-selected"); + let (mut sel, last_q, mut offset, last_view, last_id) = ctx.data(|d| d.get_temp::(sel_id)).unwrap_or_default(); + let mut view = last_view; + let new_query = last_q != q; + // A result that ranks above the highlighted one when the results change under the same query + // can push it past the last shown result; it then takes the last shown row instead, and + // `kept` holds its place among every match. + let mut kept = None; + if !new_query + && let Some(at) = matches.iter().position(|e| e.id == last_id) + && at >= MAX_RESULTS + { + let held_result = matches.remove(at); + matches.truncate(MAX_RESULTS - 1); + matches.push(held_result); + kept = Some(at); + } + matches.truncate(MAX_RESULTS); + let recent = recent(&entries.list, &app.ui.recent_commands); // While the Recent Commands list is open, the arrow keys and Enter go to its rows, and the // search field leaves them the keyboard. let list_open = recent_list_open(ctx); let mut run: Option = None; let mut history_focused = false; - // The highlighted result (#1757): Up and Down move it (wrapping), 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) = ctx.data(|d| d.get_temp::<(usize, String)>(sel_id)).unwrap_or_default(); - if 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; // The Recent Commands row with the keyboard: Up and Down move it, wrapping at the ends, so the // keys never leave the list for the results below it. let rsel_id = egui::Id::unique("palette-recent-selected"); @@ -222,67 +652,141 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { run = Some(e.id.clone()); } let n = matches.len(); + let mut moves = Moves::default(); if n > 0 && !list_open { - let (down, up) = - ctx.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown), i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp))); - if down { - sel = (sel + 1) % n; - } - if up { - sel = (sel + n - 1) % n; - } - sel = sel.min(n - 1); + ctx.input_mut(|i| { + let mut key = |k| i.count_and_consume_key(egui::Modifiers::NONE, k); + moves = Moves { + down: key(egui::Key::ArrowDown), + up: key(egui::Key::ArrowUp), + page_down: key(egui::Key::PageDown), + page_up: key(egui::Key::PageUp), + }; + }); } - egui::Area::new(egui::Id::unique("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, 90.0]).show(ctx, |ui| { - egui::Frame::popup(ui.style()).fill(t.panel).inner_margin(egui::Margin::same(10)).show(ui, |ui| { + let screen = ctx.content_rect(); + // The highlighted result the rows and the field's description are drawn with. + let mut drawn = sel; + // The backdrop covers the canvas, the toolbars, the docked panels and the app bar under the + // popup, in the order of a modal dialog's backdrop (`dialogs::modal::backdrop`), so the press + // that closes the palette does not press a control under it. Windows in the Foreground order + // stay above it. Not focusable (`Sense::click()` is): Tab stays in the popup. + egui::Area::new(egui::Id::unique("palette-backdrop")).order(egui::Order::Middle).fixed_pos(screen.min).show(ctx, |ui| { + ui.allocate_rect(screen, egui::Sense::CLICK); + }); + // The area keeps itself inside the window (egui's `Area::constrain` is on), so in a window too + // short for the field, one row and the footer below TOP, the popup moves up. + egui::Area::new(egui::Id::unique("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, TOP]).show(ctx, |ui| { + let margin: i8 = 10; + egui::Frame::popup(ui.style()).fill(t.panel).inner_margin(egui::Margin::same(margin)).show(ui, |ui| { ui.set_width(520.0); - ui.horizontal(|ui| { - let r = ui.add( - egui::TextEdit::singleline(&mut app.ui.palette_query) - .align(egui::Align2::LEFT_CENTER) - .hint_text(tl!("Search commands and tools…")) - .desired_width(470.0), - ); - // Recent Commands: the last picks, most recent first. A choice runs as a pick of - // the same result does. The first row takes the keyboard when the list opens, and - // the row with the keyboard keeps it while the list is open. - let button = crate::widgets::icon_button(ui, "history", tl!("Recent Commands"), false, 24.0); - // The search field keeps the keyboard, except while the list is open or Tab has - // moved it to the list's button, where Enter or Space opens the list. - history_focused = button.has_focus(); - if !list_open && !history_focused { - r.request_focus(); - } - egui::Popup::menu(&button).id(recent_list_id()).show(|ui| { - if recent.is_empty() { - ui.add_enabled(false, egui::Button::new(tl!("No recent commands"))); + let r = ui + .horizontal(|ui| { + let r = ui.add( + egui::TextEdit::singleline(&mut app.ui.palette_query) + .align(egui::Align2::LEFT_CENTER) + .hint_text(tl!("Search commands, tools, panels and effects…")) + .desired_width(470.0), + ); + // Recent Commands: the last picks, most recent first. A choice runs as a pick of + // the same result does. The first row takes the keyboard when the list opens, and + // the row with the keyboard keeps it while the list is open. + let button = crate::widgets::icon_button(ui, "history", tl!("Recent Commands"), false, 24.0); + // The search field keeps the keyboard, except while the list is open or Tab has + // moved it to the list's button, where Enter or Space opens the list. + history_focused = button.has_focus(); + if !list_open && !history_focused { + r.request_focus(); } - for (i, e) in recent.iter().enumerate() { - let row = ui.add(egui::Button::new(e.shown.as_str()).shortcut_text(menus::shown_shortcut(&e.shortcut))); - if i == rsel { - row.request_focus(); + egui::Popup::menu(&button).id(recent_list_id()).show(|ui| { + if recent.is_empty() { + ui.add_enabled(false, egui::Button::new(tl!("No recent commands"))); } - if row.clicked() { - run = Some(e.id.clone()); + for (i, e) in recent.iter().enumerate() { + let row = ui.add(egui::Button::new(e.shown.as_str()).shortcut_text(menus::shown_shortcut(&e.shortcut))); + if i == rsel { + row.request_focus(); + } + if row.clicked() { + run = Some(e.id.clone()); + } } + }); + r + }) + .inner; + ui.ctx().data_mut(|d| d.insert_temp(field_id, r.id)); + ui.add_space(6.0); + // The list shows as many rows as fit above the footer in the window, up to + // VISIBLE_ROWS; a page is that many rows. + let spacing = ui.spacing().item_spacing.y; + let footer_height = spacing + 6.0 + ui.text_style_height(&egui::TextStyle::Body) + f32::from(margin) + BOTTOM_GAP; + let room = screen.bottom() - footer_height - ui.cursor().top() - spacing; + let rows = ((room / ROW_HEIGHT).floor().max(1.0) as usize).min(VISIBLE_ROWS); + sel = moves.apply(sel, n, rows); + drawn = sel; + view = rows.min(n) as f32 * ROW_HEIGHT; + // When the list's height changes, as when the window is resized, the list scrolls to + // keep the highlighted result in view. + let resized = (view - last_view).abs() > 0.5; + // Screen readers stay on the field: its description names the highlighted result and + // its place among every match, as the footer counts them. + if let Some(e) = matches.get(sel) { + let rank = if sel + 1 == matches.len() { kept.unwrap_or(sel) } else { sel }; + let pos = (rank + 1).to_string(); + let of = total.to_string(); + let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &row_label(e))]); + ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); + } + if n > 0 { + ui.scope(|ui| { + // `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 || moved { + offset = offset_showing(sel, if new_query { 0.0 } else { offset }, view); + area = area.vertical_scroll_offset(offset); + } + let out = area.show_rows(ui, ROW_HEIGHT, n, |ui, range| { + for i in range { + let Some(e) = matches.get(i) else { continue }; + let (rect, resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), ROW_HEIGHT), egui::Sense::click()); + if resp.hovered() && ui.input(|inp| inp.pointer.delta() != egui::Vec2::ZERO) { + sel = i; + } + let on = i == sel; + if on { + ui.painter().rect_filled(rect, 4.0, ui.visuals().selection.bg_fill); + } + let font = egui::TextStyle::Body.resolve(ui.style()); + let shortcut = menus::shown_shortcut(&e.shortcut); + let p = ui.painter(); + let shortcut_at = rect.right_center() - egui::vec2(8.0, 0.0); + let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), t.text_dim); + let name_end = if shortcut.is_empty() { rect.right() - 8.0 } else { used.left() - 12.0 }; + let name_at = rect.left() + 8.0; + let name = name_galley(p, &e.shown, font, t.text, name_end - name_at); + p.galley(egui::pos2(name_at, rect.center().y - name.size().y / 2.0), name, t.text); + // `WidgetInfo::selected` reaches screen readers as a toggled state, so the + // row sets the selected state on its node itself. + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, row_label(e))); + ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(on)); + if resp.clicked() { + run = Some(e.id.clone()); + } + } + }); + let before = offset; + offset = out.state.clamped_offset().y; + // After a scroll with the wheel or the scroll bar, the highlight moves to the + // nearest row in view, so Enter runs a result that can be seen. + if !new_query && !moves.any() && (offset - before).abs() > 0.5 { + sel = nearest_in_view(sel, offset, view, n); } }); - }); - ui.add_space(6.0); - for (i, e) in matches.iter().enumerate() { - let resp = ui.add( - egui::Button::new(e.shown.as_str()) - .shortcut_text(menus::shown_shortcut(&e.shortcut)) - .min_size(egui::vec2(500.0, 24.0)) - .selected(i == sel), - ); - if resp.hovered() && ui.input(|i| i.pointer.delta() != egui::Vec2::ZERO) { - sel = i; - } - if resp.clicked() { - run = Some(e.id.clone()); - } } + ui.add_space(6.0); + ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim)); if !list_open && !history_focused && ui.input(|i| i.key_pressed(egui::Key::Enter)) @@ -292,14 +796,37 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); }); + // A press of any pointer button that neither the popup's layer nor its Recent Commands list's + // layer gets closes it: a press on the backdrop, or on a window above it, which also gets the + // press, even where that window lies over the popup. + let presses: Vec = ctx.input(|i| { + i.events + .iter() + .filter_map(|e| match e { + egui::Event::PointerButton { pos, pressed: true, .. } => Some(*pos), + _ => None, + }) + .collect() + }); + let popup = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("palette")); + let list = egui::LayerId::new(egui::Order::Foreground, recent_list_id()); + let outside = presses.into_iter().any(|p| !ctx.layer_id_at(p).is_some_and(|l| l == popup || l == list)); + // The pointer or a scroll moved the highlight after the rows were drawn: the next frame draws + // it where it now is. + if sel != drawn { + ctx.request_repaint(); + } + let sel_key = matches.get(sel).map(|e| e.id.clone()).unwrap_or_default(); ctx.data_mut(|d| { - d.insert_temp(sel_id, (sel, q)); + d.insert_temp::(sel_id, (sel, q, offset, view, sel_key)); d.insert_temp(rsel_id, rsel); }); if let Some(id) = run { app.ui.palette_open = false; - remember(&mut app.ui.recent_commands, &id, |c| entries.iter().any(|e| e.id == c)); + remember(&mut app.ui.recent_commands, &id, |c| entries.list.iter().any(|e| e.id == c)); run_pick(app, &id); + } else if outside { + app.ui.palette_open = false; } } @@ -342,7 +869,7 @@ mod tests { let ctx = egui::Context::default(); let query = "use precise cursors"; let entries = entries(&ctx, Lang::EN); - let matches: Vec<&Entry> = entries.iter().filter(|e| query.split_whitespace().all(|word| e.haystack.contains(word))).take(14).collect(); + let matches = matching(&entries, query); assert!(matches.iter().any(|e| e.id == "view.preciseCursors"), "preference toggle appears for its name"); assert!(entries.iter().filter(|e| e.id == "view.capsLock").all(|e| e.shown != "Use Precise Cursors")); @@ -884,7 +1411,7 @@ mod tests { let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; let frame = |app: &mut VectorcraftApp, events: Vec| { ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui.ctx())).textures_delta.clear(); - ctx.data(|d| d.get_temp::<(usize, String)>(egui::Id::unique("palette-selected"))).unwrap().0 + ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().0 }; assert_eq!(frame(&mut app, vec![]), 0); assert_eq!(frame(&mut app, vec![key(egui::Key::ArrowDown)]), 1); @@ -893,6 +1420,149 @@ mod tests { assert!(last > 1, "Up on the first result wraps to the last: {last}"); app.ui.palette_query = "zoom in".into(); assert_eq!(frame(&mut app, vec![]), 0); + // With more matches than the list holds, Up on the first wraps to the last one it holds, and + // Down there wraps to the first. + app.ui.palette_query = "select".into(); + assert!(matching(&entries(&ctx, Lang::EN), "select").len() > MAX_RESULTS); + assert_eq!(frame(&mut app, vec![]), 0); + assert_eq!(frame(&mut app, vec![key(egui::Key::ArrowUp)]), MAX_RESULTS - 1); + assert_eq!(frame(&mut app, vec![key(egui::Key::ArrowDown)]), 0); + } + + /// Each command, tool and plug-in is one result: Place… and Print…, which are engine commands + /// and UI commands of one id, are listed once, under their engine menu path. + #[test] + fn each_id_is_one_result() { + let entries = build(Lang::EN); + let mut seen = std::collections::HashSet::new(); + let twice: Vec<&str> = entries.iter().filter(|e| !seen.insert(e.id.as_str())).map(|e| e.id.as_str()).collect(); + assert!(twice.is_empty(), "{twice:?}"); + let shown = |id: &str| entries.iter().find(|e| e.id == id).map(|e| e.shown.as_str()); + assert_eq!((shown("file.place"), shown("file.print")), (Some("File › Place…"), Some("Print…"))); + } + + /// No two results for different commands, tools or plug-ins show the same name, in English or + /// in any language with a complete menu catalog. + #[test] + fn different_results_show_different_names() { + let langs = std::iter::once(Lang::EN).chain(Lang::all().filter(|l| l.complete_menus())); + let mut shared = vec![]; + for lang in langs { + let mut by_name: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for e in build(lang) { + let ids = by_name.entry(e.shown).or_default(); + if !ids.contains(&e.id) { + ids.push(e.id); + } + } + shared.extend(by_name.into_iter().filter(|(_, ids)| ids.len() > 1).map(|(name, ids)| format!("{}: {name}: {ids:?}", lang.code()))); + } + assert!(shared.is_empty(), "{} shared names:\n{}", shared.len(), shared.join("\n")); + } + + /// Results that would share a name show the panel, menu or command they belong to, or their id + /// when nothing else tells them apart. A query still finds them + /// by the plain name, the new path in English or in the UI language, and the id. + #[test] + fn results_that_share_a_name_show_where_they_belong() { + let entries = build(Lang::EN); + let shown = |id: &str| entries.iter().find(|e| e.id == id).map(|e| e.shown.clone()).unwrap_or_else(|| panic!("{id} is a result")); + for (id, want) in [ + ("file.exportInBackground", "Export › Continue in Background"), + ("file.openInBackground", "Open › Continue in Background"), + ("imageTrace.hideRuns", "Image Trace › Continue in Background"), + ("plugin.hideRuns", "Plug-ins › Continue in Background"), + ("ui.layersPanelOptions", "Layers › Panel Options…"), + ("ui.navigatorPanelOptions", "Navigator › Panel Options…"), + ("ui.charStyleOptions.resetPanel", "Character Style Options › Reset Panel"), + ("ui.paraStyleOptions.resetPanel", "Paragraph Style Options › Reset Panel"), + ("window.swatchLibrary.other", "Window › Swatch Libraries › Other Library…"), + ("window.brushLibrary.other", "Window › Brush Libraries › Other Library…"), + ("tool:knife", "Tools › Knife"), + ("path.knife", "Path › Knife"), + ("addon.pen.close", "Pen › Close Path"), + ("path.close", "Path › Close Path"), + ("type.fitHeadline", "Type › Fit Headline (type.fitHeadline)"), + ("text.fitHeadline", "Type › Fit Headline (text.fitHeadline)"), + ("shape.ellipse", "Ellipse (shape.ellipse)"), + ("addon.shapes.ellipse", "Ellipse (addon.shapes.ellipse)"), + ("perspective.editText", "Object › Perspective › Edit Text"), + ("ui.action.play", "Play Action (ui.action.play)"), + ("ui.action.playAt", "Play Action (ui.action.playAt)"), + ("ui.batchDialog", "Batch…"), + ("ui.flattenerPreview", "Flattener Preview"), + ] { + assert_eq!(shown(id), want, "{id}"); + } + assert!(shown("perspective.grid.rulers").contains("Perspective Grid"), "{}", shown("perspective.grid.rulers")); + assert_ne!(shown("perspective.grid.rulers"), shown("view.rulers")); + assert!(entries.iter().all(|e| e.id != "action.batch" && e.id != "flattener.preview"), "the engine commands are listed as their UI commands"); + // A name nobody else has stays as it was. + assert_eq!(shown("object.group"), "Object › Group"); + let found = |entries: &[Entry], query: &str| -> Vec { + entries.iter().filter(|e| query.split_whitespace().all(|w| e.haystack.contains(&w.to_lowercase()))).map(|e| e.id.clone()).collect() + }; + let id = "file.exportInBackground".to_string(); + for query in ["continue in background", "export continue in background", "file.exportinbackground"] { + assert!(found(&entries, query).contains(&id), "{query}"); + } + assert!(!found(&entries, "open continue in background").contains(&id)); + let zh = Lang::from_code("zh-hant").unwrap(); + let zh_entries = build(zh); + let export = crate::i18n::tr(zh, "Export"); + let background = zh_entries.iter().find(|e| e.id == id).unwrap(); + assert_eq!(background.shown, format!("{export} › {}", crate::i18n::tr(zh, "Continue in Background"))); + assert!(found(&zh_entries, &format!("{export} continue in background")).contains(&id)); + } + + /// Every menu path a result can take when it shares a name, and Window › Show Panel, has a row + /// in each catalog with complete menus. Each command [`CONTEXTS`] names is a result. + #[test] + fn the_paths_of_results_that_share_a_name_translate() { + let ids: Vec = items().into_iter().map(|(_, id, _)| id).collect(); + for (id, _) in CONTEXTS { + assert!(ids.iter().any(|i| i == id), "{id} is a result"); + } + let mut paths: Vec = CONTEXTS.iter().map(|(_, path)| path.to_string()).collect(); + paths.push("Tools".into()); + paths.push(PANEL_PATH.into()); + let mut by_name: std::collections::HashMap> = std::collections::HashMap::new(); + for d in drafts() { + by_name.entry(d.name(Lang::EN)).or_default().push(d.id); + } + paths.extend(by_name.into_values().filter(|ids| ids.len() > 1).flatten().filter_map(|id| context(&id))); + let mut missing = vec![]; + for lang in Lang::all().filter(|l| l.complete_menus()) { + for segment in paths.iter().flat_map(|p| p.split(" › ")) { + let row = format!("{}: {segment}", lang.code()); + if !crate::i18n::has(lang, segment) && !missing.contains(&row) { + missing.push(row); + } + } + } + assert!(missing.is_empty(), "{}", missing.join("\n")); + } + + /// A pick of each of two results that shared a name runs its own command: Show Rulers under View + /// › Rulers toggles the document rulers, and the one under the perspective grid toggles the + /// grid's rulers. + #[test] + fn a_pick_of_a_renamed_result_runs_its_own_command() { + let entries = build(Lang::EN); + let picks: Vec<(String, String)> = + entries.iter().filter(|e| e.haystack.lines().next() == Some("show rulers")).map(|e| (e.id.clone(), e.shown.clone())).collect(); + assert_eq!(picks.len(), 2, "{picks:?}"); + assert!(picks.iter().all(|(_, name)| name != "Show Rulers") && picks[0].1 != picks[1].1, "{picks:?}"); + for (id, name) in &picks { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let label = |app: &VectorcraftApp, id: &str| crate::menus::dynamic_label(app, id, ""); + let before: Vec = picks.iter().map(|(other, _)| label(&app, other)).collect(); + run_pick(&mut app, id); + for ((other, _), before) in picks.iter().zip(before) { + assert_eq!(label(&app, other) != before, other == id, "{name}: {other}"); + } + } } /// Each filter plug-in has one result, also when two share a name: its menu path translates, @@ -929,4 +1599,1026 @@ mod tests { vectorcraft_plugins::registry::remove(one); vectorcraft_plugins::registry::remove(two); } + + /// Of the engine commands the palette listed before, it leaves out only the ones + /// [`crate::shortcut_editor::needs_a_value`] marks: queries with no default key and no item of + /// the menu bar, and commands that need a value no menu item gives. A pick of each one it leaves + /// out (with no document, one object selected or several) changes neither the document, its + /// selection, history and layer state, nor the interface. Every [`PICK_RUNS`] query is still + /// listed. + #[test] + fn the_palette_leaves_out_the_commands_a_pick_cannot_run() { + use vectorcraft_testkit::fixtures::Fixture; + let ui_ids: std::collections::HashSet<&str> = menus::UI_COMMANDS.iter().map(|c| c.0).collect(); + // The rule before: every engine command but the aliases, the wrapped commands and the ids of + // UI commands. + let before: Vec<&vectorcraft_engine::CommandSpec> = vectorcraft_engine::command_specs() + .iter() + .filter(|c| !vectorcraft_engine::cmd::is_alias(c.id) && !WRAPPED.iter().any(|(e, _)| *e == c.id) && !ui_ids.contains(c.id)) + .collect(); + let listed: std::collections::HashSet = items().into_iter().map(|(_, id, _)| id).collect(); + let dropped: Vec<&vectorcraft_engine::CommandSpec> = before.iter().copied().filter(|c| !listed.contains(c.id)).collect(); + let ids: Vec<&str> = dropped.iter().map(|c| c.id).collect(); + for id in ["document.json", "brush.unused", "symbol.unused", "transparency.set"] { + assert!(ids.contains(&id), "{id} is left out: {ids:?}"); + } + // What a pick can change: the document with its selection, history, revision and layer + // state, the Script Console, and the interface's state (an open dialog or panel, the + // selected tool), the status line aside. + let look = |app: &VectorcraftApp| { + let mut ui = serde_json::to_value(&app.ui).unwrap_or_default(); + if let Some(o) = ui.as_object_mut() { + o.remove("status"); + } + let doc = app.session.active().map(|st| { + (st.doc.clone(), format!("{:?}", st.selection), st.history.undo.len(), st.revision, st.active_layer, st.layer_rows.clone()) + }); + (doc, app.session.script_console().lines().len(), ui) + }; + let acts = |id: &str| { + [vectorcraft_engine::Session::new(), Fixture::Single.session(), Fixture::Multi.session()].into_iter().any(|session| { + let mut app = VectorcraftApp::new(session, crate::Services::default()); + let before = look(&app); + run_pick(&mut app, id); + look(&app) != before + }) + }; + // `layer.setProps {}` records an undo step that changes nothing. + let changed: Vec<&str> = ids.iter().copied().filter(|id| *id != "layer.setProps" && acts(id)).collect(); + assert!(changed.is_empty(), "a pick of these does something: {changed:?}"); + for c in &dropped { + assert!(c.shortcut.is_none() && crate::shortcut_editor::menu_bar_path(c.id).is_none(), "{}", c.id); + } + // The others are still listed, and each of PICK_RUNS, which needs_a_value marks. A pick of + // each one changes what `look` sees, except the commands that act on the session alone: + // [`a_pick_of_a_session_command_runs_it`] covers those, or they need a running script, an + // installed plug-in or saved import matches. + for c in &before { + let marked = crate::shortcut_editor::needs_a_value(c.id); + assert_eq!(listed.contains(c.id), !marked || PICK_RUNS.contains(&c.id), "{}", c.id); + assert!(marked || !PICK_RUNS.contains(&c.id), "{} needs no entry in PICK_RUNS", c.id); + } + let session_only = [ + "script.stop", + "script.console.clear", + "plugin.clearCache", + "prefs.reset", + "importMatches.reset", + "edit.undoGroup.begin", + "edit.undoGroup.end", + "imageTrace.presets.save", + "flattener.presets.save", + "pdf.preset.save", + "print.presets.save", + "perspective.presets.save", + "gradient.presets.save", + "gradient.presets.delete", + ]; + for id in PICK_RUNS.iter().filter(|id| !session_only.contains(id)) { + assert!(acts(id), "a pick of {id} does something"); + } + for id in PICK_RUNS.iter().chain(&["object.group", "select.key", "view.preciseCursors", "path.close"]) { + assert!(listed.contains(*id), "{id} stays"); + } + } + + /// A pick of a query that changes the session runs it: Clear Script Console empties the Script + /// Console, Reset Preferences resets a changed preference, each Save … Preset command adds a + /// preset, Delete Gradient Preset deletes the one saved from the selection, and the edits between Begin Undo Group and End Undo Group are one undo step. + #[test] + fn a_pick_of_a_session_command_runs_it() { + let ids: Vec = items().into_iter().map(|(_, id, _)| id).collect(); + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default()); + let pick = |app: &mut VectorcraftApp, id: &str| { + assert!(ids.iter().any(|i| i == id), "{id} is a result"); + run_pick(app, id); + }; + app.session.script_frames = true; + app.run("script.run", json!({"source": "$.writeln('line')", "name": "c.js"})).unwrap(); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(&mut app); + } + assert!(!app.session.script_running() && !app.session.script_console().lines().is_empty()); + pick(&mut app, "script.console.clear"); + assert!(app.session.script_console().lines().is_empty(), "{}", app.ui.status); + + let default = app.session.prefs.use_precise_cursors; + app.session.prefs.use_precise_cursors = !default; + pick(&mut app, "prefs.reset"); + assert_eq!(app.session.prefs.use_precise_cursors, default, "{}", app.ui.status); + + for (save, list) in [ + ("imageTrace.presets.save", "imageTrace.presets"), + ("flattener.presets.save", "flattener.presets.list"), + ("pdf.preset.save", "pdf.preset.list"), + ("print.presets.save", "print.presets.list"), + ("perspective.presets.save", "perspective.presets.list"), + ] { + let count = |app: &mut VectorcraftApp| app.run(list, json!({})).unwrap()["presets"].as_array().map_or(0, Vec::len); + let before = count(&mut app); + pick(&mut app, save); + assert_eq!(count(&mut app), before + 1, "{save}: {}", app.ui.status); + } + // Save Gradient Preset saves the selection's gradient, and Delete Gradient Preset deletes + // the saved preset it matches. + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"kind": "linear", "stops": stops}})).unwrap(); + pick(&mut app, "gradient.presets.save"); + assert_eq!(app.session.prefs.gradient_presets.len(), 1, "{}", app.ui.status); + pick(&mut app, "gradient.presets.delete"); + assert!(app.session.prefs.gradient_presets.is_empty(), "{}", app.ui.status); + + let undo = |app: &VectorcraftApp| app.session.active().map_or(0, |st| st.history.undo.len()); + let before = undo(&app); + pick(&mut app, "edit.undoGroup.begin"); + for x in [10, 200] { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + } + pick(&mut app, "edit.undoGroup.end"); + assert_eq!(undo(&app), before + 1, "{}", app.ui.status); + } + + /// The UI commands that open an engine command's dialog or ask first are still listed, and the + /// engine commands they wrap are not. + #[test] + fn the_wrapping_ui_commands_stay_listed() { + let ids: std::collections::HashSet = items().into_iter().map(|(_, id, _)| id).collect(); + for (engine, ui) in WRAPPED { + assert!(ids.contains(*ui) && !ids.contains(*engine), "{ui} listed, {engine} not"); + } + assert!(menus::UI_COMMANDS.iter().filter(|c| c.0 != "plugin.dialog" && c.0 != crate::scripts_menu::COMMAND).all(|c| ids.contains(c.0))); + } + + /// Each panel is a result under Window › Show Panel. A pick shows the panel, and a second pick + /// 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 = 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. + for (query, want) in [("layers", "panel:layers"), ("color guide", "panel:colorGuide"), ("Layers ", "panel:layers")] { + let all = entries.iter().filter(|e| query.to_lowercase().split_whitespace().all(|w| e.haystack.contains(w))).count(); + let shown: Vec<&str> = matching(&entries, &query.to_lowercase()).into_iter().map(|e| e.id.as_str()).collect(); + assert_eq!(shown.first(), Some(&want), "{query}: {shown:?}"); + assert_eq!(shown.len(), all, "{query}"); + } + let layers = entries.iter().find(|e| e.id == "panel:layers").unwrap(); + assert_eq!(layers.shown, "Window › Show Panel › Layers"); + assert_eq!(layers.shortcut, crate::shortcut_editor::panel_shortcut("layers").unwrap_or("")); + let zh = Lang::from_code("zh-hant").unwrap(); + let shown = build(zh).into_iter().find(|e| e.id == "panel:layers").map(|e| e.shown).unwrap(); + assert_eq!(shown, ["Window", "Show Panel", "Layers"].map(|s| crate::i18n::tr(zh, s)).join(" › ")); + for id in ["swatches", crate::panels::asset_export::ID] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + assert!(!crate::panel_docking::showing(&app.ui, id), "{id}"); + run_pick(&mut app, &format!("panel:{id}")); + assert!(crate::panel_docking::showing(&app.ui, id), "{id}: {}", app.ui.status); + run_pick(&mut app, &format!("panel:{id}")); + assert!(crate::panel_docking::showing(&app.ui, id), "{id}: picked twice, still showing"); + } + } + + /// In Presentation Mode a panel's pick fails as `window.panel` does: the status line says why, + /// and the panel does not show when the mode ends. + #[test] + fn a_panel_pick_in_presentation_mode_changes_nothing() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let (open_panel, dock) = (app.ui.open_panel.clone(), app.ui.dock); + app.ui.screen_mode = 3; + run_pick(&mut app, "panel:swatches"); + assert_eq!(app.ui.status, "panels can't be shown in Presentation Mode"); + assert_eq!((app.ui.open_panel.clone(), app.ui.dock), (open_panel, dock)); + app.ui.screen_mode = 0; + assert!(!crate::panel_docking::showing(&app.ui, "swatches"), "the pick did not place the panel"); + } + + /// Each Effect menu item is a result under its menu path, with its shortcut. With a document + /// open and an object selected, a pick of Drop Shadow… opens its dialog, as the menu item + /// does, and changes nothing until the dialog is confirmed. + #[test] + fn an_effect_is_a_result_whose_pick_runs_its_menu_item() { + let entries = build(Lang::EN); + let effects = crate::shortcut_editor::effect_items(); + for e in effects.iter() { + let key = format!("effect:{}", e.effect); + assert_eq!(entries.iter().filter(|r| r.id == key).count(), 1, "{key}"); + } + let found: Vec<&Entry> = entries.iter().filter(|e| "drop shadow".split_whitespace().all(|w| e.haystack.contains(w))).collect(); + let shadow = + found.iter().find(|e| e.id.starts_with("effect:")).unwrap_or_else(|| panic!("{:?}", found.iter().map(|e| &e.id).collect::>())); + let item = effects.iter().find(|e| format!("effect:{}", e.effect) == shadow.id).unwrap(); + assert_eq!(shadow.shown, format!("{} › {}", item.group, item.label)); + let mut picked = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default()); + let mut clicked = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default()); + let before = outcome(&picked); + run_pick(&mut picked, &shadow.id); + menus::invoke(&mut clicked, item.command, json!({ "effect": item.effect })); + let after = outcome(&picked); + assert!(after.0.is_some(), "the dialog opens: {}", after.2); + assert_eq!(after.1, before.1, "nothing changes yet"); + assert_eq!(after, outcome(&clicked), "the pick runs what the menu item runs"); + // With nothing selected the menu item is dimmed: no dialog opens, and the status line says + // why. + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.status.clear(); + run_pick(&mut app, &shadow.id); + assert!(app.ui.dialog.is_none() && !app.ui.status.is_empty(), "{}", app.ui.status); + // A built-in effect's name translates by its id, as the Effect menu shows it. + let fr = Lang::from_code("fr").unwrap(); + let add = build(fr).into_iter().find(|e| e.id == "effect:pathfinder.add").map(|e| e.shown).unwrap(); + assert!(add.ends_with(crate::i18n::tr_id(fr, "pathfinder.add", "Add")), "{add}"); + assert_eq!(crate::i18n::tr_id(fr, "pathfinder.add", "Add"), "Réunion"); + } + + /// Two filter plug-ins with one name show their ids after it, the name untranslated, and each + /// pick runs its own filter. + #[test] + fn filter_plugins_with_one_name_show_their_ids() { + use vectorcraft_plugins::wat as tpl; + let (one, two) = ("test.UI.palette_same-one", "test.UI.palette_same-two"); + for id in [one, two] { + let manifest = format!(r#"{{"id":"{id}","name":"Same Name","version":"1","kind":"filter","params":{{"wiggle":{{"type":"bool"}}}}}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + } + let zh = Lang::from_code("zh-hant").unwrap(); + let built = build(zh); + let path = format!("{} › {}", crate::i18n::tr(zh, "Object"), crate::i18n::tr(zh, "Plug-ins")); + for id in [one, two] { + let key = format!("plugin:{id}"); + let shown: Vec<&str> = built.iter().filter(|e| e.id == key).map(|e| e.shown.as_str()).collect(); + assert_eq!(shown, [format!("{path} › Same Name… ({key})")], "{id}"); + } + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + for id in [one, two] { + run_pick(&mut app, &format!("plugin:{id}")); + let d = app.ui.dialog.take().expect("the filter's dialog opens"); + assert_eq!(d.str("__plugin"), id.to_string()); + } + vectorcraft_plugins::registry::remove(one); + vectorcraft_plugins::registry::remove(two); + } + + /// The open palette in a window, drawn a frame at a time with the app's theme, in English, with + /// screen readers on. + struct Open { + app: VectorcraftApp, + ctx: egui::Context, + size: egui::Vec2, + time: f64, + /// Whether the last frame asked for another one at once. + repaint: bool, + } + + impl Open { + /// The palette open on `query` in a window `size` points big. + fn new(query: &str, size: egui::Vec2) -> Open { + crate::i18n::set_current(Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui.palette_open = true; + app.ui.palette_query = query.into(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let mut open = Open { app, ctx, size, time: 0.0, repaint: false }; + open.frame(vec![]); + open + } + + /// One frame with `events`: its screen-reader tree. + fn frame(&mut self, events: Vec) -> Vec { + self.time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, self.size); + let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; + let app = &mut self.app; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + self.repaint = out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() + } + + /// A frame where `k` is pressed `times` times. + fn press(&mut self, k: egui::Key, times: usize) -> Vec { + let key = egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + self.frame(vec![key; times]) + } + + /// The highlighted result's index. + fn highlighted(&self) -> usize { + self.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().0 + } + + /// The popup's rectangle. + fn popup(&self) -> egui::Rect { + self.ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))).unwrap() + } + + /// The results the palette lists for its query. + fn listed(&self) -> Vec { + let entries = entries(&self.ctx, Lang::EN); + matching(&entries, &self.app.ui.palette_query.to_lowercase()).iter().take(MAX_RESULTS).map(|e| e.id.clone()).collect() + } + } + + /// The result rows of a screen-reader tree, top to bottom: (label, highlighted, top, bottom). + fn rows(nodes: &[egui::accesskit::Node]) -> Vec<(String, bool, f64, f64)> { + let mut rows: Vec<(String, bool, f64, f64)> = nodes + .iter() + .filter(|n| n.role() == egui::accesskit::Role::ListItem) + .map(|n| { + let b = n.bounds().unwrap(); + (n.label().unwrap_or_default().to_string(), n.is_selected() == Some(true), b.y0, b.y1) + }) + .collect(); + rows.sort_by(|a, b| a.2.total_cmp(&b.2)); + rows + } + + /// The text of the labels in a screen-reader tree. + fn labels(nodes: &[egui::accesskit::Node]) -> Vec { + nodes.iter().filter(|n| n.role() == egui::accesskit::Role::Label).filter_map(|n| n.label().or(n.value()).map(str::to_string)).collect() + } + + /// The search field's screen-reader description. + fn field_description(nodes: &[egui::accesskit::Node]) -> String { + let field = nodes.iter().find(|n| n.role() == egui::accesskit::Role::TextInput).expect("the search field is in the tree"); + field.description().unwrap_or_default().to_string() + } + + const WINDOW: egui::Vec2 = egui::vec2(1280.0, 900.0); + + /// Each result is a 20-point row, rows touch, and 12 show at once; the popup is shorter than + /// the 14 24-point buttons it showed before. + #[test] + fn results_are_compact_rows_that_touch() { + let mut open = Open::new("select", WINDOW); + let nodes = open.frame(vec![]); + let rows = rows(&nodes); + let inside: Vec<_> = rows.iter().filter(|r| r.3 <= f64::from(open.popup().bottom())).collect(); + assert!(inside.len() >= VISIBLE_ROWS, "{rows:?}"); + for pair in inside.windows(2).take(VISIBLE_ROWS - 1) { + assert_eq!(pair[0].3 - pair[0].2, f64::from(ROW_HEIGHT), "{pair:?}"); + assert_eq!(pair[0].3, pair[1].2, "rows touch: {pair:?}"); + } + // 14 results took 458 points before the rows were made compact. + let height = open.popup().height(); + println!("popup height for {VISIBLE_ROWS} rows: {height}"); + assert!(height <= 330.0, "{height}"); + } + + /// The footer says how many results matched, how many of them the list holds when it holds + /// fewer, or that none matched. + #[test] + fn the_footer_counts_the_results() { + crate::i18n::set_current(Lang::EN); + assert_eq!(footer(50, 60), "50 of 60 results. Keep typing to narrow them."); + assert_eq!(footer(3, 3), "3 results"); + assert_eq!(footer(1, 1), "1 result"); + assert_eq!(footer(0, 0), "No commands match"); + // The count takes each language's form. + crate::i18n::set_current(Lang::from_code("ru").unwrap()); + let ru = [footer(50, 51), footer(50, 52), footer(2, 2)]; + crate::i18n::set_current(Lang::EN); + assert_eq!( + ru, + [ + "50 из 51 результата. Продолжайте вводить, чтобы сузить их.", + "50 из 52 результатов. Продолжайте вводить, чтобы сузить их.", + "2 результата" + ] + ); + let mut open = Open::new("select", WINDOW); + let total = matching(&entries(&open.ctx, Lang::EN), "select").len(); + assert!(total > MAX_RESULTS, "{total}"); + let nodes = open.frame(vec![]); + assert!(labels(&nodes).contains(&format!("50 of {total} results. Keep typing to narrow them.")), "{:?}", labels(&nodes)); + // Every result the list holds is reachable: End of the list by keyboard shows the 50th. + let nodes = open.press(egui::Key::ArrowUp, 1); + assert_eq!(open.highlighted(), MAX_RESULTS - 1); + assert!(rows(&nodes).iter().any(|r| r.1), "the 50th row is drawn and highlighted"); + } + + /// With no match, the footer says so and Enter runs nothing and leaves the palette open. + #[test] + fn with_no_match_enter_runs_nothing() { + let mut open = Open::new("qqzzxxnothing", WINDOW); + let nodes = open.frame(vec![]); + assert!(rows(&nodes).is_empty()); + assert!(labels(&nodes).contains(&"No commands match".to_string()), "{:?}", labels(&nodes)); + open.app.ui.status.clear(); + open.press(egui::Key::Enter, 1); + open.frame(vec![]); + assert!(open.app.ui.palette_open && open.app.ui.status.is_empty(), "{}", open.app.ui.status); + } + + /// Down 15 times from the first result highlights the 16th, scrolled into view, and Enter runs + /// it. + #[test] + fn the_sixteenth_result_is_reached_by_keyboard_and_runs() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + assert!(listed.len() > 16, "{listed:?}"); + let nodes = open.press(egui::Key::ArrowDown, 15); + assert_eq!(open.highlighted(), 15); + let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); + let entries = entries(&open.ctx, Lang::EN); + let want = entries.iter().find(|e| e.id == listed[15]).map(row_label).unwrap(); + assert_eq!(lit.len(), 1, "{lit:?}"); + assert_eq!(lit[0].0, want); + let popup = open.popup(); + assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "scrolled into view: {lit:?} in {popup:?}"); + let panel = listed[15].strip_prefix("panel:").expect("a panel's result").to_string(); + assert!(!crate::panel_docking::showing(&open.app.ui, &panel), "{panel}"); + open.press(egui::Key::Enter, 1); + assert!(!open.app.ui.palette_open); + assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); + } + + /// Page Down and Page Up move the highlight by the rows shown, stopping at the ends; Up and + /// Down wrap. + #[test] + fn page_keys_move_by_a_page_without_wrapping() { + let moves = |down, up, page_down, page_up| Moves { down, up, page_down, page_up }; + assert_eq!(moves(0, 0, 1, 0).apply(0, 50, 12), 12); + assert_eq!(moves(0, 0, 1, 0).apply(45, 50, 12), 49); + assert_eq!(moves(0, 0, 0, 1).apply(5, 50, 12), 0); + assert_eq!(moves(1, 0, 0, 0).apply(49, 50, 12), 0); + assert_eq!(moves(0, 1, 0, 0).apply(0, 50, 12), 49); + assert_eq!(moves(3, 0, 0, 0).apply(48, 50, 12), 1); + assert_eq!(moves(1, 0, 0, 0).apply(0, 0, 12), 0); + let mut open = Open::new("select", WINDOW); + open.press(egui::Key::PageDown, 1); + assert_eq!(open.highlighted(), VISIBLE_ROWS); + open.press(egui::Key::PageDown, 5); + assert_eq!(open.highlighted(), MAX_RESULTS - 1, "stops at the last"); + open.press(egui::Key::PageUp, 1); + assert_eq!(open.highlighted(), MAX_RESULTS - 1 - VISIBLE_ROWS); + open.press(egui::Key::PageUp, 9); + assert_eq!(open.highlighted(), 0, "stops at the first"); + } + + /// After the list is scrolled with the wheel, the highlight is on a row in view, so Enter runs a + /// result that can be seen. + #[test] + fn a_wheel_scroll_keeps_the_highlight_in_view() { + assert_eq!(nearest_in_view(0, 100.0, 240.0, 50), 5); + assert_eq!(nearest_in_view(30, 100.0, 240.0, 50), 16); + assert_eq!(nearest_in_view(8, 100.0, 240.0, 50), 8); + assert_eq!(nearest_in_view(3, 0.0, 240.0, 3), 2); + assert_eq!(nearest_in_view(0, 0.0, 240.0, 0), 0); + let mut open = Open::new("select", WINDOW); + let nodes = open.frame(vec![]); + let first = rows(&nodes).into_iter().next().unwrap(); + let at = egui::pos2(open.popup().center().x, ((first.2 + first.3) / 2.0) as f32); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -200.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + open.frame(vec![egui::Event::PointerMoved(at)]); + let mut nodes = open.frame(vec![wheel]); + // The frames that follow, up to the last one the palette or the scroll asks for, which + // has to show the highlight where Enter runs it. + for _ in 0..120 { + if !open.repaint { + break; + } + nodes = open.frame(vec![]); + } + assert!(!open.repaint, "the scroll settles"); + let sel = open.highlighted(); + assert!(sel > 0, "the highlight left the row scrolled out of view"); + let popup = open.popup(); + let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); + assert_eq!(lit.len(), 1, "{lit:?}"); + assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}"); + assert_eq!(lit[0].0, row_label(entries(&open.ctx, Lang::EN).iter().find(|e| e.id == open.listed()[sel]).unwrap())); + } + + /// When the window shrinks so the list shows fewer rows, the list scrolls to keep the + /// highlighted result in view, and Enter runs that result. + #[test] + fn a_shorter_window_keeps_the_highlight_in_view() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + assert!(listed.len() > VISIBLE_ROWS, "{listed:?}"); + open.press(egui::Key::ArrowDown, VISIBLE_ROWS - 1); + assert_eq!(open.highlighted(), VISIBLE_ROWS - 1); + open.size = egui::vec2(800.0, 300.0); + let nodes = open.frame(vec![]); + assert_eq!(open.highlighted(), VISIBLE_ROWS - 1); + let popup = open.popup(); + let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); + assert_eq!(lit.len(), 1, "{lit:?}"); + assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}"); + let panel = listed[VISIBLE_ROWS - 1].strip_prefix("panel:").expect("a panel's result").to_string(); + assert!(!crate::panel_docking::showing(&open.app.ui, &panel), "{panel}"); + open.press(egui::Key::Enter, 1); + assert!(!open.app.ui.palette_open); + assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); + } + + /// The pointer moved onto a row highlights that row alone, and the field's description names + /// it, on the frame drawn straight after. + #[test] + fn the_row_under_the_pointer_is_the_one_highlighted() { + let mut open = Open::new("select", WINDOW); + let listed = open.listed(); + let entries = entries(&open.ctx, Lang::EN); + let nodes = open.frame(vec![]); + let all = rows(&nodes); + let middle = |r: &(String, bool, f64, f64)| egui::pos2(open.popup().center().x, ((r.2 + r.3) / 2.0) as f32); + let (first, fourth) = (middle(&all[0]), middle(&all[3])); + open.frame(vec![egui::Event::PointerMoved(first)]); + open.frame(vec![egui::Event::PointerMoved(fourth)]); + assert_eq!(open.highlighted(), 3); + assert!(open.repaint, "the frame that moved the highlight asks for another"); + let nodes = open.frame(vec![]); + let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); + let label = entries.iter().find(|e| e.id == listed[3]).map(row_label).unwrap(); + assert_eq!(lit, std::slice::from_ref(&label)); + assert_eq!(field_description(&nodes), format!("4 of {}: {label}", matching(&entries, "select").len())); + } + + /// A name too long for its row is cut short with "…" and stays inside the width it is given. + #[test] + fn a_long_name_ends_with_an_ellipsis() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let font = egui::TextStyle::Body.resolve(ui.style()); + let long = "Window › Show Panel › A Panel Name Long Enough Not To Fit In The Row (addon.panels.long)"; + let cut = name_galley(ui.painter(), long, font.clone(), egui::Color32::WHITE, 200.0); + assert!(cut.elided && cut.size().x <= 200.0, "{:?}", cut.size()); + assert_eq!(cut.rows.last().and_then(|r| r.glyphs.last()).map(|g| g.chr), Some('…')); + let short = name_galley(ui.painter(), "Edit › Copy", font, egui::Color32::WHITE, 200.0); + assert!(!short.elided); + }); + out.textures_delta.clear(); + } + + /// The popup stays inside a short window, showing fewer rows when 12 don't fit; a page is the + /// rows shown. + #[test] + fn the_popup_stays_inside_a_short_window() { + for size in [egui::vec2(1280.0, 600.0), egui::vec2(800.0, 300.0), egui::vec2(800.0, 160.0)] { + let mut open = Open::new("select", size); + open.frame(vec![]); + let popup = open.popup(); + assert!(popup.top() >= 0.0 && popup.bottom() <= size.y, "{size:?}: {popup:?}"); + open.press(egui::Key::PageDown, 1); + let page = open.highlighted(); + if size.y < 400.0 { + assert!((1..VISIBLE_ROWS).contains(&page), "a short window shows fewer than 12 rows: {size:?}: {page}"); + } else { + assert_eq!(page, VISIBLE_ROWS, "{size:?}"); + } + } + } + + /// A click anywhere on a row, its empty right end included, runs it. + #[test] + fn a_click_anywhere_on_a_row_runs_it() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + let nodes = open.frame(vec![]); + let hidden = |id: &String| id.strip_prefix("panel:").is_some_and(|p| !crate::panel_docking::showing(&open.app.ui, p)); + let k = listed.iter().position(hidden).expect("a hidden panel's result"); + assert!(k < VISIBLE_ROWS, "{listed:?}"); + let row = rows(&nodes).into_iter().nth(k).unwrap(); + let popup = open.popup(); + let at = egui::pos2(popup.right() - 24.0, ((row.2 + row.3) / 2.0) as f32); + let panel = listed[k].strip_prefix("panel:").unwrap_or_default().to_string(); + assert!(!crate::panel_docking::showing(&open.app.ui, &panel), "{panel}"); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + open.frame(vec![egui::Event::PointerMoved(at)]); + open.frame(vec![button(true)]); + open.frame(vec![button(false)]); + assert!(!open.app.ui.palette_open); + assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); + } + + /// Screen readers stay on the field: its description names the highlighted result and its + /// place, and follows the highlight; the rows are list items, the highlighted one selected, and + /// the footer's count is a label. + #[test] + fn screen_readers_hear_the_highlighted_result_and_the_count() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + let entries = entries(&open.ctx, Lang::EN); + let label = |i: usize| entries.iter().find(|e| e.id == listed[i]).map(row_label).unwrap(); + let nodes = open.frame(vec![]); + // More results match than the list holds: the place counts every match, as the footer does. + let total = matching(&entries, "show panel").len(); + assert!(total > MAX_RESULTS && listed.len() == MAX_RESULTS, "{total}"); + assert_eq!(field_description(&nodes), format!("1 of {total}: {}", label(0))); + let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); + assert_eq!(lit, [label(0)]); + assert!(labels(&nodes).contains(&format!("50 of {total} results. Keep typing to narrow them.")), "{:?}", labels(&nodes)); + let nodes = open.press(egui::Key::ArrowDown, 1); + assert_eq!(field_description(&nodes), format!("2 of {total}: {}", label(1))); + // Fewer results match than the list holds. + let mut open = Open::new("copy", WINDOW); + let n = open.listed().len(); + assert!((1..MAX_RESULTS).contains(&n), "{n}"); + let first = entries.iter().find(|e| e.id == open.listed()[0]).map(row_label).unwrap(); + let nodes = open.frame(vec![]); + assert_eq!(field_description(&nodes), format!("1 of {n}: {first}")); + assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes)); + } + + /// The widget that had the keyboard focus when the palette opened has it again once the + /// palette closes. + #[test] + fn closing_gives_the_focus_back() { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut text = String::new(); + let field = egui::Id::unique("other field"); + let mut frame = |app: &mut VectorcraftApp, focus: bool| { + ctx.run_ui(egui::RawInput::default(), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut text).id(field)); + if focus { + r.request_focus(); + } + show(app, ui.ctx()); + }) + .textures_delta + .clear(); + }; + frame(&mut app, true); + frame(&mut app, false); + assert_eq!(ctx.memory(|m| m.focused()), Some(field)); + app.ui.palette_open = true; + frame(&mut app, false); + frame(&mut app, false); + assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the search field takes the focus"); + app.ui.palette_open = false; + frame(&mut app, false); + frame(&mut app, false); + assert_eq!(ctx.memory(|m| m.focused()), Some(field)); + // A pick that opens a dialog leaves the focus to the dialog. + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default()); + frame(&mut app, true); + app.ui.palette_open = true; + frame(&mut app, false); + frame(&mut app, false); + app.ui.palette_open = false; + run_pick(&mut app, "object.path.cleanUp"); + assert!(app.ui.dialog.is_some(), "Clean Up… opens its dialog: {}", app.ui.status); + frame(&mut app, false); + frame(&mut app, false); + assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the dialog keeps the focus"); + // A click on a field in a window above the backdrop closes the palette and leaves the + // focus in that field. + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let (mut text, mut above_text) = (String::new(), String::new()); + let above = egui::Id::unique("field above"); + let corner = egui::pos2(40.0, 400.0); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, focus: bool, events: Vec| { + time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, WINDOW); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }; + ctx.run_ui(input, |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut text).id(field)); + if focus { + r.request_focus(); + } + // Drawn before the palette, so the palette's own focus requests come after the field's. + egui::Area::new(egui::Id::unique("window above")).order(egui::Order::Foreground).fixed_pos(corner).show(ui.ctx(), |ui| { + ui.add(egui::TextEdit::singleline(&mut above_text).id(above)); + }); + show(app, ui.ctx()); + }) + .textures_delta + .clear(); + }; + frame(&mut app, true, vec![]); + frame(&mut app, false, vec![]); + app.ui.palette_open = true; + frame(&mut app, false, vec![]); + frame(&mut app, false, vec![]); + let at = corner + egui::vec2(20.0, 8.0); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, false, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, false, vec![button(true)]); + frame(&mut app, false, vec![button(false)]); + assert!(!app.ui.palette_open, "the click on the window above closes the palette"); + frame(&mut app, false, vec![]); + frame(&mut app, false, vec![]); + assert_eq!(ctx.memory(|m| m.focused()), Some(above), "the clicked field keeps the focus"); + } + + /// The whole window, with a document whose rectangle is selected, drawn a frame at a time in + /// English with screen readers on. + struct Window { + app: VectorcraftApp, + ctx: egui::Context, + time: f64, + /// Draw a window with an "Above" button at this place, in the Foreground order after the + /// app, as a progress window is drawn, and count its clicks. + above: Option, + above_clicks: usize, + } + + impl Window { + fn new() -> Window { + crate::i18n::set_current(Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + assert!(!app.session.doc().unwrap().selection.is_empty()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0 }; + window.frame(vec![]); + window.frame(vec![]); + window + } + + /// One frame of the whole window with `events`: its screen-reader tree. + fn frame(&mut self, events: Vec) -> Vec { + self.time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, WINDOW); + let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; + let app = &mut self.app; + let (above, clicks) = (self.above, &mut self.above_clicks); + let mut out = self.ctx.run_ui(input, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + if let Some(at) = above { + let area = egui::Area::new(egui::Id::unique("test-above")).order(egui::Order::Foreground).fixed_pos(at); + area.show(ui.ctx(), |ui| { + if ui.button("Above").clicked() { + *clicks += 1; + } + }); + } + }); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() + } + + /// A primary click at `at`, a frame for the move, the press and the release: the release + /// frame's screen-reader tree. + fn click(&mut self, at: egui::Pos2) -> Vec { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + self.frame(vec![egui::Event::PointerMoved(at)]); + self.frame(vec![button(true)]); + self.frame(vec![button(false)]) + } + + /// A press of `button` at `from`, a move to `to` and the release there, a frame each. + fn drag(&mut self, button: egui::PointerButton, from: egui::Pos2, to: egui::Pos2) { + let event = |pos, pressed| egui::Event::PointerButton { pos, button, pressed, modifiers: egui::Modifiers::NONE }; + self.frame(vec![egui::Event::PointerMoved(from)]); + self.frame(vec![event(from, true)]); + self.frame(vec![egui::Event::PointerMoved(to)]); + self.frame(vec![event(to, false)]); + } + + fn selection(&self) -> String { + format!("{:?}", self.app.session.doc().unwrap().selection) + } + + fn popup(&self) -> egui::Rect { + self.ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))).unwrap() + } + } + + /// The middle of the button whose screen-reader name is `name`, alone or followed by its + /// shortcut in parentheses. + fn button_at(nodes: &[egui::accesskit::Node], name: &str) -> egui::Pos2 { + let names: Vec<_> = nodes.iter().filter(|n| n.role() == egui::accesskit::Role::Button).filter_map(|n| n.label()).collect(); + let named = |l: &str| l == name || l.strip_prefix(name).is_some_and(|rest| rest.starts_with(' ') && rest.trim_start().starts_with('(')); + let node = nodes + .iter() + .find(|n| n.role() == egui::accesskit::Role::Button && n.label().is_some_and(named)) + .unwrap_or_else(|| panic!("a button named {name}: {names:?}")); + let b = node.bounds().unwrap(); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + } + + /// A click on the canvas outside the popup closes it and leaves the selection as it was. + #[test] + fn a_click_on_the_canvas_closes_the_palette() { + let mut window = Window::new(); + let before = window.selection(); + window.app.ui.palette_open = true; + window.frame(vec![]); + let canvas = window.app.canvas_rect.expect("the canvas is drawn"); + let at = canvas.left_bottom() + egui::vec2(30.0, -30.0); + assert!(!window.popup().contains(at), "{at:?} is outside {:?}", window.popup()); + window.click(at); + assert!(!window.app.ui.palette_open, "the click outside closes the palette"); + window.frame(vec![]); + assert_eq!(window.selection(), before, "the click does not reach the canvas"); + } + + /// A click on another control outside the popup closes the popup and does not press the + /// control. + #[test] + fn a_click_on_another_control_closes_the_palette_without_pressing_it() { + let mut window = Window::new(); + let tool = window.app.session.tool_id(); + window.app.ui.palette_open = true; + let nodes = window.frame(vec![]); + let at = button_at(&nodes, "Pen Tool"); + assert!(!window.popup().contains(at), "{at:?} is outside {:?}", window.popup()); + window.click(at); + assert!(!window.app.ui.palette_open, "the click outside closes the palette"); + window.frame(vec![]); + assert_eq!(window.app.session.tool_id(), tool, "the click does not pick the tool"); + // With the palette closed, the same click picks it. + window.click(at); + assert_eq!(window.app.session.tool_id(), "pen"); + } + + /// A right-click outside the popup closes it, and so does a drag that starts outside it. + #[test] + fn a_right_click_or_a_drag_outside_closes_the_palette() { + let mut window = Window::new(); + let before = window.selection(); + let canvas = window.app.canvas_rect.expect("the canvas is drawn"); + let at = canvas.left_bottom() + egui::vec2(30.0, -30.0); + window.app.ui.palette_open = true; + window.frame(vec![]); + assert!(!window.popup().contains(at), "{at:?} is outside {:?}", window.popup()); + window.drag(egui::PointerButton::Secondary, at, at); + assert!(!window.app.ui.palette_open, "the right-click outside closes the palette"); + window.app.ui.palette_open = true; + window.frame(vec![]); + window.drag(egui::PointerButton::Primary, at, at + egui::vec2(80.0, -60.0)); + assert!(!window.app.ui.palette_open, "the drag outside closes the palette"); + window.frame(vec![]); + assert_eq!(window.selection(), before, "the drag does not reach the canvas"); + } + + /// A click on a window drawn above the backdrop, as a progress window is, closes the palette + /// and presses that window's button, beside the popup and where the window lies over it. + #[test] + fn a_click_on_a_window_above_closes_the_palette_and_reaches_it() { + for over in [false, true] { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + let popup = window.popup(); + window.above = Some(if over { popup.center() } else { egui::pos2(40.0, 400.0) }); + window.frame(vec![]); + let nodes = window.frame(vec![]); + let at = button_at(&nodes, "Above"); + assert_eq!(popup.contains(at), over, "{at:?} and the popup {popup:?}"); + window.click(at); + assert!(!window.app.ui.palette_open, "over the popup: {over}; the click on the window closes the palette"); + assert_eq!(window.above_clicks, 1, "over the popup: {over}; the window gets the click"); + } + } + + /// The click on the app bar's search button that opens the palette leaves it open; the next + /// click on the button closes it. + #[test] + fn the_click_that_opens_the_palette_does_not_close_it() { + let mut window = Window::new(); + let nodes = window.frame(vec![]); + let at = button_at(&nodes, "Search commands, tools, panels and effects"); + window.click(at); + assert!(window.app.ui.palette_open, "the click opens the palette"); + window.frame(vec![]); + window.frame(vec![]); + assert!(window.app.ui.palette_open, "and it stays open"); + window.click(at); + assert!(!window.app.ui.palette_open, "a second click closes it"); + } + + /// Clicks inside the popup keep it open: one in the search field, and one on a result, which + /// runs that result. + #[test] + fn clicks_inside_the_palette_keep_it_or_run_a_result() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.app.ui.palette_query = "show panel".into(); + window.frame(vec![]); + let nodes = window.frame(vec![]); + let popup = window.popup(); + let middle = |b: egui::accesskit::Rect| egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + let field = nodes + .iter() + .filter(|n| n.role() == egui::accesskit::Role::TextInput) + .filter_map(|n| n.bounds().map(middle)) + .find(|p| popup.contains(*p)) + .expect("the search field"); + window.click(field); + window.frame(vec![]); + assert!(window.app.ui.palette_open, "a click in the field keeps the palette open"); + assert_eq!(window.app.ui.palette_query, "show panel"); + let nodes = window.frame(vec![]); + let entries = entries(&window.ctx, Lang::EN); + let listed: Vec<_> = matching(&entries, "show panel").into_iter().take(MAX_RESULTS).collect(); + let hidden = |e: &&&Entry| e.id.strip_prefix("panel:").is_some_and(|p| !crate::panel_docking::showing(&window.app.ui, p)); + let e = listed.iter().find(hidden).expect("a hidden panel's result"); + let label = row_label(e); + let row = rows(&nodes).into_iter().find(|r| r.0 == label).expect("its row is drawn"); + let panel = e.id.strip_prefix("panel:").unwrap_or_default().to_string(); + window.click(egui::pos2(window.popup().center().x, ((row.2 + row.3) / 2.0) as f32)); + 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); + let built = |ctx: &egui::Context| ctx.data(|d| d.get_temp::(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); + // Deep enough in the list that the highlighted result's name does not start with the query, + // also while other tests' "Group" filter plug-ins are installed. + open.press(egui::Key::ArrowDown, 6); + let held = |open: &Open| open.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap(); + let id = held(&open).4; + assert_eq!(open.listed().get(6), Some(&id)); + // A name no other test gives a plug-in, so the other tests' results keep their names. + let filter = "test.UI.palette_highlight-group"; + let manifest = format!(r#"{{"id":"{filter}","name":"Group Highlight Probe","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); + let was = listed.iter().position(|r| *r == id); + assert!(plugin.is_some() && plugin < was, "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 = 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"); + } + + /// A highlighted last shown result that a new result pushes past the limit stays shown and + /// highlighted, in the last row, so Enter still runs it; screen readers hear its place among + /// every match. + #[test] + fn the_highlighted_last_result_stays_shown_when_a_result_ranks_above_it() { + use vectorcraft_plugins::wat as tpl; + // A query no other test searches for, so the plug-in below leaves their results alone. + let mut open = Open::new("path", WINDOW); + assert!(matching(&entries(&open.ctx, Lang::EN), "path").len() > MAX_RESULTS); + open.press(egui::Key::ArrowUp, 1); + let held = |open: &Open| open.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap(); + let (sel, .., id) = held(&open); + assert_eq!(sel, MAX_RESULTS - 1); + let filter = "test.UI.palette_last-highlight-path"; + let manifest = format!(r#"{{"id":"{filter}","name":"Path Last Highlight Probe","version":"1","kind":"filter","params":{{}}}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + open.frame(vec![]); + let entries = entries(&open.ctx, Lang::EN); + let ranked: Vec<&Entry> = matching(&entries, "path"); + let nodes = open.frame(vec![]); + let (sel, .., now) = held(&open); + vectorcraft_plugins::registry::remove(filter); + let plugin = ranked.iter().position(|e| e.id == format!("plugin:{filter}")); + assert!(plugin.is_some_and(|p| p < MAX_RESULTS), "the plug-in is shown: {plugin:?}"); + assert_eq!(ranked.iter().position(|e| e.id == id), Some(MAX_RESULTS), "the plug-in pushed the highlight past the limit"); + assert_eq!((sel, &now), (MAX_RESULTS - 1, &id), "the highlight stays on its result, in the last row"); + let label = row_label(ranked[MAX_RESULTS]); + assert!(rows(&nodes).iter().any(|r| r.1 && r.0 == label), "its row is drawn and highlighted"); + assert_eq!(field_description(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); + } } diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs new file mode 100644 index 0000000000..a2bc113d4a --- /dev/null +++ b/crates/ui-egui/src/palette/search.rs @@ -0,0 +1,764 @@ +//! 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, + /// 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 { + 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 { + 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 { + 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]) -> 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 = 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::() + + 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 { + 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::>().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. A query starts a name +/// when it starts the name's label, or, for a query that holds `›`, the name with its menu path. +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; + } + // A menu's title alone does not put the items of that menu in this tier. + let with_path = query.contains('›'); + if names(e).any(|n| split_name(n).0.starts_with(query) || (with_path && n.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 { + 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> = 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:` for a Window menu panel (Learn too), +/// `effect:` for an Effect menu item and `plugin:` 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 { + 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) { + 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 { + 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) -> 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 { + 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")); + } + + /// 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. + #[test] + fn a_menu_title_does_not_lift_its_items() { + let c = synthetic(vec![entry("Object › Paint", "a.one"), entry("Outline Object", "b.two")]); + assert_eq!(ranked(&c, "object"), ["b.two", "a.one"]); + 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 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:?}"); + } + } + + /// The application menu of the native Mac menu bar holds the items [`menu_homes`] puts there, + /// under the same submenus. + #[test] + fn native_homes_follow_the_native_application_menu() { + use crate::native_menu::{self, MenuRole, Node}; + fn walk(nodes: &[Node], path: &mut Vec, out: &mut HashMap) { + for n in nodes { + match n { + Node::Item(it) => { + if let Some(id) = it.command { + out.entry(id.to_string()).or_insert_with(|| path.join(" › ")); + } + } + Node::Submenu { label, children } => { + path.push(label.clone()); + walk(children, path, out); + path.pop(); + } + _ => {} + } + } + } + let app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let bar = native_menu::mac_layout(&app, &native_menu::from_tree(&app, &menus::menu_tree()), Lang::EN).bar; + let app_menu = bar.menus.iter().find(|m| m.role == MenuRole::App).unwrap(); + let mut found = HashMap::new(); + walk(&app_menu.children, &mut vec![app_menu.title.clone()], &mut found); + // The items the native bar runs itself (Hide, Hide Others, Minimize) are not palette results. + found.retain(|id, _| ![native_menu::HIDE, native_menu::HIDE_OTHERS, native_menu::MINIMIZE].contains(&id.as_str())); + let homes = menu_homes(true); + let expected: HashMap = homes + .iter() + .filter(|(_, (path, _))| path.split(" › ").next() == Some(native_menu::APP_NAME)) + .map(|(id, (path, _))| (id.clone(), path.clone())) + .collect(); + assert!(!expected.is_empty()); + assert_eq!(found, expected); + } + + /// Queries from the list of things people type, on the English results: some list their command + /// first, others within the first few results. + #[test] + fn common_queries_list_the_command_near_the_top() { + 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_eq!(first("drop shadow"), "effect:stylize.dropShadow"); + 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 = 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); + } +} diff --git a/crates/ui-egui/src/panels/learn/tests.rs b/crates/ui-egui/src/panels/learn/tests.rs index 319ca1decf..bc58612701 100644 --- a/crates/ui-egui/src/panels/learn/tests.rs +++ b/crates/ui-egui/src/panels/learn/tests.rs @@ -104,7 +104,7 @@ fn explore_tutorials_on_the_app_bar_shows_and_hides_the_learn_panel() { let ctx = context(); assert!(!shown(&app)); let nodes = frame(&mut app, &ctx, vec![], app_bar); - let search = center_where(&nodes, |label| label.starts_with("Search commands and tools")); + let search = center_where(&nodes, |label| label.starts_with("Search commands, tools, panels and effects")); let learn = center(&nodes, "Explore tutorials"); let (search, learn) = (search.expect("the search icon shows"), learn.expect("the app bar has Explore tutorials")); assert!(learn.x < search.x && (learn.y - search.y).abs() < 1.0, "beside the search icon: {learn:?}, {search:?}"); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 348aed01fa..84c1ff4fa0 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -753,7 +753,7 @@ fn menu_bar_paths() -> &'static HashMap<&'static str, Vec<(String, Value)>> { /// The menu path of the item of the menu bar that runs command `id` as a key press runs it /// ([`a_menu_bar_item_runs`]): the first item that runs it with no params, or else the first item, /// whose params all its items give. -fn menu_bar_path(id: &str) -> Option<&'static str> { +pub(crate) fn menu_bar_path(id: &str) -> Option<&'static str> { let (_, params) = command_doc(id)?; let items = menu_bar_paths().get(id).filter(|_| a_menu_bar_item_runs(id, params))?; chosen_path(items) @@ -924,7 +924,7 @@ pub(crate) fn menu_target_now(app: &VectorcraftApp, id: &str) -> Option Result<(String, Value), String> { +pub(crate) fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> { let Some(why) = vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()) else { return Err(format!("command `{id}` is not available right now")); }; @@ -936,7 +936,7 @@ fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> { /// run without them (as the Variables panel's commands do), and it is a query, whose answer a key /// press drops (Select All Unused), a command of [`NEEDS_A_PARAM`], or a menu command whose params /// doc names a field a call must give (File › Document Setup › Units, `{units}`)? -fn needs_a_value(key: &str) -> bool { +pub(crate) fn needs_a_value(key: &str) -> bool { static KEYS: OnceLock> = OnceLock::new(); KEYS.get_or_init(|| { vectorcraft_engine::command_specs() @@ -3191,4 +3191,16 @@ mod tests { assert_eq!(r["shortcut"], "Cmd+Alt+Shift+F11"); assert!(app.run("shortcuts.preset", json!({"name": null})).unwrap_err().starts_with("unknown preset")); } + + /// A command that needs a value is listed in the editor once the user gives it a key, but the + /// command search still leaves it out: a pick gives it no value. + #[test] + fn a_command_given_a_key_that_needs_a_value_is_no_pick() { + let mut overrides = Overrides::default(); + crate::keymap::set_override(&mut overrides, "document.setUnits", "Cmd+Alt+Shift+F12"); + let entry = entries().iter().find(|e| e.key == "document.setUnits").cloned().expect("the editor has a row for it"); + assert!(!listed(&Overrides::default(), &entry) && listed(&overrides, &entry)); + assert!(needs_a_value("document.setUnits")); + assert!(crate::palette::items().iter().all(|(_, id, _)| id != "document.setUnits")); + } } diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs index b9b4111516..95756262b8 100644 --- a/crates/ui-egui/src/tests/save.rs +++ b/crates/ui-egui/src/tests/save.rs @@ -205,11 +205,13 @@ fn show_in_folder_needs_a_saved_document_and_a_file_manager() { assert_eq!(*shown.borrow(), ["/art/a.vectorcraft"]); } +/// The palette lists neither the old alias nor `file.documentColorMode`, which a pick can't run +/// without a mode; the CMYK and RGB menu items run the one command. #[test] -fn the_palette_lists_document_color_mode_once() { +fn document_color_mode_is_one_command() { let items = palette::items(); let ids: Vec<&str> = items.iter().map(|(_, id, _)| id.as_str()).filter(|id| id.to_ascii_lowercase().contains("documentcolormode")).collect(); - assert_eq!(ids, ["file.documentColorMode"]); + assert!(ids.is_empty(), "{ids:?}"); let mut app = app(); app.run("file.new", json!({})).unwrap(); let entries = menus::menu_entries(&app); diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index cbbd216e75..dd4ce4e38e 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -327,7 +327,7 @@ mod tests { let has = |s: &str| texts.iter().any(|t| t == s); assert_eq!(has("Discord"), width > 1000.0, "{width}: {texts:?}"); // Search is an icon only (as in PhotoCraft): its label lives in the tooltip. - assert!(!has("Search commands and tools"), "{width}: {texts:?}"); + assert!(!has("Search commands, tools, panels and effects"), "{width}: {texts:?}"); } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c96eeae8bd..04f9907fec 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1327,6 +1327,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The panel menu's Save Selection submenu has Save Selection…, Update Selection and Edit Selection…, enabled and run as in the Select menu, and lists the document's saved selections: choosing one selects its objects again (`select.recall`). Deleting rows from the Layers panel (the trash button, rows dragged onto it, the panel menu's Delete Selection, and Delete or Backspace on highlighted rows) asks "Delete this layer and its artwork?" when a layer or sublayer among them holds art, hidden, locked and nested art included, and "Delete the selected items and their artwork?" when several rows are deleted; OK deletes the rows it asked about in one undo step, and Cancel keeps them (`ui.layerDelete`). The help page's shortcut list names the Layers panel as the place where deleting asks for confirmation ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). An empty layer, a layer with only guides, and groups or objects alone are deleted without a question, and `layer.delete` itself does not ask (`panels::layers` tests `deleting_a_layer_that_holds_art_asks_first`, `delete_selection_asks_only_for_layers_with_art`). The Command Palette lists Window › Layers › Delete Selection once, as the Layers panel's `ui.layerDelete`, so a pick asks the same question; it does not list `layer.delete`, which scripts run without a question. New Brush…, Brush Options…, Symbol Options…, Import SVG Filter… and Convert to Text are also listed once each, as the UI command that opens the dialog or file chooser (`palette` tests `a_wrapped_engine_command_is_listed_once_as_its_ui_command`, `a_pick_of_delete_selection_asks_before_deleting_a_layer_with_art`). + No two Command Palette results for different commands, tools or plug-ins show the same name, in English or in any language with a complete menu catalog. Results that would share a name show the panel, menu or command they belong to (Export › Continue in Background and Open › Continue in Background, View › Rulers › Show Rulers and View › Perspective Grid › Show Rulers, Layers › Panel Options… and Navigator › Panel Options…, Tools › Knife and Path › Knife); results that still share one show their id after it (Ellipse (shape.ellipse) and Ellipse (addon.shapes.ellipse)), as two filter plug-ins with one name do. A query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as their UI command, and Place… and Print… once each (`palette` tests `different_results_show_different_names`, `results_that_share_a_name_show_where_they_belong`, `filter_plugins_with_one_name_show_their_ids`, `each_id_is_one_result`, `a_pick_of_a_renamed_result_runs_its_own_command`). + 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. A query of "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 without its menu path 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, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. 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); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). 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`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `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`, `native_homes_follow_the_native_application_menu`; `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.