diff --git a/Eu07.BlackBox.Views/BlackBoxStrings.cs b/Eu07.BlackBox.Views/BlackBoxStrings.cs index 645599d..1d9d8c4 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 physics logs on.", @@ -295,6 +299,10 @@ public sealed class DefaultBlackBoxStrings : IBlackBoxStrings ["LiveTip"] = "Co 2 sekundy doczytuje to, co symulator dopisał do pliku", ["Play"] = "Odtwarzaj", ["Pause"] = "Pauza", + ["PlaySpeed"] = "Prędkość odtwarzania", + ["TimelineHelp"] = "Strzałki przesuwają o 10 sekund, z Ctrl o minutę, Page Up i Page Down o dziesięć minut, Home i End na początek i koniec.", + ["TimetableHelp"] = "Strzałki w górę i w dół przechodzą po stacjach, Enter przenosi do chwili, gdy pociąg tam był.", + ["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.", ["Follow"] = "Śledź pociąg", ["Fit"] = "Cała mapa", ["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną razem z logami fizyki.", 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 f896579..03388ec 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; @@ -36,6 +38,36 @@ public sealed class CabPanel : Control { ClipToBounds = true; Height = 696; + // Reached with Tab, where a screen reader reads what the panel shows. + Focusable = true; + } + + // What the panel showed when last drawn, a line a figure, as a screen reader is told it. + private List? _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(); @@ -62,6 +94,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; @@ -70,95 +118,150 @@ public sealed class CabPanel : Control if (_recording is not { } recording || recording.CabAt(_time) is not { } s || _time - s.Time > 1.5) { context.DrawText(MapView.Text(Strings["CabNoData"], Palette.DimText, 12), new Point(Pad, 40)); + Say(Strings["CabNoData"]); return; } Measure(recording); var culture = CultureInfo.CurrentCulture; - var extra = s.Extra; - // The vehicle at the left; who drives, from which cab, at the right. + DrawHeader(context, recording.Vehicle(s.Vehicle)?.Name ?? "", s, right); + DrawSpeed(context, s, width, right, culture); + DrawControls(context, s, width, right, culture); + double y = DrawBrakes(context, s, width, right, culture); + + // The traction at the left, as fits what drives the vehicle; the lights of both ends of the train at the right. + double half = Pad + width / 2; + double driveTop = y + BrakeRow + 4; + double top = Section(context, Strings["CabSectionDrive"], Pad, driveTop, half - 10); + Section(context, Strings["CabLights"], half + 4, driveTop, right); + DrawDrive(context, s, top, half - 10 - Pad, culture); + DrawLights(context, s, new Rect(half, top, right - half, 0), culture); + + top = DrawDevices(context, s, new Rect(Pad, top + 3 * DriveRow + 6, width, size.Height), culture); + DrawDoors(context, s, top, width, size.Height); + } + + private const double BrakeRow = 17; + + /// 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"); context.DrawText(MapView.Text("km/h", Palette.DimText, 12), new Point(Pad + speed.Width + 4, 24 + speed.Height - 21)); double gaugeX = Pad + Math.Max(150, width * 0.42); if (s.AiValid) { using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40))) { - context.DrawText(MapView.Text(string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh), Palette.Target, 12), new Point(Pad, 76)); + string target = string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh); + context.DrawText(MapView.Text(target, Palette.Target, 12), new Point(Pad, 76)); + Say(target); if (s.Ai.HasNextLimit) - context.DrawText(MapView.Text(string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance), Palette.Limit, 11), - new Point(Pad, 93)); + { + string limit = string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance); + Say(limit); + context.DrawText(MapView.Text(limit, Palette.Limit, 11), new Point(Pad, 93)); + } } } double gaugeWidth = right - gaugeX; Balance(context, Strings["CabAcceleration"], s.Acceleration, 1.5, gaugeX, 34, gaugeWidth); Balance(context, Strings["CabLateral"], s.LateralAcceleration, 1.5, gaugeX, 70, gaugeWidth); + } - // The controllers. + private static IBrush SpeedBrush(SpeedJudgement judgement) => judgement switch + { + SpeedJudgement.Over => Palette.Bad, + SpeedJudgement.Slightly => Palette.Warn, + _ => Palette.Text + }; + + /// 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)), @@ -166,14 +269,9 @@ public sealed class CabPanel : Control }) { DrawFace(context, lights, new Point(half + 4 + 17, row + 15)); - // the end, and under it the signal it shows: green as it is to be (with the lamps the vehicle has), - // red otherwise with the one it is to show - var shown = HeadCodes.Of(lights); - var text = HeadCodes.NoLamps(equipped) ? Strings["CabLightsNone"] - : isRight == false && required is { } want - ? string.Format(culture, Strings["CabLightsWant"], HeadCodes.Name(shown), HeadCodes.Name(want)) - : isRight == true && required is { } met ? HeadCodes.Name(met) : HeadCodes.Name(shown); - var brush = isRight is null ? Palette.DimText : isRight.Value ? Palette.Good : Palette.Bad; + string text = LightsText(HeadCodes.Of(lights), HeadCodes.NoLamps(equipped), required, isRight, culture); + IBrush brush = isRight switch { null => Palette.DimText, true => Palette.Good, false => Palette.Bad }; + Say($"{Strings[key]}: {text}"); using (context.PushClip(new Rect(half + 44, row, right - half - 44, 28))) { context.DrawText(MapView.Text(Strings[key], Palette.DimText, 10), new Point(half + 46, row)); @@ -181,9 +279,24 @@ public sealed class CabPanel : Control } row += 27; } + } - // The devices, in three groups side by side: lit as their lamps are in the cab, the ones off faint. - top = Section(context, Strings["CabSectionDevices"], Pad, top + 3 * DriveRow + 6, right); + private string LightsText(HeadCode shown, bool noLamps, HeadCode? required, bool? isRight, CultureInfo culture) + { + if (noLamps) + return Strings["CabLightsNone"]; + if (isRight == false && required is { } want) + return string.Format(culture, Strings["CabLightsWant"], HeadCodes.Name(shown), HeadCodes.Name(want)); + return isRight == true && required is { } met ? HeadCodes.Name(met) : HeadCodes.Name(shown); + } + + /// 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++) @@ -194,33 +307,42 @@ public sealed class CabPanel : Control } // each group as wide as its longest name, what is left shared between them double spare = (width - widths.Sum()) / groups.Length; - double x = Pad, bottom = top; + double x = area.X, bottom = top; for (int g = 0; g < groups.Length; g++) { double groupWidth = Math.Max(20, widths[g] + spare); - using (context.PushClip(new Rect(x, top, groupWidth, size.Height - top))) - { - context.DrawText(MapView.Text(Strings[groups[g].Title], Palette.DimText, 10, FontWeight.SemiBold), new Point(x, top)); - double lampY = top + 16; - foreach (var (text, brush) in groups[g].Lamps) - { - Lamp(context, text, brush, x, lampY); - lampY += LampRow; - } - bottom = Math.Max(bottom, lampY); - } + using (context.PushClip(new Rect(x, top, groupWidth, height - top))) + bottom = Math.Max(bottom, DrawGroup(context, groups[g], x, top)); x += groupWidth; } + return Math.Max(bottom, top + 16 + 9 * LampRow) + 6; + } - // The doors under them, in two columns: open, permitted, the departure signal, the steps and the lock. - top = Math.Max(bottom, top + 16 + 9 * LampRow) + 6; + /// 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); double doorColumn = width / DoorColumns; for (int i = 0; i < doors.Length; i++) { double doorX = Pad + i % DoorColumns * doorColumn; - using (context.PushClip(new Rect(doorX, top, doorColumn, size.Height - top))) + using (context.PushClip(new Rect(doorX, top, doorColumn, height - top))) Lamp(context, doors[i].Text, doors[i].Lit, doorX, top + 16 + i / DoorColumns * LampRow); } } @@ -279,6 +401,7 @@ public sealed class CabPanel : Control break; default: context.DrawText(MapView.Text(Strings["CabNoDrive"], Palette.DimText, 11), new Point(Pad, top + 2)); + Say(Strings["CabNoDrive"]); return; } double column = width / 2; @@ -321,8 +444,9 @@ public sealed class CabPanel : Control } /// 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; @@ -370,8 +494,9 @@ public sealed class CabPanel : Control _measured = recording.Revision; } - private static void Value(DrawingContext context, string label, string value, double x, double y, IBrush? brush = null) + private void Value(DrawingContext context, string label, string value, double x, double y, IBrush? brush = null) { + Say($"{label}: {value}"); context.DrawText(MapView.Text(label, Palette.DimText, 10), new Point(x, y)); context.DrawText(MapView.Text(value, brush ?? Palette.Text, 14, FontWeight.SemiBold), new Point(x, y + 13)); } @@ -387,9 +512,10 @@ public sealed class CabPanel : Control } /// 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; @@ -408,9 +534,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)); @@ -455,8 +582,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); @@ -564,4 +694,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/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/Palette.cs b/Eu07.BlackBox.Views/Palette.cs index 91319b3..6dae8b5 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. 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..f58cdd3 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; 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/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 2a203ad..6d5c6d8 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 += (_, _) => @@ -237,6 +239,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. 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 63f062d..ca073c5 100644 --- a/StarterNG/StarterNG.csproj +++ b/StarterNG/StarterNG.csproj @@ -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/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/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 30818b4..f2cda95 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 { @@ -56,6 +64,9 @@ public static class MessageBox var okBtn = DialogButton(App.Loc["Ok"], "Flat", 80, () => win.Close()); var silence = new CheckBox { Content = silenceText, VerticalAlignment = VerticalAlignment.Center }; + actBtn.IsDefault = true; + okBtn.IsCancel = true; + ReadMessage(win, actBtn, message); win.Content = new StackPanel { @@ -79,6 +90,16 @@ public static class MessageBox return (act, silence.IsChecked == true); } + /// + /// 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 4c0643f..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 @@ -759,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; @@ -831,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) @@ -838,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 f6cd705..73fc382 100644 --- a/StarterNG/Views/Settings.axaml +++ b/StarterNG/Views/Settings.axaml @@ -22,7 +22,7 @@ TextTrimming="LeadingCharacterEllipsis" /> - +