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.
This commit is contained in:
maj00r
2026-11-15 21:18:20 +01:00
parent 744720d922
commit 31fc4c3fdc
5 changed files with 292 additions and 12 deletions

View File

@@ -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<bool> 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);
}
}

View File

@@ -0,0 +1,80 @@
using StarterNG.Application;
namespace StarterNG.Tests;
public class OneAtATimeTests
{
private static async Task Until(Func<bool> 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<TaskCompletionSource>();
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<IOException>(once.RunAsync);
fail = false;
await once.RunAsync();
Assert.Equal(2, runs);
Assert.False(once.IsRunning);
}
}

View File

@@ -0,0 +1,45 @@
using System;
using System.Threading.Tasks;
namespace StarterNG.Application;
/// <summary>
/// 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.
/// </summary>
public sealed class OneAtATime
{
private readonly Func<Task> _work;
private bool _running;
private bool _again;
public OneAtATime(Func<Task> 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;
}
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.IO;
namespace StarterNG.Infrastructure.Adapters;
/// <summary>
/// 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.
/// </summary>
public sealed class FolderChanges : IDisposable
{
private readonly FileSystemWatcher? _watcher;
/// <summary>Something changed, or the reports were lost and anything may have: on a thread of the pool.</summary>
public event Action? Changed;
/// <param name="folder">Watched with everything below it; a missing one is not watched.</param>
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.
}
}
/// <summary>Whether the system reports changes here at all.</summary>
public bool Watching => _watcher is not null;
public void Dispose() => _watcher?.Dispose();
}

View File

@@ -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();
}
/// <summary>
/// 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 <see cref="_sceneryLook"/>, one look at a time.
/// </summary>
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;
}
}
/// <summary>
@@ -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);
}