diff --git a/Eu07.BlackBox.Views/BlackBoxStrings.cs b/Eu07.BlackBox.Views/BlackBoxStrings.cs index c31ad20..87ad6e1 100644 --- a/Eu07.BlackBox.Views/BlackBoxStrings.cs +++ b/Eu07.BlackBox.Views/BlackBoxStrings.cs @@ -24,6 +24,10 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["LiveTip"] = "Reads what the simulator adds to the file every 2 seconds", ["Play"] = "Play", ["Pause"] = "Pause", + ["PlaySpeed"] = "Playback speed", + ["TimelineHelp"] = "The arrows go 10 seconds back or on, with Ctrl a minute, Page Up and Page Down ten minutes, Home and End to the start and the end.", + ["TimetableHelp"] = "The up and down arrows go through the stations, Enter goes to the moment the train was there.", + ["MapHelp"] = "The map of the run. What it shows is also in the events and the timetable, and on the run below it.", ["Follow"] = "Follow the train", ["Fit"] = "Whole map", ["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the black box or the physics logs on.", @@ -181,6 +185,9 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["EventHornMissed"] = "W6: NO HORN", ["EventCab"] = "Cab {0} of {1}", ["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}", ["CabSpeed"] = "Speed", ["CabWheels"] = "wheels {0:0}", @@ -296,6 +303,10 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["LiveTip"] = "Co 2 sekundy doczytuje to, co symulator dopisał do pliku", ["Play"] = "Odtwarzaj", ["Pause"] = "Pauza", + ["PlaySpeed"] = "Prędkość odtwarzania", + ["TimelineHelp"] = "Strzałki przesuwają o 10 sekund, z Ctrl o minutę, Page Up i Page Down o dziesięć minut, Home i End na początek i koniec.", + ["TimetableHelp"] = "Strzałki w górę i w dół przechodzą po stacjach, Enter przenosi do chwili, gdy pociąg tam był.", + ["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.", ["Follow"] = "Śledź pociąg", ["Fit"] = "Cała mapa", ["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną przy włączonej czarnej skrzynce albo logach fizyki.", @@ -453,6 +464,9 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["EventHornMissed"] = "W6: BEZ TRĄBIENIA", ["EventCab"] = "Kabina {0} w {1}", ["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}", ["CabSpeed"] = "Prędkość", ["CabWheels"] = "koła {0:0}", @@ -558,7 +572,11 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["FileFilter"] = "Czarna skrzynka" }; + /// The key of the text of a simulator's command: and its name. + public const string CommandPrefix = "Cmd."; + private readonly Dictionary _texts; + private readonly string _languageCode; public DefaultBlackBoxStrings() : this(CultureInfo.CurrentUICulture) { @@ -571,11 +589,15 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings /// Polish for "pl", English for any other language. public DefaultBlackBoxStrings(string languageCode) { + _languageCode = languageCode; _texts = languageCode == "pl" ? Polish : English; } /// The keys there are texts for, for a translation to give them all. public static IEnumerable Keys => English.Keys; - public string this[string key] => _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key); + /// A key of gives what the command does (). + 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); } diff --git a/Eu07.BlackBox.Views/BlackBoxWindow.cs b/Eu07.BlackBox.Views/BlackBoxWindow.cs index 987a2aa..fdbfd88 100644 --- a/Eu07.BlackBox.Views/BlackBoxWindow.cs +++ b/Eu07.BlackBox.Views/BlackBoxWindow.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; using Avalonia; +using Avalonia.Automation; using Avalonia.Controls; using Avalonia.Layout; using Avalonia.Media; @@ -106,6 +107,13 @@ public sealed class BlackBoxWindow : Window _play.Click += (_, _) => Playing = !Playing; _speed.ItemsSource = Speeds.Select(s => $"×{s.ToString(CultureInfo.InvariantCulture)}").ToArray(); _speed.SelectedIndex = 3; + // What a screen reader calls the parts that have no label of their own on the screen. + AutomationProperties.SetName(_speed, _strings["PlaySpeed"]); + AutomationProperties.SetName(_timeline, _strings["PanelTimeline"]); + AutomationProperties.SetName(_timetable, _strings["TabTimetable"]); + AutomationProperties.SetName(_cab, _strings["Cab"]); + AutomationProperties.SetName(_map, _strings["PanelMap"]); + AutomationProperties.SetHelpText(_map, _strings["MapHelp"]); var titles = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Children = { _title, _subtitle } }; var transport = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { _play, _clock, _speed, _delayText } }; @@ -455,6 +463,7 @@ public sealed class BlackBoxWindow : Window _clock.Text = recording.ClockAt(_time).ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture); _events.ShowTime(_time); ShowReadout(null); + _timeline.Spoken = _readout.Text; ShowDelay(recording); TimeChanged?.Invoke(_time); } diff --git a/Eu07.BlackBox.Views/CabPanel.cs b/Eu07.BlackBox.Views/CabPanel.cs index 741bace..79706ca 100644 --- a/Eu07.BlackBox.Views/CabPanel.cs +++ b/Eu07.BlackBox.Views/CabPanel.cs @@ -3,7 +3,9 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; +using Avalonia.Automation.Peers; using Avalonia.Controls; +using Avalonia.Input; using Avalonia.Media; namespace Eu07.BlackBox.Views; @@ -37,6 +39,36 @@ public sealed class CabPanel : Control { ClipToBounds = true; Height = 696; + // Reached with Tab, where a screen reader reads what the panel shows. + Focusable = true; + } + + // What the panel showed when last drawn, a line a figure, as a screen reader is told it. + private List? _saying; + private string? _said; + + /// What the panel shows, said in words: the figures and the lamps that are lit. + 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(); @@ -63,6 +95,22 @@ public sealed class CabPanel : Control } public override void Render(DrawingContext context) + { + _saying = new List(); + try + { + DrawPanel(context); + } + finally + { + _said = string.Join(". ", _saying); + _saying = null; + } + if (IsFocused) + context.DrawRectangle(null, Palette.FocusPen, new Rect(Bounds.Size).Deflate(1)); + } + + private void DrawPanel(DrawingContext context) { var size = Bounds.Size; double width = size.Width - 2 * Pad, right = size.Width - Pad; @@ -71,28 +119,62 @@ public sealed class CabPanel : Control if (_recording is not { } recording || recording.CabAt(_time) is not { } s || _time - s.Time > 1.5) { context.DrawText(MapView.Text(Strings["CabNoData"], Palette.DimText, 12), new Point(Pad, 40)); + Say(Strings["CabNoData"]); return; } Measure(recording); var culture = CultureInfo.CurrentCulture; - var extra = s.Extra; - // The vehicle at the left; who drives, from which cab, at the right. + DrawHeader(context, recording.Vehicle(s.Vehicle)?.Name ?? "", s, right); + DrawSpeed(context, s, width, right, culture); + DrawControls(context, s, width, right, culture); + double y = DrawBrakes(context, s, width, right, culture); + + // The traction at the left, as fits what drives the vehicle; the lights of both ends of the train at the right. + double half = Pad + width / 2; + double driveTop = y + BrakeRow + 4; + double top = Section(context, Strings["CabSectionDrive"], Pad, driveTop, half - 10); + Section(context, Strings["CabLights"], half + 4, driveTop, right); + DrawDrive(context, s, top, half - 10 - Pad, culture); + DrawLights(context, s, new Rect(half, top, right - half, 0), culture); + + top = DrawDevices(context, s, new Rect(Pad, top + 3 * DriveRow + 6, width, size.Height), culture); + DrawDoors(context, s, top, width, size.Height); + } + + private const double BrakeRow = 17; + + /// The vehicle at the left; who drives, from which cab, at the right. + private void DrawHeader(DrawingContext context, string name, CabSample s, double right) + { + string? end = s.CabEnd == 0 ? null : Strings[s.CabEnd > 0 ? "CabEndFront" : "CabEndRear"]; double chipX = right; - if (s.CabEnd != 0) - chipX -= ChipLeft(context, Strings[s.CabEnd > 0 ? "CabEndFront" : "CabEndRear"], Palette.Text, chipX, 4) + 5; - var (driverText, driverBrush) = !s.InCab ? (Strings["CabOutside"], Palette.DimText) - : s.Driving == Driver.Ai ? (Strings["CabDriverAi"], Palette.Autopilot) - : (Strings["CabDriverUser"], Palette.UserTrain); + if (end is not null) + chipX -= ChipLeft(context, end, Palette.Text, chipX, 4) + 5; + var (driverText, driverBrush) = DriverChip(s); chipX -= ChipLeft(context, driverText, driverBrush, chipX, 4) + 10; + Say(name); + Say(driverText); + if (end is not null) + Say(end); using (context.PushClip(new Rect(Pad, 0, Math.Max(0, chipX - Pad), 28))) - context.DrawText(MapView.Text(recording.Vehicle(s.Vehicle)?.Name ?? "", Palette.Text, 12, FontWeight.SemiBold), new Point(Pad, 6)); + context.DrawText(MapView.Text(name, Palette.Text, 12, FontWeight.SemiBold), new Point(Pad, 6)); + } - // The speed, large, what the AI would do under it, the accelerations at the right. - var judgement = DrivingSummary.Judge(s); - var speed = MapView.Text(s.AbsSpeedKmh.ToString("0", culture), judgement is SpeedJudgement.Over ? Palette.Bad - : judgement is SpeedJudgement.Slightly ? Palette.Warn : Palette.Text, 36, FontWeight.SemiBold); + private (string Text, IBrush Brush) DriverChip(CabSample s) + { + if (!s.InCab) + return (Strings["CabOutside"], Palette.DimText); + return s.Driving == Driver.Ai ? (Strings["CabDriverAi"], Palette.Autopilot) : (Strings["CabDriverUser"], Palette.UserTrain); + } + + /// The speed, large, what the AI would do under it, the accelerations at the right. + private void DrawSpeed(DrawingContext context, CabSample s, double width, double right, CultureInfo culture) + { + string kmh = s.AbsSpeedKmh.ToString("0", culture); + var speed = MapView.Text(kmh, SpeedBrush(DrivingSummary.Judge(s)), 36, FontWeight.SemiBold); context.DrawText(speed, new Point(Pad, 24)); + Say($"{kmh} km/h"); 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); @@ -101,75 +183,97 @@ public sealed class CabPanel : Control 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(string.Format(culture, Strings["CabWheels"], Math.Abs(wheels)), Palette.Warn, 12), - new Point(wheelsX, 24 + speed.Height - 21)); + context.DrawText(MapView.Text(wheelsText, Palette.Warn, 12), new Point(wheelsX, 24 + speed.Height - 21)); + Say(wheelsText); } if (s.AiValid) { using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40))) { - context.DrawText(MapView.Text(string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh), Palette.Target, 12), new Point(Pad, 76)); + string target = string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh); + context.DrawText(MapView.Text(target, Palette.Target, 12), new Point(Pad, 76)); + Say(target); if (s.Ai.HasNextLimit) - context.DrawText(MapView.Text(string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance), Palette.Limit, 11), - new Point(Pad, 93)); + { + string limit = string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance); + Say(limit); + context.DrawText(MapView.Text(limit, Palette.Limit, 11), new Point(Pad, 93)); + } } } double gaugeWidth = right - gaugeX; Balance(context, Strings["CabAcceleration"], s.Acceleration, 1.5, gaugeX, 34, gaugeWidth); Balance(context, Strings["CabLateral"], s.LateralAcceleration, 1.5, gaugeX, 70, gaugeWidth); + } - // The controllers. + private static IBrush SpeedBrush(SpeedJudgement judgement) => judgement switch + { + SpeedJudgement.Over => Palette.Bad, + SpeedJudgement.Slightly => Palette.Warn, + _ => Palette.Text + }; + + /// The controllers. + private void DrawControls(DrawingContext context, CabSample s, double width, double right, CultureInfo culture) + { double top = Section(context, Strings["CabSectionControls"], Pad, 118, right); double column = width / 4; Value(context, Strings["CabController"], s.MainController.ToString(culture), Pad, top); Steps(context, s.MainController, _controllerTop, Pad, top + 34, column - 14); - if (extra is { } handle && _integrated.Contains(s.Vehicle)) + if (s.Extra is { } handle && _integrated.Contains(s.Vehicle)) Value(context, Strings["CabIntegrated"], (handle.IntegratedController * 100).ToString("+0;−0;0", culture) + " %", Pad + column, top); else Value(context, Strings["CabShunt"], s.ScndController.ToString(culture), Pad + column, top); - Value(context, Strings["CabReverser"], Strings[s.Reverser > 0 ? "CabForward" : s.Reverser < 0 ? "CabBackward" : "CabNeutral"], Pad + 2 * column, top); + string reverser = s.Reverser switch { > 0 => "CabForward", < 0 => "CabBackward", _ => "CabNeutral" }; + Value(context, Strings["CabReverser"], Strings[reverser], Pad + 2 * column, top); Value(context, Strings["CabTrainBrake"], s.TrainBrake.ToString("0.0", culture), Pad + 3 * column, top); + } - // The brakes, as gauges, the setting (G, P, R) at the right of the title. + /// The brakes, as gauges, the setting (G, P, R) at the right of the title. + /// Where the last gauge stands. + private double DrawBrakes(DrawingContext context, CabSample s, double width, double right, CultureInfo culture) + { + var extra = s.Extra; string? setting = extra is { } e && (e.BrakeDelay | e.BrakeMode) != 0 ? string.Format(culture, Strings["CabBrakeSetting"], string.Join(" · ", new[] { BrakeSetting(e.BrakeDelay), BrakeMode(e.BrakeMode) }.Where(t => t.Length > 0))) : null; - top = Section(context, Strings["CabSectionBrakes"], Pad, 180, right, setting); - const double gauge = 17; - Gauge(context, Strings["CabPipe"], s.BrakePipe, 6, 5, $"{s.BrakePipe:0.00} bar", Palette.Station, Pad, top, width); - double y = top + gauge; - if (extra is { } x1) + double y = Section(context, Strings["CabSectionBrakes"], Pad, 180, right, setting); + var gauges = new List { - // what the driver's brake valve shows: its equalizing reservoir, the FV4a's time reservoir - Gauge(context, Strings["CabDriverValve"], x1.DriverValve, 6, null, $"{x1.DriverValve:0.00} bar", Palette.Target, Pad, y, width); - y += gauge; - } - Gauge(context, Strings["CabCylinder"], s.BrakeCylinder, 6, null, $"{s.BrakeCylinder:0.0} bar", Palette.Brakes, Pad, y, width); - y += gauge; - if (extra is { } x3) - { - // the most braked vehicle of the train - Gauge(context, Strings["CabConsistCylinder"], x3.ConsistBrakeCylinder, 6, null, $"{x3.ConsistBrakeCylinder:0.0} bar", Palette.Brakes, Pad, y, width); - y += gauge; - } - Gauge(context, Strings["CabReservoir"], s.MainReservoir, 10, null, $"{s.MainReservoir:0.0} bar", Palette.Controller, Pad, y, width); - y += gauge; - if (extra is { } x2) - { - bool has = _feedPipe.Contains(s.Vehicle); - Gauge(context, Strings["CabFeedPipe"], has ? x2.FeedPipe : 0, 10, null, has ? $"{x2.FeedPipe:0.0} bar" : "—", Palette.Controller, Pad, y, width); - y += gauge; - } - Gauge(context, Strings["CabLocalBrake"], s.LocalBrake, 1, null, $"{s.LocalBrake * 100:0} %", Palette.Brakes, Pad, y, width); + new(Strings["CabPipe"], s.BrakePipe, 6, 5, $"{s.BrakePipe:0.00} bar", Palette.Station) + }; + // what the driver's brake valve shows: its equalizing reservoir, the FV4a's time reservoir + if (extra is { } valve) + gauges.Add(new(Strings["CabDriverValve"], valve.DriverValve, 6, null, $"{valve.DriverValve:0.00} bar", Palette.Target)); + gauges.Add(new(Strings["CabCylinder"], s.BrakeCylinder, 6, null, $"{s.BrakeCylinder:0.0} bar", Palette.Brakes)); + // the most braked vehicle of the train + if (extra is { } most) + gauges.Add(new(Strings["CabConsistCylinder"], most.ConsistBrakeCylinder, 6, null, $"{most.ConsistBrakeCylinder:0.0} bar", Palette.Brakes)); + gauges.Add(new(Strings["CabReservoir"], s.MainReservoir, 10, null, $"{s.MainReservoir:0.0} bar", Palette.Controller)); + if (extra is { } feed) + gauges.Add(FeedPipe(s, feed)); + gauges.Add(new(Strings["CabLocalBrake"], s.LocalBrake, 1, null, $"{s.LocalBrake * 100:0} %", Palette.Brakes)); - // The traction at the left, as fits what drives the vehicle; the lights of both ends of the train at the right. - double half = Pad + width / 2; - double driveTop = y + gauge + 4; - top = Section(context, Strings["CabSectionDrive"], Pad, driveTop, half - 10); - Section(context, Strings["CabLights"], half + 4, driveTop, right); - DrawDrive(context, s, top, half - 10 - Pad, culture); - double row = top; + for (int i = 0; i < gauges.Count; i++) + { + if (i > 0) + y += BrakeRow; + Gauge(context, gauges[i], Pad, y, width); + } + return y; + } + + private GaugeReading FeedPipe(CabSample s, CabExtra feed) => _feedPipe.Contains(s.Vehicle) + ? new(Strings["CabFeedPipe"], feed.FeedPipe, 10, null, $"{feed.FeedPipe:0.0} bar", Palette.Controller) + : new(Strings["CabFeedPipe"], 0, 10, null, "—", Palette.Controller); + + /// The lights of both ends: the signal shown, green as it is to be, red otherwise with the one it is to show. + /// Left edge, top and width of the column; its height is not used. + private void DrawLights(DrawingContext context, CabSample s, Rect area, CultureInfo culture) + { + double half = area.X, right = area.Right, row = area.Y; foreach (var (key, lights, equipped, required, isRight) in new[] { ("CabLightsHead", s.LightsHead, s.EquippedHead, HeadCodes.RequiredHead(s), HeadCodes.HeadRight(s)), @@ -177,14 +281,9 @@ public sealed class CabPanel : Control }) { DrawFace(context, lights, new Point(half + 4 + 17, row + 15)); - // the end, and under it the signal it shows: green as it is to be (with the lamps the vehicle has), - // red otherwise with the one it is to show - var shown = HeadCodes.Of(lights); - var text = HeadCodes.NoLamps(equipped) ? Strings["CabLightsNone"] - : isRight == false && required is { } want - ? string.Format(culture, Strings["CabLightsWant"], HeadCodes.Name(shown), HeadCodes.Name(want)) - : isRight == true && required is { } met ? HeadCodes.Name(met) : HeadCodes.Name(shown); - var brush = isRight is null ? Palette.DimText : isRight.Value ? Palette.Good : Palette.Bad; + string text = LightsText(HeadCodes.Of(lights), HeadCodes.NoLamps(equipped), required, isRight, culture); + IBrush brush = isRight switch { null => Palette.DimText, true => Palette.Good, false => Palette.Bad }; + Say($"{Strings[key]}: {text}"); using (context.PushClip(new Rect(half + 44, row, right - half - 44, 28))) { context.DrawText(MapView.Text(Strings[key], Palette.DimText, 10), new Point(half + 46, row)); @@ -192,9 +291,24 @@ public sealed class CabPanel : Control } row += 27; } + } - // The devices, in three groups side by side: lit as their lamps are in the cab, the ones off faint. - top = Section(context, Strings["CabSectionDevices"], Pad, top + 3 * DriveRow + 6, right); + private string LightsText(HeadCode shown, bool noLamps, HeadCode? required, bool? isRight, CultureInfo culture) + { + if (noLamps) + return Strings["CabLightsNone"]; + if (isRight == false && required is { } want) + return string.Format(culture, Strings["CabLightsWant"], HeadCodes.Name(shown), HeadCodes.Name(want)); + return isRight == true && required is { } met ? HeadCodes.Name(met) : HeadCodes.Name(shown); + } + + /// The devices, in three groups side by side: lit as their lamps are in the cab, the ones off faint. + /// Left edge, top, width and the height of the whole panel. + /// Where the doors go, under them. + private double DrawDevices(DrawingContext context, CabSample s, Rect area, CultureInfo culture) + { + double width = area.Width, height = area.Height; + double top = Section(context, Strings["CabSectionDevices"], area.X, area.Y, area.X + width); var groups = Devices(s, culture); var widths = new double[groups.Length]; for (int g = 0; g < groups.Length; g++) @@ -205,33 +319,42 @@ public sealed class CabPanel : Control } // each group as wide as its longest name, what is left shared between them double spare = (width - widths.Sum()) / groups.Length; - double x = Pad, bottom = top; + double x = area.X, bottom = top; for (int g = 0; g < groups.Length; g++) { double groupWidth = Math.Max(20, widths[g] + spare); - using (context.PushClip(new Rect(x, top, groupWidth, size.Height - top))) - { - context.DrawText(MapView.Text(Strings[groups[g].Title], Palette.DimText, 10, FontWeight.SemiBold), new Point(x, top)); - double lampY = top + 16; - foreach (var (text, brush) in groups[g].Lamps) - { - Lamp(context, text, brush, x, lampY); - lampY += LampRow; - } - bottom = Math.Max(bottom, lampY); - } + using (context.PushClip(new Rect(x, top, groupWidth, height - top))) + bottom = Math.Max(bottom, DrawGroup(context, groups[g], x, top)); x += groupWidth; } + return Math.Max(bottom, top + 16 + 9 * LampRow) + 6; + } - // The doors under them, in two columns: open, permitted, the departure signal, the steps and the lock. - top = Math.Max(bottom, top + 16 + 9 * LampRow) + 6; + /// Where the group ends. + private double DrawGroup(DrawingContext context, (string Title, (string Text, IBrush? Lit)[] Lamps) group, double x, double top) + { + context.DrawText(MapView.Text(Strings[group.Title], Palette.DimText, 10, FontWeight.SemiBold), new Point(x, top)); + Say(Strings[group.Title]); + double lampY = top + 16; + foreach (var (text, brush) in group.Lamps) + { + Lamp(context, text, brush, x, lampY); + lampY += LampRow; + } + return lampY; + } + + /// The doors, in two columns: open, permitted, the departure signal, the steps and the lock. + private void DrawDoors(DrawingContext context, CabSample s, double top, double width, double height) + { context.DrawText(MapView.Text(Strings["CabGroupDoors"], Palette.DimText, 10, FontWeight.SemiBold), new Point(Pad, top)); + Say(Strings["CabGroupDoors"]); var doors = Doors(s.AsTheCabSees); double doorColumn = width / DoorColumns; for (int i = 0; i < doors.Length; i++) { double doorX = Pad + i % DoorColumns * doorColumn; - using (context.PushClip(new Rect(doorX, top, doorColumn, size.Height - top))) + using (context.PushClip(new Rect(doorX, top, doorColumn, height - top))) Lamp(context, doors[i].Text, doors[i].Lit, doorX, top + 16 + i / DoorColumns * LampRow); } } @@ -290,6 +413,7 @@ public sealed class CabPanel : Control break; default: context.DrawText(MapView.Text(Strings["CabNoDrive"], Palette.DimText, 11), new Point(Pad, top + 2)); + Say(Strings["CabNoDrive"]); return; } double column = width / 2; @@ -332,8 +456,9 @@ public sealed class CabPanel : Control } /// 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. - private static double Section(DrawingContext context, string title, double x, double y, double right, string? note = null) + private double Section(DrawingContext context, string title, double x, double y, double right, string? note = null) { + Say(note is null ? title : $"{title}, {note}"); var text = MapView.Text(title.ToUpper(CultureInfo.CurrentCulture), Palette.DimText, 9, FontWeight.SemiBold); context.DrawText(text, new Point(x, y)); double end = right; @@ -381,8 +506,9 @@ public sealed class CabPanel : Control _measured = recording.Revision; } - private static void Value(DrawingContext context, string label, string value, double x, double y, IBrush? brush = null) + private void Value(DrawingContext context, string label, string value, double x, double y, IBrush? brush = null) { + Say($"{label}: {value}"); context.DrawText(MapView.Text(label, Palette.DimText, 10), new Point(x, y)); context.DrawText(MapView.Text(value, brush ?? Palette.Text, 14, FontWeight.SemiBold), new Point(x, y + 13)); } @@ -398,9 +524,10 @@ public sealed class CabPanel : Control } /// A gauge: its name, a bar up to the value against the scale, a mark where it should stand, the value. - private static void Gauge(DrawingContext context, string label, float value, double scale, double? mark, string text, - IBrush brush, double x, double y, double width) + private void Gauge(DrawingContext context, GaugeReading reading, double x, double y, double width) { + var (label, value, scale, mark, text, brush) = reading; + Say($"{label}: {text}"); const double labelWidth = 118, valueWidth = 64; context.DrawText(MapView.Text(label, Palette.DimText, 11), new Point(x, y)); double barX = x + labelWidth, barWidth = width - labelWidth - valueWidth; @@ -419,9 +546,10 @@ public sealed class CabPanel : Control } /// A value either way of nought: a bar from the middle, to the right above it. - private static void Balance(DrawingContext context, string label, float value, double scale, double x, double y, double width) + private void Balance(DrawingContext context, string label, float value, double scale, double x, double y, double width) { var culture = CultureInfo.CurrentCulture; + Say($"{label}: {value.ToString("+0.00;−0.00;0.00", culture)} m/s²"); context.DrawText(MapView.Text(label, Palette.DimText, 10), new Point(x, y)); var v = MapView.Text($"{value.ToString("+0.00;−0.00;0.00", culture)} m/s²", Palette.Text, 11, FontWeight.SemiBold); context.DrawText(v, new Point(x + width - v.Width, y)); @@ -466,8 +594,11 @@ public sealed class CabPanel : Control } /// A device's lamp and its name: lit in its colour, the name bright; off, both faint. - private static void Lamp(DrawingContext context, string text, IBrush? lit, double x, double y) + private void Lamp(DrawingContext context, string text, IBrush? lit, double x, double y) { + // Only the lamps that are lit are told: the dark ones are the panel, not the moment. + if (lit is not null) + Say(text); var center = new Point(x + 4, y + 7); if (lit is not null) context.DrawEllipse(Palette.Faded(lit, 0.3), null, center, 6, 6); @@ -541,12 +672,12 @@ public sealed class CabPanel : Control if (s.Security != SecurityFlags.None || s.CabEnd != 0) { // A recording which tells them apart. - safety.Add((Strings["DevVigilance"], Security(SecurityFlags.VigilanceBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.Vigilance, Palette.Vigilance))); - safety.Add((Strings["DevCabSignal"], Security(SecurityFlags.CabSignalBeeping, Palette.LampAlarm) ?? Security(SecurityFlags.CabSignal, Palette.CabSignal))); - safety.Add((Strings["DevSecurityBraking"], Security(SecurityFlags.Braking, Palette.LampAlarm))); + safety.Add((Strings["DevVigilance"], s.VigilanceBuzzer ? Palette.Buzzer : Security(SecurityFlags.Vigilance, Palette.Vigilance))); + safety.Add((Strings["DevCabSignal"], s.CabSignalBuzzer ? Palette.Buzzer : Security(SecurityFlags.CabSignal, Palette.CabSignal))); + safety.Add((Strings["DevSecurityBraking"], s.ProtectionBraking ? Palette.LampAlarm : null)); } else - safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm + safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer : (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.LampWarning : null)); safety.Add(Flag("DevWheelSlip", CabFlags.WheelSlip, Palette.LampAlarm)); safety.Add(On("DevOverloadRelay", CabDevices.OverloadRelay, Palette.LampAlarm)); @@ -575,4 +706,7 @@ public sealed class CabPanel : Control doors.Add(On("DevDepartureSignal", CabDevices.DepartureSignal, Palette.LampWarning)); return doors.ToArray(); } + + /// What one gauge shows: its name, the value against the scale, the mark, the value written out. + private readonly record struct GaugeReading(string Label, float Value, double Scale, double? Mark, string Text, IBrush Brush); } diff --git a/Eu07.BlackBox.Views/CommandTexts.cs b/Eu07.BlackBox.Views/CommandTexts.cs new file mode 100644 index 0000000..7c20383 --- /dev/null +++ b/Eu07.BlackBox.Views/CommandTexts.cs @@ -0,0 +1,378 @@ +using System.Collections.Generic; + +namespace Eu07.BlackBox.Views; + +/// +/// 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. +/// +public static class CommandTexts +{ + private static readonly Dictionary 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"), + }; + + /// The text of , Polish for "pl", else English; its name when unknown. + public static string Of(string command, string languageCode) => + Texts.TryGetValue(command, out var text) ? languageCode == "pl" ? text.Polish : text.English : command; + + /// The commands there are texts for. + public static IEnumerable Commands => Texts.Keys; +} diff --git a/Eu07.BlackBox.Views/Eu07.BlackBox.Views.csproj b/Eu07.BlackBox.Views/Eu07.BlackBox.Views.csproj index 53efe37..9f92822 100644 --- a/Eu07.BlackBox.Views/Eu07.BlackBox.Views.csproj +++ b/Eu07.BlackBox.Views/Eu07.BlackBox.Views.csproj @@ -14,6 +14,10 @@ + + + + diff --git a/Eu07.BlackBox.Views/EventList.cs b/Eu07.BlackBox.Views/EventList.cs index b55cca9..a3786bd 100644 --- a/Eu07.BlackBox.Views/EventList.cs +++ b/Eu07.BlackBox.Views/EventList.cs @@ -155,7 +155,9 @@ public sealed class EventList : ListBox var culture = CultureInfo.CurrentCulture; var events = new List(); foreach (var c in recording.UserCommands()) - events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"], c.Name), Palette.Command, false)); + events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"], + strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]), + Palette.Command, false)); foreach (var d in recording.DriverChanges) { if (recording.CabAt(d.Time + 0.5) is not { } s || s.Vehicle != d.Vehicle) @@ -176,14 +178,7 @@ public sealed class EventList : ListBox foreach (var horn in recording.UserHornChecks()) events.Add(new BlackBoxEvent(horn.Request.Time, strings[horn.Sounded ? "EventHornSounded" : "EventHornMissed"], horn.Sounded ? Palette.HornPoint : Palette.Bad, !horn.Sounded)); - 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)); - } + AddSecurity(recording, strings, events, culture); AddCameras(recording, strings, events, culture); AddCouplings(recording, strings, events, culture); AddCabChanges(recording, strings, events, culture); @@ -196,6 +191,45 @@ public sealed class EventList : ListBox return events.OrderBy(e => e.Time).ToList(); } + /// + /// 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. + /// + private static void AddSecurity(Recording recording, IBlackBoxStrings strings, List 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)); + } + + /// Which of them it was: the lamps blinking. + 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 events, CultureInfo culture) { UserVehicleChange? before = null; diff --git a/Eu07.BlackBox.Views/Palette.cs b/Eu07.BlackBox.Views/Palette.cs index 91319b3..cedbd79 100644 --- a/Eu07.BlackBox.Views/Palette.cs +++ b/Eu07.BlackBox.Views/Palette.cs @@ -26,6 +26,8 @@ public static class Palette public static readonly IBrush AccentFill = Brush("#177F00"); public static readonly IBrush AccentFillHover = Brush("#1E9000"); public static readonly IBrush AccentText = Brush("#FFFFFF"); + /// The ring round a drawn control that has the keyboard, in the green of the starter's own. + public static readonly IPen FocusPen = new Pen(Accent, 2); public static readonly IBrush Good = Brush("#4cc46e"); /// A delay: green on time, yellow a little late, red late, blue early. @@ -79,6 +81,8 @@ public static class Palette public static readonly IBrush LampOn = Brush("#4cc46e"); public static readonly IBrush LampWarning = Brush("#e8c547"); public static readonly IBrush LampAlarm = Brush("#f0584a"); + /// The train protection's buzzer: still to be acknowledged, not braking yet. + public static readonly IBrush Buzzer = Brush("#c77dff"); public static readonly IBrush LightWhite = Brush("#fff6d8"); public static readonly IBrush LightRed = Brush("#ff3b30"); public static readonly IBrush Command = Brush("#8b96a3"); diff --git a/Eu07.BlackBox.Views/SpokenPeer.cs b/Eu07.BlackBox.Views/SpokenPeer.cs new file mode 100644 index 0000000..8917f50 --- /dev/null +++ b/Eu07.BlackBox.Views/SpokenPeer.cs @@ -0,0 +1,47 @@ +using System; +using Avalonia.Automation; +using Avalonia.Automation.Peers; +using Avalonia.Automation.Provider; +using Avalonia.Controls; + +namespace Eu07.BlackBox.Views; + +/// +/// 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. +/// +internal sealed class SpokenPeer : ControlAutomationPeer, IValueProvider +{ + private readonly AutomationControlType _type; + private readonly Func _value; + private readonly Func _help; + + public SpokenPeer(Control owner, AutomationControlType type, Func value, Func help) : base(owner) + { + _type = type; + _value = value; + _help = help; + } + + /// Tells the reader the value changed, so it reads the new one. + 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."); +} diff --git a/Eu07.BlackBox.Views/TimelineView.cs b/Eu07.BlackBox.Views/TimelineView.cs index 6105c5a..7716db1 100644 --- a/Eu07.BlackBox.Views/TimelineView.cs +++ b/Eu07.BlackBox.Views/TimelineView.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Globalization; using Avalonia; +using Avalonia.Automation.Peers; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; @@ -51,6 +52,67 @@ public sealed class TimelineView : Control { ClipToBounds = true; MinHeight = 160; + // Walked from the keyboard too: the arrows step through the time. + Focusable = true; + } + + private string? _spoken; + + /// + /// 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. + /// + 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"]); + + /// How far one press of an arrow goes, in seconds: Ctrl a minute, Page Up and Down ten. + public const double Step = 10, CtrlStep = 60, PageStep = 600; + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (_recording is not { } recording || recording.Duration <= 0) + return; + + bool ctrl = e.KeyModifiers.HasFlag(KeyModifiers.Control); + double? to = e.Key switch + { + Key.Left => _time - (ctrl ? CtrlStep : Step), + Key.Right => _time + (ctrl ? CtrlStep : Step), + Key.PageUp => _time - PageStep, + Key.PageDown => _time + PageStep, + Key.Home => 0, + Key.End => recording.Duration, + _ => null + }; + if (to is not { } t) + return; + + Seek?.Invoke(Math.Clamp(t, 0, recording.Duration)); + e.Handled = true; + } + + protected override void OnGotFocus(FocusChangedEventArgs e) + { + base.OnGotFocus(e); + InvalidateVisual(); + } + + protected override void OnLostFocus(FocusChangedEventArgs e) + { + base.OnLostFocus(e); + InvalidateVisual(); } public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings(); @@ -100,6 +162,8 @@ public sealed class TimelineView : Control public override void Render(DrawingContext context) { var size = Bounds.Size; + if (IsFocused) + context.DrawRectangle(null, Palette.FocusPen, new Rect(size).Deflate(1)); var recording = _recording; if (recording is null || recording.Duration <= 0) return; @@ -245,16 +309,16 @@ public sealed class TimelineView : Control rows[2].Add(x0, x1, s.BrakeCylinder > 0.2f ? BrakeShade(s.BrakeCylinder) : null, BandHeight); if (s.Security != SecurityFlags.None || s.CabEnd != 0) { - // The alerter and the cab signalling apart, red when not acknowledged in time. - rows[3].Add(x0, x1, s.Has(SecurityFlags.VigilanceBeeping) ? Palette.LampAlarm + // The alerter and the cab signalling apart: the lamp, then its buzzer, red when it braked. + rows[3].Add(x0, x1, s.VigilanceBuzzer ? Palette.Buzzer : s.Has(SecurityFlags.Vigilance) ? Palette.Vigilance : null, BandHeight); - rows[4].Add(x0, x1, s.Has(SecurityFlags.CabSignalBeeping) ? Palette.LampAlarm + rows[4].Add(x0, x1, s.CabSignalBuzzer ? Palette.Buzzer : s.Has(SecurityFlags.CabSignal) ? Palette.CabSignal : null, BandHeight); - if (s.Has(SecurityFlags.Braking)) + if (s.ProtectionBraking) rows[s.Has(SecurityFlags.CabSignal) && !s.Has(SecurityFlags.Vigilance) ? 4 : 3].Add(x0, x1, Palette.Bad, BandHeight); } else - rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.LampAlarm + rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer : (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. while (camera + 1 < cameras.Count && cameras[camera + 1].Time <= s.Time) @@ -526,7 +590,8 @@ public sealed class TimelineView : Control foreach (var d in recording.DriverChanges) Consider(d.Time, () => Strings[d.Driving == Driver.Ai ? "TlAutopilotOn" : "TlAutopilotOff"]); foreach (var c in recording.UserCommands()) - Consider(c.Time, () => string.Format(culture, Strings["TlCommand"], c.Name)); + Consider(c.Time, () => string.Format(culture, Strings["TlCommand"], + Strings[DefaultBlackBoxStrings.CommandPrefix + c.Name])); } return found; } diff --git a/Eu07.BlackBox.Views/TimetablePanel.cs b/Eu07.BlackBox.Views/TimetablePanel.cs index 625c2f4..a82e2d6 100644 --- a/Eu07.BlackBox.Views/TimetablePanel.cs +++ b/Eu07.BlackBox.Views/TimetablePanel.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using Avalonia; +using Avalonia.Automation.Peers; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; @@ -36,6 +38,84 @@ public sealed class TimetablePanel : Control { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.Hand); + // The stations walked from the keyboard as well: the arrows go up and down the rows, + // Enter goes to the moment as a click does. + Focusable = true; + } + + // The row the keyboard stands at; -1 until it is moved, when the station played is meant. + private int _keyRow = -1; + private string? _spoken; + + protected override AutomationPeer OnCreateAutomationPeer() => + new SpokenPeer(this, AutomationControlType.List, () => _spoken ?? RowText(KeyRow), () => Strings["TimetableHelp"]); + + private int KeyRow => _keyRow >= 0 && _keyRow < _rows.Count ? _keyRow : Current(); + + /// A row as it is read: the station, the times of the timetable, the kilometre and what happened there. + 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 { StationNames.Display(row.Row.Station), planned }; + if (row.Row.Km > 0 || i > 0) + parts.Add($"km {row.Row.Km.ToString("0.0", culture)}"); + parts.AddRange(Chips(row, culture).Select(c => c.Text)); + return $"{i + 1}/{_rows.Count}. {string.Join(", ", parts)}"; + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (_rows.Count == 0) + return; + + int at = KeyRow; + int? to = e.Key switch + { + Key.Up => at - 1, + Key.Down => at + 1, + Key.Home => 0, + Key.End => _rows.Count - 1, + _ => null + }; + if (e.Key == Key.Enter && at >= 0 && (_rows[at].ArrivedAt ?? _rows[at].DepartedAt) is { } t) + { + Seek?.Invoke(Math.Max(0, t - 5)); + e.Handled = true; + return; + } + if (to is not { } row) + return; + + _keyRow = Math.Clamp(row, 0, _rows.Count - 1); + string? before = _spoken; + _spoken = RowText(_keyRow); + (ControlAutomationPeer.FromElement(this) as SpokenPeer)?.Told(before, _spoken); + this.BringIntoView(new Rect(0, HeaderHeight + _keyRow * RowHeight, Bounds.Width, RowHeight)); + InvalidateVisual(); + e.Handled = true; + } + + protected override void OnGotFocus(FocusChangedEventArgs e) + { + base.OnGotFocus(e); + _spoken = null; + InvalidateVisual(); + } + + protected override void OnLostFocus(FocusChangedEventArgs e) + { + base.OnLostFocus(e); + _keyRow = -1; + InvalidateVisual(); } public Recording? Recording @@ -103,6 +183,8 @@ public sealed class TimetablePanel : Control { var size = Bounds.Size; var culture = CultureInfo.CurrentCulture; + if (IsFocused) + context.DrawRectangle(null, Palette.FocusPen, new Rect(size).Deflate(1)); if (_timetable is not { } timetable) { context.DrawText(MapView.Text(Strings["TimetableNone"], Palette.DimText, 12), new Point(Pad, Pad)); @@ -130,6 +212,8 @@ public sealed class TimetablePanel : Control } else if (i == _hover) context.DrawRectangle(Palette.Faded(Palette.CardHover, 0.6), null, new Rect(0, top, size.Width, RowHeight - 1)); + if (IsFocused && i == KeyRow) + context.DrawRectangle(null, Palette.FocusPen, new Rect(1, top + 1, size.Width - 2, RowHeight - 3)); // The line of the route through the stations, a dot each: hollow ahead, filled when done. var outcome = row.Outcome; diff --git a/Eu07.BlackBox.Views/UiKit.cs b/Eu07.BlackBox.Views/UiKit.cs index 0fbbd72..8bcba49 100644 --- a/Eu07.BlackBox.Views/UiKit.cs +++ b/Eu07.BlackBox.Views/UiKit.cs @@ -1,5 +1,8 @@ using System; using Avalonia; +using Avalonia.Automation; +using Avalonia.Automation.Peers; +using Avalonia.Automation.Provider; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Layout; @@ -235,10 +238,13 @@ internal static class UiKit BorderBrush = Palette.CardBorder; BorderThickness = new Thickness(0, 0, 0, 1); Child = _row; + // Read as the tabs they are, which of them is picked. + AutomationProperties.SetControlTypeOverride(_row, AutomationControlType.Tab); + AutomationProperties.SetAccessibilityView(_row, AccessibilityView.Content); for (int i = 0; i < choices.Length; i++) { int index = i; - var button = new Button + var button = new SegmentButton { Content = choices[i], Padding = new Thickness(14, 3), @@ -267,8 +273,9 @@ internal static class UiKit _selected = value; for (int i = 0; i < _row.Children.Count; i++) { - var button = (Button)_row.Children[i]; + var button = (SegmentButton)_row.Children[i]; bool on = i == value; + button.IsOn = on; var line = on ? Palette.Accent : Brushes.Transparent; button.Background = on ? Palette.Panel : Brushes.Transparent; button.BorderBrush = line; @@ -280,4 +287,51 @@ internal static class UiKit } } } + + /// + /// A choice of : a button to look at, a tab to a screen reader, + /// which says whether it is the one picked. + /// + 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() + { + } + } + } } diff --git a/Eu07.BlackBox/Recording.cs b/Eu07.BlackBox/Recording.cs index 50f2fdd..b764f9a 100644 --- a/Eu07.BlackBox/Recording.cs +++ b/Eu07.BlackBox/Recording.cs @@ -520,7 +520,13 @@ public sealed class Recording } /// When the train protection braked the user's train: the alerter or the cab signalling not acknowledged. - public IReadOnlyList SecurityBrakings() => CabSpans(s => s.Has(SecurityFlags.Braking)); + public IReadOnlyList SecurityBrakings() => CabSpans(s => s.ProtectionBraking); + + /// + /// 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. + /// + public IReadOnlyList SecurityAlarms() => CabSpans(s => s.VigilanceBuzzer || s.CabSignalBuzzer); /// The commands the user gave in a vehicle, presses only. public IEnumerable UserCommands() => _commands.Where(c => c.Pressed && c.Vehicle != 0); diff --git a/Eu07.BlackBox/Records.cs b/Eu07.BlackBox/Records.cs index bf100d7..89e44a7 100644 --- a/Eu07.BlackBox/Records.cs +++ b/Eu07.BlackBox/Records.cs @@ -375,6 +375,21 @@ public readonly record struct CabSample(double Time, int Vehicle, Position Posit public bool Has(CabDevices device) => (Devices & device) == device; public bool Has(SecurityFlags flag) => (Security & flag) == flag; + /// + /// 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. + /// + public bool VigilanceBuzzer => Has(SecurityFlags.VigilanceBeeping) && Has(SecurityFlags.Vigilance); + + /// The cab signalling's buzzer: its lamp not acknowledged in time. + public bool CabSignalBuzzer => Has(SecurityFlags.CabSignalBeeping); + + /// + /// 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. + /// + 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; diff --git a/StarterNG.Tests/AnnouncerTests.cs b/StarterNG.Tests/AnnouncerTests.cs new file mode 100644 index 0000000..1d16702 --- /dev/null +++ b/StarterNG.Tests/AnnouncerTests.cs @@ -0,0 +1,125 @@ +using Avalonia.Automation; +using Avalonia.Automation.Peers; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.VisualTree; +using StarterNG.Controls; + +namespace StarterNG.Tests; + +[Collection(AvaloniaControls.Name)] +public class AnnouncerTests +{ + private DateTime _now = new(2026, 11, 15, 12, 0, 0, DateTimeKind.Utc); + + private Announcer NewAnnouncer() => new(() => _now); + + [Fact] + public void A_message_is_read_while_fresh_and_then_forgotten() + { + var announcer = NewAnnouncer(); + announcer.Say(" Jakość grafiki: Wysoka "); + Assert.Equal("Jakość grafiki: Wysoka", announcer.Message); + + _now += Announcer.Shown; + Assert.Null(announcer.Message); + } + + [Fact] + public void Nothing_to_say_says_nothing() + { + var announcer = NewAnnouncer(); + announcer.Say("Zapisano ustawienia"); + announcer.Say(" "); + + Assert.Equal("Zapisano ustawienia", announcer.Message); + } + + [Fact] + public void A_control_inside_says_it_through_the_window_announcer() + { + var button = new Button(); + var announcer = NewAnnouncer(); + announcer.Child = new Border { Child = button }; + + Announcer.Say(button, "Godzina: 07:05"); + + Assert.Equal("Godzina: 07:05", announcer.Message); + } + + [Fact] + public void A_control_outside_any_announcer_is_not_heard() + { + var button = new Button(); + + var thrown = Record.Exception(() => Announcer.Say(button, "Godzina: 07:05")); + + Assert.Null(thrown); + Assert.Null(button.FindAncestorOfType()); + } + + [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)); + } +} diff --git a/StarterNG.Tests/AvaloniaControls.cs b/StarterNG.Tests/AvaloniaControls.cs new file mode 100644 index 0000000..8edcc55 --- /dev/null +++ b/StarterNG.Tests/AvaloniaControls.cs @@ -0,0 +1,11 @@ +namespace StarterNG.Tests; + +/// +/// 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. +/// +[CollectionDefinition(Name)] +public sealed class AvaloniaControls +{ + public const string Name = "Avalonia controls"; +} diff --git a/StarterNG.Tests/BlackBox/BlackBoxViewsTests.cs b/StarterNG.Tests/BlackBox/BlackBoxViewsTests.cs new file mode 100644 index 0000000..6102433 --- /dev/null +++ b/StarterNG.Tests/BlackBox/BlackBoxViewsTests.cs @@ -0,0 +1,284 @@ +using Avalonia.Automation; +using Avalonia.Automation.Peers; +using Avalonia.Automation.Provider; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.VisualTree; +using Eu07.BlackBox; +using Eu07.BlackBox.Views; + +namespace StarterNG.Tests.BlackBox; + +/// +/// 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. +/// +[Collection(AvaloniaControls.Name)] +public class BlackBoxViewsTests +{ + private const uint Head = 1; + + /// + /// 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). + /// + 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(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(() => value.SetValue("x")); + + timeline.Spoken = "10:35:22, 40 km/h"; + Assert.Equal("10:35:22, 40 km/h", value.Value); + } + + [Fact] + public void A_description_set_on_the_timeline_wins_over_its_own() + { + var timeline = new TimelineView(); + AutomationProperties.SetHelpText(timeline, "own words"); + + Assert.Equal("own words", Controls.Peer(timeline).GetHelpText()); + } + + [Theory] + [InlineData(Key.Right, KeyModifiers.None, 70)] + [InlineData(Key.Left, KeyModifiers.None, 50)] + [InlineData(Key.Right, KeyModifiers.Control, 120)] + [InlineData(Key.Left, KeyModifiers.Control, 0)] + [InlineData(Key.PageDown, KeyModifiers.None, 120)] + [InlineData(Key.PageUp, KeyModifiers.None, 0)] + [InlineData(Key.Home, KeyModifiers.None, 0)] + [InlineData(Key.End, KeyModifiers.None, 120)] + public void The_keys_take_the_timeline_through_the_recording(Key key, KeyModifiers modifiers, double expected) + { + var timeline = new TimelineView { Recording = Journey(), Time = 60 }; + double? sought = null; + timeline.Seek += t => sought = t; + + Assert.True(Controls.Press(timeline, key, modifiers)); + Assert.Equal(expected, sought); + } + + [Fact] + public void Other_keys_and_an_empty_timeline_are_left_alone() + { + var empty = new TimelineView(); + var timeline = new TimelineView { Recording = Journey(), Time = 60 }; + bool sought = false; + empty.Seek += _ => sought = true; + timeline.Seek += _ => sought = true; + + Assert.False(Controls.Press(empty, Key.Right)); + Assert.False(Controls.Press(timeline, Key.A)); + Assert.False(sought); + } + + [Fact] + public void The_timeline_draws_with_and_without_the_focus() + { + var timeline = new TimelineView { Recording = Journey(), Time = 60 }; + var window = Controls.Show(timeline, 900, 300); + try + { + timeline.Fit(); + Controls.Draw(timeline); + Assert.True(timeline.IsFocused); + timeline.Time = 119; + Controls.Draw(timeline); + window.Focus(); + Controls.Draw(timeline); + } + finally + { + window.Close(); + } + } + + // --- timetable --- + + [Fact] + public void The_timetable_is_a_list_read_row_by_row_from_the_keys() + { + var table = new TimetablePanel { Recording = Journey(), Time = 30 }; + var peer = Controls.Peer(table); + var value = Value(table); + + Assert.Equal(AutomationControlType.List, peer.GetAutomationControlType()); + Assert.False(string.IsNullOrEmpty(peer.GetHelpText())); + Assert.StartsWith("1/3. A", value.Value); + + Assert.True(Controls.Press(table, Key.Down)); + Assert.StartsWith("2/3. Stacja B", value.Value); + Assert.True(Controls.Press(table, Key.Up)); + Assert.StartsWith("1/3. A", value.Value); + Assert.True(Controls.Press(table, Key.End)); + Assert.StartsWith("3/3. C", value.Value); + Assert.True(Controls.Press(table, Key.Down)); + Assert.StartsWith("3/3. C", value.Value); + Assert.True(Controls.Press(table, Key.Home)); + Assert.StartsWith("1/3. A", value.Value); + Assert.Contains("km 2.5", value.Value.Replace(',', '.')); + Assert.False(Controls.Press(table, Key.A)); + } + + [Fact] + public void Enter_on_a_station_passed_goes_to_a_little_before_it() + { + var table = new TimetablePanel { Recording = Journey(), Time = 110 }; + double? sought = null; + table.Seek += t => sought = t; + + Controls.Press(table, Key.Home); + Controls.Press(table, Key.Down); + + Assert.True(Controls.Press(table, Key.Enter)); + Assert.Equal(55, sought); + } + + [Fact] + public void A_recording_without_a_timetable_says_so_and_ignores_the_keys() + { + var recording = BlackBoxReader.Read(new BlackBoxFile().Info().Vehicle(Head, "EU07-005") + .Cab(0, Head, 1150, 40).End(1).Stream()); + var table = new TimetablePanel { Recording = recording, Time = 0 }; + + Assert.False(string.IsNullOrEmpty(Value(table).Value)); + Assert.False(Controls.Press(table, Key.Down)); + table.Recording = null; + Controls.Lay(table); + Controls.Draw(table); + } + + [Fact] + public void The_timetable_draws_its_rows_and_the_one_the_keys_stand_at() + { + var table = new TimetablePanel { Recording = Journey(), Time = 65 }; + var window = Controls.Show(table, 600, 400); + try + { + Controls.Draw(table); + Controls.Press(table, Key.Down); + Controls.Draw(table); + window.Focus(); + Controls.Draw(table); + } + finally + { + window.Close(); + } + } + + // --- cab --- + + [Theory] + [InlineData(true, null)] + [InlineData(true, (byte)1)] + [InlineData(true, (byte)2)] + [InlineData(false, null)] + public void The_cab_says_what_it_draws(bool extended, byte? engine) + { + var cab = new CabPanel { Recording = Journey(extended, engine), Time = 30 }; + Controls.Lay(cab, 600, 900); + + Controls.Draw(cab); + + Assert.NotNull(cab.Said); + Assert.Contains("EU07-005", cab.Said); + Assert.Contains("40 km/h", cab.Said); + Assert.Equal(AutomationControlType.Pane, Controls.Peer(cab).GetAutomationControlType()); + Assert.Equal(cab.Said, Controls.Peer(cab).GetHelpText()); + } + + [Fact] + public void The_cab_stopped_under_the_brakes_and_out_of_the_recording() + { + var cab = new CabPanel { Recording = Journey(), Time = 60 }; + var window = Controls.Show(cab, 600, 900); + try + { + Controls.Draw(cab); + Assert.Contains("0 km/h", cab.Said); + + cab.Time = 500; + Controls.Draw(cab); + Assert.DoesNotContain("km/h", cab.Said); + } + finally + { + window.Close(); + } + } + + [Fact] + public void An_empty_cab_says_there_is_nothing_to_show() + { + var cab = new CabPanel(); + Controls.Lay(cab); + + Controls.Draw(cab); + + Assert.False(string.IsNullOrEmpty(cab.Said)); + } + + // --- segmented choice --- + + [Fact] + public void A_segmented_choice_is_a_row_of_tabs_one_of_them_selected() + { + var choice = new UiKit.Segmented("Mapa", "Profil", "Rozkład"); + int? picked = null; + choice.SelectedChanged += i => picked = i; + var tabs = choice.GetVisualDescendants().OfType - - + + - - - + - - + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - + + + + + + + + + + diff --git a/StarterNG/MainWindow.axaml.cs b/StarterNG/MainWindow.axaml.cs index 6f75ceb..16272d2 100644 --- a/StarterNG/MainWindow.axaml.cs +++ b/StarterNG/MainWindow.axaml.cs @@ -13,6 +13,7 @@ using Avalonia.Layout; using Avalonia.Threading; using Avalonia.VisualTree; using StarterNG.Classes; +using StarterNG.Controls; using StarterNG.Infrastructure; using StarterNG.Views; using StarterNG.Application; @@ -98,6 +99,7 @@ public partial class MainWindow : Window // Tunnelling: the shortcuts are checked before any view sees the key, which is // why OnShortcutKey has to be careful about text entry and key capture. AddHandler(KeyDownEvent, OnShortcutKey, RoutingStrategies.Tunnel); + AddHandler(KeyDownEvent, OnTabWithNothingFocused, RoutingStrategies.Tunnel); AppServices.Current.State.Changed += UpdateStartButton; Opened += (_, _) => @@ -108,7 +110,13 @@ public partial class MainWindow : Window _sceneryFilesTimer.Start(); FollowLastRun(); }; - Activated += (_, _) => CheckExternalSettings(); + Activated += (_, _) => + { + CheckExternalSettings(); + // Back from a build or a download: a new simulator is on the list already. + if (SettingsView.IsVisible) + SettingsView.RefreshExecutables(); + }; _sceneryFilesTimer.Tick += async (_, _) => await LookAtSceneryFilesAsync(); Closed += (_, _) => _sceneryFilesTimer.Stop(); } @@ -237,6 +245,17 @@ public partial class MainWindow : Window win.ShowDialog(this); } + private void OnTabWithNothingFocused(object? sender, KeyEventArgs e) + { + if (FocusManager is not { } focus) + return; + + var next = KeyboardFocus.TabFromNowhere(e.Key, e.KeyModifiers, focus.GetFocusedElement(), this, + focus.FindFirstFocusableElement, focus.FindLastFocusableElement); + if (next is not null && next.Focus(NavigationMethod.Tab)) + e.Handled = true; + } + private void OnShortcutKey(object? sender, KeyEventArgs e) { // A cab-control binding in Settings is waiting for this very keypress. @@ -508,11 +527,34 @@ public partial class MainWindow : Window private const string SimulatorBuildGuide = "https://github.com/MaSzyna-EU07/maszyna#getting-started"; /// - /// Tells a user whose processor lacks AVX2 that the published simulator will - /// not run, and where the instructions for a build of their own are. + /// Tells a user whose processor lacks AVX2 that the simulator that would start will + /// not run. With a build without AVX2 in the folder, chosen away from by hand, the + /// notice offers to go back to the automatic choice, which takes it; with none, it + /// says what such a build is called and where the instructions for one's own are. /// - public async Task ShowCpuNoticeAsync() + public async Task ShowCpuNoticeAsync(string executable) { + var services = AppServices.Current; + if (services.Executables.NewestNoAvx2() is { } noAvx2) + { + var (useIt, quiet) = await MessageBox.ShowNotice( + this, string.Format(App.Loc["CpuNoAvx2Chosen"], Path.GetFileName(executable), noAvx2), + App.Loc["CpuNoAvx2Title"], App.Loc["CpuNoAvx2UseIt"], App.Loc["DontShowAgain"]); + if (useIt) + { + services.Settings.SelectExeAutomatically = true; + services.SettingsStore.Save(); + SettingsView.ReloadFromSettings(); + UpdateStartButton(); + } + if (quiet) + { + services.Settings.CpuNotice = false; + services.SettingsStore.Save(); + } + return; + } + var (open, silence) = await MessageBox.ShowNotice( this, string.Format(App.Loc["CpuNoAvx2"], SimulatorBuildGuide), App.Loc["CpuNoAvx2Title"], App.Loc["CpuNoAvx2Open"], App.Loc["DontShowAgain"]); diff --git a/StarterNG/Program.cs b/StarterNG/Program.cs index 2c1beca..aa0a8c8 100644 --- a/StarterNG/Program.cs +++ b/StarterNG/Program.cs @@ -10,12 +10,22 @@ namespace StarterNG; static class Program { + private static bool _softwareRender; + [STAThread] public static void Main(string[] args) { + // Ahead of everything that could draw: what lies beside the starter is the simulator's. + var graphics = SystemGraphicsLibraries.TakeOnWindows(); + graphics?.ServeTo(typeof(Win32PlatformOptions).Assembly); + + _softwareRender = SoftwareRender.AskedIn(args); + // Composition root first: everything below, including the crash handlers, // resolves its collaborators from this graph. AppServices.Initialize(); + if (graphics?.Note is { } note) + Diagnostics.Log(note); AppDomain.CurrentDomain.UnhandledException += (_, e) => { @@ -63,9 +73,13 @@ static class Program }; } + private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) => + _softwareRender ? SoftwareRender.ApplyTo(builder) : builder; + public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() .UsePlatformDetect() + .WithSoftwareRenderIfAsked() .WithInterFont() .WithDiagnosticsLogging() .AfterSetup(_ => LogUiExceptions()); diff --git a/StarterNG/SplashWindow.axaml b/StarterNG/SplashWindow.axaml index 0c7a4b3..bf148d4 100644 --- a/StarterNG/SplashWindow.axaml +++ b/StarterNG/SplashWindow.axaml @@ -2,6 +2,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:starterNg="clr-namespace:StarterNG" x:Class="StarterNG.SplashWindow" + Title="Starter MaSzyna" SystemDecorations="None" CanResize="False" ShowInTaskbar="True" @@ -18,6 +19,7 @@ TextTrimming="CharacterEllipsis" Text="{Binding [LoadingVehicles], Source={x:Static starterNg:App.Loc}}" /> diff --git a/StarterNG/StarterNG.csproj b/StarterNG/StarterNG.csproj index a8f2865..ca073c5 100644 --- a/StarterNG/StarterNG.csproj +++ b/StarterNG/StarterNG.csproj @@ -12,7 +12,7 @@ true - 1.5 + 1.6 Starter eu07.pl @@ -43,6 +43,10 @@ + + + + diff --git a/StarterNG/Styles/Carbon.axaml b/StarterNG/Styles/Carbon.axaml index b44937d..2f7d88f 100644 --- a/StarterNG/Styles/Carbon.axaml +++ b/StarterNG/Styles/Carbon.axaml @@ -17,6 +17,8 @@ + + @@ -77,7 +79,7 @@ Height="{StaticResource CarbonCheckSize}" VerticalAlignment="Center" Background="{StaticResource CarbonInputBg}" - BorderBrush="{StaticResource CarbonBorderLight}" + BorderBrush="{StaticResource CarbonInputBorder}" BorderThickness="1" CornerRadius="2"> - + @@ -187,7 +189,7 @@ MinHeight="{StaticResource CarbonControlHeight}" Padding="0" BorderThickness="1" - BorderBrush="{StaticResource CarbonBorderLight}" + BorderBrush="{StaticResource CarbonInputBorder}" Background="{StaticResource CarbonInputBg}" CornerRadius="2" HorizontalAlignment="Stretch" @@ -304,12 +306,14 @@ + diff --git a/StarterNG/Styles/Settings.axaml b/StarterNG/Styles/Settings.axaml index dc938c0..6e238bc 100644 --- a/StarterNG/Styles/Settings.axaml +++ b/StarterNG/Styles/Settings.axaml @@ -61,8 +61,10 @@ with no label hides PART_Label, and without this the column would collapse onto the key and every explanation would start at a different place again. --> + win.Close(); + close.IsDefault = true; + close.IsCancel = true; var footer = new StackPanel { diff --git a/StarterNG/Views/Depot.axaml b/StarterNG/Views/Depot.axaml index 09625f8..1f874e1 100644 --- a/StarterNG/Views/Depot.axaml +++ b/StarterNG/Views/Depot.axaml @@ -81,11 +81,12 @@ PointerWheelChanged="Combo_OnPointerWheel" SelectionChanged="ClassCombo_OnSelectionChanged" /> - @@ -126,7 +127,8 @@ BorderThickness="1" CornerRadius="2" Padding="6"> - + @@ -145,6 +147,7 @@ Content="{Binding [ShowAiVehicles], Source={x:Static starterNg:App.Loc}}" /> @@ -160,7 +163,8 @@ - + @@ -195,7 +199,7 @@ Background="{StaticResource CarbonPanelBg}" BorderBrush="{StaticResource CarbonBorderLight}" BorderThickness="1" CornerRadius="2" Padding="6"> - + @@ -213,7 +217,7 @@ Background="{StaticResource CarbonPanelBg}" BorderBrush="{StaticResource CarbonBorderLight}" BorderThickness="1" CornerRadius="2" Padding="6"> - + + diff --git a/StarterNG/Views/Depot.axaml.cs b/StarterNG/Views/Depot.axaml.cs index 5d3efe9..a17e2ba 100644 --- a/StarterNG/Views/Depot.axaml.cs +++ b/StarterNG/Views/Depot.axaml.cs @@ -369,6 +369,41 @@ public partial class Depot : UserControl // The cards are thrown away and rebuilt on every change, so a keyboard-driven // edit has to be handed its card back or focus escapes the strip. _cards.FocusSelectedCard(onlyIfRequested: true); + TellChange(); + } + + // The consist as it was last told, and whose it was. + private List _told = new(); + private Trainset? _toldTrainset; + + // While an undo or a redo loads the consist: the word said before what it changed. + private string? _restoreWord; + + /// + /// 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. + /// + private void TellChange() + { + var now = _consist.Select(item => new ConsistNarration.Unit( + string.Join(", ", item.Cars.Select(car => TrainsetDisplay.VehicleLabel(car))), item.Flipped)).ToList(); + var trainset = _consist.EditingTrainset; + bool same = trainset is not null && ReferenceEquals(trainset, _toldTrainset); + var before = _told; + _told = now; + _toldTrainset = trainset; + if (!same) + return; + + // A card moved or turned from the keyboard is focused again, and says its new place itself. + if (_restoreWord is null && before.Count == now.Count && consistStack.IsKeyboardFocusWithin) + return; + + string? said = ConsistNarration.Describe(before, now, _consist.VehicleCount, key => App.Loc[key]); + if (_restoreWord is not null) + said = string.Format(App.Loc[_restoreWord], said ?? string.Empty).Trim(); + Controls.Announcer.Say(this, said); } private void WriteBackToScenery() @@ -492,11 +527,11 @@ public partial class Depot : UserControl redoButton.IsEnabled = editing is not null && _history.CanRedo(editing); } - public void Undo() => Restore(_history.Undo); + public void Undo() => Restore(_history.Undo, "ConsistSaidUndone"); - public void Redo() => Restore(_history.Redo); + public void Redo() => Restore(_history.Redo, "ConsistSaidRedone"); - private void Restore(Func step) + private void Restore(Func step, string word) { if (_consist.EditingTrainset is not { } trainset || step(trainset, SelectedIndex()) is not { } state) @@ -504,6 +539,7 @@ public partial class Depot : UserControl trainset.Vehicles = state.Vehicles.ToList(); _restoring = true; + _restoreWord = word; try { _consist.LoadFrom(trainset, state.Selected); @@ -511,6 +547,7 @@ public partial class Depot : UserControl finally { _restoring = false; + _restoreWord = null; } } @@ -682,6 +719,8 @@ public partial class Depot : UserControl Foreground = new SolidColorBrush(Color.Parse("#E0A030")) }; ToolTip.SetTip(dot, App.Loc["ConsistUnsaved"]); + // Read as its meaning in the entry's name, not as "black circle". + Avalonia.Automation.AutomationProperties.SetName(dot, App.Loc["ConsistUnsaved"]); var row = new DockPanel(); DockPanel.SetDock(dot, Dock.Left); row.Children.Add(dot); diff --git a/StarterNG/Views/Depot/ConsistNarration.cs b/StarterNG/Views/Depot/ConsistNarration.cs new file mode 100644 index 0000000..054649e --- /dev/null +++ b/StarterNG/Views/Depot/ConsistNarration.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace StarterNG.Views; + +/// +/// 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. +/// +public static class ConsistNarration +{ + /// One position of the consist as it is told: what stands there, and whether it is turned. + public readonly record struct Unit(string Label, bool Turned); + + /// + /// The sentence for the change from to ; + /// null when nothing a listener would notice changed, such as a coupling or the crew. + /// + /// How many vehicles the consist has now, its units counted car by car. + /// The starter's texts by key. + public static string? Describe(IReadOnlyList before, IReadOnlyList after, int vehicles, + Func 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); + } + + /// How many units at the front and at the back stayed as they were. + private static (int Head, int Tail) Common(IReadOnlyList before, IReadOnlyList 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); + } + + /// A change that left as many units as there were: turned, moved, reordered or one replaced; or null. + private static string? SameCount(List gone, List come, int head, int count, Func 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 gone, List come, Func 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); + } + + /// The unit and the place it went to when one alone moved, or null. + private static (Unit Unit, int To)? MovedOne(List gone, List 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 units) => string.Join(", ", units.Select(u => u.Label)); +} diff --git a/StarterNG/Views/Depot/TextureMenuItems.cs b/StarterNG/Views/Depot/TextureMenuItems.cs index b54810e..0461a99 100644 --- a/StarterNG/Views/Depot/TextureMenuItems.cs +++ b/StarterNG/Views/Depot/TextureMenuItems.cs @@ -1,8 +1,10 @@ using System.IO; using Avalonia.Controls; using Avalonia.Input.Platform; +using StarterNG.Application; using StarterNG.Domain; using StarterNG.Domain.Vehicles; +using StarterNG.Infrastructure.Vehicles; namespace StarterNG.Views; @@ -17,13 +19,7 @@ internal static class TextureMenuItems if (TopLevel.GetTopLevel(owner)?.Clipboard is { } clipboard) await clipboard.SetTextAsync(Consist.Base(texture.Skinfile)); }); - menu.AddItem(App.Loc["OpenTextureFolder"], () => Infrastructure.Diagnostics.OpenOrReport(FolderOf(texture))); - } - - private static string FolderOf(VehicleTexture texture) - { - string dir = Path.Combine(Directory.GetCurrentDirectory(), "dynamic", - texture.Directory.Replace('/', Path.DirectorySeparatorChar).TrimEnd('\\', '/')); - return Directory.Exists(dir) ? dir : Path.Combine(Directory.GetCurrentDirectory(), texture.Directory); + menu.AddItem(App.Loc["OpenTextureFolder"], () => Infrastructure.Diagnostics.OpenOrReport( + Path.GetFullPath(TextureFolder.Of(AppServices.Current.Files, AppServices.Current.Paths, texture)))); } } diff --git a/StarterNG/Views/Depot/TextureRandomizerDialog.cs b/StarterNG/Views/Depot/TextureRandomizerDialog.cs index ec9efd8..1b9d862 100644 --- a/StarterNG/Views/Depot/TextureRandomizerDialog.cs +++ b/StarterNG/Views/Depot/TextureRandomizerDialog.cs @@ -77,6 +77,9 @@ public sealed class TextureRandomizerDialog FontSize = 12 }; + // Each box stands beside the choice it belongs to, which is no label a reader finds. + Avalonia.Automation.AutomationProperties.SetName(age, App.Loc["RandomizeTexturesRevDiff"]); + Avalonia.Automation.AutomationProperties.SetName(year, App.Loc["RandomizeTexturesVsYear"]); revDiff.IsCheckedChanged += (_, _) => age.IsEnabled = revDiff.IsChecked == true; vsYear.IsCheckedChanged += (_, _) => year.IsEnabled = vsYear.IsChecked == true; @@ -118,6 +121,8 @@ public sealed class TextureRandomizerDialog }; cancel.Classes.Add("Flat"); cancel.Click += (_, _) => win.Close(false); + ok.IsDefault = true; + cancel.IsCancel = true; win.Content = new StackPanel { diff --git a/StarterNG/Views/Depot/VehicleBrowser.cs b/StarterNG/Views/Depot/VehicleBrowser.cs index 31e4ae6..1904768 100644 --- a/StarterNG/Views/Depot/VehicleBrowser.cs +++ b/StarterNG/Views/Depot/VehicleBrowser.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; using Avalonia; +using Avalonia.Automation; using Avalonia.Controls; using Avalonia.Controls.Templates; using Avalonia.Input; @@ -59,6 +60,8 @@ public sealed class VehicleBrowser private DispatcherTimer? _searchTimer; + private readonly SearchResultsTeller _searchResults; + private Func? _categoryFilter; private string? _classFilter; @@ -81,6 +84,7 @@ public sealed class VehicleBrowser vehicleListBox.ContextRequested += List_OnContextRequested; + _searchResults = new SearchResultsTeller(searchBox, () => vehicleListBox.ItemCount); _searchTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(220) }; _searchTimer.Tick += (_, _) => { @@ -338,6 +342,7 @@ public sealed class VehicleBrowser Selected = null; miniPreview.Source = null; + miniPreview.ClearValue(AutomationProperties.NameProperty); addVehicleButton.IsEnabled = false; vehicleListBox.Items.Clear(); @@ -381,10 +386,12 @@ public sealed class VehicleBrowser public void VehicleListBox_OnSelectionChanged(object? sender, SelectionChangedEventArgs e) { - if (vehicleListBox.SelectedItem is ListBoxItem { Tag: VehicleTexture texture }) + if (vehicleListBox.SelectedItem is ListBoxItem { Tag: VehicleTexture texture } row) { Selected = texture; miniPreview.Source = _minis.Get(_db.ResolveMiniName(texture), MiniPreviewHeight); + // Under the mouse a reader hears which vehicle the picture shows. + AutomationProperties.SetName(miniPreview, ScreenReaderNames.TextOf(row.Content)); addVehicleButton.IsEnabled = true; SyncCombosTo(texture); @@ -397,6 +404,7 @@ public sealed class VehicleBrowser { Selected = null; miniPreview.Source = null; + miniPreview.ClearValue(AutomationProperties.NameProperty); addVehicleButton.IsEnabled = false; } } @@ -559,6 +567,7 @@ public sealed class VehicleBrowser if (_suppress || _searchTimer is null) return; _searchTimer.Stop(); _searchTimer.Start(); + _searchResults.Changed(); } public void HideArchivalCheck_OnChanged(object? sender, Avalonia.Interactivity.RoutedEventArgs e) @@ -578,12 +587,29 @@ public sealed class VehicleBrowser var set = _db.ResolveSet(texture); var browserTex = set is { Count: > 0 } ? set[0] : texture; - WhileSyncing(() => + KeepingKeyboardFocus(() => WhileSyncing(() => { ApplyFilters(VehicleInfo.CategoryOf(browserTex), VehicleInfo.ClassOf(browserTex)); Rebuild(); SelectListEntry(browserTex); - }); + })); + } + + /// + /// 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. + /// + private void KeepingKeyboardFocus(Action rebuild) + { + bool onAdd = addVehicleButton.IsFocused; + bool inList = vehicleListBox.IsKeyboardFocusWithin; + rebuild(); + + if (onAdd && addVehicleButton.IsEnabled) + addVehicleButton.Focus(NavigationMethod.Tab); + else if (onAdd || inList) + (vehicleListBox.SelectedItem as Control ?? vehicleListBox).Focus(NavigationMethod.Tab); } private void SyncCombosTo(VehicleTexture texture) @@ -591,7 +617,7 @@ public sealed class VehicleBrowser if (_syncingCombos || !ApplyFilters(VehicleInfo.CategoryOf(texture), VehicleInfo.ClassOf(texture))) return; - PostSyncing(() => { Rebuild(); SelectListEntry(texture); }); + PostSyncing(() => KeepingKeyboardFocus(() => { Rebuild(); SelectListEntry(texture); })); } private void WhileSyncing(Action work) diff --git a/StarterNG/Views/Depot/VehicleCards.cs b/StarterNG/Views/Depot/VehicleCards.cs index cf8929c..b399539 100644 --- a/StarterNG/Views/Depot/VehicleCards.cs +++ b/StarterNG/Views/Depot/VehicleCards.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.Linq; using Avalonia; +using Avalonia.Automation; +using Avalonia.Automation.Peers; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Layout; @@ -13,6 +15,7 @@ using Material.Icons.Avalonia; using StarterNG.Classes; using StarterNG.Domain; using StarterNG.Domain.Vehicles; +using StarterNG.Controls; namespace StarterNG.Views; @@ -146,6 +149,10 @@ public sealed class VehicleCards Focusable = true }; card.Classes.Add("ConsistCard"); + // The card shows pictures only; without a name a screen reader said nothing on it. + AutomationProperties.SetName(card, CardName(item, index)); + AutomationProperties.SetControlTypeOverride(card, AutomationControlType.ListItem); + AutomationProperties.SetIsControlElementOverride(card, true); card.GotFocus += (_, _) => Select(item, null); card.KeyDown += (_, e) => OnCardKey(card, item, e); card.PointerPressed += (_, e) => @@ -179,6 +186,11 @@ public sealed class VehicleCards return card; } + /// Its place in the consist and what it holds, as a screen reader says it. + private string CardName(ConsistItem item, int index) => + $"{index + 1}. {string.Join(", ", item.Cars.Select(car => CardCaption(item, car, index)))}" + + (item.Flipped ? $", {App.Loc["Reversed"]}" : string.Empty); + private string CardCaption(ConsistItem item, Dynamic car, int index) => TrainsetDisplay.VehicleLabel(car, head: index == 0 && ReferenceEquals(car, Consist.HeadCar(item)) && TrainsetDisplay.IsPowered(car)); @@ -411,12 +423,22 @@ public sealed class VehicleCards panel.Children.Add(apply); var flyout = new Flyout { Content = panel, Placement = PlacementMode.Top }; - apply.Click += (_, _) => + void Apply() { _consist.SetWagonNumber(car, (int)(num.Value ?? 0)); flyout.Hide(); + } + + apply.Click += (_, _) => Apply(); + // As the flyout for several vehicles does: typed into at once, Enter sets it. + num.KeyDown += (_, e) => + { + if (e.Key != Key.Enter) return; + e.Handled = true; + Apply(); }; flyout.ShowAt(anchor); + num.Focus(); } /// @@ -623,6 +645,10 @@ public sealed class VehicleCards btn.Content = glyph; btn.Foreground = new SolidColorBrush(Color.Parse(color)); + // "2" alone said nothing read aloud: the reader hears who rides in it. + int choice = CrewChoices.IndexOf(type); + AutomationProperties.SetName(btn, ScreenReaderNames.PickerText( + App.Loc["CrewLabel"], choice >= 0 ? App.Loc[CrewChoices.All[choice].Key] : glyph)); } /// @@ -668,7 +694,7 @@ public sealed class VehicleCards var crew = new MenuItem { Header = App.Loc["CrewLabel"] }; foreach (var (type, key) in CrewChoices.All) - crew.AddItem((item.Driver == type ? "● " : "○ ") + App.Loc[key], () => _consist.SetCrew(item, type)); + crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type))); menu.Items.Add(crew); // The member the panels show, not always the first car of a unit. diff --git a/StarterNG/Views/Depot/VehicleDetails.cs b/StarterNG/Views/Depot/VehicleDetails.cs index b87cb2a..1cd74e3 100644 --- a/StarterNG/Views/Depot/VehicleDetails.cs +++ b/StarterNG/Views/Depot/VehicleDetails.cs @@ -595,6 +595,9 @@ public sealed class VehicleDetails return Row(content: ready); var why = PanelNote(App.Loc["ConsistReadyOverridden"]); why.Margin = new Thickness(0); + // The reader is told it too, with the box, and not only by a text it may never come to. + Avalonia.Automation.AutomationProperties.SetHelpText(ready, + $"{App.Loc["ConsistReadyOverridden"]} {App.Loc["ConsistReadyDesc"]}"); return Row(content: new StackPanel { Spacing = 2, Children = { ready, why } }); } diff --git a/StarterNG/Views/Depot/Warehouse.cs b/StarterNG/Views/Depot/Warehouse.cs index fb4269b..1c9d927 100644 --- a/StarterNG/Views/Depot/Warehouse.cs +++ b/StarterNG/Views/Depot/Warehouse.cs @@ -116,8 +116,8 @@ public sealed class Warehouse } private MenuItem SortItem(PresetSort mode, string locKey) => - MenuItems.Item((PresetStore.SortMode == mode ? "● " : "○ ") + App.Loc[locKey], - () => { PresetStore.SortMode = mode; Refresh(); }); + MenuItems.Choice(App.Loc[locKey], PresetStore.SortMode == mode, + () => { PresetStore.SortMode = mode; Refresh(); }); /// Asks for a name at the button pressed, and says where the consist went. public void SaveCurrent(Control anchor) => diff --git a/StarterNG/Views/ExecutableList.cs b/StarterNG/Views/ExecutableList.cs new file mode 100644 index 0000000..3174ed7 --- /dev/null +++ b/StarterNG/Views/ExecutableList.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace StarterNG.Views; + +/// +/// The simulators offered in the settings after the folder was looked at again: a build +/// copied in while the starter runs joins the list, and what was chosen stays chosen, even +/// a file picked from elsewhere or one since removed - looking again never changes the choice. +/// +public static class ExecutableList +{ + /// The entries that follow "automatic", and the place of among them. + /// The simulators in the folder now, newest first. + /// The entry chosen, or null for "automatic" or nothing chosen yet. + /// Entries, and the index of the chosen one in them, -1 when is null. + public static (IReadOnlyList Entries, int Chosen) Refreshed(IReadOnlyList found, string? chosen) + { + var entries = found.ToList(); + if (chosen is null) + return (entries, -1); + + int at = entries.FindIndex(entry => string.Equals(entry, chosen, StringComparison.OrdinalIgnoreCase)); + if (at >= 0) + return (entries, at); + + entries.Add(chosen); + return (entries, entries.Count - 1); + } +} diff --git a/StarterNG/Views/IniChangesWindow.cs b/StarterNG/Views/IniChangesWindow.cs index 0af2bfe..3c7b323 100644 --- a/StarterNG/Views/IniChangesWindow.cs +++ b/StarterNG/Views/IniChangesWindow.cs @@ -46,6 +46,8 @@ internal static class IniChangesWindow var closeBtn = new Button { Content = App.Loc["Close"], MinWidth = 80 }; closeBtn.Classes.Add("Flat"); closeBtn.Click += (_, _) => win.Close(); + saveBtn.IsDefault = true; + closeBtn.IsCancel = true; body.Children.Add(MessageBox.ButtonRow(saveBtn, closeBtn)); win.Content = body; diff --git a/StarterNG/Views/KeyBindingsTab.cs b/StarterNG/Views/KeyBindingsTab.cs index 0670b56..9663ee1 100644 --- a/StarterNG/Views/KeyBindingsTab.cs +++ b/StarterNG/Views/KeyBindingsTab.cs @@ -1,12 +1,15 @@ using System; using System.Collections.Generic; using Avalonia; +using Avalonia.Automation; +using Avalonia.Automation.Peers; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Layout; using Avalonia.Media; using StarterNG.Classes; +using StarterNG.Controls; using StarterNG.Infrastructure; using KeyBinding = StarterNG.Classes.KeyBinding; @@ -34,6 +37,14 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) private KeyBinding? _capturing; private Button? _capturingButton; + // The row buttons of each binding on the list, so focus goes back to the row it + // left when the list is drawn anew after an edit. + private readonly Dictionary _rowButtons = new(); + + // The keys of the drawn keyboard that can be bound, in reading order, with the block + // and the row each lies in: the arrow keys walk them as they lie. + private readonly List<(Border Cap, int Block, int Row)> _caps = new(); + private readonly Dictionary _keyCells = new(StringComparer.OrdinalIgnoreCase); private bool _flyoutLoading; @@ -48,6 +59,7 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) private static readonly IBrush FgBrush = new SolidColorBrush(Color.Parse("#E6E8EA")); private static readonly IBrush FgDimBrush = new SolidColorBrush(Color.Parse("#9098A0")); private static readonly IBrush ConflictBrush = new SolidColorBrush(Color.Parse("#E06C5A")); + private static readonly IBrush KeyFocusBrush = new SolidColorBrush(Color.Parse("#41C400")); // The four combinations a key can be on. After the brushes: static fields start in text order. private static readonly (bool Shift, bool Ctrl, string SlotTextKey, IBrush Colour)[] ModifierSlots = @@ -151,11 +163,27 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) RedrawBindings(); } - private void BindingsEdited() + private void BindingsEdited(KeyBinding? focusRow = null) { KeyboardConfig.Instance.Dirty = true; Changed?.Invoke(); RedrawBindings(); + if (focusRow is not null) + FocusRow(focusRow); + } + + /// + /// Puts focus back on a binding's row once the list is drawn anew: it went with the + /// old row, and a keyboard user was left nowhere. + /// + private void FocusRow(KeyBinding binding) + { + if (!_rowButtons.TryGetValue(binding, out var row)) + return; + + // The key button, which says what the binding is now. + row.Combo.Focus(NavigationMethod.Tab); + row.Combo.BringIntoView(); } private void RedrawBindings() @@ -164,12 +192,16 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) RebuildKeyboard(); } + /// How many bindings the list shows, after the search. + public int ShownCount => _rowButtons.Count; + public void RebuildList() { if (_bindingListPanel is null) return; _bindingListPanel.Children.Clear(); + _rowButtons.Clear(); // The sidebar search box serves this list too - see Settings.ApplyFilter. string filter = search.Text?.Trim() ?? string.Empty; var conflicts = KeyboardConfig.Instance.ConflictingCombos(); @@ -253,6 +285,7 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) ToolTip.SetTip(comboButton, SimulatorUseText(b.Key, b.Shift, b.Ctrl, use)); else if (conflict) ToolTip.SetTip(comboButton, App.Loc["ConflictTooltip"]); + NameCombo(comboButton, b, comboButton.Content as string); comboButton.Click += (_, _) => StartCapture(b, comboButton); Grid.SetColumn(comboButton, 1); grid.Children.Add(comboButton); @@ -265,12 +298,15 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) }; clearButton.Classes.Add("Basic"); ToolTip.SetTip(clearButton, App.Loc["ClearBinding"]); + // Every row has one: the reader is told whose it is. + AutomationProperties.SetName(clearButton, ScreenReaderNames.PickerText(App.Loc["ClearBinding"], CommandLabel(b))); clearButton.Click += (_, _) => { CancelCapture(); b.Clear(); - BindingsEdited(); + BindingsEdited(b); }; + _rowButtons[b] = (comboButton, clearButton); Grid.SetColumn(clearButton, 2); grid.Children.Add(clearButton); @@ -289,22 +325,39 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) { if (_capturing is not null && _capturingButton is not null) - _capturingButton.Content = ComboText(_capturing); + Show(_capturingButton, _capturing, ComboText(_capturing)); _capturing = b; _capturingButton = button; - button.Content = App.Loc["PressKey"]; button.Focus(); + Show(button, b, App.Loc["PressKey"], say: true); } private void CancelCapture() { if (_capturing is not null && _capturingButton is not null) - _capturingButton.Content = ComboText(_capturing); + Show(_capturingButton, _capturing, ComboText(_capturing), say: _capturingButton.IsKeyboardFocusWithin); _capturing = null; _capturingButton = null; } + /// + /// Writes on a binding's button what it shows and names it after its command too, so + /// a reader hears "Odluźniacz: Num 4" and not a key alone. Said aloud when the change + /// happens under the focus, where nothing else would tell of it. + /// + private static void Show(Button button, KeyBinding b, string text, bool say = false) + { + button.Content = text; + NameCombo(button, b, text); + if (say) + Announcer.Say(button, text); + } + + private static void NameCombo(Button button, KeyBinding b, string? shown) => + AutomationProperties.SetName(button, ScreenReaderNames.PickerText( + CommandLabel(b), b.IsAssigned || shown != ComboText(b) ? shown : App.Loc["KbUnassigned"])); + public void OnKeyDown(object? sender, KeyEventArgs e) { if (_capturing is null) @@ -333,18 +386,19 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) { // Bound here it would never fire: the wait for a key goes on. if (_capturingButton is not null) - _capturingButton.Content = string.Format(App.Loc["KbTaken"], App.Loc[taken.TextKey]); + Show(_capturingButton, _capturing, string.Format(App.Loc["KbTaken"], App.Loc[taken.TextKey]), say: true); e.Handled = true; return; } // As the key flyout does: the combination moves here, not doubled up. - KeyboardConfig.Instance.Put(_capturing, token, shift, ctrl); + var bound = _capturing; + KeyboardConfig.Instance.Put(bound, token, shift, ctrl); e.Handled = true; _capturing = null; _capturingButton = null; - BindingsEdited(); + BindingsEdited(bound); } private void RebuildKeyboard() @@ -353,13 +407,16 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) return; _keyCells.Clear(); + _caps.Clear(); _keyboardPanel.Children.Clear(); + // Tab reaches the keyboard once; the arrow keys walk it from there. + KeyboardNavigation.SetTabNavigation(_keyboardPanel, KeyboardNavigationMode.Once); var states = ComputeKeyStates(); var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 14 }; - row.Children.Add(BuildKeyBlock(KeyMap.MainBlock, states)); - row.Children.Add(BuildKeyBlock(KeyMap.NavBlock, states)); - row.Children.Add(BuildKeyBlock(KeyMap.NumpadBlock, states)); + row.Children.Add(BuildKeyBlock(KeyMap.MainBlock, states, 0)); + row.Children.Add(BuildKeyBlock(KeyMap.NavBlock, states, 1)); + row.Children.Add(BuildKeyBlock(KeyMap.NumpadBlock, states, 2)); _keyboardPanel.Children.Add(row); } @@ -372,24 +429,27 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) content.Children.RemoveAt(0); content.Children.Insert(0, BuildKeyBackground(token, states)); states.TryGetValue(token, out var state); - ToolTip.SetTip(content, BuildKeyTooltip(token, state)); + string tip = BuildKeyTooltip(token, state); + ToolTip.SetTip(content, tip); + if (content.Parent is Border cap) + NameCap(cap, tip); } } - private Control BuildKeyBlock(KeyCap[][] rows, Dictionary states) + private StackPanel BuildKeyBlock(KeyCap[][] rows, Dictionary states, int blockIndex) { var block = new StackPanel { Spacing = KeyGap, VerticalAlignment = VerticalAlignment.Top }; - foreach (var rowCaps in rows) + for (int r = 0; r < rows.Length; r++) { var rowPanel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = KeyGap }; - foreach (var cap in rowCaps) - rowPanel.Children.Add(BuildKeyCap(cap, states)); + foreach (var cap in rows[r]) + rowPanel.Children.Add(BuildKeyCap(cap, states, blockIndex, r)); block.Children.Add(rowPanel); } return block; } - private Control BuildKeyCap(KeyCap cap, Dictionary states) + private Border BuildKeyCap(KeyCap cap, Dictionary states, int blockIndex, int rowIndex) { double width = cap.Width * KeyUnit + (cap.Width - 1) * KeyGap; var content = new Grid { Width = width, Height = KeyHeight }; @@ -438,14 +498,84 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }); - ToolTip.SetTip(content, BuildKeyTooltip(token, st)); + string tip = BuildKeyTooltip(token, st); + ToolTip.SetTip(content, tip); keyBorder.Cursor = new Cursor(StandardCursorType.Hand); keyBorder.PointerPressed += (_, _) => ShowKeyFlyout(token, keyBorder); + // Reached and opened from the keyboard as well, and read as the button it is. + keyBorder.Focusable = true; + keyBorder.Classes.Add("KeyCap"); + AutomationProperties.SetControlTypeOverride(keyBorder, AutomationControlType.Button); + AutomationProperties.SetIsControlElementOverride(keyBorder, true); + NameCap(keyBorder, tip); + keyBorder.KeyDown += (_, e) => OnCapKey(keyBorder, token, e); + // The ring the theme gives focus, drawn here: the key clips anything outside it. + keyBorder.GotFocus += (_, _) => keyBorder.BorderBrush = KeyFocusBrush; + keyBorder.LostFocus += (_, _) => keyBorder.BorderBrush = KeyBorderBrush; + _caps.Add((keyBorder, blockIndex, rowIndex)); _keyCells[token] = content; return keyBorder; } + // The tooltip says the key and what is on it, one thing a line; read as one sentence. + private static void NameCap(Border cap, string tip) => + AutomationProperties.SetName(cap, tip.Replace("\n", ", ")); + + private void OnCapKey(Border cap, string token, KeyEventArgs e) + { + int at = _caps.FindIndex(c => ReferenceEquals(c.Cap, cap)); + if (at < 0) + return; + + if (e.Key is Key.Enter or Key.Space) + { + ShowKeyFlyout(token, cap); + e.Handled = true; + return; + } + + Border? next; + switch (e.Key) + { + case Key.Left: next = at > 0 ? _caps[at - 1].Cap : null; break; + case Key.Right: next = at < _caps.Count - 1 ? _caps[at + 1].Cap : null; break; + case Key.Home: next = _caps[0].Cap; break; + case Key.End: next = _caps[^1].Cap; break; + case Key.Up: next = CapNextRow(at, -1); break; + case Key.Down: next = CapNextRow(at, 1); break; + default: return; + } + + next?.Focus(NavigationMethod.Directional); + e.Handled = true; + } + + /// The key in the next row up or down of the same block that lies nearest over or under this one. + private Border? CapNextRow(int at, int step) + { + var (cap, block, row) = _caps[at]; + if (_keyboardPanel is null || cap.TranslatePoint(new Point(cap.Bounds.Width / 2, 0), _keyboardPanel) is not { } from) + return null; + + Border? best = null; + double nearest = double.MaxValue; + foreach (var (other, otherBlock, otherRow) in _caps) + { + if (otherBlock != block || otherRow != row + step + || other.TranslatePoint(new Point(other.Bounds.Width / 2, 0), _keyboardPanel) is not { } to) + continue; + + double distance = Math.Abs(to.X - from.X); + if (distance < nearest) + { + nearest = distance; + best = other; + } + } + return best; + } + private Control BuildKeyBackground(string token, Dictionary states) { states.TryGetValue(token.ToLowerInvariant(), out var state); @@ -545,6 +675,8 @@ internal sealed class KeyBindingsTab(Grid host, TextBox search) Margin = new Thickness(0, 4), HorizontalAlignment = HorizontalAlignment.Stretch }; + // Its label is a swatch and a text in a panel, which a reader does not take for one. + AutomationProperties.SetName(cb, KeyMap.ComboText(token, shift, ctrl)); if (KeyMap.SimulatorUse(token, shift, ctrl) is { } use) { ToolTip.SetTip(cb, SimulatorUseText(token, shift, ctrl, use)); diff --git a/StarterNG/Views/LogAndToolsWindow.cs b/StarterNG/Views/LogAndToolsWindow.cs index 0c0793d..ea8e462 100644 --- a/StarterNG/Views/LogAndToolsWindow.cs +++ b/StarterNG/Views/LogAndToolsWindow.cs @@ -34,6 +34,7 @@ public sealed class LogAndToolsWindow : Window WindowStartupLocation = WindowStartupLocation.CenterOwner; var tabs = new TabControl(); + Avalonia.Automation.AutomationProperties.SetName(tabs, App.Loc["LogAndTools"]); tabs.Items.Add(new TabItem { Header = App.Loc["AdvLogPage"], Content = BuildLogPage() }); tabs.Items.Add(new TabItem { Header = App.Loc["Tools"], Content = BuildToolsPage() }); @@ -47,6 +48,7 @@ public sealed class LogAndToolsWindow : Window }; close.Classes.Add("Accent"); close.Click += (_, _) => Close(); + close.IsCancel = true; var root = new DockPanel { Margin = new Avalonia.Thickness(10) }; DockPanel.SetDock(close, Dock.Bottom); diff --git a/StarterNG/Views/MenuItems.cs b/StarterNG/Views/MenuItems.cs index 4e83816..6a6182d 100644 --- a/StarterNG/Views/MenuItems.cs +++ b/StarterNG/Views/MenuItems.cs @@ -15,6 +15,18 @@ internal static class MenuItems return item; } + /// + /// One of a set of entries of which one is chosen, marked as a radio entry. A dot + /// written before the text was read out as "black circle" and told no state. + /// + public static MenuItem Choice(string header, bool chosen, Action run) + { + var item = Item(header, run); + item.ToggleType = MenuItemToggleType.Radio; + item.IsChecked = chosen; + return item; + } + /// The entry at the end of a menu or a submenu. public static MenuItem AddItem(this ItemsControl menu, object header, Action run, bool enabled = true, KeyGesture? gesture = null) diff --git a/StarterNG/Views/MessageBox.cs b/StarterNG/Views/MessageBox.cs index 1067562..71346d3 100644 --- a/StarterNG/Views/MessageBox.cs +++ b/StarterNG/Views/MessageBox.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using Avalonia.Automation; using Avalonia.Controls; using Avalonia.Layout; using Avalonia.Media; @@ -26,6 +27,13 @@ public static class MessageBox "Accent", 80, () => { yes = true; win.Close(); }); var noBtn = DialogButton(noText ?? App.Loc["No"], "Flat", 80, () => win.Close()); noBtn.IsVisible = buttons != MessageBoxButtons.Ok; + // Enter answers, Esc declines - or only closes, where OK is all there is. + yesBtn.IsDefault = true; + if (buttons == MessageBoxButtons.Ok) + yesBtn.IsCancel = true; + else + noBtn.IsCancel = true; + ReadMessage(win, yesBtn, message); win.Content = new StackPanel { @@ -85,6 +93,9 @@ public static class MessageBox var okBtn = DialogButton(App.Loc["Ok"], "Flat", 80, () => win.Close()); var silence = new CheckBox { Content = silenceText, VerticalAlignment = VerticalAlignment.Center }; + actBtn.IsDefault = true; + okBtn.IsCancel = true; + ReadMessage(win, actBtn, message); win.Content = new StackPanel { @@ -108,6 +119,16 @@ public static class MessageBox return (act, silence.IsChecked == true); } + /// + /// The message is told with the window and with the button focus opens on: a + /// screen reader said only the title, and the question it asked went unheard. + /// + internal static void ReadMessage(Window win, Control first, string message) + { + AutomationProperties.SetHelpText(win, message); + AutomationProperties.SetHelpText(first, message); + } + /// A dialog over its owner, as tall as what it holds, not to be resized. internal static Window FixedDialog(string title, double width) => new() { diff --git a/StarterNG/Views/RulesWindow.cs b/StarterNG/Views/RulesWindow.cs index 8660cfe..1c1215c 100644 --- a/StarterNG/Views/RulesWindow.cs +++ b/StarterNG/Views/RulesWindow.cs @@ -80,6 +80,7 @@ public sealed class RulesWindow : Window }; cancel.Classes.Add("Flat"); cancel.Click += (_, _) => Close(); + cancel.IsCancel = true; var footer = new StackPanel { diff --git a/StarterNG/Views/Scenarios.axaml b/StarterNG/Views/Scenarios.axaml index 99a4a19..7e733dd 100644 --- a/StarterNG/Views/Scenarios.axaml +++ b/StarterNG/Views/Scenarios.axaml @@ -4,6 +4,7 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:starterNg="clr-namespace:StarterNG" xmlns:infra="clr-namespace:StarterNG.Infrastructure" + xmlns:ctl="clr-namespace:StarterNG.Controls" xmlns:materialIcons="clr-namespace:Material.Icons.Avalonia;assembly=Material.Icons.Avalonia" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" x:Class="StarterNG.Views.Scenarios" @@ -33,6 +34,7 @@ IsCheckedChanged="ArchivalSwitch_OnChanged" Content="{Binding [HideArchivalSceneries], Source={x:Static starterNg:App.Loc}}" /> @@ -49,7 +51,7 @@ - @@ -70,13 +72,14 @@ - - + @@ -108,11 +111,11 @@ Foreground="{StaticResource CarbonFgDim}" Text="{Binding [Date], Source={x:Static starterNg:App.Loc}}" /> - - @@ -130,7 +133,7 @@ Foreground="{StaticResource CarbonFgDim}" Text="{Binding [Time], Source={x:Static starterNg:App.Loc}}" /> - - @@ -162,8 +165,8 @@ - - diff --git a/StarterNG/Views/Scenarios.axaml.cs b/StarterNG/Views/Scenarios.axaml.cs index eb00a93..326a283 100644 --- a/StarterNG/Views/Scenarios.axaml.cs +++ b/StarterNG/Views/Scenarios.axaml.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Avalonia; +using Avalonia.Automation; using Avalonia.Animation; using Avalonia.Controls; using Avalonia.Input; @@ -17,6 +18,7 @@ using Avalonia.Media.Imaging; using Avalonia.Threading; using Avalonia.VisualTree; using StarterNG.Classes; +using StarterNG.Controls; using StarterNG.Domain; using StarterNG.Application; using StarterNG.Domain.Sceneries; @@ -99,9 +101,9 @@ public partial class Scenarios : UserControl sceneryList.Items.Add(ToTreeItem(node, expandGroups)); } - private TreeViewItem ToTreeItem(SceneryTreeNode node, bool expandGroups) + private ExpandableTreeViewItem ToTreeItem(SceneryTreeNode node, bool expandGroups) { - var item = new TreeViewItem + var item = new ExpandableTreeViewItem { Header = node.IsGroup ? node.Label : SceneryHeader(node.Label, Sceneries[node.SceneryIndex]), Tag = node.IsGroup ? null : node.SceneryIndex, @@ -409,6 +411,8 @@ public partial class Scenarios : UserControl sceneryDescription.Text = scenery.LocalizedDescription(AppServices.Current.SceneryTexts); string? imagePath = AppServices.Current.SceneryImages.Resolve(scenery); + // Under the mouse a reader hears what the picture is of. + AutomationProperties.SetName(sceneryImage, $"{App.Loc["SceneryImage"]}: {scenery.Name}"); if (imagePath is not null) { try @@ -492,20 +496,18 @@ public partial class Scenarios : UserControl btn.Classes.Add("Flat"); ToolTip.SetTip(btn, att.FilePath); // A button that does nothing is no way to say the file is not there. - btn.IsEnabled = File.Exists(Path.GetFullPath(att.FilePath)); + btn.IsEnabled = AppServices.Current.Attachments.Resolve(att) is not null; ToolTip.SetShowOnDisabled(btn, true); - btn.Click += (_, _) => OpenAttachment(att.FilePath); + btn.Click += (_, _) => OpenAttachment(att); attachmentsPanel.Children.Add(btn); } } - private static void OpenAttachment(string relativePath) + private static void OpenAttachment(SceneryAttachment attachment) { - string full = Path.GetFullPath(relativePath); - if (!File.Exists(full)) - full = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), relativePath)); - if (!File.Exists(full)) + if (AppServices.Current.Attachments.Resolve(attachment) is not { } found) return; + string full = Path.GetFullPath(found); try { Process.Start(new ProcessStartInfo(full) { UseShellExecute = true }); @@ -761,6 +763,8 @@ public partial class Scenarios : UserControl { weatherTempLabel.Text = $"{(int)weatherTemp.Value} °C"; weatherFogLabel.Text = FogScale2(FogScale.ToMetres(weatherFog.Value)); + weatherTemp.ValueText = weatherTempLabel.Text; + weatherFog.ValueText = weatherFogLabel.Text; weatherDayDate.Text = string.Format(LanguageCulture, App.Loc["DayOfYear"], SelectedDayOfYear()); weatherRestore.IsEnabled = _currentScenery?.Weather.Changed ?? false; @@ -833,6 +837,7 @@ public partial class Scenarios : UserControl { var now = DateTime.Now; weatherTime.SelectedTime = new TimeSpan(now.Hour, now.Minute, 0); + Announcer.Say(this, ScreenReaderNames.PickerText(App.Loc["Time"], ScreenReaderNames.TimeText(weatherTime.SelectedTime))); } private void WeatherRestore_OnClick(object? sender, RoutedEventArgs e) @@ -840,8 +845,18 @@ public partial class Scenarios : UserControl if (_currentScenery is null) return; _currentScenery.Weather.Restore(); ShowWeather(_currentScenery); + Announcer.Say(this, WeatherSummary()); } + /// The weather as a reader hears it once put back: every field and its value. + private string WeatherSummary() => string.Join(", ", + ScreenReaderNames.PickerText(App.Loc["Date"], ScreenReaderNames.DateText(weatherDate.SelectedDate, weatherDate.YearVisible)), + ScreenReaderNames.PickerText(App.Loc["Season"], ScreenReaderNames.TextOf(weatherSeason.SelectedItem)), + ScreenReaderNames.PickerText(App.Loc["Time"], ScreenReaderNames.TimeText(weatherTime.SelectedTime)), + ScreenReaderNames.PickerText(App.Loc["Temperature"], weatherTempLabel.Text), + ScreenReaderNames.PickerText(App.Loc["Visibility"], weatherFogLabel.Text), + ScreenReaderNames.PickerText(App.Loc["Overcast"], ScreenReaderNames.TextOf(weatherOvercast.SelectedItem))); + private static TimeSpan? ParseTime(string? text) { if (string.IsNullOrWhiteSpace(text)) diff --git a/StarterNG/Views/Settings.axaml b/StarterNG/Views/Settings.axaml index af447a6..1e4886b 100644 --- a/StarterNG/Views/Settings.axaml +++ b/StarterNG/Views/Settings.axaml @@ -22,7 +22,7 @@ TextTrimming="LeadingCharacterEllipsis" /> - +