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..88a8f09 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,6 +118,7 @@ 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); @@ -84,6 +133,10 @@ public sealed class CabPanel : Control : s.Driving == Driver.Ai ? (Strings["CabDriverAi"], Palette.Autopilot) : (Strings["CabDriverUser"], Palette.UserTrain); chipX -= ChipLeft(context, driverText, driverBrush, chipX, 4) + 10; + Say(recording.Vehicle(s.Vehicle)?.Name ?? ""); + Say(driverText); + if (s.CabEnd != 0) + Say(Strings[s.CabEnd > 0 ? "CabEndFront" : "CabEndRear"]); 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)); @@ -92,6 +145,7 @@ public sealed class CabPanel : Control 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); context.DrawText(speed, new Point(Pad, 24)); + Say($"{s.AbsSpeedKmh.ToString("0", culture)} 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) @@ -99,6 +153,9 @@ public sealed class CabPanel : Control 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)); + Say(string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh)); + if (s.Ai.HasNextLimit) + Say(string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance)); 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)); @@ -174,6 +231,7 @@ public sealed class CabPanel : Control ? 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; + 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)); @@ -201,6 +259,7 @@ public sealed class CabPanel : Control 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)); + Say(Strings[groups[g].Title]); double lampY = top + 16; foreach (var (text, brush) in groups[g].Lamps) { @@ -215,6 +274,7 @@ public sealed class CabPanel : Control // 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; 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++) @@ -279,6 +339,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 +382,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 +432,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 +450,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, string label, float value, double scale, double? mark, string text, + IBrush brush, double x, double y, double width) { + 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 +472,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 +520,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); 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/ConsistNarrationTests.cs b/StarterNG.Tests/ConsistNarrationTests.cs new file mode 100644 index 0000000..dd657c2 --- /dev/null +++ b/StarterNG.Tests/ConsistNarrationTests.cs @@ -0,0 +1,101 @@ +using StarterNG.Views; +using Unit = StarterNG.Views.ConsistNarration.Unit; + +namespace StarterNG.Tests; + +public class ConsistNarrationTests +{ + // Each text shows its key and its arguments, so a test sees which sentence was picked and with what. + private static string Loc(string key) => key switch + { + "ConsistSaidEmpty" => "empty", + "ConsistSaidAdded" => "added {0} at {1}/{2}", + "ConsistSaidRemoved" => "removed {0}, {1} left", + "ConsistSaidTurned" => "turned {0}", + "ConsistSaidUnturned" => "unturned {0}", + "ConsistSaidTurnedMany" => "turned {0}", + "ConsistSaidMoved" => "moved {0} to {1}/{2}", + "ConsistSaidReordered" => "reordered", + "ConsistSaidReplaced" => "replaced {0} with {1}", + "ConsistSaidChangedMany" => "changed {0}, {1} now", + _ => throw new KeyNotFoundException(key) + }; + + private static Unit[] Units(params string[] labels) => + labels.Select(l => new Unit(l.TrimEnd('^'), l.EndsWith('^'))).ToArray(); + + private static string? Say(string[] before, string[] after, int? vehicles = null) => + ConsistNarration.Describe(Units(before), Units(after), vehicles ?? after.Length, Loc); + + [Fact] + public void Nothing_changed_says_nothing() => + Assert.Null(Say(["EU07", "Bdhpumn"], ["EU07", "Bdhpumn"])); + + [Fact] + public void An_empty_consist_staying_empty_says_nothing() => + Assert.Null(Say([], [])); + + [Fact] + public void Clearing_the_consist_says_it_is_empty() => + Assert.Equal("empty", Say(["EU07", "Bdhpumn"], [])); + + [Fact] + public void A_vehicle_added_at_the_end_is_named_with_its_place() => + Assert.Equal("added Bdhpumn at 2/2", Say(["EU07"], ["EU07", "Bdhpumn"])); + + [Fact] + public void A_vehicle_added_in_the_middle_is_named_with_its_place() => + Assert.Equal("added WRmnouz at 2/3", Say(["EU07", "Bdhpumn"], ["EU07", "WRmnouz", "Bdhpumn"])); + + [Fact] + public void Two_vehicles_added_at_once_are_both_named() => + Assert.Equal("added A, B at 1/3", Say(["EU07"], ["A", "B", "EU07"])); + + [Fact] + public void A_removed_vehicle_is_named_with_the_count_left() => + Assert.Equal("removed WRmnouz, 2 left", Say(["EU07", "WRmnouz", "Bdhpumn"], ["EU07", "Bdhpumn"])); + + [Fact] + public void The_count_left_counts_vehicles_not_units() => + Assert.Equal("removed EU07, 3 left", Say(["EU07", "EN57"], ["EN57"], vehicles: 3)); + + [Fact] + public void A_vehicle_turned_round_is_named() => + Assert.Equal("turned Bdhpumn", Say(["EU07", "Bdhpumn"], ["EU07", "Bdhpumn^"])); + + [Fact] + public void A_vehicle_turned_back_is_told_apart_from_one_turned() => + Assert.Equal("unturned Bdhpumn", Say(["EU07", "Bdhpumn^"], ["EU07", "Bdhpumn"])); + + [Fact] + public void Several_turned_at_once_are_counted() => + Assert.Equal("turned 3", Say(["A", "B", "C"], ["A^", "B^", "C^"])); + + [Fact] + public void A_vehicle_moved_towards_the_end_is_named_with_its_new_place() => + Assert.Equal("moved A to 3/4", Say(["A", "B", "C", "D"], ["B", "C", "A", "D"])); + + [Fact] + public void A_vehicle_moved_towards_the_front_is_named_with_its_new_place() => + Assert.Equal("moved C to 1/4", Say(["A", "B", "C", "D"], ["C", "A", "B", "D"])); + + [Fact] + public void Neighbours_swapped_are_told_as_one_moved() => + Assert.Equal("moved A to 2/2", Say(["A", "B"], ["B", "A"])); + + [Fact] + public void The_same_vehicles_shuffled_are_told_as_a_new_order() => + Assert.Equal("reordered", Say(["A", "B", "C", "D"], ["B", "A", "D", "C"])); + + [Fact] + public void One_vehicle_swapped_for_another_names_both() => + Assert.Equal("replaced B with X", Say(["A", "B", "C"], ["A", "X", "C"])); + + [Fact] + public void A_bigger_change_counts_the_vehicles_it_touched() => + Assert.Equal("changed 2, 3 now", Say(["A", "B", "C"], ["A", "X", "Y"])); + + [Fact] + public void Same_named_vehicles_next_to_each_other_still_count_one_added() => + Assert.Equal("added Bdhpumn at 3/3", Say(["EU07", "Bdhpumn"], ["EU07", "Bdhpumn", "Bdhpumn"])); +} diff --git a/StarterNG/App.axaml.cs b/StarterNG/App.axaml.cs index 7e23076..c39ea3c 100644 --- a/StarterNG/App.axaml.cs +++ b/StarterNG/App.axaml.cs @@ -27,6 +27,7 @@ public partial class App : Avalonia.Application { // Before any control exists: the names are given as controls are filled in. ScreenReaderNames.Install(); + DialogKeyboard.Install(); AvaloniaXamlLoader.Load(this); diff --git a/StarterNG/Application/AppServices.cs b/StarterNG/Application/AppServices.cs index 7f7b6ce..4c9087e 100644 --- a/StarterNG/Application/AppServices.cs +++ b/StarterNG/Application/AppServices.cs @@ -80,6 +80,9 @@ public sealed class AppServices _current ?? throw new InvalidOperationException( "AppServices.Current read before Initialize(); the composition root must be built first."); + /// The services once built, or null before: for what may run either way, such as a control in a test. + public static AppServices? CurrentOrNull => _current; + public static AppServices Initialize(IGamePaths? paths = null, IFileSystem? files = null, IClock? clock = null, IEnvironment? environment = null) { diff --git a/StarterNG/Controls/AppLanguage.cs b/StarterNG/Controls/AppLanguage.cs new file mode 100644 index 0000000..bccc62b --- /dev/null +++ b/StarterNG/Controls/AppLanguage.cs @@ -0,0 +1,28 @@ +using System; +using StarterNG.Application; + +namespace StarterNG.Controls; + +/// +/// The starter's texts as the controls here read them: in its language once the +/// application is built, the key itself before that, as in a test. +/// +internal static class AppLanguage +{ + public static string Text(string key) => AppServices.CurrentOrNull?.Localization[key] ?? key; + + /// Raised when the language is changed; nothing is raised before the application is built. + public static event Action? Changed + { + add + { + if (AppServices.CurrentOrNull?.Localization is { } loc) + loc.LanguageChanged += value; + } + remove + { + if (AppServices.CurrentOrNull?.Localization is { } loc) + loc.LanguageChanged -= value; + } + } +} diff --git a/StarterNG/Controls/DialogKeyboard.cs b/StarterNG/Controls/DialogKeyboard.cs new file mode 100644 index 0000000..44a867d --- /dev/null +++ b/StarterNG/Controls/DialogKeyboard.cs @@ -0,0 +1,77 @@ +using System.Linq; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Threading; +using Avalonia.VisualTree; + +namespace StarterNG.Controls; + +/// +/// What every window opened over another does for someone at the keyboard, as a dialog +/// of Windows does: it opens with focus on its default button or else its first +/// control, where it opened with nothing focused and a screen reader said only its +/// title; Esc closes it; Tab with nothing focused starts from the first control. +/// +public static class DialogKeyboard +{ + /// False for a window that stays open beside the main one, such as the tapes: Esc there is not a way out. + public static readonly Avalonia.AttachedProperty EscapeClosesProperty = + Avalonia.AvaloniaProperty.RegisterAttached("EscapeCloses", typeof(DialogKeyboard), defaultValue: true); + + public static bool GetEscapeCloses(Window window) => window.GetValue(EscapeClosesProperty); + + public static void SetEscapeCloses(Window window, bool value) => window.SetValue(EscapeClosesProperty, value); + + public static void Install() => + Window.WindowOpenedEvent.AddClassHandler((window, _) => OnOpened(window)); + + private static void OnOpened(Window window) + { + // The main window and the splash have no owner, and their own ways. + if (window.Owner is null) + return; + + window.AddHandler(InputElement.KeyDownEvent, (_, e) => OnTab(window, e), RoutingStrategies.Tunnel); + window.AddHandler(InputElement.KeyDownEvent, (_, e) => OnEscape(window, e)); + Dispatcher.UIThread.Post(() => FocusFirst(window), DispatcherPriority.Loaded); + } + + // Bubbling and only when nothing took it: a list closing its drop-down, a cancel + // button or a window of its own that handles the key keep it. + private static void OnEscape(Window window, KeyEventArgs e) + { + if (e.Handled || e.Key != Key.Escape || e.KeyModifiers != KeyModifiers.None || !GetEscapeCloses(window)) + return; + + window.Close(); + e.Handled = true; + } + + private static void OnTab(Window window, KeyEventArgs e) + { + if (window.FocusManager is not { } focus) + return; + + var next = KeyboardFocus.TabFromNowhere(e.Key, e.KeyModifiers, focus.GetFocusedElement(), window, + focus.FindFirstFocusableElement, focus.FindLastFocusableElement); + if (next is not null && next.Focus(NavigationMethod.Tab)) + e.Handled = true; + } + + /// Focus on the default button, or the first control when there is none; left alone when the window placed it itself. + public static void FocusFirst(Window window) + { + if (window.FocusManager is not { } focus) + return; + + var focused = focus.GetFocusedElement(); + if (focused is not null && !ReferenceEquals(focused, window)) + return; + + IInputElement? target = window.GetVisualDescendants().OfType