From 48af11b4b215d771f79b8b8b15fdfddec713401f Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:04:49 +0100 Subject: [PATCH 01/35] refactor: share the case-insensitive lookup of data files The scenery repository's include lookup becomes CaseInsensitivePaths, which takes any folder over IFileSystem and gives a name as it is on disk. Of folders named alike in other case it now tries each, not only the first. A name is joined to the folder as the simulator joins it, a leading slash counting for nothing. IFileSystem tells whether the disk ignores case; there, as on Windows, a name missed as written is not looked for any further, so no folder is listed. --- StarterNG.Tests/CaseInsensitivePathsTests.cs | 119 ++++++++++++++++ StarterNG.Tests/Fakes/InMemoryFileSystem.cs | 2 + .../Application/Abstractions/IFileSystem.cs | 3 + .../Adapters/PhysicalFileSystem.cs | 3 + .../Infrastructure/CaseInsensitivePaths.cs | 132 ++++++++++++++++++ .../Sceneries/SceneryRepository.cs | 46 +----- 6 files changed, 264 insertions(+), 41 deletions(-) create mode 100644 StarterNG.Tests/CaseInsensitivePathsTests.cs create mode 100644 StarterNG/Infrastructure/CaseInsensitivePaths.cs diff --git a/StarterNG.Tests/CaseInsensitivePathsTests.cs b/StarterNG.Tests/CaseInsensitivePathsTests.cs new file mode 100644 index 0000000..9d8bfeb --- /dev/null +++ b/StarterNG.Tests/CaseInsensitivePathsTests.cs @@ -0,0 +1,119 @@ +using StarterNG.Infrastructure; +using StarterNG.Tests.Fakes; + +namespace StarterNG.Tests; + +public class CaseInsensitivePathsTests +{ + private static InMemoryFileSystem Disk() => new InMemoryFileSystem(caseSensitive: true) + .WithFile("game/scenery/Braniewo/Base.ctr", "") + .WithFile("game/scenery/Braniewo/rozklady/TGS3657.txt", "") + .WithDirectory("game/textures/mini"); + + [Theory] + [InlineData("braniewo/base.ctr", "Braniewo/Base.ctr")] + [InlineData(@"BRANIEWO\Rozklady\tgs3657.TXT", "Braniewo/rozklady/TGS3657.txt")] + [InlineData("Braniewo/Base.ctr", "Braniewo/Base.ctr")] + [InlineData("braniewo//base.ctr", "Braniewo/Base.ctr")] + [InlineData("/braniewo/base.ctr", "Braniewo/Base.ctr")] + [InlineData(@"\Braniewo\Base.ctr", "Braniewo/Base.ctr")] + public void A_name_in_any_case_is_given_as_it_is_on_disk(string name, string onDisk) => + Assert.Equal(onDisk, new CaseInsensitivePaths(Disk()).Resolve("game/scenery", name)); + + [Theory] + [InlineData("braniewo/brak.ctr")] + [InlineData("brak/base.ctr")] + [InlineData("")] + public void A_name_nothing_answers_to_is_not_found(string name) => + Assert.Null(new CaseInsensitivePaths(Disk()).Resolve("game/scenery", name)); + + [Fact] + public void A_folder_is_found_only_when_one_is_asked_for() + { + var names = new CaseInsensitivePaths(Disk()); + + Assert.Equal("Braniewo/rozklady", names.Resolve("game/scenery", "braniewo/ROZKLADY", directory: true)); + Assert.Null(names.Resolve("game/scenery", "braniewo/ROZKLADY")); + Assert.Null(names.Resolve("game/scenery", "braniewo/base.ctr", directory: true)); + } + + [Fact] + public void The_name_written_as_on_disk_wins_over_one_in_other_case() + { + var files = Disk().WithFile("game/scenery/braniewo/base.ctr", ""); + var names = new CaseInsensitivePaths(files); + + Assert.Equal("braniewo/base.ctr", names.Resolve("game/scenery", "braniewo/base.ctr")); + Assert.Equal("Braniewo/Base.ctr", names.Resolve("game/scenery", "Braniewo/base.CTR")); + } + + [Fact] + public void Of_folders_named_alike_the_one_holding_the_file_is_taken() + { + var files = Disk().WithFile("game/scenery/braniewo/tory.scm", ""); + var names = new CaseInsensitivePaths(files); + + Assert.Equal("Braniewo/Base.ctr", names.Resolve("game/scenery", "braniewo/base.ctr")); + Assert.Equal("braniewo/tory.scm", names.Resolve("game/scenery", "Braniewo/Tory.scm")); + } + + [Fact] + public void The_full_path_joins_the_folder_and_the_name_on_disk() => + Assert.Equal(Path.Combine("game/scenery", "Braniewo", "Base.ctr"), + new CaseInsensitivePaths(Disk()).Find("game/scenery", "BRANIEWO/BASE.CTR")); + + [Fact] + public void A_full_path_is_found_from_its_own_root() + { + string scenery = Path.GetFullPath(Path.Combine("game", "scenery")); + var files = new InMemoryFileSystem(caseSensitive: true) + .WithFile(Path.Combine(scenery, "Braniewo", "Base.ctr"), ""); + + Assert.Equal(Path.Combine(scenery, "Braniewo", "Base.ctr"), + new CaseInsensitivePaths(files).Find("elsewhere", Path.Combine(scenery, "BRANIEWO", "base.CTR"))); + } + + [Fact] + public void A_disk_that_ignores_case_gives_the_name_back_as_written() + { + var files = new InMemoryFileSystem().WithFile("game/scenery/Braniewo/Base.ctr", ""); + var names = new CaseInsensitivePaths(files); + + Assert.Equal("BRANIEWO/base.CTR", names.Resolve("game/scenery", "BRANIEWO/base.CTR")); + Assert.Null(names.Resolve("game/scenery", "braniewo/brak.ctr")); + } + + [Fact] + public void Kept_listings_hold_until_forgotten() + { + var files = Disk(); + var names = new CaseInsensitivePaths(files, keepListings: true); + Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm")); + + files.WithFile("game/scenery/Braniewo/Nowy.scm", ""); + Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm")); + + names.Forget(); + Assert.Equal("Braniewo/Nowy.scm", names.Resolve("game/scenery", "braniewo/nowy.scm")); + } + + [Fact] + public void Listings_not_kept_see_a_file_added_since() + { + var files = Disk(); + var names = new CaseInsensitivePaths(files); + Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm")); + + files.WithFile("game/scenery/Braniewo/Nowy.scm", ""); + + Assert.Equal("Braniewo/Nowy.scm", names.Resolve("game/scenery", "braniewo/nowy.scm")); + } + + [Fact] + public void A_folder_that_cannot_be_listed_holds_nothing_to_find() + { + var files = Disk().DenyListing("game/scenery"); + + Assert.Null(new CaseInsensitivePaths(files).Resolve("game/scenery", "braniewo/base.ctr")); + } +} diff --git a/StarterNG.Tests/Fakes/InMemoryFileSystem.cs b/StarterNG.Tests/Fakes/InMemoryFileSystem.cs index 79108cb..0709309 100644 --- a/StarterNG.Tests/Fakes/InMemoryFileSystem.cs +++ b/StarterNG.Tests/Fakes/InMemoryFileSystem.cs @@ -97,6 +97,8 @@ public sealed class InMemoryFileSystem : IFileSystem return this; } + public bool IgnoresCase => _comparison == StringComparison.OrdinalIgnoreCase; + public bool FileExists(string path) => _files.ContainsKey(Normalize(path)); /// A link counts as the directory it points at, as the disk has it. diff --git a/StarterNG/Application/Abstractions/IFileSystem.cs b/StarterNG/Application/Abstractions/IFileSystem.cs index e04f862..b9c0e3a 100644 --- a/StarterNG/Application/Abstractions/IFileSystem.cs +++ b/StarterNG/Application/Abstractions/IFileSystem.cs @@ -7,6 +7,9 @@ namespace StarterNG.Application.Abstractions; public interface IFileSystem { + /// Whether a name finds its file whatever the case of its letters, as on Windows and macOS. + bool IgnoresCase { get; } + bool FileExists(string path); bool DirectoryExists(string path); diff --git a/StarterNG/Infrastructure/Adapters/PhysicalFileSystem.cs b/StarterNG/Infrastructure/Adapters/PhysicalFileSystem.cs index 15ae4ee..14ab1d6 100644 --- a/StarterNG/Infrastructure/Adapters/PhysicalFileSystem.cs +++ b/StarterNG/Infrastructure/Adapters/PhysicalFileSystem.cs @@ -10,6 +10,9 @@ public sealed class PhysicalFileSystem : IFileSystem { public const string TempSuffix = ".starter.tmp"; + // Their disks as they come; a Linux one tells case apart. + public bool IgnoresCase { get; } = OperatingSystem.IsWindows() || OperatingSystem.IsMacOS(); + public bool FileExists(string path) => File.Exists(path); public bool DirectoryExists(string path) => Directory.Exists(path); diff --git a/StarterNG/Infrastructure/CaseInsensitivePaths.cs b/StarterNG/Infrastructure/CaseInsensitivePaths.cs new file mode 100644 index 0000000..51c81d4 --- /dev/null +++ b/StarterNG/Infrastructure/CaseInsensitivePaths.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Linq; +using StarterNG.Application.Abstractions; + +namespace StarterNG.Infrastructure; + +/// +/// Finds a file or folder of the game's data by a name whose letters may stand in +/// another case than on disk, as Windows, Wine and the simulator find it, and gives +/// the name as the disk has it. The data is made on Windows: its names and the +/// names written in it seldom agree letter for letter, which on Linux matters. +/// +public sealed class CaseInsensitivePaths +{ + private readonly IFileSystem _files; + private readonly Func<(string Folder, bool Files), ILookup> _list; + + /// Each folder's files and folders by name, listed once until ; null lists every time. + private readonly ConcurrentDictionary<(string Folder, bool Files), ILookup>? _listings; + + /// + /// Lists each folder once, for many names looked up in data that stays as it is + /// meanwhile, until . + /// + public CaseInsensitivePaths(IFileSystem files, bool keepListings = false) + { + _files = files; + _list = List; + if (keepListings) + _listings = new ConcurrentDictionary<(string, bool), ILookup>(); + } + + /// Lets the next lookups list the folders again. + public void Forget() => _listings?.Clear(); + + /// + /// The file named so under as it is named on disk, relative + /// to the folder with forward slashes; null when nothing there answers to it. A name + /// written with its letters as on disk wins over one differing only in their case; + /// a disk that does not tell case apart gives it back as written. + /// + /// + /// A name under the folder, with either slash, joined to it as the simulator joins + /// it: a slash ahead of it counts for nothing. + /// + /// Looks for a folder instead of a file. + public string? Resolve(string folder, string name, bool directory = false) + { + string[] parts = name.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) + return null; + + string exact = string.Join('/', parts); + string whole = Path.Combine(folder, exact); + if (directory ? _files.DirectoryExists(whole) : _files.FileExists(whole)) + return exact; + // Where case does not matter, missed as written is missed in any case. + if (_files.IgnoresCase) + return null; + + var found = new string[parts.Length]; + return Walk(folder, parts, 0, directory, found) ? string.Join('/', found) : null; + } + + /// + /// The full path of the file named so, its letters as on disk; null when there is + /// none. A name given in full is looked up from its own root, any other under + /// as does. + /// + public string? Find(string folder, string name, bool directory = false) + { + if (Path.IsPathFullyQualified(name)) + { + folder = Path.GetPathRoot(name)!; + name = name[folder.Length..]; + } + + return Resolve(folder, name, directory) is { } found + ? Path.Combine(folder, found.Replace('/', Path.DirectorySeparatorChar)) + : null; + } + + /// + /// Finds the parts from on under . Of + /// folders named alike in other case - two copies of the data on Linux - each is + /// tried, the one written as on disk first. + /// + private bool Walk(string current, string[] parts, int at, bool directory, string[] found) + { + if (at == parts.Length) + return true; + + string part = parts[at]; + if (part is "." or "..") + { + found[at] = part; + return Walk(Path.Combine(current, part), parts, at + 1, directory, found); + } + + bool last = at == parts.Length - 1; + var matches = Listing(current, files: last && !directory)[part] + .OrderBy(entry => string.Equals(Path.GetFileName(entry), part, StringComparison.Ordinal) ? 0 : 1); + foreach (string match in matches) + { + found[at] = Path.GetFileName(match); + if (Walk(match, parts, at + 1, directory, found)) + return true; + } + return false; + } + + private ILookup Listing(string folder, bool files) => + _listings is null ? List((folder, files)) : _listings.GetOrAdd((folder, files), _list); + + // A folder that cannot be listed holds nothing to be found. + private ILookup List((string Folder, bool Files) key) + { + var entries = Array.Empty(); + try + { + if (_files.DirectoryExists(key.Folder)) + entries = (key.Files ? _files.GetFiles(key.Folder) : _files.GetDirectories(key.Folder)).ToArray(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Nothing listed, nothing found. + } + return entries.ToLookup(entry => Path.GetFileName(entry), StringComparer.OrdinalIgnoreCase); + } +} diff --git a/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs b/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs index 0aa4008..62c68ad 100644 --- a/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs +++ b/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs @@ -23,7 +23,7 @@ public sealed class SceneryRepository : ISceneryRepository private readonly SceneryParser _parser; /// The scenery folders' files and folders, listed once per load of them all. - private readonly ConcurrentDictionary<(string, bool), IReadOnlyList> _listings = new(); + private readonly CaseInsensitivePaths _names; public SceneryRepository(IFileSystem files, IGamePaths paths, IDiagnosticsLog log, SceneryParser parser) { @@ -31,11 +31,12 @@ public sealed class SceneryRepository : ISceneryRepository _paths = paths; _log = log; _parser = parser; + _names = new CaseInsensitivePaths(files, keepListings: true); } public IReadOnlyList LoadAll(IProgress? progress = null) { - _listings.Clear(); + _names.Forget(); var files = SceneryFiles().ToList(); var loaded = new ConcurrentBag(); int total = Math.Max(1, files.Count); @@ -58,7 +59,7 @@ public sealed class SceneryRepository : ISceneryRepository public Scenery? Load(string path) { - _listings.Clear(); + _names.Forget(); return LoadOne(path); } @@ -126,44 +127,7 @@ public sealed class SceneryRepository : ISceneryRepository /// copy written for a start carries in place of the include, so they come along /// on Linux too. /// - private string? ResolveInclude(string name) - { - string relative = name.Replace('\\', '/'); - if (_files.FileExists(Path.Combine(_paths.Scenery, relative))) - return relative; - - string[] parts = relative.Split('/', StringSplitOptions.RemoveEmptyEntries); - string directory = _paths.Scenery; - var found = new List(); - for (int i = 0; i < parts.Length; i++) - { - if (parts[i] is "." or "..") - { - directory = Path.Combine(directory, parts[i]); - found.Add(parts[i]); - continue; - } - - bool last = i == parts.Length - 1; - string? match = Listing(directory, last) - .FirstOrDefault(entry => string.Equals(Path.GetFileName(entry), parts[i], - StringComparison.OrdinalIgnoreCase)); - if (match is null) - return null; - directory = match; - found.Add(Path.GetFileName(match)); - } - - return string.Join('/', found); - } - - private IReadOnlyList Listing(string directory, bool files) => - _listings.GetOrAdd((directory, files), key => - { - if (!_files.DirectoryExists(key.Item1)) - return Array.Empty(); - return key.Item2 ? _files.GetFiles(key.Item1) : _files.GetDirectories(key.Item1); - }); + private string? ResolveInclude(string name) => _names.Resolve(_paths.Scenery, name); private IEnumerable SceneryFiles() => _files.GetFiles(_paths.Scenery, "*.scn") From d4975796a8253d19c7e538f1502bcf851ef4aa4e Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:05:47 +0100 Subject: [PATCH 02/35] fix: find a scenery's image and timetables whatever the case of their names The //$i image and a trainset's timetable are looked up through CaseInsensitivePaths, so on Linux they show when the scenery names them in other letter case than the disk has. A timetable written with backslashes is found there too, and with it the train number of a Hasler tape. --- StarterNG.Tests/ScenarioPresentationTests.cs | 14 ++++++++++ StarterNG.Tests/SceneryRepositoryTests.cs | 17 ++++++++++++ StarterNG.Tests/TapeLaunchTests.cs | 11 ++++++++ .../Sceneries/SceneryImageLocator.cs | 26 +++++++++++-------- .../Sceneries/TimetableLocator.cs | 18 ++++++++----- 5 files changed, 68 insertions(+), 18 deletions(-) diff --git a/StarterNG.Tests/ScenarioPresentationTests.cs b/StarterNG.Tests/ScenarioPresentationTests.cs index 70b3c2f..8448790 100644 --- a/StarterNG.Tests/ScenarioPresentationTests.cs +++ b/StarterNG.Tests/ScenarioPresentationTests.cs @@ -182,6 +182,20 @@ public class TimetableLocatorTests Assert.NotNull(new TimetableLocator(files).Resolve(scenery, "r1.txt")); } + [Theory] + [InlineData(@"rozklady\tgs3657")] + [InlineData("ROZKLADY/TGS3657.TXT")] + public void A_timetable_named_in_other_case_or_with_backslashes_is_found_as_on_disk(string name) + { + var files = new InMemoryFileSystem(caseSensitive: true) + .WithFile(TestInstallation.At("scenery", "Braniewo.scn"), "//$n Braniewo") + .WithFile(TestInstallation.At("scenery", "Rozklady", "TGS3657.txt"), "rozkład"); + var scenery = Assert.Single(new TestInstallation(files).Sceneries.LoadAll()); + + Assert.Equal(TestInstallation.At("scenery", "Rozklady", "TGS3657.txt"), + new TimetableLocator(files).Resolve(scenery, name)); + } + [Fact] public void The_formats_none_and_a_missing_file_both_resolve_to_nothing() { diff --git a/StarterNG.Tests/SceneryRepositoryTests.cs b/StarterNG.Tests/SceneryRepositoryTests.cs index 08dbfcb..44fd753 100644 --- a/StarterNG.Tests/SceneryRepositoryTests.cs +++ b/StarterNG.Tests/SceneryRepositoryTests.cs @@ -89,6 +89,23 @@ public class SceneryRepositoryTests Assert.Equal(Path.Combine("game", "scenery", "images", "kato.jpg"), image); } + [Theory] + [InlineData("calkowo_v2_kopalniaA.jpg", "game/scenery/images/calkowo_v2_kopalniaA.jpg")] + [InlineData(@"Images\Calkowo_V2_KopalniaA.JPG", "game/scenery/images/calkowo_v2_kopalniaA.jpg")] + [InlineData("CALKOWO_V2.JPG", "game/scenery/Calkowo_v2.jpg")] + public void The_preview_image_is_found_whatever_the_case_it_is_named_in(string named, string onDisk) + { + var files = new InMemoryFileSystem(caseSensitive: true) + .WithFile("game/scenery/calkowo.scn", "//$i " + named) + .WithFile("game/scenery/images/calkowo_v2_kopalniaA.jpg", "binary") + .WithFile("game/scenery/Calkowo_v2.jpg", "binary"); + var scenery = Assert.Single(Build(files, out _).LoadAll()); + + string? image = new SceneryImageLocator(files).Resolve(scenery); + + Assert.Equal(Path.GetFullPath(onDisk), Path.GetFullPath(image!)); + } + [Fact] public void A_scenery_without_an_image_directive_resolves_to_nothing() { diff --git a/StarterNG.Tests/TapeLaunchTests.cs b/StarterNG.Tests/TapeLaunchTests.cs index a1285fa..ae1689f 100644 --- a/StarterNG.Tests/TapeLaunchTests.cs +++ b/StarterNG.Tests/TapeLaunchTests.cs @@ -130,6 +130,17 @@ public class TapeLaunchTests Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem()) .TrainNumber(new StarterNG.Domain.Sceneries.Scenery(TestInstallation.At("scenery", "td.scn"), ""), name)); + [Fact] + public void The_train_number_comes_from_a_timetable_named_in_other_case_with_backslashes() + { + var files = new InMemoryFileSystem(caseSensitive: true) + .WithFile(TestInstallation.At("scenery", "Baltyk", "EIE1531.txt"), "[ Rodzaj i numer pociagu | EIE1531 ]\r\n"); + + Assert.Equal("EIE1531", new StarterNG.Infrastructure.Sceneries.TimetableLocator(files) + .TrainNumber(new StarterNG.Domain.Sceneries.Scenery(TestInstallation.At("scenery", "td.scn"), ""), + @"baltyk\eie1531")); + } + [Fact] public void A_timetable_that_is_not_there_gives_no_train_number() => Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem()) diff --git a/StarterNG/Infrastructure/Sceneries/SceneryImageLocator.cs b/StarterNG/Infrastructure/Sceneries/SceneryImageLocator.cs index dba90fe..df266a7 100644 --- a/StarterNG/Infrastructure/Sceneries/SceneryImageLocator.cs +++ b/StarterNG/Infrastructure/Sceneries/SceneryImageLocator.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.IO; +using System.Linq; using StarterNG.Application.Abstractions; using StarterNG.Domain.Sceneries; @@ -8,11 +9,13 @@ namespace StarterNG.Infrastructure.Sceneries; public sealed class SceneryImageLocator { private readonly IFileSystem _files; + private readonly CaseInsensitivePaths _names; private readonly Dictionary _cache = new(); public SceneryImageLocator(IFileSystem files) { _files = files; + _names = new CaseInsensitivePaths(files); } public string? Resolve(Scenery scenery) @@ -34,22 +37,23 @@ public sealed class SceneryImageLocator return null; string name = scenery.ImageName.Replace('\\', '/').Trim(); + if (Path.IsPathFullyQualified(name)) + return _names.Find("", name); + if (_files.FileExists(name)) + return name; + string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? "."; string root = Path.GetDirectoryName(sceneryDir) ?? "."; - string[] candidates = + (string Folder, string Name)[] candidates = { - name, - Path.Combine(root, name), - Path.Combine(sceneryDir, name), - Path.Combine(sceneryDir, "images", name), - Path.Combine(root, "scenery", "images", name) + (root, name), + (sceneryDir, name), + (sceneryDir, "images/" + name), + (root, "scenery/images/" + name) }; - foreach (string candidate in candidates) - if (_files.FileExists(candidate)) - return candidate; - - return null; + return candidates.Select(candidate => _names.Find(candidate.Folder, candidate.Name)) + .FirstOrDefault(found => found is not null); } } diff --git a/StarterNG/Infrastructure/Sceneries/TimetableLocator.cs b/StarterNG/Infrastructure/Sceneries/TimetableLocator.cs index d309b47..35a7614 100644 --- a/StarterNG/Infrastructure/Sceneries/TimetableLocator.cs +++ b/StarterNG/Infrastructure/Sceneries/TimetableLocator.cs @@ -17,10 +17,12 @@ public sealed class TimetableLocator RegexOptions.Multiline | RegexOptions.IgnoreCase); private readonly IFileSystem _files; + private readonly CaseInsensitivePaths _names; public TimetableLocator(IFileSystem files) { _files = files; + _names = new CaseInsensitivePaths(files); } public string? Resolve(Scenery scenery, string? name) @@ -30,17 +32,19 @@ public sealed class TimetableLocator string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? "."; string root = Path.GetDirectoryName(sceneryDir) ?? "."; + name = name.Replace('\\', '/'); - string[] candidates = + (string Folder, string Name)[] candidates = { - Path.Combine(root, "timetables", name + ".txt"), - Path.Combine(sceneryDir, name + ".txt"), - Path.Combine(root, "scenario", name + ".txt"), - Path.Combine(root, "timetables", name), - Path.Combine(sceneryDir, name) + (root, "timetables/" + name + ".txt"), + (sceneryDir, name + ".txt"), + (root, "scenario/" + name + ".txt"), + (root, "timetables/" + name), + (sceneryDir, name) }; - return candidates.FirstOrDefault(_files.FileExists); + return candidates.Select(candidate => _names.Find(candidate.Folder, candidate.Name)) + .FirstOrDefault(found => found is not null); } /// The number the timetable gives its train; null with no timetable or no such heading in it. From 6279228a7d80e1bd52db17e506ff34cd3d322c4f Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:07:04 +0100 Subject: [PATCH 03/35] fix: find a scenery's i18n tables whatever the case of their names The i18n folder and its _.json tables are looked up through CaseInsensitivePaths, so on Linux a scenery's texts are translated when the table is named in other letter case than the scenery file. --- StarterNG.Tests/SceneryTranslationsTests.cs | 18 ++++++++++++++++++ .../Sceneries/SceneryTranslations.cs | 11 ++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/StarterNG.Tests/SceneryTranslationsTests.cs b/StarterNG.Tests/SceneryTranslationsTests.cs index a2d422b..308f794 100644 --- a/StarterNG.Tests/SceneryTranslationsTests.cs +++ b/StarterNG.Tests/SceneryTranslationsTests.cs @@ -39,6 +39,24 @@ public class SceneryTranslationsTests Assert.Equal("Polski", scenery.LocalizedDescription(translations)); } + [Fact] + public void The_tables_are_found_whatever_the_case_of_their_names() + { + var files = new InMemoryFileSystem(caseSensitive: true) + .WithFile(TestInstallation.At("scenery", "Braniewo.scn"), "//$d @brief") + .WithFile(Path.Combine(Path.GetFullPath(TestInstallation.At("scenery")), "I18N", "braniewo_en.json"), + """{ "brief": "English" }""") + .WithFile(Path.Combine(Path.GetFullPath(TestInstallation.At("scenery")), "I18N", "BRANIEWO_PL.json"), + """{ "brief": "Polski" }"""); + var installation = new TestInstallation(files); + var scenery = Assert.Single(installation.Sceneries.LoadAll()); + var translations = new SceneryTranslations(files, installation.Log); + + translations.LoadFor(scenery, "Polski"); + + Assert.Equal("Polski", scenery.LocalizedDescription(translations)); + } + [Fact] public void Literal_text_and_unknown_keys_are_left_alone() { diff --git a/StarterNG/Infrastructure/Sceneries/SceneryTranslations.cs b/StarterNG/Infrastructure/Sceneries/SceneryTranslations.cs index efcc73d..c71b786 100644 --- a/StarterNG/Infrastructure/Sceneries/SceneryTranslations.cs +++ b/StarterNG/Infrastructure/Sceneries/SceneryTranslations.cs @@ -14,12 +14,14 @@ public sealed class SceneryTranslations : ISceneryTranslations private const string BaseLanguage = "en"; private readonly IFileSystem _files; + private readonly CaseInsensitivePaths _names; private readonly IDiagnosticsLog _log; private readonly Dictionary _map = new(StringComparer.OrdinalIgnoreCase); public SceneryTranslations(IFileSystem files, IDiagnosticsLog log) { _files = files; + _names = new CaseInsensitivePaths(files); _log = log; } @@ -29,12 +31,11 @@ public sealed class SceneryTranslations : ISceneryTranslations string sceneryDir = Path.GetDirectoryName(Path.GetFullPath(scenery.Path)) ?? "scenery"; string id = Path.GetFileNameWithoutExtension(scenery.Path); - string i18nDir = Path.Combine(sceneryDir, "i18n"); string language = NormalizeLanguage(langCode); - TryLoad(Path.Combine(i18nDir, $"{id}_{BaseLanguage}.json")); + TryLoad(_names.Find(sceneryDir, $"i18n/{id}_{BaseLanguage}.json")); if (!string.Equals(language, BaseLanguage, StringComparison.OrdinalIgnoreCase)) - TryLoad(Path.Combine(i18nDir, $"{id}_{language}.json")); + TryLoad(_names.Find(sceneryDir, $"i18n/{id}_{language}.json")); } public string Translate(string? text) @@ -50,9 +51,9 @@ public sealed class SceneryTranslations : ISceneryTranslations return _map.TryGetValue(key, out string? translated) ? translated : text; } - private void TryLoad(string path) + private void TryLoad(string? path) { - if (!_files.FileExists(path)) + if (path is null) return; try From 290b753f40a368318f3661e3f78f79e3b25d2ec3 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:07:05 +0100 Subject: [PATCH 04/35] fix: open a scenery's attachments whatever the case of their names A //$f attachment is looked up from the game folder through the new AttachmentLocator, so on Linux its button is enabled and opens the file when the scenery names it in other letter case or with backslashes. --- StarterNG.Tests/ScenarioPresentationTests.cs | 23 ++++++++++++++++++ StarterNG/Application/AppServices.cs | 3 +++ .../Sceneries/AttachmentLocator.cs | 24 +++++++++++++++++++ StarterNG/Views/Scenarios.axaml.cs | 12 ++++------ 4 files changed, 55 insertions(+), 7 deletions(-) create mode 100644 StarterNG/Infrastructure/Sceneries/AttachmentLocator.cs diff --git a/StarterNG.Tests/ScenarioPresentationTests.cs b/StarterNG.Tests/ScenarioPresentationTests.cs index 8448790..75b82cb 100644 --- a/StarterNG.Tests/ScenarioPresentationTests.cs +++ b/StarterNG.Tests/ScenarioPresentationTests.cs @@ -209,3 +209,26 @@ public class TimetableLocatorTests Assert.Null(locator.Resolve(scenery, null)); } } + +public class AttachmentLocatorTests +{ + [Theory] + [InlineData(@"scenery\Braniewo\opis.PDF")] + [InlineData("SCENERY/braniewo/Opis.pdf")] + public void An_attachment_named_in_other_case_is_found_as_on_disk(string named) + { + var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true) + .WithFile(TestInstallation.At("scenery", "Braniewo", "Opis.pdf"), "%PDF")); + + Assert.Equal(TestInstallation.At("scenery", "Braniewo", "Opis.pdf"), + new AttachmentLocator(installation.Files, installation.Paths) + .Resolve(new SceneryAttachment { FilePath = named })); + } + + [Theory] + [InlineData("scenery/brak.pdf")] + [InlineData("")] + public void An_attachment_that_is_not_there_is_not_found(string named) => + Assert.Null(new AttachmentLocator(new InMemoryFileSystem(caseSensitive: true), new TestInstallation().Paths) + .Resolve(new SceneryAttachment { FilePath = named })); +} diff --git a/StarterNG/Application/AppServices.cs b/StarterNG/Application/AppServices.cs index 7f7b6ce..0bf1693 100644 --- a/StarterNG/Application/AppServices.cs +++ b/StarterNG/Application/AppServices.cs @@ -56,6 +56,7 @@ public sealed class AppServices var missingAssets = new MissingAssetScanner(files, paths); SceneryTexts = new SceneryTranslations(files, log); Timetables = new TimetableLocator(files); + Attachments = new AttachmentLocator(files, paths); LoadWeights = new LoadWeightsRepository(files, paths, log); Library = new GameLibrary(Vehicles, Sceneries, MiniTextures, Physics, log); State = new AppState(); @@ -119,6 +120,8 @@ public sealed class AppServices public TimetableLocator Timetables { get; } + public AttachmentLocator Attachments { get; } + public LoadWeightsRepository LoadWeights { get; } public GameLibrary Library { get; } diff --git a/StarterNG/Infrastructure/Sceneries/AttachmentLocator.cs b/StarterNG/Infrastructure/Sceneries/AttachmentLocator.cs new file mode 100644 index 0000000..dab11ec --- /dev/null +++ b/StarterNG/Infrastructure/Sceneries/AttachmentLocator.cs @@ -0,0 +1,24 @@ +using StarterNG.Application.Abstractions; +using StarterNG.Domain.Sceneries; + +namespace StarterNG.Infrastructure.Sceneries; + +/// Where the file a scenery attaches (//$f) is on disk. +public sealed class AttachmentLocator +{ + private readonly IGamePaths _paths; + private readonly CaseInsensitivePaths _names; + + public AttachmentLocator(IFileSystem files, IGamePaths paths) + { + _paths = paths; + _names = new CaseInsensitivePaths(files); + } + + /// + /// The attachment's file, named from the game's folder or in full, with its letters + /// as on disk; null when it is not there. + /// + public string? Resolve(SceneryAttachment attachment) => + string.IsNullOrWhiteSpace(attachment.FilePath) ? null : _names.Find(_paths.Root, attachment.FilePath.Trim()); +} diff --git a/StarterNG/Views/Scenarios.axaml.cs b/StarterNG/Views/Scenarios.axaml.cs index eb00a93..4c0643f 100644 --- a/StarterNG/Views/Scenarios.axaml.cs +++ b/StarterNG/Views/Scenarios.axaml.cs @@ -492,20 +492,18 @@ public partial class Scenarios : UserControl btn.Classes.Add("Flat"); ToolTip.SetTip(btn, att.FilePath); // A button that does nothing is no way to say the file is not there. - btn.IsEnabled = File.Exists(Path.GetFullPath(att.FilePath)); + btn.IsEnabled = AppServices.Current.Attachments.Resolve(att) is not null; ToolTip.SetShowOnDisabled(btn, true); - btn.Click += (_, _) => OpenAttachment(att.FilePath); + btn.Click += (_, _) => OpenAttachment(att); attachmentsPanel.Children.Add(btn); } } - private static void OpenAttachment(string relativePath) + private static void OpenAttachment(SceneryAttachment attachment) { - string full = Path.GetFullPath(relativePath); - if (!File.Exists(full)) - full = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), relativePath)); - if (!File.Exists(full)) + if (AppServices.Current.Attachments.Resolve(attachment) is not { } found) return; + string full = Path.GetFullPath(found); try { Process.Start(new ProcessStartInfo(full) { UseShellExecute = true }); From 52408a99311fee3ba7958a81dac36df1bb7964a0 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:08:06 +0100 Subject: [PATCH 05/35] fix: follow .fiz includes and check vehicle files whatever their case An include in a .fiz is looked up in the vehicle's folder through CaseInsensitivePaths, so its physics are read on Linux when the include names the file in other letter case. The missing-asset scan finds skins and models the same way, with extensions in any case, instead of reporting files that are there. --- StarterNG.Tests/PhysicsAndAssetsTests.cs | 40 ++++++++++++++++++ .../Vehicles/FizPhysicsRepository.cs | 7 +++- .../Vehicles/MissingAssetScanner.cs | 41 +++++++++++-------- 3 files changed, 70 insertions(+), 18 deletions(-) diff --git a/StarterNG.Tests/PhysicsAndAssetsTests.cs b/StarterNG.Tests/PhysicsAndAssetsTests.cs index 1e86f73..5c6066d 100644 --- a/StarterNG.Tests/PhysicsAndAssetsTests.cs +++ b/StarterNG.Tests/PhysicsAndAssetsTests.cs @@ -65,6 +65,19 @@ public class PhysicsAndAssetsTests Assert.Equal(125, physics.VMax); } + [Fact] + public void An_include_named_in_other_case_is_followed() + { + var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true) + .WithFile(Fiz("pkp", "ep07", "ep07"), "include Common.FIZ 84000 end") + .WithFile(TestInstallation.At("dynamic", "pkp", "ep07", "common.fiz"), "Param: M=(1) Vmax=125")); + + var physics = installation.Physics.For("pkp/ep07/", "ep07")!; + + Assert.Equal(84000, physics.Mass); + Assert.Equal(125, physics.VMax); + } + [Fact] public void A_dot_in_the_model_name_is_part_of_the_name() { @@ -202,4 +215,31 @@ public class PhysicsAndAssetsTests Assert.Empty(installation.MissingAssets.Scan(installation.Library.Vehicles)); } + + [Fact] + public void A_livery_with_no_folder_is_looked_for_in_dynamic_itself() + { + var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true) + .WithFile(TestInstallation.At("dynamic", "EP09.bmp"), "bitmap") + .WithFile(TestInstallation.At("dynamic", "ep09.e3d"), "model")); + var catalog = new StarterNG.Domain.Vehicles.VehicleCatalog(installation.MiniTextures); + catalog.Textures.Add(new StarterNG.Domain.Vehicles.VehicleTexture { Directory = "", Skinfile = "ep09", Model = "EP09" }); + + Assert.Empty(installation.MissingAssets.Scan(catalog)); + } + + [Fact] + public void A_skin_and_model_on_disk_in_other_case_are_not_reported() + { + var files = new InMemoryFileSystem(caseSensitive: true) + .WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "textures.txt"), + "EP09-014.mat=ep09.e3d,ep09") + .WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "ep09-014.BMP"), "bitmap") + .WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "EP09.E3D"), "model"); + var installation = new TestInstallation(files); + installation.Vehicles.Load(installation.Library.Vehicles); + Assert.NotEmpty(installation.Library.Vehicles.Textures); + + Assert.Empty(installation.MissingAssets.Scan(installation.Library.Vehicles)); + } } diff --git a/StarterNG/Infrastructure/Vehicles/FizPhysicsRepository.cs b/StarterNG/Infrastructure/Vehicles/FizPhysicsRepository.cs index e17128a..845472d 100644 --- a/StarterNG/Infrastructure/Vehicles/FizPhysicsRepository.cs +++ b/StarterNG/Infrastructure/Vehicles/FizPhysicsRepository.cs @@ -23,6 +23,7 @@ public sealed class FizPhysicsRepository : IPhysicsRepository }; private readonly IFileSystem _files; + private readonly CaseInsensitivePaths _names; private readonly IGamePaths _paths; private readonly IDiagnosticsLog _log; @@ -38,6 +39,7 @@ public sealed class FizPhysicsRepository : IPhysicsRepository public FizPhysicsRepository(IFileSystem files, IGamePaths paths, IDiagnosticsLog log) { _files = files; + _names = new CaseInsensitivePaths(files); _paths = paths; _log = log; } @@ -165,8 +167,9 @@ public sealed class FizPhysicsRepository : IPhysicsRepository while (i < tokens.Count && !tokens[i].Equals("end", StringComparison.OrdinalIgnoreCase)) includeParameters.Add(Resolve(tokens[i++], parameters)); - Parse(physics, Path.Combine(directory, includeFile), directory, includeParameters.ToArray(), - depth + 1); + // Named in the letter case of whoever wrote the include, not always that of the file. + string included = _names.Find(directory, includeFile) ?? Path.Combine(directory, includeFile); + Parse(physics, included, directory, includeParameters.ToArray(), depth + 1); pendingKey = null; continue; } diff --git a/StarterNG/Infrastructure/Vehicles/MissingAssetScanner.cs b/StarterNG/Infrastructure/Vehicles/MissingAssetScanner.cs index d303e69..6c523d7 100644 --- a/StarterNG/Infrastructure/Vehicles/MissingAssetScanner.cs +++ b/StarterNG/Infrastructure/Vehicles/MissingAssetScanner.cs @@ -10,44 +10,53 @@ public sealed class MissingAssetScanner private static readonly string[] TextureExtensions = { ".mat", ".bmp" }; private static readonly string[] ModelExtensions = { ".t3d", ".e3d" }; - private readonly IFileSystem _files; private readonly IGamePaths _paths; + private readonly CaseInsensitivePaths _names; public MissingAssetScanner(IFileSystem files, IGamePaths paths) { - _files = files; _paths = paths; + _names = new CaseInsensitivePaths(files, keepListings: true); } public List Scan(VehicleCatalog catalog) { var lines = new List(); - - foreach (var texture in catalog.Textures) + try { - string directory = Path.Combine( - _paths.Dynamic, - texture.Directory.Replace('/', Path.DirectorySeparatorChar).TrimEnd('\\', '/')); + foreach (var texture in catalog.Textures) + { + string directory = texture.Directory.Replace('\\', '/').TrimEnd('/'); - if (!string.IsNullOrEmpty(texture.Skinfile) && - !ExistsWithAnyExtension(Path.Combine(directory, texture.Skinfile), TextureExtensions)) - lines.Add($"# no file: {texture.Directory}{texture.Skinfile}"); + if (!string.IsNullOrEmpty(texture.Skinfile) && + !ExistsWithAnyExtension(Under(directory, texture.Skinfile), TextureExtensions)) + lines.Add($"# no file: {texture.Directory}{texture.Skinfile}"); - if (!string.IsNullOrEmpty(texture.Model) && - !ExistsWithAnyExtension(Path.Combine(directory, texture.Model), ModelExtensions)) - lines.Add($"# no model: {texture.Directory}{texture.Model}"); + if (!string.IsNullOrEmpty(texture.Model) && + !ExistsWithAnyExtension(Under(directory, texture.Model), ModelExtensions)) + lines.Add($"# no model: {texture.Directory}{texture.Model}"); + } + } + finally + { + // The folders are listed once for the whole catalog, and not kept past it. + _names.Forget(); } return lines; } - private bool ExistsWithAnyExtension(string path, string[] extensions) + private static string Under(string directory, string name) => + directory.Length == 0 ? name : directory + "/" + name; + + /// Whether the file is under dynamic as named, or with one of the extensions, in any letter case. + private bool ExistsWithAnyExtension(string name, string[] extensions) { - if (_files.FileExists(path)) + if (_names.Resolve(_paths.Dynamic, name) is not null) return true; foreach (string extension in extensions) - if (_files.FileExists(Path.ChangeExtension(path, extension))) + if (_names.Resolve(_paths.Dynamic, Path.ChangeExtension(name, extension)) is not null) return true; return false; From 34f2ce99e86d0eef7b88752b0fd48bac89215e20 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:11:58 +0100 Subject: [PATCH 06/35] fix: list files whatever the case of their extensions on Linux PhysicalFileSystem matches a search pattern case-insensitively, as on Windows, so X.SCN, .BMP minis and .FIZ files of data made on Windows are listed on Linux as well. --- StarterNG.Tests/PhysicalFileSystemTests.cs | 14 ++++++++++++++ .../Infrastructure/Adapters/PhysicalFileSystem.cs | 15 +++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/StarterNG.Tests/PhysicalFileSystemTests.cs b/StarterNG.Tests/PhysicalFileSystemTests.cs index 1d0e85c..811e812 100644 --- a/StarterNG.Tests/PhysicalFileSystemTests.cs +++ b/StarterNG.Tests/PhysicalFileSystemTests.cs @@ -21,6 +21,20 @@ public sealed class PhysicalFileSystemTests : IDisposable Assert.Equal(new[] { path }, Directory.GetFiles(_root)); } + [Fact] + public void A_pattern_lists_names_in_any_letter_case() + { + Directory.CreateDirectory(Path.Combine(_root, "PKP", "EP09")); + foreach (string name in new[] { "Braniewo.SCN", "kato.scn", "notes.txt", Path.Combine("PKP", "EP09", "EP09.FIZ"), + Path.Combine("PKP", "EP09", "ep09dumb.fiz") }) + File.WriteAllText(Path.Combine(_root, name), ""); + + Assert.Equal(new[] { "Braniewo.SCN", "kato.scn" }, + _files.GetFiles(_root, "*.scn").Select(Path.GetFileName).Order(StringComparer.Ordinal)); + Assert.Equal(new[] { "EP09.FIZ", "ep09dumb.fiz" }, + _files.GetFilesRecursive(_root, "*.fiz").Select(Path.GetFileName).Order(StringComparer.Ordinal)); + } + [Fact] public void An_atomic_write_that_cannot_finish_leaves_what_stood_there() { diff --git a/StarterNG/Infrastructure/Adapters/PhysicalFileSystem.cs b/StarterNG/Infrastructure/Adapters/PhysicalFileSystem.cs index 14ab1d6..dcdc457 100644 --- a/StarterNG/Infrastructure/Adapters/PhysicalFileSystem.cs +++ b/StarterNG/Infrastructure/Adapters/PhysicalFileSystem.cs @@ -91,8 +91,18 @@ public sealed class PhysicalFileSystem : IFileSystem public void CopyFile(string sourcePath, string destinationPath, bool overwrite) => File.Copy(sourcePath, destinationPath, overwrite); + // The pattern matches names in any letter case, as on Windows: the game's data, + // made there, has X.SCN as well as x.scn. public IReadOnlyList GetFiles(string path, string searchPattern = "*") => - Directory.Exists(path) ? Directory.GetFiles(path, searchPattern) : Array.Empty(); + Directory.Exists(path) + ? Directory.GetFiles(path, searchPattern, new EnumerationOptions + { + IgnoreInaccessible = false, + AttributesToSkip = 0, + MatchType = MatchType.Win32, + MatchCasing = MatchCasing.CaseInsensitive + }) + : Array.Empty(); // A folder it may not enter costs what is in it, not the whole listing. public IReadOnlyList GetFilesRecursive(string path, string searchPattern) => @@ -102,7 +112,8 @@ public sealed class PhysicalFileSystem : IFileSystem RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = 0, - MatchType = MatchType.Win32 + MatchType = MatchType.Win32, + MatchCasing = MatchCasing.CaseInsensitive }) : Array.Empty(); From 2efae83b579f5bf3bdc8533882acc653eaa8762b Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:09:51 +0100 Subject: [PATCH 07/35] fix: find the loading screen logo whatever the case of its name The textures/logo folder and a trainset's or scenery's logo in it are looked up through CaseInsensitivePaths, with extensions in any case, so on Linux the chosen logo is shown instead of a random one or none. The lookup takes the file system, so it is tested. --- StarterNG.Tests/LoadingScreenLogoTests.cs | 28 +++++++++++++ StarterNG/Infrastructure/LoadingScreen.cs | 49 ++++++++++++++--------- 2 files changed, 57 insertions(+), 20 deletions(-) create mode 100644 StarterNG.Tests/LoadingScreenLogoTests.cs diff --git a/StarterNG.Tests/LoadingScreenLogoTests.cs b/StarterNG.Tests/LoadingScreenLogoTests.cs new file mode 100644 index 0000000..a00dd83 --- /dev/null +++ b/StarterNG.Tests/LoadingScreenLogoTests.cs @@ -0,0 +1,28 @@ +using StarterNG.Infrastructure; +using StarterNG.Tests.Fakes; + +namespace StarterNG.Tests; + +public class LoadingScreenLogoTests +{ + private static InMemoryFileSystem Logos() => new InMemoryFileSystem(caseSensitive: true) + .WithFile("game/Textures/Logo/EP09_Logo.PNG", "png") + .WithFile("game/Textures/Logo/Braniewo.JPG", "jpg") + .WithFile("game/Textures/Logo/Logo1.BMP", "bmp") + .WithFile("game/Textures/Logo/notes.txt", ""); + + [Theory] + [InlineData("ep09_logo", null, "EP09_Logo.PNG")] + [InlineData("ep09_logo.bmp", "braniewo", "EP09_Logo.PNG")] + [InlineData(null, "braniewo", "Braniewo.JPG")] + [InlineData("brak", "brak", "Logo1.BMP")] + public void The_logo_is_found_whatever_the_case_of_its_name_and_extension(string? logo, string? scenery, + string onDisk) => + Assert.Equal(Path.GetFullPath(Path.Combine("game", "Textures", "Logo", onDisk)), + Path.GetFullPath(LoadingScreen.FindSource(Logos(), "game", logo, scenery, new Random(1))!)); + + [Fact] + public void With_no_logo_folder_there_is_no_logo() => + Assert.Null(LoadingScreen.FindSource(new InMemoryFileSystem(caseSensitive: true), "game", "x", "y", + new Random(1))); +} diff --git a/StarterNG/Infrastructure/LoadingScreen.cs b/StarterNG/Infrastructure/LoadingScreen.cs index 97ea515..eeca8fa 100644 --- a/StarterNG/Infrastructure/LoadingScreen.cs +++ b/StarterNG/Infrastructure/LoadingScreen.cs @@ -5,16 +5,21 @@ using System.Runtime.InteropServices; using Avalonia; using Avalonia.Media.Imaging; using Avalonia.Platform; +using StarterNG.Application.Abstractions; +using StarterNG.Infrastructure.Adapters; namespace StarterNG.Infrastructure; public static class LoadingScreen { + private static readonly string[] Extensions = { ".bmp", ".jpg", ".jpeg", ".png" }; + public static void Prepare(string? logoKey, string? sceneryName = null) { try { - string? src = ResolveSource(logoKey) ?? ResolveSource(sceneryName) ?? PickRandom(); + string? src = FindSource(new PhysicalFileSystem(), Directory.GetCurrentDirectory(), logoKey, sceneryName, + Random.Shared); if (src is null) return; string destDir = Path.Combine(Directory.GetCurrentDirectory(), "textures"); @@ -35,32 +40,36 @@ public static class LoadingScreen } } - private static string? ResolveSource(string? key) + /// + /// The picture of textures/logo under to show: the trainset's, + /// else the scenery's, else one of logo*.* at random; its name and extension in any + /// letter case. Null when there is none. + /// + public static string? FindSource(IFileSystem files, string root, string? logoKey, string? sceneryName, + Random random) + { + var names = new CaseInsensitivePaths(files); + if (names.Find(root, "textures/logo", directory: true) is not { } dir) + return null; + return Named(names, dir, logoKey) ?? Named(names, dir, sceneryName) ?? PickRandom(files, dir, random); + } + + private static string? Named(CaseInsensitivePaths names, string dir, string? key) { if (string.IsNullOrWhiteSpace(key)) return null; key = Path.GetFileNameWithoutExtension(key.Trim()); - string dir = Path.Combine(Directory.GetCurrentDirectory(), "textures", "logo"); - foreach (string ext in new[] { ".bmp", ".jpg", ".jpeg", ".png" }) - { - string path = Path.Combine(dir, key + ext); - if (File.Exists(path)) return path; - } - return null; + if (key.Length == 0) return null; + return Extensions.Select(ext => names.Find(dir, key + ext)).FirstOrDefault(path => path is not null); } - private static string? PickRandom() + private static string? PickRandom(IFileSystem files, string dir, Random random) { - string dir = Path.Combine(Directory.GetCurrentDirectory(), "textures", "logo"); - if (!Directory.Exists(dir)) return null; - var files = Directory.GetFiles(dir, "logo*.*") - .Where(f => - { - string e = Path.GetExtension(f).ToLowerInvariant(); - return e is ".bmp" or ".jpg" or ".jpeg" or ".png"; - }) + var logos = files.GetFiles(dir, "logo*.*") + .Where(f => Extensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase)) + .Order(StringComparer.Ordinal) .ToArray(); - if (files.Length == 0) return null; - return files[Random.Shared.Next(files.Length)]; + if (logos.Length == 0) return null; + return logos[random.Next(logos.Length)]; } private static void WriteBmp(string sourcePath, string destPath) From 7f57160aae455c75fbfe89cb848d5217631b1211 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:09:52 +0100 Subject: [PATCH 08/35] fix: open a livery's folder whatever the case of its name "Open texture folder" finds the folder under dynamic, or from the game folder, through CaseInsensitivePaths, so on Linux it opens the folder when textures.txt names it in other letter case. --- StarterNG.Tests/TextureFolderTests.cs | 22 +++++++++++++++++ .../Infrastructure/Vehicles/TextureFolder.cs | 24 +++++++++++++++++++ StarterNG/Views/Depot/TextureMenuItems.cs | 12 ++++------ 3 files changed, 50 insertions(+), 8 deletions(-) create mode 100644 StarterNG.Tests/TextureFolderTests.cs create mode 100644 StarterNG/Infrastructure/Vehicles/TextureFolder.cs diff --git a/StarterNG.Tests/TextureFolderTests.cs b/StarterNG.Tests/TextureFolderTests.cs new file mode 100644 index 0000000..2384c37 --- /dev/null +++ b/StarterNG.Tests/TextureFolderTests.cs @@ -0,0 +1,22 @@ +using StarterNG.Domain.Vehicles; +using StarterNG.Infrastructure.Vehicles; +using StarterNG.Tests.Fakes; + +namespace StarterNG.Tests; + +public class TextureFolderTests +{ + private static readonly TestInstallation Installation = new(new InMemoryFileSystem(caseSensitive: true) + .WithFile("game/dynamic/PKP/EP09_v1/textures.txt", "") + .WithDirectory("game/Other/Folder")); + + [Theory] + [InlineData("pkp/ep09_v1/", "dynamic/PKP/EP09_v1")] + [InlineData(@"PKP\EP09_V1", "dynamic/PKP/EP09_v1")] + [InlineData("other/folder/", "Other/Folder")] + [InlineData("pkp/brak/", "pkp/brak")] + public void A_liverys_folder_is_found_as_it_is_named_on_disk(string named, string onDisk) => + Assert.Equal(Path.GetFullPath(Path.Combine("game", onDisk)), + Path.GetFullPath(TextureFolder.Of(Installation.Files, Installation.Paths, + new VehicleTexture { Directory = named }))); +} diff --git a/StarterNG/Infrastructure/Vehicles/TextureFolder.cs b/StarterNG/Infrastructure/Vehicles/TextureFolder.cs new file mode 100644 index 0000000..530d5bb --- /dev/null +++ b/StarterNG/Infrastructure/Vehicles/TextureFolder.cs @@ -0,0 +1,24 @@ +using System.IO; +using StarterNG.Application.Abstractions; +using StarterNG.Domain.Vehicles; + +namespace StarterNG.Infrastructure.Vehicles; + +public static class TextureFolder +{ + /// + /// A livery's folder as it is named on disk: under dynamic, or from the game's folder + /// when its name starts there, in any letter case. Where it would be when it is not there. + /// + public static string Of(IFileSystem files, IGamePaths paths, VehicleTexture texture) + { + string directory = texture.Directory.Replace('\\', '/').TrimEnd('/'); + if (directory.Length == 0) + return paths.Dynamic; + + var names = new CaseInsensitivePaths(files); + return names.Find(paths.Dynamic, directory, directory: true) ?? + names.Find(paths.Root, directory, directory: true) ?? + Path.Combine(paths.Root, directory.Replace('/', Path.DirectorySeparatorChar)); + } +} diff --git a/StarterNG/Views/Depot/TextureMenuItems.cs b/StarterNG/Views/Depot/TextureMenuItems.cs index b54810e..0461a99 100644 --- a/StarterNG/Views/Depot/TextureMenuItems.cs +++ b/StarterNG/Views/Depot/TextureMenuItems.cs @@ -1,8 +1,10 @@ using System.IO; using Avalonia.Controls; using Avalonia.Input.Platform; +using StarterNG.Application; using StarterNG.Domain; using StarterNG.Domain.Vehicles; +using StarterNG.Infrastructure.Vehicles; namespace StarterNG.Views; @@ -17,13 +19,7 @@ internal static class TextureMenuItems if (TopLevel.GetTopLevel(owner)?.Clipboard is { } clipboard) await clipboard.SetTextAsync(Consist.Base(texture.Skinfile)); }); - menu.AddItem(App.Loc["OpenTextureFolder"], () => Infrastructure.Diagnostics.OpenOrReport(FolderOf(texture))); - } - - private static string FolderOf(VehicleTexture texture) - { - string dir = Path.Combine(Directory.GetCurrentDirectory(), "dynamic", - texture.Directory.Replace('/', Path.DirectorySeparatorChar).TrimEnd('\\', '/')); - return Directory.Exists(dir) ? dir : Path.Combine(Directory.GetCurrentDirectory(), texture.Directory); + menu.AddItem(App.Loc["OpenTextureFolder"], () => Infrastructure.Diagnostics.OpenOrReport( + Path.GetFullPath(TextureFolder.Of(AppServices.Current.Files, AppServices.Current.Paths, texture)))); } } From 42f702a0962ad382ce82ed4b1fc4b8be81fa0623 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:11:10 +0100 Subject: [PATCH 09/35] fix: an include in other letter case is no fault, as eu07 opens it eu07 now finds files whatever the case of their names on Linux too (MaSzyna-EU07/maszyna#362), so the starter no longer folds an include or a scenery's .sbt to lower case to judge whether the simulator opens it: it looks them up through CaseInsensitivePaths. The IncludeLetterCase fault and its texts go, being a false alarm now, and the parser takes a plain yes or no for each include. --- StarterNG.Tests/ScenerySyntaxTests.cs | 23 ++++++++--------- StarterNG/Domain/Sceneries/SceneryFault.cs | 7 ------ StarterNG/Domain/Sceneries/ScenerySyntax.cs | 25 ++++++------------- .../Infrastructure/Sceneries/SceneryParser.cs | 8 +++--- .../Sceneries/SceneryRepository.cs | 16 ++++++------ StarterNG/startercfg/lang/cz.xml | 1 - StarterNG/startercfg/lang/en.xml | 1 - StarterNG/startercfg/lang/hu.xml | 1 - StarterNG/startercfg/lang/pl.xml | 1 - StarterNG/startercfg/lang/ru.xml | 1 - 10 files changed, 29 insertions(+), 55 deletions(-) diff --git a/StarterNG.Tests/ScenerySyntaxTests.cs b/StarterNG.Tests/ScenerySyntaxTests.cs index 3052cd3..39fede4 100644 --- a/StarterNG.Tests/ScenerySyntaxTests.cs +++ b/StarterNG.Tests/ScenerySyntaxTests.cs @@ -273,7 +273,7 @@ public class ScenerySyntaxTests include koniec.scm """; - var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => new IncludeLookup(true)); + var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => true); Assert.Empty(scenery.Faults); Assert.Equal("td/rozklad", Assert.Single(scenery.Trainsets).Name); @@ -326,7 +326,7 @@ public class ScenerySyntaxTests endoptional """; - var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, name => new IncludeLookup(name is "tory.scm" or "budynek.inc")).Faults; + var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, name => name is "tory.scm" or "budynek.inc").Faults; Assert.Equal((SceneryFaultKind.MissingInclude, "x.scn", 2, null, "brak.scm"), Seen(Assert.Single(faults))); } @@ -347,9 +347,9 @@ public class ScenerySyntaxTests } [Fact] - public void An_include_on_disk_only_in_other_letter_case_is_what_linux_misses() + public void An_include_on_disk_in_other_letter_case_is_no_fault() { - // The simulator folds the name to lower case and opens it so. + // The simulator finds the file whatever the case of its letters, on Linux too. var files = new InMemoryFileSystem(caseSensitive: true) .WithLegacyFile("game/scenery/braniewo_szeroki.scn", "include braniewo/base.ctr end\ninclude Braniewo/Tory.SCM end\n") @@ -357,21 +357,20 @@ public class ScenerySyntaxTests .WithFile("game/scenery/braniewo/tory.scm", ""); var repository = TestScenery.Repository(files); - var faults = repository.Load("game/scenery/braniewo_szeroki.scn")!.Faults; - - Assert.Equal((SceneryFaultKind.IncludeLetterCase, "braniewo_szeroki.scn", 1, "Braniewo/Base.ctr", "braniewo/base.ctr"), - Seen(Assert.Single(faults))); + Assert.Empty(repository.Load("game/scenery/braniewo_szeroki.scn")!.Faults); } [Theory] - [InlineData(true)] - [InlineData(false)] - public void A_missing_terrain_file_is_no_fault_while_the_scenery_has_its_own_sbt(bool sbt) + [InlineData(null)] + [InlineData("lk2_sandbox.sbt")] + [InlineData("Lk2_Sandbox.SBT")] + public void A_missing_terrain_file_is_no_fault_while_the_scenery_has_its_own_sbt(string? sbtOnDisk) { + bool sbt = sbtOnDisk is not null; var files = new InMemoryFileSystem(caseSensitive: true) .WithLegacyFile("game/scenery/Lk2_Sandbox.scn", "include nmt/nmt100_mazowieckie_ter.scm end\nFirstInit\n"); if (sbt) - files.WithFile("game/scenery/lk2_sandbox.sbt", "EU07"); + files.WithFile("game/scenery/" + sbtOnDisk, "EU07"); var repository = TestScenery.Repository(files); var scenery = repository.Load("game/scenery/Lk2_Sandbox.scn")!; diff --git a/StarterNG/Domain/Sceneries/SceneryFault.cs b/StarterNG/Domain/Sceneries/SceneryFault.cs index 2fd42ef..1b4f5f7 100644 --- a/StarterNG/Domain/Sceneries/SceneryFault.cs +++ b/StarterNG/Domain/Sceneries/SceneryFault.cs @@ -61,13 +61,6 @@ public enum SceneryFaultKind /// An include whose file is not there; names it. MissingInclude, - /// - /// An include whose file is there only under a name in other letter case: the - /// simulator looks for it in lower case, which on Linux misses it. The - /// holds the name on disk. - /// - IncludeLetterCase, - /// An include with no end, which swallows what follows it. IncludeNotClosed, diff --git a/StarterNG/Domain/Sceneries/ScenerySyntax.cs b/StarterNG/Domain/Sceneries/ScenerySyntax.cs index a943d32..87ee063 100644 --- a/StarterNG/Domain/Sceneries/ScenerySyntax.cs +++ b/StarterNG/Domain/Sceneries/ScenerySyntax.cs @@ -5,12 +5,6 @@ using System.Linq; namespace StarterNG.Domain.Sceneries; -/// -/// What the simulator makes of an include: whether it opens the file - and when -/// it does not, the file that is there under a name differing only in letter case. -/// -public readonly record struct IncludeLookup(bool Opens, string? OnDisk = null); - /// /// Goes through a scenery's text for the parts the starter reads - trainsets, /// vehicles, includes - finding where each trainset and loose vehicle is, and @@ -35,17 +29,17 @@ public static class ScenerySyntax /// The scenery's text, its includes put in place. /// The scenery's file name, for faults in its own text. - /// - /// What the simulator makes of an include, named as the include names it; null + /// + /// Whether the simulator opens an include, named as the include names it; null /// leaves includes unchecked. /// - public static Result Scan(string text, string file, Func? findInclude = null) + public static Result Scan(string text, string file, Func? opensInclude = null) { string code = SceneryCode.Mask(text, out int unclosed); var tokens = SceneryCode.Tokens(code); var lines = new SceneryLines(text, file); - var simulator = new Reading(tokens, lines, findInclude, asSimulator: true); + var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true); simulator.Run(); var author = new Reading(tokens, lines, null, asSimulator: false); author.Run(); @@ -116,7 +110,7 @@ public static class ScenerySyntax } private sealed class Reading( - List tokens, SceneryLines lines, Func? findInclude, bool asSimulator) + List tokens, SceneryLines lines, Func? opensInclude, bool asSimulator) { public readonly List<(int Start, int End, string Name)> Trainsets = new(); public readonly List<(int, int)> Loose = new(); @@ -375,13 +369,8 @@ public static class ScenerySyntax return stop < tokens.Count && tokens[stop].Is("end") ? stop : stop - 1; } - if (findInclude is not null && Plain(name) && findInclude(name) is { Opens: false } lookup) - { - if (lookup.OnDisk is { } onDisk) - Fault(SceneryFaultKind.IncludeLetterCase, token.Index, onDisk, name); - else - Fault(SceneryFaultKind.MissingInclude, token.Index, token: name); - } + if (opensInclude is not null && Plain(name) && !opensInclude(name)) + Fault(SceneryFaultKind.MissingInclude, token.Index, token: name); // The simulator takes its parameters up to the word "end", written just so, // whatever comes before it. diff --git a/StarterNG/Infrastructure/Sceneries/SceneryParser.cs b/StarterNG/Infrastructure/Sceneries/SceneryParser.cs index e7d3bac..f8072ba 100644 --- a/StarterNG/Infrastructure/Sceneries/SceneryParser.cs +++ b/StarterNG/Infrastructure/Sceneries/SceneryParser.cs @@ -20,11 +20,11 @@ public sealed class SceneryParser _random = random; } - /// - /// What the simulator makes of an include, as the include names it; null leaves + /// + /// Whether the simulator opens an include, as the include names it; null leaves /// includes unchecked. /// - public Scenery Parse(string path, string content, Func? findInclude = null) + public Scenery Parse(string path, string content, Func? opensInclude = null) { string original = content; @@ -38,7 +38,7 @@ public sealed class SceneryParser // Read from the text with its optional includes blanked, which keeps every // place where it was, so a fault's line is the line in the file. - var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), findInclude); + var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), opensInclude); var faults = syntax.Faults.ToList(); var inlined = SceneryIncludes.Ranges(content); diff --git a/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs b/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs index 62c68ad..229d59a 100644 --- a/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs +++ b/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs @@ -80,10 +80,8 @@ 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"); - IncludeLookup FindInclude(string name) => - Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm")) - ? new IncludeLookup(true) - : new IncludeLookup(false, ResolveInclude(name)); + bool OpensInclude(string name) => + Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm")); (string File, string Text)? ReadInclude(string name) { @@ -100,7 +98,7 @@ public sealed class SceneryRepository : ISceneryRepository string own = LegacyText.Decode(_files.ReadAllBytes(path), out var ownEncoding); string text = SceneryIncludes.Inline(own, ReadInclude); - var scenery = _parser.Parse(path, text, FindInclude); + var scenery = _parser.Parse(path, text, OpensInclude); scenery.HasCompanionTimetable = binaryTerrain; scenery.Sources = sources; scenery.TextEncoding = ownEncoding; @@ -115,11 +113,11 @@ public sealed class SceneryRepository : ISceneryRepository } /// - /// Whether the simulator opens a file of the scenery folder named so: by the - /// name in lower case, which on Linux has to be how it is named on disk. + /// Whether the simulator opens a file of the scenery folder named so: whatever the + /// case of its letters, on Linux too. A shade more lenient than eu07 there, which + /// folds only the letters A to Z and of two folders named alike takes the first. /// - private bool Opens(string name) => - _files.FileExists(Path.Combine(_paths.Scenery, SimulatorNames.Lower(name.Replace('\\', '/')))); + private bool Opens(string name) => ResolveInclude(name) is not null; /// /// An include's file as it is named on disk, from the scenery folder, whatever diff --git a/StarterNG/startercfg/lang/cz.xml b/StarterNG/startercfg/lang/cz.xml index 0bb1d32..64df1b5 100644 --- a/StarterNG/startercfg/lang/cz.xml +++ b/StarterNG/startercfg/lang/cz.xml @@ -742,7 +742,6 @@ Vozidlo {0} stojí mimo soupravu: chybí záhlaví trainset? {0}: „{1}“ místo čísla Soubor {1} nenalezen (include) - Soubor {1} je na disku jako {0}: linuxový eu07 ho nenačte include {1} bez end Soupravu {0} se nepodařilo načíst Vozidlo {0} se nepodařilo načíst diff --git a/StarterNG/startercfg/lang/en.xml b/StarterNG/startercfg/lang/en.xml index e0a4ba1..3e1c383 100644 --- a/StarterNG/startercfg/lang/en.xml +++ b/StarterNG/startercfg/lang/en.xml @@ -772,7 +772,6 @@ Vehicle {0} stands outside a trainset: header missing? {0}: “{1}” instead of a number File {1} not found (include) - File {1} is on disk as {0}: the Linux eu07 will not load it include {1} without end Trainset {0} could not be read Vehicle {0} could not be read diff --git a/StarterNG/startercfg/lang/hu.xml b/StarterNG/startercfg/lang/hu.xml index 4c1a4dc..d7286f1 100644 --- a/StarterNG/startercfg/lang/hu.xml +++ b/StarterNG/startercfg/lang/hu.xml @@ -742,7 +742,6 @@ A(z) {0} jármű szerelvényen kívül áll: hiányzik a trainset fejléc? {0}: „{1}” szám helyett A(z) {1} fájl nem található (include) - A(z) {1} fájl a lemezen {0} néven van: a linuxos eu07 nem tölti be include {1} end nélkül A(z) {0} szerelvényt nem sikerült beolvasni A(z) {0} járművet nem sikerült beolvasni diff --git a/StarterNG/startercfg/lang/pl.xml b/StarterNG/startercfg/lang/pl.xml index 3713dd5..7e2df79 100644 --- a/StarterNG/startercfg/lang/pl.xml +++ b/StarterNG/startercfg/lang/pl.xml @@ -769,7 +769,6 @@ Pojazd {0} stoi poza składem: brak nagłówka trainset? {0}: „{1}” zamiast liczby Brak pliku {1} (include) - Plik {1} jest na dysku jako {0}: linuksowy eu07 go nie wczyta include {1} bez end Nie udało się odczytać składu {0} Nie udało się odczytać pojazdu {0} diff --git a/StarterNG/startercfg/lang/ru.xml b/StarterNG/startercfg/lang/ru.xml index c73f842..280351e 100644 --- a/StarterNG/startercfg/lang/ru.xml +++ b/StarterNG/startercfg/lang/ru.xml @@ -742,7 +742,6 @@ Транспорт {0} стоит вне состава: нет заголовка trainset? {0}: «{1}» вместо числа Файл {1} не найден (include) - Файл {1} на диске назван {0}: eu07 на Linux его не загрузит include {1} без end Не удалось прочитать состав {0} Не удалось прочитать единицу {0} From 1b41ef752a75c1755b3e23e0624e35ff252fcd63 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:13:18 +0100 Subject: [PATCH 10/35] chore: version 1.6 Data names are now found whatever their letter case on Linux. --- StarterNG/StarterNG.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/StarterNG/StarterNG.csproj b/StarterNG/StarterNG.csproj index a8f2865..63f062d 100644 --- a/StarterNG/StarterNG.csproj +++ b/StarterNG/StarterNG.csproj @@ -12,7 +12,7 @@ true - 1.5 + 1.6 Starter eu07.pl From 7cd3ef8f1a8d9fff2393b503a47e2e817fc2043c Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 17:44:26 +0100 Subject: [PATCH 11/35] test: the in-memory disk has the root of an absolute Linux path --- StarterNG.Tests/Fakes/InMemoryFileSystem.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/StarterNG.Tests/Fakes/InMemoryFileSystem.cs b/StarterNG.Tests/Fakes/InMemoryFileSystem.cs index 0709309..22c2868 100644 --- a/StarterNG.Tests/Fakes/InMemoryFileSystem.cs +++ b/StarterNG.Tests/Fakes/InMemoryFileSystem.cs @@ -275,6 +275,9 @@ public sealed class InMemoryFileSystem : IFileSystem return; slash = key.LastIndexOf('/'); } + // An absolute Unix path's parent is the root, "/", which normalises to "". + if (slash == 0) + _directories.Add(""); } private static string Normalize(string path) => From 91c496ab4894d1e921038fe6bfd70bc3afae4265 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 14:41:48 +0100 Subject: [PATCH 12/35] fix: graphics wrappers beside the starter no longer reach its window ReShade installed for Direct3D as dxgi.dll in the simulator's folder was loaded into the starter as well, and its window came up empty. The system dxgi, d3d11, d3d9 and opengl32 are loaded first, and the window code's own imports are handed those. The simulator still finds its wrappers. --software-render draws the window on the processor, on Windows and X11, for a machine on which it still comes up empty. --- .../Infrastructure/SystemGraphicsLibraries.cs | 76 +++++++++++++++++++ StarterNG/Program.cs | 29 +++++++ 2 files changed, 105 insertions(+) create mode 100644 StarterNG/Infrastructure/SystemGraphicsLibraries.cs diff --git a/StarterNG/Infrastructure/SystemGraphicsLibraries.cs b/StarterNG/Infrastructure/SystemGraphicsLibraries.cs new file mode 100644 index 0000000..2aa2f3a --- /dev/null +++ b/StarterNG/Infrastructure/SystemGraphicsLibraries.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace StarterNG.Infrastructure; + +/// +/// The starter sits in the simulator's folder, and so do the graphics wrappers a player +/// puts there for the simulator - ReShade and the like, named after the system library +/// they stand in for. Windows looks in the program's own folder first, so the starter's +/// window drew through them too, and with some of them it drew nothing at all. +/// Loaded from System32 by full path before anything asks for them, these names are +/// taken: a native library that asks by name gets the system one. .NET looks beside the +/// program by full path before it asks by name, so the window code's own imports are +/// handed the same libraries. The simulator is a process of its own and still finds its +/// wrappers. +/// Elsewhere there is nothing of the kind to keep out. Under Wine or Proton the system +/// folder is the prefix's, so what is taken there is what would have been taken anyway. +/// +public static class SystemGraphicsLibraries +{ + // dxgi ahead of d3d11, which asks for it. + private static readonly string[] Names = { "dxgi", "d3d11", "d3d9", "opengl32" }; + + private static readonly Dictionary Loaded = new(StringComparer.OrdinalIgnoreCase); + private static readonly List Shadowed = new(); + + /// The assemblies whose imports of these libraries are to get the system ones. + public static void LoadFirst(params Assembly[] importers) + { + if (!OperatingSystem.IsWindows()) + return; + + string system = Environment.SystemDirectory; + string own = AppContext.BaseDirectory; + + foreach (string name in Names) + { + string file = name + ".dll"; + if (File.Exists(Path.Combine(own, file))) + Shadowed.Add(file); + if (NativeLibrary.TryLoad(Path.Combine(system, file), out IntPtr handle)) + Loaded[name] = handle; + } + + foreach (var importer in importers) + { + try + { + NativeLibrary.SetDllImportResolver(importer, Resolve); + } + catch (InvalidOperationException) + { + // It has a resolver of its own already; that one decides. + } + } + } + + private static IntPtr Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) + { + string name = libraryName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + ? libraryName[..^4] + : libraryName; + // Zero leaves the library to the usual search. + return Loaded.TryGetValue(name, out IntPtr handle) ? handle : IntPtr.Zero; + } + + /// Which of them lay beside the starter, once the log can take it. + public static void LogShadowed() + { + if (Shadowed.Count > 0) + Diagnostics.Log($"Graphics libraries beside the starter, left to the simulator: {string.Join(", ", Shadowed)}"); + } +} diff --git a/StarterNG/Program.cs b/StarterNG/Program.cs index 2c1beca..da02172 100644 --- a/StarterNG/Program.cs +++ b/StarterNG/Program.cs @@ -1,6 +1,7 @@ using Avalonia; using Avalonia.Threading; using System; +using System.Linq; using System.Threading.Tasks; using StarterNG.Application; using StarterNG.Infrastructure; @@ -10,12 +11,24 @@ namespace StarterNG; static class Program { + /// + /// Drawn by the processor instead of the graphics card, for a machine on which the + /// window comes up empty. Started with --software-render. + /// + private static bool _softwareRender; + [STAThread] public static void Main(string[] args) { + // Ahead of everything that could draw: what lies beside the starter is the simulator's. + SystemGraphicsLibraries.LoadFirst(typeof(Win32PlatformOptions).Assembly); + + _softwareRender = args.Any(a => string.Equals(a, "--software-render", StringComparison.OrdinalIgnoreCase)); + // Composition root first: everything below, including the crash handlers, // resolves its collaborators from this graph. AppServices.Initialize(); + SystemGraphicsLibraries.LogShadowed(); AppDomain.CurrentDomain.UnhandledException += (_, e) => { @@ -63,9 +76,25 @@ static class Program }; } + // Each platform reads only its own options, so both can be given everywhere. + private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) => + _softwareRender + ? builder + .With(new Win32PlatformOptions + { + RenderingMode = new[] { Win32RenderingMode.Software }, + CompositionMode = new[] { Win32CompositionMode.RedirectionSurface } + }) + .With(new X11PlatformOptions + { + RenderingMode = new[] { X11RenderingMode.Software } + }) + : builder; + public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() .UsePlatformDetect() + .WithSoftwareRenderIfAsked() .WithInterFont() .WithDiagnosticsLogging() .AfterSetup(_ => LogUiExceptions()); From 6e2dbf9eac5b8130a6b13187bad8efc35590d527 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 17:30:13 +0100 Subject: [PATCH 13/35] test: the system graphics libraries and the software render switch Taking the libraries and the switch's options are apart from Main, so they are tested on every system, not only where Windows has them to load. --- StarterNG.Tests/SoftwareRenderTests.cs | 45 +++++++++ .../SystemGraphicsLibrariesTests.cs | 98 +++++++++++++++++++ StarterNG/Infrastructure/SoftwareRender.cs | 32 ++++++ .../Infrastructure/SystemGraphicsLibraries.cs | 80 ++++++++------- StarterNG/Program.cs | 27 ++--- 5 files changed, 228 insertions(+), 54 deletions(-) create mode 100644 StarterNG.Tests/SoftwareRenderTests.cs create mode 100644 StarterNG.Tests/SystemGraphicsLibrariesTests.cs create mode 100644 StarterNG/Infrastructure/SoftwareRender.cs diff --git a/StarterNG.Tests/SoftwareRenderTests.cs b/StarterNG.Tests/SoftwareRenderTests.cs new file mode 100644 index 0000000..88cc2c9 --- /dev/null +++ b/StarterNG.Tests/SoftwareRenderTests.cs @@ -0,0 +1,45 @@ +using Avalonia; +using StarterNG.Infrastructure; + +namespace StarterNG.Tests; + +public class SoftwareRenderTests +{ + [Theory] + [InlineData("--software-render")] + [InlineData("--Software-Render")] + public void The_switch_asks_for_it_in_any_case(string arg) + { + Assert.True(SoftwareRender.AskedIn(new[] { "--other", arg })); + } + + [Fact] + public void Without_the_switch_the_graphics_card_draws() + { + Assert.False(SoftwareRender.AskedIn(Array.Empty())); + Assert.False(SoftwareRender.AskedIn(new[] { "--software" })); + } + + [Fact] + public void Windows_draws_on_the_processor_into_a_plain_window_surface() + { + var options = SoftwareRender.Win32Options; + + Assert.Equal(new[] { Win32RenderingMode.Software }, options.RenderingMode); + Assert.Equal(new[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode); + } + + [Fact] + public void X11_draws_on_the_processor() + { + Assert.Equal(new[] { X11RenderingMode.Software }, SoftwareRender.X11Options.RenderingMode); + } + + [Fact] + public void Both_platforms_options_go_to_the_same_builder() + { + var builder = AppBuilder.Configure(); + + Assert.Same(builder, SoftwareRender.ApplyTo(builder)); + } +} diff --git a/StarterNG.Tests/SystemGraphicsLibrariesTests.cs b/StarterNG.Tests/SystemGraphicsLibrariesTests.cs new file mode 100644 index 0000000..875699b --- /dev/null +++ b/StarterNG.Tests/SystemGraphicsLibrariesTests.cs @@ -0,0 +1,98 @@ +using StarterNG.Infrastructure; + +namespace StarterNG.Tests; + +public class SystemGraphicsLibrariesTests +{ + private const string System32 = @"C:\Windows\System32"; + private const string Game = @"E:\SteamLibrary\steamapps\common\MaSzyna"; + + private static readonly IntPtr Dxgi = new(0x1000); + private static readonly IntPtr D3d11 = new(0x2000); + + private static SystemGraphicsLibraries Take(Func beside, Dictionary system) + { + return SystemGraphicsLibraries.Take(System32, Game, beside, Load); + + bool Load(string path, out IntPtr handle) + { + handle = system.GetValueOrDefault(Path.GetFileName(path)); + return handle != IntPtr.Zero; + } + } + + private static SystemGraphicsLibraries WithDxgiAndD3d11(Func beside) => + Take(beside, new Dictionary { ["dxgi.dll"] = Dxgi, ["d3d11.dll"] = D3d11 }); + + [Fact] + public void An_import_by_name_gets_the_system_library_with_or_without_its_extension() + { + var taken = WithDxgiAndD3d11(_ => false); + + Assert.Equal(Dxgi, taken.Resolve("dxgi")); + Assert.Equal(Dxgi, taken.Resolve("dxgi.dll")); + Assert.Equal(D3d11, taken.Resolve("D3D11.DLL")); + } + + [Fact] + public void Other_libraries_and_ones_the_system_lacks_are_left_to_the_usual_search() + { + var taken = WithDxgiAndD3d11(_ => false); + + Assert.Equal(IntPtr.Zero, taken.Resolve("user32.dll")); + Assert.Equal(IntPtr.Zero, taken.Resolve("opengl32")); + } + + [Fact] + public void They_are_loaded_from_the_system_folder_dxgi_first() + { + var asked = new List(); + SystemGraphicsLibraries.Take(System32, Game, _ => false, Load); + + Assert.Equal(SystemGraphicsLibraries.Names.Select(n => Path.Combine(System32, n + ".dll")), asked); + Assert.Equal("dxgi", SystemGraphicsLibraries.Names[0]); + + bool Load(string path, out IntPtr handle) + { + asked.Add(path); + handle = IntPtr.Zero; + return false; + } + } + + [Fact] + public void A_wrapper_beside_the_starter_is_noted() + { + var taken = WithDxgiAndD3d11(path => path == Path.Combine(Game, "dxgi.dll")); + + Assert.Equal(new[] { "dxgi.dll" }, taken.Shadowed); + Assert.Contains("dxgi.dll", taken.Note); + } + + [Fact] + public void With_nothing_beside_the_starter_there_is_nothing_to_note() + { + var taken = WithDxgiAndD3d11(_ => false); + + Assert.Empty(taken.Shadowed); + Assert.Null(taken.Note); + } + + [Fact] + public void Only_windows_has_system_libraries_to_take() + { + var taken = SystemGraphicsLibraries.TakeOnWindows(); + + Assert.Equal(OperatingSystem.IsWindows(), taken is not null); + } + + [Fact] + public void An_assembly_with_a_resolver_of_its_own_keeps_it() + { + var taken = WithDxgiAndD3d11(_ => false); + var assembly = typeof(SystemGraphicsLibrariesTests).Assembly; + + Assert.True(taken.ServeTo(assembly)); + Assert.False(taken.ServeTo(assembly)); + } +} diff --git a/StarterNG/Infrastructure/SoftwareRender.cs b/StarterNG/Infrastructure/SoftwareRender.cs new file mode 100644 index 0000000..9d0443d --- /dev/null +++ b/StarterNG/Infrastructure/SoftwareRender.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; + +namespace StarterNG.Infrastructure; + +/// +/// Drawn by the processor instead of the graphics card, for a machine on which the +/// window comes up empty. Each platform reads only its own options, so both are given. +/// +public static class SoftwareRender +{ + public const string Switch = "--software-render"; + + public static bool AskedIn(IEnumerable args) => + args.Any(a => string.Equals(a, Switch, StringComparison.OrdinalIgnoreCase)); + + public static Win32PlatformOptions Win32Options => new() + { + RenderingMode = new[] { Win32RenderingMode.Software }, + CompositionMode = new[] { Win32CompositionMode.RedirectionSurface } + }; + + public static X11PlatformOptions X11Options => new() + { + RenderingMode = new[] { X11RenderingMode.Software } + }; + + public static AppBuilder ApplyTo(AppBuilder builder) => + builder.With(Win32Options).With(X11Options); +} diff --git a/StarterNG/Infrastructure/SystemGraphicsLibraries.cs b/StarterNG/Infrastructure/SystemGraphicsLibraries.cs index 2aa2f3a..6c5cbe3 100644 --- a/StarterNG/Infrastructure/SystemGraphicsLibraries.cs +++ b/StarterNG/Infrastructure/SystemGraphicsLibraries.cs @@ -19,58 +19,72 @@ namespace StarterNG.Infrastructure; /// Elsewhere there is nothing of the kind to keep out. Under Wine or Proton the system /// folder is the prefix's, so what is taken there is what would have been taken anyway. /// -public static class SystemGraphicsLibraries +public sealed class SystemGraphicsLibraries { + public delegate bool Loader(string path, out IntPtr handle); + // dxgi ahead of d3d11, which asks for it. - private static readonly string[] Names = { "dxgi", "d3d11", "d3d9", "opengl32" }; + public static readonly IReadOnlyList Names = new[] { "dxgi", "d3d11", "d3d9", "opengl32" }; - private static readonly Dictionary Loaded = new(StringComparer.OrdinalIgnoreCase); - private static readonly List Shadowed = new(); + private readonly Dictionary _loaded = new(StringComparer.OrdinalIgnoreCase); + private readonly List _shadowed = new(); - /// The assemblies whose imports of these libraries are to get the system ones. - public static void LoadFirst(params Assembly[] importers) + private SystemGraphicsLibraries() { - if (!OperatingSystem.IsWindows()) - return; + } - string system = Environment.SystemDirectory; - string own = AppContext.BaseDirectory; + /// The files of these names that lay beside the starter. + public IReadOnlyList Shadowed => _shadowed; + /// What goes to the log about them, or null when none lay there. + public string? Note => _shadowed.Count > 0 + ? $"Graphics libraries beside the starter, left to the simulator: {string.Join(", ", _shadowed)}" + : null; + + /// The libraries of this Windows, or null on any other system. + public static SystemGraphicsLibraries? TakeOnWindows() => + OperatingSystem.IsWindows() + ? Take(Environment.SystemDirectory, AppContext.BaseDirectory, File.Exists, NativeLibrary.TryLoad) + : null; + + public static SystemGraphicsLibraries Take(string systemDirectory, string ownDirectory, + Func exists, Loader load) + { + var taken = new SystemGraphicsLibraries(); foreach (string name in Names) { string file = name + ".dll"; - if (File.Exists(Path.Combine(own, file))) - Shadowed.Add(file); - if (NativeLibrary.TryLoad(Path.Combine(system, file), out IntPtr handle)) - Loaded[name] = handle; - } - - foreach (var importer in importers) - { - try - { - NativeLibrary.SetDllImportResolver(importer, Resolve); - } - catch (InvalidOperationException) - { - // It has a resolver of its own already; that one decides. - } + if (exists(Path.Combine(ownDirectory, file))) + taken._shadowed.Add(file); + if (load(Path.Combine(systemDirectory, file), out IntPtr handle)) + taken._loaded[name] = handle; } + return taken; } - private static IntPtr Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) + /// The system library for an import of one of these names; zero leaves it to the usual search. + public IntPtr Resolve(string libraryName) { string name = libraryName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? libraryName[..^4] : libraryName; - // Zero leaves the library to the usual search. - return Loaded.TryGetValue(name, out IntPtr handle) ? handle : IntPtr.Zero; + return _loaded.TryGetValue(name, out IntPtr handle) ? handle : IntPtr.Zero; } - /// Which of them lay beside the starter, once the log can take it. - public static void LogShadowed() + /// + /// The assembly's imports of these names get the system libraries. False when it + /// has a resolver of its own already; that one decides. + /// + public bool ServeTo(Assembly importer) { - if (Shadowed.Count > 0) - Diagnostics.Log($"Graphics libraries beside the starter, left to the simulator: {string.Join(", ", Shadowed)}"); + try + { + NativeLibrary.SetDllImportResolver(importer, (name, _, _) => Resolve(name)); + return true; + } + catch (InvalidOperationException) + { + return false; + } } } diff --git a/StarterNG/Program.cs b/StarterNG/Program.cs index da02172..aa0a8c8 100644 --- a/StarterNG/Program.cs +++ b/StarterNG/Program.cs @@ -1,7 +1,6 @@ using Avalonia; using Avalonia.Threading; using System; -using System.Linq; using System.Threading.Tasks; using StarterNG.Application; using StarterNG.Infrastructure; @@ -11,24 +10,22 @@ namespace StarterNG; static class Program { - /// - /// Drawn by the processor instead of the graphics card, for a machine on which the - /// window comes up empty. Started with --software-render. - /// private static bool _softwareRender; [STAThread] public static void Main(string[] args) { // Ahead of everything that could draw: what lies beside the starter is the simulator's. - SystemGraphicsLibraries.LoadFirst(typeof(Win32PlatformOptions).Assembly); + var graphics = SystemGraphicsLibraries.TakeOnWindows(); + graphics?.ServeTo(typeof(Win32PlatformOptions).Assembly); - _softwareRender = args.Any(a => string.Equals(a, "--software-render", StringComparison.OrdinalIgnoreCase)); + _softwareRender = SoftwareRender.AskedIn(args); // Composition root first: everything below, including the crash handlers, // resolves its collaborators from this graph. AppServices.Initialize(); - SystemGraphicsLibraries.LogShadowed(); + if (graphics?.Note is { } note) + Diagnostics.Log(note); AppDomain.CurrentDomain.UnhandledException += (_, e) => { @@ -76,20 +73,8 @@ static class Program }; } - // Each platform reads only its own options, so both can be given everywhere. private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) => - _softwareRender - ? builder - .With(new Win32PlatformOptions - { - RenderingMode = new[] { Win32RenderingMode.Software }, - CompositionMode = new[] { Win32CompositionMode.RedirectionSurface } - }) - .With(new X11PlatformOptions - { - RenderingMode = new[] { X11RenderingMode.Software } - }) - : builder; + _softwareRender ? SoftwareRender.ApplyTo(builder) : builder; public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() From a83bb4a7ebcdf4d95162641b5e9ec52afad68552 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 17:40:51 +0100 Subject: [PATCH 14/35] fix: a screen reader names every control and Tab survives adding a vehicle NVDA read icon buttons as "Material.Icons.Avalonia.MaterialIcon" and the sceneries in the tree as nothing. Icon buttons are now named by their tooltip, list and tree entries by the text they show, fields by the hint in them, and the inputs of a setting row by its label. The lists, the tree and the language and profile pickers have names, and a consist card says its place and vehicles. Adding a vehicle rebuilt the browser list and switched the add button off for a moment, and focus fell out of the window: Tab did nothing until something was clicked. Focus goes back to the button or the list, and Tab with nothing focused starts from the first control. The splitters are no longer Tab stops. --- StarterNG.Tests/KeyboardFocusTests.cs | 39 ++++++ StarterNG.Tests/ScreenReaderNamesTests.cs | 151 ++++++++++++++++++++++ StarterNG/App.axaml.cs | 4 + StarterNG/Controls/KeyboardFocus.cs | 24 ++++ StarterNG/Controls/ScreenReaderNames.cs | 103 +++++++++++++++ StarterNG/Controls/SettingRow.cs | 11 ++ StarterNG/MainWindow.axaml | 1 + StarterNG/MainWindow.axaml.cs | 13 ++ StarterNG/Views/Depot.axaml | 5 +- StarterNG/Views/Depot/VehicleBrowser.cs | 23 +++- StarterNG/Views/Depot/VehicleCards.cs | 10 ++ StarterNG/Views/Scenarios.axaml | 6 +- StarterNG/Views/Settings.axaml | 3 +- StarterNG/Views/VehicleBaseWindow.axaml | 4 +- 14 files changed, 388 insertions(+), 9 deletions(-) create mode 100644 StarterNG.Tests/KeyboardFocusTests.cs create mode 100644 StarterNG.Tests/ScreenReaderNamesTests.cs create mode 100644 StarterNG/Controls/KeyboardFocus.cs create mode 100644 StarterNG/Controls/ScreenReaderNames.cs diff --git a/StarterNG.Tests/KeyboardFocusTests.cs b/StarterNG.Tests/KeyboardFocusTests.cs new file mode 100644 index 0000000..f531627 --- /dev/null +++ b/StarterNG.Tests/KeyboardFocusTests.cs @@ -0,0 +1,39 @@ +using Avalonia.Controls; +using Avalonia.Input; +using StarterNG.Controls; + +namespace StarterNG.Tests; + +public class KeyboardFocusTests +{ + private readonly Button _window = new(); + private readonly Button _first = new(); + private readonly Button _last = new(); + + private IInputElement? Tab(Key key, KeyModifiers modifiers, IInputElement? focused) => + KeyboardFocus.TabFromNowhere(key, modifiers, focused, _window, () => _first, () => _last); + + [Fact] + public void Tab_with_nothing_focused_starts_from_the_first_control() + { + Assert.Same(_first, Tab(Key.Tab, KeyModifiers.None, null)); + } + + [Fact] + public void Shift_tab_with_only_the_window_focused_starts_from_the_last_control() + { + Assert.Same(_last, Tab(Key.Tab, KeyModifiers.Shift, _window)); + } + + [Fact] + public void Tab_from_a_focused_control_is_left_to_the_usual_order() + { + Assert.Null(Tab(Key.Tab, KeyModifiers.None, new TextBox())); + } + + [Fact] + public void Other_keys_are_left_alone() + { + Assert.Null(Tab(Key.Enter, KeyModifiers.None, null)); + } +} diff --git a/StarterNG.Tests/ScreenReaderNamesTests.cs b/StarterNG.Tests/ScreenReaderNamesTests.cs new file mode 100644 index 0000000..8e45293 --- /dev/null +++ b/StarterNG.Tests/ScreenReaderNamesTests.cs @@ -0,0 +1,151 @@ +using Avalonia.Automation; +using Avalonia.Controls; +using Avalonia.Controls.Documents; +using StarterNG.Controls; + +namespace StarterNG.Tests; + +public class ScreenReaderNamesTests +{ + static ScreenReaderNamesTests() => ScreenReaderNames.Install(); + + private static StackPanel Row(params Control[] children) + { + var panel = new StackPanel(); + panel.Children.AddRange(children); + return panel; + } + + [Fact] + public void An_icon_button_is_named_by_its_tooltip() + { + var button = new Button { Content = new Image() }; + ToolTip.SetTip(button, "Otwórz ostatni log symulatora"); + + Assert.Equal("Otwórz ostatni log symulatora", AutomationProperties.GetName(button)); + } + + [Fact] + public void A_button_without_a_tooltip_is_named_by_the_text_it_shows() + { + var button = new Button { Content = Row(new Image(), new TextBlock { Text = "Dodaj" }) }; + + Assert.Equal("Dodaj", AutomationProperties.GetName(button)); + } + + [Fact] + public void A_button_with_text_of_its_own_keeps_it() + { + var button = new Button { Content = "Zapisz" }; + ToolTip.SetTip(button, "Zapisz ustawienia"); + + Assert.Null(AutomationProperties.GetName(button)); + } + + [Fact] + public void A_name_given_on_purpose_is_left_alone() + { + var button = new Button(); + AutomationProperties.SetName(button, "Discord"); + button.Content = new Image(); + ToolTip.SetTip(button, "Dołącz do nas"); + + Assert.Equal("Discord", AutomationProperties.GetName(button)); + } + + [Fact] + public void A_new_tooltip_replaces_the_name_it_gave() + { + var button = new Button { Content = new Image() }; + ToolTip.SetTip(button, "Undo"); + ToolTip.SetTip(button, "Cofnij"); + + Assert.Equal("Cofnij", AutomationProperties.GetName(button)); + } + + [Fact] + public void Text_put_on_a_button_later_takes_back_the_name_it_was_given() + { + var button = new Button { Content = new Image() }; + ToolTip.SetTip(button, "Pomoc"); + button.Content = "?"; + + Assert.Null(AutomationProperties.GetName(button)); + } + + [Fact] + public void A_tree_entry_is_named_by_the_visible_text_of_its_header() + { + var hidden = new TextBlock { Text = "ukryte", IsVisible = false }; + var item = new TreeViewItem + { + Header = Row(new Image(), new TextBlock { Text = "baltyk_cargo" }, hidden, new TextBlock { Text = " " }) + }; + + Assert.Equal("baltyk_cargo", AutomationProperties.GetName(item)); + } + + [Fact] + public void A_list_entry_joins_the_texts_it_shows() + { + var item = new ListBoxItem + { + Content = new Border { Child = Row(new TextBlock { Text = "PKPIC" }, new TextBlock { Text = "303E-EP-426" }) } + }; + + Assert.Equal("PKPIC, 303E-EP-426", AutomationProperties.GetName(item)); + } + + [Fact] + public void Text_made_of_runs_is_read_whole() + { + var block = new TextBlock(); + block.Inlines!.Add(new Run("EP07")); + block.Inlines.Add(new LineBreak()); + block.Inlines.Add(new Span { Inlines = { new Run("544") } }); + + Assert.Equal("EP07 544", ScreenReaderNames.TextOf(block)); + } + + [Fact] + public void Nothing_to_read_gives_no_name() + { + Assert.Null(ScreenReaderNames.TextOf(null)); + Assert.Null(ScreenReaderNames.TextOf(new Image())); + Assert.Null(ScreenReaderNames.TextOf(" ")); + Assert.Equal("Opis", ScreenReaderNames.TextOf(new ContentControl { Content = " Opis " })); + } + + [Fact] + public void A_field_is_named_by_the_hint_written_in_it() + { + var search = new TextBox { PlaceholderText = "Szukaj…" }; + var category = new ComboBox { PlaceholderText = "Kategoria" }; + + Assert.Equal("Szukaj…", AutomationProperties.GetName(search)); + Assert.Equal("Kategoria", AutomationProperties.GetName(category)); + } + + [Fact] + public void A_setting_row_names_its_inputs_by_its_label() + { + var combo = new ComboBox(); + var slider = new Slider(); + var browse = new Button { Content = "Wybierz plik…" }; + var row = new SettingRow { Content = new Border { Child = Row(combo, slider, browse) } }; + row.Label = "Wybór exe"; + + Assert.Equal("Wybór exe", AutomationProperties.GetName(combo)); + Assert.Equal("Wybór exe", AutomationProperties.GetName(slider)); + Assert.Null(AutomationProperties.GetName(browse)); + } + + [Fact] + public void A_setting_row_without_a_label_leaves_its_input_unnamed() + { + var box = new TextBox(); + _ = new SettingRow { Content = box }; + + Assert.Null(AutomationProperties.GetName(box)); + } +} diff --git a/StarterNG/App.axaml.cs b/StarterNG/App.axaml.cs index 76778b8..7e23076 100644 --- a/StarterNG/App.axaml.cs +++ b/StarterNG/App.axaml.cs @@ -7,6 +7,7 @@ using Avalonia.Markup.Xaml; using Avalonia.Threading; using StarterNG.Application; using StarterNG.Classes; +using StarterNG.Controls; using StarterNG.Infrastructure; using StarterNG.Services; @@ -24,6 +25,9 @@ public partial class App : Avalonia.Application public override void Initialize() { + // Before any control exists: the names are given as controls are filled in. + ScreenReaderNames.Install(); + AvaloniaXamlLoader.Load(this); AppServices.Current.SettingsStore.Load(); diff --git a/StarterNG/Controls/KeyboardFocus.cs b/StarterNG/Controls/KeyboardFocus.cs new file mode 100644 index 0000000..ae68585 --- /dev/null +++ b/StarterNG/Controls/KeyboardFocus.cs @@ -0,0 +1,24 @@ +using System; +using Avalonia.Input; + +namespace StarterNG.Controls; + +public static class KeyboardFocus +{ + /// + /// Focus that fell out with a control taken away or switched off leaves the window + /// itself focused, and Tab then went nowhere until something was clicked - for + /// someone without a mouse, nowhere at all. Tab starts again from the first + /// control, Shift+Tab from the last. Null when focus is somewhere and Tab moves it + /// as usual. + /// + public static IInputElement? TabFromNowhere(Key key, KeyModifiers modifiers, IInputElement? focused, + IInputElement window, Func first, + Func last) + { + if (key != Key.Tab || focused is not null && !ReferenceEquals(focused, window)) + return null; + + return modifiers.HasFlag(KeyModifiers.Shift) ? last() : first(); + } +} diff --git a/StarterNG/Controls/ScreenReaderNames.cs b/StarterNG/Controls/ScreenReaderNames.cs new file mode 100644 index 0000000..1ce9499 --- /dev/null +++ b/StarterNG/Controls/ScreenReaderNames.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using Avalonia; +using Avalonia.Automation; +using Avalonia.Controls; +using Avalonia.Controls.Documents; +using Avalonia.Controls.Primitives; + +namespace StarterNG.Controls; + +/// +/// The names a screen reader says for controls that show no plain text of their own. +/// Without one it said the type of whatever was inside: an icon button was read as +/// "Material.Icons.Avalonia.MaterialIcon", a scenery in the tree as nothing at all. +/// An icon button is named by its tooltip, a list or tree entry by the text it shows, +/// a field by the hint written in it. A name given on purpose is left alone. +/// +public static class ScreenReaderNames +{ + // What was given here last, so a later change replaces it but nothing else. + private static readonly ConditionalWeakTable Given = new(); + + public static void Install() + { + ContentControl.ContentProperty.Changed.AddClassHandler - - + + - - - + - - + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - + + + + + + + + + + diff --git a/StarterNG/Views/Depot.axaml b/StarterNG/Views/Depot.axaml index f808ac9..fb84198 100644 --- a/StarterNG/Views/Depot.axaml +++ b/StarterNG/Views/Depot.axaml @@ -81,7 +81,7 @@ PointerWheelChanged="Combo_OnPointerWheel" SelectionChanged="ClassCombo_OnSelectionChanged" /> - diff --git a/StarterNG/Views/Scenarios.axaml.cs b/StarterNG/Views/Scenarios.axaml.cs index 9514941..fc0afba 100644 --- a/StarterNG/Views/Scenarios.axaml.cs +++ b/StarterNG/Views/Scenarios.axaml.cs @@ -836,6 +836,7 @@ public partial class Scenarios : UserControl { var now = DateTime.Now; weatherTime.SelectedTime = new TimeSpan(now.Hour, now.Minute, 0); + Announcer.Say(this, ScreenReaderNames.PickerText(App.Loc["Time"], ScreenReaderNames.TimeText(weatherTime.SelectedTime))); } private void WeatherRestore_OnClick(object? sender, RoutedEventArgs e) @@ -843,8 +844,18 @@ public partial class Scenarios : UserControl if (_currentScenery is null) return; _currentScenery.Weather.Restore(); ShowWeather(_currentScenery); + Announcer.Say(this, WeatherSummary()); } + /// The weather as a reader hears it once put back: every field and its value. + private string WeatherSummary() => string.Join(", ", + ScreenReaderNames.PickerText(App.Loc["Date"], ScreenReaderNames.DateText(weatherDate.SelectedDate, weatherDate.YearVisible)), + ScreenReaderNames.PickerText(App.Loc["Season"], ScreenReaderNames.TextOf(weatherSeason.SelectedItem)), + ScreenReaderNames.PickerText(App.Loc["Time"], ScreenReaderNames.TimeText(weatherTime.SelectedTime)), + ScreenReaderNames.PickerText(App.Loc["Temperature"], weatherTempLabel.Text), + ScreenReaderNames.PickerText(App.Loc["Visibility"], weatherFogLabel.Text), + ScreenReaderNames.PickerText(App.Loc["Overcast"], ScreenReaderNames.TextOf(weatherOvercast.SelectedItem))); + private static TimeSpan? ParseTime(string? text) { if (string.IsNullOrWhiteSpace(text)) diff --git a/StarterNG/Views/Settings.axaml b/StarterNG/Views/Settings.axaml index d3a8431..15d8578 100644 --- a/StarterNG/Views/Settings.axaml +++ b/StarterNG/Views/Settings.axaml @@ -22,7 +22,7 @@ TextTrimming="LeadingCharacterEllipsis" /> - +