Compare commits

...

10 Commits

Author SHA1 Message Date
maj00r
7e249a7a9a fix(settings): a first start has nothing to save before the simulator starts
With no eu07.ini of the player's own, starting the simulator asked to save
changes nobody made. The UART tune box and the Vulkan device box went by
TextChanged, which Avalonia raises later from the dispatcher: the text the
page put there while loading came back as an edit once the window was shown.

Both now go by their Text property, which changes at once and is passed over
while the page loads; typing in them still counts.
2026-11-17 22:14:45 +01:00
maj00r
97a2c2c75c fix(sceneries): an .sbt in the way of terrain files that are there can go
Any terrain directive kept the scenery's .sbt, as if it brought the terrain
from elsewhere. The directive names either .sbt files, which nothing makes
again, or terrain files (.txtf) with their binary copies (.btf). A scenery
with the terrain files has no use for its own .sbt: the simulator never
writes one for it, and an old one keeps the terrain files from being used.

- An .sbt named by the directive still keeps the scenery's own.
- A .txtf, or its .btf, on disk lets the scenery's .sbt go; with neither,
  the .sbt stays and the missing .txtf is given as the reason.
2026-11-17 22:14:45 +01:00
maj00r
943b855f20 feat(warehouse): the old starter's magazyn.ini joins the warehouse at every start
The old starter read starter\magazyn.ini each time it opened and wrote it on
every change; this one kept its warehouse apart and took the file in only from
the list's menu, so a consist saved there never showed here.

- At the start, ahead of the scenery list, the consists of magazyn.ini not
  taken in before join the warehouse. Each one taken is remembered in
  userpresets.json by its name and vehicles, so one removed here stays removed
  while the old starter keeps it as it was.
- A consist changed there replaces the one here when that one is as an earlier
  start brought it; one of the same name made here stays, and the old one comes
  in beside it as "name (magazyn.ini)".
- A warehouse file that cannot be read is left alone by the import.
- The file is read as UTF-8 or code page 1250, whichever it is, by hand too.
2026-11-17 14:55:04 +01:00
maj00r
797e2e70a7 feat(sceneries): a release clears the .sbt files once, and a scenery's menu deletes its own
The simulator makes a scenery's .sbt on its first load and never checks it
against the text again, so an older simulator's file, or one made before a
scenery update, keeps showing the old terrain.

- CleanupGeneration, raised by a release, clears the .sbt files once per
  installation on the first start, ahead of the scenery list. A file goes only
  while its scenery's terrain files (*_ter.scm) are all there and no terrain
  directive brings terrain from elsewhere; an .sbt standing in for missing
  terrain stays, and the log says what is missing. Which cleanup each
  installation had is kept in sbt-cleanup.txt in the user's folder.
- "Delete SBT" in the scenery list's menu does the same for one scenery,
  asking first and refusing where nothing could make the file again.
- The .sbt is among the files a scenery is watched by, so one made or removed
  reaches the list without a reload.
2026-11-17 02:15:45 +01:00
c07ed2fb4d Merge pull request #54 from MaSzyna-EU07/feat/tapes-from-blackbox
feat(tapes): tapes from the black box, live view that keeps up, train tapes setting
2026-11-16 16:00:52 +00:00
cfea240243 Merge pull request #53 from MaSzyna-EU07/fix/scenery-file-events
fix: scenery files are looked at when they change, not every two seconds
2026-11-16 16:00:36 +00:00
maj00r
2a85ca384a 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 <noreply@anthropic.com>
2026-11-16 15:55:22 +01:00
maj00r
100bbea83e 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 <noreply@anthropic.com>
2026-11-16 15:42:56 +01:00
maj00r
c370d1509e Merge main into fix/scenery-file-events
Conflict in MainWindow.axaml.cs, the Activated handler: main (#52) refreshes the list of simulators when
the settings are shown, this branch looks at the scenery files through _sceneryLook. Both kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:02:45 +01:00
maj00r
31fc4c3fdc 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.
2026-11-15 21:18:20 +01:00
25 changed files with 1423 additions and 43 deletions

View File

@@ -0,0 +1,197 @@
using StarterNG.Infrastructure.Adapters;
using StarterNG.Infrastructure.Sceneries;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class BinaryTerrainFilesTests
{
private const string Record = "user/sbt-cleanup.txt";
private static BinaryTerrainFiles Build(InMemoryFileSystem files, string root = "game") =>
new(files, new GamePaths(root), TestLog.Over(files), Record);
private static string Scenery(string name) => $"game/scenery/{name}";
[Fact]
public void An_sbt_whose_terrain_files_are_all_there_goes()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("kato.scn"), "include kato/kato_ter.scm end\nFirstInit\n")
.WithFile(Scenery("kato/kato_ter.scm"), "node")
.WithFile(Scenery("kato.sbt"), "EU07SBT2");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Equal("kato.sbt", Assert.Single(cleanup.Deleted));
Assert.False(files.FileExists(Scenery("kato.sbt")));
}
[Fact]
public void An_sbt_standing_in_for_missing_terrain_files_stays()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile(Scenery("Lk2_Sandbox.scn"), "include nmt/nmt100_mazowieckie_ter.scm end\nFirstInit\n")
.WithFile(Scenery("lk2_sandbox.sbt"), "EU07SBT2");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Empty(cleanup.Deleted);
Assert.Equal(("lk2_sandbox.sbt", "nmt/nmt100_mazowieckie_ter.scm"), Assert.Single(cleanup.Kept));
Assert.True(files.FileExists(Scenery("lk2_sandbox.sbt")));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Terrain_included_through_another_file_is_looked_for_too(bool present)
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "include td/base.inc end\nFirstInit\n")
.WithLegacyFile(Scenery("td/base.inc"), "include td/td_ter.scm 1 2 end\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
if (present)
files.WithFile(Scenery("td/td_ter.scm"), "node");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Equal(present, cleanup.Deleted.Count == 1);
Assert.Equal(present, !files.FileExists(Scenery("td.sbt")));
}
[Fact]
public void A_missing_include_other_than_terrain_does_not_keep_the_sbt()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("tomaszewo.scn"), "include tomaszewo/modele.scm end\nFirstInit\n")
.WithLegacyFile(Scenery("tomaszewo/modele.scm"),
"include;przejazdy_kombud\\1t12m_0rog_2zar_1x_1dzw.inc;p_czernica15;0;0;0;end\n")
.WithFile(Scenery("tomaszewo.sbt"), "EU07SBT2");
Assert.Single(Build(files).CleanUpOnce(1)!.Deleted);
}
[Fact]
public void An_include_commented_out_needs_no_file()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "// include gone_ter.scm end\n/* include gone.inc end */\nFirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Single(Build(files).CleanUpOnce(1)!.Deleted);
}
[Fact]
public void A_scenery_bringing_terrain_by_a_terrain_directive_keeps_its_sbt()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "terrain td.sbt endterrain\nFirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Equal("td.sbt", Assert.Single(Build(files).CleanUpOnce(1)!.Kept).File);
}
[Theory]
[InlineData("td/teren.txtf")]
[InlineData("td/Teren.btf")]
public void An_sbt_in_the_way_of_terrain_files_that_are_there_goes(string onDisk)
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile(Scenery("td.scn"), "terrain td/teren.txtf endterrain\nFirstInit\n")
.WithFile(Scenery(onDisk), "x")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Single(Build(files).CleanUpOnce(1)!.Deleted);
Assert.False(files.FileExists(Scenery("td.sbt")));
}
[Fact]
public void An_sbt_standing_in_for_a_missing_terrain_file_stays()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "terrain td/a.txtf td/b.txtf endterrain\nFirstInit\n")
.WithFile(Scenery("td/a.txtf"), "x")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Equal(("td.sbt", "td/b.txtf"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept));
}
[Fact]
public void An_sbt_named_beside_terrain_files_keeps_the_scenery_s_own()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "terrain td/a.txtf wspolny.sbt endterrain\nFirstInit\n")
.WithFile(Scenery("td/a.txtf"), "x")
.WithFile(Scenery("wspolny.sbt"), "EU07SBT2")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
var cleanup = Build(files).CleanUpOnce(1)!;
Assert.Empty(cleanup.Deleted);
Assert.Contains(("td.sbt", "terrain wspolny.sbt"), cleanup.Kept);
}
[Fact]
public void An_sbt_of_no_scenery_stays()
{
var files = new InMemoryFileSystem()
.WithFile(Scenery("old.sbt"), "EU07SBT2");
Assert.Equal(("old.sbt", "old.scn"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept));
}
[Fact]
public void Each_generation_clears_an_installation_once()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "FirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
var sbt = Build(files);
Assert.NotNull(sbt.CleanUpOnce(1));
files.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Null(sbt.CleanUpOnce(1));
Assert.True(files.FileExists(Scenery("td.sbt")));
Assert.Single(sbt.CleanUpOnce(2)!.Deleted);
}
[Fact]
public void Generation_zero_clears_nothing()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "FirstInit\n")
.WithFile(Scenery("td.sbt"), "EU07SBT2");
Assert.Null(Build(files).CleanUpOnce(0));
Assert.True(files.FileExists(Scenery("td.sbt")));
}
[Fact]
public void Another_installation_has_a_cleanup_of_its_own()
{
var files = new InMemoryFileSystem()
.WithLegacyFile(Scenery("td.scn"), "FirstInit\n")
.WithLegacyFile("other/scenery/td.scn", "FirstInit\n")
.WithFile("other/scenery/td.sbt", "EU07SBT2");
Assert.NotNull(Build(files).CleanUpOnce(1));
Assert.Single(Build(files, "other").CleanUpOnce(1)!.Deleted);
}
[Fact]
public void One_scenery_s_sbt_is_found_whatever_its_case_and_deleted()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile(Scenery("Kato.scn"), "FirstInit\n")
.WithFile(Scenery("kato.sbt"), "EU07SBT2");
var sbt = Build(files);
Assert.Equal(Path.Combine("game", "scenery", "kato.sbt"), sbt.Of(Scenery("Kato.scn")));
Assert.Null(sbt.MissingOriginal(Scenery("Kato.scn")));
Assert.True(sbt.Delete(Scenery("Kato.scn")));
Assert.Null(sbt.Of(Scenery("Kato.scn")));
}
}

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,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<bool> 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<ManualTimer> _timers = new();
public IReadOnlyList<ManualTimer> 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;
}
}
}

View File

@@ -0,0 +1,132 @@
using StarterNG.Classes;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
// The old starter's magazyn.ini taken in at a start, over the fake disk.
public class OldStarterWarehouseTests
{
private const string PresetsPath = "/home/user/.config/MaSzyna/starter/userpresets.json";
// As the old starter writes it: CRLF, code page 1250, the scenery's path for a name.
private const string Magazyn =
"[TRAINSET0=baltyk/baltyk_km/mpj15120]\r\n" +
"00=node -1 0 EN57AKM-1682RA dynamic pkp\\en57akm_2013_v1 EN57AKM-1682ra akm_2013_ra_male_okna 0 headdriver 255 0 enddynamic\r\n" +
"01=node -1 0 EN57AKM-1682S dynamic pkp\\en57akm_2013_v1 EN57AKM-1682s akm_2013_s 0 nobody 255 0 enddynamic\r\n" +
"02=node -1 0 EN57AKM-1682RB dynamic pkp\\en57akm_2013_v1 EN57AKM-1682rb akm_2013_rb_male_okna 0 nobody 0 0 enddynamic\r\n";
private static (PresetFile Presets, InMemoryFileSystem Files) Rig()
{
var files = new InMemoryFileSystem();
return (new PresetFile(files, TestLog.Over(files), PresetsPath), files);
}
private static List<TrainsetPreset> Consist(string name, string vehicle) =>
OldStarterWarehouse.Read($"[TRAINSET0={name}]\r\n00=node -1 0 {vehicle} dynamic pkp\\x {vehicle} x 0 headdriver 3 0 enddynamic\r\n");
[Fact]
public void A_consist_of_the_old_starter_reads_as_a_trainset_with_its_vehicles()
{
var consist = Assert.Single(OldStarterWarehouse.Read(Magazyn));
Assert.Equal("baltyk/baltyk_km/mpj15120", consist.Name);
Assert.StartsWith("trainset baltyk/baltyk_km/mpj15120 none 0 0\n", consist.Entry);
Assert.EndsWith("endtrainset\n", consist.Entry);
var vehicles = ConsistText.VehiclesFrom(consist.Entry);
Assert.NotNull(vehicles);
Assert.Equal(new[] { "EN57AKM-1682RA", "EN57AKM-1682S", "EN57AKM-1682RB" }, vehicles!.Select(v => v.Name));
}
[Fact]
public void A_consist_new_in_the_old_starter_joins_the_warehouse()
{
var (presets, _) = Rig();
presets.Save("mine", "trainset mine");
int added = presets.TakeFromOldStarter(OldStarterWarehouse.Read(Magazyn));
Assert.Equal(1, added);
Assert.Equal(new[] { "baltyk/baltyk_km/mpj15120", "mine" }, presets.Presets().Select(p => p.Name));
}
[Fact]
public void A_consist_removed_here_does_not_come_back_at_the_next_start()
{
var (presets, _) = Rig();
var found = OldStarterWarehouse.Read(Magazyn);
presets.TakeFromOldStarter(found);
presets.Delete("baltyk/baltyk_km/mpj15120");
int added = presets.TakeFromOldStarter(found);
Assert.Equal(0, added);
Assert.Empty(presets.Presets());
}
[Fact]
public void Nothing_new_leaves_the_file_unwritten()
{
var (presets, files) = Rig();
var found = OldStarterWarehouse.Read(Magazyn);
presets.TakeFromOldStarter(found);
string before = files.ReadAllText(PresetsPath);
files.WithFile(PresetsPath, before + " ");
presets.TakeFromOldStarter(found);
Assert.Equal(before + " ", files.ReadAllText(PresetsPath));
}
[Fact]
public void A_consist_imported_by_hand_before_is_not_taken_twice()
{
var (presets, _) = Rig();
var found = OldStarterWarehouse.Read(Magazyn);
presets.Save(found[0].Name, found[0].Entry);
int added = presets.TakeFromOldStarter(found);
Assert.Equal(0, added);
Assert.Single(presets.Presets());
}
[Fact]
public void A_consist_of_the_same_name_made_here_stays_and_the_old_one_comes_in_beside_it()
{
var (presets, _) = Rig();
presets.Save("osobowy", "trainset osobowy none 0 0\nendtrainset\n");
presets.TakeFromOldStarter(Consist("osobowy", "SM42"));
var all = presets.Presets();
Assert.Equal(new[] { "osobowy", "osobowy" + PresetFile.OldStarterSuffix }, all.Select(p => p.Name));
Assert.Equal("trainset osobowy none 0 0\nendtrainset\n", all[0].Entry);
Assert.Contains("SM42", all[1].Entry);
}
[Fact]
public void A_consist_changed_in_the_old_starter_and_untouched_here_is_replaced()
{
var (presets, _) = Rig();
presets.TakeFromOldStarter(Consist("osobowy", "SM42"));
presets.TakeFromOldStarter(Consist("osobowy", "SU45"));
var only = Assert.Single(presets.Presets());
Assert.Equal("osobowy", only.Name);
Assert.Contains("SU45", only.Entry);
}
[Fact]
public void A_warehouse_file_that_cannot_be_read_is_left_as_it_is()
{
var (presets, files) = Rig();
files.WithFile(PresetsPath, "{ cut");
int added = presets.TakeFromOldStarter(OldStarterWarehouse.Read(Magazyn));
Assert.Equal(0, added);
Assert.Equal("{ cut", files.ReadAllText(PresetsPath));
Assert.False(files.FileExists(PresetsPath + ".unreadable"));
}
}

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

@@ -53,6 +53,26 @@ public class SceneryFileWatchTests
Assert.Equal("Katowice Główne", change.Fresh!.Name);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void An_sbt_made_or_removed_makes_the_scenery_read_anew(bool there)
{
string sbt = TestInstallation.At("scenery", "kato.sbt");
var files = Folder();
if (there)
files.WithFile(sbt, "EU07SBT2");
var (installation, watch, _) = Rig(files);
if (there)
files.DeleteFile(sbt);
else
files.WithFile(sbt, "EU07SBT2");
var change = Assert.Single(watch.Look(installation.Library.Sceneries));
Assert.Equal(!there, change.Fresh!.HasCompanionTimetable);
}
[Fact]
public void An_include_that_changed_or_came_makes_the_scenery_read_anew()
{

View File

@@ -0,0 +1,39 @@
using StarterNG.Application;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
/// <summary>The settings page on a start with no eu07.ini of the player's own yet.</summary>
[Collection(AvaloniaControls.Name)]
public class SettingsFirstStartTests
{
[Fact]
public void A_first_start_has_nothing_to_save_before_the_simulator_starts()
{
var files = new InMemoryFileSystem();
files.WriteAllText(TestInstallation.At("eu07.ini"), "width 1920\nheight 1080\nendconfig\n");
var installation = new TestInstallation(files);
installation.Environment.AsWindows();
var services = AppServices.Initialize(installation.Paths, installation.Files, installation.Clock,
installation.Environment);
services.SettingsStore.Load();
services.SettingsStore.StartAtHighWithoutOwnSettings();
HeadlessDrawing.Ensure();
// The page reads the graphics cards away from the window and comes back to it, as in the application.
var context = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(new Avalonia.Threading.AvaloniaSynchronizationContext());
Avalonia.Controls.Window? window = null;
try
{
var page = new StarterNG.Views.Settings();
window = Controls.Show(page, 1600, 1000, themed: true);
Assert.False(page.HasUnsavedChanges);
}
finally
{
window?.Close();
SynchronizationContext.SetSynchronizationContext(context);
}
}
}

View File

@@ -160,6 +160,11 @@ public partial class App : Avalonia.Application
});
});
// Ahead of the sceneries, so the list knows which still have their .sbt.
try { AppServices.Current.BinaryTerrain.CleanUpOnce(); }
catch (Exception ex) { Diagnostics.Log("sbt cleanup", ex); }
// Before any window lists the warehouse; it catches what it meets itself.
PresetStore.TakeFromOldStarter();
AppServices.Current.Library.Load(progress);
}).ContinueWith(load =>
{

View File

@@ -43,6 +43,7 @@ public sealed class AppServices
paths.FromRoot("starter"),
paths.FromRoot("lang")));
Sceneries = new SceneryRepository(files, paths, log, new SceneryParser(clock, random));
BinaryTerrain = new BinaryTerrainFiles(files, paths, log, settingsPaths.SbtCleanupPath());
SceneryImages = new SceneryImageLocator(files);
MiniTextures = new MiniTextureIndex(files, paths);
@@ -111,6 +112,8 @@ public sealed class AppServices
public SceneryFileWatch SceneryFiles { get; }
public BinaryTerrainFiles BinaryTerrain { get; }
public SceneryImageLocator SceneryImages { get; }
public IMiniTextureIndex MiniTextures { get; }

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

@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
@@ -28,6 +30,9 @@ public sealed class TrainsetPreset
public sealed class PresetCollection
{
public List<TrainsetPreset> Presets { get; set; } = new();
/// <summary>The old starter's consists taken in at a start, by <see cref="PresetFile.Fingerprint"/>.</summary>
public List<string> OldStarterSeen { get; set; } = new();
}
public static class PresetStore
@@ -81,33 +86,9 @@ public static class PresetStore
int added = 0;
try
{
string text = File.ReadAllText(path, LegacyText.CodePage1250);
var section = Regex.Matches(text,
@"\[TRAINSET\d+\s*=\s*([^\]]*)\](.*?)(?=\[TRAINSET|\z)",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in section)
foreach (var consist in OldStarterWarehouse.Read(LegacyText.Decode(File.ReadAllBytes(path))))
{
string name = m.Groups[1].Value.Trim();
if (name.Length == 0) name = $"import_{added + 1}";
var nodes = new List<string>();
foreach (Match line in Regex.Matches(m.Groups[2].Value, @"(?m)^\s*\d+\s*=\s*(.+)$"))
{
string body = line.Groups[1].Value.Trim();
if (!body.Contains("enddynamic", StringComparison.OrdinalIgnoreCase))
body += " enddynamic";
nodes.Add(body);
}
if (nodes.Count == 0) continue;
var sb = new StringBuilder();
sb.Append("trainset ").Append(Sanitize(name)).Append(" none 0 0\n");
foreach (string n in nodes)
sb.Append(n).Append('\n');
sb.Append("endtrainset\n");
Save(name, sb.ToString());
Save(consist.Name, consist.Entry);
added++;
}
}
@@ -118,6 +99,26 @@ public static class PresetStore
return added;
}
/// <summary>
/// At the start: what the old starter put in its warehouse since the last start
/// joins this one, as that starter showed its magazyn.ini each time it was opened.
/// </summary>
public static void TakeFromOldStarter()
{
string? path = FindMagazynPath();
if (path is null)
return;
try
{
Disk.TakeFromOldStarter(OldStarterWarehouse.Read(LegacyText.Decode(File.ReadAllBytes(path))));
}
catch (Exception ex)
{
Infrastructure.Diagnostics.Log($"Import {path}", ex);
}
}
private static string? FindMagazynPath()
{
string cwd = Directory.GetCurrentDirectory();
@@ -139,6 +140,46 @@ public static class PresetStore
var m = Regex.Match(p.Entry ?? "", @"^\s*trainset\s+\S+\s+(\S+)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
return m.Success ? m.Groups[1].Value : "";
}
}
/// <summary>
/// The old starter's magazyn.ini: a [TRAINSETn=name] line for each consist, then
/// its vehicles as numbered "node … enddynamic" lines.
/// </summary>
public static class OldStarterWarehouse
{
public static List<TrainsetPreset> Read(string text)
{
var consists = new List<TrainsetPreset>();
var sections = Regex.Matches(text,
@"\[TRAINSET\d+\s*=\s*([^\]]*)\](.*?)(?=\[TRAINSET|\z)",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in sections)
{
string name = m.Groups[1].Value.Trim();
if (name.Length == 0) name = $"import_{consists.Count + 1}";
var nodes = new List<string>();
foreach (Match line in Regex.Matches(m.Groups[2].Value, @"(?m)^\s*\d+\s*=\s*(.+)$"))
{
string body = line.Groups[1].Value.Trim();
if (!body.Contains("enddynamic", StringComparison.OrdinalIgnoreCase))
body += " enddynamic";
nodes.Add(body);
}
if (nodes.Count == 0) continue;
var sb = new StringBuilder();
sb.Append("trainset ").Append(Sanitize(name)).Append(" none 0 0\n");
foreach (string n in nodes)
sb.Append(n).Append('\n');
sb.Append("endtrainset\n");
consists.Add(new TrainsetPreset { Name = name, Entry = sb.ToString() });
}
return consists;
}
private static string Sanitize(string name) =>
string.IsNullOrWhiteSpace(name) ? "preset" : name.Replace(' ', '_');
@@ -193,6 +234,55 @@ public sealed class PresetFile
Persist(col, read);
}
/// <summary>Where a consist of the old starter goes when one of its name with other vehicles is here.</summary>
public const string OldStarterSuffix = " (magazyn.ini)";
/// <summary>
/// Takes in the old starter's consists not taken at an earlier start, so one
/// removed here stays removed while the old starter keeps it as it was. One
/// whose name is here with other vehicles comes in beside it, unless what is
/// here is that consist as an earlier start brought it, untouched since.
/// </summary>
/// <returns>How many came in.</returns>
public int TakeFromOldStarter(IReadOnlyList<TrainsetPreset> found)
{
// A file that cannot be read is not replaced by an import nobody asked for.
if (found.Count == 0 || !TryRead(out var col))
return 0;
var seenBefore = new HashSet<string>(col.OldStarterSeen, StringComparer.Ordinal);
var seen = new HashSet<string>(seenBefore, StringComparer.Ordinal);
int added = 0;
foreach (var consist in found)
{
if (!seen.Add(Fingerprint(consist)))
continue;
var here = col.Presets.Find(p => string.Equals(p.Name, consist.Name, StringComparison.OrdinalIgnoreCase));
if (here is not null && here.Entry == consist.Entry)
continue;
string name = here is null || seenBefore.Contains(Fingerprint(here))
? consist.Name
: consist.Name + OldStarterSuffix;
col.Presets.RemoveAll(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase));
col.Presets.Add(new TrainsetPreset { Name = name, Entry = consist.Entry });
added++;
}
if (seen.Count == seenBefore.Count)
return 0;
col.OldStarterSeen = seen.Order(StringComparer.Ordinal).ToList();
col.Presets.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
Persist(col, read: true);
return added;
}
/// <summary>A consist by its name and vehicles, short enough to keep each one ever taken in.</summary>
public static string Fingerprint(TrainsetPreset preset) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(preset.Name + "\n" + preset.Entry)));
/// <summary>The file's presets; false, with none, when there is a file but they cannot be had from it.</summary>
private bool TryRead(out PresetCollection col)
{

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

@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed class FolderLooks
{
/// <summary>How long the reports have to stop for: a save comes as several of them.</summary>
public static readonly TimeSpan Quiet = TimeSpan.FromMilliseconds(400);
/// <summary>How often it looks anyway where the system reports the changes.</summary>
public static readonly TimeSpan Watched = TimeSpan.FromSeconds(30);
/// <summary>How often it looks where the system reports nothing.</summary>
public static readonly TimeSpan Unwatched = TimeSpan.FromSeconds(2);
private readonly Func<string> _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;
/// <param name="window">Looked for from its opening to its closing.</param>
/// <param name="folder">The folder, as it is when the window opens.</param>
/// <param name="look">The look itself; it knows when it is no time to look.</param>
/// <param name="time">The clock of the timers, the system's when not given.</param>
public FolderLooks(Window window, Func<string> folder, Func<Task> 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();
}
/// <summary>Whether the system reports the folder's changes; not before the window opens.</summary>
public bool Watching => _changes?.Watching == true;
/// <summary>Looks now, or once more after the look that runs.</summary>
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();
}
}

View File

@@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using StarterNG.Application.Abstractions;
using StarterNG.Domain;
using StarterNG.Domain.Sceneries;
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Infrastructure.Sceneries;
/// <summary>
/// The sceneries' binary terrain files (.sbt): the simulator writes one beside a
/// scenery on its first load and from then on takes the terrain from it, passing
/// the scenery's terrain includes (<c>*_ter.scm</c>) over. It never asks whether
/// the text changed since, so a file made by an older simulator, or before the
/// scenery was updated, keeps showing what was there then.
/// <para>
/// A file goes only when the scenery's text still holds what it was made of: some
/// sceneries come with the .sbt in place of their terrain includes, and without it
/// they would have no terrain at all.
/// </para>
/// </summary>
public sealed class BinaryTerrainFiles
{
/// <summary>
/// Raised by a release that wants the .sbt files made anew: each installation is
/// cleared once for each value, on the first start of a starter carrying it.
/// Zero clears nothing.
/// </summary>
public const int CleanupGeneration = 1;
private const string Extension = ".sbt";
// The simulator splits its text into words at spaces, tabs, line ends and semicolons.
private static readonly Regex Word = new(@"[^\s;]+", RegexOptions.CultureInvariant);
private readonly IFileSystem _files;
private readonly IGamePaths _paths;
private readonly IDiagnosticsLog _log;
private readonly string _recordPath;
/// <param name="recordPath">Where the cleanups done are noted, for each installation.</param>
public BinaryTerrainFiles(IFileSystem files, IGamePaths paths, IDiagnosticsLog log, string recordPath)
{
_files = files;
_paths = paths;
_log = log;
_recordPath = recordPath;
}
/// <summary>The scenery's own .sbt as it is on disk, whatever the case of its letters; null when it has none.</summary>
public string? Of(string sceneryPath)
{
string? file = new CaseInsensitivePaths(_files)
.Resolve(_paths.Scenery, Path.GetFileNameWithoutExtension(sceneryPath) + Extension);
return file is null ? null : Path.Combine(_paths.Scenery, file);
}
/// <summary>
/// What the simulator would miss to make the scenery's .sbt again - the first
/// terrain file its text names and the installation lacks, or the terrain directive
/// that brings terrain from elsewhere; null when the text holds it all.
/// </summary>
public string? MissingOriginal(string sceneryPath)
{
try
{
var names = new CaseInsensitivePaths(_files, keepListings: true);
string? own = names.Resolve(_paths.Scenery, Path.GetFileName(sceneryPath));
if (own is null)
return Path.GetFileName(sceneryPath);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var pending = new Stack<string>();
pending.Push(own);
while (pending.Count > 0)
{
string file = pending.Pop();
if (!seen.Add(file))
continue;
if (Scan(file, names, pending) is { } missing)
return missing;
}
return null;
}
catch (Exception ex)
{
_log.Log($"sbt/{Path.GetFileName(sceneryPath)}", ex);
return Path.GetFileName(sceneryPath);
}
}
/// <summary>
/// Reads one file of the scenery for its includes: the terrain ones have to be
/// there, the others are read in turn. Terrain files are not opened - they are the
/// largest of all and include nothing.
/// </summary>
private string? Scan(string file, CaseInsensitivePaths names, Stack<string> pending)
{
string text = LegacyText.Decode(_files.ReadAllBytes(Path.Combine(_paths.Scenery, file)));
string code = SceneryCode.Mask(text, out _);
bool includeNext = false;
bool terrainDirective = false;
for (var word = Word.Match(code); word.Success; word = word.NextMatch())
{
string token = word.Value;
if (terrainDirective)
{
if (token.Equals("endterrain", StringComparison.OrdinalIgnoreCase))
terrainDirective = false;
else if (TerrainFileMissing(token, names) is { } missing)
return missing;
}
else if (includeNext)
{
includeNext = false;
bool terrain = SimulatorNames.Lower(token).Contains("_ter.scm");
string? found = names.Resolve(_paths.Scenery, token);
if (found is null && terrain)
return token;
// Any other file the simulator reads from the text, .sbt or not: missing,
// it is missing either way, and the .sbt made again lacks nothing.
if (found is not null && !terrain)
pending.Push(found);
}
else if (token.Equals("include", StringComparison.OrdinalIgnoreCase))
includeNext = true;
else if (token.Equals("terrain", StringComparison.OrdinalIgnoreCase))
terrainDirective = true;
}
return null;
}
/// <summary>
/// One file named by a terrain directive. An .sbt named there holds the geometry
/// of the whole scenery and nothing makes it again, so the scenery's own goes
/// only without one. A terrain file (.txtf) has its geometry in itself or in its
/// binary copy (.btf) beside it: with either one there, the scenery's .sbt only
/// keeps that terrain from being used, and the simulator asks for it to go.
/// </summary>
private string? TerrainFileMissing(string token, CaseInsensitivePaths names)
{
string extension = Path.GetExtension(token);
if (extension.Equals(Extension, StringComparison.OrdinalIgnoreCase))
return "terrain " + token;
if (!extension.Equals(".txtf", StringComparison.OrdinalIgnoreCase)
&& !extension.Equals(".btf", StringComparison.OrdinalIgnoreCase))
return null;
string stem = token[..^extension.Length];
return names.Resolve(_paths.Scenery, stem + ".txtf") is null
&& names.Resolve(_paths.Scenery, stem + ".btf") is null
? stem + ".txtf"
: null;
}
/// <summary>Removes the scenery's .sbt; false when it has none or it could not go.</summary>
public bool Delete(string sceneryPath)
{
if (Of(sceneryPath) is not { } file)
return false;
try
{
_files.DeleteFile(file);
_log.Log($"{file} removed, the simulator makes it again on the next load of the scenery");
return true;
}
catch (Exception ex)
{
_log.Log($"sbt/{Path.GetFileName(file)}", ex);
return false;
}
}
/// <summary>
/// Clears the .sbt files the simulator can make again, once for each
/// <paramref name="generation"/> on this installation; null when it was done
/// already. A file that could not go leaves the cleanup to the next start.
/// </summary>
public BinaryTerrainCleanup? CleanUpOnce(int generation = CleanupGeneration)
{
if (generation <= 0 || !_files.DirectoryExists(_paths.Scenery))
return null;
var record = ReadRecord();
string installation = Installation();
if (record.TryGetValue(installation, out int done) && done >= generation)
return null;
var deleted = new List<string>();
var kept = new List<(string File, string Reason)>();
var failed = new List<string>();
var names = new CaseInsensitivePaths(_files);
foreach (string sbt in _files.GetFiles(_paths.Scenery)
.Where(f => Path.GetExtension(f).Equals(Extension, StringComparison.OrdinalIgnoreCase)))
{
string name = Path.GetFileName(sbt);
string? scenery = names.Resolve(_paths.Scenery, Path.GetFileNameWithoutExtension(sbt) + ".scn");
string? missing = scenery is null ? Path.GetFileNameWithoutExtension(sbt) + ".scn" : MissingOriginal(scenery);
if (missing is not null)
{
kept.Add((name, missing));
_log.Log($"{name} kept: the scenery cannot be made without it, {missing} is missing");
continue;
}
try
{
_files.DeleteFile(sbt);
deleted.Add(name);
}
catch (Exception ex)
{
failed.Add(name);
_log.Log($"sbt/{name}", ex);
}
}
if (deleted.Count > 0)
_log.Log($"Binary terrain files removed, the simulator makes them again: {string.Join(", ", deleted)}");
if (failed.Count == 0)
{
record[installation] = generation;
WriteRecord(record);
}
return new BinaryTerrainCleanup(deleted, kept, failed);
}
private string Installation() =>
Path.TrimEndingDirectorySeparator(Path.GetFullPath(_paths.Root));
private Dictionary<string, int> ReadRecord()
{
var record = new Dictionary<string, int>(
_files.IgnoresCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
try
{
if (!_files.FileExists(_recordPath))
return record;
foreach (string line in _files.ReadAllLines(_recordPath))
{
int tab = line.IndexOf('\t');
if (tab > 0 && int.TryParse(line[..tab], out int generation))
record[line[(tab + 1)..]] = generation;
}
}
catch (Exception ex)
{
_log.Log("sbt cleanup record", ex);
}
return record;
}
private void WriteRecord(Dictionary<string, int> record)
{
try
{
if (Path.GetDirectoryName(_recordPath) is { Length: > 0 } folder)
_files.CreateDirectory(folder);
_files.WriteAllTextAtomic(_recordPath,
string.Concat(record.Select(entry => $"{entry.Value}\t{entry.Key}\n")));
}
catch (Exception ex)
{
_log.Log("sbt cleanup record", ex);
}
}
}
/// <param name="Deleted">The files removed.</param>
/// <param name="Kept">The files left, as nothing could make them again, each with what is missing.</param>
/// <param name="Failed">The files that could not be removed.</param>
public sealed record BinaryTerrainCleanup(
IReadOnlyList<string> Deleted,
IReadOnlyList<(string File, string Reason)> Kept,
IReadOnlyList<string> Failed);

View File

@@ -79,7 +79,12 @@ public sealed class SceneryRepository : ISceneryRepository
// With its own .sbt the scenery's terrain comes from it, and the simulator
// passes its terrain includes over without opening them.
bool binaryTerrain = Opens(Path.GetFileNameWithoutExtension(path) + ".sbt");
// Watched with the text: made by the simulator on a load, or removed, it changes the scenery too.
string sbtName = Path.GetFileNameWithoutExtension(path) + ".sbt";
string? sbt = ResolveInclude(sbtName);
bool binaryTerrain = sbt is not null;
string sbtPath = Path.Combine(_paths.Scenery, sbt ?? sbtName);
sources[sbtPath] = FileStamp.Of(_files, sbtPath);
bool OpensInclude(string name) =>
Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm"));

View File

@@ -53,6 +53,9 @@ public sealed class SettingsPaths
/// <summary>The sceneries starred in the list.</summary>
public string FavoritesPath() => Path.Combine(UserConfigDirectory(), "favorites.txt");
/// <summary>Which cleanup of the .sbt files each installation had.</summary>
public string SbtCleanupPath() => Path.Combine(UserConfigDirectory(), "sbt-cleanup.txt");
public string UserConfigDirectory() =>
Path.GetDirectoryName(UserConfigPath()) ?? _environment.BaseDirectory;
}

View File

@@ -40,8 +40,9 @@ 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 they change, on coming back to the window or from the
// simulator, and now and then anyway.
private readonly FolderLooks _sceneryLooks;
public MainWindow()
{
@@ -107,7 +108,6 @@ public partial class MainWindow : Window
_openedUtc = DateTime.UtcNow;
UpdateStartButton();
_sceneryFilesTimer.Start();
FollowLastRun();
};
Activated += (_, _) =>
@@ -117,20 +117,20 @@ public partial class MainWindow : Window
if (SettingsView.IsVisible)
SettingsView.RefreshExecutables();
};
_sceneryFilesTimer.Tick += async (_, _) => await LookAtSceneryFilesAsync();
Closed += (_, _) => _sceneryFilesTimer.Stop();
// After the handlers above: back at the window, the settings are checked first.
_sceneryLooks = new FolderLooks(this, () => AppServices.Current.Paths.Scenery, LookAtSceneryFilesAsync);
}
/// <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="_sceneryLooks"/>, 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;
@@ -146,10 +146,6 @@ public partial class MainWindow : Window
{
Diagnostics.Log("Following the scenery files", ex);
}
finally
{
_lookingAtSceneryFiles = false;
}
}
/// <summary>
@@ -765,6 +761,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.
_ = _sceneryLooks.LookAsync();
}), TaskScheduler.Default);
}

View File

@@ -45,6 +45,8 @@
Header="{Binding [ReloadSceneries], Source={x:Static starterNg:App.Loc}}" />
<MenuItem Click="OpenSceneryDir_OnClick"
Header="{Binding [OpenSceneryFolder], Source={x:Static starterNg:App.Loc}}" />
<MenuItem Name="deleteSbtMenuItem" Click="DeleteSbt_OnClick"
Header="{Binding [DeleteSbt], Source={x:Static starterNg:App.Loc}}" />
</ContextMenu>
</TreeView.ContextMenu>
</TreeView>

View File

@@ -165,6 +165,39 @@ public partial class Scenarios : UserControl
favoriteMenuItem.Header = App.Loc[scenery is not null && AppServices.Current.Favorites.Contains(scenery)
? "FavoriteRemove"
: "FavoriteAdd"];
deleteSbtMenuItem.IsEnabled = scenery is not null
&& !AppServices.Current.State.SimulatorRunning
&& AppServices.Current.BinaryTerrain.Of(scenery.Path) is not null;
}
// Only a file the simulator can make again from the scenery's text goes: one
// standing in for terrain files the installation lacks takes the terrain with it.
private async void DeleteSbt_OnClick(object? sender, RoutedEventArgs e)
{
if (SelectedScenery is not { } scenery || TopLevel.GetTopLevel(this) is not Window owner)
return;
var sbt = AppServices.Current.BinaryTerrain;
if (sbt.Of(scenery.Path) is not { } file)
return;
string name = Path.GetFileName(file);
string title = App.Loc["DeleteSbt"];
if (await Task.Run(() => sbt.MissingOriginal(scenery.Path)) is { } missing)
{
await MessageBox.Show(owner, string.Format(App.Loc["DeleteSbtNoOriginal"], name, missing), title,
MessageBoxButtons.Ok);
return;
}
long megabytes = AppServices.Current.Files.GetFileSize(file) / (1024 * 1024);
if (!await MessageBox.Show(owner, string.Format(App.Loc["DeleteSbtConfirm"], name, megabytes), title,
MessageBoxButtons.YesNo))
return;
// Gone, the scenery follows by the watch on its files, as it would after any other change.
if (!await Task.Run(() => sbt.Delete(scenery.Path)))
await MessageBox.Show(owner, string.Format(App.Loc["DeleteSbtFailed"], name), title, MessageBoxButtons.Ok);
}
private void ToggleFavorite_OnClick(object? sender, RoutedEventArgs e)

View File

@@ -966,11 +966,11 @@ public partial class Settings : UserControl, ISettingsCapture
OnControlChanged();
};
UartEnabledCb.IsCheckedChanged += (_, _) => ValidateUart();
UartTuneBox.TextChanged += (_, _) =>
OnTextEdited(UartTuneBox, () =>
{
ValidateUart();
OnControlChanged();
};
});
App.Loc.LanguageChanged += UpdateUartTexts;
UpdateUartTexts();
}
@@ -1511,7 +1511,7 @@ public partial class Settings : UserControl, ISettingsCapture
nud.ValueChanged += (_, _) => OnControlChanged();
break;
case TextBox box when ReferenceEquals(box, VulkanDeviceTb):
box.TextChanged += (_, _) => OnControlChanged();
OnTextEdited(box, OnControlChanged);
break;
}
}
@@ -1521,6 +1521,18 @@ public partial class Settings : UserControl, ISettingsCapture
toggle.IsCheckedChanged += (_, _) => OnControlChanged();
}
/// <summary>
/// The text as it changes, not TextChanged: that one comes later, from the
/// dispatcher, so the text the page itself put there while loading came back
/// as an edit once the window was shown - the first start asked to save.
/// </summary>
private static void OnTextEdited(TextBox box, Action edited) =>
box.PropertyChanged += (_, e) =>
{
if (e.Property == TextBox.TextProperty)
edited();
};
private void OnControlChanged()
{
MarkDirty();
@@ -1533,8 +1545,7 @@ public partial class Settings : UserControl, ISettingsCapture
if (_loading || _dirty)
return;
_dirty = true;
UpdateSaveState();
_dirty = true; UpdateSaveState();
}
/// <summary>Edits on the page, or of the keys, not saved yet: what "Niezapisane zmiany" tells.</summary>

View File

@@ -69,6 +69,10 @@
<String key="FavoriteAdd">Přidat do oblíbených</String>
<String key="FavoriteRemove">Odebrat z oblíbených</String>
<String key="OpenSceneryFolder">Otevřít složku</String>
<String key="DeleteSbt">Smazat SBT</String>
<String key="DeleteSbtConfirm">Smazat {0} ({1} MB)? Simulátor jej znovu sestaví ze souborů scenérie při jejím dalším načtení, které potrvá déle.</String>
<String key="DeleteSbtNoOriginal">Soubor {0} zůstává: není z čeho jej znovu sestavit, chybí {1}. Bez něj by scenérie přišla o terén.</String>
<String key="DeleteSbtFailed">Soubor {0} nelze smazat. Možná jej používá simulátor, nebo je složka jen pro čtení.</String>
<String key="OptionalIncludes">Volitelné prvky</String>
<String key="OpenTextureFolder">Otevřít složku s texturami</String>
<String key="CopyTextureName">Kopírovat název</String>

View File

@@ -69,6 +69,10 @@
<String key="FavoriteAdd">Add to favourites</String>
<String key="FavoriteRemove">Remove from favourites</String>
<String key="OpenSceneryFolder">Open folder</String>
<String key="DeleteSbt">Delete SBT</String>
<String key="DeleteSbtConfirm">Delete {0} ({1} MB)? The simulator makes it again from the scenery files on its next load, which takes longer.</String>
<String key="DeleteSbtNoOriginal">{0} stays: nothing is there to make it again, {1} is missing. Without it the scenery would lose its terrain.</String>
<String key="DeleteSbtFailed">Could not delete {0}. The simulator may be using it, or the folder is read-only.</String>
<String key="OptionalIncludes">Optional elements</String>
<String key="OpenTextureFolder">Open texture folder</String>
<String key="CopyTextureName">Copy name</String>

View File

@@ -69,6 +69,10 @@
<String key="FavoriteAdd">Hozzáadás a kedvencekhez</String>
<String key="FavoriteRemove">Eltávolítás a kedvencek közül</String>
<String key="OpenSceneryFolder">Mappa megnyitása</String>
<String key="DeleteSbt">SBT törlése</String>
<String key="DeleteSbtConfirm">Törlöd: {0} ({1} MB)? A szimulátor a színtér fájljaiból a következő betöltéskor újra elkészíti, ami tovább tart.</String>
<String key="DeleteSbtNoOriginal">{0} megmarad: nincs miből újra elkészíteni, hiányzik: {1}. Nélküle a színtér elveszítené a terepet.</String>
<String key="DeleteSbtFailed">Nem sikerült törölni: {0}. Lehet, hogy a szimulátor használja, vagy a mappa csak olvasható.</String>
<String key="OptionalIncludes">Opcionális elemek</String>
<String key="OpenTextureFolder">Textúramappa megnyitása</String>
<String key="CopyTextureName">Név másolása</String>

View File

@@ -69,6 +69,10 @@
<String key="FavoriteAdd">Dodaj do ulubionych</String>
<String key="FavoriteRemove">Usuń z ulubionych</String>
<String key="OpenSceneryFolder">Otwórz folder</String>
<String key="DeleteSbt">Usuń SBT</String>
<String key="DeleteSbtConfirm">Usunąć {0} ({1} MB)? Symulator zbuduje go od nowa z plików scenerii przy jej następnym wczytaniu, które potrwa dłużej.</String>
<String key="DeleteSbtNoOriginal">Plik {0} zostaje: sceneria nie ma z czego go odbudować, brakuje {1}. Bez niego straciłaby teren.</String>
<String key="DeleteSbtFailed">Nie udało się usunąć {0}. Może używa go symulator albo folder jest tylko do odczytu.</String>
<String key="OptionalIncludes">Elementy opcjonalne</String>
<String key="OpenTextureFolder">Otwórz folder tekstury</String>
<String key="CopyTextureName">Kopiuj nazwę</String>

View File

@@ -69,6 +69,10 @@
<String key="FavoriteAdd">Добавить в избранное</String>
<String key="FavoriteRemove">Удалить из избранного</String>
<String key="OpenSceneryFolder">Открыть папку</String>
<String key="DeleteSbt">Удалить SBT</String>
<String key="DeleteSbtConfirm">Удалить {0} ({1} МБ)? Симулятор заново соберёт его из файлов сценария при следующей загрузке, которая займёт больше времени.</String>
<String key="DeleteSbtNoOriginal">Файл {0} остаётся: его не из чего собрать заново, нет {1}. Без него сценарий лишится рельефа.</String>
<String key="DeleteSbtFailed">Не удалось удалить {0}. Возможно, его использует симулятор или папка только для чтения.</String>
<String key="OptionalIncludes">Дополнительные элементы</String>
<String key="OpenTextureFolder">Открыть папку с текстурами</String>
<String key="CopyTextureName">Копировать название</String>