Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Add category tabs, judging cache and hidden-preset search to the toolbar palette
SeoJCalive936b5e34a462
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.jsonindex e97ca3ee..6a3b608c 100644--- a/src/Filee.App/Assets/i18n/ar.json+++ b/src/Filee.App/Assets/i18n/ar.json@@ -404,6 +404,10 @@"toolbar.face_hint": "قلب الشريط المفتوح: {0}","toolbar.face_hint_wheel": "عجلة الماوس","toolbar.face_hint_off": "اختر مفتاحًا أو عجلة الماوس من الاختصارات لقلب الشريط المفتوح",+ "toolbar.tab.all": "الكل",+ "toolbar.tab.media": "فيديو وصوت",+ "toolbar.tab.edit": "تحرير",+ "toolbar.tab.model3d_cad": "ثلاثي الأبعاد وCAD","group.editor_title": "المجموعة","group.hint": "تجمع المجموعة عدة إعدادات مسبقة في قطاع واحد: توقّف عليه أو تحرّك إلى الخارج لتظهر حوله.","group.members": "الإعدادات المسبقة ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex a8576b23..e833fbf1 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -418,6 +418,10 @@"toolbar.face_hint": "Flip the open donut: {0}","toolbar.face_hint_wheel": "mouse wheel","toolbar.face_hint_off": "Choose a key or the mouse wheel in Shortcuts to flip the open donut",+ "toolbar.tab.all": "All",+ "toolbar.tab.media": "Video & audio",+ "toolbar.tab.edit": "Edit",+ "toolbar.tab.model3d_cad": "3D & CAD","group.editor_title": "Group","group.hint": "A group is one donut slice for several presets: rest on it or move outward and they fan out around it.","group.members": "Presets ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex 91298bff..e74a84e3 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -404,6 +404,10 @@"toolbar.face_hint": "Dar la vuelta al menú circular abierto: {0}","toolbar.face_hint_wheel": "rueda del ratón","toolbar.face_hint_off": "Elige una tecla o la rueda del ratón en Atajos para dar la vuelta al menú circular abierto",+ "toolbar.tab.all": "Todo",+ "toolbar.tab.media": "Vídeo y audio",+ "toolbar.tab.edit": "Editar",+ "toolbar.tab.model3d_cad": "3D y CAD","group.editor_title": "Grupo","group.hint": "Un grupo es una sola porción del menú circular para varios ajustes preestablecidos: detente en él o muévete hacia fuera y se despliegan a su alrededor.","group.members": "Ajustes preestablecidos ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.jsonindex c82921d5..34911b9f 100644--- a/src/Filee.App/Assets/i18n/fr.json+++ b/src/Filee.App/Assets/i18n/fr.json@@ -418,6 +418,10 @@"toolbar.face_hint": "Retourner le menu ouvert : {0}","toolbar.face_hint_wheel": "molette de la souris","toolbar.face_hint_off": "Choisissez une touche ou la molette dans Raccourcis pour retourner le menu ouvert",+ "toolbar.tab.all": "Tout",+ "toolbar.tab.media": "Vidéo et audio",+ "toolbar.tab.edit": "Édition",+ "toolbar.tab.model3d_cad": "3D et CAO","group.editor_title": "Groupe","group.hint": "Un groupe réunit plusieurs préréglages dans une seule tranche du menu circulaire : survolez-la ou déplacez-vous vers l'extérieur et ils se déploient autour.","group.members": "Préréglages ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex d72aeadb..16c95f64 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -404,6 +404,10 @@"toolbar.face_hint": "खुले डोनट को पलटें: {0}","toolbar.face_hint_wheel": "माउस व्हील","toolbar.face_hint_off": "खुले डोनट को पलटने के लिए शॉर्टकट में कोई कुंजी या माउस व्हील चुनें",+ "toolbar.tab.all": "सभी",+ "toolbar.tab.media": "वीडियो और ऑडियो",+ "toolbar.tab.edit": "संपादन",+ "toolbar.tab.model3d_cad": "3D और CAD","group.editor_title": "समूह","group.hint": "समूह कई प्रीसेट के लिए डोनट की एक स्लाइस होता है: उस पर रुकें या बाहर की ओर बढ़ें और प्रीसेट उसके चारों ओर फैल जाएँगे।","group.members": "प्रीसेट ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.jsonindex 2bf8a1fa..0a4b16f7 100644--- a/src/Filee.App/Assets/i18n/ja.json+++ b/src/Filee.App/Assets/i18n/ja.json@@ -404,6 +404,10 @@"toolbar.face_hint": "開いたドーナツメニューを裏返す: {0}","toolbar.face_hint_wheel": "マウスホイール","toolbar.face_hint_off": "開いたドーナツメニューを裏返すには、ショートカットでキーかマウスホイールを選んでください",+ "toolbar.tab.all": "すべて",+ "toolbar.tab.media": "動画・音声",+ "toolbar.tab.edit": "編集",+ "toolbar.tab.model3d_cad": "3D・CAD","group.editor_title": "グループ","group.hint": "グループは複数のプリセットをまとめた、ドーナツメニュー内の1つの項目です。カーソルを置いたままにするか外側へ動かすと、プリセットが周囲に展開します。","group.members": "プリセット({0}/{1})",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 19aaab67..f148043e 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -418,6 +418,10 @@"toolbar.face_hint": "열린 도넛 뒤집기: {0}","toolbar.face_hint_wheel": "마우스 휠","toolbar.face_hint_off": "단축키에서 키나 마우스 휠을 고르면 열린 도넛을 뒤집을 수 있어요",+ "toolbar.tab.all": "전체",+ "toolbar.tab.media": "동영상·소리",+ "toolbar.tab.edit": "편집",+ "toolbar.tab.model3d_cad": "3D·CAD","group.editor_title": "묶음","group.hint": "묶음은 여러 프리셋을 도넛 한 칸에 담아요. 칸 위에 머물거나 바깥으로 움직이면 주변으로 펼쳐져요.","group.members": "프리셋 ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.jsonindex a1c291ff..26a841de 100644--- a/src/Filee.App/Assets/i18n/ne.json+++ b/src/Filee.App/Assets/i18n/ne.json@@ -404,6 +404,10 @@"toolbar.face_hint": "खुला डोनट पल्टाउनुहोस्: {0}","toolbar.face_hint_wheel": "माउस ह्विल","toolbar.face_hint_off": "खुला डोनट पल्टाउन सर्टकटहरूमा कुनै कुञ्जी वा माउस ह्विल छनोट गर्नुहोस्",+ "toolbar.tab.all": "सबै",+ "toolbar.tab.media": "भिडियो र अडियो",+ "toolbar.tab.edit": "सम्पादन",+ "toolbar.tab.model3d_cad": "थ्रीडी र CAD","group.editor_title": "समूह","group.hint": "समूह भनेको धेरै प्रिसेटहरूका लागि एउटा डोनट स्लाइस हो: त्यसमा रोकिनुहोस् वा बाहिर जानुहोस् र तिनीहरू वरिपरि फैलिनेछन्।","group.members": "प्रिसेटहरू ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex e07632dc..94bd23b5 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -418,6 +418,10 @@"toolbar.face_hint": "Obracanie otwartego pierścienia: {0}","toolbar.face_hint_wheel": "kółko myszy","toolbar.face_hint_off": "Wybierz klawisz lub kółko myszy w Skrótach, by obracać otwarty pierścień",+ "toolbar.tab.all": "Wszystkie",+ "toolbar.tab.media": "Wideo i dźwięk",+ "toolbar.tab.edit": "Edycja",+ "toolbar.tab.model3d_cad": "3D i CAD","group.editor_title": "Grupa","group.hint": "Grupa to jeden wycinek pierścienia dla kilku ustawień: zatrzymaj się na nim lub przesuń na zewnątrz, a rozłożą się wokół.","group.members": "Ustawienia ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.jsonindex 59614122..75aa74ed 100644--- a/src/Filee.App/Assets/i18n/pt-BR.json+++ b/src/Filee.App/Assets/i18n/pt-BR.json@@ -418,6 +418,10 @@"toolbar.face_hint": "Vire o menu aberto: {0}","toolbar.face_hint_wheel": "roda do mouse","toolbar.face_hint_off": "Escolha uma tecla ou a roda do mouse em Atalhos para virar o menu aberto",+ "toolbar.tab.all": "Todos",+ "toolbar.tab.media": "Vídeo e áudio",+ "toolbar.tab.edit": "Editar",+ "toolbar.tab.model3d_cad": "3D e CAD","group.editor_title": "Grupo","group.hint": "Um grupo é uma fatia do menu para várias predefinições: pare sobre ela ou mova para fora e elas se abrem ao redor.","group.members": "Predefinições ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.jsonindex 5e8d9564..913f30d6 100644--- a/src/Filee.App/Assets/i18n/ru.json+++ b/src/Filee.App/Assets/i18n/ru.json@@ -418,6 +418,10 @@"toolbar.face_hint": "Перевернуть открытое меню: {0}","toolbar.face_hint_wheel": "колесо мыши","toolbar.face_hint_off": "Чтобы переворачивать открытое меню, выберите клавишу или колесо мыши в разделе «Горячие клавиши»",+ "toolbar.tab.all": "Все",+ "toolbar.tab.media": "Видео и аудио",+ "toolbar.tab.edit": "Редактирование",+ "toolbar.tab.model3d_cad": "3D и CAD","group.editor_title": "Группа","group.hint": "Группа — это один сектор круга для нескольких пресетов: задержитесь на нём или ведите наружу, и они раскроются веером.","group.members": "Пресеты ({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex cfa40e2b..4e7ea05b 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -418,6 +418,10 @@"toolbar.face_hint": "用 {0} 翻转打开的圆环","toolbar.face_hint_wheel": "鼠标滚轮","toolbar.face_hint_off": "在快捷操作中选择按键或鼠标滚轮,即可翻转打开的圆环",+ "toolbar.tab.all": "全部",+ "toolbar.tab.media": "视频、音频",+ "toolbar.tab.edit": "编辑",+ "toolbar.tab.model3d_cad": "3D 与 CAD","group.editor_title": "组","group.hint": "组把多个预设放进圆环的一格。停留在上面或向外移动,它们就会在周围展开。","group.members": "预设({0} / {1})",diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.jsonindex 3fc0e8cf..e68d6cf1 100644--- a/src/Filee.App/Assets/i18n/zh-TW.json+++ b/src/Filee.App/Assets/i18n/zh-TW.json@@ -418,6 +418,10 @@"toolbar.face_hint": "用 {0} 翻轉開啟的圓環","toolbar.face_hint_wheel": "滑鼠滾輪","toolbar.face_hint_off": "在快捷操作中選擇按鍵或滑鼠滾輪,即可翻轉開啟的圓環",+ "toolbar.tab.all": "全部",+ "toolbar.tab.media": "影片與音訊",+ "toolbar.tab.edit": "編輯",+ "toolbar.tab.model3d_cad": "3D 與 CAD","group.editor_title": "群組","group.hint": "群組把多個預設放進圓環的一格。停留在上面或向外移動,它們就會在周圍展開。","group.members": "預設({0} / {1})",diff --git a/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.csindex 1d05900d..cf9dc737 100644--- a/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs@@ -51,26 +51,56 @@ public sealed partial class ProfileItemViewModel(ToolbarProfile profile, ILocali}/// <summary>A preset chip in the "available presets" palette.</summary>-public sealed record PaletteChip(string PresetId, string Label, string? Caption, string? Reason = null)+public enum PaletteTab { All, Image, Document, Media, Edit, Model3DCad, Map, Archive, Font }++public sealed record PaletteTabItem(PaletteTab Id, string Label);++public sealed record PaletteChip(string PresetId, string Label, string? Caption, string? Reason = null,+ PresetUse Use = PresetUse.Usable){- public bool IsDimmed => Reason is not null;+ public bool IsDimmed => Use != PresetUse.Usable;+ public bool CanAdd => Use != PresetUse.Unusable;}public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposable{+ internal static readonly (PaletteTab Id, string LabelKey, FormatCategory[] Categories)[] TabDefinitions =+ [+ (PaletteTab.All, "toolbar.tab.all", []),+ (PaletteTab.Image, "format.category.Image", [FormatCategory.Image, FormatCategory.Vector]),+ (PaletteTab.Document, "format.category.Document", [FormatCategory.Pdf, FormatCategory.Document,+ FormatCategory.Spreadsheet, FormatCategory.Presentation, FormatCategory.Hwp, FormatCategory.Text,+ FormatCategory.Ebook, FormatCategory.Data]),+ (PaletteTab.Media, "toolbar.tab.media", [FormatCategory.Video, FormatCategory.Audio, FormatCategory.Subtitle]),+ (PaletteTab.Edit, "toolbar.tab.edit", []),+ (PaletteTab.Model3DCad, "toolbar.tab.model3d_cad", [FormatCategory.Model3D, FormatCategory.Cad]),+ (PaletteTab.Map, "format.category.Geo", [FormatCategory.Geo]),+ (PaletteTab.Archive, "format.category.Archive", [FormatCategory.Archive]),+ (PaletteTab.Font, "format.category.Font", [FormatCategory.Font]),+ ];+private readonly UserDataStore _store;private readonly ILocalizer _loc;private readonly WindowService _windows;private readonly PresetAvailability _availability;private readonly ConverterCatalog _catalog;private readonly ILogger<ToolbarPageViewModel> _log;- private PresetAvailability.PaletteSession? _session;- private readonly Dictionary<string, PresetJudgement> _judged = [];+ private sealed class PaletteJudging+ {+ public Dictionary<string, PresetJudgement> Judged { get; } = [];+ public PresetAvailability.PaletteSession? Session { get; set; }+ }++ private readonly Dictionary<string, PaletteJudging> _judgingByProfile = [];private object? _pass;private bool _disposed;+ private bool _savingOwnLibrary;private static readonly TimeSpan JudgeSlice = TimeSpan.FromMilliseconds(8);private bool _loading;private bool _repositioning;+ private string? _newPresetToSelect;+ private PaletteTab? _pendingTabRestore;+ private bool _updatingTabs;public ToolbarPageViewModel(UserDataStore store, ILocalizer loc, WindowService windows,PresetAvailability availability, ConverterCatalog catalog, ILogger<ToolbarPageViewModel> log)@@ -83,7 +113,6 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposable_log = log;// A profile is found by its name or by an extension it handles ("png" finds the photo donut).VisibleProfiles = new FilteredList<ProfileItemViewModel>(Profiles, p => [p.Name, .. p.Profile.Extensions]);- VisiblePalette = new FilteredList<PaletteChip>(Palette, c => [c.Label, c.Caption]);foreach (var profile in store.Profiles)Profiles.Add(new ProfileItemViewModel(profile, loc));@@ -103,45 +132,115 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposableways.Add(loc["toolbar.face_hint_wheel"]);FaceHint = ways.Count == 0 ? loc["toolbar.face_hint_off"] : loc.Format("toolbar.face_hint", string.Join(" / ", ways));_catalog.Changed += OnCatalogChanged;+ _store.LibraryChanged += OnLibraryChanged;}public void Dispose(){_disposed = true;_catalog.Changed -= OnCatalogChanged;+ _store.LibraryChanged -= OnLibraryChanged;StopJudging();+ _judgingByProfile.Clear();}private void StopJudging(){_pass = null;- _session = null;}- private void ForgetJudgements()+ private void ForgetJudgements(string? profileId = null){StopJudging();- _judged.Clear();+ if (profileId is null)+ _judgingByProfile.Clear();+ else+ _judgingByProfile.Remove(profileId);}private void OnCatalogChanged(object? sender, EventArgs e) =>Dispatcher.UIThread.Post(() => { if (_disposed) return; ForgetJudgements(); Rebuild(); });+ private void OnLibraryChanged(object? sender, EventArgs e)+ {+ if (_disposed)+ return;+ if (!Dispatcher.UIThread.CheckAccess())+ {+ Dispatcher.UIThread.Post(InvalidateExternalLibrary);+ return;+ }+ if (!_savingOwnLibrary)+ InvalidateExternalLibrary();+ }++ private void InvalidateExternalLibrary()+ {+ if (_disposed)+ return;+ _pendingTabRestore ??= SelectedTab is { Id: not PaletteTab.All } tab ? tab.Id : null;+ ForgetJudgements();+ Rebuild();+ }++ private T SaveOwnLibrary<T>(Func<T> action)+ {+ var previous = _savingOwnLibrary;+ _savingOwnLibrary = true;+ try+ {+ DuringOwnSave?.Invoke();+ return action();+ }+ finally { _savingOwnLibrary = previous; }+ }++ private void SaveOwnLibrary() => SaveOwnLibrary(() => { _store.SaveLibrary(); return true; });++ internal Action? DuringOwnSave { get; set; }++ internal Action<string, string>? JudgementObserved { get; set; }+ internal bool HasJudgement(string profileId, string presetId) =>+ _judgingByProfile.TryGetValue(profileId, out var judging) && judging.Judged.ContainsKey(presetId);++ internal static PaletteTab TabOf(Preset preset)+ {+ if (preset.IsTool || preset.TargetFormat == BuiltInData.SameAsSource)+ return PaletteTab.Edit;+ var category = FormatRegistry.FindById(preset.TargetFormat)?.Category;+ return category is { } value+ ? TabDefinitions.First(t => t.Categories.Contains(value)).Id+ : PaletteTab.All;+ }+/// <summary>Under the Front / Back switch: what flips the open donut (or that nothing does).</summary>public string FaceHint { get; }public ObservableCollection<ProfileItemViewModel> Profiles { get; } = [];public ObservableCollection<PaletteChip> Palette { get; } = [];+ public ObservableCollection<PaletteTabItem> Tabs { get; } = [];+ public ObservableCollection<PaletteChip> VisiblePalette { get; } = [];- /// <summary>The profiles and the presets the search boxes above the two lists let through.</summary>+ /// <summary>The profiles the search box above the list lets through.</summary>public FilteredList<ProfileItemViewModel> VisibleProfiles { get; }- public FilteredList<PaletteChip> VisiblePalette { get; }[ObservableProperty] private string _profileSearch = "";[ObservableProperty] private string _paletteSearch = "";+ [ObservableProperty] private PaletteTabItem? _selectedTab;+ [ObservableProperty] private bool _showTabRow;partial void OnProfileSearchChanged(string value) => VisibleProfiles.Query = value;- partial void OnPaletteSearchChanged(string value) => VisiblePalette.Query = value;+ partial void OnPaletteSearchChanged(string value)+ {+ _pendingTabRestore = null;+ Rebuild();+ }+ partial void OnSelectedTabChanged(PaletteTabItem? value)+ {+ if (!_updatingTabs)+ _pendingTabRestore = null;+ RefreshVisiblePalette();+ }[ObservableProperty] private ProfileItemViewModel? _selectedProfile;[ObservableProperty] private IReadOnlyList<DonutItem> _donutItems = [];@@ -211,7 +310,10 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposable// A search typed for the last donut's presets would hide this one's (#427).PaletteSearch = "";RebuildProfileEditor();- ForgetJudgements();+ StopJudging();+ _newPresetToSelect = null;+ _pendingTabRestore = null;+ SelectedTab = null;Rebuild();}@@ -222,7 +324,7 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposableProfile.Name = value.Trim();SelectedProfile!.Refresh(_loc);CenterTitle = value.Trim();- _store.SaveLibrary();+ SaveOwnLibrary();}partial void OnIsMixedChanged(bool value)@@ -237,7 +339,7 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposable// The extensions are kept either way: chips become checks and back, so switching is harmless.item.Profile.IsFallback = value;Reposition(item);- _store.SaveLibrary();+ SaveOwnLibrary();item.Refresh(_loc);RebuildProfileEditor();}@@ -280,8 +382,8 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposableprivate void OnExtensionsSaved(){- _store.SaveLibrary();- ForgetJudgements();+ SaveOwnLibrary();+ ForgetJudgements(Profile?.Id);Rebuild();}@@ -361,7 +463,9 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposableinternal void PresetEdited(Preset preset){- _judged.Remove(preset.Id);+ StopJudging();+ foreach (var judging in _judgingByProfile.Values)+ judging.Judged.Remove(preset.Id);Commit();}@@ -395,6 +499,8 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposable_store.Presets.Add(preset);if (Slices is { Count: < ToolbarProfile.MaxSlices } slices)slices.Add(preset.Id);+ else+ _newPresetToSelect = preset.Id;Commit();}@@ -406,7 +512,7 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposablevar index = _store.Profiles.FindIndex(p => p.IsFallback);index = index < 0 ? _store.Profiles.Count : index;_store.Profiles.Insert(index, profile);- _store.SaveLibrary();+ SaveOwnLibrary();var item = new ProfileItemViewModel(profile, _loc);Profiles.Insert(index, item);SelectedProfile = item;@@ -420,7 +526,10 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposableif (!await _windows.ConfirmAsync(_windows.Main, _loc["toolbar.delete_profile"] + "?", destructive: true))return;_store.Profiles.Remove(Profile);- _store.SaveLibrary();+ var id = Profile.Id;+ _judgingByProfile.Remove(id);+ StopJudging();+ SaveOwnLibrary();Profiles.Remove(SelectedProfile!);SelectedProfile = Profiles.FirstOrDefault();}@@ -438,7 +547,7 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposable/// <summary>Puts a built-in profile back to its defaults (see <see cref="UserDataStore.ResetProfile"/>).</summary>internal void Reset(ProfileItemViewModel item){- if (!_store.ResetProfile(item.Profile))+ if (!SaveOwnLibrary(() => _store.ResetProfile(item.Profile)))return;// A profile that changed kind moved to the border between the normal and the mixed ones.var from = Profiles.IndexOf(item);@@ -464,13 +573,13 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposableforeach (var other in Profiles)other.Refresh(_loc);RebuildProfileEditor();- ForgetJudgements();+ ForgetJudgements(item.Profile.Id);Rebuild();}private void Commit(){- _store.SaveLibrary();+ SaveOwnLibrary();// Every profile: deleting a group (or a preset) takes it off every donut, not just this one.foreach (var item in Profiles)item.Refresh(_loc);@@ -491,20 +600,39 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposablePalette.Clear();var placed = profile is null ? [] : profile.PresetIds.Concat(profile.BackPresetIds ?? []).ToHashSet();var judge = profile is { Extensions.Count: > 0 };+ _judgingByProfile.TryGetValue(profile?.Id ?? "", out var judging);var pending = false;+ var query = PaletteSearch.Trim();+ if (_newPresetToSelect is { } newId && (!judge || judging?.Judged.ContainsKey(newId) == true)+ && _store.FindPreset(newId) is { } newPreset)+ {+ var newName = _loc.DisplayName(newPreset);+ if (judge && judging!.Judged[newId].Use == PresetUse.Unusable && query != newName)+ {+ PaletteSearch = newName;+ return;+ }+ if (query.Length > 0 && !newName.Contains(query, StringComparison.CurrentCultureIgnoreCase)+ && (Caption(newPreset)?.Contains(query, StringComparison.CurrentCultureIgnoreCase) != true))+ {+ PaletteSearch = "";+ return;+ }+ }+ var candidates = new List<(PaletteChip Chip, PaletteTab Tab, bool Group)>();// Groups first: few, and otherwise at the very end, below every conversion.foreach (var preset in _store.Presets.Where(p => !placed.Contains(p.Id)).OrderBy(p => !p.IsGroup)){string? reason = null;+ var use = PresetUse.Usable;if (judge && !preset.IsGroup){- if (!_judged.TryGetValue(preset.Id, out var judgement))+ if (judging is null || !judging.Judged.TryGetValue(preset.Id, out var judgement)){pending = true;continue;}- if (judgement.Use == PresetUse.Unusable)- continue;+ use = judgement.Use;reason = judgement.Reason;}var label = _loc.DisplayName(preset);@@ -512,13 +640,67 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposable// "GIF GIF" says nothing twice: only show the format when the name doesn't already.if (caption is not null && label.Contains(caption, StringComparison.OrdinalIgnoreCase))caption = null;- Palette.Add(new PaletteChip(preset.Id, label, caption, reason));+ var chip = new PaletteChip(preset.Id, label, caption, reason, use);+ if (use != PresetUse.Unusable)+ Palette.Add(chip);+ if ((query.Length == 0 && use != PresetUse.Unusable)+ || (query.Length > 0 && (label.Contains(query, StringComparison.CurrentCultureIgnoreCase)+ || caption?.Contains(query, StringComparison.CurrentCultureIgnoreCase) == true)))+ candidates.Add((chip, preset.IsGroup ? PaletteTab.All : TabOf(preset), preset.IsGroup));}if (pending && _pass is null && !_disposed){var pass = _pass = new object();- Dispatcher.UIThread.Post(() => JudgeSome(pass), DispatcherPriority.Background);+ var profileId = profile!.Id;+ Dispatcher.UIThread.Post(() => JudgeSome(pass, profileId), DispatcherPriority.Background);+ }+ var selected = SelectedTab?.Id ?? PaletteTab.All;+ var active = candidates.Where(c => !c.Group).Select(c => c.Tab).ToHashSet();+ var wanted = TabDefinitions.Where(t => t.Id == PaletteTab.All || active.Contains(t.Id)).ToList();+ _updatingTabs = true;+ try+ {+ for (var i = Tabs.Count - 1; i >= 0; i--)+ if (!wanted.Any(t => t.Id == Tabs[i].Id))+ Tabs.RemoveAt(i);+ for (var i = 0; i < wanted.Count; i++)+ {+ if (i < Tabs.Count && Tabs[i].Id == wanted[i].Id)+ continue;+ var existing = Tabs.FirstOrDefault(t => t.Id == wanted[i].Id);+ if (existing is not null)+ Tabs.Move(Tabs.IndexOf(existing), i);+ else+ Tabs.Insert(i, new PaletteTabItem(wanted[i].Id, _loc[wanted[i].LabelKey]));+ }+ var allIds = candidates.Where(c => !c.Group).Select(c => c.Chip.PresetId).ToHashSet();+ ShowTabRow = Tabs.Count > 2 || (Tabs.Count == 2+ && !allIds.SetEquals(candidates.Where(c => !c.Group && c.Tab == Tabs[1].Id)+ .Select(c => c.Chip.PresetId)));+ if (_newPresetToSelect is { } addedId && candidates.FirstOrDefault(c => c.Chip.PresetId == addedId) is { Chip: not null } added)+ {+ if (added.Chip.Use == PresetUse.Unusable && query != added.Chip.Label)+ {+ PaletteSearch = added.Chip.Label;+ return;+ }+ _newPresetToSelect = null;+ selected = added.Tab;+ }+ if (!pending && _pendingTabRestore is { } restore)+ {+ selected = restore;+ _pendingTabRestore = null;+ }+ if (!ShowTabRow || !wanted.Any(t => t.Id == selected))+ selected = PaletteTab.All;+ SelectedTab = Tabs.First(t => t.Id == selected);}+ finally+ {+ _updatingTabs = false;+ }+ RefreshVisiblePalette(candidates);CenterTitle = profile is null ? "" : _loc.DisplayName(profile);CenterSubtitle = EditingBack@@ -528,33 +710,65 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposableOnPropertyChanged(nameof(BackCount));}- private void JudgeSome(object pass)+ private void RefreshVisiblePalette(){- if (pass != _pass || _disposed)- return;- var profile = Profile;- if (profile is null)+ var query = PaletteSearch.Trim();+ var placed = Profile is null ? [] : Profile.PresetIds.Concat(Profile.BackPresetIds ?? []).ToHashSet();+ _judgingByProfile.TryGetValue(Profile?.Id ?? "", out var judging);+ var candidates = new List<(PaletteChip Chip, PaletteTab Tab, bool Group)>();+ foreach (var preset in _store.Presets.Where(p => !placed.Contains(p.Id)).OrderBy(p => !p.IsGroup)){- _pass = null;- Rebuild();- return;+ var judgement = judging?.Judged.GetValueOrDefault(preset.Id) ?? new(PresetUse.Usable, null);+ if (Profile is { Extensions.Count: > 0 } && !preset.IsGroup && !HasJudgement(Profile.Id, preset.Id))+ continue;+ if (judgement.Use == PresetUse.Unusable && query.Length == 0)+ continue;+ var label = _loc.DisplayName(preset);+ var caption = Caption(preset);+ if (caption is not null && label.Contains(caption, StringComparison.OrdinalIgnoreCase))+ caption = null;+ if (query.Length > 0 && !label.Contains(query, StringComparison.CurrentCultureIgnoreCase)+ && caption?.Contains(query, StringComparison.CurrentCultureIgnoreCase) != true)+ continue;+ candidates.Add((new PaletteChip(preset.Id, label, caption, judgement.Reason, judgement.Use),+ preset.IsGroup ? PaletteTab.All : TabOf(preset), preset.IsGroup));}+ RefreshVisiblePalette(candidates);+ }++ private void RefreshVisiblePalette(List<(PaletteChip Chip, PaletteTab Tab, bool Group)> candidates)+ {+ var tab = SelectedTab?.Id ?? PaletteTab.All;+ var wanted = candidates.Where(c => c.Group || tab == PaletteTab.All || c.Tab == tab).Select(c => c.Chip).ToList();+ VisiblePalette.Clear();+ foreach (var chip in wanted)+ VisiblePalette.Add(chip);+ }++ private void JudgeSome(object pass, string profileId)+ {+ if (pass != _pass || _disposed || Profile?.Id != profileId)+ return;+ var profile = Profile;+ if (!_judgingByProfile.TryGetValue(profileId, out var judging))+ _judgingByProfile[profileId] = judging = new PaletteJudging();var placed = profile.PresetIds.Concat(profile.BackPresetIds ?? []).ToHashSet();- var pending = _store.Presets.Where(p => !p.IsGroup && !placed.Contains(p.Id) && !_judged.ContainsKey(p.Id)).ToList();+ var pending = _store.Presets.Where(p => !p.IsGroup && !placed.Contains(p.Id) && !judging.Judged.ContainsKey(p.Id)).ToList();if (pending.Count > 0){- _session ??= _availability.ForPalette(profile.Extensions.Select(FormatRegistry.FindByExtension)+ judging.Session ??= _availability.ForPalette(profile.Extensions.Select(FormatRegistry.FindByExtension).OfType<FileFormat>().DistinctBy(f => f.Id).ToList());var clock = Stopwatch.StartNew();foreach (var preset in pending){- _judged[preset.Id] = JudgeOne(preset);+ judging.Judged[preset.Id] = JudgeOne(judging.Session, preset);+ JudgementObserved?.Invoke(profileId, preset.Id);if (clock.Elapsed >= JudgeSlice)break;}}- if (_store.Presets.Any(p => !p.IsGroup && !placed.Contains(p.Id) && !_judged.ContainsKey(p.Id)))- Dispatcher.UIThread.Post(() => JudgeSome(pass), DispatcherPriority.Background);+ if (_store.Presets.Any(p => !p.IsGroup && !placed.Contains(p.Id) && !judging.Judged.ContainsKey(p.Id)))+ Dispatcher.UIThread.Post(() => JudgeSome(pass, profileId), DispatcherPriority.Background);else{_pass = null;@@ -564,11 +778,11 @@ public sealed partial class ToolbarPageViewModel : ObservableObject, IDisposable// A preset whose judging throws stays usable (not dimmed) and the rest go on: this runs as a dispatcher job, where an// exception would end Filee.- private PresetJudgement JudgeOne(Preset preset)+ private PresetJudgement JudgeOne(PresetAvailability.PaletteSession session, Preset preset){try{- return _session!.Judge(preset);+ return session.Judge(preset);}catch (Exception ex) when (ex is not OutOfMemoryException){diff --git a/src/Filee.App/Views/Pages/ToolbarPage.axaml b/src/Filee.App/Views/Pages/ToolbarPage.axamlindex 0e4c3129..95393fea 100644--- a/src/Filee.App/Views/Pages/ToolbarPage.axaml+++ b/src/Filee.App/Views/Pages/ToolbarPage.axaml@@ -74,6 +74,42 @@<Setter Property="Opacity" Value="0.8" /></Style>+ <!-- Palette tabs: pills that wrap inside the narrow column (every name stays whole), the selected one filled with the accent -->+ <Style Selector="ListBox#PaletteTabs">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="Padding" Value="0" />+ </Style>+ <Style Selector="ListBox#PaletteTabs ListBoxItem">+ <Setter Property="Margin" Value="0,0,4,4" />+ <Setter Property="Padding" Value="10,3" />+ <Setter Property="MinHeight" Value="0" />+ <Setter Property="FontSize" Value="12.5" />+ <Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="Template">+ <ControlTemplate>+ <Border x:Name="Pill" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="1"+ CornerRadius="999" Padding="{TemplateBinding Padding}">+ <ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"+ Foreground="{TemplateBinding Foreground}" />+ </Border>+ </ControlTemplate>+ </Setter>+ </Style>+ <Style Selector="ListBox#PaletteTabs ListBoxItem:pointerover">+ <Setter Property="Background" Value="{DynamicResource AccentFaintBrush}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />+ </Style>+ <Style Selector="ListBox#PaletteTabs ListBoxItem:selected">+ <Setter Property="Background" Value="{DynamicResource AccentBrush}" />+ <Setter Property="Foreground" Value="{DynamicResource OnAccentBrush}" />+ </Style>+ <Style Selector="ListBox#PaletteTabs ListBoxItem:focus-visible /template/ Border#Pill">+ <Setter Property="BorderBrush" Value="{DynamicResource TextPrimaryBrush}" />+ </Style>+<!-- Mixed-selection check list: group rows with a chevron, extension toggle chips --><Style Selector="Border.ext-groups"><Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />@@ -329,7 +365,7 @@</StackPanel><!-- Palette -->- <StackPanel Grid.Column="4" Spacing="8">+ <StackPanel x:Name="PaletteColumn" Grid.Column="4" Spacing="8"><TextBlock Classes="label" Text="{DynamicResource toolbar.available}" /><!-- Two to a row in a narrow column: little padding, centred, and an ellipsis rather than text past the edge. --><Grid ColumnDefinitions="*,6,*">@@ -348,11 +384,26 @@</StackPanel></Button></Grid>- <TextBox Classes="search clearButton" Text="{Binding PaletteSearch}" Watermark="{DynamicResource common.search}">+ <TextBox x:Name="PaletteSearchBox" Classes="search clearButton" Text="{Binding PaletteSearch}" Watermark="{DynamicResource common.search}"><TextBox.InnerLeftContent><PathIcon Width="14" Height="14" Margin="10,0,0,0" Data="{StaticResource Icon.Search}" Foreground="{DynamicResource TextSecondaryBrush}" /></TextBox.InnerLeftContent></TextBox>+ <!-- Kinds of preset (All first). Hidden when one kind would only repeat All. Wraps rather than scrolls sideways. -->+ <ListBox x:Name="PaletteTabs" ItemsSource="{Binding Tabs}" SelectedItem="{Binding SelectedTab}"+ IsVisible="{Binding ShowTabRow}"+ ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled">+ <ListBox.ItemsPanel>+ <ItemsPanelTemplate>+ <WrapPanel />+ </ItemsPanelTemplate>+ </ListBox.ItemsPanel>+ <ListBox.ItemTemplate>+ <DataTemplate x:DataType="vm:PaletteTabItem">+ <TextBlock Text="{Binding Label}" TextWrapping="Wrap" />+ </DataTemplate>+ </ListBox.ItemTemplate>+ </ListBox><Border x:Name="PaletteBox" MinHeight="180" Padding="6" CornerRadius="{DynamicResource SoftRadius}"BorderThickness="2" BorderBrush="{DynamicResource SubtleBorderBrush}" Background="Transparent"><ItemsControl ItemsSource="{Binding VisiblePalette}">diff --git a/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs b/src/Filee.App/Views/Pages/ToolbarPage.axaml.csindex 8aecceea..78455219 100644--- a/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs+++ b/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs@@ -12,6 +12,7 @@ using Avalonia;using Avalonia.Controls;using Avalonia.Input;using Avalonia.Interactivity;+using Avalonia.VisualTree;using Filee.App.Controls;using Filee.App.ViewModels.Pages;@@ -23,7 +24,8 @@ public partial class ToolbarPage : UserControlprivate enum Source { Chip, Slice }- private sealed record DragState(Source Source, string? PresetId, int SliceIndex, string Label, Point Start)+ // CanAdd: fixed when the drag starts, so a chip that a search or a tab swaps under the pointer can't change it.+ private sealed record DragState(Source Source, string? PresetId, int SliceIndex, string Label, Point Start, bool CanAdd = true){public bool Active { get; set; }}@@ -39,6 +41,8 @@ public partial class ToolbarPage : UserControlRoot.AddHandler(PointerMovedEvent, OnRootPointerMoved, RoutingStrategies.Tunnel, handledEventsToo: true);Root.AddHandler(PointerReleasedEvent, OnRootPointerReleased, RoutingStrategies.Tunnel, handledEventsToo: true);Root.AddHandler(PointerCaptureLostEvent, (_, _) => EndDrag(), RoutingStrategies.Tunnel, handledEventsToo: true);+ // Before the list box, which doesn't move between the rows of its wrap panel.+ PaletteTabs.AddHandler(KeyDownEvent, OnTabsKeyDown, RoutingStrategies.Tunnel);Donut.SegmentDragStarted += (_, e) =>{@@ -76,6 +80,25 @@ public partial class ToolbarPage : UserControlprivate ToolbarPageViewModel? Vm => DataContext as ToolbarPageViewModel;+ /// <summary>Down / Up in the wrapped tab row: the tab on the next / previous row nearest below / above this one.</summary>+ private void OnTabsKeyDown(object? sender, KeyEventArgs e)+ {+ if (e.Key is not (Key.Down or Key.Up) || e.KeyModifiers != KeyModifiers.None ||+ (e.Source as Visual)?.FindAncestorOfType<ListBoxItem>(includeSelf: true) is not { } from)+ return;+ var down = e.Key == Key.Down;+ var tabs = PaletteTabs.GetRealizedContainers().OfType<ListBoxItem>().ToList();+ var beyond = tabs.Where(t => down ? t.Bounds.Top >= from.Bounds.Bottom - 0.5 : t.Bounds.Bottom <= from.Bounds.Top + 0.5).ToList();+ if (beyond.Count == 0)+ return;+ var row = down ? beyond.Min(t => t.Bounds.Top) : beyond.Max(t => t.Bounds.Top);+ var to = beyond.Where(t => Math.Abs(t.Bounds.Top - row) < 0.5)+ .MinBy(t => Math.Abs(t.Bounds.Center.X - from.Bounds.Center.X))!;+ PaletteTabs.SelectedIndex = PaletteTabs.IndexFromContainer(to);+ to.Focus(NavigationMethod.Directional);+ e.Handled = true;+ }+private void OnChipPressed(object? sender, PointerPressedEventArgs e){if (sender is not Border { DataContext: PaletteChip chip } border)@@ -87,10 +110,11 @@ public partial class ToolbarPage : UserControle.Handled = true;return;}- if (!point.Properties.IsLeftButtonPressed)+ // A preset this donut can't run (shown by a search) can be edited, not added.+ if (!point.Properties.IsLeftButtonPressed || !chip.CanAdd)return;- _drag = new DragState(Source.Chip, chip.PresetId, -1, chip.Label, e.GetPosition(Root));+ _drag = new DragState(Source.Chip, chip.PresetId, -1, chip.Label, e.GetPosition(Root), chip.CanAdd);e.Pointer.Capture(border);e.Handled = true;}@@ -98,7 +122,7 @@ public partial class ToolbarPage : UserControl/// <summary>Double-clicking a chip appends it to the donut.</summary>private void OnChipDoubleTapped(object? sender, TappedEventArgs e){- if (sender is Border { DataContext: PaletteChip chip } && Vm is { } vm)+ if (sender is Border { DataContext: PaletteChip { CanAdd: true } chip } && Vm is { } vm)vm.Insert(chip.PresetId, vm.SliceCount);}@@ -132,7 +156,7 @@ public partial class ToolbarPage : UserControlvar (sliceTarget, overPalette) = FindTarget(e);switch (drag.Source){- case Source.Chip when sliceTarget >= 0:+ case Source.Chip when drag.CanAdd && sliceTarget >= 0:vm.Insert(drag.PresetId!, sliceTarget);break;case Source.Slice when overPalette:diff --git a/tests/Filee.App.Tests/LocalizationTests.cs b/tests/Filee.App.Tests/LocalizationTests.csindex 9316b147..98e48751 100644--- a/tests/Filee.App.Tests/LocalizationTests.cs+++ b/tests/Filee.App.Tests/LocalizationTests.cs@@ -52,6 +52,37 @@ public partial class LocalizationTestsAssert.Empty(other.Except(english));}+ [Fact]+ public void Toolbar_tabs_and_reused_categories_exist_in_every_language()+ {+ string[] required =+ [+ "toolbar.tab.all",+ "toolbar.tab.media",+ "toolbar.tab.edit",+ "toolbar.tab.model3d_cad",+ "format.category.Image",+ "format.category.Document",+ "format.category.Geo",+ "format.category.Archive",+ "format.category.Font"+ ];+ string[] removed = ["toolbar.tab.document", "toolbar.tab.other"];++ foreach (var language in LocalizationService.Languages)+ {+ var translations = Load(language.Code);+ foreach (var key in required)+ {+ Assert.True(translations.TryGetValue(key, out var value), $"{language.Code}:{key} is missing");+ Assert.False(string.IsNullOrWhiteSpace(value), $"{language.Code}:{key} is empty");+ }++ foreach (var key in removed)+ Assert.False(translations.ContainsKey(key), $"{language.Code}:{key} should be removed");+ }+ }+[Theory][MemberData(nameof(Languages))]public void Format_placeholders_match_english(string code)diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.csindex ae99f9d2..27149330 100644--- a/tests/Filee.App.Tests/RenderTests.cs+++ b/tests/Filee.App.Tests/RenderTests.cs@@ -1757,6 +1757,196 @@ public class RenderTests});}+ /// <summary>+ /// The palette tabs of the mixed donut (no extensions, so every kind and no judging) wrap inside the 230 px column:+ /// every tab whole, in rows, reachable with the arrow keys, the last one too.+ /// </summary>+ [AvaloniaTheory]+ [InlineData("en", false)]+ [InlineData("en", true)]+ [InlineData("ko", false)]+ [InlineData("ko", true)]+ [InlineData("es", false)]+ [InlineData("es", true)]+ [InlineData("ru", false)]+ [InlineData("ru", true)]+ public void Palette_tabs_fit_narrow_column(string language, bool dark)+ {+ WithProfiles(language, dark, 820, _ => { }, (window, vm) =>+ {+ vm.SelectedProfile = vm.Profiles.Single(p => p.Profile.Id == "mixed");+ Pump();+ Assert.Empty(vm.SelectedProfile.Profile.Extensions);+ var column = window.GetVisualDescendants().OfType<StackPanel>().Single(s => s.Name == "PaletteColumn");+ var tabs = window.GetVisualDescendants().OfType<ListBox>().Single(l => l.Name == "PaletteTabs");+ Assert.True(tabs.IsEffectivelyVisible);+ Assert.Equal(Enum.GetValues<PaletteTab>(), tabs.Items.Cast<PaletteTabItem>().Select(t => t.Id));++ Avalonia.Rect InWindow(Avalonia.Visual v) =>+ new Avalonia.Rect(v.Bounds.Size).TransformToAABB(Avalonia.VisualExtensions.TransformToVisual(v, window)!.Value);+ var columnBox = InWindow(column);+ var rowBox = InWindow(tabs);+ Assert.Equal(230, columnBox.Width, 0.5);+ var items = Enumerable.Range(0, tabs.ItemCount).Select(i => (ListBoxItem)tabs.ContainerFromIndex(i)!).ToList();+ var boxes = items.Select(InWindow).ToList();+ for (var i = 0; i < items.Count; i++)+ {+ var box = boxes[i];+ Assert.True(box.Left >= columnBox.Left - 0.5 && box.Right <= columnBox.Right + 0.5, $"tab {i} {box} outside {columnBox}");+ Assert.True(box.Top >= rowBox.Top - 0.5 && box.Bottom <= rowBox.Bottom + 0.5, $"tab {i} {box} outside {rowBox}");+ var text = items[i].GetVisualDescendants().OfType<TextBlock>().Single();+ Assert.Single(text.TextLayout.TextLines);+ Assert.True(text.TextLayout.WidthIncludingTrailingWhitespace <= text.Bounds.Width + 0.5, text.Text);+ if (i == 0)+ continue;+ // Reading order: right of the previous tab on its row, or on a row below it.+ var previous = boxes[i - 1];+ Assert.True(Math.Abs(box.Top - previous.Top) < 0.5 ? box.Left >= previous.Right - 0.5 : box.Top >= previous.Bottom - 0.5,+ $"tab {i} {box} overlaps or precedes {previous}");+ }+ Assert.True(boxes.Select(b => Math.Round(b.Top)).Distinct().Count() >= 2);+ var suffix = dark ? "dark" : "light";+ Save(window, $"toolbar-tabs-{language}-{suffix}.png");++ // Right along a row, Down at its end to the tab on the next row nearest below, up to the last tab.+ void Press(Key key, PhysicalKey physical)+ {+ window.KeyPress(key, RawInputModifiers.None, physical, null);+ window.KeyRelease(key, RawInputModifiers.None, physical, null);+ Pump();+ }+ bool SameRow(int a, int b) => Math.Abs(boxes[a].Top - boxes[b].Top) < 0.5;+ int Nearest(int from, bool below)+ {+ var beyond = Enumerable.Range(0, boxes.Count)+ .Where(i => below ? boxes[i].Top >= boxes[from].Bottom - 0.5 : boxes[i].Bottom <= boxes[from].Top + 0.5).ToList();+ var row = below ? beyond.Min(i => boxes[i].Top) : beyond.Max(i => boxes[i].Top);+ return beyond.Where(i => Math.Abs(boxes[i].Top - row) < 0.5).MinBy(i => Math.Abs(boxes[i].Center.X - boxes[from].Center.X));+ }+ var visited = new HashSet<int>();+ void Expect(int index)+ {+ Assert.Same(tabs.Items[index], tabs.SelectedItem);+ Assert.Same(vm.Tabs[index], vm.SelectedTab);+ Assert.True(items[index].IsFocused, $"tab {index} not focused");+ visited.Add(index);+ }+ Assert.True(items[0].Focus());+ // The first row has nothing above it: Up stays.+ Press(Key.Up, PhysicalKey.ArrowUp);+ Expect(0);+ var current = 0;+ var downs = 0;+ while (current < items.Count - 1)+ {+ if (SameRow(current, current + 1))+ {+ Press(Key.Right, PhysicalKey.ArrowRight);+ current++;+ }+ else+ {+ Press(Key.Down, PhysicalKey.ArrowDown);+ current = Nearest(current, below: true);+ downs++;+ }+ Expect(current);+ }+ Assert.True(downs >= 1);+ // The last row has nothing below it: Down stays.+ Press(Key.Down, PhysicalKey.ArrowDown);+ Expect(items.Count - 1);+ var last = items[^1];+ last.BringIntoView();+ Pump();+ var scroller = window.FindControl<ScrollViewer>("PageScroller")!;+ Assert.True(last.IsEffectivelyVisible);+ Assert.True(InWindow(scroller).Intersects(InWindow(last)));+ Assert.True(InWindow(last).Right <= InWindow(column).Right + 0.5);+ var chips = window.GetVisualDescendants().OfType<Border>().Where(b => b.DataContext is PaletteChip && b.Classes.Contains("chip"))+ .Select(b => ((PaletteChip)b.DataContext!).PresetId).ToList();+ // The last tab is Font: font presets, no image or archive ones.+ Assert.Equal(PaletteTab.Font, vm.SelectedTab!.Id);+ Assert.Contains("to-ttf", chips);+ Assert.DoesNotContain("to-zip", chips);+ Assert.DoesNotContain("to-png", chips);+ Save(window, $"toolbar-tabs-{language}-{suffix}-font.png");++ // Up goes back to the row above, to the tab nearest above.+ var above = Nearest(items.Count - 1, below: false);+ Press(Key.Up, PhysicalKey.ArrowUp);+ Expect(above);+ Assert.False(SameRow(above, items.Count - 1));++ // From there Right reaches the tabs a Down skipped, then Left walks back over every tab, across the row ends,+ // to the first.+ for (current = above; current < items.Count - 1; current++)+ {+ Press(Key.Right, PhysicalKey.ArrowRight);+ Expect(current + 1);+ }+ for (current = items.Count - 1; current > 0; current--)+ {+ Press(Key.Left, PhysicalKey.ArrowLeft);+ Expect(current - 1);+ }+ Assert.Equal(Enumerable.Range(0, items.Count), visited.Order());+ });+ }++ /// <summary>A search shows a preset this donut can't run: dimmed, with its reason, under its own tab.</summary>+ [AvaloniaTheory]+ [InlineData("en", false)]+ [InlineData("ko", true)]+ public void Palette_search_reveals_unusable(string language, bool dark)+ {+ using var f = new PresetAvailabilityTests.Fixture();+ TestServices.EnsureInitialized(language);+ var theme = AppHost.Get<ThemeService>();+ f.Preset("test-wav").Name = "Hidden WAV sample";+ f.Preset("test-jpg").Name = "Hidden JPG sample";+ if (dark)+ theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark }, language);+ using var vm = f.PageWithPalette("png");+ Dispatcher.UIThread.RunJobs();+ var page = new ToolbarPage { DataContext = vm };+ var window = new Window { Width = 1080, Height = 820, Content = page };+ window.Bind(Window.BackgroundProperty, window.GetResourceObservable("PageBrush"));+ try+ {+ window.Show();+ Pump();+ var search = page.FindControl<TextBox>("PaletteSearchBox")!;+ Assert.True(search.Focus());+ window.KeyTextInput("Hidden");+ Pump();+ var tabs = page.FindControl<ListBox>("PaletteTabs")!;+ Assert.True(tabs.IsEffectivelyVisible);+ Assert.Equal([PaletteTab.All, PaletteTab.Image, PaletteTab.Media], tabs.Items.Cast<PaletteTabItem>().Select(t => t.Id));+ var media = (ListBoxItem)tabs.ContainerFromIndex(2)!;+ var point = Avalonia.VisualExtensions.TranslatePoint(media, new Avalonia.Point(media.Bounds.Width / 2, media.Bounds.Height / 2), window)!.Value;+ window.MouseDown(point, MouseButton.Left);+ window.MouseUp(point, MouseButton.Left);+ Pump();+ Assert.Same(vm.Tabs[2], tabs.SelectedItem);+ var chip = page.GetVisualDescendants().OfType<Border>().Single(b => b.DataContext is PaletteChip { PresetId: "test-wav" });+ Assert.Contains("dimmed", chip.Classes);+ Assert.Equal(f.Loc["error.no_route"], ToolTip.GetTip(chip));+ var suffix = dark ? "dark" : "light";+ Save(window, $"toolbar-search-unusable-{language}-{suffix}.png");+ ToolTip.SetIsOpen(chip, true);+ Pump();+ Save(window, $"toolbar-search-unusable-{language}-{suffix}-tooltip.png");+ ToolTip.SetIsOpen(chip, false);+ }+ finally+ {+ window.Close();+ if (dark)+ theme.Apply(new ThemeSettings(), language);+ }+ }+/// <summary>Shows the toolbar page (tall, so the profile card is visible) with temporarily changed profiles.</summary>private static void WithProfiles(string language, bool dark, double height, Action<List<ToolbarProfile>> change, Action<Window, ToolbarPageViewModel> act){diff --git a/tests/Filee.App.Tests/ToolbarEditorTests.cs b/tests/Filee.App.Tests/ToolbarEditorTests.csindex 07112027..f88449d7 100644--- a/tests/Filee.App.Tests/ToolbarEditorTests.cs+++ b/tests/Filee.App.Tests/ToolbarEditorTests.cs@@ -312,6 +312,8 @@ public class ToolbarPageTestsAppHost.Get<PresetAvailability>(), AppHost.Get<ConverterCatalog>(), NullLogger<ToolbarPageViewModel>.Instance);vm.SelectedProfile = vm.Profiles.Single(p => p.Profile.Id == "images");vm.PaletteSearch = "png"; // a search that would hide it+ Dispatcher.UIThread.RunJobs();+ vm.SelectedTab = vm.Tabs.Single(t => t.Id == PaletteTab.Image);var pdf = vm.Profiles.Single(p => p.Profile.Id == "pdf");pdf.Profile.PresetIds.RemoveAt(0); // changed elsewhere, as when a deleted group leaves every donut@@ -325,6 +327,8 @@ public class ToolbarPageTestsDispatcher.UIThread.RunJobs();Assert.Equal("", vm.PaletteSearch);+ Assert.Equal(PaletteTab.Image, vm.SelectedTab!.Id);+ Assert.Equal("test-new-group", vm.VisiblePalette[0].PresetId);// Up with the groups at the top, above every conversion: not below ~80 presets.var chips = vm.VisiblePalette.Select(c => store.FindPreset(c.PresetId)!).ToList();var at = chips.FindIndex(p => p.Id == "test-new-group");@@ -415,7 +419,7 @@ public class ToolbarPageTestspublic class PresetAvailabilityTests{- private class FakeConverter(string id, IReadOnlyList<ConversionEdge> edges) : IConverter+ internal class FakeConverter(string id, IReadOnlyList<ConversionEdge> edges) : IConverter{public FakeConverter(string id, params (string From, string To)[] edges): this(id, edges.Select(e => new ConversionEdge(e.From, e.To)).ToList()) { }@@ -435,7 +439,7 @@ public class PresetAvailabilityTeststhrow new NotSupportedException();}- private sealed class FakeTransformer(string id, IReadOnlyList<ConversionEdge> edges)+ internal sealed class FakeTransformer(string id, IReadOnlyList<ConversionEdge> edges): FakeConverter(id, edges), IImageTransformer{public bool Transforms(string from, string to) => true;@@ -465,7 +469,7 @@ public class PresetAvailabilityTests}}- private sealed class Fixture : IDisposable+ internal sealed class Fixture : IDisposable{private readonly UserDataStore _store;private readonly List<Preset> _presets;@@ -908,3 +912,665 @@ public class PresetAvailabilityTestsAssert.True(vm.Palette.Single(c => c.PresetId == "test-mp4").IsDimmed);}}++public class ToolbarPaletteModelTests+{+ private static ToolbarProfile Profile(string id, string extension) => new()+ {+ Id = id,+ Name = id,+ Extensions = [extension],+ PresetIds = [],+ BackPresetIds = [],+ };++ private static void Select(ToolbarPageViewModel vm, string id) =>+ vm.SelectedProfile = vm.Profiles.Single(p => p.Profile.Id == id);++ /// <summary>+ /// Searches for the preset's name on the selected profile and checks its chip against a fresh palette session for that+ /// profile's extensions: the same use (<paramref name="use"/>), dimmed unless usable, and the same reason.+ /// </summary>+ private static void AssertJudgedAfresh(PresetAvailabilityTests.Fixture f, ToolbarPageViewModel vm, string id, PresetUse use)+ {+ var formats = vm.SelectedProfile!.Profile.Extensions.Select(FormatRegistry.FindByExtension).OfType<FileFormat>()+ .DistinctBy(x => x.Id).ToList();+ var expected = f.Availability.ForPalette(formats).Judge(f.Preset(id));+ Assert.Equal(use, expected.Use);+ var search = vm.PaletteSearch;+ vm.PaletteSearch = f.Loc.DisplayName(f.Preset(id));+ var chip = Assert.Single(vm.VisiblePalette, c => c.PresetId == id);+ Assert.Equal(expected.Use, chip.Use);+ Assert.Equal(expected.Use != PresetUse.Usable, chip.IsDimmed);+ Assert.Equal(expected.Reason, chip.Reason);+ vm.PaletteSearch = search;+ }++ [AvaloniaFact]+ public void Groups_categories_into_eight_tabs()+ {+ var targets = new (string Format, PaletteTab Tab)[]+ {+ ("png", PaletteTab.Image), ("svg", PaletteTab.Image),+ ("pdf", PaletteTab.Document), ("csv", PaletteTab.Document),+ ("mp4", PaletteTab.Media), ("srt", PaletteTab.Media),+ ("zip", PaletteTab.Archive), ("geojson", PaletteTab.Map),+ (FormatRegistry.Known.First(f => f.Category == FormatCategory.Model3D).Id, PaletteTab.Model3DCad),+ (FormatRegistry.Known.First(f => f.Category == FormatCategory.Cad).Id, PaletteTab.Model3DCad),+ (FormatRegistry.Known.First(f => f.Category == FormatCategory.Font).Id, PaletteTab.Font),+ };+ foreach (var (format, tab) in targets)+ Assert.Equal(tab, ToolbarPageViewModel.TabOf(new Preset { TargetFormat = format }));+ Assert.Equal(PaletteTab.Edit, ToolbarPageViewModel.TabOf(new Preset { Kind = PresetKind.Tool, TargetFormat = "mp4" }));+ Assert.Equal(PaletteTab.Edit, ToolbarPageViewModel.TabOf(new Preset { TargetFormat = BuiltInData.SameAsSource }));+ Assert.Equal(PaletteTab.Image, ToolbarPageViewModel.TabOf(new Preset { TargetFormat = "png" }));+ Assert.Equal(PaletteTab.All, ToolbarPageViewModel.TabOf(new Preset { TargetFormat = "not-registered" }));+ Assert.Equal(PaletteTab.Archive, ToolbarPageViewModel.TabOf(new Preset { TargetFormat = FormatRegistry.Folder }));+ }++ [AvaloniaFact]+ public void Category_mapping_covers_every_enum_value()+ {+ var expected = new Dictionary<FormatCategory, PaletteTab>+ {+ [FormatCategory.Image] = PaletteTab.Image,+ [FormatCategory.Vector] = PaletteTab.Image,+ [FormatCategory.Pdf] = PaletteTab.Document,+ [FormatCategory.Document] = PaletteTab.Document,+ [FormatCategory.Spreadsheet] = PaletteTab.Document,+ [FormatCategory.Presentation] = PaletteTab.Document,+ [FormatCategory.Hwp] = PaletteTab.Document,+ [FormatCategory.Text] = PaletteTab.Document,+ [FormatCategory.Ebook] = PaletteTab.Document,+ [FormatCategory.Data] = PaletteTab.Document,+ [FormatCategory.Video] = PaletteTab.Media,+ [FormatCategory.Audio] = PaletteTab.Media,+ [FormatCategory.Subtitle] = PaletteTab.Media,+ [FormatCategory.Archive] = PaletteTab.Archive,+ [FormatCategory.Font] = PaletteTab.Font,+ [FormatCategory.Model3D] = PaletteTab.Model3DCad,+ [FormatCategory.Cad] = PaletteTab.Model3DCad,+ [FormatCategory.Geo] = PaletteTab.Map,+ };+ Assert.Equal(Enum.GetValues<FormatCategory>().Length, expected.Count);+ var definitions = ToolbarPageViewModel.TabDefinitions;+ Assert.Equal(Enum.GetValues<PaletteTab>(), definitions.Select(t => t.Id));+ Assert.Equal(expected.OrderBy(x => x.Key), definitions.SelectMany(t => t.Categories.Select(c => new KeyValuePair<FormatCategory, PaletteTab>(c, t.Id)))+ .OrderBy(x => x.Key));+ foreach (var category in Enum.GetValues<FormatCategory>())+ Assert.Equal(expected[category], ToolbarPageViewModel.TabOf(new Preset+ {+ TargetFormat = FormatRegistry.Known.First(f => f.Category == category).Id,+ }));+ }++ [AvaloniaFact]+ public void Two_tabs_hide_the_row_only_when_their_preset_ids_match()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ f.Store.Presets.Add(new Preset { Id = "test-unregistered", Name = "OnlyPair unknown", TargetFormat = "not-registered" });+ f.Store.Presets.Add(new Preset { Id = "test-image-pair", Name = "OnlyPair image", TargetFormat = "png" });+ using var vm = f.PageWithPalette();+ vm.PaletteSearch = "OnlyPair";+ Assert.Equal([PaletteTab.All, PaletteTab.Image], vm.Tabs.Select(t => t.Id));+ Assert.True(vm.ShowTabRow);+ Assert.Contains(vm.VisiblePalette, c => c.PresetId == "test-unregistered");+ Assert.Contains(vm.VisiblePalette, c => c.PresetId == "test-image-pair");+ vm.SelectedTab = vm.Tabs[1];+ Assert.DoesNotContain(vm.VisiblePalette, c => c.PresetId == "test-unregistered");+ Assert.Contains(vm.VisiblePalette, c => c.PresetId == "test-image-pair");++ vm.PaletteSearch = "OnlyPair image";+ Assert.Equal([PaletteTab.All, PaletteTab.Image], vm.Tabs.Select(t => t.Id));+ Assert.False(vm.ShowTabRow);+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ Assert.Contains(vm.VisiblePalette, c => c.PresetId == "test-image-pair");+ }++ [AvaloniaFact]+ public void Tab_labels_reuse_format_categories_in_declaration_order()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ using var vm = f.PageWithPalette();+ var expectedKeys = new[]+ {+ "toolbar.tab.all", "format.category.Image", "format.category.Document",+ "toolbar.tab.media", "toolbar.tab.edit", "toolbar.tab.model3d_cad",+ "format.category.Geo", "format.category.Archive", "format.category.Font",+ };+ Assert.Equal(Enum.GetValues<PaletteTab>(), vm.Tabs.Select(t => t.Id));+ Assert.Equal(expectedKeys.Select(key => f.Loc[key]), vm.Tabs.Select(t => t.Label));+ }++ [AvaloniaFact]+ public void Search_finds_hidden_presets_across_tabs()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ f.Preset("test-wav").Name = "Hidden WAV sample";+ using var vm = f.PageWithPalette("png");+ Assert.DoesNotContain(vm.VisiblePalette, c => c.PresetId == "test-wav");+ Dispatcher.UIThread.RunJobs();+ Assert.True(vm.HasJudgement("test-palette", "test-wav"));+ Assert.DoesNotContain(vm.Palette, c => c.PresetId == "test-wav");+ vm.SelectedTab = vm.Tabs.Single(t => t.Id == PaletteTab.Image);+ vm.PaletteSearch = " hidden WAV ";+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ Assert.Contains(vm.Tabs, t => t.Id == PaletteTab.Media);+ vm.SelectedTab = vm.Tabs.Single(t => t.Id == PaletteTab.Media);+ var chip = Assert.Single(vm.VisiblePalette, c => c.PresetId == "test-wav");+ Assert.Equal(PresetUse.Unusable, chip.Use);+ Assert.False(chip.CanAdd);+ Assert.True(chip.IsDimmed);+ Assert.Equal(f.Loc["error.no_route"], chip.Reason);+ vm.PaletteSearch = "";+ Assert.DoesNotContain(vm.VisiblePalette, c => c.PresetId == "test-wav");+ Assert.Contains(vm.VisiblePalette, c => c.PresetId == "test-group");+ }++ [AvaloniaFact]+ public void Selecting_a_cached_profile_reuses_its_results()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var a = Profile("cache-a", "png");+ using var vm = f.Page(a);+ var b = Profile("cache-b", "mp4");+ f.Store.Profiles.Add(b);+ vm.Profiles.Add(new ProfileItemViewModel(b, f.Loc));+ var judged = new List<(string Profile, string Preset)>();+ vm.JudgementObserved = (profile, preset) => judged.Add((profile, preset));+ Dispatcher.UIThread.RunJobs();+ Assert.True(vm.HasJudgement(a.Id, "test-jpg"));+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.True(vm.HasJudgement(b.Id, "test-wav"));+ var count = judged.Count;+ Select(vm, a.Id);+ Assert.Contains(vm.VisiblePalette, c => c.PresetId == "test-jpg");+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(count, judged.Count);+ }++ [AvaloniaFact]+ public void Adding_presets_judges_only_new_ids_on_visit()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var a = Profile("add-a", "png");+ using var vm = f.Page(a);+ var b = Profile("add-b", "mp4");+ f.Store.Profiles.Add(b);+ vm.Profiles.Add(new ProfileItemViewModel(b, f.Loc));+ Dispatcher.UIThread.RunJobs();+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Select(vm, a.Id);+ var observed = new List<(string, string)>();+ vm.JudgementObserved = (id, preset) => observed.Add((id, preset));+ f.Store.Presets.Add(new Preset { Id = "test-jpg-after", TargetFormat = "jpg" });+ vm.AddGroup(new Preset { Id = "test-added-group", Kind = PresetKind.Group, SubPresetIds = ["test-jpg"] });+ Dispatcher.UIThread.RunJobs();+ Assert.Equal([("add-a", "test-jpg-after")], observed);+ Assert.Contains(vm.VisiblePalette, c => c.PresetId == "test-added-group");+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.Equal([("add-a", "test-jpg-after"), ("add-b", "test-jpg-after")], observed);+ Assert.DoesNotContain(observed, x => x.Item2 is "test-jpg" or "test-added-group");+ }++ [AvaloniaFact]+ public async Task External_library_save_rejudges_cached_profiles()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ f.Preset("test-wav").Name = "Hidden WAV sample";+ var a = Profile("external-a", "png");+ using var vm = f.Page(a);+ var b = Profile("external-b", "mp4");+ f.Store.Profiles.Add(b);+ vm.Profiles.Add(new ProfileItemViewModel(b, f.Loc));+ Dispatcher.UIThread.RunJobs();+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ AssertJudgedAfresh(f, vm, "test-wav", PresetUse.Unusable);+ Select(vm, a.Id);+ vm.SelectedTab = vm.Tabs.Single(t => t.Id == PaletteTab.Image);+ var observed = new List<(string, string)>();+ var lastCandidate = f.Store.Presets.Last(p => !p.IsGroup).Id;+ var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);+ vm.JudgementObserved = (id, preset) =>+ {+ observed.Add((id, preset));+ if (id == a.Id && preset == lastCandidate)+ completed.TrySetResult();+ };+ f.Preset("test-wav").TargetFormat = "jpg";+ f.Store.SaveLibrary();+ Assert.False(vm.HasJudgement(a.Id, "test-wav"));+ Assert.False(vm.HasJudgement(b.Id, "test-wav"));+ Assert.DoesNotContain(vm.Tabs, t => t.Id == PaletteTab.Image);+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ Dispatcher.UIThread.RunJobs();+ await completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(PaletteTab.Image, vm.SelectedTab!.Id);+ Assert.Contains(vm.VisiblePalette, c => c.PresetId == "test-wav" && c.Use == PresetUse.Usable);+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ AssertJudgedAfresh(f, vm, "test-wav", PresetUse.Unusable);+ Assert.Equal(1, observed.Count(x => x == (a.Id, "test-wav")));+ Assert.Equal(1, observed.Count(x => x == (b.Id, "test-wav")));+ }++ [AvaloniaFact]+ public void External_save_on_another_thread_during_own_save_invalidates_all_profiles()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var a = Profile("thread-a", "png");+ using var vm = f.Page(a);+ var b = Profile("thread-b", "mp4");+ var c = Profile("thread-c", "png");+ foreach (var profile in new[] { b, c })+ {+ f.Store.Profiles.Add(profile);+ vm.Profiles.Add(new ProfileItemViewModel(profile, f.Loc));+ }+ Dispatcher.UIThread.RunJobs();+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Select(vm, c.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.True(vm.HasJudgement(a.Id, "test-wav"));+ Assert.True(vm.HasJudgement(b.Id, "test-wav"));+ var postedOffThread = false;+ var ownThread = Environment.CurrentManagedThreadId;+ f.Preset("test-wav").TargetFormat = "jpg";+ vm.DuringOwnSave = () =>+ {+ var worker = new Thread(() =>+ {+ postedOffThread = Environment.CurrentManagedThreadId != ownThread;+ f.Store.SaveLibrary();+ });+ worker.Start();+ Assert.True(worker.Join(TimeSpan.FromSeconds(5)), "external save thread did not finish");+ };+ vm.ProfileName = "Updated C";+ vm.DuringOwnSave = null;+ Assert.True(postedOffThread);+ Dispatcher.UIThread.RunJobs();+ Assert.False(vm.HasJudgement(a.Id, "test-wav"));+ Assert.False(vm.HasJudgement(b.Id, "test-wav"));+ var observed = new List<(string Profile, string Preset)>();+ vm.JudgementObserved = (profile, preset) => observed.Add((profile, preset));+ Select(vm, a.Id);+ Dispatcher.UIThread.RunJobs();+ AssertJudgedAfresh(f, vm, "test-wav", PresetUse.Usable);+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ AssertJudgedAfresh(f, vm, "test-wav", PresetUse.Unusable);+ Assert.Equal(1, observed.Count(x => x == (a.Id, "test-wav")));+ Assert.Equal(1, observed.Count(x => x == (b.Id, "test-wav")));+ }++ [AvaloniaFact]+ public void Search_change_cancels_pending_external_tab_restore()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ using var vm = f.PageWithPalette("png");+ Dispatcher.UIThread.RunJobs();+ vm.SelectedTab = vm.Tabs.Single(t => t.Id == PaletteTab.Image);+ f.Store.SaveLibrary();+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ Assert.DoesNotContain(vm.Tabs, t => t.Id == PaletteTab.Image);+ vm.PaletteSearch = "test-jpg";+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ vm.PaletteSearch = "";+ Dispatcher.UIThread.RunJobs();+ Assert.True(vm.ShowTabRow);+ Assert.Contains(vm.Tabs, t => t.Id == PaletteTab.Image);+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ }++ [AvaloniaFact]+ public void Deleted_preset_never_resurrects_from_cache()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ f.Preset("test-wav").Name = "Hidden WAV sample";+ f.Preset("test-jpg").Name = "Hidden JPG sample";+ var a = Profile("delete-a", "png");+ using var vm = f.Page(a);+ var b = Profile("delete-b", "mp4");+ // C has the preset on its front face.+ var c = Profile("delete-c", "png");+ c.PresetIds.Add("test-wav");+ foreach (var other in new[] { b, c })+ {+ f.Store.Profiles.Add(other);+ vm.Profiles.Add(new ProfileItemViewModel(other, f.Loc));+ }+ var page = new ToolbarPage { DataContext = vm };+ var window = new Window { Width = 1080, Height = 820, Content = page };+ List<string> Shown() => page.FindControl<Border>("PaletteBox")!.GetVisualDescendants().OfType<Border>()+ .Where(x => x.Classes.Contains("chip") && x.DataContext is PaletteChip).Select(x => ((PaletteChip)x.DataContext!).PresetId).ToList();+ try+ {+ window.Show();+ RenderTests.Pump();+ vm.PaletteSearch = "Hidden";+ RenderTests.Pump();+ Assert.Contains("test-wav", Shown());+ Select(vm, b.Id);+ RenderTests.Pump();+ // Another donut starts with an empty search (#427), so type it again.+ Assert.Equal("", vm.PaletteSearch);+ vm.PaletteSearch = "Hidden";+ RenderTests.Pump();+ Assert.Contains("test-wav", Shown());+ Assert.True(vm.HasJudgement(a.Id, "test-wav"));+ Assert.True(vm.HasJudgement(b.Id, "test-wav"));+ Assert.Equal(["test-wav"], c.PresetIds);++ // As the presets page deletes: removed, then saved. Checked before any posted judging runs.+ f.Store.Presets.Remove(f.Preset("test-wav"));+ f.Store.SaveLibrary();+ Assert.False(vm.HasJudgement(a.Id, "test-wav"));+ Assert.False(vm.HasJudgement(b.Id, "test-wav"));+ Assert.Null(f.Store.FindPreset("test-wav"));+ Assert.DoesNotContain("test-wav", c.PresetIds);++ Dispatcher.UIThread.RunJobs();+ foreach (var id in new[] { a.Id, b.Id })+ {+ Select(vm, id);+ RenderTests.Pump();+ vm.PaletteSearch = "Hidden";+ RenderTests.Pump();+ var shown = Shown();+ Assert.DoesNotContain("test-wav", shown);+ Assert.Contains("test-jpg", shown);+ }+ }+ finally+ {+ window.Close();+ }+ }++ [AvaloniaFact]+ public void Moving_slices_and_flipping_keep_judgement_cache()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ using var vm = f.Page(Profile("moving-a", "png"));+ Dispatcher.UIThread.RunJobs();+ var profile = vm.SelectedProfile!.Profile;+ string[] moved = ["test-jpg", "test-mp4", "test-rotate-png", "test-motion"];+ Assert.All(moved, id => Assert.True(vm.HasJudgement("moving-a", id)));+ var observed = new List<string>();+ vm.JudgementObserved = (_, preset) => observed.Add(preset);++ // Front: two slices, then the first moved onto the second.+ Assert.True(vm.Insert("test-jpg", 0));+ Assert.True(vm.Insert("test-mp4", 1));+ vm.Move(0, 1);+ Assert.Equal(["test-mp4", "test-jpg"], profile.PresetIds);++ // Back: the same, the other way round.+ vm.EditingBack = true;+ Assert.True(vm.Insert("test-rotate-png", 0));+ Assert.True(vm.Insert("test-motion", 1));+ vm.Move(1, 0);+ Assert.Equal(["test-motion", "test-rotate-png"], profile.BackPresetIds);+ Assert.Equal(["test-mp4", "test-jpg"], profile.PresetIds);+ Assert.DoesNotContain(vm.Palette, c => moved.Contains(c.PresetId));++ // Flipped back to the front: both faces stay off the palette until a slice comes off.+ vm.EditingBack = false;+ Assert.DoesNotContain(vm.Palette, c => moved.Contains(c.PresetId));+ vm.RemoveAt(0);+ Assert.Equal(["test-jpg"], profile.PresetIds);+ Assert.Equal(["test-motion", "test-rotate-png"], profile.BackPresetIds);+ Assert.Contains(vm.Palette, c => c.PresetId == "test-mp4");+ Assert.All(moved, id => Assert.True(vm.HasJudgement("moving-a", id)));+ Dispatcher.UIThread.RunJobs();+ Assert.Empty(observed);+ }++ [AvaloniaFact]+ public void Editing_a_preset_invalidates_its_id_in_every_profile()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var a = Profile("edit-a", "png");+ using var vm = f.Page(a);+ var b = Profile("edit-b", "png");+ f.Store.Profiles.Add(b);+ vm.Profiles.Add(new ProfileItemViewModel(b, f.Loc));+ Dispatcher.UIThread.RunJobs();+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Select(vm, a.Id);+ var observed = new List<(string, string)>();+ vm.JudgementObserved = (id, preset) => observed.Add((id, preset));+ var preset = f.Preset("test-wav");+ preset.TargetFormat = "jpg";+ vm.PresetEdited(preset);+ Dispatcher.UIThread.RunJobs();+ Assert.Contains(vm.Palette, c => c.PresetId == preset.Id && c.Use == PresetUse.Usable);+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.Equal([("edit-a", preset.Id), ("edit-b", preset.Id)], observed);+ Assert.DoesNotContain(observed, x => x.Item2 == "test-jpg");+ }++ [AvaloniaFact]+ public void Extension_save_invalidates_only_its_profile()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var a = Profile("extensions-a", "mp4");+ using var vm = f.Page(a);+ var b = Profile("extensions-b", "png");+ f.Store.Profiles.Add(b);+ vm.Profiles.Add(new ProfileItemViewModel(b, f.Loc));+ Dispatcher.UIThread.RunJobs();+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Select(vm, a.Id);+ var observed = new List<(string, string)>();+ vm.JudgementObserved = (id, preset) => observed.Add((id, preset));+ int OnA() => observed.Count(x => x == (a.Id, "test-jpg"));+ // B (PNG) keeps its cached judgement: the chip is there at once, and nothing is judged for B.+ void BStaysCached()+ {+ Select(vm, b.Id);+ Assert.Contains(vm.Palette, c => c.PresetId == "test-jpg" && c.Use == PresetUse.Usable);+ Dispatcher.UIThread.RunJobs();+ Assert.DoesNotContain(observed, x => x.Item1 == b.Id);+ Select(vm, a.Id);+ Dispatcher.UIThread.RunJobs();+ }++ vm.ExtensionTags!.AddCommand.Execute("png");+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(1, OnA());+ AssertJudgedAfresh(f, vm, "test-jpg", PresetUse.Usable);+ BStaysCached();+ vm.ExtensionTags!.RemoveCommand.Execute(vm.ExtensionTags.Tags.Single(t => t.Value == "png"));+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(2, OnA());+ Assert.DoesNotContain(vm.Palette, c => c.PresetId == "test-jpg");+ AssertJudgedAfresh(f, vm, "test-jpg", PresetUse.Unusable);+ BStaysCached();++ // The same through the mixed-selection checkboxes: checked, then unchecked.+ vm.IsMixed = true;+ Dispatcher.UIThread.RunJobs();+ var judged = OnA();+ var png = vm.MixedExtensions!.Groups.SelectMany(g => g.Extensions).First(e => e.Extension == "png");+ png.IsChecked = true;+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(judged + 1, OnA());+ AssertJudgedAfresh(f, vm, "test-jpg", PresetUse.Usable);+ BStaysCached();+ png = vm.MixedExtensions!.Groups.SelectMany(g => g.Extensions).First(e => e.Extension == "png");+ png.IsChecked = false;+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(judged + 2, OnA());+ Assert.DoesNotContain(vm.Palette, c => c.PresetId == "test-jpg");+ AssertJudgedAfresh(f, vm, "test-jpg", PresetUse.Unusable);+ BStaysCached();+ }++ [AvaloniaFact]+ public void Catalog_change_invalidates_every_profile()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var a = Profile("catalog-a", "png");+ using var vm = f.Page(a);+ var b = Profile("catalog-b", "png");+ f.Store.Profiles.Add(b);+ vm.Profiles.Add(new ProfileItemViewModel(b, f.Loc));+ Dispatcher.UIThread.RunJobs();+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Select(vm, a.Id);+ Assert.Equal(PresetUse.NeedsPackage, vm.Palette.Single(c => c.PresetId == "test-mp4").Use);+ var observed = new List<(string, string)>();+ vm.JudgementObserved = (id, preset) => observed.Add((id, preset));+ f.Gated.Available = true;+ f.Catalog.Refresh();+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(PresetUse.Usable, vm.Palette.Single(c => c.PresetId == "test-mp4").Use);+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(1, observed.Count(x => x == (a.Id, "test-mp4")));+ Assert.Equal(1, observed.Count(x => x == (b.Id, "test-mp4")));+ }++ [AvaloniaFact]+ public void Resetting_a_built_in_donut_invalidates_only_that_profile()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var images = f.Store.Profiles.Single(p => p.Id == "images");+ images.Extensions = ["wav"];+ var b = Profile("reset-b", "png");+ b.IsFallback = true;+ using var vm = f.Page(b);+ Dispatcher.UIThread.RunJobs();+ Select(vm, images.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.DoesNotContain(vm.Palette, c => c.PresetId == "test-jpg");+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Select(vm, images.Id);+ var observed = new List<(string, string)>();+ vm.JudgementObserved = (id, preset) => observed.Add((id, preset));+ vm.Reset(vm.SelectedProfile!);+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(1, observed.Count(x => x == (images.Id, "test-jpg")));+ Assert.Contains(vm.Palette, c => c.PresetId == "test-jpg" && c.Use == PresetUse.Usable);+ Select(vm, b.Id);+ Assert.Contains(vm.Palette, c => c.PresetId == "test-jpg");+ Dispatcher.UIThread.RunJobs();+ Assert.DoesNotContain(observed, x => x.Item1 == b.Id);+ }++ [AvaloniaFact]+ public void Closing_a_cached_page_clears_both_profiles_and_subscriptions()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var a = Profile("closing-a", "png");+ var vm = f.Page(a);+ var b = Profile("closing-b", "mp4");+ f.Store.Profiles.Add(b);+ vm.Profiles.Add(new ProfileItemViewModel(b, f.Loc));+ Dispatcher.UIThread.RunJobs();+ Select(vm, b.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.True(vm.HasJudgement(a.Id, "test-wav"));+ Assert.True(vm.HasJudgement(b.Id, "test-wav"));+ var library = typeof(UserDataStore).GetField("LibraryChanged", BindingFlags.Instance | BindingFlags.NonPublic);+ var catalog = typeof(ConverterCatalog).GetField("Changed", BindingFlags.Instance | BindingFlags.NonPublic);+ Assert.NotNull(library);+ Assert.NotNull(catalog);+ bool Subscribed(object source, FieldInfo field) =>+ (field.GetValue(source) as EventHandler)?.GetInvocationList().Any(d => ReferenceEquals(d.Target, vm)) == true;+ Assert.True(Subscribed(f.Store, library));+ Assert.True(Subscribed(f.Catalog, catalog));+ var closed = new List<(string, string)>();+ vm.JudgementObserved = (id, preset) => closed.Add((id, preset));+ f.Store.Presets.Add(new Preset { Id = "test-late-control", TargetFormat = "jpg" });+ vm.PaletteSearch = "test-late-control";+ Dispatcher.UIThread.RunJobs();+ Assert.Contains((b.Id, "test-late-control"), closed);+ closed.Clear();+ f.Store.Presets.Add(new Preset { Id = "test-late", TargetFormat = "jpg" });+ vm.PaletteSearch = "test-late";+ Assert.False(vm.HasJudgement(b.Id, "test-late"));+ vm.Dispose();+ Assert.False(vm.HasJudgement(a.Id, "test-wav"));+ Assert.False(vm.HasJudgement(b.Id, "test-wav"));+ Assert.False(Subscribed(f.Store, library));+ Assert.False(Subscribed(f.Catalog, catalog));+ f.Store.SaveLibrary();+ f.Catalog.Refresh();+ Dispatcher.UIThread.RunJobs();+ Assert.False(vm.HasJudgement(a.Id, "test-wav"));+ Assert.Empty(closed);+ Assert.False(vm.HasJudgement(b.Id, "test-late"));++ // The page opened again: a new view model on the same library judges each profile afresh, once.+ using var reopened = new ToolbarPageViewModel(f.Store, f.Loc, AppHost.Get<WindowService>(), f.Availability, f.Catalog,+ NullLogger<ToolbarPageViewModel>.Instance);+ var observed = new List<(string, string)>();+ reopened.JudgementObserved = (id, preset) => observed.Add((id, preset));+ Select(reopened, a.Id);+ Dispatcher.UIThread.RunJobs();+ Select(reopened, b.Id);+ Dispatcher.UIThread.RunJobs();+ Select(reopened, a.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.True(reopened.HasJudgement(a.Id, "test-wav"));+ Assert.True(reopened.HasJudgement(b.Id, "test-wav"));+ Assert.True(reopened.HasJudgement(b.Id, "test-late"));+ Assert.Equal(1, observed.Count(x => x == (a.Id, "test-wav")));+ Assert.Equal(1, observed.Count(x => x == (b.Id, "test-wav")));+ Assert.Empty(closed);+ }++ [AvaloniaFact]+ public async Task Deleted_profile_loses_its_cache_entry()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var original = Profile("reused-id", "png");+ using var vm = f.Page(original);+ Dispatcher.UIThread.RunJobs();+ Assert.True(vm.HasJudgement(original.Id, "test-jpg"));+ var windows = AppHost.Get<WindowService>();+ Assert.Null(windows.Main);+ windows.ShowMain();+ try+ {+ var delete = vm.DeleteProfileCommand.ExecuteAsync(null);+ Dispatcher.UIThread.RunJobs();+ var dialog = Assert.Single(windows.Main!.OwnedWindows);+ var button = ((StackPanel)dialog.Content!).Children.OfType<StackPanel>()+ .Single().Children.OfType<Button>().Single(b => b.IsDefault);+ button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));+ await delete.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);+ Assert.False(vm.HasJudgement(original.Id, "test-jpg"));+ var replacement = Profile(original.Id, "mp4");+ f.Store.Profiles.Add(replacement);+ vm.Profiles.Add(new ProfileItemViewModel(replacement, f.Loc));+ var observed = new List<(string, string)>();+ vm.JudgementObserved = (id, preset) => observed.Add((id, preset));+ Select(vm, replacement.Id);+ Dispatcher.UIThread.RunJobs();+ Assert.Equal(1, observed.Count(x => x == (replacement.Id, "test-jpg")));+ Assert.DoesNotContain(vm.Palette, c => c.PresetId == "test-jpg");+ }+ finally+ {+ windows.Main?.Close();+ Dispatcher.UIThread.RunJobs();+ }+ }+}diff --git a/tests/Filee.App.Tests/ToolbarPaletteViewTests.cs b/tests/Filee.App.Tests/ToolbarPaletteViewTests.csnew file mode 100644index 00000000..30e6cc04--- /dev/null+++ b/tests/Filee.App.Tests/ToolbarPaletteViewTests.cs@@ -0,0 +1,636 @@+// The palette tabs, the search and the chip input on the real ToolbarPage: what the user sees and can do in the+// "available presets" column (tests/Filee.App.Tests/ToolbarEditorTests.cs checks the view model behind it).++using Avalonia;+using Avalonia.Controls;+using Avalonia.Headless;+using Avalonia.Headless.XUnit;+using Avalonia.Input;+using Avalonia.Interactivity;+using Avalonia.Threading;+using Avalonia.VisualTree;+using Filee.App.Services;+using Filee.App.ViewModels;+using Filee.App.ViewModels.Pages;+using Filee.App.Views;+using Filee.App.Views.Pages;+using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Core.Localization;+using Filee.Core.Presets;+using Filee.Core.Profiles;+using Filee.Core.Settings;+using Microsoft.Extensions.Logging.Abstractions;++namespace Filee.App.Tests;++public class ToolbarPaletteViewTests+{+ /// <summary>A ToolbarPage for a fixture view model in a window, and the controls of its palette column.</summary>+ private sealed class View : IDisposable+ {+ public View(ToolbarPageViewModel vm)+ {+ Page = new ToolbarPage { DataContext = vm };+ // In a scroll viewer, as the main window shows this page (MainWindowViewModel.PageScroll).+ Window = new Window { Width = 1080, Height = 820, Content = new ScrollViewer { Content = Page } };+ Window.Show();+ RenderTests.Pump();+ }++ public ToolbarPage Page { get; }+ public Window Window { get; }+ public ListBox Tabs => Page.FindControl<ListBox>("PaletteTabs")!;+ public TextBox Search => Page.FindControl<TextBox>("PaletteSearchBox")!;+ public Border Box => Page.FindControl<Border>("PaletteBox")!;+ public Border Ghost => Page.FindControl<Border>("Ghost")!;++ /// <summary>The chips shown in the palette box, in their order on screen.</summary>+ public List<Border> ChipBorders => Box.GetVisualDescendants().OfType<Border>()+ .Where(b => b.Classes.Contains("chip") && b.DataContext is PaletteChip).ToList();++ public List<string> Chips => ChipBorders.Select(b => ((PaletteChip)b.DataContext!).PresetId).ToList();+ public Border Chip(string id) => ChipBorders.Single(b => ((PaletteChip)b.DataContext!).PresetId == id);+ public List<PaletteTab> TabIds => Tabs.Items.Cast<PaletteTabItem>().Select(t => t.Id).ToList();+ public PaletteTab? Selected => (Tabs.SelectedItem as PaletteTabItem)?.Id;++ public Point Center(Control control) =>+ control.TranslatePoint(new Point(control.Bounds.Width / 2, control.Bounds.Height / 2), Window)!.Value;++ public void Click(Control control, MouseButton button = MouseButton.Left)+ {+ var point = Center(control);+ Window.MouseDown(point, button);+ Window.MouseUp(point, button);+ RenderTests.Pump();+ }++ /// <summary>Clicks the tab of that kind in the tab row.</summary>+ public void ClickTab(PaletteTab tab)+ {+ Assert.True(Tabs.IsEffectivelyVisible);+ var item = Tabs.Items.Cast<PaletteTabItem>().Single(t => t.Id == tab);+ Click((ListBoxItem)Tabs.ContainerFromItem(item)!);+ Assert.Equal(tab, Selected);+ }++ public void Type(string text)+ {+ Assert.True(Search.Focus());+ Search.SelectAll();+ Window.KeyTextInput(text);+ RenderTests.Pump();+ Assert.Equal(text, Search.Text);+ }++ public void ClearSearch()+ {+ Search.Clear();+ RenderTests.Pump();+ }++ /// <summary>Presses on the chip, moves into the donut's hole (a drop there appends) and lets go.</summary>+ public bool DragToDonut(Border chip)+ {+ var donut = Page.FindControl<Filee.App.Controls.DonutMenu>("Donut")!;+ // Below the window's bottom edge (how far down depends on the font): scrolled to, as a user would.+ chip.BringIntoView();+ RenderTests.Pump();+ var from = Center(chip);+ var to = Center(donut);+ var hit = Window.InputHitTest(from) as Visual;+ Assert.True(hit is not null && (hit == chip || chip.IsVisualAncestorOf(hit)),+ $"press at {from} hits {hit?.GetType().Name}");+ Window.MouseDown(from, MouseButton.Left);+ Window.MouseMove(to);+ RenderTests.Pump();+ var dragging = Ghost.IsVisible;+ Window.MouseUp(to, MouseButton.Left);+ RenderTests.Pump();+ return dragging;+ }++ public void Dispose() => Window.Close();+ }++ private static ToolbarProfile Profile(string id, params string[] extensions) => new()+ {+ Id = id,+ Name = id,+ Extensions = [.. extensions],+ PresetIds = [],+ BackPresetIds = [],+ };++ private static void DoubleTap(Border chip) => chip.RaiseEvent(new TappedEventArgs(InputElement.DoubleTappedEvent, null!));++ // The editors need a visible owner (see PresetAvailabilityTests).+ private static WindowService OpenMain()+ {+ var windows = AppHost.Get<WindowService>();+ Assert.Null(windows.Main);+ windows.ShowMain();+ return windows;+ }++ private static void CloseMain(WindowService windows)+ {+ windows.Main?.Close();+ Dispatcher.UIThread.RunJobs();+ Assert.Null(windows.Main);+ }++ private static void SaveInEditor(WindowService windows, string target)+ {+ Dispatcher.UIThread.RunJobs();+ var editor = Assert.Single(windows.Main!.OwnedWindows.OfType<PresetEditorWindow>());+ var model = Assert.IsType<PresetEditorViewModel>(editor.DataContext);+ model.Target = model.Targets.Single(t => t.Value == target);+ Dispatcher.UIThread.RunJobs();+ editor.GetVisualDescendants().OfType<Button>().Single(b => b.IsDefault).RaiseEvent(new RoutedEventArgs(Button.ClickEvent));+ Dispatcher.UIThread.RunJobs();+ Assert.True(editor.Saved);+ }++ [AvaloniaFact]+ public void All_is_the_first_selected_tab()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ using var vm = f.PageWithPalette("png");+ Dispatcher.UIThread.RunJobs();+ using var view = new View(vm);++ Assert.True(view.Tabs.IsEffectivelyVisible);+ Assert.Equal([PaletteTab.All, PaletteTab.Image, PaletteTab.Media, PaletteTab.Edit], view.TabIds);+ Assert.Same(view.Tabs.Items[0], view.Tabs.SelectedItem);+ Assert.True(((ListBoxItem)view.Tabs.ContainerFromIndex(0)!).IsSelected);+ Assert.Equal(f.Loc["toolbar.tab.all"], ((PaletteTabItem)view.Tabs.Items[0]!).Label);+ Assert.Contains("test-jpg", view.Chips);+ Assert.Contains("test-mp4", view.Chips);++ // A donut with no extensions (nothing to judge, so every kind at once): All is chosen there too.+ var everything = Profile("tabs-all");+ f.Store.Profiles.Add(everything);+ vm.Profiles.Add(new ProfileItemViewModel(everything, f.Loc));+ var profiles = view.Page.GetVisualDescendants().OfType<ListBox>().Single(l => l.Classes.Contains("soft"));+ profiles.SelectedItem = vm.Profiles[^1];+ RenderTests.Pump();+ Assert.Equal(Enum.GetValues<PaletteTab>(), view.TabIds);+ Assert.True(view.Tabs.IsEffectivelyVisible);+ Assert.Same(view.Tabs.Items[0], view.Tabs.SelectedItem);+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ }++ [AvaloniaFact]+ public void Empty_tabs_and_redundant_row_disappear()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ // Nothing converts a WAV here: only the groups are left, and no tab row.+ using var vm = f.Page(Profile("tabs-wav", "wav"));+ Dispatcher.UIThread.RunJobs();+ using var view = new View(vm);+ Assert.False(view.Tabs.IsVisible);+ Assert.Equal(["rotate", "flip", "test-group"], view.Chips);++ // PDF: one kind (Documents) that would only repeat All. Two tabs, but the row stays hidden.+ f.Store.Profiles.Add(Profile("tabs-pdf", "pdf"));+ vm.Profiles.Add(new ProfileItemViewModel(f.Store.Profiles[^1], f.Loc));+ vm.SelectedProfile = vm.Profiles[^1];+ Dispatcher.UIThread.RunJobs();+ RenderTests.Pump();+ Assert.Equal([PaletteTab.All, PaletteTab.Document], view.TabIds);+ Assert.False(view.Tabs.IsVisible);+ Assert.Equal(PaletteTab.All, view.Selected);+ Assert.Equal(["rotate", "flip", "test-group", "merge-pdf", "test-merge"], view.Chips);++ // PNG: several kinds, so the row shows.+ f.Store.Profiles.Add(Profile("tabs-png", "png"));+ vm.Profiles.Add(new ProfileItemViewModel(f.Store.Profiles[^1], f.Loc));+ vm.SelectedProfile = vm.Profiles[^1];+ Dispatcher.UIThread.RunJobs();+ RenderTests.Pump();+ Assert.True(view.Tabs.IsEffectivelyVisible);+ Assert.Equal([PaletteTab.All, PaletteTab.Image, PaletteTab.Media, PaletteTab.Edit], view.TabIds);++ // Two tabs that differ: a match of no kind and a PNG one. All has both, Image only the PNG one, so the row shows.+ f.Store.Presets.AddRange(+ [+ new() { Id = "test-odd", Name = "Odd pair unregistered", TargetFormat = "not-registered" },+ new() { Id = "test-odd-png", Name = "Odd pair PNG", TargetFormat = "png" },+ ]);+ f.Store.Profiles.Add(Profile("tabs-odd", "png"));+ vm.Profiles.Add(new ProfileItemViewModel(f.Store.Profiles[^1], f.Loc));+ vm.SelectedProfile = vm.Profiles[^1];+ Dispatcher.UIThread.RunJobs();+ RenderTests.Pump();+ view.Type("Odd pair");+ Assert.Equal([PaletteTab.All, PaletteTab.Image], view.TabIds);+ Assert.True(view.Tabs.IsEffectivelyVisible);+ Assert.Equal(PaletteTab.All, view.Selected);+ Assert.Equal(["test-odd", "test-odd-png"], view.Chips.Order());+ view.ClickTab(PaletteTab.Image);+ Assert.Equal(PaletteTab.Image, vm.SelectedTab!.Id);+ Assert.True(((ListBoxItem)view.Tabs.ContainerFromIndex(1)!).IsFocused);+ Assert.Equal(["test-odd-png"], view.Chips);++ // Back to the WAV donut: the row hides again, and Tab from the search box never lands on one of its tabs.+ vm.SelectedProfile = vm.Profiles.Single(p => p.Profile.Id == "tabs-wav");+ view.ClearSearch();+ Assert.False(view.Tabs.IsVisible);+ Assert.True(view.Search.Focus());+ for (var i = 0; i < 4; i++)+ {+ view.Window.KeyPress(Key.Tab, RawInputModifiers.None, PhysicalKey.Tab, null);+ view.Window.KeyRelease(Key.Tab, RawInputModifiers.None, PhysicalKey.Tab, null);+ RenderTests.Pump();+ var focused = view.Window.FocusManager?.GetFocusedElement() as Visual;+ Assert.False(focused is not null && (focused == view.Tabs || view.Tabs.IsVisualAncestorOf(focused)),+ $"focus on {focused?.GetType().Name} in the hidden tab row");+ }+ }++ [AvaloniaFact]+ public void Audio_donut_tabs_follow_its_real_presets()+ {+ // The built-in audio donut with the real converters. Its presets change as built-ins are added, so this checks+ // the rules rather than a fixed list: each kind tab holds exactly All's chips of that kind, and the row shows+ // only when more than one kind is left.+ TestServices.EnsureInitialized("en");+ var store = AppHost.Get<UserDataStore>();+ using var vm = new ToolbarPageViewModel(store, AppHost.Get<ILocalizer>(), AppHost.Get<WindowService>(),+ AppHost.Get<PresetAvailability>(), AppHost.Get<ConverterCatalog>(), NullLogger<ToolbarPageViewModel>.Instance);+ vm.SelectedProfile = vm.Profiles.Single(p => p.Profile.Id == "audio");+ Dispatcher.UIThread.RunJobs();+ using var view = new View(vm);+ var groups = store.Presets.Where(p => p.IsGroup).Select(p => p.Id).ToList();++ Assert.Equal(PaletteTab.All, view.Selected);+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ var all = view.Chips.ToList();+ Assert.Equal(groups, all.Take(groups.Count));+ var presets = all.Skip(groups.Count).ToList();+ Assert.NotEmpty(presets);+ PaletteTab KindOf(string id) => ToolbarPageViewModel.TabOf(store.FindPreset(id)!);+ var kinds = ToolbarPageViewModel.TabDefinitions.Select(d => d.Id).Where(t => presets.Any(id => KindOf(id) == t)).ToList();+ Assert.Equal([PaletteTab.All, .. kinds], view.TabIds);+ Assert.Equal(kinds.Count > 1, view.Tabs.IsVisible);++ foreach (var kind in kinds)+ {+ vm.SelectedTab = vm.Tabs.Single(t => t.Id == kind);+ RenderTests.Pump();+ Assert.Equal([.. groups, .. presets.Where(id => KindOf(id) == kind)], view.Chips);+ }+ }++ [AvaloniaFact]+ public void Groups_lead_every_tab_and_tools_use_edit()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ f.Store.Presets.AddRange(+ [+ new() { Id = "tool-clip", Kind = PresetKind.Tool, TargetFormat = "mp4" },+ new() { Id = "tool-join", Kind = PresetKind.Tool, TargetFormat = "mp4" },+ new() { Id = "test-same", TargetFormat = BuiltInData.SameAsSource },+ // A target no format is registered for: in All only, under no kind.+ new() { Id = "test-unregistered", TargetFormat = "not-registered" },+ ]);+ // No extensions: nothing is judged, every kind has presets.+ using var vm = f.Page(Profile("tabs-all"));+ using var view = new View(vm);+ var groups = f.Store.Presets.Where(p => p.IsGroup).Select(p => p.Id).ToList();+ Assert.Equal(Enum.GetValues<PaletteTab>(), view.TabIds);++ var shown = new Dictionary<PaletteTab, List<string>>();+ foreach (var tab in Enum.GetValues<PaletteTab>())+ {+ view.ClickTab(tab);+ var chips = view.Chips;+ Assert.Equal(groups, chips.Take(groups.Count));+ Assert.DoesNotContain(chips.Skip(groups.Count), id => groups.Contains(id));+ shown[tab] = chips.Skip(groups.Count).ToList();+ }+ foreach (var tool in new[] { "tool-crop", "tool-clip", "tool-join", "test-same" })+ {+ Assert.Contains(tool, shown[PaletteTab.Edit]);+ Assert.DoesNotContain(tool, shown[PaletteTab.Media]);+ Assert.DoesNotContain(tool, shown[PaletteTab.Image]);+ }+ Assert.Contains("to-png", shown[PaletteTab.Image]);+ Assert.Contains("remove-background", shown[PaletteTab.Image]);+ Assert.DoesNotContain("to-png", shown[PaletteTab.Edit]);+ Assert.Contains("to-pdf", shown[PaletteTab.Document]);+ Assert.Contains("to-zip", shown[PaletteTab.Archive]);++ // Every chip with a kind is under exactly one tab; together they are All without the chips of no kind.+ var kinds = shown.Where(s => s.Key != PaletteTab.All).SelectMany(s => s.Value).ToList();+ Assert.Equal(kinds.Count, kinds.Distinct().Count());+ var noKind = shown[PaletteTab.All].Except(kinds).ToList();+ Assert.Contains("test-unregistered", noKind);+ Assert.All(noKind, id =>+ {+ var preset = f.Preset(id);+ Assert.False(preset.IsTool);+ Assert.NotEqual(BuiltInData.SameAsSource, preset.TargetFormat);+ Assert.Null(FormatRegistry.FindById(preset.TargetFormat));+ });+ Assert.Equal(shown[PaletteTab.All].Except(noKind).Order(), kinds.Order());+ }++ [AvaloniaFact]+ public void Search_finds_hidden_presets_across_tabs()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ f.Preset("test-wav").Name = "Hidden WAV sample";+ // A second match of another kind keeps the tab row up while searching (one kind alone would hide it).+ f.Preset("test-jpg").Name = "Hidden JPG sample";+ using var vm = f.PageWithPalette("png");+ Dispatcher.UIThread.RunJobs();+ using var view = new View(vm);+ Assert.True(vm.HasJudgement("test-palette", "test-wav"));+ Assert.DoesNotContain("test-wav", view.Chips);+ Assert.Contains(PaletteTab.Media, view.TabIds);++ view.ClickTab(PaletteTab.Image);+ Assert.Contains("test-jpg", view.Chips);+ Assert.Contains("Hidden WAV", f.Loc.DisplayName(f.Preset("test-wav")));+ view.Type("Hidden");+ Assert.Equal([PaletteTab.All, PaletteTab.Image, PaletteTab.Media], view.TabIds);+ Assert.Equal(PaletteTab.Image, view.Selected);+ Assert.Equal(["test-jpg"], view.Chips);++ view.ClickTab(PaletteTab.Media);+ Assert.Equal(["test-wav"], view.Chips);+ var chip = view.Chip("test-wav");+ Assert.Contains("dimmed", chip.Classes);+ Assert.Equal(0.55, chip.Opacity);+ Assert.Equal(f.Loc["error.no_route"], ToolTip.GetTip(chip));+ Assert.False(((PaletteChip)chip.DataContext!).CanAdd);++ // Cleared: hidden again; Media stays (the engine-gated MP4 presets) and so does the choice.+ view.ClearSearch();+ Assert.DoesNotContain("test-wav", view.Chips);+ Assert.Contains("test-mp4", view.Chips);+ Assert.Equal(PaletteTab.Media, view.Selected);+ }++ [AvaloniaFact]+ public void External_library_save_restores_selected_tab_after_rejudging()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ f.Preset("test-wav").Name = "Hidden WAV sample";+ f.Preset("test-jpg").Name = "Hidden JPG sample";+ using var vm = f.PageWithPalette("png");+ Dispatcher.UIThread.RunJobs();+ using var view = new View(vm);+ var groups = f.Store.Presets.Where(p => p.IsGroup).Select(p => p.Id).ToList();++ // Before the save: the search shows both, the WAV one dimmed under Media, the JPG one under Image.+ view.Type("Hidden");+ Assert.Equal("Hidden", view.Search.Text);+ Assert.Equal([PaletteTab.All, PaletteTab.Image, PaletteTab.Media], view.TabIds);+ view.ClickTab(PaletteTab.Media);+ var wav = view.Chip("test-wav");+ Assert.Equal(PresetUse.Unusable, ((PaletteChip)wav.DataContext!).Use);+ Assert.Contains("dimmed", wav.Classes);+ Assert.Equal(0.55, wav.Opacity);+ Assert.Equal(f.Loc["error.no_route"], ToolTip.GetTip(wav));+ view.ClickTab(PaletteTab.Image);+ Assert.Equal(["test-jpg"], view.Chips.Except(groups));+ view.ClearSearch();+ view.ClickTab(PaletteTab.Image);++ // Saved elsewhere (the open donut's editor): every judgement goes. Until they are made again, no unjudged chip+ // and no empty Image tab: All is chosen. No jobs run here (they would judge), only the layout.+ f.Preset("test-wav").TargetFormat = "jpg";+ f.Store.SaveLibrary();+ view.Window.UpdateLayout();+ Assert.Equal("", view.Search.Text);+ Assert.DoesNotContain(PaletteTab.Image, view.TabIds);+ Assert.Equal(PaletteTab.All, view.Selected);+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);+ Assert.Equal(groups, view.Chips);++ // Judged again: Image is back with its chips, and chosen again.+ Dispatcher.UIThread.RunJobs();+ view.Window.UpdateLayout();+ Assert.Contains(PaletteTab.Image, view.TabIds);+ Assert.Equal(PaletteTab.Image, view.Selected);+ Assert.Equal(PaletteTab.Image, vm.SelectedTab!.Id);+ Assert.Contains("test-jpg", view.Chips);+ Assert.Contains("test-wav", view.Chips);++ // Searched again: both are Image presets now, so the row would only repeat All. It hides and All is chosen.+ view.Type("Hidden");+ Dispatcher.UIThread.RunJobs();+ RenderTests.Pump();+ Assert.Equal("Hidden", view.Search.Text);+ Assert.Equal([PaletteTab.All, PaletteTab.Image], view.TabIds);+ Assert.False(view.Tabs.IsVisible);+ Assert.Equal(PaletteTab.All, view.Selected);+ Assert.Equal(["test-jpg", "test-wav"], view.Chips.Except(groups).Order());+ var session = f.Availability.ForPalette([PresetAvailabilityTests.Fixture.Format("png")]);+ foreach (var id in new[] { "test-jpg", "test-wav" })+ {+ var expected = session.Judge(f.Preset(id));+ var border = view.Chip(id);+ var chip = (PaletteChip)border.DataContext!;+ Assert.Equal(expected.Use, chip.Use);+ Assert.Equal(expected.Use != PresetUse.Usable, border.Classes.Contains("dimmed"));+ Assert.Equal(expected.Use != PresetUse.Usable ? 0.55 : 1, border.Opacity);+ Assert.Equal(expected.Reason, ToolTip.GetTip(border));+ }+ Assert.Equal(PresetUse.Usable, ((PaletteChip)view.Chip("test-wav").DataContext!).Use);+ }++ [AvaloniaFact]+ public void Profile_change_resets_tab_but_face_flip_keeps_it()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ var jpg = Profile("tabs-jpg", "jpg");+ using var vm = f.Page(jpg);+ var png = Profile("tabs-png", "png");+ f.Store.Profiles.Add(png);+ vm.Profiles.Add(new ProfileItemViewModel(png, f.Loc));+ Dispatcher.UIThread.RunJobs();+ using var view = new View(vm);+ var faces = view.Page.FindControl<Border>("FaceSwitch")!.GetVisualDescendants().OfType<RadioButton>().ToList();+ var profiles = view.Page.GetVisualDescendants().OfType<ListBox>().Single(l => l.Classes.Contains("soft"));+ Assert.Equal([PaletteTab.All, PaletteTab.Media, PaletteTab.Edit], view.TabIds);+ // PNG judged once: going there later shows its tabs (Video & audio too) at once, so only the reset makes it All.+ profiles.SelectedItem = vm.Profiles.Single(p => p.Profile == png);+ Dispatcher.UIThread.RunJobs();+ profiles.SelectedItem = vm.Profiles.Single(p => p.Profile == jpg);+ RenderTests.Pump();+ Assert.Equal([PaletteTab.All, PaletteTab.Media, PaletteTab.Edit], view.TabIds);++ view.ClickTab(PaletteTab.Media);+ view.Click(faces[1]);+ Assert.True(vm.EditingBack);+ Assert.Equal(PaletteTab.Media, view.Selected);+ Assert.Equal(["rotate", "flip", "test-group", "extract-motion", "test-motion"], view.Chips);+ view.Click(faces[0]);+ Assert.False(vm.EditingBack);+ Assert.Equal(PaletteTab.Media, view.Selected);++ profiles.SelectedItem = vm.Profiles.Single(p => p.Profile == png);+ RenderTests.Pump();+ Assert.Contains(PaletteTab.Media, view.TabIds);+ Assert.True(view.Tabs.IsEffectivelyVisible);+ Assert.Equal(PaletteTab.All, view.Selected);+ Assert.Contains("test-jpg", view.Chips);++ // Back on JPG: All again. Its only edit preset goes on the donut, the Edit tab empties and All takes over.+ profiles.SelectedItem = vm.Profiles.Single(p => p.Profile == jpg);+ RenderTests.Pump();+ Assert.Equal(PaletteTab.All, view.Selected);+ view.ClickTab(PaletteTab.Edit);+ Assert.Equal(["rotate", "flip", "test-group", "tool-crop"], view.Chips);+ DoubleTap(view.Chip("tool-crop"));+ RenderTests.Pump();+ Assert.Equal(["tool-crop"], jpg.PresetIds);+ Assert.DoesNotContain(PaletteTab.Edit, view.TabIds);+ Assert.Equal(PaletteTab.All, view.Selected);+ Assert.Equal(["rotate", "flip", "test-group", "extract-motion", "test-motion"], view.Chips);+ }++ [AvaloniaFact]+ public void Unusable_blocks_add_but_allows_edit()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ f.Preset("test-wav").Name = "Hidden WAV sample";+ using var vm = f.PageWithPalette("png");+ Dispatcher.UIThread.RunJobs();+ using var view = new View(vm);+ List<string> Slices() => vm.SelectedProfile!.Profile.PresetIds;+ view.Type("Hidden WAV");+ var unusable = view.Chip("test-wav");+ var chip = (PaletteChip)unusable.DataContext!;+ Assert.Equal(PresetUse.Unusable, chip.Use);+ Assert.False(chip.CanAdd);+ Assert.Contains("dimmed", unusable.Classes);+ Assert.Equal(0.55, unusable.Opacity);+ Assert.Equal(f.Loc["error.no_route"], ToolTip.GetTip(unusable));++ // Neither a double-click nor a drag onto the donut adds it; the drag doesn't even start.+ DoubleTap(unusable);+ RenderTests.Pump();+ Assert.Empty(Slices());+ Assert.False(view.DragToDonut(unusable));+ Assert.Empty(Slices());++ // A right-click still opens its editor.+ var windows = OpenMain();+ try+ {+ view.Click(unusable, MouseButton.Right);+ Dispatcher.UIThread.RunJobs();+ var editor = Assert.Single(windows.Main!.OwnedWindows.OfType<PresetEditorWindow>());+ Assert.IsType<PresetEditorViewModel>(editor.DataContext);+ editor.Close();+ Dispatcher.UIThread.RunJobs();+ Assert.Empty(windows.Main!.OwnedWindows.OfType<PresetEditorWindow>());+ }+ finally { CloseMain(windows); }++ // A preset that only needs an engine download goes on by drag and by double-click.+ view.ClearSearch();+ var needsPackage = view.Chip("test-mp4");+ Assert.Equal(PresetUse.NeedsPackage, ((PaletteChip)needsPackage.DataContext!).Use);+ Assert.True(view.DragToDonut(needsPackage));+ Assert.Equal(["test-mp4"], Slices());+ var other = view.Chip("to-mp4");+ Assert.Equal(PresetUse.NeedsPackage, ((PaletteChip)other.DataContext!).Use);+ DoubleTap(other);+ RenderTests.Pump();+ Assert.Equal(["test-mp4", "to-mp4"], Slices());+ }++ [AvaloniaFact]+ public async Task New_group_and_unplaced_preset_select_visible_tab()+ {+ using var f = new PresetAvailabilityTests.Fixture();+ f.Preset("test-jpg").Name = "Sample JPG";+ f.Preset("test-mp4").Name = "Sample MP4";+ var profile = Profile("tabs-new", "png");+ profile.PresetIds.AddRange(["to-webp", "to-tiff", "to-bmp", "to-ico", "to-gif", "to-avif", "to-heic", "to-pdf",+ "to-docx", "to-txt", "to-md"]);+ Assert.Equal(ToolbarProfile.MaxSlices - 1, profile.PresetIds.Count);+ using var vm = f.Page(profile);+ Dispatcher.UIThread.RunJobs();+ using var view = new View(vm);+ var groups = f.Store.Presets.Where(p => p.IsGroup).Select(p => p.Id).ToList();++ // A group made while searching: the search clears, the tab stays, and the group heads its chips.+ view.ClickTab(PaletteTab.Image);+ view.Type("Sample");+ Assert.Equal([PaletteTab.All, PaletteTab.Image, PaletteTab.Media], view.TabIds);+ Assert.Equal(PaletteTab.Image, view.Selected);+ Assert.Equal(["test-jpg"], view.Chips);+ var group = new Preset { Id = "test-new-group", Kind = PresetKind.Group, SubPresetIds = ["test-jpg"] };+ vm.AddGroup(group);+ RenderTests.Pump();+ Assert.Equal("", view.Search.Text);+ Assert.Equal(PaletteTab.Image, view.Selected);+ Assert.Equal([.. groups, group.Id], view.Chips.Take(groups.Count + 1));++ var windows = OpenMain();+ try+ {+ // A free slot: the new preset goes on the donut, and the tab stays.+ var saving = vm.NewPresetCommand.ExecuteAsync(null);+ SaveInEditor(windows, "mp4");+ await saving.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);+ Dispatcher.UIThread.RunJobs();+ RenderTests.Pump();+ Assert.Equal(f.Store.Presets[^1].Id, profile.PresetIds[^1]);+ Assert.Equal(PaletteTab.Image, view.Selected);++ // A full donut: the new preset stays in the palette and its tab is chosen for it.+ Assert.Equal(ToolbarProfile.MaxSlices, profile.PresetIds.Count);+ saving = vm.NewPresetCommand.ExecuteAsync(null);+ SaveInEditor(windows, "mp4");+ await saving.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);+ Dispatcher.UIThread.RunJobs();+ RenderTests.Pump();+ var kept = f.Store.Presets[^1];+ Assert.DoesNotContain(kept.Id, profile.PresetIds);+ Assert.Equal(PaletteTab.Media, view.Selected);+ Assert.Contains(kept.Id, view.Chips);+ Assert.Equal("", view.Search.Text);++ // One this donut can't run: searched for by its name, so it shows (dimmed).+ saving = vm.NewPresetCommand.ExecuteAsync(null);+ SaveInEditor(windows, "wav");+ await saving.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);+ Dispatcher.UIThread.RunJobs();+ RenderTests.Pump();+ var unusable = f.Store.Presets[^1];+ Assert.Equal(f.Loc.DisplayName(unusable), view.Search.Text);+ Assert.Contains("dimmed", view.Chip(unusable.Id).Classes);+ Assert.False(((PaletteChip)view.Chip(unusable.Id).DataContext!).CanAdd);+ // Its name finds Media presets only: no tab row, so All (every tab of a hidden row is All's list).+ Assert.Equal([PaletteTab.All, PaletteTab.Media], view.TabIds);+ Assert.False(view.Tabs.IsVisible);+ Assert.Equal(PaletteTab.All, view.Selected);+ Assert.Equal(PaletteTab.All, vm.SelectedTab!.Id);++ // The same name on an image preset too: the search keeps two kinds, the row shows and the new preset's tab is chosen.+ f.Preset("test-jpg").Name = f.Loc.DisplayName(unusable) + " JPG";+ saving = vm.NewPresetCommand.ExecuteAsync(null);+ SaveInEditor(windows, "wav");+ await saving.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);+ Dispatcher.UIThread.RunJobs();+ RenderTests.Pump();+ var second = f.Store.Presets[^1];+ Assert.Equal(f.Loc.DisplayName(second), view.Search.Text);+ Assert.Equal([PaletteTab.All, PaletteTab.Image, PaletteTab.Media], view.TabIds);+ Assert.True(view.Tabs.IsEffectivelyVisible);+ Assert.Equal(PaletteTab.Media, view.Selected);+ Assert.Equal(PaletteTab.Media, vm.SelectedTab!.Id);+ Assert.Contains("dimmed", view.Chip(second.Id).Classes);+ Assert.DoesNotContain("test-jpg", view.Chips);+ }+ finally { CloseMain(windows); }+ }+}