Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 46 additions & 6 deletions app/JustHostMC.App/Controls/Sparkline.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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,
Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion app/JustHostMC.App/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
14 changes: 13 additions & 1 deletion app/JustHostMC.App/ViewModels/NavShellViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.</summary>
public sealed class NavShellViewModel : ObservableObject {
public sealed class NavShellViewModel : ObservableObject, IAsyncDisposable {
private readonly Dictionary<string, ServerViewModelCache> _serverVmCache =
new();

Expand Down Expand Up @@ -59,4 +59,16 @@ public async Task EvictServerCacheAsync(string serverId) {
if (_serverVmCache.Remove(serverId, out var cache))
await cache.DisposeAsync();
}

/// <summary>Tears down cached server view models and the shared main view
/// model when the navigation shell closes.</summary>
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));
}
}
47 changes: 45 additions & 2 deletions app/JustHostMC.Core.Tests/MainWindowLifecycleTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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.");
Expand All @@ -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"));
}
60 changes: 60 additions & 0 deletions app/JustHostMC.Core.Tests/SparklineLifecycleTests.cs
Original file line number Diff line number Diff line change
@@ -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"));
}
Loading