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/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/lib.rs b/crates/ui-egui/src/lib.rs index 37fb86df31e..0ad57909afb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -63,6 +63,18 @@ 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_groups; +#[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; @@ -221,7 +233,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/denoise.rs b/crates/ui-egui/src/panels/denoise.rs index 75488f76b04..9caf1ebe14a 100644 --- a/crates/ui-egui/src/panels/denoise.rs +++ b/crates/ui-egui/src/panels/denoise.rs @@ -413,12 +413,12 @@ 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" { @@ -428,10 +428,12 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, })); 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.font(11.5)).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.font(11.5)).color(t.legible(t.caution, t.chrome, 4.5))); } None => {} } @@ -448,11 +450,13 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, 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.font(11.5)).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.font(11.5)).color(t.legible(t.caution, t.chrome, 4.5))).wrap()); } _ => {} } @@ -461,6 +465,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 +647,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.semibold(13.5)).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 +655,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 { @@ -679,13 +693,23 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info } 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 +726,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.font(11.5)).color(t.legible(t.text_dim, t.chrome, 4.5))); } diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index a79261fdc7f..913f0990bad 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -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, diff --git a/crates/ui-egui/src/panels/faces.rs b/crates/ui-egui/src/panels/faces.rs index 2b3fe0329af..7199b5f6b44 100644 --- a/crates/ui-egui/src/panels/faces.rs +++ b/crates/ui-egui/src/panels/faces.rs @@ -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.font(11.5)).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); @@ -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; diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index a0717ccfd6a..4f055831f32 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,24 +63,464 @@ 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)); + let mut filter = kept.filter(|k| k.pass.checked_add(1) == Some(pass)).unwrap_or_default(); + filter.pass = pass; + let had_text = !filter.text.is_empty(); + let typed = crate::text_field::TextField::singleline("field:settingsFilter", &mut filter.text) + .hint(crate::i18n::tr("Filter settings")) + .width(ui.available_width()) + .show(ui); + // 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(); + 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(ui, &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(); + } + } + }); + 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; + visuals.selection.stroke.color = t.legible(t.accent, t.chrome, 3.0); + 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"; + +/// 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, + sections: Option<(String, std::sync::Arc>)>, +} + +impl Filter { + /// The sections that have every word of `words` (lower case), in the order of the tabs. + fn found(&mut self, app: &mut LightcraftApp, words: &str, now: f64) -> Vec
{ + let of = format!("{}|{}", app.ui.language.code(), app.session.library.as_ref().map(|l| l.dir.display().to_string()).unwrap_or_default()); + let sections = match &self.sections { + Some((read_for, sections)) if *read_for == of => sections.clone(), + _ => { + let sections = std::sync::Arc::new(sections(app, now)); + self.sections = Some((of, sections.clone())); + sections + } + }; + sections.iter().filter(|section| section.has(words)).cloned().collect() + } +} + +impl Section { + /// Whether the section, with the name of its tab, has every word of `words` (lower case). + fn has(&self, words: &str) -> bool { + let label = TABS.iter().find(|(id, _)| *id == self.tab).map_or("", |(id, label)| crate::i18n::tr(tab_label(id, label))); + let all = format!("{label} {}", self.texts.join(" ")).to_lowercase(); + words.split_whitespace().all(|word| all.contains(word)) + } + + /// What the section is called in the list of what was found: its tab, then its heading. + fn title(&self) -> String { + let tab = TABS.iter().find(|(id, _)| *id == self.tab).map_or("", |(id, label)| crate::i18n::tr(tab_label(id, label))); + if self.name.is_empty() { tab.to_string() } else { format!("{tab} › {}", crate::i18n::tr(&self.name)) } + } +} + +/// 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<(f32, String)>) { + match shape { + egui::Shape::Text(text) => out.push((text.pos.y, text.galley.job.text.clone())), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), + _ => {} + } + } + let scratch = egui::Context::default(); + 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 mut headings: Vec<(f32, String)> = crate::widgets::take_registry(&scratch) + .into_iter() + .filter_map(|(id, r)| Some((r.top(), id.strip_prefix("heading:")?.to_string()))) + .collect(); + headings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut drawn = Vec::new(); + output.shapes.iter().for_each(|clipped| texts(&clipped.shape, &mut drawn)); + drawn.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut of_tab: Vec
= std::iter::once(String::new()) + .chain(headings.iter().map(|(_, name)| name.clone())) + .map(|name| Section { tab, name, texts: Vec::new() }) + .collect(); + for (y, text) in drawn { + // (a text counts as under a heading from a little above the heading's own top) + let under = headings.iter().take_while(|(top, _)| *top <= y + 1.0).count(); + if let Some(section) = of_tab.get_mut(under) + && !text.trim().is_empty() + { + section.texts.push(text); + } + } + all.extend(of_tab.into_iter().filter(|section| !section.texts.is_empty())); + } + all +} + +/// The sections found, each a row to choose (`settingsFound:{tab}:{section}`): its tab and +/// heading, and under them the first texts of it that have a word of `words`. Gives the section +/// chosen, by a click, by Return or Space with the focus on it, or (`open_first`) by Return in +/// the filter, which chooses the first. `focus_first` gives the first row the keyboard focus. +fn results(ui: &mut egui::Ui, found: &[Section], words: &str, open_first: bool, focus_first: bool) -> Option<(&'static str, String)> { + let t = Tokens::get(ui.ctx()); + if found.is_empty() { + ui.add_space(8.0); + ui.label(RichText::new(crate::i18n::tr("No setting matches what is typed.")).color(t.text_label)); + hint(ui, &t, "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through."); + return None; + } + let mut chosen = open_first.then(|| found.first().map(|first| (first.tab, first.name.clone()))).flatten(); + for (place, section) in found.iter().enumerate() { + let fill = ui.painter().add(egui::Shape::Noop); + let row = ui + .scope_builder(egui::UiBuilder::new().sense(egui::Sense::click()), |ui| { + ui.set_width(ui.available_width()); + ui.spacing_mut().item_spacing.y = 2.0; + ui.add_space(3.0); + ui.add(egui::Label::new(RichText::new(section.title()).font(t.semibold(13.0)).color(t.text)).selectable(false)); + // (what of it has a word that was typed; its heading is in the line above already) + let heading = crate::i18n::tr(§ion.name); + let with: Vec<&str> = section + .texts + .iter() + .map(String::as_str) + .filter(|text| *text != heading && words.split_whitespace().any(|word| text.to_lowercase().contains(word))) + .take(2) + .collect(); + for text in with { + // (legible on the fill a hovered or focused row has, and so on a plain one) + let dim = t.legible(t.legible(t.text_dim, t.hover, 4.5), t.chrome, 4.5); + ui.add(egui::Label::new(RichText::new(text).size(11.0).color(dim)).selectable(false).truncate()); + } + ui.add_space(3.0); + }) + .response; + if focus_first && place == 0 { + row.request_focus(); + } + let around = row.rect.expand2(egui::vec2(6.0, 0.0)); + if row.hovered() || row.has_focus() { + ui.painter().set(fill, egui::Shape::rect_filled(around, egui::CornerRadius::same(4), t.hover)); + } + if row.has_focus() { + ui.painter().rect_stroke(around, egui::CornerRadius::same(4), egui::Stroke::new(2.0, t.text), egui::StrokeKind::Inside); + } + row.widget_info(|| egui::WidgetInfo::labeled(egui::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); + 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 r = ui.label(RichText::new(crate::i18n::tr(text)).font(t.semibold(12.5)).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) + 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)); + } } 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)).size(11.0).color(t.legible(t.text_dim, t.chrome, 4.5))); } /// A checkbox addressable as `check:{id}`; true when toggled. @@ -90,7 +535,7 @@ pub(super) fn choices(ui: &mut egui::Ui, id: &str, options: let mut changed = false; ui.spacing_mut().item_spacing.x = 4.0; 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(ui, &format!("{id}-{i}"), l, *value == *v).clicked() && *value != *v { *value = *v; changed = true; } @@ -100,19 +545,51 @@ pub(super) fn choices(ui: &mut egui::Ui, id: &str, options: // ------------------------------------------------------------------------------------- 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 +607,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 +623,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 +798,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 +836,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 +860,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 +894,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 +925,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 +957,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 +993,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 +1018,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 +1052,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 +1080,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 +1190,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).size(11.0).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, egui::FontId::proportional(11.0), t.legible(t.text_dim, t.chrome, 4.5)); }); } row(ui, t, crate::i18n::tr("Type"), |ui| { @@ -622,7 +1210,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).size(11.0).color(t.legible(t.text_dim, t.chrome, 4.5))); }); } hint( @@ -702,7 +1290,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 +1301,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")).size(11.0).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(); @@ -1182,3 +1771,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/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_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_tabs.rs b/crates/ui-egui/src/tests_dialog_settings_tabs.rs new file mode 100644 index 00000000000..a5a86810daa --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings_tabs.rs @@ -0,0 +1,298 @@ +//! 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 three times (the filter, General, then Library) + key(&mut h, "Tab"); + key(&mut h, "Tab"); + key(&mut h, "Tab"); + // 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, then the tabs) + key(&mut h, "Tab"); + 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 second preview size has the focus (the tabs and the GPU checkbox come first) + let reached = (0..40).any(|_| { + key(&mut h, "Tab"); + 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/theme.rs b/crates/ui-egui/src/theme.rs index 282f9c70ef2..2ddecf567ff 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -378,6 +378,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())) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index a6af3dc7a87..331c75fc14a 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -500,13 +500,26 @@ pub fn flyout_row(ui: &mut Ui, id: &str, title: &str, icon: Icon, open: bool) -> /// A small bordered text button (Auto, B&W, HDR…). pub fn text_button(ui: &mut Ui, id: &str, label: &str, active: bool) -> Response { + chip(ui, id, label, active, false) +} + +/// 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) +} + +fn chip(ui: &mut Ui, id: &str, label: &str, active: bool, choice: bool) -> 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 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 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,9 +528,63 @@ 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. +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 { + 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.semibold(13.5), color); + let size = vec2((galley.size().x + 20.0).max(37.0), TAB_HEIGHT); + let (r, resp) = ui.allocate_exact_size(size, Sense::click()); + 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 } 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-