fix: a screen reader names every control and Tab survives adding a vehicle

NVDA read icon buttons as "Material.Icons.Avalonia.MaterialIcon" and the
sceneries in the tree as nothing. Icon buttons are now named by their
tooltip, list and tree entries by the text they show, fields by the hint in
them, and the inputs of a setting row by its label. The lists, the tree and
the language and profile pickers have names, and a consist card says its
place and vehicles.

Adding a vehicle rebuilt the browser list and switched the add button off
for a moment, and focus fell out of the window: Tab did nothing until
something was clicked. Focus goes back to the button or the list, and Tab
with nothing focused starts from the first control. The splitters are no
longer Tab stops.
This commit is contained in:
maj00r
2026-11-15 17:40:51 +01:00
parent 744720d922
commit a83bb4a7eb
14 changed files with 388 additions and 9 deletions

View File

@@ -7,6 +7,7 @@ using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using StarterNG.Application;
using StarterNG.Classes;
using StarterNG.Controls;
using StarterNG.Infrastructure;
using StarterNG.Services;
@@ -24,6 +25,9 @@ public partial class App : Avalonia.Application
public override void Initialize()
{
// Before any control exists: the names are given as controls are filled in.
ScreenReaderNames.Install();
AvaloniaXamlLoader.Load(this);
AppServices.Current.SettingsStore.Load();

View File

@@ -0,0 +1,24 @@
using System;
using Avalonia.Input;
namespace StarterNG.Controls;
public static class KeyboardFocus
{
/// <summary>
/// Focus that fell out with a control taken away or switched off leaves the window
/// itself focused, and Tab then went nowhere until something was clicked - for
/// someone without a mouse, nowhere at all. Tab starts again from the first
/// control, Shift+Tab from the last. Null when focus is somewhere and Tab moves it
/// as usual.
/// </summary>
public static IInputElement? TabFromNowhere(Key key, KeyModifiers modifiers, IInputElement? focused,
IInputElement window, Func<IInputElement?> first,
Func<IInputElement?> last)
{
if (key != Key.Tab || focused is not null && !ReferenceEquals(focused, window))
return null;
return modifiers.HasFlag(KeyModifiers.Shift) ? last() : first();
}
}

View File

@@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
namespace StarterNG.Controls;
/// <summary>
/// The names a screen reader says for controls that show no plain text of their own.
/// Without one it said the type of whatever was inside: an icon button was read as
/// "Material.Icons.Avalonia.MaterialIcon", a scenery in the tree as nothing at all.
/// An icon button is named by its tooltip, a list or tree entry by the text it shows,
/// a field by the hint written in it. A name given on purpose is left alone.
/// </summary>
public static class ScreenReaderNames
{
// What was given here last, so a later change replaces it but nothing else.
private static readonly ConditionalWeakTable<StyledElement, string> Given = new();
public static void Install()
{
ContentControl.ContentProperty.Changed.AddClassHandler<Button>((b, _) => NameButton(b));
ToolTip.TipProperty.Changed.AddClassHandler<Button>((b, _) => NameButton(b));
ContentControl.ContentProperty.Changed.AddClassHandler<ListBoxItem>((i, _) => Give(i, TextOf(i.Content)));
HeaderedItemsControl.HeaderProperty.Changed.AddClassHandler<TreeViewItem>((i, _) => Give(i, TextOf(i.Header)));
ComboBox.PlaceholderTextProperty.Changed.AddClassHandler<ComboBox>((c, _) => Give(c, c.PlaceholderText));
TextBox.PlaceholderTextProperty.Changed.AddClassHandler<TextBox>((t, _) => Give(t, t.PlaceholderText));
}
private static void NameButton(Button button) =>
Give(button, button.Content is string ? null : TextOf(ToolTip.GetTip(button)) ?? TextOf(button.Content));
/// <summary>
/// The inputs of a setting row, named by the row's label: a list, a slider or a box
/// beside the label otherwise had no name at all.
/// </summary>
public static void NameInputs(object? content, string? label)
{
foreach (var input in Inputs(content))
Give(input, label);
}
private static IEnumerable<Control> Inputs(object? content) => content switch
{
ComboBox or Slider or TextBox or NumericUpDown => new[] { (Control)content },
Panel panel => panel.Children.SelectMany(Inputs),
Decorator decorator => Inputs(decorator.Child),
_ => Array.Empty<Control>()
};
/// <summary>The text a reader would see on it, or null when it shows none.</summary>
public static string? TextOf(object? content)
{
string? text = content switch
{
string s => s,
TextBlock block => block.Inlines is { Count: > 0 } inlines ? TextOf(inlines) : block.Text,
ContentControl inner => TextOf(inner.Content),
Decorator decorator => TextOf(decorator.Child),
Panel panel => Join(panel.Children.Where(c => c.IsVisible).Select(TextOf)),
_ => null
};
return string.IsNullOrWhiteSpace(text) ? null : text.Trim();
}
private static string TextOf(InlineCollection inlines) =>
string.Concat(inlines.Select(i => i switch
{
Run run => run.Text,
LineBreak => " ",
Span span => TextOf(span.Inlines),
_ => null
}));
private static string Join(IEnumerable<string?> parts) =>
string.Join(", ", parts.Where(p => !string.IsNullOrWhiteSpace(p)));
private static void Give(StyledElement target, string? name)
{
string? current = AutomationProperties.GetName(target);
bool ours = Given.TryGetValue(target, out string? given) && current == given;
if (!string.IsNullOrEmpty(current) && !ours)
return;
if (string.IsNullOrEmpty(name))
{
if (ours)
target.ClearValue(AutomationProperties.NameProperty);
Given.Remove(target);
return;
}
AutomationProperties.SetName(target, name);
Given.AddOrUpdate(target, name);
}
}

View File

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

View File

@@ -64,6 +64,7 @@
</StackPanel>
<ComboBox x:Name="LangCombo" Width="96" VerticalAlignment="Center"
AutomationProperties.Name="{Binding [Language], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="LangCombo_OnSelectionChanged" />
<Button Classes="Basic" Cursor="Hand" Tag="https://discord.gg/eu07" Click="linkClick"

View File

@@ -13,6 +13,7 @@ using Avalonia.Layout;
using Avalonia.Threading;
using Avalonia.VisualTree;
using StarterNG.Classes;
using StarterNG.Controls;
using StarterNG.Infrastructure;
using StarterNG.Views;
using StarterNG.Application;
@@ -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.

View File

@@ -86,6 +86,7 @@
TextChanged="SearchBox_OnTextChanged" />
<ListBox Name="vehicleListBox" Grid.Row="4" Classes="Compact" MinHeight="60"
AutomationProperties.Name="{Binding [Vehicles], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="VehicleListBox_OnSelectionChanged"
DoubleTapped="VehicleListBox_OnDoubleTapped"
PointerPressed="VehicleListBox_OnPointerPressed" />
@@ -145,6 +146,7 @@
Content="{Binding [ShowAiVehicles], Source={x:Static starterNg:App.Loc}}" />
</StackPanel>
<ListBox Name="sceneryConsistList" Classes="Compact"
AutomationProperties.Name="{Binding [SceneryConsists], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="SceneryConsistList_OnSelectionChanged"
KeyDown="SceneryConsistList_OnKeyDown" />
</DockPanel>
@@ -160,7 +162,8 @@
<TextBlock DockPanel.Dock="Bottom" Margin="2,6,0,0" FontSize="12" Opacity="0.6"
TextWrapping="Wrap"
Text="{Binding [WarehouseEditHint], Source={x:Static starterNg:App.Loc}}" />
<ListBox Name="warehouseList" Classes="Compact" />
<ListBox Name="warehouseList" Classes="Compact"
AutomationProperties.Name="{Binding [WarehouseConsists], Source={x:Static starterNg:App.Loc}}" />
</DockPanel>
</TabItem>
</TabControl>

View File

@@ -578,12 +578,29 @@ public sealed class VehicleBrowser
var set = _db.ResolveSet(texture);
var browserTex = set is { Count: > 0 } ? set[0] : texture;
WhileSyncing(() =>
KeepingKeyboardFocus(() => WhileSyncing(() =>
{
ApplyFilters(VehicleInfo.CategoryOf(browserTex), VehicleInfo.ClassOf(browserTex));
Rebuild();
SelectListEntry(browserTex);
});
}));
}
/// <summary>
/// The list is rebuilt under the keyboard: the add button is switched off for a
/// moment and the rows are replaced, and focus fell out of the window with them -
/// Tab then went nowhere until something was clicked. It is handed back.
/// </summary>
private void KeepingKeyboardFocus(Action rebuild)
{
bool onAdd = addVehicleButton.IsFocused;
bool inList = vehicleListBox.IsKeyboardFocusWithin;
rebuild();
if (onAdd && addVehicleButton.IsEnabled)
addVehicleButton.Focus(NavigationMethod.Tab);
else if (onAdd || inList)
(vehicleListBox.SelectedItem as Control ?? vehicleListBox).Focus(NavigationMethod.Tab);
}
private void SyncCombosTo(VehicleTexture texture)
@@ -591,7 +608,7 @@ public sealed class VehicleBrowser
if (_syncingCombos || !ApplyFilters(VehicleInfo.CategoryOf(texture), VehicleInfo.ClassOf(texture)))
return;
PostSyncing(() => { Rebuild(); SelectListEntry(texture); });
PostSyncing(() => KeepingKeyboardFocus(() => { Rebuild(); SelectListEntry(texture); }));
}
private void WhileSyncing(Action work)

View File

@@ -2,6 +2,8 @@ using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
@@ -146,6 +148,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 +185,10 @@ public sealed class VehicleCards
return card;
}
/// <summary>Its place in the consist and what it holds, as a screen reader says it.</summary>
private string CardName(ConsistItem item, int index) =>
$"{index + 1}. {string.Join(", ", item.Cars.Select(car => CardCaption(item, car, index)))}";
private string CardCaption(ConsistItem item, Dynamic car, int index) =>
TrainsetDisplay.VehicleLabel(car,
head: index == 0 && ReferenceEquals(car, Consist.HeadCar(item)) && TrainsetDisplay.IsPowered(car));

View File

@@ -33,6 +33,7 @@
IsCheckedChanged="ArchivalSwitch_OnChanged"
Content="{Binding [HideArchivalSceneries], Source={x:Static starterNg:App.Loc}}" />
<TreeView Name="sceneryList" Classes="Compact"
AutomationProperties.Name="{Binding [Sceneries], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="SceneryList_OnSelectionChanged"
ContextRequested="SceneryList_OnContextRequested">
<TreeView.ContextMenu>
@@ -49,7 +50,7 @@
</DockPanel>
</HeaderedContentControl>
<GridSplitter Grid.Column="1" Grid.Row="0" Width="6"
<GridSplitter IsTabStop="False" Grid.Column="1" Grid.Row="0" Width="6"
Background="Transparent" ResizeDirection="Columns" />
<Grid Grid.Column="2" Grid.Row="0">
@@ -70,10 +71,11 @@
</HeaderedContentControl.Tag>
<ListBox Name="vehicleList" Classes="Compact"
AutomationProperties.Name="{Binding [SceneryConsists], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="VehicleList_OnSelectionChanged" />
</HeaderedContentControl>
<GridSplitter Grid.Row="1" Height="4" HorizontalAlignment="Stretch"
<GridSplitter IsTabStop="False" Grid.Row="1" Height="4" HorizontalAlignment="Stretch"
Background="Transparent" ResizeDirection="Rows" />
<TabControl Grid.Row="2" Name="infoTabs">

View File

@@ -47,7 +47,8 @@
<StackPanel DockPanel.Dock="Bottom" Spacing="6" Margin="0,14,0,0">
<TextBlock Classes="FieldLabel"
Text="{Binding [SettingsProfile], Source={x:Static starterNg:App.Loc}}" />
<ComboBox x:Name="ProfileCb" HorizontalAlignment="Stretch" />
<ComboBox x:Name="ProfileCb" HorizontalAlignment="Stretch"
AutomationProperties.Name="{Binding [ProfilePick], Source={x:Static starterNg:App.Loc}}" />
<Button x:Name="ProfileApplyBtn" Classes="Flat" HorizontalAlignment="Stretch"
HorizontalContentAlignment="Center"
Content="{Binding [ProfileApply], Source={x:Static starterNg:App.Loc}}"

View File

@@ -77,7 +77,7 @@
<Grid RowDefinitions="Auto,*,4,Auto,*,Auto,Auto">
<TextBlock Grid.Row="0" Classes="Heading" Text="{Binding [Category], Source={x:Static starterNg:App.Loc}}" />
<ListBox Name="categoryList" Grid.Row="1" Classes="Compact" />
<GridSplitter Grid.Row="2" Height="4" HorizontalAlignment="Stretch"
<GridSplitter IsTabStop="False" Grid.Row="2" Height="4" HorizontalAlignment="Stretch"
Background="Transparent" ResizeDirection="Rows" />
<TextBlock Grid.Row="3" Classes="Heading" Text="{Binding [Class], Source={x:Static starterNg:App.Loc}}" />
<ListBox Name="classList" Grid.Row="4" Classes="Compact">
@@ -97,7 +97,7 @@
</Grid>
</Border>
<GridSplitter Grid.Column="1" Width="3" Background="Transparent" ResizeDirection="Columns" />
<GridSplitter IsTabStop="False" Grid.Column="1" Width="3" Background="Transparent" ResizeDirection="Columns" />
<Border Grid.Column="2" Classes="Panel">
<Grid RowDefinitions="Auto,*">