diff --git a/CLAUDE.md b/CLAUDE.md index 136e821bbf5..b295f6c5868 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -117,6 +117,10 @@ of it. Full standard: `../craftrules/standards/never-crash.md` - Text boxes use `crates/ui-egui/src/text_field.rs` (`TextField`), not `egui::TextEdit`: it gives every field the Cut / Copy / Paste / Select All menu, Esc restoring the text, and reports how an edit ended. Give each a widget id that is unique on screen. Older fields still on `TextEdit` move over as they are touched. +- Text sizes are the seven of `theme::TextSize` (10 micro, 11 caption, 12 label, 13 body, 14 title, 15 panel title, + 18 display): write `t.caption()`, `t.body_strong()`, … and never a number (`.size(11.5)`, `FontId::proportional(13.0)`). + `t.font(n)` / `t.semibold(n)` still take a number and draw at the nearest size; `cargo xtask type` (in `ci`) fails + on a number written where a font is made past the theme (one held in a constant it cannot see: don't). - Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. - Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`//`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone). - Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media. diff --git a/Cargo.lock b/Cargo.lock index bf2ac824f74..4359f920dbf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3497,6 +3497,7 @@ dependencies = [ "serde", "serde_json", "toml", + "unicode-segmentation", "web-time", ] diff --git a/crates/engine/src/cmd/prefs.rs b/crates/engine/src/cmd/prefs.rs index 78de9d8500c..7003ee5bc10 100644 --- a/crates/engine/src/cmd/prefs.rs +++ b/crates/engine/src/cmd/prefs.rs @@ -1,4 +1,4 @@ -//! Library preferences (Settings → Import / Performance): develop defaults applied on import and +//! Library preferences (Settings → Library / Import / Performance): develop defaults applied on import and //! the thumbnail cache budget. Saved in the library's `prefs.json` (see [`crate::library`]). use serde_json::{Value, json}; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 74bc800582e..c7aaabd65c7 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -19,6 +19,8 @@ lightcraft-develop = { workspace = true } lightcraft-pipeline = { workspace = true } lightcraft-catalog = { workspace = true } web-time = { workspace = true } +# file names are shortened between letters, not inside one (readout::elide_middle); the engine has it already +unicode-segmentation = "1.13" lightcraft-engine = { workspace = true } lightcraft-preview = { workspace = true } egui = { workspace = true } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 25c411ce0e0..bbb819126a8 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2036,6 +2036,41 @@ "Not saved": "Nicht gespeichert", "A folder is being synchronized": "Ein Ordner wird gerade synchronisiert", "Wait for the import to finish": "Warten Sie, 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.", + "Choose Profile…": "Profil auswählen…", + "Delete and Change Folder": "Löschen und Ordner wechseln", + "Delete the smart previews in the folder used until now?": "Smart-Vorschauen im bisherigen Ordner löschen?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "In anderem Editor bearbeiten (⌥⌘E) öffnet die Kopie in dieser Anwendung (App-Name unter macOS, sonst Programmpfad).", + "External Editing": "Externe Bearbeitung", + "Faces": "Gesichter", + "Found automatically": "Wird automatisch gefunden", + "Keep": "Behalten", + "LUT-based": "LUT-basiert", + "Matrix/TRC": "Matrix/TRC", + "Model installation failed": "Modellinstallation fehlgeschlagen", + "Monitor profile": "Monitorprofil", + "None (the display is treated as sRGB)": "Keines (der Bildschirm wird als sRGB behandelt)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.": "Ein: Jede Änderung an den Bearbeitungen oder Metadaten eines Fotos wird in eine XMP-Datei neben dem Foto geschrieben, damit andere Apps sie lesen können. Aus: Das geschieht, wenn du im Menü „Foto“ den Befehl „Metadaten in Datei speichern“ wählst.", + "Other editor": "Anderer 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 > Bearbeiten in > In PhotoCraft bearbeiten (⇧⌘E oder Rechtsklick auf ein Foto) rendert eine Kopie mit deinen Bearbeitungen, stapelt sie mit dem Original und öffnet sie in PhotoCraft. Speichere dort, und die Kopie wird hier aktualisiert. Ist die Kopie eine PSD, speichert PhotoCraft direkt in sie zurück. Lass den Speicherort leer, sofern du keine portable Version verwendest.", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Fotos werden über das ICC-Profil deines Monitors angezeigt, damit die Farben auf Wide-Gamut- und kalibrierten Bildschirmen stimmen; die Detailansicht nutzt den gesamten Farbraum des Bildschirms. Histogramm, Vorschau-Caches und Exporte sind davon nicht betroffen.", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.": "Fotos, deren Originale nicht verbunden sind, werden anhand ihrer Smart-Vorschauen angezeigt und bearbeitet; neue lassen sich nur aus verbundenen Originalen erstellen.", + "Primaries (x, y)": "Primärfarben (x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "Profile, die in den Farbeinstellungen deines Desktops zugewiesen sind, liegen meist in ~/.local/share/icc.", + "The download failed": "Der Download ist fehlgeschlagen", + "The model's file is deleted. To use it again you download or add it again.": "Die Datei des Modells wird gelöscht. Um es wieder zu verwenden, musst du es erneut herunterladen oder hinzufügen.", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.": "Miniaturbilder und Vorschauen werden beim Durchsehen neu erstellt, was bei einer großen Bibliothek eine Weile dauert. Deine Fotos und Bearbeitungen bleiben unberührt.", + "Use Screen Profile": "Bildschirmprofil verwenden", + "Use sRGB": "sRGB verwenden", + "starting…": "wird gestartet…", + "this screen's profile": "Profil dieses Bildschirms", + "Edit In": "Bearbeiten in", + "Edit in PhotoCraft": "In PhotoCraft bearbeiten", + "Edit in Other Editor": "In anderem Editor bearbeiten", + "Files": "Dateien", + "Monitor": "Monitor", "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 ba3e1e33165..8ef01776c4b 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1916,6 +1916,41 @@ "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.", + "Choose Profile…": "Elegir perfil…", + "Delete and Change Folder": "Eliminar y cambiar de carpeta", + "Delete the smart previews in the folder used until now?": "¿Eliminar las vistas previas inteligentes de la carpeta usada hasta ahora?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Editar en otro editor (⌥⌘E) abre la copia en esta aplicación (un nombre de aplicación en macOS, una ruta de programa en otros sistemas).", + "External Editing": "Edición externa", + "Faces": "Caras", + "Found automatically": "Se encuentra automáticamente", + "Keep": "Conservar", + "LUT-based": "Basado en LUT", + "Matrix/TRC": "Matriz/TRC", + "Model installation failed": "Error al instalar el modelo", + "Monitor profile": "Perfil del monitor", + "None (the display is treated as sRGB)": "Ninguno (la pantalla se trata como sRGB)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.": "Activado: cada cambio en las ediciones o los metadatos de una foto se escribe en un archivo XMP junto a la foto, para que otras aplicaciones lo lean. Desactivado: eso ocurre al elegir Guardar metadatos en el archivo en el menú Foto.", + "Other editor": "Otro 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 > Editar en > Editar en PhotoCraft (⇧⌘E, o clic derecho en una foto) renderiza una copia con las ediciones, la apila con el original y la abre en PhotoCraft. Al guardar allí, la copia se actualiza aquí. Si es un PSD, PhotoCraft guarda directamente en ella. Dejar la ubicación vacía salvo que se use una copia portátil.", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Las fotos se muestran a través del perfil ICC del monitor, para que los colores sean correctos en pantallas calibradas y de gama amplia, y la vista Detalle usa toda la gama de la pantalla. El histograma, las cachés de vistas previas y las exportaciones no se ven afectados.", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.": "Las fotos cuyos originales no están conectados se muestran y se editan a partir de sus vistas previas inteligentes; solo se pueden generar otras nuevas a partir de originales conectados.", + "Primaries (x, y)": "Primarios (x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "Los perfiles asignados en los ajustes de color del escritorio suelen estar en ~/.local/share/icc.", + "The download failed": "Error en la descarga", + "The model's file is deleted. To use it again you download or add it again.": "El archivo del modelo se elimina. Para volver a usarlo hay que descargarlo o añadirlo de nuevo.", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.": "Las miniaturas y las vistas previas se vuelven a generar al navegar, lo que tarda un rato en una biblioteca grande. Las fotos y las ediciones no se tocan.", + "Use Screen Profile": "Usar perfil de la pantalla", + "Use sRGB": "Usar sRGB", + "starting…": "iniciando…", + "this screen's profile": "perfil de esta pantalla", + "Edit In": "Editar en", + "Edit in PhotoCraft": "Editar en PhotoCraft", + "Edit in Other Editor": "Editar en otro editor", + "Files": "Archivos", + "Monitor": "Monitor", "Appearance": "Apariencia", "Appearance Mode": "Modo de apariencia", "Sync with System": "Sincronizar con el sistema", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index b0becb154e4..263adfe0688 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1937,6 +1937,41 @@ "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.", + "Choose Profile…": "Choisir un profil…", + "Delete and Change Folder": "Supprimer et changer de dossier", + "Delete the smart previews in the folder used until now?": "Supprimer les aperçus dynamiques du dossier utilisé jusqu'ici ?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Modifier dans un autre éditeur (⌥⌘E) ouvre la copie dans cette application (un nom d'application sur macOS, un chemin de programme ailleurs).", + "External Editing": "Édition externe", + "Faces": "Visages", + "Found automatically": "Détecté automatiquement", + "Keep": "Conserver", + "LUT-based": "À base de LUT", + "Matrix/TRC": "Matrice/TRC", + "Model installation failed": "Échec de l'installation du modèle", + "Monitor profile": "Profil du moniteur", + "None (the display is treated as sRGB)": "Aucun (l'écran est traité comme sRGB)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.": "Activé : chaque modification des retouches ou des métadonnées d'une photo est écrite dans un fichier XMP à côté de la photo, pour que d'autres applications puissent la lire. Désactivé : cela se fait lorsque vous choisissez Enregistrer les métadonnées dans le fichier dans le menu Photo.", + "Other editor": "Autre éditeur", + "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.": "Photo > Modifier dans > Modifier dans PhotoCraft (⇧⌘E, ou clic droit sur une photo) génère une copie avec vos retouches, l'empile avec l'original et l'ouvre dans PhotoCraft. Enregistrez-la là-bas et la copie se met à jour ici. En PSD, PhotoCraft enregistre directement dans la copie. Laissez l'emplacement vide, sauf si vous utilisez une version portable.", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Les photos sont affichées à travers le profil ICC de votre moniteur : les couleurs sont justes sur les écrans à large gamut et calibrés, et la vue Détail exploite tout le gamut de l'écran. L'histogramme, les caches d'aperçus et les exportations ne sont pas concernés.", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.": "Les photos dont les originaux ne sont pas connectés sont affichées et retouchées à partir de leurs aperçus dynamiques ; de nouveaux aperçus ne peuvent être générés qu'à partir d'originaux connectés.", + "Primaries (x, y)": "Primaires (x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "Les profils attribués dans les réglages de couleur de votre bureau se trouvent généralement dans ~/.local/share/icc.", + "The download failed": "Le téléchargement a échoué", + "The model's file is deleted. To use it again you download or add it again.": "Le fichier du modèle est supprimé. Pour l'utiliser à nouveau, vous devrez le télécharger ou l'ajouter de nouveau.", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.": "Les miniatures et les aperçus sont recréés au fil de la navigation, ce qui prend du temps dans une grande bibliothèque. Vos photos et vos retouches ne sont pas touchées.", + "Use Screen Profile": "Utiliser le profil de l'écran", + "Use sRGB": "Utiliser sRGB", + "starting…": "démarrage…", + "this screen's profile": "profil de cet écran", + "Edit In": "Modifier dans", + "Edit in PhotoCraft": "Modifier dans PhotoCraft", + "Edit in Other Editor": "Modifier dans un autre éditeur", + "Files": "Fichiers", + "Monitor": "Moniteur", "Appearance": "Apparence", "Appearance Mode": "Mode d’apparence", "Sync with System": "Synchroniser avec le système", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 7a282e676e4..e534876d3cb 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1882,6 +1882,41 @@ "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.": "単語またはその一部で試してください。タブとセクションの名前、ラベル、説明文が検索されます。", + "Choose Profile…": "プロファイルを選択…", + "Delete and Change Folder": "削除してフォルダを変更", + "Delete the smart previews in the folder used until now?": "これまで使用していたフォルダのスマートプレビューを削除しますか?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "「他のエディターで編集」(⌥⌘E)は、コピーをこのアプリケーションで開きます(macOSではアプリ名、それ以外ではプログラムのパス)", + "External Editing": "外部編集", + "Faces": "顔", + "Found automatically": "自動検出", + "Keep": "残す", + "LUT-based": "LUTベース", + "Matrix/TRC": "マトリックス/TRC", + "Model installation failed": "モデルのインストールに失敗しました", + "Monitor profile": "モニタープロファイル", + "None (the display is treated as sRGB)": "なし(ディスプレイをsRGBとして扱います)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.": "オンの場合、写真の編集内容やメタデータを変更するたびに、写真と同じ場所のXMPファイルに書き込み、他のアプリで読み取れるようにします。オフの場合は、「写真」メニューの「メタデータをファイルに保存」を選んだときに書き込みます", + "Other 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.": "「写真 > アプリで編集 > PhotoCraftで編集」(⇧⌘E、または写真を右クリック)は、編集内容を反映したコピーを作成し、元画像とスタックにまとめてPhotoCraftで開きます。PhotoCraftで保存すると、こちらのコピーも更新されます。PSDの場合、PhotoCraftはそのファイルに直接保存します。ポータブル版を使わない場合は、場所を空欄のままにしてください", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "写真はモニターのICCプロファイルを通して表示されるため、広色域ディスプレイやキャリブレーション済みのディスプレイでも正しい色になり、詳細表示ではディスプレイの色域全体を使用します。ヒストグラム、プレビューキャッシュ、書き出しには影響しません", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.": "元画像が接続されていない写真は、スマートプレビューを使って表示・編集されます。新しいスマートプレビューは、接続されている元画像からのみ作成できます", + "Primaries (x, y)": "原色(x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "デスクトップのカラー設定で割り当てたプロファイルは、通常 ~/.local/share/icc にあります", + "The download failed": "ダウンロードに失敗しました", + "The model's file is deleted. To use it again you download or add it again.": "モデルのファイルは削除されます。再び使用するには、もう一度ダウンロードまたは追加してください", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.": "サムネイルとプレビューは閲覧時に作り直されるため、大きなライブラリでは時間がかかります。写真と編集内容には影響しません", + "Use Screen Profile": "画面のプロファイルを使用", + "Use sRGB": "sRGBを使用", + "starting…": "起動中…", + "this screen's profile": "この画面のプロファイル", + "Edit In": "アプリで編集", + "Edit in PhotoCraft": "PhotoCraftで編集", + "Edit in Other Editor": "他のエディターで編集", + "Files": "ファイル", + "Monitor": "モニター", "Appearance": "外観", "Appearance Mode": "外観モード", "Sync with System": "システムと同期", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index f8e4753e5ce..30e72368336 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1880,6 +1880,41 @@ "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.", + "Choose Profile…": "Escolher perfil…", + "Delete and Change Folder": "Excluir e alterar pasta", + "Delete the smart previews in the folder used until now?": "Excluir as pré-visualizações inteligentes da pasta usada até agora?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Editar em outro editor (⌥⌘E) abre a cópia neste aplicativo (um nome de aplicativo no macOS, um caminho de programa em outros sistemas).", + "External Editing": "Edição externa", + "Faces": "Rostos", + "Found automatically": "Encontrado automaticamente", + "Keep": "Manter", + "LUT-based": "Baseado em LUT", + "Matrix/TRC": "Matriz/TRC", + "Model installation failed": "Falha na instalação do modelo", + "Monitor profile": "Perfil do monitor", + "None (the display is treated as sRGB)": "Nenhum (a tela é tratada como sRGB)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.": "Ativado: toda alteração nas edições ou nos metadados de uma foto é gravada em um arquivo XMP ao lado da foto, para que outros aplicativos possam ler. Desativado: isso acontece quando você escolhe Salvar metadados no arquivo no menu Foto.", + "Other editor": "Outro 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 > Editar em > Editar no PhotoCraft (⇧⌘E, ou clique com o botão direito em uma foto) renderiza uma cópia com suas edições, empilha-a com o original e a abre no PhotoCraft. Salve lá e a cópia é atualizada aqui. Se for um PSD, o PhotoCraft salva diretamente nela. Deixe o local vazio, a menos que você use uma cópia portátil.", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "As fotos são exibidas por meio do perfil ICC do seu monitor, para que as cores fiquem corretas em telas calibradas e de gamut amplo, e a exibição Detalhe usa todo o gamut da tela. O histograma, os caches de pré-visualização e as exportações não são afetados.", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.": "As fotos cujos originais não estão conectados são exibidas e editadas a partir de suas pré-visualizações inteligentes; novas só podem ser geradas a partir de originais conectados.", + "Primaries (x, y)": "Primárias (x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "Os perfis atribuídos nas configurações de cor da sua área de trabalho geralmente ficam em ~/.local/share/icc.", + "The download failed": "Falha no download", + "The model's file is deleted. To use it again you download or add it again.": "O arquivo do modelo é excluído. Para usá-lo novamente, você precisa baixá-lo ou adicioná-lo de novo.", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.": "As miniaturas e as pré-visualizações são geradas novamente conforme você navega, o que demora um pouco em uma biblioteca grande. Suas fotos e edições não são alteradas.", + "Use Screen Profile": "Usar perfil da tela", + "Use sRGB": "Usar sRGB", + "starting…": "iniciando…", + "this screen's profile": "perfil desta tela", + "Edit In": "Editar em", + "Edit in PhotoCraft": "Editar no PhotoCraft", + "Edit in Other Editor": "Editar em outro editor", + "Files": "Arquivos", + "Monitor": "Monitor", "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 c840218a039..0bca28fe7a3 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1593,6 +1593,40 @@ "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.": "Попробуйте одно слово или его часть: поиск ведётся по названиям вкладок и разделов, подписям и пояснениям.", + "Choose Profile…": "Выбрать профиль…", + "Delete and Change Folder": "Удалить и сменить папку", + "Delete the smart previews in the folder used until now?": "Удалить смарт-просмотры из папки, которая использовалась до сих пор?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Править в другом редакторе (⌥⌘E) открывает копию в этом приложении (имя приложения в macOS, путь к программе в других системах).", + "External Editing": "Внешнее редактирование", + "Found automatically": "Определяется автоматически", + "Keep": "Оставить", + "LUT-based": "На основе LUT", + "Matrix/TRC": "Матрица/TRC", + "Model installation failed": "Не удалось установить модель", + "Monitor profile": "Профиль монитора", + "None (the display is treated as sRGB)": "Нет (дисплей считается sRGB)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.": "Вкл.: каждое изменение правок или метаданных фото записывается в XMP-файл рядом с фото, чтобы его могли прочитать другие приложения. Выкл.: это происходит, когда вы выбираете «Сохранить метаданные в файл» в меню «Фото».", + "Other 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.": "Фото > Править в > Править в PhotoCraft (⇧⌘E или щелчок правой кнопкой по фото) создаёт копию с вашими правками, помещает её в стопку с оригиналом и открывает в PhotoCraft. Сохраните её там, и копия обновится здесь. Если это PSD, PhotoCraft сохраняет прямо в неё. Оставьте расположение пустым, если не используете портативную версию.", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Фото отображаются через ICC-профиль вашего монитора, поэтому цвета верны на калиброванных дисплеях и дисплеях с широким цветовым охватом, а режим «Детализация» использует весь охват дисплея. На гистограмму, кэши просмотров и экспорт это не влияет.", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.": "Фото, оригиналы которых не подключены, отображаются и правятся по смарт-просмотрам; новые смарт-просмотры можно создать только из подключённых оригиналов.", + "Primaries (x, y)": "Основные цвета (x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "Профили, назначенные в настройках цвета рабочего стола, обычно находятся в ~/.local/share/icc.", + "The download failed": "Загрузка не удалась", + "The model's file is deleted. To use it again you download or add it again.": "Файл модели будет удалён. Чтобы использовать её снова, загрузите или добавьте её заново.", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.": "Миниатюры и просмотры создаются заново по мере просмотра, что в большой библиотеке занимает время. Ваши фото и правки не затрагиваются.", + "Use Screen Profile": "Использовать профиль экрана", + "Use sRGB": "Использовать sRGB", + "starting…": "запуск…", + "this screen's profile": "профиль этого экрана", + "Edit In": "Править в", + "Edit in PhotoCraft": "Править в PhotoCraft", + "Edit in Other Editor": "Править в другом редакторе", + "Files": "Файлы", + "Monitor": "Монитор", "Appearance": "Оформление", "Appearance Mode": "Режим оформления", "Sync with System": "Как в системе", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 85a83809806..2dd577caa7b 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2131,6 +2131,40 @@ "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.": "Спробуйте одне слово або його частину: пошук ведеться за назвами вкладок і розділів, підписами та поясненнями.", + "Choose Profile…": "Вибрати профіль…", + "Delete and Change Folder": "Видалити й змінити теку", + "Delete the smart previews in the folder used until now?": "Видалити смарт-перегляди з теки, яка використовувалася досі?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Редагувати в іншому редакторі (⌥⌘E) відкриває копію в цьому застосунку (назва застосунку в macOS, шлях до програми в інших системах).", + "External Editing": "Зовнішнє редагування", + "Found automatically": "Визначається автоматично", + "Keep": "Залишити", + "LUT-based": "На основі LUT", + "Matrix/TRC": "Матриця/TRC", + "Model installation failed": "Не вдалося встановити модель", + "Monitor profile": "Профіль монітора", + "None (the display is treated as sRGB)": "Немає (дисплей вважається sRGB)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.": "Увімкнено: кожна зміна редагувань або метаданих фото записується до файлу XMP поруч із фото, щоб її могли прочитати інші застосунки. Вимкнено: це відбувається, коли ви вибираєте «Зберегти метадані до файлу» в меню «Фото».", + "Other 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.": "Фото > Редагувати в > Редагувати в PhotoCraft (⇧⌘E або клацання фото правою кнопкою) створює копію з вашими редагуваннями, додає її до стосу з оригіналом і відкриває в PhotoCraft. Збережіть її там, і копія оновиться тут. Якщо це PSD, PhotoCraft зберігає безпосередньо в неї. Залиште розташування порожнім, якщо не використовуєте портативну версію.", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Фото відображаються через ICC-профіль вашого монітора, тому кольори правильні на каліброваних дисплеях і дисплеях із широким колірним охопленням, а подання «Деталі» використовує все охоплення дисплея. На гістограму, кеші переглядів і експорт це не впливає.", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.": "Фото, оригінали яких не під’єднано, відображаються й редагуються зі смарт-переглядів; нові можна створити лише з під’єднаних оригіналів.", + "Primaries (x, y)": "Основні кольори (x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "Профілі, призначені в налаштуваннях кольору робочого столу, зазвичай містяться в ~/.local/share/icc.", + "The download failed": "Завантаження не вдалося", + "The model's file is deleted. To use it again you download or add it again.": "Файл моделі буде видалено. Щоб використовувати її знову, завантажте або додайте її ще раз.", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.": "Мініатюри та перегляди створюються заново під час перегляду, що у великій бібліотеці потребує часу. Ваші фото й редагування не зачіпаються.", + "Use Screen Profile": "Використовувати профіль екрана", + "Use sRGB": "Використовувати sRGB", + "starting…": "запуск…", + "this screen's profile": "профіль цього екрана", + "Edit In": "Редагувати в", + "Edit in PhotoCraft": "Редагувати в PhotoCraft", + "Edit in Other Editor": "Редагувати в іншому редакторі", + "Files": "Файли", + "Monitor": "Монітор", "Appearance": "Вигляд", "Appearance Mode": "Режим вигляду", "Sync with System": "Як у системі", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ad379f1ef3c..a8189ec7fac 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -819,7 +819,7 @@ "Keywords you add appear here; ⌥1–⌥9 apply them.": "您添加的关键字会显示在此处;按 ⌥1–⌥9 即可应用。", "Landscape": "横向", "Language": "语言", - "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "“自动”按详细视图的显示大小渲染(最高为照片自身像素)。选择一个大小可设上限:越小越快。", + "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "“自动”按细节视图的显示大小渲染(最高为照片自身像素)。选择一个大小可设上限:越小越快。", "Last": "上次", "Last view": "上次视图", "Lateral Chromatic Aberration": "横向色差", @@ -1880,6 +1880,40 @@ "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.": "请尝试一个词或词的一部分:会搜索标签页和分区的名称、标签和说明。", + "Choose Profile…": "选择配置文件…", + "Delete and Change Folder": "删除并更改文件夹", + "Delete the smart previews in the folder used until now?": "要删除之前所用文件夹中的智能预览吗?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "“在其他编辑器中编辑”(⌥⌘E)会在此应用程序中打开副本(macOS 上填应用名称,其他平台填程序路径)。", + "External Editing": "外部编辑", + "Found automatically": "自动查找", + "Keep": "保留", + "LUT-based": "基于 LUT", + "Matrix/TRC": "矩阵/TRC", + "Model installation failed": "模型安装失败", + "Monitor profile": "显示器配置文件", + "None (the display is treated as sRGB)": "无(将显示器视为 sRGB)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.": "开启时,对照片的编辑或元数据所做的每次更改都会写入照片旁的 XMP 文件,供其他应用读取。关闭时,只有在“照片”菜单中选择“将元数据保存到文件”时才会写入。", + "Other 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.": "“照片 > 在应用中编辑 > 在 PhotoCraft 中编辑”(⇧⌘E,或右键单击照片)会渲染一份包含编辑效果的副本,与原图堆叠并在 PhotoCraft 中打开。在 PhotoCraft 中保存后,此处的副本会随之更新。如果副本为 PSD,PhotoCraft 会直接保存回该文件。除非使用便携版,否则请将位置留空。", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "照片会通过显示器的 ICC 配置文件显示,因此在广色域和已校准的显示器上颜色准确,细节视图也会使用显示器的全部色域。直方图、预览缓存和导出不受影响。", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.": "原图未连接的照片会通过智能预览显示和编辑;新的智能预览只能从已连接的原图生成。", + "Primaries (x, y)": "基色(x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "在桌面颜色设置中指定的配置文件通常位于 ~/.local/share/icc。", + "The download failed": "下载失败", + "The model's file is deleted. To use it again you download or add it again.": "模型文件将被删除。如需再次使用,需要重新下载或添加。", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.": "缩略图和预览会在浏览时重新生成,图库较大时需要一些时间。照片和编辑不受影响。", + "Use Screen Profile": "使用屏幕配置文件", + "Use sRGB": "使用 sRGB", + "starting…": "正在启动…", + "this screen's profile": "此屏幕的配置文件", + "Edit In": "在应用中编辑", + "Edit in PhotoCraft": "在 PhotoCraft 中编辑", + "Edit in Other Editor": "在其他编辑器中编辑", + "Files": "文件", + "Monitor": "显示器", "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 647d153d0a7..133a4e2ac0f 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1880,6 +1880,41 @@ "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.": "請嘗試一個詞或詞的一部分:會搜尋分頁和區段的名稱、標籤和說明。", + "Choose Profile…": "選擇描述檔…", + "Delete and Change Folder": "刪除並變更資料夾", + "Delete the smart previews in the folder used until now?": "要刪除先前所用資料夾中的智慧型預覽嗎?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "「在其他編輯器中編輯」(⌥⌘E)會在此應用程式中開啟副本(macOS 填應用程式名稱,其他平台填程式路徑)。", + "External Editing": "外部編輯", + "Faces": "臉部", + "Found automatically": "自動尋找", + "Keep": "保留", + "LUT-based": "以 LUT 為基礎", + "Matrix/TRC": "矩陣/TRC", + "Model installation failed": "模型安裝失敗", + "Monitor profile": "顯示器描述檔", + "None (the display is treated as sRGB)": "無(將螢幕視為 sRGB)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.": "開啟時,照片的編輯或中繼資料每次變更都會寫入照片旁的 XMP 檔案,供其他應用程式讀取。關閉時,只有在「照片」選單中選擇「將中繼資料儲存至檔案」時才會寫入。", + "Other 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.": "「照片 > 在應用程式中編輯 > 在 PhotoCraft 中編輯」(⇧⌘E,或在照片上按右鍵)會算繪一份包含編輯效果的副本,與原始照片堆疊後在 PhotoCraft 中開啟。在 PhotoCraft 中儲存後,此處的副本會隨之更新。若副本為 PSD,PhotoCraft 會直接存回該檔案。除非使用可攜版,否則請將位置留空。", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "照片會透過顯示器的 ICC 描述檔顯示,因此在廣色域及已校正的螢幕上色彩正確,詳細檢視也會使用螢幕的完整色域。色階分佈圖、預覽快取與匯出不受影響。", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.": "原始檔案未連接的照片會透過智慧型預覽顯示及編輯;新的智慧型預覽只能從已連接的原始檔案建立。", + "Primaries (x, y)": "原色(x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "在桌面色彩設定中指定的描述檔通常位於 ~/.local/share/icc。", + "The download failed": "下載失敗", + "The model's file is deleted. To use it again you download or add it again.": "模型檔案將會刪除。若要再次使用,需要重新下載或加入。", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.": "縮圖與預覽會在瀏覽時重新產生,照片庫較大時需要一些時間。照片與編輯不受影響。", + "Use Screen Profile": "使用螢幕描述檔", + "Use sRGB": "使用 sRGB", + "starting…": "正在啟動…", + "this screen's profile": "此螢幕的描述檔", + "Edit In": "在應用程式中編輯", + "Edit in PhotoCraft": "在 PhotoCraft 中編輯", + "Edit in Other Editor": "在其他編輯器中編輯", + "Files": "檔案", + "Monitor": "顯示器", "Appearance": "外觀", "Appearance Mode": "外觀模式", "Sync with System": "與系統同步", diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 109accfa9ea..473ac1d9d51 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -166,6 +166,22 @@ pub fn tr(source: &str) -> &str { tr_in(language(), source) } +/// The source (English) text a piece of interface text stands for in the current language, or +/// the text itself when it stands for none (it is English already, or was never a message). For +/// names that scripts and tests look things up by, which must not change with the language. +/// When two messages read alike in a language, the first in the catalog's order is given. +pub fn source_of(text: &str) -> &str { + source_of_in(language(), text) +} + +fn source_of_in(language: Locale, text: &str) -> &str { + language + .catalog() + .iter() + .find(|(source, translation)| translation.as_str() == text && !source.contains('|')) + .map_or(text, |(source, _)| source.as_str()) +} + /// [`tr`] for a message whose translation depends on where it appears: a catalog entry keyed /// `"|"` wins, else the plain message. A language adds the contextual entry only /// where its shared translation reads wrongly there (Japanese はい / いいえ as a rule's value). @@ -430,6 +446,17 @@ pub fn rules_label(rules: &lightcraft_catalog::RuleSet, catalog: &lightcraft_cat #[cfg(test)] mod tests { + /// A section's name for scripts is its English one whatever the language shows. + #[test] + fn interface_text_is_traced_back_to_its_source() { + let german = super::Locale::De.tr("Library").to_string(); + assert_ne!(german, "Library", "German has a word of its own for it"); + assert_eq!(super::source_of_in(super::Locale::De, &german), "Library"); + assert_eq!(super::source_of_in(super::Locale::De, "Library"), "Library", "English text is itself"); + assert_eq!(super::source_of_in(super::Locale::En, "Library"), "Library"); + assert_eq!(super::source_of_in(super::Locale::De, "no such message"), "no such message"); + } + use super::*; #[test] @@ -834,7 +861,7 @@ mod tests { let mut labels: Vec<&str> = lightcraft_engine::command_specs().iter().map(|spec| spec.label).collect(); labels.extend(crate::menus::ui_commands().map(|command| command.1).filter(|label| !Locale::ALL.iter().any(|locale| locale.name() == *label))); labels.extend(lightcraft_develop::CONTROLS.iter().map(|control| control.label)); - labels.extend(crate::panels::settings::TABS.iter().map(|(_, label)| *label)); + labels.extend(crate::panels::settings::TABS.iter().map(|(id, label)| crate::panels::settings::tab_label(id, label))); for (_, label, kind) in lightcraft_catalog::rules::FIELDS { labels.push(label); labels.extend(lightcraft_catalog::rules::ops_for(*kind).iter().map(|(_, label)| *label)); diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rs index a1a720a8e07..2bf1b6bf1e5 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -1074,7 +1074,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { } _ => "Add in place: the library references the files where they are; nothing is copied or moved.", })) - .color(if d.copy && d.move_files { t.caution } else { t.text_dim }) + .color(if d.copy && d.move_files { t.text_caution() } else { t.text_dim }) .small(), ); register(ui.ctx(), "label:importModeHelp", r.rect); @@ -1131,7 +1131,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let t = Tokens::get(ui.ctx()); match lightcraft_engine::rename::folder_template_error(&d.folder_template) { Some(e) => { - ui.label(egui::RichText::new(e).color(t.caution)); + ui.label(egui::RichText::new(e).color(t.text_caution())); } None => unknown_tags_warning(ui, &d.folder_template), } @@ -1327,8 +1327,9 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial p.rect_filled(br, 3.0, Color32::from_rgba_unmultiplied(170, 60, 50, 220)); p.galley(br.min + vec2(4.0, 2.0), g, Color32::WHITE); } - let name = if c.name.chars().count() > 18 { format!("{}…", c.name.chars().take(17).collect::()) } else { c.name.clone() }; - p.text(pos2(rect.left() + 2.0, img.bottom() + 9.0), Align2::LEFT_CENTER, name, t.font(10.5), if ok { t.text_label } else { t.text_dim }); + // (shortened in the middle to the cell's width: the end of a name is the number of the frame) + let name = crate::readout::elide_middle(&c.name, rect.width() - 4.0, |s| p.layout_no_wrap(s.to_string(), t.caption(), t.text_label).size().x); + p.text(pos2(rect.left() + 2.0, img.bottom() + 9.0), Align2::LEFT_CENTER, name, t.caption(), if ok { t.text_label } else { t.text_dim }); let tip = format!( "{}\n{} × {} · {} · {:.1} MB{}", c.path, @@ -1357,7 +1358,7 @@ fn badge_rect(img: Rect, cb: Rect, text: Vec2) -> Rect { /// Reserve the actual translated tag button width beside a template field. pub(crate) fn tag_field_width(ui: &egui::Ui) -> f32 { let t = Tokens::get(ui.ctx()); - let galley = ui.painter().layout_no_wrap(crate::i18n::tr("Tags").to_string(), t.semibold(11.5), t.text); + let galley = ui.painter().layout_no_wrap(crate::i18n::tr("Tags").to_string(), t.caption_strong(), t.text); (ui.available_width() - (galley.size().x + 18.0).max(37.0) - ui.spacing().item_spacing.x).max(80.0) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 37fb86df31e..82377b9d22a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -27,6 +27,7 @@ pub mod merge; mod model_setup; pub mod panels; pub mod pick; +mod readout; pub mod region; pub mod render; pub mod shortcuts; @@ -63,6 +64,22 @@ mod tests_date_picker; #[cfg(test)] mod tests_dialog_fit; #[cfg(test)] +mod tests_dialog_settings; +#[cfg(test)] +mod tests_dialog_settings_contrast; +#[cfg(test)] +mod tests_dialog_settings_filter; +#[cfg(test)] +mod tests_dialog_settings_filter_words; +#[cfg(test)] +mod tests_dialog_settings_groups; +#[cfg(test)] +mod tests_dialog_settings_keys; +#[cfg(test)] +mod tests_dialog_settings_tabs; +#[cfg(test)] +mod tests_dialog_settings_trust; +#[cfg(test)] mod tests_dialogs; #[cfg(test)] mod tests_error_kinds; @@ -123,6 +140,16 @@ mod tests_temp_slider; #[cfg(test)] mod tests_titlebar; #[cfg(test)] +mod tests_type_contrast; +#[cfg(test)] +mod tests_type_fit; +#[cfg(test)] +mod tests_type_on_photo; +#[cfg(test)] +mod tests_type_readout; +#[cfg(test)] +mod tests_type_scale; +#[cfg(test)] mod tests_unsaved; #[cfg(test)] mod tests_wb_selector; @@ -221,7 +248,7 @@ pub struct Services { /// The host's current log file (`/logs/lightcraft.log`), which Help ▸ Open Log /// Folder reveals (#260). None where no log is kept: the web, `--memory`, `LIGHTCRAFT_NO_PREFS`. pub log_file: Option, - /// Choose a folder (Settings → General → Open Library…; desktop only). + /// Choose a folder (Settings → Library → Open Library…; desktop only). pub pick_folder: Option, /// Open a Lightroom Classic `.lrcat` catalog for read-only import. pub pick_lightroom_catalog: Option, diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index 7b0d449c699..4a477cc7872 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -95,7 +95,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if hidden > 0 || (app.activity_expanded && tasks.len() > MAX_ROWS) { ui.add_space(4.0); let text = if hidden > 0 { tr_format!("+{n} more", n = hidden) } else { tr("Show less").to_string() }; - let r = ui.add(egui::Label::new(RichText::new(text).font(t.font(11.0)).color(t.accent)).sense(Sense::click())); + let r = ui.add(egui::Label::new(RichText::new(text).font(t.font(11.0)).color(t.text_link())).sense(Sense::click())); register(ui.ctx(), "activity:more", r.rect); toggle = r.clicked(); } @@ -126,7 +126,7 @@ fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { ui.allocate_ui_with_layout(vec2(label_w, 18.0), Layout::left_to_right(Align::Center), |ui| { // the whole width, so the cross lands at the right edge however short the name ui.set_width(label_w); - ui.add(egui::Label::new(RichText::new(tr(&task.label)).font(t.font(12.5)).color(t.text)).truncate()); + ui.add(egui::Label::new(RichText::new(tr(&task.label)).font(t.body()).color(t.text)).truncate()); }); if cross { let (rect, resp) = ui.allocate_exact_size(vec2(CROSS, CROSS), Sense::click()); diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index 4aacfaead61..3ee311c2ac2 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -325,7 +325,7 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo x += g.size().x + 10.0; } let name = photo.copy_name.as_ref().map(|c| format!("{} ({c})", photo.file_name)).unwrap_or(photo.file_name.clone()); - let g = pt.layout_no_wrap(name, t.font(11.5), t.text_dim); + let g = pt.layout_no_wrap(name, t.caption(), t.text_dim); let name_w = g.size().x; if x + name_w + 110.0 < cap.right() { pt.galley(pos2(x, cap.center().y - g.size().y / 2.0), g, t.text_dim); diff --git a/crates/ui-egui/src/panels/denoise.rs b/crates/ui-egui/src/panels/denoise.rs index 75488f76b04..e5ee3aff205 100644 --- a/crates/ui-egui/src/panels/denoise.rs +++ b/crates/ui-egui/src/panels/denoise.rs @@ -147,7 +147,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am let state = app.session.denoise_photo_state(id); let pad = egui::Margin { left: 24, right: 22, top: 0, bottom: 6 }; let note = |ui: &mut egui::Ui, text: &str, color: egui::Color32| { - ui.add(egui::Label::new(RichText::new(crate::i18n::tr(text)).size(11.0).color(color)).wrap()); + ui.add(egui::Label::new(RichText::new(crate::i18n::tr(text)).font(t.caption()).color(color)).wrap()); }; match state { PhotoState::NotApplicable | PhotoState::Ready => {} @@ -199,7 +199,8 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am } else { tr("Starting…").to_string() }; - let bar = ui.add(egui::ProgressBar::new(frac).desired_width(ui.available_width().min(240.0)).text(RichText::new(text).size(11.0))); + let bar = + ui.add(egui::ProgressBar::new(frac).desired_width(ui.available_width().min(240.0)).text(RichText::new(text).font(t.caption()))); register(ui.ctx(), "denoise:progress", bar.rect); }); } @@ -333,7 +334,7 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V done = done, total = total ); - let bar = ui.add(egui::ProgressBar::new(frac).desired_width(380.0).text(RichText::new(text).size(11.5))); + let bar = ui.add(egui::ProgressBar::new(frac).desired_width(380.0).text(RichText::new(text).font(t.caption()))); register(ui.ctx(), "denoise:settingsProgress", bar.rect); } None if queued > 0 => hint(ui, t, &count(queued, "photo waiting", "photos waiting")), @@ -413,25 +414,27 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, ui.label(RichText::new(m["name"].as_str().unwrap_or("")).color(t.text)); let size = mb(m["sizeBytes"].as_u64()); if !size.is_empty() { - ui.label(RichText::new(size).color(t.text_dim)); + ui.label(RichText::new(size).color(t.legible(t.text_dim, t.chrome, 4.5))); } if selected { - ui.label(RichText::new(tr("in use")).color(t.accent)); + ui.label(RichText::new(tr("in use")).color(t.legible(t.accent, t.chrome, 4.5))); } else if installed { - ui.label(RichText::new(tr("installed")).color(t.text_dim)); + ui.label(RichText::new(tr("installed")).color(t.legible(t.text_dim, t.chrome, 4.5))); } }); - ui.label(RichText::new(licence_line(m)).font(t.font(11.5)).color(if m["licence"]["commercial"] == "yes" { + ui.label(RichText::new(licence_line(m)).font(t.caption()).color(if m["licence"]["commercial"] == "yes" { t.text_dim } else { t.caution })); match m["accepted"]["selfTest"].as_object() { Some(test) if test.get("ok").and_then(Value::as_bool) == Some(true) => { - ui.label(RichText::new(tr("Tested and works on this computer")).font(t.font(11.5)).color(t.text_dim)); + ui.label( + RichText::new(tr("Tested and works on this computer")).font(t.caption()).color(t.legible(t.text_dim, t.chrome, 4.5)), + ); } Some(_) => { - ui.label(RichText::new(tr("Failed its last test")).font(t.font(11.5)).color(t.caution)); + ui.label(RichText::new(tr("Failed its last test")).font(t.caption()).color(t.legible(t.caution, t.chrome, 4.5))); } None => {} } @@ -444,15 +447,17 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, } else { tr_format!("{} of {} from {host}", mb(Some(got)), mb(Some(total)), host = host) }; - let bar = ui.add(egui::ProgressBar::new(frac).desired_width(260.0).text(RichText::new(text).font(t.font(11.5)))); + let bar = ui.add(egui::ProgressBar::new(frac).desired_width(260.0).text(RichText::new(text).font(t.caption()))); register(ui.ctx(), format!("denoise:progress:{id}"), bar.rect); } (Some("done" | "installing"), _) => { - ui.label(RichText::new(tr("Downloaded and checked. Installing…")).font(t.font(11.5)).color(t.text_dim)); + ui.label( + RichText::new(tr("Downloaded and checked. Installing…")).font(t.caption()).color(t.legible(t.text_dim, t.chrome, 4.5)), + ); } (Some("failed"), Some(d)) => { let why = sentence(d["error"].as_str().unwrap_or("The download failed")); - ui.add(egui::Label::new(RichText::new(why).font(t.font(11.5)).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(why).font(t.caption()).color(t.legible(t.caution, t.chrome, 4.5))).wrap()); } _ => {} } @@ -461,6 +466,13 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, if installed { let r = ui.button(tr("Remove")); register(ui.ctx(), format!("denoise:remove:{id}"), r.rect); + let r = super::settings::ask_first( + t, + &format!("denoise:remove:{id}"), + r, + "The model's file is deleted. To use it again you download or add it again.", + "Remove", + ); if r.clicked() { let _ = app.run("denoise.models.remove", json!({"id": id})); app.caches.denoise.epoch += 1; @@ -636,7 +648,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info let kind = info["kind"].as_str().unwrap_or("unsupported"); let file = info["fileName"].as_str().unwrap_or(""); if kind == "unsupported" { - ui.label(RichText::new(tr("This file cannot be used yet")).font(t.semibold(13.5)).color(t.caution)); + ui.label(RichText::new(tr("This file cannot be used yet")).font(t.body_strong()).color(t.legible(t.caution, t.chrome, 4.5))); ui.add( egui::Label::new( RichText::new(sentence(tr(info["reason"].as_str().unwrap_or("It is not a denoise model LightCraft understands")))) @@ -644,16 +656,19 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info ) .wrap(), ); - ui.label(RichText::new(tr_format!("{file} · {size}", file = file, size = mb(info["sizeBytes"].as_u64()))).color(t.text_dim)); + ui.label( + RichText::new(tr_format!("{file} · {size}", file = file, size = mb(info["sizeBytes"].as_u64()))) + .color(t.legible(t.text_dim, t.chrome, 4.5)), + ); return; } let m = &info["model"]; ui.horizontal(|ui| { ui.label(RichText::new(m["name"].as_str().unwrap_or(file)).font(t.semibold(14.0)).color(t.text)); - ui.label(RichText::new(mb(info["sizeBytes"].as_u64())).color(t.text_dim)); + ui.label(RichText::new(mb(info["sizeBytes"].as_u64())).color(t.legible(t.text_dim, t.chrome, 4.5))); }); if info["alreadyInstalled"] == true { - ui.label(RichText::new(tr("Already installed. Remove it before installing a replacement.")).color(t.text_dim)); + ui.label(RichText::new(tr("Already installed. Remove it before installing a replacement.")).color(t.legible(t.text_dim, t.chrome, 4.5))); } let download = info["download"].is_string(); if download { @@ -672,20 +687,30 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info ); } let commercial = m["licence"]["commercial"].as_str().unwrap_or("unknown"); - ui.label(RichText::new(licence_line(m)).font(t.semibold(12.5)).color(if commercial == "yes" { t.text } else { t.caution })); + ui.label(RichText::new(licence_line(m)).font(t.body_strong()).color(if commercial == "yes" { t.text } else { t.text_caution() })); let notice = m["licence"]["notice"].as_str().unwrap_or(""); if !notice.is_empty() { ui.add(egui::Label::new(RichText::new(notice).color(t.text_label)).wrap()); } let provenance = m["provenance"].as_str().unwrap_or(""); if !provenance.is_empty() { - ui.add(egui::Label::new(RichText::new(tr_format!("Trained on: {provenance}", provenance = provenance)).color(t.text_dim)).wrap()); + ui.add( + egui::Label::new( + RichText::new(tr_format!("Trained on: {provenance}", provenance = provenance)).color(t.legible(t.text_dim, t.chrome, 4.5)), + ) + .wrap(), + ); } if kind == "draft" { ui.add_space(2.0); ui.label(RichText::new(tr("LightCraft does not know this model, so it assumed:")).color(t.text_label)); for a in info["assumptions"].as_array().into_iter().flatten().filter_map(Value::as_str) { - ui.add(egui::Label::new(RichText::new(tr_format!("• {assumption}", assumption = tr(a))).font(t.font(12.0)).color(t.text_dim)).wrap()); + ui.add( + egui::Label::new( + RichText::new(tr_format!("• {assumption}", assumption = tr(a))).font(t.font(12.0)).color(t.legible(t.text_dim, t.chrome, 4.5)), + ) + .wrap(), + ); } } if let Some(url) = m["source"].as_str().or(m["licence"]["url"].as_str()) { @@ -702,5 +727,5 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info } else { "The model is kept on this computer only. LightCraft never uploads or shares it." }; - ui.label(RichText::new(tr(closing)).font(t.font(11.5)).color(t.text_dim)); + ui.label(RichText::new(tr(closing)).font(t.caption()).color(t.legible(t.text_dim, t.chrome, 4.5))); } diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 151d4a57a2e..5cb4d3d2918 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -606,7 +606,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if app.ui.soft_proof && !fullscreen { p.rect_filled(canvas, 0.0, Color32::from_gray(238)); let label = crate::i18n::tr_format!("Proof Preview · {}", app.ui.proof.space.label()); - p.text(pos2(canvas.right() - 16.0, canvas.top() + 14.0), Align2::RIGHT_CENTER, label, t.font(12.5), Color32::from_gray(60)); + p.text(pos2(canvas.right() - 16.0, canvas.top() + 14.0), Align2::RIGHT_CENTER, label, t.label(), Color32::from_gray(60)); } let shown; if split { @@ -621,7 +621,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { p.text(label_at(img_rect, main_area), Align2::LEFT_CENTER, crate::i18n::tr("After"), t.font(12.0), t.text_dim); } else if show_before { shown = draw(Slot::Before, img_rect, canvas); - p.text(pos2(img_rect.left() + 8.0, img_rect.top() + 14.0), Align2::LEFT_CENTER, crate::i18n::tr("Before"), t.font(12.0), t.text); + crate::widgets::on_photo_label(&p, pos2(img_rect.left() + 8.0, img_rect.top() + 8.0), crate::i18n::tr("Before"), t.label()); } else if let Some((_key, label)) = &hover_key && let Some(tex) = app.renderer.textures.get(&Slot::Hover).filter(|t| t.photo == id) { @@ -824,22 +824,10 @@ fn info_overlay(app: &LightcraftApp, p: &egui::Painter, canvas: Rect, photo: &li } InfoOverlay::Exposure => { let m = &photo.meta; - let mut exp = Vec::new(); - if !m.shutter.is_empty() { - exp.push(format!("{} s", m.shutter)); - } - if let Some(a) = m.aperture { - exp.push(format!("f/{a:.1}")); - } - if let Some(i) = m.iso { - exp.push(format!("ISO {i}")); - } - if let Some(f) = m.focal_mm { - exp.push(format!("{f:.0} mm")); - } + let exp = crate::readout::exposure(m); let camera = [m.camera.as_str(), m.lens.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::>().join(" · "); let mut v = vec![photo.file_name.clone()]; - v.push(if exp.is_empty() { "No exposure information".into() } else { exp.join(" ") }); + v.push(if exp.is_empty() { "No exposure information".into() } else { exp.join(" · ") }); if !camera.is_empty() { v.push(camera); } @@ -849,7 +837,7 @@ fn info_overlay(app: &LightcraftApp, p: &egui::Painter, canvas: Rect, photo: &li let t = Tokens::get(p.ctx()); let mut y = canvas.top() + 12.0; for (i, l) in lines.iter().enumerate() { - let font = if i == 0 { t.semibold(15.0) } else { t.font(12.5) }; + let font = if i == 0 { t.semibold(15.0) } else { t.body() }; let g = p.layout_no_wrap(l.clone(), font, Color32::WHITE); let at = pos2(canvas.left() + 14.0, y); // a soft shadow keeps the text readable on bright photos @@ -1596,7 +1584,7 @@ fn rotate_cursor_turn(pts: &[Pos2], q: Pos2, inside: bool) -> f32 { fn angle_readout(ui: &egui::Ui, at: Pos2, angle: f64, bounds: Rect) { let t = Tokens::get(ui.ctx()); let p = top_painter(ui, "crop-angle-readout"); - let galley = p.layout_no_wrap(crop_angle_label(angle), t.font(12.5), Color32::WHITE); + let galley = p.layout_no_wrap(crop_angle_label(angle), t.body(), Color32::WHITE); let rect = readout_rect(at, galley.size() + vec2(12.0, 6.0), bounds); p.rect_filled(rect, 4.0, Color32::from_black_alpha(170)); p.galley(rect.min + vec2(6.0, 3.0), galley, Color32::WHITE); @@ -2250,10 +2238,11 @@ fn eye_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response // ------------------------------------------------------------------------ filmstrip -/// A filmstrip cell's file-name label: names longer than 14 characters are cut to 13 and an -/// ellipsis. Counts characters, not bytes, so a CJK name is never cut inside a character (#266). -fn film_label(name: &str) -> String { - if name.chars().nth(14).is_some() { format!("{}…", name.chars().take(13).collect::()) } else { name.to_string() } +/// A file name over a filmstrip cell, in the room left of the format: shortened in the middle +/// when it is too long, so that the number at its end stays ("IMG_2024…3012"). It lost its end +/// after 13 characters, however wide they were. +fn film_label(name: &str, room: f32, width: impl Fn(&str) -> f32) -> String { + crate::readout::elide_middle(name, room, width) } pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { @@ -2266,7 +2255,7 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { let ppp = ui.ctx().pixels_per_point(); if ids.is_empty() { let why = if app.session.filter != Default::default() { "No photos match the filters (View → Clear Filters)" } else { "No photos" }; - ui.painter().text(r.center(), Align2::CENTER_CENTER, why, t.font(12.5), t.text_dim); + ui.painter().text(r.center(), Align2::CENTER_CENTER, why, t.label(), t.text_dim); return; } let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r.shrink2(vec2(0.0, 4.0)))); @@ -2301,12 +2290,19 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { } else { t.canvas }; - p.rect_filled(cr, 0.0, crate::theme::label_background(base, label, selected)); + let fill = crate::theme::label_background(base, label, selected); + p.rect_filled(cr, 0.0, fill); + // (a selected cell is lighter than the canvas the dim text is made for, or darker, and + // a colour label tints any cell; under the pointer the fill is see-through, and what + // the text is on is that fill over the strip) + let dim = t.legible(t.text_dim, t.canvas.blend(fill), 4.5); let names = app.ui.settings.film_names; if let Some(ph) = app.session.catalog.photo(*id).filter(|_| names) { let name = ph.file_name.rsplit_once('.').map(|(n, _)| n).unwrap_or(&ph.file_name); - p.text(pos2(cr.left() + 8.0, cr.top() + 10.0), Align2::LEFT_CENTER, film_label(name), t.font(10.0), t.text_dim); - p.text(pos2(cr.right() - 8.0, cr.top() + 10.0), Align2::RIGHT_CENTER, &ph.format, t.semibold(8.5), t.text_dim); + let format = p.text(pos2(cr.right() - 8.0, cr.top() + 10.0), Align2::RIGHT_CENTER, &ph.format, t.micro(), dim); + let room = format.left() - 6.0 - (cr.left() + 8.0); + let shown = film_label(name, room, |s| p.layout_no_wrap(s.to_string(), t.micro(), dim).size().x); + p.text(pos2(cr.left() + 8.0, cr.top() + 10.0), Align2::LEFT_CENTER, shown, t.micro(), dim); } let img_area = Rect::from_min_max(cr.min + vec2(10.0, 22.0), cr.max - vec2(10.0, 8.0)); super::grid::request_thumb(app, *id, (256.0 * ppp.min(2.0) / 2.0) as usize * 2, 8); @@ -2323,12 +2319,12 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { if app.ui.settings.film_badges && let Some(ph) = app.session.catalog.photo(*id) { - film_badges(p, &t, fr, ph); + film_badges(p, fr, ph); } if let Some(st) = app.session.catalog.stack_of(*id) { let text = if st.collapsed { st.photos.len().to_string() } else { format!("{}/{}", st.position(*id).unwrap_or(0) + 1, st.photos.len()) }; - let g = p.layout_no_wrap(text, t.semibold(9.5), Color32::WHITE); + let g = p.layout_no_wrap(text, t.micro_strong(), Color32::WHITE); let br = Rect::from_min_size(fr.min + vec2(3.0, 3.0), vec2(g.size().x + 22.0, 15.0)); p.rect_filled(br, 7.5, Color32::from_black_alpha(170)); crate::icons::paint(p, Rect::from_min_size(br.min + vec2(4.0, 2.0), vec2(11.0, 11.0)), crate::icons::Icon::Stack, Color32::WHITE); @@ -2365,7 +2361,7 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { } /// Rating, flag and edited badges along a filmstrip thumbnail's bottom edge (Settings → Interface). -fn film_badges(p: &egui::Painter, t: &Tokens, fr: Rect, ph: &lightcraft_catalog::Photo) { +fn film_badges(p: &egui::Painter, fr: Rect, ph: &lightcraft_catalog::Photo) { use crate::icons::{Icon, paint}; use lightcraft_catalog::Flag; let edited = ph.is_edited(); @@ -2373,20 +2369,36 @@ fn film_badges(p: &egui::Painter, t: &Tokens, fr: Rect, ph: &lightcraft_catalog: return; } let bar = Rect::from_min_max(pos2(fr.left(), fr.bottom() - 15.0), fr.right_bottom()); - p.rect_filled(bar, 0.0, Color32::from_black_alpha(130)); + // (a picture has no theme: its marks are in one light ink on a shade as wide as they are, + // not in the theme's star and label colours, which are dark in the light themes) + let ink = Tokens::on_photo(); + let clipped = p.with_clip_rect(bar.intersect(p.clip_rect())); + let p = &clipped; + let shade = |from: f32, to: f32| { + if to > from { + p.rect_filled(Rect::from_min_max(pos2(from, bar.top() + 1.0), pos2(to, bar.bottom() - 1.0)), 3.0, Tokens::photo_shade()); + } + }; + let marks_w = ph.rating as f32 * 9.0 + if ph.flag == Flag::None { 0.0 } else { 12.0 }; + if marks_w > 0.0 { + shade(bar.left() + 1.0, (bar.left() + 5.0 + marks_w).min(bar.right())); + } + if edited { + shade((bar.right() - 16.0).max(bar.left()), bar.right() - 1.0); + } let y = bar.center().y; let mut x = bar.left() + 3.0; for i in 0..ph.rating { - paint(p, Rect::from_min_size(pos2(x + i as f32 * 9.0, y - 4.0), vec2(8.0, 8.0)), Icon::StarFilled, t.star); + paint(p, Rect::from_min_size(pos2(x + i as f32 * 9.0, y - 4.0), vec2(8.0, 8.0)), Icon::StarFilled, ink); } x += ph.rating as f32 * 9.0 + 2.0; match ph.flag { - Flag::Pick => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagPick, t.pick), - Flag::Reject => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagReject, t.reject), + Flag::Pick => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagPick, ink), + Flag::Reject => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagReject, Tokens::on_photo_reject()), Flag::None => {} } if edited { - paint(p, Rect::from_min_size(pos2(bar.right() - 13.0, y - 5.0), vec2(10.0, 10.0)), Icon::Sliders, t.text_label); + paint(p, Rect::from_min_size(pos2(bar.right() - 13.0, y - 5.0), vec2(10.0, 10.0)), Icon::Sliders, ink); } } @@ -2622,14 +2634,17 @@ mod tests { #[test] fn film_labels_cut_on_characters_not_bytes() { - // the name from #266: byte 13 falls inside '限' - assert_eq!(film_label("202407層三限定訂閱圖(4)"), "202407層三限定訂閱圖…"); - assert_eq!(film_label("写真"), "写真"); + // (a character is a unit wide here; the cell has room for 14) + let label = |name: &str| film_label(name, 14.0, |s| s.chars().count() as f32); + // the name from #266: no cut falls inside a character + assert_eq!(label("202407層三限定訂閱圖(4)"), "202407…定訂閱圖(4)"); + assert_eq!(label("写真"), "写真"); // exactly 14 characters (42 bytes) is shown whole - assert_eq!(film_label("一二三四五六七八九十一二三四"), "一二三四五六七八九十一二三四"); - assert_eq!(film_label("IMG_20240712_153012"), "IMG_20240712_…"); - assert_eq!(film_label("DSC_0001"), "DSC_0001"); - assert_eq!(film_label(""), ""); + assert_eq!(label("一二三四五六七八九十一二三四"), "一二三四五六七八九十一二三四"); + // the number of the frame stays + assert_eq!(label("IMG_20240712_153012"), "IMG_20…_153012"); + assert_eq!(label("DSC_0001"), "DSC_0001"); + assert_eq!(label(""), ""); } /// With the photo flipped, the crop box's corners reach the screen mirrored; the dimming diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index a79261fdc7f..20bf9bd14b0 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -330,7 +330,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let l = line.trim_end(); if let Some(h) = l.strip_prefix("### ") { ui.add_space(6.0); - ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(12.5)).color(t.text)); + ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.body_strong()).color(t.text)); } else if let Some(h) = l.strip_prefix("## ") { ui.add_space(8.0); ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(14.0)).color(t.text)); @@ -391,7 +391,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { } for (g, list) in &groups { ui.add_space(6.0); - ui.label(egui::RichText::new(g).font(t.semibold(12.5)).color(t.text)); + ui.label(egui::RichText::new(g).font(t.body_strong()).color(t.text)); egui::Grid::new(format!("meta-{g}")).num_columns(2).spacing([16.0, 3.0]).striped(true).show(ui, |ui| { for (n, v) in list { ui.label(egui::RichText::new(n).color(t.text_dim)); @@ -423,7 +423,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { .color(t.text_dim), ); } else { - ui.label(egui::RichText::new(crate::i18n::tr("Fix the marked rules to save this album.")).color(t.caution)); + ui.label(egui::RichText::new(crate::i18n::tr("Fix the marked rules to save this album.")).color(t.text_caution())); } } Dialog::NewSmartAlbum { name, .. } => { @@ -957,7 +957,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { }); ui.label( egui::RichText::new(crate::i18n::tr("The first time, macOS asks whether LightCraft may control Photos.")) - .size(11.0) + .font(t.caption()) .color(t.text_dim), ); } @@ -987,7 +987,9 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { } Dialog::Merge { opts } => crate::merge::body(app, ui, opts), Dialog::Import { opts } => crate::import::body(app, ui, opts), - Dialog::Settings { tab } => crate::panels::settings::body(app, ui, tab), + // (Settings is never taller than `body_max`, so the scroll area round it never + // scrolls: its tab bar stays put and its pages scroll by themselves) + Dialog::Settings { tab } => crate::panels::settings::window(app, ui, tab, body_max), Dialog::SamModel { error, .. } => sam_model_body(app, ui, error.as_deref()), Dialog::KeywordTag { editing, @@ -1162,7 +1164,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { 1 => crate::credits::contributors_ui(app, ui), 2 => crate::credits::models_ui(ui), _ => { - ui.label(egui::RichText::new("LightCraft").font(t.semibold(20.0)).color(t.text)); + ui.label(egui::RichText::new("LightCraft").font(t.display_strong()).color(t.text)); ui.label(crate::i18n::tr_format!("Version {} — a clean-room, pure-Rust photo library and raw developer.", env!("CARGO_PKG_VERSION"))); ui.label(crate::i18n::tr_format!( "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.", diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 533354b6c56..ce12ce16722 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -107,8 +107,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::hover()); ui.painter().text(pos2(hr.left() + 24.0, hr.bottom() - 10.0), Align2::LEFT_CENTER, crate::i18n::tr("Edit"), t.semibold(15.0), t.text); egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 8, bottom: 14 }).show(ui, |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(8.0, 6.0); if text_button(ui, "auto", crate::i18n::tr("Auto"), false).clicked() { let _ = app.run("develop.auto", json!({})); app.toast(ui.ctx(), crate::i18n::tr("Auto settings applied")); @@ -124,9 +124,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { { let _ = app.run("develop.hdr", json!({"enabled": !d.hdr.enabled})); } + // (Reset at the right of the row when it has room there, else on a row of its own: in + // German it is "Zurücksetzen" and lay over HDR) + let reset = crate::i18n::tr("Reset"); + if ui.available_size_before_wrap().x < crate::widgets::text_button_width(ui, reset) { + ui.end_row(); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if text_button(ui, "reset", crate::i18n::tr("Reset"), false).on_hover_text(crate::i18n::tr("Reset all edits (Cmd+Shift+R)")).clicked() - { + if text_button(ui, "reset", reset, false).on_hover_text(crate::i18n::tr("Reset all edits (Cmd+Shift+R)")).clicked() { reset_clicked = true; } }); @@ -144,7 +149,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if app.session.auto_sync && n > 1 { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 0, bottom: 10 }).show(ui, |ui| { ui.horizontal(|ui| { - ui.label(egui::RichText::new(crate::i18n::tr_format!("Auto Sync: edits apply to {n} photos", n = n)).color(t.accent).size(12.0)); + ui.label( + egui::RichText::new(crate::i18n::tr_format!("Auto Sync: edits apply to {n} photos", n = n)).color(t.text_link()).font(t.label()), + ); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if text_button(ui, "autoSyncOff", crate::i18n::tr("Turn Off"), false).clicked() { let _ = app.run("develop.autoSync", json!({"on": false})); @@ -368,7 +375,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if lp && !has_lens { ui.label( egui::RichText::new(crate::i18n::tr("No lens data embedded in this file (DNG lens opcodes only).")) - .size(11.0) + .font(t.caption()) .color(Tokens::get(ui.ctx()).text_dim), ); } @@ -441,7 +448,7 @@ fn profile_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) } }; let heading = |ui: &mut egui::Ui, s: &str| { - ui.label(egui::RichText::new(crate::i18n::tr(s)).font(t.semibold(11.5)).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr(s)).font(t.caption_strong()).color(t.text_dim)); }; for (title, key, ids) in [("Favorites", "fav", app.session.profile_favorites.clone()), ("Recent", "recent", app.session.profile_recent.clone())] { let list: Vec<_> = ids.iter().filter_map(|id| app.session.profile_info(id).map(|(name, _)| (id.as_str(), name))).collect(); @@ -612,8 +619,8 @@ fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { bar(a + 1.0, z - 1.0, Color32::from_rgb(c[0], c[1], c[2])); } let y = plot.bottom() + 18.0; - p.text(pos2((plot.left() + x0) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("SDR"), t.font(12.5), t.text_label); - p.text(pos2((x0 + plot.right()) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("HDR"), t.font(12.5), t.text_label); + p.text(pos2((plot.left() + x0) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("SDR"), t.body(), t.text_label); + p.text(pos2((x0 + plot.right()) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("HDR"), t.body(), t.text_label); let info = Rect::from_center_size(pos2(plot.right() - 16.0, y), vec2(14.0, 14.0)); paint(p, info, Icon::Info, t.text_label); ui.interact(info, egui::Id::new("hdrHistogramInfo"), Sense::hover()).on_hover_text(crate::i18n::tr( @@ -691,21 +698,10 @@ fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // EXIF strip if let Some(ph) = app.session.catalog.photo(id) { let m = &ph.meta; - let parts: Vec = [ - m.iso.map(|i| format!("ISO {i}")), - m.focal_mm.map(|f| format!("{f:.0}mm")), - m.aperture.map(|a| format!("f/{a:.1}")), - if m.shutter.is_empty() { None } else { Some(m.shutter.clone()) }, - ] - .into_iter() - .flatten() - .collect(); - - if !parts.is_empty() { - let text = parts.join(" · "); + if let Some(text) = crate::readout::exposure_line(m) { let y = r.bottom() - 13.0; let x = r.left() + r.width() / 2.0; - p.text(pos2(x, y), Align2::CENTER_CENTER, text, t.font(12.5), t.text_label); + p.text(pos2(x, y), Align2::CENTER_CENTER, text, t.body(), t.text_label); } } } @@ -1313,7 +1309,7 @@ fn point_color(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) }); if n == 0 { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 2, bottom: 8 }).show(ui, |ui| { - ui.label(egui::RichText::new(crate::i18n::tr("Pick a colour on the photo with the eyedropper.")).size(12.0).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr("Pick a colour on the photo with the eyedropper.")).font(t.label()).color(t.text_dim)); }); return; } @@ -1650,7 +1646,7 @@ fn paint_wheel(p: &egui::Painter, c: Pos2, rad: f32) { fn quick_develop(app: &mut LightcraftApp, ui: &mut egui::Ui, n: usize) { let t = Tokens::get(ui.ctx()); egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 0, bottom: 10 }).show(ui, |ui| { - ui.label(egui::RichText::new(crate::i18n::tr_format!("Quick Develop · {n} photos", n = n)).color(t.text_label).size(12.5)); + ui.label(egui::RichText::new(crate::i18n::tr_format!("Quick Develop · {n} photos", n = n)).color(t.text_label).font(t.body())); ui.add_space(4.0); let rows: [(&str, &str, f64, f64); 9] = [ ("Exposure", "light.exposure", 1.0 / 3.0, 1.0), @@ -1665,9 +1661,9 @@ fn quick_develop(app: &mut LightcraftApp, ui: &mut egui::Ui, n: usize) { ]; egui::Grid::new("quick-develop").num_columns(5).spacing([4.0, 3.0]).show(ui, |ui| { for (label, ctl, small, big) in rows { - ui.label(egui::RichText::new(crate::i18n::tr(label)).size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr(label)).font(t.caption()).color(t.text_dim)); for (txt, d) in [("◀◀", -big), ("◀", -small), ("▶", small), ("▶▶", big)] { - let r = ui.add(egui::Button::new(egui::RichText::new(txt).size(10.0)).min_size(egui::vec2(28.0, 18.0))); + let r = ui.add(egui::Button::new(egui::RichText::new(txt).font(t.micro())).min_size(egui::vec2(28.0, 18.0))); crate::widgets::register(ui.ctx(), format!("button:quick-{ctl}-{txt}"), r.rect); if r.on_hover_text(crate::i18n::tr_format!("{label} {d:+} on every selected photo", d = d, label = crate::i18n::tr(label))) .clicked() diff --git a/crates/ui-egui/src/panels/faces.rs b/crates/ui-egui/src/panels/faces.rs index 2b3fe0329af..d003b5228cc 100644 --- a/crates/ui-egui/src/panels/faces.rs +++ b/crates/ui-egui/src/panels/faces.rs @@ -147,7 +147,7 @@ pub fn setup_banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 6)).show(ui, |ui| { ui.horizontal_wrapped(|ui| { - ui.label(RichText::new(message).font(t.font(12.5)).color(t.text_dim)); + ui.label(RichText::new(message).font(t.label()).color(t.text_dim)); let r = ui.button(button); register(ui.ctx(), "faces:setup", r.rect); if r.clicked() { @@ -254,7 +254,7 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { }); // what is wrong with the user's own catalog (catalog.json in the models folder), if anything for e in list["catalog"]["errors"].as_array().into_iter().flatten().filter_map(Value::as_str).take(3) { - ui.add(egui::Label::new(RichText::new(format!("catalog.json: {e}")).font(t.font(11.5)).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(format!("catalog.json: {e}")).font(t.caption()).color(t.legible(t.caution, t.chrome, 4.5))).wrap()); } if let Some(d) = all.iter().find(|m| m["role"] == "detector") { ui.add_space(4.0); @@ -271,7 +271,7 @@ fn scan_progress(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } let text = format!("Scanning photos for faces: {left} left · {faces} faces so far"); let bar = ui.add( - egui::ProgressBar::new((1.0 - left as f32 / peak as f32).clamp(0.0, 1.0)).desired_width(380.0).text(RichText::new(text).font(t.font(11.5))), + egui::ProgressBar::new((1.0 - left as f32 / peak as f32).clamp(0.0, 1.0)).desired_width(380.0).text(RichText::new(text).font(t.caption())), ); register(ui.ctx(), "faces:scanProgress", bar.rect); } @@ -293,12 +293,12 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, ui.label(RichText::new(size).color(t.text_dim)); } if selected { - ui.label(RichText::new("in use").color(t.accent)); + ui.label(RichText::new("in use").color(t.text_link())); } else if installed { ui.label(RichText::new("installed").color(t.text_dim)); } }); - ui.label(RichText::new(licence_line(m)).font(t.font(11.5)).color(if m["licence"]["commercial"] == "yes" { + ui.label(RichText::new(licence_line(m)).font(t.caption()).color(if m["licence"]["commercial"] == "yes" { t.text_dim } else { t.caution @@ -314,7 +314,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, None => (speed.map(str::to_string), true), }; if let Some(line) = line { - ui.label(RichText::new(line).font(t.font(11.5)).color(if ok { t.text_dim } else { t.caution })); + ui.label(RichText::new(line).font(t.caption()).color(if ok { t.text_dim } else { t.text_caution() })); } match (dl_state, dl) { (Some("running"), Some(d)) => { @@ -325,15 +325,15 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, } else { format!("{} of {} from {host}", mb(Some(got)), mb(Some(total))) }; - let bar = ui.add(egui::ProgressBar::new(frac).desired_width(260.0).text(RichText::new(text).font(t.font(11.5)))); + let bar = ui.add(egui::ProgressBar::new(frac).desired_width(260.0).text(RichText::new(text).font(t.caption()))); register(ui.ctx(), format!("faces:progress:{id}"), bar.rect); } (Some("done"), _) => { - ui.label(RichText::new("Downloaded and checked. Installing…").font(t.font(11.5)).color(t.text_dim)); + ui.label(RichText::new("Downloaded and checked. Installing…").font(t.caption()).color(t.text_dim)); } (Some("failed"), Some(d)) => { let why = sentence(d["error"].as_str().unwrap_or("The download failed")); - ui.add(egui::Label::new(RichText::new(why).font(t.font(11.5)).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(why).font(t.caption()).color(t.text_caution())).wrap()); } _ => {} } @@ -342,6 +342,13 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, if installed { let r = ui.button("Remove"); register(ui.ctx(), format!("faces:remove:{id}"), r.rect); + let r = super::settings::ask_first( + t, + &format!("faces:remove:{id}"), + r, + "The model's file is deleted. To use it again you download or add it again.", + "Remove", + ); if r.clicked() { let _ = app.run("faces.models.remove", json!({"id": id})); app.caches.faces_epoch += 1; @@ -403,7 +410,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info let kind = info["kind"].as_str().unwrap_or("unsupported"); let file = info["fileName"].as_str().unwrap_or(""); if kind == "unsupported" { - ui.label(RichText::new("This file cannot be used yet").font(t.semibold(13.5)).color(t.caution)); + ui.label(RichText::new("This file cannot be used yet").font(t.body_strong()).color(t.text_caution())); ui.add( egui::Label::new( RichText::new(sentence(info["reason"].as_str().unwrap_or("It is not a face recognition model LightCraft understands"))) @@ -438,7 +445,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info ); } let commercial = m["licence"]["commercial"].as_str().unwrap_or("unknown"); - ui.label(RichText::new(licence_line(m)).font(t.semibold(12.5)).color(if commercial == "yes" { t.text } else { t.caution })); + ui.label(RichText::new(licence_line(m)).font(t.body_strong()).color(if commercial == "yes" { t.text } else { t.text_caution() })); let notice = m["licence"]["notice"].as_str().unwrap_or(""); if !notice.is_empty() { ui.add(egui::Label::new(RichText::new(notice).color(t.text_label)).wrap()); @@ -468,7 +475,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info } else { "The model is kept on this computer only. LightCraft never uploads or shares it." }; - ui.label(RichText::new(closing).font(t.font(11.5)).color(t.text_dim)); + ui.label(RichText::new(closing).font(t.caption()).color(t.text_dim)); } /// Pressing Download: the model's terms first, in the same dialog as a model file. Accepting them starts the download; @@ -634,7 +641,7 @@ pub fn name_editor( } } if let Some(label) = setup.short() { - let b = ui.add(egui::Button::new(RichText::new(label).font(t.font(12.0)).color(t.accent)).frame(false)); + let b = ui.add(egui::Button::new(RichText::new(label).font(t.font(12.0)).color(t.text_link())).frame(false)); register(ui.ctx(), "faces:setup", b.rect); if b.clicked() { outcome = Editor::Setup; diff --git a/crates/ui-egui/src/panels/filterbar.rs b/crates/ui-egui/src/panels/filterbar.rs index c0962b59f13..f7c3e7a0951 100644 --- a/crates/ui-egui/src/panels/filterbar.rs +++ b/crates/ui-egui/src/panels/filterbar.rs @@ -14,6 +14,8 @@ use crate::widgets::register; pub const HEIGHT: f32 = 40.0; /// Bar width (points) below which the controls take two rows. const WIDE: f32 = 1240.0; +/// Between two controls of a row. +const GAP: f32 = 4.0; /// Colour-label swatches (UI colours, our own choice). pub use crate::theme::label_color; @@ -61,7 +63,7 @@ fn picker(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, current: &str, a ui, &format!("filter-{id}"), if active && matches!(id, "camera" | "lens" | "keyword") { current } else { crate::i18n::tr(current) }, - t.font(12.5), + t.label(), if active { t.text } else { t.text_label }, ); if active { @@ -94,9 +96,30 @@ fn picker(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, current: &str, a pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - // one row when there is room, else the metadata pickers and actions go to a second row - let two_rows = ui.available_width() < WIDE; - let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), if two_rows { 2.0 * HEIGHT - 8.0 } else { HEIGHT }), Sense::hover()); + // How wide the three parts of the bar were when last drawn (rating, flag and label; type and + // edited; the metadata pickers and the buttons): their words are longer in some languages, + // and what a row holds follows what fits, not a width that suits English. + let widths_id = egui::Id::new("filterbar:widths"); + let seen: [f32; 3] = ui.data(|d| d.get_temp(widths_id)).unwrap_or([0.0; 3]); + let room = ui.available_width() - 32.0; + // One row when there is room, else the metadata pickers and actions go to a second row. Type + // and edited go down with them when they would run off the first, and stand on a row of + // their own between the two when they fit on neither. + // (Each part is measured from where it begins, so it measures the same on whichever row it + // stands, and parts that share a row have a gap between them: what fits is then a matter of + // the widths alone, and the bar comes to rest. Measured with the gap before it, a part was + // four points wider when it followed another, and in that band the bar changed its mind + // every frame.) + let [first, second, third] = seen; + let two_rows = ui.available_width() < WIDE || first + GAP + second + GAP + third > room; + let (second_row, third_row) = match (two_rows, first + GAP + second <= room, second + GAP + third <= room) { + (false, _, _) => (0, 0), + (true, true, _) => (0, 1), + (true, false, true) => (1, 1), + (true, false, false) => (1, 2), + }; + let rows = third_row as f32 + 1.0; + let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), rows * (HEIGHT - 8.0) + 8.0), Sense::hover()); ui.painter().rect_filled(bar, 0.0, t.chrome); ui.painter().line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.divider)); register(ui.ctx(), "filterbar", bar); @@ -104,12 +127,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let row = |ui: &mut egui::Ui, i: f32| { let r = Rect::from_min_size(bar.min + vec2(16.0, 4.0 + i * (HEIGHT - 8.0)), vec2(bar.width() - 32.0, HEIGHT - 8.0)); let mut c = ui.new_child(egui::UiBuilder::new().max_rect(r).layout(egui::Layout::left_to_right(egui::Align::Center))); - c.spacing_mut().item_spacing.x = 4.0; + c.spacing_mut().item_spacing.x = GAP; c }; - let mut row1 = row(ui, 0.0); - let mut row2 = row(ui, 1.0); - let ui = &mut row1; + let mut rows = [row(ui, 0.0), row(ui, 1.0), row(ui, 2.0)]; + let [ui, ..] = &mut rows; + let began = ui.cursor().left(); // rating: operator + stars caption(ui, "Rating"); @@ -196,8 +219,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } ui.add_space(14.0); + let first_w = ui.min_rect().right() - began; // kind + edited + let Some(ui) = rows.get_mut(second_row) else { return }; + let began = ui.cursor().left(); let kind_label = match f.kind { None => "All types", Some(MediaKind::Image) => "Photos", @@ -249,8 +275,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { .collect(), ); + let second_w = ui.min_rect().right() - began; + // metadata pickers - let ui: &mut egui::Ui = if two_rows { &mut row2 } else { &mut row1 }; + let Some(ui) = rows.get_mut(third_row) else { return }; + let began = ui.cursor().left(); let values = app.caches.filter_values(&app.session.catalog); let (cameras, lenses, keywords) = (values.cameras.clone(), values.lenses.clone(), values.keywords.clone()); for (id, key, all_label, current, values) in [ @@ -268,20 +297,26 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // save / clear ui.add_space(14.0); let filtering = app.session.filter != Default::default(); - let save = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Save as Smart Album…")).font(t.font(12.5)))); + let save = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Save as Smart Album…")).font(t.label()))); register(ui.ctx(), "button:filterSave", save.rect); if save.clicked() { let _ = app.run("dialog.newSmartAlbum", json!({})); } - let clear = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Clear")).font(t.font(12.5)))); + let clear = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Clear")).font(t.label()))); register(ui.ctx(), "button:filterClear", clear.rect); if clear.clicked() { app.ui.search.clear(); let _ = app.run("library.clearFilter", json!({})); } // filter presets: apply one, save the current filter, delete - let presets = ui.button(egui::RichText::new(crate::i18n::tr("Presets ▾")).font(t.font(12.5))); + let presets = ui.button(egui::RichText::new(crate::i18n::tr("Presets ▾")).font(t.label())); register(ui.ctx(), "button:filterPresets", presets.rect); + let now = [first_w, second_w, ui.min_rect().right() - began]; + // (a number that is none would never equal itself: it is not kept, nor asked about again) + if now.iter().all(|w| w.is_finite()) && now.iter().zip(seen).any(|(now, seen)| (now - seen).abs() > 0.5) { + ui.data_mut(|d| d.insert_temp(widths_id, now)); + ui.ctx().request_repaint(); + } egui::Popup::menu(&presets).show(|ui| { let names: Vec = app.session.filter_presets.iter().map(|f| f.name.clone()).collect(); for n in &names { diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 52edfa460c2..c4666e49990 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -155,13 +155,13 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover()); ui.painter().rect_filled(hr, 0.0, t.canvas); let full = crate::i18n::source_title(&app.session); - let count_w = ui.painter().layout_no_wrap(cnt.clone(), t.font(12.5), t.text_dim).size().x; + let count_w = ui.painter().layout_no_wrap(cnt.clone(), t.label(), t.text_dim).size().x; // the title gives way to the count: a long album or folder name is trimmed, in full on hover let room = (hr.width() - 20.0 - count_w - 36.0).max(0.0); - let font = t.semibold(17.0); + let font = t.display_strong(); let title = crate::widgets::elide_head(&full, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text).size().x); let title_rect = ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, &title, font, t.text); - let count_rect = ui.painter().text(pos2(hr.right() - 20.0, hr.center().y), Align2::RIGHT_CENTER, cnt, t.font(12.5), t.text_dim); + let count_rect = ui.painter().text(pos2(hr.right() - 20.0, hr.center().y), Align2::RIGHT_CENTER, cnt, t.label(), t.text_dim); crate::widgets::register(ui.ctx(), "grid:title", title_rect); crate::widgets::register(ui.ctx(), "grid:count", count_rect); if title != full { @@ -475,7 +475,7 @@ fn group_header(app: &mut LightcraftApp, ui: &mut egui::Ui, run: &DateRun, ids: pos2(x + gw + 10.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::tr_format!("· {n} photo{}", if n == 1 { "" } else { "s" }, n = n), - t.font(12.5), + t.label(), t.text_dim, ); if resp.clicked() { @@ -616,29 +616,31 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square if square && app.ui.show_filenames { let m = &photo.meta; let name = match app.ui.grid_info.as_str() { - "exposure" => { - let parts: Vec = [ - // whole seconds read "8 s"; fractions as written ("1/250") - (!m.shutter.is_empty()) - .then(|| if m.shutter.contains('/') || m.shutter.ends_with('s') { m.shutter.clone() } else { format!("{} s", m.shutter) }), - m.aperture.map(|a| format!("f/{a:.1}").replace(".0", "")), - m.iso.map(|i| format!("ISO {i}")), - m.focal_mm.map(|f| format!("{f:.0} mm")), - ] - .into_iter() - .flatten() - .collect(); - if parts.is_empty() { "—".to_string() } else { parts.join(" · ") } - } + "exposure" => crate::readout::exposure_line(m).unwrap_or_else(|| "—".to_string()), "date" => photo.captured.as_deref().map(crate::i18n::display_time).unwrap_or_else(|| crate::i18n::tr("No date").into()), _ => photo.file_name.rsplit_once('.').map(|(n, _)| n.to_string()).unwrap_or(photo.file_name.clone()), }; - p.text(pos2(r.left() + 8.0, r.top() + 12.0), Align2::LEFT_CENTER, name, t.font(10.5), t.text_dim); let fmt = photo.format.clone(); - let g = p.layout_no_wrap(fmt, t.semibold(9.0), t.text_label); + // (the format's chip is dark in every theme, so its letters are light in every theme: in + // the light themes they were the label colour, dark on dark) + let chip = Color32::from_gray(26); + let ink = t.ink_on(chip); + let g = p.layout_no_wrap(fmt, t.micro_strong(), ink); let br = Rect::from_min_size(pos2(r.right() - g.size().x - 14.0, r.top() + 5.0), g.size() + vec2(8.0, 3.0)); - p.rect_filled(br, 2.0, Color32::from_gray(26)); - p.galley(br.min + vec2(4.0, 1.5), g, t.text_label); + // (a chosen cell is lighter than the cell the dim text is made for, or darker, and a + // colour label tints either: the line is made legible on the cell as it is) + let base = if selected { t.cell_selected } else { t.cell }; + let dim = t.legible(t.text_dim, crate::theme::label_background(base, photo.label, selected), 4.5); + // (the line ends before the format: it used to run on under it) + let line = crate::widgets::one_line(p, &name, t.caption(), dim, br.left() - 6.0 - (r.left() + 8.0)); + p.galley(pos2(r.left() + 8.0, r.top() + 12.0 - line.size().y / 2.0), line, dim); + p.rect_filled(br, 2.0, chip); + p.galley(br.min + vec2(4.0, 1.5), g, ink); + } + // (a rejected photo is dimmed under its marks, not over them: over them it took the flag's + // red down with the photo, to under 3:1 on the shade) + if photo.flag == Flag::Reject { + p.rect_filled(img_rect, 0.0, Color32::from_black_alpha(110)); } let show_badges = match app.ui.settings.grid_badges { crate::state::GridBadges::Auto => resp.hovered() || selected || photo.rating > 0 || photo.flag != Flag::None || photo.label.is_some(), @@ -653,22 +655,47 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square } if show_badges { let bar = badge_bar; + // A picture has no theme: its marks are in one light ink on a shade, not in the theme's + // star and label colours (dark in the light themes). Each group of marks has a shade as + // wide as it is, so that a rated photo keeps its lower edge; shade and marks end where + // the photo ends (on a narrow one they ran on over the gap to the next). Under the + // pointer and on a chosen photo the band along the lower edge is there as it was: it is + // what says "this one", and in the light themes the outline of a chosen photo alone + // hardly shows. + let ink = Tokens::on_photo(); + let (marks_w, flag_w) = (photo.rating as f32 * 13.0, if photo.flag == Flag::None { 0.0 } else { 18.0 }); + let right_w = if photo.is_edited() { 20.0 } else { 0.0 } + if photo.label.is_some() { 20.0 } else { 0.0 }; + let clipped = p.with_clip_rect(bar.intersect(p.clip_rect())); + let p = &clipped; if (resp.hovered() || selected) && (square || photo.label.is_none()) { p.rect_filled(bar, 0.0, Color32::from_black_alpha(120)); } + let shade = |from: f32, to: f32| { + if to > from { + p.rect_filled(Rect::from_min_max(pos2(from, bar.top() + 3.0), pos2(to, bar.bottom() - 3.0)), 4.0, Tokens::photo_shade()); + } + }; + if marks_w + flag_w > 0.0 { + shade(bar.left() + 3.0, (bar.left() + 9.0 + marks_w + flag_w).min(bar.right())); + } + if right_w > 0.0 { + shade((bar.right() - right_w - 6.0).max(bar.left()), bar.right() - 3.0); + } let mut x = bar.left() + 6.0; for i in 0..photo.rating { - paint(p, Rect::from_min_size(pos2(x + i as f32 * 13.0, bar.center().y - 6.0), vec2(12.0, 12.0)), Icon::StarFilled, t.star); + paint(p, Rect::from_min_size(pos2(x + i as f32 * 13.0, bar.center().y - 6.0), vec2(12.0, 12.0)), Icon::StarFilled, ink); } x += photo.rating as f32 * 13.0 + 4.0; match photo.flag { - Flag::Pick => paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagPick, t.pick), - Flag::Reject => paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagReject, t.reject), + Flag::Pick => paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagPick, ink), + Flag::Reject => { + paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagReject, Tokens::on_photo_reject()) + } Flag::None => {} } let mut right = bar.right(); if photo.is_edited() { - paint(p, Rect::from_min_size(pos2(right - 20.0, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::Sliders, t.text_label); + paint(p, Rect::from_min_size(pos2(right - 20.0, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::Sliders, ink); right -= 20.0; } if let Some(l) = photo.label { @@ -677,7 +704,7 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square } if let Some(name) = &photo.copy_name { // virtual copy: a folded-corner tag at the top right - let g = p.layout_no_wrap(name.clone(), t.semibold(10.5), Color32::WHITE); + let g = p.layout_no_wrap(name.clone(), t.micro_strong(), Color32::WHITE); let tr = if square { img_rect.right_top() + vec2(-6.0, 6.0) } else { img_rect.right_top() + vec2(-5.0, 5.0) }; let br = Rect::from_min_max(pos2(tr.x - g.size().x - 26.0, tr.y), pos2(tr.x, tr.y + 20.0)); p.rect_filled(br, 10.0, Color32::from_black_alpha(165)); @@ -695,7 +722,7 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square if let Some(why) = &photo.preview_only { // a raw shown from its embedded JPEG: a small amber "Preview" pill at the image's bottom // left, above the badge bar (always shown: it changes what editing does) - let g = p.layout_no_wrap(crate::i18n::tr("Preview").into(), t.semibold(9.5), Color32::WHITE); + let g = p.layout_no_wrap(crate::i18n::tr("Preview").into(), t.micro_strong(), Color32::WHITE); let at = pos2(img_rect.left() + 6.0, img_rect.bottom() - 30.0 - 16.0); let br = Rect::from_min_size(at, vec2(g.size().x + 24.0, 16.0)); p.rect_filled(br, 8.0, Color32::from_black_alpha(170)); @@ -705,9 +732,6 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square ui.interact(br, egui::Id::new(("preview-only-badge", id.0)), Sense::hover()) .on_hover_text(crate::i18n::tr_format!("Preview only — {}", crate::widgets::preview_only_explanation(why))); } - if photo.flag == Flag::Reject { - p.rect_filled(img_rect, 0.0, Color32::from_black_alpha(110)); - } // interaction if let Some(k) = app.ui.keyword_painter.clone() { // painting: a click toggles the keyword on this photo @@ -757,12 +781,12 @@ fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engi ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 8.0; let count_w = - ui.painter().layout_no_wrap(cnt.to_owned(), t.font(12.5), t.text_dim).size().x.ceil().min((ui.available_width() * 0.45).floor()); + ui.painter().layout_no_wrap(cnt.to_owned(), t.label(), t.text_dim).size().x.ceil().min((ui.available_width() * 0.45).floor()); let path_w = (ui.available_width() - count_w - 8.0).max(0.0).floor(); ui.allocate_ui_with_layout(vec2(path_w, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { folder_breadcrumbs(app, ui, &b.path); }); - let count = ui.add_sized(vec2(count_w, 24.0), egui::Label::new(egui::RichText::new(cnt).size(12.5).color(t.text_dim)).truncate()); + let count = ui.add_sized(vec2(count_w, 24.0), egui::Label::new(egui::RichText::new(cnt).font(t.label()).color(t.text_dim)).truncate()); register(ui.ctx(), "grid:count", count.rect); count.on_hover_text(cnt); }); @@ -779,7 +803,7 @@ fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engi if local_n > 0 { let label = crate::i18n::tr_format!("Add {local_n} to My Photos", local_n = local_n); let button = - ui.add(egui::Button::new(egui::RichText::new(label).font(t.semibold(11.5)).color(t.text)).wrap().min_size(vec2(37.0, 24.0))); + ui.add(egui::Button::new(egui::RichText::new(label).font(t.caption_strong()).color(t.text)).wrap().min_size(vec2(37.0, 24.0))); register(ui.ctx(), "button:addToLibrary", button.rect); if button.clicked() { let local: Vec = ids.iter().filter(|id| app.session.catalog.photo(**id).is_some_and(|p| p.local)).map(|id| id.0).collect(); @@ -836,7 +860,7 @@ fn folder_breadcrumbs(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str) { let last = remaining == 1; // Share the bounded row among the remaining crumbs, leaving room for every separator. let width = ((ui.available_width() - separator_w * (remaining - 1) as f32) / remaining as f32).max(0.0).floor(); - let text = egui::RichText::new(*part).size(13.0).color(if last { t.text } else { t.text_label }); + let text = egui::RichText::new(*part).font(t.body()).color(if last { t.text } else { t.text_label }); let r = ui.add_sized(vec2(width, 24.0), egui::Label::new(if last { text.strong() } else { text }).truncate().sense(Sense::click())); register(ui.ctx(), format!("crumb:{i}"), r.rect); if !last { @@ -848,7 +872,7 @@ fn folder_breadcrumbs(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str) { { let _ = app.run("library.browse", json!({"path": to})); } - ui.label(egui::RichText::new("›").size(13.0).color(t.text_dim)); + ui.label(egui::RichText::new("›").font(t.body()).color(t.text_dim)); } r.on_hover_text(path); } diff --git a/crates/ui-egui/src/panels/keymap.rs b/crates/ui-egui/src/panels/keymap.rs index a844b7b24cc..ce9ddbbd8dc 100644 --- a/crates/ui-egui/src/panels/keymap.rs +++ b/crates/ui-egui/src/panels/keymap.rs @@ -40,7 +40,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { d.insert_temp(search_id, search.clone()); d.insert_temp(all_id, show_all); }); - ui.label(RichText::new(crate::i18n::tr("Click a shortcut, then press the new keys (Esc cancels).")).size(11.0).color(t.text_dim)); + ui.label(RichText::new(crate::i18n::tr("Click a shortcut, then press the new keys (Esc cancels).")).font(t.caption()).color(t.text_dim)); ui.add_space(4.0); let needle = search.trim().to_lowercase(); @@ -122,7 +122,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, b: &Bindable, sc: apply(app, ui.ctx(), serde_json::json!({"id": b.id, "reset": true})); } }); - ui.label(RichText::new(b.id).size(10.5).color(t.text_dim)); + ui.label(RichText::new(b.id).font(t.caption()).color(t.text_dim)); ui.end_row(); } @@ -161,7 +161,7 @@ fn fixed_keys(app: &LightcraftApp, ui: &mut egui::Ui, t: &Tokens, mac: bool, nee return; } ui.add_space(8.0); - ui.label(RichText::new(crate::i18n::tr("Fixed keys")).font(t.semibold(12.5)).color(t.text)); + ui.label(RichText::new(crate::i18n::tr("Fixed keys")).font(t.body_strong()).color(t.text)); let taken: Vec<_> = app.ui.settings.keymap.values().filter_map(|s| shortcuts::parse(s)).collect(); egui::Grid::new("shortcuts-fixed").striped(true).num_columns(2).spacing([12.0, 4.0]).show(ui, |ui| { for (sc, label) in fixed { diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index fcaab2926e9..28939b2fa73 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -111,11 +111,11 @@ fn row_sensed( icon, if selected { t.text } else { t.icon }, ); - let font = t.font(13.5); + let font = t.body(); let color = if selected { t.text } else { t.text_label }; // a count of nothing is there, but fainter: the rows that hold photos stand out let count_color = |n: usize| if n == 0 { t.text_dim.gamma_multiply(0.55) } else { t.text_dim }; - let count_galley = count.filter(|_| app.ui.show_counts).map(|n| ui.painter().layout_no_wrap(n.to_string(), t.font(12.5), count_color(n))); + let count_galley = count.filter(|_| app.ui.show_counts).map(|n| crate::readout::figures(ui.painter(), &n.to_string(), t.label(), count_color(n))); let label_left = r.left() + 42.0 + indent; let count_left = count_galley.as_ref().map_or(edge - 18.0, |g| edge - 18.0 - g.size().x); // a label's dot sits just before the count @@ -306,7 +306,7 @@ fn empty_hint(ui: &mut egui::Ui, section: SidebarSection) { let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); register(ui.ctx(), format!("sidebarEmpty:{}", section.id()), r); let text = crate::i18n::tr(section.empty_hint()); - let galley = ui.painter().layout_no_wrap(text.to_string(), t.font(12.5), t.text_dim); + let galley = ui.painter().layout_no_wrap(text.to_string(), t.label(), t.text_dim); note_width(ui, 42.0 + galley.size().x + 18.0); ui.painter().galley(pos2(r.left() + 42.0, r.center().y - galley.size().y / 2.0), galley, t.text_dim); } @@ -436,14 +436,14 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSe register(ui.ctx(), format!("{widget}Chevron:{id}"), Rect::from_center_size(c, vec2(14.0, 14.0))); let col = if hovered { t.text } else { t.text_dim }; ui.painter().add(egui::Shape::convex_polygon(triangle_points(c, open), col, egui::Stroke::NONE)); - ui.painter().text(pos2(r.left() + 18.0, r.center().y), Align2::LEFT_CENTER, title, t.semibold(13.5), t.text_label); + ui.painter().text(pos2(r.left() + 18.0, r.center().y), Align2::LEFT_CENTER, title, t.title_strong(), t.text_label); let button = header_button(section); // (an album being dragged puts "Top Level" in the Albums header) let room = !(section == SidebarSection::Albums && app.ui.dragging_album.is_some()); if !open && rows > 0 && app.ui.show_counts && room { // folded: how much is in there (left of the header's own button) let right = edge - 18.0 - if button.is_some() { HEADER_BUTTON + 4.0 } else { 0.0 }; - let count = ui.painter().text(pos2(right, r.center().y), Align2::RIGHT_CENTER, rows.to_string(), t.font(12.5), t.text_dim); + let count = ui.painter().text(pos2(right, r.center().y), Align2::RIGHT_CENTER, rows.to_string(), t.label(), t.text_dim); register(ui.ctx(), format!("{widget}Count:{id}"), count); } if section == SidebarSection::Albums { @@ -1473,7 +1473,7 @@ fn top_level_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, header: Rec ui.painter().rect_stroke(header.shrink2(vec2(8.0, 3.0)), 4.0, stroke, egui::StrokeKind::Inside); // right-aligned, left of the + button let edge = header.right().min(ui.clip_rect().right()); - ui.painter().text(pos2(edge - 56.0, header.center().y), Align2::RIGHT_CENTER, crate::i18n::tr("Top Level"), t.font(12.5), t.text_dim); + ui.painter().text(pos2(edge - 56.0, header.center().y), Align2::RIGHT_CENTER, crate::i18n::tr("Top Level"), t.label(), t.text_dim); if over && ui.input(|i| i.pointer.primary_released()) { drop_album(app, ui, dragged, None); } diff --git a/crates/ui-egui/src/panels/library_problem.rs b/crates/ui-egui/src/panels/library_problem.rs index 212e57d9045..d404640ac94 100644 --- a/crates/ui-egui/src/panels/library_problem.rs +++ b/crates/ui-egui/src/panels/library_problem.rs @@ -113,9 +113,9 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { ui.label(RichText::new(crate::i18n::tr("LightCraft couldn't find where to keep your library.")).color(t.text)); } else { ui.label(RichText::new(crate::i18n::tr("LightCraft couldn't open the library at")).color(t.text_label)); - ui.label(RichText::new(&problem.path).font(t.semibold(12.5)).color(t.text)); + ui.label(RichText::new(&problem.path).font(t.body_strong()).color(t.text)); } - ui.add(egui::Label::new(RichText::new(&problem.error).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(&problem.error).color(t.text_caution())).wrap()); ui.label( RichText::new( "Your photos and edits in it are untouched. You can try again (e.g. after closing another program that has it open \ @@ -173,7 +173,7 @@ pub fn banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.horizontal_centered(|ui| { let r = ui.label( RichText::new(crate::i18n::tr("Temporary session — your library isn't open, and nothing you do here is saved.")) - .font(t.semibold(12.5)) + .font(t.body_strong()) .color(t.canvas), ); register(ui.ctx(), "indicator:temporarySession", r.rect); diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index 26577524a7b..3008691abc9 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -9,7 +9,7 @@ use super::edit::apply_slider_out; use super::right::header; use crate::LightcraftApp; use crate::icons::{Icon, paint}; -use crate::theme::Tokens; +use crate::theme::{TextSize, Tokens}; use crate::widgets::{divider, icon_button, one_line, register, slider, text_button}; const fn spec(id: &'static str, label: &'static str, min: f64, max: f64, step: f64, decimals: u8, track: Track) -> ControlSpec { @@ -66,7 +66,7 @@ const TILE_PAD: f32 = 3.0; /// Columns, tile width and label size of the Create New Mask grid in `width`, `label(size)` being /// the widest label at a font size: four tiles of up to 52 pt (at least 48), else three, else two — -/// the first that fits the labels at 10.5 pt, or at 9.5 pt before a column is dropped. A tile grows +/// the first that fits the labels at caption size, or at micro size before a column is dropped. A tile grows /// past 52 pt for a long (translated) label. In a panel too narrow even for that, two tiles whose /// labels are cut short. fn tile_layout(width: f32, label: impl Fn(f32) -> f32) -> (usize, f32, f32) { @@ -76,14 +76,14 @@ fn tile_layout(width: f32, label: impl Fn(f32) -> f32) -> (usize, f32, f32) { if n == 4 && w < 48.0 { continue; } - for size in [10.5, 9.5] { + for size in [TextSize::Caption.points(), TextSize::Micro.points()] { let need = (label(size) + 2.0 * TILE_PAD).ceil(); if need <= w { return (n, w.min(TILE.max(need)), size); } } } - (2, room(2).max(24.0), 9.5) + (2, room(2).max(24.0), TextSize::Micro.points()) } pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { @@ -250,7 +250,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let icon = m.components.first().map(|c| kind_label(&c.shape).1).unwrap_or(Icon::Mask); paint(ui.painter(), Rect::from_min_size(r.min + vec2(8.0, 7.0), vec2(16.0, 16.0)), icon, t.text_label); // a long name is cut short (with …) before the eye, the full name on hover - let color = if m.visible { t.text } else { t.text_disabled }; + // (a hidden mask's name is still read: dimmer, not the colour of what cannot be used) + let color = if m.visible { t.text } else { t.text_dim }; let g = one_line(ui.painter(), &m.name, t.font(13.0), color, r.width() - 32.0 - 32.0); let elided = g.elided; let at = pos2(r.left() + 32.0, r.center().y - g.size().y / 2.0); @@ -454,7 +455,7 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { let view = MaskView::parse(&app.ui.mask_overlay_mode).unwrap_or_default(); ui.horizontal(|ui| { ui.label(egui::RichText::new(crate::i18n::tr("Overlay")).color(t.text_dim)); - let r = crate::widgets::dropdown(ui, "maskOverlayMode", menu_label(view.label()), t.font(12.5), t.text_label); + let r = crate::widgets::dropdown(ui, "maskOverlayMode", menu_label(view.label()), t.body(), t.text_label); egui::Popup::menu(&r).show(|ui| { for v in MaskView::ALL { if ui.selectable_label(v == view, menu_label(v.label())).clicked() { @@ -509,7 +510,7 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape }; match shape { MaskShape::LuminanceRange { lo, hi, lo_feather, hi_feather } => { - ui.label(egui::RichText::new(crate::i18n::tr("Select Luminance Range")).color(t.text_dim).size(11.5)); + ui.label(egui::RichText::new(crate::i18n::tr("Select Luminance Range")).color(t.text_dim).font(t.caption())); let (lo, hi) = (*lo, *hi); let w = ui.available_width().min(240.0); let (rect, resp) = ui.allocate_exact_size(vec2(w, 18.0), Sense::click_and_drag()); @@ -607,14 +608,14 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape } app.run("mask.update", json!({"component": comp, "shape": s})) }); - ui.label(egui::RichText::new(crate::i18n::tr("− harder border · + softer border")).color(t.text_dim).size(11.0)); + ui.label(egui::RichText::new(crate::i18n::tr("− harder border · + softer border")).color(t.text_dim).font(t.caption())); } MaskShape::ColorRange { samples, refine } => { ui.horizontal(|ui| { ui.label( egui::RichText::new(crate::i18n::tr_format!("{} sample{}", samples.len(), if samples.len() == 1 { "" } else { "s" })) .color(t.text_dim) - .size(11.5), + .font(t.caption()), ); let picking = app.ui.tool == "colorRange"; if text_button(ui, &format!("colorPick{comp}"), crate::i18n::tr("Pick"), picking) @@ -894,16 +895,16 @@ mod tests { /// room by dropping a column rather than drawing it past its tile. #[test] fn tile_labels_get_the_room_they_need() { - let short = |size: f32| size * 4.0; // "Luminance"-ish: 42 pt at 10.5 - let long = |size: f32| size * 5.6; // "Background"/"Hintergrund": 59 pt at 10.5, 53 at 9.5 - assert_eq!(tile_layout(224.0, short), (4, 51.0, 10.5)); + let short = |size: f32| size * 4.0; // "Luminance"-ish: 44 pt at 11 + let long = |size: f32| size * 5.6; // "Background"/"Hintergrund": 62 pt at 11, 56 at 10 + assert_eq!(tile_layout(224.0, short), (4, 51.0, 11.0)); // too wide for four at either size: three tiles, wider than 52 so the label fits let (n, w, size) = tile_layout(224.0, long); - assert_eq!((n, size), (3, 10.5)); - assert!(w >= long(10.5) + 2.0 * TILE_PAD && w <= (224.0 - 2.0 * TILE_GAP) / 3.0, "{w}"); - // a smaller label keeps a column: 9.5 pt fits where 10.5 doesn't - let mid = |size: f32| size * 4.6; // 48.3 at 10.5, 43.7 at 9.5 - assert_eq!(tile_layout(224.0, mid), (4, 51.0, 9.5)); + assert_eq!((n, size), (3, 11.0)); + assert!(w >= long(11.0) + 2.0 * TILE_PAD && w <= (224.0 - 2.0 * TILE_GAP) / 3.0, "{w}"); + // a smaller label keeps a column: 10 pt fits where 11 doesn't + let mid = |size: f32| size * 4.4; // 48.4 at 11, 44 at 10 + assert_eq!(tile_layout(224.0, mid), (4, 51.0, 10.0)); // a wide panel: tiles stay 52 pt (or as wide as the label) assert_eq!(tile_layout(474.0, short).0, 4); assert_eq!(tile_layout(474.0, short).1, TILE); diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index a8d99aed288..a3aba1a548f 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -82,7 +82,7 @@ pub fn toast(app: &mut LightcraftApp, ctx: &egui::Context) { let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("toast"))); // long messages (a save warning, the web build's notices) wrap within the canvas let wrap = (canvas.width() - 80.0).clamp(200.0, 720.0); - let (background, foreground) = label.map(crate::theme::label_toast_colors).unwrap_or((egui::Color32::from_black_alpha(200), t.text)); + let (background, foreground) = label.map(crate::theme::label_toast_colors).unwrap_or((Tokens::photo_shade(), Tokens::on_photo())); let foreground = foreground.gamma_multiply(fade); let galley = painter.layout(text, t.font(14.0), foreground, wrap); let size = vec2(galley.size().x + 40.0, (galley.size().y + 22.0).max(40.0)); diff --git a/crates/ui-egui/src/panels/people.rs b/crates/ui-egui/src/panels/people.rs index 6fdf032f307..ca3fe8fd0d2 100644 --- a/crates/ui-egui/src/panels/people.rs +++ b/crates/ui-egui/src/panels/people.rs @@ -167,7 +167,7 @@ fn card(app: &mut LightcraftApp, ui: &mut egui::Ui, person: &Person, r: Rect, ed } // how many photos they are in, on the picture let count = if person.count > 999 { "999+".to_string() } else { person.count.to_string() }; - let g = p.layout_no_wrap(count, t.font(11.5), Color32::WHITE); + let g = p.layout_no_wrap(count, t.caption(), Color32::WHITE); let pill = Rect::from_min_size(pos2(face.right() - g.size().x - 14.0, face.bottom() - g.size().y - 11.0), g.size() + vec2(10.0, 6.0)); p.rect_filled(pill, 4.0, Color32::from_black_alpha(175)); p.galley(pill.min + vec2(5.0, 3.0), g, Color32::WHITE); diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rs index 3d90c00c3bf..363a5189084 100644 --- a/crates/ui-egui/src/panels/presets.rs +++ b/crates/ui-egui/src/panels/presets.rs @@ -335,7 +335,7 @@ pub fn picker_rows(ui: &mut egui::Ui, salt: &str, presets: &PresetList, selected let size = vec2(ui.available_width(), row_h); match row { PickRow::Header(g) => { - ui.add_sized(size, egui::Label::new(egui::RichText::new(g).size(10.5).weak())); + ui.add_sized(size, egui::Label::new(egui::RichText::new(g).font(Tokens::get(ui.ctx()).caption()).weak())); } PickRow::Preset(i) => { let Some(p) = presets.get(*i) else { continue }; diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 8d0cc0d3a96..b51495d06d0 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -60,8 +60,8 @@ pub fn header(ui: &mut egui::Ui, title: &str) { pub fn label_row(ui: &mut egui::Ui, label: &str, value: &str) { let t = Tokens::get(ui.ctx()); let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::hover()); - ui.painter().text(pos2(r.left() + 24.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::tr(label), t.font(12.5), t.text_dim); - ui.painter().text(pos2(r.left() + 110.0, r.center().y), Align2::LEFT_CENTER, value, t.font(12.5), t.text_label); + ui.painter().text(pos2(r.left() + 24.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::tr(label), t.body(), t.text_dim); + ui.painter().text(pos2(r.left() + 110.0, r.center().y), Align2::LEFT_CENTER, value, t.body(), t.text_label); } fn padded(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) { @@ -148,7 +148,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.label(crate::i18n::tr("Aspect Ratio")); let cur = aspect_label(app.crop_tool_aspect(), original); let t = Tokens::get(ui.ctx()); - let r = crate::widgets::dropdown(ui, "cropAspect", crate::i18n::tr(&cur), t.font(12.5), t.text); + let r = crate::widgets::dropdown(ui, "cropAspect", crate::i18n::tr(&cur), t.body(), t.text); egui::Popup::menu(&r).show(|ui| { for (label, a) in ASPECT_PRESETS { @@ -323,7 +323,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { "{} of 4 guides — drag along lines that should be vertical or horizontal.", d.geometry.guides.len() )) - .size(11.0) + .font(Tokens::get(ui.ctx()).caption()) .color(Tokens::get(ui.ctx()).text_dim), ); } @@ -592,7 +592,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { meta_field(app, ui, label, key, value, lines); } // file: name (rename), path (reveal), capture time (edit) - let small = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(crate::i18n::tr(text)).size(11.5).color(t.text_dim)); + let small = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(crate::i18n::tr(text)).font(t.caption()).color(t.text_dim)); small(ui, "File Name"); ui.allocate_ui_with_layout(vec2(ui.available_width(), 22.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::icon_button(ui, "infoRename", Icon::Pencil, vec2(20.0, 20.0), false, true, "Rename…").clicked() { @@ -609,7 +609,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { lightcraft_catalog::Source::File { path } => path.clone(), lightcraft_catalog::Source::Demo { .. } => crate::i18n::tr("Generated demo photo").into(), }; - ui.add(egui::Label::new(egui::RichText::new(path).size(12.0).color(t.text_label)).truncate()); + ui.add(egui::Label::new(egui::RichText::new(path).font(t.label()).color(t.text_label)).truncate()); if crate::menus::ui_enabled(app, "app.showInFinder") { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::icon_button(ui, "infoReveal", Icon::Folder, vec2(20.0, 20.0), false, true, crate::menus::reveal_label()) @@ -628,7 +628,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } let cap = p.captured.as_deref().map(crate::i18n::display_time).unwrap_or_else(|| "—".into()); ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.add(egui::Label::new(egui::RichText::new(cap).size(12.5).color(t.text)).truncate()); + ui.add(egui::Label::new(egui::RichText::new(cap).font(t.body()).color(t.text)).truncate()); }); }); ui.add_space(6.0); @@ -643,7 +643,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // GPS: typed as "lat, lon" (or degrees / minutes / seconds); empty clears it let gps = m.gps.map(|(la, lo)| format!("{la:.6}, {lo:.6}")).unwrap_or_default(); let gid = egui::Id::new("info-gps"); - ui.label(egui::RichText::new("GPS").size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new("GPS").font(t.caption()).color(t.text_dim)); let mut text: String = ui.data(|d| d.get_temp(gid)).unwrap_or_else(|| gps.clone()); let r = ui.add(egui::TextEdit::singleline(&mut text).hint_text(crate::i18n::tr("latitude, longitude")).desired_width(f32::INFINITY)); crate::widgets::screen_reader_name(ui.ctx(), r.id, "GPS"); @@ -662,7 +662,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if let Some((la, lo)) = m.gps { let pretty = format!("{:.5}° {}, {:.5}° {}", la.abs(), if la >= 0.0 { "N" } else { "S" }, lo.abs(), if lo >= 0.0 { "E" } else { "W" }); ui.horizontal(|ui| { - ui.label(egui::RichText::new(pretty).size(11.0).color(t.text_dim)); + ui.label(egui::RichText::new(pretty).font(t.caption()).color(t.text_dim)); if text_button(ui, "showOnMap", crate::i18n::tr("Show on Map"), false) .on_hover_text(crate::i18n::tr("Open the place in OpenStreetMap")) .clicked() @@ -709,7 +709,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { _ => "Smart preview available", }; ui.add_space(6.0); - ui.label(egui::RichText::new(crate::i18n::tr(text)).color(if online { t.text_dim } else { t.accent })); + ui.label(egui::RichText::new(crate::i18n::tr(text)).color(if online { t.text_dim } else { t.text_link() })); } } ui.add_space(10.0); @@ -729,7 +729,7 @@ fn camera_card(ui: &mut egui::Ui, p: &lightcraft_catalog::Photo) { let m = &p.meta; egui::Frame::NONE.fill(t.canvas).corner_radius(6.0).inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| { ui.set_width(ui.available_width()); - let dim = |s: &str| egui::RichText::new(s.to_string()).size(12.0).color(t.text_label); + let dim = |s: &str| egui::RichText::new(s.to_string()).font(t.label()).color(t.text_label); if !m.camera.is_empty() { ui.label(dim(&m.camera)); } @@ -740,14 +740,14 @@ fn camera_card(ui: &mut egui::Ui, p: &lightcraft_catalog::Photo) { ui.label(dim(&format!("{} × {} · {}", p.width, p.height, human_size(p.file_size)))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { egui::Frame::NONE.fill(t.chrome).corner_radius(3.0).inner_margin(egui::Margin::symmetric(5, 1)).show(ui, |ui| { - ui.label(egui::RichText::new(p.format.to_uppercase()).size(10.5).color(t.text_label)); + ui.label(egui::RichText::new(p.format.to_uppercase()).font(t.caption()).color(t.text_label)); }); }); }); let rows = [ - ("Focal length", m.focal_mm.map(|f| format!("{f:.1} mm").replace(".0 mm", " mm"))), - ("Shutter speed", (!m.shutter.is_empty()).then(|| crate::i18n::tr_format!("{} sec", m.shutter))), - ("Aperture", m.aperture.map(|f| format!("f / {f:.1}").replace(".0", ""))), + ("Focal length", m.focal_mm.and_then(crate::readout::focal)), + ("Shutter speed", crate::readout::shutter(&m.shutter)), + ("Aperture", m.aperture.and_then(crate::readout::aperture)), ("ISO", m.iso.map(|i| i.to_string())), ]; if rows.iter().any(|r| r.1.is_some()) { @@ -776,7 +776,7 @@ fn human_size(bytes: u64) -> String { /// Copyright Status: Unknown / Copyrighted / Public Domain (`xmpRights:Marked`). fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcraft_catalog::CopyrightStatus) { let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(crate::i18n::tr("Copyright Status")).size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr("Copyright Status")).font(t.caption()).color(t.text_dim)); let r = egui::ComboBox::from_id_salt("info-copyright-status").selected_text(crate::i18n::tr(current.label())).show_ui(ui, |ui| { for st in lightcraft_catalog::CopyrightStatus::ALL { if ui.selectable_label(st == current, crate::i18n::tr(st.label())).clicked() && st != current { @@ -790,7 +790,7 @@ fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcr fn meta_field(app: &mut LightcraftApp, ui: &mut egui::Ui, label: &str, key: &str, value: &str, lines: usize) { let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(crate::i18n::tr(label)).size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr(label)).font(t.caption()).color(t.text_dim)); let id = egui::Id::new(("info-field", key)); let mut text: String = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| value.to_string()); let widget = format!("field:{key}"); @@ -981,7 +981,9 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { let r = ui .add_sized( [bw, 22.0], - egui::Button::new(egui::RichText::new(short).size(11.5).color(if on { t.text } else { t.text_label })).selected(on).truncate(), + egui::Button::new(egui::RichText::new(short).font(t.label()).color(if on { t.text } else { t.text_label })) + .selected(on) + .truncate(), ) .on_hover_text(format!("{} — ⌥{}", k.replace('|', " › "), i + 1)); register(ui.ctx(), format!("kwSet:{}", i + 1), r.rect); @@ -1149,7 +1151,7 @@ fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { pos2(r.left() + 24.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::history_label(&h.label, &app.session.presets), - t.font(12.5), + t.body(), text, ); if resp.clicked() { diff --git a/crates/ui-egui/src/panels/rules_editor.rs b/crates/ui-egui/src/panels/rules_editor.rs index 006d426679d..a14f0c43992 100644 --- a/crates/ui-egui/src/panels/rules_editor.rs +++ b/crates/ui-egui/src/panels/rules_editor.rs @@ -285,7 +285,7 @@ fn field_menu(ui: &mut egui::Ui, salt: &str, field: &mut String, op: &mut String fn problem_note(ui: &mut egui::Ui, problem: Option<&Problem>, salt: &str) { let Some(p) = problem else { return }; let t = Tokens::get(ui.ctx()); - let r = ui.label(RichText::new(format!("⚠ {}", crate::i18n::problem_text(p))).color(t.caution).small()); + let r = ui.label(RichText::new(format!("⚠ {}", crate::i18n::problem_text(p))).color(t.text_caution()).small()); register(ui.ctx(), format!("ruleProblem:{salt}"), r.rect); } diff --git a/crates/ui-egui/src/panels/second.rs b/crates/ui-egui/src/panels/second.rs index 79aa31d1dc5..976f8e9b8fd 100644 --- a/crates/ui-egui/src/panels/second.rs +++ b/crates/ui-egui/src/panels/second.rs @@ -30,7 +30,7 @@ fn body(app: &mut LightcraftApp, ui: &mut egui::Ui) { area.center(), egui::Align2::CENTER_CENTER, crate::i18n::tr("No photo selected"), - egui::FontId::proportional(14.0), + crate::theme::Tokens::get(ui.ctx()).title(), Color32::GRAY, ); return; diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index a0717ccfd6a..41a8856b014 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -20,7 +20,9 @@ use crate::widgets::register; /// (id, label) of the tabs, in order. pub const TABS: &[(&str, &str)] = &[ ("general", "General"), + ("library", "Library"), ("import", "Import"), + ("files", "Files"), ("performance", "Performance"), ("display", "Display"), ("interface", "Interface"), @@ -28,26 +30,29 @@ pub const TABS: &[(&str, &str)] = &[ ("denoise", "AI Denoise"), ]; +/// What a tab is called on the tab bar. Two tabs go by another name than [`TABS`] gives them, +/// so that the monitor's colour profile and how LightCraft looks are not taken for each other: +/// `display` is Monitor and `interface` is Appearance. (Said here and not in `TABS`, whose lines +/// after these two are where other work adds its tabs; ids stay as they are.) +pub fn tab_label(id: &str, label: &'static str) -> &'static str { + match id { + "display" => "Monitor", + "interface" => "Appearance", + _ => label, + } +} + /// Thumbnail cache sizes offered (MB). const CACHE_SIZES: [u32; 5] = [512, 1024, 2048, 4096, 8192]; const LABEL_W: f32 = 150.0; -/// The dialog body for `tab` (the tab bar switches `tab`). -pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String) { +/// The page of `tab` (the tab bar in [`window`] switches `tab`). +pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &str) { let t = Tokens::get(ui.ctx()); - ui.set_width((ui.ctx().content_rect().width() - 64.0).clamp(240.0, 560.0)); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - for (id, label) in TABS { - if crate::widgets::text_button(ui, &format!("settingsTab-{id}"), label, tab == id).clicked() { - *tab = id.to_string(); - } - } - }); - ui.separator(); - ui.add_space(2.0); - match tab.as_str() { + match tab { + "library" => library_tab(app, ui, &t), + "files" => files_tab(app, ui, &t), "import" => import_tab(app, ui, &t), "performance" => performance_tab(app, ui, &t), "display" => display_tab(app, ui, &t), @@ -58,30 +63,806 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String) { } } +/// The widest the Settings window's content gets, and the tallest its pages get: the window is +/// one size on every tab, so it stays where it is as the tabs are gone through. +const PAGE_SIZE: egui::Vec2 = egui::vec2(560.0, 640.0); + +/// The least room in which a page scrolls by itself. In a window with less (far below the +/// desktop minimum), the tabs and the page scroll together in the dialog's own scroll area. +const PAGE_MIN_HEIGHT: f32 = 120.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 +/// two together never take more, so the scroll area every dialog is drawn in has nothing to +/// scroll (but for a window with less than [`PAGE_MIN_HEIGHT`] for the page, where that area +/// scrolls the two together). Every page gets the same room whatever it holds, and each keeps a +/// scroll position of its own. Nothing here is wider than the window from 640 pt of app window +/// up: a row's controls wrap ([`row`]) and paths are shortened ([`path_label`]). +pub fn window(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String, max_height: f32) { + ui.set_width((ui.ctx().content_rect().width() - 64.0).clamp(240.0, PAGE_SIZE.x)); + // The page drawn is the one that was open when the frame began: a tab clicked now opens on + // 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(); + let top = ui.cursor().top(); + // 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. + // What says where a control is, and what a text box says while it is empty, are made legible + // here for everything in the window: a theme's border is 1.6 to 1.7:1 against the window and + // its weak text under 4.3:1 in a box (the tokens keep their values for the rest of the app). + let t = Tokens::get(ui.ctx()); + legible_controls(ui, &t); + let filter_id = egui::Id::new("settings-filter"); + let pass = ui.ctx().cumulative_pass_nr(); + let kept: Option = ui.data(|d| d.get_temp(filter_id)); + // (Settings shown anew: the filter starts empty, and nothing is marked as landed on) + let opened = !kept.as_ref().is_some_and(|k| k.pass.checked_add(1) == Some(pass)); + if opened { + ui.data_mut(|d| d.remove::<(String, f64)>(egui::Id::new(LANDED))); + } + let mut filter = kept.filter(|_| !opened).unwrap_or_default(); + filter.pass = pass; + // (the mark is for arriving at a section from the filter: a tab left, however, and come back + // to shows none. Arriving sets it again when the heading is drawn, further down this frame.) + if filter.tab != shown { + ui.data_mut(|d| d.remove::<(String, f64)>(egui::Id::new(LANDED))); + } + filter.tab.clone_from(&shown); + 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); + // The box is ready to type in when Settings opens: the filter reaches every section from + // wherever one is. (Not where typing brings up a keyboard over the window.) + if opened && !matches!(ui.ctx().os(), egui::os::OperatingSystem::Android | egui::os::OperatingSystem::IOS) { + typed.response.request_focus(); + } + // 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. + let escape = had_text && !crate::widgets::escape_taken(ui.ctx()) && ui.input(|i| i.key_pressed(egui::Key::Escape)); + if 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(); + // Each line of tabs stands on a line of its own the width of the window, so the open tab's + // line always has the bar's under it: in a narrow window, or a language with long names, the + // tabs take two lines or more. + let mut lines: Vec = Vec::new(); + // (the bar is one stop for Tab, at the open tab; the arrow keys go along it) + let mut bar = crate::widgets::Roving::new(ui, "settingsTabs", TABS.iter().position(|(id, _)| *id == shown)); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = egui::vec2(4.0, 5.0); + for (id, label) in TABS { + let r = crate::widgets::tab_button_in(ui, &mut bar, &format!("settingsTab-{id}"), tab_label(id, label), shown == *id && !filtering); + let bottom = egui::emath::GuiRounding::round_to_pixels(r.rect.bottom(), ui.pixels_per_point()); + if !lines.iter().any(|line| (line - bottom).abs() < 0.5) { + lines.push(bottom); + } + if r.clicked() { + *tab = id.to_string(); + // (a tab opened is its page asked for: the filter gives way) + filter.text.clear(); + ui.ctx().request_repaint(); + } + } + }); + bar.end(ui); + let divider = t.legible(t.divider, t.chrome, 3.0); + for bottom in lines { + let line = egui::Rect::from_min_max(egui::pos2(ui.min_rect().left(), bottom), egui::pos2(ui.min_rect().right(), bottom + 1.0)); + ui.painter().rect_filled(line, egui::CornerRadius::ZERO, divider); + } + ui.add_space(1.0); + // 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; + let mut page = |ui: &mut egui::Ui| match &found { + Some(found) => goto = results(ui, found, &words, open_first, to_first), + None => { + body(app, ui, shown.as_str()); + // (what the page took: wider than the room for it would mean a control is cut off) + register(ui.ctx(), "settings:page", ui.min_rect()); + } + }; + if room < PAGE_MIN_HEIGHT { + page(ui); + } else { + let height = room.min(PAGE_SIZE.y); + // 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.ctx(), "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::new(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 == shown) { + // (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)); +} + +/// What says where a control is, and what a text box says while it is empty, made legible for +/// everything drawn in `ui` from here on (the window, and each panel that opens over it, which +/// has a style of its own): the border of a button, checkbox, radio button, list or text box +/// stands 3:1 against the window and against a theme card's fill, a text box in use is +/// outlined in an accent that does too, and placeholder text stands 4.5:1 in its box. +pub(super) fn legible_controls(ui: &mut egui::Ui, t: &Tokens) { + // (a little over 3:1 as a colour: a radio button's ring is one antialiased pixel wide, and + // what is drawn of it is fainter than the colour it is drawn in) + let border = t.legible(t.legible(t.button_border, t.chrome, 3.0), t.inset, 3.6); + let visuals = ui.visuals_mut(); + visuals.widgets.inactive.bg_stroke.color = border; + // One look for "the focus is here", whatever the control: a line 2 pt wide in the text + // colour round it, as round a tab or a choice ([`crate::widgets::focus_ring`]). egui draws a + // button, checkbox, radio button or list that has the focus (or is being pressed) with its + // "active" outline, and a text box in use with the selection's. + visuals.widgets.active.bg_stroke = egui::Stroke::new(2.0, t.text); + visuals.selection.stroke = egui::Stroke::new(2.0, t.text); + visuals.weak_text_color = Some(t.legible(t.text_dim, t.field, 4.5)); +} + +/// Where the section to scroll to is kept between the click on a result and its page being drawn. +const GOTO: &str = "settings-goto"; + +/// Where the section landed on from the filter is kept while its heading is marked: its name +/// and when. +const LANDED: &str = "settings-landed"; + +/// How long the heading of the section landed on stays marked, in seconds. +const LANDED_FOR: f64 = 1.6; + +/// Words people type for a section that the section does not say itself: the tab, the heading's +/// English name (empty for what a tab draws above its first heading) and the words, in lower +/// case and in the spelling [`fold`] gives. They are English whatever language is shown (in the +/// others a section is found by what it says), and count as much as a word in an explanation. +pub const ALSO: &[(&str, &str, &str)] = &[ + ("general", "", "locale translation translate"), + ("general", "Startup", "launch start"), + ("general", "Culling", "trash bin delete deleted"), + ("library", "Library", "catalog database"), + ("library", "Smart previews", "proxy proxies offline"), + ("import", "Raw defaults", "preset develop"), + ("import", "Metadata", "iptc author credit"), + ("import", "Auto Import", "watch tether"), + ("files", "XMP sidecars", "metadata"), + ("files", "External Editing", "editor photoshop color space bit depth"), + ("performance", "Rendering", "graphics card speed resolution"), + ("performance", "Thumbnail cache", "disk space storage previews"), + ("display", "Monitor profile", "screen color management calibration calibrate"), + ("interface", "Appearance", "theme color scheme skin"), + ("faces", "Face recognition", "people person"), + ("denoise", "AI Denoise", "noise reduction"), +]; + +/// Pairs of spellings of one word, the one [`fold`] gives first. +const SPELLINGS: &[(&str, &str)] = + &[("color", "colour"), ("gray", "grey"), ("catalog", "catalogue"), ("favorite", "favourite"), ("center", "centre"), ("license", "licence")]; + +/// `text` as the filter compares it: in lower case, and in one spelling of the words that have +/// two (colour as color), so that either finds the other. +fn fold(text: &str) -> String { + let mut folded = text.to_lowercase(); + for (one, other) in SPELLINGS { + if folded.contains(other) { + folded = folded.replace(other, one); + } + } + folded +} + +/// A word typed (in lower case) in the one spelling ([`fold`]), which a word still being typed +/// in the other is brought to as well: "colou" is on the way to "colour" and is compared as +/// "color", "catalogu" as "catalog". Only once it has gone past where the two spellings part, +/// so that "colo" stays what it is. +fn fold_typed(word: &str) -> String { + let folded = fold(word); + for (one, other) in SPELLINGS { + let shared = one.chars().zip(other.chars()).take_while(|(a, b)| a == b).count(); + // (the longest start of the other spelling the word ends in, past what the two share) + let ends_in = other.char_indices().skip(shared + 1).filter_map(|(at, _)| other.get(..at)).filter(|start| folded.ends_with(start)).last(); + if let Some(stem) = ends_in.and_then(|start| folded.strip_suffix(start)) { + return format!("{stem}{one}"); + } + } + folded +} + +/// A text as the filter compares it: in lower case, and in one spelling ([`fold`]). +#[derive(Clone)] +struct Compared { + lower: String, + folded: String, +} + +impl Compared { + fn of(text: &str) -> Self { + let lower = text.to_lowercase(); + Self { folded: fold(&lower), lower } + } + + /// Whether the text has `word` (in lower case): as typed, or in the other spelling of it. As + /// typed counts too, so that a word is found all the way while it is typed ("colou" is on + /// the way to "colour", and is in no text once that is spelt "color"). + fn has(&self, word: &str) -> bool { + self.lower.contains(word) || self.folded.contains(&fold_typed(word)) + } +} + +/// A text a section draws: as drawn, as the filter compares it, and whether it is in the small +/// type of an explanation. +#[derive(Clone)] +struct Drawn { + text: String, + compared: Compared, + small: bool, +} + +/// 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 and library they were read in. +#[derive(Clone, Default)] +struct Filter { + pass: u64, + text: String, + /// The tab that was open on the frame before. + tab: String, + sections: Option<(String, std::sync::Arc>)>, +} + +impl Filter { + /// The sections that have every word of `words` (in lower case), the best match first + /// ([`Section::rank`]) and those that match alike 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()); + 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 + } + }; + let mut found: Vec<(u32, &Section)> = sections.iter().filter_map(|section| Some((section.rank(words)?, section))).collect(); + // (a stable sort: the order of the tabs is kept among equals) + found.sort_by_key(|(rank, _)| *rank); + found.into_iter().map(|(_, section)| section.clone()).collect() + } +} + +impl Section { + /// The name of the section's tab, as shown. + fn tab_name(&self) -> &'static str { + TABS.iter().find(|(id, _)| *id == self.tab).map_or("", |(id, label)| crate::i18n::tr(tab_label(id, label))) + } + + /// How well the section matches `words` (in lower case), less being better, or `None` when one + /// of them is nowhere in it. Each word counts by the best place it is found in: 0 in the + /// name of the section or its tab, 1 in a label, choice or button, 2 in an explanation or + /// among the words people type for the section ([`ALSO`], from the start of one). + fn rank(&self, words: &str) -> Option { + let names = Compared::of(&format!("{} {}", self.tab_name(), crate::i18n::tr(&self.name))); + let also = || ALSO.iter().filter(|(tab, name, _)| *tab == self.tab && *name == self.name).flat_map(|(_, _, also)| also.split_whitespace()); + words + .split_whitespace() + .map(|word| { + if names.has(word) { + Some(0) + } else if self.texts.iter().any(|drawn| !drawn.small && drawn.compared.has(word)) { + Some(1) + } else if self.texts.iter().any(|drawn| drawn.compared.has(word)) || also().any(|also| also.starts_with(&fold_typed(word))) { + Some(2) + } else { + None + } + }) + .sum() + } + + /// 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)) } + } +} + +/// Where in `text` a word of `words` (in lower case) stands, as ranges of bytes of `text`, in +/// the order they stand in and none inside another: in either case and either spelling. +fn places(text: &str, words: &str) -> Vec> { + // each char of the text in lower case, with where it starts (a char that is several in lower + // case counts by its first: the ranges are of `text`, which `to_lowercase` would not keep) + let chars: Vec<(usize, char)> = text.char_indices().map(|(at, c)| (at, c.to_lowercase().next().unwrap_or(c))).collect(); + let mut found: Vec> = Vec::new(); + for word in words.split_whitespace() { + // (as typed, in the one spelling, and in the other) + let folded = fold_typed(word); + let other = SPELLINGS.iter().find(|(one, _)| folded.contains(one)).map(|(one, other)| folded.replace(one, other)); + let mut spellings = vec![word.to_string()]; + spellings.extend(std::iter::once(folded).chain(other).filter(|spelt| spelt != word)); + for spelt in spellings { + let spelt: Vec = spelt.chars().collect(); + if spelt.is_empty() { + continue; + } + for start in 0..chars.len() { + let Some(run) = chars.get(start..start.saturating_add(spelt.len())) else { break }; + if run.iter().map(|(_, c)| c).eq(spelt.iter()) { + let from = run.first().map_or(0, |(at, _)| *at); + let to = chars.get(start + spelt.len()).map_or(text.len(), |(at, _)| *at); + found.push(from..to); + } + } + } + } + found.sort_by_key(|range| (range.start, std::cmp::Reverse(range.end))); + let mut apart: Vec> = Vec::new(); + for range in found { + if apart.last().is_none_or(|last| range.start >= last.end) { + apart.push(range); + } + } + apart +} + +/// How far into a line under a result the first word found may stand, in chars, before the +/// line is started later so that the word is in sight. +const SNIPPET_LEAD: usize = 40; + +/// The line shown under a result for `text`: `text` itself, or from a word's start shortly +/// before the first word found with `…` before it when that word stands far in (the line is cut +/// at its end by the room there is), and where the words found stand in what is given. +fn snippet(text: &str, words: &str) -> (String, Vec>) { + let found = places(text, words); + let Some(first) = found.first().map(|range| range.start) else { return (text.to_string(), found) }; + let before = text.get(..first).unwrap_or(""); + if before.chars().count() <= SNIPPET_LEAD { + return (text.to_string(), found); + } + // (from the start of a word, a few words before the one found) + let lead = before.char_indices().rev().nth(SNIPPET_LEAD / 2).map_or(0, |(at, _)| at); + let from = before.get(lead..).and_then(|rest| rest.find(' ')).map_or(lead, |space| lead + space + 1).min(first); + let Some(shown) = text.get(from..) else { return (text.to_string(), found) }; + let shift = '…'.len_utf8(); + let found = found.into_iter().map(|range| range.start - from + shift..range.end - from + shift).collect(); + (format!("…{shown}"), found) +} + +/// 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) and fills the +/// same caches of those answers; 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<(egui::Pos2, String, bool)>) { + match shape { + egui::Shape::Text(text) => { + // (an explanation is in 11 pt; a label, choice or button in 12 pt or more) + let small = text.galley.job.sections.first().is_some_and(|section| section.format.font_id.size < 12.0); + out.push((text.pos, text.galley.job.text.clone(), small)); + } + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), + _ => {} + } + } + let scratch = egui::Context::default(); + 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); + }); + // (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 registry = crate::widgets::take_registry(&scratch); + let mut headings: Vec<(f32, String)> = + registry.iter().filter_map(|(id, r)| Some((r.top(), id.strip_prefix("heading:")?.to_string()))).collect(); + // (where a folder or file is shown, [`path_label`], and what is in a text box: where a + // library, a cache or an editor happens to be, or the name someone typed, is not what a + // setting is called, and is not looked through) + let paths: Vec = + registry.iter().filter(|(id, _)| id.starts_with("path:") || id.starts_with("field:")).map(|(_, r)| r.expand(1.0)).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.y.total_cmp(&b.0.y)); + 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 (at, text, small) 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 <= at.y + 1.0).count(); + if let Some(section) = of_tab.get_mut(under) + && !text.trim().is_empty() + && !paths.iter().any(|path| path.contains(at)) + { + section.texts.push(Drawn { compared: Compared::of(&text), text, small }); + } + } + all.extend(of_tab.into_iter().filter(|section| !section.texts.is_empty())); + } + all +} + +/// Whether `c` is of a script written from right to left (Hebrew, Arabic and those beside them). +fn right_to_left(c: char) -> bool { + matches!(u32::from(c), 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF) +} + +/// Whether `c` is part of a word written from right to left: its letters and marks, and the joiner +/// and non-joiner between them (Persian writes a non-joiner inside a word), which are shaped with it. +fn in_word_from_the_right(c: char) -> bool { + right_to_left(c) || matches!(c, '\u{200c}' | '\u{200d}') +} + +/// Which char of `chars` each of a row's `glyphs` draws, the row's first being of the char `at` +/// (left at the next row's first). Text written from left to right has a glyph for each char, in +/// their order. A word written from right to left has its glyphs from its last char to its +/// first, a mark before the letter it is on, and after them glyphs of no width that are of no +/// char in particular: there each glyph is placed by the char it says it draws. +/// +/// Two things this takes for granted, true of the faces there are today: text from left to right +/// has one glyph a char (a face that draws one char as two glyphs would move the later marks of +/// its row), and two words from right to left in different scripts have something between them +/// (with nothing between them the second is left unmarked). +fn chars_drawn(glyphs: &[egui::epaint::text::Glyph], chars: &[char], at: &mut usize) -> Vec> { + let mut drawn = Vec::with_capacity(glyphs.len()); + while let Some(glyph) = glyphs.get(drawn.len()) { + if !right_to_left(glyph.chr) { + drawn.push(Some(*at)); + *at = at.saturating_add(1); + continue; + } + let word = chars.get(*at..).map_or(0, |rest| rest.iter().take_while(|c| in_word_from_the_right(**c)).count()); + // (the chars of the word no glyph has been found for yet end before `left`; a mark has no + // width, and the next glyph may be the letter it is on) + let (mut left, mut marked) = (*at + word, false); + while let Some(glyph) = glyphs.get(drawn.len()).filter(|glyph| in_word_from_the_right(glyph.chr)) { + let before = if marked { left + 1 } else { left }.min(*at + word); + let place = chars.get(*at..before).and_then(|rest| rest.iter().rposition(|c| *c == glyph.chr)).map(|place| *at + place); + if let Some(place) = place { + (left, marked) = (place, glyph.advance_width <= 0.0); + } + drawn.push(place); + } + *at += word; + } + drawn +} + +/// Where the chars at `found` (ranges of bytes of the galley's text) are drawn, from the +/// galley's corner: a rectangle for each stretch of them in each row. +fn marks(galley: &egui::Galley, found: &[std::ops::Range]) -> Vec { + let (chars, hit): (Vec, Vec) = galley.text().char_indices().map(|(at, c)| (c, found.iter().any(|range| range.contains(&at)))).unzip(); + let mut rects = Vec::new(); + let mut at = 0; + for row in &galley.rows { + let mut open: Option = None; + for (glyph, drawn) in row.glyphs.iter().zip(chars_drawn(&row.glyphs, &chars, &mut at)) { + if drawn.and_then(|place| hit.get(place)).copied().unwrap_or(false) { + let left = row.pos.x + glyph.pos.x; + let rect = egui::Rect::from_x_y_ranges(left..=left + glyph.advance_width, row.min_y()..=row.max_y()); + open = Some(open.map_or(rect, |open| open.union(rect))); + } else if glyph.advance_width > 0.0 { + rects.extend(open.take()); + } + } + rects.extend(open); + at += usize::from(row.ends_with_newline); + } + rects +} + +/// The line under a result, with the chars at `found` (ranges of bytes of it) told apart by a +/// fill behind them and a line under them (the line for whoever cannot tell the fill's colour from +/// the row's). The line of text is one piece in one format: a piece is shaped by itself, so +/// letters found inside a word, in a font or a colour of their own, would cut the word in three +/// (no kerning across the cuts, and in Arabic the letters either side of them left unjoined). +pub(crate) fn found_line(ui: &mut egui::Ui, t: &Tokens, line: String, found: &[std::ops::Range]) { + let fill = t.chrome.lerp_to_gamma(t.accent, 0.3); + // (legible on the fill a hovered or focused row has, and so on a plain one, and on the fill + // behind what was found: the line is in one colour) + let dim = t.legible(t.legible(t.legible(t.text_dim, t.hover, 4.5), t.chrome, 4.5), fill, 4.5); + let format = egui::TextFormat { font_id: t.caption(), color: dim, ..Default::default() }; + let job = egui::text::LayoutJob::single_section(line, format); + let (at, galley, response) = egui::Label::new(job).selectable(false).truncate().layout_in_ui(ui); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), galley.text())); + if ui.is_rect_visible(response.rect) { + // (a line that stands on the fill and on a plain, hovered or focused row) + let under = egui::Stroke::new(1.0, t.legible(t.legible(t.legible(t.text, t.hover, 3.0), t.chrome, 3.0), fill, 3.0)); + for rect in marks(&galley, found) { + let rect = rect.translate(at.to_vec2()).expand2(egui::vec2(1.0, 0.0)); + ui.painter().rect_filled(rect, egui::CornerRadius::same(2), fill); + ui.painter().hline(rect.x_range(), rect.bottom() - 1.0, under); + } + if galley.elided { + response.on_hover_text(galley.text().to_string()); + } + ui.painter().add(egui::epaint::TextShape::new(at, galley, dim)); + } +} + +/// 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` ([`snippet`]). 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 = section + .texts + .iter() + .filter(|drawn| drawn.text != heading && words.split_whitespace().any(|word| drawn.compared.has(word))) + .take(2); + for drawn in with { + let (line, found) = snippet(&drawn.text, words); + found_line(ui, &t, line, &found); + } + 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::WidgetType::Button, true, section.title())); + register(ui.ctx(), format!("settingsFound:{}:{}", section.tab, section.name), row.rect); + if row.clicked() { + chosen = Some((section.tab, section.name.clone())); + } + } + chosen +} + +/// `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`, +/// `…\Pictures\Library`): the end says which folder it is. A last folder too long by itself +/// loses its end ([`crate::widgets::elide_head`]). +fn elide_path(path: &str, max: f32, width: impl Fn(&str) -> f32) -> String { + if width(path) <= max { + return path.to_string(); + } + // (a separator at the very end is not where a name starts: `…/` alone would say nothing) + let end = path.trim_end_matches(['/', '\\']).len(); + let mut rest = path; + while let Some(i) = rest.find(['/', '\\']).filter(|i| path.len() - rest.len() + i + 1 < end) { + let separator = if rest.get(i..).is_some_and(|r| r.starts_with('\\')) { '\\' } else { '/' }; + rest = rest.get(i + 1..).unwrap_or(""); + let shorter = format!("…{separator}{rest}"); + if width(&shorter) <= max { + return shorter; + } + } + let name = rest.trim_end_matches(['/', '\\']); + // (nothing but separators: never an empty label) + if name.is_empty() { "…".to_string() } else { crate::widgets::elide_head(name, max, width) } +} + +/// A folder or file path on one line in the room left in its row (`text:{id}`): shortened from +/// the front when it is too long ([`elide_path`]), with all of it in a tooltip then. +fn path_label(ui: &mut egui::Ui, id: &str, path: &str, font: egui::FontId, color: egui::Color32) { + let shown = elide_path(path, ui.available_width(), |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), color).size().x); + // (`truncate` is the last resort, for a room narrower than "…") + let r = ui.add(egui::Label::new(RichText::new(&shown).font(font).color(color)).truncate().show_tooltip_when_elided(false)); + register(ui.ctx(), format!("text:{id}"), r.rect); + // (what the filter leaves out of what it looks through; not what stands here in words when + // there is no folder to show) + if path.contains(['/', '\\']) { + register(ui.ctx(), format!("path:{id}"), r.rect); + } + if shown != path { + r.on_hover_text(path); + } +} + +/// What the Smart previews section ([`smart_previews`]) keeps between frames: what is chosen for the previews already +/// built (0 move, 1 leave, 2 delete) and a change of folder that waits for a yes because it would +/// delete them, with the frame, library and folder they were chosen and asked in. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Default)] +struct SmartAsk { + pass: u64, + library: String, + folder: String, + mode: u8, + waiting: Option, +} + +/// A text box of the Settings window, shown: Esc in it gives its text back and is used up by +/// that, so Settings stays open (a second Esc, with nothing being edited, closes it). +fn field(ui: &mut egui::Ui, field: crate::text_field::TextField<'_>) -> egui::Response { + let shown = field.show(ui); + if shown.cancelled() { + crate::widgets::take_escape(ui.ctx()); + } + shown.response +} + +/// What [`ask_first`] makes of a button: [`Asked::clicked`] once the person has said yes. +pub(super) struct Asked { + yes: bool, +} + +impl Asked { + /// The person pressed the button and then said yes to its question. + pub(super) fn clicked(&self) -> bool { + self.yes + } +} + +/// A button whose action cannot be taken back, or takes long to make good again, asks before it +/// acts. Pressing `button` (registered by the caller as `id`) opens a small panel under it with +/// `question`, which says what the action costs, and two buttons: `yes` (`{id}:confirm`) and +/// Keep (`{id}:keep`), which has the focus when the panel opens. A click elsewhere or Esc answers no. What comes back stands in for the +/// button: its `clicked` is true on the frame the answer was yes. +pub(super) fn ask_first(t: &Tokens, id: &str, button: egui::Response, question: &str, yes: &str) -> Asked { + let mut answer = false; + let opened = button.clicked(); + egui::Popup::from_toggle_button_response(&button).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_max_width(280.0); + legible_controls(ui, t); + ui.add(egui::Label::new(RichText::new(crate::i18n::tr(question)).color(t.text_label)).wrap()); + ui.horizontal(|ui| { + let r = ui.button(crate::i18n::tr(yes)); + register(ui.ctx(), format!("{id}:confirm"), r.rect); + if r.clicked() { + answer = true; + ui.close(); + button.request_focus(); + } + let r = ui.button(crate::i18n::tr("Keep")); + register(ui.ctx(), format!("{id}:keep"), r.rect); + // (the question opens with the focus on Keep, so Return or Space alone changes nothing) + if opened { + r.request_focus(); + } + // (answered from the keyboard, the focus goes back to the button the question was about) + if r.clicked() { + ui.close(); + button.request_focus(); + } + }); + }); + Asked { yes: answer } +} + pub(super) 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)); + // (`heading:{its English name}`, whatever the language: where a section starts, for scripts + // and tests that look for one. Callers pass the name translated or not.) + let behind = ui.painter().add(egui::Shape::Noop); + let r = ui.label(RichText::new(crate::i18n::tr(text)).font(t.body_strong()).color(t.text)); + let name = crate::i18n::source_of(text); + register(ui.ctx(), format!("heading:{name}"), r.rect); + // (chosen from what the filter found: the section is brought to the top of the page, and its + // heading is marked for a moment, so that the one chosen is told from its neighbours) + let now = ui.input(|i| i.time); + let landed_id = egui::Id::new(LANDED); + if ui.data(|d| d.get_temp::<(&'static str, String)>(egui::Id::new(GOTO))).is_some_and(|(_, section)| section == name) { + r.scroll_to_me(Some(egui::Align::TOP)); + ui.data_mut(|d| d.insert_temp(landed_id, (name.to_string(), now))); + } + if let Some((_, since)) = ui.data(|d| d.get_temp::<(String, f64)>(landed_id)).filter(|(landed, _)| *landed == name) { + // (full for the first half of its time, then fading out) + let left = (1.0 - (now - since) / LANDED_FOR).clamp(0.0, 1.0) as f32; + if left > 0.0 { + let strength = (left * 2.0).min(1.0); + let around = r.rect.expand2(egui::vec2(6.0, 2.0)); + let outline = egui::Stroke::new(1.0, t.legible(t.accent, t.chrome, 3.0).gamma_multiply(strength)); + ui.painter().set(behind, egui::Shape::rect_filled(around, egui::CornerRadius::same(4), t.hover.gamma_multiply(strength))); + ui.painter().rect_stroke(around, egui::CornerRadius::same(4), outline, egui::StrokeKind::Inside); + register(ui.ctx(), format!("settingsLanded:{name}"), around); + ui.ctx().request_repaint(); + } else { + ui.data_mut(|d| d.remove::<(String, f64)>(landed_id)); + } + } } fn row(ui: &mut egui::Ui, t: &Tokens, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R { ui.horizontal(|ui| { ui.allocate_ui_with_layout(egui::vec2(LABEL_W, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.set_min_width(LABEL_W); - ui.label(RichText::new(crate::i18n::tr(label)).color(t.text_label)); + // (a label longer than its column wraps in it; it does not push the controls along) + ui.add(egui::Label::new(RichText::new(crate::i18n::tr(label)).color(t.text_label)).wrap()); }); - add(ui) + // The controls wrap in the room beside the label, each further line starting under the + // first control, so a row with many choices grows down and never widens the window. + let wrapped = egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true); + ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 24.0), wrapped, |ui| { + ui.spacing_mut().item_spacing.y = 4.0; + add(ui) + }) + .inner }) .inner } pub(super) fn hint(ui: &mut egui::Ui, t: &Tokens, text: &str) { - ui.label(RichText::new(crate::i18n::tr(text)).size(11.0).color(t.text_dim)); + // (an explanation is small text: the dim colour where it reads, else as near it as reads) + ui.label(RichText::new(crate::i18n::tr(text)).font(t.caption()).color(t.legible(t.text_dim, t.chrome, 4.5))); } /// A checkbox addressable as `check:{id}`; true when toggled. pub(super) fn check(ui: &mut egui::Ui, id: &str, value: &mut bool, label: &str) -> bool { let r = ui.checkbox(value, crate::i18n::tr(label)); register(ui.ctx(), format!("check:{id}"), r.rect); + // (ringed round the whole of it while it has the focus, as a choice or a tab is) + crate::widgets::focus_ring(ui, &Tokens::get(ui.ctx()), &r, r.rect.expand2(egui::vec2(3.0, 1.0))); r.changed() } @@ -89,30 +870,65 @@ pub(super) fn check(ui: &mut egui::Ui, id: &str, value: &mut bool, label: &str) pub(super) fn choices(ui: &mut egui::Ui, id: &str, options: &[(V, &str)], value: &mut V) -> bool { let mut changed = false; ui.spacing_mut().item_spacing.x = 4.0; + // (the row is one stop for Tab, at the choice that holds; the arrow keys go along it) + let mut group = crate::widgets::Roving::new(ui, id, options.iter().position(|(v, _)| *v == *value)); for (i, (v, l)) in options.iter().enumerate() { - if crate::widgets::text_button(ui, &format!("{id}-{i}"), l, *value == *v).clicked() && *value != *v { + if crate::widgets::choice_button_in(ui, &mut group, &format!("{id}-{i}"), l, *value == *v).clicked() && *value != *v { *value = *v; changed = true; } } + group.end(ui); changed } // ------------------------------------------------------------------------------------- General +/// Library: the library itself. Where it is and opening another ([`library_section`]), where +/// its smart previews are kept ([`smart_previews`], for a library on disk), and what leaves its +/// catalog by itself ([`local_folders`]). +fn library_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + library_section(app, ui, t); + #[cfg(not(target_arch = "wasm32"))] + smart_previews(app, ui, t); + local_folders(app, ui, t); + in_memory_note(app, ui, t); +} + +/// Files: what LightCraft writes beside the photo files ([`xmp_sidecars`]) and what it opens +/// them in ([`external_editing`]). +fn files_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + xmp_sidecars(app, ui, t); + in_memory_note(app, ui, t); + external_editing(app, ui, t); +} + +/// What is saved with the library lasts only as long as a library that is not on disk does: +/// said under such settings wherever they are (Import says it at its foot itself). +fn in_memory_note(app: &LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + if app.session.library.is_none() { + hint(ui, t, "In-memory session: these settings last until LightCraft quits."); + } +} + fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { row(ui, t, crate::i18n::tr("Language"), |ui| { let languages: Vec<_> = crate::i18n::Locale::ALL.iter().map(|language| (*language, language.name())).collect(); choices(ui, "settingsLanguage", &languages, &mut app.ui.language); crate::i18n::set_language(app.ui.language); }); + startup_and_culling(app, ui, t); +} + +/// Library: where the open library is, and opening or making another. +fn library_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("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(), }; row(ui, t, crate::i18n::tr("Location"), |ui| { - ui.label(RichText::new(location).color(t.text)); + path_label(ui, "settingsLocation", &location, egui::TextStyle::Body.resolve(ui.style()), t.text); }); row(ui, t, "", |ui| { let can = app.services.pick_folder.is_some(); @@ -130,6 +946,10 @@ fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { hint(ui, t, crate::i18n::tr("not available here")); } }); +} + +/// Startup and Culling: what LightCraft opens in, and how rating and deleting behave. +fn startup_and_culling(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("Startup")); row(ui, t, crate::i18n::tr("Open in"), |ui| { choices( @@ -142,26 +962,34 @@ fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("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"); +} + +/// External Editing: the editors a photo is opened in, and the copy they are given. +fn external_editing(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("External Editing")); row(ui, t, crate::i18n::tr("PhotoCraft"), |ui| { - crate::text_field::TextField::singleline("field:photocraftPath", &mut app.ui.settings.photocraft_path) - .hint(crate::i18n::tr("Found automatically")) - .width(220.0) - .show(ui); + field( + ui, + crate::text_field::TextField::singleline("field:photocraftPath", &mut app.ui.settings.photocraft_path) + .hint(crate::i18n::tr("Found automatically")) + .width(220.0), + ); }); edit_file_rows(ui, t, "photocraftFile", &mut app.ui.settings.photocraft_file); hint( ui, t, crate::i18n::tr( - "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.", + "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.", ), ); row(ui, t, crate::i18n::tr("Other editor"), |ui| { - crate::text_field::TextField::singleline("field:externalEditor", &mut app.ui.settings.external_editor) - .hint(crate::i18n::tr("System default")) - .width(220.0) - .show(ui); + field( + ui, + crate::text_field::TextField::singleline("field:externalEditor", &mut app.ui.settings.external_editor) + .hint(crate::i18n::tr("System default")) + .width(220.0), + ); }); edit_file_rows(ui, t, "externalFile", &mut app.ui.settings.external_file); hint(ui, t, crate::i18n::tr("Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).")); @@ -309,7 +1137,10 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { row(ui, t, label, |ui| { let id = egui::Id::new(("settingsMeta", key)); let mut text: String = ui.data(|m| m.get_temp(id)).unwrap_or(value.clone()); - let r = ui.add(egui::TextEdit::singleline(&mut text).hint_text(hint_text).desired_width(240.0)); + // (the project's text field: Esc gives the text back and stays in Settings, and with + // the text back the line below has nothing to save) + let widget = format!("field:settings.{key}"); + let r = field(ui, crate::text_field::TextField::singleline(&widget, &mut text).hint(hint_text).width(240.0)); register(ui.ctx(), format!("field:settings.{key}"), r.rect); if r.lost_focus() && text.trim() != value { let _ = app.run("library.preferences", json!({"import": {key: text.trim()}})); @@ -344,11 +1175,22 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } }); } + auto_import(app, ui, t); +} + +/// XMP sidecars: whether changes are written beside the photos by themselves, and how the files +/// are named. +fn xmp_sidecars(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("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})); } + hint( + ui, + t, + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.", + ); row(ui, t, crate::i18n::tr("Sidecar names"), |ui| { use lightcraft_engine::sidecar::SidecarNaming as N; let mut n = xmp.naming; @@ -357,11 +1199,19 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let _ = app.run("library.xmpPreferences", json!({"naming": naming})); } }); +} + +/// Auto Import: the folder watched for new photos, and what is done with what arrives there. +fn auto_import(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + let d = app.session.import_defaults.clone(); if !cfg!(target_arch = "wasm32") { heading(ui, t, crate::i18n::tr("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| { - ui.label(RichText::new(d.auto_folder.clone().unwrap_or_else(|| crate::i18n::tr("Off").into())).color(t.text)); + match &d.auto_folder { + Some(folder) => path_label(ui, "settingsAutoFolder", folder, egui::TextStyle::Body.resolve(ui.style()), t.text), + None => drop(ui.label(RichText::new(crate::i18n::tr("Off")).color(t.text))), + } let can = app.services.pick_folder.is_some(); let r = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Choose…"))); register(ui.ctx(), "button:settingsAutoFolder", r.rect); @@ -383,9 +1233,13 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } }); row(ui, t, crate::i18n::tr("Album"), |ui| { - let id = egui::Id::new("auto-album"); + // (per library: a name left here by one library is not another's) + let id = egui::Id::new(("auto-album", app.session.library.as_ref().map(|l| l.dir.clone()))); let mut name = ui.data(|m| m.get_temp::(id)).unwrap_or_else(|| d.auto_album.clone().unwrap_or_default()); - let r = ui.add(egui::TextEdit::singleline(&mut name).hint_text(crate::i18n::tr("None")).desired_width(180.0)); + let r = field( + ui, + crate::text_field::TextField::singleline("field:settingsAutoAlbum", &mut name).hint(crate::i18n::tr("None")).width(180.0), + ); if r.lost_focus() { let _ = app.run("library.autoImport", json!({"album": name.trim()})); } @@ -410,7 +1264,7 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { None => "No usable GPU found: rendering on the CPU".to_string(), } } else { - format!("GPU: {}", gpu::adapter_name().unwrap_or_else(|| "starting…".into())) + format!("GPU: {}", gpu::adapter_name().unwrap_or_else(|| crate::i18n::tr("starting…").into())) }; hint(ui, t, &status); row(ui, t, crate::i18n::tr("Preview size"), |ui| { @@ -442,13 +1296,27 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { }); let used = app.session.media.rendered.disk().map(|d| d.size()); row(ui, t, crate::i18n::tr("In use"), |ui| { - ui.label(RichText::new(used.map(|b| format!("{:.1} MB", b as f64 / 1048576.0)).unwrap_or_else(|| "memory only".into())).color(t.text)); + ui.label( + RichText::new(used.map(|b| format!("{:.1} MB", b as f64 / 1048576.0)).unwrap_or_else(|| crate::i18n::tr("memory only").into())) + .color(t.text), + ); let r = ui.button(crate::i18n::tr("Clear Cache")); register(ui.ctx(), "button:settingsClearCache", r.rect); + let r = ask_first( + t, + "button:settingsClearCache", + r, + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.", + "Clear Cache", + ); if r.clicked() { let _ = app.run("library.clearPreviews", json!({})); } }); +} + +/// Local folders: when photos only seen in Local, never added or changed, leave the catalog. +fn local_folders(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("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")]; @@ -464,8 +1332,6 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.", ), ); - #[cfg(not(target_arch = "wasm32"))] - smart_previews(app, ui, t); } /// Where this library keeps its smart previews (the offline-editing proxies, which can be large): @@ -491,8 +1357,17 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let available = loc["available"].as_bool().unwrap_or(true); let custom = loc["custom"].as_bool().unwrap_or(false); row(ui, t, crate::i18n::tr("Folder"), |ui| { - let text = format!("{path}{}", if custom { "" } else { " (library default)" }); - ui.add(egui::Label::new(RichText::new(text.clone()).color(if available { t.text } else { t.reject })).truncate()).on_hover_text(text); + path_label( + ui, + "settingsSmartFolder", + &path, + egui::TextStyle::Body.resolve(ui.style()), + if available { t.text } else { t.legible(t.reject, t.chrome, 4.5) }, + ); + if !custom { + // (the catalogs have it with the two spaces it once followed a path with) + ui.label(RichText::new(crate::i18n::tr(" (library default)").trim()).color(t.text)); + } }); let (count, bytes) = (loc["count"].as_u64().unwrap_or(0), loc["bytes"].as_u64().unwrap_or(0)); if available { @@ -516,17 +1391,26 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ); } // what happens to the previews already built when the folder changes - let mode_id = egui::Id::new("smart-existing"); - let mut mode: u8 = ui.data(|d| d.get_temp(mode_id)).unwrap_or(0); + // That choice, and a change waiting for an answer, are kept from one frame of this section to + // the next only, and only for this library and this folder: with Settings closed, another + // tab or library opened, or the folder changed some other way, nothing is left chosen or asked. + let ask_id = egui::Id::new("smart-ask"); + let pass = ui.ctx().cumulative_pass_nr(); + let library = app.session.library.as_ref().map(|l| l.dir.display().to_string()).unwrap_or_default(); + let kept: Option = ui.data(|d| d.get_temp(ask_id)); + let mut ask = kept.filter(|k| k.pass.checked_add(1) == Some(pass) && k.library == library && k.folder == path).unwrap_or_default(); + let mut mode = ask.mode; if count > 0 { row(ui, t, crate::i18n::tr("Existing previews"), |ui| { - if choices(ui, "settingsSmartExisting", &[(0u8, "Move them"), (1, "Leave them"), (2, "Delete them")], &mut mode) { - ui.data_mut(|d| d.insert_temp(mode_id, mode)); - } + choices(ui, "settingsSmartExisting", &[(0u8, "Move them"), (1, "Leave them"), (2, "Delete them")], &mut mode); }); } - let existing = ["move", "leave", "discard"][mode.min(2) as usize]; - let mut result = None; + let mut existing = ["move", "leave", "discard"][mode.min(2) as usize]; + // Deleting the previews already built is asked about once more, when the folder they would + // be deleted for is known: until then the change (the command's parameters) waits here. + // (asked for "Delete them" only: choosing otherwise withdraws the question) + let mut waiting: Option = ask.waiting.take().filter(|_| existing == "discard"); + let mut change = None; ui.horizontal(|ui| { ui.add_space(LABEL_W); if app.services.pick_folder.is_some() { @@ -535,15 +1419,58 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { if r.clicked() && let Some(dir) = app.services.pick_folder.as_mut().and_then(|f| f()) { - result = Some(app.run("library.smartPreviewsLocation", json!({"path": dir, "existing": existing}))); + change = Some(json!({"path": dir, "existing": existing})); } } let r = ui.add_enabled(custom, egui::Button::new(crate::i18n::tr("Use Library Folder"))); register(ui.ctx(), "button:settingsSmartReset", r.rect); if r.clicked() { - result = Some(app.run("library.smartPreviewsLocation", json!({"reset": true, "existing": existing}))); + change = Some(json!({"reset": true, "existing": existing})); } }); + if existing == "discard" && count > 0 && change.is_some() { + waiting = change.take(); + } + let mut answered = false; + if let Some(params) = &waiting { + // (said with the count line above and two plain sentences, so no new format string is needed) + let how_many = + crate::i18n::tr_format!("{count} smart preview{} · {:.1} MB", if count == 1 { "" } else { "s" }, bytes as f64 / 1048576.0, count = count); + let question = format!( + "{} {how_many}. {}", + crate::i18n::tr("Delete the smart previews in the folder used until now?"), + crate::i18n::tr( + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected." + ), + ); + ui.add(egui::Label::new(RichText::new(question).color(t.legible(t.caution, t.chrome, 4.5))).wrap()); + ui.horizontal(|ui| { + let r = ui.button(crate::i18n::tr("Delete and Change Folder")); + register(ui.ctx(), "button:settingsSmartDelete", r.rect); + if r.clicked() { + // (what the section shows is up to two seconds old: the folder is asked for + // again, and a question about a folder that is no longer the one is dropped) + let still = app.run("library.smartPreviewsLocation", json!({})).is_ok_and(|now| now["path"].as_str() == Some(path.as_str())); + if still { + change = Some(params.clone()); + existing = "discard"; + } else { + ui.data_mut(|d| d.remove::<(f64, Value)>(cache)); + } + answered = true; + } + let r = ui.button(crate::i18n::tr("Cancel")); + register(ui.ctx(), "button:settingsSmartCancel", r.rect); + answered |= r.clicked(); + }); + } + if answered || change.is_some() { + // (the choice goes back to "Move them": deleting is never left set for the next time) + waiting = None; + mode = 0; + } + ui.data_mut(|d| d.insert_temp(ask_id, SmartAsk { pass, library, folder: path.clone(), mode, waiting })); + let result = change.map(|params| app.run("library.smartPreviewsLocation", params)); if let Some(r) = result { ui.data_mut(|d| d.remove::<(f64, Value)>(cache)); match r { @@ -602,13 +1529,13 @@ fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } }); if let Some(e) = &app.display_error { - ui.label(RichText::new(e).size(11.0).color(t.reject)); + ui.label(RichText::new(e).font(t.caption()).color(t.legible(t.reject, t.chrome, 4.5))); } if let Some(d) = ¤t { let info = d.describe(); if !screen { row(ui, t, crate::i18n::tr("File"), |ui| { - ui.label(RichText::new(&d.path).size(11.0).color(t.text_dim)); + path_label(ui, "settingsDisplayFile", &d.path, t.caption(), t.legible(t.text_dim, t.chrome, 4.5)); }); } row(ui, t, crate::i18n::tr("Type"), |ui| { @@ -622,7 +1549,7 @@ fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let p = &info["primaries"]; let xy = |(k, l): (&str, &str)| format!("{l} {:.3}, {:.3}", p[k][0].as_f64().unwrap_or(0.0), p[k][1].as_f64().unwrap_or(0.0)); let text = [("red", "R"), ("green", "G"), ("blue", "B")].map(xy).join(" "); - ui.label(RichText::new(text).size(11.0).color(t.text_dim)); + ui.label(RichText::new(text).font(t.caption()).color(t.legible(t.text_dim, t.chrome, 4.5))); }); } hint( @@ -702,7 +1629,8 @@ fn theme_card( ) { egui::Frame::new() .fill(t.inset) - .stroke(egui::Stroke::new(1.0, if active { t.accent } else { t.field_border })) + // (the card in use is outlined in the accent, legible as a line on the window) + .stroke(egui::Stroke::new(1.0, if active { t.legible(t.accent, t.chrome, 3.0) } else { t.field_border })) .corner_radius(6) .inner_margin(8) .show(ui, |ui| { @@ -712,7 +1640,7 @@ fn theme_card( ui.horizontal(|ui| { ui.label(RichText::new(crate::i18n::tr(title)).font(t.semibold(12.0)).color(t.text)); if active { - ui.label(RichText::new(crate::i18n::tr("In Use")).size(11.0).color(t.accent)); + ui.label(RichText::new(crate::i18n::tr("In Use")).font(t.caption()).color(t.legible(t.accent, t.inset, 4.5))); } }); let shown = options.iter().find(|(v, _)| v == value).or(options.first()).map(|(_, k)| *k).unwrap_or_default(); @@ -723,10 +1651,14 @@ fn theme_card( ui.horizontal(|ui| { let r = ui.radio_value(value, *v, crate::i18n::tr(kind.label())); register(ui.ctx(), format!("radio:theme-{}", kind.id()), r.rect); + // (ringed round the whole of it while it has the focus, as a checkbox is) + crate::widgets::focus_ring(ui, t, &r, r.rect.expand2(egui::vec2(3.0, 1.0))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let favorite = favorites.iter().any(|id| id == kind.id()); + // (always there, so that Tab reaches it; drawn while it is a + // favourite, under the mouse or has the focus) let r = ui - .add_visible(favorite || hovered, egui::Button::new("").min_size(egui::vec2(24.0, 24.0)).frame(false)) + .add(egui::Button::new("").min_size(egui::vec2(24.0, 24.0)).frame(false)) .on_hover_text(crate::i18n::tr(if favorite { "Remove from favorites" } else { "Add to favorites" })); r.widget_info(|| { egui::WidgetInfo::labeled( @@ -740,7 +1672,8 @@ fn theme_card( ) }); register(ui.ctx(), format!("button:themeFavorite-{}", kind.id()), r.rect); - if favorite || hovered { + crate::widgets::focus_ring(ui, t, &r, r.rect); + if favorite || hovered || r.has_focus() { crate::icons::paint( ui.painter(), r.rect.shrink(4.0), @@ -1182,3 +2115,48 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(test)] +mod path_tests { + use super::elide_path; + + /// Width = characters, so a limit of 20 is "20 characters". + fn fit(path: &str, max: usize) -> String { + elide_path(path, max as f32, |s| s.chars().count() as f32) + } + + #[test] + fn a_path_that_fits_is_left_alone() { + assert_eq!(fit("/Users/me/Pictures", 18), "/Users/me/Pictures"); + assert_eq!(fit("", 5), ""); + } + + #[test] + fn leading_folders_go_first_and_the_end_stays() { + assert_eq!(fit("/Users/me/Pictures/Library", 20), "…/Pictures/Library"); + assert_eq!(fit("/Users/me/Pictures/Library", 10), "…/Library"); + } + + /// Windows paths: `Path::display` gives backslashes there. + #[test] + fn a_path_with_backslashes_keeps_its_end_too() { + assert_eq!(fit(r"C:\Users\me\Pictures\Library", 20), r"…\Pictures\Library"); + assert_eq!(fit(r"C:\Users\me/Pictures\Library", 10), r"…\Library"); + } + + #[test] + fn a_last_folder_too_long_by_itself_loses_its_end() { + assert_eq!(fit("/Users/me/a-very-long-folder-name", 8), "a-very-…"); + assert_eq!(fit("no-separator-at-all", 8), "no-sepa…"); + assert_eq!(fit("/Users/Фотографии-из-отпуска", 8), "Фотогра…"); + } + + #[test] + fn a_separator_at_the_end_is_not_where_the_name_starts() { + assert_eq!(fit("/Users/me/Pictures/Library/", 11), "…/Library/"); + assert_eq!(fit("/Users/me/a-very-long-folder-name/", 8), "a-very-…"); + assert_eq!(fit(r"C:\Users\me\Library\", 11), r"…\Library\"); + assert_eq!(fit("///", 2), "…"); + assert_eq!(fit(r"\\server\share\folder", 15), r"…\share\folder"); + } +} diff --git a/crates/ui-egui/src/panels/topbar.rs b/crates/ui-egui/src/panels/topbar.rs index 03810aca96b..2fe0ca3c8f8 100644 --- a/crates/ui-egui/src/panels/topbar.rs +++ b/crates/ui-egui/src/panels/topbar.rs @@ -98,7 +98,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.new_child(egui::UiBuilder::new().max_rect(sr.shrink2(vec2(10.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); let empty = app.ui.search.is_empty(); if empty && !focused { - let g = child.painter().layout_no_wrap(crate::i18n::tr("Search Photos").into(), t.font(13.5), t.text_dim); + let g = child.painter().layout_no_wrap(crate::i18n::tr("Search Photos").into(), t.body(), t.text_dim); let w = g.size().x + 24.0; let x0 = sr.center().x - w / 2.0; paint(child.painter(), Rect::from_min_size(pos2(x0, sr.center().y - 8.0), vec2(16.0, 16.0)), Icon::Search, t.text_dim); @@ -108,7 +108,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { .label(crate::i18n::tr("Search Photos")) .frame(false) .width(sr.width() - 20.0) - .font(t.font(13.5)) + .font(t.body()) .text_color(t.text) .show(&mut child) .response; @@ -138,7 +138,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if active > 0 { let c = fr.right_top() + vec2(-3.0, 8.0); ui.painter().circle_filled(c, 7.0, t.accent); - ui.painter().text(c, Align2::CENTER_CENTER, active.to_string(), t.semibold(9.5), t.canvas); + ui.painter().text(c, Align2::CENTER_CENTER, active.to_string(), t.micro_strong(), t.ink_on(t.accent)); } let fresp = fresp.on_hover_text(if active > 0 { crate::i18n::tr_format!("Filter bar — {active} active filter{}", if active == 1 { "" } else { "s" }, active = active) @@ -183,7 +183,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if warn { let c = r.right_top() + vec2(-5.0, 6.0); ui.painter().circle_filled(c, 6.0, t.reject); - ui.painter().text(c, Align2::CENTER_CENTER, "!", t.semibold(9.5), t.canvas); + ui.painter().text(c, Align2::CENTER_CENTER, "!", t.micro_strong(), t.ink_on(t.reject)); register(ui.ctx(), "indicator:unsaved", r); } if resp.clicked() && !cmd.is_empty() { diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 0b730db7811..6d700b518cc 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -257,8 +257,8 @@ pub fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed, i: usize } if let Some(name) = &f.suggestion { p.rect_filled(strip, 0.0, Color32::from_black_alpha(165)); - let label = super::people::fit(p, name, t.font(11.5), r.width() - 18.0); - p.text(pos2(r.left() + 5.0, strip.center().y), Align2::LEFT_CENTER, format!("{label}?"), t.font(11.5), Color32::from_gray(225)); + let label = super::people::fit(p, name, t.caption(), r.width() - 18.0); + p.text(pos2(r.left() + 5.0, strip.center().y), Align2::LEFT_CENTER, format!("{label}?"), t.caption(), Color32::from_gray(225)); } if let (Some(a), Some(who)) = (&accept, &f.suggestion) && a.clone().on_hover_text(format!("Name this face {who}")).clicked() diff --git a/crates/ui-egui/src/readout.rs b/crates/ui-egui/src/readout.rs new file mode 100644 index 00000000000..4c6c26e9538 --- /dev/null +++ b/crates/ui-egui/src/readout.rs @@ -0,0 +1,289 @@ +//! How the interface writes what it reads off a photo or a control: one way to say an exposure, +//! a minus that is a minus, figures that stand in columns, and a file name shortened in the +//! middle so that its number stays. +//! +//! Before: one exposure read "f / 2.8", "f/2.8" and "f/2.8" with "35 mm" and "35mm", "1/250 sec", +//! "1/250 s" and "1/250" in four places, each in its own order; a negative value had a hyphen; +//! Inter's figures are of unequal width, so a value changed its left edge while it was dragged +//! and counts did not line up; and a long file name on the filmstrip lost its end, where the +//! number of the frame is. + +use std::sync::Arc; + +use egui::{Color32, FontId}; +use lightcraft_catalog::Meta; + +/// The sign of a negative number. +pub(crate) const MINUS: char = '\u{2212}'; + +/// An aperture: "f/2.8", "f/11". Nothing for a number that is none. +pub(crate) fn aperture(f: f32) -> Option { + if !f.is_finite() || f <= 0.0 { + return None; + } + let tenths = (f64::from(f) * 10.0).round(); + Some(if tenths % 10.0 == 0.0 { format!("f/{:.0}", tenths / 10.0) } else { format!("f/{:.1}", tenths / 10.0) }) +} + +/// A focal length: "35 mm", "16.5 mm". +pub(crate) fn focal(mm: f32) -> Option { + if !mm.is_finite() || mm <= 0.0 { + return None; + } + let tenths = (f64::from(mm) * 10.0).round(); + Some(if tenths % 10.0 == 0.0 { format!("{:.0} mm", tenths / 10.0) } else { format!("{:.1} mm", tenths / 10.0) }) +} + +/// A shutter speed as the catalog holds it ("1/250", "8"), with its unit in the language of the +/// interface: "1/250 sec". One that names its unit already ("30s") stays as it is. +pub(crate) fn shutter(held: &str) -> Option { + let held = held.trim(); + if held.is_empty() { + return None; + } + Some(if held.ends_with(|c: char| c.is_alphabetic()) { held.to_string() } else { crate::i18n::tr_format!("{} sec", held) }) +} + +/// A sensitivity: "ISO 100". +pub(crate) fn iso(iso: u32) -> String { + format!("ISO {iso}") +} + +/// What a photo was taken with, in the order a photographer says it: shutter speed, aperture, +/// sensitivity, focal length. Only what the photo has. +pub(crate) fn exposure(m: &Meta) -> Vec { + [shutter(&m.shutter), m.aperture.and_then(aperture), m.iso.map(iso), m.focal_mm.and_then(focal)].into_iter().flatten().collect() +} + +/// [`exposure`] on one line ("1/250 sec · f/2.8 · ISO 100 · 35 mm"), or nothing. +pub(crate) fn exposure_line(m: &Meta) -> Option { + Some(exposure(m)).filter(|parts| !parts.is_empty()).map(|parts| parts.join(" · ")) +} + +/// A number as written by `format!`, with a minus for its hyphen ("−1.25"). +pub(crate) fn signed(written: &str) -> String { + match written.strip_prefix('-') { + Some(rest) => format!("{MINUS}{rest}"), + None => written.to_string(), + } +} + +/// The widths of the characters of `text` in `font`, and of the font's widest figure. +fn widths(painter: &egui::Painter, text: &str, font: &FontId) -> (Vec<(char, f32)>, f32) { + painter.ctx().fonts_mut(|fonts| { + let cell = ('0'..='9').map(|c| fonts.glyph_width(font, c)).fold(0.0, f32::max); + (text.chars().map(|c| (c, fonts.glyph_width(font, c))).collect(), cell) + }) +} + +/// The room a figure lacks to fill a cell as wide as the widest figure (none for other characters). +fn room(c: char, width: f32, cell: f32) -> f32 { + if c.is_ascii_digit() && width.is_finite() { (cell - width).max(0.0) } else { 0.0 } +} + +/// `text` on one line with every figure in a cell as wide as the widest figure of the font, so +/// that numbers stand in columns and a changing value keeps its place. (The font's own figures +/// are of unequal width, and egui cannot ask it for its tabular ones.) The text of the galley is +/// `text` unchanged. +/// +/// A figure stands at the end of its cell, so the galley is as wide as its cells: for a count, +/// which is figures only. A number with a sign is [`value`]'s. +pub(crate) fn figures(painter: &egui::Painter, text: &str, font: FontId, color: Color32) -> Arc { + let (widths, cell) = widths(painter, text, &font); + let mut job = egui::text::LayoutJob::default(); + job.wrap.max_width = f32::INFINITY; + let mut buffer = [0u8; 4]; + for (c, width) in widths { + job.append(c.encode_utf8(&mut buffer), room(c, width, cell), egui::TextFormat { font_id: font.clone(), color, ..Default::default() }); + } + painter.layout_job(job) +} + +/// A value ("−1.25", "+100") painted to end at `right_center`, each figure in the middle of a +/// cell as wide as the widest figure: the value begins and ends where any other of as many +/// figures does, and a narrow 1 does not stand off from its sign. Returns where it is. +pub(crate) fn value(painter: &egui::Painter, right_center: egui::Pos2, text: &str, font: FontId, color: Color32) -> egui::Rect { + let (widths, cell) = widths(painter, text, &font); + let mut job = egui::text::LayoutJob::default(); + job.wrap.max_width = f32::INFINITY; + let mut buffer = [0u8; 4]; + // (half a figure's room before it and half after; what is after is given as room before + // the next character, and after the last by where the galley is put) + let mut after = 0.0; + for (c, width) in widths { + let half = room(c, width, cell) / 2.0; + job.append(c.encode_utf8(&mut buffer), after + half, egui::TextFormat { font_id: font.clone(), color, ..Default::default() }); + after = half; + } + let galley = painter.layout_job(job); + let size = galley.size() + egui::vec2(after, 0.0); + let rect = egui::Rect::from_min_size(egui::pos2(right_center.x - size.x, right_center.y - size.y / 2.0), size); + painter.galley(rect.min, galley, color); + rect +} + +/// `text` shortened in the middle to fit `max` (as `width` measures it): the start and the end +/// stay, the end a character longer when they cannot be equal ("IMG_2024…153012"), for the end +/// of a file name is the number of the frame. Cuts fall between letters as a reader sees them (a +/// letter keeps its combining marks: an accent written apart, an Arabic vowel sign); what cannot +/// fit at all is "…". +pub(crate) fn elide_middle(text: &str, max: f32, width: impl Fn(&str) -> f32) -> String { + if width(text) <= max { + return text.to_string(); + } + let chars: Vec<&str> = unicode_segmentation::UnicodeSegmentation::graphemes(text, true).collect(); + let kept = |keep: usize| { + let tail = keep.div_ceil(2); + let head = keep - tail; + let mut out: String = chars.iter().take(head).copied().collect(); + out.push('…'); + out.extend(chars.iter().skip(chars.len().saturating_sub(tail)).copied()); + out + }; + // the most characters that fit (fewer never measure wider than more, near enough: the + // result is measured again below) + let (mut fits, mut too_many) = (0usize, chars.len()); + while fits + 1 < too_many { + let middle = fits + (too_many - fits) / 2; + if width(&kept(middle)) <= max { + fits = middle; + } else { + too_many = middle; + } + } + (0..=fits).rev().map(kept).find(|out| width(out) <= max).unwrap_or_else(|| "…".to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_exposure_is_said_one_way() { + crate::i18n::set_language(crate::i18n::Locale::En); + // Given what four photos were taken with + assert_eq!(aperture(2.8).as_deref(), Some("f/2.8")); + assert_eq!(aperture(11.0).as_deref(), Some("f/11")); + assert_eq!(aperture(10.04).as_deref(), Some("f/10")); + assert_eq!(aperture(1.4).as_deref(), Some("f/1.4")); + assert_eq!(focal(35.0).as_deref(), Some("35 mm")); + assert_eq!(focal(16.5).as_deref(), Some("16.5 mm")); + assert_eq!(focal(100.0).as_deref(), Some("100 mm")); + assert_eq!(shutter("1/250").as_deref(), Some("1/250 sec")); + assert_eq!(shutter("8").as_deref(), Some("8 sec")); + assert_eq!(shutter("30s").as_deref(), Some("30s")); + assert_eq!(iso(100), "ISO 100"); + // Then a photo's line gives them in a photographer's order, and leaves out what it lacks + let m = Meta { shutter: "1/250".into(), aperture: Some(2.8), iso: Some(100), focal_mm: Some(35.0), ..Default::default() }; + assert_eq!(exposure_line(&m).as_deref(), Some("1/250 sec · f/2.8 · ISO 100 · 35 mm")); + let m = Meta { aperture: Some(11.0), ..Default::default() }; + assert_eq!(exposure_line(&m).as_deref(), Some("f/11")); + assert_eq!(exposure_line(&Meta::default()), None); + } + + #[test] + fn a_number_that_is_none_says_nothing() { + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -2.8] { + assert_eq!(aperture(bad), None, "{bad}"); + assert_eq!(focal(bad), None, "{bad}"); + } + assert_eq!(shutter(""), None); + assert_eq!(shutter(" "), None); + // (a number too large to be a lens is still written, not a crash) + assert_eq!(focal(f32::MAX).map(|s| s.ends_with(" mm")), Some(true)); + } + + #[test] + fn a_negative_number_has_a_minus() { + assert_eq!(signed("-1.25"), "−1.25"); + assert_eq!(signed("+35"), "+35"); + assert_eq!(signed("0"), "0"); + assert_eq!(signed("-"), "−"); + assert_eq!(signed(""), ""); + // (only the sign: a range keeps its hyphen) + assert_eq!(signed("16-35"), "16-35"); + } + + #[test] + fn figures_stand_in_cells_of_one_width() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut output = ctx.run_ui(Default::default(), |ui| { + let t = crate::theme::Tokens::for_kind(crate::theme::ThemeKind::Charcoal); + let wide = |s: &str| figures(ui.painter(), s, t.body(), Color32::WHITE).size().x; + let plain = |s: &str| ui.painter().layout_no_wrap(s.to_string(), t.body(), Color32::WHITE).size().x; + // Given numbers of as many figures, the narrowest and the widest + // Then they are as wide as one another, which as the font draws them they are not + assert!((plain("111") - plain("444")).abs() > 2.0, "the font's own figures differ: {} and {}", plain("111"), plain("444")); + // (to a tenth of a point: a glyph is placed on a whole pixel) + assert!((wide("111") - wide("444")).abs() < 0.1, "{} and {}", wide("111"), wide("444")); + assert!((wide("+100") - wide("+111")).abs() < 0.1); + // (beside a point the font moves a figure a little, as it does a letter) + assert!((wide("−1.25") - wide("−4.04")).abs() < 1.0, "{} and {}", wide("−1.25"), wide("−4.04")); + assert!((plain("−1.11") - plain("−4.44")).abs() > 4.0); + // And what is not a figure is as the font has it, and the text is unchanged + assert!((wide("ISO") - plain("ISO")).abs() < 0.1); + assert_eq!(figures(ui.painter(), "−1.25", t.body(), Color32::WHITE).job.text, "−1.25"); + assert_eq!(figures(ui.painter(), "", t.body(), Color32::WHITE).size().x, 0.0); + // And a value with a sign ends where it is told to and begins where any other of as + // many figures does, its 1 no farther from the sign than half its room + let at = egui::pos2(300.0, 40.0); + let (narrow, wide) = + (value(ui.painter(), at, "−1.11", t.body(), Color32::WHITE), value(ui.painter(), at, "−4.44", t.body(), Color32::WHITE)); + assert_eq!((narrow.right(), wide.right()), (300.0, 300.0)); + assert!((narrow.left() - wide.left()).abs() < 1.0, "{narrow:?} {wide:?}"); + assert_eq!(value(ui.painter(), at, "", t.body(), Color32::WHITE).width(), 0.0); + }); + // (nothing is painted: the font atlas made for the measuring is not uploaded anywhere) + output.textures_delta.clear(); + } + + #[test] + fn a_long_name_loses_its_middle_and_keeps_its_number() { + // (a character is a unit wide here) + let width = |s: &str| s.chars().count() as f32; + assert_eq!(elide_middle("DSC_0001", 14.0, width), "DSC_0001"); + assert_eq!(elide_middle("IMG_20240712_153012", 14.0, width), "IMG_20…_153012"); + assert_eq!(elide_middle("IMG_20240712_153012", 5.0, width), "IM…12"); + assert_eq!(elide_middle("IMG_20240712_153012", 2.0, width), "…2"); + assert_eq!(elide_middle("IMG_20240712_153012", 1.0, width), "…"); + assert_eq!(elide_middle("IMG_20240712_153012", 0.0, width), "…"); + assert_eq!(elide_middle("IMG_20240712_153012", f32::NAN, width), "…"); + assert_eq!(elide_middle("", 0.0, width), ""); + // the name from #266: cuts fall on characters, not bytes + assert_eq!(elide_middle("202407層三限定訂閱圖(4)", 9.0, width), "2024…圖(4)"); + // a very long name is not measured once a character + let long = "x".repeat(100_000); + let measured = std::cell::Cell::new(0usize); + let counting = |s: &str| { + measured.set(measured.get() + 1); + s.chars().count() as f32 + }; + assert_eq!(elide_middle(&long, 9.0, counting).chars().count(), 9); + assert!(measured.get() < 40, "{} measurements", measured.get()); + } + + /// Scenario: a name written with combining marks (an accented name as macOS stores it, a vowelled + /// Arabic one) is cut between letters, never between a letter and its mark: no mark is left on the "…". + #[test] + fn a_cut_never_parts_a_letter_from_its_mark() { + // (a letter with its mark is a unit wide here, as it is drawn) + let width = |s: &str| s.chars().filter(|c| !('\u{300}'..='\u{36f}').contains(c) && !('\u{64b}'..='\u{652}').contains(c)).count() as f32; + // Given "été" eight times over, each é an e and a combining acute + let accented = "e\u{301}te\u{301}".repeat(8); + // and a vowelled Arabic word, each letter with its haraka + let vowelled = "\u{643}\u{64e}\u{62a}\u{64e}\u{628}\u{64e}".repeat(6); + for name in [accented.as_str(), vowelled.as_str()] { + for max in 2..12 { + // When it is shortened to any width + let short = elide_middle(name, max as f32, width); + // Then what follows the "…" starts with a letter, and both parts are parts of the name + let (head, tail) = short.split_once('…').expect("shortened"); + let first = tail.chars().next(); + assert!(first.is_none_or(|c| width(&c.to_string()) > 0.0), "{max}: a mark on the ellipsis in {short:?}"); + assert!(name.starts_with(head) && name.ends_with(tail), "{max}: {short:?}"); + assert!(width(&short) <= max as f32, "{max}: {short:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/tests_crop_rotate.rs b/crates/ui-egui/src/tests_crop_rotate.rs index 8e27411ebff..f249d33b380 100644 --- a/crates/ui-egui/src/tests_crop_rotate.rs +++ b/crates/ui-egui/src/tests_crop_rotate.rs @@ -108,7 +108,7 @@ fn the_angle_reads_like_the_straighten_value() { use crate::panels::detail::crop_angle_label; assert_eq!(crop_angle_label(0.0), "0.00°", "as the Angle field shows it at rest"); assert_eq!(crop_angle_label(2.5), "+2.50°"); - assert_eq!(crop_angle_label(-12.254), "-12.25°"); + assert_eq!(crop_angle_label(-12.254), "−12.25°", "with a minus, as a slider's value has"); assert_eq!(crop_angle_label(-0.001), "0.00°", "no minus zero, and every zero the same"); } diff --git a/crates/ui-egui/src/tests_dialog_fit.rs b/crates/ui-egui/src/tests_dialog_fit.rs index 0014c6bdb34..ed4bebf907c 100644 --- a/crates/ui-egui/src/tests_dialog_fit.rs +++ b/crates/ui-egui/src/tests_dialog_fit.rs @@ -98,7 +98,8 @@ fn export_dialog_is_unchanged_in_a_tall_window() { // (#236), so it is 876 tall there) let height = if cfg!(target_os = "macos") { 876.0 } else { 846.0 }; assert!((dialog.height() - height).abs() <= 1.0, "{dialog:?}"); - assert!((dialog.width() - 615.2).abs() <= 1.0, "{dialog:?}"); + // (602 wide since the format row's choices are set at caption size, 11 pt where they were 11.5) + assert!((dialog.width() - 602.0).abs() <= 1.0, "{dialog:?}"); } // Scenario: other long dialogs fit a short window too, with their buttons on screen diff --git a/crates/ui-egui/src/tests_dialog_settings.rs b/crates/ui-egui/src/tests_dialog_settings.rs new file mode 100644 index 00000000000..9a7414eb040 --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings.rs @@ -0,0 +1,332 @@ +//! The Settings window is one size in one place whatever tab is open, and lies inside the app +//! window: a row with more choices than fit wraps, a label longer than its column wraps, a long +//! folder path is cut short (its tooltip has all of it), and the tabs stay put while a page scrolls. +//! +//! Before, a wide row widened the whole window: General was 970 points wide and the other tabs +//! about 600, the window moved up and down between tabs, and in a 900 point wide app window the +//! row labels and the Close button of General were cut off at the left. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::panels::settings::TABS; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +/// The app window sizes tried: roomy, the desktop minimum, and smaller than that. +const SIZES: [[f32; 2]; 3] = [[1600.0, 1000.0], [900.0, 560.0], [640.0, 480.0]]; + +fn headless(session: lightcraft_engine::Session, size: [f32; 2]) -> Headless { + let mut h = Headless::new(LightcraftApp::new(session, 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 demo(size: [f32; 2]) -> Headless { + headless(lightcraft_engine::Session::with_demo(), size) +} + +/// Given Settings open on `tab`, drawn until its layout has settled. +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); + for _ in 0..4 { + h.step(); + } +} + +/// A folder under the system's temporary one, removed again when the test ends, passed or not. +struct TempFolder(std::path::PathBuf); + +impl TempFolder { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("lc-ui-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Self(dir) + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn rect(h: &Headless, id: &str) -> egui::Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +/// The controls the Settings window registers on the tab that is open (and its tab buttons). +fn controls(h: &Headless) -> Vec<(String, egui::Rect)> { + let named = |id: &str| id.split_once(':').is_some_and(|(_, name)| name.starts_with("settings") || name.starts_with("theme")); + h.app.widgets.iter().filter(|(id, _)| named(id)).cloned().collect() +} + +fn same(a: egui::Rect, b: egui::Rect) -> bool { + (a.min - b.min).abs().max_elem() < 0.5 && (a.max - b.max).abs().max_elem() < 0.5 +} + +#[test] +fn the_window_keeps_its_size_and_place_from_tab_to_tab() { + for size in SIZES { + let mut h = demo(size); + // Given the first tab, when every other tab is opened in turn + show(&mut h, "general"); + let first = rect(&h, "dialog:window"); + for (tab, _) in TABS { + show(&mut h, tab); + // Then the window has not moved or changed size + let now = rect(&h, "dialog:window"); + assert!(same(first, now), "{size:?}: Settings is {now:?} on {tab}, and was {first:?} on general"); + } + // And going back to the first tab finds it as it was + show(&mut h, "general"); + assert!(same(first, rect(&h, "dialog:window")), "{size:?}: general again"); + } +} + +#[test] +fn every_tab_keeps_its_controls_inside_the_window() { + for size in SIZES { + let mut h = demo(size); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, h.size); + for (tab, _) in TABS { + // When a tab is opened + show(&mut h, tab); + // Then the Settings window lies inside the app window + let window = rect(&h, "dialog:window"); + assert!(screen.contains_rect(window), "{size:?} {tab}: Settings {window:?} runs off the {screen:?} window"); + // And no control reaches past its left or right edge + // (the page is everything the tab drew, whether or not it has a name of its own; a + // control past the room for it would be clipped there, inside the window's margin) + let (page, room) = (rect(&h, "settings:page"), rect(&h, "settings:pageRoom")); + assert!( + page.left() >= room.left() - 0.5 && page.right() <= room.right() + 0.5, + "{size:?} {tab}: the page {page:?} is wider than the room for it {room:?}" + ); + assert!(window.contains_rect(room), "{size:?} {tab}: the page's room {room:?} is inside Settings {window:?}"); + for (id, r) in controls(&h) { + let within = if id.contains("settingsTab-") { window } else { room }; + assert!(r.left() >= within.left() - 0.5 && r.right() <= within.right() + 0.5, "{size:?} {tab}: {id} {r:?} is outside {within:?}"); + } + } + } +} + +#[test] +fn a_row_of_many_choices_wraps_under_itself() { + // Given an app window too narrow for the languages in one line + let mut h = demo([900.0, 560.0]); + show(&mut h, "general"); + let languages: Vec = (0..crate::i18n::Locale::ALL.len()).map(|i| rect(&h, &format!("button:settingsLanguage-{i}"))).collect(); + // Then they take more than one line + let first = languages[0]; + assert!(languages.iter().any(|r| r.top() > first.bottom()), "the languages wrap: {languages:?}"); + // And each further line starts under the first choice, not under the row's label + for r in languages.iter().filter(|r| r.top() > first.bottom()) { + assert!(r.left() >= first.left() - 0.5, "{r:?} starts left of the first language {first:?}"); + } + assert!( + languages.iter().filter(|r| r.top() > first.bottom()).any(|r| (r.left() - first.left()).abs() < 0.5), + "a wrapped line starts at the first choice" + ); +} + +#[test] +fn a_label_longer_than_its_column_leaves_the_controls_in_line() { + // Given Library, whose "Forget unchanged photos" label is wider than the label column + let mut h = demo([1600.0, 1000.0]); + show(&mut h, "library"); + // Then its choices start where the control of a short label does + let (short, long) = (rect(&h, "text:settingsLocation"), rect(&h, "button:settingsForgetLocal-0")); + assert!((short.left() - long.left()).abs() < 0.5, "Location starts at {} and Forget unchanged photos at {}", short.left(), long.left()); +} + +#[test] +fn a_long_library_folder_is_cut_short_and_its_tooltip_has_all_of_it() { + // Given a library in a folder with a very long path + let base = TempFolder::new("settings-window"); + let dir = + base.0.join("photographs-from-2019-to-2026-kept-on-the-second-external-drive-that-nobody-wants-to-type-twice").join("the-master-library"); + std::fs::create_dir_all(&dir).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&dir, true).unwrap(); + let path = dir.display().to_string(); + + let mut h = headless(session, [1600.0, 1000.0]); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, h.size); + // When Settings opens on Library, which shows where the library is + show(&mut h, "library"); + let library = rect(&h, "dialog:window"); + show(&mut h, "display"); + // Then the window is as wide as on a tab without a path + assert!(same(library, rect(&h, "dialog:window")), "Library is {library:?} with a long path, Display is {:?}", rect(&h, "dialog:window")); + show(&mut h, "library"); + assert!(screen.contains_rect(library), "Settings {library:?} runs off the {screen:?} window"); + // And the path is cut short, inside the window + let location = rect(&h, "text:settingsLocation"); + let room = rect(&h, "settings:pageRoom"); + assert!(location.right() <= room.right() + 0.5, "the path {location:?} stays inside the room for the page {room:?}"); + let texts = h.painted_text(); + assert!(!texts.iter().any(|text| text.contains(&path)), "the whole path is not drawn in the row"); + // And what is left of it is its end, which says which library this is + let name = "the-master-library"; + assert!(path.ends_with(name)); + assert!( + texts.iter().any(|text| text.starts_with('…') && text.ends_with(name)), + "the row keeps the end of the path: {:?}", + texts.iter().filter(|t| t.contains("library")).collect::>() + ); + // And resting the pointer on it shows the whole path + assert_eq!(h.request("ui.hoverWidget", json!({"id": "text:settingsLocation"}), T)["ok"], true); + assert!(h.step_until(T, |h| h.painted_text().iter().any(|text| text.contains(&path))), "the tooltip has the whole path"); + + // And the same holds for the folder Auto Import watches, which stays on one line + let watched = h.app.run("library.autoImport", json!({"folder": path})); + assert!(watched.is_ok(), "{watched:?}"); + show(&mut h, "import"); + // (the row is at the foot of the page: scrolled to, so that it is drawn however long the page is) + let window = rect(&h, "dialog:window"); + h.request("ui.move", json!({"x": window.center().x, "y": window.center().y}), T); + for _ in 0..6 { + h.request("ui.scroll", json!({"dy": -400.0}), T); + h.step(); + } + h.settle(T); + let (folder, room) = (rect(&h, "text:settingsAutoFolder"), rect(&h, "settings:pageRoom")); + assert!(room.intersects(folder), "the watched folder {folder:?} is in view in {room:?}"); + assert!(folder.height() < 24.0 && folder.right() <= room.right(), "the watched folder {folder:?} is one line inside {room:?}"); + assert!(h.painted_text().iter().any(|text| text.starts_with('…') && text.ends_with(name)), "and keeps its end"); + drop(h); +} + +#[test] +fn a_short_path_is_shown_whole_and_has_no_tooltip() { + // Given the in-memory library, whose Location is a short sentence + let mut h = demo([1600.0, 1000.0]); + show(&mut h, "library"); + assert!(h.painted_text().iter().any(|text| text == "In memory — nothing is saved"), "it is all there"); + let before = h.painted_text().len(); + // When the pointer rests on it + assert_eq!(h.request("ui.hoverWidget", json!({"id": "text:settingsLocation"}), T)["ok"], true); + let _ = h.step_until(Duration::from_secs(2), |h| h.painted_text().len() > before); + // Then nothing more is drawn: there is nothing a tooltip could add + assert_eq!(h.painted_text().len(), before, "no tooltip for a path that is all there"); +} + +/// How many pixels of `rect` are not `colour` (one pixel per point here). +fn other_than(image: &egui::ColorImage, rect: egui::Rect, colour: egui::Color32) -> usize { + let [w, h] = image.size; + let (x0, x1) = (rect.left().round().max(0.0) as usize, (rect.right().round().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().round().max(0.0) as usize, (rect.bottom().round().max(0.0) as usize).min(h)); + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|(x, y)| image.pixels[y * w + x] != colour).count() +} + +#[test] +fn a_page_that_goes_on_below_shows_a_scroll_handle_without_the_pointer_on_it() { + let mut h = demo([900.0, 560.0]); + let chrome = crate::theme::Tokens::get(&h.view.ctx).chrome; + // (the pointer is nowhere near the window) + h.request("ui.move", json!({"x": 5.0, "y": 5.0}), T); + let handle = |h: &Headless| { + let room = rect(h, "settings:pageRoom"); + other_than(&h.paint(), egui::Rect::from_min_max(egui::pos2(room.right() - 6.0, room.top()), room.max), chrome) + }; + // Given Appearance, which is taller than the room a 560 pt tall app window has for it + show(&mut h, "interface"); + assert!(rect(&h, "settings:page").height() > rect(&h, "settings:pageRoom").height()); + // Then a handle is drawn at the page's right edge + assert!(handle(&h) > 40, "Appearance shows a scroll handle ({} px)", handle(&h)); + // And Display, which fits, has none + show(&mut h, "display"); + assert!(rect(&h, "settings:page").height() <= rect(&h, "settings:pageRoom").height()); + assert_eq!(handle(&h), 0, "Display has nothing to scroll"); +} + +#[test] +fn a_window_too_short_for_a_page_of_its_own_scrolls_tabs_and_page_together() { + // Given an app window far below the desktop minimum + let mut h = demo([900.0, 220.0]); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, h.size); + show(&mut h, "import"); + let window = rect(&h, "dialog:window"); + assert!(screen.contains_rect(window), "Settings {window:?} is inside the {screen:?} window"); + let (tab, page) = (rect(&h, "button:settingsTab-import"), rect(&h, "check:settings.perCamera")); + // When it is scrolled + h.request("ui.move", json!({"x": window.center().x, "y": window.center().y}), T); + for _ in 0..3 { + h.request("ui.scroll", json!({"dy": -120.0}), T); + h.step(); + } + h.settle(T); + // Then the tabs and the page move as one, so every setting can still be reached + let (tab_now, page_now) = (rect(&h, "button:settingsTab-import"), rect(&h, "check:settings.perCamera")); + assert!(page_now.top() < page.top() - 50.0, "the page scrolled: {page:?} -> {page_now:?}"); + assert!(((tab.top() - tab_now.top()) - (page.top() - page_now.top())).abs() < 0.5, "tabs and page moved together"); + assert!(same(window, rect(&h, "dialog:window")), "the window did not move"); +} + +#[test] +fn the_tabs_stay_put_while_a_page_scrolls() { + // Given a page taller than the window has room for + let mut h = demo([900.0, 560.0]); + show(&mut h, "interface"); + let window = rect(&h, "dialog:window"); + let tabs: Vec = TABS.iter().map(|(id, _)| rect(&h, &format!("button:settingsTab-{id}"))).collect(); + let page_before = rect(&h, "button:settingsAppearance-0"); + // When the page is scrolled + h.request("ui.move", json!({"x": window.center().x, "y": window.center().y}), T); + for _ in 0..3 { + h.request("ui.scroll", json!({"dy": -120.0}), T); + h.step(); + } + h.settle(T); + // Then the page moved + let page_after = rect(&h, "button:settingsAppearance-0"); + assert!(page_after.top() < page_before.top() - 50.0, "the page scrolled: {page_before:?} -> {page_after:?}"); + // And the tabs and the window did not + for ((id, _), before) in TABS.iter().zip(tabs) { + assert!(same(before, rect(&h, &format!("button:settingsTab-{id}"))), "tab {id} moved"); + } + assert!(same(window, rect(&h, "dialog:window")), "the window moved"); +} + +#[test] +fn each_tab_remembers_how_far_it_was_scrolled() { + let mut h = demo([900.0, 560.0]); + show(&mut h, "import"); + let fresh = rect(&h, "check:settings.perCamera"); + // Given Appearance scrolled down + show(&mut h, "interface"); + let window = rect(&h, "dialog:window"); + let top = rect(&h, "button:settingsAppearance-0").top(); + h.request("ui.move", json!({"x": window.center().x, "y": window.center().y}), T); + for _ in 0..3 { + h.request("ui.scroll", json!({"dy": -120.0}), T); + h.step(); + } + h.settle(T); + // (the scroll glides to where it is going: read where it comes to rest) + let mut scrolled = rect(&h, "button:settingsAppearance-0").top(); + for _ in 0..200 { + h.step(); + let now = rect(&h, "button:settingsAppearance-0").top(); + if (now - scrolled).abs() < 0.01 { + break; + } + scrolled = now; + } + assert!(scrolled < top - 50.0); + // When another tab is opened, it starts at its top + show(&mut h, "import"); + let mode = rect(&h, "check:settings.perCamera"); + assert!(same(fresh, mode), "Import is at its top, as when first opened: {fresh:?} -> {mode:?}"); + // And Appearance is where it was left + show(&mut h, "interface"); + assert!((rect(&h, "button:settingsAppearance-0").top() - scrolled).abs() < 0.5, "Appearance is where it was left"); +} diff --git a/crates/ui-egui/src/tests_dialog_settings_contrast.rs b/crates/ui-egui/src/tests_dialog_settings_contrast.rs new file mode 100644 index 00000000000..05acd102252 --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings_contrast.rs @@ -0,0 +1,308 @@ +//! What Settings says and marks can be read in every theme: its explanations, placeholders, +//! cautions and the accent used as text stand 4.5:1 against what they are on, and the lines that +//! say where a control or the tab bar is stand 3:1. No text in it uses a character the interface +//! font lacks. +//! +//! Before: explanations were 4.20:1 in Charcoal and 4.33:1 in Silver, "In Use" 2.9:1 in Charcoal, +//! placeholders under 4.3:1 in every theme, the borders of text boxes and checkboxes 1.6 to 1.7:1 +//! and the line under the tabs 1.2 to 1.4:1; and the hint under External Editing drew two empty +//! boxes where its menu path had arrows. + +use std::time::Duration; + +use egui::Color32; +use serde_json::json; + +use crate::headless::Headless; +use crate::panels::settings::TABS; +use crate::theme::{ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(kind: ThemeKind) -> Headless { + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), [1200.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + let r = h.request("engine.execute", json!({"command": "view.theme", "params": {"theme": kind.id()}}), T); + assert_eq!(r["ok"], true, "{r}"); + h +} + +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); + for _ in 0..4 { + h.step(); + } + // (the pointer away from the window: nothing is hovered) + h.request("ui.move", json!({"x": 3.0, "y": 3.0}), T); + h.step(); + h.step(); +} + +fn rect(h: &Headless, id: &str) -> egui::Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +/// WCAG contrast of two opaque colours. +fn contrast(a: Color32, b: Color32) -> f32 { + let lum = |c: Color32| { + let lin = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b()) + }; + let (a, b) = (lum(a), lum(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) +} + +/// The colour a piece of text is drawn in: the first text shape that has `part`. +fn text_colour(h: &Headless, part: &str) -> Color32 { + fn find(shape: &egui::Shape, part: &str) -> Option { + match shape { + egui::Shape::Text(text) if text.galley.job.text.contains(part) => { + let own = text.galley.job.sections.first().map(|s| s.format.color).filter(|c| *c != Color32::PLACEHOLDER); + Some(text.override_text_color.or(own).unwrap_or(text.fallback_color)) + } + egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| find(shape, part)), + _ => None, + } + } + h.view.painted_shapes().iter().find_map(|shape| find(shape, part)).unwrap_or_else(|| panic!("no text with {part:?} is drawn")) +} + +/// The most any pixel of `rect` stands out from `ground` (one pixel per point here). +fn strongest(image: &egui::ColorImage, rect: egui::Rect, ground: Color32) -> f32 { + let [w, h] = image.size; + let (x0, x1) = (rect.left().floor().max(0.0) as usize, (rect.right().ceil().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().floor().max(0.0) as usize, (rect.bottom().ceil().max(0.0) as usize).min(h)); + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).map(|(x, y)| contrast(image.pixels[y * w + x], ground)).fold(1.0, f32::max) +} + +#[test] +fn a_colour_is_made_legible_only_where_it_is_not() { + for kind in ThemeKind::ALL { + let t = Tokens::for_kind(kind); + // Given the colours Settings writes and marks in, on the surfaces it puts them on + for (what, colour, on, ratio) in [ + ("an explanation", t.text_dim, t.chrome, 4.5), + ("a caution", t.caution, t.chrome, 4.5), + ("a refusal", t.reject, t.chrome, 4.5), + ("the accent as text on a card", t.accent, t.inset, 4.5), + ("a placeholder", t.text_dim, t.field, 4.5), + ("the line under the tabs", t.divider, t.chrome, 3.0), + ("a control's border", t.button_border, t.chrome, 3.0), + ] { + // Then the legible one stands the ratio asked for + let legible = t.legible(colour, on, ratio); + assert!(contrast(legible, on) >= ratio, "{kind:?}: {what} is {:.2}:1, wants {ratio}", contrast(legible, on)); + // And a colour that stood it already is left as it is + if contrast(colour, on) >= ratio { + assert_eq!(legible, colour, "{kind:?}: {what} was legible and is unchanged"); + } + } + // And even the surface's own colour is brought to stand on it + assert!(contrast(t.legible(t.chrome, t.chrome, 4.5), t.chrome) >= 4.5); + } + // (a ratio nothing can reach, or one that is not a number, ends at the text colour too) + let t = Tokens::for_kind(ThemeKind::Charcoal); + assert_eq!(t.legible(t.text_dim, t.chrome, 99.0), t.text); + assert_eq!(t.legible(t.text_dim, t.chrome, f32::NAN), t.text); +} + +#[test] +fn explanations_placeholders_and_the_accent_as_text_can_be_read_in_every_theme() { + for kind in ThemeKind::ALL { + let mut h = demo(kind); + let t = Tokens::for_kind(kind); + // An explanation under a setting + show(&mut h, "performance"); + let hint = text_colour(&h, "Choose a size to cap"); + assert!(contrast(hint, t.chrome) >= 4.5, "{kind:?}: an explanation is {:.2}:1", contrast(hint, t.chrome)); + // The filter's placeholder, on the box it is in + let placeholder = text_colour(&h, "Filter settings"); + assert!(contrast(placeholder, t.field) >= 4.5, "{kind:?}: a placeholder is {:.2}:1", contrast(placeholder, t.field)); + // "In Use" on the card of the theme that is shown + show(&mut h, "interface"); + let in_use = text_colour(&h, "In Use"); + assert!(contrast(in_use, t.inset) >= 4.5, "{kind:?}: In Use is {:.2}:1", contrast(in_use, t.inset)); + } +} + +#[test] +fn what_the_filter_found_can_be_read_with_the_pointer_or_the_focus_on_it() { + for kind in ThemeKind::ALL { + let mut h = demo(kind); + let t = Tokens::for_kind(kind); + show(&mut h, "general"); + let r = h.request("ui.clickWidget", json!({"id": "field:settingsFilter"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.request("ui.text", json!({"text": "clear cache"}), T); + for _ in 0..4 { + h.step(); + } + // (the line under a result's title; a hovered or focused row has the hover fill behind it) + let snippet = text_colour(&h, "Clear Cache"); + assert!( + contrast(snippet, t.hover) >= 4.5 && contrast(snippet, t.chrome) >= 4.5, + "{kind:?}: a result's text is {:.2}:1 on a hovered row", + contrast(snippet, t.hover) + ); + } +} + +#[test] +fn the_lines_that_say_where_a_control_is_stand_out_in_every_theme() { + for kind in ThemeKind::ALL { + let mut h = demo(kind); + let t = Tokens::for_kind(kind); + show(&mut h, "performance"); + let image = h.paint(); + // The line under the tabs: just under a tab that is not open, so its own line is not there + let tab = rect(&h, "button:settingsTab-library"); + let under = egui::Rect::from_min_max(egui::pos2(tab.left(), tab.bottom().round()), egui::pos2(tab.right(), tab.bottom().round() + 1.0)); + assert!(strongest(&image, under, t.chrome) >= 3.0, "{kind:?}: the line under the tabs is {:.2}:1", strongest(&image, under, t.chrome)); + // A text box's border: the filter's top edge + let filter = rect(&h, "field:settingsFilter"); + let edge = egui::Rect::from_min_max( + egui::pos2(filter.center().x - 20.0, filter.top() - 1.0), + egui::pos2(filter.center().x + 20.0, filter.top() + 2.0), + ); + assert!(strongest(&image, edge, t.chrome) >= 3.0, "{kind:?}: a text box's border is {:.2}:1", strongest(&image, edge, t.chrome)); + // A checkbox's border: the left edge of its box (unticked: the GPU is off here) + let check = rect(&h, "check:settings.gpu"); + let side = + egui::Rect::from_min_max(egui::pos2(check.left() - 1.0, check.center().y - 2.0), egui::pos2(check.left() + 5.0, check.center().y + 2.0)); + assert!(strongest(&image, side, t.chrome) >= 3.0, "{kind:?}: a checkbox's border is {:.2}:1", strongest(&image, side, t.chrome)); + } +} + +#[test] +fn no_text_in_settings_uses_a_character_the_font_lacks() { + let mut h = demo(ThemeKind::Charcoal); + for (tab, _) in TABS { + show(&mut h, tab); + // (▸ has no glyph in the interface's fonts: it draws as an empty box) + for text in h.painted_text() { + assert!(!text.contains('▸'), "{tab}: {text:?} has an arrow the font cannot draw"); + } + } +} + +/// What Settings says that no language had a word for: every catalog has each of these now. +const ONCE_UNTRANSLATED: [&str; 27] = [ + "Choose Profile…", + "Delete and Change Folder", + "Delete the smart previews in the folder used until now?", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).", + "External Editing", + "Faces", + "Found automatically", + "Keep", + "LUT-based", + "Matrix/TRC", + "Model installation failed", + "Monitor profile", + "None (the display is treated as sRGB)", + "On, every change to a photo's edits or metadata is written to an XMP file beside the photo, for other apps to read. Off, that happens when you choose Save Metadata to File in the Photo menu.", + "Other 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.", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.", + "Photos whose originals are not connected are shown and edited from their smart previews; new ones can only be made from originals that are connected.", + "Primaries (x, y)", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.", + "The download failed", + "The model's file is deleted. To use it again you download or add it again.", + "Thumbnails and previews are made again as you browse, which takes a while in a large library. Your photos and edits are not touched.", + "Use Screen Profile", + "Use sRGB", + "starting…", + "this screen's profile", +]; + +#[test] +fn every_language_has_the_sentences_settings_was_missing() { + use crate::i18n::Locale; + for language in Locale::ALL.iter().copied().filter(|language| *language != Locale::En) { + for source in ONCE_UNTRANSLATED { + let said = language.tr(source); + // (German says Matrix as English does, and TRC is TRC everywhere) + let same_word = source == "Matrix/TRC" && language == Locale::De; + assert!(said != source || same_word, "{}: {source:?} is still in English", language.code()); + assert!(!said.trim().is_empty() && !said.contains('▸'), "{}: {source:?} -> {said:?}", language.code()); + } + } +} + +#[test] +fn the_sentences_settings_was_missing_are_the_ones_it_says() { + // (a sentence reworded in the code and not here would leave its translations orphaned) + let sources = + [include_str!("panels/settings.rs"), include_str!("panels/denoise.rs"), include_str!("panels/faces.rs"), include_str!("widgets.rs")].concat(); + for source in ONCE_UNTRANSLATED { + let literal = format!("{source:?}"); + assert!(sources.contains(&literal), "{source:?} is no longer said by Settings as written here"); + } +} + +#[test] +fn a_choice_a_radio_and_a_question_have_borders_that_stand_out_too() { + for kind in ThemeKind::ALL { + let mut h = demo(kind); + let t = Tokens::for_kind(kind); + // A choice that is not the chosen one: its left edge (Performance, the second preview size) + show(&mut h, "performance"); + let image = h.paint(); + let choice = rect(&h, "button:settingsPreview-1"); + let side = egui::Rect::from_min_max( + egui::pos2(choice.left() - 1.0, choice.center().y - 3.0), + egui::pos2(choice.left() + 2.0, choice.center().y + 3.0), + ); + assert!(strongest(&image, side, t.chrome) >= 3.0, "{kind:?}: a choice's border is {:.2}:1", strongest(&image, side, t.chrome)); + // The question a button asks before it acts: the border of its Keep button, on the panel it is in + let r = h.request("ui.clickWidget", json!({"id": "button:settingsClearCache"}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..4 { + h.step(); + } + h.request("ui.move", json!({"x": 3.0, "y": 3.0}), T); + h.step(); + h.step(); + let image = h.paint(); + let confirm = rect(&h, "button:settingsClearCache:confirm"); + let top = egui::Rect::from_min_max( + egui::pos2(confirm.center().x - 10.0, confirm.top() - 1.0), + egui::pos2(confirm.center().x + 10.0, confirm.top() + 2.0), + ); + assert!(strongest(&image, top, t.chrome) >= 3.0, "{kind:?}: a button in the question is {:.2}:1", strongest(&image, top, t.chrome)); + h.request("ui.key", json!({"key": "Escape"}), T); + h.step(); + // A radio button on a theme's card, which is on the card's own fill: the one not chosen + show(&mut h, "interface"); + let image = h.paint(); + let other = if kind == ThemeKind::Midnight { "radio:theme-charcoal" } else { "radio:theme-midnight" }; + let radio = rect(&h, other); + let ring = + egui::Rect::from_min_max(egui::pos2(radio.left() - 1.0, radio.center().y - 2.0), egui::pos2(radio.left() + 4.0, radio.center().y + 2.0)); + assert!(strongest(&image, ring, t.inset) >= 3.0, "{kind:?}: a radio button on a card is {:.2}:1", strongest(&image, ring, t.inset)); + } +} + +#[test] +fn the_menu_path_a_hint_gives_is_the_one_the_menus_show() { + use crate::i18n::Locale; + // (the hint under External Editing says where the command is: in each language it names the + // menu items as that language's menus do) + let hint = ONCE_UNTRANSLATED.iter().find(|source| source.starts_with("Photo > Edit In > Edit in PhotoCraft")).unwrap(); + for language in Locale::ALL.iter().copied().filter(|language| *language != Locale::En) { + let said = language.tr(hint); + for item in ["Edit In", "Edit in PhotoCraft"] { + let name = language.tr(item); + assert!(name != item, "{}: the menu item {item:?} has no translation", language.code()); + assert!(said.contains(name), "{}: the hint does not name {name:?}: {said:?}", language.code()); + } + } +} 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 00000000000..5630235c1b8 --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings_filter.rs @@ -0,0 +1,292 @@ +//! 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: nine 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 + 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), ["files:XMP sidecars"]); + assert!(says(&h, "Files") && 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), ["library:Local folders"]); + // (a button) + filter(&mut h, "Clear Cache"); + assert_eq!(found(&h), ["performance:Thumbnail cache"]); + // (a hint, in other letter case) + filter(&mut h, "FOR OTHER APPS TO READ"); + assert_eq!(found(&h), ["files:XMP sidecars"]); + // (a tab's own name finds everything on it) + filter(&mut h, "Appearance"); + 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:Thumbnail cache".to_string()), "{cache:?}"); + // When a second word narrows it + filter(&mut h, "cache limit"); + assert_eq!(found(&h), ["performance:Thumbnail cache"]); + // And the words can come in any order + filter(&mut h, "limit cache"); + assert_eq!(found(&h), ["performance:Thumbnail 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()); +} + +#[test] +fn choosing_a_result_opens_its_tab_at_that_section() { + // (a window short enough that Detail, at the foot of Appearance, is below the fold) + let mut h = demo([900.0, 560.0]); + show(&mut h, "general"); + filter(&mut h, "info overlay"); + assert_eq!(found(&h), ["interface:Detail"]); + // When the result is clicked + click(&mut h, "settingsFound:interface:Detail"); + 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").unwrap(), rect(&h, "settings:pageRoom").unwrap()); + assert!(detail.top() >= room.top() - 0.5 && detail.bottom() <= room.bottom() + 0.5, "Detail {detail:?} is in view in {room:?}"); +} + +#[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: "files".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 limit"); + assert_eq!(found(&h), ["performance:Thumbnail 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()); +} diff --git a/crates/ui-egui/src/tests_dialog_settings_filter_words.rs b/crates/ui-egui/src/tests_dialog_settings_filter_words.rs new file mode 100644 index 00000000000..e8b61721262 --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings_filter_words.rs @@ -0,0 +1,586 @@ +//! The filter of Settings finds what people type, puts the best match first and shows why it +//! matched: words a section does not say itself ("trash" for Recently Deleted), either spelling +//! of a word (color, colour), a section named for the word before one that only mentions it, +//! the match in the middle of the line under a result and told apart from the rest, no folder +//! paths among what is looked through, the box ready to type in when Settings opens, and the +//! section landed on marked for a moment. +//! +//! Before, "color" and "trash" found nothing, "detail" + Return opened General ▸ Startup (the +//! first tab that says it) and not Appearance ▸ Detail, a long explanation was cut off before +//! the word it was shown for, the name of the library's folder was a search word, the box had to +//! be clicked first, and nothing said which section of the opened tab had been chosen. + +use std::path::PathBuf; +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 has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +/// What the filter lists, top to bottom: `tab:section` of each result. +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() +} + +/// The galleys painted that have `part` in their text. +fn galleys(h: &Headless, part: &str) -> Vec> { + h.view + .painted_shapes() + .into_iter() + .filter_map(|shape| match shape { + egui::epaint::Shape::Text(text) if text.galley.job.text.contains(part) => Some(text.galley.clone()), + _ => None, + }) + .collect() +} + +/// A line of text as it was painted, with the fills painted behind it. +struct Line { + text: egui::epaint::TextShape, + /// (where, in what colour), left to right + marks: Vec<(egui::Rect, egui::Color32)>, +} + +impl Line { + /// The letters that stand on each fill, as they are drawn from left to right (a mark drawn + /// on a letter is not counted beside it). + fn told_apart(&self) -> Vec { + let marked = |mark: &egui::Rect| { + // (a fill reaches a point past the letters at either end, and a glyph is placed on a + // whole pixel: the middle of a space beside them may be just inside it) + let mark = mark.shrink2(egui::vec2(1.5, 0.0)); + let rows = self.text.galley.rows.iter(); + rows.flat_map(|row| row.glyphs.iter().map(move |glyph| (self.text.pos + row.pos.to_vec2() + glyph.pos.to_vec2(), glyph))) + .filter(|(at, glyph)| { + glyph.advance_width > 0.0 && mark.x_range().contains(at.x + glyph.advance_width / 2.0) && mark.y_range().contains(at.y) + }) + .map(|(_, glyph)| glyph.chr) + .collect() + }; + self.marks.iter().map(|(mark, _)| marked(mark)).collect() + } + + /// The colour the line is in. + fn colour(&self) -> egui::Color32 { + self.text.galley.job.sections.first().map_or(self.text.fallback_color, |section| section.format.color) + } +} + +/// The lines among `shapes` (in the order painted) that have `part` in their text. +fn lines_of(shapes: &[egui::epaint::Shape], part: &str) -> Vec { + let mut lines = Vec::new(); + for (place, shape) in shapes.iter().enumerate() { + let egui::epaint::Shape::Text(text) = shape else { continue }; + if !text.galley.job.text.contains(part) { + continue; + } + // (a fill behind the line: painted before it, and no larger than the line is) + let room = text.galley.rect.translate(text.pos.to_vec2()).expand(2.0); + let mut marks: Vec<_> = shapes[..place] + .iter() + .filter_map(|shape| match shape { + egui::epaint::Shape::Rect(rect) if room.contains_rect(rect.rect) && rect.fill.a() > 0 => Some((rect.rect, rect.fill)), + _ => None, + }) + .collect(); + marks.sort_by(|a, b| a.0.left().total_cmp(&b.0.left())); + lines.push(Line { text: text.clone(), marks }); + } + lines +} + +fn lines(h: &Headless, part: &str) -> Vec { + lines_of(&h.view.painted_shapes(), part) +} + +#[test] +fn a_word_people_type_for_a_section_finds_it_though_the_section_does_not_say_it() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // "trash": Culling says "Recently Deleted" + filter(&mut h, "trash"); + assert_eq!(found(&h), ["general:Culling"]); + // "theme" is said by Appearance; "scheme" is not + filter(&mut h, "scheme"); + assert_eq!(found(&h), ["interface:Appearance"]); + // And such a word counts with the others typed: every word still has to be there + filter(&mut h, "trash confirm"); + assert_eq!(found(&h), ["general:Culling"]); + filter(&mut h, "trash gpu"); + assert!(found(&h).is_empty()); + // And the start of such a word finds it, as part of any word does: the section stays found + // while the word is typed + filter(&mut h, "tras"); + assert_eq!(found(&h), ["general:Culling"]); + // And a section that says the word comes before one that is only given it + filter(&mut h, "metadata"); + let found = found(&h); + let place = |id: &str| found.iter().position(|f| f == id).unwrap_or_else(|| panic!("{id} in {found:?}")); + assert!(place("import:Metadata") < place("files:XMP sidecars"), "{found:?}"); +} + +#[test] +fn either_spelling_of_a_word_finds_it() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // Monitor ▸ Monitor profile says "colours" + filter(&mut h, "colours"); + let british = found(&h); + assert!(british.contains(&"display:Monitor profile".to_string()), "{british:?}"); + filter(&mut h, "colors"); + assert_eq!(found(&h), british, "color finds what colour finds"); + // And the word is told apart in the line under the result, in the spelling the line has + let lines = lines(&h, "colours"); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0].told_apart(), ["colours"], "\"colours\" is told apart for \"colors\""); + // And on the way to either spelling, letter by letter, the section stays found + // (Monitor profile says "colours"; External Editing and Appearance are given "color") + for typed in ["col", "colo", "colou", "colour", "color"] { + filter(&mut h, typed); + for section in ["display:Monitor profile", "files:External Editing", "interface:Appearance"] { + assert!(found(&h).contains(§ion.to_string()), "{typed} finds {section}: {:?}", found(&h)); + } + } + // And with another word beside it + for typed in ["colo space", "colou space", "colour space"] { + filter(&mut h, typed); + assert_eq!(found(&h), ["files:External Editing"], "{typed}"); + } + // And for a word Settings has in the one spelling only (Library is given "catalog") + for typed in ["catalo", "catalog", "catalogu", "catalogue"] { + filter(&mut h, typed); + assert!(found(&h).contains(&"library:Library".to_string()), "{typed}: {:?}", found(&h)); + } +} + +#[test] +fn a_section_named_for_the_word_comes_before_one_that_mentions_it() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // "detail": the name of a section of Appearance, a choice of General ▸ Startup, and a word + // in an explanation of Performance ▸ Rendering and of Monitor ▸ Monitor profile + filter(&mut h, "detail"); + assert_eq!(found(&h), ["interface:Detail", "general:Startup", "performance:Rendering", "display:Monitor profile"]); + // And Return opens the best match, not the first tab that has the word + key(&mut h, "Enter"); + h.settle(T); + steps(&mut h); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "interface".into() })); +} + +#[test] +fn sections_that_match_alike_stay_in_the_order_of_the_tabs() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // "never" is a choice in Library ▸ Local folders and in Appearance ▸ Grid, a name of neither + filter(&mut h, "never"); + assert_eq!(found(&h), ["library:Local folders", "interface:Grid"]); +} + +#[test] +fn the_line_under_a_result_shows_the_word_it_was_found_by_and_tells_it_apart() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // "wide-gamut" stands far into the explanation under Monitor ▸ Monitor profile + filter(&mut h, "wide-gamut"); + assert_eq!(found(&h), ["display:Monitor profile"]); + // (the filter box says the word too: the line under the result is the one with more to it) + let lines: Vec<_> = galleys(&h, "wide-gamut").into_iter().filter(|line| line.job.text != "wide-gamut").collect(); + assert_eq!(lines.len(), 1, "one line says it"); + let line = &lines[0]; + // Then the line starts shortly before the word, with a sign that something was left out + let text = &line.job.text; + assert!(text.starts_with('…'), "{text}"); + assert!(text.find("wide-gamut").unwrap() < 60, "the word is near the start of what is shown: {text}"); + // And the word is in sight: the line is cut after it, not before + let laid_out: String = line.rows.iter().flat_map(|row| row.glyphs.iter().map(|glyph| glyph.chr)).collect(); + assert!(laid_out.contains("wide-gamut"), "what is drawn of the line has the word: {laid_out}"); + // And the word is drawn apart from the words around it: it has a fill behind it, they have none + let marked: Vec<_> = self::lines(&h, "wide-gamut").into_iter().filter(|line| line.text.galley.job.text != "wide-gamut").collect(); + assert_eq!(marked[0].told_apart(), ["wide-gamut"]); +} + +#[test] +fn a_short_line_is_shown_whole_with_the_word_told_apart_whatever_its_case() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "NAVIGATOR"); + assert_eq!(found(&h), ["interface:Detail"]); + let lines = lines(&h, "Show the Navigator while zoomed in"); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0].text.galley.job.text, "Show the Navigator while zoomed in"); + assert_eq!(lines[0].told_apart(), ["Navigator"]); +} + +#[test] +fn letters_found_inside_a_word_are_marked_behind_it_and_the_word_is_drawn_whole() { + // Given a result found by letters in the middle of a word + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // When Settings draws the line under the result + filter(&mut h, "aviga"); + assert_eq!(found(&h), ["interface:Detail"]); + let lines = lines(&h, "Show the Navigator while zoomed in"); + assert_eq!(lines.len(), 1); + let line = &lines[0]; + // Then the line is one piece of text in one format: the word is not cut where the letters + // found start and end (each piece would be shaped by itself: no kerning across the cut, and + // in a joined script the letters on either side of it left unjoined) + let job = &line.text.galley.job; + let pieces: Vec<&str> = job.sections.iter().map(|section| &job.text[section.byte_range.start.0..section.byte_range.end.0]).collect(); + assert_eq!(pieces, ["Show the Navigator while zoomed in"], "the line is laid out as one piece"); + // And the letters found, and no others, have a fill behind them + assert_eq!(line.told_apart(), ["aviga"]); + // And the fill is within the line's row + let row = line.text.galley.rect.translate(line.text.pos.to_vec2()); + let (mark, _) = line.marks[0]; + assert!(row.y_range().contains(mark.top()) && row.y_range().contains(mark.bottom()), "{mark:?} in {row:?}"); +} + +/// Scenario: the letters found are told apart by more than a colour: a line is drawn under them. +#[test] +fn the_letters_found_are_underlined_so_that_colour_is_not_the_only_sign() { + use crate::theme::{ThemeKind, Tokens}; + for kind in ThemeKind::ALL { + // Given a theme, and a result found by letters inside a word + let mut h = demo([1200.0, 1000.0]); + let r = h.request("engine.execute", json!({"command": "view.theme", "params": {"theme": kind.id()}}), T); + assert_eq!(r["ok"], true, "{r}"); + let t = Tokens::for_kind(kind); + show(&mut h, "general"); + // When Settings draws the line under the result + filter(&mut h, "aviga"); + let shapes = h.view.painted_shapes(); + let lines = lines_of(&shapes, "Show the Navigator while zoomed in"); + assert_eq!(lines.len(), 1, "{kind:?}"); + let (mark, fill) = lines[0].marks[0]; + // Then a line runs under the letters found, from their first to their last, in the lower part of the row + let under: Vec<_> = shapes + .iter() + .filter_map(|shape| match shape { + egui::epaint::Shape::LineSegment { points, stroke } if (points[0].y - points[1].y).abs() < 0.01 => Some((points, stroke)), + _ => None, + }) + .filter(|(points, _)| mark.y_range().contains(points[0].y) && points[0].y > mark.center().y) + .filter(|(points, _)| { + (points[0].x.min(points[1].x) - mark.left()).abs() <= 1.5 && (points[0].x.max(points[1].x) - mark.right()).abs() <= 1.5 + }) + .collect(); + assert_eq!(under.len(), 1, "{kind:?}: one line under the letters found, {mark:?}"); + // And it can be seen without telling colours apart: 3:1 on the fill and on the row + let stroke = under[0].1; + assert!(stroke.width >= 1.0, "{kind:?}: {stroke:?}"); + for on in [fill, t.chrome, t.hover] { + // (`legible` leaves a colour as it is when it already stands at the ratio asked) + assert_eq!(t.legible(stroke.color, on, 3.0), stroke.color, "{kind:?}: the line under the letters on {on:?}"); + } + } +} + +#[test] +fn the_letters_found_can_be_read_on_their_fill_in_every_theme() { + use crate::theme::{ThemeKind, Tokens}; + for kind in ThemeKind::ALL { + // Given a theme, and a result found by letters inside a word + let mut h = demo([1200.0, 1000.0]); + let r = h.request("engine.execute", json!({"command": "view.theme", "params": {"theme": kind.id()}}), T); + assert_eq!(r["ok"], true, "{r}"); + let t = Tokens::for_kind(kind); + show(&mut h, "general"); + filter(&mut h, "aviga"); + let lines = lines(&h, "Show the Navigator while zoomed in"); + let line = &lines[0]; + let (_, fill) = *line.marks.first().unwrap_or_else(|| panic!("{kind:?}: the letters found have a fill")); + // Then the line, which is in one colour, stands 4.5:1 on the fill (a colour that does is + // left as it is by `legible`), as on a row with the pointer or the focus on it, or neither + let colour = line.colour(); + for (ground, what) in [(fill, "the fill"), (t.hover, "a hovered row"), (t.chrome, "a plain row")] { + assert_eq!(t.legible(colour, ground, 4.5), colour, "{kind:?}: {colour:?} on {what} ({ground:?})"); + } + // And the fill is not the colour of a row, hovered or not: it is seen on both + assert!(fill != t.hover && fill != t.chrome, "{kind:?}"); + } +} + +#[test] +fn letters_found_inside_an_arabic_word_leave_its_letters_joined() { + use crate::theme::Tokens; + if !lightcraft_engine::CRAFT_FONTS.iter().any(|font| font.covers("Arab")) { + eprintln!("no Arabic face in craft-fonts: nothing to check"); + return; + } + // Given a line with an Arabic word, found by letters in its middle (Settings has no Arabic + // yet: the line is made by hand and drawn as the line under a result is) + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let t = Tokens::default(); + let line = "Preview المعاينة size"; + let at = line.find("معاين").unwrap(); + let found = at..at + "معاين".len(); + // When it is drawn + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 100.0)); + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + crate::panels::settings::found_line(ui, &t, line.to_string(), std::slice::from_ref(&found)); + }); + output.textures_delta.clear(); + let mut shapes = Vec::new(); + fn flat(shape: &egui::epaint::Shape, out: &mut Vec) { + match shape { + egui::epaint::Shape::Vec(shapes) => shapes.iter().for_each(|shape| flat(shape, out)), + other => out.push(other.clone()), + } + } + output.shapes.iter().for_each(|clipped| flat(&clipped.shape, &mut shapes)); + let lines = lines_of(&shapes, "المعاينة"); + assert_eq!(lines.len(), 1); + let drawn = &lines[0].text.galley; + // Then the line is as wide as the same line with nothing found in it: the word's letters + // join one another as they do there (a word cut at the letters found is three pieces, each + // with the forms letters have at a word's start and end, and is wider) + let format = egui::TextFormat { font_id: t.font(11.0), ..Default::default() }; + let plain = ctx.fonts_mut(|fonts| fonts.layout_job(egui::text::LayoutJob::single_section(line.to_string(), format))); + let glyphs = |galley: &egui::Galley| galley.rows.iter().map(|row| row.glyphs.len()).sum::(); + assert_eq!(glyphs(drawn), glyphs(&plain)); + assert!((drawn.size().x - plain.size().x).abs() < 0.01, "drawn {} wide, the plain line {}", drawn.size().x, plain.size().x); + // And the fill is behind the letters found: they are drawn from right to left + let told: Vec = lines[0].told_apart().iter().map(|letters| letters.chars().rev().collect()).collect(); + assert_eq!(told, ["معاين"]); +} + +/// Scenario: a Persian word holds a zero-width non-joiner (it keeps two letters from joining). The +/// letters found in the word, and those found after it, are still the ones marked. +#[test] +fn a_non_joiner_inside_a_word_does_not_move_the_marks() { + use crate::theme::Tokens; + if !lightcraft_engine::CRAFT_FONTS.iter().any(|font| font.covers("Arab")) { + eprintln!("no Arabic face in craft-fonts: nothing to check"); + return; + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let t = Tokens::default(); + // Given a line with such a word and a Latin word after it + let line = "می\u{200c}خواهم ok"; + let told = |part: &str| { + let at = line.find(part).unwrap(); + let found = at..at + part.len(); + // When it is drawn with `part` found in it + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 100.0)); + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + crate::panels::settings::found_line(ui, &t, line.to_string(), std::slice::from_ref(&found)); + }); + output.textures_delta.clear(); + fn flat(shape: &egui::epaint::Shape, out: &mut Vec) { + match shape { + egui::epaint::Shape::Vec(shapes) => shapes.iter().for_each(|shape| flat(shape, out)), + other => out.push(other.clone()), + } + } + let mut shapes = Vec::new(); + output.shapes.iter().for_each(|clipped| flat(&clipped.shape, &mut shapes)); + let lines = lines_of(&shapes, "ok"); + assert_eq!(lines.len(), 1); + lines[0].told_apart() + }; + // Then the Latin word after it is the one marked, not the letters a place before it + assert_eq!(told("ok"), ["ok"]); + // And letters found in the word itself are marked (drawn from right to left) + let inside: Vec = told("خواه").iter().map(|letters| letters.chars().rev().collect()).collect(); + assert_eq!(inside, ["خواه"]); +} + +/// A folder under the system's temporary one, removed again when the test ends, passed or not. +struct TempFolder(PathBuf); + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn the_names_of_folders_are_not_looked_through() { + // Given a library on disk in a folder with a word of its own in its name + let dir = TempFolder(std::env::temp_dir().join(format!("lc-ui-filterwords-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir_all(&dir.0).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(dir.0.join("zebrafolder"), false).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services::default()), [1200.0, 1000.0], 1.0); + h.app.ui.dialog = Some(Dialog::Settings { tab: "library".into() }); + steps(&mut h); + assert!(h.painted_text().iter().any(|text| text.contains("zebrafolder")), "Library ▸ Location shows the folder"); + // When a word of the folder's name is typed + filter(&mut h, "zebrafolder"); + // Then nothing is found: where a library happens to be is not a setting's name + assert!(found(&h).is_empty(), "{:?}", found(&h)); + // And the row that shows it is still found by what it is called + filter(&mut h, "location"); + assert_eq!(found(&h).first().map(String::as_str), Some("library:Library")); +} + +#[test] +fn what_stands_where_a_folder_would_is_still_found_when_it_is_no_folder() { + // Given the demo, whose library is in memory: Library ▸ Location says so where a folder would stand + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "library"); + assert!(h.painted_text().iter().any(|text| text.contains("nothing is saved"))); + filter(&mut h, "nothing is saved"); + assert_eq!(found(&h), ["library:Library"]); +} + +#[test] +fn what_is_typed_into_a_box_of_settings_is_not_looked_through() { + let mut h = demo([1200.0, 1000.0]); + // Given an editor of the person's own, in a folder with a word of its own + h.app.ui.settings.external_editor = "/opt/zebraedit/bin/zed".into(); + show(&mut h, "files"); + assert!(h.painted_text().iter().any(|text| text.contains("zebraedit"))); + // Then that folder is not a word a section is found by + filter(&mut h, "zebraedit"); + assert!(found(&h).is_empty(), "{:?}", found(&h)); + // And "bin" finds Culling (where photos are thrown away), not the editor's folder + filter(&mut h, "bin"); + assert_eq!(found(&h), ["general:Culling"]); +} + +#[test] +fn the_filter_is_ready_to_type_in_when_settings_opens() { + let mut h = demo([1200.0, 1000.0]); + // When Settings is opened and something is typed, without a click + show(&mut h, "general"); + assert_eq!(h.view.ctx.memory(|m| m.focused()), Some(crate::text_field::id("field:settingsFilter"))); + h.request("ui.text", json!({"text": "culling"}), T); + steps(&mut h); + // Then it went into the filter + assert_eq!(found(&h), ["general:Culling"]); + // And a tab opened afterwards does not take the focus back to the box + click(&mut h, "button:settingsTab-performance"); + assert_ne!(h.view.ctx.memory(|m| m.focused()), Some(crate::text_field::id("field:settingsFilter"))); + // And Esc in the empty box, as it opens, closes Settings in one press + key(&mut h, "Escape"); + h.app.ui.dialog = None; + steps(&mut h); + show(&mut h, "general"); + key(&mut h, "Escape"); + assert_eq!(h.app.ui.dialog, None); +} + +#[test] +fn the_section_landed_on_is_marked_for_a_moment() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + assert!(!has(&h, "settingsLanded:Culling")); + filter(&mut h, "info overlay"); + click(&mut h, "settingsFound:interface:Detail"); + steps(&mut h); + // Then the heading of the section chosen is marked, and no other + assert!(has(&h, "settingsLanded:Detail"), "{:?}", h.app.widgets.iter().map(|(w, _)| w).filter(|w| w.contains("Landed")).collect::>()); + assert!(!has(&h, "settingsLanded:Grid") && !has(&h, "settingsLanded:Appearance")); + // And leaving the tab and coming back to it shows no mark: it was for arriving + click(&mut h, "button:settingsTab-general"); + click(&mut h, "button:settingsTab-interface"); + assert!(!has(&h, "settingsLanded:Detail"), "a tab opened by its own button marks nothing"); + // And nor does leaving by a command, or closing Settings and opening it again + filter(&mut h, "info overlay"); + click(&mut h, "settingsFound:interface:Detail"); + steps(&mut h); + assert!(has(&h, "settingsLanded:Detail")); + show(&mut h, "general"); + show(&mut h, "interface"); + assert!(!has(&h, "settingsLanded:Detail"), "a tab opened by a command marks nothing"); + filter(&mut h, "info overlay"); + click(&mut h, "settingsFound:interface:Detail"); + steps(&mut h); + assert!(has(&h, "settingsLanded:Detail")); + h.app.ui.dialog = None; + steps(&mut h); + h.app.ui.dialog = Some(Dialog::Settings { tab: "interface".into() }); + steps(&mut h); + assert!(!has(&h, "settingsLanded:Detail"), "Settings opened again marks nothing"); + // And the mark goes by itself + filter(&mut h, "info overlay"); + click(&mut h, "settingsFound:interface:Detail"); + steps(&mut h); + assert!(has(&h, "settingsLanded:Detail")); + for _ in 0..240 { + h.step(); + } + assert!(!has(&h, "settingsLanded:Detail"), "the mark is gone after a few seconds"); + // And a tab opened by its own button marks nothing + click(&mut h, "button:settingsTab-general"); + assert!(!h.app.widgets.iter().any(|(w, _)| w.starts_with("settingsLanded:"))); +} + +#[test] +fn every_word_given_to_a_section_finds_that_section() { + // Given a library on disk (Library ▸ Smart previews is only there for one) + let dir = TempFolder(std::env::temp_dir().join(format!("lc-ui-filteralso-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir_all(&dir.0).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(dir.0.join("library"), false).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services::default()), [1200.0, 1000.0], 1.0); + h.app.ui.dialog = Some(Dialog::Settings { tab: "general".into() }); + steps(&mut h); + for (tab, section, words) in crate::panels::settings::ALSO { + for word in words.split_whitespace() { + // Then each word finds the section it is given to: the section is drawn on that tab + // under that name, and the word is in the spelling the filter compares in + filter(&mut h, word); + assert!(found(&h).contains(&format!("{tab}:{section}")), "\"{word}\" finds {tab} ▸ {section}: {:?}", found(&h)); + // And is not a part of a word half of Settings says, which would bury the section + assert!(found(&h).len() <= 6, "\"{word}\" finds too much to be of use: {:?}", found(&h)); + } + } +} diff --git a/crates/ui-egui/src/tests_dialog_settings_groups.rs b/crates/ui-egui/src/tests_dialog_settings_groups.rs new file mode 100644 index 00000000000..99d29ac3683 --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings_groups.rs @@ -0,0 +1,164 @@ +//! The Settings tabs are grouped by what a person comes to do: the library itself (where it is, +//! what leaves it by itself) under Library; what is written beside and opened from the photo +//! files under Files; and the tabs for the monitor and for how LightCraft looks named for that. +//! +//! Before, General held the library's location beside the language and the external editors, +//! XMP sidecar writing (which governs every later edit) sat under Import, and forgetting unchanged +//! photos (catalog housekeeping) under Performance. "Display" was the monitor's colour profile and +//! "Interface" was how the app looks. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::panels::settings::TABS; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo() -> Headless { + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), [1200.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +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); + for _ in 0..4 { + h.step(); + } +} + +/// Every section heading of the open page, top to bottom (`heading:{its English name}`). +fn headings(h: &Headless) -> Vec { + let mut found: Vec<(f32, String)> = + h.app.widgets.iter().filter_map(|(id, r)| Some((r.top(), id.strip_prefix("heading:")?.to_string()))).collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + found.into_iter().map(|(_, text)| text).collect() +} + +#[test] +fn the_tabs_are_named_and_ordered_for_what_they_hold() { + let names: Vec<(&str, &str)> = TABS.iter().take(9).map(|(id, label)| (*id, crate::panels::settings::tab_label(id, label))).collect(); + assert_eq!( + names, + [ + ("general", "General"), + ("library", "Library"), + ("import", "Import"), + ("files", "Files"), + ("performance", "Performance"), + ("display", "Monitor"), + ("interface", "Appearance"), + ("faces", "Faces"), + ("denoise", "AI Denoise"), + ] + ); +} + +#[test] +fn each_section_is_under_the_tab_a_person_would_look_in() { + let mut h = demo(); + // (every heading a page has, so a section that turns up on a tab it does not belong to is seen) + let mut under = |tab: &str| { + show(&mut h, tab); + headings(&h) + }; + // General is about the app as a whole + assert_eq!(under("general"), ["Startup", "Culling"]); + // Library is the library itself: where it is, and what leaves it by itself + assert_eq!(under("library"), ["Library", "Local folders"]); + // Import is what happens to photos as they come in + assert_eq!(under("import"), ["Raw defaults", "Other images (JPEG, PNG, TIFF, HEIC…)", "Metadata", "Auto Import"]); + // Files is what is written beside the photo files and what they are opened in + assert_eq!(under("files"), ["XMP sidecars", "External Editing"]); + // Performance is speed and the cache that buys it + assert_eq!(under("performance"), ["Rendering", "Thumbnail cache"]); + assert_eq!(under("display"), ["Monitor profile"]); + assert_eq!(under("interface"), ["Appearance", "Filmstrip", "Grid", "Detail"]); + // Faces and AI Denoise are as they were (here without a way to download models) + assert_eq!(under("faces"), ["Face recognition"]); + assert_eq!(under("denoise"), ["AI Denoise"]); + // And every tab there is was looked at + assert_eq!(TABS.len(), 9, "a new tab needs its sections listed here"); +} + +#[test] +fn what_is_saved_with_a_library_in_memory_says_it_will_not_last() { + let mut h = demo(); + let note = "In-memory session: these settings last until LightCraft quits."; + for tab in ["library", "import", "files"] { + show(&mut h, tab); + assert!(h.painted_text().iter().any(|text| text == note), "{tab} says so"); + } + show(&mut h, "general"); + assert!(!h.painted_text().iter().any(|text| text == note), "General is saved on this computer"); +} + +#[test] +fn every_tab_id_from_before_still_opens_its_tab() { + let mut h = demo(); + // Given the ids agents, the docs and the rest of the app have used so far, and the two new ones + for id in ["general", "import", "performance", "display", "interface", "faces", "denoise", "library", "files"] { + show(&mut h, id); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: id.into() }), "{id}"); + } + // And an id that names no tab is refused, saying which there are + let r = h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": "nowhere"}}), T); + assert_eq!(r["ok"], false, "{r}"); + assert!(r.to_string().contains("library") && r.to_string().contains("files"), "the refusal lists the tabs: {r}"); +} + +#[test] +fn controls_keep_their_names_where_they_moved_to() { + let mut h = demo(); + let has = |h: &Headless, id: &str| h.app.widgets.iter().any(|(w, _)| w == id); + // (what scripts and agents click is found by the same name on its new tab) + show(&mut h, "library"); + assert!(has(&h, "button:settingsOpenLibrary") && has(&h, "text:settingsLocation") && has(&h, "button:settingsForgetLocal-0")); + show(&mut h, "files"); + assert!(has(&h, "check:settings.autoWriteXmp") && has(&h, "field:externalEditor") && has(&h, "field:photocraftPath")); + show(&mut h, "general"); + assert!(has(&h, "button:settingsLanguage-0") && has(&h, "check:settings.autoAdvance")); + assert!(!has(&h, "button:settingsOpenLibrary") && !has(&h, "field:externalEditor"), "and no longer on General"); + show(&mut h, "import"); + assert!(has(&h, "field:settings.copyright") && !has(&h, "check:settings.autoWriteXmp")); + show(&mut h, "performance"); + assert!(has(&h, "button:settingsClearCache") && !has(&h, "button:settingsForgetLocal-0")); +} + +#[test] +fn a_library_on_disk_has_its_smart_previews_folder_under_library() { + let dir = std::env::temp_dir().join(format!("lc-ui-settings-groups-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&dir, true).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services::default()), [1200.0, 1000.0], 1.0); + h.settle(T); + show(&mut h, "performance"); + let on_performance = headings(&h); + show(&mut h, "library"); + let on_library = headings(&h); + drop(h); + let _ = std::fs::remove_dir_all(&dir); + // (where a library keeps its files is the library's; Performance keeps rendering and the cache) + assert_eq!(on_library, ["Library", "Smart previews", "Local folders"]); + assert_eq!(on_performance, ["Rendering", "Thumbnail cache"]); +} + +#[test] +fn the_tab_bar_shows_the_names_people_read() { + let mut h = demo(); + show(&mut h, "general"); + let texts = h.painted_text(); + for name in ["General", "Library", "Import", "Files", "Performance", "Monitor", "Appearance", "Faces", "AI Denoise"] { + assert!(texts.iter().any(|text| text == name), "the tab bar has {name}"); + } + assert!(!texts.iter().any(|text| text == "Display" || text == "Interface"), "and not the names from before"); +} diff --git a/crates/ui-egui/src/tests_dialog_settings_keys.rs b/crates/ui-egui/src/tests_dialog_settings_keys.rs new file mode 100644 index 00000000000..710309d45e3 --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings_keys.rs @@ -0,0 +1,348 @@ +//! Settings by keyboard: a short way to any setting, and one look for "the focus is here". +//! +//! Tab stops once at the tab bar and once at each row of choices (the open tab, the choice that +//! holds), and the arrow keys move inside; every control that has the focus is ringed 2 pt in +//! the text colour; a theme's favourite star can be reached and pressed without the mouse. +//! +//! Before, Tab stopped at each of the nine tabs and then each of the ten languages (some twenty +//! presses to General's first checkbox), a focused checkbox, button or list showed a thin line +//! of another colour than a focused tab or choice, a focused text box an accent outline, and the +//! star of a theme that was no favourite was only there under the mouse. + +use std::time::Duration; + +use egui::Color32; +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::theme::{ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo() -> Headless { + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), [1200.0, 1000.0], 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 run(h: &mut Headless, command: &str, params: serde_json::Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.settle(T); + steps(h); +} + +fn show(h: &mut Headless, tab: &str) { + run(h, "app.settings", json!({"tab": tab})); +} + +fn key(h: &mut Headless, key: &str) { + assert_eq!(h.request("ui.key", json!({"key": key}), T)["ok"], true, "{key}"); + steps(h); +} + +fn back_tab(h: &mut Headless) { + assert_eq!(h.request("ui.key", json!({"key": "Tab", "shift": true}), T)["ok"], true); + steps(h); +} + +fn rect(h: &Headless, id: &str) -> egui::Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +/// The widget the keyboard focus is on, by the name it is registered under (a control's, not a +/// heading's or a page's), or "" when it is on none. +fn focused(h: &Headless) -> String { + let Some(id) = h.view.ctx.memory(|m| m.focused()) else { return String::new() }; + if id == crate::text_field::id("field:settingsFilter") { + return "field:settingsFilter".into(); + } + let Some(at) = h.view.ctx.read_response(id).map(|r| r.rect) else { return String::new() }; + let near = |a: egui::Rect| (a.min - at.min).abs().max_elem() < 1.5 && (a.max - at.max).abs().max_elem() < 1.5; + h.app + .widgets + .iter() + .find(|(w, r)| ["button:", "check:", "radio:", "field:", "settingsFound:"].iter().any(|kind| w.starts_with(kind)) && near(*r)) + .map(|(w, _)| w.clone()) + .unwrap_or_else(|| format!("{at:?}")) +} + +/// How many pixels within `rect` are exactly `colour` (one pixel per point here). +fn count(image: &egui::ColorImage, rect: egui::Rect, colour: Color32) -> usize { + let [w, h] = image.size; + let (x0, x1) = (rect.left().round().max(0.0) as usize, (rect.right().round().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().round().max(0.0) as usize, (rect.bottom().round().max(0.0) as usize).min(h)); + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|(x, y)| image.pixels[y * w + x] == colour).count() +} + +/// How many pixels of `colour` lie in the band round the edge of `rect`: from 3 pt outside it to +/// 3 pt inside (a control's ring is drawn at its edge, a point or two either way). +fn band(image: &egui::ColorImage, rect: egui::Rect, colour: Color32) -> usize { + count(image, rect.expand(3.0), colour) - count(image, rect.shrink(3.0), colour) +} + +#[test] +fn tab_stops_once_at_the_tabs_and_once_at_each_row_of_choices() { + let mut h = demo(); + show(&mut h, "general"); + // Given Settings just opened: the focus is in the filter + assert_eq!(focused(&h), "field:settingsFilter"); + // When Tab is pressed, it goes to the tab that is open + key(&mut h, "Tab"); + assert_eq!(focused(&h), "button:settingsTab-general"); + // And again: to the language that is chosen, past the other eight tabs + key(&mut h, "Tab"); + assert_eq!(focused(&h), "button:settingsLanguage-0"); + // And again: to Open in, past the other nine languages + key(&mut h, "Tab"); + assert_eq!(focused(&h), "button:settingsStartup-0"); + // And the fourth press reaches the first checkbox of General + key(&mut h, "Tab"); + assert_eq!(focused(&h), "check:settings.autoAdvance"); + // And Shift+Tab goes back the same way, one stop a row + back_tab(&mut h); + assert_eq!(focused(&h), "button:settingsStartup-0"); + back_tab(&mut h); + assert_eq!(focused(&h), "button:settingsLanguage-0"); + back_tab(&mut h); + assert_eq!(focused(&h), "button:settingsTab-general"); +} + +#[test] +fn the_stop_of_a_row_is_the_choice_that_holds() { + let mut h = demo(); + // Given LightCraft set to open in Detail (the third choice) and Appearance open (the seventh tab) + h.app.ui.settings.startup_view = crate::state::StartupView::Detail; + show(&mut h, "general"); + key(&mut h, "Tab"); + key(&mut h, "Tab"); + key(&mut h, "Tab"); + assert_eq!(focused(&h), "button:settingsStartup-2"); + // (Settings closed and opened on Appearance: the focus starts in the filter again) + h.app.ui.dialog = None; + steps(&mut h); + show(&mut h, "interface"); + key(&mut h, "Tab"); + assert_eq!(focused(&h), "button:settingsTab-interface"); +} + +#[test] +fn the_arrow_keys_move_inside_the_tabs_and_do_not_leave_them() { + let mut h = demo(); + show(&mut h, "general"); + key(&mut h, "Tab"); + // → and ↓ go to the next tab, ← and ↑ to the one before; nothing opens by that + key(&mut h, "ArrowRight"); + assert_eq!(focused(&h), "button:settingsTab-library"); + key(&mut h, "ArrowDown"); + assert_eq!(focused(&h), "button:settingsTab-import"); + key(&mut h, "ArrowUp"); + assert_eq!(focused(&h), "button:settingsTab-library"); + key(&mut h, "ArrowLeft"); + assert_eq!(focused(&h), "button:settingsTab-general"); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "general".into() })); + // ← on the first stays there; End goes to the last, → stays there, Home goes to the first + key(&mut h, "ArrowLeft"); + assert_eq!(focused(&h), "button:settingsTab-general"); + key(&mut h, "End"); + assert_eq!(focused(&h), "button:settingsTab-denoise"); + key(&mut h, "ArrowRight"); + assert_eq!(focused(&h), "button:settingsTab-denoise"); + key(&mut h, "Home"); + assert_eq!(focused(&h), "button:settingsTab-general"); + // Space opens the tab the focus is on, which keeps the focus and is the bar's stop from then on + key(&mut h, "ArrowRight"); + key(&mut h, "Space"); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "library".into() })); + assert_eq!(focused(&h), "button:settingsTab-library"); + key(&mut h, "Tab"); + back_tab(&mut h); + assert_eq!(focused(&h), "button:settingsTab-library"); +} + +#[test] +fn the_arrow_keys_move_inside_a_row_of_choices_and_space_chooses() { + let mut h = demo(); + show(&mut h, "general"); + for _ in 0..3 { + key(&mut h, "Tab"); + } + assert_eq!(focused(&h), "button:settingsStartup-0"); + // → moves the focus, and the setting stays what it was until Space + key(&mut h, "ArrowRight"); + assert_eq!(focused(&h), "button:settingsStartup-1"); + assert_eq!(h.app.ui.settings.startup_view, crate::state::StartupView::Last); + key(&mut h, "Space"); + assert_eq!(h.app.ui.settings.startup_view, crate::state::StartupView::Grid); + // And the row is left with Tab from wherever in it the focus is: to the next control + key(&mut h, "ArrowRight"); + assert_eq!(focused(&h), "button:settingsStartup-2"); + key(&mut h, "Tab"); + assert_eq!(focused(&h), "check:settings.autoAdvance"); + // And coming back, the stop is the choice that holds + back_tab(&mut h); + assert_eq!(focused(&h), "button:settingsStartup-1"); + // Home and End go to the ends of the row, and Return chooses as Space does + key(&mut h, "End"); + assert_eq!(focused(&h), "button:settingsStartup-2"); + key(&mut h, "Home"); + assert_eq!(focused(&h), "button:settingsStartup-0"); + key(&mut h, "Enter"); + assert_eq!(h.app.ui.settings.startup_view, crate::state::StartupView::Last); + // And an arrow key held with ⌘ or ⇧ is not this row's: the focus stays in it, where it was + assert_eq!(h.request("ui.key", json!({"key": "ArrowRight", "cmd": true}), T)["ok"], true); + steps(&mut h); + assert_eq!(h.request("ui.key", json!({"key": "ArrowRight", "shift": true}), T)["ok"], true); + steps(&mut h); + assert_eq!(focused(&h), "button:settingsStartup-0"); +} + +/// `key` pressed and let go within one frame, and that one frame drawn. +fn press(h: &mut Headless, key: egui::Key) { + for pressed in [true, false] { + h.events.push(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }); + } + h.step(); +} + +#[test] +fn arrow_keys_pressed_faster_than_frames_are_drawn_stay_in_the_row() { + let mut h = demo(); + show(&mut h, "general"); + key(&mut h, "Tab"); + key(&mut h, "Tab"); + assert_eq!(focused(&h), "button:settingsLanguage-0"); + // Given the focus walked along the languages (so each of them has been the row's stop) + for _ in 0..4 { + key(&mut h, "ArrowRight"); + } + assert_eq!(focused(&h), "button:settingsLanguage-4"); + // When ← arrives on one frame after the other, with none drawn in between + for _ in 0..3 { + press(&mut h, egui::Key::ArrowLeft); + } + steps(&mut h); + // Then the focus has gone back along the row, and not up to the tabs + assert_eq!(focused(&h), "button:settingsLanguage-1"); + for _ in 0..6 { + press(&mut h, egui::Key::ArrowRight); + } + steps(&mut h); + assert_eq!(focused(&h), "button:settingsLanguage-7"); +} + +#[test] +fn a_click_on_a_choice_that_is_not_the_stop_still_chooses_it() { + let mut h = demo(); + show(&mut h, "general"); + let r = h.request("ui.clickWidget", json!({"id": "button:settingsStartup-2"}), T); + assert_eq!(r["ok"], true, "{r}"); + steps(&mut h); + assert_eq!(h.app.ui.settings.startup_view, crate::state::StartupView::Detail); + // And it is not left ringed as if the keyboard had come to it: a click on a choice shows no + // more of the focus than a click on a checkbox does + let t = Tokens::get(&h.view.ctx); + let ringed = |h: &Headless, id: &str| band(&h.paint(), rect(h, id), t.text) as f32 >= rect(h, id).width() + rect(h, id).height(); + assert!(!ringed(&h, "button:settingsStartup-2"), "a clicked choice shows no focus ring"); + let r = h.request("ui.clickWidget", json!({"id": "button:settingsTab-performance"}), T); + assert_eq!(r["ok"], true, "{r}"); + steps(&mut h); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "performance".into() })); + // (the open tab has its own line in the text colour: asked of the focus itself) + assert_ne!(focused(&h), "button:settingsTab-performance", "a clicked tab does not take the focus"); +} + +#[test] +fn every_kind_of_control_shows_the_focus_by_a_ring_in_the_text_colour() { + for kind in ThemeKind::ALL { + let mut h = demo(); + run(&mut h, "view.theme", json!({"theme": kind.id()})); + let t = Tokens::for_kind(kind); + // Performance has a checkbox, a row of choices and a button; the filter is a text box + show(&mut h, "performance"); + let controls = + ["field:settingsFilter", "button:settingsTab-performance", "check:settings.gpu", "button:settingsPreview-0", "button:settingsClearCache"]; + // (how much of the text colour is at each control's edge with the focus elsewhere) + key(&mut h, "Tab"); + let plain = h.paint(); + let mut before: Vec = controls.iter().map(|id| band(&plain, rect(&h, id), t.text)).collect(); + // (the tab has the focus in that picture: it is measured with the focus on the next stop) + key(&mut h, "Tab"); + before[1] = band(&h.paint(), rect(&h, controls[1]), t.text); + back_tab(&mut h); + back_tab(&mut h); + for (control, before) in controls.iter().zip(before) { + let reached = (0..30).any(|_| { + if focused(&h) == *control { + return true; + } + key(&mut h, "Tab"); + false + }); + assert!(reached, "{kind:?}: Tab reaches {control} (the focus is on {})", focused(&h)); + let at = rect(&h, control); + let ring = band(&h.paint(), at, t.text).saturating_sub(before); + // Then a line in the text colour runs round the whole of it + let least = at.width() + at.height(); + assert!(ring as f32 >= least, "{kind:?}: {control} shows the focus by {ring} px in the text colour (at least {least})"); + } + } +} + +#[test] +fn a_section_found_shows_the_focus_as_everything_else_does() { + let mut h = demo(); + let t = Tokens::get(&h.view.ctx); + show(&mut h, "general"); + h.request("ui.text", json!({"text": "culling"}), T); + steps(&mut h); + let row = rect(&h, "settingsFound:general:Culling"); + let before = band(&h.paint(), row, t.text); + key(&mut h, "ArrowDown"); + let ring = band(&h.paint(), row, t.text).saturating_sub(before); + assert!(ring as f32 >= row.width() + row.height(), "the result shows the focus by {ring} px in the text colour"); +} + +#[test] +fn a_themes_star_is_reached_and_pressed_with_the_keyboard() { + let mut h = demo(); + h.app.ui.settings.favorite_themes.clear(); + show(&mut h, "interface"); + // Given no theme is a favourite, and the mouse is nowhere near + // When Tab is pressed until the star of Paper has the focus + let reached = (0..40).any(|_| { + key(&mut h, "Tab"); + focused(&h) == "button:themeFavorite-paper" + }); + assert!(reached, "the star of a theme that is no favourite is a Tab stop (the focus is on {})", focused(&h)); + // Then the star is drawn there, ringed + let t = Tokens::get(&h.view.ctx); + let star = rect(&h, "button:themeFavorite-paper"); + let image = h.paint(); + assert!(band(&image, star, t.text) as f32 >= star.width() + star.height(), "the star shows the focus"); + let inside = star.shrink(5.0); + let drawn = (inside.area() as usize).saturating_sub(count(&image, inside, t.inset)); + assert!(drawn > 12, "the star itself is drawn while it has the focus ({drawn} px of it)"); + // And the theme's radio button before it, with the focus, is ringed round the whole of it + back_tab(&mut h); + assert_eq!(focused(&h), "radio:theme-paper"); + let radio = rect(&h, "radio:theme-paper"); + let ring = band(&h.paint(), radio, t.text); + assert!(ring as f32 >= radio.width() + radio.height(), "the radio button shows the focus by {ring} px"); + key(&mut h, "Tab"); + // And Space makes Paper a favourite, and the focus stays on the star + key(&mut h, "Space"); + assert_eq!(h.app.ui.settings.favorite_themes, ["paper"]); + assert_eq!(focused(&h), "button:themeFavorite-paper"); + key(&mut h, "Space"); + assert!(h.app.ui.settings.favorite_themes.is_empty()); +} diff --git a/crates/ui-egui/src/tests_dialog_settings_tabs.rs b/crates/ui-egui/src/tests_dialog_settings_tabs.rs new file mode 100644 index 00000000000..4053201816f --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings_tabs.rs @@ -0,0 +1,300 @@ +//! The Settings tabs look like tabs and not like the choices under them, the open tab and a chosen +//! option are marked by more than a slightly different fill, and a tab or choice reached with the +//! keyboard shows that it has the focus. +//! +//! Before, one widget drew both: on General the languages read as a second tab bar, what was +//! chosen stood 1.35 to 1.56:1 against what was not, and Tab moved a focus nobody could see (the +//! picture with and without it was the same, pixel for pixel). + +use std::time::Duration; + +use egui::Color32; +use serde_json::json; + +use crate::headless::Headless; +use crate::panels::settings::TABS; +use crate::theme::{ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo() -> Headless { + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), [1200.0, 900.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn run(h: &mut Headless, command: &str, params: serde_json::Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.settle(T); + for _ in 0..4 { + h.step(); + } +} + +fn show(h: &mut Headless, tab: &str) { + run(h, "app.settings", json!({"tab": tab})); +} + +fn key(h: &mut Headless, key: &str) { + assert_eq!(h.request("ui.key", json!({"key": key}), T)["ok"], true, "{key}"); + for _ in 0..3 { + h.step(); + } +} + +fn rect(h: &Headless, id: &str) -> egui::Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +fn tab(h: &Headless, id: &str) -> egui::Rect { + rect(h, &format!("button:settingsTab-{id}")) +} + +/// How many pixels of `rect` are `colour` (one pixel per point here). +fn count(image: &egui::ColorImage, rect: egui::Rect, colour: Color32) -> usize { + let [w, h] = image.size; + let (x0, x1) = (rect.left().round().max(0.0) as usize, (rect.right().round().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().round().max(0.0) as usize, (rect.bottom().round().max(0.0) as usize).min(h)); + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|(x, y)| image.pixels[y * w + x] == colour).count() +} + +/// How many pixels of the focus ring's colour run round `rect`: along its top and its two sides +/// (not its bottom, where the open tab has its line in the same colour). +fn ring(image: &egui::ColorImage, rect: egui::Rect, colour: Color32) -> usize { + let [top, _, left, right] = edges(rect, 2.0); + [top, left, right].iter().map(|e| count(image, *e, colour)).sum() +} + +/// The outermost ring of `rect`, `width` points thick, as its four edges. +fn edges(rect: egui::Rect, width: f32) -> [egui::Rect; 4] { + [ + egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), rect.top() + width)), + egui::Rect::from_min_max(egui::pos2(rect.left(), rect.bottom() - width), rect.max), + egui::Rect::from_min_max(rect.min, egui::pos2(rect.left() + width, rect.bottom())), + egui::Rect::from_min_max(egui::pos2(rect.right() - width, rect.top()), rect.max), + ] +} + +/// WCAG contrast of two opaque colours. +fn contrast(a: Color32, b: Color32) -> f32 { + let lum = |c: Color32| { + let lin = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b()) + }; + let (a, b) = (lum(a), lum(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) +} + +#[test] +fn the_open_tab_is_underlined_and_the_others_are_not() { + for kind in ThemeKind::ALL { + let mut h = demo(); + run(&mut h, "view.theme", json!({"theme": kind.id()})); + let t = Tokens::for_kind(kind); + // Given Settings on Performance + show(&mut h, "performance"); + let image = h.paint(); + for (id, _) in TABS { + let r = tab(&h, id); + // Then a line in the text colour runs under the open tab's whole name, and under no other tab + let line = count(&image, egui::Rect::from_min_max(egui::pos2(r.left(), r.bottom() - 2.0), r.max), t.text); + if *id == "performance" { + assert!(line as f32 >= 2.0 * (r.width() - 2.0), "{kind:?}: the open tab {id} is underlined ({line} px of {r:?})"); + } else { + assert_eq!(line, 0, "{kind:?}: {id} is not open and has no line"); + } + } + // And that line stands out from the window whatever the theme (3:1 for a mark that is not text) + assert!(contrast(t.text, t.chrome) >= 3.0, "{kind:?}: {}", contrast(t.text, t.chrome)); + } +} + +#[test] +fn tabs_are_not_drawn_as_the_choices_under_them_are() { + let mut h = demo(); + let t = Tokens::get(&h.view.ctx); + // Given General, where a row of language choices sits right under the tabs + show(&mut h, "general"); + let image = h.paint(); + // Then a choice is a bordered button + let choice = rect(&h, "button:settingsLanguage-4"); + // (in the border colour made to stand out from the window) + let line = t.legible(t.button_border, t.chrome, 3.0); + let border: usize = edges(choice, 1.0).iter().map(|e| count(&image, *e, line)).sum(); + assert!(border as f32 > choice.width(), "a choice has a border ({border} px)"); + // And a tab that is not open is its name alone on the window: no border, no fill of its own + let import = tab(&h, "import"); + let border: usize = edges(import, 1.0).iter().map(|e| count(&image, *e, line) + count(&image, *e, t.button_border)).sum(); + assert_eq!(border, 0, "a tab has no border"); + assert_eq!(count(&image, import, t.button), 0, "a tab has no button fill"); + assert!(count(&image, import, t.chrome) as f32 > 0.6 * import.area(), "a tab is drawn on the window itself"); +} + +#[test] +fn a_tab_reached_with_the_keyboard_shows_the_focus() { + for kind in ThemeKind::ALL { + let mut h = demo(); + run(&mut h, "view.theme", json!({"theme": kind.id()})); + let t = Tokens::for_kind(kind); + show(&mut h, "general"); + let import = tab(&h, "library"); + let ring = |h: &Headless| ring(&h.paint(), import, t.text); + // Given no tab has the focus, there is no ring round Library + assert!(ring(&h) < 8, "{kind:?}: no ring before ({})", ring(&h)); + // When Tab is pressed (the filter has the focus as Settings opens: the tab bar is the next + // stop, at General) and then → (to Library) + key(&mut h, "Tab"); + key(&mut h, "ArrowRight"); + // Then a ring in the text colour runs round Library + let length = import.width() + 2.0 * import.height(); + assert!(ring(&h) as f32 > 1.5 * length, "{kind:?}: Library shows the focus ({} px of ring along {length} pt)", ring(&h)); + // And it is still General that is open: the focus is not the choice + assert_eq!(h.app.ui.dialog, Some(crate::state::Dialog::Settings { tab: "general".into() })); + } +} + +#[test] +fn the_arrow_keys_move_along_the_tabs_and_space_opens_one() { + let mut h = demo(); + let t = Tokens::get(&h.view.ctx); + show(&mut h, "general"); + let ring = |h: &Headless, id: &str| ring(&h.paint(), tab(h, id), t.text); + // Given the focus on the first tab + // (the filter comes first and has the focus as Settings opens, then the tabs) + key(&mut h, "Tab"); + assert!(ring(&h, "general") > 60, "General has the focus"); + // When → is pressed twice + key(&mut h, "ArrowRight"); + key(&mut h, "ArrowRight"); + // Then the focus is on the third tab, and nothing has opened yet + assert!(ring(&h, "import") > 60, "Import has the focus"); + assert!(ring(&h, "general") < 60 && ring(&h, "library") < 60, "and no other tab has"); + assert_eq!(h.app.ui.dialog, Some(crate::state::Dialog::Settings { tab: "general".into() })); + // And ← goes back one + key(&mut h, "ArrowLeft"); + assert!(ring(&h, "library") > 60, "Library has the focus"); + // When Space is pressed, that tab opens and keeps the focus + key(&mut h, "Space"); + assert_eq!(h.app.ui.dialog, Some(crate::state::Dialog::Settings { tab: "library".into() })); + assert!(ring(&h, "library") > 60, "Library still has the focus"); +} + +#[test] +fn a_chosen_option_has_an_outline_and_the_others_do_not() { + for kind in ThemeKind::ALL { + let mut h = demo(); + run(&mut h, "view.theme", json!({"theme": kind.id()})); + let t = Tokens::for_kind(kind); + // Given Performance, where Preview size is Automatic (the first choice) + show(&mut h, "performance"); + assert_eq!(h.app.ui.settings.preview_limit, 0); + let image = h.paint(); + let outline = |id: &str| edges(rect(&h, id), 1.0).iter().map(|e| count(&image, *e, t.text_label)).sum::(); + // Then the chosen one is outlined in the label colour, and one that is not chosen is not + let chosen = rect(&h, "button:settingsPreview-0"); + assert!( + outline("button:settingsPreview-0") as f32 > chosen.width() + chosen.height(), + "{kind:?}: the chosen size is outlined ({})", + outline("button:settingsPreview-0") + ); + assert!(outline("button:settingsPreview-1") < 8, "{kind:?}: another size is not ({})", outline("button:settingsPreview-1")); + // And an outline is not the focus ring: nothing in the ring's colour runs round the chosen one + assert!(ring(&image, chosen, t.text) < 8, "{kind:?}: chosen is not focused ({})", ring(&image, chosen, t.text)); + // And the outline stands out from the button it is on, from one that is not chosen and from the window + for (what, other) in [("its fill", t.pressed), ("a button", t.button), ("the window", t.chrome)] { + assert!(contrast(t.text_label, other) >= 3.0, "{kind:?}: the outline against {what} is {}", contrast(t.text_label, other)); + } + } +} + +#[test] +fn a_choice_reached_with_the_keyboard_shows_the_focus() { + let mut h = demo(); + let t = Tokens::get(&h.view.ctx); + show(&mut h, "performance"); + let ring = |h: &Headless, id: &str| ring(&h.paint(), rect(h, id), t.text); + assert!(ring(&h, "button:settingsPreview-1") < 8); + // When Tab is pressed until the preview sizes have the focus (the tabs and the GPU checkbox + // come first; the row's stop is the size that holds, the first) and then → (to the second) + let reached = (0..40).any(|_| { + key(&mut h, "Tab"); + ring(&h, "button:settingsPreview-0") > 60 + }); + key(&mut h, "ArrowRight"); + let reached = reached && ring(&h, "button:settingsPreview-1") > 60; + // Then it shows a ring, and is not chosen by that + assert!(reached, "a choice shows the focus"); + assert_eq!(h.app.ui.settings.preview_limit, 0); + // And Space chooses it + key(&mut h, "Space"); + assert_eq!(h.app.ui.settings.preview_limit, crate::state::PREVIEW_LIMITS[1]); +} + +/// What a screen reader is told: a choice is a radio button that says whether it is the one +/// chosen, a tab a button that says whether it is the one open. +#[test] +fn choices_and_tabs_say_what_they_are_and_which_one_holds() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let mut found = Vec::new(); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let _ = crate::widgets::choice_button(ui, "size-0", "Automatic", true); + let _ = crate::widgets::choice_button(ui, "size-1", "1600 px", false); + let _ = crate::widgets::tab_button(ui, "tab-general", "General", true); + let _ = crate::widgets::tab_button(ui, "tab-import", "Import", false); + }); + out.textures_delta.clear(); + if let Some(update) = out.platform_output.accesskit_update.take() { + found = update + .nodes + .iter() + .map(|(_, n)| (format!("{:?}", n.role()), n.label().unwrap_or_default().to_string(), format!("{:?}", n.toggled()))) + .collect(); + } + } + let has = + |role: &str, label: &str, on: bool| found.iter().any(|(r, l, t)| r == role && l == label && t.contains(if on { "True" } else { "False" })); + assert!(has("RadioButton", "Automatic", true), "{found:?}"); + assert!(has("RadioButton", "1600 px", false), "{found:?}"); + assert!(has("Button", "General", true), "{found:?}"); + assert!(has("Button", "Import", false), "{found:?}"); +} + +#[test] +fn tabs_on_two_lines_each_stand_on_a_line_of_their_own() { + // Given an app window too narrow for the tabs in one line + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), [480.0, 640.0], 1.0); + h.settle(T); + let t = Tokens::get(&h.view.ctx); + // (the bar's line: the divider colour, made to stand out from the window) + let line = t.legible(t.divider, t.chrome, 3.0); + show(&mut h, "general"); + let tabs: Vec = TABS.iter().map(|(id, _)| tab(&h, id)).collect(); + let first = tabs[0]; + let lower: Vec<&egui::Rect> = tabs.iter().filter(|r| r.top() >= first.bottom()).collect(); + assert!(!lower.is_empty(), "the tabs take more than one line: {tabs:?}"); + let image = h.paint(); + let window = rect(&h, "dialog:window"); + // Then a line the width of the window runs right under each line of tabs, the first too, + // where the open tab is: its own line does not hang in the air over the names below + for bottom in [first.bottom().round(), lower[0].bottom().round()] { + let strip = egui::Rect::from_min_max(egui::pos2(window.left(), bottom), egui::pos2(window.right(), bottom + 1.0)); + assert!( + count(&image, strip, line) as f32 > 0.8 * (window.width() - 32.0), + "a line runs under the tabs at y = {bottom} ({} px)", + count(&image, strip, line) + ); + } + // And the lower line of tabs starts clear of it + assert!(lower[0].top() >= first.bottom() + 4.0, "the second line of tabs {:?} is clear of the first {first:?}", lower[0]); + // And the page starts under the last of them + assert!(rect(&h, "settings:pageRoom").top() > lower[0].bottom(), "the page is under the tabs"); +} diff --git a/crates/ui-egui/src/tests_dialog_settings_trust.rs b/crates/ui-egui/src/tests_dialog_settings_trust.rs new file mode 100644 index 00000000000..8e7bd22fd15 --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings_trust.rs @@ -0,0 +1,472 @@ +//! Settings does not do what cannot be taken back, or takes long to make again, on one click, and +//! Esc in one of its text boxes gives the text back. +//! +//! Before: Esc in Copyright or Creator saved what had been typed and closed the window; Clear +//! Cache and a model's Remove acted at once; and deleting the smart previews already built was a +//! choice made beforehand, which a later press of Choose Folder then carried out without a word. + +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +/// A folder under the system's temporary one, removed again when the test ends, passed or not. +struct TempFolder(std::path::PathBuf); + +impl TempFolder { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("lc-ui-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn path(&self, rest: &str) -> String { + self.0.join(rest).to_string_lossy().into_owned() + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn headless(session: lightcraft_engine::Session, services: Services) -> Headless { + let mut h = Headless::new(LightcraftApp::new(session, services), [1200.0, 900.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn demo() -> Headless { + headless(lightcraft_engine::Session::with_demo(), Services::default()) +} + +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); + for _ in 0..4 { + h.step(); + } +} + +fn steps(h: &mut Headless) { + for _ in 0..4 { + h.step(); + } +} + +/// Scroll the Settings page until `id` is inside the room for it: a control below the fold of a +/// long page is not drawn, and a click on where it would be goes nowhere. +fn reach(h: &mut Headless, id: &str) { + let find = |h: &Headless, id: &str| h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r); + for _ in 0..6 { + let (Some(rect), Some(room)) = (find(h, id), find(h, "settings:pageRoom")) else { return }; + if rect.top() >= room.top() && rect.bottom() <= room.bottom() { + return; + } + h.request("ui.move", json!({"x": room.center().x, "y": room.center().y}), T); + h.request("ui.scroll", json!({"dy": room.center().y - rect.center().y}), T); + steps(h); + } +} + +fn click(h: &mut Headless, id: &str) { + reach(h, id); + 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); +} + +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +fn says(h: &Headless, part: &str) -> bool { + h.painted_text().iter().any(|text| text.contains(part)) +} + +fn settings_open(h: &Headless, tab: &str) -> bool { + h.app.ui.dialog == Some(Dialog::Settings { tab: tab.into() }) +} + +fn copyright(h: &mut Headless) -> Value { + h.app.run("library.preferences", json!({})).unwrap()["import"]["copyright"].clone() +} + +#[test] +fn esc_in_copyright_gives_the_text_back_and_leaves_settings_open() { + let mut h = demo(); + show(&mut h, "import"); + let before = copyright(&mut h); + // Given a name typed into Copyright + click(&mut h, "field:settings.copyright"); + h.request("ui.text", json!({"text": "Example Name"}), T); + steps(&mut h); + assert!(says(&h, "Example Name"), "the typing shows"); + // When Esc is pressed + key(&mut h, "Escape"); + // Then the name is gone again, nothing was saved, and Settings is still open + assert!(!says(&h, "Example Name"), "Esc gives the text back"); + assert_eq!(copyright(&mut h), before, "nothing was saved"); + assert!(settings_open(&h, "import"), "Settings stays open: {:?}", h.app.ui.dialog); + // And a second Esc, with no edit under way, closes Settings as it always did + key(&mut h, "Escape"); + assert!(h.app.ui.dialog.is_none()); +} + +#[test] +fn return_in_copyright_saves_the_text() { + let mut h = demo(); + show(&mut h, "import"); + click(&mut h, "field:settings.copyright"); + h.request("ui.text", json!({"text": "Example Name"}), T); + steps(&mut h); + key(&mut h, "Enter"); + assert_eq!(copyright(&mut h), json!("Example Name")); + assert!(settings_open(&h, "import")); +} + +#[test] +fn clear_cache_asks_first() { + let mut h = demo(); + show(&mut h, "performance"); + let used = |h: &Headless| h.app.session.media.rendered.mem_usage().0; + let before = used(&h); + assert!(before > 0, "the demo's thumbnails are cached"); + // When Clear Cache is pressed + click(&mut h, "button:settingsClearCache"); + // Then it says what clearing costs and waits for an answer; nothing is cleared yet + assert!(says(&h, "made again"), "it says what clearing costs: {:?}", h.painted_text().iter().filter(|t| t.contains("again")).collect::>()); + assert!(has(&h, "button:settingsClearCache:confirm") && has(&h, "button:settingsClearCache:keep")); + assert_eq!(used(&h), before, "nothing is cleared before the answer"); + // When the answer is to keep it + click(&mut h, "button:settingsClearCache:keep"); + // Then the question goes and the cache is as it was + assert!(!has(&h, "button:settingsClearCache:confirm")); + assert_eq!(used(&h), before); + // When it is pressed again and confirmed, the cache is cleared + click(&mut h, "button:settingsClearCache"); + let r = h.request("ui.clickWidget", json!({"id": "button:settingsClearCache:confirm"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + assert!(used(&h) < before, "the cache was cleared: {} of {before}", used(&h)); + steps(&mut h); + assert!(!has(&h, "button:settingsClearCache:confirm"), "and the question is gone"); +} + +#[test] +fn esc_takes_the_question_away_and_leaves_settings_open() { + let mut h = demo(); + show(&mut h, "performance"); + let before = h.app.session.media.rendered.mem_usage().0; + click(&mut h, "button:settingsClearCache"); + assert!(has(&h, "button:settingsClearCache:confirm")); + key(&mut h, "Escape"); + assert!(!has(&h, "button:settingsClearCache:confirm"), "Esc answers no"); + assert!(settings_open(&h, "performance"), "and Settings stays open"); + assert_eq!(h.app.session.media.rendered.mem_usage().0, before); +} + +#[test] +fn removing_a_face_model_asks_first() { + let dir = TempFolder::new("settings-trust-faces"); + let mut h = demo(); + h.app.session.face_models_dir = Some(dir.0.join("models")); + if h.app.session.execute("faces.models.list", &json!({})).unwrap()["runtime"] != true { + return; // this build cannot run recognition models: there is nothing to install or remove + } + // Given a recognition model installed + let model = dir.0.join("Mine.onnx"); + std::fs::write(&model, lightcraft_faces::synthetic::tiny_embedder_model(512)).unwrap(); + let installed = h.app.run("faces.models.install", json!({"path": model.to_string_lossy(), "acknowledged": true, "activate": false})).unwrap(); + let id = installed["installed"]["id"].as_str().unwrap().to_string(); + h.app.caches.faces_epoch += 1; + let is_installed = |h: &mut Headless| h.app.run("faces.models.list", json!({})).unwrap().to_string().contains(&id); + show(&mut h, "faces"); + let remove = format!("faces:remove:{id}"); + // When Remove is pressed + click(&mut h, &remove); + // Then it asks, and the model is still there + assert!(has(&h, &format!("{remove}:confirm")), "Remove asks first"); + assert!(is_installed(&mut h), "the model is still installed"); + // When the answer is yes, it is removed + click(&mut h, &format!("{remove}:confirm")); + assert!(!is_installed(&mut h), "the model is removed"); + assert!(!has(&h, &remove), "and its Remove button is gone with it"); +} + +fn write_png(path: &str, seed: u8) { + let (w, h) = (24usize, 16usize); + let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 9) as u8, (i / w * 13) as u8, seed, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::create_dir_all(std::path::Path::new(path).parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); +} + +/// A library on disk with one photo and its smart preview built, whose folder picker answers `to`. +fn with_smart_preview(dir: &TempFolder, to: &str) -> Headless { + write_png(&dir.path("trip/a.png"), 3); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(dir.0.join("library"), false).unwrap(); + session.execute("library.import", &json!({"paths": [dir.path("trip/a.png")]})).unwrap(); + session.execute("library.smartPreviews", &json!({})).unwrap(); + std::fs::create_dir_all(to).unwrap(); + let to = to.to_string(); + headless(session, Services { pick_folder: Some(Box::new(move || Some(to.clone()))), ..Default::default() }) +} + +fn smart(h: &mut Headless) -> Value { + h.app.run("library.smartPreviewsLocation", json!({})).unwrap() +} + +#[test] +fn deleting_the_smart_previews_is_asked_about_when_the_folder_is_chosen() { + let dir = TempFolder::new("settings-trust-smart"); + let to = dir.path("elsewhere"); + let mut h = with_smart_preview(&dir, &to); + assert_eq!(smart(&mut h)["count"], 1); + show(&mut h, "library"); + // Given "Delete them" chosen for the previews already built + click(&mut h, "button:settingsSmartExisting-2"); + // When a new folder is chosen + click(&mut h, "button:settingsSmartChoose"); + // Then nothing has happened yet: it asks, saying how many previews would go + let now = smart(&mut h); + assert_eq!((now["count"].clone(), now["custom"].clone()), (json!(1), json!(false)), "nothing is deleted or moved before the answer: {now}"); + assert!(has(&h, "button:settingsSmartDelete") && has(&h, "button:settingsSmartCancel"), "it asks"); + let question: Vec = h.painted_text().into_iter().filter(|text| text.contains("Delete the smart previews")).collect(); + assert!(question.iter().any(|text| text.contains("1 smart preview")), "it asks, saying how many would go: {question:?}"); + // When the answer is no + click(&mut h, "button:settingsSmartCancel"); + // Then the folder and its previews are as they were, and the question is gone + let now = smart(&mut h); + assert_eq!((now["count"].clone(), now["custom"].clone()), (json!(1), json!(false))); + assert!(!has(&h, "button:settingsSmartDelete")); + // And the choice is back at "Move them": deleting is not left armed for next time + click(&mut h, "button:settingsSmartChoose"); + let moved = smart(&mut h); + assert_eq!((moved["count"].clone(), moved["custom"].clone()), (json!(1), json!(true)), "the previews moved with the folder: {moved}"); +} + +#[test] +fn saying_yes_deletes_the_smart_previews_and_changes_the_folder() { + let dir = TempFolder::new("settings-trust-smart-yes"); + let to = dir.path("elsewhere"); + let mut h = with_smart_preview(&dir, &to); + show(&mut h, "library"); + click(&mut h, "button:settingsSmartExisting-2"); + click(&mut h, "button:settingsSmartChoose"); + assert_eq!(smart(&mut h)["count"], 1); + click(&mut h, "button:settingsSmartDelete"); + let now = smart(&mut h); + assert_eq!((now["count"].clone(), now["custom"].clone()), (json!(0), json!(true)), "{now}"); + assert_eq!(now["path"], json!(to)); + assert!(!has(&h, "button:settingsSmartDelete")); +} + +#[test] +fn moving_the_smart_previews_needs_no_question() { + let dir = TempFolder::new("settings-trust-smart-move"); + let to = dir.path("elsewhere"); + let mut h = with_smart_preview(&dir, &to); + show(&mut h, "library"); + click(&mut h, "button:settingsSmartChoose"); + let now = smart(&mut h); + assert_eq!((now["count"].clone(), now["custom"].clone()), (json!(1), json!(true)), "{now}"); + assert!(!has(&h, "button:settingsSmartDelete")); +} + +#[test] +fn writing_xmp_by_itself_says_what_is_written_where() { + let mut h = demo(); + show(&mut h, "files"); + assert!(says(&h, "beside the photo"), "{:?}", h.painted_text().iter().filter(|t| t.contains("XMP")).collect::>()); +} + +/// A second library on disk with a smart preview of its own, in a folder chosen for it. +fn another_library(dir: &TempFolder) -> (String, String) { + write_png(&dir.path("other/b.png"), 9); + let (library, folder) = (dir.path("library-b"), dir.path("previews-b")); + std::fs::create_dir_all(&folder).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&library, false).unwrap(); + session.execute("library.import", &json!({"paths": [dir.path("other/b.png")]})).unwrap(); + session.execute("library.smartPreviewsLocation", &json!({"path": folder, "existing": "leave"})).unwrap(); + session.execute("library.smartPreviews", &json!({})).unwrap(); + session.close_library().unwrap(); + (library, folder) +} + +#[test] +fn a_question_left_unanswered_is_gone_when_settings_is_opened_again() { + let dir = TempFolder::new("settings-trust-smart-left"); + let to = dir.path("elsewhere"); + let mut h = with_smart_preview(&dir, &to); + show(&mut h, "library"); + // Given the question about deleting, left unanswered + click(&mut h, "button:settingsSmartExisting-2"); + click(&mut h, "button:settingsSmartChoose"); + assert!(has(&h, "button:settingsSmartDelete")); + // When Settings is closed and opened again + key(&mut h, "Escape"); + assert!(h.app.ui.dialog.is_none()); + show(&mut h, "library"); + // Then nothing waits: no question, and the choice is back at "Move them" + assert!(!has(&h, "button:settingsSmartDelete"), "the question does not outlive Settings"); + click(&mut h, "button:settingsSmartChoose"); + let now = smart(&mut h); + assert_eq!((now["count"].clone(), now["custom"].clone()), (json!(1), json!(true)), "the previews moved: {now}"); +} + +#[test] +fn a_question_asked_in_one_library_is_not_there_in_another() { + let dir = TempFolder::new("settings-trust-smart-other"); + let (library_b, folder_b) = another_library(&dir); + let to = dir.path("elsewhere"); + let mut h = with_smart_preview(&dir, &to); + show(&mut h, "library"); + // Given the question about deleting asked in one library, and left + click(&mut h, "button:settingsSmartExisting-2"); + click(&mut h, "button:settingsSmartChoose"); + assert!(has(&h, "button:settingsSmartDelete")); + key(&mut h, "Escape"); + // When another library is opened and its Settings looked at + h.app.run("app.openLibrary", json!({"path": library_b})).unwrap(); + h.settle(T); + show(&mut h, "library"); + // Then that library is not asked anything, and its smart previews are where they were + assert!(!has(&h, "button:settingsSmartDelete"), "the question belongs to the library it was asked in"); + let now = smart(&mut h); + assert_eq!((now["count"].clone(), now["path"].clone()), (json!(1), json!(folder_b)), "{now}"); +} + +#[test] +fn a_change_made_another_way_takes_the_question_away() { + let dir = TempFolder::new("settings-trust-smart-other-way"); + let to = dir.path("elsewhere"); + let mut h = with_smart_preview(&dir, &to); + show(&mut h, "library"); + click(&mut h, "button:settingsSmartExisting-2"); + click(&mut h, "button:settingsSmartChoose"); + assert!(has(&h, "button:settingsSmartDelete")); + // When "Move them" is chosen instead and the folder chosen again + click(&mut h, "button:settingsSmartExisting-0"); + assert!(!has(&h, "button:settingsSmartDelete"), "choosing not to delete takes the question away"); + click(&mut h, "button:settingsSmartChoose"); + // Then the previews moved, and no question about deleting them is left standing + let now = smart(&mut h); + assert_eq!((now["count"].clone(), now["custom"].clone()), (json!(1), json!(true)), "{now}"); + assert!(!has(&h, "button:settingsSmartDelete")); +} + +#[test] +fn use_library_folder_asks_before_deleting_too() { + let dir = TempFolder::new("settings-trust-smart-reset"); + let to = dir.path("elsewhere"); + let mut h = with_smart_preview(&dir, &to); + show(&mut h, "library"); + // Given the previews moved to a chosen folder, then "Delete them" chosen + click(&mut h, "button:settingsSmartChoose"); + assert_eq!(smart(&mut h)["custom"], true); + h.settle(T); + steps(&mut h); + click(&mut h, "button:settingsSmartExisting-2"); + // When Use Library Folder is pressed, it asks first + click(&mut h, "button:settingsSmartReset"); + let now = smart(&mut h); + assert_eq!((now["count"].clone(), now["custom"].clone()), (json!(1), json!(true)), "{now}"); + assert!(has(&h, "button:settingsSmartDelete")); +} + +#[test] +fn text_typed_in_copyright_is_saved_when_another_tab_is_opened() { + let mut h = demo(); + show(&mut h, "import"); + click(&mut h, "field:settings.copyright"); + h.request("ui.text", json!({"text": "Example Name"}), T); + steps(&mut h); + // When another tab is clicked with the text still being typed + click(&mut h, "button:settingsTab-general"); + // Then that tab opens and the text was saved, as leaving the box any other way saves it + assert!(settings_open(&h, "general")); + assert_eq!(copyright(&mut h), json!("Example Name")); +} + +#[test] +fn esc_in_an_external_editing_box_leaves_settings_open_too() { + let mut h = demo(); + show(&mut h, "files"); + let before = h.app.ui.settings.external_editor.clone(); + click(&mut h, "field:externalEditor"); + h.request("ui.text", json!({"text": "Example Editor"}), T); + steps(&mut h); + key(&mut h, "Escape"); + assert_eq!(h.app.ui.settings.external_editor, before, "Esc gives the text back"); + assert!(settings_open(&h, "files"), "and Settings stays open: {:?}", h.app.ui.dialog); +} + +#[test] +fn the_question_opens_with_the_focus_on_keep() { + let mut h = demo(); + show(&mut h, "performance"); + let before = h.app.session.media.rendered.mem_usage().0; + click(&mut h, "button:settingsClearCache"); + assert!(has(&h, "button:settingsClearCache:confirm")); + // When Return is pressed straight away + key(&mut h, "Enter"); + // Then the answer was Keep: the question is gone and nothing was cleared + assert!(!has(&h, "button:settingsClearCache:confirm")); + assert_eq!(h.app.session.media.rendered.mem_usage().0, before); + assert!(settings_open(&h, "performance")); +} + +#[test] +fn a_question_about_a_folder_that_has_changed_since_deletes_nothing() { + let dir = TempFolder::new("settings-trust-smart-outside"); + let to = dir.path("elsewhere"); + let mut h = with_smart_preview(&dir, &to); + show(&mut h, "library"); + click(&mut h, "button:settingsSmartExisting-2"); + click(&mut h, "button:settingsSmartChoose"); + assert!(has(&h, "button:settingsSmartDelete")); + // Given the folder changed from outside Settings (an agent, say) while the question stands + let other = dir.path("another"); + std::fs::create_dir_all(&other).unwrap(); + h.app.run("library.smartPreviewsLocation", json!({"path": other, "existing": "move"})).unwrap(); + // When Delete and Change Folder is pressed all the same + reach(&mut h, "button:settingsSmartDelete"); + let r = h.request("ui.clickWidget", json!({"id": "button:settingsSmartDelete"}), T); + assert_eq!(r["ok"], true, "{r}"); + steps(&mut h); + // Then nothing is deleted and the folder is the one set from outside: the question was about another + let now = smart(&mut h); + assert_eq!((now["count"].clone(), now["path"].clone()), (json!(1), json!(other)), "{now}"); + assert!(!has(&h, "button:settingsSmartDelete")); +} + +#[test] +fn after_keep_the_focus_is_back_on_the_button() { + let mut h = demo(); + show(&mut h, "performance"); + click(&mut h, "button:settingsClearCache"); + key(&mut h, "Enter"); // Keep, which has the focus + assert!(!has(&h, "button:settingsClearCache:confirm")); + // When Space is pressed again, the question opens again: the focus was on Clear Cache + key(&mut h, "Space"); + assert!(has(&h, "button:settingsClearCache:confirm"), "the focus went back to Clear Cache"); +} diff --git a/crates/ui-egui/src/tests_type_contrast.rs b/crates/ui-egui/src/tests_type_contrast.rs new file mode 100644 index 00000000000..424d4f12933 --- /dev/null +++ b/crates/ui-egui/src/tests_type_contrast.rs @@ -0,0 +1,319 @@ +//! What the interface writes can be read in every theme: text stands 4.5:1 against what it is +//! drawn on (3:1 at display size), on the panels, the grid, a photo being edited, Settings and the +//! dialogs. Left out: what is disabled, and text over a picture (its own scrim is another test). +//! +//! Before: the dim text of captions, counts and explanations was 4.20:1 on a panel in Charcoal and +//! 3.3 to 4.3:1 in the light themes, a link in the accent colour 2.56:1 in Charcoal, a caution +//! 3.09:1 in Silver, and anything `.weak()` under 4.1:1 in every theme. + +use std::collections::BTreeMap; +use std::time::Duration; + +use egui::{Color32, Rect}; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::panels::settings::TABS; +use crate::theme::{TextSize, ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(kind: ThemeKind) -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1280.0, 900.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + run(&mut h, "view.theme", json!({"theme": kind.id()})); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + rest(h); +} + +fn set(h: &mut Headless, what: Value) { + let r = h.request("ui.set", what, T); + assert_eq!(r["ok"], true, "ui.set: {r}"); + rest(h); +} + +/// Everything drawn and at rest, the pointer over nothing. +fn rest(h: &mut Headless) { + h.settle(T); + h.request("ui.move", json!({"x": 2.0, "y": 2.0}), T); + for _ in 0..3 { + h.step(); + } +} + +/// WCAG contrast of two opaque colours. +fn contrast(a: Color32, b: Color32) -> f32 { + let lum = |c: Color32| { + let lin = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b()) + }; + let (a, b) = (lum(a), lum(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) +} + +/// `over` drawn on `under`. +fn blend(over: Color32, under: Color32) -> Color32 { + let a = f32::from(over.a()) / 255.0; + // (premultiplied: the colour's channels already carry its alpha) + let mix = |o: u8, u: u8| (f32::from(o) + f32::from(u) * (1.0 - a)).round().clamp(0.0, 255.0) as u8; + Color32::from_rgb(mix(over.r(), under.r()), mix(over.g(), under.g()), mix(over.b(), under.b())) +} + +/// The colour most of `rect` is, and the share of its pixels that are it (one pixel a point). +fn ground(image: &egui::ColorImage, rect: Rect) -> Option<(Color32, f32)> { + let [w, h] = image.size; + let (x0, x1) = (rect.left().floor().max(0.0) as usize, (rect.right().ceil().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().floor().max(0.0) as usize, (rect.bottom().ceil().max(0.0) as usize).min(h)); + let mut seen: BTreeMap<[u8; 4], usize> = BTreeMap::new(); + for y in y0..y1 { + for x in x0..x1 { + *seen.entry(image.pixels[y * w + x].to_array()).or_default() += 1; + } + } + let all: usize = seen.values().sum(); + let (most, n) = seen.into_iter().max_by_key(|(_, n)| *n)?; + Some((Color32::from_rgba_premultiplied(most[0], most[1], most[2], most[3]), n as f32 / all as f32)) +} + +/// Whether any pixel of `rect` is nearly `colour`, and nearer it than the ground it would be on +/// (text under a light header is not "inked" by the header's being nearly white). +fn inked(image: &egui::ColorImage, rect: Rect, colour: Color32, ground: Color32) -> bool { + let [w, h] = image.size; + let (x0, x1) = (rect.left().floor().max(0.0) as usize, (rect.right().ceil().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().floor().max(0.0) as usize, (rect.bottom().ceil().max(0.0) as usize).min(h)); + let far = |p: Color32, from: Color32| p.r().abs_diff(from.r()).max(p.g().abs_diff(from.g())).max(p.b().abs_diff(from.b())); + (y0..y1).any(|y| (x0..x1).any(|x| image.pixels.get(y * w + x).is_some_and(|p| far(*p, colour) <= 20 && far(*p, colour) < far(*p, ground)))) +} + +/// The text on screen that cannot be read: what it says, its colour, what it is on and how far +/// apart the two stand. +fn unreadable(h: &Headless, t: &Tokens, within: Option) -> Vec { + let image = h.paint(); + let mut out = BTreeMap::new(); + fn texts(shape: &egui::Shape, clip: Rect, out: &mut Vec<(egui::epaint::TextShape, Rect)>) { + match shape { + egui::Shape::Text(text) => out.push((text.clone(), clip)), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| texts(s, clip, out)), + _ => {} + } + } + let mut drawn = Vec::new(); + h.view.shapes.iter().for_each(|s| texts(&s.shape, s.clip_rect, &mut drawn)); + for (text, clip) in drawn { + let said = text.galley.job.text.trim(); + // (a disabled control is drawn fainter as a whole; nothing to read in an empty string) + if said.is_empty() || text.opacity_factor < 1.0 { + continue; + } + let rect = text.visual_bounding_rect().intersect(clip); + // (what lies under a dialog's shade is not what is being read) + if within.is_some_and(|within| !within.contains_rect(rect)) { + continue; + } + // (a row cut by the edge of what scrolls: too little of it is left to say what it is on) + let whole = text.visual_bounding_rect(); + if rect.width() < 2.0 || rect.height() < 2.0 || rect.area() < 0.6 * whole.area() { + continue; + } + // (a little around the letters: a dash's own rectangle is mostly dash) + let Some((on, share)) = ground(&image, rect.expand(2.0)) else { continue }; + // (over a picture no colour is most of the rectangle) + if share < 0.3 { + continue; + } + let large = text.galley.job.sections.iter().all(|s| s.format.font_id.size >= TextSize::Display.points()); + for section in &text.galley.job.sections { + let own = Some(section.format.color).filter(|c| *c != Color32::PLACEHOLDER); + let colour = text.override_text_color.or(own).unwrap_or(text.fallback_color); + // (a count of nothing is fainter on purpose: the rows that hold photos stand out) + if colour == t.text_disabled || colour.a() == 0 || colour == t.text_dim.gamma_multiply(0.55) { + continue; + } + let shown = blend(colour, on); + // (text under a window is drawn and then covered: none of its colour is left) + if !inked(&image, rect, shown, on) { + continue; + } + let stands = contrast(shown, on); + if stands < if large { 3.0 } else { 4.5 } { + let what: String = said.chars().take(28).collect(); + out.entry((shown.to_array(), on.to_array())) + .or_insert_with(|| format!("{what:?} {:?} on {:?}: {stands:.2}", shown.to_array(), on.to_array())); + } + } + } + out.into_values().collect() +} + +fn assert_readable(h: &Headless, kind: ThemeKind, screen: &str, bad: &mut Vec) { + let t = Tokens::for_kind(kind); + // (with a dialog open, the dialog is what is read) + let dialog = h.app.widgets.iter().find(|(w, _)| w == "dialog:window").map(|(_, r)| *r); + assert_eq!(dialog.is_some(), h.app.ui.dialog.is_some(), "{screen}: a dialog and its window go together"); + bad.extend(unreadable(h, &t, dialog).into_iter().map(|line| format!("{kind:?}, {screen}: {line}"))); +} + +fn report(bad: Vec) { + assert!(bad.is_empty(), "{} kinds of text cannot be read:\n{}", bad.len(), bad.join("\n")); +} + +#[test] +fn the_library_can_be_read_in_every_theme() { + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + // Given the demo library in the grid in a theme, with the sidebar and each right panel + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + run(&mut h, "library.select", json!({"ids": [1]})); + for right in ["info", "keywords", "edit", "versions", "activity"] { + // When the panel is shown + set(&mut h, json!({"leftPanel": true, "right": right, "thumbSize": 200})); + // Then its text stands out from what it is on + assert_readable(&h, kind, &format!("grid with {right}"), &mut bad); + } + // And with a filter on (its count is written on a circle of the accent in the top bar), + // in square cells, each with its name and format over it, one of them the chosen one + run(&mut h, "library.filter", json!({"rating": 1})); + run(&mut h, "view.squareGrid", json!({})); + // (two of them with a colour label, which tints the cell: the chosen one and another) + let shown: Vec = h.app.session.visible_cloned().iter().take(3).map(|id| id.0).collect(); + let [chosen, other, ..] = shown[..] else { panic!("{kind:?}: three photos pass the filter") }; + run(&mut h, "photo.label", json!({"ids": [chosen], "label": "red"})); + run(&mut h, "photo.label", json!({"ids": [other], "label": "yellow"})); + run(&mut h, "library.select", json!({"ids": [chosen]})); + for id in [chosen, other] { + assert!(h.app.widgets.iter().any(|(w, _)| *w == format!("thumb:{id}")), "{kind:?}: photo {id} is on screen"); + } + assert!(h.painted_text().iter().any(|t| t == "JPEG"), "{kind:?}: the cells say their format"); + assert_readable(&h, kind, "square grid, filtered", &mut bad); + } + report(bad); +} + +#[test] +fn a_photo_being_edited_can_be_read_in_every_theme() { + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme, the filmstrip under it + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + for right in ["edit", "info", "masking", "crop", "remove", "profiles"] { + // When each tool panel is shown + set(&mut h, json!({"leftPanel": false, "right": right, "openSections": ["light", "color", "effects", "detail"]})); + // Then its text stands out from what it is on + assert_readable(&h, kind, &format!("detail with {right}"), &mut bad); + } + } + report(bad); +} + +#[test] +fn the_names_over_the_filmstrip_can_be_read_on_any_cell_in_every_theme() { + /// The filmstrip's cells that are wholly on screen, by photo. + fn cells(h: &Headless) -> Vec<(u64, Rect)> { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let cell = |(w, r): &(String, Rect)| Some((w.strip_prefix("film:")?.parse().ok()?, *r)); + h.app.widgets.iter().filter_map(cell).filter(|(_, r)| screen.contains_rect(*r)).collect() + } + const LABELS: [&str; 5] = ["red", "yellow", "green", "blue", "purple"]; + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme, and on the filmstrip under it a photo with + // each colour label, which tints its cell, and one with none + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "info"})); + let others: Vec = cells(&h).iter().map(|(id, _)| *id).filter(|id| *id != 1).take(LABELS.len() + 1).collect(); + let [labelled @ .., plain] = &others[..] else { panic!("{kind:?}: other photos are on the filmstrip") }; + assert_eq!(labelled.len(), LABELS.len(), "{kind:?}: a photo for each label and one more are on the filmstrip"); + for (id, label) in labelled.iter().zip(LABELS) { + run(&mut h, "photo.label", json!({"ids": [id], "label": label})); + } + assert!(h.painted_text().iter().any(|t| t == "JPEG"), "{kind:?}: the cells say their format"); + // Then at rest the names stand out from their cells + assert_readable(&h, kind, "filmstrip at rest", &mut bad); + for (id, label) in labelled.iter().zip(LABELS).chain([(plain, "no label")]) { + // When the pointer is on a cell that is not the chosen one (its fill is see-through) + let cell = cells(&h).iter().find(|(c, _)| c == id).map(|(_, r)| *r); + let Some(cell) = cell else { panic!("{kind:?}: photo {id} is on the filmstrip") }; + h.request("ui.move", json!({"x": cell.center().x, "y": cell.top() + 10.0}), T); + for _ in 0..3 { + h.step(); + } + // Then its name and format stand out from the cell as it is painted + assert_readable(&h, kind, &format!("filmstrip, pointer on a cell with {label}"), &mut bad); + } + for (id, label) in labelled.iter().zip(LABELS) { + // And when a labelled photo is the chosen one + run(&mut h, "library.select", json!({"ids": [id]})); + assert_readable(&h, kind, &format!("filmstrip, the photo with {label} chosen"), &mut bad); + } + } + report(bad); +} + +#[test] +fn settings_and_the_dialogs_can_be_read_in_every_theme() { + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + let mut h = demo(kind); + // Given each tab of Settings in a theme + for (tab, _) in TABS { + run(&mut h, "app.settings", json!({"tab": tab})); + assert_readable(&h, kind, &format!("Settings ▸ {tab}"), &mut bad); + } + h.request("ui.dialog.cancel", json!({}), T); + // And the dialogs a person meets most + for command in ["dialog.export", "app.shortcuts", "app.about"] { + run(&mut h, command, json!({})); + assert_readable(&h, kind, command, &mut bad); + h.request("ui.dialog.cancel", json!({}), T); + h.step(); + } + } + report(bad); +} + +#[test] +fn the_colours_that_say_something_stand_out_from_every_surface_in_every_theme() { + for kind in ThemeKind::ALL { + let t = Tokens::for_kind(kind); + // Given the surfaces text is written on at rest + for on in [t.chrome, t.canvas, t.grid_bg, t.cell, t.inset, t.field, t.button] { + // When dim text, a link, a caution or an error is written on one + for (what, colour) in [("dim", t.text_dim), ("link", t.text_link()), ("caution", t.text_caution()), ("error", t.text_error())] { + // Then it stands 4.5:1 + assert!(contrast(colour, on) >= 4.5, "{kind:?}: {what} {colour:?} on {on:?} is {:.2}", contrast(colour, on)); + } + } + // And dim text is still dimmer than a label, which is dimmer than what is written + let (dim, label, text) = (contrast(t.text_dim, t.chrome), contrast(t.text_label, t.chrome), contrast(t.text, t.chrome)); + assert!(dim + 1.0 < label && label < text, "{kind:?}: dim {dim:.2}, label {label:.2}, text {text:.2}"); + // And what is chosen keeps its label readable on the accent mixed in behind it + assert!(contrast(t.text_label, t.selection_fill()) >= 4.5, "{kind:?}: a chosen chip"); + assert_ne!(t.selection_fill(), t.chrome, "{kind:?}: what is chosen is marked"); + // And a count or a mark on a filled circle is in the ink that stands out from the fill + for fill in [t.accent, t.reject, t.caution] { + let ink = t.ink_on(fill); + assert!(contrast(ink, fill) >= 4.5, "{kind:?}: {ink:?} on {fill:?} is {:.2}", contrast(ink, fill)); + } + } + // And black or white is chosen by which is farther, also where neither is far + let t = Tokens::for_kind(ThemeKind::Charcoal); + assert_eq!(t.ink_on(Color32::BLACK), Color32::WHITE); + assert_eq!(t.ink_on(Color32::WHITE), Color32::BLACK); + assert_eq!(t.ink_on(Color32::from_gray(118)), Color32::BLACK); +} diff --git a/crates/ui-egui/src/tests_type_fit.rs b/crates/ui-egui/src/tests_type_fit.rs new file mode 100644 index 00000000000..3be71049ebf --- /dev/null +++ b/crates/ui-egui/src/tests_type_fit.rs @@ -0,0 +1,195 @@ +//! Words that are longer in another language keep to their place: a button does not lie over +//! its neighbour, a choice's name stays inside the choice, a row of the filter bar ends inside +//! the bar, and a value begins after its label. +//! +//! Before, in German: Reset ("Zurücksetzen") lay over HDR in the head of the Edit panel, "Mit +//! Hilfslinien" ran out of its third of the Upright choices, and the filter bar's first row ran +//! off the grid at "Bearbeitet oder nicht". (The card of Info already gives a long label its +//! room, "Velocidade do obturador" among them: its scenario keeps it so.) + +use std::time::Duration; + +use egui::Rect; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(language: &str) -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + run(&mut h, language, json!({})); + run(&mut h, "library.select", json!({"ids": [1]})); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + rest(h); +} + +fn set(h: &mut Headless, what: Value) { + let r = h.request("ui.set", what, T); + assert_eq!(r["ok"], true, "ui.set: {r}"); + rest(h); +} + +fn rest(h: &mut Headless) { + h.settle(T); + h.request("ui.move", json!({"x": 2.0, "y": 2.0}), T); + // (a layout that follows what it measured the frame before has come to rest) + for _ in 0..5 { + h.step(); + } +} + +fn rect(h: &Headless, id: &str) -> Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +fn widgets(h: &Headless, prefix: &str) -> Vec<(String, Rect)> { + h.app.widgets.iter().filter(|(w, _)| w.starts_with(prefix)).cloned().collect() +} + +/// Every piece of text drawn, with where it is. +fn texts(h: &Headless) -> Vec<(String, Rect)> { + h.view + .painted_shapes() + .iter() + .filter_map(|shape| match shape { + egui::Shape::Text(text) => Some((text.galley.job.text.clone(), text.visual_bounding_rect())), + _ => None, + }) + .collect() +} + +#[test] +fn the_buttons_at_the_head_of_edit_do_not_lie_over_one_another() { + for language in ["app.language.english", "app.language.german", "app.language.russian", "app.language.french"] { + // Given a photo being edited in a language + let mut h = demo(language); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light"]})); + // When the head of the Edit panel is drawn + let buttons: Vec<(&str, Rect)> = ["auto", "bw", "hdr", "reset"].into_iter().map(|id| (id, rect(&h, &format!("button:{id}")))).collect(); + // Then no button touches another + for (i, (a, ra)) in buttons.iter().enumerate() { + for (b, rb) in buttons.iter().skip(i + 1) { + assert!(!ra.expand(1.0).intersects(*rb), "{language}: {a} {ra:?} lies over {b} {rb:?}"); + } + } + } +} + +#[test] +fn the_name_of_a_choice_stays_inside_the_choice() { + for language in ["app.language.english", "app.language.german", "app.language.russian", "app.language.french", "app.language.spanish"] { + // Given the Crop panel in a language, with its rows of choices + let mut h = demo(language); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "crop"})); + let drawn = texts(&h); + let mut choices = widgets(&h, "button:cropOverlay-"); + choices.extend(widgets(&h, "button:upright-")); + assert!(choices.len() >= 10, "{language}: the overlay and upright choices are on screen ({})", choices.len()); + // Then each choice's name lies inside it, with a little room at each side + for (id, choice) in choices { + let name = drawn.iter().find(|(_, at)| choice.contains(at.center())).unwrap_or_else(|| panic!("{language}: {id} has no name")); + assert!( + choice.shrink2(egui::vec2(2.0, 0.0)).contains_rect(name.1), + "{language}: {:?} at {:?} runs out of {id} {choice:?}", + name.0, + name.1 + ); + } + } +} + +#[test] +fn a_row_of_the_filter_bar_ends_inside_the_bar() { + for language in ["app.language.english", "app.language.german", "app.language.russian", "app.language.french"] { + // Given the grid with both side panels and the filter bar, in a language + let mut h = demo(language); + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200, "filterBar": true})); + let bar = rect(&h, "filterbar"); + // When its controls are drawn + let mut controls = widgets(&h, "dropdown:filter-"); + controls.extend(["button:filterSave", "button:filterClear", "button:filterPresets"].into_iter().map(|id| (id.to_string(), rect(&h, id)))); + assert!(controls.len() >= 8, "{language}: {}", controls.len()); + // Then every one of them lies in the bar + for (id, control) in controls { + assert!(bar.contains_rect(control), "{language}: {id} {control:?} runs out of the bar {bar:?}"); + } + } +} + +#[test] +fn a_value_on_the_card_of_info_begins_after_its_label() { + for language in ["app.language.english", "app.language.german", "app.language.portuguese", "app.language.spanish", "app.language.french"] { + // Given the Info panel of a photo in a language + let mut h = demo(language); + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200})); + let drawn = texts(&h); + let meta = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(1)).map(|p| p.meta.clone()).expect("photo 1"); + let mut begins = Vec::new(); + for (label, value) in [ + ("Focal length", meta.focal_mm.and_then(crate::readout::focal)), + ("Shutter speed", crate::readout::shutter(&meta.shutter)), + ("Aperture", meta.aperture.and_then(crate::readout::aperture)), + ] { + let (label, value) = (crate::i18n::tr(label).to_string(), value.expect("the demo photo has it")); + let at = |said: &str| { + drawn.iter().find(|(text, _)| text == said).map(|(_, at)| *at).unwrap_or_else(|| panic!("{language}: {said:?} is not drawn")) + }; + let (label_at, value_at) = (at(&label), at(&value)); + // Then the value begins at least a gap after its label ends + assert!(value_at.left() >= label_at.right() + 8.0, "{language}: {label:?} {label_at:?} and {value:?} {value_at:?}"); + begins.push(value_at.left()); + } + // And the values stand under one another + assert!(begins.iter().all(|x| (x - begins[0]).abs() < 1.0), "{language}: {begins:?}"); + } +} + +#[test] +fn the_filter_bar_comes_to_rest_at_every_width() { + for language in ["app.language.english", "app.language.german", "app.language.french"] { + // Given the grid and the filter bar in a language, and what the bar's three parts measure + let mut h = demo(language); + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200, "filterBar": true})); + let parts: [f32; 3] = h.view.ctx.data(|d| d.get_temp(egui::Id::new("filterbar:widths"))).expect("the bar has measured its parts"); + assert!(parts.iter().all(|w| *w > 40.0), "{language}: {parts:?}"); + let gap = 4.0; + // When the window is as wide as leaves the bar a point or two more or less than each of + // the widths at which what a row holds changes + for edge in [parts[0] + parts[1] + parts[2] + 2.0 * gap, parts[0] + parts[1] + gap, parts[1] + parts[2] + gap] { + for tenth in -40..=40 { + let room = edge + tenth as f32 / 10.0; + h.size.x += room - (rect(&h, "filterbar").width() - 32.0); + let mut heights = Vec::new(); + for _ in 0..12 { + h.step(); + heights.push(rect(&h, "filterbar").height()); + } + assert!(((rect(&h, "filterbar").width() - 32.0) - room).abs() < 0.05, "{language}: the bar has the room asked for"); + // Then within a few frames the bar is one height and stays it: it used to change + // every frame in a band four points wide, and the grid under it jumped + let rest: Vec = heights.iter().skip(6).copied().collect(); + assert!(rest.iter().all(|height| *height == rest[0]), "{language}: at {room} pt of room the bar is {heights:?} high frame by frame"); + // And nothing in it runs out of it + let bar = rect(&h, "filterbar"); + for (id, control) in widgets(&h, "dropdown:filter-") { + assert!(control.right() <= bar.right() + 0.5, "{language}: at {room} pt {id} {control:?} runs out of {bar:?}"); + } + } + } + } +} diff --git a/crates/ui-egui/src/tests_type_on_photo.rs b/crates/ui-egui/src/tests_type_on_photo.rs new file mode 100644 index 00000000000..489e5a8165c --- /dev/null +++ b/crates/ui-egui/src/tests_type_on_photo.rs @@ -0,0 +1,394 @@ +//! What is written or marked over a picture is in one light ink on a dark shade of its own, in +//! every theme: the ratings and flags on a thumbnail, the toast, the name of a side in Before and +//! After. A picture has no theme, so the colours of a theme's text do not belong on it. +//! +//! Before: in the light themes a thumbnail's stars were dark grey (the theme's star colour) on the +//! photo or on a dark bar, and the toast wrote the theme's near-black text on a black shade; in +//! the dark themes a rated thumbnail's stars lay on the bare photo and went out on a bright one. + +use std::time::Duration; + +use egui::{Color32, Rect}; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::theme::{ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(kind: ThemeKind) -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + run(&mut h, "view.theme", json!({"theme": kind.id()})); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + rest(h); +} + +/// Everything drawn and at rest, the pointer over nothing. +fn rest(h: &mut Headless) { + h.settle(T); + h.request("ui.move", json!({"x": 2.0, "y": 2.0}), T); + for _ in 0..3 { + h.step(); + } +} + +/// WCAG contrast of two opaque colours. +fn contrast(a: Color32, b: Color32) -> f32 { + let lum = |c: Color32| { + let lin = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b()) + }; + let (a, b) = (lum(a), lum(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) +} + +fn pixels(image: &egui::ColorImage, rect: Rect) -> Vec { + let [w, h] = image.size; + let (x0, x1) = (rect.left().floor().max(0.0) as usize, (rect.right().ceil().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().floor().max(0.0) as usize, (rect.bottom().ceil().max(0.0) as usize).min(h)); + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).map(|(x, y)| image.pixels[y * w + x]).collect() +} + +/// The colours a drawn shape is filled and outlined in (text aside). +fn colours(shape: &egui::Shape) -> Vec { + match shape { + egui::Shape::Path(path) => match &path.stroke.color { + egui::epaint::ColorMode::Solid(stroke) => vec![path.fill, *stroke], + egui::epaint::ColorMode::UV(_) => vec![path.fill], + }, + egui::Shape::LineSegment { stroke, .. } => vec![stroke.color], + egui::Shape::Circle(circle) => vec![circle.fill, circle.stroke.color], + egui::Shape::Ellipse(ellipse) => vec![ellipse.fill, ellipse.stroke.color], + egui::Shape::Rect(rect) => vec![rect.fill, rect.stroke.color], + _ => Vec::new(), + } +} + +/// A rated photo's cell that is on screen and not the chosen one: `prefix` is `thumb` or `film`. +fn rated_cell(h: &Headless, prefix: &str, chosen: u64) -> (Rect, u8) { + let screen = Rect::from_min_size(egui::Pos2::ZERO, h.size); + h.app + .widgets + .iter() + .filter_map(|(id, r)| Some((id.strip_prefix(prefix)?.strip_prefix(':')?.parse::().ok()?, *r))) + .filter(|(id, r)| *id != chosen && screen.contains_rect(*r)) + .find_map(|(id, r)| { + let photo = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(id))?; + (photo.rating >= 2 && photo.label.is_none()).then_some((r, photo.rating)) + }) + .unwrap_or_else(|| panic!("no rated {prefix} on screen")) +} + +/// In the strip along the bottom of `cell`: marks are drawn in the ink for pictures, each on a +/// rectangle of the shade, and the shade is under them in the picture that results. +fn assert_marked(h: &Headless, cell: Rect, rating: u8, what: &str) { + let (ink, shade) = (Tokens::on_photo(), Tokens::photo_shade()); + let strip = Rect::from_min_max(egui::pos2(cell.left(), cell.bottom() - 30.0), cell.right_bottom()); + let shapes = h.view.painted_shapes(); + let within: Vec<&egui::Shape> = shapes.iter().filter(|s| strip.contains_rect(s.visual_bounding_rect())).collect(); + // (a star is one shape or a few; there are at least as many in the ink as stars) + let marks: Vec = + within.iter().filter(|s| !matches!(s, egui::Shape::Rect(_)) && colours(s).contains(&ink)).map(|s| s.visual_bounding_rect()).collect(); + assert!(marks.len() >= usize::from(rating), "{what}: {} marks in the ink {ink:?} for {rating} stars", marks.len()); + // (the shade may be wider than the cell: a photo cut to its cell brings its strip along) + let shades: Vec = + shapes.iter().filter(|s| matches!(s, egui::Shape::Rect(r) if r.fill == shade)).map(|s| s.visual_bounding_rect()).collect(); + for mark in &marks { + assert!(shades.iter().any(|shade| shade.expand(1.0).contains_rect(*mark)), "{what}: the mark at {mark:?} has no shade under it ({shades:?})"); + } + // And in the picture: the shade beside the marks is dark enough for the ink to stand 3:1 + let image = h.paint(); + let [w, height] = image.size; + let mut stands = Vec::new(); + for shade in shades.iter().filter(|shade| marks.iter().any(|mark| shade.expand(1.0).contains_rect(*mark))) { + let inside = shade.shrink(1.0).intersect(cell); + for y in inside.top().ceil().max(0.0) as usize..(inside.bottom().floor().max(0.0) as usize).min(height) { + for x in inside.left().ceil().max(0.0) as usize..(inside.right().floor().max(0.0) as usize).min(w) { + let here = egui::pos2(x as f32 + 0.5, y as f32 + 0.5); + if !marks.iter().any(|mark| mark.expand(1.5).contains(here)) { + stands.push(contrast(ink, image.pixels[y * w + x])); + } + } + } + } + stands.sort_by(f32::total_cmp); + // (a tenth in: a mark's soft edge may reach a pixel past its rectangle) + let ground = stands.get(stands.len() / 10).copied().unwrap_or(1.0); + assert!(stands.len() >= 12 && ground >= 3.0, "{what}: the ink stands {ground:.2} against its shade ({} pixels of it)", stands.len()); +} + +/// The first text shape that says `part`: its colour and where it is. +fn text(h: &Headless, part: &str) -> (Color32, Rect) { + h.view + .painted_shapes() + .iter() + .find_map(|shape| match shape { + egui::Shape::Text(text) if text.galley.job.text.contains(part) => { + let own = text.galley.job.sections.first().map(|s| s.format.color).filter(|c| *c != Color32::PLACEHOLDER); + Some((text.override_text_color.or(own).unwrap_or(text.fallback_color), text.visual_bounding_rect())) + } + _ => None, + }) + .unwrap_or_else(|| panic!("no text with {part:?} is drawn")) +} + +/// The colour most of `rect` is. +fn ground(image: &egui::ColorImage, rect: Rect) -> Color32 { + let mut seen = std::collections::BTreeMap::new(); + for p in pixels(image, rect) { + *seen.entry(p.to_array()).or_insert(0usize) += 1; + } + let most = seen.into_iter().max_by_key(|(_, n)| *n).map(|(c, _)| c).unwrap_or([0; 4]); + Color32::from_rgb(most[0], most[1], most[2]) +} + +#[test] +fn the_marks_on_a_thumbnail_stand_out_from_the_photo_in_every_theme() { + for kind in ThemeKind::ALL { + // Given the grid in a theme, and a rated photo that is neither chosen nor under the pointer + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + run(&mut h, "library.select", json!({"ids": [2]})); + let r = h.request("ui.set", json!({"leftPanel": true, "right": "info", "thumbSize": 200}), T); + assert_eq!(r["ok"], true, "{r}"); + rest(&mut h); + // When it is drawn + let (thumb, rating) = rated_cell(&h, "thumb", 2); + // Then its stars are in the ink for pictures, on a shade that lets them stand 3:1 + assert_marked(&h, thumb, rating, &format!("{kind:?}: the stars on a thumbnail")); + } +} + +#[test] +fn the_marks_on_a_filmstrip_cell_stand_out_in_every_theme() { + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme, the filmstrip under it + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [2]})); + run(&mut h, "view.detail", json!({})); + // When a rated photo's cell is drawn + let (cell, rating) = rated_cell(&h, "film", 2); + // Then its stars are in the ink for pictures on their shade + assert_marked(&h, cell, rating, &format!("{kind:?}: the stars on a filmstrip cell")); + } +} + +#[test] +fn a_toast_can_be_read_in_every_theme() { + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + // When something is said in a toast + let now = h.view.ctx.input(|i| i.time); + h.app.ui.toast = Some(("Rated 3 stars".into(), now + 60.0, None)); + h.step(); + h.step(); + // Then it is written in the ink for pictures and stands 4.5:1 against its shade + let (colour, at) = text(&h, "Rated 3 stars"); + assert_eq!(colour, Tokens::on_photo(), "{kind:?}"); + let on = ground(&h.paint(), at.expand(6.0)); + assert!(contrast(colour, on) >= 4.5, "{kind:?}: {colour:?} on {on:?} is {:.2}", contrast(colour, on)); + } +} + +#[test] +fn before_is_named_on_a_shade_of_its_own_in_every_theme() { + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + // When the photo is shown as it was before its edits + run(&mut h, "view.showOriginal", json!({})); + // Then "Before" is written over the picture in the ink for pictures, on a shade + let (colour, at) = text(&h, "Before"); + assert_eq!(colour, Tokens::on_photo(), "{kind:?}"); + let on = ground(&h.paint(), at.expand(3.0)); + assert!(contrast(colour, on) >= 4.5, "{kind:?}: {colour:?} on {on:?} is {:.2}", contrast(colour, on)); + } +} + +#[test] +fn the_ink_for_pictures_stands_out_from_its_shade_over_any_picture() { + // Given the shade laid over the brightest and the darkest a picture can be + let (ink, shade) = (Tokens::on_photo(), Tokens::photo_shade()); + let a = f32::from(shade.a()) / 255.0; + for under in [Color32::WHITE, Color32::BLACK, Color32::from_rgb(255, 230, 40)] { + let mix = |u: u8| (f32::from(u) * (1.0 - a)).round() as u8; + let on = Color32::from_rgb(mix(under.r()), mix(under.g()), mix(under.b())); + // Then the ink stands 4.5:1 on it + assert!(contrast(ink, on) >= 4.5, "{ink:?} over {under:?}: {:.2}", contrast(ink, on)); + } +} + +#[test] +fn a_rejection_over_a_picture_is_a_red_that_stands_out_from_its_shade() { + // Given the red a rejected photo's flag is drawn in over a picture + let (red, shade) = (Tokens::on_photo_reject(), Tokens::photo_shade()); + let a = f32::from(shade.a()) / 255.0; + // When the shade lies over the brightest a picture can be, and over the darkest + for under in [Color32::WHITE, Color32::BLACK] { + let mix = |u: u8| (f32::from(u) * (1.0 - a)).round() as u8; + let on = Color32::from_rgb(mix(under.r()), mix(under.g()), mix(under.b())); + // Then the flag stands 3:1, as a mark must + assert!(contrast(red, on) >= 3.0, "{red:?} over {under:?}: {:.2}", contrast(red, on)); + } + // And it is drawn in that red in every theme, on a shade (the theme's own red is for panels) + for kind in ThemeKind::ALL { + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + let rejected = h + .app + .session + .catalog + .photos() + .find(|p| p.flag == lightcraft_catalog::Flag::Reject) + .map(|p| p.id.0) + .expect("the demo has a rejected photo"); + run(&mut h, "library.select", json!({"ids": [rejected]})); + run(&mut h, "view.detail", json!({})); + let cell = h.app.widgets.iter().find(|(w, _)| *w == format!("film:{rejected}")).map(|(_, r)| *r).expect("its filmstrip cell"); + let shapes = h.view.painted_shapes(); + let flags: Vec = shapes + .iter() + .filter(|s| colours(s).contains(&red) && cell.intersects(s.visual_bounding_rect())) + .map(|s| s.visual_bounding_rect()) + .collect(); + assert!(!flags.is_empty(), "{kind:?}: the flag is in {red:?}"); + let shades: Vec = + shapes.iter().filter(|s| matches!(s, egui::Shape::Rect(r) if r.fill == shade)).map(|s| s.visual_bounding_rect()).collect(); + for flag in flags { + assert!(shades.iter().any(|shade| shade.expand(1.0).contains_rect(flag)), "{kind:?}: the flag at {flag:?} has no shade ({shades:?})"); + } + } +} + +#[test] +fn the_marks_of_a_narrow_thumbnail_stay_on_the_thumbnail() { + // Given the grid with thumbnails so small that a portrait one is narrower than its marks + let mut h = demo(ThemeKind::Charcoal); + run(&mut h, "view.photoGrid", json!({})); + let r = h.request("ui.set", json!({"leftPanel": true, "right": "info", "thumbSize": 60}), T); + assert_eq!(r["ok"], true, "{r}"); + rest(&mut h); + let cells: Vec = h.app.widgets.iter().filter(|(w, _)| w.starts_with("thumb:")).map(|(_, r)| *r).collect(); + assert!(cells.len() >= 8 && cells.iter().any(|c| c.width() < 60.0), "narrow thumbnails are on screen"); + // When their marks are drawn + fn marks(shape: &egui::Shape, clip: Rect, out: &mut Vec<(Rect, Rect)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| marks(s, clip, out)), + other if colours(other).contains(&Tokens::on_photo()) && !matches!(other, egui::Shape::Rect(_)) => { + out.push((other.visual_bounding_rect(), clip)) + } + _ => {} + } + } + let mut drawn = Vec::new(); + h.view.shapes.iter().for_each(|s| marks(&s.shape, s.clip_rect, &mut drawn)); + assert!(drawn.len() >= 8, "marks are drawn ({})", drawn.len()); + // Then what shows of each lies on its own thumbnail: none reaches over the gap to the next + for (mark, clip) in drawn { + let shown = mark.intersect(clip); + if shown.width() <= 0.0 || shown.height() <= 0.0 { + continue; + } + assert!(cells.iter().any(|cell| cell.expand(0.5).contains_rect(shown)), "the mark at {shown:?} is on no thumbnail"); + } +} + +#[test] +fn a_photo_chosen_or_under_the_pointer_keeps_the_band_along_its_lower_edge() { + for kind in ThemeKind::ALL { + // Given the grid in a theme, and a photo with no rating, flag, label or edit + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + let r = h.request("ui.set", json!({"leftPanel": true, "right": "info", "thumbSize": 200}), T); + assert_eq!(r["ok"], true, "{r}"); + rest(&mut h); + let screen = Rect::from_min_size(egui::Pos2::ZERO, h.size); + let plain = h + .app + .widgets + .iter() + .filter_map(|(id, r)| Some((id.strip_prefix("thumb:")?.parse::().ok()?, *r))) + .filter(|(_, r)| screen.contains_rect(*r)) + .find(|(id, _)| { + h.app + .session + .catalog + .photo(lightcraft_catalog::PhotoId(*id)) + .is_some_and(|p| p.rating == 0 && p.flag == lightcraft_catalog::Flag::None && p.label.is_none() && !p.is_edited()) + }) + .map(|(id, _)| id) + .expect("a plain photo is on screen"); + let band = |h: &Headless| { + let cell = h.app.widgets.iter().find(|(w, _)| *w == format!("thumb:{plain}")).map(|(_, r)| *r).expect("its thumbnail"); + let strip = Rect::from_min_max(egui::pos2(cell.left(), cell.bottom() - 24.0), cell.right_bottom()); + h.view.painted_shapes().iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.fill == Color32::from_black_alpha(120) && (r.rect.width() - strip.width()).abs() < 1.0 && strip.expand(1.0).contains_rect(r.rect))) + }; + // When it is not chosen, it has no band; when it is chosen, it has one the width of the + // photo: in the light themes its outline alone is 1.1 to 2.1:1 against the grid + run(&mut h, "library.select", json!({"ids": []})); + assert!(!band(&h), "{kind:?}: a photo that is not chosen has no band"); + // When the pointer is on it, it has the band (nothing else says the pointer is there) + let cell = h.app.widgets.iter().find(|(w, _)| *w == format!("thumb:{plain}")).map(|(_, r)| *r).expect("its thumbnail"); + h.request("ui.move", json!({"x": cell.center().x, "y": cell.center().y}), T); + for _ in 0..3 { + h.step(); + } + assert!(band(&h), "{kind:?}: the photo under the pointer has its band"); + rest(&mut h); + assert!(!band(&h), "{kind:?}: the band goes when the pointer does"); + run(&mut h, "library.select", json!({"ids": [plain]})); + assert!(band(&h), "{kind:?}: the chosen photo has its band"); + } +} + +#[test] +fn a_rejected_photos_flag_is_not_dimmed_with_the_photo() { + for kind in ThemeKind::ALL { + // Given the grid in a theme, with a rejected photo (which is drawn dimmed) + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + let r = h.request("ui.set", json!({"leftPanel": false, "right": "none", "thumbSize": 110}), T); + assert_eq!(r["ok"], true, "{r}"); + run(&mut h, "library.select", json!({"ids": []})); + let screen = Rect::from_min_size(egui::Pos2::ZERO, h.size); + let cell = h + .app + .widgets + .iter() + .filter_map(|(id, r)| Some((id.strip_prefix("thumb:")?.parse::().ok()?, *r))) + .filter(|(_, r)| screen.contains_rect(*r)) + .find(|(id, _)| h.app.session.catalog.photo(lightcraft_catalog::PhotoId(*id)).is_some_and(|p| p.flag == lightcraft_catalog::Flag::Reject)) + .map(|(_, r)| r) + .expect("a rejected photo is on screen"); + // When it is painted + let image = h.paint(); + let strip = Rect::from_min_max(egui::pos2(cell.left(), cell.bottom() - 24.0), cell.right_bottom()); + // Then its flag is in the red for pictures as that red is, and stands 3:1 on what is + // beside it: the dimming lies under the marks, not over them + let red = Tokens::on_photo_reject(); + let all = pixels(&image, strip); + let flag = all.iter().filter(|p| p.r().abs_diff(red.r()).max(p.g().abs_diff(red.g())).max(p.b().abs_diff(red.b())) <= 24).count(); + assert!(flag >= 6, "{kind:?}: {flag} pixels of the flag's red {red:?} along the lower edge"); + let mut stands: Vec = all.iter().map(|p| contrast(red, *p)).collect(); + stands.sort_by(f32::total_cmp); + let darkest = stands.last().copied().unwrap_or(1.0); + assert!(darkest >= 3.0, "{kind:?}: the red stands {darkest:.2} against its shade"); + } +} diff --git a/crates/ui-egui/src/tests_type_readout.rs b/crates/ui-egui/src/tests_type_readout.rs new file mode 100644 index 00000000000..206106d2bde --- /dev/null +++ b/crates/ui-egui/src/tests_type_readout.rs @@ -0,0 +1,211 @@ +//! What is read off a photo or a control is written one way: an exposure in the same words +//! wherever it is shown, a negative value with a minus, values in a column of figures. +//! (The parts are tested in `readout.rs`; here, what a person sees.) + +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo() -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + rest(h); +} + +fn set(h: &mut Headless, what: Value) { + let r = h.request("ui.set", what, T); + assert_eq!(r["ok"], true, "ui.set: {r}"); + rest(h); +} + +fn rest(h: &mut Headless) { + h.settle(T); + for _ in 0..3 { + h.step(); + } +} + +/// Where the text that is exactly `said` was drawn. +fn drawn(h: &Headless, said: &str) -> egui::Rect { + h.view + .painted_shapes() + .iter() + .find_map(|shape| match shape { + egui::Shape::Text(text) if text.galley.job.text == said => Some(text.visual_bounding_rect()), + _ => None, + }) + .unwrap_or_else(|| { + panic!( + "{said:?} is not drawn; drawn: {:?}", + h.painted_text().iter().filter(|t| t.chars().any(|c| c.is_ascii_digit())).collect::>() + ) + }) +} + +#[test] +fn a_photos_exposure_reads_the_same_wherever_it_is_shown() { + // Given a photo of the demo library and what it was taken with + let mut h = demo(); + run(&mut h, "library.select", json!({"ids": [1]})); + let meta = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(1)).map(|p| p.meta.clone()).expect("photo 1"); + let parts = crate::readout::exposure(&meta); + let line = parts.join(" · "); + assert_eq!(parts.len(), 4, "the demo photo has all four: {line}"); + assert!(line.contains(" sec · f/") && line.contains(" · ISO ") && line.ends_with(" mm"), "{line}"); + let said = |h: &Headless, what: &str| h.painted_text().iter().any(|t| t == what); + // When it is shown in the Info panel, each part is on its row as the line has it + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200})); + for part in parts.iter().filter(|part| !part.starts_with("ISO")) { + assert!(said(&h, part), "Info says {part:?}: {:?}", h.painted_text()); + } + // And over a square cell of the grid, the line + run(&mut h, "view.squareGrid", json!({})); + run(&mut h, "view.gridInfo", json!({"info": "exposure"})); + set(&mut h, json!({"thumbSize": 320})); + let lines: Vec = h.app.session.catalog.photos().filter_map(|p| crate::readout::exposure_line(&p.meta)).collect(); + let over_cells: Vec = h.painted_text().into_iter().filter(|t| t.contains(" · ISO ")).collect(); + assert!(over_cells.len() >= 3, "cells say what their photos were taken with: {over_cells:?}"); + for over in &over_cells { + assert!(lines.contains(over), "the grid says {over:?}, which is no photo's line"); + } + run(&mut h, "view.squareGrid", json!({})); + // And under the histogram of the Edit panel, the line + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light"]})); + assert!(said(&h, &line), "the histogram says {line:?}"); + // And in the overlay on the photo, the line + run(&mut h, "view.infoOverlay", json!({})); + if !said(&h, &line) { + run(&mut h, "view.infoOverlay", json!({})); + } + assert!(said(&h, &line), "the overlay says {line:?}"); + // Then nowhere on these screens is an aperture spaced out or a focal length run together + for text in h.painted_text() { + assert!(!text.contains("f / "), "{text:?}"); + assert!(!text.as_bytes().windows(3).any(|w| w[0].is_ascii_digit() && &w[1..] == b"mm"), "{text:?}"); + } +} + +#[test] +fn a_negative_value_has_a_minus_and_is_typed_with_either_sign() { + // Given a photo being edited + let mut h = demo(); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light"]})); + // When its exposure is taken down + run(&mut h, "develop.set", json!({"values": {"light.exposure": -1.25}})); + // Then the value is written with a minus, not a hyphen + let texts = h.painted_text(); + assert!(texts.iter().any(|t| t == "−1.25"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "-1.25")); + // And what is typed into the value is read with the minus it was shown with, or a hyphen + let exposure = lightcraft_develop::controls::find("light.exposure").expect("the exposure control"); + assert_eq!(crate::widgets::typed_value(exposure, "−1.25"), Some(-1.25)); + assert_eq!(crate::widgets::typed_value(exposure, "-1.25"), Some(-1.25)); + assert_eq!(crate::widgets::typed_value(exposure, "−"), None); +} + +/// Scenario: a value is typed with the digits an Arabic or Persian keyboard gives. +#[test] +fn a_value_is_typed_in_arabic_or_persian_digits() { + // Given the exposure, contrast and temperature controls + let exposure = lightcraft_develop::controls::find("light.exposure").expect("the exposure control"); + let contrast = lightcraft_develop::controls::find("light.contrast").expect("the contrast control"); + let temp = lightcraft_develop::controls::find("wb.temp").expect("the temperature control"); + // When a value is typed in Arabic-Indic digits, with the Arabic decimal sign or a point + // Then it is the number those digits write + assert_eq!(crate::widgets::typed_value(exposure, "١٫٢٥"), Some(1.25)); + assert_eq!(crate::widgets::typed_value(exposure, "١.٢٥"), Some(1.25)); + assert_eq!(crate::widgets::typed_value(exposure, "-٠٫٥"), Some(-0.5)); + assert_eq!(crate::widgets::typed_value(exposure, "−٠٫٥"), Some(-0.5), "with the minus a value is shown with"); + // And with the Arabic percent sign, or a unit, after it + assert_eq!(crate::widgets::typed_value(contrast, "٢٠٪"), Some(20.0)); + assert_eq!(crate::widgets::typed_value(temp, "٥٦٠٠ K"), Some(5600.0)); + // And in the Persian forms of the digits, or the two kinds together + assert_eq!(crate::widgets::typed_value(exposure, "۱٫۲۵"), Some(1.25)); + assert_eq!(crate::widgets::typed_value(contrast, "۲0"), Some(20.0)); + // And with the direction marks a keyboard or a paste can put around a number + assert_eq!(crate::widgets::typed_value(contrast, "\u{200f}٢٠\u{200e}"), Some(20.0)); + assert_eq!(crate::widgets::typed_value(contrast, "\u{61c}-٢٠"), Some(-20.0)); + // (a number pasted from an app that wraps it in an isolate or an embedding) + assert_eq!(crate::widgets::typed_value(contrast, "\u{2068}٢٠\u{2069}"), Some(20.0)); + assert_eq!(crate::widgets::typed_value(contrast, "\u{202a}20\u{202c}"), Some(20.0)); + // And with the Arabic comma for the decimal sign, as a comma is one + assert_eq!(crate::widgets::typed_value(exposure, "١،٥"), Some(1.5)); + // And an angle with its degree sign, whatever follows the sign + assert_eq!(crate::widgets::typed_value(contrast, "٥°\u{200e}"), Some(5.0)); + assert_eq!(crate::widgets::typed_value(contrast, "5 °"), Some(5.0)); + // But what is not a number stays one: the slider keeps its value + for bad in ["٫", "١٫٢٫٣", "٪", "١٬٢٠٠", "٢٠ك"] { + assert_eq!(crate::widgets::typed_value(contrast, bad), None, "{bad:?}"); + } +} + +#[test] +fn the_values_of_sliders_stand_in_one_column() { + // Given a photo being edited + let mut h = demo(); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light"]})); + // When two sliders hold numbers of as many figures, narrow ones and wide ones + run(&mut h, "develop.set", json!({"values": {"light.contrast": 11, "light.highlights": 44}})); + // Then the two values begin at the same place, and end within half the room a 1 leaves in + // its cell (as the font draws them, "+11" is six points narrower than "+44") + let (narrow, wide) = (drawn(&h, "+11"), drawn(&h, "+44")); + assert!((narrow.left() - wide.left()).abs() < 1.0, "{narrow:?} {wide:?}"); + assert!((narrow.right() - wide.right()).abs() < 2.5, "{narrow:?} {wide:?}"); +} + +#[test] +fn the_counts_of_the_sidebar_are_set_in_figures_of_one_width() { + // Given the library with its sidebar and the counts beside its rows + let mut h = demo(); + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200})); + let left = h.app.widgets.iter().find(|(w, _)| w == "thumb:1").map_or(480.0, |(_, r)| r.left()); + // When the count of all photos is drawn (two figures) + let all = h.app.session.catalog.photos().count().to_string(); + let counts: Vec = h + .view + .painted_shapes() + .into_iter() + .filter_map(|shape| match shape { + egui::Shape::Text(text) if text.galley.job.text == all && text.pos.x < left => Some(text), + _ => None, + }) + .collect(); + // Then on the row of All Photos a figure narrower than the widest is given the room it + // lacks before it (the font's own "2" is narrower than its "4"; rows drawn by other code, + // such as By Date, are not this change's) + let room = |count: &egui::epaint::TextShape| count.galley.job.sections.first().map_or(0.0, |s| s.leading_space); + assert!(all.starts_with('2'), "the demo has twenty-odd photos ({all})"); + assert!(counts.iter().any(|count| room(count) > 0.1), "no count of {all} in the sidebar is set in cells ({} counts)", counts.len()); +} + +#[test] +fn a_value_opens_for_typing_with_a_hyphen_a_keyboard_has() { + // Given a negative and a positive value as a slider shows them + let exposure = lightcraft_develop::controls::find("light.exposure").expect("the exposure control"); + assert_eq!(crate::widgets::shown_value(exposure, -1.25), "−1.25"); + // When the value is opened to be typed over + // Then the draft has the keyboard's hyphen (what is copied from it pastes anywhere) and no plus + assert_eq!(crate::widgets::draft_value(exposure, -1.25), "-1.25"); + assert_eq!(crate::widgets::draft_value(exposure, 0.5), "0.50"); + assert_eq!(crate::widgets::typed_value(exposure, &crate::widgets::draft_value(exposure, -1.25)), Some(-1.25)); +} diff --git a/crates/ui-egui/src/tests_type_scale.rs b/crates/ui-egui/src/tests_type_scale.rs new file mode 100644 index 00000000000..890a87b9996 --- /dev/null +++ b/crates/ui-egui/src/tests_type_scale.rs @@ -0,0 +1,193 @@ +//! Text is set in seven sizes, one per job (`theme::TextSize`), so that two sizes on a screen are +//! always told apart and the same job is the same size on every panel. +//! +//! Before: 17 sizes from 8.5 to 20 pt, 102 of 237 uses on half points. A slider's name (12.5) stood +//! by a checkbox's (13), a caption was 11 in Settings and 11.5 in Info, and panel titles came in +//! 13.5, 14, 15 and 17. + +use std::collections::BTreeMap; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::panels::settings::TABS; +use crate::theme::{TextSize, ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo() -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.settle(T); + h.step(); + h.step(); +} + +fn set(h: &mut Headless, what: Value) { + let r = h.request("ui.set", what, T); + assert_eq!(r["ok"], true, "ui.set: {r}"); + h.settle(T); + h.step(); + h.step(); +} + +/// The sizes of the text the last frame drew that are not on the scale, each with a piece of +/// text drawn in it (hundredths of a point, so that they sort). +fn off_scale(h: &Headless) -> BTreeMap { + let mut out = BTreeMap::new(); + for shape in h.view.painted_shapes() { + let egui::Shape::Text(text) = shape else { continue }; + for section in &text.galley.job.sections { + let size = section.format.font_id.size; + if !TextSize::ALL.iter().any(|role| (role.points() - size).abs() < 0.01) { + out.entry((size * 100.0).round() as u32).or_insert_with(|| text.galley.job.text.chars().take(40).collect()); + } + } + } + out +} + +fn assert_on_scale(h: &Headless, screen: &str) { + let off = off_scale(h); + assert!(off.is_empty(), "{screen}: text drawn off the scale (size × 100, a sample): {off:?}"); +} + +#[test] +fn the_library_draws_its_text_on_the_scale() { + // Given the demo library in the grid, with the sidebar and each right panel in turn + let mut h = demo(); + run(&mut h, "view.photoGrid", json!({})); + run(&mut h, "library.select", json!({"ids": [1]})); + for right in ["info", "keywords", "edit", "versions", "activity"] { + // When the panel is shown + set(&mut h, json!({"leftPanel": true, "right": right, "thumbSize": 200})); + // Then every piece of text on screen is one of the seven sizes + assert_on_scale(&h, &format!("grid with {right}")); + } +} + +#[test] +fn a_photo_being_edited_draws_its_text_on_the_scale() { + // Given a photo opened by itself with the Edit panel's sections open and the filmstrip under it + let mut h = demo(); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + for right in ["edit", "info", "masking", "crop", "remove", "profiles"] { + // When each tool panel is shown + set(&mut h, json!({"leftPanel": false, "right": right, "openSections": ["light", "color", "effects", "detail"]})); + // Then every piece of text on screen is one of the seven sizes + assert_on_scale(&h, &format!("detail with {right}")); + } +} + +#[test] +fn settings_and_the_dialogs_draw_their_text_on_the_scale() { + let mut h = demo(); + // Given each tab of Settings + for (tab, _) in TABS { + // When it is shown + run(&mut h, "app.settings", json!({"tab": tab})); + // Then its title, tabs, headings, rows and explanations are on the scale + assert_on_scale(&h, &format!("Settings ▸ {tab}")); + } + h.request("ui.dialog.cancel", json!({}), T); + // And given the dialogs a person meets most + for command in ["dialog.export", "app.shortcuts", "app.about"] { + // When one is open + run(&mut h, command, json!({})); + // Then so is everything in it + assert_on_scale(&h, command); + h.request("ui.dialog.cancel", json!({}), T); + h.step(); + } +} + +#[test] +fn the_text_styles_of_the_interface_are_sizes_of_the_scale() { + // Given the theme applied + let h = demo(); + // When a label, a button, small text and a window title take their style's font + let style = h.view.ctx.global_style(); + let size = |s: egui::TextStyle| style.text_styles.get(&s).map(|f| f.size); + // Then each is a named size, and a window's title is the size of a panel's + assert_eq!(size(egui::TextStyle::Body), Some(TextSize::Body.points())); + assert_eq!(size(egui::TextStyle::Button), Some(TextSize::Body.points())); + assert_eq!(size(egui::TextStyle::Small), Some(TextSize::Caption.points())); + assert_eq!(size(egui::TextStyle::Heading), Some(TextSize::PanelTitle.points())); +} + +#[test] +fn a_size_asked_for_by_number_is_given_on_the_scale() { + let t = Tokens::for_kind(ThemeKind::Charcoal); + let on_scale = |points: f32| TextSize::ALL.iter().any(|size| size.points() == points); + // Given any number of points, also none at all + for asked in (0..=120).map(|quarter| quarter as f32 * 0.25).chain([f32::NAN, f32::INFINITY, -4.0]) { + // When either face is asked for at it + let (regular, strong) = (t.font(asked), t.semibold(asked)); + // Then the font is one of the seven sizes + assert!(on_scale(regular.size) && on_scale(strong.size), "{asked} gave {} and {}", regular.size, strong.size); + } + // And a size between two goes to the one nearer a control's, one below the smallest to the smallest + for (asked, given) in [(8.5, 10.0), (10.5, 11.0), (11.5, 12.0), (12.5, 13.0), (13.5, 13.0), (16.0, 15.0), (17.0, 18.0), (20.0, 18.0)] { + assert_eq!(TextSize::nearest(asked).points(), given, "{asked}"); + } + // And what is past either end is the end, however far + for (asked, given) in [(1e9, 18.0), (f32::MAX, 18.0), (f32::INFINITY, 18.0), (-1e9, 10.0), (f32::NEG_INFINITY, 10.0), (0.0, 10.0)] { + assert_eq!(TextSize::nearest(asked).points(), given, "{asked}"); + } + assert_eq!(TextSize::nearest(f32::NAN), TextSize::Body); + // And a size of the scale is itself + for size in TextSize::ALL { + assert_eq!(TextSize::nearest(size.points()), size); + } +} + +#[test] +fn the_sizes_of_the_scale_are_a_point_or_more_apart() { + for pair in TextSize::ALL.windows(2) { + assert!(pair[1].points() - pair[0].points() >= 1.0, "{pair:?}"); + } +} + +#[test] +fn the_line_over_a_square_cell_ends_before_the_format() { + // Given the square grid with small cells, and each thing a cell can say over its photo + // (one language: the language is the whole process's, and other tests read English) + for language in ["English"] { + let mut h = demo(); + run(&mut h, "view.photoGrid", json!({})); + run(&mut h, "view.squareGrid", json!({})); + for info in ["exposure", "date", "filename"] { + run(&mut h, "view.gridInfo", json!({"info": info})); + set(&mut h, json!({"thumbSize": 110})); + // When the cells are drawn + let texts: Vec<(String, egui::Rect)> = h + .view + .painted_shapes() + .iter() + .filter_map(|shape| match shape { + egui::Shape::Text(text) => Some((text.galley.job.text.clone(), text.visual_bounding_rect())), + _ => None, + }) + .collect(); + let formats: Vec<&(String, egui::Rect)> = texts.iter().filter(|(said, _)| said == "JPEG").collect(); + assert!(formats.len() >= 4, "{language} {info}: cells with their format are on screen ({})", formats.len()); + // Then no line runs under a format: it is cut short before it + for (_, format) in formats { + let room = format.expand2(egui::vec2(3.0, 0.0)); + let under: Vec<&String> = texts.iter().filter(|(said, at)| said != "JPEG" && at.intersects(room)).map(|(said, _)| said).collect(); + assert!(under.is_empty(), "{language} {info}: {under:?} runs under the format at {format:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 282f9c70ef2..e2867de124b 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -10,6 +10,64 @@ use std::sync::Arc; use egui::{Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Stroke, Visuals}; pub const FONT_SEMIBOLD: &str = "semibold"; + +/// The sizes text is set in, one per job. Two sizes on a screen are always told apart (the steps +/// are a point or more), and the same job is the same size on every panel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextSize { + /// A badge or a pill on a thumbnail or an icon. + Micro, + /// An explanation, the caption over a field, a line of status; in semibold, a chip or a + /// choice. + Caption, + /// What stands by something larger: a count, the title of a tab, a control of the filter bar. + Label, + /// Controls, rows, values and menus. + Body, + /// The header of a section in a panel. + Title, + /// The name of a panel or of a window. + PanelTitle, + /// The title over the photos, and what an empty screen says. + Display, +} + +impl TextSize { + /// Smallest first. + pub const ALL: [TextSize; 7] = + [TextSize::Micro, TextSize::Caption, TextSize::Label, TextSize::Body, TextSize::Title, TextSize::PanelTitle, TextSize::Display]; + + /// The size in points. + pub const fn points(self) -> f32 { + match self { + TextSize::Micro => 10.0, + TextSize::Caption => 11.0, + TextSize::Label => 12.0, + TextSize::Body => 13.0, + TextSize::Title => 14.0, + TextSize::PanelTitle => 15.0, + TextSize::Display => 18.0, + } + } + + /// The size nearest a number of points; of two equally near, the one nearer [`TextSize::Body`] + /// (12.5 is 13 and so is 13.5). Anything past the ends is the end: a huge number or infinity + /// the largest, a negative one the smallest. Not a number: the size of a control. + pub fn nearest(points: f32) -> TextSize { + // (far from the scale every size is as near as the next in an f32) + let points = points.clamp(0.0, 1000.0); + let body = TextSize::Body.points(); + let mut best = TextSize::Body; + let mut least = f32::INFINITY; + for size in TextSize::ALL { + let off = (size.points() - points).abs(); + if off < least || (off == least && (size.points() - body).abs() < (best.points() - body).abs()) { + (best, least) = (size, off); + } + } + best + } +} const WEB_CHINESE_FONT: &str = "web Noto Sans CJK SC"; /// Shared colour-label palette for badges, thumbnail surrounds and feedback. @@ -164,7 +222,7 @@ impl Tokens { pub fn for_kind(kind: ThemeKind) -> Tokens { let rgb = |v: u32| Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8); let base = Tokens::default(); - match kind { + let t = match kind { ThemeKind::Charcoal => base, ThemeKind::Midnight => Tokens { chrome: rgb(0x1e1e1e), @@ -243,17 +301,170 @@ impl Tokens { caution: rgb(0xb0761a), ..base }, + }; + // The dim text of captions, counts and explanations is read like any other: it stands + // 4.5:1 against every surface it is written on (as observed it was 4.20:1 on a panel in + // Charcoal, and 3.3 to 4.3:1 on the light themes' surfaces). + Tokens { text_dim: t.on_surfaces(t.text_dim), ..t } + } + + /// The surfaces text is written on at rest: panels, the canvas, the grid and its cells, + /// insets, text boxes and buttons. (A hovered, pressed or selected surface is passing or + /// marked otherwise: text there is made legible against it where it is drawn.) + fn surfaces(&self) -> [Color32; 7] { + [self.chrome, self.canvas, self.grid_bg, self.cell, self.inset, self.field, self.button] + } + + /// `color`, brought as far toward the text colour as it takes to stand 4.5:1 against every + /// surface of [`Self::surfaces`]: a colour that says something as text. + fn on_surfaces(&self, color: Color32) -> Color32 { + self.surfaces().into_iter().fold(color, |c, on| self.legible(c, on, 4.5)) + } + + /// What is written or marked over a picture: a picture has no theme, so this is the same + /// light ink in every theme, on [`Self::photo_shade`]. + pub const fn on_photo() -> Color32 { + Color32::from_rgb(0xf2, 0xf2, 0xf2) + } + + /// The flag of a rejected photo over a picture: a red light enough to stand 3:1 on the shade + /// whatever is under it (a theme's own red is made for its panels: 2.3 to 3:1 here). + pub const fn on_photo_reject() -> Color32 { + Color32::from_rgb(0xff, 0x6b, 0x6b) + } + + /// The shade under what is written or marked over a picture. + /// (Black at 200 of 255: over white it is a grey the ink stands 12:1 against, and + /// [`Self::on_photo_reject`] 4:1.) + pub fn photo_shade() -> Color32 { + Color32::from_black_alpha(200) + } + + /// The accent as text: a link, "in use", what Auto Sync is doing. (The accent itself is + /// for fills and outlines: as text it is 2.56:1 on a panel in Charcoal.) + pub fn text_link(&self) -> Color32 { + self.on_surfaces(self.accent) + } + + /// The caution colour as text. (3.09:1 on a panel in Silver as it is.) + pub fn text_caution(&self) -> Color32 { + self.on_surfaces(self.caution) + } + + /// The colour of a rejection or an error as text. + pub fn text_error(&self) -> Color32 { + self.on_surfaces(self.reject) + } + + /// What is written on a filled mark (a count on the accent, "!" on the error colour): black + /// or white, whichever stands out more. + pub fn ink_on(&self, fill: Color32) -> Color32 { + let white = self.legible(Color32::WHITE, fill, 4.5) == Color32::WHITE; + let black = self.legible(Color32::BLACK, fill, 4.5) == Color32::BLACK; + match (white, black) { + (true, false) => Color32::WHITE, + (false, true) => Color32::BLACK, + // both stand 4.5:1 or neither does: the farther from the fill + _ if Self::lightness(fill) < 0.18 => Color32::WHITE, + _ => Color32::BLACK, } } + /// Relative luminance (WCAG), 0 black to 1 white. + fn lightness(c: Color32) -> f32 { + let linear = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * linear(c.r()) + 0.7152 * linear(c.g()) + 0.0722 * linear(c.b()) + } + + /// The fill behind what is chosen (a chosen chip, selected text): the accent mixed into the + /// panel as strongly as leaves the label colour 4.5:1 on it. + pub fn selection_fill(&self) -> Color32 { + const STEPS: u8 = 12; + (0..=STEPS) + .rev() + .map(|step| self.chrome.lerp_to_gamma(self.accent, 0.6 * f32::from(step) / f32::from(STEPS))) + .find(|fill| self.legible(self.text_label, *fill, 4.5) == self.text_label) + .unwrap_or(self.chrome) + } + pub fn get(ctx: &egui::Context) -> Tokens { ctx.data(|d| d.get_temp::(egui::Id::NULL)).unwrap_or_default() } + /// The regular face at a size of the scale. + pub fn regular(&self, size: TextSize) -> FontId { + FontId::proportional(size.points()) + } + /// The semibold face at a size of the scale. + pub fn strong(&self, size: TextSize) -> FontId { + FontId::new(size.points(), FontFamily::Name(FONT_SEMIBOLD.into())) + } + /// The regular face at the size of the scale nearest `size` ([`TextSize::nearest`]): text + /// asked for by a number is on the scale too. New code names the size (`t.body()`, …). pub fn font(&self, size: f32) -> FontId { - FontId::proportional(size) + self.regular(TextSize::nearest(size)) } + /// The semibold face at the size of the scale nearest `size`. pub fn semibold(&self, size: f32) -> FontId { - FontId::new(size, FontFamily::Name(FONT_SEMIBOLD.into())) + self.strong(TextSize::nearest(size)) + } + /// Micro: a badge or a pill on a thumbnail or an icon. + pub fn micro(&self) -> FontId { + self.regular(TextSize::Micro) + } + /// [`Self::micro`] in semibold. + pub fn micro_strong(&self) -> FontId { + self.strong(TextSize::Micro) + } + /// Caption: an explanation, the caption over a field, a line of status; in semibold, a chip. + pub fn caption(&self) -> FontId { + self.regular(TextSize::Caption) + } + /// [`Self::caption`] in semibold. + pub fn caption_strong(&self) -> FontId { + self.strong(TextSize::Caption) + } + /// Label: what stands by something larger: a count, the title of a tab. + pub fn label(&self) -> FontId { + self.regular(TextSize::Label) + } + /// [`Self::label`] in semibold. + pub fn label_strong(&self) -> FontId { + self.strong(TextSize::Label) + } + /// Body: controls, rows, values and menus. + pub fn body(&self) -> FontId { + self.regular(TextSize::Body) + } + /// [`Self::body`] in semibold. + pub fn body_strong(&self) -> FontId { + self.strong(TextSize::Body) + } + /// Title: the header of a section in a panel (set strong; plain is for a value at its size). + pub fn title(&self) -> FontId { + self.regular(TextSize::Title) + } + /// [`Self::title`] in semibold. + pub fn title_strong(&self) -> FontId { + self.strong(TextSize::Title) + } + /// PanelTitle: the name of a panel or of a window (set strong). + pub fn panel_title(&self) -> FontId { + self.regular(TextSize::PanelTitle) + } + /// [`Self::panel_title`] in semibold. + pub fn panel_title_strong(&self) -> FontId { + self.strong(TextSize::PanelTitle) + } + /// Display: the title over the photos, and what an empty screen says (set strong). + pub fn display(&self) -> FontId { + self.regular(TextSize::Display) + } + /// [`Self::display`] in semibold. + pub fn display_strong(&self) -> FontId { + self.strong(TextSize::Display) } } @@ -378,6 +589,32 @@ fn theme_id() -> egui::Id { egui::Id::new("lightcraft-theme") } +impl Tokens { + /// `color` as it is where it stands `ratio`:1 or more against `on`, as WCAG measures it (4.5 + /// for text, 3 for a line or a mark that says where something is); else moved toward the text + /// colour, which stands furthest from every surface, in small steps until it does, and the + /// text colour itself when nothing on the way does (or `ratio` is no number). + /// + /// For text and marks drawn in a token chosen for its hue or its quietness (the dim text, the + /// accent, the caution and reject colours, a border) on a surface where a theme's value for it + /// is too close to read: the token keeps its value for everything else that uses it. + pub fn legible(&self, color: Color32, on: Color32, ratio: f32) -> Color32 { + fn luminance(c: Color32) -> f32 { + let linear = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * linear(c.r()) + 0.7152 * linear(c.g()) + 0.0722 * linear(c.b()) + } + let stands = |c: Color32| { + let (a, b) = (luminance(c), luminance(on)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) >= ratio + }; + const STEPS: u8 = 32; + (0..STEPS).map(|step| color.lerp_to_gamma(self.text, f32::from(step) / f32::from(STEPS))).find(|c| stands(*c)).unwrap_or(self.text) + } +} + /// The theme `ctx` is styled with (none before the first [`apply_kind`]). pub fn current(ctx: &egui::Context) -> Option { ctx.data(|d| d.get_temp::(theme_id())) @@ -415,9 +652,12 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { v.window_stroke = Stroke::new(1.0, t.button_border); v.window_corner_radius = CornerRadius::same(6); v.menu_corner_radius = CornerRadius::same(6); - v.selection.bg_fill = t.accent.gamma_multiply(0.6); + v.selection.bg_fill = t.selection_fill(); v.selection.stroke = Stroke::new(1.0, t.accent); v.override_text_color = Some(t.text_label); + // (egui's own: the label colour at 60 %, under 4.1:1 in every theme, and a bright blue) + v.weak_text_color = Some(t.text_dim); + v.hyperlink_color = t.text_link(); let (popup, window) = if dark { (140, 160) } else { (50, 60) }; v.popup_shadow = egui::epaint::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(popup) }; v.window_shadow = egui::epaint::Shadow { offset: [0, 8], blur: 30, spread: 0, color: Color32::from_black_alpha(window) }; @@ -436,10 +676,10 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { s.spacing.item_spacing = egui::vec2(6.0, 4.0); s.spacing.button_padding = egui::vec2(8.0, 3.0); s.spacing.interact_size.y = 22.0; - s.text_styles.insert(egui::TextStyle::Body, FontId::proportional(13.0)); - s.text_styles.insert(egui::TextStyle::Button, FontId::proportional(13.0)); - s.text_styles.insert(egui::TextStyle::Small, FontId::proportional(11.0)); - s.text_styles.insert(egui::TextStyle::Heading, FontId::new(16.0, FontFamily::Name(FONT_SEMIBOLD.into()))); + s.text_styles.insert(egui::TextStyle::Body, t.body()); + s.text_styles.insert(egui::TextStyle::Button, t.body()); + s.text_styles.insert(egui::TextStyle::Small, t.caption()); + s.text_styles.insert(egui::TextStyle::Heading, t.panel_title_strong()); s.animation_time = 0.08; }); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index a6af3dc7a87..b54711059f3 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -71,10 +71,10 @@ pub fn preview_only_notice(ui: &mut Ui, key: &str, reason: &str) { ui.horizontal(|ui| { let (ir, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover()); paint(ui.painter(), ir, Icon::Info, t.caution); - ui.label(egui::RichText::new(crate::i18n::tr("Preview only")).font(t.semibold(12.5)).color(t.text)); + ui.label(egui::RichText::new(crate::i18n::tr("Preview only")).font(t.body_strong()).color(t.text)); }); ui.add_space(2.0); - ui.label(egui::RichText::new(preview_only_explanation(reason)).size(11.5).color(t.text_label)); + ui.label(egui::RichText::new(preview_only_explanation(reason)).font(t.caption()).color(t.text_label)); }) .response; let r = r.on_hover_text(crate::i18n::tr_format!("Decoder: {reason}", reason = reason)); @@ -160,11 +160,29 @@ pub struct SliderOut { } /// What a value typed into a slider asks for (issue #322): a number such as `0.5`, `+12`, `-1,5` -/// (comma or point) or `5600 K`, on the control's steps and clamped to its range. `None` when it -/// isn't a finite number, so the slider keeps its value. +/// (comma or point), `5600 K` or `5°`, on the control's steps and clamped to its range. The digits may +/// be the Arabic-Indic or Persian ones (`١٫٥`, `۲۰٪`), as an Arabic or Persian keyboard gives +/// them. `None` when it isn't a finite number, so the slider keeps its value. pub fn typed_value(spec: &ControlSpec, text: &str) -> Option { - let t = text.trim().replace(',', "."); - let t = t.trim_end_matches(|c: char| c == '%' || c == 'K' || c == 'k' || c.is_whitespace()); + let t: String = text + .chars() + // (the marks a keyboard or a paste puts around a number to say which way it reads: the + // direction marks, and the embeddings and isolates an app wraps a number in) + .filter(|c| !matches!(c, '\u{200e}' | '\u{200f}' | '\u{61c}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')) + .map(|c| match c { + // (Arabic-Indic digits, and their Persian forms) + '\u{660}'..='\u{669}' => char::from_digit(c as u32 - 0x660, 10).unwrap_or(c), + '\u{6f0}'..='\u{6f9}' => char::from_digit(c as u32 - 0x6f0, 10).unwrap_or(c), + // (a decimal comma, the Arabic comma, or the Arabic decimal sign) + ',' | '\u{60c}' | '\u{66b}' => '.', + '\u{66a}' => '%', + // (a minus as the value is shown with, or the hyphen of a keyboard) + crate::readout::MINUS => '-', + c => c, + }) + .collect(); + let t = t.trim(); + let t = t.trim_end_matches(|c: char| c == '%' || c == '°' || c == 'K' || c == 'k' || c.is_whitespace()); let v: f64 = t.parse().ok().filter(|v: &f64| v.is_finite())?; let step = spec.step.max(1e-9); Some(((v / step).round() * step).clamp(spec.min, spec.max)) @@ -173,7 +191,13 @@ pub fn typed_value(spec: &ControlSpec, text: &str) -> Option { /// A slider's value as shown next to its label. pub(crate) fn shown_value(spec: &ControlSpec, v: f64) -> String { let shown = if spec.id == "wb.temp" { format!("{v:.0}") } else { spec.format(v).replace("+0.00", "0").replace("-0.00", "0") }; - if shown == "+0" || shown == "-0" { "0".to_string() } else { shown } + if shown == "+0" || shown == "-0" { "0".to_string() } else { crate::readout::signed(&shown) } +} + +/// A slider's value as the text its field opens with: no plus, and the hyphen of a keyboard +/// for the minus it is shown with, so that what is copied from the field pastes anywhere. +pub(crate) fn draft_value(spec: &ControlSpec, v: f64) -> String { + shown_value(spec, v).trim_start_matches('+').replace(crate::readout::MINUS, "-") } /// A Lightroom slider row (label + value above a track with a hollow ring thumb). @@ -228,7 +252,7 @@ pub fn slider(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label_ let value_pressed = value_resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.button_pressed(egui::PointerButton::Primary)); // Focus on the owned primary press before fast typing; retain the readout's click activation. if enabled && typing.is_none() && (value_resp.clicked() || value_pressed) { - typing = Some((shown_value(spec, value).trim_start_matches('+').to_string(), 0, value_pressed)); + typing = Some((draft_value(spec, value), 0, value_pressed)); } let value_released = ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)); // The opening press must complete the readout's original click before the edit continues. @@ -255,7 +279,7 @@ pub fn slider(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label_ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(value_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); // the old value is selected when the field takes the focus, so typing replaces it let field = crate::text_field::TextField::singleline(&format!("sliderField:{}", spec.id), &mut text) - .font(t.font(12.5)) + .font(t.body()) .horizontal_align(egui::Align::RIGHT) .width(value_rect.width()) .margin(egui::Margin::ZERO) @@ -384,9 +408,10 @@ pub fn slider(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label_ let hovered = resp.hovered() || resp.dragged(); let text_c = if enabled { t.text_label } else { t.text_disabled }; let p = ui.painter(); - p.text(label_rect.left_center(), Align2::LEFT_CENTER, crate::i18n::tr(label_override.unwrap_or(spec.label)), t.font(12.5), text_c); + p.text(label_rect.left_center(), Align2::LEFT_CENTER, crate::i18n::tr(label_override.unwrap_or(spec.label)), t.body(), text_c); if typing.is_none() { - p.text(label_rect.right_center(), Align2::RIGHT_CENTER, shown_value(spec, v), t.font(12.5), text_c); + // (in a column of figures: the value keeps its place while it changes) + crate::readout::value(p, label_rect.right_center(), &shown_value(spec, v), t.body(), text_c); if enabled && value_resp.hovered() { ui.ctx().set_cursor_icon(egui::CursorIcon::Text); } @@ -499,14 +524,124 @@ pub fn flyout_row(ui: &mut Ui, id: &str, title: &str, icon: Icon, open: bool) -> } /// A small bordered text button (Auto, B&W, HDR…). +/// How wide a [`text_button`] with this label is: for a row that has to know whether one fits. +pub fn text_button_width(ui: &Ui, label: &str) -> f32 { + let t = Tokens::get(ui.ctx()); + (ui.painter().layout_no_wrap(crate::i18n::tr(label).to_string(), t.caption_strong(), t.text).size().x + 18.0).max(37.0) +} + pub fn text_button(ui: &mut Ui, id: &str, label: &str, active: bool) -> Response { + chip(ui, id, label, active, false, None) +} + +/// One of a row of choices of which exactly one holds (`button:{id}`), drawn as [`text_button`] +/// is, except that the one chosen is also outlined in the label colour: its fill alone stands +/// about 1.4:1 against the others, the outline 3:1 or more in every theme. A screen reader is +/// told it is a radio button. +pub fn choice_button(ui: &mut Ui, id: &str, label: &str, chosen: bool) -> Response { + chip(ui, id, label, chosen, true, None) +} + +/// A [`choice_button`] of a row that is one Tab stop ([`Roving`]). +pub fn choice_button_in(ui: &mut Ui, row: &mut Roving, id: &str, label: &str, chosen: bool) -> Response { + chip(ui, id, label, chosen, true, Some(row)) +} + +/// A row of buttons that is one stop for Tab, as a tab bar or a group of radio buttons is: Tab +/// comes to the one that holds (`chosen`, or the first) and leaves the row from wherever in it +/// the focus is, and the arrow keys move the focus inside it (→ ↓ to the next, ← ↑ to the one +/// before, Home and End to the ends) without choosing anything: Space or Return does that. The +/// buttons are told to it one by one as they are drawn ([`choice_button_in`], [`tab_button_in`]), +/// and it is [`Roving::end`]ed after the last. +pub struct Roving { + key: egui::Id, + /// The buttons of the row as they were drawn on the frame before, in order. + last: Vec, + now: Vec, + /// Which of them Tab stops at on this frame: the one with the focus, or the one that holds. + stop: usize, + /// The button an arrow key moved the focus to, given it when the row has been drawn. + to: Option, +} + +impl Roving { + /// The row named `name` (unique on screen), of which the button at `chosen` holds. + pub fn new(ui: &Ui, name: &str, chosen: Option) -> Self { + let key = egui::Id::new(("roving-row", name)); + let last: Vec = ui.data(|d| d.get_temp(key)).unwrap_or_default(); + let focused = ui.memory(|m| m.focused()); + let stop = focused.and_then(|focused| last.iter().position(|id| *id == focused)).or(chosen).unwrap_or(0); + // (a choice that is not among the buttons leaves the first as the stop) + let stop = if last.is_empty() || stop < last.len() { stop } else { 0 }; + Self { key, last, now: Vec::new(), stop, to: None } + } + + /// What the next button of the row senses: clicks, and the focus by Tab if it is the stop. + fn sense(&self) -> Sense { + if self.now.len() == self.stop { Sense::click() } else { Sense::CLICK } + } + + /// The next button of the row, drawn: the arrow keys move from it while it has the focus. + fn drawn(&mut self, ui: &Ui, resp: &Response) { + let place = self.now.len(); + self.now.push(resp.id); + if !resp.has_focus() { + return; + } + // (the arrow keys are this row's while the focus is in it: not egui's, which go to + // whatever is nearest in that direction) + let arrows = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }; + // (and on the frame the focus came here, when egui takes no filter yet and would look for + // what is nearest in the arrow's direction, starting from the button the focus was just + // given to: that search is called off) + ui.memory_mut(|m| { + m.set_focus_lock_filter(resp.id, arrows); + m.move_focus(egui::FocusDirection::None); + }); + let end = self.last.len().saturating_sub(1); + let to = ui.input(|i| { + // (an arrow held with a modifier is somebody else's) + if i.modifiers.any() { + None + } else if i.key_pressed(egui::Key::ArrowRight) || i.key_pressed(egui::Key::ArrowDown) { + Some(place.saturating_add(1).min(end)) + } else if i.key_pressed(egui::Key::ArrowLeft) || i.key_pressed(egui::Key::ArrowUp) { + Some(place.saturating_sub(1)) + } else if i.key_pressed(egui::Key::Home) { + Some(0) + } else if i.key_pressed(egui::Key::End) { + Some(end) + } else { + None + } + }); + // (given in `end`: a button drawn after this one on this frame does not take the focus + // by Tab yet, and egui takes the focus from one that does not) + self.to = to.filter(|to| *to != place).and_then(|to| self.last.get(to)).copied(); + } + + /// After the row's last button: what was drawn is remembered for the next frame. + pub fn end(self, ui: &Ui) { + if let Some(to) = self.to { + ui.memory_mut(|m| m.request_focus(to)); + ui.ctx().request_repaint(); + } + ui.data_mut(|d| d.insert_temp(self.key, self.now)); + } +} + +fn chip(ui: &mut Ui, id: &str, label: &str, active: bool, choice: bool, row: Option<&mut Roving>) -> Response { let label = if id.starts_with("labelSet-") { label } else { crate::i18n::tr(label) }; let t = Tokens::get(ui.ctx()); - let font = t.semibold(11.5); + let font = t.caption_strong(); let galley = ui.painter().layout_no_wrap(label.to_string(), font, t.text); let size = vec2((galley.size().x + 18.0).max(37.0), 24.0); - let (r, resp) = ui.allocate_exact_size(size, Sense::click()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, active, label)); + let (r, resp) = ui.allocate_exact_size(size, row.as_ref().map_or(Sense::click(), |row| row.sense())); + if let Some(row) = row { + row.drawn(ui, &resp); + } + let kind = if choice { egui::WidgetType::RadioButton } else { egui::WidgetType::Button }; + resp.widget_info(|| egui::WidgetInfo::selected(kind, true, active, label)); register(ui.ctx(), format!("button:{id}"), r); let fill = if active { t.pressed @@ -515,20 +650,96 @@ pub fn text_button(ui: &mut Ui, id: &str, label: &str, active: bool) -> Response } else { t.button }; + // (a choice's border says where it is, among its neighbours on the window: it stands 3:1 + // there in every theme, where a button's own border is 1.6 to 1.7:1) + let border = match (choice, active) { + (true, true) => t.text_label, + (true, false) => t.legible(t.button_border, t.chrome, 3.0), + (false, _) => t.button_border, + }; let p = ui.painter(); - p.rect(r, CornerRadius::same(4), fill, Stroke::new(1.0, t.button_border), StrokeKind::Inside); + p.rect(r, CornerRadius::same(4), fill, Stroke::new(1.0, border), StrokeKind::Inside); p.galley(r.center() - galley.size() / 2.0, galley, t.text); + focus_ring(ui, &t, &resp, r); + resp +} + +/// The ring a button drawn here shows while it has the keyboard focus (Tab, the arrow keys): 2 pt +/// in the text colour with a 1 pt line of the surface's colour inside it, both within its rect so +/// that a neighbour or the edge of a scrolled list never cuts them. The inner line sets the ring +/// off from the button's fill, and makes it a double line: a chosen [`choice_button`] has a +/// single thin one, so "has the focus" and "is chosen" are told apart by shape, not thickness. +pub(crate) fn focus_ring(ui: &Ui, t: &Tokens, resp: &Response, r: Rect) { + if resp.has_focus() { + let p = ui.painter(); + p.rect_stroke(r, CornerRadius::same(4), Stroke::new(2.0, t.text), StrokeKind::Inside); + p.rect_stroke(r.shrink(2.0), CornerRadius::same(2), Stroke::new(1.0, t.chrome), StrokeKind::Inside); + } +} + +/// How tall a [`tab_button`] is. +const TAB_HEIGHT: f32 = 28.0; + +/// A tab of a tab bar (`button:{id}`): its name on the surface it is on, with no border and no +/// fill, so that it does not read as one of the buttons a page holds. The open tab's name is in +/// the text colour over a 2 pt line of that colour along its bottom edge (the bar's own line, when +/// the caller draws one there); the others are in the label colour. The names are a size up from +/// the headings inside a page, which are in the same face. To a screen reader a tab is a button +/// that says whether it is the one chosen (egui has no tab role to give it). +pub fn tab_button(ui: &mut Ui, id: &str, label: &str, open: bool) -> Response { + tab(ui, id, label, open, None) +} + +/// A [`tab_button`] of a tab bar that is one Tab stop ([`Roving`]). +pub fn tab_button_in(ui: &mut Ui, bar: &mut Roving, id: &str, label: &str, open: bool) -> Response { + tab(ui, id, label, open, Some(bar)) +} + +fn tab(ui: &mut Ui, id: &str, label: &str, open: bool, bar: Option<&mut Roving>) -> Response { + let label = crate::i18n::tr(label); + let t = Tokens::get(ui.ctx()); + let color = if open { t.text } else { t.text_label }; + let galley = ui.painter().layout_no_wrap(label.to_string(), t.body_strong(), color); + let size = vec2((galley.size().x + 20.0).max(37.0), TAB_HEIGHT); + let (r, resp) = ui.allocate_exact_size(size, bar.as_ref().map_or(Sense::click(), |bar| bar.sense())); + if let Some(bar) = bar { + bar.drawn(ui, &resp); + } + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, open, label)); + register(ui.ctx(), format!("button:{id}"), r); + let p = ui.painter(); + // (on whole pixels, so the line under the open tab is crisp at a whole-number scale) + let r = egui::emath::GuiRounding::round_to_pixels(r, p.pixels_per_point()); + if resp.hovered() && !open { + p.rect_filled(r.shrink2(vec2(0.0, 3.0)), CornerRadius::same(4), t.hover); + } + let color = if resp.hovered() { t.text } else { color }; + p.galley_with_override_text_color(r.center() - galley.size() / 2.0, galley, color); + if open { + p.rect_filled(Rect::from_min_max(pos2(r.left(), r.bottom() - 2.0), r.max), CornerRadius::ZERO, t.text); + } + focus_ring(ui, &t, &resp, r); resp } +/// Room left and right of a segment's name. +const SEGMENT_PAD: f32 = 5.0; + /// A segmented control: `labels` share the available width equally, `per_row` per row. Each segment is /// addressable as `button:{id}-{key}` (keys parallel to labels). Returns the clicked index. pub fn segmented(ui: &mut Ui, id: &str, items: &[(&str, &str)], active: Option, per_row: usize) -> Option { let t = Tokens::get(ui.ctx()); - let per_row = per_row.max(1); let gap = 4.0; let w = ui.available_width(); - let seg_w = ((w - gap * (per_row as f32 - 1.0)) / per_row as f32).max(24.0); + let width_of = |per_row: usize| ((w - gap * (per_row as f32 - 1.0)) / per_row as f32).max(24.0); + // `per_row` to a row, or fewer where the longest name (a translation) would not fit its + // share of the width: "Mit Hilfslinien" ran out of a third of the panel + let widest = items + .iter() + .map(|(label, _)| ui.painter().layout_no_wrap(crate::i18n::tr(label).to_string(), t.caption_strong(), t.text).size().x) + .fold(0.0, f32::max); + let per_row = (1..=per_row.max(1)).rev().find(|n| width_of(*n) >= widest + 2.0 * SEGMENT_PAD).unwrap_or(1); + let seg_w = width_of(per_row); let mut clicked = None; for (row_i, row) in items.chunks(per_row).enumerate() { ui.horizontal(|ui| { @@ -547,7 +758,9 @@ pub fn segmented(ui: &mut Ui, id: &str, items: &[(&str, &str)], active: Option egui::Response { r } +/// `text` written over a picture, its top left corner at `at`: in the ink for pictures on a +/// shade of its own (`Tokens::on_photo`, `Tokens::photo_shade`), so that it reads on any photo +/// in any theme. Returns the shade's rectangle. +pub(crate) fn on_photo_label(painter: &egui::Painter, at: egui::Pos2, text: &str, font: egui::FontId) -> Rect { + let galley = painter.layout_no_wrap(text.to_string(), font, Tokens::on_photo()); + let shade = Rect::from_min_size(at, galley.size() + vec2(16.0, 8.0)); + painter.rect_filled(shade, 4.0, Tokens::photo_shade()); + painter.galley(shade.min + vec2(8.0, 4.0), galley, Tokens::on_photo()); + shade +} + /// `text` laid out on one line, cut short with … when it is wider than `max` (the galley's /// `elided` says whether it was): for text painted into a fixed box (a tile, a row before its /// buttons), which a plain `Painter::text` would draw past. diff --git a/docs/display-profiles.md b/docs/display-profiles.md index 67892a3cbba..ee715eaef4d 100644 --- a/docs/display-profiles.md +++ b/docs/display-profiles.md @@ -18,7 +18,7 @@ would correct twice; KWin keeps that profile in its own settings, not colord, so ## Using it -Settings ▸ Display ▸ **Choose Profile…** picks an `.icc` / `.icm` file (the dialog opens where the system keeps +Settings ▸ Monitor ▸ **Choose Profile…** picks an `.icc` / `.icm` file (the dialog opens where the system keeps them: `~/.local/share/icc` on Linux, ColorSync's folders on macOS, `…\spool\drivers\color` on Windows). **Use sRGB** (on macOS and Linux **Use Screen Profile**) goes back to no profile. The choice is an app setting (`ui.json`, `displayProfile`) and applies at once; a file that can't be used is reported there and previews stay sRGB. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 7bb187811c1..23d7d0665df 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -424,7 +424,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/panels/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; a damaged settings file is kept as `.corrupt-