Compare commits

...

40 Commits

Author SHA1 Message Date
952618be13 Merge pull request #52 from MaSzyna-EU07/fix/exe-list-refresh
fix: a simulator copied in while the starter runs is on the list
2026-11-16 09:16:17 +00:00
156af3fdd1 Merge pull request #51 from MaSzyna-EU07/fix/noavx2-exe
fix: without AVX2 the starter starts the simulator built without it
2026-11-16 09:16:05 +00:00
49b76aa66c Merge pull request #49 from MaSzyna-EU07/fix/reshade-beside-starter
fix: graphics wrappers beside the starter no longer reach its window
2026-11-16 09:15:52 +00:00
9b1523ef78 Merge pull request #50 from MaSzyna-EU07/fix/screen-reader-names
fix: a screen reader user can find, hear and work every part of the starter
2026-11-16 09:15:39 +00:00
1d5b0ea1f4 Merge pull request #46 from MaSzyna-EU07/fix/linux-file-case
fix: find game data whatever the case of its names on Linux
2026-11-16 09:14:44 +00:00
maj00r
3f4a20097e fix: Sonar's remarks on the screen reader work, and tests for it
The cab panel's drawing and the consist narration are split into smaller
steps, with plain switches and concrete return types where Sonar asked.

Tests drive the black box panels, both tape views, the key bindings, the
windows opened over another, the search count and the themed tree
entries, sliders, number boxes, pickers and settings sections headless,
as someone at the keyboard with a screen reader meets them.
2026-11-15 22:06:55 +01:00
maj00r
38802845c7 test: no-AVX2 build names carry the date as the simulator writes it, 2026-11-15 2026-11-15 21:35:58 +01:00
maj00r
bba9e3ef48 fix: without AVX2 the starter starts the simulator built without it
The simulator now also comes built without AVX2, its file name ending in
_noavx2 (eu07-x64_<date>_<hash>_noavx2.exe, eu07_noavx2 on Linux), and both
builds can lie side by side in the game folder. The automatic choice took
eu07.exe or the shortest name and never that one, so a processor without
AVX2 got a simulator that stops at its first instruction and a notice
telling it to build its own.

Without AVX2 the automatic choice now takes the newest _noavx2 build, even
one through Wine before a native build that would not run. With AVX2 the
build made for it stays first and a _noavx2 one is used only when it is all
there is.

The notice comes only when what would start still needs AVX2. With a
_noavx2 build in the folder but another chosen by hand it names both and
offers to go back to the automatic choice; with none it says what such a
build is called and that the starter picks it up from the game folder.
2026-11-15 21:28:47 +01:00
maj00r
f29ce10f5c fix: a simulator copied in while the starter runs is on the list
The list of simulators in the settings was filled when they opened, so a new
eu07*.exe from CI or one's own build stayed missing until the starter was
reopened, and the older file was easy to start by mistake. The folder is now
looked at again when the settings page is shown, when the list takes focus
and when the window comes back to the front.

Looking again never changes the choice: a file picked from elsewhere, or one
since removed, stays chosen rather than falling back to automatic, and
nothing waits for Save after it. A list that did not change is left alone.

Closes #48
2026-11-15 21:13:53 +01:00
maj00r
ff5228555e fix: a blind player can bind keys, build a consist and read the tapes
A review against WCAG 2.2 AA left places a screen reader user could not work:

- Key bindings: a key's button says the command and the key, the clear button
  which command it clears; a new key is said aloud and focus comes back to its
  row. The on-screen keyboard is reached with Tab and walked with the arrows.
- Number fields read their label; the spin buttons are named and left out of Tab.
- Dialogs: Enter presses the main button, Esc closes, focus starts on the first
  button and the message is read with it.
- Consist: every change is said - added, removed, turned, moved, replaced,
  undone - and the strip is a named list; a turned card says so.
- Searches say how many entries are left once typing pauses.
- Hasler tapes, the black box timeline, timetable and cab panel take focus, work
  from the keyboard, read their value as it changes and draw a focus frame.
- Section reset and level controls, the crew button and the tabs carry names;
  English names from Avalonia's templates are read in the starter's language;
  sort and crew menus are radio items.
- Input borders reach 3:1 against the panels; Tab starts at the top bar; the
  splash screen has a title and its progress reads the loading step.
2026-11-15 20:46:55 +01:00
maj00r
07bd3d27fb fix: a tree entry tells its state wherever the mouse is on its row
Windows passes over the parts of a template when it looks for what lies under the
mouse, so the gaps beside the arrow and after the name led to the entry, which
told no state: NVDA said "Całkowo" there and "Całkowo zwinięte" on the name.
The row is now a control and is found in those gaps.
2026-11-15 20:07:26 +01:00
maj00r
ee6da4c8ee fix: nothing under the mouse is silent: dividers, previews, class pictures, categories
A page swept point by point left a few places a reader heard nothing: the panel
dividers, the vehicle preview in the depot and the texture base, the picture by
a vehicle class and the empty part of the settings categories. Each now has a
name; a picture with a caption beside it reads as the caption.

The tests that build controls run one after another: a control belongs to the
thread that made the first one, and side by side they now and then failed.
2026-11-15 20:01:25 +01:00
maj00r
184629b544 fix: NVDA hears a tree entry open, a list's new choice and the pictures and figures
Under the mouse a reader hears only what lies there. The row of a tree entry now
carries whether it is open, an arrow or icon in it its name; a picture takes the
name of the button or card it sits in, the scenery picture says what it shows; a
consist figure is one text, label and value together.

Avalonia tells Windows of a closed list's new value only for a list one types
into, so going through the weathers with the arrows was silent; the new choice
is now said aloud.
2026-11-15 19:39:09 +01:00
maj00r
95f1cd2398 fix: NVDA reads the tree entry, slider and help button under the mouse
The tree entry listed the entries under it as its own children, so the controls
inside it lost their way up and Windows failed every lookup there. It now only
points up to the entry it hangs under, which is all the level needs.

The buttons and knob of a slider's track had no name; they now say the slider's
name and value. A button showing only a sign such as "?" takes its tooltip.
2026-11-15 19:07:20 +01:00
maj00r
edd530cb4b fix: NVDA says the section focus enters, a setting's explanation and each fog step
NVDA passes over a group that is not content as well as control, so titled
panels and the landmarks are now both. A setting's explanation and the note on
why the simulator ignores it are read after its name. The key under each setting
is no longer a silent stop for Tab, and a step of the fog slider moves the shown
distance.
2026-11-15 18:45:06 +01:00
maj00r
d2b8cdf3ba fix: a screen reader hears which sceneries lie under a group
Avalonia hung the entries under a group on the panel inside it, so NVDA counted
every scenery at level one and the tree sounded flat. An open group now gives its
entries as its own, and each entry names its group as its parent: Całkowo is
level one, calkowo_lotos under it level two.
2026-11-15 18:36:23 +01:00
maj00r
099ff3603e fix: a field without a name is read by the label beside it
A list, box, slider or picker with no name of its own takes the text a sighted
reader sees next to it: to its left in a grid row, above it in a grid column, or
just before it in a panel. The name follows the label into another language.
2026-11-15 18:09:13 +01:00
maj00r
6c696b44e0 fix: a screen reader finds its way by landmarks and hears what a click changed
Titled panels are named groups, so the reader says which one focus went into.
The tab bar and the settings categories are navigation, the page is the main
part, the search boxes are search. A quality level, a section put back to its
defaults, settings reloaded, the weather put back or its time set to now are
spoken, as is the save status.
2026-11-15 18:05:26 +01:00
maj00r
a0a6ebdffa fix: a screen reader reads a slider as the value shown beside it
NVDA read a slider's bare number as a share of its length, so -5 °C was 45 and
the fog was where the knob stood on its scale. Sliders now give the text shown
next to them: the weather's temperature and visibility, and every setting row.
2026-11-15 17:59:04 +01:00
maj00r
5883376762 fix: a screen reader says what the date and time hold and that a tree group opens
The date and time pickers were read as a grid: the button inside them now carries
the field's label and its value. A scenery group in the tree says whether it is
open or closed, and the weather fields are named by their labels.
2026-11-15 17:49:44 +01:00
maj00r
a83bb4a7eb 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.
2026-11-15 17:40:51 +01:00
maj00r
6e2dbf9eac 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.
2026-11-15 17:30:13 +01:00
maj00r
91c496ab48 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.
2026-11-15 14:41:48 +01:00
maj00r
7cd3ef8f1a test: the in-memory disk has the root of an absolute Linux path 2026-11-13 17:44:26 +01:00
maj00r
1b41ef752a chore: version 1.6
Data names are now found whatever their letter case on Linux.
2026-11-13 16:23:47 +01:00
maj00r
42f702a096 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.
2026-11-13 16:23:47 +01:00
maj00r
7f57160aae 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.
2026-11-13 16:23:47 +01:00
maj00r
2efae83b57 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.
2026-11-13 16:23:47 +01:00
maj00r
34f2ce99e8 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.
2026-11-13 16:23:47 +01:00
maj00r
52408a9931 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.
2026-11-13 16:23:47 +01:00
maj00r
290b753f40 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.
2026-11-13 16:23:47 +01:00
maj00r
6279228a7d fix: find a scenery's i18n tables whatever the case of their names
The i18n folder and its <scenery>_<language>.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.
2026-11-13 16:23:47 +01:00
maj00r
d4975796a8 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.
2026-11-13 16:23:47 +01:00
maj00r
48af11b4b2 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.
2026-11-13 16:23:47 +01:00
maj00r
744720d922 Merge pull request #44 from MaSzyna-EU07/fix/dotted-model-names
fix: a dot in a model name is part of the name, not an extension
2026-11-12 21:33:51 +01:00
maj00r
b5ba67430f fix: a dot in a model name is part of the name, not an extension
The 9-107 and 9-110 coal wagons (9-107.13.fiz and the like) found no physics, so no load could be set on them.
2026-11-12 20:57:36 +01:00
maj00r
c261d4b0ab Merge pull request #43 from MaSzyna-EU07/fix/version-no-suffix
fix: the version is the number alone, with no public beta after it
2026-11-12 19:41:31 +01:00
maj00r
3aa6a256a5 fix: the version is the number alone, with no public beta after it 2026-11-12 19:38:11 +01:00
maj00r
95c510b3ac Merge pull request #41 from MaSzyna-EU07/fix/version-in-title
The version in the window's title
2026-11-12 17:44:17 +01:00
maj00r
da5a1efea1 fix: the version in the window's title, where it has room at any width 2026-11-11 17:53:01 +01:00
111 changed files with 5669 additions and 511 deletions

View File

@@ -24,6 +24,10 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
["LiveTip"] = "Reads what the simulator adds to the file every 2 seconds",
["Play"] = "Play",
["Pause"] = "Pause",
["PlaySpeed"] = "Playback speed",
["TimelineHelp"] = "The arrows go 10 seconds back or on, with Ctrl a minute, Page Up and Page Down ten minutes, Home and End to the start and the end.",
["TimetableHelp"] = "The up and down arrows go through the stations, Enter goes to the moment the train was there.",
["MapHelp"] = "The map of the run. What it shows is also in the events and the timetable, and on the run below it.",
["Follow"] = "Follow the train",
["Fit"] = "Whole map",
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the physics logs on.",
@@ -295,6 +299,10 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
["LiveTip"] = "Co 2 sekundy doczytuje to, co symulator dopisał do pliku",
["Play"] = "Odtwarzaj",
["Pause"] = "Pauza",
["PlaySpeed"] = "Prędkość odtwarzania",
["TimelineHelp"] = "Strzałki przesuwają o 10 sekund, z Ctrl o minutę, Page Up i Page Down o dziesięć minut, Home i End na początek i koniec.",
["TimetableHelp"] = "Strzałki w górę i w dół przechodzą po stacjach, Enter przenosi do chwili, gdy pociąg tam był.",
["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.",
["Follow"] = "Śledź pociąg",
["Fit"] = "Cała mapa",
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną razem z logami fizyki.",

View File

@@ -6,6 +6,7 @@ using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
@@ -106,6 +107,13 @@ public sealed class BlackBoxWindow : Window
_play.Click += (_, _) => Playing = !Playing;
_speed.ItemsSource = Speeds.Select(s => $"×{s.ToString(CultureInfo.InvariantCulture)}").ToArray();
_speed.SelectedIndex = 3;
// What a screen reader calls the parts that have no label of their own on the screen.
AutomationProperties.SetName(_speed, _strings["PlaySpeed"]);
AutomationProperties.SetName(_timeline, _strings["PanelTimeline"]);
AutomationProperties.SetName(_timetable, _strings["TabTimetable"]);
AutomationProperties.SetName(_cab, _strings["Cab"]);
AutomationProperties.SetName(_map, _strings["PanelMap"]);
AutomationProperties.SetHelpText(_map, _strings["MapHelp"]);
var titles = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Children = { _title, _subtitle } };
var transport = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { _play, _clock, _speed, _delayText } };
@@ -455,6 +463,7 @@ public sealed class BlackBoxWindow : Window
_clock.Text = recording.ClockAt(_time).ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture);
_events.ShowTime(_time);
ShowReadout(null);
_timeline.Spoken = _readout.Text;
ShowDelay(recording);
TimeChanged?.Invoke(_time);
}

View File

@@ -3,7 +3,9 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
@@ -36,6 +38,36 @@ public sealed class CabPanel : Control
{
ClipToBounds = true;
Height = 696;
// Reached with Tab, where a screen reader reads what the panel shows.
Focusable = true;
}
// What the panel showed when last drawn, a line a figure, as a screen reader is told it.
private List<string>? _saying;
private string? _said;
/// <summary>What the panel shows, said in words: the figures and the lamps that are lit.</summary>
public string? Said => _said;
private void Say(string text)
{
if (!string.IsNullOrWhiteSpace(text))
_saying?.Add(text.Trim());
}
protected override AutomationPeer OnCreateAutomationPeer() =>
new SpokenPeer(this, AutomationControlType.Pane, () => null, () => _said);
protected override void OnGotFocus(FocusChangedEventArgs e)
{
base.OnGotFocus(e);
InvalidateVisual();
}
protected override void OnLostFocus(FocusChangedEventArgs e)
{
base.OnLostFocus(e);
InvalidateVisual();
}
public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings();
@@ -62,6 +94,22 @@ public sealed class CabPanel : Control
}
public override void Render(DrawingContext context)
{
_saying = new List<string>();
try
{
DrawPanel(context);
}
finally
{
_said = string.Join(". ", _saying);
_saying = null;
}
if (IsFocused)
context.DrawRectangle(null, Palette.FocusPen, new Rect(Bounds.Size).Deflate(1));
}
private void DrawPanel(DrawingContext context)
{
var size = Bounds.Size;
double width = size.Width - 2 * Pad, right = size.Width - Pad;
@@ -70,95 +118,150 @@ public sealed class CabPanel : Control
if (_recording is not { } recording || recording.CabAt(_time) is not { } s || _time - s.Time > 1.5)
{
context.DrawText(MapView.Text(Strings["CabNoData"], Palette.DimText, 12), new Point(Pad, 40));
Say(Strings["CabNoData"]);
return;
}
Measure(recording);
var culture = CultureInfo.CurrentCulture;
var extra = s.Extra;
// The vehicle at the left; who drives, from which cab, at the right.
DrawHeader(context, recording.Vehicle(s.Vehicle)?.Name ?? "", s, right);
DrawSpeed(context, s, width, right, culture);
DrawControls(context, s, width, right, culture);
double y = DrawBrakes(context, s, width, right, culture);
// The traction at the left, as fits what drives the vehicle; the lights of both ends of the train at the right.
double half = Pad + width / 2;
double driveTop = y + BrakeRow + 4;
double top = Section(context, Strings["CabSectionDrive"], Pad, driveTop, half - 10);
Section(context, Strings["CabLights"], half + 4, driveTop, right);
DrawDrive(context, s, top, half - 10 - Pad, culture);
DrawLights(context, s, new Rect(half, top, right - half, 0), culture);
top = DrawDevices(context, s, new Rect(Pad, top + 3 * DriveRow + 6, width, size.Height), culture);
DrawDoors(context, s, top, width, size.Height);
}
private const double BrakeRow = 17;
/// <summary>The vehicle at the left; who drives, from which cab, at the right.</summary>
private void DrawHeader(DrawingContext context, string name, CabSample s, double right)
{
string? end = s.CabEnd == 0 ? null : Strings[s.CabEnd > 0 ? "CabEndFront" : "CabEndRear"];
double chipX = right;
if (s.CabEnd != 0)
chipX -= ChipLeft(context, Strings[s.CabEnd > 0 ? "CabEndFront" : "CabEndRear"], Palette.Text, chipX, 4) + 5;
var (driverText, driverBrush) = !s.InCab ? (Strings["CabOutside"], Palette.DimText)
: s.Driving == Driver.Ai ? (Strings["CabDriverAi"], Palette.Autopilot)
: (Strings["CabDriverUser"], Palette.UserTrain);
if (end is not null)
chipX -= ChipLeft(context, end, Palette.Text, chipX, 4) + 5;
var (driverText, driverBrush) = DriverChip(s);
chipX -= ChipLeft(context, driverText, driverBrush, chipX, 4) + 10;
Say(name);
Say(driverText);
if (end is not null)
Say(end);
using (context.PushClip(new Rect(Pad, 0, Math.Max(0, chipX - Pad), 28)))
context.DrawText(MapView.Text(recording.Vehicle(s.Vehicle)?.Name ?? "", Palette.Text, 12, FontWeight.SemiBold), new Point(Pad, 6));
context.DrawText(MapView.Text(name, Palette.Text, 12, FontWeight.SemiBold), new Point(Pad, 6));
}
// The speed, large, what the AI would do under it, the accelerations at the right.
var judgement = DrivingSummary.Judge(s);
var speed = MapView.Text(s.AbsSpeedKmh.ToString("0", culture), judgement is SpeedJudgement.Over ? Palette.Bad
: judgement is SpeedJudgement.Slightly ? Palette.Warn : Palette.Text, 36, FontWeight.SemiBold);
private (string Text, IBrush Brush) DriverChip(CabSample s)
{
if (!s.InCab)
return (Strings["CabOutside"], Palette.DimText);
return s.Driving == Driver.Ai ? (Strings["CabDriverAi"], Palette.Autopilot) : (Strings["CabDriverUser"], Palette.UserTrain);
}
/// <summary>The speed, large, what the AI would do under it, the accelerations at the right.</summary>
private void DrawSpeed(DrawingContext context, CabSample s, double width, double right, CultureInfo culture)
{
string kmh = s.AbsSpeedKmh.ToString("0", culture);
var speed = MapView.Text(kmh, SpeedBrush(DrivingSummary.Judge(s)), 36, FontWeight.SemiBold);
context.DrawText(speed, new Point(Pad, 24));
Say($"{kmh} km/h");
context.DrawText(MapView.Text("km/h", Palette.DimText, 12), new Point(Pad + speed.Width + 4, 24 + speed.Height - 21));
double gaugeX = Pad + Math.Max(150, width * 0.42);
if (s.AiValid)
{
using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40)))
{
context.DrawText(MapView.Text(string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh), Palette.Target, 12), new Point(Pad, 76));
string target = string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh);
context.DrawText(MapView.Text(target, Palette.Target, 12), new Point(Pad, 76));
Say(target);
if (s.Ai.HasNextLimit)
context.DrawText(MapView.Text(string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance), Palette.Limit, 11),
new Point(Pad, 93));
{
string limit = string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance);
Say(limit);
context.DrawText(MapView.Text(limit, Palette.Limit, 11), new Point(Pad, 93));
}
}
}
double gaugeWidth = right - gaugeX;
Balance(context, Strings["CabAcceleration"], s.Acceleration, 1.5, gaugeX, 34, gaugeWidth);
Balance(context, Strings["CabLateral"], s.LateralAcceleration, 1.5, gaugeX, 70, gaugeWidth);
}
// The controllers.
private static IBrush SpeedBrush(SpeedJudgement judgement) => judgement switch
{
SpeedJudgement.Over => Palette.Bad,
SpeedJudgement.Slightly => Palette.Warn,
_ => Palette.Text
};
/// <summary>The controllers.</summary>
private void DrawControls(DrawingContext context, CabSample s, double width, double right, CultureInfo culture)
{
double top = Section(context, Strings["CabSectionControls"], Pad, 118, right);
double column = width / 4;
Value(context, Strings["CabController"], s.MainController.ToString(culture), Pad, top);
Steps(context, s.MainController, _controllerTop, Pad, top + 34, column - 14);
if (extra is { } handle && _integrated.Contains(s.Vehicle))
if (s.Extra is { } handle && _integrated.Contains(s.Vehicle))
Value(context, Strings["CabIntegrated"], (handle.IntegratedController * 100).ToString("+0;−0;0", culture) + " %", Pad + column, top);
else
Value(context, Strings["CabShunt"], s.ScndController.ToString(culture), Pad + column, top);
Value(context, Strings["CabReverser"], Strings[s.Reverser > 0 ? "CabForward" : s.Reverser < 0 ? "CabBackward" : "CabNeutral"], Pad + 2 * column, top);
string reverser = s.Reverser switch { > 0 => "CabForward", < 0 => "CabBackward", _ => "CabNeutral" };
Value(context, Strings["CabReverser"], Strings[reverser], Pad + 2 * column, top);
Value(context, Strings["CabTrainBrake"], s.TrainBrake.ToString("0.0", culture), Pad + 3 * column, top);
}
// The brakes, as gauges, the setting (G, P, R) at the right of the title.
/// <summary>The brakes, as gauges, the setting (G, P, R) at the right of the title.</summary>
/// <returns>Where the last gauge stands.</returns>
private double DrawBrakes(DrawingContext context, CabSample s, double width, double right, CultureInfo culture)
{
var extra = s.Extra;
string? setting = extra is { } e && (e.BrakeDelay | e.BrakeMode) != 0
? string.Format(culture, Strings["CabBrakeSetting"], string.Join(" · ", new[] { BrakeSetting(e.BrakeDelay), BrakeMode(e.BrakeMode) }.Where(t => t.Length > 0)))
: null;
top = Section(context, Strings["CabSectionBrakes"], Pad, 180, right, setting);
const double gauge = 17;
Gauge(context, Strings["CabPipe"], s.BrakePipe, 6, 5, $"{s.BrakePipe:0.00} bar", Palette.Station, Pad, top, width);
double y = top + gauge;
if (extra is { } x1)
double y = Section(context, Strings["CabSectionBrakes"], Pad, 180, right, setting);
var gauges = new List<GaugeReading>
{
// what the driver's brake valve shows: its equalizing reservoir, the FV4a's time reservoir
Gauge(context, Strings["CabDriverValve"], x1.DriverValve, 6, null, $"{x1.DriverValve:0.00} bar", Palette.Target, Pad, y, width);
y += gauge;
}
Gauge(context, Strings["CabCylinder"], s.BrakeCylinder, 6, null, $"{s.BrakeCylinder:0.0} bar", Palette.Brakes, Pad, y, width);
y += gauge;
if (extra is { } x3)
{
// the most braked vehicle of the train
Gauge(context, Strings["CabConsistCylinder"], x3.ConsistBrakeCylinder, 6, null, $"{x3.ConsistBrakeCylinder:0.0} bar", Palette.Brakes, Pad, y, width);
y += gauge;
}
Gauge(context, Strings["CabReservoir"], s.MainReservoir, 10, null, $"{s.MainReservoir:0.0} bar", Palette.Controller, Pad, y, width);
y += gauge;
if (extra is { } x2)
{
bool has = _feedPipe.Contains(s.Vehicle);
Gauge(context, Strings["CabFeedPipe"], has ? x2.FeedPipe : 0, 10, null, has ? $"{x2.FeedPipe:0.0} bar" : "—", Palette.Controller, Pad, y, width);
y += gauge;
}
Gauge(context, Strings["CabLocalBrake"], s.LocalBrake, 1, null, $"{s.LocalBrake * 100:0} %", Palette.Brakes, Pad, y, width);
new(Strings["CabPipe"], s.BrakePipe, 6, 5, $"{s.BrakePipe:0.00} bar", Palette.Station)
};
// what the driver's brake valve shows: its equalizing reservoir, the FV4a's time reservoir
if (extra is { } valve)
gauges.Add(new(Strings["CabDriverValve"], valve.DriverValve, 6, null, $"{valve.DriverValve:0.00} bar", Palette.Target));
gauges.Add(new(Strings["CabCylinder"], s.BrakeCylinder, 6, null, $"{s.BrakeCylinder:0.0} bar", Palette.Brakes));
// the most braked vehicle of the train
if (extra is { } most)
gauges.Add(new(Strings["CabConsistCylinder"], most.ConsistBrakeCylinder, 6, null, $"{most.ConsistBrakeCylinder:0.0} bar", Palette.Brakes));
gauges.Add(new(Strings["CabReservoir"], s.MainReservoir, 10, null, $"{s.MainReservoir:0.0} bar", Palette.Controller));
if (extra is { } feed)
gauges.Add(FeedPipe(s, feed));
gauges.Add(new(Strings["CabLocalBrake"], s.LocalBrake, 1, null, $"{s.LocalBrake * 100:0} %", Palette.Brakes));
// The traction at the left, as fits what drives the vehicle; the lights of both ends of the train at the right.
double half = Pad + width / 2;
double driveTop = y + gauge + 4;
top = Section(context, Strings["CabSectionDrive"], Pad, driveTop, half - 10);
Section(context, Strings["CabLights"], half + 4, driveTop, right);
DrawDrive(context, s, top, half - 10 - Pad, culture);
double row = top;
for (int i = 0; i < gauges.Count; i++)
{
if (i > 0)
y += BrakeRow;
Gauge(context, gauges[i], Pad, y, width);
}
return y;
}
private GaugeReading FeedPipe(CabSample s, CabExtra feed) => _feedPipe.Contains(s.Vehicle)
? new(Strings["CabFeedPipe"], feed.FeedPipe, 10, null, $"{feed.FeedPipe:0.0} bar", Palette.Controller)
: new(Strings["CabFeedPipe"], 0, 10, null, "—", Palette.Controller);
/// <summary>The lights of both ends: the signal shown, green as it is to be, red otherwise with the one it is to show.</summary>
/// <param name="area">Left edge, top and width of the column; its height is not used.</param>
private void DrawLights(DrawingContext context, CabSample s, Rect area, CultureInfo culture)
{
double half = area.X, right = area.Right, row = area.Y;
foreach (var (key, lights, equipped, required, isRight) in new[]
{
("CabLightsHead", s.LightsHead, s.EquippedHead, HeadCodes.RequiredHead(s), HeadCodes.HeadRight(s)),
@@ -166,14 +269,9 @@ public sealed class CabPanel : Control
})
{
DrawFace(context, lights, new Point(half + 4 + 17, row + 15));
// the end, and under it the signal it shows: green as it is to be (with the lamps the vehicle has),
// red otherwise with the one it is to show
var shown = HeadCodes.Of(lights);
var text = HeadCodes.NoLamps(equipped) ? Strings["CabLightsNone"]
: isRight == false && required is { } want
? string.Format(culture, Strings["CabLightsWant"], HeadCodes.Name(shown), HeadCodes.Name(want))
: isRight == true && required is { } met ? HeadCodes.Name(met) : HeadCodes.Name(shown);
var brush = isRight is null ? Palette.DimText : isRight.Value ? Palette.Good : Palette.Bad;
string text = LightsText(HeadCodes.Of(lights), HeadCodes.NoLamps(equipped), required, isRight, culture);
IBrush brush = isRight switch { null => Palette.DimText, true => Palette.Good, false => Palette.Bad };
Say($"{Strings[key]}: {text}");
using (context.PushClip(new Rect(half + 44, row, right - half - 44, 28)))
{
context.DrawText(MapView.Text(Strings[key], Palette.DimText, 10), new Point(half + 46, row));
@@ -181,9 +279,24 @@ public sealed class CabPanel : Control
}
row += 27;
}
}
// The devices, in three groups side by side: lit as their lamps are in the cab, the ones off faint.
top = Section(context, Strings["CabSectionDevices"], Pad, top + 3 * DriveRow + 6, right);
private string LightsText(HeadCode shown, bool noLamps, HeadCode? required, bool? isRight, CultureInfo culture)
{
if (noLamps)
return Strings["CabLightsNone"];
if (isRight == false && required is { } want)
return string.Format(culture, Strings["CabLightsWant"], HeadCodes.Name(shown), HeadCodes.Name(want));
return isRight == true && required is { } met ? HeadCodes.Name(met) : HeadCodes.Name(shown);
}
/// <summary>The devices, in three groups side by side: lit as their lamps are in the cab, the ones off faint.</summary>
/// <param name="area">Left edge, top, width and the height of the whole panel.</param>
/// <returns>Where the doors go, under them.</returns>
private double DrawDevices(DrawingContext context, CabSample s, Rect area, CultureInfo culture)
{
double width = area.Width, height = area.Height;
double top = Section(context, Strings["CabSectionDevices"], area.X, area.Y, area.X + width);
var groups = Devices(s, culture);
var widths = new double[groups.Length];
for (int g = 0; g < groups.Length; g++)
@@ -194,33 +307,42 @@ public sealed class CabPanel : Control
}
// each group as wide as its longest name, what is left shared between them
double spare = (width - widths.Sum()) / groups.Length;
double x = Pad, bottom = top;
double x = area.X, bottom = top;
for (int g = 0; g < groups.Length; g++)
{
double groupWidth = Math.Max(20, widths[g] + spare);
using (context.PushClip(new Rect(x, top, groupWidth, size.Height - top)))
{
context.DrawText(MapView.Text(Strings[groups[g].Title], Palette.DimText, 10, FontWeight.SemiBold), new Point(x, top));
double lampY = top + 16;
foreach (var (text, brush) in groups[g].Lamps)
{
Lamp(context, text, brush, x, lampY);
lampY += LampRow;
}
bottom = Math.Max(bottom, lampY);
}
using (context.PushClip(new Rect(x, top, groupWidth, height - top)))
bottom = Math.Max(bottom, DrawGroup(context, groups[g], x, top));
x += groupWidth;
}
return Math.Max(bottom, top + 16 + 9 * LampRow) + 6;
}
// The doors under them, in two columns: open, permitted, the departure signal, the steps and the lock.
top = Math.Max(bottom, top + 16 + 9 * LampRow) + 6;
/// <returns>Where the group ends.</returns>
private double DrawGroup(DrawingContext context, (string Title, (string Text, IBrush? Lit)[] Lamps) group, double x, double top)
{
context.DrawText(MapView.Text(Strings[group.Title], Palette.DimText, 10, FontWeight.SemiBold), new Point(x, top));
Say(Strings[group.Title]);
double lampY = top + 16;
foreach (var (text, brush) in group.Lamps)
{
Lamp(context, text, brush, x, lampY);
lampY += LampRow;
}
return lampY;
}
/// <summary>The doors, in two columns: open, permitted, the departure signal, the steps and the lock.</summary>
private void DrawDoors(DrawingContext context, CabSample s, double top, double width, double height)
{
context.DrawText(MapView.Text(Strings["CabGroupDoors"], Palette.DimText, 10, FontWeight.SemiBold), new Point(Pad, top));
Say(Strings["CabGroupDoors"]);
var doors = Doors(s);
double doorColumn = width / DoorColumns;
for (int i = 0; i < doors.Length; i++)
{
double doorX = Pad + i % DoorColumns * doorColumn;
using (context.PushClip(new Rect(doorX, top, doorColumn, size.Height - top)))
using (context.PushClip(new Rect(doorX, top, doorColumn, height - top)))
Lamp(context, doors[i].Text, doors[i].Lit, doorX, top + 16 + i / DoorColumns * LampRow);
}
}
@@ -279,6 +401,7 @@ public sealed class CabPanel : Control
break;
default:
context.DrawText(MapView.Text(Strings["CabNoDrive"], Palette.DimText, 11), new Point(Pad, top + 2));
Say(Strings["CabNoDrive"]);
return;
}
double column = width / 2;
@@ -321,8 +444,9 @@ public sealed class CabPanel : Control
}
/// <summary>The title of a part of the panel, with a line from it to the right (and a note at its end); the top of the part returned.</summary>
private static double Section(DrawingContext context, string title, double x, double y, double right, string? note = null)
private double Section(DrawingContext context, string title, double x, double y, double right, string? note = null)
{
Say(note is null ? title : $"{title}, {note}");
var text = MapView.Text(title.ToUpper(CultureInfo.CurrentCulture), Palette.DimText, 9, FontWeight.SemiBold);
context.DrawText(text, new Point(x, y));
double end = right;
@@ -370,8 +494,9 @@ public sealed class CabPanel : Control
_measured = recording.Revision;
}
private static void Value(DrawingContext context, string label, string value, double x, double y, IBrush? brush = null)
private void Value(DrawingContext context, string label, string value, double x, double y, IBrush? brush = null)
{
Say($"{label}: {value}");
context.DrawText(MapView.Text(label, Palette.DimText, 10), new Point(x, y));
context.DrawText(MapView.Text(value, brush ?? Palette.Text, 14, FontWeight.SemiBold), new Point(x, y + 13));
}
@@ -387,9 +512,10 @@ public sealed class CabPanel : Control
}
/// <summary>A gauge: its name, a bar up to the value against the scale, a mark where it should stand, the value.</summary>
private static void Gauge(DrawingContext context, string label, float value, double scale, double? mark, string text,
IBrush brush, double x, double y, double width)
private void Gauge(DrawingContext context, GaugeReading reading, double x, double y, double width)
{
var (label, value, scale, mark, text, brush) = reading;
Say($"{label}: {text}");
const double labelWidth = 118, valueWidth = 64;
context.DrawText(MapView.Text(label, Palette.DimText, 11), new Point(x, y));
double barX = x + labelWidth, barWidth = width - labelWidth - valueWidth;
@@ -408,9 +534,10 @@ public sealed class CabPanel : Control
}
/// <summary>A value either way of nought: a bar from the middle, to the right above it.</summary>
private static void Balance(DrawingContext context, string label, float value, double scale, double x, double y, double width)
private void Balance(DrawingContext context, string label, float value, double scale, double x, double y, double width)
{
var culture = CultureInfo.CurrentCulture;
Say($"{label}: {value.ToString("+0.00;−0.00;0.00", culture)} m/s²");
context.DrawText(MapView.Text(label, Palette.DimText, 10), new Point(x, y));
var v = MapView.Text($"{value.ToString("+0.00;−0.00;0.00", culture)} m/s²", Palette.Text, 11, FontWeight.SemiBold);
context.DrawText(v, new Point(x + width - v.Width, y));
@@ -455,8 +582,11 @@ public sealed class CabPanel : Control
}
/// <summary>A device's lamp and its name: lit in its colour, the name bright; off, both faint.</summary>
private static void Lamp(DrawingContext context, string text, IBrush? lit, double x, double y)
private void Lamp(DrawingContext context, string text, IBrush? lit, double x, double y)
{
// Only the lamps that are lit are told: the dark ones are the panel, not the moment.
if (lit is not null)
Say(text);
var center = new Point(x + 4, y + 7);
if (lit is not null)
context.DrawEllipse(Palette.Faded(lit, 0.3), null, center, 6, 6);
@@ -564,4 +694,7 @@ public sealed class CabPanel : Control
doors.Add(On("DevDepartureSignal", CabDevices.DepartureSignal, Palette.LampWarning));
return doors.ToArray();
}
/// <summary>What one gauge shows: its name, the value against the scale, the mark, the value written out.</summary>
private readonly record struct GaugeReading(string Label, float Value, double Scale, double? Mark, string Text, IBrush Brush);
}

View File

@@ -14,6 +14,10 @@
<PackageReference Include="Avalonia" Version="12.1.4" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="StarterNG.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Eu07.BlackBox\Eu07.BlackBox.csproj" />
</ItemGroup>

View File

@@ -26,6 +26,8 @@ public static class Palette
public static readonly IBrush AccentFill = Brush("#177F00");
public static readonly IBrush AccentFillHover = Brush("#1E9000");
public static readonly IBrush AccentText = Brush("#FFFFFF");
/// <summary>The ring round a drawn control that has the keyboard, in the green of the starter's own.</summary>
public static readonly IPen FocusPen = new Pen(Accent, 2);
public static readonly IBrush Good = Brush("#4cc46e");
/// <summary>A delay: green on time, yellow a little late, red late, blue early.</summary>

View File

@@ -0,0 +1,47 @@
using System;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
namespace Eu07.BlackBox.Views;
/// <summary>
/// What a screen reader is told of a control that draws itself: a name, the moment or
/// the row it stands at as its value - read again whenever it changes under the focus,
/// as a slider's is - and a description of what it shows or how to work it.
/// </summary>
internal sealed class SpokenPeer : ControlAutomationPeer, IValueProvider
{
private readonly AutomationControlType _type;
private readonly Func<string?> _value;
private readonly Func<string?> _help;
public SpokenPeer(Control owner, AutomationControlType type, Func<string?> value, Func<string?> help) : base(owner)
{
_type = type;
_value = value;
_help = help;
}
/// <summary>Tells the reader the value changed, so it reads the new one.</summary>
public void Told(string? before, string? now)
{
if (before != now)
RaisePropertyChangedEvent(ValuePatternIdentifiers.ValueProperty, before, now);
}
protected override AutomationControlType GetAutomationControlTypeCore() => _type;
protected override string? GetHelpTextCore() => base.GetHelpTextCore() is { Length: > 0 } own ? own : _help();
protected override bool IsContentElementCore() => true;
protected override bool IsControlElementCore() => true;
string? IValueProvider.Value => _value();
bool IValueProvider.IsReadOnly => true;
void IValueProvider.SetValue(string? value) => throw new InvalidOperationException("The value is read only.");
}

View File

@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
@@ -51,6 +52,67 @@ public sealed class TimelineView : Control
{
ClipToBounds = true;
MinHeight = 160;
// Walked from the keyboard too: the arrows step through the time.
Focusable = true;
}
private string? _spoken;
/// <summary>
/// What the moment played is said as - the clock, the speed, what the AI held - the
/// value a screen reader reads, again whenever it changes.
/// </summary>
public string? Spoken
{
get => _spoken;
set
{
string? before = _spoken;
_spoken = value;
(ControlAutomationPeer.FromElement(this) as SpokenPeer)?.Told(before, value);
}
}
protected override AutomationPeer OnCreateAutomationPeer() =>
new SpokenPeer(this, AutomationControlType.Slider, () => _spoken, () => Strings["TimelineHelp"]);
/// <summary>How far one press of an arrow goes, in seconds: Ctrl a minute, Page Up and Down ten.</summary>
public const double Step = 10, CtrlStep = 60, PageStep = 600;
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (_recording is not { } recording || recording.Duration <= 0)
return;
bool ctrl = e.KeyModifiers.HasFlag(KeyModifiers.Control);
double? to = e.Key switch
{
Key.Left => _time - (ctrl ? CtrlStep : Step),
Key.Right => _time + (ctrl ? CtrlStep : Step),
Key.PageUp => _time - PageStep,
Key.PageDown => _time + PageStep,
Key.Home => 0,
Key.End => recording.Duration,
_ => null
};
if (to is not { } t)
return;
Seek?.Invoke(Math.Clamp(t, 0, recording.Duration));
e.Handled = true;
}
protected override void OnGotFocus(FocusChangedEventArgs e)
{
base.OnGotFocus(e);
InvalidateVisual();
}
protected override void OnLostFocus(FocusChangedEventArgs e)
{
base.OnLostFocus(e);
InvalidateVisual();
}
public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings();
@@ -100,6 +162,8 @@ public sealed class TimelineView : Control
public override void Render(DrawingContext context)
{
var size = Bounds.Size;
if (IsFocused)
context.DrawRectangle(null, Palette.FocusPen, new Rect(size).Deflate(1));
var recording = _recording;
if (recording is null || recording.Duration <= 0)
return;

View File

@@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
@@ -36,6 +38,84 @@ public sealed class TimetablePanel : Control
{
ClipToBounds = true;
Cursor = new Cursor(StandardCursorType.Hand);
// The stations walked from the keyboard as well: the arrows go up and down the rows,
// Enter goes to the moment as a click does.
Focusable = true;
}
// The row the keyboard stands at; -1 until it is moved, when the station played is meant.
private int _keyRow = -1;
private string? _spoken;
protected override AutomationPeer OnCreateAutomationPeer() =>
new SpokenPeer(this, AutomationControlType.List, () => _spoken ?? RowText(KeyRow), () => Strings["TimetableHelp"]);
private int KeyRow => _keyRow >= 0 && _keyRow < _rows.Count ? _keyRow : Current();
/// <summary>A row as it is read: the station, the times of the timetable, the kilometre and what happened there.</summary>
private string? RowText(int i)
{
if (_timetable is null)
return Strings["TimetableNone"];
if (i < 0 || i >= _rows.Count)
return null;
var row = _rows[i];
var culture = CultureInfo.CurrentCulture;
string planned = row.Row.IsStop
? $"{Minutes(row.Row.Arrival)} – {Minutes(row.Row.Departure)}"
: Minutes(row.Row.Departure);
var parts = new List<string> { StationNames.Display(row.Row.Station), planned };
if (row.Row.Km > 0 || i > 0)
parts.Add($"km {row.Row.Km.ToString("0.0", culture)}");
parts.AddRange(Chips(row, culture).Select(c => c.Text));
return $"{i + 1}/{_rows.Count}. {string.Join(", ", parts)}";
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (_rows.Count == 0)
return;
int at = KeyRow;
int? to = e.Key switch
{
Key.Up => at - 1,
Key.Down => at + 1,
Key.Home => 0,
Key.End => _rows.Count - 1,
_ => null
};
if (e.Key == Key.Enter && at >= 0 && (_rows[at].ArrivedAt ?? _rows[at].DepartedAt) is { } t)
{
Seek?.Invoke(Math.Max(0, t - 5));
e.Handled = true;
return;
}
if (to is not { } row)
return;
_keyRow = Math.Clamp(row, 0, _rows.Count - 1);
string? before = _spoken;
_spoken = RowText(_keyRow);
(ControlAutomationPeer.FromElement(this) as SpokenPeer)?.Told(before, _spoken);
this.BringIntoView(new Rect(0, HeaderHeight + _keyRow * RowHeight, Bounds.Width, RowHeight));
InvalidateVisual();
e.Handled = true;
}
protected override void OnGotFocus(FocusChangedEventArgs e)
{
base.OnGotFocus(e);
_spoken = null;
InvalidateVisual();
}
protected override void OnLostFocus(FocusChangedEventArgs e)
{
base.OnLostFocus(e);
_keyRow = -1;
InvalidateVisual();
}
public Recording? Recording
@@ -103,6 +183,8 @@ public sealed class TimetablePanel : Control
{
var size = Bounds.Size;
var culture = CultureInfo.CurrentCulture;
if (IsFocused)
context.DrawRectangle(null, Palette.FocusPen, new Rect(size).Deflate(1));
if (_timetable is not { } timetable)
{
context.DrawText(MapView.Text(Strings["TimetableNone"], Palette.DimText, 12), new Point(Pad, Pad));
@@ -130,6 +212,8 @@ public sealed class TimetablePanel : Control
}
else if (i == _hover)
context.DrawRectangle(Palette.Faded(Palette.CardHover, 0.6), null, new Rect(0, top, size.Width, RowHeight - 1));
if (IsFocused && i == KeyRow)
context.DrawRectangle(null, Palette.FocusPen, new Rect(1, top + 1, size.Width - 2, RowHeight - 3));
// The line of the route through the stations, a dot each: hollow ahead, filled when done.
var outcome = row.Outcome;

View File

@@ -1,5 +1,8 @@
using System;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
@@ -235,10 +238,13 @@ internal static class UiKit
BorderBrush = Palette.CardBorder;
BorderThickness = new Thickness(0, 0, 0, 1);
Child = _row;
// Read as the tabs they are, which of them is picked.
AutomationProperties.SetControlTypeOverride(_row, AutomationControlType.Tab);
AutomationProperties.SetAccessibilityView(_row, AccessibilityView.Content);
for (int i = 0; i < choices.Length; i++)
{
int index = i;
var button = new Button
var button = new SegmentButton
{
Content = choices[i],
Padding = new Thickness(14, 3),
@@ -267,8 +273,9 @@ internal static class UiKit
_selected = value;
for (int i = 0; i < _row.Children.Count; i++)
{
var button = (Button)_row.Children[i];
var button = (SegmentButton)_row.Children[i];
bool on = i == value;
button.IsOn = on;
var line = on ? Palette.Accent : Brushes.Transparent;
button.Background = on ? Palette.Panel : Brushes.Transparent;
button.BorderBrush = line;
@@ -280,4 +287,51 @@ internal static class UiKit
}
}
}
/// <summary>
/// A choice of <see cref="Segmented"/>: a button to look at, a tab to a screen reader,
/// which says whether it is the one picked.
/// </summary>
private sealed class SegmentButton : Button
{
private bool _on;
protected override Type StyleKeyOverride => typeof(Button);
public bool IsOn
{
get => _on;
set
{
if (_on == value)
return;
_on = value;
(ControlAutomationPeer.FromElement(this) as Peer)?.Told(!value, value);
}
}
public void Pick() => OnClick();
protected override AutomationPeer OnCreateAutomationPeer() => new Peer(this);
private sealed class Peer(SegmentButton owner) : ButtonAutomationPeer(owner), ISelectionItemProvider
{
public void Told(bool before, bool now) =>
RaisePropertyChangedEvent(SelectionItemPatternIdentifiers.IsSelectedProperty, before, now);
protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.TabItem;
public bool IsSelected => owner.IsOn;
public ISelectionProvider? SelectionContainer => null;
public void Select() => owner.Pick();
public void AddToSelection() => owner.Pick();
public void RemoveFromSelection()
{
}
}
}
}

View File

@@ -0,0 +1,125 @@
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.VisualTree;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class AnnouncerTests
{
private DateTime _now = new(2026, 11, 15, 12, 0, 0, DateTimeKind.Utc);
private Announcer NewAnnouncer() => new(() => _now);
[Fact]
public void A_message_is_read_while_fresh_and_then_forgotten()
{
var announcer = NewAnnouncer();
announcer.Say(" Jakość grafiki: Wysoka ");
Assert.Equal("Jakość grafiki: Wysoka", announcer.Message);
_now += Announcer.Shown;
Assert.Null(announcer.Message);
}
[Fact]
public void Nothing_to_say_says_nothing()
{
var announcer = NewAnnouncer();
announcer.Say("Zapisano ustawienia");
announcer.Say(" ");
Assert.Equal("Zapisano ustawienia", announcer.Message);
}
[Fact]
public void A_control_inside_says_it_through_the_window_announcer()
{
var button = new Button();
var announcer = NewAnnouncer();
announcer.Child = new Border { Child = button };
Announcer.Say(button, "Godzina: 07:05");
Assert.Equal("Godzina: 07:05", announcer.Message);
}
[Fact]
public void A_control_outside_any_announcer_is_not_heard()
{
var button = new Button();
var thrown = Record.Exception(() => Announcer.Say(button, "Godzina: 07:05"));
Assert.Null(thrown);
Assert.Null(button.FindAncestorOfType<Announcer>());
}
[Fact]
public void A_marked_text_is_read_when_it_changes()
{
var status = new TextBlock();
Announcer.SetChanges(status, true);
var plain = new TextBlock();
var announcer = NewAnnouncer();
announcer.Child = new StackPanel { Children = { status, plain } };
plain.Text = "Ścieżka";
Assert.Null(announcer.Message);
status.Text = "Niezapisane zmiany";
Assert.True(Announcer.GetChanges(status));
Assert.Equal("Niezapisane zmiany", announcer.Message);
}
[Fact]
public void A_screen_reader_hears_it_as_a_polite_live_region()
{
var announcer = NewAnnouncer();
var peer = ControlAutomationPeer.CreatePeerForElement(announcer);
announcer.Say("Przywrócono domyślne");
Assert.Equal("Przywrócono domyślne", peer.GetName());
Assert.Equal(AutomationLiveSetting.Polite, peer.GetLiveSetting());
Assert.Equal(AutomationControlType.Group, peer.GetAutomationControlType());
}
}
[Collection(AvaloniaControls.Name)]
public class NamedGroupTests
{
static NamedGroupTests() => ScreenReaderNames.Install();
[Fact]
public void A_panel_with_a_title_is_a_group_named_by_it()
{
var panel = new HeaderedContentControl { Header = "Scenerie" };
Assert.Equal("Scenerie", AutomationProperties.GetName(panel));
Assert.Equal(AutomationControlType.Group, AutomationProperties.GetControlTypeOverride(panel));
Assert.Equal(AccessibilityView.Content, AutomationProperties.GetAccessibilityView(panel));
}
[Fact]
public void A_panel_whose_title_goes_is_no_longer_a_group()
{
var panel = new HeaderedContentControl { Header = "Skład" };
panel.Header = null;
Assert.Null(AutomationProperties.GetName(panel));
Assert.Null(AutomationProperties.GetControlTypeOverride(panel));
Assert.Equal(AccessibilityView.Default, AutomationProperties.GetAccessibilityView(panel));
}
[Fact]
public void A_tab_keeps_its_own_way_of_speaking()
{
var tab = new TabItem { Header = "Pogoda" };
Assert.Null(AutomationProperties.GetName(tab));
Assert.Equal(AutomationControlType.TabItem, AutomationProperties.GetControlTypeOverride(tab));
}
}

View File

@@ -0,0 +1,11 @@
namespace StarterNG.Tests;
/// <summary>
/// Tests that build Avalonia controls run one after another: a control belongs to the
/// thread that made the first one, and run side by side they now and then failed.
/// </summary>
[CollectionDefinition(Name)]
public sealed class AvaloniaControls
{
public const string Name = "Avalonia controls";
}

View File

@@ -0,0 +1,284 @@
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.VisualTree;
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
/// <summary>
/// The black box's own drawn panels as a screen reader user meets them: reached with Tab,
/// walked with the keys, their value and description read, what they show said aloud.
/// </summary>
[Collection(AvaloniaControls.Name)]
public class BlackBoxViewsTests
{
private const uint Head = 1;
/// <summary>
/// The user in vehicle 1 from t = 0 to 120: timetable ROJ1 standing at A, stopping at B
/// from 60 to 70, passing C at 100; the clock at 10:34 (634 min).
/// </summary>
private static Recording Journey(bool extended = true, byte? engine = null)
{
var f = new BlackBoxFile().Info()
.Vehicle(Head, "EU07-005", "ROJ1")
.User(0, Head, true, 1)
.Timetable(0, Head, "ROJ1", "A", "C", ("A", -1, 634), ("Stacja_B", 635, 635.5f), ("C", 637.5f, 638))
.Station(1, Head, 4, 1, "A", 1150);
for (double t = 0; t <= 120; t += 0.5)
{
float speed = t is >= 55 and < 70 ? 0 : 40;
f.Cab(t, Head, 1150 + t * 10, speed, extended: extended, engine: engine, nextLimit: 60, nextDistance: 500,
brakeCylinder: t is >= 50 and < 70 ? 2.5f : 0, devices: 0x0207);
}
f.Station(60, Head, 1, 2, "Stacja_B", 1300)
.Station(100, Head, 3, 3, "C", 2150);
return BlackBoxReader.Read(f.End(120).Stream());
}
private static IValueProvider Value(Control control) =>
Assert.IsAssignableFrom<IValueProvider>(Controls.Peer(control));
// --- timeline ---
[Fact]
public void The_timeline_is_a_slider_read_as_the_moment_with_how_to_walk_it()
{
var timeline = new TimelineView { Spoken = "10:35:12, 40 km/h" };
var peer = Controls.Peer(timeline);
var value = Value(timeline);
Assert.Equal(AutomationControlType.Slider, peer.GetAutomationControlType());
Assert.Equal("10:35:12, 40 km/h", value.Value);
Assert.True(value.IsReadOnly);
Assert.False(string.IsNullOrEmpty(peer.GetHelpText()));
Assert.True(peer.IsContentElement());
Assert.True(peer.IsControlElement());
Assert.Throws<InvalidOperationException>(() => value.SetValue("x"));
timeline.Spoken = "10:35:22, 40 km/h";
Assert.Equal("10:35:22, 40 km/h", value.Value);
}
[Fact]
public void A_description_set_on_the_timeline_wins_over_its_own()
{
var timeline = new TimelineView();
AutomationProperties.SetHelpText(timeline, "own words");
Assert.Equal("own words", Controls.Peer(timeline).GetHelpText());
}
[Theory]
[InlineData(Key.Right, KeyModifiers.None, 70)]
[InlineData(Key.Left, KeyModifiers.None, 50)]
[InlineData(Key.Right, KeyModifiers.Control, 120)]
[InlineData(Key.Left, KeyModifiers.Control, 0)]
[InlineData(Key.PageDown, KeyModifiers.None, 120)]
[InlineData(Key.PageUp, KeyModifiers.None, 0)]
[InlineData(Key.Home, KeyModifiers.None, 0)]
[InlineData(Key.End, KeyModifiers.None, 120)]
public void The_keys_take_the_timeline_through_the_recording(Key key, KeyModifiers modifiers, double expected)
{
var timeline = new TimelineView { Recording = Journey(), Time = 60 };
double? sought = null;
timeline.Seek += t => sought = t;
Assert.True(Controls.Press(timeline, key, modifiers));
Assert.Equal(expected, sought);
}
[Fact]
public void Other_keys_and_an_empty_timeline_are_left_alone()
{
var empty = new TimelineView();
var timeline = new TimelineView { Recording = Journey(), Time = 60 };
bool sought = false;
empty.Seek += _ => sought = true;
timeline.Seek += _ => sought = true;
Assert.False(Controls.Press(empty, Key.Right));
Assert.False(Controls.Press(timeline, Key.A));
Assert.False(sought);
}
[Fact]
public void The_timeline_draws_with_and_without_the_focus()
{
var timeline = new TimelineView { Recording = Journey(), Time = 60 };
var window = Controls.Show(timeline, 900, 300);
try
{
timeline.Fit();
Controls.Draw(timeline);
Assert.True(timeline.IsFocused);
timeline.Time = 119;
Controls.Draw(timeline);
window.Focus();
Controls.Draw(timeline);
}
finally
{
window.Close();
}
}
// --- timetable ---
[Fact]
public void The_timetable_is_a_list_read_row_by_row_from_the_keys()
{
var table = new TimetablePanel { Recording = Journey(), Time = 30 };
var peer = Controls.Peer(table);
var value = Value(table);
Assert.Equal(AutomationControlType.List, peer.GetAutomationControlType());
Assert.False(string.IsNullOrEmpty(peer.GetHelpText()));
Assert.StartsWith("1/3. A", value.Value);
Assert.True(Controls.Press(table, Key.Down));
Assert.StartsWith("2/3. Stacja B", value.Value);
Assert.True(Controls.Press(table, Key.Up));
Assert.StartsWith("1/3. A", value.Value);
Assert.True(Controls.Press(table, Key.End));
Assert.StartsWith("3/3. C", value.Value);
Assert.True(Controls.Press(table, Key.Down));
Assert.StartsWith("3/3. C", value.Value);
Assert.True(Controls.Press(table, Key.Home));
Assert.StartsWith("1/3. A", value.Value);
Assert.Contains("km 2.5", value.Value.Replace(',', '.'));
Assert.False(Controls.Press(table, Key.A));
}
[Fact]
public void Enter_on_a_station_passed_goes_to_a_little_before_it()
{
var table = new TimetablePanel { Recording = Journey(), Time = 110 };
double? sought = null;
table.Seek += t => sought = t;
Controls.Press(table, Key.Home);
Controls.Press(table, Key.Down);
Assert.True(Controls.Press(table, Key.Enter));
Assert.Equal(55, sought);
}
[Fact]
public void A_recording_without_a_timetable_says_so_and_ignores_the_keys()
{
var recording = BlackBoxReader.Read(new BlackBoxFile().Info().Vehicle(Head, "EU07-005")
.Cab(0, Head, 1150, 40).End(1).Stream());
var table = new TimetablePanel { Recording = recording, Time = 0 };
Assert.False(string.IsNullOrEmpty(Value(table).Value));
Assert.False(Controls.Press(table, Key.Down));
table.Recording = null;
Controls.Lay(table);
Controls.Draw(table);
}
[Fact]
public void The_timetable_draws_its_rows_and_the_one_the_keys_stand_at()
{
var table = new TimetablePanel { Recording = Journey(), Time = 65 };
var window = Controls.Show(table, 600, 400);
try
{
Controls.Draw(table);
Controls.Press(table, Key.Down);
Controls.Draw(table);
window.Focus();
Controls.Draw(table);
}
finally
{
window.Close();
}
}
// --- cab ---
[Theory]
[InlineData(true, null)]
[InlineData(true, (byte)1)]
[InlineData(true, (byte)2)]
[InlineData(false, null)]
public void The_cab_says_what_it_draws(bool extended, byte? engine)
{
var cab = new CabPanel { Recording = Journey(extended, engine), Time = 30 };
Controls.Lay(cab, 600, 900);
Controls.Draw(cab);
Assert.NotNull(cab.Said);
Assert.Contains("EU07-005", cab.Said);
Assert.Contains("40 km/h", cab.Said);
Assert.Equal(AutomationControlType.Pane, Controls.Peer(cab).GetAutomationControlType());
Assert.Equal(cab.Said, Controls.Peer(cab).GetHelpText());
}
[Fact]
public void The_cab_stopped_under_the_brakes_and_out_of_the_recording()
{
var cab = new CabPanel { Recording = Journey(), Time = 60 };
var window = Controls.Show(cab, 600, 900);
try
{
Controls.Draw(cab);
Assert.Contains("0 km/h", cab.Said);
cab.Time = 500;
Controls.Draw(cab);
Assert.DoesNotContain("km/h", cab.Said);
}
finally
{
window.Close();
}
}
[Fact]
public void An_empty_cab_says_there_is_nothing_to_show()
{
var cab = new CabPanel();
Controls.Lay(cab);
Controls.Draw(cab);
Assert.False(string.IsNullOrEmpty(cab.Said));
}
// --- segmented choice ---
[Fact]
public void A_segmented_choice_is_a_row_of_tabs_one_of_them_selected()
{
var choice = new UiKit.Segmented("Mapa", "Profil", "Rozkład");
int? picked = null;
choice.SelectedChanged += i => picked = i;
var tabs = choice.GetVisualDescendants().OfType<Button>().ToList();
if (tabs.Count == 0)
tabs = ((Panel)choice.Child!).Children.OfType<Button>().ToList();
var second = Assert.IsAssignableFrom<ISelectionItemProvider>(Controls.Peer(tabs[1]));
Assert.Equal(AutomationControlType.TabItem, Controls.Peer(tabs[1]).GetAutomationControlType());
Assert.Null(second.SelectionContainer);
second.Select();
Assert.Equal(1, picked);
Assert.True(second.IsSelected);
Assert.Equal(1, choice.Selected);
var third = Assert.IsAssignableFrom<ISelectionItemProvider>(Controls.Peer(tabs[2]));
third.AddToSelection();
Assert.Equal(2, choice.Selected);
Assert.False(second.IsSelected);
third.RemoveFromSelection();
Assert.Equal(2, choice.Selected);
}
}

View File

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

View File

@@ -0,0 +1,101 @@
using StarterNG.Views;
using Unit = StarterNG.Views.ConsistNarration.Unit;
namespace StarterNG.Tests;
public class ConsistNarrationTests
{
// Each text shows its key and its arguments, so a test sees which sentence was picked and with what.
private static string Loc(string key) => key switch
{
"ConsistSaidEmpty" => "empty",
"ConsistSaidAdded" => "added {0} at {1}/{2}",
"ConsistSaidRemoved" => "removed {0}, {1} left",
"ConsistSaidTurned" => "turned {0}",
"ConsistSaidUnturned" => "unturned {0}",
"ConsistSaidTurnedMany" => "turned {0}",
"ConsistSaidMoved" => "moved {0} to {1}/{2}",
"ConsistSaidReordered" => "reordered",
"ConsistSaidReplaced" => "replaced {0} with {1}",
"ConsistSaidChangedMany" => "changed {0}, {1} now",
_ => throw new KeyNotFoundException(key)
};
private static Unit[] Units(params string[] labels) =>
labels.Select(l => new Unit(l.TrimEnd('^'), l.EndsWith('^'))).ToArray();
private static string? Say(string[] before, string[] after, int? vehicles = null) =>
ConsistNarration.Describe(Units(before), Units(after), vehicles ?? after.Length, Loc);
[Fact]
public void Nothing_changed_says_nothing() =>
Assert.Null(Say(["EU07", "Bdhpumn"], ["EU07", "Bdhpumn"]));
[Fact]
public void An_empty_consist_staying_empty_says_nothing() =>
Assert.Null(Say([], []));
[Fact]
public void Clearing_the_consist_says_it_is_empty() =>
Assert.Equal("empty", Say(["EU07", "Bdhpumn"], []));
[Fact]
public void A_vehicle_added_at_the_end_is_named_with_its_place() =>
Assert.Equal("added Bdhpumn at 2/2", Say(["EU07"], ["EU07", "Bdhpumn"]));
[Fact]
public void A_vehicle_added_in_the_middle_is_named_with_its_place() =>
Assert.Equal("added WRmnouz at 2/3", Say(["EU07", "Bdhpumn"], ["EU07", "WRmnouz", "Bdhpumn"]));
[Fact]
public void Two_vehicles_added_at_once_are_both_named() =>
Assert.Equal("added A, B at 1/3", Say(["EU07"], ["A", "B", "EU07"]));
[Fact]
public void A_removed_vehicle_is_named_with_the_count_left() =>
Assert.Equal("removed WRmnouz, 2 left", Say(["EU07", "WRmnouz", "Bdhpumn"], ["EU07", "Bdhpumn"]));
[Fact]
public void The_count_left_counts_vehicles_not_units() =>
Assert.Equal("removed EU07, 3 left", Say(["EU07", "EN57"], ["EN57"], vehicles: 3));
[Fact]
public void A_vehicle_turned_round_is_named() =>
Assert.Equal("turned Bdhpumn", Say(["EU07", "Bdhpumn"], ["EU07", "Bdhpumn^"]));
[Fact]
public void A_vehicle_turned_back_is_told_apart_from_one_turned() =>
Assert.Equal("unturned Bdhpumn", Say(["EU07", "Bdhpumn^"], ["EU07", "Bdhpumn"]));
[Fact]
public void Several_turned_at_once_are_counted() =>
Assert.Equal("turned 3", Say(["A", "B", "C"], ["A^", "B^", "C^"]));
[Fact]
public void A_vehicle_moved_towards_the_end_is_named_with_its_new_place() =>
Assert.Equal("moved A to 3/4", Say(["A", "B", "C", "D"], ["B", "C", "A", "D"]));
[Fact]
public void A_vehicle_moved_towards_the_front_is_named_with_its_new_place() =>
Assert.Equal("moved C to 1/4", Say(["A", "B", "C", "D"], ["C", "A", "B", "D"]));
[Fact]
public void Neighbours_swapped_are_told_as_one_moved() =>
Assert.Equal("moved A to 2/2", Say(["A", "B"], ["B", "A"]));
[Fact]
public void The_same_vehicles_shuffled_are_told_as_a_new_order() =>
Assert.Equal("reordered", Say(["A", "B", "C", "D"], ["B", "A", "D", "C"]));
[Fact]
public void One_vehicle_swapped_for_another_names_both() =>
Assert.Equal("replaced B with X", Say(["A", "B", "C"], ["A", "X", "C"]));
[Fact]
public void A_bigger_change_counts_the_vehicles_it_touched() =>
Assert.Equal("changed 2, 3 now", Say(["A", "B", "C"], ["A", "X", "Y"]));
[Fact]
public void Same_named_vehicles_next_to_each_other_still_count_one_added() =>
Assert.Equal("added Bdhpumn at 3/3", Say(["EU07", "Bdhpumn"], ["EU07", "Bdhpumn", "Bdhpumn"]));
}

View File

@@ -0,0 +1,75 @@
using Avalonia;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Themes.Fluent;
using Avalonia.Threading;
namespace StarterNG.Tests;
/// <summary>Keys, focus, layout and drawing for the tests of controls, with no one at the keyboard.</summary>
internal static class Controls
{
/// <summary>Presses a key on the control as the keyboard would; true when the control took it.</summary>
public static bool Press(Control control, Key key, KeyModifiers modifiers = KeyModifiers.None)
{
var e = new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Key = key, KeyModifiers = modifiers, Source = control };
control.RaiseEvent(e);
return e.Handled;
}
/// <summary>
/// The control in a window of its own, shown, laid out and focused if it can be;
/// themed, its parts are built from the templates the application uses.
/// </summary>
public static Window Show(Control control, double width = 640, double height = 720, bool themed = false)
{
HeadlessDrawing.Ensure();
if (themed)
Theme();
var window = new Window { Width = width, Height = height, Content = control };
window.Show();
window.UpdateLayout();
Settle();
if (control.Focusable)
control.Focus();
return window;
}
/// <summary>Lays the control out alone at the size given.</summary>
public static void Lay(Control control, double width = 640, double height = 720)
{
HeadlessDrawing.Ensure();
control.Measure(new Size(width, height));
control.Arrange(new Rect(0, 0, width, height));
}
/// <summary>Has the control draw itself once.</summary>
public static void Draw(Control control)
{
HeadlessDrawing.Ensure();
var group = new DrawingGroup();
using var context = group.Open();
control.Render(context);
}
private static bool _themed;
// Where the application keeps it: given to a window alone, a slider or a number box was left without its parts.
private static void Theme()
{
if (_themed)
return;
Avalonia.Application.Current!.Styles.Add(new FluentTheme());
_themed = true;
}
/// <summary>Runs what was left for the dispatcher to do later, such as naming a row once it is laid out.</summary>
public static void Settle() => Dispatcher.UIThread.RunJobs();
public static AutomationPeer Peer(Control control) => ControlAutomationPeer.CreatePeerForElement(control);
public static RoutedEventArgs Click() => new(Button.ClickEvent);
}

View File

@@ -0,0 +1,376 @@
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.VisualTree;
using StarterNG.Controls;
namespace StarterNG.Tests;
/// <summary>
/// Windows opened over another, searches and the starter's own controls as someone at the
/// keyboard with a screen reader meets them, in windows built as the application builds them.
/// </summary>
[Collection(AvaloniaControls.Name)]
public class DialogControlsTests
{
static DialogControlsTests()
{
HeadlessDrawing.Ensure();
DialogKeyboard.Install();
ScreenReaderNames.Install();
}
private static (Window Owner, Window Dialog) Dialog(Control content, bool escapeCloses = true)
{
var owner = new Window();
owner.Show();
var dialog = new Window { Width = 300, Height = 200, Content = content };
DialogKeyboard.SetEscapeCloses(dialog, escapeCloses);
_ = dialog.ShowDialog(owner);
// Headless a window says it opened before it is given its owner; it says so again once it has one.
Assert.Same(owner, dialog.Owner);
dialog.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Window.WindowOpenedEvent));
Controls.Settle();
return (owner, dialog);
}
// --- windows over another ---
[Fact]
public void A_dialog_opens_on_its_default_button_and_esc_closes_it()
{
var other = new Button { Content = "Nie" };
var yes = new Button { Content = "Tak", IsDefault = true };
var (owner, dialog) = Dialog(new StackPanel { Children = { other, yes } });
bool closed = false;
dialog.Closed += (_, _) => closed = true;
Assert.True(yes.IsFocused);
Assert.False(Controls.Press(dialog, Key.Escape, KeyModifiers.Shift));
Assert.True(Controls.Press(dialog, Key.Escape));
Assert.True(closed);
owner.Close();
}
[Fact]
public void Without_a_default_button_focus_goes_to_the_first_control()
{
var first = new TextBox();
var (owner, dialog) = Dialog(new StackPanel { Children = { first, new Button { Content = "OK" } } });
Assert.True(first.IsFocused);
dialog.Close();
owner.Close();
}
[Fact]
public void A_window_that_placed_the_focus_itself_keeps_it()
{
var first = new Button { Content = "1" };
var chosen = new Button { Content = "2" };
var (owner, dialog) = Dialog(new StackPanel { Children = { first, chosen } });
chosen.Focus();
Assert.False(first.IsFocused);
DialogKeyboard.FocusFirst(dialog);
Assert.True(chosen.IsFocused);
dialog.Close();
owner.Close();
}
[Fact]
public void Esc_does_not_close_a_window_that_stays_beside_the_main_one()
{
var (owner, dialog) = Dialog(new Button { Content = "OK" }, escapeCloses: false);
bool closed = false;
dialog.Closed += (_, _) => closed = true;
Assert.False(DialogKeyboard.GetEscapeCloses(dialog));
Assert.False(Controls.Press(dialog, Key.Escape));
Assert.False(closed);
dialog.Close();
owner.Close();
}
[Fact]
public void Tab_with_only_the_window_focused_starts_from_the_first_control()
{
var first = new Button { Content = "1" };
// Opened with nothing to focus, its controls put in afterwards.
var (owner, dialog) = Dialog(new TextBlock { Text = "…" });
dialog.Content = new StackPanel { Children = { first, new Button { Content = "2" } } };
dialog.UpdateLayout();
Assert.False(first.IsFocused);
Assert.True(Controls.Press(dialog, Key.Tab));
Assert.True(first.IsFocused);
dialog.Close();
owner.Close();
}
[Fact]
public void A_window_of_its_own_is_left_to_its_own_ways()
{
var button = new Button { Content = "1" };
var window = Controls.Show(button);
Assert.False(Controls.Press(window, Key.Escape));
window.Close();
}
// --- searches ---
[Fact]
public void A_search_says_how_many_entries_are_left_once_typing_pauses()
{
var box = new TextBox();
var announcer = new Announcer { Child = box };
var window = Controls.Show(announcer);
try
{
var teller = new SearchResultsTeller(box, () => 3);
box.Focus();
box.Text = "EU07";
teller.Changed();
Thread.Sleep(SearchResultsTeller.Pause + TimeSpan.FromMilliseconds(300));
Controls.Settle();
Assert.NotNull(announcer.Message);
}
finally
{
window.Close();
}
}
[Fact]
public void An_empty_search_or_one_left_says_nothing()
{
var box = new TextBox();
var elsewhere = new Button { Content = "x" };
var announcer = new Announcer { Child = new StackPanel { Children = { box, elsewhere } } };
var window = Controls.Show(announcer);
try
{
var teller = new SearchResultsTeller(box, () => 3);
box.Focus();
box.Text = " ";
teller.Changed();
Thread.Sleep(SearchResultsTeller.Pause + TimeSpan.FromMilliseconds(300));
Controls.Settle();
Assert.Null(announcer.Message);
box.Text = "EU07";
elsewhere.Focus();
teller.Changed();
Thread.Sleep(SearchResultsTeller.Pause + TimeSpan.FromMilliseconds(300));
Controls.Settle();
Assert.Null(announcer.Message);
}
finally
{
window.Close();
}
}
// --- tree entries ---
[Fact]
public void Every_part_of_a_row_tells_whether_the_entry_is_open()
{
var words = ExpandableTreeViewItem.StateWords;
ExpandableTreeViewItem.StateWords = s => s switch
{
ExpandCollapseState.Expanded => "rozwinięte",
ExpandCollapseState.Collapsed => "zwinięte",
_ => null
};
var child = new ExpandableTreeViewItem { Header = "test32" };
var group = new ExpandableTreeViewItem { Header = "Całkowo", Items = { child } };
AutomationProperties.SetName(group, "Całkowo");
var tree = new TreeView { Items = { group } };
var window = Controls.Show(tree, themed: true);
try
{
var row = group.GetVisualDescendants().OfType<Control>().First(c => c.Name == "PART_LayoutRoot");
Assert.Equal("zwinięte", AutomationProperties.GetHelpText(row));
Assert.Equal("Całkowo", AutomationProperties.GetName(row));
var peer = Controls.Peer(group);
((IExpandCollapseProvider)peer).Expand();
Controls.Settle();
Assert.Equal("rozwinięte", AutomationProperties.GetHelpText(row));
AutomationProperties.SetName(group, "Całkowo i okolice");
Assert.Equal("Całkowo i okolice", AutomationProperties.GetName(row));
group.Header = "Całkowo 2";
Controls.Settle();
window.UpdateLayout();
Assert.Same(group, child.ReadableParent);
Assert.Same(peer, Controls.Peer(child).GetParent());
var leafRow = child.GetVisualDescendants().OfType<Control>().First(c => c.Name == "PART_LayoutRoot");
Assert.Null(AutomationProperties.GetHelpText(leafRow));
tree.Items.Clear();
Controls.Settle();
}
finally
{
ExpandableTreeViewItem.StateWords = words;
window.Close();
}
}
// --- sliders and number boxes ---
[Fact]
public void The_track_and_knob_of_a_slider_are_named_with_its_value()
{
var fog = new ReadableSlider { Minimum = 0, Maximum = 1000, Value = 500, ValueText = "2,4 km" };
AutomationProperties.SetName(fog, "Widoczność");
var window = Controls.Show(fog, themed: true);
try
{
var track = fog.GetVisualDescendants().OfType<Avalonia.Controls.Primitives.Track>().Single();
Assert.Equal("Widoczność: 2,4 km", AutomationProperties.GetName(track));
fog.ValueText = "3 km";
Assert.Equal("Widoczność: 3 km", AutomationProperties.GetName(track));
var value = Assert.IsAssignableFrom<IValueProvider>(Controls.Peer(fog));
Assert.False(value.IsReadOnly);
Assert.Equal("Slider", Controls.Peer(fog).GetClassName());
Assert.Throws<ArgumentException>(() => value.SetValue("duĹĽo"));
}
finally
{
window.Close();
}
}
[Fact]
public void A_number_box_gives_its_name_to_the_text_inside_and_its_arrows_say_what_they_do()
{
var box = new NumericUpDown { Value = 3 };
AutomationProperties.SetName(box, "Liczba wagonĂłw");
var window = Controls.Show(box, themed: true);
try
{
var text = box.GetVisualDescendants().OfType<TextBox>().Single();
Assert.Equal("Liczba wagonĂłw", AutomationProperties.GetName(text));
var arrows = box.GetVisualDescendants().OfType<Control>()
.Where(c => c.Name is "PART_IncreaseButton" or "PART_DecreaseButton").ToList();
Assert.NotEmpty(arrows);
Assert.All(arrows, a => Assert.False(KeyboardNavigation.GetIsTabStop(a)));
Assert.All(arrows, a => Assert.False(string.IsNullOrEmpty(AutomationProperties.GetName(a))));
}
finally
{
window.Close();
}
}
[Fact]
public void A_picker_is_reached_through_its_button_named_with_the_label_and_value()
{
var date = new DatePicker { SelectedDate = new DateTimeOffset(2026, 11, 15, 0, 0, 0, TimeSpan.Zero) };
var time = new TimePicker { SelectedTime = new TimeSpan(7, 5, 0) };
AutomationProperties.SetName(date, "Data");
AutomationProperties.SetName(time, "Godzina");
var window = Controls.Show(new StackPanel { Children = { date, time } }, themed: true);
try
{
var dateButton = date.GetVisualDescendants().OfType<Button>().First(b => b.Name == "PART_FlyoutButton");
var timeButton = time.GetVisualDescendants().OfType<Button>().First(b => b.Name == "PART_FlyoutButton");
Assert.StartsWith("Data", AutomationProperties.GetName(dateButton));
Assert.StartsWith("Godzina", AutomationProperties.GetName(timeButton));
time.SelectedTime = new TimeSpan(8, 0, 0);
Assert.StartsWith("Godzina", AutomationProperties.GetName(timeButton));
}
finally
{
window.Close();
}
}
[Fact]
public void A_list_says_its_new_choice_when_the_arrows_change_it()
{
var combo = new ComboBox { ItemsSource = new[] { "Niska", "Ĺšrednia", "Wysoka" }, SelectedIndex = 0 };
var announcer = new Announcer { Child = combo };
var window = Controls.Show(announcer, themed: true);
try
{
combo.Focus();
combo.SelectedIndex = 2;
Assert.Equal("Wysoka", announcer.Message);
}
finally
{
window.Close();
}
}
// --- settings sections ---
private static SettingsSection Section() => new()
{
Template = new FuncControlTemplate<SettingsSection>((_, scope) =>
{
var reset = new Button { Name = "PART_Reset" };
scope.Register(reset.Name, reset);
return reset;
})
};
[Fact]
public void A_sections_reset_button_says_which_section_it_puts_back()
{
var section = Section();
section.Header = "Grafika";
section.ResetLabel = "Przywróć";
SettingsSection? asked = null;
section.ResetRequested += s => asked = s;
Controls.Lay(section);
section.ApplyTemplate();
var reset = (Button)section.GetVisualChildren().Single();
Assert.Equal("Przywróć: Grafika", AutomationProperties.GetName(reset));
section.Header = "Dźwięk";
Assert.Equal("Przywróć: Dźwięk", AutomationProperties.GetName(reset));
section.ResetLabel = null;
section.Header = null;
Assert.True(string.IsNullOrEmpty(AutomationProperties.GetName(reset)));
reset.RaiseEvent(Controls.Click());
Assert.Same(section, asked);
section.Template = Section().Template;
section.ApplyTemplate();
Assert.Null(section.ToggleKey);
Assert.Null(section.Toggle);
}
[Fact]
public void A_sections_list_of_levels_is_named_as_the_level_of_that_section()
{
var level = new ComboBox();
var section = new SettingsSection { Level = level, Header = "Grafika", ToggleKey = "shadows", Toggle = new CheckBox() };
Assert.EndsWith("Grafika", AutomationProperties.GetName(level));
Assert.Same(level, section.Level);
Assert.Equal("shadows", section.ToggleKey);
}
}

View File

@@ -0,0 +1,53 @@
using StarterNG.Views;
namespace StarterNG.Tests;
public class ExecutableListTests
{
[Fact]
public void A_build_copied_in_joins_the_list_and_the_choice_stays()
{
var (entries, chosen) = ExecutableList.Refreshed(["eu07_new.exe", "eu07.exe"], "eu07.exe");
Assert.Equal(new[] { "eu07_new.exe", "eu07.exe" }, entries);
Assert.Equal(1, chosen);
}
[Fact]
public void Automatic_stays_automatic()
{
var (entries, chosen) = ExecutableList.Refreshed(["eu07_new.exe", "eu07.exe"], null);
Assert.Equal(new[] { "eu07_new.exe", "eu07.exe" }, entries);
Assert.Equal(-1, chosen);
}
[Fact]
public void A_simulator_picked_from_elsewhere_stays_on_the_list_and_chosen()
{
const string picked = @"D:\build\eu07.exe";
var (entries, chosen) = ExecutableList.Refreshed(["eu07.exe"], picked);
Assert.Equal(new[] { "eu07.exe", picked }, entries);
Assert.Equal(1, chosen);
}
[Fact]
public void A_chosen_file_since_removed_stays_chosen_rather_than_switch_silently()
{
var (entries, chosen) = ExecutableList.Refreshed(["eu07.exe"], "eu07_old.exe");
Assert.Equal(new[] { "eu07.exe", "eu07_old.exe" }, entries);
Assert.Equal(1, chosen);
}
[Fact]
public void The_choice_is_found_whatever_the_case_of_its_name()
{
var (entries, chosen) = ExecutableList.Refreshed(["EU07.exe"], "eu07.exe");
Assert.Equal(new[] { "EU07.exe" }, entries);
Assert.Equal(0, chosen);
}
}

View File

@@ -0,0 +1,82 @@
using StarterNG.Domain.Settings;
using StarterNG.Infrastructure.Settings;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class ExecutableNoAvx2Tests
{
private const string Elf = "\u007fELF binary";
private static readonly DateTime Older = new(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly DateTime Newer = new(2026, 11, 15, 0, 0, 0, DateTimeKind.Utc);
private static InMemoryFileSystem With(params string[] names)
{
var files = new InMemoryFileSystem();
foreach (string name in names)
files.WithExecutable(TestInstallation.At(name), Elf);
return files;
}
private static string Automatic(InMemoryFileSystem files, bool lacksAvx2) =>
Path.GetFileName(new TestInstallation(files, lacksAvx2: lacksAvx2).Executables
.Resolve(new SimulatorSettings(), out _));
[Theory]
[InlineData("eu07_noavx2", true)]
[InlineData("eu07-x64_2026-11-15_abc1234_noavx2.exe", true)]
[InlineData("EU07_NOAVX2.EXE", true)]
[InlineData("eu07", false)]
[InlineData("eu07-x64_2026-11-15_abc1234.exe", false)]
[InlineData("eu07_noavx2_old.exe", false)]
public void A_build_without_avx2_is_known_by_the_end_of_its_name(string name, bool noAvx2) =>
Assert.Equal(noAvx2, ExecutableLocator.IsNoAvx2(name));
[Fact]
public void Without_avx2_the_build_without_it_is_chosen_over_the_canonical_one() =>
Assert.Equal("eu07_noavx2", Automatic(With("eu07", "eu07_noavx2"), lacksAvx2: true));
[Fact]
public void With_avx2_the_build_made_for_it_stays_first() =>
Assert.Equal("eu07", Automatic(With("eu07", "eu07_noavx2"), lacksAvx2: false));
[Fact]
public void With_avx2_a_build_without_it_is_used_when_it_is_the_only_one() =>
Assert.Equal("eu07_noavx2", Automatic(With("eu07_noavx2"), lacksAvx2: false));
[Fact]
public void Without_avx2_the_newest_build_without_it_is_chosen()
{
var files = With("eu07_2026-11-01_aaa_noavx2", "eu07_2026-11-15_bbb_noavx2")
.WrittenAt(TestInstallation.At("eu07_2026-11-01_aaa_noavx2"), Older)
.WrittenAt(TestInstallation.At("eu07_2026-11-15_bbb_noavx2"), Newer);
Assert.Equal("eu07_2026-11-15_bbb_noavx2", Automatic(files, lacksAvx2: true));
}
[Fact]
public void Without_avx2_and_no_build_without_it_the_usual_choice_stands() =>
Assert.Equal("eu07", Automatic(With("eu07-dev", "eu07"), lacksAvx2: true));
[Fact]
public void Only_a_build_with_avx2_on_a_processor_without_it_will_not_run()
{
var lacking = new TestInstallation(lacksAvx2: true).Executables;
var able = new TestInstallation(lacksAvx2: false).Executables;
Assert.True(lacking.WillNotRunHere("eu07.exe"));
Assert.False(lacking.WillNotRunHere("eu07-x64_noavx2.exe"));
Assert.False(able.WillNotRunHere("eu07.exe"));
}
[Fact]
public void The_newest_build_without_avx2_is_offered_by_name()
{
var files = With("eu07", "eu07_2026-11-01_aaa_noavx2", "eu07_2026-11-15_bbb_noavx2")
.WrittenAt(TestInstallation.At("eu07_2026-11-01_aaa_noavx2"), Older)
.WrittenAt(TestInstallation.At("eu07_2026-11-15_bbb_noavx2"), Newer);
Assert.Equal("eu07_2026-11-15_bbb_noavx2", new TestInstallation(files).Executables.NewestNoAvx2());
Assert.Null(new TestInstallation(With("eu07")).Executables.NewestNoAvx2());
}
}

View File

@@ -0,0 +1,63 @@
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class ExpandableTreeViewItemTests
{
private static IExpandCollapseProvider Peer(ExpandableTreeViewItem item) =>
Assert.IsAssignableFrom<IExpandCollapseProvider>(ControlAutomationPeer.CreatePeerForElement(item));
[Fact]
public void A_scenery_with_nothing_under_it_is_a_leaf()
{
var peer = Peer(new ExpandableTreeViewItem { Header = "test32" });
Assert.Equal(ExpandCollapseState.LeafNode, peer.ExpandCollapseState);
Assert.False(peer.ShowsMenu);
}
[Fact]
public void A_group_says_whether_it_is_open()
{
Assert.Equal(ExpandCollapseState.Collapsed, ExpandableTreeViewItem.StateFor(hasChildren: true, expanded: false));
Assert.Equal(ExpandCollapseState.Expanded, ExpandableTreeViewItem.StateFor(hasChildren: true, expanded: true));
Assert.Equal(ExpandCollapseState.LeafNode, ExpandableTreeViewItem.StateFor(hasChildren: false, expanded: true));
}
[Fact]
public void A_screen_reader_can_open_and_close_an_entry()
{
var item = new ExpandableTreeViewItem { Header = "Całkowo" };
var peer = Peer(item);
peer.Expand();
Assert.True(item.IsExpanded);
peer.Collapse();
Assert.False(item.IsExpanded);
}
[Fact]
public void An_entry_on_its_own_has_nothing_over_it()
{
var item = new ExpandableTreeViewItem { Header = "Całkowo", IsExpanded = true };
var peer = ControlAutomationPeer.CreatePeerForElement(item);
Assert.Null(item.ReadableParent);
Assert.Null(peer.GetParent());
}
[Fact]
public void The_row_under_the_mouse_is_told_open_or_closed_and_a_leaf_nothing()
{
static string Loc(string key) => key == "TreeExpanded" ? "rozwinięte" : "zwinięte";
Assert.Equal("rozwinięte", ExpandableTreeViewItem.WordFor(ExpandCollapseState.Expanded, Loc));
Assert.Equal("zwinięte", ExpandableTreeViewItem.WordFor(ExpandCollapseState.Collapsed, Loc));
Assert.Null(ExpandableTreeViewItem.WordFor(ExpandCollapseState.LeafNode, Loc));
}
}

View File

@@ -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));
/// <summary>A link counts as the directory it points at, as the disk has it.</summary>
@@ -273,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) =>

View File

@@ -14,7 +14,7 @@ public sealed class TestInstallation
{
public const string Root = "game";
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null)
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null, bool lacksAvx2 = false)
{
Files = files ?? new InMemoryFileSystem();
Paths = new GamePaths(Root);
@@ -35,7 +35,8 @@ public sealed class TestInstallation
SettingsPaths.VehicleCacheDirectory());
Library = new GameLibrary(VehicleCache, Sceneries, MiniTextures, Physics, Log);
Executables = new ExecutableLocator(Files, Paths, Environment, Log);
// The processor of the machine running the tests is not the one tested.
Executables = new ExecutableLocator(Files, Paths, Environment, Log, lacksAvx2);
SettingsStore = new SettingsStore(Files, Clock, Log, SettingsPaths, new SettingsSerializer(), Executables);
Tapes = new HaslerTapes(Files, Paths, Log, Clock, new TimetableLocator(Files), () => SimulatorRunning);
}

View File

@@ -0,0 +1,98 @@
using Avalonia.Automation;
using Avalonia.Controls;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class FieldLabelTests
{
static FieldLabelTests() => ScreenReaderNames.Install();
private static T At<T>(T control, int row, int column) where T : Control
{
Grid.SetRow(control, row);
Grid.SetColumn(control, column);
return control;
}
[Fact]
public void A_field_is_named_by_the_nearest_label_left_of_it_in_its_row()
{
var far = At(new TextBlock { Text = "Pogoda" }, 0, 0);
var near = At(new TextBlock { Text = "Temperatura" }, 0, 1);
var value = At(new TextBlock { Text = "-5 °C" }, 0, 3);
var other = At(new TextBlock { Text = "Widoczność" }, 1, 1);
var slider = At(new Slider(), 0, 2);
_ = new Grid { Children = { far, near, value, other, slider } };
ScreenReaderNames.NameByLabel(slider);
Assert.Equal("Temperatura", AutomationProperties.GetName(slider));
}
[Fact]
public void A_field_with_nothing_to_its_left_is_named_by_the_label_above()
{
var label = At(new TextBlock { Text = "Klasa" }, 0, 1);
var combo = At(new ComboBox(), 1, 1);
_ = new Grid { Children = { label, combo } };
Assert.Same(label, ScreenReaderNames.LabelOf(combo));
}
[Fact]
public void In_a_panel_the_label_is_the_text_just_before_the_field()
{
var label = new TextBlock { Text = "Profil" };
var box = new TextBox();
var after = new TextBox();
_ = new StackPanel { Children = { label, box, new Button(), after } };
ScreenReaderNames.NameByLabel(box);
Assert.Equal("Profil", AutomationProperties.GetName(box));
Assert.Null(ScreenReaderNames.LabelOf(after));
}
[Fact]
public void A_hidden_text_or_a_long_description_is_no_label()
{
var hidden = new TextBlock { Text = "Ukryte", IsVisible = false };
var first = new ComboBox();
var description = new TextBlock { Text = new string('x', 61) };
var second = new ComboBox();
_ = new StackPanel { Children = { hidden, first, description, second } };
Assert.Null(ScreenReaderNames.LabelOf(first));
Assert.Null(ScreenReaderNames.LabelOf(second));
Assert.Null(ScreenReaderNames.LabelOf(new ComboBox()));
}
[Fact]
public void The_name_follows_the_label_into_another_language()
{
var label = new TextBlock { Text = "Data" };
var picker = new DatePicker();
_ = new DockPanel { Children = { label, picker } };
ScreenReaderNames.NameByLabel(picker);
ScreenReaderNames.NameByLabel(picker);
label.Text = "Date";
Assert.Equal("Date", AutomationProperties.GetName(picker));
}
[Fact]
public void A_name_given_on_purpose_beats_the_label()
{
var label = new TextBlock { Text = "Szukaj" };
var box = new TextBox();
AutomationProperties.SetName(box, "Szukaj pojazdów");
_ = new StackPanel { Children = { label, box } };
ScreenReaderNames.NameByLabel(box);
Assert.Equal("Szukaj pojazdów", AutomationProperties.GetName(box));
}
}

View File

@@ -0,0 +1,27 @@
using Avalonia;
using Avalonia.Headless;
namespace StarterNG.Tests;
/// <summary>
/// Text and drawing for tests of controls that draw themselves: the headless platform
/// with its stand-in fonts, set up once, on the thread the control tests run on.
/// </summary>
public static class HeadlessDrawing
{
private static readonly object Gate = new();
private static bool _ready;
public static void Ensure()
{
lock (Gate)
{
if (_ready)
return;
AppBuilder.Configure<Avalonia.Application>()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = true })
.SetupWithoutStarting();
_ready = true;
}
}
}

View File

@@ -0,0 +1,105 @@
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.VisualTree;
using StarterNG.Application;
using StarterNG.Classes;
using StarterNG.Controls;
using StarterNG.Tests.Fakes;
using StarterNG.Views;
namespace StarterNG.Tests;
/// <summary>The key bindings as someone at the keyboard binds a key: the list of commands, and the keyboard drawn beside it walked with the arrows.</summary>
[Collection(AvaloniaControls.Name)]
public class KeyBindingsTabTests
{
static KeyBindingsTabTests()
{
if (AppServices.CurrentOrNull is null)
{
var installation = new TestInstallation(new InMemoryFileSystem());
AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
}
}
private sealed record Shown(Window Window, KeyBindingsTab Tab, Grid Host, Announcer Announcer) : IDisposable
{
public List<Border> Caps() =>
Host.GetVisualDescendants().OfType<Border>().Where(b => b.Classes.Contains("KeyCap")).ToList();
public void Dispose() => Window.Close();
}
private static Shown Open()
{
KeyboardConfig.Instance.Parse("hornhighactivate a\nhornlowactivate none\n");
var host = new Grid();
var search = new TextBox();
var tab = new KeyBindingsTab(host, search);
var announcer = new Announcer { Child = new DockPanel { Children = { search, host } } };
var window = Controls.Show(announcer, 1600, 1000, themed: true);
window.AddHandler(InputElement.KeyDownEvent, tab.OnKeyDown, Avalonia.Interactivity.RoutingStrategies.Tunnel);
tab.Build();
window.UpdateLayout();
Controls.Settle();
return new Shown(window, tab, host, announcer);
}
[Fact]
public void The_arrows_walk_the_keys_as_they_lie()
{
using var shown = Open();
var caps = shown.Caps();
Assert.True(caps.Count > 50);
Assert.All(caps, c => Assert.False(string.IsNullOrEmpty(AutomationProperties.GetName(c))));
caps[0].Focus();
Assert.True(Controls.Press(caps[0], Key.Right));
Assert.True(caps[1].IsFocused);
Assert.True(Controls.Press(caps[1], Key.Left));
Assert.True(caps[0].IsFocused);
Assert.True(Controls.Press(caps[0], Key.Left));
Assert.True(caps[0].IsFocused);
Assert.True(Controls.Press(caps[0], Key.End));
Assert.True(caps[^1].IsFocused);
Assert.True(Controls.Press(caps[^1], Key.Right));
Assert.True(caps[^1].IsFocused);
Assert.True(Controls.Press(caps[^1], Key.Home));
Assert.True(caps[0].IsFocused);
Assert.True(Controls.Press(caps[0], Key.Down));
var below = caps.Single(c => c.IsFocused);
Assert.NotSame(caps[0], below);
Assert.True(Controls.Press(below, Key.Up));
var above = caps.Single(c => c.IsFocused);
Assert.NotSame(below, above);
Assert.True(Controls.Press(above, Key.Up));
Assert.True(above.IsFocused);
Assert.False(Controls.Press(caps[0], Key.F24));
}
[Fact]
public void A_binding_takes_the_next_key_pressed_and_esc_gives_up_waiting()
{
using var shown = Open();
Assert.True(shown.Tab.ShownCount >= 2);
var combos = shown.Host.GetVisualDescendants().OfType<Button>()
.Where(b => b.Classes.Contains("Flat") && b.MinWidth == 140).ToList();
Assert.NotEmpty(combos);
combos[0].RaiseEvent(Controls.Click());
Assert.True(shown.Tab.IsCapturing);
Assert.True(Controls.Press(combos[0], Key.Escape));
Assert.False(shown.Tab.IsCapturing);
combos[0].RaiseEvent(Controls.Click());
Assert.False(Controls.Press(combos[0], Key.LeftShift));
Assert.True(shown.Tab.IsCapturing);
Assert.True(Controls.Press(combos[0], Key.J, KeyModifiers.Control | KeyModifiers.Shift));
Assert.False(shown.Tab.IsCapturing);
Assert.True(KeyboardConfig.Instance.Dirty);
}
}

View File

@@ -0,0 +1,40 @@
using Avalonia.Controls;
using Avalonia.Input;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
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));
}
}

View File

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

View File

@@ -0,0 +1,102 @@
using Avalonia.Automation;
using Avalonia.Controls;
using StarterNG.Controls;
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class MouseReadingTests
{
static MouseReadingTests() => ScreenReaderNames.Install();
[Fact]
public void A_picture_on_a_button_is_read_as_the_button()
{
var logo = new Image();
var button = new Button { Content = logo };
ScreenReaderNames.NamePicture(logo);
Assert.Same(button, AutomationProperties.GetLabeledBy(logo));
}
[Fact]
public void A_picture_beside_a_caption_is_read_as_the_caption()
{
var mini = new Image();
var caption = new TextBlock { Text = "EU07" };
_ = new StackPanel { Children = { mini, new TextBlock { IsVisible = false, Text = "ukryte" }, caption } };
ScreenReaderNames.NamePicture(mini);
Assert.Same(caption, AutomationProperties.GetLabeledBy(mini));
}
[Fact]
public void A_picture_in_a_card_is_read_as_the_card_tooltip()
{
var mini = new Image();
var card = new Border { Child = new Panel { Children = { mini } } };
ToolTip.SetTip(card, "EP09-018");
ScreenReaderNames.NamePicture(mini);
Assert.Equal("EP09-018", AutomationProperties.GetName(mini));
}
[Fact]
public void A_picture_named_on_purpose_or_far_from_any_name_is_left_alone()
{
var named = new Image();
AutomationProperties.SetName(named, "Obraz scenerii: baltyk");
var far = new Image();
var outer = new Border { Child = new Border { Child = new Border { Child = new Border { Child = far } } } };
ToolTip.SetTip(outer, "Opis");
_ = new Button { Content = named };
ScreenReaderNames.NamePicture(named);
ScreenReaderNames.NamePicture(far);
Assert.Equal("Obraz scenerii: baltyk", AutomationProperties.GetName(named));
Assert.Null(AutomationProperties.GetLabeledBy(named));
Assert.Null(AutomationProperties.GetName(far));
}
[Fact]
public void A_list_entry_is_read_as_its_text()
{
var named = new ComboBoxItem { Content = "Lato" };
AutomationProperties.SetName(named, "Pora: lato");
Assert.Equal("Pogodnie", ScreenReaderNames.SpokenItem(new ComboBoxItem { Content = "Pogodnie" }));
Assert.Equal("Pora: lato", ScreenReaderNames.SpokenItem(named));
Assert.Equal("12", ScreenReaderNames.SpokenItem(12));
Assert.Null(ScreenReaderNames.SpokenItem(null));
}
[Fact]
public void A_list_not_in_focus_says_nothing_of_its_new_choice()
{
var combo = new ComboBox();
var announcer = new Announcer();
announcer.Child = combo;
ScreenReaderNames.TellChoice(combo);
Assert.Null(announcer.Message);
}
[Fact]
public void A_figure_says_its_label_and_its_value_together()
{
var host = new StackPanel();
StatsBar.Fill(host, new[] { ("Masa [t]:", "440"), ("Tor:", "tor0325") });
var figure = Assert.IsType<TextBlock>(host.Children[0]);
Assert.Equal("Masa [t]: 440", figure.Inlines!.Text);
Assert.Equal(22, figure.Margin.Right);
Assert.Equal(0, ((TextBlock)host.Children[1]).Margin.Right);
}
}

View File

@@ -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()
{

View File

@@ -65,6 +65,32 @@ 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()
{
// As in the game: cd/9-107_v1 holds 9-107.13.fiz, 9-107.6.fiz and more.
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Fiz("cd", "9-107_v1", "9-107.13"), "Load: LoadAccepted=coal MaxLoad=58")
.WithFile(Fiz("cd", "9-107_v1", "9-107.6"), "Load: LoadAccepted=coal MaxLoad=55"));
Assert.Equal(58, installation.Physics.For("cd/9-107_v1/", "9-107.13")!.MaxLoad);
Assert.Equal(55, installation.Physics.For("cd/9-107_v1/", "9-107.6")!.MaxLoad);
Assert.Equal(58, installation.Physics.For("cd/9-107_v1/", "9-107.13.e3d")!.MaxLoad);
}
[Fact]
public void A_dumb_variant_stands_in_when_the_model_has_no_fiz_of_its_own()
{
@@ -189,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));
}
}

View File

@@ -0,0 +1,76 @@
using System.Globalization;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class ReadableSliderTests
{
[Fact]
public void The_track_under_the_mouse_says_the_name_and_the_value()
{
var fog = new ReadableSlider { ValueText = "2,4 km" };
Assert.Equal("2,4 km", fog.TrackText);
AutomationProperties.SetName(fog, "Widoczność ");
Assert.Equal("Widoczność: 2,4 km", fog.TrackText);
}
[Fact]
public void A_slider_is_read_as_the_value_shown_beside_it()
{
var fog = new ReadableSlider { Minimum = 0, Maximum = 1000, Value = 523, ValueText = " 2,4 km " };
Assert.Equal("2,4 km", fog.SpokenValue);
}
[Fact]
public void Without_a_shown_value_the_number_itself_is_read()
{
var before = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("pl-PL");
try
{
Assert.Equal("-5", ReadableSlider.SpokenText(null, -5));
Assert.Equal("1,25", ReadableSlider.SpokenText(" ", 1.25));
}
finally
{
CultureInfo.CurrentCulture = before;
}
}
[Fact]
public void A_setting_row_gives_its_value_to_the_slider_in_it()
{
var slider = new ReadableSlider { Minimum = 0, Maximum = 100, Value = 40 };
var row = new SettingRow { Content = new Border { Child = slider } };
row.ValueText = "40%";
Assert.Equal("40%", slider.SpokenValue);
row.ValueText = null;
Assert.Equal("40", slider.SpokenValue);
}
[Fact]
public void A_screen_reader_is_given_the_text_and_may_set_a_number()
{
var slider = new ReadableSlider { Minimum = 0, Maximum = 1000, Value = 523, ValueText = "2 km" };
var peer = ControlAutomationPeer.CreatePeerForElement(slider);
var value = Assert.IsAssignableFrom<IValueProvider>(peer);
Assert.Equal(AutomationControlType.Slider, peer.GetAutomationControlType());
Assert.Equal("Slider", peer.GetClassName());
Assert.Equal("2 km", value.Value);
Assert.False(value.IsReadOnly);
value.SetValue("300");
Assert.Equal(300, slider.Value);
Assert.Throws<ArgumentException>(() => value.SetValue("dużo"));
}
}

View File

@@ -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()
{
@@ -195,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 }));
}

View File

@@ -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()
{

View File

@@ -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")!;

View File

@@ -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()
{

View File

@@ -0,0 +1,229 @@
using System.Globalization;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
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 = "Pomoc";
Assert.Null(AutomationProperties.GetName(button));
}
[Fact]
public void A_button_with_only_a_sign_on_it_is_named_by_its_tooltip()
{
var button = new Button { Content = "?" };
ToolTip.SetTip(button, "Pomoc");
Assert.Equal("Pomoc", 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_describes_its_inputs_with_its_explanation()
{
var check = new CheckBox { Content = "Tryb pełnoekranowy" };
var slider = new Slider();
var row = new SettingRow { Label = "Ekran", Content = Row(check, slider) };
row.Description = "Gra zajmie cały ekran.";
row.IdleNote = "Ten symulator nie zna tego ustawienia.";
Assert.Equal("Gra zajmie cały ekran., Ten symulator nie zna tego ustawienia.", AutomationProperties.GetHelpText(check));
Assert.Equal(AutomationProperties.GetHelpText(check), AutomationProperties.GetHelpText(slider));
Assert.Null(AutomationProperties.GetName(check));
row.Description = null;
row.IdleNote = null;
Assert.Null(AutomationProperties.GetHelpText(check));
}
[Fact]
public void A_description_given_on_purpose_is_left_alone()
{
var box = new TextBox();
AutomationProperties.SetHelpText(box, "Ścieżka do exe");
_ = new SettingRow { Content = box, Description = "Plik symulatora" };
Assert.Equal("Ścieżka do exe", AutomationProperties.GetHelpText(box));
}
[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));
}
}
[Collection(AvaloniaControls.Name)]
public class PickerNameTests
{
[Fact]
public void A_picker_is_read_as_its_label_and_its_value()
{
Assert.Equal("Godzina: 07:05", ScreenReaderNames.PickerText("Godzina", "07:05"));
Assert.Equal("Data", ScreenReaderNames.PickerText("Data", null));
Assert.Equal("07:05", ScreenReaderNames.PickerText(null, "07:05"));
Assert.Null(ScreenReaderNames.PickerText("", null));
}
[Fact]
public void A_date_is_read_in_words_with_the_year_only_when_shown()
{
var before = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("pl-PL");
try
{
var date = new DateTimeOffset(2026, 10, 27, 0, 0, 0, TimeSpan.FromHours(1));
Assert.Equal("27 października", ScreenReaderNames.DateText(date, withYear: false));
Assert.Equal("wtorek, 27 października 2026", ScreenReaderNames.DateText(date, withYear: true));
Assert.Null(ScreenReaderNames.DateText(null, withYear: false));
}
finally
{
CultureInfo.CurrentCulture = before;
}
}
[Fact]
public void A_time_is_read_as_hours_and_minutes()
{
Assert.Equal("07:05", ScreenReaderNames.TimeText(new TimeSpan(7, 5, 30)));
Assert.Null(ScreenReaderNames.TimeText(null));
}
}

View File

@@ -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<string>()));
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<Avalonia.Application>();
Assert.Same(builder, SoftwareRender.ApplyTo(builder));
}
}

View File

@@ -8,6 +8,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="12.1.4" />
<PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />

View File

@@ -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<string, bool> beside, Dictionary<string, IntPtr> 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<string, bool> beside) =>
Take(beside, new Dictionary<string, IntPtr> { ["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<string>();
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));
}
}

View File

@@ -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())

View File

@@ -0,0 +1,175 @@
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Input;
using StarterNG.Application;
using StarterNG.Domain.Tapes;
using StarterNG.Tests.Fakes;
using StarterNG.Views.Tapes;
namespace StarterNG.Tests;
/// <summary>A recorded trip walked from the keyboard and read by a screen reader, on both ways of drawing it.</summary>
[Collection(AvaloniaControls.Name)]
public class TapeViewTests
{
// The electronic tape writes its legend in the starter's language.
static TapeViewTests()
{
if (AppServices.CurrentOrNull is null)
{
var installation = new TestInstallation(new InMemoryFileSystem());
AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
}
}
public static TheoryData<string> Views => new() { "hasler", "electronic" };
private static TapeView View(string kind) => kind == "hasler" ? new HaslerTapeView() : new ElectronicTapeView();
/// <summary>Two minutes, a sample a second, 15 m a second; running from 10 s to 110 s, braking after 100 s.</summary>
private static HaslerTape Trip() =>
new(Enumerable.Range(0, 121)
.Select(i => new TapeSample(i, i is > 10 and < 110 ? 54 : 0, i * 15.0, i > 100 ? 2 : 0, 5,
i < 50 ? 300 : 0, i == 70))
.ToList());
private static (TapeView View, List<TapeSample?> Hovered) Walking(string kind, bool byDistance = true)
{
var view = View(kind);
view.Tape = Trip();
view.ByDistance = byDistance;
var hovered = new List<TapeSample?>();
view.Hovered += s => hovered.Add(s);
return (view, hovered);
}
[Theory]
[MemberData(nameof(Views))]
public void The_trip_is_a_slider_read_as_the_moment_under_the_cursor(string kind)
{
var view = View(kind);
var peer = Controls.Peer(view);
var value = Assert.IsAssignableFrom<IValueProvider>(peer);
view.Spoken = "10:00:12, km 0,2, 54 km/h";
Assert.Equal(AutomationControlType.Slider, peer.GetAutomationControlType());
Assert.True(peer.IsContentElement());
Assert.True(peer.IsControlElement());
Assert.Equal("10:00:12, km 0,2, 54 km/h", value.Value);
Assert.True(value.IsReadOnly);
Assert.Throws<InvalidOperationException>(() => value.SetValue("x"));
view.Spoken = "10:00:13, km 0,2, 54 km/h";
Assert.Equal("10:00:13, km 0,2, 54 km/h", value.Value);
}
[Theory]
[MemberData(nameof(Views))]
public void The_first_arrow_starts_at_the_beginning_and_the_next_go_a_hundred_metres(string kind)
{
var (view, hovered) = Walking(kind);
Assert.True(Controls.Press(view, Key.Right));
Assert.Equal(0, hovered[^1]!.Value.Time);
Assert.True(Controls.Press(view, Key.Right));
Assert.InRange(hovered[^1]!.Value.DistanceM, TapeView.DistanceStep - 15, TapeView.DistanceStep + 15);
Assert.True(Controls.Press(view, Key.Right, KeyModifiers.Control));
Assert.True(hovered[^1]!.Value.DistanceM >= TapeView.DistanceStep * TapeView.CtrlTimes - 15);
Assert.True(Controls.Press(view, Key.Left, KeyModifiers.Control));
Assert.True(hovered[^1]!.Value.DistanceM <= TapeView.DistanceStep + 15);
Assert.True(Controls.Press(view, Key.End));
Assert.Equal(120, hovered[^1]!.Value.Time);
Assert.True(Controls.Press(view, Key.Right));
Assert.Equal(120, hovered[^1]!.Value.Time);
Assert.True(Controls.Press(view, Key.Home));
Assert.Equal(0, hovered[^1]!.Value.Time);
Assert.True(Controls.Press(view, Key.Left));
Assert.Equal(0, hovered[^1]!.Value.Time);
}
[Theory]
[MemberData(nameof(Views))]
public void By_time_an_arrow_goes_ten_seconds(string kind)
{
var (view, hovered) = Walking(kind, byDistance: false);
Controls.Press(view, Key.Left);
Assert.Equal(0, hovered[^1]!.Value.Time);
Controls.Press(view, Key.Right);
Assert.Equal(TapeView.TimeStep, hovered[^1]!.Value.Time);
Controls.Press(view, Key.Left);
Assert.Equal(0, hovered[^1]!.Value.Time);
}
[Theory]
[MemberData(nameof(Views))]
public void Enter_picks_the_sample_the_keys_stand_at_once_they_have_moved(string kind)
{
var (view, _) = Walking(kind);
TapeSample? picked = null;
view.Picked += s => picked = s;
Assert.False(Controls.Press(view, Key.Enter));
Assert.Null(picked);
Controls.Press(view, Key.End);
Assert.True(Controls.Press(view, Key.Enter));
Assert.Equal(120, picked!.Value.Time);
}
[Theory]
[MemberData(nameof(Views))]
public void A_new_trip_starts_the_keys_from_its_beginning(string kind)
{
var (view, hovered) = Walking(kind);
Controls.Press(view, Key.End);
view.Tape = Trip();
Controls.Press(view, Key.Right);
Assert.Equal(0, hovered[^1]!.Value.Time);
}
[Theory]
[MemberData(nameof(Views))]
public void Other_keys_and_an_empty_trip_are_left_alone(string kind)
{
var (view, hovered) = Walking(kind);
var empty = View(kind);
var blank = View(kind);
blank.Tape = new HaslerTape([]);
Assert.False(Controls.Press(view, Key.A));
Assert.False(Controls.Press(empty, Key.Right));
Assert.False(Controls.Press(blank, Key.Right));
Assert.Empty(hovered);
}
[Theory]
[MemberData(nameof(Views))]
public void The_trip_draws_with_and_without_the_focus(string kind)
{
var (view, _) = Walking(kind);
view.Mark = 60;
var window = Controls.Show(view, 1200, 600);
try
{
Assert.True(view.Focusable);
view.Focus();
Controls.Press(view, Key.Right);
Controls.Settle();
window.Focus();
Controls.Settle();
}
finally
{
window.Close();
}
}
}

View File

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

View File

@@ -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,10 @@ 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();
DialogKeyboard.Install();
AvaloniaXamlLoader.Load(this);
AppServices.Current.SettingsStore.Load();
@@ -202,8 +207,12 @@ public partial class App : Avalonia.Application
if (check.ExecutableMissing())
await main.OfferExecutablePickAsync();
if (CpuFeatures.LacksAvx2 && AppServices.Current.Settings.CpuNotice)
await main.ShowCpuNoticeAsync();
// A build without AVX2 in the folder is started instead, and needs no notice.
var services = AppServices.Current;
if (services.Settings.CpuNotice
&& services.Executables.Resolve(services.Settings, out _) is var executable
&& services.Executables.WillNotRunHere(executable))
await main.ShowCpuNoticeAsync(executable);
});
});
}

View File

@@ -13,6 +13,6 @@ public static class AppInfo
#if DEBUG
text += " (DEBUG)";
#endif
return text + " public beta";
return text;
}
}

View File

@@ -7,6 +7,9 @@ namespace StarterNG.Application.Abstractions;
public interface IFileSystem
{
/// <summary>Whether a name finds its file whatever the case of its letters, as on Windows and macOS.</summary>
bool IgnoresCase { get; }
bool FileExists(string path);
bool DirectoryExists(string path);

View File

@@ -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();
@@ -80,6 +81,9 @@ public sealed class AppServices
_current ?? throw new InvalidOperationException(
"AppServices.Current read before Initialize(); the composition root must be built first.");
/// <summary>The services once built, or null before: for what may run either way, such as a control in a test.</summary>
public static AppServices? CurrentOrNull => _current;
public static AppServices Initialize(IGamePaths? paths = null, IFileSystem? files = null, IClock? clock = null,
IEnvironment? environment = null)
{
@@ -119,6 +123,8 @@ public sealed class AppServices
public TimetableLocator Timetables { get; }
public AttachmentLocator Attachments { get; }
public LoadWeightsRepository LoadWeights { get; }
public GameLibrary Library { get; }

View File

@@ -0,0 +1,89 @@
using System;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.VisualTree;
namespace StarterNG.Controls;
/// <summary>
/// Says what a click changed out of sight, such as a quality level that moved a dozen
/// sliders or a time set to now. It wraps the whole window: a screen reader learns of
/// an element only on its way to the focused one, and this lies on every such way.
/// A text marked <see cref="ChangesProperty"/> is read whenever it changes.
/// </summary>
public class Announcer : Decorator
{
/// <summary>How long a message stays its name, so it is not read again later on.</summary>
public static readonly TimeSpan Shown = TimeSpan.FromSeconds(3);
public static readonly AttachedProperty<bool> ChangesProperty =
AvaloniaProperty.RegisterAttached<Announcer, TextBlock, bool>("Changes");
public static bool GetChanges(TextBlock block) => block.GetValue(ChangesProperty);
public static void SetChanges(TextBlock block, bool value) => block.SetValue(ChangesProperty, value);
static Announcer()
{
TextBlock.TextProperty.Changed.AddClassHandler<TextBlock>((block, _) =>
{
if (GetChanges(block))
Say(block, block.Text);
});
}
private readonly Func<DateTime> _now;
private string? _message;
private DateTime _saidAt;
public Announcer() : this(() => DateTime.UtcNow)
{
}
public Announcer(Func<DateTime> now) => _now = now;
/// <summary>The message while it is fresh, then nothing.</summary>
public string? Message => _message is not null && _now() - _saidAt < Shown ? _message : null;
/// <summary>Says the text through the announcer of the window <paramref name="from"/> is in.</summary>
public static void Say(Visual from, string? text)
{
var announcer = from as Announcer ?? from.FindAncestorOfType<Announcer>();
announcer?.Say(text);
}
public void Say(string? text)
{
if (string.IsNullOrWhiteSpace(text))
return;
string? before = Message;
_message = text.Trim();
_saidAt = _now();
// Its name changing is what makes a live region speak.
if (ControlAutomationPeer.CreatePeerForElement(this) is Peer peer)
peer.Told(before, _message);
}
protected override AutomationPeer OnCreateAutomationPeer() => new Peer(this);
private sealed class Peer : ControlAutomationPeer
{
public Peer(Announcer owner) : base(owner)
{
}
private Announcer Announcer => (Announcer)Owner;
public void Told(string? before, string now) =>
RaisePropertyChangedEvent(AutomationElementIdentifiers.NameProperty, before, now);
protected override string? GetNameCore() => Announcer.Message;
protected override AutomationLiveSetting GetLiveSettingCore() => AutomationLiveSetting.Polite;
protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Group;
}
}

View File

@@ -0,0 +1,28 @@
using System;
using StarterNG.Application;
namespace StarterNG.Controls;
/// <summary>
/// The starter's texts as the controls here read them: in its language once the
/// application is built, the key itself before that, as in a test.
/// </summary>
internal static class AppLanguage
{
public static string Text(string key) => AppServices.CurrentOrNull?.Localization[key] ?? key;
/// <summary>Raised when the language is changed; nothing is raised before the application is built.</summary>
public static event Action? Changed
{
add
{
if (AppServices.CurrentOrNull?.Localization is { } loc)
loc.LanguageChanged += value;
}
remove
{
if (AppServices.CurrentOrNull?.Localization is { } loc)
loc.LanguageChanged -= value;
}
}
}

View File

@@ -0,0 +1,77 @@
using System.Linq;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace StarterNG.Controls;
/// <summary>
/// What every window opened over another does for someone at the keyboard, as a dialog
/// of Windows does: it opens with focus on its default button or else its first
/// control, where it opened with nothing focused and a screen reader said only its
/// title; Esc closes it; Tab with nothing focused starts from the first control.
/// </summary>
public static class DialogKeyboard
{
/// <summary>False for a window that stays open beside the main one, such as the tapes: Esc there is not a way out.</summary>
public static readonly Avalonia.AttachedProperty<bool> EscapeClosesProperty =
Avalonia.AvaloniaProperty.RegisterAttached<Window, bool>("EscapeCloses", typeof(DialogKeyboard), defaultValue: true);
public static bool GetEscapeCloses(Window window) => window.GetValue(EscapeClosesProperty);
public static void SetEscapeCloses(Window window, bool value) => window.SetValue(EscapeClosesProperty, value);
public static void Install() =>
Window.WindowOpenedEvent.AddClassHandler<Window>((window, _) => OnOpened(window));
private static void OnOpened(Window window)
{
// The main window and the splash have no owner, and their own ways.
if (window.Owner is null)
return;
window.AddHandler(InputElement.KeyDownEvent, (_, e) => OnTab(window, e), RoutingStrategies.Tunnel);
window.AddHandler(InputElement.KeyDownEvent, (_, e) => OnEscape(window, e));
Dispatcher.UIThread.Post(() => FocusFirst(window), DispatcherPriority.Loaded);
}
// Bubbling and only when nothing took it: a list closing its drop-down, a cancel
// button or a window of its own that handles the key keep it.
private static void OnEscape(Window window, KeyEventArgs e)
{
if (e.Handled || e.Key != Key.Escape || e.KeyModifiers != KeyModifiers.None || !GetEscapeCloses(window))
return;
window.Close();
e.Handled = true;
}
private static void OnTab(Window window, KeyEventArgs e)
{
if (window.FocusManager is not { } focus)
return;
var next = KeyboardFocus.TabFromNowhere(e.Key, e.KeyModifiers, focus.GetFocusedElement(), window,
focus.FindFirstFocusableElement, focus.FindLastFocusableElement);
if (next is not null && next.Focus(NavigationMethod.Tab))
e.Handled = true;
}
/// <summary>Focus on the default button, or the first control when there is none; left alone when the window placed it itself.</summary>
public static void FocusFirst(Window window)
{
if (window.FocusManager is not { } focus)
return;
var focused = focus.GetFocusedElement();
if (focused is not null && !ReferenceEquals(focused, window))
return;
IInputElement? target = window.GetVisualDescendants().OfType<Button>()
.FirstOrDefault(b => b.IsDefault && b.IsEffectivelyVisible && b.IsEffectivelyEnabled)
?? focus.FindFirstFocusableElement();
target?.Focus(NavigationMethod.Tab);
}
}

View File

@@ -0,0 +1,157 @@
using System;
using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Avalonia.VisualTree;
using StarterNG.Application;
namespace StarterNG.Controls;
/// <summary>
/// A tree entry that tells a screen reader whether it opens and what lies under it.
/// Avalonia's own says only that it is an entry, and hangs the entries under a group
/// on the panel inside the group, so a reader heard every scenery at level one: a
/// group such as Całkowo sounded like a scenery, and what was in it like its neighbours.
/// Under the mouse a reader hears only what lies there, the name in the row; the row
/// is told the state as well, so the mouse also hears that an entry opens.
/// </summary>
public class ExpandableTreeViewItem : TreeViewItem
{
protected override Type StyleKeyOverride => typeof(TreeViewItem);
protected override AutomationPeer OnCreateAutomationPeer() => new Peer(this);
/// <summary>The words for an open and a closed entry, in the starter's language.</summary>
public static Func<ExpandCollapseState, string?> StateWords { get; set; } = DefaultStateWords;
private static string? DefaultStateWords(ExpandCollapseState state) =>
AppServices.Current?.Localization is { } loc
? WordFor(state, key => loc[key])
: null;
public static string? WordFor(ExpandCollapseState state, Func<string, string> loc) => state switch
{
ExpandCollapseState.Expanded => loc("TreeExpanded"),
ExpandCollapseState.Collapsed => loc("TreeCollapsed"),
_ => null,
};
private Control? _row;
private string? _rowName;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_row = e.NameScope.Find<Control>("PART_LayoutRoot");
// A part of a template is passed over when Windows looks for what lies under the
// mouse, so the gaps beside the arrow and the name led to the entry, which told no
// state. As a control the row itself is found there.
if (_row is not null)
AutomationProperties.SetAccessibilityView(_row, AccessibilityView.Control);
TellRowLater();
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
if (AppServices.Current?.Localization is { } loc)
loc.LanguageChanged += TellRowLater;
TellRow();
}
protected override void OnUnloaded(RoutedEventArgs e)
{
base.OnUnloaded(e);
if (AppServices.Current?.Localization is { } loc)
loc.LanguageChanged -= TellRowLater;
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == IsExpandedProperty || change.Property == ItemCountProperty
|| change.Property == AutomationProperties.NameProperty)
TellRow();
else if (change.Property == HeaderProperty)
TellRowLater();
}
// A new header is laid out only after it is set.
private void TellRowLater() => Dispatcher.UIThread.Post(TellRow, DispatcherPriority.Loaded);
/// <summary>
/// Gives whatever the mouse may point at in the row the entry's state, and its name
/// where it shows no text of its own, such as the arrow or an icon.
/// </summary>
private void TellRow()
{
if (_row is null)
return;
string? state = StateWords(ExpandState);
string? name = AutomationProperties.GetName(this);
foreach (var part in _row.GetVisualDescendants().OfType<Control>().Prepend(_row))
{
if (string.IsNullOrEmpty(state))
part.ClearValue(AutomationProperties.HelpTextProperty);
else
AutomationProperties.SetHelpText(part, state);
if (part is TextBlock)
continue;
string? had = AutomationProperties.GetName(part);
if (string.IsNullOrEmpty(had) || had == _rowName)
AutomationProperties.SetName(part, name);
}
_rowName = name;
}
/// <summary>What a screen reader is told: a leaf, or open or closed.</summary>
public ExpandCollapseState ExpandState => StateFor(ItemCount > 0, IsExpanded);
public static ExpandCollapseState StateFor(bool hasChildren, bool expanded) => (hasChildren, expanded) switch
{
(false, _) => ExpandCollapseState.LeafNode,
(true, true) => ExpandCollapseState.Expanded,
(true, false) => ExpandCollapseState.Collapsed
};
/// <summary>The entry this one hangs under, or null at the top of the tree.</summary>
public ExpandableTreeViewItem? ReadableParent => ItemsControlFromItemContainer(this) as ExpandableTreeViewItem;
private sealed class Peer : TreeViewItemAutomationPeer, IExpandCollapseProvider
{
private readonly ExpandableTreeViewItem _item;
public Peer(ExpandableTreeViewItem item) : base(item)
{
_item = item;
item.PropertyChanged += (_, e) =>
{
if (e.Property == IsExpandedProperty && e.OldValue is bool was && e.NewValue is bool now)
RaisePropertyChangedEvent(ExpandCollapsePatternIdentifiers.ExpandCollapseStateProperty,
StateFor(item.ItemCount > 0, was), StateFor(item.ItemCount > 0, now));
};
}
// Only the way up changes: a reader counts the entries over this one to tell its
// level. The way down stays the controls on screen, so whatever the mouse points
// at still leads up through its entry to the window.
protected override AutomationPeer? GetParentCore() =>
_item.ReadableParent is { } parent ? GetOrCreate(parent) : base.GetParentCore();
public ExpandCollapseState ExpandCollapseState => _item.ExpandState;
public bool ShowsMenu => false;
public void Expand() => _item.IsExpanded = true;
public void Collapse() => _item.IsExpanded = false;
}
}

View File

@@ -0,0 +1,24 @@
using System;
using Avalonia.Input;
namespace StarterNG.Controls;
public static class KeyboardFocus
{
/// <summary>
/// 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.
/// </summary>
public static IInputElement? TabFromNowhere(Key key, KeyModifiers modifiers, IInputElement? focused,
IInputElement window, Func<IInputElement?> first,
Func<IInputElement?> last)
{
if (key != Key.Tab || focused is not null && !ReferenceEquals(focused, window))
return null;
return modifiers.HasFlag(KeyModifiers.Shift) ? last() : first();
}
}

View File

@@ -0,0 +1,108 @@
using System;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
namespace StarterNG.Controls;
/// <summary>
/// A slider that tells a screen reader the value it shows beside it. Avalonia's own
/// gives only the bare number, which NVDA reads as a share of the slider's length:
/// -5 °C was read as 45, a fog of 2 km as wherever the knob stood on its scale.
/// The track under the mouse says the same, where its bare buttons and knob said nothing.
/// </summary>
public class ReadableSlider : Slider
{
public static readonly StyledProperty<string?> ValueTextProperty =
AvaloniaProperty.Register<ReadableSlider, string?>(nameof(ValueText));
/// <summary>The value as written for the reader, such as "2,4 km"; the number when unset.</summary>
public string? ValueText
{
get => GetValue(ValueTextProperty);
set => SetValue(ValueTextProperty, value);
}
protected override Type StyleKeyOverride => typeof(Slider);
protected override AutomationPeer OnCreateAutomationPeer() => new Peer(this);
/// <summary>What a screen reader is told the slider holds.</summary>
public string SpokenValue => SpokenText(ValueText, Value);
public static string SpokenText(string? valueText, double value) =>
string.IsNullOrWhiteSpace(valueText)
? value.ToString("0.##", CultureInfo.CurrentCulture)
: valueText.Trim();
/// <summary>What the mouse finds over the track: the slider's name and its value.</summary>
public string TrackText =>
AutomationProperties.GetName(this) is { } name && !string.IsNullOrWhiteSpace(name)
? $"{name.Trim()}: {SpokenValue}"
: SpokenValue;
private Track? _track;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_track = e.NameScope.Find<Track>("PART_Track");
NameTrack();
}
// The knob gets its own template only when first laid out.
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
NameTrack();
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == ValueProperty || change.Property == ValueTextProperty
|| change.Property == AutomationProperties.NameProperty)
NameTrack();
}
private void NameTrack()
{
if (_track is null)
return;
string text = TrackText;
foreach (var part in _track.GetVisualDescendants().OfType<Control>().Prepend(_track))
AutomationProperties.SetName(part, text);
}
private sealed class Peer : RangeBaseAutomationPeer, IValueProvider
{
private readonly ReadableSlider _slider;
// A moved knob is told by the range peer already; the reader then asks for this
// text, set by then. Telling the text's change too would have it spoken twice.
public Peer(ReadableSlider slider) : base(slider) => _slider = slider;
protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Slider;
protected override string GetClassNameCore() => "Slider";
string? IValueProvider.Value => _slider.SpokenValue;
bool IValueProvider.IsReadOnly => !_slider.IsEnabled;
void IValueProvider.SetValue(string? value)
{
if (!double.TryParse(value, NumberStyles.Float, CultureInfo.CurrentCulture, out double number))
throw new ArgumentException($"Not a number: {value}", nameof(value));
_slider.Value = number;
}
}
}

View File

@@ -0,0 +1,433 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
namespace StarterNG.Controls;
/// <summary>
/// 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.
/// </summary>
public static class ScreenReaderNames
{
// What was given here last, so a later change replaces it but nothing else.
private static readonly ConditionalWeakTable<StyledElement, string> Given = new();
public static void Install()
{
ContentControl.ContentProperty.Changed.AddClassHandler<Button>((b, _) => NameButton(b));
ToolTip.TipProperty.Changed.AddClassHandler<Button>((b, _) => NameButton(b));
ContentControl.ContentProperty.Changed.AddClassHandler<ListBoxItem>((i, _) => Give(i, TextOf(i.Content)));
HeaderedItemsControl.HeaderProperty.Changed.AddClassHandler<TreeViewItem>((i, _) => Give(i, TextOf(i.Header)));
HeaderedContentControl.HeaderProperty.Changed.AddClassHandler<HeaderedContentControl>((c, _) => NameGroup(c));
ComboBox.PlaceholderTextProperty.Changed.AddClassHandler<ComboBox>((c, _) => Give(c, c.PlaceholderText));
TextBox.PlaceholderTextProperty.Changed.AddClassHandler<TextBox>((t, _) => Give(t, t.PlaceholderText));
SelectingItemsControl.SelectionChangedEvent.AddClassHandler<ComboBox>((c, _) => TellChoice(c));
Control.LoadedEvent.AddClassHandler<ComboBox>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<TextBox>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<Slider>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<NumericUpDown>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<DatePicker>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<TimePicker>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<Image>((i, _) => NamePicture(i));
Control.LoadedEvent.AddClassHandler<PathIcon>((i, _) => NamePicture(i));
TemplatedControl.TemplateAppliedEvent.AddClassHandler<DatePicker>((p, e) => KeepPickerButton(p, e));
TemplatedControl.TemplateAppliedEvent.AddClassHandler<TimePicker>((p, e) => KeepPickerButton(p, e));
DatePicker.SelectedDateProperty.Changed.AddClassHandler<DatePicker>((p, _) => NamePicker(p));
TimePicker.SelectedTimeProperty.Changed.AddClassHandler<TimePicker>((p, _) => NamePicker(p));
AutomationProperties.NameProperty.Changed.AddClassHandler<DatePicker>((p, _) => NamePicker(p));
AutomationProperties.NameProperty.Changed.AddClassHandler<TimePicker>((p, _) => NamePicker(p));
TemplatedControl.TemplateAppliedEvent.AddClassHandler<NumericUpDown>((n, e) => ForwardToTextBox(n, e));
TemplatedControl.TemplateAppliedEvent.AddClassHandler<ButtonSpinner>((s, e) => NameSpinButtons(s, e));
AutomationProperties.NameProperty.Changed.AddClassHandler<Control>((c, e) => TranslateTemplateName(c, e));
AppLanguage.Changed += RetranslateTemplateNames;
}
/// <summary>
/// A number box is reached through the text box inside it, which had no name: the
/// reader heard "edit, 0,1" and not what the number is. It takes the box's name and
/// explanation, and keeps them when they change.
/// </summary>
private static void ForwardToTextBox(NumericUpDown box, TemplateAppliedEventArgs e)
{
if (e.NameScope.Find<TextBox>("PART_TextBox") is not { } text)
return;
text.Bind(AutomationProperties.NameProperty, box.GetObservable(AutomationProperties.NameProperty));
text.Bind(AutomationProperties.HelpTextProperty, box.GetObservable(AutomationProperties.HelpTextProperty));
}
/// <summary>
/// The arrows of a number box were read as "Avalonia.Controls.Shapes.Path" and were two
/// more stops for Tab. They say what they do, and Tab passes them: the arrow keys in the
/// box do the same, as in any spin box of Windows.
/// </summary>
private static void NameSpinButtons(ButtonSpinner spinner, TemplateAppliedEventArgs e)
{
foreach (var (part, key) in new[] { ("PART_IncreaseButton", "SpinUp"), ("PART_DecreaseButton", "SpinDown") })
{
if (e.NameScope.Find<Control>(part) is not { } button)
continue;
KeyboardNavigation.SetIsTabStop(button, false);
TemplateNames.AddOrUpdate(button, key);
AutomationProperties.SetName(button, AppLanguage.Text(key));
}
}
/// <summary>
/// The English names Avalonia's own templates give their parts - the window's buttons,
/// the arrows of a scroll bar - and the texts they are read as instead.
/// </summary>
private static readonly Dictionary<string, string> EnglishTemplateNames = new(StringComparer.Ordinal)
{
["Minimize"] = "ChromeMinimize",
["Maximize"] = "ChromeMaximize",
["Restore"] = "ChromeRestore",
["Close"] = "ChromeClose",
["Line up"] = "ScrollLineUp",
["Line down"] = "ScrollLineDown",
["Page up"] = "ScrollPageUp",
["Page down"] = "ScrollPageDown",
["Column left"] = "ScrollColumnLeft",
["Column right"] = "ScrollColumnRight",
["Page left"] = "ScrollPageLeft",
["Page right"] = "ScrollPageRight",
["Position"] = "ScrollPosition",
};
// The parts given a translated name, with the text they were given it from.
private static readonly ConditionalWeakTable<Control, string> TemplateNames = new();
/// <summary>An English name set by a template is replaced by the same thing in the starter's language.</summary>
private static void TranslateTemplateName(Control control, AvaloniaPropertyChangedEventArgs e)
{
if (e.Priority == Avalonia.Data.BindingPriority.LocalValue || e.NewValue is not string english
|| !EnglishTemplateNames.TryGetValue(english, out string? key)
|| AppLanguage.Text(key) is not { Length: > 0 } text || text == english)
return;
TemplateNames.AddOrUpdate(control, key);
AutomationProperties.SetName(control, text);
}
private static void RetranslateTemplateNames()
{
foreach (var (control, key) in TemplateNames)
AutomationProperties.SetName(control, AppLanguage.Text(key));
}
// A date or time picker is reached through the button inside it, which was read as
// "Avalonia.Controls.Grid": its texts are filled in only after the name is looked for.
private static readonly ConditionalWeakTable<TemplatedControl, Button> PickerButtons = new();
private static void KeepPickerButton(TemplatedControl picker, TemplateAppliedEventArgs e)
{
if (e.NameScope.Find<Button>("PART_FlyoutButton") is not { } button)
return;
PickerButtons.AddOrUpdate(picker, button);
NamePicker(picker);
}
private static void NamePicker(TemplatedControl picker)
{
if (!PickerButtons.TryGetValue(picker, out var button))
return;
string? value = picker switch
{
DatePicker date => DateText(date.SelectedDate, date.YearVisible),
TimePicker time => TimeText(time.SelectedTime),
_ => null
};
AutomationProperties.SetName(button, PickerText(AutomationProperties.GetName(picker), value));
}
/// <summary>The picker's label and what it holds, as the button inside it is read.</summary>
public static string? PickerText(string? label, string? value)
{
if (string.IsNullOrEmpty(label))
return value;
return string.IsNullOrEmpty(value) ? label : $"{label}: {value}";
}
/// <summary>Day and month in words, the year too when the picker shows one.</summary>
public static string? DateText(DateTimeOffset? date, bool withYear) =>
date?.ToString(withYear ? "D" : "M", CultureInfo.CurrentCulture);
public static string? TimeText(TimeSpan? time) =>
time?.ToString(@"hh\:mm", CultureInfo.InvariantCulture);
// The labels already followed, so a label read again is not followed twice.
private static readonly ConditionalWeakTable<TextBlock, Control> Followed = new();
/// <summary>Longer than this, a text beside a field is a description, not its label.</summary>
private const int LabelLength = 60;
/// <summary>
/// A field named by the label a sighted reader sees beside it, and named again when
/// the label changes with the language. A name given otherwise is left alone.
/// </summary>
public static void NameByLabel(Control input)
{
if (LabelOf(input) is not { } label)
return;
Give(input, TextOf(label));
if (Followed.TryAdd(label, input))
label.PropertyChanged += (_, e) =>
{
if (e.Property == TextBlock.TextProperty)
Give(input, TextOf(label));
};
}
/// <summary>
/// The text that labels a field: to its left in the same grid row, above it in the
/// same grid column, or just before it in any other panel. Null when there is none.
/// </summary>
public static TextBlock? LabelOf(Control input)
{
if (input.Parent is not Panel panel)
return null;
var labels = panel.Children.OfType<TextBlock>().Where(IsLabel).ToList();
// A panel that only holds inputs - a number box and the list shown in its place -
// is labelled where it stands itself.
if (labels.Count == 0)
return panel.Parent is Panel ? LabelOf(panel) : null;
if (panel is Grid)
{
int row = Grid.GetRow(input), column = Grid.GetColumn(input);
return labels.Where(t => Grid.GetRow(t) == row && Grid.GetColumn(t) < column)
.OrderByDescending(Grid.GetColumn).FirstOrDefault()
?? labels.FirstOrDefault(t => Grid.GetColumn(t) == column && Grid.GetRow(t) == row - 1);
}
int at = panel.Children.IndexOf(input);
return at > 0 && panel.Children[at - 1] is TextBlock before && labels.Contains(before) ? before : null;
}
private static bool IsLabel(TextBlock block) =>
block.IsVisible && TextOf(block) is { Length: <= LabelLength };
/// <summary>
/// A panel with a title, such as Scenerie or Skład, made a named group: the reader
/// says where focus went in, where before the panel was not there for it at all.
/// Tabs and expanders, which are panels with a title too, speak for themselves.
/// </summary>
private static void NameGroup(HeaderedContentControl panel)
{
if (panel.GetType() != typeof(HeaderedContentControl) && panel is not SettingsSection)
return;
string? name = TextOf(panel.Header);
Give(panel, name);
AutomationProperties.SetControlTypeOverride(panel, name is null ? null : AutomationControlType.Group);
// Content as well as control: NVDA passes over a group that is not both.
AutomationProperties.SetAccessibilityView(panel, name is null ? AccessibilityView.Default : AccessibilityView.Content);
}
// How far up a picture looks for what it shows: the button or card it sits in,
// not the panel around them.
private const int PictureReach = 3;
/// <summary>
/// Names a picture after the caption beside it or the button or card it lies in. Under the mouse a reader
/// hears what lies there, and a bare picture said nothing: a vehicle in the consist,
/// the logo, an icon on a button.
/// </summary>
public static void NamePicture(Control picture)
{
if ((!string.IsNullOrEmpty(AutomationProperties.GetName(picture)) && !Given.TryGetValue(picture, out _))
|| AutomationProperties.GetLabeledBy(picture) is not null)
return;
// A caption beside it says what it shows, such as a vehicle class by its picture.
if (picture.Parent is Panel row
&& row.Children.OfType<TextBlock>().FirstOrDefault(t => t.IsVisible && !string.IsNullOrWhiteSpace(t.Text)) is { } caption)
{
AutomationProperties.SetLabeledBy(picture, caption);
return;
}
var holder = picture.Parent as Control;
for (int i = 0; i < PictureReach && holder is not null; i++, holder = holder.Parent as Control)
{
if (!string.IsNullOrEmpty(AutomationProperties.GetName(holder)) || holder is Button)
{
AutomationProperties.SetLabeledBy(picture, holder);
return;
}
if (TextOf(ToolTip.GetTip(holder)) is { } tip)
{
Give(picture, tip);
return;
}
}
}
/// <summary>
/// Says what a closed list now holds when the arrow keys change it. Avalonia tells
/// Windows of a new value only for a list one types into, so NVDA said nothing.
/// </summary>
public static void TellChoice(ComboBox combo)
{
if (combo.IsKeyboardFocusWithin && !combo.IsDropDownOpen && !combo.IsEditable)
Announcer.Say(combo, SpokenItem(combo.SelectedItem));
}
/// <summary>What a reader is told a list entry is, as Avalonia tells it.</summary>
public static string? SpokenItem(object? item) => item switch
{
null => null,
Control c when AutomationProperties.GetName(c) is { Length: > 0 } name => name,
ContentControl c => TextOf(c.Content) ?? c.Content?.ToString(),
_ => TextOf(item) ?? item.ToString(),
};
// A sign such as "?" says nothing read aloud; its tooltip says what it does.
private static void NameButton(Button button) =>
Give(button, button.Content is string text && text.Any(char.IsLetterOrDigit)
? null
: TextOf(ToolTip.GetTip(button)) ?? TextOf(button.Content));
// The descriptions given here, so a later one replaces it but nothing else.
private static readonly ConditionalWeakTable<StyledElement, string> Described = new();
/// <summary>
/// The inputs of a setting row, described by the row's explanation and the note on
/// why the simulator would pass it over: a reader hears them after the name, where
/// a sighted one sees them under it.
/// </summary>
public static void DescribeInputs(object? content, params string?[] notes)
{
string? text = Join(notes) is { Length: > 0 } joined ? joined : null;
foreach (var input in DescribedInputs(content))
Describe(input, text);
}
private static void Describe(StyledElement target, string? text)
{
string? current = AutomationProperties.GetHelpText(target);
bool ours = Described.TryGetValue(target, out string? given) && current == given;
if (!string.IsNullOrEmpty(current) && !ours)
return;
if (string.IsNullOrEmpty(text))
{
if (ours)
target.ClearValue(AutomationProperties.HelpTextProperty);
Described.Remove(target);
return;
}
AutomationProperties.SetHelpText(target, text);
Described.AddOrUpdate(target, text);
}
/// <summary>
/// The inputs of a setting row, named by the row's label: a list, a slider or a box
/// beside the label otherwise had no name at all.
/// </summary>
public static void NameInputs(object? content, string? label)
{
foreach (var input in Inputs(content))
Give(input, label);
}
/// <summary>
/// The value a setting row shows, given to the slider in it, so the reader hears
/// "100%" or "Wyłączone" and not where the knob stands.
/// </summary>
public static void TellValue(object? content, string? valueText)
{
foreach (var slider in Inputs(content).OfType<ReadableSlider>())
slider.ValueText = valueText;
}
private static IEnumerable<Control> Inputs(object? content) => content switch
{
ComboBox or Slider or TextBox or NumericUpDown => new[] { (Control)content },
Panel panel => panel.Children.SelectMany(Inputs),
Decorator decorator => Inputs(decorator.Child),
_ => Array.Empty<Control>()
};
// A check box says its own text, so it is described but never named by the row.
private static IEnumerable<Control> DescribedInputs(object? content) => content switch
{
CheckBox box => new[] { (Control)box },
Panel panel => panel.Children.SelectMany(DescribedInputs),
Decorator decorator => DescribedInputs(decorator.Child),
_ => Inputs(content)
};
/// <summary>The text a reader would see on it, or null when it shows none.</summary>
public static string? TextOf(object? content)
{
string? text = content switch
{
string s => s,
// A sign such as a dot is given the words it stands for.
TextBlock block when AutomationProperties.GetName(block) is { Length: > 0 } name => name,
TextBlock block => block.Inlines is { Count: > 0 } inlines ? TextOf(inlines) : block.Text,
ContentControl inner => TextOf(inner.Content),
Decorator decorator => TextOf(decorator.Child),
Panel panel => Join(panel.Children.Where(c => c.IsVisible).Select(TextOf)),
_ => null
};
return string.IsNullOrWhiteSpace(text) ? null : text.Trim();
}
private static string TextOf(InlineCollection inlines) =>
string.Concat(inlines.Select(i => i switch
{
Run run => run.Text,
LineBreak => " ",
Span span => TextOf(span.Inlines),
_ => null
}));
private static string Join(IEnumerable<string?> parts) =>
string.Join(", ", parts.Where(p => !string.IsNullOrWhiteSpace(p)));
private static void Give(StyledElement target, string? name)
{
string? current = AutomationProperties.GetName(target);
bool ours = Given.TryGetValue(target, out string? given) && current == given;
if (!string.IsNullOrEmpty(current) && !ours)
return;
if (string.IsNullOrEmpty(name))
{
if (ours)
target.ClearValue(AutomationProperties.NameProperty);
Given.Remove(target);
return;
}
AutomationProperties.SetName(target, name);
Given.AddOrUpdate(target, name);
}
}

View File

@@ -0,0 +1,43 @@
using System;
using Avalonia.Controls;
using Avalonia.Threading;
namespace StarterNG.Controls;
/// <summary>
/// Says how many entries a search box left once typing pauses: the list filled itself
/// out of sight, and a screen reader heard only the letters typed. Nothing is said
/// while focus is elsewhere or the box is empty.
/// </summary>
public sealed class SearchResultsTeller
{
/// <summary>The pause after the last key that counts as done typing.</summary>
public static readonly TimeSpan Pause = TimeSpan.FromMilliseconds(900);
private readonly TextBox _box;
private readonly Func<int> _count;
private readonly DispatcherTimer _timer = new() { Interval = Pause };
public SearchResultsTeller(TextBox box, Func<int> count)
{
_box = box;
_count = count;
_timer.Tick += (_, _) => Tell();
}
/// <summary>The text changed: the count is said after the pause, once.</summary>
public void Changed()
{
_timer.Stop();
_timer.Start();
}
private void Tell()
{
_timer.Stop();
if (!_box.IsKeyboardFocusWithin || string.IsNullOrWhiteSpace(_box.Text))
return;
Announcer.Say(_box, string.Format(AppLanguage.Text("SearchFound"), _count()));
}
}

View File

@@ -1,5 +1,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace StarterNG.Controls;
@@ -73,6 +74,25 @@ public class SettingRow : ContentControl
if (change.Property == IdleNoteProperty)
ToolTip.SetTip(this, string.IsNullOrEmpty(IdleNote) ? null : IdleNote);
if (change.Property == LabelProperty || change.Property == ContentProperty)
ScreenReaderNames.NameInputs(Content, Label);
if (change.Property == ValueTextProperty || change.Property == ContentProperty)
ScreenReaderNames.TellValue(Content, ValueText);
if (change.Property == DescriptionProperty || change.Property == IdleNoteProperty ||
change.Property == ContentProperty)
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
}
// Again once in the window: a panel given as content may be filled after it was set.
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
ScreenReaderNames.NameInputs(Content, Label);
ScreenReaderNames.TellValue(Content, ValueText);
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
}
private void UpdatePseudoClasses()

View File

@@ -59,6 +59,43 @@ public class SettingsSection : HeaderedContentControl
_reset = e.NameScope.Find<Button>("PART_Reset");
if (_reset is not null)
_reset.Click += OnResetClick;
NameReset();
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == HeaderProperty || change.Property == ResetLabelProperty)
NameReset();
if (change.Property == HeaderProperty || change.Property == LevelProperty)
NameLevel();
}
/// <summary>
/// The header's list of levels was named by the word it shows with nothing chosen,
/// "Własne"; it is named as the level of this section.
/// </summary>
private void NameLevel()
{
if (Level is Control level)
Avalonia.Automation.AutomationProperties.SetName(level, ScreenReaderNames.PickerText(
AppLanguage.Text("SectionLevel"), ScreenReaderNames.TextOf(Header)));
}
/// <summary>
/// Every section has a button with the same words; a reader is told which section
/// it puts back, as a sighted one sees from where it stands.
/// </summary>
private void NameReset()
{
if (_reset is null)
return;
string? name = ScreenReaderNames.PickerText(ResetLabel, ScreenReaderNames.TextOf(Header));
if (string.IsNullOrEmpty(name))
_reset.ClearValue(Avalonia.Automation.AutomationProperties.NameProperty);
else
Avalonia.Automation.AutomationProperties.SetName(_reset, name);
}
private void OnResetClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e) => ResetRequested?.Invoke(this);

View File

@@ -61,13 +61,6 @@ public enum SceneryFaultKind
/// <summary>An include whose file is not there; <see cref="SceneryFault.Token"/> names it.</summary>
MissingInclude,
/// <summary>
/// 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
/// <see cref="SceneryFault.Subject"/> holds the name on disk.
/// </summary>
IncludeLetterCase,
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
IncludeNotClosed,

View File

@@ -5,12 +5,6 @@ using System.Linq;
namespace StarterNG.Domain.Sceneries;
/// <summary>
/// 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.
/// </summary>
public readonly record struct IncludeLookup(bool Opens, string? OnDisk = null);
/// <summary>
/// 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
/// <param name="text">The scenery's text, its includes put in place.</param>
/// <param name="file">The scenery's file name, for faults in its own text.</param>
/// <param name="findInclude">
/// What the simulator makes of an include, named as the include names it; null
/// <param name="opensInclude">
/// Whether the simulator opens an include, named as the include names it; null
/// leaves includes unchecked.
/// </param>
public static Result Scan(string text, string file, Func<string, IncludeLookup>? findInclude = null)
public static Result Scan(string text, string file, Func<string, bool>? 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<SceneryCode.Token> tokens, SceneryLines lines, Func<string, IncludeLookup>? findInclude, bool asSimulator)
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? 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.

View File

@@ -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);
@@ -88,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<string> GetFiles(string path, string searchPattern = "*") =>
Directory.Exists(path) ? Directory.GetFiles(path, searchPattern) : Array.Empty<string>();
Directory.Exists(path)
? Directory.GetFiles(path, searchPattern, new EnumerationOptions
{
IgnoreInaccessible = false,
AttributesToSkip = 0,
MatchType = MatchType.Win32,
MatchCasing = MatchCasing.CaseInsensitive
})
: Array.Empty<string>();
// A folder it may not enter costs what is in it, not the whole listing.
public IReadOnlyList<string> GetFilesRecursive(string path, string searchPattern) =>
@@ -99,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<string>();

View File

@@ -0,0 +1,132 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using StarterNG.Application.Abstractions;
namespace StarterNG.Infrastructure;
/// <summary>
/// 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.
/// </summary>
public sealed class CaseInsensitivePaths
{
private readonly IFileSystem _files;
private readonly Func<(string Folder, bool Files), ILookup<string, string>> _list;
/// <summary>Each folder's files and folders by name, listed once until <see cref="Forget"/>; null lists every time.</summary>
private readonly ConcurrentDictionary<(string Folder, bool Files), ILookup<string, string>>? _listings;
/// <param name="keepListings">
/// Lists each folder once, for many names looked up in data that stays as it is
/// meanwhile, until <see cref="Forget"/>.
/// </param>
public CaseInsensitivePaths(IFileSystem files, bool keepListings = false)
{
_files = files;
_list = List;
if (keepListings)
_listings = new ConcurrentDictionary<(string, bool), ILookup<string, string>>();
}
/// <summary>Lets the next lookups list the folders again.</summary>
public void Forget() => _listings?.Clear();
/// <summary>
/// The file named so under <paramref name="folder"/> 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.
/// </summary>
/// <param name="name">
/// A name under the folder, with either slash, joined to it as the simulator joins
/// it: a slash ahead of it counts for nothing.
/// </param>
/// <param name="directory">Looks for a folder instead of a file.</param>
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;
}
/// <summary>
/// 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
/// <paramref name="folder"/> as <see cref="Resolve"/> does.
/// </summary>
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;
}
/// <summary>
/// Finds the parts from <paramref name="at"/> on under <paramref name="current"/>. Of
/// folders named alike in other case - two copies of the data on Linux - each is
/// tried, the one written as on disk first.
/// </summary>
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<string, string> 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<string, string> List((string Folder, bool Files) key)
{
var entries = Array.Empty<string>();
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);
}
}

View File

@@ -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)
/// <summary>
/// The picture of textures/logo under <paramref name="root"/> 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.
/// </summary>
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)

View File

@@ -0,0 +1,24 @@
using StarterNG.Application.Abstractions;
using StarterNG.Domain.Sceneries;
namespace StarterNG.Infrastructure.Sceneries;
/// <summary>Where the file a scenery attaches (<c>//$f</c>) is on disk.</summary>
public sealed class AttachmentLocator
{
private readonly IGamePaths _paths;
private readonly CaseInsensitivePaths _names;
public AttachmentLocator(IFileSystem files, IGamePaths paths)
{
_paths = paths;
_names = new CaseInsensitivePaths(files);
}
/// <summary>
/// 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.
/// </summary>
public string? Resolve(SceneryAttachment attachment) =>
string.IsNullOrWhiteSpace(attachment.FilePath) ? null : _names.Find(_paths.Root, attachment.FilePath.Trim());
}

View File

@@ -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<string, string?> _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);
}
}

View File

@@ -20,11 +20,11 @@ public sealed class SceneryParser
_random = random;
}
/// <param name="findInclude">
/// What the simulator makes of an include, as the include names it; null leaves
/// <param name="opensInclude">
/// Whether the simulator opens an include, as the include names it; null leaves
/// includes unchecked.
/// </param>
public Scenery Parse(string path, string content, Func<string, IncludeLookup>? findInclude = null)
public Scenery Parse(string path, string content, Func<string, bool>? 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);

View File

@@ -23,7 +23,7 @@ public sealed class SceneryRepository : ISceneryRepository
private readonly SceneryParser _parser;
/// <summary>The scenery folders' files and folders, listed once per load of them all.</summary>
private readonly ConcurrentDictionary<(string, bool), IReadOnlyList<string>> _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<Scenery> LoadAll(IProgress<SceneryLoadProgress>? progress = null)
{
_listings.Clear();
_names.Forget();
var files = SceneryFiles().ToList();
var loaded = new ConcurrentBag<Scenery>();
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);
}
@@ -79,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)
{
@@ -99,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;
@@ -114,11 +113,11 @@ public sealed class SceneryRepository : ISceneryRepository
}
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>
/// An include's file as it is named on disk, from the scenery folder, whatever
@@ -126,44 +125,7 @@ public sealed class SceneryRepository : ISceneryRepository
/// copy written for a start carries in place of the include, so they come along
/// on Linux too.
/// </summary>
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<string>();
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<string> Listing(string directory, bool files) =>
_listings.GetOrAdd((directory, files), key =>
{
if (!_files.DirectoryExists(key.Item1))
return Array.Empty<string>();
return key.Item2 ? _files.GetFiles(key.Item1) : _files.GetDirectories(key.Item1);
});
private string? ResolveInclude(string name) => _names.Resolve(_paths.Scenery, name);
private IEnumerable<string> SceneryFiles() =>
_files.GetFiles(_paths.Scenery, "*.scn")

View File

@@ -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<string, string> _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

View File

@@ -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);
}
/// <summary>The number the timetable gives its train; null with no timetable or no such heading in it.</summary>

View File

@@ -22,15 +22,37 @@ public sealed class ExecutableLocator
private string? _wine;
private bool _wineLookedUp;
private string? _missingPickLogged;
private readonly bool _lacksAvx2;
public ExecutableLocator(IFileSystem files, IGamePaths paths, IEnvironment environment, IDiagnosticsLog log)
/// <param name="lacksAvx2">Whether this processor runs no AVX2; asked of it when left out.</param>
public ExecutableLocator(IFileSystem files, IGamePaths paths, IEnvironment environment, IDiagnosticsLog log,
bool? lacksAvx2 = null)
{
_files = files;
_paths = paths;
_environment = environment;
_log = log;
_lacksAvx2 = lacksAvx2 ?? CpuFeatures.LacksAvx2;
}
/// <summary>
/// The end of the name of a simulator built without AVX2, last before any extension:
/// eu07-x64_2026-11-15_abc1234_noavx2.exe, eu07_noavx2. It runs on any x86-64 processor.
/// </summary>
public const string NoAvx2Suffix = "_noavx2";
public static bool IsNoAvx2(string path) =>
Path.GetFileNameWithoutExtension(path).EndsWith(NoAvx2Suffix, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Whether <paramref name="executable"/> stops at its first instruction here: a build
/// with AVX2 on a processor without it. Such a processor is told so before a start.
/// </summary>
public bool WillNotRunHere(string executable) => _lacksAvx2 && !IsNoAvx2(executable);
/// <summary>The newest build without AVX2 in the installation, or null where there is none.</summary>
public string? NewestNoAvx2() => ListCandidates().FirstOrDefault(IsNoAvx2);
public string CanonicalName => _environment.IsWindows ? "eu07.exe" : "eu07";
/// <summary>
@@ -71,7 +93,8 @@ public sealed class ExecutableLocator
{
var candidates = _files.GetFiles(_paths.Root, "eu07*")
.Where(IsCandidate)
.OrderBy(path => IsExeOnLinux(path) ? 1 : 0)
.OrderBy(Rank)
.ThenByDescending(path => _lacksAvx2 && IsNoAvx2(path) ? _files.GetLastWriteTimeUtc(path) : DateTime.MinValue)
.ThenBy(path => string.Equals(Path.GetFileName(path), CanonicalName,
StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(path => Path.GetFileName(path).Length);
@@ -101,6 +124,18 @@ public sealed class ExecutableLocator
return CanonicalName;
}
/// <summary>
/// The order of the search. Without AVX2 a build without it comes first, the newest of
/// them, even through Wine: the others stop at once. With AVX2 one is the last resort,
/// as the build made for the processor runs faster; native before Wine either way.
/// </summary>
private int Rank(string path)
{
int wine = IsExeOnLinux(path) ? 1 : 0;
int noAvx2 = IsNoAvx2(path) ? 1 : 0;
return _lacksAvx2 ? (1 - noAvx2) * 2 + wine : wine * 2 + noAvx2;
}
public List<string> ListCandidates(string? directory = null)
{
try

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
namespace StarterNG.Infrastructure;
/// <summary>
/// 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.
/// </summary>
public static class SoftwareRender
{
public const string Switch = "--software-render";
public static bool AskedIn(IEnumerable<string> 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);
}

View File

@@ -1,6 +1,8 @@
using System.Collections.Generic;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Layout;
using Avalonia.Markup.Xaml.MarkupExtensions;
using Avalonia.Media;
namespace StarterNG.Infrastructure;
@@ -13,31 +15,34 @@ public static class StatsBar
for (int i = 0; i < fields.Count; i++)
{
var (label, value) = fields[i];
var pair = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 5,
// no trailing gap on the last pair - these sit in a panel title,
// flush with its right edge
Margin = new Avalonia.Thickness(0, 0, i == fields.Count - 1 ? 0 : 22, 0),
VerticalAlignment = VerticalAlignment.Center
};
pair.Children.Add(new TextBlock
{
Text = label,
FontSize = 12,
Opacity = 0.65,
VerticalAlignment = VerticalAlignment.Center
});
pair.Children.Add(new TextBlock
{
Text = value,
FontSize = 12,
FontWeight = FontWeight.SemiBold,
VerticalAlignment = VerticalAlignment.Center,
TextTrimming = TextTrimming.CharacterEllipsis
});
host.Children.Add(pair);
host.Children.Add(Figure(label, value, last: i == fields.Count - 1));
}
}
/// <summary>
/// One text holding the label and the value: under the mouse a reader hears the
/// text that lies there, and with two it heard "Masa [t]:" without the mass.
/// </summary>
public static TextBlock Figure(string label, string value, bool last)
{
var name = new Run(label);
// The label dimmed, as the panel titles' other labels.
name.Bind(TextElement.ForegroundProperty, new DynamicResourceExtension("CarbonFgDim"));
return new TextBlock
{
FontSize = 12,
// no trailing gap on the last pair - these sit in a panel title,
// flush with its right edge
Margin = new Avalonia.Thickness(0, 0, last ? 0 : 22, 0),
VerticalAlignment = VerticalAlignment.Center,
TextTrimming = TextTrimming.CharacterEllipsis,
Inlines = new InlineCollection
{
name,
new Run(" "),
new Run(value) { FontWeight = FontWeight.SemiBold },
},
};
}
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace StarterNG.Infrastructure;
/// <summary>
/// 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.
/// </summary>
public sealed class SystemGraphicsLibraries
{
public delegate bool Loader(string path, out IntPtr handle);
// dxgi ahead of d3d11, which asks for it.
public static readonly IReadOnlyList<string> Names = new[] { "dxgi", "d3d11", "d3d9", "opengl32" };
private readonly Dictionary<string, IntPtr> _loaded = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _shadowed = new();
private SystemGraphicsLibraries()
{
}
/// <summary>The files of these names that lay beside the starter.</summary>
public IReadOnlyList<string> Shadowed => _shadowed;
/// <summary>What goes to the log about them, or null when none lay there.</summary>
public string? Note => _shadowed.Count > 0
? $"Graphics libraries beside the starter, left to the simulator: {string.Join(", ", _shadowed)}"
: null;
/// <summary>The libraries of this Windows, or null on any other system.</summary>
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<string, bool> exists, Loader load)
{
var taken = new SystemGraphicsLibraries();
foreach (string name in Names)
{
string file = name + ".dll";
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;
}
/// <summary>The system library for an import of one of these names; zero leaves it to the usual search.</summary>
public IntPtr Resolve(string libraryName)
{
string name = libraryName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
? libraryName[..^4]
: libraryName;
return _loaded.TryGetValue(name, out IntPtr handle) ? handle : IntPtr.Zero;
}
/// <summary>
/// The assembly's imports of these names get the system libraries. False when it
/// has a resolver of its own already; that one decides.
/// </summary>
public bool ServeTo(Assembly importer)
{
try
{
NativeLibrary.SetDllImportResolver(importer, (name, _, _) => Resolve(name));
return true;
}
catch (InvalidOperationException)
{
return false;
}
}
}

View File

@@ -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;
}
@@ -51,7 +53,7 @@ public sealed class FizPhysicsRepository : IPhysicsRepository
if (string.IsNullOrEmpty(model))
return null;
string name = Path.GetFileNameWithoutExtension(model);
string name = Path.GetFileName(model);
if (name.Length == 0)
return null;
@@ -60,7 +62,10 @@ public sealed class FizPhysicsRepository : IPhysicsRepository
if (_cache.TryGetValue(key, out var cached))
return cached;
var physics = Read(folder, name);
// The name as written first: in 9-107.13 the dot is part of the name, not an extension.
string bare = Path.GetFileNameWithoutExtension(name);
var physics = Read(folder, name)
?? (bare.Length > 0 && bare != name ? Read(folder, bare) : null);
_cache[key] = physics;
return physics;
}
@@ -162,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;
}

View File

@@ -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<string> Scan(VehicleCatalog catalog)
{
var lines = new List<string>();
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;
/// <summary>Whether the file is under dynamic as named, or with one of the extensions, in any letter case.</summary>
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;

View File

@@ -0,0 +1,24 @@
using System.IO;
using StarterNG.Application.Abstractions;
using StarterNG.Domain.Vehicles;
namespace StarterNG.Infrastructure.Vehicles;
public static class TextureFolder
{
/// <summary>
/// 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.
/// </summary>
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));
}
}

View File

@@ -8,124 +8,129 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:views="clr-namespace:StarterNG.Views"
xmlns:starterNg="clr-namespace:StarterNG"
xmlns:ctl="clr-namespace:StarterNG.Controls"
Title="Starter MaSzyna"
Icon="/Assets/starter.ico"
Width="1010" Height="768" MinWidth="1010" MinHeight="666"
WindowStartupLocation="CenterScreen">
<DockPanel LastChildFill="True">
<!-- Says what a click changed out of sight; see Announcer. -->
<ctl:Announcer>
<DockPanel LastChildFill="True">
<Border x:Name="TopBar" DockPanel.Dock="Top"
Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderThickness="0,0,0,1"
PointerPressed="TitleBar_OnPointerPressed">
<Grid RowDefinitions="44">
<Border x:Name="TopBar" DockPanel.Dock="Top" TabIndex="0"
Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderThickness="0,0,0,1"
PointerPressed="TitleBar_OnPointerPressed">
<Grid RowDefinitions="44">
<Grid ColumnDefinitions="Auto,*,Auto" Background="Transparent">
<Grid ColumnDefinitions="Auto,*,Auto" Background="Transparent">
<StackPanel x:Name="TopBarLeft" Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Stretch">
<RadioButton x:Name="NavScenarios" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="scenarios" IsChecked="True"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavScenarios], Source={x:Static starterNg:App.Loc}}" />
<RadioButton x:Name="NavDepot" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="depot"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavDepot], Source={x:Static starterNg:App.Loc}}" />
<RadioButton x:Name="NavSettings" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="settings"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavSettings], Source={x:Static starterNg:App.Loc}}" />
<Button Classes="Basic" Click="openLastLogClick" Width="48" Cursor="Hand"
HorizontalContentAlignment="Center"
ToolTip.Tip="{Binding [ShowLatestLogTooltip], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="FileDocument" Height="16" Width="16" />
</Button>
<Button Classes="Basic" Click="openHaslerTapesClick" Width="48" Cursor="Hand"
HorizontalContentAlignment="Center"
ToolTip.Tip="{Binding [HaslerTapesTooltip], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChartLine" Height="16" Width="16" />
</Button>
<Button x:Name="HelpButton" Classes="Basic" Width="48" Cursor="Hand"
ToolTip.Tip="{Binding [Help], Source={x:Static starterNg:App.Loc}}"
Click="HelpButton_OnClick"
Content="?" FontWeight="Bold" FontSize="16"
HorizontalContentAlignment="Center" />
</StackPanel>
<StackPanel x:Name="TopBarRight" Grid.Column="2" Orientation="Horizontal"
VerticalAlignment="Center" Margin="0,0,3,0" Spacing="0">
<StackPanel x:Name="VersionPanel" Orientation="Vertical" VerticalAlignment="Center" Margin="0,0,6,0">
<Label Content="{Binding [Version], Source={x:Static starterNg:App.Loc}}"
FontSize="12" Foreground="{StaticResource CarbonFgDim}" Padding="0" />
<Label Content="{x:Static starterNg:AppInfo.Version}"
FontSize="12" Foreground="{StaticResource CarbonFg}" Padding="0" />
<StackPanel x:Name="TopBarLeft" Grid.Column="0" AutomationProperties.LandmarkType="Navigation" AutomationProperties.ControlTypeOverride="Group" AutomationProperties.AccessibilityView="Content" Orientation="Horizontal" VerticalAlignment="Stretch">
<RadioButton x:Name="NavScenarios" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="scenarios" IsChecked="True"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavScenarios], Source={x:Static starterNg:App.Loc}}" />
<RadioButton x:Name="NavDepot" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="depot"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavDepot], Source={x:Static starterNg:App.Loc}}" />
<RadioButton x:Name="NavSettings" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="settings"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavSettings], Source={x:Static starterNg:App.Loc}}" />
<Button Classes="Basic" Click="openLastLogClick" Width="48" Cursor="Hand"
HorizontalContentAlignment="Center"
ToolTip.Tip="{Binding [ShowLatestLogTooltip], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="FileDocument" Height="16" Width="16" />
</Button>
<Button Classes="Basic" Click="openHaslerTapesClick" Width="48" Cursor="Hand"
HorizontalContentAlignment="Center"
ToolTip.Tip="{Binding [HaslerTapesTooltip], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChartLine" Height="16" Width="16" />
</Button>
<Button x:Name="HelpButton" Classes="Basic" Width="48" Cursor="Hand"
ToolTip.Tip="{Binding [Help], Source={x:Static starterNg:App.Loc}}"
Click="HelpButton_OnClick"
Content="?" FontWeight="Bold" FontSize="16"
HorizontalContentAlignment="Center" />
</StackPanel>
<ComboBox x:Name="LangCombo" Width="96" VerticalAlignment="Center"
SelectionChanged="LangCombo_OnSelectionChanged" />
<StackPanel x:Name="TopBarRight" Grid.Column="2" Orientation="Horizontal"
VerticalAlignment="Center" Margin="0,0,3,0" Spacing="0">
<StackPanel x:Name="VersionPanel" Orientation="Vertical" VerticalAlignment="Center" Margin="0,0,6,0">
<Label Content="{Binding [Version], Source={x:Static starterNg:App.Loc}}"
FontSize="12" Foreground="{StaticResource CarbonFgDim}" Padding="0" />
<Label Content="{x:Static starterNg:AppInfo.Version}"
FontSize="12" Foreground="{StaticResource CarbonFg}" Padding="0" />
</StackPanel>
<Button Classes="Basic" Cursor="Hand" Tag="https://discord.gg/eu07" Click="linkClick"
ToolTip.Tip="Discord">
<PathIcon Data="{StaticResource DiscordLogo}" Height="12" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://www.facebook.com/MaSzynaeu07pl" Click="linkClick"
ToolTip.Tip="Facebook">
<materialIcons:MaterialIcon Kind="Facebook" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://www.youtube.com/@eu07official" Click="linkClick"
ToolTip.Tip="YouTube">
<materialIcons:MaterialIcon Kind="Youtube" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://github.com/MaSzyna-EU07/" Click="linkClick"
ToolTip.Tip="GitHub">
<materialIcons:MaterialIcon Kind="Github" />
</Button>
<ComboBox x:Name="LangCombo" Width="96" VerticalAlignment="Center"
AutomationProperties.Name="{Binding [Language], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="LangCombo_OnSelectionChanged" />
<Button x:Name="LogoLink" Classes="Basic" Cursor="Hand" Tag="http://eu07.pl/" Click="linkClick"
Padding="6,0" Margin="4,0,0,0"
ToolTip.Tip="eu07.pl">
<Image Source="/Assets/Logo/maszyna_white.png" Height="26" />
</Button>
</StackPanel>
<Button Classes="Basic" Cursor="Hand" Tag="https://discord.gg/eu07" Click="linkClick"
ToolTip.Tip="Discord">
<PathIcon Data="{StaticResource DiscordLogo}" Height="12" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://www.facebook.com/MaSzynaeu07pl" Click="linkClick"
ToolTip.Tip="Facebook">
<materialIcons:MaterialIcon Kind="Facebook" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://www.youtube.com/@eu07official" Click="linkClick"
ToolTip.Tip="YouTube">
<materialIcons:MaterialIcon Kind="Youtube" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://github.com/MaSzyna-EU07/" Click="linkClick"
ToolTip.Tip="GitHub">
<materialIcons:MaterialIcon Kind="Github" />
</Button>
<Button x:Name="LogoLink" Classes="Basic" Cursor="Hand" Tag="http://eu07.pl/" Click="linkClick"
Padding="6,0" Margin="4,0,0,0"
ToolTip.Tip="eu07.pl">
<Image Source="/Assets/Logo/maszyna_white.png" Height="26" />
</Button>
</StackPanel>
</Grid>
</Grid>
</Border>
<!-- The other ways to start - without saving, free fly - were only under the
right button; the arrow beside it says they exist. The editor is not one
of them: it opens the scenery itself, so it has a button of its own. -->
<Grid DockPanel.Dock="Bottom" ColumnDefinitions="*,Auto,Auto,Auto" ColumnSpacing="4" Margin="3">
<Button Name="startButton" Classes="Start" Height="42"
TabIndex="9"
Click="StartButton_OnClick"
Content="{Binding [Start], Source={x:Static starterNg:App.Loc}}" />
<Button Name="startMoreButton" Grid.Column="1" Classes="Start" Width="36" Height="42"
TabIndex="10" Cursor="Hand"
Click="StartMoreButton_OnClick"
ToolTip.Tip="{Binding [StartMore], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChevronUp" Width="20" Height="20" />
</Button>
<Button Name="startEditorButton" Grid.Column="2" Classes="Flat" Height="42" Padding="14,0"
TabIndex="11" Cursor="Hand" VerticalContentAlignment="Center"
Click="StartEditorButton_OnClick" />
<Button Name="startEditorMoreButton" Grid.Column="3" Classes="Flat" Width="36" Height="42" Padding="0"
TabIndex="12" Cursor="Hand" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
Click="StartEditorMoreButton_OnClick"
ToolTip.Tip="{Binding [StartEditorWizard], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChevronUp" Width="20" Height="20" />
</Button>
</Grid>
</Border>
<!-- The other ways to start - without saving, free fly - were only under the
right button; the arrow beside it says they exist. The editor is not one
of them: it opens the scenery itself, so it has a button of its own. -->
<Grid DockPanel.Dock="Bottom" ColumnDefinitions="*,Auto,Auto,Auto" ColumnSpacing="4" Margin="3">
<Button Name="startButton" Classes="Start" Height="42"
TabIndex="9"
Click="StartButton_OnClick"
Content="{Binding [Start], Source={x:Static starterNg:App.Loc}}" />
<Button Name="startMoreButton" Grid.Column="1" Classes="Start" Width="36" Height="42"
TabIndex="10" Cursor="Hand"
Click="StartMoreButton_OnClick"
ToolTip.Tip="{Binding [StartMore], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChevronUp" Width="20" Height="20" />
</Button>
<Button Name="startEditorButton" Grid.Column="2" Classes="Flat" Height="42" Padding="14,0"
TabIndex="11" Cursor="Hand" VerticalContentAlignment="Center"
Click="StartEditorButton_OnClick" />
<Button Name="startEditorMoreButton" Grid.Column="3" Classes="Flat" Width="36" Height="42" Padding="0"
TabIndex="12" Cursor="Hand" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
Click="StartEditorMoreButton_OnClick"
ToolTip.Tip="{Binding [StartEditorWizard], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChevronUp" Width="20" Height="20" />
</Button>
</Grid>
<!-- Scrolls only below the size the pages are laid out for; see KeepPagesUsable. -->
<ScrollViewer x:Name="PageScroll" Margin="3,3,3,0" TabIndex="1"
HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled">
<Panel x:Name="PageHost">
<views:Scenarios x:Name="ScenariosView" />
<views:Depot x:Name="DepotView" IsVisible="False" />
<views:Settings x:Name="SettingsView" IsVisible="False" />
</Panel>
</ScrollViewer>
</DockPanel>
<!-- Scrolls only below the size the pages are laid out for; see KeepPagesUsable. -->
<ScrollViewer x:Name="PageScroll" AutomationProperties.LandmarkType="Main" AutomationProperties.AccessibilityView="Content" Margin="3,3,3,0" TabIndex="1"
HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled">
<Panel x:Name="PageHost">
<views:Scenarios x:Name="ScenariosView" />
<views:Depot x:Name="DepotView" IsVisible="False" />
<views:Settings x:Name="SettingsView" IsVisible="False" />
</Panel>
</ScrollViewer>
</DockPanel>
</ctl:Announcer>
</Window>

View File

@@ -13,6 +13,7 @@ using Avalonia.Layout;
using Avalonia.Threading;
using Avalonia.VisualTree;
using StarterNG.Classes;
using StarterNG.Controls;
using StarterNG.Infrastructure;
using StarterNG.Views;
using StarterNG.Application;
@@ -46,6 +47,9 @@ public partial class MainWindow : Window
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
InitializeComponent();
// The top bar lets the version go first when it runs short of room, which at the usual widths it does;
// the title has room for it at any width.
Title = $"{Title} {AppInfo.Version}";
ExtendClientAreaToDecorationsHint = true;
ExtendClientAreaTitleBarHeightHint = TitleBarHeight;
@@ -95,6 +99,7 @@ public partial class MainWindow : Window
// Tunnelling: the shortcuts are checked before any view sees the key, which is
// why OnShortcutKey has to be careful about text entry and key capture.
AddHandler(KeyDownEvent, OnShortcutKey, RoutingStrategies.Tunnel);
AddHandler(KeyDownEvent, OnTabWithNothingFocused, RoutingStrategies.Tunnel);
AppServices.Current.State.Changed += UpdateStartButton;
Opened += (_, _) =>
@@ -105,7 +110,13 @@ public partial class MainWindow : Window
_sceneryFilesTimer.Start();
FollowLastRun();
};
Activated += (_, _) => CheckExternalSettings();
Activated += (_, _) =>
{
CheckExternalSettings();
// Back from a build or a download: a new simulator is on the list already.
if (SettingsView.IsVisible)
SettingsView.RefreshExecutables();
};
_sceneryFilesTimer.Tick += async (_, _) => await LookAtSceneryFilesAsync();
Closed += (_, _) => _sceneryFilesTimer.Stop();
}
@@ -234,6 +245,17 @@ public partial class MainWindow : Window
win.ShowDialog(this);
}
private void OnTabWithNothingFocused(object? sender, KeyEventArgs e)
{
if (FocusManager is not { } focus)
return;
var next = KeyboardFocus.TabFromNowhere(e.Key, e.KeyModifiers, focus.GetFocusedElement(), this,
focus.FindFirstFocusableElement, focus.FindLastFocusableElement);
if (next is not null && next.Focus(NavigationMethod.Tab))
e.Handled = true;
}
private void OnShortcutKey(object? sender, KeyEventArgs e)
{
// A cab-control binding in Settings is waiting for this very keypress.
@@ -505,11 +527,34 @@ public partial class MainWindow : Window
private const string SimulatorBuildGuide = "https://github.com/MaSzyna-EU07/maszyna#getting-started";
/// <summary>
/// Tells a user whose processor lacks AVX2 that the published simulator will
/// not run, and where the instructions for a build of their own are.
/// Tells a user whose processor lacks AVX2 that the simulator that would start will
/// not run. With a build without AVX2 in the folder, chosen away from by hand, the
/// notice offers to go back to the automatic choice, which takes it; with none, it
/// says what such a build is called and where the instructions for one's own are.
/// </summary>
public async Task ShowCpuNoticeAsync()
public async Task ShowCpuNoticeAsync(string executable)
{
var services = AppServices.Current;
if (services.Executables.NewestNoAvx2() is { } noAvx2)
{
var (useIt, quiet) = await MessageBox.ShowNotice(
this, string.Format(App.Loc["CpuNoAvx2Chosen"], Path.GetFileName(executable), noAvx2),
App.Loc["CpuNoAvx2Title"], App.Loc["CpuNoAvx2UseIt"], App.Loc["DontShowAgain"]);
if (useIt)
{
services.Settings.SelectExeAutomatically = true;
services.SettingsStore.Save();
SettingsView.ReloadFromSettings();
UpdateStartButton();
}
if (quiet)
{
services.Settings.CpuNotice = false;
services.SettingsStore.Save();
}
return;
}
var (open, silence) = await MessageBox.ShowNotice(
this, string.Format(App.Loc["CpuNoAvx2"], SimulatorBuildGuide), App.Loc["CpuNoAvx2Title"],
App.Loc["CpuNoAvx2Open"], App.Loc["DontShowAgain"]);

View File

@@ -10,12 +10,22 @@ namespace StarterNG;
static class Program
{
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.
var graphics = SystemGraphicsLibraries.TakeOnWindows();
graphics?.ServeTo(typeof(Win32PlatformOptions).Assembly);
_softwareRender = SoftwareRender.AskedIn(args);
// Composition root first: everything below, including the crash handlers,
// resolves its collaborators from this graph.
AppServices.Initialize();
if (graphics?.Note is { } note)
Diagnostics.Log(note);
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
{
@@ -63,9 +73,13 @@ static class Program
};
}
private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) =>
_softwareRender ? SoftwareRender.ApplyTo(builder) : builder;
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.WithSoftwareRenderIfAsked()
.WithInterFont()
.WithDiagnosticsLogging()
.AfterSetup(_ => LogUiExceptions());

View File

@@ -2,6 +2,7 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:starterNg="clr-namespace:StarterNG"
x:Class="StarterNG.SplashWindow"
Title="Starter MaSzyna"
SystemDecorations="None"
CanResize="False"
ShowInTaskbar="True"
@@ -18,6 +19,7 @@
TextTrimming="CharacterEllipsis"
Text="{Binding [LoadingVehicles], Source={x:Static starterNg:App.Loc}}" />
<ProgressBar x:Name="progressBar"
AutomationProperties.Name="{Binding #statusText.Text}"
Minimum="0" Maximum="1" Value="0" Height="6" />
</StackPanel>
</Border>

View File

@@ -12,7 +12,7 @@
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<!-- Major and minor only: CI adds the patch, the number of commits, so every
build of main is a higher version without anyone bumping it. -->
<VersionPrefix>1.5</VersionPrefix>
<VersionPrefix>1.6</VersionPrefix>
<AssemblyName>Starter</AssemblyName>
<Company>eu07.pl</Company>
</PropertyGroup>
@@ -43,6 +43,10 @@
<ProjectReference Include="..\Eu07.BlackBox.Views\Eu07.BlackBox.Views.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="StarterNG.Tests" />
</ItemGroup>
<ItemGroup>
<Folder Include="Assets\Logo\" />
</ItemGroup>

View File

@@ -17,6 +17,8 @@
<SolidColorBrush x:Key="CarbonInputBg" Color="#262C31" />
<SolidColorBrush x:Key="CarbonBorderLight" Color="#3A424A" />
<!-- Frames of things you type in or tick: 3:1 against the panels they sit on, so the field can be found without hovering. -->
<SolidColorBrush x:Key="CarbonInputBorder" Color="#737C86" />
<SolidColorBrush x:Key="CarbonBorderDark" Color="#0E0F12" />
<SolidColorBrush x:Key="CarbonFg" Color="#E6E8EA" />
<SolidColorBrush x:Key="CarbonFgDim" Color="#9098A0" />
@@ -77,7 +79,7 @@
Height="{StaticResource CarbonCheckSize}"
VerticalAlignment="Center"
Background="{StaticResource CarbonInputBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderBrush="{StaticResource CarbonInputBorder}"
BorderThickness="1" CornerRadius="2">
<Path Name="glyph" Margin="3" Stretch="Uniform"
Data="M 0,4 L 3,7 L 9,0"
@@ -139,7 +141,7 @@
the same shape and height as a combo box. -->
<ControlTheme x:Key="{x:Type ButtonSpinner}" TargetType="ButtonSpinner">
<Setter Property="Background" Value="{StaticResource CarbonInputBg}" />
<Setter Property="BorderBrush" Value="{StaticResource CarbonBorderLight}" />
<Setter Property="BorderBrush" Value="{StaticResource CarbonInputBorder}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="2" />
<Setter Property="MinHeight" Value="{StaticResource CarbonControlHeight}" />
@@ -187,7 +189,7 @@
MinHeight="{StaticResource CarbonControlHeight}"
Padding="0"
BorderThickness="1"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderBrush="{StaticResource CarbonInputBorder}"
Background="{StaticResource CarbonInputBg}"
CornerRadius="2"
HorizontalAlignment="Stretch"
@@ -304,12 +306,14 @@
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="8,1" />
<Setter Property="CornerRadius" Value="2" />
<Setter Property="BorderBrush" Value="{StaticResource CarbonInputBorder}" />
</Style>
<Style Selector="TextBox">
<Setter Property="MinHeight" Value="{StaticResource CarbonControlHeight}" />
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="6,1" />
<Setter Property="CornerRadius" Value="2" />
<Setter Property="BorderBrush" Value="{StaticResource CarbonInputBorder}" />
</Style>
<!-- Fluent gives the spinner and the check controls a 32 px floor of their own,
inside the template, so setting MinHeight on the control alone does nothing. -->

View File

@@ -61,8 +61,10 @@
with no label hides PART_Label, and without this the
column would collapse onto the key and every
explanation would start at a different place again. -->
<!-- Selectable for copying, but no stop for Tab: a reader found
nothing there to say between one setting and the next. -->
<SelectableTextBlock Name="PART_ConfigKey"
Grid.Row="1" Grid.Column="0"
Grid.Row="1" Grid.Column="0" IsTabStop="False"
Text="{TemplateBinding ConfigKey}"
FontFamily="Consolas, DejaVu Sans Mono, Liberation Mono, Menlo, Courier New"
FontSize="11"

View File

@@ -82,6 +82,8 @@ public static class AboutWindow
};
close.Classes.Add("Accent");
close.Click += (_, _) => win.Close();
close.IsDefault = true;
close.IsCancel = true;
var footer = new StackPanel
{

View File

@@ -81,11 +81,12 @@
PointerWheelChanged="Combo_OnPointerWheel"
SelectionChanged="ClassCombo_OnSelectionChanged" />
<TextBox Name="searchBox" Grid.Row="3" Margin="0,0,0,6"
<TextBox Name="searchBox" AutomationProperties.LandmarkType="Search" Grid.Row="3" Margin="0,0,0,6"
PlaceholderText="{Binding [SearchAllVehicles], Source={x:Static starterNg:App.Loc}}"
TextChanged="SearchBox_OnTextChanged" />
<ListBox Name="vehicleListBox" Grid.Row="4" Classes="Compact" MinHeight="60"
AutomationProperties.Name="{Binding [Vehicles], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="VehicleListBox_OnSelectionChanged"
DoubleTapped="VehicleListBox_OnDoubleTapped"
PointerPressed="VehicleListBox_OnPointerPressed" />
@@ -126,7 +127,8 @@
BorderThickness="1" CornerRadius="2" Padding="6">
<!-- The tab picks what the consist strip edits: a consist of the scenery,
or a consist kept in the warehouse. -->
<TabControl Name="consistSourceTabs" SelectionChanged="ConsistSourceTabs_OnSelectionChanged">
<TabControl Name="consistSourceTabs" AutomationProperties.Name="{Binding [DepotConsistSources], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="ConsistSourceTabs_OnSelectionChanged">
<TabItem Name="sceneryConsistsTab"
Header="{Binding [SceneryConsists], Source={x:Static starterNg:App.Loc}}">
<DockPanel LastChildFill="True">
@@ -145,6 +147,7 @@
Content="{Binding [ShowAiVehicles], Source={x:Static starterNg:App.Loc}}" />
</StackPanel>
<ListBox Name="sceneryConsistList" Classes="Compact"
AutomationProperties.Name="{Binding [SceneryConsists], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="SceneryConsistList_OnSelectionChanged"
KeyDown="SceneryConsistList_OnKeyDown" />
</DockPanel>
@@ -160,7 +163,8 @@
<TextBlock DockPanel.Dock="Bottom" Margin="2,6,0,0" FontSize="12" Opacity="0.6"
TextWrapping="Wrap"
Text="{Binding [WarehouseEditHint], Source={x:Static starterNg:App.Loc}}" />
<ListBox Name="warehouseList" Classes="Compact" />
<ListBox Name="warehouseList" Classes="Compact"
AutomationProperties.Name="{Binding [WarehouseConsists], Source={x:Static starterNg:App.Loc}}" />
</DockPanel>
</TabItem>
</TabControl>
@@ -195,7 +199,7 @@
Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderThickness="1" CornerRadius="2" Padding="6">
<TabControl>
<TabControl AutomationProperties.Name="{Binding [DepotVehicleInfo], Source={x:Static starterNg:App.Loc}}">
<TabItem Header="{Binding [GeneralInfo], Source={x:Static starterNg:App.Loc}}">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Name="generalPanel" Margin="4" Grid.IsSharedSizeScope="True" />
@@ -213,7 +217,7 @@
Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderThickness="1" CornerRadius="2" Padding="6">
<TabControl>
<TabControl AutomationProperties.Name="{Binding [DepotVehicleEdit], Source={x:Static starterNg:App.Loc}}">
<TabItem Header="{Binding [Coupling], Source={x:Static starterNg:App.Loc}}">
<!-- The coupling grid now uses the full tab width. The two
actions sit underneath, so they do not steal horizontal
@@ -318,7 +322,12 @@
<Panel>
<!-- Tab reaches the strip once and lands on the selected
card; the arrow keys walk it from there. -->
<!-- Read as the list of cards it is, so a reader hears where it is
and how many cards it holds. -->
<StackPanel Name="consistStack" Orientation="Horizontal"
AutomationProperties.Name="{Binding [Consist], Source={x:Static starterNg:App.Loc}}"
AutomationProperties.ControlTypeOverride="List"
AutomationProperties.AccessibilityView="Content"
KeyboardNavigation.TabNavigation="Once"
VerticalAlignment="Center" Spacing="0" />
<Canvas Name="consistOverlay" IsHitTestVisible="False" />

View File

@@ -369,6 +369,41 @@ public partial class Depot : UserControl
// The cards are thrown away and rebuilt on every change, so a keyboard-driven
// edit has to be handed its card back or focus escapes the strip.
_cards.FocusSelectedCard(onlyIfRequested: true);
TellChange();
}
// The consist as it was last told, and whose it was.
private List<ConsistNarration.Unit> _told = new();
private Trainset? _toldTrainset;
// While an undo or a redo loads the consist: the word said before what it changed.
private string? _restoreWord;
/// <summary>
/// Says what the change did to the consist: nothing on the strip told a screen
/// reader of a vehicle added from the list, removed, turned or of an undo. Another
/// consist taken up is not told, its entry on the list says what it is.
/// </summary>
private void TellChange()
{
var now = _consist.Select(item => new ConsistNarration.Unit(
string.Join(", ", item.Cars.Select(car => TrainsetDisplay.VehicleLabel(car))), item.Flipped)).ToList();
var trainset = _consist.EditingTrainset;
bool same = trainset is not null && ReferenceEquals(trainset, _toldTrainset);
var before = _told;
_told = now;
_toldTrainset = trainset;
if (!same)
return;
// A card moved or turned from the keyboard is focused again, and says its new place itself.
if (_restoreWord is null && before.Count == now.Count && consistStack.IsKeyboardFocusWithin)
return;
string? said = ConsistNarration.Describe(before, now, _consist.VehicleCount, key => App.Loc[key]);
if (_restoreWord is not null)
said = string.Format(App.Loc[_restoreWord], said ?? string.Empty).Trim();
Controls.Announcer.Say(this, said);
}
private void WriteBackToScenery()
@@ -492,11 +527,11 @@ public partial class Depot : UserControl
redoButton.IsEnabled = editing is not null && _history.CanRedo(editing);
}
public void Undo() => Restore(_history.Undo);
public void Undo() => Restore(_history.Undo, "ConsistSaidUndone");
public void Redo() => Restore(_history.Redo);
public void Redo() => Restore(_history.Redo, "ConsistSaidRedone");
private void Restore(Func<Trainset, int, ConsistHistory.State?> step)
private void Restore(Func<Trainset, int, ConsistHistory.State?> step, string word)
{
if (_consist.EditingTrainset is not { } trainset ||
step(trainset, SelectedIndex()) is not { } state)
@@ -504,6 +539,7 @@ public partial class Depot : UserControl
trainset.Vehicles = state.Vehicles.ToList();
_restoring = true;
_restoreWord = word;
try
{
_consist.LoadFrom(trainset, state.Selected);
@@ -511,6 +547,7 @@ public partial class Depot : UserControl
finally
{
_restoring = false;
_restoreWord = null;
}
}
@@ -682,6 +719,8 @@ public partial class Depot : UserControl
Foreground = new SolidColorBrush(Color.Parse("#E0A030"))
};
ToolTip.SetTip(dot, App.Loc["ConsistUnsaved"]);
// Read as its meaning in the entry's name, not as "black circle".
Avalonia.Automation.AutomationProperties.SetName(dot, App.Loc["ConsistUnsaved"]);
var row = new DockPanel();
DockPanel.SetDock(dot, Dock.Left);
row.Children.Add(dot);

View File

@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace StarterNG.Views;
/// <summary>
/// What a change to the consist is said as, to someone who cannot see the strip: a
/// vehicle added from the list, removed with Delete, turned, moved, or a whole undo,
/// each of which changed only pictures before. Worked out from the consist as it was
/// and as it is, so every way of making the change - a button, a key, the menu, a
/// drag - is told the same way.
/// </summary>
public static class ConsistNarration
{
/// <summary>One position of the consist as it is told: what stands there, and whether it is turned.</summary>
public readonly record struct Unit(string Label, bool Turned);
/// <summary>
/// The sentence for the change from <paramref name="before"/> to <paramref name="after"/>;
/// null when nothing a listener would notice changed, such as a coupling or the crew.
/// </summary>
/// <param name="vehicles">How many vehicles the consist has now, its units counted car by car.</param>
/// <param name="loc">The starter's texts by key.</param>
public static string? Describe(IReadOnlyList<Unit> before, IReadOnlyList<Unit> after, int vehicles,
Func<string, string> loc)
{
if (after.Count == 0)
return before.Count == 0 ? null : loc("ConsistSaidEmpty");
var (head, tail) = Common(before, after);
var gone = before.Skip(head).Take(before.Count - head - tail).ToList();
var come = after.Skip(head).Take(after.Count - head - tail).ToList();
if (gone.Count == 0 && come.Count == 0)
return null;
if (gone.Count == 0)
return string.Format(loc("ConsistSaidAdded"), Labels(come), head + 1, after.Count);
if (come.Count == 0)
return string.Format(loc("ConsistSaidRemoved"), Labels(gone), vehicles);
if (gone.Count == come.Count && SameCount(gone, come, head, after.Count, loc) is { } said)
return said;
return string.Format(loc("ConsistSaidChangedMany"), Math.Max(gone.Count, come.Count), vehicles);
}
/// <summary>How many units at the front and at the back stayed as they were.</summary>
private static (int Head, int Tail) Common(IReadOnlyList<Unit> before, IReadOnlyList<Unit> after)
{
int head = 0;
while (head < before.Count && head < after.Count && before[head] == after[head])
head++;
int tail = 0;
while (tail < before.Count - head && tail < after.Count - head
&& before[before.Count - 1 - tail] == after[after.Count - 1 - tail])
tail++;
return (head, tail);
}
/// <summary>A change that left as many units as there were: turned, moved, reordered or one replaced; or null.</summary>
private static string? SameCount(List<Unit> gone, List<Unit> come, int head, int count, Func<string, string> loc)
{
// The same vehicles in the same places: some of them turned round.
if (gone.Select(u => u.Label).SequenceEqual(come.Select(u => u.Label)))
return Turned(gone, come, loc);
// One vehicle taken out and put back elsewhere: the rest keep their order.
if (MovedOne(gone, come) is { } moved)
return string.Format(loc("ConsistSaidMoved"), moved.Unit.Label, head + moved.To + 1, count);
if (gone.OrderBy(u => u.Label, StringComparer.Ordinal).SequenceEqual(
come.OrderBy(u => u.Label, StringComparer.Ordinal)))
return loc("ConsistSaidReordered");
return gone.Count == 1 ? string.Format(loc("ConsistSaidReplaced"), gone[0].Label, come[0].Label) : null;
}
private static string Turned(List<Unit> gone, List<Unit> come, Func<string, string> loc)
{
var turned = come.Where((u, i) => u.Turned != gone[i].Turned).ToList();
if (turned.Count != 1)
return string.Format(loc("ConsistSaidTurnedMany"), turned.Count);
string key = turned[0].Turned ? "ConsistSaidTurned" : "ConsistSaidUnturned";
return string.Format(loc(key), turned[0].Label);
}
/// <summary>The unit and the place it went to when one alone moved, or null.</summary>
private static (Unit Unit, int To)? MovedOne(List<Unit> gone, List<Unit> come)
{
// The run that differs starts and ends with a change, so the mover is at one end of it.
if (come.Count >= 2 && come.Take(come.Count - 1).SequenceEqual(gone.Skip(1)) && come[^1] == gone[0])
return (come[^1], come.Count - 1);
if (come.Count >= 2 && come.Skip(1).SequenceEqual(gone.Take(gone.Count - 1)) && come[0] == gone[^1])
return (come[0], 0);
return null;
}
private static string Labels(IEnumerable<Unit> units) => string.Join(", ", units.Select(u => u.Label));
}

View File

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

View File

@@ -77,6 +77,9 @@ public sealed class TextureRandomizerDialog
FontSize = 12
};
// Each box stands beside the choice it belongs to, which is no label a reader finds.
Avalonia.Automation.AutomationProperties.SetName(age, App.Loc["RandomizeTexturesRevDiff"]);
Avalonia.Automation.AutomationProperties.SetName(year, App.Loc["RandomizeTexturesVsYear"]);
revDiff.IsCheckedChanged += (_, _) => age.IsEnabled = revDiff.IsChecked == true;
vsYear.IsCheckedChanged += (_, _) => year.IsEnabled = vsYear.IsChecked == true;
@@ -118,6 +121,8 @@ public sealed class TextureRandomizerDialog
};
cancel.Classes.Add("Flat");
cancel.Click += (_, _) => win.Close(false);
ok.IsDefault = true;
cancel.IsCancel = true;
win.Content = new StackPanel
{

View File

@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Input;
@@ -59,6 +60,8 @@ public sealed class VehicleBrowser
private DispatcherTimer? _searchTimer;
private readonly SearchResultsTeller _searchResults;
private Func<string?, bool>? _categoryFilter;
private string? _classFilter;
@@ -81,6 +84,7 @@ public sealed class VehicleBrowser
vehicleListBox.ContextRequested += List_OnContextRequested;
_searchResults = new SearchResultsTeller(searchBox, () => vehicleListBox.ItemCount);
_searchTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(220) };
_searchTimer.Tick += (_, _) =>
{
@@ -338,6 +342,7 @@ public sealed class VehicleBrowser
Selected = null;
miniPreview.Source = null;
miniPreview.ClearValue(AutomationProperties.NameProperty);
addVehicleButton.IsEnabled = false;
vehicleListBox.Items.Clear();
@@ -381,10 +386,12 @@ public sealed class VehicleBrowser
public void VehicleListBox_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (vehicleListBox.SelectedItem is ListBoxItem { Tag: VehicleTexture texture })
if (vehicleListBox.SelectedItem is ListBoxItem { Tag: VehicleTexture texture } row)
{
Selected = texture;
miniPreview.Source = _minis.Get(_db.ResolveMiniName(texture), MiniPreviewHeight);
// Under the mouse a reader hears which vehicle the picture shows.
AutomationProperties.SetName(miniPreview, ScreenReaderNames.TextOf(row.Content));
addVehicleButton.IsEnabled = true;
SyncCombosTo(texture);
@@ -397,6 +404,7 @@ public sealed class VehicleBrowser
{
Selected = null;
miniPreview.Source = null;
miniPreview.ClearValue(AutomationProperties.NameProperty);
addVehicleButton.IsEnabled = false;
}
}
@@ -559,6 +567,7 @@ public sealed class VehicleBrowser
if (_suppress || _searchTimer is null) return;
_searchTimer.Stop();
_searchTimer.Start();
_searchResults.Changed();
}
public void HideArchivalCheck_OnChanged(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
@@ -578,12 +587,29 @@ public sealed class VehicleBrowser
var set = _db.ResolveSet(texture);
var browserTex = set is { Count: > 0 } ? set[0] : texture;
WhileSyncing(() =>
KeepingKeyboardFocus(() => WhileSyncing(() =>
{
ApplyFilters(VehicleInfo.CategoryOf(browserTex), VehicleInfo.ClassOf(browserTex));
Rebuild();
SelectListEntry(browserTex);
});
}));
}
/// <summary>
/// The list is rebuilt under the keyboard: the add button is switched off for a
/// moment and the rows are replaced, and focus fell out of the window with them -
/// Tab then went nowhere until something was clicked. It is handed back.
/// </summary>
private void KeepingKeyboardFocus(Action rebuild)
{
bool onAdd = addVehicleButton.IsFocused;
bool inList = vehicleListBox.IsKeyboardFocusWithin;
rebuild();
if (onAdd && addVehicleButton.IsEnabled)
addVehicleButton.Focus(NavigationMethod.Tab);
else if (onAdd || inList)
(vehicleListBox.SelectedItem as Control ?? vehicleListBox).Focus(NavigationMethod.Tab);
}
private void SyncCombosTo(VehicleTexture texture)
@@ -591,7 +617,7 @@ public sealed class VehicleBrowser
if (_syncingCombos || !ApplyFilters(VehicleInfo.CategoryOf(texture), VehicleInfo.ClassOf(texture)))
return;
PostSyncing(() => { Rebuild(); SelectListEntry(texture); });
PostSyncing(() => KeepingKeyboardFocus(() => { Rebuild(); SelectListEntry(texture); }));
}
private void WhileSyncing(Action work)

View File

@@ -2,6 +2,8 @@ using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
@@ -13,6 +15,7 @@ using Material.Icons.Avalonia;
using StarterNG.Classes;
using StarterNG.Domain;
using StarterNG.Domain.Vehicles;
using StarterNG.Controls;
namespace StarterNG.Views;
@@ -146,6 +149,10 @@ public sealed class VehicleCards
Focusable = true
};
card.Classes.Add("ConsistCard");
// The card shows pictures only; without a name a screen reader said nothing on it.
AutomationProperties.SetName(card, CardName(item, index));
AutomationProperties.SetControlTypeOverride(card, AutomationControlType.ListItem);
AutomationProperties.SetIsControlElementOverride(card, true);
card.GotFocus += (_, _) => Select(item, null);
card.KeyDown += (_, e) => OnCardKey(card, item, e);
card.PointerPressed += (_, e) =>
@@ -179,6 +186,11 @@ public sealed class VehicleCards
return card;
}
/// <summary>Its place in the consist and what it holds, as a screen reader says it.</summary>
private string CardName(ConsistItem item, int index) =>
$"{index + 1}. {string.Join(", ", item.Cars.Select(car => CardCaption(item, car, index)))}"
+ (item.Flipped ? $", {App.Loc["Reversed"]}" : string.Empty);
private string CardCaption(ConsistItem item, Dynamic car, int index) =>
TrainsetDisplay.VehicleLabel(car,
head: index == 0 && ReferenceEquals(car, Consist.HeadCar(item)) && TrainsetDisplay.IsPowered(car));
@@ -411,12 +423,22 @@ public sealed class VehicleCards
panel.Children.Add(apply);
var flyout = new Flyout { Content = panel, Placement = PlacementMode.Top };
apply.Click += (_, _) =>
void Apply()
{
_consist.SetWagonNumber(car, (int)(num.Value ?? 0));
flyout.Hide();
}
apply.Click += (_, _) => Apply();
// As the flyout for several vehicles does: typed into at once, Enter sets it.
num.KeyDown += (_, e) =>
{
if (e.Key != Key.Enter) return;
e.Handled = true;
Apply();
};
flyout.ShowAt(anchor);
num.Focus();
}
/// <summary>
@@ -623,6 +645,10 @@ public sealed class VehicleCards
btn.Content = glyph;
btn.Foreground = new SolidColorBrush(Color.Parse(color));
// "2" alone said nothing read aloud: the reader hears who rides in it.
int choice = CrewChoices.IndexOf(type);
AutomationProperties.SetName(btn, ScreenReaderNames.PickerText(
App.Loc["CrewLabel"], choice >= 0 ? App.Loc[CrewChoices.All[choice].Key] : glyph));
}
/// <summary>
@@ -668,7 +694,7 @@ public sealed class VehicleCards
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
foreach (var (type, key) in CrewChoices.All)
crew.AddItem((item.Driver == type ? "● " : "○ ") + App.Loc[key], () => _consist.SetCrew(item, type));
crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type)));
menu.Items.Add(crew);
// The member the panels show, not always the first car of a unit.

View File

@@ -595,6 +595,9 @@ public sealed class VehicleDetails
return Row(content: ready);
var why = PanelNote(App.Loc["ConsistReadyOverridden"]);
why.Margin = new Thickness(0);
// The reader is told it too, with the box, and not only by a text it may never come to.
Avalonia.Automation.AutomationProperties.SetHelpText(ready,
$"{App.Loc["ConsistReadyOverridden"]} {App.Loc["ConsistReadyDesc"]}");
return Row(content: new StackPanel { Spacing = 2, Children = { ready, why } });
}

View File

@@ -116,8 +116,8 @@ public sealed class Warehouse
}
private MenuItem SortItem(PresetSort mode, string locKey) =>
MenuItems.Item((PresetStore.SortMode == mode ? "● " : "○ ") + App.Loc[locKey],
() => { PresetStore.SortMode = mode; Refresh(); });
MenuItems.Choice(App.Loc[locKey], PresetStore.SortMode == mode,
() => { PresetStore.SortMode = mode; Refresh(); });
/// <summary>Asks for a name at the button pressed, and says where the consist went.</summary>
public void SaveCurrent(Control anchor) =>

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace StarterNG.Views;
/// <summary>
/// The simulators offered in the settings after the folder was looked at again: a build
/// copied in while the starter runs joins the list, and what was chosen stays chosen, even
/// a file picked from elsewhere or one since removed - looking again never changes the choice.
/// </summary>
public static class ExecutableList
{
/// <summary>The entries that follow "automatic", and the place of <paramref name="chosen"/> among them.</summary>
/// <param name="found">The simulators in the folder now, newest first.</param>
/// <param name="chosen">The entry chosen, or null for "automatic" or nothing chosen yet.</param>
/// <returns>Entries, and the index of the chosen one in them, -1 when <paramref name="chosen"/> is null.</returns>
public static (IReadOnlyList<string> Entries, int Chosen) Refreshed(IReadOnlyList<string> found, string? chosen)
{
var entries = found.ToList();
if (chosen is null)
return (entries, -1);
int at = entries.FindIndex(entry => string.Equals(entry, chosen, StringComparison.OrdinalIgnoreCase));
if (at >= 0)
return (entries, at);
entries.Add(chosen);
return (entries, entries.Count - 1);
}
}

View File

@@ -46,6 +46,8 @@ internal static class IniChangesWindow
var closeBtn = new Button { Content = App.Loc["Close"], MinWidth = 80 };
closeBtn.Classes.Add("Flat");
closeBtn.Click += (_, _) => win.Close();
saveBtn.IsDefault = true;
closeBtn.IsCancel = true;
body.Children.Add(MessageBox.ButtonRow(saveBtn, closeBtn));
win.Content = body;

View File

@@ -1,12 +1,15 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using StarterNG.Classes;
using StarterNG.Controls;
using StarterNG.Infrastructure;
using KeyBinding = StarterNG.Classes.KeyBinding;
@@ -34,6 +37,14 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
private KeyBinding? _capturing;
private Button? _capturingButton;
// The row buttons of each binding on the list, so focus goes back to the row it
// left when the list is drawn anew after an edit.
private readonly Dictionary<KeyBinding, (Button Combo, Button Clear)> _rowButtons = new();
// The keys of the drawn keyboard that can be bound, in reading order, with the block
// and the row each lies in: the arrow keys walk them as they lie.
private readonly List<(Border Cap, int Block, int Row)> _caps = new();
private readonly Dictionary<string, Grid> _keyCells = new(StringComparer.OrdinalIgnoreCase);
private bool _flyoutLoading;
@@ -48,6 +59,7 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
private static readonly IBrush FgBrush = new SolidColorBrush(Color.Parse("#E6E8EA"));
private static readonly IBrush FgDimBrush = new SolidColorBrush(Color.Parse("#9098A0"));
private static readonly IBrush ConflictBrush = new SolidColorBrush(Color.Parse("#E06C5A"));
private static readonly IBrush KeyFocusBrush = new SolidColorBrush(Color.Parse("#41C400"));
// The four combinations a key can be on. After the brushes: static fields start in text order.
private static readonly (bool Shift, bool Ctrl, string SlotTextKey, IBrush Colour)[] ModifierSlots =
@@ -151,11 +163,27 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
RedrawBindings();
}
private void BindingsEdited()
private void BindingsEdited(KeyBinding? focusRow = null)
{
KeyboardConfig.Instance.Dirty = true;
Changed?.Invoke();
RedrawBindings();
if (focusRow is not null)
FocusRow(focusRow);
}
/// <summary>
/// Puts focus back on a binding's row once the list is drawn anew: it went with the
/// old row, and a keyboard user was left nowhere.
/// </summary>
private void FocusRow(KeyBinding binding)
{
if (!_rowButtons.TryGetValue(binding, out var row))
return;
// The key button, which says what the binding is now.
row.Combo.Focus(NavigationMethod.Tab);
row.Combo.BringIntoView();
}
private void RedrawBindings()
@@ -164,12 +192,16 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
RebuildKeyboard();
}
/// <summary>How many bindings the list shows, after the search.</summary>
public int ShownCount => _rowButtons.Count;
public void RebuildList()
{
if (_bindingListPanel is null)
return;
_bindingListPanel.Children.Clear();
_rowButtons.Clear();
// The sidebar search box serves this list too - see Settings.ApplyFilter.
string filter = search.Text?.Trim() ?? string.Empty;
var conflicts = KeyboardConfig.Instance.ConflictingCombos();
@@ -253,6 +285,7 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
ToolTip.SetTip(comboButton, SimulatorUseText(b.Key, b.Shift, b.Ctrl, use));
else if (conflict)
ToolTip.SetTip(comboButton, App.Loc["ConflictTooltip"]);
NameCombo(comboButton, b, comboButton.Content as string);
comboButton.Click += (_, _) => StartCapture(b, comboButton);
Grid.SetColumn(comboButton, 1);
grid.Children.Add(comboButton);
@@ -265,12 +298,15 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
};
clearButton.Classes.Add("Basic");
ToolTip.SetTip(clearButton, App.Loc["ClearBinding"]);
// Every row has one: the reader is told whose it is.
AutomationProperties.SetName(clearButton, ScreenReaderNames.PickerText(App.Loc["ClearBinding"], CommandLabel(b)));
clearButton.Click += (_, _) =>
{
CancelCapture();
b.Clear();
BindingsEdited();
BindingsEdited(b);
};
_rowButtons[b] = (comboButton, clearButton);
Grid.SetColumn(clearButton, 2);
grid.Children.Add(clearButton);
@@ -289,22 +325,39 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
{
if (_capturing is not null && _capturingButton is not null)
_capturingButton.Content = ComboText(_capturing);
Show(_capturingButton, _capturing, ComboText(_capturing));
_capturing = b;
_capturingButton = button;
button.Content = App.Loc["PressKey"];
button.Focus();
Show(button, b, App.Loc["PressKey"], say: true);
}
private void CancelCapture()
{
if (_capturing is not null && _capturingButton is not null)
_capturingButton.Content = ComboText(_capturing);
Show(_capturingButton, _capturing, ComboText(_capturing), say: _capturingButton.IsKeyboardFocusWithin);
_capturing = null;
_capturingButton = null;
}
/// <summary>
/// Writes on a binding's button what it shows and names it after its command too, so
/// a reader hears "Odluźniacz: Num 4" and not a key alone. Said aloud when the change
/// happens under the focus, where nothing else would tell of it.
/// </summary>
private static void Show(Button button, KeyBinding b, string text, bool say = false)
{
button.Content = text;
NameCombo(button, b, text);
if (say)
Announcer.Say(button, text);
}
private static void NameCombo(Button button, KeyBinding b, string? shown) =>
AutomationProperties.SetName(button, ScreenReaderNames.PickerText(
CommandLabel(b), b.IsAssigned || shown != ComboText(b) ? shown : App.Loc["KbUnassigned"]));
public void OnKeyDown(object? sender, KeyEventArgs e)
{
if (_capturing is null)
@@ -333,18 +386,19 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
{
// Bound here it would never fire: the wait for a key goes on.
if (_capturingButton is not null)
_capturingButton.Content = string.Format(App.Loc["KbTaken"], App.Loc[taken.TextKey]);
Show(_capturingButton, _capturing, string.Format(App.Loc["KbTaken"], App.Loc[taken.TextKey]), say: true);
e.Handled = true;
return;
}
// As the key flyout does: the combination moves here, not doubled up.
KeyboardConfig.Instance.Put(_capturing, token, shift, ctrl);
var bound = _capturing;
KeyboardConfig.Instance.Put(bound, token, shift, ctrl);
e.Handled = true;
_capturing = null;
_capturingButton = null;
BindingsEdited();
BindingsEdited(bound);
}
private void RebuildKeyboard()
@@ -353,13 +407,16 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
return;
_keyCells.Clear();
_caps.Clear();
_keyboardPanel.Children.Clear();
// Tab reaches the keyboard once; the arrow keys walk it from there.
KeyboardNavigation.SetTabNavigation(_keyboardPanel, KeyboardNavigationMode.Once);
var states = ComputeKeyStates();
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 14 };
row.Children.Add(BuildKeyBlock(KeyMap.MainBlock, states));
row.Children.Add(BuildKeyBlock(KeyMap.NavBlock, states));
row.Children.Add(BuildKeyBlock(KeyMap.NumpadBlock, states));
row.Children.Add(BuildKeyBlock(KeyMap.MainBlock, states, 0));
row.Children.Add(BuildKeyBlock(KeyMap.NavBlock, states, 1));
row.Children.Add(BuildKeyBlock(KeyMap.NumpadBlock, states, 2));
_keyboardPanel.Children.Add(row);
}
@@ -372,24 +429,27 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
content.Children.RemoveAt(0);
content.Children.Insert(0, BuildKeyBackground(token, states));
states.TryGetValue(token, out var state);
ToolTip.SetTip(content, BuildKeyTooltip(token, state));
string tip = BuildKeyTooltip(token, state);
ToolTip.SetTip(content, tip);
if (content.Parent is Border cap)
NameCap(cap, tip);
}
}
private Control BuildKeyBlock(KeyCap[][] rows, Dictionary<string, KeyState> states)
private StackPanel BuildKeyBlock(KeyCap[][] rows, Dictionary<string, KeyState> states, int blockIndex)
{
var block = new StackPanel { Spacing = KeyGap, VerticalAlignment = VerticalAlignment.Top };
foreach (var rowCaps in rows)
for (int r = 0; r < rows.Length; r++)
{
var rowPanel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = KeyGap };
foreach (var cap in rowCaps)
rowPanel.Children.Add(BuildKeyCap(cap, states));
foreach (var cap in rows[r])
rowPanel.Children.Add(BuildKeyCap(cap, states, blockIndex, r));
block.Children.Add(rowPanel);
}
return block;
}
private Control BuildKeyCap(KeyCap cap, Dictionary<string, KeyState> states)
private Border BuildKeyCap(KeyCap cap, Dictionary<string, KeyState> states, int blockIndex, int rowIndex)
{
double width = cap.Width * KeyUnit + (cap.Width - 1) * KeyGap;
var content = new Grid { Width = width, Height = KeyHeight };
@@ -438,14 +498,84 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
});
ToolTip.SetTip(content, BuildKeyTooltip(token, st));
string tip = BuildKeyTooltip(token, st);
ToolTip.SetTip(content, tip);
keyBorder.Cursor = new Cursor(StandardCursorType.Hand);
keyBorder.PointerPressed += (_, _) => ShowKeyFlyout(token, keyBorder);
// Reached and opened from the keyboard as well, and read as the button it is.
keyBorder.Focusable = true;
keyBorder.Classes.Add("KeyCap");
AutomationProperties.SetControlTypeOverride(keyBorder, AutomationControlType.Button);
AutomationProperties.SetIsControlElementOverride(keyBorder, true);
NameCap(keyBorder, tip);
keyBorder.KeyDown += (_, e) => OnCapKey(keyBorder, token, e);
// The ring the theme gives focus, drawn here: the key clips anything outside it.
keyBorder.GotFocus += (_, _) => keyBorder.BorderBrush = KeyFocusBrush;
keyBorder.LostFocus += (_, _) => keyBorder.BorderBrush = KeyBorderBrush;
_caps.Add((keyBorder, blockIndex, rowIndex));
_keyCells[token] = content;
return keyBorder;
}
// The tooltip says the key and what is on it, one thing a line; read as one sentence.
private static void NameCap(Border cap, string tip) =>
AutomationProperties.SetName(cap, tip.Replace("\n", ", "));
private void OnCapKey(Border cap, string token, KeyEventArgs e)
{
int at = _caps.FindIndex(c => ReferenceEquals(c.Cap, cap));
if (at < 0)
return;
if (e.Key is Key.Enter or Key.Space)
{
ShowKeyFlyout(token, cap);
e.Handled = true;
return;
}
Border? next;
switch (e.Key)
{
case Key.Left: next = at > 0 ? _caps[at - 1].Cap : null; break;
case Key.Right: next = at < _caps.Count - 1 ? _caps[at + 1].Cap : null; break;
case Key.Home: next = _caps[0].Cap; break;
case Key.End: next = _caps[^1].Cap; break;
case Key.Up: next = CapNextRow(at, -1); break;
case Key.Down: next = CapNextRow(at, 1); break;
default: return;
}
next?.Focus(NavigationMethod.Directional);
e.Handled = true;
}
/// <summary>The key in the next row up or down of the same block that lies nearest over or under this one.</summary>
private Border? CapNextRow(int at, int step)
{
var (cap, block, row) = _caps[at];
if (_keyboardPanel is null || cap.TranslatePoint(new Point(cap.Bounds.Width / 2, 0), _keyboardPanel) is not { } from)
return null;
Border? best = null;
double nearest = double.MaxValue;
foreach (var (other, otherBlock, otherRow) in _caps)
{
if (otherBlock != block || otherRow != row + step
|| other.TranslatePoint(new Point(other.Bounds.Width / 2, 0), _keyboardPanel) is not { } to)
continue;
double distance = Math.Abs(to.X - from.X);
if (distance < nearest)
{
nearest = distance;
best = other;
}
}
return best;
}
private Control BuildKeyBackground(string token, Dictionary<string, KeyState> states)
{
states.TryGetValue(token.ToLowerInvariant(), out var state);
@@ -545,6 +675,8 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search)
Margin = new Thickness(0, 4),
HorizontalAlignment = HorizontalAlignment.Stretch
};
// Its label is a swatch and a text in a panel, which a reader does not take for one.
AutomationProperties.SetName(cb, KeyMap.ComboText(token, shift, ctrl));
if (KeyMap.SimulatorUse(token, shift, ctrl) is { } use)
{
ToolTip.SetTip(cb, SimulatorUseText(token, shift, ctrl, use));

View File

@@ -34,6 +34,7 @@ public sealed class LogAndToolsWindow : Window
WindowStartupLocation = WindowStartupLocation.CenterOwner;
var tabs = new TabControl();
Avalonia.Automation.AutomationProperties.SetName(tabs, App.Loc["LogAndTools"]);
tabs.Items.Add(new TabItem { Header = App.Loc["AdvLogPage"], Content = BuildLogPage() });
tabs.Items.Add(new TabItem { Header = App.Loc["Tools"], Content = BuildToolsPage() });
@@ -47,6 +48,7 @@ public sealed class LogAndToolsWindow : Window
};
close.Classes.Add("Accent");
close.Click += (_, _) => Close();
close.IsCancel = true;
var root = new DockPanel { Margin = new Avalonia.Thickness(10) };
DockPanel.SetDock(close, Dock.Bottom);

View File

@@ -15,6 +15,18 @@ internal static class MenuItems
return item;
}
/// <summary>
/// One of a set of entries of which one is chosen, marked as a radio entry. A dot
/// written before the text was read out as "black circle" and told no state.
/// </summary>
public static MenuItem Choice(string header, bool chosen, Action run)
{
var item = Item(header, run);
item.ToggleType = MenuItemToggleType.Radio;
item.IsChecked = chosen;
return item;
}
/// <summary>The entry at the end of a menu or a submenu.</summary>
public static MenuItem AddItem(this ItemsControl menu, object header, Action run, bool enabled = true,
KeyGesture? gesture = null)

View File

@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
@@ -26,6 +27,13 @@ public static class MessageBox
"Accent", 80, () => { yes = true; win.Close(); });
var noBtn = DialogButton(noText ?? App.Loc["No"], "Flat", 80, () => win.Close());
noBtn.IsVisible = buttons != MessageBoxButtons.Ok;
// Enter answers, Esc declines - or only closes, where OK is all there is.
yesBtn.IsDefault = true;
if (buttons == MessageBoxButtons.Ok)
yesBtn.IsCancel = true;
else
noBtn.IsCancel = true;
ReadMessage(win, yesBtn, message);
win.Content = new StackPanel
{
@@ -56,6 +64,9 @@ public static class MessageBox
var okBtn = DialogButton(App.Loc["Ok"], "Flat", 80, () => win.Close());
var silence = new CheckBox { Content = silenceText, VerticalAlignment = VerticalAlignment.Center };
actBtn.IsDefault = true;
okBtn.IsCancel = true;
ReadMessage(win, actBtn, message);
win.Content = new StackPanel
{
@@ -79,6 +90,16 @@ public static class MessageBox
return (act, silence.IsChecked == true);
}
/// <summary>
/// The message is told with the window and with the button focus opens on: a
/// screen reader said only the title, and the question it asked went unheard.
/// </summary>
internal static void ReadMessage(Window win, Control first, string message)
{
AutomationProperties.SetHelpText(win, message);
AutomationProperties.SetHelpText(first, message);
}
/// <summary>A dialog over its owner, as tall as what it holds, not to be resized.</summary>
internal static Window FixedDialog(string title, double width) => new()
{

View File

@@ -80,6 +80,7 @@ public sealed class RulesWindow : Window
};
cancel.Classes.Add("Flat");
cancel.Click += (_, _) => Close();
cancel.IsCancel = true;
var footer = new StackPanel
{

View File

@@ -4,6 +4,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:starterNg="clr-namespace:StarterNG"
xmlns:infra="clr-namespace:StarterNG.Infrastructure"
xmlns:ctl="clr-namespace:StarterNG.Controls"
xmlns:materialIcons="clr-namespace:Material.Icons.Avalonia;assembly=Material.Icons.Avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="StarterNG.Views.Scenarios"
@@ -33,6 +34,7 @@
IsCheckedChanged="ArchivalSwitch_OnChanged"
Content="{Binding [HideArchivalSceneries], Source={x:Static starterNg:App.Loc}}" />
<TreeView Name="sceneryList" Classes="Compact"
AutomationProperties.Name="{Binding [Sceneries], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="SceneryList_OnSelectionChanged"
ContextRequested="SceneryList_OnContextRequested">
<TreeView.ContextMenu>
@@ -49,7 +51,7 @@
</DockPanel>
</HeaderedContentControl>
<GridSplitter Grid.Column="1" Grid.Row="0" Width="6"
<GridSplitter IsTabStop="False" AutomationProperties.Name="{Binding [PanelSplitter], Source={x:Static starterNg:App.Loc}}" Grid.Column="1" Grid.Row="0" Width="6"
Background="Transparent" ResizeDirection="Columns" />
<Grid Grid.Column="2" Grid.Row="0">
@@ -70,13 +72,14 @@
</HeaderedContentControl.Tag>
<ListBox Name="vehicleList" Classes="Compact"
AutomationProperties.Name="{Binding [SceneryConsists], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="VehicleList_OnSelectionChanged" />
</HeaderedContentControl>
<GridSplitter Grid.Row="1" Height="4" HorizontalAlignment="Stretch"
<GridSplitter IsTabStop="False" AutomationProperties.Name="{Binding [PanelSplitter], Source={x:Static starterNg:App.Loc}}" Grid.Row="1" Height="4" HorizontalAlignment="Stretch"
Background="Transparent" ResizeDirection="Rows" />
<TabControl Grid.Row="2" Name="infoTabs">
<TabControl Grid.Row="2" Name="infoTabs" AutomationProperties.Name="{Binding [ScenarioDetails], Source={x:Static starterNg:App.Loc}}">
<TabItem Header="{Binding [TabDescription], Source={x:Static starterNg:App.Loc}}">
<Grid RowDefinitions="2*,6,*" Margin="4">
<Grid Grid.Row="0" ColumnDefinitions="*,3,225">
@@ -108,11 +111,11 @@
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Date], Source={x:Static starterNg:App.Loc}}" />
<Grid Grid.Row="0" Grid.Column="2" ColumnDefinitions="150,10,150,10,*">
<DatePicker Grid.Column="0" Name="weatherDate"
<DatePicker Grid.Column="0" Name="weatherDate" AutomationProperties.Name="{Binding [Date], Source={x:Static starterNg:App.Loc}}"
YearVisible="False" MinWidth="0"
VerticalAlignment="Center" HorizontalAlignment="Stretch"
SelectedDateChanged="WeatherDate_OnChanged" />
<ComboBox Grid.Column="2" Name="weatherSeason" Classes="Localized"
<ComboBox Grid.Column="2" Name="weatherSeason" AutomationProperties.Name="{Binding [Season], Source={x:Static starterNg:App.Loc}}" Classes="Localized"
HorizontalAlignment="Stretch" VerticalAlignment="Center"
SelectionChanged="WeatherSeason_OnChanged">
<ComboBoxItem Tag="0" Content="{Binding [SeasonNow], Source={x:Static starterNg:App.Loc}}" />
@@ -130,7 +133,7 @@
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Time], Source={x:Static starterNg:App.Loc}}" />
<Grid Grid.Row="2" Grid.Column="2" ColumnDefinitions="150,8,*">
<TimePicker Grid.Column="0" Name="weatherTime"
<TimePicker Grid.Column="0" Name="weatherTime" AutomationProperties.Name="{Binding [Time], Source={x:Static starterNg:App.Loc}}"
ClockIdentifier="24HourClock" MinuteIncrement="1"
MinWidth="0" VerticalAlignment="Center"
HorizontalAlignment="Stretch"
@@ -145,7 +148,7 @@
<TextBlock Grid.Row="4" Grid.Column="0" VerticalAlignment="Center"
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Temperature], Source={x:Static starterNg:App.Loc}}" />
<Slider Grid.Row="4" Grid.Column="2" Name="weatherTemp"
<ctl:ReadableSlider Grid.Row="4" Grid.Column="2" Name="weatherTemp" AutomationProperties.Name="{Binding [Temperature], Source={x:Static starterNg:App.Loc}}"
Minimum="-50" Maximum="50"
TickFrequency="1" IsSnapToTickEnabled="True"
ValueChanged="Weather_OnSliderChanged" />
@@ -162,8 +165,8 @@
<TextBlock Grid.Row="7" Grid.Column="0" VerticalAlignment="Center"
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Visibility], Source={x:Static starterNg:App.Loc}}" />
<Slider Grid.Row="7" Grid.Column="2" Name="weatherFog"
Minimum="0" Maximum="1000"
<ctl:ReadableSlider Grid.Row="7" Grid.Column="2" Name="weatherFog" AutomationProperties.Name="{Binding [Visibility], Source={x:Static starterNg:App.Loc}}"
Minimum="0" Maximum="1000" SmallChange="20" LargeChange="100"
TickFrequency="1" IsSnapToTickEnabled="True"
ValueChanged="Weather_OnSliderChanged" />
<TextBlock Grid.Row="7" Grid.Column="4" Name="weatherFogLabel"
@@ -180,7 +183,7 @@
<TextBlock Grid.Row="10" Grid.Column="0" VerticalAlignment="Center"
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Overcast], Source={x:Static starterNg:App.Loc}}" />
<ComboBox Grid.Row="10" Grid.Column="2" Name="weatherOvercast" Classes="Localized"
<ComboBox Grid.Row="10" Grid.Column="2" Name="weatherOvercast" AutomationProperties.Name="{Binding [Overcast], Source={x:Static starterNg:App.Loc}}" Classes="Localized"
HorizontalAlignment="Stretch"
SelectionChanged="Weather_OnSelectionChanged">
<ComboBoxItem Tag="random" Content="{Binding [OvercastRandom], Source={x:Static starterNg:App.Loc}}" />

View File

@@ -8,6 +8,7 @@ using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Animation;
using Avalonia.Controls;
using Avalonia.Input;
@@ -17,6 +18,7 @@ using Avalonia.Media.Imaging;
using Avalonia.Threading;
using Avalonia.VisualTree;
using StarterNG.Classes;
using StarterNG.Controls;
using StarterNG.Domain;
using StarterNG.Application;
using StarterNG.Domain.Sceneries;
@@ -99,9 +101,9 @@ public partial class Scenarios : UserControl
sceneryList.Items.Add(ToTreeItem(node, expandGroups));
}
private TreeViewItem ToTreeItem(SceneryTreeNode node, bool expandGroups)
private ExpandableTreeViewItem ToTreeItem(SceneryTreeNode node, bool expandGroups)
{
var item = new TreeViewItem
var item = new ExpandableTreeViewItem
{
Header = node.IsGroup ? node.Label : SceneryHeader(node.Label, Sceneries[node.SceneryIndex]),
Tag = node.IsGroup ? null : node.SceneryIndex,
@@ -409,6 +411,8 @@ public partial class Scenarios : UserControl
sceneryDescription.Text = scenery.LocalizedDescription(AppServices.Current.SceneryTexts);
string? imagePath = AppServices.Current.SceneryImages.Resolve(scenery);
// Under the mouse a reader hears what the picture is of.
AutomationProperties.SetName(sceneryImage, $"{App.Loc["SceneryImage"]}: {scenery.Name}");
if (imagePath is not null)
{
try
@@ -492,20 +496,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 });
@@ -761,6 +763,8 @@ public partial class Scenarios : UserControl
{
weatherTempLabel.Text = $"{(int)weatherTemp.Value} °C";
weatherFogLabel.Text = FogScale2(FogScale.ToMetres(weatherFog.Value));
weatherTemp.ValueText = weatherTempLabel.Text;
weatherFog.ValueText = weatherFogLabel.Text;
weatherDayDate.Text = string.Format(LanguageCulture, App.Loc["DayOfYear"], SelectedDayOfYear());
weatherRestore.IsEnabled = _currentScenery?.Weather.Changed ?? false;
@@ -833,6 +837,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)
@@ -840,8 +845,18 @@ public partial class Scenarios : UserControl
if (_currentScenery is null) return;
_currentScenery.Weather.Restore();
ShowWeather(_currentScenery);
Announcer.Say(this, WeatherSummary());
}
/// <summary>The weather as a reader hears it once put back: every field and its value.</summary>
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))

View File

@@ -22,7 +22,7 @@
TextTrimming="LeadingCharacterEllipsis" />
</DockPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="12" HorizontalAlignment="Right">
<TextBlock x:Name="SaveStatus" VerticalAlignment="Center" Opacity="0.8" Text="" />
<TextBlock x:Name="SaveStatus" ctl:Announcer.Changes="True" VerticalAlignment="Center" Opacity="0.8" Text="" />
<Button x:Name="ChangesButton" Classes="Flat" Click="ChangesButton_OnClick"
Content="{Binding [IniChangesButton], Source={x:Static starterNg:App.Loc}}" />
<Button x:Name="ResetButton" Classes="Flat" Click="ResetButton_OnClick"
@@ -40,14 +40,15 @@
<Border Grid.Column="0" Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}" BorderThickness="0,0,1,0">
<DockPanel Margin="8,10,8,10">
<TextBox x:Name="SettingsSearch" DockPanel.Dock="Top" Margin="0,0,0,10"
<TextBox x:Name="SettingsSearch" AutomationProperties.LandmarkType="Search" DockPanel.Dock="Top" Margin="0,0,0,10"
PlaceholderText="{Binding [Search], Source={x:Static starterNg:App.Loc}}"
TextChanged="SettingsSearch_OnTextChanged" />
<StackPanel DockPanel.Dock="Bottom" Spacing="6" Margin="0,14,0,0">
<TextBlock Classes="FieldLabel"
Text="{Binding [SettingsProfile], Source={x:Static starterNg:App.Loc}}" />
<ComboBox x:Name="ProfileCb" HorizontalAlignment="Stretch" />
<ComboBox x:Name="ProfileCb" HorizontalAlignment="Stretch"
AutomationProperties.Name="{Binding [ProfilePick], Source={x:Static starterNg:App.Loc}}" />
<Button x:Name="ProfileApplyBtn" Classes="Flat" HorizontalAlignment="Stretch"
HorizontalContentAlignment="Center"
Content="{Binding [ProfileApply], Source={x:Static starterNg:App.Loc}}"
@@ -68,7 +69,7 @@
Click="ExportIniButton_OnClick" />
</StackPanel>
<ListBox x:Name="CategoryList" Classes="SettingsNav" SelectedIndex="0"
<ListBox x:Name="CategoryList" AutomationProperties.LandmarkType="Navigation" AutomationProperties.Name="{Binding [SettingsCategories], Source={x:Static starterNg:App.Loc}}" Classes="SettingsNav" SelectedIndex="0"
ItemContainerTheme="{StaticResource SettingsNavItem}"
SelectionChanged="CategoryList_OnSelectionChanged">
<ListBoxItem Tag="general" Content="{Binding [General], Source={x:Static starterNg:App.Loc}}" />
@@ -93,7 +94,7 @@
<TextBlock VerticalAlignment="Center" FontWeight="Bold"
Text="{Binding [GfxColPresets], Source={x:Static starterNg:App.Loc}}" />
<StackPanel x:Name="PresetButtons" Grid.Column="1" Orientation="Horizontal" Spacing="6" />
<TextBlock x:Name="PresetStateText" Grid.Column="2" VerticalAlignment="Center" FontSize="12"
<TextBlock x:Name="PresetStateText" ctl:Announcer.Changes="True" Grid.Column="2" VerticalAlignment="Center" FontSize="12"
Foreground="{StaticResource CarbonFgDim}" />
</Grid>
<Grid ColumnDefinitions="Auto,*" ColumnSpacing="10">
@@ -141,7 +142,7 @@
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="mousescale" x:Name="CursorSensitivityRow"
Label="{Binding [CursorSensitivity], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="CursorSensitivitySlider" Minimum="1" Maximum="5" TickFrequency="1"
<ctl:ReadableSlider x:Name="CursorSensitivitySlider" Minimum="1" Maximum="5" TickFrequency="1"
IsSnapToTickEnabled="True" Value="3"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
@@ -258,13 +259,13 @@
Label="{Binding [BufforResolution], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [BufforResolutionDesc], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #bufferScale.Value, StringFormat='{}{0:0}%'}">
<Slider Name="bufferScale" Minimum="25" Maximum="200" TickFrequency="1"
<ctl:ReadableSlider Name="bufferScale" Minimum="25" Maximum="200" TickFrequency="1"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="fieldofview" Label="{Binding [FieldOfView], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [FieldOfViewDesc], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #fovSlider.Value, StringFormat='{}{0:0}°'}">
<Slider Name="fovSlider" Minimum="10" Maximum="75" TickFrequency="5"
<ctl:ReadableSlider Name="fovSlider" Minimum="10" Maximum="75" TickFrequency="5"
IsSnapToTickEnabled="True" Value="45" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="gfx.antialiasing, multisampling"
@@ -296,7 +297,7 @@
Description="{Binding [FpsLimitDesc], Source={x:Static starterNg:App.Loc}}">
<StackPanel Spacing="4">
<!-- Moves through no limit and Steps.FrameRateLimits; see SliderSteps. -->
<Slider x:Name="FpsLimitSlider" ValueChanged="QualitySlider_OnValueChanged" />
<ctl:ReadableSlider x:Name="FpsLimitSlider" ValueChanged="QualitySlider_OnValueChanged" />
<!-- The screens found, each with a button to match the limit to it. -->
<WrapPanel x:Name="MonitorRates" IsVisible="False" />
</StackPanel>
@@ -312,14 +313,14 @@
Label="{Binding [RenderRange], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [RenderRangeDesc], Source={x:Static starterNg:App.Loc}}">
<!-- Moves through Steps.DrawRangeFactors; see SliderSteps. -->
<Slider x:Name="RenderRangeSlider"
<ctl:ReadableSlider x:Name="RenderRangeSlider"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:KeySlot Key="sleeperdistance" />
<ctl:SettingRow ConfigKey="splinefidelity" x:Name="TrackCurvesRow"
Label="{Binding [TrackCurvesQuality], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [TrackCurvesQualityDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="TrackCurvesSlider" Minimum="1" Maximum="4" TickFrequency="1"
<ctl:ReadableSlider x:Name="TrackCurvesSlider" Minimum="1" Maximum="4" TickFrequency="1"
IsSnapToTickEnabled="True" Value="4"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
@@ -330,13 +331,13 @@
<StackPanel>
<ctl:SettingRow ConfigKey="maxtexturesize" x:Name="TexResolutionRow"
Label="{Binding [MaxTexResolution], Source={x:Static starterNg:App.Loc}}">
<Slider Name="textureResolutionSlider" Minimum="6" Maximum="13" TickFrequency="1"
<ctl:ReadableSlider Name="textureResolutionSlider" Minimum="6" Maximum="13" TickFrequency="1"
IsSnapToTickEnabled="True" Value="12"
ValueChanged="TextureResolutionSlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="maxcabtexturesize" x:Name="CabTexResolutionRow"
Label="{Binding [MaxTexCabResolution], Source={x:Static starterNg:App.Loc}}">
<Slider Name="cabTextureResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
<ctl:ReadableSlider Name="cabTextureResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
IsSnapToTickEnabled="True" Value="12"
ValueChanged="CabTextureResolutionSlider_OnValueChanged" />
</ctl:SettingRow>
@@ -344,7 +345,7 @@
Label="{Binding [TexFilteringQuality], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [TexFilteringQualityDesc], Source={x:Static starterNg:App.Loc}}">
<!-- Moves through Steps.Anisotropy; see SliderSteps. -->
<Slider x:Name="TexFilteringSlider"
<ctl:ReadableSlider x:Name="TexFilteringSlider"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:KeySlot Key="gfx.textures.streaming" />
@@ -397,7 +398,7 @@
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="shadowtune" x:Name="ShadowResolutionRow"
Label="{Binding [ShadowsResolution], Source={x:Static starterNg:App.Loc}}">
<Slider Name="shaderResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
<ctl:ReadableSlider Name="shaderResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
IsSnapToTickEnabled="True" Value="12"
ValueChanged="shaderResolutionSlider_OnValueChanged" />
</ctl:SettingRow>
@@ -405,14 +406,14 @@
Label="{Binding [ShaderRange], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [ShaderRangeDesc], Source={x:Static starterNg:App.Loc}}">
<!-- The simulator's floor follows the map size: see shaderResolutionSlider_OnValueChanged. -->
<Slider Name="shaderRange" Minimum="75" Maximum="600" TickFrequency="5"
<ctl:ReadableSlider Name="shaderRange" Minimum="75" Maximum="600" TickFrequency="5"
IsSnapToTickEnabled="True" Value="150"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="gfx.shadows.cab.range" x:Name="CabShadowRangeRow"
Label="{Binding [CabShadowsRange], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [CabShadowsRangeDesc], Source={x:Static starterNg:App.Loc}}">
<Slider Name="cabShaderSourceRange" Minimum="0" Maximum="100" TickFrequency="10"
<ctl:ReadableSlider Name="cabShaderSourceRange" Minimum="0" Maximum="100" TickFrequency="10"
IsSnapToTickEnabled="True" Value="30"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
@@ -420,7 +421,7 @@
Label="{Binding [ShadowAngleLimit], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [ShadowAngleLimitDesc], Source={x:Static starterNg:App.Loc}}">
<StackPanel>
<Slider x:Name="ShadowAngleLimitSlider" Minimum="0.2" Maximum="1.0"
<ctl:ReadableSlider x:Name="ShadowAngleLimitSlider" Minimum="0.2" Maximum="1.0"
TickFrequency="0.05" IsSnapToTickEnabled="True" Value="0.2" HorizontalAlignment="Stretch"
ValueChanged="QualitySlider_OnValueChanged" />
<DockPanel>
@@ -438,7 +439,7 @@
<StackPanel>
<ctl:SettingRow x:Name="DynamicLightsRow" Description="{Binding [DynamicLightsDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="dynamiclights" Label="{Binding [DynamicLights], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #DynamicLightsSlider.Value, StringFormat='{}{0:0}'}">
<Slider x:Name="DynamicLightsSlider" Minimum="0" Maximum="7" TickFrequency="1"
<ctl:ReadableSlider x:Name="DynamicLightsSlider" Minimum="0" Maximum="7" TickFrequency="1"
IsSnapToTickEnabled="True" Value="7" />
</ctl:SettingRow>
</StackPanel>
@@ -462,7 +463,7 @@
Label="{Binding [ReflectionsFramerate], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [ReflectionsFramerateDesc], Source={x:Static starterNg:App.Loc}}">
<!-- Moves through Steps.ReflectionUpdates; see SliderSteps. -->
<Slider Name="reflectionsFramerate"
<ctl:ReadableSlider Name="reflectionsFramerate"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:KeySlot Key="gfx.reflections.range_instances" />
@@ -491,7 +492,7 @@
<ctl:SettingRow ConfigKey="gfx.smoke.fidelity" x:Name="SmokeParticlesRow"
Label="{Binding [SmokeParticlesMultiplier], Source={x:Static starterNg:App.Loc}}"
IsEnabled="{Binding #SmokeDisplayCb.IsChecked}">
<Slider x:Name="SmokeParticlesSlider" Minimum="1" Maximum="4" TickFrequency="1"
<ctl:ReadableSlider x:Name="SmokeParticlesSlider" Minimum="1" Maximum="4" TickFrequency="1"
IsSnapToTickEnabled="True" Value="2"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
@@ -511,27 +512,27 @@
<StackPanel IsEnabled="{Binding #EnableSoundsCb.IsChecked}">
<ctl:SettingRow ConfigKey="sound.volume" Label="{Binding [Volume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #VolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="VolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="VolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="sound.volume.radio" Label="{Binding [RadiophoneVolume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #RadioVolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="RadioVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="RadioVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="sound.volume.vehicle" Label="{Binding [VehiclesVolume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #VehiclesVolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="VehiclesVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="VehiclesVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="sound.volume.positional" Label="{Binding [PositionedSoundsVolume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #PositionalVolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="PositionalVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="PositionalVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="sound.volume.ambient" Label="{Binding [AmbientVolume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #AmbientVolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="AmbientVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="AmbientVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
</StackPanel>
@@ -574,17 +575,17 @@
<ctl:SettingRow ConfigKey="friction" x:Name="FrictionRow" Label="{Binding [Friction], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [FrictionDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="FrictionSlider" Minimum="0.1" Maximum="3.0" TickFrequency="0.1" Value="1.0"
<ctl:ReadableSlider x:Name="FrictionSlider" Minimum="0.1" Maximum="3.0" TickFrequency="0.1" Value="1.0"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="brakestep" x:Name="BrakeStepRow" Label="{Binding [BrakeStep], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [BrakeStepDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="BrakeStepSlider" Minimum="0.4" Maximum="3.0" TickFrequency="0.1" Value="1.0"
<ctl:ReadableSlider x:Name="BrakeStepSlider" Minimum="0.4" Maximum="3.0" TickFrequency="0.1" Value="1.0"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="brakespeed" x:Name="BrakeSpeedRow" Label="{Binding [BrakeSpeed], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [BrakeSpeedDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="BrakeSpeedSlider" Minimum="0.4" Maximum="3.0" TickFrequency="0.1" Value="1.0"
<ctl:ReadableSlider x:Name="BrakeSpeedSlider" Minimum="0.4" Maximum="3.0" TickFrequency="0.1" Value="1.0"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
</StackPanel>
@@ -699,7 +700,7 @@
<ctl:SettingRow ConfigKey="async.trainThreads" x:Name="TrainThreadsRow"
Label="{Binding [TrainPhysicsThreads], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [TrainPhysicsThreadsDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="TrainThreadsSlider" Minimum="0" Maximum="16" TickFrequency="1"
<ctl:ReadableSlider x:Name="TrainThreadsSlider" Minimum="0" Maximum="16" TickFrequency="1"
IsSnapToTickEnabled="True" ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="starter.ignoreirrelevant" Description="{Binding [IgnoreIrrelevantTrainsDesc], Source={x:Static starterNg:App.Loc}}">
@@ -774,7 +775,7 @@
<ctl:SettingRow x:Name="RayTracingRangeRow" ConfigKey="gfx.raytracing.range"
Label="{Binding [RayTracingRange], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #RayTracingRangeSlider.Value, StringFormat='{}{0:0} m'}">
<Slider x:Name="RayTracingRangeSlider" Minimum="50" Maximum="2000" TickFrequency="50" IsSnapToTickEnabled="True" Value="500" />
<ctl:ReadableSlider x:Name="RayTracingRangeSlider" Minimum="50" Maximum="2000" TickFrequency="50" IsSnapToTickEnabled="True" Value="500" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="gfx.ssr" Label="{Binding [Ssr], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [SsrDesc], Source={x:Static starterNg:App.Loc}}">
@@ -851,7 +852,7 @@
Label="{Binding [CabProbeBounce], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [CabProbeBounceDesc], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #CabProbeBounceSlider.Value, StringFormat='{}{0:0.0}'}">
<Slider x:Name="CabProbeBounceSlider" Minimum="0" Maximum="4" TickFrequency="0.1" IsSnapToTickEnabled="True" Value="1" />
<ctl:ReadableSlider x:Name="CabProbeBounceSlider" Minimum="0" Maximum="4" TickFrequency="0.1" IsSnapToTickEnabled="True" Value="1" />
</ctl:SettingRow>
<ctl:SettingRow x:Name="CabProbeReflectionsRow" ConfigKey="gfx.cabprobe.reflections" Description="{Binding [CabProbeReflectionsDesc], Source={x:Static starterNg:App.Loc}}">
<CheckBox x:Name="CabProbeReflectionsCb" Content="{Binding [CabProbeReflections], Source={x:Static starterNg:App.Loc}}" />
@@ -892,12 +893,12 @@
<ctl:SettingRow x:Name="GrassDistanceRow" ConfigKey="gfx.grass.distance, gfx.grass.fadedistance"
Label="{Binding [GrassDistance], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #GrassDistanceSlider.Value, StringFormat='{}{0:0} m'}">
<Slider x:Name="GrassDistanceSlider" Minimum="20" Maximum="300" TickFrequency="10" IsSnapToTickEnabled="True" Value="60" />
<ctl:ReadableSlider x:Name="GrassDistanceSlider" Minimum="20" Maximum="300" TickFrequency="10" IsSnapToTickEnabled="True" Value="60" />
</ctl:SettingRow>
<ctl:SettingRow x:Name="GrassDensityRow" ConfigKey="gfx.grass.density"
Label="{Binding [GrassDensity], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #GrassDensitySlider.Value, StringFormat='{}{0:0.00}'}">
<Slider x:Name="GrassDensitySlider" Minimum="0.25" Maximum="2.0" TickFrequency="0.25" IsSnapToTickEnabled="True" Value="1.0" />
<ctl:ReadableSlider x:Name="GrassDensitySlider" Minimum="0.25" Maximum="2.0" TickFrequency="0.25" IsSnapToTickEnabled="True" Value="1.0" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="gfx.precipitation.particles" Label="{Binding [Precipitation], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [PrecipitationDesc], Source={x:Static starterNg:App.Loc}}">

Some files were not shown because too many files have changed in this diff Show More