diff --git a/app/JustHostMC.App/Controls/Sparkline.xaml.cs b/app/JustHostMC.App/Controls/Sparkline.xaml.cs index 6e77727..b64b8b7 100644 --- a/app/JustHostMC.App/Controls/Sparkline.xaml.cs +++ b/app/JustHostMC.App/Controls/Sparkline.xaml.cs @@ -21,7 +21,15 @@ public sealed partial class Sparkline : UserControl { nameof(StrokeBrush), typeof(Brush), typeof(Sparkline), new PropertyMetadata(null, OnStrokeChanged)); - public Sparkline() => InitializeComponent(); + private INotifyCollectionChanged? _observableValues; + private bool _seriesSubscriptionAttached; + private bool _isLoaded; + + public Sparkline() { + InitializeComponent(); + Loaded += OnLoaded; + Unloaded += OnUnloaded; + } public object? Values { get => GetValue(ValuesProperty); @@ -36,11 +44,12 @@ public Brush? StrokeBrush { private static void OnValuesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var self = (Sparkline)d; - if (e.OldValue is INotifyCollectionChanged oldObservable) - oldObservable.CollectionChanged -= self.OnSeriesChanged; - if (e.NewValue is INotifyCollectionChanged newObservable) - newObservable.CollectionChanged += self.OnSeriesChanged; - self.Redraw(); + self.DetachSeries(); + self._observableValues = e.NewValue as INotifyCollectionChanged; + if (self._isLoaded) { + self.AttachSeries(); + self.Redraw(); + } } private static void OnStrokeChanged(DependencyObject d, @@ -53,7 +62,38 @@ private void OnSeriesChanged( private void OnSizeChanged(object sender, SizeChangedEventArgs e) => Redraw(); + private void OnLoaded(object sender, RoutedEventArgs e) { + _isLoaded = true; + AttachSeries(); + Redraw(); + } + + private void OnUnloaded(object sender, RoutedEventArgs e) { + _isLoaded = false; + DetachSeries(); + } + + private void AttachSeries() { + if (_seriesSubscriptionAttached || _observableValues is null) + return; + + _observableValues.CollectionChanged += OnSeriesChanged; + _seriesSubscriptionAttached = true; + } + + private void DetachSeries() { + if (!_seriesSubscriptionAttached) + return; + + if (_observableValues is not null) + _observableValues.CollectionChanged -= OnSeriesChanged; + _seriesSubscriptionAttached = false; + } + private void Redraw() { + if (!_isLoaded) + return; + Line.Points.Clear(); double width = ActualWidth; diff --git a/app/JustHostMC.App/MainWindow.xaml.cs b/app/JustHostMC.App/MainWindow.xaml.cs index cb0eac7..f4007dd 100644 --- a/app/JustHostMC.App/MainWindow.xaml.cs +++ b/app/JustHostMC.App/MainWindow.xaml.cs @@ -151,7 +151,7 @@ private async void OnClosed(object sender, WindowEventArgs args) { foreach (var server in _trackedServers.Values.ToList()) UntrackServer(server); - await Shell.Main.DisposeAsync(); + await Shell.DisposeAsync(); } private IntPtr WindowSubclassProc(IntPtr hWnd, uint uMsg, IntPtr wParam, diff --git a/app/JustHostMC.App/ViewModels/NavShellViewModel.cs b/app/JustHostMC.App/ViewModels/NavShellViewModel.cs index 19d4998..0ee03da 100644 --- a/app/JustHostMC.App/ViewModels/NavShellViewModel.cs +++ b/app/JustHostMC.App/ViewModels/NavShellViewModel.cs @@ -9,7 +9,7 @@ namespace JustHostMC.App.ViewModels; /// cref="MainViewModel"/> (the single source of the live server list) and /// raises navigation requests that the shell window fulfills by changing the /// NavigationView selection. -public sealed class NavShellViewModel : ObservableObject { +public sealed class NavShellViewModel : ObservableObject, IAsyncDisposable { private readonly Dictionary _serverVmCache = new(); @@ -59,4 +59,16 @@ public async Task EvictServerCacheAsync(string serverId) { if (_serverVmCache.Remove(serverId, out var cache)) await cache.DisposeAsync(); } + + /// Tears down cached server view models and the shared main view + /// model when the navigation shell closes. + public async ValueTask DisposeAsync() { + var caches = _serverVmCache.Values.ToArray(); + _serverVmCache.Clear(); + + var cacheDisposals = caches.Select(cache => cache.DisposeAsync().AsTask()) + .ToArray(); + var mainDisposal = Main.DisposeAsync().AsTask(); + await Task.WhenAll(cacheDisposals.Append(mainDisposal)); + } } diff --git a/app/JustHostMC.Core.Tests/MainWindowLifecycleTests.cs b/app/JustHostMC.Core.Tests/MainWindowLifecycleTests.cs index c824b39..f9758d0 100644 --- a/app/JustHostMC.Core.Tests/MainWindowLifecycleTests.cs +++ b/app/JustHostMC.Core.Tests/MainWindowLifecycleTests.cs @@ -5,7 +5,7 @@ namespace JustHostMC.Core.Tests; public class MainWindowLifecycleTests { [Fact] - public void OnClosed_CleansUpWindowBeforeAwaitingDisposal() { + public void OnClosed_CleansUpWindowBeforeAwaitingShellDisposal() { var source = File.ReadAllText(MainWindowSourcePath()); var methodStart = source.IndexOf("private async void OnClosed", StringComparison.Ordinal); @@ -20,7 +20,7 @@ public void OnClosed_CleansUpWindowBeforeAwaitingDisposal() { var lastWindowCleanup = method.IndexOf("UntrackServer(server);", StringComparison.Ordinal); var asynchronousDisposal = method.IndexOf( - "await Shell.Main.DisposeAsync();", StringComparison.Ordinal); + "await Shell.DisposeAsync();", StringComparison.Ordinal); Assert.True(lastWindowCleanup >= 0, "The final window cleanup operation was not found."); @@ -29,9 +29,52 @@ public void OnClosed_CleansUpWindowBeforeAwaitingDisposal() { "Window cleanup must complete before asynchronous disposal."); } + [Fact] + public void NavShell_DisposeAsync_ClearsCacheBeforeStartingAllDisposals() { + var source = File.ReadAllText(NavShellSourcePath()); + Assert.Contains("IAsyncDisposable", source, StringComparison.Ordinal); + + var methodStart = source.IndexOf("public async ValueTask DisposeAsync()", + StringComparison.Ordinal); + var methodEnd = source.IndexOf("\n }\n}", methodStart, + StringComparison.Ordinal); + + Assert.True(methodStart >= 0, "NavShell DisposeAsync method was not found."); + Assert.True(methodEnd > methodStart, + "NavShell DisposeAsync method end was not found."); + + var method = source[methodStart..methodEnd]; + var snapshot = method.IndexOf("_serverVmCache.Values.ToArray()", + StringComparison.Ordinal); + var clear = method.IndexOf("_serverVmCache.Clear();", + StringComparison.Ordinal); + var cacheDisposal = method.IndexOf("cache.DisposeAsync().AsTask()", + StringComparison.Ordinal); + var mainDisposal = method.IndexOf("Main.DisposeAsync().AsTask()", + StringComparison.Ordinal); + var awaitAll = method.IndexOf("await Task.WhenAll", + StringComparison.Ordinal); + + Assert.True(snapshot >= 0, "Cache values must be snapshotted for disposal."); + Assert.True(clear > snapshot, + "The cache must be cleared immediately after snapshotting."); + Assert.True(cacheDisposal > clear, + "Cached view models must be disposed after the cache is cleared."); + Assert.True(mainDisposal > cacheDisposal, + "MainViewModel disposal must start after cached disposal starts."); + Assert.True(awaitAll > mainDisposal, + "Every disposal must start before the method awaits completion."); + } + private static string MainWindowSourcePath( [CallerFilePath] string testSourcePath = "") => Path.GetFullPath(Path.Combine(Path.GetDirectoryName(testSourcePath)!, "..", "JustHostMC.App", "MainWindow.xaml.cs")); + + private static string NavShellSourcePath( + [CallerFilePath] string testSourcePath = "") => + Path.GetFullPath(Path.Combine(Path.GetDirectoryName(testSourcePath)!, + "..", "JustHostMC.App", "ViewModels", + "NavShellViewModel.cs")); } diff --git a/app/JustHostMC.Core.Tests/SparklineLifecycleTests.cs b/app/JustHostMC.Core.Tests/SparklineLifecycleTests.cs new file mode 100644 index 0000000..010151d --- /dev/null +++ b/app/JustHostMC.Core.Tests/SparklineLifecycleTests.cs @@ -0,0 +1,60 @@ +using System.Runtime.CompilerServices; +using Xunit; + +namespace JustHostMC.Core.Tests; + +public class SparklineLifecycleTests { + [Fact] + public void CollectionSubscription_IsScopedToLoadedLifetime() { + var source = File.ReadAllText(SparklineSourcePath()); + + Assert.Contains("Loaded += OnLoaded;", source, + StringComparison.Ordinal); + Assert.Contains("Unloaded += OnUnloaded;", source, + StringComparison.Ordinal); + Assert.Contains("private void AttachSeries()", source, + StringComparison.Ordinal); + Assert.Contains("private void DetachSeries()", source, + StringComparison.Ordinal); + + var unloaded = MethodBody(source, "private void OnUnloaded"); + Assert.Contains("_isLoaded = false;", unloaded, + StringComparison.Ordinal); + Assert.Contains("DetachSeries();", unloaded, + StringComparison.Ordinal); + } + + [Fact] + public void Redraw_ReturnsBeforeTouchingVisualWhenUnloaded() { + var source = File.ReadAllText(SparklineSourcePath()); + var redraw = MethodBody(source, "private void Redraw"); + + var loadedGuard = redraw.IndexOf("if (!_isLoaded)", + StringComparison.Ordinal); + var visualAccess = redraw.IndexOf("Line.Points", StringComparison.Ordinal); + + Assert.True(loadedGuard >= 0, + "Redraw must guard against an unloaded control."); + Assert.True(visualAccess > loadedGuard, + "The loaded-state guard must run before native visual access."); + } + + private static string MethodBody(string source, string signature) { + var methodStart = source.IndexOf(signature, StringComparison.Ordinal); + var methodEnd = source.IndexOf("\n private ", methodStart + 1, + StringComparison.Ordinal); + if (methodEnd < 0) + methodEnd = source.LastIndexOf("\n}", StringComparison.Ordinal); + + Assert.True(methodStart >= 0, $"{signature} was not found."); + Assert.True(methodEnd > methodStart, + $"The end of {signature} was not found."); + return source[methodStart..methodEnd]; + } + + private static string SparklineSourcePath( + [CallerFilePath] string testSourcePath = "") => + Path.GetFullPath(Path.Combine(Path.GetDirectoryName(testSourcePath)!, + "..", "JustHostMC.App", "Controls", + "Sparkline.xaml.cs")); +}