Skip to content

armgit / Filee

Public Imported from GitHub
0

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.

Combo boxes keep their choice on Ctrl+Space and Ctrl+click (#107)

KnifeLemonc491712a46ea
diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.cs
index 9ad8ebec..74ac774f 100644
--- a/src/Filee.App/App.axaml.cs
+++ b/src/Filee.App/App.axaml.cs
@@ -5,6 +5,7 @@ using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
+using Filee.App.Controls;
using Filee.App.Services;
using Filee.App.Services.Triggers;
using Filee.Core.Conversion;
@@ -22,7 +23,11 @@ public partial class App : Application
private IDisposable? _convertDebounce;
private bool _selectionPending;
- public override void Initialize() => AvaloniaXamlLoader.Load(this);
+ public override void Initialize()
+ {
+ AvaloniaXamlLoader.Load(this);
+ SingleSelectionGuard.Register();
+ }
public override void OnFrameworkInitializationCompleted()
{
diff --git a/src/Filee.App/Controls/SingleSelectionGuard.cs b/src/Filee.App/Controls/SingleSelectionGuard.cs
new file mode 100644
index 00000000..6b48ef51
--- /dev/null
+++ b/src/Filee.App/Controls/SingleSelectionGuard.cs
@@ -0,0 +1,76 @@
+// Keeps combo boxes and single-selection lists from losing their selection to the toggle modifier. Avalonia treats
+// Ctrl+Space, Ctrl+Enter and Ctrl+click (Cmd on macOS) on the selected item as "toggle", which leaves a combo box
+// empty and pushes null into a setting that always has a value (#107). Multi-selection lists keep the toggle.
+//
+// A selection cleared some other way is refused by the view models (Choices.Restore); the control then shows the
+// bound value again.
+
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
+using Avalonia.Data;
+using Avalonia.Input;
+using Avalonia.Interactivity;
+using Avalonia.Threading;
+
+namespace Filee.App.Controls;
+
+public static class SingleSelectionGuard
+{
+ private static bool _registered;
+
+ /// <summary>Installs the class handlers once for every combo box and list box of the application.</summary>
+ public static void Register()
+ {
+ if (_registered)
+ return;
+ _registered = true;
+ // Tunnel: the item's own handlers (which toggle) run in the bubble phase.
+ InputElement.KeyDownEvent.AddClassHandler<ListBoxItem>(OnKeyDown, RoutingStrategies.Tunnel);
+ InputElement.PointerPressedEvent.AddClassHandler<ListBoxItem>(OnPointer, RoutingStrategies.Tunnel);
+ InputElement.PointerReleasedEvent.AddClassHandler<ListBoxItem>(OnPointer, RoutingStrategies.Tunnel);
+ SelectingItemsControl.SelectedItemProperty.Changed.AddClassHandler<SelectingItemsControl>(OnSelectedItemChanged);
+ }
+
+ /// <summary>
+ /// The view model puts its value back while the control is still clearing its selection, which the control misses:
+ /// once it is done, it reads the bound value again (still null when the view model took the null).
+ /// </summary>
+ private static void OnSelectedItemChanged(SelectingItemsControl control, AvaloniaPropertyChangedEventArgs e)
+ {
+ if (e.NewValue is null && e.OldValue is not null && control is ComboBox or ListBox
+ && BindingOperations.GetBindingExpressionBase(control, SelectingItemsControl.SelectedItemProperty) is { } binding)
+ Dispatcher.UIThread.Post(binding.UpdateTarget);
+ }
+
+ private static void OnKeyDown(ListBoxItem item, KeyEventArgs e)
+ {
+ if (ItemSelectionEventTriggers.ShouldTriggerSelection(item, e) && WouldDeselect(item, e))
+ Keep(item, e);
+ }
+
+ private static void OnPointer(ListBoxItem item, PointerEventArgs e)
+ {
+ if (e.GetCurrentPoint(item).Properties.PointerUpdateKind is PointerUpdateKind.LeftButtonPressed or PointerUpdateKind.LeftButtonReleased
+ && WouldDeselect(item, e))
+ Keep(item, e);
+ }
+
+ /// <summary>The selected item of a single-selection control, picked again with the toggle modifier held.</summary>
+ private static bool WouldDeselect(ListBoxItem item, RoutedEventArgs e) =>
+ !e.Handled && item.IsSelected && ItemSelectionEventTriggers.HasToggleSelectionModifier(item, e)
+ && ItemsControl.ItemsControlFromItemContainer(item) switch
+ {
+ ComboBox => true,
+ ListBox list => (list.SelectionMode & (SelectionMode.Multiple | SelectionMode.Toggle)) == 0,
+ _ => false,
+ };
+
+ /// <summary>Picking the item that is already selected: nothing changes, an open combo box closes as after any pick.</summary>
+ private static void Keep(ListBoxItem item, RoutedEventArgs e)
+ {
+ e.Handled = true;
+ if (e.RoutedEvent != InputElement.PointerPressedEvent && ItemsControl.ItemsControlFromItemContainer(item) is ComboBox combo)
+ combo.SetCurrentValue(ComboBox.IsDropDownOpenProperty, false);
+ }
+}
diff --git a/src/Filee.App/ViewModels/MainWindowViewModel.cs b/src/Filee.App/ViewModels/MainWindowViewModel.cs
index c64dcc4f..629d9a81 100644
--- a/src/Filee.App/ViewModels/MainWindowViewModel.cs
+++ b/src/Filee.App/ViewModels/MainWindowViewModel.cs
@@ -109,8 +109,13 @@ public sealed partial class MainWindowViewModel : ObservableObject
SelectedItem = item;
}
- // Pages are recreated on every visit so they always reflect the latest settings.
- partial void OnSelectedItemChanged(NavItem value) => CurrentPage = CreatePage(value);
+ // Pages are recreated on every visit so they always reflect the latest settings. A navigation list that loses its
+ // selection keeps the open page (Choices.Restore).
+ partial void OnSelectedItemChanged(NavItem? oldValue, NavItem newValue)
+ {
+ if (!Choices.Restore(oldValue, newValue, v => SelectedItem = v))
+ CurrentPage = CreatePage(newValue);
+ }
// Old pages may hold event subscriptions on long-lived services.
partial void OnCurrentPageChanged(ObservableObject? oldValue, ObservableObject newValue) => (oldValue as IDisposable)?.Dispose();
diff --git a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
index cd03b1fe..623d5b34 100644
--- a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
@@ -65,7 +65,11 @@ public sealed partial class GeneralPageViewModel : ObservableObject
public bool ShowDefaultSubfolder => DefaultLocation.Value == OutputLocation.Subfolder;
public bool ShowDefaultFolder => DefaultLocation.Value == OutputLocation.CustomFolder;
- partial void OnDefaultLocationChanged(Choice<OutputLocation> value) => Save(s => s.DefaultOutput.Location = value.Value);
+ partial void OnDefaultLocationChanged(Choice<OutputLocation>? oldValue, Choice<OutputLocation> newValue)
+ {
+ if (!Choices.Restore(oldValue, newValue, v => DefaultLocation = v))
+ Save(s => s.DefaultOutput.Location = newValue.Value);
+ }
partial void OnDefaultSubfolderChanged(string value) =>
Save(s => s.DefaultOutput.SubfolderName = string.IsNullOrWhiteSpace(value) ? "converted" : value.Trim());
@@ -96,7 +100,11 @@ public sealed partial class GeneralPageViewModel : ObservableObject
public bool CanAddModernMenu => !ModernMenuBusy && ModernMenuState is ModernContextMenuState.Off or ModernContextMenuState.Outdated;
public bool CanRemoveModernMenu => !ModernMenuBusy && ModernMenuState is ModernContextMenuState.On or ModernContextMenuState.Outdated;
- partial void OnLanguageChanged(Choice<string> value) => Save(s => s.Language = value.Value);
+ partial void OnLanguageChanged(Choice<string>? oldValue, Choice<string> newValue)
+ {
+ if (!Choices.Restore(oldValue, newValue, v => Language = v))
+ Save(s => s.Language = newValue.Value);
+ }
partial void OnStartWithSystemChanged(bool value) => Save(s => s.StartWithSystem = value);
partial void OnContextMenuChanged(bool value)
diff --git a/src/Filee.App/ViewModels/Pages/ThemePageViewModel.cs b/src/Filee.App/ViewModels/Pages/ThemePageViewModel.cs
index c93ecbd4..badc7bc3 100644
--- a/src/Filee.App/ViewModels/Pages/ThemePageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/ThemePageViewModel.cs
@@ -51,7 +51,11 @@ public sealed partial class ThemePageViewModel : ObservableObject
[ObservableProperty] private double _cornerRadius;
[ObservableProperty] private bool _reduceMotion;
- partial void OnModeChanged(Choice<ThemeMode> value) => Save(t => t.Mode = value.Value);
+ partial void OnModeChanged(Choice<ThemeMode>? oldValue, Choice<ThemeMode> newValue)
+ {
+ if (!Choices.Restore(oldValue, newValue, v => Mode = v))
+ Save(t => t.Mode = newValue.Value);
+ }
partial void OnAccentChanged(Color value)
{
var hex = $"#{value.R:X2}{value.G:X2}{value.B:X2}";
diff --git a/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs
index cf1c8bd2..9e5c8ae1 100644
--- a/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs
@@ -85,6 +85,11 @@ public sealed partial class TriggerGestureViewModel : ObservableObject
public string ThresholdText => DragThreshold == 0 ? SystemLabel : $"{DragThreshold}px";
public string Summary => GestureText.Describe(_gesture);
+ // Runs before OnPropertyChanged below, which reads every choice.
+ partial void OnKindChanged(Choice<TriggerKind>? oldValue, Choice<TriggerKind> newValue) => Choices.Restore(oldValue, newValue, v => Kind = v);
+ partial void OnButtonChanged(Choice<TriggerMouseButton>? oldValue, Choice<TriggerMouseButton> newValue) => Choices.Restore(oldValue, newValue, v => Button = v);
+ partial void OnScopeChanged(Choice<TriggerScope>? oldValue, Choice<TriggerScope> newValue) => Choices.Restore(oldValue, newValue, v => Scope = v);
+
protected override void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
diff --git a/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs b/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
index 8e60dd37..e32635cd 100644
--- a/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
@@ -333,10 +333,19 @@ public sealed partial class WatchRuleViewModel : ObservableObject
partial void OnEnabledChanged(bool value) => Change(r => r.Enabled = value);
partial void OnFolderChanged(string value) => Change(r => r.Folder = value.Trim());
- partial void OnPresetChanged(Choice<string>? value) => Change(r => r.PresetId = value?.Value ?? "");
+ // Null only while no preset was found for the rule (deleted); the combo box clearing itself doesn't forget the preset.
+ partial void OnPresetChanged(Choice<string>? oldValue, Choice<string>? newValue)
+ {
+ if (!Choices.Restore(oldValue, newValue, v => Preset = v))
+ Change(r => r.PresetId = newValue?.Value ?? "");
+ }
partial void OnIncludeSubfoldersChanged(bool value) => Change(r => r.IncludeSubfolders = value);
partial void OnOutputFolderChanged(string value) => Change(r => r.OutputFolder = value.Trim());
- partial void OnOriginalsChanged(Choice<AfterConversion> value) => Change(r => r.Originals = value.Value);
+ partial void OnOriginalsChanged(Choice<AfterConversion>? oldValue, Choice<AfterConversion> newValue)
+ {
+ if (!Choices.Restore(oldValue, newValue, v => Originals = v))
+ Change(r => r.Originals = newValue.Value);
+ }
partial void OnIncludeTextChanged(string value)
{
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 45382072..2541b32a 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -25,6 +25,23 @@ public sealed record Choice<T>(T Value, string Label, string? Detail = null) : I
public override string ToString() => Label;
}
+/// <summary>Selections bound to properties that always hold a value (a choice, the open page).</summary>
+public static class Choices
+{
+ /// <summary>
+ /// For the OnXxxChanged(oldValue, newValue) hook of such a property. A combo box or list box sets null when it
+ /// loses its selection (the selected item toggled off, its items replaced): the previous value is put back through
+ /// <paramref name="restore"/>, which also shows it in the control again. Returns true then, so the hook stops.
+ /// </summary>
+ public static bool Restore<T>(T? oldValue, T? newValue, Action<T> restore) where T : class
+ {
+ if (newValue is not null || oldValue is null)
+ return false;
+ restore(oldValue);
+ return true;
+ }
+}
+
public sealed partial class PresetEditorViewModel : ObservableObject
{
private static readonly HashSet<string> LossyTargets = ["jpg", "webp", "avif", "heic"];
@@ -181,8 +198,14 @@ public sealed partial class PresetEditorViewModel : ObservableObject
get => VideoCodecs.FirstOrDefault(c => c.Value == _videoCodecValue) ?? VideoCodecs[0];
set
{
- // The combo box clears its selection while its list is replaced.
- if (value is null || value.Value == _videoCodecValue)
+ // The combo box clears its selection while its list is replaced (or the selected item is toggled off):
+ // announcing the value shows it again.
+ if (value is null)
+ {
+ OnPropertyChanged();
+ return;
+ }
+ if (value.Value == _videoCodecValue)
return;
_videoCodecValue = value.Value;
OnPropertyChanged();
@@ -199,7 +222,12 @@ public sealed partial class PresetEditorViewModel : ObservableObject
get => AudioCodecs.FirstOrDefault(c => c.Value == _audioCodecValue) ?? AudioCodecs[0];
set
{
- if (value is null || value.Value == _audioCodecValue)
+ if (value is null)
+ {
+ OnPropertyChanged();
+ return;
+ }
+ if (value.Value == _audioCodecValue)
return;
_audioCodecValue = value.Value;
OnPropertyChanged();
@@ -290,6 +318,25 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private int _traceColors;
[ObservableProperty] private int _traceDetail;
+ // A combo box that loses its selection sets null: every choice keeps its value (see Choices.Restore).
+ partial void OnTargetChanged(Choice<string>? oldValue, Choice<string> newValue) => Choices.Restore(oldValue, newValue, v => Target = v);
+ partial void OnResizeChanged(Choice<ResizeMode>? oldValue, Choice<ResizeMode> newValue) => Choices.Restore(oldValue, newValue, v => Resize = v);
+ partial void OnRotationChanged(Choice<ImageRotation>? oldValue, Choice<ImageRotation> newValue) => Choices.Restore(oldValue, newValue, v => Rotation = v);
+ partial void OnFlipChanged(Choice<ImageFlip>? oldValue, Choice<ImageFlip> newValue) => Choices.Restore(oldValue, newValue, v => Flip = v);
+ partial void OnPageSizeChanged(Choice<PdfPageSize>? oldValue, Choice<PdfPageSize> newValue) => Choices.Restore(oldValue, newValue, v => PageSize = v);
+ partial void OnLocationChanged(Choice<OutputLocation>? oldValue, Choice<OutputLocation> newValue) => Choices.Restore(oldValue, newValue, v => Location = v);
+ partial void OnConflictChanged(Choice<ConflictPolicy>? oldValue, Choice<ConflictPolicy> newValue) => Choices.Restore(oldValue, newValue, v => Conflict = v);
+ partial void OnTiffCompressionChanged(Choice<TiffCompression>? oldValue, Choice<TiffCompression> newValue) =>
+ Choices.Restore(oldValue, newValue, v => TiffCompression = v);
+ partial void OnMediaQualityChanged(Choice<MediaQuality>? oldValue, Choice<MediaQuality> newValue) => Choices.Restore(oldValue, newValue, v => MediaQuality = v);
+ partial void OnMaxHeightChanged(Choice<int>? oldValue, Choice<int> newValue) => Choices.Restore(oldValue, newValue, v => MaxHeight = v);
+ partial void OnAudioBitrateChanged(Choice<int>? oldValue, Choice<int> newValue) => Choices.Restore(oldValue, newValue, v => AudioBitrate = v);
+ partial void OnAudioChannelsChanged(Choice<int>? oldValue, Choice<int> newValue) => Choices.Restore(oldValue, newValue, v => AudioChannels = v);
+ partial void OnSampleRateChanged(Choice<int>? oldValue, Choice<int> newValue) => Choices.Restore(oldValue, newValue, v => SampleRate = v);
+ partial void OnWavFormatChanged(Choice<WavSampleFormat>? oldValue, Choice<WavSampleFormat> newValue) => Choices.Restore(oldValue, newValue, v => WavFormat = v);
+ partial void OnArchiveLevelChanged(Choice<ArchiveLevel>? oldValue, Choice<ArchiveLevel> newValue) => Choices.Restore(oldValue, newValue, v => ArchiveLevel = v);
+ partial void OnTraceModeChanged(Choice<TracingMode>? oldValue, Choice<TracingMode> newValue) => Choices.Restore(oldValue, newValue, v => TraceMode = v);
+
private string TargetId => Target.Value;
private FormatCategory? TargetCategory => FormatRegistry.FindById(TargetId)?.Category;
private bool TargetIsImage => TargetId == BuiltInData.SameAsSource || TargetCategory == FormatCategory.Image;
diff --git a/src/Filee.App/ViewModels/RenameToolViewModel.cs b/src/Filee.App/ViewModels/RenameToolViewModel.cs
index c26b5d32..adc373aa 100644
--- a/src/Filee.App/ViewModels/RenameToolViewModel.cs
+++ b/src/Filee.App/ViewModels/RenameToolViewModel.cs
@@ -187,9 +187,11 @@ public sealed partial class RenameStepViewModel : ObservableObject
_ => "watch.ph.replace",
});
- partial void OnKindChanged(Choice<RenameKind> value)
+ partial void OnKindChanged(Choice<RenameKind>? oldValue, Choice<RenameKind> newValue)
{
- Step.Kind = value.Value;
+ if (Choices.Restore(oldValue, newValue, v => Kind = v))
+ return;
+ Step.Kind = newValue.Value;
OnPropertyChanged(nameof(ShowFind));
OnPropertyChanged(nameof(ShowReplace));
OnPropertyChanged(nameof(ShowArrow));
diff --git a/tests/Filee.App.Tests/SelectionGuardTests.cs b/tests/Filee.App.Tests/SelectionGuardTests.cs
new file mode 100644
index 00000000..5ecc80da
--- /dev/null
+++ b/tests/Filee.App.Tests/SelectionGuardTests.cs
@@ -0,0 +1,282 @@
+// Combo boxes and the navigation list keep their selection when the selected item is picked again with the toggle
+// modifier (Ctrl+Space / Ctrl+click, Cmd on macOS), and the settings behind them never become null (#107).
+
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Headless.XUnit;
+using Avalonia.Input;
+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.Localization;
+using Filee.Core.Platform;
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+
+namespace Filee.App.Tests;
+
+public class SelectionGuardTests
+{
+ private static void Pump()
+ {
+ for (var i = 0; i < 10; i++)
+ {
+ Dispatcher.UIThread.RunJobs();
+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();
+ }
+ }
+
+ /// <summary>Ctrl on Windows and Linux, Cmd on macOS: what Avalonia reads as "toggle the selection".</summary>
+ private static RawInputModifiers Toggle(TopLevel top) =>
+ (RawInputModifiers)(top.GetPlatformSettings() ?? Application.Current!.PlatformSettings)!.HotkeyConfiguration.CommandModifiers;
+
+ private static void CtrlSpace(Window window)
+ {
+ window.KeyPress(Key.Space, Toggle(window), PhysicalKey.Space, " ");
+ window.KeyRelease(Key.Space, Toggle(window), PhysicalKey.Space, " ");
+ Pump();
+ }
+
+ private static Point Middle(Control control, Visual to) =>
+ control.TranslatePoint(new Point(control.Bounds.Width / 2, control.Bounds.Height / 2), to)!.Value;
+
+ private static (Window Window, TriggerGestureViewModel Gesture, ComboBox Kind) ShowTriggers()
+ {
+ TestServices.EnsureInitialized("en");
+ var vm = new TriggersPageViewModel(AppHost.Get<UserDataStore>(), AppHost.Get<ILocalizer>());
+ var window = new Window { Content = new TriggersPage { DataContext = vm }, Width = 900, Height = 900 };
+ window.Show();
+ Pump();
+ var gesture = vm.Gestures[0];
+ var kind = window.GetVisualDescendants().OfType<ComboBox>().First(c => ReferenceEquals(c.ItemsSource, gesture.Kinds));
+ return (window, gesture, kind);
+ }
+
+ [AvaloniaFact]
+ public void Ctrl_space_twice_on_a_combo_box_keeps_its_choice()
+ {
+ var (window, gesture, kind) = ShowTriggers();
+ try
+ {
+ var before = gesture.Kind;
+ var changes = 0;
+ kind.SelectionChanged += (_, _) => changes++;
+ Assert.True(kind.Focus(NavigationMethod.Tab));
+
+ CtrlSpace(window); // opens the drop-down on the selected item
+ CtrlSpace(window); // picks that item again: used to clear the selection
+ CtrlSpace(window);
+ CtrlSpace(window);
+
+ Assert.Same(before, gesture.Kind);
+ Assert.Same(before, kind.SelectedItem);
+ Assert.Equal(0, changes); // never cleared, not just put back
+ Assert.False(kind.IsDropDownOpen);
+ Assert.Equal(before.Value, gesture.Gesture.Kind);
+ Assert.Empty(DataValidationErrors.GetErrors(kind) ?? []);
+ }
+ finally
+ {
+ window.Close();
+ }
+ }
+
+ [AvaloniaFact]
+ public void Ctrl_clicking_the_selected_item_of_an_open_combo_box_keeps_it_and_closes_the_drop_down()
+ {
+ var (window, gesture, kind) = ShowTriggers();
+ try
+ {
+ var before = gesture.Kind;
+ kind.IsDropDownOpen = true;
+ Pump();
+ var changes = 0;
+ kind.SelectionChanged += (_, _) => changes++;
+ var item = (ComboBoxItem)kind.ContainerFromItem(before)!;
+ var root = TopLevel.GetTopLevel(item)!;
+ var at = Middle(item, root);
+ root.MouseDown(at, MouseButton.Left, Toggle(root));
+ root.MouseUp(at, MouseButton.Left, Toggle(root));
+ Pump();
+
+ Assert.Same(before, gesture.Kind);
+ Assert.Same(before, kind.SelectedItem);
+ Assert.Equal(0, changes);
+ Assert.False(kind.IsDropDownOpen);
+ }
+ finally
+ {
+ window.Close();
+ }
+ }
+
+ [AvaloniaFact]
+ public void A_combo_box_cleared_anyway_shows_its_choice_again()
+ {
+ var (window, gesture, kind) = ShowTriggers();
+ try
+ {
+ var before = gesture.Kind;
+ kind.SelectedItem = null; // e.g. an Avalonia path the guard does not know
+ Pump();
+
+ Assert.Same(before, gesture.Kind);
+ Assert.Same(before, kind.SelectedItem);
+ Assert.Empty(DataValidationErrors.GetErrors(kind) ?? []);
+ }
+ finally
+ {
+ window.Close();
+ }
+ }
+
+ [AvaloniaFact]
+ public void Ctrl_clicking_the_open_page_in_the_navigation_keeps_it_open()
+ {
+ TestServices.EnsureInitialized("en");
+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<ILocalizer>(), AppHost.Get<UpdateService>());
+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };
+ window.Show();
+ Pump();
+ try
+ {
+ var nav = window.GetVisualDescendants().OfType<ListBox>().First(l => l.Classes.Contains("nav"));
+ var home = vm.SelectedItem;
+ var page = vm.CurrentPage;
+ var changes = 0;
+ nav.SelectionChanged += (_, _) => changes++;
+ var at = Middle(nav.ContainerFromItem(home)!, window);
+ window.MouseDown(at, MouseButton.Left, Toggle(window));
+ window.MouseUp(at, MouseButton.Left, Toggle(window));
+ Pump();
+ Assert.Same(home, vm.SelectedItem);
+ Assert.Same(page, vm.CurrentPage);
+ Assert.Equal(0, changes);
+
+ // Ctrl+clicking another page still opens it.
+ at = Middle(nav.ContainerFromItem(vm.Items[1])!, window);
+ window.MouseDown(at, MouseButton.Left, Toggle(window));
+ window.MouseUp(at, MouseButton.Left, Toggle(window));
+ Pump();
+ Assert.Same(vm.Items[1], vm.SelectedItem);
+ }
+ finally
+ {
+ window.Close();
+ }
+ }
+
+ [AvaloniaFact]
+ public void Multi_selection_lists_still_toggle()
+ {
+ TestServices.EnsureInitialized("en");
+ var list = new ListBox { ItemsSource = new[] { "a", "b", "c" }, SelectionMode = SelectionMode.Multiple };
+ var window = new Window { Content = list, Width = 300, Height = 300 };
+ window.Show();
+ Pump();
+ try
+ {
+ list.SelectedIndex = 0;
+ Pump();
+ Assert.True(list.ContainerFromIndex(0)!.Focus(NavigationMethod.Tab));
+ CtrlSpace(window);
+ Assert.Empty(list.SelectedItems!);
+ }
+ finally
+ {
+ window.Close();
+ }
+ }
+
+ [AvaloniaFact]
+ public void Choice_properties_ignore_null_and_announce_their_value_again()
+ {
+ TestServices.EnsureInitialized("en");
+ var loc = AppHost.Get<ILocalizer>();
+ var store = AppHost.Get<UserDataStore>();
+
+ var gesture = new TriggerGestureViewModel(new TriggerGesture { Button = TriggerMouseButton.Left }, loc, () => { });
+ AssertKeeps(gesture, nameof(gesture.Kind), () => gesture.Kind, v => gesture.Kind = v);
+ AssertKeeps(gesture, nameof(gesture.Button), () => gesture.Button, v => gesture.Button = v);
+ AssertKeeps(gesture, nameof(gesture.Scope), () => gesture.Scope, v => gesture.Scope = v);
+
+ var theme = new ThemePageViewModel(store, loc, AppHost.Get<IPlatformServices>());
+ AssertKeeps(theme, nameof(theme.Mode), () => theme.Mode, v => theme.Mode = v);
+
+ var general = ActivatorUtilitiesCreate<GeneralPageViewModel>();
+ AssertKeeps(general, nameof(general.Language), () => general.Language, v => general.Language = v);
+ AssertKeeps(general, nameof(general.DefaultLocation), () => general.DefaultLocation, v => general.DefaultLocation = v);
+
+ var editor = new PresetEditorViewModel(store.FindPreset("to-png")!, loc);
+ AssertKeeps(editor, nameof(editor.Target), () => editor.Target, v => editor.Target = v);
+ AssertKeeps(editor, nameof(editor.Resize), () => editor.Resize, v => editor.Resize = v);
+ AssertKeeps(editor, nameof(editor.Rotation), () => editor.Rotation, v => editor.Rotation = v);
+ AssertKeeps(editor, nameof(editor.Flip), () => editor.Flip, v => editor.Flip = v);
+ AssertKeeps(editor, nameof(editor.PageSize), () => editor.PageSize, v => editor.PageSize = v);
+ AssertKeeps(editor, nameof(editor.Location), () => editor.Location, v => editor.Location = v);
+ AssertKeeps(editor, nameof(editor.Conflict), () => editor.Conflict, v => editor.Conflict = v);
+ AssertKeeps(editor, nameof(editor.TiffCompression), () => editor.TiffCompression, v => editor.TiffCompression = v);
+ AssertKeeps(editor, nameof(editor.MediaQuality), () => editor.MediaQuality, v => editor.MediaQuality = v);
+ AssertKeeps(editor, nameof(editor.MaxHeight), () => editor.MaxHeight, v => editor.MaxHeight = v);
+ AssertKeeps(editor, nameof(editor.AudioBitrate), () => editor.AudioBitrate, v => editor.AudioBitrate = v);
+ AssertKeeps(editor, nameof(editor.AudioChannels), () => editor.AudioChannels, v => editor.AudioChannels = v);
+ AssertKeeps(editor, nameof(editor.SampleRate), () => editor.SampleRate, v => editor.SampleRate = v);
+ AssertKeeps(editor, nameof(editor.WavFormat), () => editor.WavFormat, v => editor.WavFormat = v);
+ AssertKeeps(editor, nameof(editor.ArchiveLevel), () => editor.ArchiveLevel, v => editor.ArchiveLevel = v);
+ AssertKeeps(editor, nameof(editor.TraceMode), () => editor.TraceMode, v => editor.TraceMode = v);
+ AssertKeeps(editor, nameof(editor.VideoCodecChoice), () => editor.VideoCodecChoice, v => editor.VideoCodecChoice = v);
+ AssertKeeps(editor, nameof(editor.AudioCodecChoice), () => editor.AudioCodecChoice, v => editor.AudioCodecChoice = v);
+ Assert.True(editor.Apply());
+
+ var nav = new MainWindowViewModel(AppHost.Services, loc, AppHost.Get<UpdateService>());
+ AssertKeeps(nav, nameof(nav.SelectedItem), () => nav.SelectedItem, v => nav.SelectedItem = v);
+
+ var rename = new RenameToolViewModel("", "{name}", [new RenameStep()], [], (_, _, name) => name, loc);
+ var step = rename.Steps[0];
+ AssertKeeps(step, nameof(step.Kind), () => step.Kind, v => step.Kind = v);
+
+ var watch = ActivatorUtilitiesCreate<WatchFoldersPageViewModel>();
+ watch.AddCommand.Execute(null);
+ var rule = watch.Rules[^1];
+ try
+ {
+ AssertKeeps(rule, nameof(rule.Preset), () => rule.Preset!, v => rule.Preset = v);
+ AssertKeeps(rule, nameof(rule.Originals), () => rule.Originals, v => rule.Originals = v);
+ Assert.Equal(rule.Preset!.Value, rule.Rule.PresetId);
+ }
+ finally
+ {
+ store.Settings.WatchFolders.Remove(rule.Rule);
+ store.SaveSettings();
+ watch.Dispose();
+ }
+ }
+
+ private static T ActivatorUtilitiesCreate<T>() =>
+ Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance<T>(AppHost.Services);
+
+ private static void AssertKeeps<T>(System.ComponentModel.INotifyPropertyChanged vm, string property, Func<T> get, Action<T> set)
+ where T : class
+ {
+ var before = get();
+ Assert.NotNull(before);
+ var announced = false;
+ void OnChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) => announced |= e.PropertyName == property;
+ vm.PropertyChanged += OnChanged;
+ try
+ {
+ set(null!);
+ }
+ finally
+ {
+ vm.PropertyChanged -= OnChanged;
+ }
+ Assert.Equal(before, get()); // the codec choices are rebuilt on every read: equal, not the same
+ Assert.True(announced, $"{property} did not announce its value again");
+ }
+}