mirror of
https://github.com/MaSzyna-EU07/StarterNG.git
synced 2026-11-17 22:15:59 +01:00
Compare commits
2 Commits
feat/audio
...
fix/linux-
| Author | SHA1 | Date | |
|---|---|---|---|
| 714cf335eb | |||
|
|
dee54a34bb |
@@ -24,13 +24,9 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
["LiveTip"] = "Reads what the simulator adds to the file every 2 seconds",
|
["LiveTip"] = "Reads what the simulator adds to the file every 2 seconds",
|
||||||
["Play"] = "Play",
|
["Play"] = "Play",
|
||||||
["Pause"] = "Pause",
|
["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",
|
["Follow"] = "Follow the train",
|
||||||
["Fit"] = "Whole map",
|
["Fit"] = "Whole map",
|
||||||
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the black box or the physics logs on.",
|
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the physics logs on.",
|
||||||
["Unreadable"] = "Can't read {0}: {1}",
|
["Unreadable"] = "Can't read {0}: {1}",
|
||||||
["Reading"] = "Reading {0}…",
|
["Reading"] = "Reading {0}…",
|
||||||
["Summary"] = "{0} · {1:0.0} km · max {2:0} km/h · driven {3} · autopilot {4} · over the AI {5} ({6} by more than {7:0} km/h, at most +{8:0} km/h) · signals {9} · at danger {10} · commands {11}",
|
["Summary"] = "{0} · {1:0.0} km · max {2:0} km/h · driven {3} · autopilot {4} · over the AI {5} ({6} by more than {7:0} km/h, at most +{8:0} km/h) · signals {9} · at danger {10} · commands {11}",
|
||||||
@@ -185,12 +181,8 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
["EventHornMissed"] = "W6: NO HORN",
|
["EventHornMissed"] = "W6: NO HORN",
|
||||||
["EventCab"] = "Cab {0} of {1}",
|
["EventCab"] = "Cab {0} of {1}",
|
||||||
["EventSecurityBraking"] = "BRAKING BY {0}",
|
["EventSecurityBraking"] = "BRAKING BY {0}",
|
||||||
["EventSecurityAlarm"] = "{0} buzzer",
|
|
||||||
["EventSecurityAlarmAcknowledged"] = "{0} buzzer, acknowledged after {1:0.0} s",
|
|
||||||
["EventSecurityAlarmMissed"] = "{0} buzzer, not acknowledged",
|
|
||||||
["EventTimetable"] = "Timetable {0}, {1}",
|
["EventTimetable"] = "Timetable {0}, {1}",
|
||||||
["CabSpeed"] = "Speed",
|
["CabSpeed"] = "Speed",
|
||||||
["CabWheels"] = "wheels {0:0}",
|
|
||||||
["CabAiTarget"] = "AI {0:0} km/h",
|
["CabAiTarget"] = "AI {0:0} km/h",
|
||||||
["CabAcceleration"] = "Along",
|
["CabAcceleration"] = "Along",
|
||||||
["CabLateral"] = "Lateral",
|
["CabLateral"] = "Lateral",
|
||||||
@@ -303,13 +295,9 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
["LiveTip"] = "Co 2 sekundy doczytuje to, co symulator dopisał do pliku",
|
["LiveTip"] = "Co 2 sekundy doczytuje to, co symulator dopisał do pliku",
|
||||||
["Play"] = "Odtwarzaj",
|
["Play"] = "Odtwarzaj",
|
||||||
["Pause"] = "Pauza",
|
["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",
|
["Follow"] = "Śledź pociąg",
|
||||||
["Fit"] = "Cała mapa",
|
["Fit"] = "Cała mapa",
|
||||||
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną przy włączonej czarnej skrzynce albo logach fizyki.",
|
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną razem z logami fizyki.",
|
||||||
["Unreadable"] = "Nie można odczytać {0}: {1}",
|
["Unreadable"] = "Nie można odczytać {0}: {1}",
|
||||||
["Reading"] = "Czytanie {0}…",
|
["Reading"] = "Czytanie {0}…",
|
||||||
["Summary"] = "{0} · {1:0.0} km · maks. {2:0} km/h · jazda {3} · autopilot {4} · ponad AI {5} (w tym {6} o więcej niż {7:0} km/h, najwyżej +{8:0} km/h) · sygnalizatory {9} · minięte na „Stój” {10} · komendy {11}",
|
["Summary"] = "{0} · {1:0.0} km · maks. {2:0} km/h · jazda {3} · autopilot {4} · ponad AI {5} (w tym {6} o więcej niż {7:0} km/h, najwyżej +{8:0} km/h) · sygnalizatory {9} · minięte na „Stój” {10} · komendy {11}",
|
||||||
@@ -464,12 +452,8 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
["EventHornMissed"] = "W6: BEZ TRĄBIENIA",
|
["EventHornMissed"] = "W6: BEZ TRĄBIENIA",
|
||||||
["EventCab"] = "Kabina {0} w {1}",
|
["EventCab"] = "Kabina {0} w {1}",
|
||||||
["EventSecurityBraking"] = "HAMOWANIE PRZEZ {0}",
|
["EventSecurityBraking"] = "HAMOWANIE PRZEZ {0}",
|
||||||
["EventSecurityAlarm"] = "Brzęczyk {0}",
|
|
||||||
["EventSecurityAlarmAcknowledged"] = "Brzęczyk {0}, potwierdzony po {1:0.0} s",
|
|
||||||
["EventSecurityAlarmMissed"] = "Brzęczyk {0}, bez potwierdzenia",
|
|
||||||
["EventTimetable"] = "Rozkład {0}, {1}",
|
["EventTimetable"] = "Rozkład {0}, {1}",
|
||||||
["CabSpeed"] = "Prędkość",
|
["CabSpeed"] = "Prędkość",
|
||||||
["CabWheels"] = "koła {0:0}",
|
|
||||||
["CabAiTarget"] = "AI {0:0} km/h",
|
["CabAiTarget"] = "AI {0:0} km/h",
|
||||||
["CabAcceleration"] = "Wzdłużne",
|
["CabAcceleration"] = "Wzdłużne",
|
||||||
["CabLateral"] = "Boczne",
|
["CabLateral"] = "Boczne",
|
||||||
@@ -572,11 +556,7 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
["FileFilter"] = "Czarna skrzynka"
|
["FileFilter"] = "Czarna skrzynka"
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>The key of the text of a simulator's command: <see cref="CommandPrefix"/> and its name.</summary>
|
|
||||||
public const string CommandPrefix = "Cmd.";
|
|
||||||
|
|
||||||
private readonly Dictionary<string, string> _texts;
|
private readonly Dictionary<string, string> _texts;
|
||||||
private readonly string _languageCode;
|
|
||||||
|
|
||||||
public DefaultBlackBoxStrings() : this(CultureInfo.CurrentUICulture)
|
public DefaultBlackBoxStrings() : this(CultureInfo.CurrentUICulture)
|
||||||
{
|
{
|
||||||
@@ -589,15 +569,11 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
|
|||||||
/// <summary>Polish for "pl", English for any other language.</summary>
|
/// <summary>Polish for "pl", English for any other language.</summary>
|
||||||
public DefaultBlackBoxStrings(string languageCode)
|
public DefaultBlackBoxStrings(string languageCode)
|
||||||
{
|
{
|
||||||
_languageCode = languageCode;
|
|
||||||
_texts = languageCode == "pl" ? Polish : English;
|
_texts = languageCode == "pl" ? Polish : English;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The keys there are texts for, for a translation to give them all.</summary>
|
/// <summary>The keys there are texts for, for a translation to give them all.</summary>
|
||||||
public static IEnumerable<string> Keys => English.Keys;
|
public static IEnumerable<string> Keys => English.Keys;
|
||||||
|
|
||||||
/// <summary>A key of <see cref="CommandPrefix"/> gives what the command does (<see cref="CommandTexts"/>).</summary>
|
public string this[string key] => _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key);
|
||||||
public string this[string key] =>
|
|
||||||
key.StartsWith(CommandPrefix, System.StringComparison.Ordinal) ? CommandTexts.Of(key[CommandPrefix.Length..], _languageCode)
|
|
||||||
: _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ using System.IO;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Automation;
|
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Layout;
|
using Avalonia.Layout;
|
||||||
using Avalonia.Media;
|
using Avalonia.Media;
|
||||||
@@ -107,13 +106,6 @@ public sealed class BlackBoxWindow : Window
|
|||||||
_play.Click += (_, _) => Playing = !Playing;
|
_play.Click += (_, _) => Playing = !Playing;
|
||||||
_speed.ItemsSource = Speeds.Select(s => $"×{s.ToString(CultureInfo.InvariantCulture)}").ToArray();
|
_speed.ItemsSource = Speeds.Select(s => $"×{s.ToString(CultureInfo.InvariantCulture)}").ToArray();
|
||||||
_speed.SelectedIndex = 3;
|
_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 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 } };
|
var transport = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { _play, _clock, _speed, _delayText } };
|
||||||
@@ -463,7 +455,6 @@ public sealed class BlackBoxWindow : Window
|
|||||||
_clock.Text = recording.ClockAt(_time).ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture);
|
_clock.Text = recording.ClockAt(_time).ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture);
|
||||||
_events.ShowTime(_time);
|
_events.ShowTime(_time);
|
||||||
ShowReadout(null);
|
ShowReadout(null);
|
||||||
_timeline.Spoken = _readout.Text;
|
|
||||||
ShowDelay(recording);
|
ShowDelay(recording);
|
||||||
TimeChanged?.Invoke(_time);
|
TimeChanged?.Invoke(_time);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,7 @@ using System.Collections.Generic;
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Automation.Peers;
|
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Input;
|
|
||||||
using Avalonia.Media;
|
using Avalonia.Media;
|
||||||
|
|
||||||
namespace Eu07.BlackBox.Views;
|
namespace Eu07.BlackBox.Views;
|
||||||
@@ -24,7 +22,6 @@ public sealed class CabPanel : Control
|
|||||||
private const double LampRow = 14;
|
private const double LampRow = 14;
|
||||||
private const int DoorColumns = 2;
|
private const int DoorColumns = 2;
|
||||||
private const double DriveRow = 34;
|
private const double DriveRow = 34;
|
||||||
private const double WheelsApartKmh = 1.0; // the wheels shown when they turn this much faster or slower
|
|
||||||
|
|
||||||
private Recording? _recording;
|
private Recording? _recording;
|
||||||
private double _time;
|
private double _time;
|
||||||
@@ -39,36 +36,6 @@ public sealed class CabPanel : Control
|
|||||||
{
|
{
|
||||||
ClipToBounds = true;
|
ClipToBounds = true;
|
||||||
Height = 696;
|
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();
|
public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings();
|
||||||
@@ -95,22 +62,6 @@ public sealed class CabPanel : Control
|
|||||||
}
|
}
|
||||||
|
|
||||||
public override void Render(DrawingContext context)
|
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;
|
var size = Bounds.Size;
|
||||||
double width = size.Width - 2 * Pad, right = size.Width - Pad;
|
double width = size.Width - 2 * Pad, right = size.Width - Pad;
|
||||||
@@ -119,161 +70,95 @@ public sealed class CabPanel : Control
|
|||||||
if (_recording is not { } recording || recording.CabAt(_time) is not { } s || _time - s.Time > 1.5)
|
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));
|
context.DrawText(MapView.Text(Strings["CabNoData"], Palette.DimText, 12), new Point(Pad, 40));
|
||||||
Say(Strings["CabNoData"]);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Measure(recording);
|
Measure(recording);
|
||||||
var culture = CultureInfo.CurrentCulture;
|
var culture = CultureInfo.CurrentCulture;
|
||||||
|
var extra = s.Extra;
|
||||||
|
|
||||||
DrawHeader(context, recording.Vehicle(s.Vehicle)?.Name ?? "", s, right);
|
// The vehicle at the left; who drives, from which cab, at the 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;
|
double chipX = right;
|
||||||
if (end is not null)
|
if (s.CabEnd != 0)
|
||||||
chipX -= ChipLeft(context, end, Palette.Text, chipX, 4) + 5;
|
chipX -= ChipLeft(context, Strings[s.CabEnd > 0 ? "CabEndFront" : "CabEndRear"], Palette.Text, chipX, 4) + 5;
|
||||||
var (driverText, driverBrush) = DriverChip(s);
|
var (driverText, driverBrush) = !s.InCab ? (Strings["CabOutside"], Palette.DimText)
|
||||||
|
: s.Driving == Driver.Ai ? (Strings["CabDriverAi"], Palette.Autopilot)
|
||||||
|
: (Strings["CabDriverUser"], Palette.UserTrain);
|
||||||
chipX -= ChipLeft(context, driverText, driverBrush, chipX, 4) + 10;
|
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)))
|
using (context.PushClip(new Rect(Pad, 0, Math.Max(0, chipX - Pad), 28)))
|
||||||
context.DrawText(MapView.Text(name, Palette.Text, 12, FontWeight.SemiBold), new Point(Pad, 6));
|
context.DrawText(MapView.Text(recording.Vehicle(s.Vehicle)?.Name ?? "", Palette.Text, 12, FontWeight.SemiBold), new Point(Pad, 6));
|
||||||
}
|
|
||||||
|
|
||||||
private (string Text, IBrush Brush) DriverChip(CabSample s)
|
// The speed, large, what the AI would do under it, the accelerations at the right.
|
||||||
{
|
var judgement = DrivingSummary.Judge(s);
|
||||||
if (!s.InCab)
|
var speed = MapView.Text(s.AbsSpeedKmh.ToString("0", culture), judgement is SpeedJudgement.Over ? Palette.Bad
|
||||||
return (Strings["CabOutside"], Palette.DimText);
|
: judgement is SpeedJudgement.Slightly ? Palette.Warn : Palette.Text, 36, FontWeight.SemiBold);
|
||||||
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));
|
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));
|
||||||
var unit = MapView.Text("km/h", Palette.DimText, 12);
|
|
||||||
context.DrawText(unit, new Point(Pad + speed.Width + 4, 24 + speed.Height - 21));
|
|
||||||
double gaugeX = Pad + Math.Max(150, width * 0.42);
|
double gaugeX = Pad + Math.Max(150, width * 0.42);
|
||||||
// the wheels, when they turn otherwise: slipping, or locked in a skid. Signed both, so wheels slipping ahead
|
|
||||||
// of a train rolling back show too. Kept off the gauges at the right, as the AI's line is.
|
|
||||||
if (s.WheelSpeedKmh is { } wheels && Math.Abs(wheels - s.SpeedKmh) >= WheelsApartKmh)
|
|
||||||
{
|
|
||||||
double wheelsX = Pad + speed.Width + 4 + unit.Width + 8;
|
|
||||||
string wheelsText = string.Format(culture, Strings["CabWheels"], Math.Abs(wheels));
|
|
||||||
using (context.PushClip(new Rect(wheelsX, 24, Math.Max(0, gaugeX - 8 - wheelsX), 40)))
|
|
||||||
context.DrawText(MapView.Text(wheelsText, Palette.Warn, 12), new Point(wheelsX, 24 + speed.Height - 21));
|
|
||||||
Say(wheelsText);
|
|
||||||
}
|
|
||||||
if (s.AiValid)
|
if (s.AiValid)
|
||||||
{
|
{
|
||||||
using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40)))
|
using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40)))
|
||||||
{
|
{
|
||||||
string target = string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh);
|
context.DrawText(MapView.Text(string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh), Palette.Target, 12), new Point(Pad, 76));
|
||||||
context.DrawText(MapView.Text(target, Palette.Target, 12), new Point(Pad, 76));
|
|
||||||
Say(target);
|
|
||||||
if (s.Ai.HasNextLimit)
|
if (s.Ai.HasNextLimit)
|
||||||
{
|
context.DrawText(MapView.Text(string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance), Palette.Limit, 11),
|
||||||
string limit = string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance);
|
new Point(Pad, 93));
|
||||||
Say(limit);
|
|
||||||
context.DrawText(MapView.Text(limit, Palette.Limit, 11), new Point(Pad, 93));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
double gaugeWidth = right - gaugeX;
|
double gaugeWidth = right - gaugeX;
|
||||||
Balance(context, Strings["CabAcceleration"], s.Acceleration, 1.5, gaugeX, 34, gaugeWidth);
|
Balance(context, Strings["CabAcceleration"], s.Acceleration, 1.5, gaugeX, 34, gaugeWidth);
|
||||||
Balance(context, Strings["CabLateral"], s.LateralAcceleration, 1.5, gaugeX, 70, gaugeWidth);
|
Balance(context, Strings["CabLateral"], s.LateralAcceleration, 1.5, gaugeX, 70, gaugeWidth);
|
||||||
}
|
|
||||||
|
|
||||||
private static IBrush SpeedBrush(SpeedJudgement judgement) => judgement switch
|
// The controllers.
|
||||||
{
|
|
||||||
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 top = Section(context, Strings["CabSectionControls"], Pad, 118, right);
|
||||||
double column = width / 4;
|
double column = width / 4;
|
||||||
Value(context, Strings["CabController"], s.MainController.ToString(culture), Pad, top);
|
Value(context, Strings["CabController"], s.MainController.ToString(culture), Pad, top);
|
||||||
Steps(context, s.MainController, _controllerTop, Pad, top + 34, column - 14);
|
Steps(context, s.MainController, _controllerTop, Pad, top + 34, column - 14);
|
||||||
if (s.Extra is { } handle && _integrated.Contains(s.Vehicle))
|
if (extra is { } handle && _integrated.Contains(s.Vehicle))
|
||||||
Value(context, Strings["CabIntegrated"], (handle.IntegratedController * 100).ToString("+0;−0;0", culture) + " %", Pad + column, top);
|
Value(context, Strings["CabIntegrated"], (handle.IntegratedController * 100).ToString("+0;−0;0", culture) + " %", Pad + column, top);
|
||||||
else
|
else
|
||||||
Value(context, Strings["CabShunt"], s.ScndController.ToString(culture), Pad + column, top);
|
Value(context, Strings["CabShunt"], s.ScndController.ToString(culture), Pad + column, top);
|
||||||
string reverser = s.Reverser switch { > 0 => "CabForward", < 0 => "CabBackward", _ => "CabNeutral" };
|
Value(context, Strings["CabReverser"], Strings[s.Reverser > 0 ? "CabForward" : s.Reverser < 0 ? "CabBackward" : "CabNeutral"], Pad + 2 * column, top);
|
||||||
Value(context, Strings["CabReverser"], Strings[reverser], Pad + 2 * column, top);
|
|
||||||
Value(context, Strings["CabTrainBrake"], s.TrainBrake.ToString("0.0", culture), Pad + 3 * column, top);
|
Value(context, Strings["CabTrainBrake"], s.TrainBrake.ToString("0.0", culture), Pad + 3 * column, top);
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>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.
|
||||||
/// <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? 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)))
|
? string.Format(culture, Strings["CabBrakeSetting"], string.Join(" · ", new[] { BrakeSetting(e.BrakeDelay), BrakeMode(e.BrakeMode) }.Where(t => t.Length > 0)))
|
||||||
: null;
|
: null;
|
||||||
double y = Section(context, Strings["CabSectionBrakes"], Pad, 180, right, setting);
|
top = Section(context, Strings["CabSectionBrakes"], Pad, 180, right, setting);
|
||||||
var gauges = new List<GaugeReading>
|
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)
|
||||||
{
|
{
|
||||||
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
|
||||||
};
|
Gauge(context, Strings["CabDriverValve"], x1.DriverValve, 6, null, $"{x1.DriverValve:0.00} bar", Palette.Target, Pad, y, width);
|
||||||
// what the driver's brake valve shows: its equalizing reservoir, the FV4a's time reservoir
|
y += gauge;
|
||||||
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));
|
|
||||||
|
|
||||||
for (int i = 0; i < gauges.Count; i++)
|
|
||||||
{
|
|
||||||
if (i > 0)
|
|
||||||
y += BrakeRow;
|
|
||||||
Gauge(context, gauges[i], Pad, y, width);
|
|
||||||
}
|
}
|
||||||
return y;
|
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);
|
||||||
|
|
||||||
private GaugeReading FeedPipe(CabSample s, CabExtra feed) => _feedPipe.Contains(s.Vehicle)
|
// The traction at the left, as fits what drives the vehicle; the lights of both ends of the train at the right.
|
||||||
? new(Strings["CabFeedPipe"], feed.FeedPipe, 10, null, $"{feed.FeedPipe:0.0} bar", Palette.Controller)
|
double half = Pad + width / 2;
|
||||||
: new(Strings["CabFeedPipe"], 0, 10, null, "—", Palette.Controller);
|
double driveTop = y + gauge + 4;
|
||||||
|
top = Section(context, Strings["CabSectionDrive"], Pad, driveTop, half - 10);
|
||||||
/// <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>
|
Section(context, Strings["CabLights"], half + 4, driveTop, right);
|
||||||
/// <param name="area">Left edge, top and width of the column; its height is not used.</param>
|
DrawDrive(context, s, top, half - 10 - Pad, culture);
|
||||||
private void DrawLights(DrawingContext context, CabSample s, Rect area, CultureInfo culture)
|
double row = top;
|
||||||
{
|
|
||||||
double half = area.X, right = area.Right, row = area.Y;
|
|
||||||
foreach (var (key, lights, equipped, required, isRight) in new[]
|
foreach (var (key, lights, equipped, required, isRight) in new[]
|
||||||
{
|
{
|
||||||
("CabLightsHead", s.LightsHead, s.EquippedHead, HeadCodes.RequiredHead(s), HeadCodes.HeadRight(s)),
|
("CabLightsHead", s.LightsHead, s.EquippedHead, HeadCodes.RequiredHead(s), HeadCodes.HeadRight(s)),
|
||||||
@@ -281,9 +166,14 @@ public sealed class CabPanel : Control
|
|||||||
})
|
})
|
||||||
{
|
{
|
||||||
DrawFace(context, lights, new Point(half + 4 + 17, row + 15));
|
DrawFace(context, lights, new Point(half + 4 + 17, row + 15));
|
||||||
string text = LightsText(HeadCodes.Of(lights), HeadCodes.NoLamps(equipped), required, isRight, culture);
|
// the end, and under it the signal it shows: green as it is to be (with the lamps the vehicle has),
|
||||||
IBrush brush = isRight switch { null => Palette.DimText, true => Palette.Good, false => Palette.Bad };
|
// red otherwise with the one it is to show
|
||||||
Say($"{Strings[key]}: {text}");
|
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;
|
||||||
using (context.PushClip(new Rect(half + 44, row, right - half - 44, 28)))
|
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));
|
context.DrawText(MapView.Text(Strings[key], Palette.DimText, 10), new Point(half + 46, row));
|
||||||
@@ -291,24 +181,9 @@ public sealed class CabPanel : Control
|
|||||||
}
|
}
|
||||||
row += 27;
|
row += 27;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private string LightsText(HeadCode shown, bool noLamps, HeadCode? required, bool? isRight, CultureInfo culture)
|
// 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);
|
||||||
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 groups = Devices(s, culture);
|
||||||
var widths = new double[groups.Length];
|
var widths = new double[groups.Length];
|
||||||
for (int g = 0; g < groups.Length; g++)
|
for (int g = 0; g < groups.Length; g++)
|
||||||
@@ -319,42 +194,33 @@ public sealed class CabPanel : Control
|
|||||||
}
|
}
|
||||||
// each group as wide as its longest name, what is left shared between them
|
// each group as wide as its longest name, what is left shared between them
|
||||||
double spare = (width - widths.Sum()) / groups.Length;
|
double spare = (width - widths.Sum()) / groups.Length;
|
||||||
double x = area.X, bottom = top;
|
double x = Pad, bottom = top;
|
||||||
for (int g = 0; g < groups.Length; g++)
|
for (int g = 0; g < groups.Length; g++)
|
||||||
{
|
{
|
||||||
double groupWidth = Math.Max(20, widths[g] + spare);
|
double groupWidth = Math.Max(20, widths[g] + spare);
|
||||||
using (context.PushClip(new Rect(x, top, groupWidth, height - top)))
|
using (context.PushClip(new Rect(x, top, groupWidth, size.Height - top)))
|
||||||
bottom = Math.Max(bottom, DrawGroup(context, groups[g], x, 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);
|
||||||
|
}
|
||||||
x += groupWidth;
|
x += groupWidth;
|
||||||
}
|
}
|
||||||
return Math.Max(bottom, top + 16 + 9 * LampRow) + 6;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <returns>Where the group ends.</returns>
|
// The doors under them, in two columns: open, permitted, the departure signal, the steps and the lock.
|
||||||
private double DrawGroup(DrawingContext context, (string Title, (string Text, IBrush? Lit)[] Lamps) group, double x, double top)
|
top = Math.Max(bottom, top + 16 + 9 * LampRow) + 6;
|
||||||
{
|
|
||||||
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));
|
context.DrawText(MapView.Text(Strings["CabGroupDoors"], Palette.DimText, 10, FontWeight.SemiBold), new Point(Pad, top));
|
||||||
Say(Strings["CabGroupDoors"]);
|
var doors = Doors(s);
|
||||||
var doors = Doors(s.AsTheCabSees);
|
|
||||||
double doorColumn = width / DoorColumns;
|
double doorColumn = width / DoorColumns;
|
||||||
for (int i = 0; i < doors.Length; i++)
|
for (int i = 0; i < doors.Length; i++)
|
||||||
{
|
{
|
||||||
double doorX = Pad + i % DoorColumns * doorColumn;
|
double doorX = Pad + i % DoorColumns * doorColumn;
|
||||||
using (context.PushClip(new Rect(doorX, top, doorColumn, height - top)))
|
using (context.PushClip(new Rect(doorX, top, doorColumn, size.Height - top)))
|
||||||
Lamp(context, doors[i].Text, doors[i].Lit, doorX, top + 16 + i / DoorColumns * LampRow);
|
Lamp(context, doors[i].Text, doors[i].Lit, doorX, top + 16 + i / DoorColumns * LampRow);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -413,7 +279,6 @@ public sealed class CabPanel : Control
|
|||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
context.DrawText(MapView.Text(Strings["CabNoDrive"], Palette.DimText, 11), new Point(Pad, top + 2));
|
context.DrawText(MapView.Text(Strings["CabNoDrive"], Palette.DimText, 11), new Point(Pad, top + 2));
|
||||||
Say(Strings["CabNoDrive"]);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
double column = width / 2;
|
double column = width / 2;
|
||||||
@@ -456,9 +321,8 @@ 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>
|
/// <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 double Section(DrawingContext context, string title, double x, double y, double right, string? note = null)
|
private static 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);
|
var text = MapView.Text(title.ToUpper(CultureInfo.CurrentCulture), Palette.DimText, 9, FontWeight.SemiBold);
|
||||||
context.DrawText(text, new Point(x, y));
|
context.DrawText(text, new Point(x, y));
|
||||||
double end = right;
|
double end = right;
|
||||||
@@ -506,9 +370,8 @@ public sealed class CabPanel : Control
|
|||||||
_measured = recording.Revision;
|
_measured = recording.Revision;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Value(DrawingContext context, string label, string value, double x, double y, IBrush? brush = null)
|
private static 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(label, Palette.DimText, 10), new Point(x, y));
|
||||||
context.DrawText(MapView.Text(value, brush ?? Palette.Text, 14, FontWeight.SemiBold), new Point(x, y + 13));
|
context.DrawText(MapView.Text(value, brush ?? Palette.Text, 14, FontWeight.SemiBold), new Point(x, y + 13));
|
||||||
}
|
}
|
||||||
@@ -524,10 +387,9 @@ 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>
|
/// <summary>A gauge: its name, a bar up to the value against the scale, a mark where it should stand, the value.</summary>
|
||||||
private void Gauge(DrawingContext context, GaugeReading reading, double x, double y, double width)
|
private static void Gauge(DrawingContext context, string label, float value, double scale, double? mark, string text,
|
||||||
|
IBrush brush, double x, double y, double width)
|
||||||
{
|
{
|
||||||
var (label, value, scale, mark, text, brush) = reading;
|
|
||||||
Say($"{label}: {text}");
|
|
||||||
const double labelWidth = 118, valueWidth = 64;
|
const double labelWidth = 118, valueWidth = 64;
|
||||||
context.DrawText(MapView.Text(label, Palette.DimText, 11), new Point(x, y));
|
context.DrawText(MapView.Text(label, Palette.DimText, 11), new Point(x, y));
|
||||||
double barX = x + labelWidth, barWidth = width - labelWidth - valueWidth;
|
double barX = x + labelWidth, barWidth = width - labelWidth - valueWidth;
|
||||||
@@ -546,10 +408,9 @@ public sealed class CabPanel : Control
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>A value either way of nought: a bar from the middle, to the right above it.</summary>
|
/// <summary>A value either way of nought: a bar from the middle, to the right above it.</summary>
|
||||||
private void Balance(DrawingContext context, string label, float value, double scale, double x, double y, double width)
|
private static void Balance(DrawingContext context, string label, float value, double scale, double x, double y, double width)
|
||||||
{
|
{
|
||||||
var culture = CultureInfo.CurrentCulture;
|
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));
|
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);
|
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));
|
context.DrawText(v, new Point(x + width - v.Width, y));
|
||||||
@@ -594,11 +455,8 @@ public sealed class CabPanel : Control
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>A device's lamp and its name: lit in its colour, the name bright; off, both faint.</summary>
|
/// <summary>A device's lamp and its name: lit in its colour, the name bright; off, both faint.</summary>
|
||||||
private void Lamp(DrawingContext context, string text, IBrush? lit, double x, double y)
|
private static 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);
|
var center = new Point(x + 4, y + 7);
|
||||||
if (lit is not null)
|
if (lit is not null)
|
||||||
context.DrawEllipse(Palette.Faded(lit, 0.3), null, center, 6, 6);
|
context.DrawEllipse(Palette.Faded(lit, 0.3), null, center, 6, 6);
|
||||||
@@ -672,12 +530,12 @@ public sealed class CabPanel : Control
|
|||||||
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
||||||
{
|
{
|
||||||
// A recording which tells them apart.
|
// A recording which tells them apart.
|
||||||
safety.Add((Strings["DevVigilance"], s.VigilanceBuzzer ? Palette.Buzzer : Security(SecurityFlags.Vigilance, Palette.Vigilance)));
|
safety.Add((Strings["DevVigilance"], Security(SecurityFlags.VigilanceBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.Vigilance, Palette.Vigilance)));
|
||||||
safety.Add((Strings["DevCabSignal"], s.CabSignalBuzzer ? Palette.Buzzer : Security(SecurityFlags.CabSignal, Palette.CabSignal)));
|
safety.Add((Strings["DevCabSignal"], Security(SecurityFlags.CabSignalBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.CabSignal, Palette.CabSignal)));
|
||||||
safety.Add((Strings["DevSecurityBraking"], s.ProtectionBraking ? Palette.LampAlarm : null));
|
safety.Add((Strings["DevSecurityBraking"], Security(SecurityFlags.Braking, Palette.LampAlarm)));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
|
safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm
|
||||||
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.LampWarning : null));
|
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.LampWarning : null));
|
||||||
safety.Add(Flag("DevWheelSlip", CabFlags.WheelSlip, Palette.LampAlarm));
|
safety.Add(Flag("DevWheelSlip", CabFlags.WheelSlip, Palette.LampAlarm));
|
||||||
safety.Add(On("DevOverloadRelay", CabDevices.OverloadRelay, Palette.LampAlarm));
|
safety.Add(On("DevOverloadRelay", CabDevices.OverloadRelay, Palette.LampAlarm));
|
||||||
@@ -706,7 +564,4 @@ public sealed class CabPanel : Control
|
|||||||
doors.Add(On("DevDepartureSignal", CabDevices.DepartureSignal, Palette.LampWarning));
|
doors.Add(On("DevDepartureSignal", CabDevices.DepartureSignal, Palette.LampWarning));
|
||||||
return doors.ToArray();
|
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);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,378 +0,0 @@
|
|||||||
using System.Collections.Generic;
|
|
||||||
|
|
||||||
namespace Eu07.BlackBox.Views;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// What the simulator's commands of a vehicle do, as the black box names them (input/command.cpp): Polish
|
|
||||||
/// and English. Those with a key carry the texts of the key file (eu07_input-keyboard.ini) and of the starter's
|
|
||||||
/// English; the rest, worked by the mouse in the cab or by scripts, are written here.
|
|
||||||
/// </summary>
|
|
||||||
public static class CommandTexts
|
|
||||||
{
|
|
||||||
private static readonly Dictionary<string, (string Polish, string English)> Texts = new()
|
|
||||||
{
|
|
||||||
["aidriverenable"] = ("Aktywacja automechanika", "Engage the AI driver"),
|
|
||||||
["aidriverdisable"] = ("Dezaktywacja automechanika", "Disengage the AI driver"),
|
|
||||||
["jointcontrollerset"] = ("Ustawienie nastawnika zespolonego", "Set the combined controller"),
|
|
||||||
["mastercontrollerincrease"] = ("Zwiększenie nastawnika głównego", "Master controller up"),
|
|
||||||
["mastercontrollerincreasefast"] = ("Szybkie zwiększenie nastawnika głównego", "Master controller up, fast"),
|
|
||||||
["mastercontrollerdecrease"] = ("Zmniejszenie nastawnika głównego", "Master controller down"),
|
|
||||||
["mastercontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawnika głównego", "Master controller down, fast"),
|
|
||||||
["mastercontrollerset"] = ("Ustawienie nastawnika głównego", "Set the master controller"),
|
|
||||||
["dynamicbrakecontrollerincrease"] = ("Zwiększenie nastawy hamulca elektrodynamicznego", "Increase the dynamic brake"),
|
|
||||||
["dynamicbrakecontrollerdecrease"] = ("Zmniejszenie nastawy hamulca elektrodynamicznego", "Decrease the dynamic brake"),
|
|
||||||
["dynamicbrakecontrollerset"] = ("Ustawienie hamulca elektrodynamicznego", "Set the dynamic brake"),
|
|
||||||
["dynamicbrakecontrollerincreasefast"] = ("Szybkie zwiększenie nastawy hamulca elektrodynamicznego", "Increase the dynamic brake fast"),
|
|
||||||
["dynamicbrakecontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawy hamulca elektrodynamicznego", "Decrease the dynamic brake fast"),
|
|
||||||
["secondcontrollerincrease"] = ("Zwiększenie nastawnika boczników", "Shunt controller up"),
|
|
||||||
["secondcontrollerincreasefast"] = ("Szybkie zwiększenie nastawnika boczników", "Shunt controller up, fast"),
|
|
||||||
["secondcontrollerdecrease"] = ("Zmniejszenie nastawnika boczników", "Shunt controller down"),
|
|
||||||
["secondcontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawnika boczników", "Shunt controller down, fast"),
|
|
||||||
["secondcontrollerset"] = ("Ustawienie nastawnika boczników", "Set the shunt controller"),
|
|
||||||
["mucurrentindicatorothersourceactivate"] = ("Zmiana członu dla wskaźnika prądu", "Switch the current gauge to the other unit"),
|
|
||||||
["independentbrakeincrease"] = ("Zwiększenie nastawy hamulca lokomotywy", "Apply more locomotive brake"),
|
|
||||||
["independentbrakeincreasefast"] = ("Szybkie zwiększenie nastawy hamulca lokomotywy", "Apply more locomotive brake, fast"),
|
|
||||||
["independentbrakedecrease"] = ("Zmniejszenie nastawy hamulca lokomotywy", "Release locomotive brake"),
|
|
||||||
["independentbrakedecreasefast"] = ("Szybkie zmniejszenie nastawy hamulca lokomotywy", "Release locomotive brake, fast"),
|
|
||||||
["independentbrakeset"] = ("Ustawienie hamulca lokomotywy", "Set the locomotive brake"),
|
|
||||||
["independentbrakebailoff"] = ("Odluźniacz", "Bail off the locomotive brake"),
|
|
||||||
["universalbrakebutton1"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 1", "Universal brake button 1"),
|
|
||||||
["universalbrakebutton2"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 2", "Universal brake button 2"),
|
|
||||||
["universalbrakebutton3"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 3", "Universal brake button 3"),
|
|
||||||
["trainbrakeincrease"] = ("Zwiększenie stopnia hamowania zaworu maszynisty", "Train brake valve: more braking"),
|
|
||||||
["trainbrakedecrease"] = ("Zmniejszenie stopnia hamowania zaworu maszynisty", "Train brake valve: less braking"),
|
|
||||||
["trainbrakeset"] = ("Ustawienie hamulca zespolonego", "Set the train brake"),
|
|
||||||
["trainbrakecharging"] = ("Napełnianie uderzeniowe przewodu głównego", "Train brake valve: overcharge the brake pipe"),
|
|
||||||
["trainbrakerelease"] = ("Ustawienie zaworu maszynisty w pozycji jazdy", "Train brake valve: running position"),
|
|
||||||
["trainbrakefirstservice"] = ("Pozycja pierwszego stopnia hamowania", "Train brake valve: first braking step"),
|
|
||||||
["trainbrakeservice"] = ("Pozycja hamowania służbowego", "Train brake valve: service braking"),
|
|
||||||
["trainbrakefullservice"] = ("Pozycja hamowania pełnego", "Train brake valve: full service"),
|
|
||||||
["trainbrakehandleoff"] = ("Pozycja odcięcia", "Train brake valve: lap position"),
|
|
||||||
["trainbrakeemergency"] = ("Hamowanie nagłe", "Emergency braking"),
|
|
||||||
["trainbrakebasepressureincrease"] = ("Zwiększenie poziomu ciśnienia w przewodzie głównym", "Raise the brake pipe pressure level"),
|
|
||||||
["trainbrakebasepressuredecrease"] = ("Zmniejszenie poziomu ciśnienia w przewodzie głównym", "Lower the brake pipe pressure level"),
|
|
||||||
["trainbrakebasepressurereset"] = ("Domyślny poziom ciśnienia w przewodzie głównym", "Default brake pipe pressure level"),
|
|
||||||
["trainbrakeoperationtoggle"] = ("Przełączenie stanu hamulca pojazdu", "Toggle the vehicle's brake"),
|
|
||||||
["manualbrakeincrease"] = ("Zwiększenie nastawy hamulca ręcznego", "Apply more hand brake"),
|
|
||||||
["manualbrakedecrease"] = ("Zmniejszenie nastawy hamulca ręcznego", "Release hand brake"),
|
|
||||||
["alarmchaintoggle"] = ("Przełączenie stanu hamulca bezpieczeństwa", "Toggle the emergency brake"),
|
|
||||||
["alarmchainenable"] = ("Pociągnięcie hamulca bezpieczeństwa", "Pull the alarm chain"),
|
|
||||||
["alarmchaindisable"] = ("Zwolnienie hamulca bezpieczeństwa", "Release the alarm chain"),
|
|
||||||
["wheelspinbrakeactivate"] = ("Aktywacja podhamowania przeciwpoślizgowego", "Anti-slip brake"),
|
|
||||||
["sandboxactivate"] = ("Aktywacja piasecznicy", "Sander"),
|
|
||||||
["autosandboxtoggle"] = ("Przełączenie automatycznej piasecznicy", "Toggle the automatic sander"),
|
|
||||||
["autosandboxactivate"] = ("Włączenie automatycznej piasecznicy", "Turn the automatic sander on"),
|
|
||||||
["autosandboxdeactivate"] = ("Wyłączenie automatycznej piasecznicy", "Turn the automatic sander off"),
|
|
||||||
["reverserincrease"] = ("Zwiększenie pozycji nastawnika kierunku", "Reverser up"),
|
|
||||||
["reverserdecrease"] = ("Zmniejszenie pozycji nastawnika kierunku", "Reverser down"),
|
|
||||||
["reverserforwardhigh"] = ("Pozycja jazdy do przodu II nastawnika kierunku", "Reverser: forward II"),
|
|
||||||
["reverserforward"] = ("Pozycja jazdy do przodu nastawnika kierunku", "Reverser: forward"),
|
|
||||||
["reverserneutral"] = ("Pozycja neutralna nastawnika kierunku", "Reverser: neutral"),
|
|
||||||
["reverserbackward"] = ("Pozycja jazdy do tyłu nastawnika kierunku", "Reverser: backward"),
|
|
||||||
["waterpumpbreakertoggle"] = ("Przełączenie stanu wyłącznika samoczynnego pompy wody", "Toggle the water pump circuit breaker"),
|
|
||||||
["waterpumpbreakerclose"] = ("Załączenie wyłącznika pompy wody", "Close the water pump breaker"),
|
|
||||||
["waterpumpbreakeropen"] = ("Wyłączenie wyłącznika pompy wody", "Open the water pump breaker"),
|
|
||||||
["waterpumptoggle"] = ("Przełączenie stanu pompy wody", "Toggle the water pump"),
|
|
||||||
["waterpumpenable"] = ("Włączenie pompy wody", "Turn the water pump on"),
|
|
||||||
["waterpumpdisable"] = ("Wyłączenie pompy wody", "Turn the water pump off"),
|
|
||||||
["waterheaterbreakertoggle"] = ("Przełączenie stanu wyłącznika samoczynnego podgrzewacza wody", "Toggle the water heater circuit breaker"),
|
|
||||||
["waterheaterbreakerclose"] = ("Załączenie wyłącznika podgrzewacza wody", "Close the water heater breaker"),
|
|
||||||
["waterheaterbreakeropen"] = ("Wyłączenie wyłącznika podgrzewacza wody", "Open the water heater breaker"),
|
|
||||||
["waterheatertoggle"] = ("Przełączenie stanu podgrzewacza wody", "Toggle the water heater"),
|
|
||||||
["waterheaterenable"] = ("Włączenie podgrzewacza wody", "Turn the water heater on"),
|
|
||||||
["waterheaterdisable"] = ("Wyłączenie podgrzewacza wody", "Turn the water heater off"),
|
|
||||||
["watercircuitslinktoggle"] = ("Przełączenie stanu połączenia obiegów wody", "Toggle the link between the water circuits"),
|
|
||||||
["watercircuitslinkenable"] = ("Połączenie obiegów wody", "Link the water circuits"),
|
|
||||||
["watercircuitslinkdisable"] = ("Rozłączenie obiegów wody", "Unlink the water circuits"),
|
|
||||||
["fuelpumptoggle"] = ("Przełączenie stanu pompy paliwa", "Toggle the fuel pump"),
|
|
||||||
["fuelpumpenable"] = ("Włączenie pompy paliwa", "Turn the fuel pump on"),
|
|
||||||
["fuelpumpdisable"] = ("Wyłączenie pompy paliwa", "Turn the fuel pump off"),
|
|
||||||
["oilpumptoggle"] = ("Przełączenie stanu pompy oleju", "Toggle the oil pump"),
|
|
||||||
["oilpumpenable"] = ("Włączenie pompy oleju", "Turn the oil pump on"),
|
|
||||||
["oilpumpdisable"] = ("Wyłączenie pompy oleju", "Turn the oil pump off"),
|
|
||||||
["linebreakertoggle"] = ("Przełączenie stanu wyłącznika szybkiego", "Toggle the line breaker"),
|
|
||||||
["linebreakeropen"] = ("Wyłączenie wyłącznika szybkiego", "Open the line breaker"),
|
|
||||||
["linebreakerclose"] = ("Załączenie wyłącznika szybkiego", "Close the line breaker"),
|
|
||||||
["convertertoggle"] = ("Przełączenie stanu przetwornicy", "Toggle the converter"),
|
|
||||||
["converterenable"] = ("Włączenie przetwornicy", "Turn the converter on"),
|
|
||||||
["converterdisable"] = ("Wyłączenie przetwornicy", "Turn the converter off"),
|
|
||||||
["convertertogglelocal"] = ("Przełączenie stanu przetwornicy w obsadzonym członie", "Toggle the converter in the occupied unit"),
|
|
||||||
["converteroverloadrelayreset"] = ("Odblokowanie przekaźnika nadmiarowego przetwornicy", "Reset the converter overload relay"),
|
|
||||||
["compressortoggle"] = ("Przełączenie stanu sprężarki", "Toggle the compressor"),
|
|
||||||
["compressorenable"] = ("Włączenie sprężarki", "Turn the compressor on"),
|
|
||||||
["compressordisable"] = ("Wyłączenie sprężarki", "Turn the compressor off"),
|
|
||||||
["compressortogglelocal"] = ("Przełączenie stanu sprężarki w obsadzonym członie", "Toggle the compressor in the occupied unit"),
|
|
||||||
["compressorpresetactivatenext"] = ("Następny tryb pracy sprężarek", "Next compressor mode"),
|
|
||||||
["compressorpresetactivateprevious"] = ("Poprzedni tryb pracy sprężarek", "Previous compressor mode"),
|
|
||||||
["compressorpresetactivatedefault"] = ("Domyślny tryb pracy sprężarek", "Default compressor mode"),
|
|
||||||
["motoroverloadrelaythresholdtoggle"] = ("Przełączenie rozruchu niskiego/wysokiego", "Switch between low and high starting current"),
|
|
||||||
["motoroverloadrelaythresholdsetlow"] = ("Niski próg przekaźnika nadmiarowego silników", "Motor overload relay threshold low"),
|
|
||||||
["motoroverloadrelaythresholdsethigh"] = ("Wysoki próg przekaźnika nadmiarowego silników", "Motor overload relay threshold high"),
|
|
||||||
["motoroverloadrelayreset"] = ("Odblokowanie przekaźnika nadmiarowego silników", "Reset the traction motor overload relay"),
|
|
||||||
["universalrelayreset1"] = ("Odblokowanie zdefiniowanych przekaźników nr 1", "Reset the defined relays, set 1"),
|
|
||||||
["universalrelayreset2"] = ("Odblokowanie zdefiniowanych przekaźników nr 2", "Reset the defined relays, set 2"),
|
|
||||||
["universalrelayreset3"] = ("Odblokowanie zdefiniowanych przekaźników nr 3", "Reset the defined relays, set 3"),
|
|
||||||
["notchingrelaytoggle"] = ("Przełączenie stanu przekaźnika samoczynnego rozruchu", "Toggle the automatic notching relay"),
|
|
||||||
["epbrakecontroltoggle"] = ("Przełączenie stanu hamulca elektropneumatycznego", "Toggle the electro-pneumatic brake"),
|
|
||||||
["epbrakecontrolenable"] = ("Włączenie hamulca elektropneumatycznego", "Turn the electro-pneumatic brake on"),
|
|
||||||
["epbrakecontroldisable"] = ("Wyłączenie hamulca elektropneumatycznego", "Turn the electro-pneumatic brake off"),
|
|
||||||
["trainbrakeoperationmodeincrease"] = ("Zmiana trybu pracy hamulca na bardziej efektywny", "Brake operation mode: more effective"),
|
|
||||||
["trainbrakeoperationmodedecrease"] = ("Zmiana trybu pracy hamulca na prostszy", "Brake operation mode: simpler"),
|
|
||||||
["brakeactingspeedincrease"] = ("Wybór szybszego trybu działania hamulca pociągu", "Faster train brake acting speed"),
|
|
||||||
["brakeactingspeeddecrease"] = ("Wybór wolniejszego trybu działania hamulca pociągu", "Slower train brake acting speed"),
|
|
||||||
["brakeactingspeedsetcargo"] = ("Wybór trybu hamulca dla pociągu towarowego", "Brake acting speed for a freight train"),
|
|
||||||
["brakeactingspeedsetpassenger"] = ("Wybór trybu hamulca dla pociągu osobowego", "Brake acting speed for a passenger train"),
|
|
||||||
["brakeactingspeedsetrapid"] = ("Wybór trybu hamulca dla pociągu pospiesznego", "Brake acting speed for an express train"),
|
|
||||||
["brakeloadcompensationincrease"] = ("Wybór wyższego przełożenia hamulca", "Higher brake load setting"),
|
|
||||||
["brakeloadcompensationdecrease"] = ("Wybór niższego przełożenia hamulca", "Lower brake load setting"),
|
|
||||||
["mubrakingindicatortoggle"] = ("Przełączenie stanu wskaźnika hamowania członów EZT", "Toggle the EMU unit braking indicator"),
|
|
||||||
["alerteracknowledge"] = ("Wygaszenie czuwaka i SHP", "Acknowledge the vigilance device and cab signalling"),
|
|
||||||
["cabsignalacknowledge"] = ("Wygaszenie SHP", "Acknowledge the cab signalling"),
|
|
||||||
["hornlowactivate"] = ("Aktywacja syreny niskotonowej", "Low-tone horn"),
|
|
||||||
["hornhighactivate"] = ("Aktywacja syreny wysokotonowej", "High-tone horn"),
|
|
||||||
["whistleactivate"] = ("Aktywacja gwizdka", "Whistle"),
|
|
||||||
["radiotoggle"] = ("Przełączenie stanu radiotelefonu", "Toggle the radio"),
|
|
||||||
["radioenable"] = ("Włączenie radiotelefonu", "Turn the radio on"),
|
|
||||||
["radiodisable"] = ("Wyłączenie radiotelefonu", "Turn the radio off"),
|
|
||||||
["radiochannelincrease"] = ("Wybór kolejnego kanału radia", "Next radio channel"),
|
|
||||||
["radiochanneldecrease"] = ("Wybór poprzedniego kanału radia", "Previous radio channel"),
|
|
||||||
["radiochannelset"] = ("Ustawienie kanału radiotelefonu", "Set the radio channel"),
|
|
||||||
["radiostopsend"] = ("Emisja radiostopu", "Send radio-stop"),
|
|
||||||
["radiostopenable"] = ("Włączenie sygnału Radio-Stop", "Send Radio-Stop"),
|
|
||||||
["radiostopdisable"] = ("Wyłączenie sygnału Radio-Stop", "Stop sending Radio-Stop"),
|
|
||||||
["radiostoptest"] = ("Lokalny test radiostopu", "Local radio-stop test"),
|
|
||||||
["radiocall1send"] = ("Wywołanie radiowe 1", "Radio call 1"),
|
|
||||||
["radiocall3send"] = ("Emisja sygnału zew3", "Send the call-3 signal"),
|
|
||||||
["radiovolumeincrease"] = ("Zwiększenie głośności radia", "Radio volume up"),
|
|
||||||
["radiovolumedecrease"] = ("Zmniejszenie głośności radia", "Radio volume down"),
|
|
||||||
["radiovolumeset"] = ("Ustawienie głośności radiotelefonu", "Set the radio volume"),
|
|
||||||
["radiofusetoggle"] = ("Przełączenie bezpiecznika radiotelefonu", "Toggle the radio fuse"),
|
|
||||||
["radiofuseenable"] = ("Załączenie bezpiecznika radiotelefonu", "Close the radio fuse"),
|
|
||||||
["radiofusedisable"] = ("Wyłączenie bezpiecznika radiotelefonu", "Open the radio fuse"),
|
|
||||||
["cabchangeforward"] = ("Przejście do sąsiedniego pomieszczenia w kierunku czoła pociągu", "Move to the next compartment towards the front"),
|
|
||||||
["cabchangebackward"] = ("Przejście do sąsiedniego pomieszczenia w kierunku tyłu pociągu", "Move to the next compartment towards the rear"),
|
|
||||||
["modernlightdimmerdecrease"] = ("Przyciemnienie oświetlenia", "Dim the lights"),
|
|
||||||
["modernlightdimmerincrease"] = ("Rozjaśnienie oświetlenia", "Brighten the lights"),
|
|
||||||
["nearestcarcouplingincrease"] = ("Łączenie sprzęgów", "Couple"),
|
|
||||||
["nearestcarcouplingdisconnect"] = ("Rozłączenie sprzęgów", "Uncouple"),
|
|
||||||
["nearestcarcoupleradapterattach"] = ("Nałożenie półsprzęgu", "Attach the coupler adapter"),
|
|
||||||
["nearestcarcoupleradapterremove"] = ("Demontaż półsprzęgu", "Remove the coupler adapter"),
|
|
||||||
["occupiedcarcouplingdisconnect"] = ("Rozłączenie sprzęgów po stronie obsadzonej kabiny", "Uncouple at the occupied cab's end"),
|
|
||||||
["occupiedcarcouplingdisconnectback"] = ("Rozłączenie sprzęgu z tyłu zajmowanego pojazdu", "Uncouple at the back of the occupied car"),
|
|
||||||
["doortoggleleft"] = ("Przełączenie stanu drzwi lewych", "Toggle the left doors"),
|
|
||||||
["doortoggleright"] = ("Przełączenie stanu drzwi prawych", "Toggle the right doors"),
|
|
||||||
["doorpermitleft"] = ("Zezwolenie na otwarcie drzwi lewych", "Permit opening the left doors"),
|
|
||||||
["doorpermitright"] = ("Zezwolenie na otwarcie drzwi prawych", "Permit opening the right doors"),
|
|
||||||
["doorpermitpresetactivatenext"] = ("Aktywacja kolejnej konfiguracji zezwolenia na otwarcie drzwi", "Next door permit preset"),
|
|
||||||
["doorpermitpresetactivateprevious"] = ("Aktywacja poprzedniej konfiguracji zezwolenia na otwarcie drzwi", "Previous door permit preset"),
|
|
||||||
["dooropenleft"] = ("Otwarcie drzwi z lewej", "Open the left doors"),
|
|
||||||
["dooropenright"] = ("Otwarcie drzwi z prawej", "Open the right doors"),
|
|
||||||
["dooropenall"] = ("Otwarcie drzwi z zezwoleniem", "Open the permitted doors"),
|
|
||||||
["doorcloseleft"] = ("Zamknięcie drzwi lewych", "Close the left doors"),
|
|
||||||
["doorcloseright"] = ("Zamknięcie drzwi prawych", "Close the right doors"),
|
|
||||||
["doorcloseall"] = ("Zamknięcie wszystkich drzwi", "Close all doors"),
|
|
||||||
["doorsteptoggle"] = ("Przełączenie stanu stopnia drzwi", "Toggle the door steps"),
|
|
||||||
["doormodetoggle"] = ("Przełączenie trybu działania drzwi", "Toggle the door operation mode"),
|
|
||||||
["mirrorstoggle"] = ("Złożenie lub rozłożenie lusterek", "Fold or unfold the mirrors"),
|
|
||||||
["departureannounce"] = ("Sygnał odjazdu", "Departure signal"),
|
|
||||||
["doorlocktoggle"] = ("Przełączenie stanu blokady drzwi", "Toggle the door lock"),
|
|
||||||
["pantographcompressorvalvetoggle"] = ("Przełączenie stanu kurka trójdrogowego", "Toggle the three-way pantograph valve"),
|
|
||||||
["pantographcompressorvalveenable"] = ("Otwarcie zaworu sprężarki pantografów", "Open the pantograph compressor valve"),
|
|
||||||
["pantographcompressorvalvedisable"] = ("Zamknięcie zaworu sprężarki pantografów", "Close the pantograph compressor valve"),
|
|
||||||
["pantographcompressoractivate"] = ("Aktywacja sprężarki pomocniczej", "Auxiliary pantograph compressor"),
|
|
||||||
["pantographtogglefront"] = ("Przełączenie stanu pantografu przedniego", "Toggle the front pantograph"),
|
|
||||||
["pantographtogglerear"] = ("Przełączenie stanu pantografu tylnego", "Toggle the rear pantograph"),
|
|
||||||
["pantographraisefront"] = ("Podniesienie przedniego pantografu", "Raise the front pantograph"),
|
|
||||||
["pantographraiserear"] = ("Podniesienie tylnego pantografu", "Raise the rear pantograph"),
|
|
||||||
["pantographlowerfront"] = ("Opuszczenie przedniego pantografu", "Lower the front pantograph"),
|
|
||||||
["pantographlowerrear"] = ("Opuszczenie tylnego pantografu", "Lower the rear pantograph"),
|
|
||||||
["pantographlowerall"] = ("Opuszczenie wszystkich pantografów", "Lower all pantographs"),
|
|
||||||
["pantographselectnext"] = ("Aktywacja kolejnej konfiguracji wyboru pantografów", "Next pantograph selection preset"),
|
|
||||||
["pantographselectprevious"] = ("Aktywacja poprzedniej konfiguracji wyboru pantografów", "Previous pantograph selection preset"),
|
|
||||||
["pantographtoggleselected"] = ("Przełączenie stanu wybranych pantografów", "Toggle the selected pantographs"),
|
|
||||||
["pantographraiseselected"] = ("Podniesienie wybranych pantografów", "Raise the selected pantographs"),
|
|
||||||
["pantographlowerselected"] = ("Opuszczenie wybranych pantografów", "Lower the selected pantographs"),
|
|
||||||
["pantographvalvesupdate"] = ("Ustawienie zaworów pantografów", "Set the pantograph valves"),
|
|
||||||
["pantographvalvesoff"] = ("Zamknięcie zaworów pantografów", "Close the pantograph valves"),
|
|
||||||
["heatingtoggle"] = ("Przełączenie stanu ogrzewania pociągu", "Toggle train heating"),
|
|
||||||
["heatingenable"] = ("Włączenie ogrzewania pociągu", "Turn the train heating on"),
|
|
||||||
["heatingdisable"] = ("Wyłączenie ogrzewania pociągu", "Turn the train heating off"),
|
|
||||||
["lightspresetactivatenext"] = ("Aktywacja kolejnej konfiguracji reflektorów", "Next headlight preset"),
|
|
||||||
["lightspresetactivateprevious"] = ("Aktywacja poprzedniej konfiguracji reflektorów", "Previous headlight preset"),
|
|
||||||
["headlighttoggleleft"] = ("Przełączenie stanu lewego reflektora", "Toggle the left headlight"),
|
|
||||||
["headlightenableleft"] = ("Włączenie lewego reflektora z przodu", "Turn the front left headlight on"),
|
|
||||||
["headlightdisableleft"] = ("Wyłączenie lewego reflektora z przodu", "Turn the front left headlight off"),
|
|
||||||
["headlighttoggleright"] = ("Przełączenie stanu prawego reflektora", "Toggle the right headlight"),
|
|
||||||
["headlightenableright"] = ("Włączenie prawego reflektora z przodu", "Turn the front right headlight on"),
|
|
||||||
["headlightdisableright"] = ("Wyłączenie prawego reflektora z przodu", "Turn the front right headlight off"),
|
|
||||||
["headlighttoggleupper"] = ("Przełączenie stanu górnego reflektora", "Toggle the upper headlight"),
|
|
||||||
["headlightenableupper"] = ("Włączenie górnego reflektora z przodu", "Turn the front upper headlight on"),
|
|
||||||
["headlightdisableupper"] = ("Wyłączenie górnego reflektora z przodu", "Turn the front upper headlight off"),
|
|
||||||
["redmarkertoggleleft"] = ("Przełączenie lewego światła czerwonego", "Toggle the left red marker"),
|
|
||||||
["redmarkerenableleft"] = ("Włączenie lewego sygnału końcowego z przodu", "Turn the front left red marker on"),
|
|
||||||
["redmarkerdisableleft"] = ("Wyłączenie lewego sygnału końcowego z przodu", "Turn the front left red marker off"),
|
|
||||||
["redmarkertoggleright"] = ("Przełączenie prawego światła czerwonego", "Toggle the right red marker"),
|
|
||||||
["redmarkerenableright"] = ("Włączenie prawego sygnału końcowego z przodu", "Turn the front right red marker on"),
|
|
||||||
["redmarkerdisableright"] = ("Wyłączenie prawego sygnału końcowego z przodu", "Turn the front right red marker off"),
|
|
||||||
["headlighttogglerearleft"] = ("Przełączenie stanu lewego tylnego reflektora", "Toggle the rear left headlight"),
|
|
||||||
["headlightenablerearleft"] = ("Włączenie lewego reflektora z tyłu", "Turn the rear left headlight on"),
|
|
||||||
["headlightdisablerearleft"] = ("Wyłączenie lewego reflektora z tyłu", "Turn the rear left headlight off"),
|
|
||||||
["headlighttogglerearright"] = ("Przełączenie stanu prawego tylnego reflektora", "Toggle the rear right headlight"),
|
|
||||||
["headlightenablerearright"] = ("Włączenie prawego reflektora z tyłu", "Turn the rear right headlight on"),
|
|
||||||
["headlightdisablerearright"] = ("Wyłączenie prawego reflektora z tyłu", "Turn the rear right headlight off"),
|
|
||||||
["headlighttogglerearupper"] = ("Przełączenie stanu górnego tylnego reflektora", "Toggle the rear upper headlight"),
|
|
||||||
["headlightenablerearupper"] = ("Włączenie górnego reflektora z tyłu", "Turn the rear upper headlight on"),
|
|
||||||
["headlightdisablerearupper"] = ("Wyłączenie górnego reflektora z tyłu", "Turn the rear upper headlight off"),
|
|
||||||
["redmarkertogglerearleft"] = ("Przełączenie lewego tylnego światła czerwonego", "Toggle the rear left red marker"),
|
|
||||||
["redmarkerenablerearleft"] = ("Włączenie lewego sygnału końcowego z tyłu", "Turn the rear left red marker on"),
|
|
||||||
["redmarkerdisablerearleft"] = ("Wyłączenie lewego sygnału końcowego z tyłu", "Turn the rear left red marker off"),
|
|
||||||
["redmarkertogglerearright"] = ("Przełączenie prawego tylnego światła czerwonego", "Toggle the rear right red marker"),
|
|
||||||
["redmarkerenablerearright"] = ("Włączenie prawego sygnału końcowego z tyłu", "Turn the rear right red marker on"),
|
|
||||||
["redmarkerdisablerearright"] = ("Wyłączenie prawego sygnału końcowego z tyłu", "Turn the rear right red marker off"),
|
|
||||||
["redmarkerstoggle"] = ("Przełączenie świateł końca pociągu", "Toggle the end-of-train lights"),
|
|
||||||
["endsignalstoggle"] = ("Przełączenie tabliczek końca pociągu", "Toggle the end-of-train plates"),
|
|
||||||
["headlightsdimtoggle"] = ("Przełączenie przyciemnienia reflektorów", "Toggle headlight dimming"),
|
|
||||||
["headlightsdimenable"] = ("Przyciemnienie reflektorów", "Dim the headlights"),
|
|
||||||
["headlightsdimdisable"] = ("Pełne światło reflektorów", "Headlights at full"),
|
|
||||||
["motorconnectorsopen"] = ("Rozłączenie styczników liniowych", "Open the line contactors"),
|
|
||||||
["motorconnectorsclose"] = ("Załączenie styczników liniowych", "Close the line contactors"),
|
|
||||||
["motordisconnect"] = ("Odłączenie uszkodzonych silników", "Cut out the damaged motors"),
|
|
||||||
["interiorlighttoggle"] = ("Przełączenie stanu oświetlenia kabiny", "Toggle the cab light"),
|
|
||||||
["interiorlightenable"] = ("Włączenie oświetlenia kabiny", "Turn the cab light on"),
|
|
||||||
["interiorlightdisable"] = ("Wyłączenie oświetlenia kabiny", "Turn the cab light off"),
|
|
||||||
["interiorlightdimtoggle"] = ("Przełączenie przyciemnienia oświetlenia kabiny", "Toggle cab light dimming"),
|
|
||||||
["interiorlightdimenable"] = ("Przyciemnienie oświetlenia kabiny", "Dim the cab light"),
|
|
||||||
["interiorlightdimdisable"] = ("Pełne oświetlenie kabiny", "Cab light at full"),
|
|
||||||
["compartmentlightstoggle"] = ("Przełączenie stanu oświetlenia przedziałów", "Toggle the compartment lights"),
|
|
||||||
["compartmentlightsenable"] = ("Włączenie oświetlenia przedziałów", "Turn the compartment lights on"),
|
|
||||||
["compartmentlightsdisable"] = ("Wyłączenie oświetlenia przedziałów", "Turn the compartment lights off"),
|
|
||||||
["instrumentlighttoggle"] = ("Przełączenie stanu oświetlenia przyrządów", "Toggle the instrument lights"),
|
|
||||||
["instrumentlightenable"] = ("Włączenie oświetlenia przyrządów", "Turn the instrument lights on"),
|
|
||||||
["instrumentlightdisable"] = ("Wyłączenie oświetlenia przyrządów", "Turn the instrument lights off"),
|
|
||||||
["dashboardlighttoggle"] = ("Przełączenie stanu oświetlenia pulpitu", "Toggle the dashboard light"),
|
|
||||||
["dashboardlightenable"] = ("Włączenie oświetlenia pulpitu", "Turn the dashboard light on"),
|
|
||||||
["dashboardlightdisable"] = ("Wyłączenie oświetlenia pulpitu", "Turn the dashboard light off"),
|
|
||||||
["timetablelighttoggle"] = ("Przełączenie stanu oświetlenia rozkładu jazdy", "Toggle the timetable light"),
|
|
||||||
["timetablelightenable"] = ("Włączenie oświetlenia rozkładu jazdy", "Turn the timetable light on"),
|
|
||||||
["timetablelightdisable"] = ("Wyłączenie oświetlenia rozkładu jazdy", "Turn the timetable light off"),
|
|
||||||
["generictoggle0"] = ("Przełączenie elementu uniwersalnego nr 0", "Generic switch 0"),
|
|
||||||
["generictoggle1"] = ("Przełączenie elementu uniwersalnego nr 1", "Generic switch 1"),
|
|
||||||
["generictoggle2"] = ("Przełączenie elementu uniwersalnego nr 2", "Generic switch 2"),
|
|
||||||
["generictoggle3"] = ("Przełączenie elementu uniwersalnego nr 3", "Generic switch 3"),
|
|
||||||
["generictoggle4"] = ("Przełączenie elementu uniwersalnego nr 4", "Generic switch 4"),
|
|
||||||
["generictoggle5"] = ("Przełączenie elementu uniwersalnego nr 5", "Generic switch 5"),
|
|
||||||
["generictoggle6"] = ("Przełączenie elementu uniwersalnego nr 6", "Generic switch 6"),
|
|
||||||
["generictoggle7"] = ("Przełączenie elementu uniwersalnego nr 7", "Generic switch 7"),
|
|
||||||
["generictoggle8"] = ("Przełączenie elementu uniwersalnego nr 8", "Generic switch 8"),
|
|
||||||
["generictoggle9"] = ("Przełączenie elementu uniwersalnego nr 9", "Generic switch 9"),
|
|
||||||
["generictoggle10"] = ("Przełączenie elementu uniwersalnego nr 10", "Generic switch 10"),
|
|
||||||
["generictoggle11"] = ("Przełączenie elementu uniwersalnego nr 11", "Generic switch 11"),
|
|
||||||
["generictoggle12"] = ("Przełączenie elementu uniwersalnego nr 12", "Generic switch 12"),
|
|
||||||
["generictoggle13"] = ("Przełączenie elementu uniwersalnego nr 13", "Generic switch 13"),
|
|
||||||
["generictoggle14"] = ("Przełączenie elementu uniwersalnego nr 14", "Generic switch 14"),
|
|
||||||
["generictoggle15"] = ("Przełączenie elementu uniwersalnego nr 15", "Generic switch 15"),
|
|
||||||
["generictoggle16"] = ("Przełączenie elementu uniwersalnego nr 16", "Generic switch 16"),
|
|
||||||
["generictoggle17"] = ("Przełączenie elementu uniwersalnego nr 17", "Generic switch 17"),
|
|
||||||
["generictoggle18"] = ("Przełączenie elementu uniwersalnego nr 18", "Generic switch 18"),
|
|
||||||
["generictoggle19"] = ("Przełączenie elementu uniwersalnego nr 19", "Generic switch 19"),
|
|
||||||
["generictoggle20"] = ("Przełączenie elementu uniwersalnego nr 20", "Generic switch 20"),
|
|
||||||
["generictoggle21"] = ("Przełączenie elementu uniwersalnego nr 21", "Generic switch 21"),
|
|
||||||
["generictoggle22"] = ("Przełączenie elementu uniwersalnego nr 22", "Generic switch 22"),
|
|
||||||
["generictoggle23"] = ("Przełączenie elementu uniwersalnego nr 23", "Generic switch 23"),
|
|
||||||
["generictoggle24"] = ("Przełączenie elementu uniwersalnego nr 24", "Generic switch 24"),
|
|
||||||
["generictoggle25"] = ("Przełączenie elementu uniwersalnego nr 25", "Generic switch 25"),
|
|
||||||
["generictoggle26"] = ("Przełączenie elementu uniwersalnego nr 26", "Generic switch 26"),
|
|
||||||
["generictoggle27"] = ("Przełączenie elementu uniwersalnego nr 27", "Generic switch 27"),
|
|
||||||
["generictoggle28"] = ("Przełączenie elementu uniwersalnego nr 28", "Generic switch 28"),
|
|
||||||
["generictoggle29"] = ("Przełączenie elementu uniwersalnego nr 29", "Generic switch 29"),
|
|
||||||
["batterytoggle"] = ("Przełączenie stanu akumulatorów", "Toggle the batteries"),
|
|
||||||
["batteryenable"] = ("Włączenie baterii", "Turn the battery on"),
|
|
||||||
["batterydisable"] = ("Wyłączenie baterii", "Turn the battery off"),
|
|
||||||
["cabactivationtoggle"] = ("Przełączenie stanu aktywacji kabiny", "Toggle cab activation"),
|
|
||||||
["cabactivationenable"] = ("Aktywacja kabiny", "Activate the cab"),
|
|
||||||
["cabactivationdisable"] = ("Dezaktywacja kabiny", "Deactivate the cab"),
|
|
||||||
["motorblowerstogglefront"] = ("Przełączenie stanu wentylatorów przednich silników trakcyjnych", "Toggle the front traction motor blowers"),
|
|
||||||
["motorblowerstogglerear"] = ("Przełączenie stanu wentylatorów tylnych silników trakcyjnych", "Toggle the rear traction motor blowers"),
|
|
||||||
["motorblowersdisableall"] = ("Wyłączenie wszystkich wentylatorów silników trakcyjnych", "Switch off all traction motor blowers"),
|
|
||||||
["coolingfanstoggle"] = ("Przełączenie stanu wentylatorów oporów rozruchowych", "Toggle the starting resistor fans"),
|
|
||||||
["tempomattoggle"] = ("Przełączenie stanu tempomatu", "Toggle the cruise control"),
|
|
||||||
["springbraketoggle"] = ("Przełączenie stanu hamulca sprężynowego", "Toggle the spring brake"),
|
|
||||||
["springbrakeenable"] = ("Załączenie hamulca sprężynowego", "Apply the spring brake"),
|
|
||||||
["springbrakedisable"] = ("Zwolnienie hamulca sprężynowego", "Release the spring brake"),
|
|
||||||
["springbrakeshutofftoggle"] = ("Przełączenie stanu kurka odcinającego hamulca sprężynowego", "Toggle the spring brake shut-off cock"),
|
|
||||||
["springbrakeshutoffenable"] = ("Odcięcie hamulca sprężynowego", "Cut the spring brake off"),
|
|
||||||
["springbrakeshutoffdisable"] = ("Przywrócenie hamulca sprężynowego", "Cut the spring brake back in"),
|
|
||||||
["springbrakerelease"] = ("Luzowanie hamulca sprężynowego", "Release the spring brake"),
|
|
||||||
["distancecounteractivate"] = ("Załączenie miernika przejechanego dystansu", "Start the distance counter"),
|
|
||||||
["speedcontrolincrease"] = ("Zwiększenie prędkości utrzymywanej przez tempomat", "Cruise control speed up"),
|
|
||||||
["speedcontroldecrease"] = ("Zmniejszenie prędkości utrzymywanej przez tempomat", "Cruise control speed down"),
|
|
||||||
["speedcontrolpowerincrease"] = ("Zwiększenie maksymalnego poziomu mocy dostępnej dla tempomatu", "More power for the cruise control"),
|
|
||||||
["speedcontrolpowerdecrease"] = ("Zmniejszenie maksymalnego poziomu mocy dostępnej dla tempomatu", "Less power for the cruise control"),
|
|
||||||
["speedcontrolbutton0"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 0", "Cruise control preset speed 0"),
|
|
||||||
["speedcontrolbutton1"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 1", "Cruise control preset speed 1"),
|
|
||||||
["speedcontrolbutton2"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 2", "Cruise control preset speed 2"),
|
|
||||||
["speedcontrolbutton3"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 3", "Cruise control preset speed 3"),
|
|
||||||
["speedcontrolbutton4"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 4", "Cruise control preset speed 4"),
|
|
||||||
["speedcontrolbutton5"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 5", "Cruise control preset speed 5"),
|
|
||||||
["speedcontrolbutton6"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 6", "Cruise control preset speed 6"),
|
|
||||||
["speedcontrolbutton7"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 7", "Cruise control preset speed 7"),
|
|
||||||
["speedcontrolbutton8"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 8", "Cruise control preset speed 8"),
|
|
||||||
["speedcontrolbutton9"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 9", "Cruise control preset speed 9"),
|
|
||||||
["inverterenable1"] = ("Włączenie falownika 1", "Turn inverter 1 on"),
|
|
||||||
["inverterenable2"] = ("Włączenie falownika 2", "Turn inverter 2 on"),
|
|
||||||
["inverterenable3"] = ("Włączenie falownika 3", "Turn inverter 3 on"),
|
|
||||||
["inverterenable4"] = ("Włączenie falownika 4", "Turn inverter 4 on"),
|
|
||||||
["inverterenable5"] = ("Włączenie falownika 5", "Turn inverter 5 on"),
|
|
||||||
["inverterenable6"] = ("Włączenie falownika 6", "Turn inverter 6 on"),
|
|
||||||
["inverterenable7"] = ("Włączenie falownika 7", "Turn inverter 7 on"),
|
|
||||||
["inverterenable8"] = ("Włączenie falownika 8", "Turn inverter 8 on"),
|
|
||||||
["inverterenable9"] = ("Włączenie falownika 9", "Turn inverter 9 on"),
|
|
||||||
["inverterenable10"] = ("Włączenie falownika 10", "Turn inverter 10 on"),
|
|
||||||
["inverterenable11"] = ("Włączenie falownika 11", "Turn inverter 11 on"),
|
|
||||||
["inverterenable12"] = ("Włączenie falownika 12", "Turn inverter 12 on"),
|
|
||||||
["inverterdisable1"] = ("Wyłączenie falownika 1", "Turn inverter 1 off"),
|
|
||||||
["inverterdisable2"] = ("Wyłączenie falownika 2", "Turn inverter 2 off"),
|
|
||||||
["inverterdisable3"] = ("Wyłączenie falownika 3", "Turn inverter 3 off"),
|
|
||||||
["inverterdisable4"] = ("Wyłączenie falownika 4", "Turn inverter 4 off"),
|
|
||||||
["inverterdisable5"] = ("Wyłączenie falownika 5", "Turn inverter 5 off"),
|
|
||||||
["inverterdisable6"] = ("Wyłączenie falownika 6", "Turn inverter 6 off"),
|
|
||||||
["inverterdisable7"] = ("Wyłączenie falownika 7", "Turn inverter 7 off"),
|
|
||||||
["inverterdisable8"] = ("Wyłączenie falownika 8", "Turn inverter 8 off"),
|
|
||||||
["inverterdisable9"] = ("Wyłączenie falownika 9", "Turn inverter 9 off"),
|
|
||||||
["inverterdisable10"] = ("Wyłączenie falownika 10", "Turn inverter 10 off"),
|
|
||||||
["inverterdisable11"] = ("Wyłączenie falownika 11", "Turn inverter 11 off"),
|
|
||||||
["inverterdisable12"] = ("Wyłączenie falownika 12", "Turn inverter 12 off"),
|
|
||||||
["invertertoggle1"] = ("Przełączenie falownika 1", "Toggle inverter 1"),
|
|
||||||
["invertertoggle2"] = ("Przełączenie falownika 2", "Toggle inverter 2"),
|
|
||||||
["invertertoggle3"] = ("Przełączenie falownika 3", "Toggle inverter 3"),
|
|
||||||
["invertertoggle4"] = ("Przełączenie falownika 4", "Toggle inverter 4"),
|
|
||||||
["invertertoggle5"] = ("Przełączenie falownika 5", "Toggle inverter 5"),
|
|
||||||
["invertertoggle6"] = ("Przełączenie falownika 6", "Toggle inverter 6"),
|
|
||||||
["invertertoggle7"] = ("Przełączenie falownika 7", "Toggle inverter 7"),
|
|
||||||
["invertertoggle8"] = ("Przełączenie falownika 8", "Toggle inverter 8"),
|
|
||||||
["invertertoggle9"] = ("Przełączenie falownika 9", "Toggle inverter 9"),
|
|
||||||
["invertertoggle10"] = ("Przełączenie falownika 10", "Toggle inverter 10"),
|
|
||||||
["invertertoggle11"] = ("Przełączenie falownika 11", "Toggle inverter 11"),
|
|
||||||
["invertertoggle12"] = ("Przełączenie falownika 12", "Toggle inverter 12"),
|
|
||||||
["vehiclemoveforwards"] = ("Przesunięcie pojazdu do przodu", "Move the vehicle forwards"),
|
|
||||||
["vehiclemovebackwards"] = ("Przesunięcie pojazdu do tyłu", "Move the vehicle backwards"),
|
|
||||||
["vehicleboost"] = ("Przyspieszenie pojazdu", "Boost the vehicle"),
|
|
||||||
["wiperswitchincrease"] = ("Szybsza praca wycieraczek", "Wipers faster"),
|
|
||||||
["wiperswitchdecrease"] = ("Wolniejsza praca wycieraczek", "Wipers slower"),
|
|
||||||
["lightsset"] = ("Ustawienie świateł", "Set the lights"),
|
|
||||||
["oilfuelpumptoggle"] = ("Przełączenie pomp oleju i paliwa", "Toggle the oil and fuel pumps"),
|
|
||||||
["linebreakertoggleb"] = ("Przełączenie wyłącznika szybkiego B", "Toggle line breaker B"),
|
|
||||||
["linebreakeropenb"] = ("Wyłączenie wyłącznika szybkiego B", "Open line breaker B"),
|
|
||||||
["linebreakercloseb"] = ("Załączenie wyłącznika szybkiego B", "Close line breaker B"),
|
|
||||||
["linebreakertogglec"] = ("Przełączenie wyłącznika szybkiego C", "Toggle line breaker C"),
|
|
||||||
["linebreakeropenc"] = ("Wyłączenie wyłącznika szybkiego C", "Open line breaker C"),
|
|
||||||
["linebreakerclosec"] = ("Załączenie wyłącznika szybkiego C", "Close line breaker C"),
|
|
||||||
};
|
|
||||||
|
|
||||||
/// <summary>The text of <paramref name="command"/>, Polish for "pl", else English; its name when unknown.</summary>
|
|
||||||
public static string Of(string command, string languageCode) =>
|
|
||||||
Texts.TryGetValue(command, out var text) ? languageCode == "pl" ? text.Polish : text.English : command;
|
|
||||||
|
|
||||||
/// <summary>The commands there are texts for.</summary>
|
|
||||||
public static IEnumerable<string> Commands => Texts.Keys;
|
|
||||||
}
|
|
||||||
@@ -14,10 +14,6 @@
|
|||||||
<PackageReference Include="Avalonia" Version="12.1.4" />
|
<PackageReference Include="Avalonia" Version="12.1.4" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<InternalsVisibleTo Include="StarterNG.Tests" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Eu07.BlackBox\Eu07.BlackBox.csproj" />
|
<ProjectReference Include="..\Eu07.BlackBox\Eu07.BlackBox.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -155,9 +155,7 @@ public sealed class EventList : ListBox
|
|||||||
var culture = CultureInfo.CurrentCulture;
|
var culture = CultureInfo.CurrentCulture;
|
||||||
var events = new List<BlackBoxEvent>();
|
var events = new List<BlackBoxEvent>();
|
||||||
foreach (var c in recording.UserCommands())
|
foreach (var c in recording.UserCommands())
|
||||||
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"],
|
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"], c.Name), Palette.Command, false));
|
||||||
strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]),
|
|
||||||
Palette.Command, false));
|
|
||||||
foreach (var d in recording.DriverChanges)
|
foreach (var d in recording.DriverChanges)
|
||||||
{
|
{
|
||||||
if (recording.CabAt(d.Time + 0.5) is not { } s || s.Vehicle != d.Vehicle)
|
if (recording.CabAt(d.Time + 0.5) is not { } s || s.Vehicle != d.Vehicle)
|
||||||
@@ -178,7 +176,14 @@ public sealed class EventList : ListBox
|
|||||||
foreach (var horn in recording.UserHornChecks())
|
foreach (var horn in recording.UserHornChecks())
|
||||||
events.Add(new BlackBoxEvent(horn.Request.Time, strings[horn.Sounded ? "EventHornSounded" : "EventHornMissed"],
|
events.Add(new BlackBoxEvent(horn.Request.Time, strings[horn.Sounded ? "EventHornSounded" : "EventHornMissed"],
|
||||||
horn.Sounded ? Palette.HornPoint : Palette.Bad, !horn.Sounded));
|
horn.Sounded ? Palette.HornPoint : Palette.Bad, !horn.Sounded));
|
||||||
AddSecurity(recording, strings, events, culture);
|
foreach (var span in recording.SecurityBrakings())
|
||||||
|
{
|
||||||
|
// Which of them was not acknowledged: the lamps blinking when it braked.
|
||||||
|
string who = recording.CabAt(span.Start) is { } s
|
||||||
|
? s.Has(SecurityFlags.CabSignal) && s.Has(SecurityFlags.Vigilance) ? "CA/SHP" : s.Has(SecurityFlags.CabSignal) ? "SHP" : "CA"
|
||||||
|
: "CA";
|
||||||
|
events.Add(new BlackBoxEvent(span.Start, string.Format(culture, strings["EventSecurityBraking"], who), Palette.Bad, true));
|
||||||
|
}
|
||||||
AddCameras(recording, strings, events, culture);
|
AddCameras(recording, strings, events, culture);
|
||||||
AddCouplings(recording, strings, events, culture);
|
AddCouplings(recording, strings, events, culture);
|
||||||
AddCabChanges(recording, strings, events, culture);
|
AddCabChanges(recording, strings, events, culture);
|
||||||
@@ -191,45 +196,6 @@ public sealed class EventList : ListBox
|
|||||||
return events.OrderBy(e => e.Time).ToList();
|
return events.OrderBy(e => e.Time).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The train protection: its buzzer, acknowledged or not, and the braking apart. A lamp acknowledged before the
|
|
||||||
/// buzzer is the driving as usual, not told.
|
|
||||||
/// </summary>
|
|
||||||
private static void AddSecurity(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
|
|
||||||
{
|
|
||||||
var brakings = recording.SecurityBrakings();
|
|
||||||
foreach (var span in recording.SecurityAlarms())
|
|
||||||
{
|
|
||||||
// The lamps of all its buzzing samples: one buzzer for both, the other may join it before it's acknowledged.
|
|
||||||
var lamps = recording.Cab.Where(c => c.Time >= span.Start && c.Time <= span.End && (c.VigilanceBuzzer || c.CabSignalBuzzer))
|
|
||||||
.Aggregate(SecurityFlags.None, (all, c) => all | c.Security);
|
|
||||||
string who = ProtectionName(lamps);
|
|
||||||
var before = recording.CabAt(span.Start);
|
|
||||||
string text = brakings.Any(b => b.Start >= span.Start && b.Start <= span.End)
|
|
||||||
? string.Format(culture, strings["EventSecurityAlarmMissed"], who)
|
|
||||||
// Acknowledged when the sample it ended at buzzes no more and doesn't brake, in the same vehicle: not
|
|
||||||
// the end of the recording or a gap in it, nor the power cut or the protection switched off.
|
|
||||||
: recording.CabAt(span.End) is { } after && !after.VigilanceBuzzer && !after.CabSignalBuzzer
|
|
||||||
&& !after.Has(SecurityFlags.Braking) && after.Vehicle == before?.Vehicle
|
|
||||||
? string.Format(culture, strings["EventSecurityAlarmAcknowledged"], who, span.End - span.Start)
|
|
||||||
: string.Format(culture, strings["EventSecurityAlarm"], who);
|
|
||||||
events.Add(new BlackBoxEvent(span.Start, text, Palette.Buzzer, false));
|
|
||||||
}
|
|
||||||
foreach (var span in brakings)
|
|
||||||
events.Add(new BlackBoxEvent(span.Start, string.Format(culture, strings["EventSecurityBraking"],
|
|
||||||
ProtectionName(recording.CabAt(span.Start)?.Security ?? SecurityFlags.None)),
|
|
||||||
Palette.Bad, true));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Which of them it was: the lamps blinking.</summary>
|
|
||||||
private static string ProtectionName(SecurityFlags lamps) =>
|
|
||||||
(lamps & (SecurityFlags.CabSignal | SecurityFlags.Vigilance)) switch
|
|
||||||
{
|
|
||||||
SecurityFlags.CabSignal | SecurityFlags.Vigilance => "CA/SHP",
|
|
||||||
SecurityFlags.CabSignal => "SHP",
|
|
||||||
_ => "CA"
|
|
||||||
};
|
|
||||||
|
|
||||||
private static void AddUserVehicles(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
|
private static void AddUserVehicles(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
|
||||||
{
|
{
|
||||||
UserVehicleChange? before = null;
|
UserVehicleChange? before = null;
|
||||||
@@ -316,8 +282,6 @@ public sealed class EventList : ListBox
|
|||||||
(CabDevices.DoorStep, "DevDoorStep"), (CabDevices.DoorLock, "DevDoorLock"), (CabDevices.SpeedControl, "DevSpeedControl")
|
(CabDevices.DoorStep, "DevDoorStep"), (CabDevices.DoorLock, "DevDoorLock"), (CabDevices.SpeedControl, "DevSpeedControl")
|
||||||
];
|
];
|
||||||
|
|
||||||
private const CabDevices DoorSides = CabDevices.DoorsLeft | CabDevices.DoorsRight | CabDevices.DoorPermitLeft | CabDevices.DoorPermitRight;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// What the driver did in the cab, from one look to the next in the same vehicle: the switches on and off, the
|
/// What the driver did in the cab, from one look to the next in the same vehicle: the switches on and off, the
|
||||||
/// doors opened and closed, the departure signal, the hand brake, the brakes' setting, the radio's channel, the
|
/// doors opened and closed, the departure signal, the hand brake, the brakes' setting, the radio's channel, the
|
||||||
@@ -327,8 +291,7 @@ public sealed class EventList : ListBox
|
|||||||
{
|
{
|
||||||
CabSample? last = null;
|
CabSample? last = null;
|
||||||
bool movingOpen = false;
|
bool movingOpen = false;
|
||||||
// the doors' sides as the driver has them, from the cab the driver is in (CabSample.AsTheCabSees)
|
foreach (var s in recording.Cab)
|
||||||
foreach (var s in recording.Cab.Select(sample => sample.AsTheCabSees))
|
|
||||||
{
|
{
|
||||||
if (last is not { } b || b.Vehicle != s.Vehicle)
|
if (last is not { } b || b.Vehicle != s.Vehicle)
|
||||||
{
|
{
|
||||||
@@ -336,10 +299,8 @@ public sealed class EventList : ListBox
|
|||||||
movingOpen = false;
|
movingOpen = false;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// the other end swaps the sides, and tells nothing of the doors; no cab (0) sees them as the front one does
|
bool Came(CabDevices device) => !b.Has(device) && s.Has(device);
|
||||||
bool sameCab = (b.CabEnd < 0) == (s.CabEnd < 0);
|
bool Went(CabDevices device) => b.Has(device) && !s.Has(device);
|
||||||
bool Came(CabDevices device) => !b.Has(device) && s.Has(device) && (sameCab || (device & DoorSides) == 0);
|
|
||||||
bool Went(CabDevices device) => b.Has(device) && !s.Has(device) && (sameCab || (device & DoorSides) == 0);
|
|
||||||
foreach (var (device, key) in Switched)
|
foreach (var (device, key) in Switched)
|
||||||
{
|
{
|
||||||
if (Came(device))
|
if (Came(device))
|
||||||
|
|||||||
@@ -26,8 +26,6 @@ public static class Palette
|
|||||||
public static readonly IBrush AccentFill = Brush("#177F00");
|
public static readonly IBrush AccentFill = Brush("#177F00");
|
||||||
public static readonly IBrush AccentFillHover = Brush("#1E9000");
|
public static readonly IBrush AccentFillHover = Brush("#1E9000");
|
||||||
public static readonly IBrush AccentText = Brush("#FFFFFF");
|
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");
|
public static readonly IBrush Good = Brush("#4cc46e");
|
||||||
|
|
||||||
/// <summary>A delay: green on time, yellow a little late, red late, blue early.</summary>
|
/// <summary>A delay: green on time, yellow a little late, red late, blue early.</summary>
|
||||||
@@ -81,8 +79,6 @@ public static class Palette
|
|||||||
public static readonly IBrush LampOn = Brush("#4cc46e");
|
public static readonly IBrush LampOn = Brush("#4cc46e");
|
||||||
public static readonly IBrush LampWarning = Brush("#e8c547");
|
public static readonly IBrush LampWarning = Brush("#e8c547");
|
||||||
public static readonly IBrush LampAlarm = Brush("#f0584a");
|
public static readonly IBrush LampAlarm = Brush("#f0584a");
|
||||||
/// <summary>The train protection's buzzer: still to be acknowledged, not braking yet.</summary>
|
|
||||||
public static readonly IBrush Buzzer = Brush("#c77dff");
|
|
||||||
public static readonly IBrush LightWhite = Brush("#fff6d8");
|
public static readonly IBrush LightWhite = Brush("#fff6d8");
|
||||||
public static readonly IBrush LightRed = Brush("#ff3b30");
|
public static readonly IBrush LightRed = Brush("#ff3b30");
|
||||||
public static readonly IBrush Command = Brush("#8b96a3");
|
public static readonly IBrush Command = Brush("#8b96a3");
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
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.");
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,6 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Automation.Peers;
|
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Input;
|
using Avalonia.Input;
|
||||||
using Avalonia.Media;
|
using Avalonia.Media;
|
||||||
@@ -52,67 +51,6 @@ public sealed class TimelineView : Control
|
|||||||
{
|
{
|
||||||
ClipToBounds = true;
|
ClipToBounds = true;
|
||||||
MinHeight = 160;
|
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();
|
public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings();
|
||||||
@@ -162,8 +100,6 @@ public sealed class TimelineView : Control
|
|||||||
public override void Render(DrawingContext context)
|
public override void Render(DrawingContext context)
|
||||||
{
|
{
|
||||||
var size = Bounds.Size;
|
var size = Bounds.Size;
|
||||||
if (IsFocused)
|
|
||||||
context.DrawRectangle(null, Palette.FocusPen, new Rect(size).Deflate(1));
|
|
||||||
var recording = _recording;
|
var recording = _recording;
|
||||||
if (recording is null || recording.Duration <= 0)
|
if (recording is null || recording.Duration <= 0)
|
||||||
return;
|
return;
|
||||||
@@ -309,16 +245,16 @@ public sealed class TimelineView : Control
|
|||||||
rows[2].Add(x0, x1, s.BrakeCylinder > 0.2f ? BrakeShade(s.BrakeCylinder) : null, BandHeight);
|
rows[2].Add(x0, x1, s.BrakeCylinder > 0.2f ? BrakeShade(s.BrakeCylinder) : null, BandHeight);
|
||||||
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
|
||||||
{
|
{
|
||||||
// The alerter and the cab signalling apart: the lamp, then its buzzer, red when it braked.
|
// The alerter and the cab signalling apart, red when not acknowledged in time.
|
||||||
rows[3].Add(x0, x1, s.VigilanceBuzzer ? Palette.Buzzer
|
rows[3].Add(x0, x1, s.Has(SecurityFlags.VigilanceBeeping) ? Palette.LampAlarm
|
||||||
: s.Has(SecurityFlags.Vigilance) ? Palette.Vigilance : null, BandHeight);
|
: s.Has(SecurityFlags.Vigilance) ? Palette.Vigilance : null, BandHeight);
|
||||||
rows[4].Add(x0, x1, s.CabSignalBuzzer ? Palette.Buzzer
|
rows[4].Add(x0, x1, s.Has(SecurityFlags.CabSignalBeeping) ? Palette.LampAlarm
|
||||||
: s.Has(SecurityFlags.CabSignal) ? Palette.CabSignal : null, BandHeight);
|
: s.Has(SecurityFlags.CabSignal) ? Palette.CabSignal : null, BandHeight);
|
||||||
if (s.ProtectionBraking)
|
if (s.Has(SecurityFlags.Braking))
|
||||||
rows[s.Has(SecurityFlags.CabSignal) && !s.Has(SecurityFlags.Vigilance) ? 4 : 3].Add(x0, x1, Palette.Bad, BandHeight);
|
rows[s.Has(SecurityFlags.CabSignal) && !s.Has(SecurityFlags.Vigilance) ? 4 : 3].Add(x0, x1, Palette.Bad, BandHeight);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
|
rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm
|
||||||
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.Vigilance : null, BandHeight);
|
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.Vigilance : null, BandHeight);
|
||||||
// Where the user looked from: the samples go on in time, and so does the camera.
|
// Where the user looked from: the samples go on in time, and so does the camera.
|
||||||
while (camera + 1 < cameras.Count && cameras[camera + 1].Time <= s.Time)
|
while (camera + 1 < cameras.Count && cameras[camera + 1].Time <= s.Time)
|
||||||
@@ -590,8 +526,7 @@ public sealed class TimelineView : Control
|
|||||||
foreach (var d in recording.DriverChanges)
|
foreach (var d in recording.DriverChanges)
|
||||||
Consider(d.Time, () => Strings[d.Driving == Driver.Ai ? "TlAutopilotOn" : "TlAutopilotOff"]);
|
Consider(d.Time, () => Strings[d.Driving == Driver.Ai ? "TlAutopilotOn" : "TlAutopilotOff"]);
|
||||||
foreach (var c in recording.UserCommands())
|
foreach (var c in recording.UserCommands())
|
||||||
Consider(c.Time, () => string.Format(culture, Strings["TlCommand"],
|
Consider(c.Time, () => string.Format(culture, Strings["TlCommand"], c.Name));
|
||||||
Strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]));
|
|
||||||
}
|
}
|
||||||
return found;
|
return found;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Linq;
|
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Automation.Peers;
|
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Input;
|
using Avalonia.Input;
|
||||||
using Avalonia.Media;
|
using Avalonia.Media;
|
||||||
@@ -38,84 +36,6 @@ public sealed class TimetablePanel : Control
|
|||||||
{
|
{
|
||||||
ClipToBounds = true;
|
ClipToBounds = true;
|
||||||
Cursor = new Cursor(StandardCursorType.Hand);
|
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
|
public Recording? Recording
|
||||||
@@ -183,8 +103,6 @@ public sealed class TimetablePanel : Control
|
|||||||
{
|
{
|
||||||
var size = Bounds.Size;
|
var size = Bounds.Size;
|
||||||
var culture = CultureInfo.CurrentCulture;
|
var culture = CultureInfo.CurrentCulture;
|
||||||
if (IsFocused)
|
|
||||||
context.DrawRectangle(null, Palette.FocusPen, new Rect(size).Deflate(1));
|
|
||||||
if (_timetable is not { } timetable)
|
if (_timetable is not { } timetable)
|
||||||
{
|
{
|
||||||
context.DrawText(MapView.Text(Strings["TimetableNone"], Palette.DimText, 12), new Point(Pad, Pad));
|
context.DrawText(MapView.Text(Strings["TimetableNone"], Palette.DimText, 12), new Point(Pad, Pad));
|
||||||
@@ -212,8 +130,6 @@ public sealed class TimetablePanel : Control
|
|||||||
}
|
}
|
||||||
else if (i == _hover)
|
else if (i == _hover)
|
||||||
context.DrawRectangle(Palette.Faded(Palette.CardHover, 0.6), null, new Rect(0, top, size.Width, RowHeight - 1));
|
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.
|
// The line of the route through the stations, a dot each: hollow ahead, filled when done.
|
||||||
var outcome = row.Outcome;
|
var outcome = row.Outcome;
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Automation;
|
|
||||||
using Avalonia.Automation.Peers;
|
|
||||||
using Avalonia.Automation.Provider;
|
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Controls.Primitives;
|
using Avalonia.Controls.Primitives;
|
||||||
using Avalonia.Layout;
|
using Avalonia.Layout;
|
||||||
@@ -238,13 +235,10 @@ internal static class UiKit
|
|||||||
BorderBrush = Palette.CardBorder;
|
BorderBrush = Palette.CardBorder;
|
||||||
BorderThickness = new Thickness(0, 0, 0, 1);
|
BorderThickness = new Thickness(0, 0, 0, 1);
|
||||||
Child = _row;
|
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++)
|
for (int i = 0; i < choices.Length; i++)
|
||||||
{
|
{
|
||||||
int index = i;
|
int index = i;
|
||||||
var button = new SegmentButton
|
var button = new Button
|
||||||
{
|
{
|
||||||
Content = choices[i],
|
Content = choices[i],
|
||||||
Padding = new Thickness(14, 3),
|
Padding = new Thickness(14, 3),
|
||||||
@@ -273,9 +267,8 @@ internal static class UiKit
|
|||||||
_selected = value;
|
_selected = value;
|
||||||
for (int i = 0; i < _row.Children.Count; i++)
|
for (int i = 0; i < _row.Children.Count; i++)
|
||||||
{
|
{
|
||||||
var button = (SegmentButton)_row.Children[i];
|
var button = (Button)_row.Children[i];
|
||||||
bool on = i == value;
|
bool on = i == value;
|
||||||
button.IsOn = on;
|
|
||||||
var line = on ? Palette.Accent : Brushes.Transparent;
|
var line = on ? Palette.Accent : Brushes.Transparent;
|
||||||
button.Background = on ? Palette.Panel : Brushes.Transparent;
|
button.Background = on ? Palette.Panel : Brushes.Transparent;
|
||||||
button.BorderBrush = line;
|
button.BorderBrush = line;
|
||||||
@@ -287,51 +280,4 @@ 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()
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -172,9 +172,6 @@ public sealed class BlackBoxReader
|
|||||||
Extra = new CabExtra((EngineKind)r.U8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32(),
|
Extra = new CabExtra((EngineKind)r.U8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32(),
|
||||||
r.F32(), r.F32(), r.F32(), r.I8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32())
|
r.F32(), r.F32(), r.F32(), r.I8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32())
|
||||||
};
|
};
|
||||||
// The speed of the wheels, later again.
|
|
||||||
if (sample.Extra is not null && r.Remaining >= 4)
|
|
||||||
sample = sample with { WheelSpeedKmh = r.F32() };
|
|
||||||
rec.AddCab(sample);
|
rec.AddCab(sample);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -520,13 +520,7 @@ public sealed class Recording
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>When the train protection braked the user's train: the alerter or the cab signalling not acknowledged.</summary>
|
/// <summary>When the train protection braked the user's train: the alerter or the cab signalling not acknowledged.</summary>
|
||||||
public IReadOnlyList<TimeSpanRange> SecurityBrakings() => CabSpans(s => s.ProtectionBraking);
|
public IReadOnlyList<TimeSpanRange> SecurityBrakings() => CabSpans(s => s.Has(SecurityFlags.Braking));
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// When the train protection's buzzer sounded in the user's cab: a lamp not acknowledged in time, the braking to
|
|
||||||
/// follow unless acknowledged on. Until it ends, braking included.
|
|
||||||
/// </summary>
|
|
||||||
public IReadOnlyList<TimeSpanRange> SecurityAlarms() => CabSpans(s => s.VigilanceBuzzer || s.CabSignalBuzzer);
|
|
||||||
|
|
||||||
/// <summary>The commands the user gave in a vehicle, presses only.</summary>
|
/// <summary>The commands the user gave in a vehicle, presses only.</summary>
|
||||||
public IEnumerable<CommandEntry> UserCommands() => _commands.Where(c => c.Pressed && c.Vehicle != 0);
|
public IEnumerable<CommandEntry> UserCommands() => _commands.Where(c => c.Pressed && c.Vehicle != 0);
|
||||||
|
|||||||
@@ -366,50 +366,11 @@ public readonly record struct CabSample(double Time, int Vehicle, Position Posit
|
|||||||
Lights LightsHead, Lights LightsTail, sbyte CabEnd = 0,
|
Lights LightsHead, Lights LightsTail, sbyte CabEnd = 0,
|
||||||
SecurityFlags Security = SecurityFlags.None, float LateralAcceleration = 0,
|
SecurityFlags Security = SecurityFlags.None, float LateralAcceleration = 0,
|
||||||
Movement Movement = Movement.Unknown, short LightHintHead = -1, short LightHintTail = -1,
|
Movement Movement = Movement.Unknown, short LightHintHead = -1, short LightHintTail = -1,
|
||||||
Lights? EquippedHead = null, Lights? EquippedTail = null, CabExtra? Extra = null,
|
Lights? EquippedHead = null, Lights? EquippedTail = null, CabExtra? Extra = null)
|
||||||
float? WheelSpeedKmh = null)
|
|
||||||
{
|
{
|
||||||
// WheelSpeedKmh: the speed of the wheels as they turn, which the speedometer shows, signed as SpeedKmh; apart
|
|
||||||
// from it while they slip, 0 while they are locked in a skid. None in a recording made before it.
|
|
||||||
|
|
||||||
public bool Has(CabDevices device) => (Devices & device) == device;
|
public bool Has(CabDevices device) => (Devices & device) == device;
|
||||||
public bool Has(SecurityFlags flag) => (Security & flag) == flag;
|
public bool Has(SecurityFlags flag) => (Security & flag) == flag;
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The alerter's buzzer: its lamp not acknowledged in time. A protection with one acknowledgement for both tells
|
|
||||||
/// the cab signalling's buzzer as the alerter's too, so the alerter's lamp has to blink with it.
|
|
||||||
/// </summary>
|
|
||||||
public bool VigilanceBuzzer => Has(SecurityFlags.VigilanceBeeping) && Has(SecurityFlags.Vigilance);
|
|
||||||
|
|
||||||
/// <summary>The cab signalling's buzzer: its lamp not acknowledged in time.</summary>
|
|
||||||
public bool CabSignalBuzzer => Has(SecurityFlags.CabSignalBeeping);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The train protection braking for an alarm not acknowledged, its lamp blinking. Braking with no lamp is the
|
|
||||||
/// protection with no power (TSecuritySystem::is_braking), a cab not started or a power cut: no driver's fault.
|
|
||||||
/// </summary>
|
|
||||||
public bool ProtectionBraking => Has(SecurityFlags.Braking) && (Has(SecurityFlags.Vigilance) || Has(SecurityFlags.CabSignal));
|
|
||||||
|
|
||||||
private const CabDevices LeftDoors = CabDevices.DoorsLeft | CabDevices.DoorPermitLeft;
|
|
||||||
private const CabDevices RightDoors = CabDevices.DoorsRight | CabDevices.DoorPermitRight;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The doors as the driver has them: the recording holds the left and right of the vehicle, and from its rear
|
|
||||||
/// cab the driver's left is the vehicle's right, as the simulator works the doors from it. Out of a cab, the
|
|
||||||
/// vehicle's.
|
|
||||||
/// </summary>
|
|
||||||
public CabSample AsTheCabSees =>
|
|
||||||
CabEnd >= 0
|
|
||||||
? this
|
|
||||||
: this with
|
|
||||||
{
|
|
||||||
Devices = (Devices & ~(LeftDoors | RightDoors))
|
|
||||||
| ((Devices & CabDevices.DoorsLeft) != 0 ? CabDevices.DoorsRight : 0)
|
|
||||||
| ((Devices & CabDevices.DoorsRight) != 0 ? CabDevices.DoorsLeft : 0)
|
|
||||||
| ((Devices & CabDevices.DoorPermitLeft) != 0 ? CabDevices.DoorPermitRight : 0)
|
|
||||||
| ((Devices & CabDevices.DoorPermitRight) != 0 ? CabDevices.DoorPermitLeft : 0)
|
|
||||||
};
|
|
||||||
|
|
||||||
public bool AiValid => (Flags & CabFlags.AiValid) != 0;
|
public bool AiValid => (Flags & CabFlags.AiValid) != 0;
|
||||||
public bool InCab => (Flags & CabFlags.InCab) != 0;
|
public bool InCab => (Flags & CabFlags.InCab) != 0;
|
||||||
public float AbsSpeedKmh => Math.Abs(SpeedKmh);
|
public float AbsSpeedKmh => Math.Abs(SpeedKmh);
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
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";
|
|
||||||
}
|
|
||||||
@@ -109,7 +109,7 @@ internal sealed class BlackBoxFile
|
|||||||
uint devices = 0x0007, bool extended = true, sbyte cabEnd = 1, byte security = 0,
|
uint devices = 0x0007, bool extended = true, sbyte cabEnd = 1, byte security = 0,
|
||||||
float lateral = 0.2f, ushort lightsHead = 0x15, ushort lightsTail = 0x22, byte? movement = null,
|
float lateral = 0.2f, ushort lightsHead = 0x15, ushort lightsTail = 0x22, byte? movement = null,
|
||||||
short hintHead = -1, short hintTail = -1, ushort? equippedHead = null, ushort? equippedTail = null,
|
short hintHead = -1, short hintTail = -1, ushort? equippedHead = null, ushort? equippedTail = null,
|
||||||
byte? engine = null, float oilTemperature = 70, float? wheelSpeed = null) =>
|
byte? engine = null, float oilTemperature = 70) =>
|
||||||
Record(0x20, w =>
|
Record(0x20, w =>
|
||||||
{
|
{
|
||||||
w.Write(time);
|
w.Write(time);
|
||||||
@@ -181,9 +181,6 @@ internal sealed class BlackBoxFile
|
|||||||
w.Write(1.0f); // clutch
|
w.Write(1.0f); // clutch
|
||||||
w.Write(0.0f); // torque converter
|
w.Write(0.0f); // torque converter
|
||||||
w.Write(2.5f); // the highest brake cylinder of the train
|
w.Write(2.5f); // the highest brake cylinder of the train
|
||||||
// the speed of the wheels: a recording made before it ends above
|
|
||||||
if (wheelSpeed is { } wheels)
|
|
||||||
w.Write(wheels);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,15 +60,13 @@ public class BlackBoxListingTests
|
|||||||
public void Black_boxes_with_no_launch_noted_go_with_the_tapes_written_about_the_same_time()
|
public void Black_boxes_with_no_launch_noted_go_with_the_tapes_written_about_the_same_time()
|
||||||
{
|
{
|
||||||
var early = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
|
var early = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||||
// named in the local time they started at, whatever the zone the tests run in
|
|
||||||
string first = Box("td", early.AddHours(-1)), second = Box("td", early.AddMinutes(30));
|
|
||||||
var installation = new TestInstallation(new InMemoryFileSystem()
|
var installation = new TestInstallation(new InMemoryFileSystem()
|
||||||
.WithFile(Log("a.dat"), "t")
|
.WithFile(Log("a.dat"), "t")
|
||||||
.WithFile(Log(first), "b")
|
.WithFile(Log("td_2026-03-01_11-00-00.blackbox"), "b")
|
||||||
.WithFile(Log(second), "b")
|
.WithFile(Log("td_2026-03-01_12-30-00.blackbox"), "b")
|
||||||
.WrittenAt(Log("a.dat"), early)
|
.WrittenAt(Log("a.dat"), early)
|
||||||
.WrittenAt(Log(first), early.AddSeconds(2))
|
.WrittenAt(Log("td_2026-03-01_11-00-00.blackbox"), early.AddSeconds(2))
|
||||||
.WrittenAt(Log(second), early.AddHours(1)));
|
.WrittenAt(Log("td_2026-03-01_12-30-00.blackbox"), early.AddHours(1)));
|
||||||
|
|
||||||
var sessions = installation.Tapes.Sessions();
|
var sessions = installation.Tapes.Sessions();
|
||||||
|
|
||||||
@@ -76,59 +74,12 @@ public class BlackBoxListingTests
|
|||||||
Assert.All(sessions, session => Assert.Null(session.Launch));
|
Assert.All(sessions, session => Assert.Null(session.Launch));
|
||||||
// Newest first: the black box on its own, then the run with the tape.
|
// Newest first: the black box on its own, then the run with the tape.
|
||||||
Assert.Empty(sessions[0].Tapes);
|
Assert.Empty(sessions[0].Tapes);
|
||||||
Assert.EndsWith(second, Assert.Single(sessions[0].BlackBoxes).Path);
|
Assert.EndsWith("12-30-00.blackbox", Assert.Single(sessions[0].BlackBoxes).Path);
|
||||||
Assert.Single(sessions[1].Tapes);
|
Assert.Single(sessions[1].Tapes);
|
||||||
Assert.EndsWith(first, Assert.Single(sessions[1].BlackBoxes).Path);
|
Assert.EndsWith("11-00-00.blackbox", Assert.Single(sessions[1].BlackBoxes).Path);
|
||||||
Assert.Equal(early, sessions[1].StartedUtc);
|
Assert.Equal(early, sessions[1].StartedUtc);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void The_tape_of_a_vehicle_left_early_in_a_run_with_no_launch_goes_with_its_black_box()
|
|
||||||
{
|
|
||||||
// The black box writes the tapes as it goes: that of the vehicle the player left after ten minutes ends
|
|
||||||
// twenty minutes before the run, that of the next one with it.
|
|
||||||
var started = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
|
|
||||||
string box = Box("td", started);
|
|
||||||
var installation = new TestInstallation(new InMemoryFileSystem()
|
|
||||||
.WithFile(Log("first.dat"), "t")
|
|
||||||
.WithFile(Log("second.dat"), "t")
|
|
||||||
.WithFile(Log(box), "b")
|
|
||||||
.WrittenAt(Log("first.dat"), started.AddMinutes(10))
|
|
||||||
.WrittenAt(Log(box), started.AddMinutes(30))
|
|
||||||
.WrittenAt(Log("second.dat"), started.AddMinutes(30).AddSeconds(1)));
|
|
||||||
|
|
||||||
var session = Assert.Single(installation.Tapes.Sessions());
|
|
||||||
|
|
||||||
Assert.Null(session.Launch);
|
|
||||||
Assert.Equal(new[] { "first", "second" }, session.Tapes.Select(tape => tape.Vehicle).Order());
|
|
||||||
Assert.EndsWith(box, Assert.Single(session.BlackBoxes).Path);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_black_box_downloaded_later_takes_in_no_tapes_of_the_runs_after_it()
|
|
||||||
{
|
|
||||||
// Shared and downloaded two weeks later, so last written then; a run of its own with no launch noted since.
|
|
||||||
var shared = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
|
|
||||||
var later = shared.AddDays(7);
|
|
||||||
string old = Box("td", shared), own = Box("td", later);
|
|
||||||
var installation = new TestInstallation(new InMemoryFileSystem()
|
|
||||||
.WithFile(Log(old), "b").WrittenAt(Log(old), shared.AddDays(14))
|
|
||||||
.WithFile(Log(own), "b").WrittenAt(Log(own), later.AddMinutes(30))
|
|
||||||
.WithFile(Log("ra.dat"), "t").WrittenAt(Log("ra.dat"), later.AddMinutes(30).AddSeconds(1))
|
|
||||||
.WithFile(Log("left.dat"), "t").WrittenAt(Log("left.dat"), later.AddMinutes(10)));
|
|
||||||
|
|
||||||
var recordings = StarterNG.Application.HaslerTapes.Recordings(new[]
|
|
||||||
{
|
|
||||||
new StarterNG.Application.BlackBoxRecording(Log(old), shared.AddDays(14), 1),
|
|
||||||
new StarterNG.Application.BlackBoxRecording(Log(own), later.AddMinutes(30), 1),
|
|
||||||
});
|
|
||||||
Assert.EndsWith(own, StarterNG.Application.HaslerTapes.RecordingAt(later.AddMinutes(10), recordings)!.Path);
|
|
||||||
|
|
||||||
var mine = Assert.Single(installation.Tapes.Sessions(), session => session.Tapes.Count > 0);
|
|
||||||
Assert.Equal(new[] { "left", "ra" }, mine.Tapes.Select(tape => tape.Vehicle).Order());
|
|
||||||
Assert.EndsWith(own, Assert.Single(mine.BlackBoxes).Path);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void The_black_box_of_a_running_session_is_listed_while_it_is_written()
|
public void The_black_box_of_a_running_session_is_listed_while_it_is_written()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -125,20 +125,6 @@ public class HeadCodeTests
|
|||||||
Assert.Null(cab[1].Extra);
|
Assert.Null(cab[1].Extra);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void The_speed_of_the_wheels_is_read_when_written()
|
|
||||||
{
|
|
||||||
var f = new BlackBoxFile().Info();
|
|
||||||
// the wheels slipping at 40 km/h
|
|
||||||
f.Cab(0, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1, wheelSpeed: 55.5f);
|
|
||||||
f.Cab(0.5, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1);
|
|
||||||
var cab = BlackBoxReader.Read(f.End(1).Stream()).Cab;
|
|
||||||
Assert.Equal(55.5f, cab[0].WheelSpeedKmh);
|
|
||||||
Assert.Equal(40f, cab[0].SpeedKmh);
|
|
||||||
// an older sample has none
|
|
||||||
Assert.Null(cab[1].WheelSpeedKmh);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void A_vehicle_with_no_lamps_is_not_judged()
|
public void A_vehicle_with_no_lamps_is_not_judged()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,312 +0,0 @@
|
|||||||
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 Wheels_turning_apart_from_the_train_are_said_beside_its_speed()
|
|
||||||
{
|
|
||||||
var f = new BlackBoxFile().Info()
|
|
||||||
.Vehicle(Head, "EU07-005", "ROJ1")
|
|
||||||
.User(0, Head, true, 1);
|
|
||||||
// slipping for the first ten seconds, then the wheels as fast as the train, give or take the rounding
|
|
||||||
for (double t = 0; t <= 20; t += 0.5)
|
|
||||||
f.Cab(t, Head, 1150 + t * 10, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1,
|
|
||||||
wheelSpeed: t < 10 ? 55.4f : 40.3f);
|
|
||||||
var cab = new CabPanel
|
|
||||||
{
|
|
||||||
Recording = BlackBoxReader.Read(f.End(20).Stream()),
|
|
||||||
Strings = new DefaultBlackBoxStrings("en"),
|
|
||||||
Time = 5
|
|
||||||
};
|
|
||||||
Controls.Lay(cab, 600, 900);
|
|
||||||
|
|
||||||
Controls.Draw(cab);
|
|
||||||
Assert.Contains("40 km/h", cab.Said);
|
|
||||||
Assert.Contains("wheels 55", cab.Said);
|
|
||||||
|
|
||||||
cab.Time = 15;
|
|
||||||
Controls.Draw(cab);
|
|
||||||
Assert.Contains("40 km/h", cab.Said);
|
|
||||||
Assert.DoesNotContain("wheels", cab.Said);
|
|
||||||
}
|
|
||||||
|
|
||||||
[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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
using Eu07.BlackBox;
|
|
||||||
using Eu07.BlackBox.Views;
|
|
||||||
|
|
||||||
namespace StarterNG.Tests.BlackBox;
|
|
||||||
|
|
||||||
// The events are coloured with the views' brushes.
|
|
||||||
[Collection(AvaloniaControls.Name)]
|
|
||||||
public class CabDoorsTests
|
|
||||||
{
|
|
||||||
private static CabSample Sample(sbyte cab, CabDevices devices) =>
|
|
||||||
default(CabSample) with { CabEnd = cab, Devices = devices | CabDevices.Radio };
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void From_the_rear_cab_the_vehicles_right_doors_are_the_drivers_left()
|
|
||||||
{
|
|
||||||
var seen = Sample(-1, CabDevices.DoorsRight | CabDevices.DoorPermitRight).AsTheCabSees;
|
|
||||||
|
|
||||||
Assert.True(seen.Has(CabDevices.DoorsLeft));
|
|
||||||
Assert.True(seen.Has(CabDevices.DoorPermitLeft));
|
|
||||||
Assert.False(seen.Has(CabDevices.DoorsRight));
|
|
||||||
Assert.False(seen.Has(CabDevices.DoorPermitRight));
|
|
||||||
Assert.True(seen.Has(CabDevices.Radio));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(1)]
|
|
||||||
[InlineData(0)]
|
|
||||||
public void From_the_front_cab_or_out_of_one_the_sides_are_the_vehicles(sbyte cab)
|
|
||||||
{
|
|
||||||
var sample = Sample(cab, CabDevices.DoorsLeft | CabDevices.DoorPermitRight);
|
|
||||||
|
|
||||||
Assert.Equal(sample, sample.AsTheCabSees);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Going_to_the_other_cab_tells_nothing_of_the_doors_and_still_tells_the_switches()
|
|
||||||
{
|
|
||||||
var f = new BlackBoxFile().Info().Vehicle(1, "EN57-1001").User(0, 1, true);
|
|
||||||
// the left doors permitted from the front cab; in the rear one the permit is still on, and the radio turned off
|
|
||||||
f.Cab(0, 1, 1000, 0, cabEnd: 1, devices: 0x0007 | (uint)(CabDevices.DoorPermitLeft | CabDevices.Radio));
|
|
||||||
f.Cab(1, 1, 1000, 0, cabEnd: -1, devices: 0x0007 | (uint)CabDevices.DoorPermitLeft);
|
|
||||||
|
|
||||||
var events = EventList.Collect(BlackBoxReader.Read(f.End(1).Stream()), new DefaultBlackBoxStrings("en"))
|
|
||||||
.Select(e => e.Text).ToList();
|
|
||||||
|
|
||||||
Assert.Contains("Radio: off", events);
|
|
||||||
Assert.DoesNotContain(events, e => e.Contains("doors permitted"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
using Eu07.BlackBox;
|
|
||||||
using Eu07.BlackBox.Views;
|
|
||||||
|
|
||||||
namespace StarterNG.Tests.BlackBox;
|
|
||||||
|
|
||||||
[Collection(AvaloniaControls.Name)]
|
|
||||||
public class EventTextsTests
|
|
||||||
{
|
|
||||||
[Theory]
|
|
||||||
[InlineData("pl", "aidriverenable", "Aktywacja automechanika")]
|
|
||||||
[InlineData("en", "aidriverenable", "Engage the AI driver")]
|
|
||||||
[InlineData("pl", "mastercontrollerset", "Ustawienie nastawnika głównego")]
|
|
||||||
[InlineData("pl", "headlightenablerearleft", "Włączenie lewego reflektora z tyłu")]
|
|
||||||
[InlineData("cz", "batteryenable", "Turn the battery on")]
|
|
||||||
public void A_command_is_told_by_what_it_does(string language, string command, string text) =>
|
|
||||||
Assert.Equal(text, new DefaultBlackBoxStrings(language)[DefaultBlackBoxStrings.CommandPrefix + command]);
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_command_with_no_text_keeps_its_name() =>
|
|
||||||
Assert.Equal("somethingnew", new DefaultBlackBoxStrings("pl")[DefaultBlackBoxStrings.CommandPrefix + "somethingnew"]);
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Every_command_has_both_texts_starting_with_a_capital()
|
|
||||||
{
|
|
||||||
foreach (string command in CommandTexts.Commands)
|
|
||||||
foreach (string language in new[] { "pl", "en" })
|
|
||||||
{
|
|
||||||
string text = CommandTexts.Of(command, language);
|
|
||||||
Assert.NotEqual(command, text);
|
|
||||||
Assert.True(char.IsUpper(text[0]), $"{command} ({language}): {text}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void The_events_name_the_commands_by_what_they_do()
|
|
||||||
{
|
|
||||||
var recording = BlackBoxReader.Read(new BlackBoxFile().Info()
|
|
||||||
.Vehicle(1, "EP07-424").User(0, 1, true).Command(12.0, 1, true, "batteryenable").Stream());
|
|
||||||
|
|
||||||
var events = EventList.Collect(recording, new DefaultBlackBoxStrings("pl"));
|
|
||||||
|
|
||||||
Assert.Contains(events, e => e.Text == "Włączenie baterii");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using Eu07.BlackBox;
|
|
||||||
using Eu07.BlackBox.Views;
|
|
||||||
|
|
||||||
namespace StarterNG.Tests.BlackBox;
|
|
||||||
|
|
||||||
[Collection(AvaloniaControls.Name)]
|
|
||||||
public class SecurityBrakingTests
|
|
||||||
{
|
|
||||||
// as the simulator writes them: one acknowledgement for both, so the cab signalling's buzzer is the alerter's too
|
|
||||||
private const byte CabSignal = 0x02, CabSignalBuzzing = 0x0e, CabSignalBraking = 0x1e, NoPower = 0x10;
|
|
||||||
|
|
||||||
private static Recording Drive(System.Func<double, byte> security)
|
|
||||||
{
|
|
||||||
var file = new BlackBoxFile().Info().Vehicle(1, "EP07-424").User(0, 1, true);
|
|
||||||
for (double t = 0; t <= 20; t += 0.5)
|
|
||||||
file.Cab(t, 1, 100, 0, security: security(t));
|
|
||||||
return BlackBoxReader.Read(file.Stream());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<string> Events(Recording recording)
|
|
||||||
{
|
|
||||||
var culture = CultureInfo.CurrentCulture;
|
|
||||||
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return EventList.Collect(recording, new DefaultBlackBoxStrings("pl")).Select(e => e.Text).ToList();
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
CultureInfo.CurrentCulture = culture;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void The_protection_braking_with_no_power_is_not_the_drivers_fault()
|
|
||||||
{
|
|
||||||
// no power for the first seconds, then the cab signalling not acknowledged
|
|
||||||
var recording = Drive(t => t < 5 ? NoPower : t is >= 10 and < 12 ? (byte)0x1a : (byte)0);
|
|
||||||
|
|
||||||
var braking = Assert.Single(recording.SecurityBrakings());
|
|
||||||
Assert.Equal(10, braking.Start, 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_buzzer_acknowledged_in_time_is_told_apart_from_braking()
|
|
||||||
{
|
|
||||||
var recording = Drive(t => t is >= 2 and < 4 ? CabSignal : t is >= 4 and < 5.5 ? CabSignalBuzzing : (byte)0);
|
|
||||||
|
|
||||||
var events = Events(recording);
|
|
||||||
|
|
||||||
Assert.Contains("Brzęczyk SHP, potwierdzony po 1.5 s", events);
|
|
||||||
Assert.DoesNotContain(events, e => e.StartsWith("HAMOWANIE", System.StringComparison.Ordinal));
|
|
||||||
Assert.Empty(recording.SecurityBrakings());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_buzzer_cut_by_the_power_is_not_acknowledged()
|
|
||||||
{
|
|
||||||
var recording = Drive(t => t is >= 2 and < 4 ? CabSignalBuzzing : t is >= 4 and < 8 ? NoPower : (byte)0);
|
|
||||||
|
|
||||||
var events = Events(recording);
|
|
||||||
|
|
||||||
Assert.Contains("Brzęczyk SHP", events);
|
|
||||||
Assert.DoesNotContain(events, e => e.Contains("potwierdzony", System.StringComparison.Ordinal));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_buzzer_the_other_joins_is_named_by_both()
|
|
||||||
{
|
|
||||||
// the alerter's buzzer, then a magnet passed before it's acknowledged
|
|
||||||
var recording = Drive(t => t is >= 2 and < 4 ? (byte)0x05 : t is >= 4 and < 5 ? (byte)0x0f : (byte)0);
|
|
||||||
|
|
||||||
Assert.Contains("Brzęczyk CA/SHP, potwierdzony po 3.0 s", Events(recording));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_buzzer_not_acknowledged_is_followed_by_the_braking()
|
|
||||||
{
|
|
||||||
// the cab signalling at the start: the buzzer at once, braking when not acknowledged
|
|
||||||
var recording = Drive(t => t < 3 ? CabSignalBuzzing : t < 6 ? CabSignalBraking : (byte)0);
|
|
||||||
|
|
||||||
var events = Events(recording);
|
|
||||||
|
|
||||||
Assert.Equal(["Brzęczyk SHP, bez potwierdzenia", "HAMOWANIE PRZEZ SHP"],
|
|
||||||
events.Where(e => e.Contains("SHP", System.StringComparison.Ordinal)));
|
|
||||||
Assert.DoesNotContain(events, e => e.Contains("CA", System.StringComparison.Ordinal));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
using Avalonia;
|
|
||||||
using StarterNG.Views.Tapes;
|
|
||||||
|
|
||||||
namespace StarterNG.Tests;
|
|
||||||
|
|
||||||
/// <summary>The line of a tape, drawn a column of pixels at a time and broken off at a gap.</summary>
|
|
||||||
public class ColumnLineTests
|
|
||||||
{
|
|
||||||
private readonly List<string> _drawn = [];
|
|
||||||
|
|
||||||
private ColumnLine Line() =>
|
|
||||||
new(p => _drawn.Add($"begin {p.X} {p.Y}"), p => _drawn.Add($"line {p.X} {p.Y}"), () => _drawn.Add("end"));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_column_is_entered_where_it_started_and_left_where_it_ended_through_its_lowest_and_highest()
|
|
||||||
{
|
|
||||||
var line = Line();
|
|
||||||
|
|
||||||
// Falling within the column: from its first through its highest and its lowest to its last.
|
|
||||||
foreach (double v in new[] { 3.0, 1.0, 4.0, 2.0 })
|
|
||||||
line.Add(5, v);
|
|
||||||
// Rising: through its lowest first.
|
|
||||||
foreach (double v in new[] { 2.0, 4.0, 1.0, 3.0 })
|
|
||||||
line.Add(6, v);
|
|
||||||
line.Break();
|
|
||||||
|
|
||||||
Assert.Equal(["begin 5 3", "line 5 4", "line 5 1", "line 5 2",
|
|
||||||
"line 6 2", "line 6 1", "line 6 4", "line 6 3", "end"], _drawn);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_break_ends_the_figure_and_the_next_point_begins_another()
|
|
||||||
{
|
|
||||||
var line = Line();
|
|
||||||
|
|
||||||
line.Add(0, 10);
|
|
||||||
line.Break();
|
|
||||||
line.Add(9, 20);
|
|
||||||
line.Break();
|
|
||||||
|
|
||||||
Assert.Equal(["begin 0 10", "line 0 10", "line 0 10", "line 0 10", "end",
|
|
||||||
"begin 9 20", "line 9 20", "line 9 20", "line 9 20", "end"], _drawn);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_break_with_nothing_drawn_ends_nothing()
|
|
||||||
{
|
|
||||||
var line = Line();
|
|
||||||
|
|
||||||
line.Break();
|
|
||||||
line.Break();
|
|
||||||
|
|
||||||
Assert.Empty(_drawn);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
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"]));
|
|
||||||
}
|
|
||||||
@@ -6,8 +6,6 @@ using StarterNG.Tests.Fakes;
|
|||||||
|
|
||||||
namespace StarterNG.Tests;
|
namespace StarterNG.Tests;
|
||||||
|
|
||||||
// Puts in services of its own: not while the controls read theirs.
|
|
||||||
[Collection(AvaloniaControls.Name)]
|
|
||||||
public class ConsistOrientationTests
|
public class ConsistOrientationTests
|
||||||
{
|
{
|
||||||
private readonly VehicleCatalog _catalog;
|
private readonly VehicleCatalog _catalog;
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -1,376 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
namespace StarterNG.Tests.Fakes;
|
|
||||||
|
|
||||||
/// <summary>A stream read from its start to its end and no other way: no length, no seeking.</summary>
|
|
||||||
internal sealed class ForwardOnlyStream(Stream inner) : Stream
|
|
||||||
{
|
|
||||||
public override bool CanRead => true;
|
|
||||||
public override bool CanSeek => false;
|
|
||||||
public override bool CanWrite => false;
|
|
||||||
public override long Length => throw new NotSupportedException();
|
|
||||||
|
|
||||||
public override long Position
|
|
||||||
{
|
|
||||||
get => throw new NotSupportedException();
|
|
||||||
set => throw new NotSupportedException();
|
|
||||||
}
|
|
||||||
|
|
||||||
public override int Read(byte[] buffer, int offset, int count) => inner.Read(buffer, offset, count);
|
|
||||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
|
||||||
public override void SetLength(long value) => throw new NotSupportedException();
|
|
||||||
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
|
||||||
public override void Flush() { }
|
|
||||||
|
|
||||||
protected override void Dispose(bool disposing)
|
|
||||||
{
|
|
||||||
if (disposing)
|
|
||||||
inner.Dispose();
|
|
||||||
base.Dispose(disposing);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -20,7 +20,6 @@ public sealed class InMemoryFileSystem : IFileSystem
|
|||||||
private readonly HashSet<string> _executable;
|
private readonly HashSet<string> _executable;
|
||||||
private readonly Dictionary<string, string> _links;
|
private readonly Dictionary<string, string> _links;
|
||||||
private readonly HashSet<string> _unreadable;
|
private readonly HashSet<string> _unreadable;
|
||||||
private readonly HashSet<string> _unseekable;
|
|
||||||
private readonly HashSet<string> _unlistable;
|
private readonly HashSet<string> _unlistable;
|
||||||
private readonly Dictionary<string, DateTime> _written;
|
private readonly Dictionary<string, DateTime> _written;
|
||||||
|
|
||||||
@@ -33,7 +32,6 @@ public sealed class InMemoryFileSystem : IFileSystem
|
|||||||
_executable = new HashSet<string>(comparer);
|
_executable = new HashSet<string>(comparer);
|
||||||
_links = new Dictionary<string, string>(comparer);
|
_links = new Dictionary<string, string>(comparer);
|
||||||
_unreadable = new HashSet<string>(comparer);
|
_unreadable = new HashSet<string>(comparer);
|
||||||
_unseekable = new HashSet<string>(comparer);
|
|
||||||
_unlistable = new HashSet<string>(comparer);
|
_unlistable = new HashSet<string>(comparer);
|
||||||
_written = new Dictionary<string, DateTime>(comparer);
|
_written = new Dictionary<string, DateTime>(comparer);
|
||||||
}
|
}
|
||||||
@@ -53,13 +51,6 @@ public sealed class InMemoryFileSystem : IFileSystem
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The file opens as a stream read only forward, as a pipe or some network shares give it.</summary>
|
|
||||||
public InMemoryFileSystem OpenedForwardOnly(string path)
|
|
||||||
{
|
|
||||||
_unseekable.Add(Normalize(path));
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public InMemoryFileSystem AllowReading(string path)
|
public InMemoryFileSystem AllowReading(string path)
|
||||||
{
|
{
|
||||||
_unreadable.Remove(Normalize(path));
|
_unreadable.Remove(Normalize(path));
|
||||||
@@ -124,11 +115,7 @@ public sealed class InMemoryFileSystem : IFileSystem
|
|||||||
|
|
||||||
public byte[] ReadAllBytes(string path) => Bytes(path);
|
public byte[] ReadAllBytes(string path) => Bytes(path);
|
||||||
|
|
||||||
public Stream OpenRead(string path)
|
public Stream OpenRead(string path) => new MemoryStream(Bytes(path), writable: false);
|
||||||
{
|
|
||||||
var stream = new MemoryStream(Bytes(path), writable: false);
|
|
||||||
return _unseekable.Contains(Normalize(path)) ? new ForwardOnlyStream(stream) : stream;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void WriteAllText(string path, string contents) => WithFile(path, contents);
|
public void WriteAllText(string path, string contents) => WithFile(path, contents);
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ public sealed class TestInstallation
|
|||||||
{
|
{
|
||||||
public const string Root = "game";
|
public const string Root = "game";
|
||||||
|
|
||||||
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null, bool lacksAvx2 = false)
|
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null)
|
||||||
{
|
{
|
||||||
Files = files ?? new InMemoryFileSystem();
|
Files = files ?? new InMemoryFileSystem();
|
||||||
Paths = new GamePaths(Root);
|
Paths = new GamePaths(Root);
|
||||||
@@ -35,8 +35,7 @@ public sealed class TestInstallation
|
|||||||
SettingsPaths.VehicleCacheDirectory());
|
SettingsPaths.VehicleCacheDirectory());
|
||||||
Library = new GameLibrary(VehicleCache, Sceneries, MiniTextures, Physics, Log);
|
Library = new GameLibrary(VehicleCache, Sceneries, MiniTextures, Physics, Log);
|
||||||
|
|
||||||
// The processor of the machine running the tests is not the one tested.
|
Executables = new ExecutableLocator(Files, Paths, Environment, Log);
|
||||||
Executables = new ExecutableLocator(Files, Paths, Environment, Log, lacksAvx2);
|
|
||||||
SettingsStore = new SettingsStore(Files, Clock, Log, SettingsPaths, new SettingsSerializer(), Executables);
|
SettingsStore = new SettingsStore(Files, Clock, Log, SettingsPaths, new SettingsSerializer(), Executables);
|
||||||
Tapes = new HaslerTapes(Files, Paths, Log, Clock, new TimetableLocator(Files), () => SimulatorRunning);
|
Tapes = new HaslerTapes(Files, Paths, Log, Clock, new TimetableLocator(Files), () => SimulatorRunning);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
using StarterNG.Infrastructure.Adapters;
|
|
||||||
|
|
||||||
namespace StarterNG.Tests;
|
|
||||||
|
|
||||||
public sealed class FolderChangesTests : IDisposable
|
|
||||||
{
|
|
||||||
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10);
|
|
||||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-changes-" + Guid.NewGuid().ToString("N"));
|
|
||||||
|
|
||||||
public FolderChangesTests() => Directory.CreateDirectory(Path.Combine(_root, "sub"));
|
|
||||||
|
|
||||||
public void Dispose() => Directory.Delete(_root, recursive: true);
|
|
||||||
|
|
||||||
private static async Task<bool> Reported(FolderChanges changes, Action change)
|
|
||||||
{
|
|
||||||
var told = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
||||||
changes.Changed += () => told.TrySetResult();
|
|
||||||
change();
|
|
||||||
return await Task.WhenAny(told.Task, Task.Delay(Patience)) == told.Task;
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task A_file_written_below_the_folder_is_reported()
|
|
||||||
{
|
|
||||||
string file = Path.Combine(_root, "sub", "a.scm");
|
|
||||||
File.WriteAllText(file, "old");
|
|
||||||
using var changes = new FolderChanges(_root);
|
|
||||||
|
|
||||||
Assert.True(changes.Watching);
|
|
||||||
Assert.True(await Reported(changes, () => File.WriteAllText(file, "new text")));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task A_save_through_a_renamed_temp_file_is_reported()
|
|
||||||
{
|
|
||||||
string file = Path.Combine(_root, "test.scn");
|
|
||||||
File.WriteAllText(file, "old");
|
|
||||||
using var changes = new FolderChanges(_root);
|
|
||||||
|
|
||||||
Assert.True(await Reported(changes, () =>
|
|
||||||
{
|
|
||||||
string temp = file + ".tmp";
|
|
||||||
File.WriteAllText(temp, "new");
|
|
||||||
File.Move(temp, file, overwrite: true);
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task A_file_removed_is_reported()
|
|
||||||
{
|
|
||||||
string file = Path.Combine(_root, "gone.scn");
|
|
||||||
File.WriteAllText(file, "x");
|
|
||||||
using var changes = new FolderChanges(_root);
|
|
||||||
|
|
||||||
Assert.True(await Reported(changes, () => File.Delete(file)));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_missing_folder_is_not_watched_and_does_not_throw()
|
|
||||||
{
|
|
||||||
using var changes = new FolderChanges(Path.Combine(_root, "nowhere"));
|
|
||||||
|
|
||||||
Assert.False(changes.Watching);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,192 +0,0 @@
|
|||||||
using Avalonia.Controls;
|
|
||||||
using StarterNG.Infrastructure;
|
|
||||||
|
|
||||||
namespace StarterNG.Tests;
|
|
||||||
|
|
||||||
[Collection(AvaloniaControls.Name)]
|
|
||||||
public sealed class FolderLooksTests : IDisposable
|
|
||||||
{
|
|
||||||
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10);
|
|
||||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-looks-" + Guid.NewGuid().ToString("N"));
|
|
||||||
private readonly ManualTime _time = new();
|
|
||||||
private readonly Window _window;
|
|
||||||
private int _looks;
|
|
||||||
|
|
||||||
public FolderLooksTests()
|
|
||||||
{
|
|
||||||
Directory.CreateDirectory(_root);
|
|
||||||
HeadlessDrawing.Ensure();
|
|
||||||
_window = new Window();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
_window.Close();
|
|
||||||
Directory.Delete(_root, recursive: true);
|
|
||||||
}
|
|
||||||
|
|
||||||
private FolderLooks Opened(string folder)
|
|
||||||
{
|
|
||||||
var looks = new FolderLooks(_window, () => folder, () =>
|
|
||||||
{
|
|
||||||
_looks++;
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}, _time);
|
|
||||||
_window.Show();
|
|
||||||
Controls.Settle();
|
|
||||||
_looks = 0;
|
|
||||||
return looks;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ManualTimer Quiet => _time.Timers.Single(t => t.Period == Timeout.InfiniteTimeSpan);
|
|
||||||
private ManualTimer Often => _time.Timers.Single(t => t.Period != Timeout.InfiniteTimeSpan);
|
|
||||||
|
|
||||||
// Waited for without leaving the thread: the window belongs to it.
|
|
||||||
private static void Until(Func<bool> condition) => Assert.True(SpinWait.SpinUntil(condition, Patience), "waited too long");
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Nothing_is_watched_before_the_window_opens()
|
|
||||||
{
|
|
||||||
_ = new FolderLooks(_window, () => _root, () => Task.CompletedTask, _time);
|
|
||||||
|
|
||||||
Assert.Empty(_time.Timers);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_watched_folder_is_looked_at_anyway_seldom()
|
|
||||||
{
|
|
||||||
var looks = Opened(_root);
|
|
||||||
|
|
||||||
Assert.True(looks.Watching);
|
|
||||||
Assert.Equal(FolderLooks.Watched, Often.Due);
|
|
||||||
Assert.Equal(FolderLooks.Watched, Often.Period);
|
|
||||||
Assert.Equal(Timeout.InfiniteTimeSpan, Quiet.Due);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_folder_the_system_reports_nothing_of_is_looked_at_often()
|
|
||||||
{
|
|
||||||
var looks = Opened(Path.Combine(_root, "nowhere"));
|
|
||||||
|
|
||||||
Assert.False(looks.Watching);
|
|
||||||
Assert.Equal(FolderLooks.Unwatched, Often.Period);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_tick_looks_on_the_ui_thread_once_it_gets_there()
|
|
||||||
{
|
|
||||||
Opened(_root);
|
|
||||||
|
|
||||||
Often.Fire();
|
|
||||||
Assert.Equal(0, _looks);
|
|
||||||
Controls.Settle();
|
|
||||||
|
|
||||||
Assert.Equal(1, _looks);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_change_is_looked_at_once_the_reports_stop()
|
|
||||||
{
|
|
||||||
Opened(_root);
|
|
||||||
|
|
||||||
File.WriteAllText(Path.Combine(_root, "test.scn"), "new");
|
|
||||||
Until(() => Quiet.Due == FolderLooks.Quiet);
|
|
||||||
Controls.Settle();
|
|
||||||
Assert.Equal(0, _looks);
|
|
||||||
|
|
||||||
Quiet.Fire();
|
|
||||||
Controls.Settle();
|
|
||||||
|
|
||||||
Assert.Equal(1, _looks);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Coming_back_to_the_window_looks()
|
|
||||||
{
|
|
||||||
Opened(_root);
|
|
||||||
|
|
||||||
_window.Activate();
|
|
||||||
Controls.Settle();
|
|
||||||
|
|
||||||
Assert.Equal(1, _looks);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Asked_it_looks()
|
|
||||||
{
|
|
||||||
var looks = Opened(_root);
|
|
||||||
|
|
||||||
Assert.True(looks.LookAsync().IsCompletedSuccessfully);
|
|
||||||
|
|
||||||
Assert.Equal(1, _looks);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Closed_it_stops_the_timers()
|
|
||||||
{
|
|
||||||
Opened(_root);
|
|
||||||
|
|
||||||
_window.Close();
|
|
||||||
|
|
||||||
Assert.Equal(2, _time.Timers.Count);
|
|
||||||
Assert.All(_time.Timers, t => Assert.True(t.Disposed));
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class ManualTime : TimeProvider
|
|
||||||
{
|
|
||||||
private readonly List<ManualTimer> _timers = new();
|
|
||||||
|
|
||||||
public IReadOnlyList<ManualTimer> Timers
|
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
lock (_timers)
|
|
||||||
return _timers.ToList();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
|
||||||
{
|
|
||||||
var timer = new ManualTimer(() => callback(state), dueTime, period);
|
|
||||||
lock (_timers)
|
|
||||||
_timers.Add(timer);
|
|
||||||
return timer;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class ManualTimer : ITimer
|
|
||||||
{
|
|
||||||
private readonly Action _tick;
|
|
||||||
private long _dueTicks;
|
|
||||||
|
|
||||||
public ManualTimer(Action tick, TimeSpan due, TimeSpan period)
|
|
||||||
{
|
|
||||||
_tick = tick;
|
|
||||||
_dueTicks = due.Ticks;
|
|
||||||
Period = period;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TimeSpan Due => TimeSpan.FromTicks(Interlocked.Read(ref _dueTicks));
|
|
||||||
public TimeSpan Period { get; private set; }
|
|
||||||
public bool Disposed { get; private set; }
|
|
||||||
|
|
||||||
public void Fire() => _tick();
|
|
||||||
|
|
||||||
public bool Change(TimeSpan dueTime, TimeSpan period)
|
|
||||||
{
|
|
||||||
if (Disposed)
|
|
||||||
throw new ObjectDisposedException(nameof(ManualTimer));
|
|
||||||
Interlocked.Exchange(ref _dueTicks, dueTime.Ticks);
|
|
||||||
Period = period;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose() => Disposed = true;
|
|
||||||
|
|
||||||
public ValueTask DisposeAsync()
|
|
||||||
{
|
|
||||||
Dispose();
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,12 +6,12 @@ namespace StarterNG.Tests;
|
|||||||
|
|
||||||
public class HaslerTapeTests
|
public class HaslerTapeTests
|
||||||
{
|
{
|
||||||
internal const string Header =
|
private const string Header =
|
||||||
"Time[s] Velocity[m/s] Acceleration[m/ss] Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] " +
|
"Time[s] Velocity[m/s] Acceleration[m/ss] Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] " +
|
||||||
"BrakeForce[kN] BrakePress[MPa] PipePress[MPa] MotorCurrent[A] MCP SCP BCP LBP Direction Command CVal1 CVal2 " +
|
"BrakeForce[kN] BrakePress[MPa] PipePress[MPa] MotorCurrent[A] MCP SCP BCP LBP Direction Command CVal1 CVal2 " +
|
||||||
"Security Wheelslip EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]\r\n";
|
"Security Wheelslip EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]\r\n";
|
||||||
|
|
||||||
internal static string Line(double t, double v, double brake, double current, string command = "none",
|
private static string Line(double t, double v, double brake, double current, string command = "none",
|
||||||
int security = 0) =>
|
int security = 0) =>
|
||||||
string.Create(CultureInfo.InvariantCulture,
|
string.Create(CultureInfo.InvariantCulture,
|
||||||
$"{t:0.0000} {v:0.0000} 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 {brake:0.0000} 0.5000 {current:0.0000} ") +
|
$"{t:0.0000} {v:0.0000} 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 {brake:0.0000} 0.5000 {current:0.0000} ") +
|
||||||
@@ -68,197 +68,6 @@ public class HaslerTapeTests
|
|||||||
Assert.Equal(5, tape.DistanceM, 6);
|
Assert.Equal(5, tape.DistanceM, 6);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void The_security_flag_is_found_where_the_header_puts_it_with_the_vehicle_speed_at_the_end()
|
|
||||||
{
|
|
||||||
// the simulator's log since 2026-10: a column of the vehicle's speed after the temperatures
|
|
||||||
string header = Header.Replace("WaterAuxTemp[Deg]\r\n", "WaterAuxTemp[Deg] VehicleVelocity[km/h]\r\n");
|
|
||||||
static string WithSpeed(string line, double kmh) =>
|
|
||||||
line.Replace("\r\n", string.Create(CultureInfo.InvariantCulture, $" {kmh:0.0000}\r\n"));
|
|
||||||
// the wheels slipping, the alerter quiet: the column before the speed used to be read as the alerter
|
|
||||||
string slipping = Line(0, 36, 0, 0, security: 0).Replace(" 0 0 0.0000 0.0000 0.0000 0.0000\r\n",
|
|
||||||
" 0 1 0.0000 0.0000 0.0000 0.0000\r\n");
|
|
||||||
|
|
||||||
var tape = HaslerTape.Parse(header + WithSpeed(slipping, 36) + WithSpeed(Line(1, 36, 0, 0, security: 1), 36));
|
|
||||||
|
|
||||||
Assert.Equal(2, tape.Samples.Count);
|
|
||||||
Assert.False(tape.Samples[0].SecurityAlarm);
|
|
||||||
Assert.True(tape.Samples[1].SecurityAlarm);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_command_named_like_a_heading_is_read_as_a_line_not_as_the_header()
|
|
||||||
{
|
|
||||||
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0, command: "Security") + Line(1, 36, 0, 0, security: 1));
|
|
||||||
|
|
||||||
Assert.Equal(2, tape.Samples.Count);
|
|
||||||
Assert.False(tape.Samples[0].SecurityAlarm);
|
|
||||||
Assert.True(tape.Samples[1].SecurityAlarm);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_gap_in_the_time_is_neither_driving_nor_standing_and_covers_no_distance()
|
|
||||||
{
|
|
||||||
// the player in another vehicle for ten minutes, then back in this one
|
|
||||||
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(601, 36, 0, 0)
|
|
||||||
+ Line(602, 36, 0, 0) + Line(603, 0, 0, 0));
|
|
||||||
|
|
||||||
Assert.Equal(603, tape.Duration, 6);
|
|
||||||
Assert.Equal(600, tape.GapTime, 6);
|
|
||||||
Assert.Equal(2, tape.RunningTime, 6);
|
|
||||||
Assert.Equal(1, tape.StandingTime, 6); // the last second, stopping
|
|
||||||
Assert.Equal(10 + 10 + 5, tape.DistanceM, 6);
|
|
||||||
Assert.Equal(25 / 3.0 * 3.6, tape.AverageWithStopsKmh, 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_stall_of_the_simulator_a_little_over_a_second_is_driven_not_a_gap()
|
|
||||||
{
|
|
||||||
// a line every 0.05 s, as at 60 FPS, and one step of 1.017 s: the frame held to a second, and the frame after
|
|
||||||
var text = new System.Text.StringBuilder(Header);
|
|
||||||
double t = 0;
|
|
||||||
for (int i = 0; i < 40; i++, t += 0.05)
|
|
||||||
text.Append(Line(t, 100, 0, 0));
|
|
||||||
t += 1.017 - 0.05;
|
|
||||||
for (int i = 0; i < 40; i++, t += 0.05)
|
|
||||||
text.Append(Line(t, 100, 0, 0));
|
|
||||||
|
|
||||||
var tape = HaslerTape.Parse(text.ToString());
|
|
||||||
|
|
||||||
Assert.Equal(0, tape.GapTime, 6);
|
|
||||||
Assert.Equal(tape.Duration, tape.RunningTime, 6);
|
|
||||||
Assert.Equal(tape.Duration * 100 / 3.6, tape.DistanceM, 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_tape_read_in_pieces_cut_anywhere_is_the_tape_read_whole()
|
|
||||||
{
|
|
||||||
string text = Header + Line(0, 18, 0, 0, command: "Set Velocity") + Line(1, 36, 0.45, 0) + Line(2, 36, 0, 400)
|
|
||||||
+ Line(602, 36, 0, 0, security: 1) + Line(603, 0, 0, 0);
|
|
||||||
var whole = HaslerTape.Parse(text);
|
|
||||||
|
|
||||||
for (int cut = 1; cut < text.Length; cut += 7)
|
|
||||||
{
|
|
||||||
var reader = new HaslerTape.Reader();
|
|
||||||
reader.Feed(text[..cut]);
|
|
||||||
reader.Feed(text[cut..]);
|
|
||||||
Assert.Equal(whole.Samples, reader.Tape(final: true).Samples);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_line_not_ended_waits_for_its_end_while_the_tape_is_followed()
|
|
||||||
{
|
|
||||||
var reader = new HaslerTape.Reader();
|
|
||||||
string line = Line(1, 36, 0, 0);
|
|
||||||
reader.Feed(Header + Line(0, 36, 0, 0) + line[..20]);
|
|
||||||
|
|
||||||
Assert.Single(reader.Tape(final: false).Samples);
|
|
||||||
Assert.Single(reader.Tape(final: false).Samples);
|
|
||||||
reader.Feed(line[20..]);
|
|
||||||
Assert.Equal(2, reader.Tape(final: false).Samples.Count);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_followed_tape_reads_what_was_added_and_one_begun_anew_whole()
|
|
||||||
{
|
|
||||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
|
||||||
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0));
|
|
||||||
var tapes = new TestInstallation(files).Tapes;
|
|
||||||
var file = Assert.Single(tapes.List());
|
|
||||||
|
|
||||||
Assert.Single(tapes.Load(file, follow: false)!.Samples);
|
|
||||||
files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(2, 36, 0, 0));
|
|
||||||
Assert.Equal(3, tapes.Load(file, follow: true)!.Samples.Count);
|
|
||||||
|
|
||||||
// begun anew, and already longer than was read: its time goes back
|
|
||||||
files.WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0) + Line(2, 72, 0, 0) + Line(3, 72, 0, 0));
|
|
||||||
var tape = tapes.Load(file, follow: true)!;
|
|
||||||
Assert.Equal(4, tape.Samples.Count);
|
|
||||||
Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
|
|
||||||
|
|
||||||
// begun anew, and shorter
|
|
||||||
files.WithFile(path, Header + Line(0, 18, 0, 0));
|
|
||||||
Assert.Equal(18, Assert.Single(tapes.Load(file, follow: true)!.Samples).SpeedKmh, 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_log_begun_anew_over_the_end_that_was_read_is_read_whole_once_its_time_goes_back()
|
|
||||||
{
|
|
||||||
// the command is free text, here long enough that the end kept of the read part holds no time
|
|
||||||
string command = new('x', 400);
|
|
||||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
|
||||||
var files = new InMemoryFileSystem().WithFile(path, Header + Line(3, 36, 0, 0, command));
|
|
||||||
var tapes = new TestInstallation(files).Tapes;
|
|
||||||
var file = Assert.Single(tapes.List());
|
|
||||||
Assert.Equal(3, Assert.Single(tapes.Load(file, follow: false)!.Samples).Time, 6);
|
|
||||||
|
|
||||||
// begun anew: where the read part ended it reads as it did, but the lines added go back to the start
|
|
||||||
files.WithFile(path, Header + Line(0, 36, 0, 0, command) + Line(1, 36, 0, 0, command) + Line(2, 36, 0, 0, command));
|
|
||||||
var tape = tapes.Load(file, follow: true)!;
|
|
||||||
|
|
||||||
Assert.Equal([0.0, 1.0, 2.0], tape.Samples.Select(s => s.Time));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_tape_that_cannot_be_read_is_none_and_told_and_is_read_whole_once_it_can()
|
|
||||||
{
|
|
||||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
|
||||||
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0));
|
|
||||||
var installation = new TestInstallation(files);
|
|
||||||
var tapes = installation.Tapes;
|
|
||||||
var file = Assert.Single(tapes.List());
|
|
||||||
tapes.Load(file, follow: false);
|
|
||||||
|
|
||||||
files.FailReading(path);
|
|
||||||
Assert.Null(tapes.Load(file, follow: true));
|
|
||||||
Assert.Contains("EU07-424.dat", installation.Log.Text);
|
|
||||||
|
|
||||||
files.AllowReading(path).WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0));
|
|
||||||
Assert.All(tapes.Load(file, follow: true)!.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_file_read_only_forward_is_read_whole_each_time()
|
|
||||||
{
|
|
||||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
|
||||||
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0)).OpenedForwardOnly(path);
|
|
||||||
var tapes = new TestInstallation(files).Tapes;
|
|
||||||
var file = Assert.Single(tapes.List());
|
|
||||||
|
|
||||||
Assert.Single(tapes.Load(file, follow: true)!.Samples);
|
|
||||||
files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0));
|
|
||||||
Assert.Equal(2, tapes.Load(file, follow: true)!.Samples.Count);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Empty_lines_in_a_log_are_passed_over()
|
|
||||||
{
|
|
||||||
var tape = HaslerTape.Parse(Header + "\r\n" + Line(0, 36, 0, 0) + " \r\n" + Line(1, 36, 0, 0));
|
|
||||||
|
|
||||||
Assert.Equal(2, tape.Samples.Count);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Forgetting_another_file_keeps_the_followed_tape_and_its_own_lets_it_go()
|
|
||||||
{
|
|
||||||
string Lines(int firstSpeed, int count) =>
|
|
||||||
Header + Line(0, firstSpeed, 0, 0) + string.Concat(Enumerable.Range(1, count).Select(t => Line(t, 36, 0, 0)));
|
|
||||||
string path = TestInstallation.At("physicslog", "EU07-424.dat");
|
|
||||||
var files = new InMemoryFileSystem().WithFile(path, Lines(36, 20));
|
|
||||||
var tapes = new TestInstallation(files).Tapes;
|
|
||||||
var file = Assert.Single(tapes.List());
|
|
||||||
tapes.Load(file, follow: false);
|
|
||||||
|
|
||||||
// the first line changed, as long as it was and far from the end: a tape still followed doesn't read it again
|
|
||||||
files.WithFile(path, Lines(72, 21));
|
|
||||||
tapes.Forget(TestInstallation.At("physicslog", "EU07-111.dat"));
|
|
||||||
Assert.Equal(36, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6);
|
|
||||||
|
|
||||||
tapes.Forget(file.Path);
|
|
||||||
Assert.Equal(72, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance()
|
public void The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,96 +0,0 @@
|
|||||||
using Avalonia.Controls;
|
|
||||||
using Avalonia.LogicalTree;
|
|
||||||
using StarterNG.Application;
|
|
||||||
using StarterNG.Domain.Tapes;
|
|
||||||
using StarterNG.Tests.Fakes;
|
|
||||||
using StarterNG.Views.Tapes;
|
|
||||||
|
|
||||||
namespace StarterNG.Tests;
|
|
||||||
|
|
||||||
/// <summary>The tapes' window over the tapes of an installation of its own, read as it is opened.</summary>
|
|
||||||
[Collection(AvaloniaControls.Name)]
|
|
||||||
public class HaslerTapeWindowTests
|
|
||||||
{
|
|
||||||
private static readonly DateTime Launched = new(2025, 12, 31, 23, 0, 0, DateTimeKind.Utc);
|
|
||||||
|
|
||||||
static HaslerTapeWindowTests() => HeadlessDrawing.Ensure();
|
|
||||||
|
|
||||||
private static AppServices Services(InMemoryFileSystem files)
|
|
||||||
{
|
|
||||||
var installation = new TestInstallation(files);
|
|
||||||
installation.Clock.Now = Launched;
|
|
||||||
return AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The window reads the tapes off the UI thread and shows them on it: what it shows is waited for.
|
|
||||||
private static void Until(Func<bool> shown) =>
|
|
||||||
Assert.True(SpinWait.SpinUntil(() =>
|
|
||||||
{
|
|
||||||
Controls.Settle();
|
|
||||||
return shown();
|
|
||||||
}, TimeSpan.FromSeconds(5)));
|
|
||||||
|
|
||||||
private static Button Button(Window window, string key) =>
|
|
||||||
window.GetLogicalDescendants().OfType<Button>().Single(b => b.Content as string == App.Loc[key]);
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void With_nothing_recorded_it_offers_to_record_and_turns_on_the_black_box_and_the_trains_tapes()
|
|
||||||
{
|
|
||||||
var services = Services(new InMemoryFileSystem());
|
|
||||||
var window = new HaslerTapeWindow();
|
|
||||||
bool told = false;
|
|
||||||
window.LogEnabled += () => told = true;
|
|
||||||
window.Show();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var strip = (Control)Button(window, "HaslerRecordingEnable").Parent!;
|
|
||||||
Until(() => strip.IsVisible);
|
|
||||||
|
|
||||||
Button(window, "HaslerRecordingEnable").RaiseEvent(Controls.Click());
|
|
||||||
|
|
||||||
Assert.True(services.Settings.BlackBox);
|
|
||||||
Assert.True(services.Settings.PhysicsLogTrains);
|
|
||||||
Assert.False(services.Settings.PhysicsLog);
|
|
||||||
Assert.True(told);
|
|
||||||
Assert.False(strip.IsVisible);
|
|
||||||
// the simulator's own log is on as it comes: nothing more to offer
|
|
||||||
Assert.False(((Control)Button(window, "HaslerLogEnable").Parent!).IsVisible);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
window.Close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_tape_of_the_last_launch_is_summed_up_with_its_scenario_and_train()
|
|
||||||
{
|
|
||||||
string path = TestInstallation.At("physicslog", "EP07-424.dat");
|
|
||||||
var files = new InMemoryFileSystem()
|
|
||||||
.WithFile(path, HaslerTapeTests.Header + HaslerTapeTests.Line(0, 36, 0, 0) + HaslerTapeTests.Line(60, 36, 0, 0));
|
|
||||||
var services = Services(files);
|
|
||||||
services.Tapes.RecordLaunch("td.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "EP07-424", new[] { "EP07-424" },
|
|
||||||
"Tor doświadczalny", "EIE1531");
|
|
||||||
var window = new HaslerTapeWindow();
|
|
||||||
window.Show();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
string scenario = string.Format(App.Loc["HaslerScenario"], "Tor doświadczalny");
|
|
||||||
var texts = window.GetLogicalDescendants().OfType<TextBlock>();
|
|
||||||
Until(() => texts.Any(t => t.Text?.Contains(scenario) == true));
|
|
||||||
string summary = texts.First(t => t.Text?.Contains(scenario) == true).Text!;
|
|
||||||
|
|
||||||
Assert.StartsWith("EP07-424", summary);
|
|
||||||
Assert.Contains(string.Format(App.Loc["HaslerTrain"], "EIE1531"), summary);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
window.Close();
|
|
||||||
}
|
|
||||||
// closed, the tape it read is no longer followed: begun anew and longer, it is read whole
|
|
||||||
files.WithFile(path, HaslerTapeTests.Header + HaslerTapeTests.Line(0, 72, 0, 0) + HaslerTapeTests.Line(1, 72, 0, 0)
|
|
||||||
+ HaslerTapeTests.Line(2, 72, 0, 0));
|
|
||||||
var tape = services.Tapes.Load(services.Tapes.List().Single(), follow: true)!;
|
|
||||||
Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
using Avalonia.Controls;
|
|
||||||
using Avalonia.LogicalTree;
|
|
||||||
using StarterNG.Application;
|
|
||||||
using StarterNG.Tests.Fakes;
|
|
||||||
using StarterNG.Views;
|
|
||||||
|
|
||||||
namespace StarterNG.Tests;
|
|
||||||
|
|
||||||
/// <summary>The starter's questions over its window, answered with the mouse or not at all.</summary>
|
|
||||||
[Collection(AvaloniaControls.Name)]
|
|
||||||
public class MessageBoxTests
|
|
||||||
{
|
|
||||||
// The buttons are labelled in the starter's language.
|
|
||||||
static MessageBoxTests()
|
|
||||||
{
|
|
||||||
HeadlessDrawing.Ensure();
|
|
||||||
if (AppServices.CurrentOrNull is null)
|
|
||||||
{
|
|
||||||
var installation = new TestInstallation(new InMemoryFileSystem());
|
|
||||||
AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static (Window Owner, Window Dialog, Task<bool?> Answer) Choose()
|
|
||||||
{
|
|
||||||
var owner = new Window();
|
|
||||||
owner.Show();
|
|
||||||
var answer = MessageBox.Choose(owner, "Zapisać zmiany przed startem?", "Niezapisane zmiany", "Zapisz", "Nie zapisuj");
|
|
||||||
Controls.Settle();
|
|
||||||
return (owner, Assert.Single(owner.OwnedWindows), answer);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The answer is given once the dialog's closing has gone through the dispatcher.
|
|
||||||
private static bool? Answered(Task<bool?> answer)
|
|
||||||
{
|
|
||||||
Assert.True(SpinWait.SpinUntil(() =>
|
|
||||||
{
|
|
||||||
Controls.Settle();
|
|
||||||
return answer.IsCompleted;
|
|
||||||
}, TimeSpan.FromSeconds(5)));
|
|
||||||
return answer.Result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Button[] Buttons(Window dialog) => dialog.GetLogicalDescendants().OfType<Button>().ToArray();
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(0, true)]
|
|
||||||
[InlineData(1, false)]
|
|
||||||
[InlineData(2, null)]
|
|
||||||
public void A_choice_gives_the_answer_clicked_and_the_way_back_gives_none(int clicked, bool? expected)
|
|
||||||
{
|
|
||||||
var (owner, dialog, answer) = Choose();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Assert.Equal("Niezapisane zmiany", dialog.Title);
|
|
||||||
Assert.Contains(dialog.GetLogicalDescendants().OfType<TextBlock>(), t => t.Text == "Zapisać zmiany przed startem?");
|
|
||||||
var buttons = Buttons(dialog);
|
|
||||||
Assert.Equal(["Zapisz", "Nie zapisuj", App.Loc["Cancel"]], buttons.Select(b => b.Content as string));
|
|
||||||
Assert.False(answer.IsCompleted);
|
|
||||||
|
|
||||||
buttons[clicked].RaiseEvent(Controls.Click());
|
|
||||||
|
|
||||||
Assert.Equal(expected, Answered(answer));
|
|
||||||
Assert.Empty(owner.OwnedWindows);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
owner.Close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Closing_the_window_of_a_choice_picks_neither_answer()
|
|
||||||
{
|
|
||||||
var (owner, dialog, answer) = Choose();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
dialog.Close();
|
|
||||||
|
|
||||||
Assert.Null(Answered(answer));
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
owner.Close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
using StarterNG.Application;
|
|
||||||
|
|
||||||
namespace StarterNG.Tests;
|
|
||||||
|
|
||||||
public class OneAtATimeTests
|
|
||||||
{
|
|
||||||
private static async Task Until(Func<bool> condition)
|
|
||||||
{
|
|
||||||
var giveUp = DateTime.UtcNow.AddSeconds(5);
|
|
||||||
while (!condition())
|
|
||||||
{
|
|
||||||
Assert.True(DateTime.UtcNow < giveUp, "waited too long");
|
|
||||||
await Task.Delay(10);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Asked_once_it_runs_once()
|
|
||||||
{
|
|
||||||
int runs = 0;
|
|
||||||
var once = new OneAtATime(() => { runs++; return Task.CompletedTask; });
|
|
||||||
|
|
||||||
await once.RunAsync();
|
|
||||||
|
|
||||||
Assert.Equal(1, runs);
|
|
||||||
Assert.False(once.IsRunning);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Asked_while_running_it_runs_once_more_after_not_alongside()
|
|
||||||
{
|
|
||||||
int runs = 0, together = 0, most = 0;
|
|
||||||
var gates = new Queue<TaskCompletionSource>();
|
|
||||||
var once = new OneAtATime(async () =>
|
|
||||||
{
|
|
||||||
runs++;
|
|
||||||
most = Math.Max(most, ++together);
|
|
||||||
var gate = new TaskCompletionSource();
|
|
||||||
gates.Enqueue(gate);
|
|
||||||
await gate.Task;
|
|
||||||
together--;
|
|
||||||
});
|
|
||||||
|
|
||||||
var first = once.RunAsync();
|
|
||||||
// Three requests during the first run make one more run, not three.
|
|
||||||
await once.RunAsync();
|
|
||||||
await once.RunAsync();
|
|
||||||
await once.RunAsync();
|
|
||||||
Assert.Equal(1, runs);
|
|
||||||
|
|
||||||
gates.Dequeue().SetResult();
|
|
||||||
await Until(() => Volatile.Read(ref runs) == 2);
|
|
||||||
await Until(() => gates.Count == 1);
|
|
||||||
gates.Dequeue().SetResult();
|
|
||||||
await first;
|
|
||||||
|
|
||||||
Assert.Equal(2, runs);
|
|
||||||
Assert.Equal(1, most);
|
|
||||||
Assert.False(once.IsRunning);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task A_failed_run_does_not_keep_it_busy()
|
|
||||||
{
|
|
||||||
bool fail = true;
|
|
||||||
int runs = 0;
|
|
||||||
var once = new OneAtATime(() =>
|
|
||||||
{
|
|
||||||
runs++;
|
|
||||||
return fail ? Task.FromException(new IOException("locked")) : Task.CompletedTask;
|
|
||||||
});
|
|
||||||
|
|
||||||
await Assert.ThrowsAsync<IOException>(once.RunAsync);
|
|
||||||
fail = false;
|
|
||||||
await once.RunAsync();
|
|
||||||
|
|
||||||
Assert.Equal(2, runs);
|
|
||||||
Assert.False(once.IsRunning);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
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"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -273,7 +273,7 @@ public class ScenerySyntaxTests
|
|||||||
include koniec.scm
|
include koniec.scm
|
||||||
""";
|
""";
|
||||||
|
|
||||||
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => true);
|
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, new SceneryFileLookup(_ => true));
|
||||||
|
|
||||||
Assert.Empty(scenery.Faults);
|
Assert.Empty(scenery.Faults);
|
||||||
Assert.Equal("td/rozklad", Assert.Single(scenery.Trainsets).Name);
|
Assert.Equal("td/rozklad", Assert.Single(scenery.Trainsets).Name);
|
||||||
@@ -326,7 +326,7 @@ public class ScenerySyntaxTests
|
|||||||
endoptional
|
endoptional
|
||||||
""";
|
""";
|
||||||
|
|
||||||
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, name => name is "tory.scm" or "budynek.inc").Faults;
|
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, new SceneryFileLookup(name => name is "tory.scm" or "budynek.inc")).Faults;
|
||||||
|
|
||||||
Assert.Equal((SceneryFaultKind.MissingInclude, "x.scn", 2, null, "brak.scm"), Seen(Assert.Single(faults)));
|
Assert.Equal((SceneryFaultKind.MissingInclude, "x.scn", 2, null, "brak.scm"), Seen(Assert.Single(faults)));
|
||||||
}
|
}
|
||||||
@@ -378,4 +378,58 @@ public class ScenerySyntaxTests
|
|||||||
Assert.Equal(sbt, scenery.HasCompanionTimetable);
|
Assert.Equal(sbt, scenery.HasCompanionTimetable);
|
||||||
Assert.Equal(sbt ? 0 : 1, scenery.Faults.Count);
|
Assert.Equal(sbt ? 0 : 1, scenery.Faults.Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<SceneryFault> TerrainFaults(string scn, bool sbt, params string[] onDisk)
|
||||||
|
{
|
||||||
|
var files = new InMemoryFileSystem(caseSensitive: true).WithLegacyFile("game/scenery/Mapa.scn", scn);
|
||||||
|
if (sbt)
|
||||||
|
files.WithFile("game/scenery/mapa.sbt", "EU07");
|
||||||
|
foreach (string file in onDisk)
|
||||||
|
files.WithFile("game/scenery/" + file, "");
|
||||||
|
return TestScenery.Repository(files).Load("game/scenery/Mapa.scn")!.Faults;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Teren/Mapa.txtf")]
|
||||||
|
[InlineData("teren/mapa.btf")]
|
||||||
|
[InlineData("TEREN/MAPA.BTF")]
|
||||||
|
public void A_terrain_file_found_as_text_or_binary_is_no_fault(string onDisk) =>
|
||||||
|
Assert.Empty(TerrainFaults("terrain teren/mapa.txtf endterrain\nFirstInit\n", sbt: false, onDisk));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_terrain_file_missing_both_ways_is_reported_but_an_sbt_named_with_it_is_not()
|
||||||
|
{
|
||||||
|
var faults = TerrainFaults("// teren\nterrain teren/mapa.btf teren/stara.sbt\nendterrain\nFirstInit\n", sbt: false);
|
||||||
|
|
||||||
|
Assert.Equal((SceneryFaultKind.MissingTerrainFile, "Mapa.scn", 2, null, "teren/mapa.btf"),
|
||||||
|
Seen(Assert.Single(faults)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_terrain_file_takes_the_place_of_the_sbt_so_terrain_includes_are_read_after_all()
|
||||||
|
{
|
||||||
|
var faults = TerrainFaults("terrain teren/mapa.txtf endterrain\ninclude nmt/brak_ter.scm end\nFirstInit\n",
|
||||||
|
sbt: true, "teren/mapa.txtf");
|
||||||
|
|
||||||
|
Assert.Equal((SceneryFaultKind.MissingInclude, "Mapa.scn", 2, null, "nmt/brak_ter.scm"),
|
||||||
|
Seen(Assert.Single(faults)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("include nmt/brak_ter.scm end\nterrain teren/mapa.txtf endterrain\nFirstInit\n", 2)]
|
||||||
|
[InlineData("node -1 0 t1 triangles trawa\n0 0 0 0 0 0 0 0 end\nendtri\nterrain teren/mapa.txtf endterrain\nFirstInit\n", 4)]
|
||||||
|
[InlineData("node -1 -1 t1 model 0 0 0 0 teren.t3d none endmodel\nterrain teren/mapa.txtf endterrain\nFirstInit\n", 2)]
|
||||||
|
[InlineData("FirstInit\nterrain teren/mapa.txtf endterrain\n", 2)]
|
||||||
|
public void A_terrain_file_behind_what_the_sbt_already_gave_is_passed_over(string scn, int line)
|
||||||
|
{
|
||||||
|
var faults = TerrainFaults(scn, sbt: true, "teren/mapa.txtf");
|
||||||
|
|
||||||
|
Assert.Equal((SceneryFaultKind.TerrainFileBehindSbt, "Mapa.scn", line, null, "teren/mapa.txtf"),
|
||||||
|
Seen(Assert.Single(faults)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_model_not_of_the_terrain_leaves_the_sbt_free_to_give_way() =>
|
||||||
|
Assert.Empty(TerrainFaults("node 500 0 m1 model 0 0 0 0 dom.t3d none endmodel\nterrain teren/mapa.txtf endterrain\nFirstInit\n",
|
||||||
|
sbt: true, "teren/mapa.txtf"));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,229 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1257,39 +1257,6 @@ public class SettingsStoreTests
|
|||||||
Assert.False(store.LoadFailed);
|
Assert.False(store.LoadFailed);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_profile_from_before_the_tapes_of_the_trains_is_moved_as_the_ini_would_be()
|
|
||||||
{
|
|
||||||
var files = new InMemoryFileSystem()
|
|
||||||
.WithFile(UserIni, "physicslog no\nphysicslog.trains no\n")
|
|
||||||
.WithFile(Profile, "physicslog yes\nblackbox yes\n");
|
|
||||||
var store = WithHome(files).SettingsStore;
|
|
||||||
store.Load();
|
|
||||||
|
|
||||||
Assert.True(store.TryLoadProfile(Profile));
|
|
||||||
store.Save();
|
|
||||||
|
|
||||||
Assert.False(store.Settings.PhysicsLog);
|
|
||||||
Assert.True(store.Settings.PhysicsLogTrains);
|
|
||||||
Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_profile_exported_from_a_pages_edits_leaves_the_settings_held_and_the_ini_alone()
|
|
||||||
{
|
|
||||||
var files = new InMemoryFileSystem().WithFile(UserIni, "fieldofview 45\n");
|
|
||||||
var store = WithHome(files).SettingsStore;
|
|
||||||
store.Load();
|
|
||||||
var edited = store.Settings.Copy();
|
|
||||||
edited.FieldOfView = 60;
|
|
||||||
|
|
||||||
Assert.True(store.ExportTo(Profile, edited));
|
|
||||||
|
|
||||||
Assert.Contains("fieldofview 60", files.ReadAllText(Profile, System.Text.Encoding.UTF8));
|
|
||||||
Assert.Equal(45, store.Settings.FieldOfView);
|
|
||||||
Assert.Contains("fieldofview 45", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void A_missing_profile_leaves_the_settings_as_they_are()
|
public void A_missing_profile_leaves_the_settings_as_they_are()
|
||||||
{
|
{
|
||||||
@@ -1335,260 +1302,4 @@ public class SettingsStoreTests
|
|||||||
Assert.False(store.LoadFailed);
|
Assert.False(store.LoadFailed);
|
||||||
Assert.Equal(60, store.Settings.FieldOfView);
|
Assert.Equal(60, store.Settings.FieldOfView);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("physicslog yes\n", true)]
|
|
||||||
[InlineData("physicslog no\n", false)]
|
|
||||||
[InlineData("physicslog yes\nblackbox no\n", false)]
|
|
||||||
[InlineData("physicslog no\nblackbox yes\n", true)]
|
|
||||||
public void The_black_box_goes_with_the_physics_log_unless_the_ini_says_otherwise(string ini, bool recorded)
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
|
||||||
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
|
|
||||||
Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Tapes_turned_on_write_the_black_box_and_leave_the_physics_log_off()
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
installation.SettingsStore.Settings.BlackBox = true;
|
|
||||||
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
|
|
||||||
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_black_box_that_says_no_more_than_the_physics_log_adds_no_line()
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n"));
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
installation.SettingsStore.Settings.Width = 1600;
|
|
||||||
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
Assert.Null(LineFor(installation, "blackbox"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("physicslog yes\nblackbox yes\n")]
|
|
||||||
[InlineData("physicslog no\nblackbox yes\n")]
|
|
||||||
public void A_black_box_line_of_the_file_says_no_once_the_box_is_off(string ini)
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
installation.SettingsStore.Settings.BlackBox = false;
|
|
||||||
installation.SettingsStore.Settings.PhysicsLog = false;
|
|
||||||
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
Assert.Equal("blackbox no", LineFor(installation, "blackbox"));
|
|
||||||
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void The_physics_log_turned_off_keeps_the_tapes_it_brought()
|
|
||||||
{
|
|
||||||
// an ini of before the black box had a key: the tapes came with the physics log
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n"));
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
installation.SettingsStore.Settings.PhysicsLog = false;
|
|
||||||
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("physicslog no\n", false, false)]
|
|
||||||
[InlineData("physicslog no\nphysicslog.trains yes\n", true, true)]
|
|
||||||
[InlineData("physicslog no\nphysicslog.trains yes\nblackbox no\n", true, false)]
|
|
||||||
public void The_logs_of_the_trains_are_read_and_bring_the_black_box_as_the_simulator_has_it(string ini, bool trains, bool recorded)
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
|
||||||
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
|
|
||||||
Assert.Equal(trains, installation.SettingsStore.Settings.PhysicsLogTrains);
|
|
||||||
Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("physicslog yes\nblackbox yes\n")]
|
|
||||||
[InlineData("physicslog no\nblackbox yes\n")]
|
|
||||||
public void Recording_turned_on_before_the_tapes_of_the_trains_is_moved_to_them(string ini)
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
|
||||||
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
var s = installation.SettingsStore.Settings;
|
|
||||||
Assert.False(s.PhysicsLog);
|
|
||||||
Assert.True(s.PhysicsLogTrains);
|
|
||||||
Assert.True(s.BlackBox);
|
|
||||||
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
|
|
||||||
Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains"));
|
|
||||||
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("physicslog yes\n", true)]
|
|
||||||
[InlineData("physicslog yes\nblackbox no\n", true)]
|
|
||||||
[InlineData("physicslog yes\nblackbox yes\nphysicslog.trains no\n", true)]
|
|
||||||
[InlineData("physicslog no\nblackbox yes\nphysicslog.trains no\n", false)]
|
|
||||||
public void Without_a_black_box_line_saying_yes_or_with_the_trains_tapes_line_nothing_is_moved(string ini, bool physicsLog)
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
|
|
||||||
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
|
|
||||||
Assert.Equal(physicsLog, installation.SettingsStore.Settings.PhysicsLog);
|
|
||||||
Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void An_imported_ini_from_before_the_tapes_of_the_trains_is_moved_as_a_profile_is()
|
|
||||||
{
|
|
||||||
string backup = Path.Combine("/home/kolejarz", "backup", "eu07.ini");
|
|
||||||
var files = new InMemoryFileSystem()
|
|
||||||
.WithFile(UserIni, "physicslog yes\nphysicslog.trains no\n")
|
|
||||||
.WithFile(backup, "physicslog yes\nblackbox yes\n");
|
|
||||||
var store = WithHome(files).SettingsStore;
|
|
||||||
store.Load();
|
|
||||||
|
|
||||||
Assert.True(store.ImportFrom(backup));
|
|
||||||
store.Save();
|
|
||||||
|
|
||||||
Assert.False(store.Settings.PhysicsLog);
|
|
||||||
Assert.True(store.Settings.PhysicsLogTrains);
|
|
||||||
Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Once_moved_the_physics_log_of_every_vehicle_turned_on_again_stays_on()
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\nblackbox yes\n"));
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
installation.SettingsStore.Settings.PhysicsLog = true;
|
|
||||||
installation.SettingsStore.Settings.PhysicsLogTrains = false;
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
|
|
||||||
Assert.True(installation.SettingsStore.Settings.PhysicsLog);
|
|
||||||
Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains);
|
|
||||||
Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void The_logs_of_the_trains_are_written_only_once_on_or_where_the_file_has_them()
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
Assert.Null(LineFor(installation, "physicslog.trains"));
|
|
||||||
|
|
||||||
installation.SettingsStore.Settings.PhysicsLogTrains = true;
|
|
||||||
installation.SettingsStore.Settings.BlackBox = true;
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains"));
|
|
||||||
// it says no more than the logs of the trains bring
|
|
||||||
Assert.Null(LineFor(installation, "blackbox"));
|
|
||||||
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
installation.SettingsStore.Settings.PhysicsLogTrains = false;
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_black_box_line_written_once_goes_away_when_it_says_no_more()
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
installation.SettingsStore.Settings.BlackBox = true;
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
installation.SettingsStore.Settings.BlackBox = false;
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
Assert.Null(LineFor(installation, "blackbox"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void The_sound_device_options_left_alone_add_nothing_to_the_file()
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "width 1920\n"));
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
string saved = SavedLines(installation);
|
|
||||||
foreach (var key in new[] { "sound.openal.renderer", "sound.outputmode", "sound.hrtf", "sound.hrtf.profile",
|
|
||||||
"sound.resampler", "sound.limiter", "sound.frequency", "sound.maxsources",
|
|
||||||
"sound.doppler", "sound.efx.lowpass", "sound.efx.airabsorption" })
|
|
||||||
Assert.Null(LineFor(installation, key));
|
|
||||||
Assert.Contains("width 1920\n", saved);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void The_sound_device_options_survive_a_round_trip_with_names_in_quotes()
|
|
||||||
{
|
|
||||||
var installation = WithHome();
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
var s = installation.SettingsStore.Settings;
|
|
||||||
s.AudioDevice = "OpenAL Soft on Speakers (Realtek(R) Audio)";
|
|
||||||
s.AudioOutputMode = "headphones";
|
|
||||||
s.AudioHrtf = "on";
|
|
||||||
s.AudioHrtfProfile = "Built-In HRTF";
|
|
||||||
s.AudioResampler = "Cubic";
|
|
||||||
s.AudioLimiter = "off";
|
|
||||||
s.AudioFrequency = 48000;
|
|
||||||
s.AudioDoppler = 0.5;
|
|
||||||
s.AudioLowpass = true;
|
|
||||||
s.AudioAirAbsorption = 1.0;
|
|
||||||
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
Assert.Equal("sound.openal.renderer \"OpenAL Soft on Speakers (Realtek(R) Audio)\"",
|
|
||||||
LineFor(installation, "sound.openal.renderer"));
|
|
||||||
Assert.Equal("sound.resampler Cubic", LineFor(installation, "sound.resampler"));
|
|
||||||
Assert.Empty(BareSimulatorKeys(installation));
|
|
||||||
|
|
||||||
var again = WithHome(new InMemoryFileSystem().WithFile(UserIni, installation.Files.ReadAllText(UserIni)));
|
|
||||||
again.SettingsStore.Load();
|
|
||||||
var read = again.SettingsStore.Settings;
|
|
||||||
Assert.Equal(s.AudioDevice, read.AudioDevice);
|
|
||||||
Assert.Equal("headphones", read.AudioOutputMode);
|
|
||||||
Assert.Equal("on", read.AudioHrtf);
|
|
||||||
Assert.Equal("Built-In HRTF", read.AudioHrtfProfile);
|
|
||||||
Assert.Equal("Cubic", read.AudioResampler);
|
|
||||||
Assert.Equal("off", read.AudioLimiter);
|
|
||||||
Assert.Equal(48000, read.AudioFrequency);
|
|
||||||
Assert.Equal(0.5, read.AudioDoppler, 6);
|
|
||||||
Assert.True(read.AudioLowpass);
|
|
||||||
Assert.Equal(1.0, read.AudioAirAbsorption, 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void A_sound_name_set_back_to_the_librarys_choice_takes_its_line_out()
|
|
||||||
{
|
|
||||||
var installation = WithHome(new InMemoryFileSystem()
|
|
||||||
.WithFile(UserIni, "sound.openal.renderer \"Old Device\"\nsound.resampler Cubic\n"));
|
|
||||||
installation.SettingsStore.Load();
|
|
||||||
Assert.Equal("Old Device", installation.SettingsStore.Settings.AudioDevice);
|
|
||||||
|
|
||||||
installation.SettingsStore.Settings.AudioDevice = "";
|
|
||||||
installation.SettingsStore.Settings.AudioResampler = "";
|
|
||||||
installation.SettingsStore.Save();
|
|
||||||
|
|
||||||
Assert.Null(LineFor(installation, "sound.openal.renderer"));
|
|
||||||
Assert.Null(LineFor(installation, "sound.resampler"));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -40,18 +40,6 @@ public class StartSimulationTests
|
|||||||
Assert.Contains($"vehicle\t{driven}\tPKP/EP07\tep07.mmd", noted);
|
Assert.Contains($"vehicle\t{driven}\tPKP/EP07\tep07.mmd", noted);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void With_the_black_box_alone_the_launch_is_noted_for_the_tapes_it_writes()
|
|
||||||
{
|
|
||||||
var (start, _, installation) = Rig(files => files.WithExecutable(Build), sceneryClock: "07:52");
|
|
||||||
installation.SettingsStore.Settings.BlackBox = true;
|
|
||||||
|
|
||||||
start.Execute(freeFly: false, saveSettings: false);
|
|
||||||
|
|
||||||
string noted = installation.Files.ReadAllText(TestInstallation.At("physicslog", "starter-launch.txt"));
|
|
||||||
Assert.Contains("clock\t07:52", noted);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Without_the_physics_log_nothing_is_noted()
|
public void Without_the_physics_log_nothing_is_noted()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,7 +8,6 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Avalonia.Headless" Version="12.1.4" />
|
|
||||||
<PackageReference Include="coverlet.collector" Version="6.0.2" />
|
<PackageReference Include="coverlet.collector" Version="6.0.2" />
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
||||||
<PackageReference Include="xunit" Version="2.9.2" />
|
<PackageReference Include="xunit" Version="2.9.2" />
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,175 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,8 +6,6 @@ namespace StarterNG.Tests;
|
|||||||
|
|
||||||
// PresetStore keeps the disk of the first test that reaches it, a fake one as every
|
// PresetStore keeps the disk of the first test that reaches it, a fake one as every
|
||||||
// composition root in the tests is built on fakes. So each test has a name to itself.
|
// composition root in the tests is built on fakes. So each test has a name to itself.
|
||||||
// Puts in services of its own: not while the controls read theirs.
|
|
||||||
[Collection(AvaloniaControls.Name)]
|
|
||||||
public class WarehouseEditTests
|
public class WarehouseEditTests
|
||||||
{
|
{
|
||||||
private const string Text =
|
private const string Text =
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ using Avalonia.Markup.Xaml;
|
|||||||
using Avalonia.Threading;
|
using Avalonia.Threading;
|
||||||
using StarterNG.Application;
|
using StarterNG.Application;
|
||||||
using StarterNG.Classes;
|
using StarterNG.Classes;
|
||||||
using StarterNG.Controls;
|
|
||||||
using StarterNG.Infrastructure;
|
using StarterNG.Infrastructure;
|
||||||
using StarterNG.Services;
|
using StarterNG.Services;
|
||||||
|
|
||||||
@@ -25,10 +24,6 @@ public partial class App : Avalonia.Application
|
|||||||
|
|
||||||
public override void Initialize()
|
public override void Initialize()
|
||||||
{
|
{
|
||||||
// Before any control exists: the names are given as controls are filled in.
|
|
||||||
ScreenReaderNames.Install();
|
|
||||||
DialogKeyboard.Install();
|
|
||||||
|
|
||||||
AvaloniaXamlLoader.Load(this);
|
AvaloniaXamlLoader.Load(this);
|
||||||
|
|
||||||
AppServices.Current.SettingsStore.Load();
|
AppServices.Current.SettingsStore.Load();
|
||||||
@@ -207,12 +202,8 @@ public partial class App : Avalonia.Application
|
|||||||
if (check.ExecutableMissing())
|
if (check.ExecutableMissing())
|
||||||
await main.OfferExecutablePickAsync();
|
await main.OfferExecutablePickAsync();
|
||||||
|
|
||||||
// A build without AVX2 in the folder is started instead, and needs no notice.
|
if (CpuFeatures.LacksAvx2 && AppServices.Current.Settings.CpuNotice)
|
||||||
var services = AppServices.Current;
|
await main.ShowCpuNoticeAsync();
|
||||||
if (services.Settings.CpuNotice
|
|
||||||
&& services.Executables.Resolve(services.Settings, out _) is var executable
|
|
||||||
&& services.Executables.WillNotRunHere(executable))
|
|
||||||
await main.ShowCpuNoticeAsync(executable);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,9 +81,6 @@ public sealed class AppServices
|
|||||||
_current ?? throw new InvalidOperationException(
|
_current ?? throw new InvalidOperationException(
|
||||||
"AppServices.Current read before Initialize(); the composition root must be built first.");
|
"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,
|
public static AppServices Initialize(IGamePaths? paths = null, IFileSystem? files = null, IClock? clock = null,
|
||||||
IEnvironment? environment = null)
|
IEnvironment? environment = null)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -35,7 +35,6 @@ public sealed class HaslerTapes
|
|||||||
{
|
{
|
||||||
private const int RememberedLaunches = 30;
|
private const int RememberedLaunches = 30;
|
||||||
private static readonly TimeSpan QuietBetweenRuns = TimeSpan.FromMinutes(2);
|
private static readonly TimeSpan QuietBetweenRuns = TimeSpan.FromMinutes(2);
|
||||||
private static readonly TimeSpan TapesAfterBlackBox = TimeSpan.FromSeconds(10);
|
|
||||||
|
|
||||||
private readonly IFileSystem _files;
|
private readonly IFileSystem _files;
|
||||||
private readonly IGamePaths _paths;
|
private readonly IGamePaths _paths;
|
||||||
@@ -245,9 +244,8 @@ public sealed class HaslerTapes
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// The runs the tapes came from, the running or latest one first. A tape belongs
|
/// The runs the tapes came from, the running or latest one first. A tape belongs
|
||||||
/// to the last launch before it was written, unless a run the starter didn't launch
|
/// to the last launch before it was written, unless a run the starter didn't launch
|
||||||
/// began between them; one with no launch goes with the black box recording when it
|
/// began between them; one with no launch goes with those written about the same
|
||||||
/// was written, or else with those written about the same time, as a run writes its
|
/// time, as a run writes them all at its end.
|
||||||
/// logs until it ends.
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public IReadOnlyList<TapeSession> Sessions()
|
public IReadOnlyList<TapeSession> Sessions()
|
||||||
{
|
{
|
||||||
@@ -280,15 +278,11 @@ public sealed class HaslerTapes
|
|||||||
boxesBehind.GetValueOrDefault(launch, new List<BlackBoxRecording>())));
|
boxesBehind.GetValueOrDefault(launch, new List<BlackBoxRecording>())));
|
||||||
}
|
}
|
||||||
|
|
||||||
// What no launch covers goes together by when it was written: a run writes its logs until it ends. A tape
|
// What no launch covers goes together by when it was written: a run writes it all at its end.
|
||||||
// written while a black box recorded is of its run, though: the black box writes the tapes of the player's
|
|
||||||
// vehicles as it goes, and that of a vehicle the player left ends before the run does.
|
|
||||||
var looseBoxes = boxes.Where(b => LaunchOf(b, launches) is null).ToList();
|
|
||||||
var recordings = Recordings(looseBoxes);
|
|
||||||
var loose = tapes.Where(t => tapeLaunch[t] is null)
|
var loose = tapes.Where(t => tapeLaunch[t] is null)
|
||||||
.Select(t => (Written: RecordingAt(t.LastWriteUtc, recordings)?.LastWriteUtc ?? t.LastWriteUtc,
|
.Select(t => (Written: t.LastWriteUtc, Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null))
|
||||||
Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null))
|
.Concat(boxes.Where(b => LaunchOf(b, launches) is null)
|
||||||
.Concat(looseBoxes.Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b)))
|
.Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b)))
|
||||||
.OrderBy(file => file.Written);
|
.OrderBy(file => file.Written);
|
||||||
var run = new List<TapeFile>();
|
var run = new List<TapeFile>();
|
||||||
var runBoxes = new List<BlackBoxRecording>();
|
var runBoxes = new List<BlackBoxRecording>();
|
||||||
@@ -321,39 +315,6 @@ public sealed class HaslerTapes
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// When each black box recorded, its name read once: from the start its name has, to when it was last written,
|
|
||||||
/// and the tapes a moment after. No longer than until the next one started, though: a box downloaded or copied
|
|
||||||
/// later was last written then, not when it stopped, and would take in the tapes of the runs since.
|
|
||||||
/// </summary>
|
|
||||||
public static IReadOnlyList<(BlackBoxRecording Box, DateTime FromUtc, DateTime ToUtc)> Recordings(IEnumerable<BlackBoxRecording> boxes)
|
|
||||||
{
|
|
||||||
var named = boxes.Select(box => (Box: box, Named: NamedBy(box.Path)))
|
|
||||||
.Where(each => each.Named is not null)
|
|
||||||
.Select(each => (each.Box, FromUtc: each.Named!.Value.StartedUtc))
|
|
||||||
.OrderBy(each => each.FromUtc)
|
|
||||||
.ToList();
|
|
||||||
var recordings = new List<(BlackBoxRecording, DateTime, DateTime)>(named.Count);
|
|
||||||
for (int i = 0; i < named.Count; i++)
|
|
||||||
{
|
|
||||||
var to = named[i].Box.LastWriteUtc + TapesAfterBlackBox;
|
|
||||||
if (i + 1 < named.Count && named[i + 1].FromUtc < to)
|
|
||||||
to = named[i + 1].FromUtc;
|
|
||||||
recordings.Add((named[i].Box, named[i].FromUtc, to));
|
|
||||||
}
|
|
||||||
return recordings;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The black box that was recording at the moment, the tapes being written last, a moment after it is closed.
|
|
||||||
/// Of more, the one that stopped nearest to it.
|
|
||||||
/// </summary>
|
|
||||||
public static BlackBoxRecording? RecordingAt(DateTime momentUtc, IEnumerable<(BlackBoxRecording Box, DateTime FromUtc, DateTime ToUtc)> recordings) =>
|
|
||||||
recordings.Where(each => each.FromUtc <= momentUtc && momentUtc <= each.ToUtc)
|
|
||||||
.OrderBy(each => (each.Box.LastWriteUtc - momentUtc).Duration())
|
|
||||||
.Select(each => each.Box)
|
|
||||||
.FirstOrDefault();
|
|
||||||
|
|
||||||
private TapeFile ReadTape(string path) =>
|
private TapeFile ReadTape(string path) =>
|
||||||
new(path, Path.GetFileNameWithoutExtension(path), _files.GetLastWriteTimeUtc(path), _files.GetFileSize(path));
|
new(path, Path.GetFileNameWithoutExtension(path), _files.GetLastWriteTimeUtc(path), _files.GetFileSize(path));
|
||||||
|
|
||||||
@@ -450,88 +411,19 @@ public sealed class HaslerTapes
|
|||||||
return new TapeSession(launch, started, written.Count > 0 ? written.Max() : started, running, listed, recorded);
|
return new TapeSession(launch, started, written.Count > 0 ? written.Max() : started, running, listed, recorded);
|
||||||
}
|
}
|
||||||
|
|
||||||
// the tape followed as the simulator writes it: what of its file was read, and where it ended
|
public HaslerTape? Load(TapeFile file)
|
||||||
private readonly object _followedLock = new();
|
|
||||||
private (string Path, long Read, byte[] Tail, HaslerTape.Reader Reader)? _followed;
|
|
||||||
// what of the end of the read part is kept, to tell the file still has it: one begun anew doesn't
|
|
||||||
private const int FollowedTail = 256;
|
|
||||||
|
|
||||||
public HaslerTape? Load(TapeFile file) => Load(file, follow: false);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The tape of this file no longer followed: what was kept of it is let go. Another file's, followed for another
|
|
||||||
/// window, stays.
|
|
||||||
/// </summary>
|
|
||||||
public void Forget(string path)
|
|
||||||
{
|
{
|
||||||
lock (_followedLock)
|
try
|
||||||
if (_followed?.Path == path)
|
|
||||||
_followed = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// what the file has between the two: less, up to its end, when it was cut shorter since its length was taken
|
|
||||||
private static byte[] Bytes(Stream stream, long from, long to)
|
|
||||||
{
|
|
||||||
stream.Seek(from, SeekOrigin.Begin);
|
|
||||||
var bytes = new byte[to - from];
|
|
||||||
int read = stream.ReadAtLeast(bytes, bytes.Length, throwOnEndOfStream: false);
|
|
||||||
return read == bytes.Length ? bytes : bytes[..read];
|
|
||||||
}
|
|
||||||
|
|
||||||
// the end of what was read, after the part added to it
|
|
||||||
private static byte[] Tail(byte[] before, byte[] added)
|
|
||||||
{
|
|
||||||
if (added.Length >= FollowedTail)
|
|
||||||
return added[^FollowedTail..];
|
|
||||||
var keptBefore = Math.Min(before.Length, FollowedTail - added.Length);
|
|
||||||
return [.. before[^keptBefore..], .. added];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The tape of the file. Followed, the one read last and grown since: only what was added is read, so a log
|
|
||||||
/// written fast, at a higher time speed, is kept up with; a line not ended yet waits for the next time. Not
|
|
||||||
/// followed, or another file, or one shorter than was read - begun anew - it is read whole, and kept to be
|
|
||||||
/// followed from there.
|
|
||||||
/// </summary>
|
|
||||||
public HaslerTape? Load(TapeFile file, bool follow)
|
|
||||||
{
|
|
||||||
lock (_followedLock)
|
|
||||||
{
|
{
|
||||||
try
|
// Through OpenRead, which does not mind the simulator still writing the file.
|
||||||
{
|
using var stream = _files.OpenRead(file.Path);
|
||||||
// Through OpenRead, which does not mind the simulator still writing the file.
|
using var reader = new StreamReader(stream, Encoding.ASCII);
|
||||||
using var stream = _files.OpenRead(file.Path);
|
return HaslerTape.Parse(reader.ReadToEnd());
|
||||||
if (!stream.CanSeek)
|
}
|
||||||
{
|
catch (Exception ex)
|
||||||
_followed = null;
|
{
|
||||||
using var whole = new StreamReader(stream, Encoding.ASCII);
|
_log.Log($"reading {file.Path}", ex);
|
||||||
return HaslerTape.Parse(whole.ReadToEnd());
|
return null;
|
||||||
}
|
|
||||||
|
|
||||||
long length = stream.Length;
|
|
||||||
// the same file grown, its end as it was read: else another, or begun anew, read whole
|
|
||||||
if (!follow || _followed is not { } followed || followed.Path != file.Path || length < followed.Read
|
|
||||||
|| !Bytes(stream, followed.Read - followed.Tail.Length, followed.Read).AsSpan().SequenceEqual(followed.Tail))
|
|
||||||
followed = (file.Path, 0, Array.Empty<byte>(), new HaslerTape.Reader());
|
|
||||||
// what was read, not the length taken before: the file may be cut shorter meanwhile
|
|
||||||
var added = Bytes(stream, followed.Read, length);
|
|
||||||
followed.Reader.Feed(Encoding.ASCII.GetString(added));
|
|
||||||
// the time went back in what was added: the log begun anew and already longer than was read
|
|
||||||
if (followed.Read > 0 && followed.Reader.WentBack)
|
|
||||||
{
|
|
||||||
followed = (file.Path, 0, Array.Empty<byte>(), new HaslerTape.Reader());
|
|
||||||
added = Bytes(stream, 0, length);
|
|
||||||
followed.Reader.Feed(Encoding.ASCII.GetString(added));
|
|
||||||
}
|
|
||||||
_followed = (file.Path, followed.Read + added.Length, Tail(followed.Tail, added), followed.Reader);
|
|
||||||
return followed.Reader.Tape(final: !follow);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_followed = null;
|
|
||||||
_log.Log($"reading {file.Path}", ex);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace StarterNG.Application;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Runs a piece of work one at a time. Asked again while it runs, it does not start a
|
|
||||||
/// second one alongside, nor forget the request: it runs once more when the first ends,
|
|
||||||
/// however many times it was asked meanwhile. For the UI thread, which calls it alone.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class OneAtATime
|
|
||||||
{
|
|
||||||
private readonly Func<Task> _work;
|
|
||||||
private bool _running;
|
|
||||||
private bool _again;
|
|
||||||
|
|
||||||
public OneAtATime(Func<Task> work) => _work = work;
|
|
||||||
|
|
||||||
public bool IsRunning => _running;
|
|
||||||
|
|
||||||
public async Task RunAsync()
|
|
||||||
{
|
|
||||||
if (_running)
|
|
||||||
{
|
|
||||||
_again = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_running = true;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
do
|
|
||||||
{
|
|
||||||
_again = false;
|
|
||||||
await _work();
|
|
||||||
}
|
|
||||||
while (_again);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_running = false;
|
|
||||||
_again = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -113,9 +113,6 @@ public sealed class SettingsStore
|
|||||||
|
|
||||||
_serializer.Read(Settings, _config);
|
_serializer.Read(Settings, _config);
|
||||||
_synced = Render(Settings);
|
_synced = Render(Settings);
|
||||||
// after the snapshot, so the next save writes it; a profile of before goes the same way as the ini would
|
|
||||||
if (!LoadFailed)
|
|
||||||
SettingsSerializer.MoveToTrainTapes(Settings);
|
|
||||||
TouchConfigAge();
|
TouchConfigAge();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,8 +233,6 @@ public sealed class SettingsStore
|
|||||||
s.WindowMaximized = maximized;
|
s.WindowMaximized = maximized;
|
||||||
s.CabLampLight = cabLampLight;
|
s.CabLampLight = cabLampLight;
|
||||||
s.DepthPrepassScene = depthPrepassScene;
|
s.DepthPrepassScene = depthPrepassScene;
|
||||||
// an ini of before the tapes of the trains goes the same way as a profile
|
|
||||||
SettingsSerializer.MoveToTrainTapes(s);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,8 +240,7 @@ public sealed class SettingsStore
|
|||||||
/// Writes the settings as a complete eu07.ini somewhere else - this user's file
|
/// Writes the settings as a complete eu07.ini somewhere else - this user's file
|
||||||
/// with the settings applied - leaving the file itself and its state alone.
|
/// with the settings applied - leaving the file itself and its state alone.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="settings">What to write, when not the settings held: a page's edits, still not taken in.</param>
|
public bool ExportTo(string path)
|
||||||
public bool ExportTo(string path, SimulatorSettings? settings = null)
|
|
||||||
{
|
{
|
||||||
if (LoadFailed)
|
if (LoadFailed)
|
||||||
{
|
{
|
||||||
@@ -255,7 +249,7 @@ public sealed class SettingsStore
|
|||||||
}
|
}
|
||||||
|
|
||||||
var copy = ConfigFile.Parse(_config.ToText());
|
var copy = ConfigFile.Parse(_config.ToText());
|
||||||
ApplyChanges(copy, Changes(settings ?? Settings));
|
ApplyChanges(copy, Changes(Settings));
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ public sealed class StartSimulation
|
|||||||
if (saveSettings)
|
if (saveSettings)
|
||||||
_settings.CaptureAndSave();
|
_settings.CaptureAndSave();
|
||||||
|
|
||||||
if (_settings.Settings.PhysicsLog || _settings.Settings.BlackBox || _settings.Settings.PhysicsLogTrains)
|
if (_settings.Settings.PhysicsLog)
|
||||||
_tapes.RecordLaunch(scenery, trainset, freeFly ? null : vehicle);
|
_tapes.RecordLaunch(scenery, trainset, freeFly ? null : vehicle);
|
||||||
|
|
||||||
string[] arguments = freeFly || string.IsNullOrEmpty(vehicle)
|
string[] arguments = freeFly || string.IsNullOrEmpty(vehicle)
|
||||||
|
|||||||
@@ -1,89 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,433 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
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()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Interactivity;
|
|
||||||
|
|
||||||
namespace StarterNG.Controls;
|
namespace StarterNG.Controls;
|
||||||
|
|
||||||
@@ -74,25 +73,6 @@ public class SettingRow : ContentControl
|
|||||||
|
|
||||||
if (change.Property == IdleNoteProperty)
|
if (change.Property == IdleNoteProperty)
|
||||||
ToolTip.SetTip(this, string.IsNullOrEmpty(IdleNote) ? null : IdleNote);
|
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()
|
private void UpdatePseudoClasses()
|
||||||
|
|||||||
@@ -59,43 +59,6 @@ public class SettingsSection : HeaderedContentControl
|
|||||||
_reset = e.NameScope.Find<Button>("PART_Reset");
|
_reset = e.NameScope.Find<Button>("PART_Reset");
|
||||||
if (_reset is not null)
|
if (_reset is not null)
|
||||||
_reset.Click += OnResetClick;
|
_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);
|
private void OnResetClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e) => ResetRequested?.Invoke(this);
|
||||||
|
|||||||
@@ -61,6 +61,19 @@ public enum SceneryFaultKind
|
|||||||
/// <summary>An include whose file is not there; <see cref="SceneryFault.Token"/> names it.</summary>
|
/// <summary>An include whose file is not there; <see cref="SceneryFault.Token"/> names it.</summary>
|
||||||
MissingInclude,
|
MissingInclude,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A terrain file named by a terrain directive whose text (.txtf) and binary
|
||||||
|
/// file (.btf) are both missing; <see cref="SceneryFault.Token"/> names it.
|
||||||
|
/// </summary>
|
||||||
|
MissingTerrainFile,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A terrain file the simulator passes over: the scenery's terrain comes from its
|
||||||
|
/// .sbt, which something before the directive was already taken from;
|
||||||
|
/// <see cref="SceneryFault.Token"/> names it.
|
||||||
|
/// </summary>
|
||||||
|
TerrainFileBehindSbt,
|
||||||
|
|
||||||
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
|
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
|
||||||
IncludeNotClosed,
|
IncludeNotClosed,
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,14 @@ using System.Linq;
|
|||||||
|
|
||||||
namespace StarterNG.Domain.Sceneries;
|
namespace StarterNG.Domain.Sceneries;
|
||||||
|
|
||||||
|
/// <summary>What the simulator finds of the files a scenery names.</summary>
|
||||||
|
/// <param name="Opens">Whether it opens a file of the scenery folder, named as the scenery names it.</param>
|
||||||
|
/// <param name="HasSbt">
|
||||||
|
/// Whether the scenery has its own .sbt: while that is in use, its terrain includes
|
||||||
|
/// (<c>_ter.scm</c>) and terrain geometry are passed over, the .sbt holding them.
|
||||||
|
/// </param>
|
||||||
|
public sealed record SceneryFileLookup(Func<string, bool> Opens, bool HasSbt = false);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Goes through a scenery's text for the parts the starter reads - trainsets,
|
/// Goes through a scenery's text for the parts the starter reads - trainsets,
|
||||||
/// vehicles, includes - finding where each trainset and loose vehicle is, and
|
/// vehicles, includes - finding where each trainset and loose vehicle is, and
|
||||||
@@ -29,17 +37,17 @@ public static class ScenerySyntax
|
|||||||
|
|
||||||
/// <param name="text">The scenery's text, its includes put in place.</param>
|
/// <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="file">The scenery's file name, for faults in its own text.</param>
|
||||||
/// <param name="opensInclude">
|
/// <param name="files">
|
||||||
/// Whether the simulator opens an include, named as the include names it; null
|
/// What the simulator finds of the files the scenery names - includes and terrain
|
||||||
/// leaves includes unchecked.
|
/// files; null leaves them unchecked.
|
||||||
/// </param>
|
/// </param>
|
||||||
public static Result Scan(string text, string file, Func<string, bool>? opensInclude = null)
|
public static Result Scan(string text, string file, SceneryFileLookup? files = null)
|
||||||
{
|
{
|
||||||
string code = SceneryCode.Mask(text, out int unclosed);
|
string code = SceneryCode.Mask(text, out int unclosed);
|
||||||
var tokens = SceneryCode.Tokens(code);
|
var tokens = SceneryCode.Tokens(code);
|
||||||
var lines = new SceneryLines(text, file);
|
var lines = new SceneryLines(text, file);
|
||||||
|
|
||||||
var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true);
|
var simulator = new Reading(tokens, lines, files, asSimulator: true);
|
||||||
simulator.Run();
|
simulator.Run();
|
||||||
var author = new Reading(tokens, lines, null, asSimulator: false);
|
var author = new Reading(tokens, lines, null, asSimulator: false);
|
||||||
author.Run();
|
author.Run();
|
||||||
@@ -110,8 +118,14 @@ public static class ScenerySyntax
|
|||||||
}
|
}
|
||||||
|
|
||||||
private sealed class Reading(
|
private sealed class Reading(
|
||||||
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator)
|
List<SceneryCode.Token> tokens, SceneryLines lines, SceneryFileLookup? files, bool asSimulator)
|
||||||
{
|
{
|
||||||
|
// Whether the scenery's .sbt is in use, and whether the simulator passed over
|
||||||
|
// something of the text on its account already - or got past FirstInit - after
|
||||||
|
// which a terrain file can no longer take its place.
|
||||||
|
private bool _sbt = files?.HasSbt ?? false;
|
||||||
|
private bool _sbtTaken;
|
||||||
|
|
||||||
public readonly List<(int Start, int End, string Name)> Trainsets = new();
|
public readonly List<(int Start, int End, string Name)> Trainsets = new();
|
||||||
public readonly List<(int, int)> Loose = new();
|
public readonly List<(int, int)> Loose = new();
|
||||||
public readonly List<SceneryFault> Faults = new();
|
public readonly List<SceneryFault> Faults = new();
|
||||||
@@ -156,12 +170,20 @@ public static class ScenerySyntax
|
|||||||
{
|
{
|
||||||
// Not a vehicle: only its kind is stepped over, what follows is its own.
|
// Not a vehicle: only its kind is stepped over, what follows is its own.
|
||||||
if (i + 4 >= tokens.Count || !tokens[i + 4].Is("dynamic"))
|
if (i + 4 >= tokens.Count || !tokens[i + 4].Is("dynamic"))
|
||||||
|
{
|
||||||
|
if (_sbt && TerrainGeometry(i))
|
||||||
|
_sbtTaken = true;
|
||||||
i += 4;
|
i += 4;
|
||||||
|
}
|
||||||
else
|
else
|
||||||
i = Vehicle(i);
|
i = Vehicle(i);
|
||||||
}
|
}
|
||||||
else if (token.Is("include"))
|
else if (token.Is("include"))
|
||||||
i = Include(i);
|
i = Include(i);
|
||||||
|
else if (token.Is("terrain") && asSimulator)
|
||||||
|
i = Terrain(i);
|
||||||
|
else if (token.Is("firstinit"))
|
||||||
|
_sbtTaken |= _sbt;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_open is { } last)
|
if (_open is { } last)
|
||||||
@@ -369,8 +391,13 @@ public static class ScenerySyntax
|
|||||||
return stop < tokens.Count && tokens[stop].Is("end") ? stop : stop - 1;
|
return stop < tokens.Count && tokens[stop].Is("end") ? stop : stop - 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opensInclude is not null && Plain(name) && !opensInclude(name))
|
if (files is not null && Plain(name))
|
||||||
Fault(SceneryFaultKind.MissingInclude, token.Index, token: name);
|
{
|
||||||
|
if (_sbt && SimulatorNames.Lower(name).Contains("_ter.scm"))
|
||||||
|
_sbtTaken = true;
|
||||||
|
else if (!files.Opens(name))
|
||||||
|
Fault(SceneryFaultKind.MissingInclude, token.Index, token: name);
|
||||||
|
}
|
||||||
|
|
||||||
// The simulator takes its parameters up to the word "end", written just so,
|
// The simulator takes its parameters up to the word "end", written just so,
|
||||||
// whatever comes before it.
|
// whatever comes before it.
|
||||||
@@ -383,6 +410,52 @@ public static class ScenerySyntax
|
|||||||
return last;
|
return last;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A terrain directive: the files it names up to <c>endterrain</c>. Of a terrain
|
||||||
|
/// file (.txtf, .btf) the simulator takes the text or the binary file of the same
|
||||||
|
/// name, whichever is there; an .sbt it passes over quietly when it cannot use it.
|
||||||
|
/// </summary>
|
||||||
|
private int Terrain(int at)
|
||||||
|
{
|
||||||
|
int end = at + 1;
|
||||||
|
while (end < tokens.Count && !tokens[end].Is("endterrain"))
|
||||||
|
end++;
|
||||||
|
|
||||||
|
for (int named = at + 1; named < end && files is not null; named++)
|
||||||
|
{
|
||||||
|
string name = tokens[named].Text;
|
||||||
|
string lower = SimulatorNames.Lower(name);
|
||||||
|
if (!Plain(name) || !(lower.EndsWith(".txtf") || lower.EndsWith(".btf")))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
string stem = name[..name.LastIndexOf('.')];
|
||||||
|
if (!files.Opens(stem + ".txtf") && !files.Opens(stem + ".btf"))
|
||||||
|
Fault(SceneryFaultKind.MissingTerrainFile, tokens[named].Index, token: name);
|
||||||
|
else if (_sbtTaken)
|
||||||
|
Fault(SceneryFaultKind.TerrainFileBehindSbt, tokens[named].Index, token: name);
|
||||||
|
else
|
||||||
|
// The .sbt gives way: the terrain includes from here on are read after all.
|
||||||
|
_sbt = false;
|
||||||
|
}
|
||||||
|
return Math.Min(end, tokens.Count - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the node starting at the given word is terrain geometry, which an .sbt
|
||||||
|
/// in use holds in its place: triangles or lines, or a model shown from any distance.
|
||||||
|
/// </summary>
|
||||||
|
private bool TerrainGeometry(int at)
|
||||||
|
{
|
||||||
|
if (at + 4 >= tokens.Count)
|
||||||
|
return false;
|
||||||
|
var kind = tokens[at + 4];
|
||||||
|
if (kind.Is("model"))
|
||||||
|
return double.TryParse(tokens[at + 2].Text, NumberStyles.Float, CultureInfo.InvariantCulture,
|
||||||
|
out double nearest) && nearest < 0;
|
||||||
|
return kind.Is("triangles") || kind.Is("triangle_strip") || kind.Is("triangle_fan") ||
|
||||||
|
kind.Is("lines") || kind.Is("line_strip") || kind.Is("line_loop");
|
||||||
|
}
|
||||||
|
|
||||||
// A vehicle with no trainset around it, written as within one - offset, crew,
|
// A vehicle with no trainset around it, written as within one - offset, crew,
|
||||||
// coupling - where its track, offset and crew belong.
|
// coupling - where its track, offset and crew belong.
|
||||||
private bool TrainsetStyle(int at) =>
|
private bool TrainsetStyle(int at) =>
|
||||||
|
|||||||
@@ -133,20 +133,6 @@ public sealed class SimulatorSettings
|
|||||||
public bool EnableTraction = true;
|
public bool EnableTraction = true;
|
||||||
public bool LiveTraction = true;
|
public bool LiveTraction = true;
|
||||||
public bool PhysicsLog;
|
public bool PhysicsLog;
|
||||||
/// <summary>
|
|
||||||
/// The black box of the session, and with it the tapes (.dat) of the vehicles the player was in, written when the
|
|
||||||
/// simulator closes: the tapes without the log of every vehicle. With no entry of its own it goes with the physics log.
|
|
||||||
/// </summary>
|
|
||||||
public bool BlackBox;
|
|
||||||
/// <summary>Whether eu07.ini had a line of its own for the black box when read: it is kept saying what is wanted.</summary>
|
|
||||||
public bool BlackBoxInIni;
|
|
||||||
/// <summary>
|
|
||||||
/// The physics logs (.dat) of the trains only, "physicslog.trains": of each driver of rail vehicles, not of the
|
|
||||||
/// passengers nor of the vehicles of the roads. The tapes of every train, far fewer files than the log of every vehicle.
|
|
||||||
/// </summary>
|
|
||||||
public bool PhysicsLogTrains;
|
|
||||||
/// <summary>Whether eu07.ini had a line for the logs of the trains when read: kept, else written only when on.</summary>
|
|
||||||
public bool PhysicsLogTrainsInIni;
|
|
||||||
public bool DebugLog = true;
|
public bool DebugLog = true;
|
||||||
public bool MultipleLogs;
|
public bool MultipleLogs;
|
||||||
public bool DisplaySimulation = true;
|
public bool DisplaySimulation = true;
|
||||||
@@ -161,29 +147,6 @@ public sealed class SimulatorSettings
|
|||||||
public int VehiclesVolume = 100;
|
public int VehiclesVolume = 100;
|
||||||
public int PositionalVolume = 100;
|
public int PositionalVolume = 100;
|
||||||
public int AmbientVolume = 100;
|
public int AmbientVolume = 100;
|
||||||
|
|
||||||
// OpenAL Soft options of the simulator; the defaults leave the choice to the library, as the
|
|
||||||
// simulator did before it had these keys.
|
|
||||||
/// <summary>sound.openal.renderer: the output device, empty for the system's default.</summary>
|
|
||||||
public string AudioDevice = "";
|
|
||||||
/// <summary>sound.outputmode: auto, mono, stereo, stereo-basic, uhj, headphones, quad, 5.1, 6.1, 7.1.</summary>
|
|
||||||
public string AudioOutputMode = "auto";
|
|
||||||
/// <summary>sound.hrtf: auto, on, off.</summary>
|
|
||||||
public string AudioHrtf = "auto";
|
|
||||||
/// <summary>sound.hrtf.profile: the HRTF data set, empty for the library's choice.</summary>
|
|
||||||
public string AudioHrtfProfile = "";
|
|
||||||
/// <summary>sound.resampler: empty for the library's default.</summary>
|
|
||||||
public string AudioResampler = "";
|
|
||||||
/// <summary>sound.limiter: auto, on, off.</summary>
|
|
||||||
public string AudioLimiter = "auto";
|
|
||||||
/// <summary>sound.frequency: the mixing rate in Hz, 0 for the device's.</summary>
|
|
||||||
public int AudioFrequency;
|
|
||||||
/// <summary>sound.doppler: the strength of the Doppler effect.</summary>
|
|
||||||
public double AudioDoppler = 0.25;
|
|
||||||
/// <summary>sound.efx.lowpass: soundproofing also muffles the high frequencies.</summary>
|
|
||||||
public bool AudioLowpass;
|
|
||||||
/// <summary>sound.efx.airabsorption: 0-10, the high frequencies fade with distance.</summary>
|
|
||||||
public double AudioAirAbsorption;
|
|
||||||
public bool SkipPipeline;
|
public bool SkipPipeline;
|
||||||
public int PythonScreenUpdateRate = 200;
|
public int PythonScreenUpdateRate = 200;
|
||||||
public bool DebugLogVisible;
|
public bool DebugLogVisible;
|
||||||
|
|||||||
@@ -29,42 +29,23 @@ public readonly record struct TapeSample(
|
|||||||
public sealed class HaslerTape
|
public sealed class HaslerTape
|
||||||
{
|
{
|
||||||
// Columns counted from the start; the security flag is counted from the end, past
|
// Columns counted from the start; the security flag is counted from the end, past
|
||||||
// the command, which is free text, as far from the end as the header has it: the
|
// the command, which is free text. The header says m/s and MPa, the values are km/h and bar.
|
||||||
// simulator adds a new column at the end (the vehicle's speed, 2026-10). The header
|
|
||||||
// says m/s and MPa, the values are km/h and bar.
|
|
||||||
private const int TimeColumn = 0;
|
private const int TimeColumn = 0;
|
||||||
private const int VelocityColumn = 1;
|
private const int VelocityColumn = 1;
|
||||||
private const int BrakePressColumn = 8;
|
private const int BrakePressColumn = 8;
|
||||||
private const int PipePressColumn = 9;
|
private const int PipePressColumn = 9;
|
||||||
private const int MotorCurrentColumn = 10;
|
private const int MotorCurrentColumn = 10;
|
||||||
private const string SecurityHeading = "Security";
|
private const int SecurityFromEnd = 6;
|
||||||
private const int SecurityFromEndOf25 = 6; // a log with no header to tell: the columns up to the water's temperature
|
|
||||||
private const int MinimumColumns = 17;
|
private const int MinimumColumns = 17;
|
||||||
|
|
||||||
// above the longest step the simulator makes at once (its frame is held to a second) and a line's interval: a
|
public HaslerTape(IReadOnlyList<TapeSample> samples)
|
||||||
// stall of the simulator, a dragged window say, is time driven or stood, not a gap
|
|
||||||
private const double MinimumGapSeconds = 2.0;
|
|
||||||
private const int GapSteps = 20;
|
|
||||||
|
|
||||||
public HaslerTape(IReadOnlyList<TapeSample> samples) : this(samples, GapAbove(samples))
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
// the gap already found, by the reader: the steps are sorted once, not again here
|
|
||||||
private HaslerTape(IReadOnlyList<TapeSample> samples, double gap)
|
|
||||||
{
|
{
|
||||||
Samples = samples;
|
Samples = samples;
|
||||||
foreach (var s in samples)
|
foreach (var s in samples)
|
||||||
MaxSpeedKmh = Math.Max(MaxSpeedKmh, s.SpeedKmh);
|
MaxSpeedKmh = Math.Max(MaxSpeedKmh, s.SpeedKmh);
|
||||||
GapSeconds = gap;
|
|
||||||
for (int i = 1; i < samples.Count; i++)
|
for (int i = 1; i < samples.Count; i++)
|
||||||
{
|
if (samples[i].SpeedKmh > 0.5)
|
||||||
double step = samples[i].Time - samples[i - 1].Time;
|
RunningTime += samples[i].Time - samples[i - 1].Time;
|
||||||
if (step > gap)
|
|
||||||
GapTime += step;
|
|
||||||
else if (samples[i].SpeedKmh > 0.5)
|
|
||||||
RunningTime += step;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public IReadOnlyList<TapeSample> Samples { get; }
|
public IReadOnlyList<TapeSample> Samples { get; }
|
||||||
@@ -79,137 +60,50 @@ public sealed class HaslerTape
|
|||||||
|
|
||||||
public double MaxSpeedKmh { get; }
|
public double MaxSpeedKmh { get; }
|
||||||
|
|
||||||
/// <summary>Seconds on the move; the rest of <see cref="Duration"/> was spent standing, or not recorded.</summary>
|
/// <summary>Seconds on the move; the rest of <see cref="Duration"/> was spent standing.</summary>
|
||||||
public double RunningTime { get; }
|
public double RunningTime { get; }
|
||||||
|
|
||||||
/// <summary>Seconds of <see cref="Duration"/> not recorded: the gaps, see <see cref="GapAbove"/>.</summary>
|
public double StandingTime => Duration - RunningTime;
|
||||||
public double GapTime { get; }
|
|
||||||
|
|
||||||
/// <summary>A step between two lines longer than this is a gap: <see cref="GapAbove"/> of this tape.</summary>
|
|
||||||
public double GapSeconds { get; }
|
|
||||||
|
|
||||||
public double StandingTime => Duration - RunningTime - GapTime;
|
|
||||||
|
|
||||||
/// <summary>Mean speed while moving.</summary>
|
/// <summary>Mean speed while moving.</summary>
|
||||||
public double AverageSpeedKmh => RunningTime > 0 ? DistanceM / RunningTime * 3.6 : 0;
|
public double AverageSpeedKmh => RunningTime > 0 ? DistanceM / RunningTime * 3.6 : 0;
|
||||||
|
|
||||||
/// <summary>Mean speed over the whole recording, stops included - the commercial speed.</summary>
|
/// <summary>Mean speed over the whole recording, stops included - the commercial speed.</summary>
|
||||||
public double AverageWithStopsKmh => Duration - GapTime > 0 ? DistanceM / (Duration - GapTime) * 3.6 : 0;
|
public double AverageWithStopsKmh => Duration > 0 ? DistanceM / Duration * 3.6 : 0;
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// A step between two lines longer than this is time not recorded, the player in another vehicle before
|
|
||||||
/// coming back to this one: neither driving nor standing, and no distance. The lines come every 0.05 s of
|
|
||||||
/// simulated time or so; it is twenty of their usual steps, two seconds at least.
|
|
||||||
/// </summary>
|
|
||||||
public static double GapAbove(IReadOnlyList<TapeSample> samples)
|
|
||||||
{
|
|
||||||
if (samples.Count < 2)
|
|
||||||
return MinimumGapSeconds;
|
|
||||||
var steps = new double[samples.Count - 1];
|
|
||||||
for (int i = 1; i < samples.Count; i++)
|
|
||||||
steps[i - 1] = samples[i].Time - samples[i - 1].Time;
|
|
||||||
Array.Sort(steps);
|
|
||||||
return Math.Max(MinimumGapSeconds, GapSteps * steps[steps.Length / 2]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HaslerTape Parse(string text)
|
public static HaslerTape Parse(string text)
|
||||||
{
|
{
|
||||||
var reader = new Reader();
|
var samples = new List<TapeSample>();
|
||||||
reader.Feed(text);
|
double distance = 0;
|
||||||
return reader.Tape(final: true);
|
TapeSample? previous = null;
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
foreach (var raw in text.Split('\n'))
|
||||||
/// A tape read as it is written: each piece of the file given once, in order, so a log the simulator keeps
|
|
||||||
/// adding to - fast, at a higher time speed - is not read and split from its start every time it grows. A line
|
|
||||||
/// not ended yet waits for the rest.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class Reader
|
|
||||||
{
|
|
||||||
private readonly List<TapeSample> _samples = new();
|
|
||||||
private readonly System.Text.StringBuilder _unended = new();
|
|
||||||
private int _securityFromEnd = SecurityFromEndOf25;
|
|
||||||
|
|
||||||
public void Feed(string text)
|
|
||||||
{
|
|
||||||
WentBack = false;
|
|
||||||
int start = 0;
|
|
||||||
for (int end = text.IndexOf('\n'); end >= 0; end = text.IndexOf('\n', start))
|
|
||||||
{
|
|
||||||
if (_unended.Length > 0)
|
|
||||||
{
|
|
||||||
_unended.Append(text, start, end - start);
|
|
||||||
Keep(_unended.ToString(), _samples);
|
|
||||||
_unended.Clear();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
Keep(text.Substring(start, end - start), _samples);
|
|
||||||
start = end + 1;
|
|
||||||
}
|
|
||||||
_unended.Append(text, start, text.Length - start);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The tape of what was read. Final, the end of the file: a last line with no end is read too, though
|
|
||||||
/// only for this tape; otherwise it may be cut short by a simulator still writing, and waits.
|
|
||||||
/// </summary>
|
|
||||||
public HaslerTape Tape(bool final)
|
|
||||||
{
|
|
||||||
var read = _samples;
|
|
||||||
if (final && _unended.Length > 0)
|
|
||||||
{
|
|
||||||
read = new List<TapeSample>(_samples);
|
|
||||||
Keep(_unended.ToString(), read);
|
|
||||||
}
|
|
||||||
// the distance, trapezoid by trapezoid, none over the gaps
|
|
||||||
var samples = new List<TapeSample>(read.Count);
|
|
||||||
double gap = GapAbove(read), distance = 0;
|
|
||||||
for (int i = 0; i < read.Count; i++)
|
|
||||||
{
|
|
||||||
var sample = read[i];
|
|
||||||
if (i > 0)
|
|
||||||
{
|
|
||||||
var before = read[i - 1];
|
|
||||||
double step = sample.Time - before.Time;
|
|
||||||
if (step <= gap)
|
|
||||||
distance += (before.SpeedKmh + sample.SpeedKmh) / 2 / 3.6 * step;
|
|
||||||
}
|
|
||||||
samples.Add(sample with { DistanceM = distance });
|
|
||||||
}
|
|
||||||
return new HaslerTape(samples, gap);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void Keep(string raw, List<TapeSample> samples)
|
|
||||||
{
|
{
|
||||||
var columns = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
|
var columns = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
|
||||||
if (columns.Length == 0)
|
if (columns.Length < MinimumColumns
|
||||||
return;
|
|| !Number(columns[TimeColumn], out double time)
|
||||||
if (!Number(columns[TimeColumn], out double time))
|
|| !Number(columns[VelocityColumn], out double velocity))
|
||||||
{
|
continue; // the header, or a line cut short by a simulator still writing
|
||||||
// the header; a line of figures may have the word too, in the free text of its command
|
|
||||||
int heading = Array.IndexOf(columns, SecurityHeading);
|
|
||||||
if (heading >= 0)
|
|
||||||
_securityFromEnd = columns.Length - heading;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (columns.Length < MinimumColumns || !Number(columns[VelocityColumn], out double velocity))
|
|
||||||
return; // a line cut short by a simulator still writing
|
|
||||||
|
|
||||||
Number(columns[BrakePressColumn], out double brake);
|
Number(columns[BrakePressColumn], out double brake);
|
||||||
Number(columns[PipePressColumn], out double pipe);
|
Number(columns[PipePressColumn], out double pipe);
|
||||||
Number(columns[MotorCurrentColumn], out double current);
|
Number(columns[MotorCurrentColumn], out double current);
|
||||||
bool security = _securityFromEnd <= columns.Length && columns[^_securityFromEnd] == "1";
|
bool security = columns[^SecurityFromEnd] == "1";
|
||||||
|
|
||||||
if (samples.Count > 0 && time < samples[^1].Time)
|
double speed = Math.Abs(velocity);
|
||||||
|
if (previous is { } p)
|
||||||
{
|
{
|
||||||
WentBack = true;
|
if (time < p.Time)
|
||||||
return;
|
continue;
|
||||||
|
distance += (p.SpeedKmh + speed) / 2 / 3.6 * (time - p.Time);
|
||||||
}
|
}
|
||||||
samples.Add(new TapeSample(time, Math.Abs(velocity), 0, brake, pipe, current, security));
|
|
||||||
|
var sample = new TapeSample(time, speed, distance, brake, pipe, current, security);
|
||||||
|
samples.Add(sample);
|
||||||
|
previous = sample;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>In the last piece fed, a line whose time was before the last one's, left out: maybe the log begun anew.</summary>
|
return new HaslerTape(samples);
|
||||||
public bool WentBack { get; private set; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Index of the last sample at or before the given time or distance.</summary>
|
/// <summary>Index of the last sample at or before the given time or distance.</summary>
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.IO;
|
|
||||||
|
|
||||||
namespace StarterNG.Infrastructure.Adapters;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Tells when anything in a folder or below it is written, made, removed or renamed, as
|
|
||||||
/// the system reports it. Only a hint that it is time to look: a save comes as several
|
|
||||||
/// reports, and on a network drive, under Wine or past the system's limit of watches it
|
|
||||||
/// may come as none, so whoever listens still looks now and then on its own.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class FolderChanges : IDisposable
|
|
||||||
{
|
|
||||||
private readonly FileSystemWatcher? _watcher;
|
|
||||||
|
|
||||||
/// <summary>Something changed, or the reports were lost and anything may have: on a thread of the pool.</summary>
|
|
||||||
public event Action? Changed;
|
|
||||||
|
|
||||||
/// <param name="folder">Watched with everything below it; a missing one is not watched.</param>
|
|
||||||
public FolderChanges(string folder)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (!Directory.Exists(folder))
|
|
||||||
return;
|
|
||||||
|
|
||||||
var watcher = new FileSystemWatcher(folder)
|
|
||||||
{
|
|
||||||
IncludeSubdirectories = true,
|
|
||||||
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName
|
|
||||||
| NotifyFilters.LastWrite | NotifyFilters.Size,
|
|
||||||
// Unpacking an update changes hundreds of files at once.
|
|
||||||
InternalBufferSize = 64 * 1024
|
|
||||||
};
|
|
||||||
watcher.Changed += (_, _) => Changed?.Invoke();
|
|
||||||
watcher.Created += (_, _) => Changed?.Invoke();
|
|
||||||
watcher.Deleted += (_, _) => Changed?.Invoke();
|
|
||||||
watcher.Renamed += (_, _) => Changed?.Invoke();
|
|
||||||
// Too many at once for the buffer: which ones is lost, so all are looked at.
|
|
||||||
watcher.Error += (_, _) => Changed?.Invoke();
|
|
||||||
watcher.EnableRaisingEvents = true;
|
|
||||||
_watcher = watcher;
|
|
||||||
}
|
|
||||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException
|
|
||||||
or PlatformNotSupportedException)
|
|
||||||
{
|
|
||||||
// Out of watches on Linux, or a drive that gives none: the slow look alone stays.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Whether the system reports changes here at all.</summary>
|
|
||||||
public bool Watching => _watcher is not null;
|
|
||||||
|
|
||||||
public void Dispose() => _watcher?.Dispose();
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using Avalonia.Controls;
|
|
||||||
using Avalonia.Threading;
|
|
||||||
using StarterNG.Application;
|
|
||||||
using StarterNG.Infrastructure.Adapters;
|
|
||||||
|
|
||||||
namespace StarterNG.Infrastructure;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Looks at a folder's files for a window, one look at a time on the UI thread: when the system
|
|
||||||
/// reports a change, once the burst a save makes has passed; when the window comes back to the
|
|
||||||
/// front; when asked; and now and then anyway, for the drives and systems where the reports do
|
|
||||||
/// not come - often where none come at all. From the window's opening to its closing.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class FolderLooks
|
|
||||||
{
|
|
||||||
/// <summary>How long the reports have to stop for: a save comes as several of them.</summary>
|
|
||||||
public static readonly TimeSpan Quiet = TimeSpan.FromMilliseconds(400);
|
|
||||||
|
|
||||||
/// <summary>How often it looks anyway where the system reports the changes.</summary>
|
|
||||||
public static readonly TimeSpan Watched = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
/// <summary>How often it looks where the system reports nothing.</summary>
|
|
||||||
public static readonly TimeSpan Unwatched = TimeSpan.FromSeconds(2);
|
|
||||||
|
|
||||||
private readonly Func<string> _folder;
|
|
||||||
private readonly OneAtATime _look;
|
|
||||||
private readonly TimeProvider _time;
|
|
||||||
private readonly object _gate = new();
|
|
||||||
private bool _closed;
|
|
||||||
private ITimer? _quiet;
|
|
||||||
private ITimer? _often;
|
|
||||||
private FolderChanges? _changes;
|
|
||||||
|
|
||||||
/// <param name="window">Looked for from its opening to its closing.</param>
|
|
||||||
/// <param name="folder">The folder, as it is when the window opens.</param>
|
|
||||||
/// <param name="look">The look itself; it knows when it is no time to look.</param>
|
|
||||||
/// <param name="time">The clock of the timers, the system's when not given.</param>
|
|
||||||
public FolderLooks(Window window, Func<string> folder, Func<Task> look, TimeProvider? time = null)
|
|
||||||
{
|
|
||||||
_folder = folder;
|
|
||||||
_look = new OneAtATime(look);
|
|
||||||
_time = time ?? TimeProvider.System;
|
|
||||||
window.Opened += (_, _) => Watch();
|
|
||||||
window.Activated += async (_, _) => await LookAsync();
|
|
||||||
window.Closed += (_, _) => Close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Whether the system reports the folder's changes; not before the window opens.</summary>
|
|
||||||
public bool Watching => _changes?.Watching == true;
|
|
||||||
|
|
||||||
/// <summary>Looks now, or once more after the look that runs.</summary>
|
|
||||||
public Task LookAsync() => _look.RunAsync();
|
|
||||||
|
|
||||||
private void Watch()
|
|
||||||
{
|
|
||||||
var changes = new FolderChanges(_folder());
|
|
||||||
var often = changes.Watching ? Watched : Unwatched;
|
|
||||||
lock (_gate)
|
|
||||||
{
|
|
||||||
_changes = changes;
|
|
||||||
_quiet = _time.CreateTimer(_ => LookLater(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
|
|
||||||
_often = _time.CreateTimer(_ => LookLater(), null, often, often);
|
|
||||||
}
|
|
||||||
changes.Changed += PutOff;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Each report puts the look off again, so a save of many files is one look after it. The
|
|
||||||
// reports come on threads of the pool, and may come still as the window closes.
|
|
||||||
private void PutOff()
|
|
||||||
{
|
|
||||||
lock (_gate)
|
|
||||||
{
|
|
||||||
if (!_closed)
|
|
||||||
_quiet?.Change(Quiet, Timeout.InfiniteTimeSpan);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The timers tick on threads of the pool; the look belongs on the UI thread.
|
|
||||||
private void LookLater() => Dispatcher.UIThread.Post(() => _ = LookAsync());
|
|
||||||
|
|
||||||
private void Close()
|
|
||||||
{
|
|
||||||
FolderChanges? changes;
|
|
||||||
lock (_gate)
|
|
||||||
{
|
|
||||||
_closed = true;
|
|
||||||
_quiet?.Dispose();
|
|
||||||
_often?.Dispose();
|
|
||||||
changes = _changes;
|
|
||||||
}
|
|
||||||
changes?.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,159 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.IO;
|
|
||||||
using System.Runtime.InteropServices;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace StarterNG.Infrastructure;
|
|
||||||
|
|
||||||
/// <summary>What the simulator's OpenAL library offers for its sound settings.</summary>
|
|
||||||
public sealed record AudioChoices(IReadOnlyList<string> Devices, IReadOnlyList<string> HrtfProfiles, IReadOnlyList<string> Resamplers)
|
|
||||||
{
|
|
||||||
public static AudioChoices None { get; } = new(Array.Empty<string>(), Array.Empty<string>(), Array.Empty<string>());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Asks the OpenAL library beside the simulator, the one it plays through, for the output devices,
|
|
||||||
/// the HRTF data sets and the resamplers. The data sets and the resamplers are known only with a
|
|
||||||
/// device open, so the default one is opened for a moment. An older library (OpenAL Soft before
|
|
||||||
/// 1.19 lists no resamplers), or none at all, gives what it can and empty lists for the rest.
|
|
||||||
/// </summary>
|
|
||||||
public static unsafe class OpenAlProbe
|
|
||||||
{
|
|
||||||
private const int AlcDeviceSpecifier = 0x1005;
|
|
||||||
private const int AlcAllDevicesSpecifier = 0x1013;
|
|
||||||
private const int AlcNumHrtfSpecifiers = 0x1994;
|
|
||||||
private const int AlcHrtfSpecifier = 0x1995;
|
|
||||||
private const int AlNumResamplers = 0x1210;
|
|
||||||
private const int AlResamplerName = 0x1213;
|
|
||||||
|
|
||||||
/// <summary>The file of the library in the simulator's folder.</summary>
|
|
||||||
public static string LibraryFile => OperatingSystem.IsWindows() ? "OpenAL32.dll" : "libopenal.so.1";
|
|
||||||
|
|
||||||
public static AudioChoices Read(string gameFolder)
|
|
||||||
{
|
|
||||||
// The library stays loaded: OpenAL Soft keeps threads of its own, unloading it under them is not safe.
|
|
||||||
if (!NativeLibrary.TryLoad(Path.Combine(gameFolder, LibraryFile), out IntPtr library))
|
|
||||||
return AudioChoices.None;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return new Api(library).Read();
|
|
||||||
}
|
|
||||||
catch (EntryPointNotFoundException)
|
|
||||||
{
|
|
||||||
return AudioChoices.None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>The entry points of one library; the extension ones are null where it lacks them.</summary>
|
|
||||||
private sealed class Api
|
|
||||||
{
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<IntPtr, byte*, byte> _alcIsExtensionPresent;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<IntPtr, int, byte*> _alcGetString;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<byte*, IntPtr> _alcOpenDevice;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<IntPtr, byte> _alcCloseDevice;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<IntPtr, int*, IntPtr> _alcCreateContext;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<IntPtr, byte> _alcMakeContextCurrent;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<IntPtr, void> _alcDestroyContext;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<IntPtr, int, int, int*, void> _alcGetIntegerv;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<int, int> _alGetInteger;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<IntPtr, int, int, byte*> _alcGetStringiSOFT;
|
|
||||||
private readonly delegate* unmanaged[Cdecl]<int, int, byte*> _alGetStringiSOFT;
|
|
||||||
|
|
||||||
public Api(IntPtr library)
|
|
||||||
{
|
|
||||||
_alcIsExtensionPresent = (delegate* unmanaged[Cdecl]<IntPtr, byte*, byte>)NativeLibrary.GetExport(library, "alcIsExtensionPresent");
|
|
||||||
_alcGetString = (delegate* unmanaged[Cdecl]<IntPtr, int, byte*>)NativeLibrary.GetExport(library, "alcGetString");
|
|
||||||
_alcOpenDevice = (delegate* unmanaged[Cdecl]<byte*, IntPtr>)NativeLibrary.GetExport(library, "alcOpenDevice");
|
|
||||||
_alcCloseDevice = (delegate* unmanaged[Cdecl]<IntPtr, byte>)NativeLibrary.GetExport(library, "alcCloseDevice");
|
|
||||||
_alcCreateContext = (delegate* unmanaged[Cdecl]<IntPtr, int*, IntPtr>)NativeLibrary.GetExport(library, "alcCreateContext");
|
|
||||||
_alcMakeContextCurrent = (delegate* unmanaged[Cdecl]<IntPtr, byte>)NativeLibrary.GetExport(library, "alcMakeContextCurrent");
|
|
||||||
_alcDestroyContext = (delegate* unmanaged[Cdecl]<IntPtr, void>)NativeLibrary.GetExport(library, "alcDestroyContext");
|
|
||||||
_alcGetIntegerv = (delegate* unmanaged[Cdecl]<IntPtr, int, int, int*, void>)NativeLibrary.GetExport(library, "alcGetIntegerv");
|
|
||||||
_alGetInteger = (delegate* unmanaged[Cdecl]<int, int>)NativeLibrary.GetExport(library, "alGetInteger");
|
|
||||||
// OpenAL Soft exports its extension functions too; a library without them leaves these null.
|
|
||||||
NativeLibrary.TryGetExport(library, "alcGetStringiSOFT", out IntPtr getStringi);
|
|
||||||
_alcGetStringiSOFT = (delegate* unmanaged[Cdecl]<IntPtr, int, int, byte*>)getStringi;
|
|
||||||
NativeLibrary.TryGetExport(library, "alGetStringiSOFT", out IntPtr alGetStringi);
|
|
||||||
_alGetStringiSOFT = (delegate* unmanaged[Cdecl]<int, int, byte*>)alGetStringi;
|
|
||||||
}
|
|
||||||
|
|
||||||
public AudioChoices Read()
|
|
||||||
{
|
|
||||||
int deviceList = HasExtension("ALC_ENUMERATE_ALL_EXT\0"u8) ? AlcAllDevicesSpecifier : AlcDeviceSpecifier;
|
|
||||||
List<string> devices = NameList(_alcGetString(IntPtr.Zero, deviceList));
|
|
||||||
|
|
||||||
IntPtr device = _alcOpenDevice(null);
|
|
||||||
if (device == IntPtr.Zero)
|
|
||||||
return new AudioChoices(devices, Array.Empty<string>(), Array.Empty<string>());
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return new AudioChoices(devices, HrtfProfiles(device), Resamplers(device));
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_alcCloseDevice(device);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool HasExtension(ReadOnlySpan<byte> name)
|
|
||||||
{
|
|
||||||
fixed (byte* text = name)
|
|
||||||
return _alcIsExtensionPresent(IntPtr.Zero, text) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<string> HrtfProfiles(IntPtr device)
|
|
||||||
{
|
|
||||||
var names = new List<string>();
|
|
||||||
if (_alcGetStringiSOFT == null)
|
|
||||||
return names;
|
|
||||||
int count = 0;
|
|
||||||
_alcGetIntegerv(device, AlcNumHrtfSpecifiers, 1, &count);
|
|
||||||
for (int index = 0; index < count; index++)
|
|
||||||
names.Add(Utf8(_alcGetStringiSOFT(device, AlcHrtfSpecifier, index)));
|
|
||||||
return names;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<string> Resamplers(IntPtr device)
|
|
||||||
{
|
|
||||||
var names = new List<string>();
|
|
||||||
if (_alGetStringiSOFT == null)
|
|
||||||
return names;
|
|
||||||
IntPtr context = _alcCreateContext(device, null);
|
|
||||||
if (context == IntPtr.Zero)
|
|
||||||
return names;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
_alcMakeContextCurrent(context);
|
|
||||||
int count = _alGetInteger(AlNumResamplers);
|
|
||||||
for (int index = 0; index < count; index++)
|
|
||||||
names.Add(Utf8(_alGetStringiSOFT(AlResamplerName, index)));
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_alcMakeContextCurrent(IntPtr.Zero);
|
|
||||||
_alcDestroyContext(context);
|
|
||||||
}
|
|
||||||
return names;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string Utf8(byte* text) => text == null ? "" : Marshal.PtrToStringUTF8((IntPtr)text) ?? "";
|
|
||||||
|
|
||||||
/// <summary>A list of null-terminated names ending with an empty one, as OpenAL gives the devices.</summary>
|
|
||||||
private static List<string> NameList(byte* list)
|
|
||||||
{
|
|
||||||
var names = new List<string>();
|
|
||||||
if (list == null)
|
|
||||||
return names;
|
|
||||||
while (*list != 0)
|
|
||||||
{
|
|
||||||
int length = 0;
|
|
||||||
while (list[length] != 0)
|
|
||||||
length++;
|
|
||||||
names.Add(Encoding.UTF8.GetString(list, length));
|
|
||||||
list += length + 1;
|
|
||||||
}
|
|
||||||
return names;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -20,11 +20,11 @@ public sealed class SceneryParser
|
|||||||
_random = random;
|
_random = random;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <param name="opensInclude">
|
/// <param name="files">
|
||||||
/// Whether the simulator opens an include, as the include names it; null leaves
|
/// What the simulator finds of the files the scenery names; null leaves them
|
||||||
/// includes unchecked.
|
/// unchecked.
|
||||||
/// </param>
|
/// </param>
|
||||||
public Scenery Parse(string path, string content, Func<string, bool>? opensInclude = null)
|
public Scenery Parse(string path, string content, SceneryFileLookup? files = null)
|
||||||
{
|
{
|
||||||
string original = content;
|
string original = content;
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ public sealed class SceneryParser
|
|||||||
|
|
||||||
// Read from the text with its optional includes blanked, which keeps every
|
// 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.
|
// 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), opensInclude);
|
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), files);
|
||||||
var faults = syntax.Faults.ToList();
|
var faults = syntax.Faults.ToList();
|
||||||
var inlined = SceneryIncludes.Ranges(content);
|
var inlined = SceneryIncludes.Ranges(content);
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ using System.Text;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using StarterNG.Application.Abstractions;
|
using StarterNG.Application.Abstractions;
|
||||||
using StarterNG.Domain;
|
|
||||||
using StarterNG.Domain.Sceneries;
|
using StarterNG.Domain.Sceneries;
|
||||||
using StarterNG.Infrastructure.Adapters;
|
using StarterNG.Infrastructure.Adapters;
|
||||||
|
|
||||||
@@ -78,10 +77,9 @@ public sealed class SceneryRepository : ISceneryRepository
|
|||||||
var encodings = new Dictionary<string, Encoding>(StringComparer.Ordinal);
|
var encodings = new Dictionary<string, Encoding>(StringComparer.Ordinal);
|
||||||
|
|
||||||
// With its own .sbt the scenery's terrain comes from it, and the simulator
|
// With its own .sbt the scenery's terrain comes from it, and the simulator
|
||||||
// passes its terrain includes over without opening them.
|
// passes its terrain includes over without opening them - unless a terrain
|
||||||
|
// file takes its place.
|
||||||
bool binaryTerrain = Opens(Path.GetFileNameWithoutExtension(path) + ".sbt");
|
bool binaryTerrain = Opens(Path.GetFileNameWithoutExtension(path) + ".sbt");
|
||||||
bool OpensInclude(string name) =>
|
|
||||||
Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm"));
|
|
||||||
|
|
||||||
(string File, string Text)? ReadInclude(string name)
|
(string File, string Text)? ReadInclude(string name)
|
||||||
{
|
{
|
||||||
@@ -98,7 +96,7 @@ public sealed class SceneryRepository : ISceneryRepository
|
|||||||
|
|
||||||
string own = LegacyText.Decode(_files.ReadAllBytes(path), out var ownEncoding);
|
string own = LegacyText.Decode(_files.ReadAllBytes(path), out var ownEncoding);
|
||||||
string text = SceneryIncludes.Inline(own, ReadInclude);
|
string text = SceneryIncludes.Inline(own, ReadInclude);
|
||||||
var scenery = _parser.Parse(path, text, OpensInclude);
|
var scenery = _parser.Parse(path, text, new SceneryFileLookup(Opens, binaryTerrain));
|
||||||
scenery.HasCompanionTimetable = binaryTerrain;
|
scenery.HasCompanionTimetable = binaryTerrain;
|
||||||
scenery.Sources = sources;
|
scenery.Sources = sources;
|
||||||
scenery.TextEncoding = ownEncoding;
|
scenery.TextEncoding = ownEncoding;
|
||||||
|
|||||||
@@ -22,37 +22,15 @@ public sealed class ExecutableLocator
|
|||||||
private string? _wine;
|
private string? _wine;
|
||||||
private bool _wineLookedUp;
|
private bool _wineLookedUp;
|
||||||
private string? _missingPickLogged;
|
private string? _missingPickLogged;
|
||||||
private readonly bool _lacksAvx2;
|
|
||||||
|
|
||||||
/// <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)
|
||||||
public ExecutableLocator(IFileSystem files, IGamePaths paths, IEnvironment environment, IDiagnosticsLog log,
|
|
||||||
bool? lacksAvx2 = null)
|
|
||||||
{
|
{
|
||||||
_files = files;
|
_files = files;
|
||||||
_paths = paths;
|
_paths = paths;
|
||||||
_environment = environment;
|
_environment = environment;
|
||||||
_log = log;
|
_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";
|
public string CanonicalName => _environment.IsWindows ? "eu07.exe" : "eu07";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -93,8 +71,7 @@ public sealed class ExecutableLocator
|
|||||||
{
|
{
|
||||||
var candidates = _files.GetFiles(_paths.Root, "eu07*")
|
var candidates = _files.GetFiles(_paths.Root, "eu07*")
|
||||||
.Where(IsCandidate)
|
.Where(IsCandidate)
|
||||||
.OrderBy(Rank)
|
.OrderBy(path => IsExeOnLinux(path) ? 1 : 0)
|
||||||
.ThenByDescending(path => _lacksAvx2 && IsNoAvx2(path) ? _files.GetLastWriteTimeUtc(path) : DateTime.MinValue)
|
|
||||||
.ThenBy(path => string.Equals(Path.GetFileName(path), CanonicalName,
|
.ThenBy(path => string.Equals(Path.GetFileName(path), CanonicalName,
|
||||||
StringComparison.OrdinalIgnoreCase) ? 0 : 1)
|
StringComparison.OrdinalIgnoreCase) ? 0 : 1)
|
||||||
.ThenBy(path => Path.GetFileName(path).Length);
|
.ThenBy(path => Path.GetFileName(path).Length);
|
||||||
@@ -124,18 +101,6 @@ public sealed class ExecutableLocator
|
|||||||
return CanonicalName;
|
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)
|
public List<string> ListCandidates(string? directory = null)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|||||||
@@ -9,21 +9,6 @@ namespace StarterNG.Infrastructure.Settings;
|
|||||||
|
|
||||||
public sealed class SettingsSerializer
|
public sealed class SettingsSerializer
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// An ini of before the tapes of the trains, its recording turned on ("blackbox yes", with the physics log of every
|
|
||||||
/// vehicle, hundreds of files on a big scenery): moved to the tapes of the trains, the log of every vehicle off.
|
|
||||||
/// Once: saved, the line of the trains' tapes is in the file, even turned off again before. A change of the
|
|
||||||
/// starter's, after the file is read, so saving writes it.
|
|
||||||
/// </summary>
|
|
||||||
public static void MoveToTrainTapes(SimulatorSettings s)
|
|
||||||
{
|
|
||||||
if (s.PhysicsLogTrainsInIni || !s.BlackBoxInIni || !s.BlackBox)
|
|
||||||
return;
|
|
||||||
s.PhysicsLogTrains = true;
|
|
||||||
s.PhysicsLogTrainsInIni = true;
|
|
||||||
s.PhysicsLog = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private readonly bool _dlssPlatform;
|
private readonly bool _dlssPlatform;
|
||||||
|
|
||||||
/// <param name="dlssPlatform">Whether the simulator can have DLSS here at all (not on macOS).</param>
|
/// <param name="dlssPlatform">Whether the simulator can have DLSS here at all (not on macOS).</param>
|
||||||
@@ -172,11 +157,6 @@ public sealed class SettingsSerializer
|
|||||||
s.EnableTraction = c.GetBool("enabletraction", true);
|
s.EnableTraction = c.GetBool("enabletraction", true);
|
||||||
s.LiveTraction = c.GetBool("livetraction", true);
|
s.LiveTraction = c.GetBool("livetraction", true);
|
||||||
s.PhysicsLog = c.GetBool("physicslog", false);
|
s.PhysicsLog = c.GetBool("physicslog", false);
|
||||||
s.PhysicsLogTrainsInIni = c.Has("physicslog.trains");
|
|
||||||
s.PhysicsLogTrains = c.GetBool("physicslog.trains", false);
|
|
||||||
// the simulator records the black box along with the physics logs when the ini says nothing of it
|
|
||||||
s.BlackBoxInIni = c.Has("blackbox");
|
|
||||||
s.BlackBox = s.BlackBoxInIni ? c.GetBool("blackbox", false) : s.PhysicsLog || s.PhysicsLogTrains;
|
|
||||||
int debugLog = c.GetInt("debuglog", 3);
|
int debugLog = c.GetInt("debuglog", 3);
|
||||||
s.DebugLog = (debugLog & 1) != 0;
|
s.DebugLog = (debugLog & 1) != 0;
|
||||||
s.DebugLogVisible = (debugLog & 2) != 0;
|
s.DebugLogVisible = (debugLog & 2) != 0;
|
||||||
@@ -194,7 +174,6 @@ public sealed class SettingsSerializer
|
|||||||
s.VehiclesVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.vehicle", 1.0) * 100), 0, 100);
|
s.VehiclesVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.vehicle", 1.0) * 100), 0, 100);
|
||||||
s.PositionalVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.positional", 1.0) * 100), 0, 100);
|
s.PositionalVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.positional", 1.0) * 100), 0, 100);
|
||||||
s.AmbientVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.ambient", 1.0) * 100), 0, 100);
|
s.AmbientVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.ambient", 1.0) * 100), 0, 100);
|
||||||
ReadAudioDevice(c, s);
|
|
||||||
s.SkipPipeline = c.GetBool("gfx.skippipeline", false);
|
s.SkipPipeline = c.GetBool("gfx.skippipeline", false);
|
||||||
s.PythonScreenUpdateRate = c.Has("python.updatetime")
|
s.PythonScreenUpdateRate = c.Has("python.updatetime")
|
||||||
? Clamp(c.GetInt("python.updatetime", 200), 0, 10000)
|
? Clamp(c.GetInt("python.updatetime", 200), 0, 10000)
|
||||||
@@ -391,13 +370,6 @@ public sealed class SettingsSerializer
|
|||||||
c.SetBool("enabletraction", s.EnableTraction);
|
c.SetBool("enabletraction", s.EnableTraction);
|
||||||
c.SetBool("livetraction", s.LiveTraction);
|
c.SetBool("livetraction", s.LiveTraction);
|
||||||
c.SetBool("physicslog", s.PhysicsLog);
|
c.SetBool("physicslog", s.PhysicsLog);
|
||||||
// written where it says more than the physics logs, or where the file has it already: an ini without it
|
|
||||||
// stays so, and a line written once and no longer saying more goes away on the next save
|
|
||||||
if (s.BlackBoxInIni || s.BlackBox != (s.PhysicsLog || s.PhysicsLogTrains))
|
|
||||||
c.SetBool("blackbox", s.BlackBox);
|
|
||||||
// a simulator before it doesn't know the line: an ini without it stays so while it is off
|
|
||||||
if (s.PhysicsLogTrainsInIni || s.PhysicsLogTrains)
|
|
||||||
c.SetBool("physicslog.trains", s.PhysicsLogTrains);
|
|
||||||
c.SetInt("debuglog",
|
c.SetInt("debuglog",
|
||||||
(s.DebugLog ? 1 : 0) | (s.DebugLogVisible ? 2 : 0) | s.DebugLogExtraBits);
|
(s.DebugLog ? 1 : 0) | (s.DebugLogVisible ? 2 : 0) | s.DebugLogExtraBits);
|
||||||
c.SetBool("multiplelogs", s.MultipleLogs);
|
c.SetBool("multiplelogs", s.MultipleLogs);
|
||||||
@@ -413,7 +385,6 @@ public sealed class SettingsSerializer
|
|||||||
c.SetDouble("sound.volume.vehicle", s.VehiclesVolume / 100.0);
|
c.SetDouble("sound.volume.vehicle", s.VehiclesVolume / 100.0);
|
||||||
c.SetDouble("sound.volume.positional", s.PositionalVolume / 100.0);
|
c.SetDouble("sound.volume.positional", s.PositionalVolume / 100.0);
|
||||||
c.SetDouble("sound.volume.ambient", s.AmbientVolume / 100.0);
|
c.SetDouble("sound.volume.ambient", s.AmbientVolume / 100.0);
|
||||||
WriteAudioDevice(c, s);
|
|
||||||
c.SetBool("gfx.skippipeline", s.SkipPipeline);
|
c.SetBool("gfx.skippipeline", s.SkipPipeline);
|
||||||
c.SetInt("python.updatetime", s.PythonScreenUpdateRate);
|
c.SetInt("python.updatetime", s.PythonScreenUpdateRate);
|
||||||
|
|
||||||
@@ -459,65 +430,6 @@ public sealed class SettingsSerializer
|
|||||||
return Clamp((int)Math.Round(value > 4 ? value : value * 100), 25, 200);
|
return Clamp((int)Math.Round(value > 4 ? value : value * 100), 25, 200);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The OpenAL Soft options. The names (devices, HRTF data sets, resamplers) can hold spaces, so
|
|
||||||
// the simulator takes them in quotes.
|
|
||||||
private static void ReadAudioDevice(ConfigFile c, SimulatorSettings s)
|
|
||||||
{
|
|
||||||
s.AudioDevice = Unquoted(c.GetString("sound.openal.renderer", ""));
|
|
||||||
s.AudioOutputMode = FirstTokenOr(c, "sound.outputmode", "auto");
|
|
||||||
s.AudioHrtf = FirstTokenOr(c, "sound.hrtf", "auto");
|
|
||||||
s.AudioHrtfProfile = Unquoted(c.GetString("sound.hrtf.profile", ""));
|
|
||||||
s.AudioResampler = Unquoted(c.GetString("sound.resampler", ""));
|
|
||||||
s.AudioLimiter = FirstTokenOr(c, "sound.limiter", "auto");
|
|
||||||
s.AudioFrequency = Clamp(c.GetInt("sound.frequency", 0), 0, 192000);
|
|
||||||
s.AudioDoppler = Math.Clamp(c.GetDouble("sound.doppler", 0.25), 0.0, 10.0);
|
|
||||||
s.AudioLowpass = c.GetBool("sound.efx.lowpass", false);
|
|
||||||
s.AudioAirAbsorption = Math.Clamp(c.GetDouble("sound.efx.airabsorption", 0.0), 0.0, 10.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// A key the file lacks is written only when the value differs from the simulator's default, so
|
|
||||||
// saving with these left alone adds nothing an older simulator would not know.
|
|
||||||
private static void WriteAudioDevice(ConfigFile c, SimulatorSettings s)
|
|
||||||
{
|
|
||||||
SetName(c, "sound.openal.renderer", s.AudioDevice);
|
|
||||||
SetUnlessDefault(c, "sound.outputmode", s.AudioOutputMode, "auto");
|
|
||||||
SetUnlessDefault(c, "sound.hrtf", s.AudioHrtf, "auto");
|
|
||||||
SetName(c, "sound.hrtf.profile", s.AudioHrtfProfile);
|
|
||||||
SetName(c, "sound.resampler", s.AudioResampler);
|
|
||||||
SetUnlessDefault(c, "sound.limiter", s.AudioLimiter, "auto");
|
|
||||||
if (c.Has("sound.frequency") || s.AudioFrequency != 0) c.SetInt("sound.frequency", s.AudioFrequency);
|
|
||||||
if (c.Has("sound.doppler") || Math.Abs(s.AudioDoppler - 0.25) > 1e-9) c.SetDouble("sound.doppler", s.AudioDoppler);
|
|
||||||
if (c.Has("sound.efx.lowpass") || s.AudioLowpass) c.SetBool("sound.efx.lowpass", s.AudioLowpass);
|
|
||||||
if (c.Has("sound.efx.airabsorption") || s.AudioAirAbsorption != 0.0) c.SetDouble("sound.efx.airabsorption", s.AudioAirAbsorption);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void SetUnlessDefault(ConfigFile c, string key, string value, string fallback)
|
|
||||||
{
|
|
||||||
if (c.Has(key) || value != fallback)
|
|
||||||
c.Set(key, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
// An empty name is the library's choice: the line goes, rather than staying with a name in it.
|
|
||||||
private static void SetName(ConfigFile c, string key, string name)
|
|
||||||
{
|
|
||||||
if (name.Length > 0)
|
|
||||||
c.Set(key, name.Contains(' ') ? $"\"{name}\"" : name);
|
|
||||||
else if (c.Has(key))
|
|
||||||
c.Remove(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string Unquoted(string value)
|
|
||||||
{
|
|
||||||
value = value.Trim();
|
|
||||||
return value.Length >= 2 && value[0] == '"' && value[^1] == '"' ? value[1..^1] : value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string FirstTokenOr(ConfigFile c, string key, string fallback)
|
|
||||||
{
|
|
||||||
string token = FirstToken(c, key);
|
|
||||||
return token.Length > 0 ? token : fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string FirstToken(ConfigFile c, string key)
|
private static string FirstToken(ConfigFile c, string key)
|
||||||
{
|
{
|
||||||
var tokens = c.GetTokens(key);
|
var tokens = c.GetTokens(key);
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Controls.Documents;
|
|
||||||
using Avalonia.Layout;
|
using Avalonia.Layout;
|
||||||
using Avalonia.Markup.Xaml.MarkupExtensions;
|
|
||||||
using Avalonia.Media;
|
using Avalonia.Media;
|
||||||
|
|
||||||
namespace StarterNG.Infrastructure;
|
namespace StarterNG.Infrastructure;
|
||||||
@@ -15,34 +13,31 @@ public static class StatsBar
|
|||||||
for (int i = 0; i < fields.Count; i++)
|
for (int i = 0; i < fields.Count; i++)
|
||||||
{
|
{
|
||||||
var (label, value) = fields[i];
|
var (label, value) = fields[i];
|
||||||
host.Children.Add(Figure(label, value, last: i == fields.Count - 1));
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <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 },
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,129 +8,124 @@
|
|||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:views="clr-namespace:StarterNG.Views"
|
xmlns:views="clr-namespace:StarterNG.Views"
|
||||||
xmlns:starterNg="clr-namespace:StarterNG"
|
xmlns:starterNg="clr-namespace:StarterNG"
|
||||||
xmlns:ctl="clr-namespace:StarterNG.Controls"
|
|
||||||
Title="Starter MaSzyna"
|
Title="Starter MaSzyna"
|
||||||
Icon="/Assets/starter.ico"
|
Icon="/Assets/starter.ico"
|
||||||
Width="1010" Height="768" MinWidth="1010" MinHeight="666"
|
Width="1010" Height="768" MinWidth="1010" MinHeight="666"
|
||||||
WindowStartupLocation="CenterScreen">
|
WindowStartupLocation="CenterScreen">
|
||||||
|
|
||||||
<!-- Says what a click changed out of sight; see Announcer. -->
|
<DockPanel LastChildFill="True">
|
||||||
<ctl:Announcer>
|
|
||||||
<DockPanel LastChildFill="True">
|
|
||||||
|
|
||||||
<Border x:Name="TopBar" DockPanel.Dock="Top" TabIndex="0"
|
<Border x:Name="TopBar" DockPanel.Dock="Top"
|
||||||
Background="{StaticResource CarbonPanelBg}"
|
Background="{StaticResource CarbonPanelBg}"
|
||||||
BorderBrush="{StaticResource CarbonBorderLight}"
|
BorderBrush="{StaticResource CarbonBorderLight}"
|
||||||
BorderThickness="0,0,0,1"
|
BorderThickness="0,0,0,1"
|
||||||
PointerPressed="TitleBar_OnPointerPressed">
|
PointerPressed="TitleBar_OnPointerPressed">
|
||||||
<Grid RowDefinitions="44">
|
<Grid RowDefinitions="44">
|
||||||
|
|
||||||
<Grid ColumnDefinitions="Auto,*,Auto" Background="Transparent">
|
<Grid ColumnDefinitions="Auto,*,Auto" Background="Transparent">
|
||||||
|
|
||||||
<StackPanel x:Name="TopBarLeft" Grid.Column="0" AutomationProperties.LandmarkType="Navigation" AutomationProperties.ControlTypeOverride="Group" AutomationProperties.AccessibilityView="Content" Orientation="Horizontal" VerticalAlignment="Stretch">
|
<StackPanel x:Name="TopBarLeft" Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Stretch">
|
||||||
<RadioButton x:Name="NavScenarios" GroupName="nav" Theme="{StaticResource NavTab}"
|
<RadioButton x:Name="NavScenarios" GroupName="nav" Theme="{StaticResource NavTab}"
|
||||||
Tag="scenarios" IsChecked="True"
|
Tag="scenarios" IsChecked="True"
|
||||||
IsCheckedChanged="Nav_OnCheckedChanged"
|
IsCheckedChanged="Nav_OnCheckedChanged"
|
||||||
Content="{Binding [NavScenarios], Source={x:Static starterNg:App.Loc}}" />
|
Content="{Binding [NavScenarios], Source={x:Static starterNg:App.Loc}}" />
|
||||||
<RadioButton x:Name="NavDepot" GroupName="nav" Theme="{StaticResource NavTab}"
|
<RadioButton x:Name="NavDepot" GroupName="nav" Theme="{StaticResource NavTab}"
|
||||||
Tag="depot"
|
Tag="depot"
|
||||||
IsCheckedChanged="Nav_OnCheckedChanged"
|
IsCheckedChanged="Nav_OnCheckedChanged"
|
||||||
Content="{Binding [NavDepot], Source={x:Static starterNg:App.Loc}}" />
|
Content="{Binding [NavDepot], Source={x:Static starterNg:App.Loc}}" />
|
||||||
<RadioButton x:Name="NavSettings" GroupName="nav" Theme="{StaticResource NavTab}"
|
<RadioButton x:Name="NavSettings" GroupName="nav" Theme="{StaticResource NavTab}"
|
||||||
Tag="settings"
|
Tag="settings"
|
||||||
IsCheckedChanged="Nav_OnCheckedChanged"
|
IsCheckedChanged="Nav_OnCheckedChanged"
|
||||||
Content="{Binding [NavSettings], Source={x:Static starterNg:App.Loc}}" />
|
Content="{Binding [NavSettings], Source={x:Static starterNg:App.Loc}}" />
|
||||||
<Button Classes="Basic" Click="openLastLogClick" Width="48" Cursor="Hand"
|
<Button Classes="Basic" Click="openLastLogClick" Width="48" Cursor="Hand"
|
||||||
HorizontalContentAlignment="Center"
|
HorizontalContentAlignment="Center"
|
||||||
ToolTip.Tip="{Binding [ShowLatestLogTooltip], Source={x:Static starterNg:App.Loc}}">
|
ToolTip.Tip="{Binding [ShowLatestLogTooltip], Source={x:Static starterNg:App.Loc}}">
|
||||||
<materialIcons:MaterialIcon Kind="FileDocument" Height="16" Width="16" />
|
<materialIcons:MaterialIcon Kind="FileDocument" Height="16" Width="16" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button Classes="Basic" Click="openHaslerTapesClick" Width="48" Cursor="Hand"
|
<Button Classes="Basic" Click="openHaslerTapesClick" Width="48" Cursor="Hand"
|
||||||
HorizontalContentAlignment="Center"
|
HorizontalContentAlignment="Center"
|
||||||
ToolTip.Tip="{Binding [HaslerTapesTooltip], Source={x:Static starterNg:App.Loc}}">
|
ToolTip.Tip="{Binding [HaslerTapesTooltip], Source={x:Static starterNg:App.Loc}}">
|
||||||
<materialIcons:MaterialIcon Kind="ChartLine" Height="16" Width="16" />
|
<materialIcons:MaterialIcon Kind="ChartLine" Height="16" Width="16" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button x:Name="HelpButton" Classes="Basic" Width="48" Cursor="Hand"
|
<Button x:Name="HelpButton" Classes="Basic" Width="48" Cursor="Hand"
|
||||||
ToolTip.Tip="{Binding [Help], Source={x:Static starterNg:App.Loc}}"
|
ToolTip.Tip="{Binding [Help], Source={x:Static starterNg:App.Loc}}"
|
||||||
Click="HelpButton_OnClick"
|
Click="HelpButton_OnClick"
|
||||||
Content="?" FontWeight="Bold" FontSize="16"
|
Content="?" FontWeight="Bold" FontSize="16"
|
||||||
HorizontalContentAlignment="Center" />
|
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>
|
</StackPanel>
|
||||||
|
|
||||||
<StackPanel x:Name="TopBarRight" Grid.Column="2" Orientation="Horizontal"
|
<ComboBox x:Name="LangCombo" Width="96" VerticalAlignment="Center"
|
||||||
VerticalAlignment="Center" Margin="0,0,3,0" Spacing="0">
|
SelectionChanged="LangCombo_OnSelectionChanged" />
|
||||||
<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>
|
|
||||||
|
|
||||||
<ComboBox x:Name="LangCombo" Width="96" VerticalAlignment="Center"
|
<Button Classes="Basic" Cursor="Hand" Tag="https://discord.gg/eu07" Click="linkClick"
|
||||||
AutomationProperties.Name="{Binding [Language], Source={x:Static starterNg:App.Loc}}"
|
ToolTip.Tip="Discord">
|
||||||
SelectionChanged="LangCombo_OnSelectionChanged" />
|
<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 Classes="Basic" Cursor="Hand" Tag="https://discord.gg/eu07" Click="linkClick"
|
<Button x:Name="LogoLink" Classes="Basic" Cursor="Hand" Tag="http://eu07.pl/" Click="linkClick"
|
||||||
ToolTip.Tip="Discord">
|
Padding="6,0" Margin="4,0,0,0"
|
||||||
<PathIcon Data="{StaticResource DiscordLogo}" Height="12" />
|
ToolTip.Tip="eu07.pl">
|
||||||
</Button>
|
<Image Source="/Assets/Logo/maszyna_white.png" Height="26" />
|
||||||
<Button Classes="Basic" Cursor="Hand" Tag="http://www.facebook.com/MaSzynaeu07pl" Click="linkClick"
|
</Button>
|
||||||
ToolTip.Tip="Facebook">
|
</StackPanel>
|
||||||
<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>
|
</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>
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
<!-- Scrolls only below the size the pages are laid out for; see KeepPagesUsable. -->
|
<!-- The other ways to start - without saving, free fly - were only under the
|
||||||
<ScrollViewer x:Name="PageScroll" AutomationProperties.LandmarkType="Main" AutomationProperties.AccessibilityView="Content" Margin="3,3,3,0" TabIndex="1"
|
right button; the arrow beside it says they exist. The editor is not one
|
||||||
HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled">
|
of them: it opens the scenery itself, so it has a button of its own. -->
|
||||||
<Panel x:Name="PageHost">
|
<Grid DockPanel.Dock="Bottom" ColumnDefinitions="*,Auto,Auto,Auto" ColumnSpacing="4" Margin="3">
|
||||||
<views:Scenarios x:Name="ScenariosView" />
|
<Button Name="startButton" Classes="Start" Height="42"
|
||||||
<views:Depot x:Name="DepotView" IsVisible="False" />
|
TabIndex="9"
|
||||||
<views:Settings x:Name="SettingsView" IsVisible="False" />
|
Click="StartButton_OnClick"
|
||||||
</Panel>
|
Content="{Binding [Start], Source={x:Static starterNg:App.Loc}}" />
|
||||||
</ScrollViewer>
|
<Button Name="startMoreButton" Grid.Column="1" Classes="Start" Width="36" Height="42"
|
||||||
</DockPanel>
|
TabIndex="10" Cursor="Hand"
|
||||||
</ctl:Announcer>
|
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>
|
||||||
</Window>
|
</Window>
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ using Avalonia.Layout;
|
|||||||
using Avalonia.Threading;
|
using Avalonia.Threading;
|
||||||
using Avalonia.VisualTree;
|
using Avalonia.VisualTree;
|
||||||
using StarterNG.Classes;
|
using StarterNG.Classes;
|
||||||
using StarterNG.Controls;
|
|
||||||
using StarterNG.Infrastructure;
|
using StarterNG.Infrastructure;
|
||||||
using StarterNG.Views;
|
using StarterNG.Views;
|
||||||
using StarterNG.Application;
|
using StarterNG.Application;
|
||||||
@@ -40,9 +39,8 @@ public partial class MainWindow : Window
|
|||||||
private DateTime _openedUtc = DateTime.UtcNow;
|
private DateTime _openedUtc = DateTime.UtcNow;
|
||||||
private DateTime _startedUtc = DateTime.MinValue;
|
private DateTime _startedUtc = DateTime.MinValue;
|
||||||
private bool _starting;
|
private bool _starting;
|
||||||
// Scenery files: looked at when they change, on coming back to the window or from the
|
private bool _lookingAtSceneryFiles;
|
||||||
// simulator, and now and then anyway.
|
private readonly DispatcherTimer _sceneryFilesTimer = new() { Interval = TimeSpan.FromSeconds(2) };
|
||||||
private readonly FolderLooks _sceneryLooks;
|
|
||||||
|
|
||||||
public MainWindow()
|
public MainWindow()
|
||||||
{
|
{
|
||||||
@@ -100,7 +98,6 @@ public partial class MainWindow : Window
|
|||||||
// Tunnelling: the shortcuts are checked before any view sees the key, which is
|
// 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.
|
// why OnShortcutKey has to be careful about text entry and key capture.
|
||||||
AddHandler(KeyDownEvent, OnShortcutKey, RoutingStrategies.Tunnel);
|
AddHandler(KeyDownEvent, OnShortcutKey, RoutingStrategies.Tunnel);
|
||||||
AddHandler(KeyDownEvent, OnTabWithNothingFocused, RoutingStrategies.Tunnel);
|
|
||||||
|
|
||||||
AppServices.Current.State.Changed += UpdateStartButton;
|
AppServices.Current.State.Changed += UpdateStartButton;
|
||||||
Opened += (_, _) =>
|
Opened += (_, _) =>
|
||||||
@@ -108,29 +105,24 @@ public partial class MainWindow : Window
|
|||||||
|
|
||||||
_openedUtc = DateTime.UtcNow;
|
_openedUtc = DateTime.UtcNow;
|
||||||
UpdateStartButton();
|
UpdateStartButton();
|
||||||
|
_sceneryFilesTimer.Start();
|
||||||
FollowLastRun();
|
FollowLastRun();
|
||||||
};
|
};
|
||||||
Activated += (_, _) =>
|
Activated += (_, _) => CheckExternalSettings();
|
||||||
{
|
_sceneryFilesTimer.Tick += async (_, _) => await LookAtSceneryFilesAsync();
|
||||||
CheckExternalSettings();
|
Closed += (_, _) => _sceneryFilesTimer.Stop();
|
||||||
// Back from a build or a download: a new simulator is on the list already.
|
|
||||||
if (SettingsView.IsVisible)
|
|
||||||
SettingsView.RefreshExecutables();
|
|
||||||
};
|
|
||||||
// After the handlers above: back at the window, the settings are checked first.
|
|
||||||
_sceneryLooks = new FolderLooks(this, () => AppServices.Current.Paths.Scenery, LookAtSceneryFilesAsync);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Scenery files changed outside the starter are picked up without a reload. Not
|
/// Scenery files changed outside the starter are picked up without a reload. Not
|
||||||
/// with the simulator running: it is left in peace, and what it changes comes in after it.
|
/// with the simulator running: it is left in peace, and what it changes comes in after it.
|
||||||
/// Run through <see cref="_sceneryLooks"/>, one look at a time.
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task LookAtSceneryFilesAsync()
|
private async Task LookAtSceneryFilesAsync()
|
||||||
{
|
{
|
||||||
if (AppServices.Current.State.SimulatorRunning || !IsVisible || WindowState == WindowState.Minimized)
|
if (_lookingAtSceneryFiles || AppServices.Current.State.SimulatorRunning || !IsVisible || WindowState == WindowState.Minimized)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
_lookingAtSceneryFiles = true;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var services = AppServices.Current;
|
var services = AppServices.Current;
|
||||||
@@ -146,6 +138,10 @@ public partial class MainWindow : Window
|
|||||||
{
|
{
|
||||||
Diagnostics.Log("Following the scenery files", ex);
|
Diagnostics.Log("Following the scenery files", ex);
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_lookingAtSceneryFiles = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -241,17 +237,6 @@ public partial class MainWindow : Window
|
|||||||
win.ShowDialog(this);
|
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)
|
private void OnShortcutKey(object? sender, KeyEventArgs e)
|
||||||
{
|
{
|
||||||
// A cab-control binding in Settings is waiting for this very keypress.
|
// A cab-control binding in Settings is waiting for this very keypress.
|
||||||
@@ -523,34 +508,11 @@ public partial class MainWindow : Window
|
|||||||
private const string SimulatorBuildGuide = "https://github.com/MaSzyna-EU07/maszyna#getting-started";
|
private const string SimulatorBuildGuide = "https://github.com/MaSzyna-EU07/maszyna#getting-started";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Tells a user whose processor lacks AVX2 that the simulator that would start will
|
/// Tells a user whose processor lacks AVX2 that the published simulator will
|
||||||
/// not run. With a build without AVX2 in the folder, chosen away from by hand, the
|
/// not run, and where the instructions for a build of their own are.
|
||||||
/// 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>
|
/// </summary>
|
||||||
public async Task ShowCpuNoticeAsync(string executable)
|
public async Task ShowCpuNoticeAsync()
|
||||||
{
|
{
|
||||||
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(
|
var (open, silence) = await MessageBox.ShowNotice(
|
||||||
this, string.Format(App.Loc["CpuNoAvx2"], SimulatorBuildGuide), App.Loc["CpuNoAvx2Title"],
|
this, string.Format(App.Loc["CpuNoAvx2"], SimulatorBuildGuide), App.Loc["CpuNoAvx2Title"],
|
||||||
App.Loc["CpuNoAvx2Open"], App.Loc["DontShowAgain"]);
|
App.Loc["CpuNoAvx2Open"], App.Loc["DontShowAgain"]);
|
||||||
@@ -648,29 +610,6 @@ public partial class MainWindow : Window
|
|||||||
App.Loc["StartNoStaffTitle"], MessageBoxButtons.YesNo))
|
App.Loc["StartNoStaffTitle"], MessageBoxButtons.YesNo))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// edits on the settings page not saved: saved, or let go - kept, the starter would write them when it
|
|
||||||
// closes, perhaps while the simulator reads the file
|
|
||||||
if (saveSettings && SettingsView.HasUnsavedChanges)
|
|
||||||
{
|
|
||||||
var save = await MessageBox.Choose(this, App.Loc["StartUnsavedMessage"], App.Loc["UnsavedChanges"],
|
|
||||||
App.Loc["StartUnsavedSave"], App.Loc["StartUnsavedWithout"]);
|
|
||||||
if (save is null)
|
|
||||||
return;
|
|
||||||
if (save == false)
|
|
||||||
SettingsView.DiscardEdits();
|
|
||||||
else
|
|
||||||
{
|
|
||||||
SettingsView.Save();
|
|
||||||
// eu07.ini or the keys' file not written: still there to be saved
|
|
||||||
if (SettingsView.HasUnsavedChanges)
|
|
||||||
{
|
|
||||||
await MessageBox.Show(this, App.Loc["SettingsNotSaved"], App.Loc["UnsavedChanges"],
|
|
||||||
MessageBoxButtons.Ok);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
LoadingScreen.Prepare(trainset?.Logo, Path.GetFileNameWithoutExtension(scenery.Path));
|
LoadingScreen.Prepare(trainset?.Logo, Path.GetFileNameWithoutExtension(scenery.Path));
|
||||||
|
|
||||||
await FollowStartAsync(() => AppServices.Current.StartSimulation.Execute(freeFly, saveSettings));
|
await FollowStartAsync(() => AppServices.Current.StartSimulation.Execute(freeFly, saveSettings));
|
||||||
@@ -761,8 +700,6 @@ public partial class MainWindow : Window
|
|||||||
FollowLastRun();
|
FollowLastRun();
|
||||||
RestoreFromSimulator();
|
RestoreFromSimulator();
|
||||||
ReportIfCrashed(simulator, executable, started);
|
ReportIfCrashed(simulator, executable, started);
|
||||||
// What the simulator or its editor wrote while it ran comes in now.
|
|
||||||
_ = _sceneryLooks.LookAsync();
|
|
||||||
}), TaskScheduler.Default);
|
}), TaskScheduler.Default);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -772,8 +709,7 @@ public partial class MainWindow : Window
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private static void FollowLastRun()
|
private static void FollowLastRun()
|
||||||
{
|
{
|
||||||
var settings = AppServices.Current.Settings;
|
if (AppServices.Current.Settings.PhysicsLog)
|
||||||
if (settings.PhysicsLog || settings.BlackBox || settings.PhysicsLogTrains)
|
|
||||||
_ = Task.Run(AppServices.Current.Tapes.FollowLastRun);
|
_ = Task.Run(AppServices.Current.Tapes.FollowLastRun);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,22 +10,12 @@ namespace StarterNG;
|
|||||||
static class Program
|
static class Program
|
||||||
{
|
{
|
||||||
|
|
||||||
private static bool _softwareRender;
|
|
||||||
|
|
||||||
[STAThread]
|
[STAThread]
|
||||||
public static void Main(string[] args)
|
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,
|
// Composition root first: everything below, including the crash handlers,
|
||||||
// resolves its collaborators from this graph.
|
// resolves its collaborators from this graph.
|
||||||
AppServices.Initialize();
|
AppServices.Initialize();
|
||||||
if (graphics?.Note is { } note)
|
|
||||||
Diagnostics.Log(note);
|
|
||||||
|
|
||||||
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
|
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
|
||||||
{
|
{
|
||||||
@@ -73,13 +63,9 @@ static class Program
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) =>
|
|
||||||
_softwareRender ? SoftwareRender.ApplyTo(builder) : builder;
|
|
||||||
|
|
||||||
public static AppBuilder BuildAvaloniaApp()
|
public static AppBuilder BuildAvaloniaApp()
|
||||||
=> AppBuilder.Configure<App>()
|
=> AppBuilder.Configure<App>()
|
||||||
.UsePlatformDetect()
|
.UsePlatformDetect()
|
||||||
.WithSoftwareRenderIfAsked()
|
|
||||||
.WithInterFont()
|
.WithInterFont()
|
||||||
.WithDiagnosticsLogging()
|
.WithDiagnosticsLogging()
|
||||||
.AfterSetup(_ => LogUiExceptions());
|
.AfterSetup(_ => LogUiExceptions());
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:starterNg="clr-namespace:StarterNG"
|
xmlns:starterNg="clr-namespace:StarterNG"
|
||||||
x:Class="StarterNG.SplashWindow"
|
x:Class="StarterNG.SplashWindow"
|
||||||
Title="Starter MaSzyna"
|
|
||||||
SystemDecorations="None"
|
SystemDecorations="None"
|
||||||
CanResize="False"
|
CanResize="False"
|
||||||
ShowInTaskbar="True"
|
ShowInTaskbar="True"
|
||||||
@@ -19,7 +18,6 @@
|
|||||||
TextTrimming="CharacterEllipsis"
|
TextTrimming="CharacterEllipsis"
|
||||||
Text="{Binding [LoadingVehicles], Source={x:Static starterNg:App.Loc}}" />
|
Text="{Binding [LoadingVehicles], Source={x:Static starterNg:App.Loc}}" />
|
||||||
<ProgressBar x:Name="progressBar"
|
<ProgressBar x:Name="progressBar"
|
||||||
AutomationProperties.Name="{Binding #statusText.Text}"
|
|
||||||
Minimum="0" Maximum="1" Value="0" Height="6" />
|
Minimum="0" Maximum="1" Value="0" Height="6" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Border>
|
</Border>
|
||||||
|
|||||||
@@ -6,8 +6,6 @@
|
|||||||
<IsAotCompatible>true</IsAotCompatible>
|
<IsAotCompatible>true</IsAotCompatible>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<!-- function pointers into the OpenAL library of the simulator (Infrastructure/OpenAlProbe.cs) -->
|
|
||||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
|
||||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
<ApplicationIcon>Assets\starter.ico</ApplicationIcon>
|
<ApplicationIcon>Assets\starter.ico</ApplicationIcon>
|
||||||
@@ -45,10 +43,6 @@
|
|||||||
<ProjectReference Include="..\Eu07.BlackBox.Views\Eu07.BlackBox.Views.csproj" />
|
<ProjectReference Include="..\Eu07.BlackBox.Views\Eu07.BlackBox.Views.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<InternalsVisibleTo Include="StarterNG.Tests" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="Assets\Logo\" />
|
<Folder Include="Assets\Logo\" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -17,8 +17,6 @@
|
|||||||
|
|
||||||
<SolidColorBrush x:Key="CarbonInputBg" Color="#262C31" />
|
<SolidColorBrush x:Key="CarbonInputBg" Color="#262C31" />
|
||||||
<SolidColorBrush x:Key="CarbonBorderLight" Color="#3A424A" />
|
<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="CarbonBorderDark" Color="#0E0F12" />
|
||||||
<SolidColorBrush x:Key="CarbonFg" Color="#E6E8EA" />
|
<SolidColorBrush x:Key="CarbonFg" Color="#E6E8EA" />
|
||||||
<SolidColorBrush x:Key="CarbonFgDim" Color="#9098A0" />
|
<SolidColorBrush x:Key="CarbonFgDim" Color="#9098A0" />
|
||||||
@@ -79,7 +77,7 @@
|
|||||||
Height="{StaticResource CarbonCheckSize}"
|
Height="{StaticResource CarbonCheckSize}"
|
||||||
VerticalAlignment="Center"
|
VerticalAlignment="Center"
|
||||||
Background="{StaticResource CarbonInputBg}"
|
Background="{StaticResource CarbonInputBg}"
|
||||||
BorderBrush="{StaticResource CarbonInputBorder}"
|
BorderBrush="{StaticResource CarbonBorderLight}"
|
||||||
BorderThickness="1" CornerRadius="2">
|
BorderThickness="1" CornerRadius="2">
|
||||||
<Path Name="glyph" Margin="3" Stretch="Uniform"
|
<Path Name="glyph" Margin="3" Stretch="Uniform"
|
||||||
Data="M 0,4 L 3,7 L 9,0"
|
Data="M 0,4 L 3,7 L 9,0"
|
||||||
@@ -141,7 +139,7 @@
|
|||||||
the same shape and height as a combo box. -->
|
the same shape and height as a combo box. -->
|
||||||
<ControlTheme x:Key="{x:Type ButtonSpinner}" TargetType="ButtonSpinner">
|
<ControlTheme x:Key="{x:Type ButtonSpinner}" TargetType="ButtonSpinner">
|
||||||
<Setter Property="Background" Value="{StaticResource CarbonInputBg}" />
|
<Setter Property="Background" Value="{StaticResource CarbonInputBg}" />
|
||||||
<Setter Property="BorderBrush" Value="{StaticResource CarbonInputBorder}" />
|
<Setter Property="BorderBrush" Value="{StaticResource CarbonBorderLight}" />
|
||||||
<Setter Property="BorderThickness" Value="1" />
|
<Setter Property="BorderThickness" Value="1" />
|
||||||
<Setter Property="CornerRadius" Value="2" />
|
<Setter Property="CornerRadius" Value="2" />
|
||||||
<Setter Property="MinHeight" Value="{StaticResource CarbonControlHeight}" />
|
<Setter Property="MinHeight" Value="{StaticResource CarbonControlHeight}" />
|
||||||
@@ -189,7 +187,7 @@
|
|||||||
MinHeight="{StaticResource CarbonControlHeight}"
|
MinHeight="{StaticResource CarbonControlHeight}"
|
||||||
Padding="0"
|
Padding="0"
|
||||||
BorderThickness="1"
|
BorderThickness="1"
|
||||||
BorderBrush="{StaticResource CarbonInputBorder}"
|
BorderBrush="{StaticResource CarbonBorderLight}"
|
||||||
Background="{StaticResource CarbonInputBg}"
|
Background="{StaticResource CarbonInputBg}"
|
||||||
CornerRadius="2"
|
CornerRadius="2"
|
||||||
HorizontalAlignment="Stretch"
|
HorizontalAlignment="Stretch"
|
||||||
@@ -306,14 +304,12 @@
|
|||||||
<Setter Property="FontSize" Value="12" />
|
<Setter Property="FontSize" Value="12" />
|
||||||
<Setter Property="Padding" Value="8,1" />
|
<Setter Property="Padding" Value="8,1" />
|
||||||
<Setter Property="CornerRadius" Value="2" />
|
<Setter Property="CornerRadius" Value="2" />
|
||||||
<Setter Property="BorderBrush" Value="{StaticResource CarbonInputBorder}" />
|
|
||||||
</Style>
|
</Style>
|
||||||
<Style Selector="TextBox">
|
<Style Selector="TextBox">
|
||||||
<Setter Property="MinHeight" Value="{StaticResource CarbonControlHeight}" />
|
<Setter Property="MinHeight" Value="{StaticResource CarbonControlHeight}" />
|
||||||
<Setter Property="FontSize" Value="12" />
|
<Setter Property="FontSize" Value="12" />
|
||||||
<Setter Property="Padding" Value="6,1" />
|
<Setter Property="Padding" Value="6,1" />
|
||||||
<Setter Property="CornerRadius" Value="2" />
|
<Setter Property="CornerRadius" Value="2" />
|
||||||
<Setter Property="BorderBrush" Value="{StaticResource CarbonInputBorder}" />
|
|
||||||
</Style>
|
</Style>
|
||||||
<!-- Fluent gives the spinner and the check controls a 32 px floor of their own,
|
<!-- 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. -->
|
inside the template, so setting MinHeight on the control alone does nothing. -->
|
||||||
|
|||||||
@@ -61,10 +61,8 @@
|
|||||||
with no label hides PART_Label, and without this the
|
with no label hides PART_Label, and without this the
|
||||||
column would collapse onto the key and every
|
column would collapse onto the key and every
|
||||||
explanation would start at a different place again. -->
|
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"
|
<SelectableTextBlock Name="PART_ConfigKey"
|
||||||
Grid.Row="1" Grid.Column="0" IsTabStop="False"
|
Grid.Row="1" Grid.Column="0"
|
||||||
Text="{TemplateBinding ConfigKey}"
|
Text="{TemplateBinding ConfigKey}"
|
||||||
FontFamily="Consolas, DejaVu Sans Mono, Liberation Mono, Menlo, Courier New"
|
FontFamily="Consolas, DejaVu Sans Mono, Liberation Mono, Menlo, Courier New"
|
||||||
FontSize="11"
|
FontSize="11"
|
||||||
|
|||||||
@@ -82,8 +82,6 @@ public static class AboutWindow
|
|||||||
};
|
};
|
||||||
close.Classes.Add("Accent");
|
close.Classes.Add("Accent");
|
||||||
close.Click += (_, _) => win.Close();
|
close.Click += (_, _) => win.Close();
|
||||||
close.IsDefault = true;
|
|
||||||
close.IsCancel = true;
|
|
||||||
|
|
||||||
var footer = new StackPanel
|
var footer = new StackPanel
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -81,12 +81,11 @@
|
|||||||
PointerWheelChanged="Combo_OnPointerWheel"
|
PointerWheelChanged="Combo_OnPointerWheel"
|
||||||
SelectionChanged="ClassCombo_OnSelectionChanged" />
|
SelectionChanged="ClassCombo_OnSelectionChanged" />
|
||||||
|
|
||||||
<TextBox Name="searchBox" AutomationProperties.LandmarkType="Search" Grid.Row="3" Margin="0,0,0,6"
|
<TextBox Name="searchBox" Grid.Row="3" Margin="0,0,0,6"
|
||||||
PlaceholderText="{Binding [SearchAllVehicles], Source={x:Static starterNg:App.Loc}}"
|
PlaceholderText="{Binding [SearchAllVehicles], Source={x:Static starterNg:App.Loc}}"
|
||||||
TextChanged="SearchBox_OnTextChanged" />
|
TextChanged="SearchBox_OnTextChanged" />
|
||||||
|
|
||||||
<ListBox Name="vehicleListBox" Grid.Row="4" Classes="Compact" MinHeight="60"
|
<ListBox Name="vehicleListBox" Grid.Row="4" Classes="Compact" MinHeight="60"
|
||||||
AutomationProperties.Name="{Binding [Vehicles], Source={x:Static starterNg:App.Loc}}"
|
|
||||||
SelectionChanged="VehicleListBox_OnSelectionChanged"
|
SelectionChanged="VehicleListBox_OnSelectionChanged"
|
||||||
DoubleTapped="VehicleListBox_OnDoubleTapped"
|
DoubleTapped="VehicleListBox_OnDoubleTapped"
|
||||||
PointerPressed="VehicleListBox_OnPointerPressed" />
|
PointerPressed="VehicleListBox_OnPointerPressed" />
|
||||||
@@ -127,8 +126,7 @@
|
|||||||
BorderThickness="1" CornerRadius="2" Padding="6">
|
BorderThickness="1" CornerRadius="2" Padding="6">
|
||||||
<!-- The tab picks what the consist strip edits: a consist of the scenery,
|
<!-- The tab picks what the consist strip edits: a consist of the scenery,
|
||||||
or a consist kept in the warehouse. -->
|
or a consist kept in the warehouse. -->
|
||||||
<TabControl Name="consistSourceTabs" AutomationProperties.Name="{Binding [DepotConsistSources], Source={x:Static starterNg:App.Loc}}"
|
<TabControl Name="consistSourceTabs" SelectionChanged="ConsistSourceTabs_OnSelectionChanged">
|
||||||
SelectionChanged="ConsistSourceTabs_OnSelectionChanged">
|
|
||||||
<TabItem Name="sceneryConsistsTab"
|
<TabItem Name="sceneryConsistsTab"
|
||||||
Header="{Binding [SceneryConsists], Source={x:Static starterNg:App.Loc}}">
|
Header="{Binding [SceneryConsists], Source={x:Static starterNg:App.Loc}}">
|
||||||
<DockPanel LastChildFill="True">
|
<DockPanel LastChildFill="True">
|
||||||
@@ -147,7 +145,6 @@
|
|||||||
Content="{Binding [ShowAiVehicles], Source={x:Static starterNg:App.Loc}}" />
|
Content="{Binding [ShowAiVehicles], Source={x:Static starterNg:App.Loc}}" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
<ListBox Name="sceneryConsistList" Classes="Compact"
|
<ListBox Name="sceneryConsistList" Classes="Compact"
|
||||||
AutomationProperties.Name="{Binding [SceneryConsists], Source={x:Static starterNg:App.Loc}}"
|
|
||||||
SelectionChanged="SceneryConsistList_OnSelectionChanged"
|
SelectionChanged="SceneryConsistList_OnSelectionChanged"
|
||||||
KeyDown="SceneryConsistList_OnKeyDown" />
|
KeyDown="SceneryConsistList_OnKeyDown" />
|
||||||
</DockPanel>
|
</DockPanel>
|
||||||
@@ -163,8 +160,7 @@
|
|||||||
<TextBlock DockPanel.Dock="Bottom" Margin="2,6,0,0" FontSize="12" Opacity="0.6"
|
<TextBlock DockPanel.Dock="Bottom" Margin="2,6,0,0" FontSize="12" Opacity="0.6"
|
||||||
TextWrapping="Wrap"
|
TextWrapping="Wrap"
|
||||||
Text="{Binding [WarehouseEditHint], Source={x:Static starterNg:App.Loc}}" />
|
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>
|
</DockPanel>
|
||||||
</TabItem>
|
</TabItem>
|
||||||
</TabControl>
|
</TabControl>
|
||||||
@@ -199,7 +195,7 @@
|
|||||||
Background="{StaticResource CarbonPanelBg}"
|
Background="{StaticResource CarbonPanelBg}"
|
||||||
BorderBrush="{StaticResource CarbonBorderLight}"
|
BorderBrush="{StaticResource CarbonBorderLight}"
|
||||||
BorderThickness="1" CornerRadius="2" Padding="6">
|
BorderThickness="1" CornerRadius="2" Padding="6">
|
||||||
<TabControl AutomationProperties.Name="{Binding [DepotVehicleInfo], Source={x:Static starterNg:App.Loc}}">
|
<TabControl>
|
||||||
<TabItem Header="{Binding [GeneralInfo], Source={x:Static starterNg:App.Loc}}">
|
<TabItem Header="{Binding [GeneralInfo], Source={x:Static starterNg:App.Loc}}">
|
||||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||||
<StackPanel Name="generalPanel" Margin="4" Grid.IsSharedSizeScope="True" />
|
<StackPanel Name="generalPanel" Margin="4" Grid.IsSharedSizeScope="True" />
|
||||||
@@ -217,7 +213,7 @@
|
|||||||
Background="{StaticResource CarbonPanelBg}"
|
Background="{StaticResource CarbonPanelBg}"
|
||||||
BorderBrush="{StaticResource CarbonBorderLight}"
|
BorderBrush="{StaticResource CarbonBorderLight}"
|
||||||
BorderThickness="1" CornerRadius="2" Padding="6">
|
BorderThickness="1" CornerRadius="2" Padding="6">
|
||||||
<TabControl AutomationProperties.Name="{Binding [DepotVehicleEdit], Source={x:Static starterNg:App.Loc}}">
|
<TabControl>
|
||||||
<TabItem Header="{Binding [Coupling], 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
|
<!-- The coupling grid now uses the full tab width. The two
|
||||||
actions sit underneath, so they do not steal horizontal
|
actions sit underneath, so they do not steal horizontal
|
||||||
@@ -322,12 +318,7 @@
|
|||||||
<Panel>
|
<Panel>
|
||||||
<!-- Tab reaches the strip once and lands on the selected
|
<!-- Tab reaches the strip once and lands on the selected
|
||||||
card; the arrow keys walk it from there. -->
|
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"
|
<StackPanel Name="consistStack" Orientation="Horizontal"
|
||||||
AutomationProperties.Name="{Binding [Consist], Source={x:Static starterNg:App.Loc}}"
|
|
||||||
AutomationProperties.ControlTypeOverride="List"
|
|
||||||
AutomationProperties.AccessibilityView="Content"
|
|
||||||
KeyboardNavigation.TabNavigation="Once"
|
KeyboardNavigation.TabNavigation="Once"
|
||||||
VerticalAlignment="Center" Spacing="0" />
|
VerticalAlignment="Center" Spacing="0" />
|
||||||
<Canvas Name="consistOverlay" IsHitTestVisible="False" />
|
<Canvas Name="consistOverlay" IsHitTestVisible="False" />
|
||||||
|
|||||||
@@ -369,41 +369,6 @@ public partial class Depot : UserControl
|
|||||||
// The cards are thrown away and rebuilt on every change, so a keyboard-driven
|
// 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.
|
// edit has to be handed its card back or focus escapes the strip.
|
||||||
_cards.FocusSelectedCard(onlyIfRequested: true);
|
_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()
|
private void WriteBackToScenery()
|
||||||
@@ -527,11 +492,11 @@ public partial class Depot : UserControl
|
|||||||
redoButton.IsEnabled = editing is not null && _history.CanRedo(editing);
|
redoButton.IsEnabled = editing is not null && _history.CanRedo(editing);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Undo() => Restore(_history.Undo, "ConsistSaidUndone");
|
public void Undo() => Restore(_history.Undo);
|
||||||
|
|
||||||
public void Redo() => Restore(_history.Redo, "ConsistSaidRedone");
|
public void Redo() => Restore(_history.Redo);
|
||||||
|
|
||||||
private void Restore(Func<Trainset, int, ConsistHistory.State?> step, string word)
|
private void Restore(Func<Trainset, int, ConsistHistory.State?> step)
|
||||||
{
|
{
|
||||||
if (_consist.EditingTrainset is not { } trainset ||
|
if (_consist.EditingTrainset is not { } trainset ||
|
||||||
step(trainset, SelectedIndex()) is not { } state)
|
step(trainset, SelectedIndex()) is not { } state)
|
||||||
@@ -539,7 +504,6 @@ public partial class Depot : UserControl
|
|||||||
|
|
||||||
trainset.Vehicles = state.Vehicles.ToList();
|
trainset.Vehicles = state.Vehicles.ToList();
|
||||||
_restoring = true;
|
_restoring = true;
|
||||||
_restoreWord = word;
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_consist.LoadFrom(trainset, state.Selected);
|
_consist.LoadFrom(trainset, state.Selected);
|
||||||
@@ -547,7 +511,6 @@ public partial class Depot : UserControl
|
|||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
_restoring = false;
|
_restoring = false;
|
||||||
_restoreWord = null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -719,8 +682,6 @@ public partial class Depot : UserControl
|
|||||||
Foreground = new SolidColorBrush(Color.Parse("#E0A030"))
|
Foreground = new SolidColorBrush(Color.Parse("#E0A030"))
|
||||||
};
|
};
|
||||||
ToolTip.SetTip(dot, App.Loc["ConsistUnsaved"]);
|
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();
|
var row = new DockPanel();
|
||||||
DockPanel.SetDock(dot, Dock.Left);
|
DockPanel.SetDock(dot, Dock.Left);
|
||||||
row.Children.Add(dot);
|
row.Children.Add(dot);
|
||||||
|
|||||||
@@ -1,102 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
@@ -77,9 +77,6 @@ public sealed class TextureRandomizerDialog
|
|||||||
FontSize = 12
|
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;
|
revDiff.IsCheckedChanged += (_, _) => age.IsEnabled = revDiff.IsChecked == true;
|
||||||
vsYear.IsCheckedChanged += (_, _) => year.IsEnabled = vsYear.IsChecked == true;
|
vsYear.IsCheckedChanged += (_, _) => year.IsEnabled = vsYear.IsChecked == true;
|
||||||
|
|
||||||
@@ -121,8 +118,6 @@ public sealed class TextureRandomizerDialog
|
|||||||
};
|
};
|
||||||
cancel.Classes.Add("Flat");
|
cancel.Classes.Add("Flat");
|
||||||
cancel.Click += (_, _) => win.Close(false);
|
cancel.Click += (_, _) => win.Close(false);
|
||||||
ok.IsDefault = true;
|
|
||||||
cancel.IsCancel = true;
|
|
||||||
|
|
||||||
win.Content = new StackPanel
|
win.Content = new StackPanel
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Automation;
|
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Controls.Templates;
|
using Avalonia.Controls.Templates;
|
||||||
using Avalonia.Input;
|
using Avalonia.Input;
|
||||||
@@ -60,8 +59,6 @@ public sealed class VehicleBrowser
|
|||||||
|
|
||||||
private DispatcherTimer? _searchTimer;
|
private DispatcherTimer? _searchTimer;
|
||||||
|
|
||||||
private readonly SearchResultsTeller _searchResults;
|
|
||||||
|
|
||||||
private Func<string?, bool>? _categoryFilter;
|
private Func<string?, bool>? _categoryFilter;
|
||||||
private string? _classFilter;
|
private string? _classFilter;
|
||||||
|
|
||||||
@@ -84,7 +81,6 @@ public sealed class VehicleBrowser
|
|||||||
|
|
||||||
vehicleListBox.ContextRequested += List_OnContextRequested;
|
vehicleListBox.ContextRequested += List_OnContextRequested;
|
||||||
|
|
||||||
_searchResults = new SearchResultsTeller(searchBox, () => vehicleListBox.ItemCount);
|
|
||||||
_searchTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(220) };
|
_searchTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(220) };
|
||||||
_searchTimer.Tick += (_, _) =>
|
_searchTimer.Tick += (_, _) =>
|
||||||
{
|
{
|
||||||
@@ -342,7 +338,6 @@ public sealed class VehicleBrowser
|
|||||||
|
|
||||||
Selected = null;
|
Selected = null;
|
||||||
miniPreview.Source = null;
|
miniPreview.Source = null;
|
||||||
miniPreview.ClearValue(AutomationProperties.NameProperty);
|
|
||||||
addVehicleButton.IsEnabled = false;
|
addVehicleButton.IsEnabled = false;
|
||||||
|
|
||||||
vehicleListBox.Items.Clear();
|
vehicleListBox.Items.Clear();
|
||||||
@@ -386,12 +381,10 @@ public sealed class VehicleBrowser
|
|||||||
|
|
||||||
public void VehicleListBox_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
public void VehicleListBox_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
||||||
{
|
{
|
||||||
if (vehicleListBox.SelectedItem is ListBoxItem { Tag: VehicleTexture texture } row)
|
if (vehicleListBox.SelectedItem is ListBoxItem { Tag: VehicleTexture texture })
|
||||||
{
|
{
|
||||||
Selected = texture;
|
Selected = texture;
|
||||||
miniPreview.Source = _minis.Get(_db.ResolveMiniName(texture), MiniPreviewHeight);
|
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;
|
addVehicleButton.IsEnabled = true;
|
||||||
SyncCombosTo(texture);
|
SyncCombosTo(texture);
|
||||||
|
|
||||||
@@ -404,7 +397,6 @@ public sealed class VehicleBrowser
|
|||||||
{
|
{
|
||||||
Selected = null;
|
Selected = null;
|
||||||
miniPreview.Source = null;
|
miniPreview.Source = null;
|
||||||
miniPreview.ClearValue(AutomationProperties.NameProperty);
|
|
||||||
addVehicleButton.IsEnabled = false;
|
addVehicleButton.IsEnabled = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -567,7 +559,6 @@ public sealed class VehicleBrowser
|
|||||||
if (_suppress || _searchTimer is null) return;
|
if (_suppress || _searchTimer is null) return;
|
||||||
_searchTimer.Stop();
|
_searchTimer.Stop();
|
||||||
_searchTimer.Start();
|
_searchTimer.Start();
|
||||||
_searchResults.Changed();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void HideArchivalCheck_OnChanged(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
public void HideArchivalCheck_OnChanged(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||||
@@ -587,29 +578,12 @@ public sealed class VehicleBrowser
|
|||||||
var set = _db.ResolveSet(texture);
|
var set = _db.ResolveSet(texture);
|
||||||
var browserTex = set is { Count: > 0 } ? set[0] : texture;
|
var browserTex = set is { Count: > 0 } ? set[0] : texture;
|
||||||
|
|
||||||
KeepingKeyboardFocus(() => WhileSyncing(() =>
|
WhileSyncing(() =>
|
||||||
{
|
{
|
||||||
ApplyFilters(VehicleInfo.CategoryOf(browserTex), VehicleInfo.ClassOf(browserTex));
|
ApplyFilters(VehicleInfo.CategoryOf(browserTex), VehicleInfo.ClassOf(browserTex));
|
||||||
Rebuild();
|
Rebuild();
|
||||||
SelectListEntry(browserTex);
|
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)
|
private void SyncCombosTo(VehicleTexture texture)
|
||||||
@@ -617,7 +591,7 @@ public sealed class VehicleBrowser
|
|||||||
if (_syncingCombos || !ApplyFilters(VehicleInfo.CategoryOf(texture), VehicleInfo.ClassOf(texture)))
|
if (_syncingCombos || !ApplyFilters(VehicleInfo.CategoryOf(texture), VehicleInfo.ClassOf(texture)))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
PostSyncing(() => KeepingKeyboardFocus(() => { Rebuild(); SelectListEntry(texture); }));
|
PostSyncing(() => { Rebuild(); SelectListEntry(texture); });
|
||||||
}
|
}
|
||||||
|
|
||||||
private void WhileSyncing(Action work)
|
private void WhileSyncing(Action work)
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Automation;
|
|
||||||
using Avalonia.Automation.Peers;
|
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Input;
|
using Avalonia.Input;
|
||||||
using Avalonia.Layout;
|
using Avalonia.Layout;
|
||||||
@@ -15,7 +13,6 @@ using Material.Icons.Avalonia;
|
|||||||
using StarterNG.Classes;
|
using StarterNG.Classes;
|
||||||
using StarterNG.Domain;
|
using StarterNG.Domain;
|
||||||
using StarterNG.Domain.Vehicles;
|
using StarterNG.Domain.Vehicles;
|
||||||
using StarterNG.Controls;
|
|
||||||
|
|
||||||
namespace StarterNG.Views;
|
namespace StarterNG.Views;
|
||||||
|
|
||||||
@@ -149,10 +146,6 @@ public sealed class VehicleCards
|
|||||||
Focusable = true
|
Focusable = true
|
||||||
};
|
};
|
||||||
card.Classes.Add("ConsistCard");
|
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.GotFocus += (_, _) => Select(item, null);
|
||||||
card.KeyDown += (_, e) => OnCardKey(card, item, e);
|
card.KeyDown += (_, e) => OnCardKey(card, item, e);
|
||||||
card.PointerPressed += (_, e) =>
|
card.PointerPressed += (_, e) =>
|
||||||
@@ -186,11 +179,6 @@ public sealed class VehicleCards
|
|||||||
return card;
|
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) =>
|
private string CardCaption(ConsistItem item, Dynamic car, int index) =>
|
||||||
TrainsetDisplay.VehicleLabel(car,
|
TrainsetDisplay.VehicleLabel(car,
|
||||||
head: index == 0 && ReferenceEquals(car, Consist.HeadCar(item)) && TrainsetDisplay.IsPowered(car));
|
head: index == 0 && ReferenceEquals(car, Consist.HeadCar(item)) && TrainsetDisplay.IsPowered(car));
|
||||||
@@ -423,22 +411,12 @@ public sealed class VehicleCards
|
|||||||
panel.Children.Add(apply);
|
panel.Children.Add(apply);
|
||||||
|
|
||||||
var flyout = new Flyout { Content = panel, Placement = PlacementMode.Top };
|
var flyout = new Flyout { Content = panel, Placement = PlacementMode.Top };
|
||||||
void Apply()
|
apply.Click += (_, _) =>
|
||||||
{
|
{
|
||||||
_consist.SetWagonNumber(car, (int)(num.Value ?? 0));
|
_consist.SetWagonNumber(car, (int)(num.Value ?? 0));
|
||||||
flyout.Hide();
|
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);
|
flyout.ShowAt(anchor);
|
||||||
num.Focus();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -645,10 +623,6 @@ public sealed class VehicleCards
|
|||||||
|
|
||||||
btn.Content = glyph;
|
btn.Content = glyph;
|
||||||
btn.Foreground = new SolidColorBrush(Color.Parse(color));
|
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>
|
/// <summary>
|
||||||
@@ -694,7 +668,7 @@ public sealed class VehicleCards
|
|||||||
|
|
||||||
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
|
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
|
||||||
foreach (var (type, key) in CrewChoices.All)
|
foreach (var (type, key) in CrewChoices.All)
|
||||||
crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type)));
|
crew.AddItem((item.Driver == type ? "● " : "○ ") + App.Loc[key], () => _consist.SetCrew(item, type));
|
||||||
menu.Items.Add(crew);
|
menu.Items.Add(crew);
|
||||||
|
|
||||||
// The member the panels show, not always the first car of a unit.
|
// The member the panels show, not always the first car of a unit.
|
||||||
|
|||||||
@@ -595,9 +595,6 @@ public sealed class VehicleDetails
|
|||||||
return Row(content: ready);
|
return Row(content: ready);
|
||||||
var why = PanelNote(App.Loc["ConsistReadyOverridden"]);
|
var why = PanelNote(App.Loc["ConsistReadyOverridden"]);
|
||||||
why.Margin = new Thickness(0);
|
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 } });
|
return Row(content: new StackPanel { Spacing = 2, Children = { ready, why } });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user