diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 4cf9cb0ff9..80efd4ce11 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2259,6 +2259,9 @@ "Display profile not used": "Profil displeje nebyl použit", "Drag to set hue and saturation. Hold Shift to keep the hue, Cmd/Ctrl to keep the saturation, Alt/Option to fine-adjust. Double-click to reset.": "Tažením nastavíte odstín a sytost. Podržením Shift zachováte odstín, Cmd/Ctrl zachováte sytost, Alt/Option umožní jemné doladění. Dvojitým kliknutím obnovíte výchozí hodnoty.", "Edit In": "Upravit v", + "Filter settings": "Filtrovat nastavení", + "No setting matches what is typed.": "Zadanému textu neodpovídá žádné nastavení.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Zkuste jedno slovo nebo jeho část: prohledávají se názvy karet a sekcí, popisky i vysvětlivky.", "Face models (ONNX)": "Modely rozpoznávání obličejů (ONNX)", "ICC Profiles": "Profily ICC", "Next History Step": "Další krok historie", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 4341093f42..0b7e542c38 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2100,6 +2100,9 @@ "Not saved": "Nicht gespeichert", "A folder is being synchronized": "Ein Ordner wird gerade synchronisiert", "Wait for the import to finish": "Warte, bis der Import abgeschlossen ist", + "Filter settings": "Einstellungen filtern", + "No setting matches what is typed.": "Keine Einstellung passt zur Eingabe.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Versuche ein Wort oder einen Teil davon: Durchsucht werden die Namen der Tabs und Abschnitte, Beschriftungen und Erklärungen.", "Appearance": "Erscheinungsbild", "Appearance Mode": "Erscheinungsmodus", "Sync with System": "Mit System synchronisieren", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index d785455880..9cdf494637 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2126,6 +2126,9 @@ "Not saved": "Sin guardar", "A folder is being synchronized": "Se está sincronizando una carpeta", "Wait for the import to finish": "Esperar a que termine la importación", + "Filter settings": "Filtrar ajustes", + "No setting matches what is typed.": "Ningún ajuste coincide con lo escrito.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Prueba con una palabra o parte de ella: se buscan los nombres de pestañas y secciones, las etiquetas y las explicaciones.", "Appearance": "Apariencia", "Appearance Mode": "Modo de apariencia", "Sync with System": "Sincronizar con el sistema", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 4f63dc555b..c1a257b577 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2432,6 +2432,9 @@ "Folder name": "Kansion nimi", "Its templates move to User Templates.": "Sen mallipohjat siirretään kansioon Käyttäjän mallipohjat.", "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", + "Filter settings": "Suodata asetuksia", + "No setting matches what is typed.": "Mikään asetus ei vastaa kirjoitettua.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Kokeile yhtä sanaa tai sen osaa: haku kattaa välilehtien ja osioiden nimet, otsikot ja selitykset.", "A smart album's rules choose its photos: change them with Edit Smart Album…": "Älyalbumin säännöt valitsevat sen kuvat: muuta niitä komennolla Muokkaa älyalbumia…", "Add keywords in the Keyword List": "Lisää avainsanoja avainsanaluettelossa", "Already on these photos": "Jo näissä kuvissa", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 209837d707..09e25a19d4 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2001,6 +2001,9 @@ "Appearance Settings…": "Réglages d’apparence…", "Add to favorites": "Ajouter aux favoris", "Remove from favorites": "Retirer des favoris", + "Filter settings": "Filtrer les réglages", + "No setting matches what is typed.": "Aucun réglage ne correspond à la saisie.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Essayez un mot ou une partie de mot : la recherche porte sur les noms des onglets et des sections, les libellés et les explications.", "Appearance": "Apparence", "Appearance Mode": "Mode d’apparence", "Sync with System": "Synchroniser avec le système", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 3e02dfe169..681dfb5d39 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2446,6 +2446,9 @@ "Folder name": "Nama folder", "Its templates move to User Templates.": "Templatnya dipindahkan ke Templat pengguna.", "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", + "Filter settings": "Filter pengaturan", + "No setting matches what is typed.": "Tidak ada pengaturan yang cocok dengan yang diketik.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Coba satu kata atau sebagiannya: yang dicari adalah nama tab dan bagian, label, serta penjelasan.", "A smart album's rules choose its photos: change them with Edit Smart Album…": "Aturan album pintar menentukan fotonya: ubah dengan Edit album pintar…", "Add keywords in the Keyword List": "Tambahkan kata kunci di Daftar kata kunci", "Already on these photos": "Sudah ada pada foto ini", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index c6ed5474c2..0eef08de10 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -1836,12 +1836,14 @@ "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Modifica nell'altro editor (⌥⌘E) apre la copia in questa applicazione (il nome di un'app su macOS, il percorso di un programma altrove).", "Edit in PhotoCraft": "Modifica in PhotoCraft", "External Editing": "Modifica esterna", + "Filter settings": "Filtra impostazioni", "Found automatically": "Trovato automaticamente", "HDR": "HDR", "LUT-based": "Basato su LUT", "Left: the standard (SDR) range up to SDR white. Right: the HDR range, one band per stop above SDR white (the orange line: the HDR headroom). With Visualize HDR range on, the bands take its colours.": "A sinistra: la gamma standard (SDR) fino al bianco SDR. A destra: la gamma HDR, una fascia per ogni stop sopra il bianco SDR (la linea arancione: il margine HDR). Con Visualizza gamma HDR attivo, le fasce ne prendono i colori.", "Matrix/TRC": "Matrice/TRC", "Monitor profile": "Profilo monitor", + "No setting matches what is typed.": "Nessuna impostazione corrisponde al testo digitato.", "None (the display is treated as sRGB)": "Nessuno (lo schermo viene trattato come sRGB)", "Other editor": "Altro editor", "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Modifica in → Modifica in PhotoCraft (⇧⌘E, o clic destro su una foto) esegue il rendering di una copia con le tue modifiche, la impila con l'originale e la apre in PhotoCraft. Salva lì e la copia si aggiorna qui. Come PSD, PhotoCraft salva direttamente su di essa. Lascia vuota la posizione a meno che tu non usi una copia portatile.", @@ -1850,6 +1852,7 @@ "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Le foto restano in Tutte le foto. Eliminando una cartella si eliminano anche i suoi album. Puoi annullare l'operazione.", "Primaries (x, y)": "Primari (x, y)", "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "I profili assegnati nelle impostazioni colore del desktop di solito sono in ~/.local/share/icc.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Prova una parola, o parte di una: vengono cercati i nomi di schede e sezioni, le etichette e le spiegazioni.", "Progressive": "Progressivo", "SDR": "SDR", "Use Screen Profile": "Usa profilo dello schermo", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 29d789180c..2909f5b818 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1947,6 +1947,9 @@ "Not saved": "保存されていません", "A folder is being synchronized": "フォルダを同期中です", "Wait for the import to finish": "読み込みが終わるまでお待ちください", + "Filter settings": "設定を絞り込む", + "No setting matches what is typed.": "入力に一致する設定はありません。", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "単語またはその一部で試してください。タブとセクションの名前、ラベル、説明文が検索されます。", "Appearance": "外観", "Appearance Mode": "外観モード", "Sync with System": "システムと同期", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 9fb0442c00..f1e18bab0b 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3742,6 +3742,9 @@ "Folder name": "საქაღალდის სახელი", "Its templates move to User Templates.": "მისი შაბლონები გადავა „მომხმარებლის შაბლონებში“.", "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", + "Filter settings": "პარამეტრების გაფილტვრა", + "No setting matches what is typed.": "აკრეფილს არც ერთი პარამეტრი არ ემთხვევა.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "სცადეთ ერთი სიტყვა ან მისი ნაწილი: იძებნება ჩანართებისა და სექციების სახელებში, წარწერებსა და განმარტებებში.", "Can't add to an album folder": "ალბომების საქაღალდეში დამატება შეუძლებელია", "An album folder holds albums, not photos: drop on an album inside it": "ალბომების საქაღალდეში ალბომებია, არა ფოტოები: ჩააგდეთ მასში არსებულ ალბომზე", "Can't add to a smart album": "სმარტ-ალბომში დამატება შეუძლებელია", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 2dea7ddeb1..a3b846fa14 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2267,6 +2267,9 @@ "End Slideshow": "Zakończ pokaz slajdów", "Contact Sheet PDF…": "Arkusz stykowy PDF…", "Edit in PhotoCraft": "Edytuj w PhotoCraft", + "Filter settings": "Filtruj ustawienia", + "No setting matches what is typed.": "Żadne ustawienie nie pasuje do wpisanego tekstu.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Wpisz jedno słowo lub jego część: przeszukiwane są nazwy kart i sekcji, etykiety oraz objaśnienia.", "Edit in Other Editor": "Edytuj w innym edytorze", "Open Original in Other Editor (RAW, no copy)": "Otwórz oryginał w innym edytorze (RAW, bez kopii)", "Save Current Settings as New Effect Preset…": "Zapisz bieżące ustawienia jako nowe ustawienie wstępne efektu…", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index c38e5df6a0..7089cb4849 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1945,6 +1945,9 @@ "Not saved": "Não salvo", "A folder is being synchronized": "Uma pasta está sendo sincronizada", "Wait for the import to finish": "Aguarde a importação terminar", + "Filter settings": "Filtrar ajustes", + "No setting matches what is typed.": "Nenhum ajuste corresponde ao que foi digitado.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Tente uma palavra ou parte dela: a busca inclui os nomes das abas e seções, os rótulos e as explicações.", "Appearance": "Aparência", "Appearance Mode": "Modo de aparência", "Sync with System": "Sincronizar com o sistema", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index e07eeea3ef..03a570f4bd 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1874,6 +1874,9 @@ "Not saved": "Не сохранено", "A folder is being synchronized": "Папка синхронизируется", "Wait for the import to finish": "Дождитесь завершения импорта", + "Filter settings": "Фильтр настроек", + "No setting matches what is typed.": "Нет настроек, соответствующих введённому.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Попробуйте одно слово или его часть: поиск ведётся по названиям вкладок и разделов, подписям и пояснениям.", "Appearance": "Оформление", "Appearance Mode": "Режим оформления", "Sync with System": "Как в системе", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 5188fb6020..8cfe3a1a1e 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -3859,6 +3859,9 @@ "Folder name": "Mappnamn", "Its templates move to User Templates.": "Dess mallar flyttas till Användarmallar.", "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", + "Filter settings": "Filtrera inställningar", + "No setting matches what is typed.": "Ingen inställning matchar det som skrivits.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Prova ett ord eller en del av ett: namnen på flikar och avsnitt, etiketter och förklaringar genomsöks.", "name for a saved preset": "namn på en sparad förinställning", "Saved as a preset": "Sparat som förinställning", "Set on every photo this import adds, after its XMP sidecar and the preset above; photos the library already has are left alone. A slider left at its default changes nothing. Nothing is saved unless you save it as a preset.": "Anges på varje foto som den här importen lägger till, efter dess XMP-sidofil och förinställningen ovanför; foton som redan finns i biblioteket lämnas orörda. Ett reglage som står kvar på standardvärdet ändrar ingenting. Ingenting sparas om du inte sparar det som en förinställning.", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index c6da5e4347..40cf6d0593 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2195,6 +2195,9 @@ "Appearance Settings…": "Налаштування вигляду…", "Add to favorites": "Додати до вибраного", "Remove from favorites": "Видалити з вибраного", + "Filter settings": "Фільтр налаштувань", + "No setting matches what is typed.": "Немає налаштувань, що відповідають введеному.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Спробуйте одне слово або його частину: пошук ведеться за назвами вкладок і розділів, підписами та поясненнями.", "Appearance": "Вигляд", "Appearance Mode": "Режим вигляду", "Sync with System": "Як у системі", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 534c5ffd23..2d7db0ddff 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2758,6 +2758,9 @@ "Folder name": "Tên thư mục", "Its templates move to User Templates.": "Các mẫu trong đó sẽ được chuyển vào Mẫu người dùng.", "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác", + "Filter settings": "Lọc cài đặt", + "No setting matches what is typed.": "Không có cài đặt nào khớp với nội dung đã nhập.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Hãy thử một từ hoặc một phần của từ: tên các tab và mục, nhãn và phần giải thích đều được tìm.", "A smart album's rules choose its photos: change them with Edit Smart Album…": "Quy tắc của album thông minh chọn ảnh của nó: thay đổi bằng Chỉnh sửa album thông minh…", "Add keywords in the Keyword List": "Thêm từ khóa trong Danh sách từ khóa", "Already on these photos": "Đã có trên các ảnh này", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 587b59091e..2b07ca89e4 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1939,6 +1939,9 @@ "Not saved": "未保存", "A folder is being synchronized": "正在同步文件夹", "Wait for the import to finish": "请等待导入完成", + "Filter settings": "筛选设置", + "No setting matches what is typed.": "没有与输入内容匹配的设置。", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "请尝试一个词或词的一部分:会搜索标签页和分区的名称、标签和说明。", "Appearance": "外观", "Appearance Mode": "外观模式", "Sync with System": "与系统同步", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 912bca0452..27566a5296 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1945,6 +1945,9 @@ "Not saved": "未儲存", "A folder is being synchronized": "正在同步資料夾", "Wait for the import to finish": "請等待匯入完成", + "Filter settings": "篩選設定", + "No setting matches what is typed.": "沒有符合輸入內容的設定。", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "請嘗試一個詞或詞的一部分:會搜尋分頁和區段的名稱、標籤和說明。", "Appearance": "外觀", "Appearance Mode": "外觀模式", "Sync with System": "與系統同步", diff --git a/crates/ui-egui/src/dialogs/settings.rs b/crates/ui-egui/src/dialogs/settings.rs index 9e90dabf6d..f64b41cdf5 100644 --- a/crates/ui-egui/src/dialogs/settings.rs +++ b/crates/ui-egui/src/dialogs/settings.rs @@ -86,13 +86,23 @@ const PAGE_SIZE: egui::Vec2 = egui::vec2(560.0, 640.0); const PAGE_MIN_HEIGHT: f32 = 120.0; /// The share of the page's room the pinned slide preview of the Slideshow tab takes, when the page -/// has more room than it needs to keep [`PAGE_MIN_HEIGHT`] for itself. +/// has more room than it needs to keep [`PINNED_PAGE_MIN_HEIGHT`] for itself. const PINNED_PREVIEW_SHARE: f32 = 0.4; /// What the preview's heading, the one-line hint under the slide, its Photo / Intro / Ending /// choice and the rule under it take around the slide (at the default spacing, about 82 pt). const PREVIEW_CHROME: f32 = 82.0; +/// What the same takes once the page has been drawn a second time (measured, at the default +/// spacing: 104 pt). The room a pinned preview leaves for the page is checked against this, not +/// against [`PREVIEW_CHROME`], so a window just tall enough never ends up with a page below +/// its least and a dialog that grows a point on this tab. +const PREVIEW_CHROME_DRAWN: f32 = 104.0; + +/// The least room the page keeps under the pinned preview: a few rows, with the filter row above +/// them in the smallest window (900 x 560) that the preview is still pinned in. +const PINNED_PAGE_MIN_HEIGHT: f32 = 100.0; + /// The Settings window's content: the tab bar, which stays put, above the page of `tab` /// ([`body`]), which scrolls when it is taller than the room for it, with a scroll handle that /// shows without the pointer on it. `max_height` is the room the app window leaves for both: the @@ -110,51 +120,90 @@ pub fn window(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String, max_ // the next frame, so a text box on the page being left is drawn once more and saves what was // typed in it (the click took the focus from it). let shown = tab.clone(); + // The filter, above the tabs it looks through. What is typed is kept from one frame of the + // window to the next only: Settings opened again starts with it empty. + let filter_id = egui::Id::unique("settings-filter"); + let pass = ui.ctx().cumulative_pass_nr(); + let kept: Option = ui.data(|d| d.get_temp(filter_id)); + let mut filter = kept.filter(|k| k.pass.checked_add(1) == Some(pass)).unwrap_or_default(); + filter.pass = pass; + let had_text = !filter.text.is_empty(); + let typed = crate::text_field::TextField::singleline("field:settingsFilter", &mut filter.text) + .hint(crate::i18n::tr("Filter settings")) + .width(ui.available_width()) + .show(ui); + let filter_row = ui.cursor().top() - top; + // Esc with something typed empties the filter and is used up by that, wherever the focus is + // (in the box, or on a section that was found); the focus goes back to the box. Not while the + // dialog is disabled behind a prompt or the library window: that owns the keys (`dialogs::show`). + let owns_keys = ui.is_enabled(); + let escape = owns_keys && had_text && !crate::widgets::escape_taken(ui.ctx()) && ui.input(|i| i.key_pressed(egui::Key::Escape)); + if owns_keys && (typed.cancelled() || escape) { + filter.text.clear(); + if had_text { + crate::widgets::take_escape(ui.ctx()); + typed.response.request_focus(); + } + } + // (an emptied filter forgets what it read: the pages are read afresh the next time it is + // used, so what is found is what they show then) + if filter.text.trim().is_empty() { + filter.sections = None; + } + // ↓ in the box goes to the first section found + let to_first = typed.response.has_focus() && ui.input(|i| i.key_pressed(egui::Key::ArrowDown)); + let open_first = typed.ending == Some(crate::text_field::Ending::Return); + // (with something typed the page is what was found, of any tab: no tab is the open one) + let filtering = !filter.text.trim().is_empty(); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = egui::vec2(4.0, 4.0); for (id, label) in TABS { - if crate::widgets::text_button(ui, &format!("settingsTab-{id}"), label, shown == *id).clicked() { + if crate::widgets::text_button(ui, &format!("settingsTab-{id}"), label, shown == *id && !filtering).clicked() { *tab = id.to_string(); ui.ctx().request_repaint(); + // (a tab opened is its page asked for: the filter gives way) + filter.text.clear(); } } }); ui.separator(); + // With something typed, the page gives way to the sections found, of whatever tab. + let words = filter.text.trim().to_lowercase(); + let now = ui.input(|i| i.time); + let found = (!words.is_empty()).then(|| filter.found(app, &words, now)); + let mut goto = None; // (a point less than the room left, so rounding never makes the dialog's own scroll area scroll) let room = max_height - (ui.cursor().top() - top) - 1.0; - if room < PAGE_MIN_HEIGHT { - body(app, ui, shown.as_str()); - register(ui, "settings:page", ui.min_rect()); - return; - } let mut height = room.min(PAGE_SIZE.y); // The slide preview stays above the page on Slideshow: hovering a template in the Template // Browser previews it there, so it has to stay in view however far down the templates are // scrolled to. With its heading and choice it takes [`PINNED_PREVIEW_SHARE`] of the room - // (at least the least tall slide); where that leaves less than [`PAGE_MIN_HEIGHT`] for the - // page, it scrolls with the page instead (as in the short window above). + // (at least the least tall slide); where that leaves less than [`PINNED_PAGE_MIN_HEIGHT`] for the + // page, it scrolls with the page instead (as in the short window above). What was found + // is drawn in its place while the filter has something typed. let mut pinned = false; - if shown == "slideshow" { - let slide_h = (height * PINNED_PREVIEW_SHARE - PREVIEW_CHROME).max(crate::panels::slide_layout::PREVIEW_MIN_H); - if height - (slide_h + PREVIEW_CHROME) >= PAGE_MIN_HEIGHT { + if shown == "slideshow" && found.is_none() && room >= PAGE_MIN_HEIGHT { + // (the filter row is taken off the page, not off the preview: the slide is as large as it was) + let slide_h = ((room + filter_row).min(PAGE_SIZE.y) * PINNED_PREVIEW_SHARE - PREVIEW_CHROME).max(crate::panels::slide_layout::PREVIEW_MIN_H); + if height - (slide_h + PREVIEW_CHROME_DRAWN) >= PINNED_PAGE_MIN_HEIGHT { let before = ui.cursor().top(); crate::panels::slide_layout::preview(app, ui, &Tokens::get(ui.ctx()), slide_h); ui.add_space(2.0); ui.separator(); - height = (height - (ui.cursor().top() - before)).max(PAGE_MIN_HEIGHT); + height = (height - (ui.cursor().top() - before)).max(PINNED_PAGE_MIN_HEIGHT); pinned = true; } } - // A page that goes on below shows its scroll handle all the time: without it, a page a line - // or two too long looks cut off, not scrollable. - ui.spacing_mut().scroll.dormant_handle_opacity = 0.6; - let page = egui::ScrollArea::vertical() - .id_salt(("settings-page", shown.as_str())) - .max_height(height) - .min_scrolled_height(height) - .auto_shrink([false, false]) - .show(ui, |ui| { - ui.add_space(2.0); + let mut page = |ui: &mut egui::Ui| match &found { + Some(found) => goto = results(ui, found, &words, open_first, to_first), + None => { + // (a section chosen that starts its tab, with no heading of its own: the page goes to its top) + if ui + .data(|d| d.get_temp::<(&'static str, String)>(egui::Id::unique(GOTO))) + .is_some_and(|(to, section)| to == tab.as_str() && section.is_empty()) + { + ui.scroll_to_cursor(Some(egui::Align::TOP)); + } if pinned { slideshow_tab(app, ui, &Tokens::get(ui.ctx()), false); } else { @@ -162,6 +211,276 @@ pub fn window(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String, max_ } // (what the page took: wider than the room for it would mean a control is cut off) register(ui, "settings:page", ui.min_rect()); + } + }; + if room < PAGE_MIN_HEIGHT { + page(ui); + } else { + // A page that goes on below shows its scroll handle all the time: without it, a page a + // line or two too long looks cut off, not scrollable. + ui.spacing_mut().scroll.dormant_handle_opacity = 0.6; + let salt = if found.is_some() { "found" } else { shown.as_str() }; + let area = egui::ScrollArea::vertical() + .id_salt(("settings-page", salt)) + .max_height(height) + .min_scrolled_height(height) + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.add_space(2.0); + page(ui); + }); + register(ui, "settings:pageRoom", area.inner_rect); + } + // A section chosen from what was found: its tab opens (on the next frame, as a clicked tab + // does), the filter is emptied, and the section's heading is scrolled to when it is drawn. + let goto_id = egui::Id::unique(GOTO); + if let Some((to, section)) = goto { + *tab = to.to_string(); + filter.text.clear(); + ui.data_mut(|d| d.insert_temp(goto_id, (to, section))); + ui.ctx().request_repaint(); + } else if ui.data(|d| d.get_temp::<(&'static str, String)>(goto_id)).is_some_and(|(to, _)| to == tab.as_str()) { + // (the page it was for has been drawn: its heading has had its chance) + ui.data_mut(|d| d.remove::<(&'static str, String)>(goto_id)); + } + ui.data_mut(|d| d.insert_temp(filter_id, filter)); +} + +/// Where the section to scroll to is kept between the click on a result and its page being drawn. +const GOTO: &str = "settings-goto"; + +/// A section of Settings as the filter knows it: the tab it is on, its heading's English name +/// (empty for what a tab draws above its first heading) and every piece of text it draws. +#[derive(Clone)] +struct Section { + tab: &'static str, + name: String, + texts: Vec, +} + +/// The filter's state between frames: what is typed, and the sections of every tab with their +/// text, read once for the language, library and display profile they were read in. (What is +/// typed is kept only from one pass to the next: a pass in which Settings is not drawn loses it.) +#[derive(Clone, Default)] +struct Filter { + pass: u64, + text: String, + sections: Option<(String, std::sync::Arc>)>, +} + +impl Filter { + /// The sections that have every word of `words` (lower case), in the order of the tabs. + fn found(&mut self, app: &mut LightcraftApp, words: &str, now: f64) -> Vec
{ + let of = format!( + "{}|{}|{:?}", + app.ui.language.code(), + app.session.library.as_ref().map(|l| l.dir.display().to_string()).unwrap_or_default(), + // (the Display page says which profile is in use) + app.renderer.display_id() + ); + let sections = match &self.sections { + Some((read_for, sections)) if *read_for == of => sections.clone(), + _ => { + let sections = std::sync::Arc::new(sections(app, now)); + self.sections = Some((of, sections.clone())); + sections + } + }; + sections.iter().filter(|section| section.has(words)).cloned().collect() + } +} + +impl Section { + /// The name of the section's tab, in the language shown. + fn tab_name(&self) -> &'static str { + TABS.iter().find(|(id, _)| *id == self.tab).map_or("", |(_, label)| crate::i18n::tr(label)) + } + + /// Whether the section, with the name of its tab, has every word of `words` (lower case). + fn has(&self, words: &str) -> bool { + let all = format!("{} {}", self.tab_name(), self.texts.join(" ")).to_lowercase(); + words.split_whitespace().all(|word| all.contains(word)) + } + + /// What the section is called in the list of what was found: its tab, then its heading. + fn title(&self) -> String { + let tab = self.tab_name(); + if self.name.is_empty() { tab.to_string() } else { format!("{tab} › {}", crate::i18n::tr(&self.name)) } + } +} + +/// The key [`sections`] sets in the context it reads the pages in. +const READING_FOR_FILTER: &str = "settingsReadingForFilter"; + +/// Whether `ctx` is the context the filter reads the pages in ([`sections`]): a page draws as usual but starts no work +/// (a render, say) for text nobody sees. +pub(crate) fn reading_for_filter(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(egui::Id::unique(READING_FOR_FILTER))).unwrap_or(false) +} + +/// Every section of every tab with the text it draws, read by drawing each tab's page once in a +/// context of its own: nothing of it reaches the screen, the list of widgets or the window's own +/// memory, and whatever a tab draws is found without a list kept by hand. Drawing a page asks +/// what opening its tab asks (the smart previews folder, the installed models): the answers the +/// app keeps (the installed denoise models) are filled as opening the tab fills them, and those a +/// page keeps in its own context (the smart previews folder, the face models) are asked again. +/// The pages know they are only being read ([`reading_for_filter`]): the slide preview of +/// Slideshow is not asked to render, as nothing of it is shown. No setting is +/// changed by it, as nothing is clicked. What a page does not draw is not found: the choices of +/// a closed list, tooltips, and rows scrolled out of a list inside a page. +fn sections(app: &mut LightcraftApp, now: f64) -> Vec
{ + fn texts(shape: &egui::Shape, out: &mut Vec<(f32, String)>) { + match shape { + egui::Shape::Text(text) => out.push((text.pos.y, text.galley.job.text.clone())), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), + _ => {} + } + } + let scratch = egui::Context::default(); + scratch.data_mut(|d| d.insert_temp(egui::Id::unique(READING_FOR_FILTER), true)); + crate::theme::install_fonts(&scratch); + // (tall enough that no page is cut off: what is outside the screen is not drawn) + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(PAGE_SIZE.x + 32.0, 20_000.0)); + let mut all = Vec::new(); + for (tab, _) in TABS { + // (on the window's clock: what a page remembers with the time it asked is not left stamped + // with another) + let input = egui::RawInput { screen_rect: Some(screen), time: Some(now), ..Default::default() }; + let mut output = scratch.run_ui(input, |ui| { + ui.set_width(PAGE_SIZE.x); + body(app, ui, tab); }); - register(ui, "settings:pageRoom", page.inner_rect); + // (the font atlas this context made is for no screen: said so, or dropping it is an error) + output.textures_delta.clear(); + // the page's headings, top to bottom, and each text under the last heading above it + let mut headings: Vec<(f32, String)> = crate::widgets::take_registry(&scratch) + .into_iter() + .filter_map(|(id, r)| Some((r.top(), id.strip_prefix("heading:")?.to_string()))) + .collect(); + headings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut drawn = Vec::new(); + output.shapes.iter().for_each(|clipped| texts(&clipped.shape, &mut drawn)); + drawn.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut of_tab: Vec
= std::iter::once(String::new()) + .chain(headings.iter().map(|(_, name)| name.clone())) + .map(|name| Section { tab, name, texts: Vec::new() }) + .collect(); + for (y, text) in drawn { + // (a text counts as under a heading from a little above the heading's own top) + let under = headings.iter().take_while(|(top, _)| *top <= y + 1.0).count(); + if let Some(section) = of_tab.get_mut(under) + && !text.trim().is_empty() + { + section.texts.push(text); + } + } + all.extend(of_tab.into_iter().filter(|section| !section.texts.is_empty())); + } + all +} + +/// The sections found, each a row to choose (`settingsFound:{tab}:{section}`): its tab and +/// heading, and under them the first texts of it that have a word of `words`. Gives the section +/// chosen, by a click, by Return or Space with the focus on it, or (`open_first`) by Return in +/// the filter, which chooses the first. `focus_first` gives the first row the keyboard focus. +fn results(ui: &mut egui::Ui, found: &[Section], words: &str, open_first: bool, focus_first: bool) -> Option<(&'static str, String)> { + let t = Tokens::get(ui.ctx()); + if found.is_empty() { + ui.add_space(8.0); + ui.label(RichText::new(crate::i18n::tr("No setting matches what is typed.")).color(t.text_label)); + hint(ui, &t, "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through."); + return None; + } + let mut chosen = open_first.then(|| found.first().map(|first| (first.tab, first.name.clone()))).flatten(); + for (place, section) in found.iter().enumerate() { + let fill = ui.painter().add(egui::Shape::Noop); + let row = ui + .scope_builder(egui::UiBuilder::new().sense(egui::Sense::click()), |ui| { + ui.set_width(ui.available_width()); + ui.spacing_mut().item_spacing.y = 2.0; + ui.add_space(3.0); + ui.add(egui::Label::new(RichText::new(section.title()).font(t.semibold(13.0)).color(t.text)).selectable(false)); + // (what of it has a word that was typed; its heading is in the line above already) + let heading = crate::i18n::tr(§ion.name); + let with: Vec<&str> = section + .texts + .iter() + .map(String::as_str) + .filter(|text| *text != heading && words.split_whitespace().any(|word| text.to_lowercase().contains(word))) + .take(2) + .collect(); + for text in with { + ui.add(egui::Label::new(RichText::new(text).size(11.0).color(t.text_dim)).selectable(false).truncate()); + } + ui.add_space(3.0); + }) + .response; + if focus_first && place == 0 { + row.request_focus(); + } + let around = row.rect.expand2(egui::vec2(6.0, 0.0)); + if row.hovered() || row.has_focus() { + ui.painter().set(fill, egui::Shape::rect_filled(around, egui::CornerRadius::same(4), t.hover)); + } + if row.has_focus() { + ui.painter().rect_stroke(around, egui::CornerRadius::same(4), egui::Stroke::new(2.0, t.text), egui::StrokeKind::Inside); + } + row.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, section.title())); + register(ui, format!("settingsFound:{}:{}", section.tab, section.name), row.rect); + if row.clicked() { + chosen = Some((section.tab, section.name.clone())); + } + } + chosen +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Services; + + /// One pass of the Settings window with the filter holding `text` and Escape pressed, in a ui + /// that is disabled (`dialogs::show` does that while a prompt or the library window owns input) + /// or not; what the filter holds afterwards. + fn text_after_escape(enabled: bool) -> String { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut tab = "general".to_string(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0)); + let mut pass = |app: &mut LightcraftApp, events: Vec, enabled: bool| { + let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + if !enabled { + ui.disable(); + } + window(app, ui, &mut tab, 800.0); + }); + output.textures_delta.clear(); + }; + let filter_id = egui::Id::unique("settings-filter"); + // (a pass draws the window, which keeps its filter for the pass after it) + pass(&mut app, Vec::new(), true); + ctx.data_mut(|d| { + let mut kept: Filter = d.get_temp(filter_id).expect("the window keeps its filter"); + kept.text = "sidecar".into(); + d.insert_temp(filter_id, kept); + }); + let escape = egui::Event::Key { + key: egui::Key::Escape, + physical_key: Some(egui::Key::Escape), + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + pass(&mut app, vec![escape], enabled); + let kept: Filter = ctx.data(|d| d.get_temp(filter_id)).expect("the filter is kept"); + kept.text + } + + #[test] + fn escape_empties_the_filter_only_while_the_dialog_owns_the_keys() { + assert_eq!(text_after_escape(true), "", "Escape empties what was typed"); + assert_eq!(text_after_escape(false), "sidecar", "behind a prompt or the library window it is not the dialog's"); + } } diff --git a/crates/ui-egui/src/dialogs/settings/appearance.rs b/crates/ui-egui/src/dialogs/settings/appearance.rs index 5f8f428d45..d92f625ba6 100644 --- a/crates/ui-egui/src/dialogs/settings/appearance.rs +++ b/crates/ui-egui/src/dialogs/settings/appearance.rs @@ -6,7 +6,7 @@ use super::{RichText, Tokens, register}; /// use is outlined. Applied on the next frame ([`LightcraftApp::sync_theme`]). pub(super) fn appearance(ui: &mut egui::Ui, t: &Tokens, s: &mut crate::state::AppSettings, system: Option) { use crate::state::{AppearanceMode as M, DarkTheme, LightTheme}; - heading(ui, t, crate::i18n::tr("Appearance")); + heading(ui, t, "Appearance"); ui.label(RichText::new(crate::i18n::tr("Appearance Mode")).color(t.text_label)); ui.horizontal_wrapped(|ui| { choices(ui, "settingsAppearance", &[(M::Auto, "Sync with System"), (M::Dark, "Dark Mode"), (M::Light, "Light Mode")], &mut s.appearance_mode); diff --git a/crates/ui-egui/src/dialogs/settings/display.rs b/crates/ui-egui/src/dialogs/settings/display.rs index c8782d281c..2ed4330bd9 100644 --- a/crates/ui-egui/src/dialogs/settings/display.rs +++ b/crates/ui-egui/src/dialogs/settings/display.rs @@ -7,7 +7,7 @@ use super::{GridBadges, LightcraftApp, RichText, Tokens, Value, json, register}; /// The monitor profile (`app.displayProfile`): previews are shown through the display's ICC /// profile, so wide-gamut and calibrated displays show colours as they are. pub(super) fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { - heading(ui, t, crate::i18n::tr("Monitor profile")); + heading(ui, t, "Monitor profile"); let current = app.renderer.display().cloned(); let screen = current.as_ref().is_some_and(|d| d.path == crate::SCREEN_PROFILE); row(ui, t, crate::i18n::tr("Profile"), |ui| { @@ -98,10 +98,10 @@ pub(super) fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke app.ui.settings.reduce_motion = None; } }); - heading(ui, t, crate::i18n::tr("Filmstrip")); + heading(ui, t, "Filmstrip"); check(ui, "settings.filmNames", &mut app.ui.settings.film_names, "Show file names"); check(ui, "settings.filmBadges", &mut app.ui.settings.film_badges, "Show ratings, flags and edit badges"); - heading(ui, t, crate::i18n::tr("Grid")); + heading(ui, t, "Grid"); row(ui, t, crate::i18n::tr("Ratings & flags"), |ui| { choices( ui, @@ -112,7 +112,7 @@ pub(super) fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke }); hint(ui, t, "Stars on hover: flags and colour labels always show; the stars and the edited mark appear while a photo is hovered or selected."); check(ui, "settings.showFilenames", &mut app.ui.show_filenames, "Square Grid: show file names and formats"); - heading(ui, t, crate::i18n::tr("Keywords")); + heading(ui, t, "Keywords"); row(ui, t, crate::i18n::tr("Keywords of the selection"), |ui| { use crate::state::KeywordChips as K; choices(ui, "settingsKeywordChips", &[(K::Paths, "Whole names"), (K::Grouped, "Grouped by parent")], &mut app.ui.settings.keyword_chips); @@ -122,7 +122,7 @@ pub(super) fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke t, crate::i18n::tr("Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened."), ); - heading(ui, t, crate::i18n::tr("Detail View")); + heading(ui, t, "Detail View"); check(ui, "settings.navigator", &mut app.ui.navigator, "Show the Navigator while zoomed in"); row(ui, t, crate::i18n::tr("Info overlay"), |ui| { use crate::state::InfoOverlay as I; @@ -137,7 +137,7 @@ pub(super) fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke /// (`view.viewOptions`). Changes apply as they are made. pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use crate::state::{InfoOverlay as I, LoupeInfo, LoupeInfoField as F}; - heading(ui, t, crate::i18n::tr("Loupe View")); + heading(ui, t, "Loupe View"); let mut show = app.ui.info_overlay != I::Off; if check(ui, "viewOptions.showInfo", &mut show, "Show Info Overlay") { app.ui.info_overlay = if show { I::Basic } else { I::Off }; @@ -148,7 +148,7 @@ pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, }); }); for (n, title, defaults) in [(1, "Loupe Info 1", LoupeInfo::INFO1), (2, "Loupe Info 2", LoupeInfo::INFO2)] { - heading(ui, t, crate::i18n::tr(title)); + heading(ui, t, title); let lines = if n == 1 { &mut app.ui.settings.loupe_info.info1 } else { &mut app.ui.settings.loupe_info.info2 }; for (i, line) in lines.iter_mut().enumerate() { let id = format!("viewOptionsInfo{n}Line{}", i + 1); @@ -180,7 +180,7 @@ pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, app.ui.settings.loupe_info.briefly = if briefly { info } else { I::Off }; } } - heading(ui, t, crate::i18n::tr("General")); + heading(ui, t, "General"); check(ui, "viewOptions.loupeMessages", &mut app.ui.settings.loupe_messages, "Show message when loading or rendering photos"); } diff --git a/crates/ui-egui/src/dialogs/settings/general.rs b/crates/ui-egui/src/dialogs/settings/general.rs index 5495ac56e7..5bb7c57059 100644 --- a/crates/ui-egui/src/dialogs/settings/general.rs +++ b/crates/ui-egui/src/dialogs/settings/general.rs @@ -12,7 +12,7 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens }); crate::i18n::set_language(app.ui.language); }); - heading(ui, t, crate::i18n::tr("Library")); + heading(ui, t, "Library"); let location = match &app.session.library { Some(l) => l.dir.display().to_string(), None => crate::i18n::tr("In memory — nothing is saved").to_string(), @@ -60,7 +60,7 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens &mut app.ui.settings.lightroom_import, ); }); - heading(ui, t, crate::i18n::tr("Startup")); + heading(ui, t, "Startup"); row(ui, t, crate::i18n::tr("Open in"), |ui| { choices( ui, @@ -69,13 +69,13 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens &mut app.ui.settings.startup_view, ); }); - heading(ui, t, crate::i18n::tr("Culling")); + heading(ui, t, "Culling"); check(ui, "settings.autoAdvance", &mut app.ui.auto_advance, "Auto Advance: move to the next photo after rating or flagging"); check(ui, "settings.confirmDelete", &mut app.ui.settings.confirm_delete, "Confirm before moving photos to Recently Deleted"); check(ui, "settings.askBeforeMove", &mut app.ui.settings.ask_before_move, "Confirm before moving photos to another folder on disk"); - heading(ui, t, crate::i18n::tr("Dialogs")); + heading(ui, t, "Dialogs"); check(ui, "settings.closeDialogsOutside", &mut app.ui.settings.close_dialogs_outside, "Close a dialog by clicking outside it"); - heading(ui, t, crate::i18n::tr("External Editing")); + heading(ui, t, "External Editing"); row(ui, t, crate::i18n::tr("PhotoCraft"), |ui| { field( ui, @@ -118,7 +118,7 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens #[cfg(not(target_arch = "wasm32"))] fn lens_profiles(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use lightcraft_engine::lensfun_download::{self, Offer}; - heading(ui, t, crate::i18n::tr("Lens profiles")); + heading(ui, t, "Lens profiles"); let running = app.session.lensfun.running(); // (the user's own folder, LIGHTCRAFT_LENSFUN_DIR, is read instead and never replaced) let own = std::env::var_os(lightcraft_engine::lens_profiles::ENV).is_some_and(|v| !v.is_empty()); diff --git a/crates/ui-egui/src/dialogs/settings/import.rs b/crates/ui-egui/src/dialogs/settings/import.rs index 9e362dbef7..f713c8033c 100644 --- a/crates/ui-egui/src/dialogs/settings/import.rs +++ b/crates/ui-egui/src/dialogs/settings/import.rs @@ -4,7 +4,7 @@ use super::{LightcraftApp, RichText, Tokens, json, register}; pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let d = app.session.import_defaults.clone(); - heading(ui, t, crate::i18n::tr("Raw defaults")); + heading(ui, t, "Raw defaults"); hint(ui, t, crate::i18n::tr("Settings new raw photos start from. Changing them doesn't touch photos already in the library.")); row(ui, t, crate::i18n::tr("Raw photos"), |ui| { if let Some(v) = preset_combo(app, ui, "settingsRawPreset", crate::i18n::tr("Raw default"), d.raw_preset.as_deref(), "LightCraft Default") { @@ -65,13 +65,13 @@ pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) } }); } - heading(ui, t, crate::i18n::tr("Other images (JPEG, PNG, TIFF, HEIC…)")); + heading(ui, t, "Other images (JPEG, PNG, TIFF, HEIC…)"); row(ui, t, crate::i18n::tr("Non-raw photos"), |ui| { if let Some(v) = preset_combo(app, ui, "settingsOtherPreset", crate::i18n::tr("Other preset"), d.other_preset.as_deref(), "None") { let _ = app.run("library.preferences", json!({"import": {"otherPreset": v}})); } }); - heading(ui, t, crate::i18n::tr("Metadata")); + heading(ui, t, "Metadata"); hint(ui, t, crate::i18n::tr("Added to photos you import that don't already have it.")); for (key, label, hint_text, value) in [("copyright", "Copyright", "© 2026 Your Name", d.copyright.clone()), ("creator", "Creator", "Your Name", d.creator.clone())] @@ -117,7 +117,7 @@ pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) } }); } - heading(ui, t, crate::i18n::tr("XMP sidecars")); + heading(ui, t, "XMP sidecars"); let mut xmp = app.session.xmp; if check(ui, "settings.autoWriteXmp", &mut xmp.auto_write, "Automatically write changes into XMP sidecars") { let _ = app.run("library.xmpPreferences", json!({"autoWrite": xmp.auto_write})); @@ -131,14 +131,14 @@ pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) } }); if !cfg!(target_arch = "wasm32") { - heading(ui, t, crate::i18n::tr("Dropped Files")); + heading(ui, t, "Dropped Files"); check(ui, "settings.importDropped", &mut app.ui.settings.import_dropped_directly, "Import dropped files without review"); - heading(ui, t, crate::i18n::tr("Cameras and Cards")); + heading(ui, t, "Cameras and Cards"); let mut on_card = d.show_on_card; if check(ui, "settings.importOnCard", &mut on_card, "Show the import review when a camera or card is connected") { let _ = app.run("library.preferences", json!({"import": {"showOnCard": on_card}})); } - heading(ui, t, crate::i18n::tr("Auto Import")); + heading(ui, t, "Auto Import"); hint(ui, t, crate::i18n::tr("Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.")); row(ui, t, crate::i18n::tr("Watched folder"), |ui| { match &d.auto_folder { diff --git a/crates/ui-egui/src/dialogs/settings/performance.rs b/crates/ui-egui/src/dialogs/settings/performance.rs index ed5eb5d1cb..74e7883e6f 100644 --- a/crates/ui-egui/src/dialogs/settings/performance.rs +++ b/crates/ui-egui/src/dialogs/settings/performance.rs @@ -9,7 +9,7 @@ use super::{ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use lightcraft_engine::gpu; - heading(ui, t, crate::i18n::tr("Rendering")); + heading(ui, t, "Rendering"); #[cfg(target_os = "windows")] check(ui, "settings.composeWindow", &mut app.ui.settings.compose_window, "Prevent G-SYNC/FreeSync flicker (applies at next launch)"); check(ui, "settings.gpu", &mut app.ui.settings.gpu, "Use the GPU for rendering"); @@ -66,7 +66,7 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To "Remove Hot Pixels (Detail) leaves a raw unchanged when more than this share of its photosites would be replaced: such a photo doesn't look like hot pixels on a sensor.", ), ); - heading(ui, t, crate::i18n::tr("Preview cache")); + heading(ui, t, "Preview cache"); let cur = app.session.cache_mb; row(ui, t, crate::i18n::tr("Size limit"), |ui| { let gb = lightcraft_engine::media::default_disk_cache_bytes(app.session.catalog.len()).div_ceil(1 << 30); @@ -103,7 +103,7 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To } }); background_prep(app, ui, t); - heading(ui, t, crate::i18n::tr("Local folders")); + heading(ui, t, "Local folders"); row(ui, t, crate::i18n::tr("Forget unchanged photos"), |ui| { let opts = [(0u32, "Never"), (7, "After 7 days"), (30, "After 30 days"), (90, "After 90 days"), (365, "After a year")]; let mut v = app.session.forget_local_days; @@ -131,7 +131,7 @@ fn ai_masks(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { if !lightcraft_engine::segment::Segmenter::AVAILABLE { return; } - heading(ui, t, crate::i18n::tr("AI masks")); + heading(ui, t, "AI masks"); let current = app.session.segmenter.run_on().name(); let mut run_on = current; if row(ui, t, "Run on", |ui| choices(ui, "settingsAiMasksRunOn", &[("auto", "Automatic (GPU when available)"), ("cpu", "CPU")], &mut run_on)) @@ -179,7 +179,7 @@ fn ai_masks(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { /// is made ready before the user gets to it (`prefs.backgroundPrep`), app-wide or for this library. fn background_prep(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use lightcraft_engine::prep::{Mode, Scope}; - heading(ui, t, crate::i18n::tr("Prepare photos in the background")); + heading(ui, t, "Prepare photos in the background"); hint( ui, t, @@ -279,7 +279,7 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { if loc.is_null() { return; } - heading(ui, t, crate::i18n::tr("Smart previews")); + heading(ui, t, "Smart previews"); let path = loc["path"].as_str().unwrap_or_default().to_string(); let available = loc["available"].as_bool().unwrap_or(true); let custom = loc["custom"].as_bool().unwrap_or(false); diff --git a/crates/ui-egui/src/dialogs/settings/slide_layout.rs b/crates/ui-egui/src/dialogs/settings/slide_layout.rs index d9595d2de9..5bd80427cb 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_layout.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_layout.rs @@ -237,14 +237,16 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: f3 ui.ctx().data_mut(|d| d.insert_temp(mem, (key, now))); } let still = if last == key { now - since } else { 0.0 }; - // the first preview (or another photo's) at once, a changing layout once it has settled - if current.is_none() || still >= DEBOUNCE { + // the first preview (or another photo's) at once, a changing layout once it has settled (none while the + // Settings filter only reads the page for its text: nothing of it is shown) + let reading = super::reading_for_filter(ui.ctx()); + if !reading && (current.is_none() || still >= DEBOUNCE) { let side = crate::panels::detail::texture_side(ui.ctx()); let edge = app.ui.settings.loupe_edge(pw.max(ph) as f32, usize::MAX, side); if let Some(job) = app.session.slide_job_look(&s, &overlays, id, pw, ph, Some(edge), false) { app.renderer.request(Slot::SlidePreview, job, 90); } - } else { + } else if !reading { ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((DEBOUNCE - still).clamp(0.01, DEBOUNCE))); } let say = diff --git a/crates/ui-egui/src/dialogs/settings/slideshow.rs b/crates/ui-egui/src/dialogs/settings/slideshow.rs index 8246858aad..049fe89010 100644 --- a/crates/ui-egui/src/dialogs/settings/slideshow.rs +++ b/crates/ui-egui/src/dialogs/settings/slideshow.rs @@ -25,7 +25,7 @@ pub(super) fn slideshow_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke /// Export: PDF, JPEG sequence or video of the slideshow (View ▸ Slideshow ▸ Export Slideshow…). fn export_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { - heading(ui, t, crate::i18n::tr("Export")); + heading(ui, t, "Export"); let running = app.session.slideshow_export.as_ref().is_some_and(|r| r.running()); ui.horizontal_wrapped(|ui| { for (id, label, format) in [ @@ -45,7 +45,7 @@ fn export_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use lightcraft_engine::slideshow::{FADE_MAX, SLIDE_MAX, SLIDE_MIN}; - heading(ui, t, crate::i18n::tr("Playback")); + heading(ui, t, "Playback"); let s = app.session.slideshow.clone(); let mut v = s.manual; if check(ui, "settings.slideshowManual", &mut v, "Manual slideshow") { diff --git a/crates/ui-egui/src/dialogs/settings/widgets.rs b/crates/ui-egui/src/dialogs/settings/widgets.rs index afd66068ea..853e66824a 100644 --- a/crates/ui-egui/src/dialogs/settings/widgets.rs +++ b/crates/ui-egui/src/dialogs/settings/widgets.rs @@ -1,4 +1,4 @@ -use super::{LABEL_W, RichText, Tokens, register}; +use super::{GOTO, LABEL_W, RichText, Tokens, register}; /// `path` shortened to fit `max` (as `width` measures it) by dropping leading folders, after /// either kind of separator, so that its end stays (`…/Pictures/Library`, @@ -61,7 +61,15 @@ pub(super) fn field(ui: &mut egui::Ui, field: crate::text_field::TextField<'_>) pub(crate) fn heading(ui: &mut egui::Ui, t: &Tokens, text: &str) { ui.add_space(4.0); - ui.label(RichText::new(crate::i18n::tr(text)).font(t.semibold(12.5)).color(t.text)); + // `text` is the heading's English name (its message key). It is shown translated and + // registered as `heading:{text}` whatever the language, where a section starts: for the + // filter, scripts and tests that look for one. + let r = ui.label(RichText::new(crate::i18n::tr(text)).font(t.semibold(12.5)).color(t.text)); + register(ui, format!("heading:{text}"), r.rect); + // (chosen from what the filter found: the section is brought to the top of the page) + if ui.data(|d| d.get_temp::<(&'static str, String)>(egui::Id::unique(GOTO))).is_some_and(|(_, section)| section == text) { + r.scroll_to_me(Some(egui::Align::TOP)); + } } pub(crate) fn row(ui: &mut egui::Ui, t: &Tokens, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R { diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 9f1eb5019e..269f5f5677 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -36,6 +36,7 @@ mod dialog_copy; mod dialog_fit; mod dialog_primary; mod dialog_settings; +mod dialog_settings_filter; mod dialog_settings_text; mod dialog_tab; mod dialogs; diff --git a/crates/ui-egui/src/tests/dialog_settings_filter.rs b/crates/ui-egui/src/tests/dialog_settings_filter.rs new file mode 100644 index 0000000000..cd35a06e9c --- /dev/null +++ b/crates/ui-egui/src/tests/dialog_settings_filter.rs @@ -0,0 +1,379 @@ +//! Settings has a filter: typing in it lists the sections, on whatever tab, whose words match, and +//! choosing one opens its tab at that section. +//! +//! Before, finding a setting meant knowing or guessing its tab: eight of them, each read through. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(size: [f32; 2]) -> Headless { + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), size, 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn steps(h: &mut Headless) { + for _ in 0..4 { + h.step(); + } +} + +fn show(h: &mut Headless, tab: &str) { + let r = h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": tab}}), T); + assert_eq!(r["ok"], true, "app.settings {tab}: {r}"); + h.settle(T); + steps(h); +} + +fn click(h: &mut Headless, id: &str) { + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "click {id}: {r}"); + steps(h); +} + +fn key(h: &mut Headless, key: &str) { + assert_eq!(h.request("ui.key", json!({"key": key}), T)["ok"], true, "{key}"); + steps(h); +} + +/// Given the filter with `text` typed into it. +fn filter(h: &mut Headless, text: &str) { + click(h, "field:settingsFilter"); + h.request("ui.key", json!({"key": "A", "cmd": true}), T); + h.request("ui.text", json!({"text": text}), T); + steps(h); +} + +fn rect(h: &Headless, id: &str) -> Option { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +/// What the filter lists, top to bottom: `tab:section` of each result (`settingsFound:{tab}:{section}`). +fn found(h: &Headless) -> Vec { + let mut found: Vec<(f32, String)> = + h.app.widgets.iter().filter_map(|(id, r)| Some((r.top(), id.strip_prefix("settingsFound:")?.to_string()))).collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + found.into_iter().map(|(_, id)| id).collect() +} + +fn headings(h: &Headless) -> Vec { + h.app.widgets.iter().filter_map(|(id, _)| Some(id.strip_prefix("heading:")?.to_string())).collect() +} + +/// Whether the keyboard focus is on something other than the filter box. +fn on_a_result(h: &Headless) -> bool { + h.view.ctx.memory(|m| m.focused()).is_some_and(|id| id != crate::text_field::id("field:settingsFilter")) +} + +fn says(h: &Headless, part: &str) -> bool { + h.painted_text().iter().any(|text| text.contains(part)) +} + +#[test] +fn typing_lists_the_sections_that_match_on_whatever_tab() { + let mut h = demo([1200.0, 1000.0]); + // Given Settings open on General, which has nothing about sidecars (they are on Import) + show(&mut h, "general"); + // When "sidecar names" is typed into the filter + filter(&mut h, "sidecar names"); + // Then the section about them is listed with the tab it is on, and the page of General is not shown + assert_eq!(found(&h), ["import:XMP sidecars"]); + assert!(says(&h, "Import") && says(&h, "XMP sidecars")); + assert!(headings(&h).is_empty(), "the tab's own page gives way to what was found: {:?}", headings(&h)); + // And the tab that was open is still the one open + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "general".into() })); +} + +#[test] +fn a_word_from_a_row_a_hint_or_a_button_finds_its_section() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // (a row's label) + filter(&mut h, "Forget unchanged"); + assert_eq!(found(&h), ["performance:Local folders"]); + // (a button) + filter(&mut h, "Clear Cache"); + assert_eq!(found(&h), ["performance:Preview cache"]); + // (a hint, in other letter case) + filter(&mut h, "CHOOSES THE LINES"); + assert_eq!(found(&h), ["interface:Detail View"]); + // (a tab's own name finds everything on it) + filter(&mut h, "Interface"); + let on_the_tab = found(&h); + assert!(on_the_tab.len() >= 4 && on_the_tab.iter().all(|id| id.starts_with("interface:")), "{on_the_tab:?}"); + assert!(on_the_tab.contains(&"interface:Filmstrip".to_string()), "a section that does not say the word itself: {on_the_tab:?}"); +} + +#[test] +fn every_word_typed_has_to_be_there() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "cache"); + let cache = found(&h); + assert!(cache.len() > 1 && cache.contains(&"performance:Preview cache".to_string()), "{cache:?}"); + // When a second word narrows it + filter(&mut h, "cache disk"); + assert_eq!(found(&h), ["performance:Preview cache"]); + // And the words can come in any order + filter(&mut h, "disk cache"); + assert_eq!(found(&h), ["performance:Preview cache"]); +} + +#[test] +fn nothing_found_says_so() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "zebra crossing"); + assert!(found(&h).is_empty()); + assert!(says(&h, "No setting matches"), "{:?}", h.painted_text().iter().filter(|t| t.contains("match")).collect::>()); + assert!(headings(&h).is_empty()); +} + +/// Reading every page for the filter shows nothing of it, so it must not start the slide preview's render (the Slideshow +/// page asks for it when it is open, which a filter on another tab is not). +#[test] +fn typing_in_the_filter_starts_no_slide_preview_render() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + assert!(h.app.session.active().is_some(), "a photo is active, so the preview would have one to render"); + assert_eq!(h.app.renderer.wanted(crate::render::Slot::SlidePreview), None, "none before"); + filter(&mut h, "sidecar names"); + assert_eq!(found(&h), ["import:XMP sidecars"]); + h.settle(T); + assert_eq!(h.app.renderer.wanted(crate::render::Slot::SlidePreview), None, "the filter asked for no render of the slide preview"); +} + +#[test] +fn choosing_a_result_opens_its_tab_at_that_section() { + // (a window short enough that Detail View, near the foot of Interface, is below the fold) + let mut h = demo([900.0, 560.0]); + // Given Detail View below the fold of Interface + show(&mut h, "interface"); + let (detail, room) = (rect(&h, "heading:Detail View").unwrap(), rect(&h, "settings:pageRoom").unwrap()); + assert!(detail.bottom() > room.bottom(), "Detail View {detail:?} starts out of view in {room:?}"); + show(&mut h, "general"); + filter(&mut h, "info overlay"); + assert_eq!(found(&h), ["interface:Detail View"]); + // When the result is clicked + click(&mut h, "settingsFound:interface:Detail View"); + h.settle(T); + steps(&mut h); + // Then its tab is open, the filter is empty again, and the section is in view + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "interface".into() })); + assert!(found(&h).is_empty() && !says(&h, "info overlay"), "the filter is cleared"); + let (detail, room) = (rect(&h, "heading:Detail View").unwrap(), rect(&h, "settings:pageRoom").unwrap()); + assert!(detail.top() >= room.top() - 0.5 && detail.bottom() <= room.bottom() + 0.5, "Detail View {detail:?} is in view in {room:?}"); +} + +#[test] +fn choosing_what_starts_a_tab_shows_the_top_of_its_page() { + let mut h = demo([900.0, 560.0]); + // Given General scrolled down, so that its first heading is out of view + show(&mut h, "general"); + let room = rect(&h, "settings:pageRoom").unwrap(); + h.request("ui.move", json!({"x": room.center().x, "y": room.center().y}), T); + h.request("ui.scroll", json!({"dy": -300.0}), T); + for _ in 0..60 { + h.step(); + } + assert!(rect(&h, "heading:Library").unwrap().top() < room.top(), "General is scrolled down"); + // When what is above its first heading (the language) is found and chosen + filter(&mut h, "language"); + assert!(found(&h).contains(&"general:".to_string()), "{:?}", found(&h)); + click(&mut h, "settingsFound:general:"); + h.settle(T); + for _ in 0..60 { + h.step(); + } + // Then the page is at its top again + assert!(rect(&h, "heading:Library").unwrap().top() >= room.top() - 0.5, "the top of General is in view"); +} + +#[test] +fn return_opens_the_first_result() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "sidecar names"); + key(&mut h, "Enter"); + h.settle(T); + steps(&mut h); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "import".into() })); + assert!(headings(&h).contains(&"XMP sidecars".to_string())); + assert!(found(&h).is_empty()); +} + +#[test] +fn esc_empties_the_filter_and_a_second_esc_closes_settings() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "import"); + filter(&mut h, "sidecar names"); + assert_eq!(found(&h).len(), 1); + // When Esc is pressed + key(&mut h, "Escape"); + // Then the filter is empty, the tab that was open shows its page again, and Settings is open + assert!(found(&h).is_empty()); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "import".into() })); + assert!(headings(&h).contains(&"Raw defaults".to_string())); + // And a second Esc closes Settings + key(&mut h, "Escape"); + assert!(h.app.ui.dialog.is_none()); +} + +#[test] +fn opening_a_tab_empties_the_filter() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "sidecar names"); + click(&mut h, "button:settingsTab-performance"); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "performance".into() })); + assert!(found(&h).is_empty()); + assert!(headings(&h).contains(&"Rendering".to_string()), "Performance shows its page"); +} + +#[test] +fn looking_through_the_tabs_changes_nothing_and_leaves_no_double_names() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // (what Settings sets: the app's own settings, the language, and what is saved with the library) + let state = |h: &mut Headless| { + ( + serde_json::to_value(&h.app.ui.settings).unwrap(), + h.app.ui.language, + h.app.ui.auto_advance, + h.app.run("library.preferences", json!({})).unwrap(), + h.app.run("library.xmpPreferences", json!({})).unwrap(), + h.app.ui.dialog.clone(), + ) + }; + let before = state(&mut h); + h.app.ui.toast = None; + filter(&mut h, "cache"); + // Then nothing changed by being looked through, and nothing was said + assert_eq!(state(&mut h), before); + assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast); + // And no control of a tab that is not shown is among the widgets scripts can click + let mut ids: Vec<&String> = h.app.widgets.iter().map(|(id, _)| id).collect(); + assert!(!ids.iter().any(|id| id.as_str() == "button:settingsClearCache"), "a tab looked through off screen leaves no widgets behind"); + let all = ids.len(); + ids.sort(); + ids.dedup(); + assert_eq!(ids.len(), all, "no widget is named twice"); +} + +#[test] +fn the_filter_is_empty_when_settings_is_opened_again() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "sidecar names"); + // (Esc once empties it; here Settings is closed from outside with the filter still set) + h.app.ui.dialog = None; + steps(&mut h); + show(&mut h, "general"); + assert!(found(&h).is_empty() && !says(&h, "sidecar names")); + assert!(headings(&h).contains(&"Startup".to_string())); +} + +#[test] +fn what_a_page_shows_now_is_what_is_found() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "import"); + // Given a sentence Import only shows with camera-specific defaults on, looked for and not found + filter(&mut h, "cameras appear"); + assert!(found(&h).is_empty()); + key(&mut h, "Escape"); + // When that is turned on, with Settings still open + click(&mut h, "check:settings.perCamera"); + assert!(says(&h, "cameras appear"), "the page shows the sentence now"); + // Then looking for it again finds it: the pages are read afresh each time the filter is used + filter(&mut h, "cameras appear"); + assert_eq!(found(&h), ["import:Raw defaults"]); +} + +#[test] +fn the_arrow_goes_from_the_filter_to_what_was_found_and_return_opens_it() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "cache disk"); + assert_eq!(found(&h), ["performance:Preview cache"]); + // When ↓ is pressed in the filter (the focus goes to the first result), then Return + key(&mut h, "ArrowDown"); + assert!(on_a_result(&h), "↓ leaves the filter for what was found"); + key(&mut h, "Enter"); + h.settle(T); + steps(&mut h); + // Then the section found is open + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "performance".into() })); + assert!(found(&h).is_empty()); +} + +#[test] +fn esc_on_a_result_empties_the_filter_and_leaves_settings_open() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "import"); + filter(&mut h, "cache"); + assert!(!found(&h).is_empty()); + // Given the focus on a result, not in the filter + key(&mut h, "ArrowDown"); + assert!(on_a_result(&h)); + // When Esc is pressed + key(&mut h, "Escape"); + // Then the filter is emptied and Settings is still open on the tab it was on + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "import".into() })); + assert!(found(&h).is_empty() && headings(&h).contains(&"Raw defaults".to_string())); + // And the next Esc closes Settings + key(&mut h, "Escape"); + assert!(h.app.ui.dialog.is_none()); +} + +/// A section's heading goes in by its English name and is translated once: View Options' General +/// heading used to be passed already translated, so in another language it was translated again +/// and registered under the translated name, where the filter and scripts look for the English one. +#[test] +fn the_general_heading_of_view_options_is_translated_once_and_registered_by_its_english_name() { + use crate::i18n::Locale; + struct Restore(Locale); + impl Drop for Restore { + fn drop(&mut self) { + crate::i18n::set_language(self.0); + } + } + let _restore = Restore(crate::i18n::language()); + let mut h = demo([1000.0, 800.0]); + h.app.ui.language = Locale::De; + crate::i18n::set_language(Locale::De); + h.app.ui.dialog = Some(Dialog::ViewOptions); + steps(&mut h); + let shown = Locale::De.tr("General"); + assert_ne!(shown, "General", "the German catalog translates the heading"); + let headings: Vec<&str> = h.app.widgets.iter().filter_map(|(id, _)| id.strip_prefix("heading:")).collect(); + assert!(headings.contains(&"General"), "registered by its English name: {headings:?}"); + assert!(!headings.contains(&shown), "not by the translated one: {headings:?}"); + assert!(h.painted_text().iter().any(|text| text == shown), "and drawn translated: {shown}"); +} + +/// The Display page reads the profile in use, so the sections read for the filter are read again +/// when it changes (the window moved to another screen), with the filter still set. +#[test] +fn a_changed_display_profile_is_read_again_while_the_filter_has_text() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // Given the page's sentence about no profile, found + filter(&mut h, "treated as sRGB"); + assert!(!found(&h).is_empty(), "no display profile: the page says so"); + // When a profile is in use from now on, the filter still holding its text + let p3 = + lightcraft_engine::display::Display::from_bytes("p3.icc", &lightcraft_codecs::icc::write_named(lightcraft_codecs::NamedSpace::DisplayP3)) + .unwrap(); + h.app.renderer.set_display(Some(std::sync::Arc::new(p3))); + steps(&mut h); + // Then the old sentence is not found any more + assert!(found(&h).is_empty(), "the sections were read for the old profile: {:?}", found(&h)); +} diff --git a/crates/ui-egui/tests/it/accessibility.rs b/crates/ui-egui/tests/it/accessibility.rs index fe5a39f107..df24b17832 100644 --- a/crates/ui-egui/tests/it/accessibility.rs +++ b/crates/ui-egui/tests/it/accessibility.rs @@ -3,7 +3,10 @@ //! node with no name, a slider without its value and range, or a canvas tool no key can reach. use egui::accesskit::Role; use egui::vec2; -use egui_kittest::{Harness, kittest::NodeT}; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; use lightcraft_ui_egui::{ LightcraftApp, Services, state::{RightPanel, ViewMode}, @@ -336,3 +339,30 @@ fn import_button_describes_its_shortcut_as_this_platform_writes_it() { let help = lightcraft_ui_egui::menubar::shortcut_text(sc, mac); assert!(button_described(&h, "Import Photos…", &help), "a button named \"Import Photos…\" describing {help:?}"); } + +/// Settings' filter reads every tab by drawing it in a context of its own. That reading leaves the +/// window's tree as it was: one Settings window, no interactive node left unnamed by it, and what was found +/// listed as the window's own widgets. +#[test] +fn the_settings_filter_reads_the_tabs_without_touching_the_tree() { + let mut h = harness(ViewMode::PhotoGrid, RightPanel::None); + // (the External Editor tab's text has a "▸" the fonts lack: drawn as a box here, as in the app, + // not a panic as the kittest harness has it by default) + h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu); + h.state_mut().run("app.settings", serde_json::json!({"tab": "general"})).unwrap(); + h.run_steps(8); + let windows = + |h: &Harness<'_, LightcraftApp>| h.root().children_recursive().map(|n| n.accesskit_node()).filter(|n| n.role() == Role::Window).count(); + let before = windows(&h); + // (what Settings leaves unnamed of its own is not this test's: the filter adds none to it) + let unnamed = |h: &Harness<'_, LightcraftApp>| audit(h, "settings").len(); + let unnamed_before = unnamed(&h); + let filter = h.get_by_label("Filter settings"); + filter.click(); + h.run_steps(2); + h.get_by_label("Filter settings").type_text("cache"); + h.run_steps(8); + assert!(h.state().widgets.iter().any(|(id, _)| id.starts_with("settingsFound:")), "the filter lists what it found"); + assert_eq!(windows(&h), before, "reading the tabs adds no window to the tree"); + assert!(unnamed(&h) <= unnamed_before, "the filter and what it found are named: {} unnamed, {unnamed_before} before", unnamed(&h)); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 636f346997..cdbe34cb82 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -436,7 +436,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-PREF-GENERAL | General settings | P0 | ✅ | `cmd:app.settings`, `cmd:app.openLibrary`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/notices.rs` | General / Import / Performance / Display / Interface tabs; app settings in ui.json (written atomically, saved when the library changes and every few seconds), library settings in prefs.json; At launch: open the last library or ask (see LRC-LIB-CATALOG-SWITCH); Startup View: an image passed at launch honors explicit Detail; Grid and Last use Photo Grid; populated-library launches without image arguments retain their saved view; a damaged settings file is kept as `.corrupt-