From 31fc4c3fdce565244443009cc0fc0a1c56e576aa Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 21:18:20 +0100 Subject: [PATCH 1/3] fix: scenery files are looked at when they change, not every two seconds The starter compared every file of every scenery each two seconds: on a full installation 175 sceneries and 378 files, 15-18 ms a look, thirty looks a minute with nothing changed. The system now reports changes in the scenery folder and a look follows once the burst of a save has passed, 400 ms after the last report. The reports are only a hint. A look still comes on coming back to the window and right after the simulator or its editor closes, and every 30 seconds anyway, for network drives, Wine and Linux past its limit of watches, where reports may not come. Where the folder cannot be watched at all the look stays every two seconds as before. A change reported during a look is not lost: one more look follows it. --- StarterNG.Tests/FolderChangesTests.cs | 65 +++++++++++++++ StarterNG.Tests/OneAtATimeTests.cs | 80 +++++++++++++++++++ StarterNG/Application/OneAtATime.cs | 45 +++++++++++ .../Infrastructure/Adapters/FolderChanges.cs | 55 +++++++++++++ StarterNG/MainWindow.axaml.cs | 59 +++++++++++--- 5 files changed, 292 insertions(+), 12 deletions(-) create mode 100644 StarterNG.Tests/FolderChangesTests.cs create mode 100644 StarterNG.Tests/OneAtATimeTests.cs create mode 100644 StarterNG/Application/OneAtATime.cs create mode 100644 StarterNG/Infrastructure/Adapters/FolderChanges.cs diff --git a/StarterNG.Tests/FolderChangesTests.cs b/StarterNG.Tests/FolderChangesTests.cs new file mode 100644 index 0000000..67e8dd1 --- /dev/null +++ b/StarterNG.Tests/FolderChangesTests.cs @@ -0,0 +1,65 @@ +using StarterNG.Infrastructure.Adapters; + +namespace StarterNG.Tests; + +public sealed class FolderChangesTests : IDisposable +{ + private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10); + private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-changes-" + Guid.NewGuid().ToString("N")); + + public FolderChangesTests() => Directory.CreateDirectory(Path.Combine(_root, "sub")); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + private static async Task Reported(FolderChanges changes, Action change) + { + var told = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + changes.Changed += () => told.TrySetResult(); + change(); + return await Task.WhenAny(told.Task, Task.Delay(Patience)) == told.Task; + } + + [Fact] + public async Task A_file_written_below_the_folder_is_reported() + { + string file = Path.Combine(_root, "sub", "a.scm"); + File.WriteAllText(file, "old"); + using var changes = new FolderChanges(_root); + + Assert.True(changes.Watching); + Assert.True(await Reported(changes, () => File.WriteAllText(file, "new text"))); + } + + [Fact] + public async Task A_save_through_a_renamed_temp_file_is_reported() + { + string file = Path.Combine(_root, "test.scn"); + File.WriteAllText(file, "old"); + using var changes = new FolderChanges(_root); + + Assert.True(await Reported(changes, () => + { + string temp = file + ".tmp"; + File.WriteAllText(temp, "new"); + File.Move(temp, file, overwrite: true); + })); + } + + [Fact] + public async Task A_file_removed_is_reported() + { + string file = Path.Combine(_root, "gone.scn"); + File.WriteAllText(file, "x"); + using var changes = new FolderChanges(_root); + + Assert.True(await Reported(changes, () => File.Delete(file))); + } + + [Fact] + public void A_missing_folder_is_not_watched_and_does_not_throw() + { + using var changes = new FolderChanges(Path.Combine(_root, "nowhere")); + + Assert.False(changes.Watching); + } +} diff --git a/StarterNG.Tests/OneAtATimeTests.cs b/StarterNG.Tests/OneAtATimeTests.cs new file mode 100644 index 0000000..63a8072 --- /dev/null +++ b/StarterNG.Tests/OneAtATimeTests.cs @@ -0,0 +1,80 @@ +using StarterNG.Application; + +namespace StarterNG.Tests; + +public class OneAtATimeTests +{ + private static async Task Until(Func condition) + { + var giveUp = DateTime.UtcNow.AddSeconds(5); + while (!condition()) + { + Assert.True(DateTime.UtcNow < giveUp, "waited too long"); + await Task.Delay(10); + } + } + + [Fact] + public async Task Asked_once_it_runs_once() + { + int runs = 0; + var once = new OneAtATime(() => { runs++; return Task.CompletedTask; }); + + await once.RunAsync(); + + Assert.Equal(1, runs); + Assert.False(once.IsRunning); + } + + [Fact] + public async Task Asked_while_running_it_runs_once_more_after_not_alongside() + { + int runs = 0, together = 0, most = 0; + var gates = new Queue(); + var once = new OneAtATime(async () => + { + runs++; + most = Math.Max(most, ++together); + var gate = new TaskCompletionSource(); + gates.Enqueue(gate); + await gate.Task; + together--; + }); + + var first = once.RunAsync(); + // Three requests during the first run make one more run, not three. + await once.RunAsync(); + await once.RunAsync(); + await once.RunAsync(); + Assert.Equal(1, runs); + + gates.Dequeue().SetResult(); + await Until(() => Volatile.Read(ref runs) == 2); + await Until(() => gates.Count == 1); + gates.Dequeue().SetResult(); + await first; + + Assert.Equal(2, runs); + Assert.Equal(1, most); + Assert.False(once.IsRunning); + } + + [Fact] + public async Task A_failed_run_does_not_keep_it_busy() + { + bool fail = true; + int runs = 0; + var once = new OneAtATime(() => + { + runs++; + return fail ? Task.FromException(new IOException("locked")) : Task.CompletedTask; + }); + + await Assert.ThrowsAsync(once.RunAsync); + fail = false; + await once.RunAsync(); + + Assert.Equal(2, runs); + Assert.False(once.IsRunning); + } +} diff --git a/StarterNG/Application/OneAtATime.cs b/StarterNG/Application/OneAtATime.cs new file mode 100644 index 0000000..4decd8b --- /dev/null +++ b/StarterNG/Application/OneAtATime.cs @@ -0,0 +1,45 @@ +using System; +using System.Threading.Tasks; + +namespace StarterNG.Application; + +/// +/// Runs a piece of work one at a time. Asked again while it runs, it does not start a +/// second one alongside, nor forget the request: it runs once more when the first ends, +/// however many times it was asked meanwhile. For the UI thread, which calls it alone. +/// +public sealed class OneAtATime +{ + private readonly Func _work; + private bool _running; + private bool _again; + + public OneAtATime(Func work) => _work = work; + + public bool IsRunning => _running; + + public async Task RunAsync() + { + if (_running) + { + _again = true; + return; + } + + _running = true; + try + { + do + { + _again = false; + await _work(); + } + while (_again); + } + finally + { + _running = false; + _again = false; + } + } +} diff --git a/StarterNG/Infrastructure/Adapters/FolderChanges.cs b/StarterNG/Infrastructure/Adapters/FolderChanges.cs new file mode 100644 index 0000000..77c3848 --- /dev/null +++ b/StarterNG/Infrastructure/Adapters/FolderChanges.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; + +namespace StarterNG.Infrastructure.Adapters; + +/// +/// Tells when anything in a folder or below it is written, made, removed or renamed, as +/// the system reports it. Only a hint that it is time to look: a save comes as several +/// reports, and on a network drive, under Wine or past the system's limit of watches it +/// may come as none, so whoever listens still looks now and then on its own. +/// +public sealed class FolderChanges : IDisposable +{ + private readonly FileSystemWatcher? _watcher; + + /// Something changed, or the reports were lost and anything may have: on a thread of the pool. + public event Action? Changed; + + /// Watched with everything below it; a missing one is not watched. + public FolderChanges(string folder) + { + try + { + if (!Directory.Exists(folder)) + return; + + var watcher = new FileSystemWatcher(folder) + { + IncludeSubdirectories = true, + NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName + | NotifyFilters.LastWrite | NotifyFilters.Size, + // Unpacking an update changes hundreds of files at once. + InternalBufferSize = 64 * 1024 + }; + watcher.Changed += (_, _) => Changed?.Invoke(); + watcher.Created += (_, _) => Changed?.Invoke(); + watcher.Deleted += (_, _) => Changed?.Invoke(); + watcher.Renamed += (_, _) => Changed?.Invoke(); + // Too many at once for the buffer: which ones is lost, so all are looked at. + watcher.Error += (_, _) => Changed?.Invoke(); + watcher.EnableRaisingEvents = true; + _watcher = watcher; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException + or PlatformNotSupportedException) + { + // Out of watches on Linux, or a drive that gives none: the slow look alone stays. + } + } + + /// Whether the system reports changes here at all. + public bool Watching => _watcher is not null; + + public void Dispose() => _watcher?.Dispose(); +} diff --git a/StarterNG/MainWindow.axaml.cs b/StarterNG/MainWindow.axaml.cs index 2a203ad..37cd629 100644 --- a/StarterNG/MainWindow.axaml.cs +++ b/StarterNG/MainWindow.axaml.cs @@ -14,6 +14,7 @@ using Avalonia.Threading; using Avalonia.VisualTree; using StarterNG.Classes; using StarterNG.Infrastructure; +using StarterNG.Infrastructure.Adapters; using StarterNG.Views; using StarterNG.Application; using StarterNG.Application.Abstractions; @@ -39,8 +40,16 @@ public partial class MainWindow : Window private DateTime _openedUtc = DateTime.UtcNow; private DateTime _startedUtc = DateTime.MinValue; private bool _starting; - private bool _lookingAtSceneryFiles; - private readonly DispatcherTimer _sceneryFilesTimer = new() { Interval = TimeSpan.FromSeconds(2) }; + // Scenery files: looked at when the system reports a change, once the burst a save makes + // has passed; on coming back to the window or from the simulator; and now and then anyway, + // for the drives and systems where the reports do not come - often where none come at all. + private static readonly TimeSpan SceneryQuiet = TimeSpan.FromMilliseconds(400); + private static readonly TimeSpan SceneryLookWatched = TimeSpan.FromSeconds(30); + private static readonly TimeSpan SceneryLookUnwatched = TimeSpan.FromSeconds(2); + private readonly DispatcherTimer _sceneryQuietTimer = new() { Interval = SceneryQuiet }; + private readonly DispatcherTimer _sceneryFilesTimer = new() { Interval = SceneryLookUnwatched }; + private readonly OneAtATime _sceneryLook; + private FolderChanges? _sceneryChanges; public MainWindow() { @@ -100,29 +109,57 @@ public partial class MainWindow : Window AddHandler(KeyDownEvent, OnShortcutKey, RoutingStrategies.Tunnel); AppServices.Current.State.Changed += UpdateStartButton; + _sceneryLook = new OneAtATime(LookAtSceneryFilesAsync); Opened += (_, _) => { _openedUtc = DateTime.UtcNow; UpdateStartButton(); - _sceneryFilesTimer.Start(); + WatchSceneryFiles(); FollowLastRun(); }; - Activated += (_, _) => CheckExternalSettings(); - _sceneryFilesTimer.Tick += async (_, _) => await LookAtSceneryFilesAsync(); - Closed += (_, _) => _sceneryFilesTimer.Stop(); + Activated += async (_, _) => + { + CheckExternalSettings(); + await _sceneryLook.RunAsync(); + }; + _sceneryFilesTimer.Tick += async (_, _) => await _sceneryLook.RunAsync(); + _sceneryQuietTimer.Tick += async (_, _) => + { + _sceneryQuietTimer.Stop(); + await _sceneryLook.RunAsync(); + }; + Closed += (_, _) => + { + _sceneryFilesTimer.Stop(); + _sceneryQuietTimer.Stop(); + _sceneryChanges?.Dispose(); + }; + } + + private void WatchSceneryFiles() + { + _sceneryChanges = new FolderChanges(AppServices.Current.Paths.Scenery); + // Each report puts the look off again, so a save of many files is one look after it. + _sceneryChanges.Changed += () => Dispatcher.UIThread.Post(() => + { + _sceneryQuietTimer.Stop(); + _sceneryQuietTimer.Start(); + }); + _sceneryFilesTimer.Interval = _sceneryChanges.Watching ? SceneryLookWatched : SceneryLookUnwatched; + _sceneryFilesTimer.Start(); } /// /// Scenery files changed outside the starter are picked up without a reload. Not /// with the simulator running: it is left in peace, and what it changes comes in after it. + /// Run through , one look at a time. /// private async Task LookAtSceneryFilesAsync() { - if (_lookingAtSceneryFiles || AppServices.Current.State.SimulatorRunning || !IsVisible || WindowState == WindowState.Minimized) + if (AppServices.Current.State.SimulatorRunning || !IsVisible || WindowState == WindowState.Minimized) return; - _lookingAtSceneryFiles = true; try { var services = AppServices.Current; @@ -138,10 +175,6 @@ public partial class MainWindow : Window { Diagnostics.Log("Following the scenery files", ex); } - finally - { - _lookingAtSceneryFiles = false; - } } /// @@ -700,6 +733,8 @@ public partial class MainWindow : Window FollowLastRun(); RestoreFromSimulator(); ReportIfCrashed(simulator, executable, started); + // What the simulator or its editor wrote while it ran comes in now. + _ = _sceneryLook.RunAsync(); }), TaskScheduler.Default); } From 100bbea83eefe5a5fbc96bc2d41c156bc3cea8f9 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 15:42:56 +0100 Subject: [PATCH 2/3] fix(tests): the black box text tests wait their turn with the other Avalonia ones EventTextsTests and SecurityBrakingTests from #55 ran beside the Avalonia controls collection; their AppBuilder setup raced it and 28 UI tests failed with "Setup was already called" on every runner. Co-Authored-By: Claude Opus 5.5 --- StarterNG.Tests/BlackBox/EventTextsTests.cs | 1 + StarterNG.Tests/BlackBox/SecurityBrakingTests.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/StarterNG.Tests/BlackBox/EventTextsTests.cs b/StarterNG.Tests/BlackBox/EventTextsTests.cs index d3cd3ba..9b1635f 100644 --- a/StarterNG.Tests/BlackBox/EventTextsTests.cs +++ b/StarterNG.Tests/BlackBox/EventTextsTests.cs @@ -3,6 +3,7 @@ using Eu07.BlackBox.Views; namespace StarterNG.Tests.BlackBox; +[Collection(AvaloniaControls.Name)] public class EventTextsTests { [Theory] diff --git a/StarterNG.Tests/BlackBox/SecurityBrakingTests.cs b/StarterNG.Tests/BlackBox/SecurityBrakingTests.cs index 12e0816..8fb4fa9 100644 --- a/StarterNG.Tests/BlackBox/SecurityBrakingTests.cs +++ b/StarterNG.Tests/BlackBox/SecurityBrakingTests.cs @@ -4,6 +4,7 @@ using Eu07.BlackBox.Views; namespace StarterNG.Tests.BlackBox; +[Collection(AvaloniaControls.Name)] public class SecurityBrakingTests { // as the simulator writes them: one acknowledgement for both, so the cab signalling's buzzer is the alerter's too From 2a85ca384ab47c872dd6264a01af72717fa2e277 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 15:55:22 +0100 Subject: [PATCH 3/3] refactor(scenery): the looks at the scenery files timed by a class of their own, under test When the main window looks at the scenery files - once the reports of a save stop, back at the window, now and then anyway, seldom where the system reports changes and often where it does not - is FolderLooks now, on TimeProvider timers, so the tests drive the clock. The window keeps only the look itself. A report coming as the window closes leaves the disposed timers be. Co-Authored-By: Claude Opus 5.5 --- StarterNG.Tests/FolderLooksTests.cs | 192 ++++++++++++++++++++++++ StarterNG/Infrastructure/FolderLooks.cs | 96 ++++++++++++ StarterNG/MainWindow.axaml.cs | 50 +----- 3 files changed, 296 insertions(+), 42 deletions(-) create mode 100644 StarterNG.Tests/FolderLooksTests.cs create mode 100644 StarterNG/Infrastructure/FolderLooks.cs diff --git a/StarterNG.Tests/FolderLooksTests.cs b/StarterNG.Tests/FolderLooksTests.cs new file mode 100644 index 0000000..e635bde --- /dev/null +++ b/StarterNG.Tests/FolderLooksTests.cs @@ -0,0 +1,192 @@ +using Avalonia.Controls; +using StarterNG.Infrastructure; + +namespace StarterNG.Tests; + +[Collection(AvaloniaControls.Name)] +public sealed class FolderLooksTests : IDisposable +{ + private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10); + private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-looks-" + Guid.NewGuid().ToString("N")); + private readonly ManualTime _time = new(); + private readonly Window _window; + private int _looks; + + public FolderLooksTests() + { + Directory.CreateDirectory(_root); + HeadlessDrawing.Ensure(); + _window = new Window(); + } + + public void Dispose() + { + _window.Close(); + Directory.Delete(_root, recursive: true); + } + + private FolderLooks Opened(string folder) + { + var looks = new FolderLooks(_window, () => folder, () => + { + _looks++; + return Task.CompletedTask; + }, _time); + _window.Show(); + Controls.Settle(); + _looks = 0; + return looks; + } + + private ManualTimer Quiet => _time.Timers.Single(t => t.Period == Timeout.InfiniteTimeSpan); + private ManualTimer Often => _time.Timers.Single(t => t.Period != Timeout.InfiniteTimeSpan); + + // Waited for without leaving the thread: the window belongs to it. + private static void Until(Func condition) => Assert.True(SpinWait.SpinUntil(condition, Patience), "waited too long"); + + [Fact] + public void Nothing_is_watched_before_the_window_opens() + { + _ = new FolderLooks(_window, () => _root, () => Task.CompletedTask, _time); + + Assert.Empty(_time.Timers); + } + + [Fact] + public void A_watched_folder_is_looked_at_anyway_seldom() + { + var looks = Opened(_root); + + Assert.True(looks.Watching); + Assert.Equal(FolderLooks.Watched, Often.Due); + Assert.Equal(FolderLooks.Watched, Often.Period); + Assert.Equal(Timeout.InfiniteTimeSpan, Quiet.Due); + } + + [Fact] + public void A_folder_the_system_reports_nothing_of_is_looked_at_often() + { + var looks = Opened(Path.Combine(_root, "nowhere")); + + Assert.False(looks.Watching); + Assert.Equal(FolderLooks.Unwatched, Often.Period); + } + + [Fact] + public void A_tick_looks_on_the_ui_thread_once_it_gets_there() + { + Opened(_root); + + Often.Fire(); + Assert.Equal(0, _looks); + Controls.Settle(); + + Assert.Equal(1, _looks); + } + + [Fact] + public void A_change_is_looked_at_once_the_reports_stop() + { + Opened(_root); + + File.WriteAllText(Path.Combine(_root, "test.scn"), "new"); + Until(() => Quiet.Due == FolderLooks.Quiet); + Controls.Settle(); + Assert.Equal(0, _looks); + + Quiet.Fire(); + Controls.Settle(); + + Assert.Equal(1, _looks); + } + + [Fact] + public void Coming_back_to_the_window_looks() + { + Opened(_root); + + _window.Activate(); + Controls.Settle(); + + Assert.Equal(1, _looks); + } + + [Fact] + public void Asked_it_looks() + { + var looks = Opened(_root); + + Assert.True(looks.LookAsync().IsCompletedSuccessfully); + + Assert.Equal(1, _looks); + } + + [Fact] + public void Closed_it_stops_the_timers() + { + Opened(_root); + + _window.Close(); + + Assert.Equal(2, _time.Timers.Count); + Assert.All(_time.Timers, t => Assert.True(t.Disposed)); + } + + private sealed class ManualTime : TimeProvider + { + private readonly List _timers = new(); + + public IReadOnlyList Timers + { + get + { + lock (_timers) + return _timers.ToList(); + } + } + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + var timer = new ManualTimer(() => callback(state), dueTime, period); + lock (_timers) + _timers.Add(timer); + return timer; + } + } + + private sealed class ManualTimer : ITimer + { + private readonly Action _tick; + private long _dueTicks; + + public ManualTimer(Action tick, TimeSpan due, TimeSpan period) + { + _tick = tick; + _dueTicks = due.Ticks; + Period = period; + } + + public TimeSpan Due => TimeSpan.FromTicks(Interlocked.Read(ref _dueTicks)); + public TimeSpan Period { get; private set; } + public bool Disposed { get; private set; } + + public void Fire() => _tick(); + + public bool Change(TimeSpan dueTime, TimeSpan period) + { + if (Disposed) + throw new ObjectDisposedException(nameof(ManualTimer)); + Interlocked.Exchange(ref _dueTicks, dueTime.Ticks); + Period = period; + return true; + } + + public void Dispose() => Disposed = true; + + public ValueTask DisposeAsync() + { + Dispose(); + return ValueTask.CompletedTask; + } + } +} diff --git a/StarterNG/Infrastructure/FolderLooks.cs b/StarterNG/Infrastructure/FolderLooks.cs new file mode 100644 index 0000000..e382f92 --- /dev/null +++ b/StarterNG/Infrastructure/FolderLooks.cs @@ -0,0 +1,96 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Controls; +using Avalonia.Threading; +using StarterNG.Application; +using StarterNG.Infrastructure.Adapters; + +namespace StarterNG.Infrastructure; + +/// +/// Looks at a folder's files for a window, one look at a time on the UI thread: when the system +/// reports a change, once the burst a save makes has passed; when the window comes back to the +/// front; when asked; and now and then anyway, for the drives and systems where the reports do +/// not come - often where none come at all. From the window's opening to its closing. +/// +public sealed class FolderLooks +{ + /// How long the reports have to stop for: a save comes as several of them. + public static readonly TimeSpan Quiet = TimeSpan.FromMilliseconds(400); + + /// How often it looks anyway where the system reports the changes. + public static readonly TimeSpan Watched = TimeSpan.FromSeconds(30); + + /// How often it looks where the system reports nothing. + public static readonly TimeSpan Unwatched = TimeSpan.FromSeconds(2); + + private readonly Func _folder; + private readonly OneAtATime _look; + private readonly TimeProvider _time; + private readonly object _gate = new(); + private bool _closed; + private ITimer? _quiet; + private ITimer? _often; + private FolderChanges? _changes; + + /// Looked for from its opening to its closing. + /// The folder, as it is when the window opens. + /// The look itself; it knows when it is no time to look. + /// The clock of the timers, the system's when not given. + public FolderLooks(Window window, Func folder, Func look, TimeProvider? time = null) + { + _folder = folder; + _look = new OneAtATime(look); + _time = time ?? TimeProvider.System; + window.Opened += (_, _) => Watch(); + window.Activated += async (_, _) => await LookAsync(); + window.Closed += (_, _) => Close(); + } + + /// Whether the system reports the folder's changes; not before the window opens. + public bool Watching => _changes?.Watching == true; + + /// Looks now, or once more after the look that runs. + public Task LookAsync() => _look.RunAsync(); + + private void Watch() + { + var changes = new FolderChanges(_folder()); + var often = changes.Watching ? Watched : Unwatched; + lock (_gate) + { + _changes = changes; + _quiet = _time.CreateTimer(_ => LookLater(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + _often = _time.CreateTimer(_ => LookLater(), null, often, often); + } + changes.Changed += PutOff; + } + + // Each report puts the look off again, so a save of many files is one look after it. The + // reports come on threads of the pool, and may come still as the window closes. + private void PutOff() + { + lock (_gate) + { + if (!_closed) + _quiet?.Change(Quiet, Timeout.InfiniteTimeSpan); + } + } + + // The timers tick on threads of the pool; the look belongs on the UI thread. + private void LookLater() => Dispatcher.UIThread.Post(() => _ = LookAsync()); + + private void Close() + { + FolderChanges? changes; + lock (_gate) + { + _closed = true; + _quiet?.Dispose(); + _often?.Dispose(); + changes = _changes; + } + changes?.Dispose(); + } +} diff --git a/StarterNG/MainWindow.axaml.cs b/StarterNG/MainWindow.axaml.cs index 24de4cd..1e9f75b 100644 --- a/StarterNG/MainWindow.axaml.cs +++ b/StarterNG/MainWindow.axaml.cs @@ -15,7 +15,6 @@ using Avalonia.VisualTree; using StarterNG.Classes; using StarterNG.Controls; using StarterNG.Infrastructure; -using StarterNG.Infrastructure.Adapters; using StarterNG.Views; using StarterNG.Application; using StarterNG.Application.Abstractions; @@ -41,16 +40,9 @@ public partial class MainWindow : Window private DateTime _openedUtc = DateTime.UtcNow; private DateTime _startedUtc = DateTime.MinValue; private bool _starting; - // Scenery files: looked at when the system reports a change, once the burst a save makes - // has passed; on coming back to the window or from the simulator; and now and then anyway, - // for the drives and systems where the reports do not come - often where none come at all. - private static readonly TimeSpan SceneryQuiet = TimeSpan.FromMilliseconds(400); - private static readonly TimeSpan SceneryLookWatched = TimeSpan.FromSeconds(30); - private static readonly TimeSpan SceneryLookUnwatched = TimeSpan.FromSeconds(2); - private readonly DispatcherTimer _sceneryQuietTimer = new() { Interval = SceneryQuiet }; - private readonly DispatcherTimer _sceneryFilesTimer = new() { Interval = SceneryLookUnwatched }; - private readonly OneAtATime _sceneryLook; - private FolderChanges? _sceneryChanges; + // Scenery files: looked at when they change, on coming back to the window or from the + // simulator, and now and then anyway. + private readonly FolderLooks _sceneryLooks; public MainWindow() { @@ -111,54 +103,28 @@ public partial class MainWindow : Window AddHandler(KeyDownEvent, OnTabWithNothingFocused, RoutingStrategies.Tunnel); AppServices.Current.State.Changed += UpdateStartButton; - _sceneryLook = new OneAtATime(LookAtSceneryFilesAsync); Opened += (_, _) => { _openedUtc = DateTime.UtcNow; UpdateStartButton(); - WatchSceneryFiles(); FollowLastRun(); }; - Activated += async (_, _) => + Activated += (_, _) => { CheckExternalSettings(); // Back from a build or a download: a new simulator is on the list already. if (SettingsView.IsVisible) SettingsView.RefreshExecutables(); - await _sceneryLook.RunAsync(); }; - _sceneryFilesTimer.Tick += async (_, _) => await _sceneryLook.RunAsync(); - _sceneryQuietTimer.Tick += async (_, _) => - { - _sceneryQuietTimer.Stop(); - await _sceneryLook.RunAsync(); - }; - Closed += (_, _) => - { - _sceneryFilesTimer.Stop(); - _sceneryQuietTimer.Stop(); - _sceneryChanges?.Dispose(); - }; - } - - private void WatchSceneryFiles() - { - _sceneryChanges = new FolderChanges(AppServices.Current.Paths.Scenery); - // Each report puts the look off again, so a save of many files is one look after it. - _sceneryChanges.Changed += () => Dispatcher.UIThread.Post(() => - { - _sceneryQuietTimer.Stop(); - _sceneryQuietTimer.Start(); - }); - _sceneryFilesTimer.Interval = _sceneryChanges.Watching ? SceneryLookWatched : SceneryLookUnwatched; - _sceneryFilesTimer.Start(); + // After the handlers above: back at the window, the settings are checked first. + _sceneryLooks = new FolderLooks(this, () => AppServices.Current.Paths.Scenery, LookAtSceneryFilesAsync); } /// /// Scenery files changed outside the starter are picked up without a reload. Not /// with the simulator running: it is left in peace, and what it changes comes in after it. - /// Run through , one look at a time. + /// Run through , one look at a time. /// private async Task LookAtSceneryFilesAsync() { @@ -773,7 +739,7 @@ public partial class MainWindow : Window RestoreFromSimulator(); ReportIfCrashed(simulator, executable, started); // What the simulator or its editor wrote while it ran comes in now. - _ = _sceneryLook.RunAsync(); + _ = _sceneryLooks.LookAsync(); }), TaskScheduler.Default); }