fix: a blind player can bind keys, build a consist and read the tapes

A review against WCAG 2.2 AA left places a screen reader user could not work:

- Key bindings: a key's button says the command and the key, the clear button
  which command it clears; a new key is said aloud and focus comes back to its
  row. The on-screen keyboard is reached with Tab and walked with the arrows.
- Number fields read their label; the spin buttons are named and left out of Tab.
- Dialogs: Enter presses the main button, Esc closes, focus starts on the first
  button and the message is read with it.
- Consist: every change is said - added, removed, turned, moved, replaced,
  undone - and the strip is a named list; a turned card says so.
- Searches say how many entries are left once typing pauses.
- Hasler tapes, the black box timeline, timetable and cab panel take focus, work
  from the keyboard, read their value as it changes and draw a focus frame.
- Section reset and level controls, the crew button and the tabs carry names;
  English names from Avalonia's templates are read in the starter's language;
  sort and crew menus are radio items.
- Input borders reach 3:1 against the panels; Tab starts at the top bar; the
  splash screen has a title and its progress reads the loading step.
This commit is contained in:
maj00r
2026-11-15 20:46:55 +01:00
parent 07bd3d27fb
commit ff5228555e
43 changed files with 1419 additions and 45 deletions

View File

@@ -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);

View File

@@ -80,6 +80,9 @@ public sealed class AppServices
_current ?? throw new InvalidOperationException(
"AppServices.Current read before Initialize(); the composition root must be built first.");
/// <summary>The services once built, or null before: for what may run either way, such as a control in a test.</summary>
public static AppServices? CurrentOrNull => _current;
public static AppServices Initialize(IGamePaths? paths = null, IFileSystem? files = null, IClock? clock = null,
IEnvironment? environment = null)
{

View File

@@ -0,0 +1,28 @@
using System;
using StarterNG.Application;
namespace StarterNG.Controls;
/// <summary>
/// The starter's texts as the controls here read them: in its language once the
/// application is built, the key itself before that, as in a test.
/// </summary>
internal static class AppLanguage
{
public static string Text(string key) => AppServices.CurrentOrNull?.Localization[key] ?? key;
/// <summary>Raised when the language is changed; nothing is raised before the application is built.</summary>
public static event Action? Changed
{
add
{
if (AppServices.CurrentOrNull?.Localization is { } loc)
loc.LanguageChanged += value;
}
remove
{
if (AppServices.CurrentOrNull?.Localization is { } loc)
loc.LanguageChanged -= value;
}
}
}

View File

@@ -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;
/// <summary>
/// What every window opened over another does for someone at the keyboard, as a dialog
/// of Windows does: it opens with focus on its default button or else its first
/// control, where it opened with nothing focused and a screen reader said only its
/// title; Esc closes it; Tab with nothing focused starts from the first control.
/// </summary>
public static class DialogKeyboard
{
/// <summary>False for a window that stays open beside the main one, such as the tapes: Esc there is not a way out.</summary>
public static readonly Avalonia.AttachedProperty<bool> EscapeClosesProperty =
Avalonia.AvaloniaProperty.RegisterAttached<Window, bool>("EscapeCloses", typeof(DialogKeyboard), defaultValue: true);
public static bool GetEscapeCloses(Window window) => window.GetValue(EscapeClosesProperty);
public static void SetEscapeCloses(Window window, bool value) => window.SetValue(EscapeClosesProperty, value);
public static void Install() =>
Window.WindowOpenedEvent.AddClassHandler<Window>((window, _) => OnOpened(window));
private static void OnOpened(Window window)
{
// The main window and the splash have no owner, and their own ways.
if (window.Owner is null)
return;
window.AddHandler(InputElement.KeyDownEvent, (_, e) => OnTab(window, e), RoutingStrategies.Tunnel);
window.AddHandler(InputElement.KeyDownEvent, (_, e) => OnEscape(window, e));
Dispatcher.UIThread.Post(() => FocusFirst(window), DispatcherPriority.Loaded);
}
// Bubbling and only when nothing took it: a list closing its drop-down, a cancel
// button or a window of its own that handles the key keep it.
private static void OnEscape(Window window, KeyEventArgs e)
{
if (e.Handled || e.Key != Key.Escape || e.KeyModifiers != KeyModifiers.None || !GetEscapeCloses(window))
return;
window.Close();
e.Handled = true;
}
private static void OnTab(Window window, KeyEventArgs e)
{
if (window.FocusManager is not { } focus)
return;
var next = KeyboardFocus.TabFromNowhere(e.Key, e.KeyModifiers, focus.GetFocusedElement(), window,
focus.FindFirstFocusableElement, focus.FindLastFocusableElement);
if (next is not null && next.Focus(NavigationMethod.Tab))
e.Handled = true;
}
/// <summary>Focus on the default button, or the first control when there is none; left alone when the window placed it itself.</summary>
public static void FocusFirst(Window window)
{
if (window.FocusManager is not { } focus)
return;
var focused = focus.GetFocusedElement();
if (focused is not null && !ReferenceEquals(focused, window))
return;
IInputElement? target = window.GetVisualDescendants().OfType<Button>()
.FirstOrDefault(b => b.IsDefault && b.IsEffectivelyVisible && b.IsEffectivelyEnabled)
?? focus.FindFirstFocusableElement();
target?.Focus(NavigationMethod.Tab);
}
}

View File

@@ -9,6 +9,7 @@ using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
namespace StarterNG.Controls;
@@ -53,6 +54,86 @@ public static class ScreenReaderNames
TimePicker.SelectedTimeProperty.Changed.AddClassHandler<TimePicker>((p, _) => NamePicker(p));
AutomationProperties.NameProperty.Changed.AddClassHandler<DatePicker>((p, _) => NamePicker(p));
AutomationProperties.NameProperty.Changed.AddClassHandler<TimePicker>((p, _) => NamePicker(p));
TemplatedControl.TemplateAppliedEvent.AddClassHandler<NumericUpDown>((n, e) => ForwardToTextBox(n, e));
TemplatedControl.TemplateAppliedEvent.AddClassHandler<ButtonSpinner>((s, e) => NameSpinButtons(s, e));
AutomationProperties.NameProperty.Changed.AddClassHandler<Control>((c, e) => TranslateTemplateName(c, e));
AppLanguage.Changed += RetranslateTemplateNames;
}
/// <summary>
/// A number box is reached through the text box inside it, which had no name: the
/// reader heard "edit, 0,1" and not what the number is. It takes the box's name and
/// explanation, and keeps them when they change.
/// </summary>
private static void ForwardToTextBox(NumericUpDown box, TemplateAppliedEventArgs e)
{
if (e.NameScope.Find<TextBox>("PART_TextBox") is not { } text)
return;
text.Bind(AutomationProperties.NameProperty, box.GetObservable(AutomationProperties.NameProperty));
text.Bind(AutomationProperties.HelpTextProperty, box.GetObservable(AutomationProperties.HelpTextProperty));
}
/// <summary>
/// The arrows of a number box were read as "Avalonia.Controls.Shapes.Path" and were two
/// more stops for Tab. They say what they do, and Tab passes them: the arrow keys in the
/// box do the same, as in any spin box of Windows.
/// </summary>
private static void NameSpinButtons(ButtonSpinner spinner, TemplateAppliedEventArgs e)
{
foreach (var (part, key) in new[] { ("PART_IncreaseButton", "SpinUp"), ("PART_DecreaseButton", "SpinDown") })
{
if (e.NameScope.Find<Control>(part) is not { } button)
continue;
KeyboardNavigation.SetIsTabStop(button, false);
TemplateNames.AddOrUpdate(button, key);
AutomationProperties.SetName(button, AppLanguage.Text(key));
}
}
/// <summary>
/// The English names Avalonia's own templates give their parts - the window's buttons,
/// the arrows of a scroll bar - and the texts they are read as instead.
/// </summary>
private static readonly Dictionary<string, string> EnglishTemplateNames = new(StringComparer.Ordinal)
{
["Minimize"] = "ChromeMinimize",
["Maximize"] = "ChromeMaximize",
["Restore"] = "ChromeRestore",
["Close"] = "ChromeClose",
["Line up"] = "ScrollLineUp",
["Line down"] = "ScrollLineDown",
["Page up"] = "ScrollPageUp",
["Page down"] = "ScrollPageDown",
["Column left"] = "ScrollColumnLeft",
["Column right"] = "ScrollColumnRight",
["Page left"] = "ScrollPageLeft",
["Page right"] = "ScrollPageRight",
["Position"] = "ScrollPosition",
};
// The parts given a translated name, with the text they were given it from.
private static readonly ConditionalWeakTable<Control, string> TemplateNames = new();
/// <summary>An English name set by a template is replaced by the same thing in the starter's language.</summary>
private static void TranslateTemplateName(Control control, AvaloniaPropertyChangedEventArgs e)
{
if (e.Priority == Avalonia.Data.BindingPriority.LocalValue || e.NewValue is not string english
|| !EnglishTemplateNames.TryGetValue(english, out string? key)
|| AppLanguage.Text(key) is not { Length: > 0 } text || text == english)
return;
TemplateNames.AddOrUpdate(control, key);
AutomationProperties.SetName(control, text);
}
private static void RetranslateTemplateNames()
{
foreach (var (control, key) in TemplateNames)
AutomationProperties.SetName(control, AppLanguage.Text(key));
}
// A date or time picker is reached through the button inside it, which was read as
@@ -129,6 +210,10 @@ public static class ScreenReaderNames
return null;
var labels = panel.Children.OfType<TextBlock>().Where(IsLabel).ToList();
// A panel that only holds inputs - a number box and the list shown in its place -
// is labelled where it stands itself.
if (labels.Count == 0)
return panel.Parent is Panel ? LabelOf(panel) : null;
if (panel is Grid)
{
int row = Grid.GetRow(input), column = Grid.GetColumn(input);
@@ -302,6 +387,8 @@ public static class ScreenReaderNames
string? text = content switch
{
string s => s,
// A sign such as a dot is given the words it stands for.
TextBlock block when AutomationProperties.GetName(block) is { Length: > 0 } name => name,
TextBlock block => block.Inlines is { Count: > 0 } inlines ? TextOf(inlines) : block.Text,
ContentControl inner => TextOf(inner.Content),
Decorator decorator => TextOf(decorator.Child),

View File

@@ -0,0 +1,43 @@
using System;
using Avalonia.Controls;
using Avalonia.Threading;
namespace StarterNG.Controls;
/// <summary>
/// Says how many entries a search box left once typing pauses: the list filled itself
/// out of sight, and a screen reader heard only the letters typed. Nothing is said
/// while focus is elsewhere or the box is empty.
/// </summary>
public sealed class SearchResultsTeller
{
/// <summary>The pause after the last key that counts as done typing.</summary>
public static readonly TimeSpan Pause = TimeSpan.FromMilliseconds(900);
private readonly TextBox _box;
private readonly Func<int> _count;
private readonly DispatcherTimer _timer = new() { Interval = Pause };
public SearchResultsTeller(TextBox box, Func<int> count)
{
_box = box;
_count = count;
_timer.Tick += (_, _) => Tell();
}
/// <summary>The text changed: the count is said after the pause, once.</summary>
public void Changed()
{
_timer.Stop();
_timer.Start();
}
private void Tell()
{
_timer.Stop();
if (!_box.IsKeyboardFocusWithin || string.IsNullOrWhiteSpace(_box.Text))
return;
Announcer.Say(_box, string.Format(AppLanguage.Text("SearchFound"), _count()));
}
}

View File

@@ -59,6 +59,43 @@ public class SettingsSection : HeaderedContentControl
_reset = e.NameScope.Find<Button>("PART_Reset");
if (_reset is not null)
_reset.Click += OnResetClick;
NameReset();
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == HeaderProperty || change.Property == ResetLabelProperty)
NameReset();
if (change.Property == HeaderProperty || change.Property == LevelProperty)
NameLevel();
}
/// <summary>
/// The header's list of levels was named by the word it shows with nothing chosen,
/// "Własne"; it is named as the level of this section.
/// </summary>
private void NameLevel()
{
if (Level is Control level)
Avalonia.Automation.AutomationProperties.SetName(level, ScreenReaderNames.PickerText(
AppLanguage.Text("SectionLevel"), ScreenReaderNames.TextOf(Header)));
}
/// <summary>
/// Every section has a button with the same words; a reader is told which section
/// it puts back, as a sighted one sees from where it stands.
/// </summary>
private void NameReset()
{
if (_reset is null)
return;
string? name = ScreenReaderNames.PickerText(ResetLabel, ScreenReaderNames.TextOf(Header));
if (string.IsNullOrEmpty(name))
_reset.ClearValue(Avalonia.Automation.AutomationProperties.NameProperty);
else
Avalonia.Automation.AutomationProperties.SetName(_reset, name);
}
private void OnResetClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e) => ResetRequested?.Invoke(this);

View File

@@ -18,7 +18,7 @@
<ctl:Announcer>
<DockPanel LastChildFill="True">
<Border x:Name="TopBar" DockPanel.Dock="Top"
<Border x:Name="TopBar" DockPanel.Dock="Top" TabIndex="0"
Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderThickness="0,0,0,1"

View File

@@ -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}}" />
<ProgressBar x:Name="progressBar"
AutomationProperties.Name="{Binding #statusText.Text}"
Minimum="0" Maximum="1" Value="0" Height="6" />
</StackPanel>
</Border>

View File

@@ -17,6 +17,8 @@
<SolidColorBrush x:Key="CarbonInputBg" Color="#262C31" />
<SolidColorBrush x:Key="CarbonBorderLight" Color="#3A424A" />
<!-- Frames of things you type in or tick: 3:1 against the panels they sit on, so the field can be found without hovering. -->
<SolidColorBrush x:Key="CarbonInputBorder" Color="#737C86" />
<SolidColorBrush x:Key="CarbonBorderDark" Color="#0E0F12" />
<SolidColorBrush x:Key="CarbonFg" Color="#E6E8EA" />
<SolidColorBrush x:Key="CarbonFgDim" Color="#9098A0" />
@@ -77,7 +79,7 @@
Height="{StaticResource CarbonCheckSize}"
VerticalAlignment="Center"
Background="{StaticResource CarbonInputBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderBrush="{StaticResource CarbonInputBorder}"
BorderThickness="1" CornerRadius="2">
<Path Name="glyph" Margin="3" Stretch="Uniform"
Data="M 0,4 L 3,7 L 9,0"
@@ -139,7 +141,7 @@
the same shape and height as a combo box. -->
<ControlTheme x:Key="{x:Type ButtonSpinner}" TargetType="ButtonSpinner">
<Setter Property="Background" Value="{StaticResource CarbonInputBg}" />
<Setter Property="BorderBrush" Value="{StaticResource CarbonBorderLight}" />
<Setter Property="BorderBrush" Value="{StaticResource CarbonInputBorder}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="2" />
<Setter Property="MinHeight" Value="{StaticResource CarbonControlHeight}" />
@@ -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 @@
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="8,1" />
<Setter Property="CornerRadius" Value="2" />
<Setter Property="BorderBrush" Value="{StaticResource CarbonInputBorder}" />
</Style>
<Style Selector="TextBox">
<Setter Property="MinHeight" Value="{StaticResource CarbonControlHeight}" />
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="6,1" />
<Setter Property="CornerRadius" Value="2" />
<Setter Property="BorderBrush" Value="{StaticResource CarbonInputBorder}" />
</Style>
<!-- Fluent gives the spinner and the check controls a 32 px floor of their own,
inside the template, so setting MinHeight on the control alone does nothing. -->

View File

@@ -82,6 +82,8 @@ public static class AboutWindow
};
close.Classes.Add("Accent");
close.Click += (_, _) => win.Close();
close.IsDefault = true;
close.IsCancel = true;
var footer = new StackPanel
{

View File

@@ -127,7 +127,8 @@
BorderThickness="1" CornerRadius="2" Padding="6">
<!-- The tab picks what the consist strip edits: a consist of the scenery,
or a consist kept in the warehouse. -->
<TabControl Name="consistSourceTabs" SelectionChanged="ConsistSourceTabs_OnSelectionChanged">
<TabControl Name="consistSourceTabs" AutomationProperties.Name="{Binding [DepotConsistSources], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="ConsistSourceTabs_OnSelectionChanged">
<TabItem Name="sceneryConsistsTab"
Header="{Binding [SceneryConsists], Source={x:Static starterNg:App.Loc}}">
<DockPanel LastChildFill="True">
@@ -198,7 +199,7 @@
Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderThickness="1" CornerRadius="2" Padding="6">
<TabControl>
<TabControl AutomationProperties.Name="{Binding [DepotVehicleInfo], Source={x:Static starterNg:App.Loc}}">
<TabItem Header="{Binding [GeneralInfo], Source={x:Static starterNg:App.Loc}}">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Name="generalPanel" Margin="4" Grid.IsSharedSizeScope="True" />
@@ -216,7 +217,7 @@
Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderThickness="1" CornerRadius="2" Padding="6">
<TabControl>
<TabControl AutomationProperties.Name="{Binding [DepotVehicleEdit], Source={x:Static starterNg:App.Loc}}">
<TabItem Header="{Binding [Coupling], Source={x:Static starterNg:App.Loc}}">
<!-- The coupling grid now uses the full tab width. The two
actions sit underneath, so they do not steal horizontal
@@ -321,7 +322,12 @@
<Panel>
<!-- Tab reaches the strip once and lands on the selected
card; the arrow keys walk it from there. -->
<!-- Read as the list of cards it is, so a reader hears where it is
and how many cards it holds. -->
<StackPanel Name="consistStack" Orientation="Horizontal"
AutomationProperties.Name="{Binding [Consist], Source={x:Static starterNg:App.Loc}}"
AutomationProperties.ControlTypeOverride="List"
AutomationProperties.AccessibilityView="Content"
KeyboardNavigation.TabNavigation="Once"
VerticalAlignment="Center" Spacing="0" />
<Canvas Name="consistOverlay" IsHitTestVisible="False" />

View File

@@ -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<ConsistNarration.Unit> _told = new();
private Trainset? _toldTrainset;
// While an undo or a redo loads the consist: the word said before what it changed.
private string? _restoreWord;
/// <summary>
/// Says what the change did to the consist: nothing on the strip told a screen
/// reader of a vehicle added from the list, removed, turned or of an undo. Another
/// consist taken up is not told, its entry on the list says what it is.
/// </summary>
private void TellChange()
{
var now = _consist.Select(item => new ConsistNarration.Unit(
string.Join(", ", item.Cars.Select(car => TrainsetDisplay.VehicleLabel(car))), item.Flipped)).ToList();
var trainset = _consist.EditingTrainset;
bool same = trainset is not null && ReferenceEquals(trainset, _toldTrainset);
var before = _told;
_told = now;
_toldTrainset = trainset;
if (!same)
return;
// A card moved or turned from the keyboard is focused again, and says its new place itself.
if (_restoreWord is null && before.Count == now.Count && consistStack.IsKeyboardFocusWithin)
return;
string? said = ConsistNarration.Describe(before, now, _consist.VehicleCount, key => App.Loc[key]);
if (_restoreWord is not null)
said = string.Format(App.Loc[_restoreWord], said ?? string.Empty).Trim();
Controls.Announcer.Say(this, said);
}
private void WriteBackToScenery()
@@ -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<Trainset, int, ConsistHistory.State?> step)
private void Restore(Func<Trainset, int, ConsistHistory.State?> 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);

View File

@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace StarterNG.Views;
/// <summary>
/// What a change to the consist is said as, to someone who cannot see the strip: a
/// vehicle added from the list, removed with Delete, turned, moved, or a whole undo,
/// each of which changed only pictures before. Worked out from the consist as it was
/// and as it is, so every way of making the change - a button, a key, the menu, a
/// drag - is told the same way.
/// </summary>
public static class ConsistNarration
{
/// <summary>One position of the consist as it is told: what stands there, and whether it is turned.</summary>
public readonly record struct Unit(string Label, bool Turned);
/// <summary>
/// The sentence for the change from <paramref name="before"/> to <paramref name="after"/>;
/// null when nothing a listener would notice changed, such as a coupling or the crew.
/// </summary>
/// <param name="vehicles">How many vehicles the consist has now, its units counted car by car.</param>
/// <param name="loc">The starter's texts by key.</param>
public static string? Describe(IReadOnlyList<Unit> before, IReadOnlyList<Unit> after, int vehicles,
Func<string, string> loc)
{
if (after.Count == 0)
return before.Count == 0 ? null : loc("ConsistSaidEmpty");
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++;
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)
{
// The same vehicles in the same places: some of them turned round.
if (gone.Select(u => u.Label).SequenceEqual(come.Select(u => u.Label)))
{
var turned = come.Where((u, i) => u.Turned != gone[i].Turned).ToList();
return turned.Count == 1
? string.Format(loc(turned[0].Turned ? "ConsistSaidTurned" : "ConsistSaidUnturned"), turned[0].Label)
: string.Format(loc("ConsistSaidTurnedMany"), turned.Count);
}
// 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, after.Count);
if (gone.OrderBy(u => u.Label, StringComparer.Ordinal).SequenceEqual(
come.OrderBy(u => u.Label, StringComparer.Ordinal)))
return loc("ConsistSaidReordered");
if (gone.Count == 1)
return string.Format(loc("ConsistSaidReplaced"), gone[0].Label, come[0].Label);
}
return string.Format(loc("ConsistSaidChangedMany"), Math.Max(gone.Count, come.Count), vehicles);
}
/// <summary>The unit and the place it went to when one alone moved, or null.</summary>
private static (Unit Unit, int To)? MovedOne(IReadOnlyList<Unit> gone, IReadOnlyList<Unit> come)
{
// The run that differs starts and ends with a change, so the mover is at one end of it.
if (come.Count >= 2 && come.Take(come.Count - 1).SequenceEqual(gone.Skip(1)) && come[^1] == gone[0])
return (come[^1], come.Count - 1);
if (come.Count >= 2 && come.Skip(1).SequenceEqual(gone.Take(gone.Count - 1)) && come[0] == gone[^1])
return (come[0], 0);
return null;
}
private static string Labels(IEnumerable<Unit> units) => string.Join(", ", units.Select(u => u.Label));
}

View File

@@ -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
{

View File

@@ -60,6 +60,8 @@ public sealed class VehicleBrowser
private DispatcherTimer? _searchTimer;
private readonly SearchResultsTeller _searchResults;
private Func<string?, bool>? _categoryFilter;
private string? _classFilter;
@@ -82,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 += (_, _) =>
{
@@ -564,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)

View File

@@ -15,6 +15,7 @@ using Material.Icons.Avalonia;
using StarterNG.Classes;
using StarterNG.Domain;
using StarterNG.Domain.Vehicles;
using StarterNG.Controls;
namespace StarterNG.Views;
@@ -187,7 +188,8 @@ public sealed class VehicleCards
/// <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)))}";
$"{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,
@@ -421,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();
}
/// <summary>
@@ -633,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));
}
/// <summary>
@@ -678,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.

View File

@@ -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 } });
}

View File

@@ -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(); });
/// <summary>Asks for a name at the button pressed, and says where the consist went.</summary>
public void SaveCurrent(Control anchor) =>

View File

@@ -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;

View File

@@ -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<KeyBinding, (Button Combo, Button Clear)> _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<string, Grid> _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);
}
/// <summary>
/// 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.
/// </summary>
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();
}
/// <summary>How many bindings the list shows, after the search.</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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<string, KeyState> states)
private Control BuildKeyBlock(KeyCap[][] rows, Dictionary<string, KeyState> 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<string, KeyState> states)
private Control BuildKeyCap(KeyCap cap, Dictionary<string, KeyState> 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;
}
/// <summary>The key in the next row up or down of the same block that lies nearest over or under this one.</summary>
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<string, KeyState> 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));

View File

@@ -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);

View File

@@ -15,6 +15,18 @@ internal static class MenuItems
return item;
}
/// <summary>
/// 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.
/// </summary>
public static MenuItem Choice(string header, bool chosen, Action run)
{
var item = Item(header, run);
item.ToggleType = MenuItemToggleType.Radio;
item.IsChecked = chosen;
return item;
}
/// <summary>The entry at the end of a menu or a submenu.</summary>
public static MenuItem AddItem(this ItemsControl menu, object header, Action run, bool enabled = true,
KeyGesture? gesture = null)

View File

@@ -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);
}
/// <summary>
/// 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.
/// </summary>
internal static void ReadMessage(Window win, Control first, string message)
{
AutomationProperties.SetHelpText(win, message);
AutomationProperties.SetHelpText(first, message);
}
/// <summary>A dialog over its owner, as tall as what it holds, not to be resized.</summary>
internal static Window FixedDialog(string title, double width) => new()
{

View File

@@ -80,6 +80,7 @@ public sealed class RulesWindow : Window
};
cancel.Classes.Add("Flat");
cancel.Click += (_, _) => Close();
cancel.IsCancel = true;
var footer = new StackPanel
{

View File

@@ -79,7 +79,7 @@
<GridSplitter IsTabStop="False" AutomationProperties.Name="{Binding [PanelSplitter], Source={x:Static starterNg:App.Loc}}" Grid.Row="1" Height="4" HorizontalAlignment="Stretch"
Background="Transparent" ResizeDirection="Rows" />
<TabControl Grid.Row="2" Name="infoTabs">
<TabControl Grid.Row="2" Name="infoTabs" AutomationProperties.Name="{Binding [ScenarioDetails], Source={x:Static starterNg:App.Loc}}">
<TabItem Header="{Binding [TabDescription], Source={x:Static starterNg:App.Loc}}">
<Grid RowDefinitions="2*,6,*" Margin="4">
<Grid Grid.Row="0" ColumnDefinitions="*,3,225">

View File

@@ -1326,8 +1326,15 @@ public partial class Settings : UserControl, ISettingsCapture
return;
ApplyFilter();
_searchResults ??= new SearchResultsTeller(SettingsSearch, () => _shownCount);
_searchResults.Changed();
}
private SearchResultsTeller? _searchResults;
// How many settings - or key bindings - the last filter left on the screen.
private int _shownCount;
/// <summary>
/// Single owner of what is on screen. With an empty query it shows the selected
/// category; with a query it stacks every category and keeps only the rows that
@@ -1350,11 +1357,13 @@ public partial class Settings : UserControl, ISettingsCapture
if (bindings)
{
_keyBindings.RebuildList();
_shownCount = _keyBindings.ShownCount;
foreach (var entry in CategoryList.Items.OfType<ListBoxItem>())
entry.Classes.Set("NoHits", false);
return;
}
_shownCount = 0;
foreach (var panel in SettingsStack.Children.OfType<StackPanel>())
{
bool anyRow = false;
@@ -1369,6 +1378,8 @@ public partial class Settings : UserControl, ISettingsCapture
(!searching || TextMatch.Contains(RowSearchText(row), query));
row.IsVisible = visible;
anyInSection |= visible;
if (visible && searching)
_shownCount++;
}
section.IsVisible = anyInSection;

View File

@@ -86,6 +86,8 @@ public sealed class HaslerTapeWindow : Window
MinWidth = 700;
MinHeight = 420;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
// A window to keep open beside the starter, not a question to answer.
DialogKeyboard.SetEscapeCloses(this, false);
_feed.ItemsSource = new[] { App.Loc["HaslerByDistance"], App.Loc["HaslerByTime"] };
_feed.SelectedIndex = 0;
@@ -286,9 +288,16 @@ public sealed class HaslerTapeWindow : Window
private RecorderKind Recorder => _recorder.SelectedIndex == 1 ? RecorderKind.Electronic : RecorderKind.Hasler;
private static TapeView NewView(RecorderKind kind) => kind == RecorderKind.Electronic
? new ElectronicTapeView { HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }
: new HaslerTapeView { HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top };
private static TapeView NewView(RecorderKind kind)
{
TapeView view = kind == RecorderKind.Electronic
? new ElectronicTapeView { HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }
: new HaslerTapeView { HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top };
// A picture to the eye; to a screen reader a slider along the trip, read sample by sample.
Avalonia.Automation.AutomationProperties.SetName(view, App.Loc["HaslerTapes"]);
Avalonia.Automation.AutomationProperties.SetHelpText(view, App.Loc["TapeKeysHelp"]);
return view;
}
/// <summary>
/// The same trip drawn the other way. Hasler paper is fed by distance and
@@ -467,6 +476,8 @@ public sealed class HaslerTapeWindow : Window
CanOpenFiles = false,
Live = _liveBlackBoxes.Contains(box.Path)
};
// It stays open beside the tapes, as they stay beside the starter.
DialogKeyboard.SetEscapeCloses(window, false);
_blackBoxes[box.Path] = window;
if (at is { } first)
_wantedAt[box.Path] = first;
@@ -770,6 +781,18 @@ public sealed class HaslerTapeWindow : Window
_cursor.Text = "";
return;
}
try
{
ShowCursorText(s);
}
finally
{
_view.Spoken = _cursor.Text;
}
}
private void ShowCursorText(TapeSample s)
{
// Only what the record in view shows: a Hasler tape has no brake pipe and
// marks current as on or off, and the electronic screen draws the current
// and the vigilance alarm as channels, not values.

View File

@@ -1,5 +1,8 @@
using System;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
@@ -48,6 +51,118 @@ public abstract class TapeView : Control
AffectsRender<TapeView>(TapeProperty, ByDistanceProperty, ScaleProperty, StartClockProperty, MarkProperty);
}
private static readonly IPen FocusPen = new Pen(new SolidColorBrush(Color.Parse("#41C400")), 2);
protected TapeView()
{
// Read from the keyboard as well as with the pointer: the arrows move the read-out along the trip.
Focusable = true;
}
// The sample the keyboard stands at, -1 before it has moved.
private int _keyIndex = -1;
private string? _spoken;
/// <summary>
/// The read-out of the sample under the cursor as words - time, kilometre, speed -
/// the value a screen reader reads, again whenever it changes.
/// </summary>
public string? Spoken
{
get => _spoken;
set
{
string? before = _spoken;
_spoken = value;
if (before != value && ControlAutomationPeer.FromElement(this) is Peer peer)
peer.Told(before, value);
}
}
/// <summary>How far an arrow moves the read-out: metres by distance, seconds by time; Ctrl ten times as far.</summary>
public const double DistanceStep = 100, TimeStep = 10, CtrlTimes = 10;
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
var tape = Tape;
if (tape is null || tape.IsEmpty)
return;
int at = _keyIndex >= 0 && _keyIndex < tape.Samples.Count ? _keyIndex : -1;
var here = at >= 0 ? tape.Samples[at] : tape.Samples[0];
if (e.Key == Key.Enter && at >= 0)
{
Picked?.Invoke(here);
e.Handled = true;
return;
}
double step = (ByDistance ? DistanceStep : TimeStep) * (e.KeyModifiers.HasFlag(KeyModifiers.Control) ? CtrlTimes : 1);
double position = ByDistance ? here.DistanceM : here.Time;
int? to = e.Key switch
{
Key.Right when at < 0 => 0,
Key.Left when at < 0 => 0,
Key.Right => Math.Max(at + 1, tape.IndexAt(position + step, ByDistance)),
Key.Left => Math.Min(at - 1, tape.IndexAt(position - step, ByDistance)),
Key.Home => 0,
Key.End => tape.Samples.Count - 1,
_ => null
};
if (to is not { } index)
return;
_keyIndex = Math.Clamp(index, 0, tape.Samples.Count - 1);
var sample = tape.Samples[_keyIndex];
double x = XOf(sample);
CursorX = x;
InvalidateVisual();
this.BringIntoView(new Rect(Math.Max(0, x - 80), 0, 160, TapeHeight));
Hovered?.Invoke(sample);
e.Handled = true;
}
protected override void OnGotFocus(FocusChangedEventArgs e)
{
base.OnGotFocus(e);
InvalidateVisual();
}
protected override void OnLostFocus(FocusChangedEventArgs e)
{
base.OnLostFocus(e);
InvalidateVisual();
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TapeProperty)
_keyIndex = -1;
}
protected override AutomationPeer OnCreateAutomationPeer() => new Peer(this);
/// <summary>The trip as a screen reader is told it: a slider whose value is the read-out at the cursor.</summary>
private sealed class Peer(TapeView owner) : ControlAutomationPeer(owner), IValueProvider
{
public void Told(string? before, string? now) =>
RaisePropertyChangedEvent(ValuePatternIdentifiers.ValueProperty, before, now);
protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Slider;
protected override bool IsContentElementCore() => true;
protected override bool IsControlElementCore() => true;
string? IValueProvider.Value => owner.Spoken;
bool IValueProvider.IsReadOnly => true;
void IValueProvider.SetValue(string? value) => throw new InvalidOperationException("The value is read only.");
}
public HaslerTape? Tape
{
get => GetValue(TapeProperty);
@@ -148,6 +263,8 @@ public abstract class TapeView : Control
DrawTape(context, tape);
DrawMark(context);
DrawCursor(context);
if (IsFocused)
context.DrawRectangle(null, FocusPen, new Rect(Bounds.Size).Deflate(1));
}
/// <summary>What is there with no trip on it.</summary>

View File

@@ -567,6 +567,40 @@
<String key="SettingsRestored">Uložené nastavení obnoveno</String>
<String key="TreeExpanded">rozbaleno</String>
<String key="TreeCollapsed">sbaleno</String>
<String key="DepotConsistSources">Zdroje soupravy</String>
<String key="DepotVehicleInfo">Informace o vozidle</String>
<String key="DepotVehicleEdit">Nastavení vozidla</String>
<String key="ScenarioDetails">Podrobnosti scénáře</String>
<String key="SectionLevel">Úroveň sekce</String>
<String key="SearchFound">Nalezeno: {0}</String>
<String key="SpinUp">Zvýšit</String>
<String key="SpinDown">Snížit</String>
<String key="ChromeMinimize">Minimalizovat</String>
<String key="ChromeMaximize">Maximalizovat</String>
<String key="ChromeRestore">Obnovit</String>
<String key="ChromeClose">Zavřít</String>
<String key="ScrollLineUp">Řádek nahoru</String>
<String key="ScrollLineDown">Řádek dolů</String>
<String key="ScrollPageUp">Stránka nahoru</String>
<String key="ScrollPageDown">Stránka dolů</String>
<String key="ScrollColumnLeft">Sloupec vlevo</String>
<String key="ScrollColumnRight">Sloupec vpravo</String>
<String key="ScrollPageLeft">Stránka vlevo</String>
<String key="ScrollPageRight">Stránka vpravo</String>
<String key="ScrollPosition">Poloha</String>
<String key="TapeKeysHelp">Šipky vlevo a vpravo posouvají po pásce, s Ctrl desetkrát dál, Home a End jdou na její konce, Enter přenese černou skříňku do tohoto okamžiku.</String>
<String key="ConsistSaidEmpty">Souprava prázdná</String>
<String key="ConsistSaidAdded">Přidáno {0} na pozici {1} z {2}</String>
<String key="ConsistSaidRemoved">Odebráno {0}, zbývá vozidel: {1}</String>
<String key="ConsistSaidTurned">{0} otočeno</String>
<String key="ConsistSaidUnturned">{0} otočeno zpět</String>
<String key="ConsistSaidTurnedMany">Otočeno vozidel: {0}</String>
<String key="ConsistSaidMoved">{0} přesunuto na pozici {1} z {2}</String>
<String key="ConsistSaidReordered">Pořadí změněno</String>
<String key="ConsistSaidReplaced">{0} nahrazeno za {1}</String>
<String key="ConsistSaidChangedMany">Změněno vozidel: {0}, v soupravě: {1}</String>
<String key="ConsistSaidUndone">Vráceno zpět. {0}</String>
<String key="ConsistSaidRedone">Znovu provedeno. {0}</String>
<String key="SceneryImage">Obrázek scenérie</String>
<String key="PanelSplitter">Oddělovač panelů</String>
<String key="SettingsCategories">Kategorie nastavení</String>

View File

@@ -593,6 +593,40 @@
<String key="SettingsRestored">Saved settings restored</String>
<String key="TreeExpanded">expanded</String>
<String key="TreeCollapsed">collapsed</String>
<String key="DepotConsistSources">Consist sources</String>
<String key="DepotVehicleInfo">Vehicle information</String>
<String key="DepotVehicleEdit">Vehicle settings</String>
<String key="ScenarioDetails">Scenario details</String>
<String key="SectionLevel">Section level</String>
<String key="SearchFound">{0} found</String>
<String key="SpinUp">Increase</String>
<String key="SpinDown">Decrease</String>
<String key="ChromeMinimize">Minimize</String>
<String key="ChromeMaximize">Maximize</String>
<String key="ChromeRestore">Restore</String>
<String key="ChromeClose">Close</String>
<String key="ScrollLineUp">Line up</String>
<String key="ScrollLineDown">Line down</String>
<String key="ScrollPageUp">Page up</String>
<String key="ScrollPageDown">Page down</String>
<String key="ScrollColumnLeft">Column left</String>
<String key="ScrollColumnRight">Column right</String>
<String key="ScrollPageLeft">Page left</String>
<String key="ScrollPageRight">Page right</String>
<String key="ScrollPosition">Position</String>
<String key="TapeKeysHelp">Left and Right arrows step along the tape, Ctrl with them steps ten times further, Home and End go to its ends, Enter takes the black box to that moment.</String>
<String key="ConsistSaidEmpty">Consist empty</String>
<String key="ConsistSaidAdded">Added {0} at position {1} of {2}</String>
<String key="ConsistSaidRemoved">Removed {0}, {1} vehicles left</String>
<String key="ConsistSaidTurned">{0} reversed</String>
<String key="ConsistSaidUnturned">{0} turned back</String>
<String key="ConsistSaidTurnedMany">{0} vehicles turned</String>
<String key="ConsistSaidMoved">{0} moved to position {1} of {2}</String>
<String key="ConsistSaidReordered">Order changed</String>
<String key="ConsistSaidReplaced">{0} replaced with {1}</String>
<String key="ConsistSaidChangedMany">{0} vehicles changed, {1} in the consist</String>
<String key="ConsistSaidUndone">Undone. {0}</String>
<String key="ConsistSaidRedone">Redone. {0}</String>
<String key="SceneryImage">Scenery picture</String>
<String key="PanelSplitter">Panel divider</String>
<String key="SettingsCategories">Settings categories</String>

View File

@@ -567,6 +567,40 @@
<String key="SettingsRestored">A mentett beállítások visszaállítva</String>
<String key="TreeExpanded">kibontva</String>
<String key="TreeCollapsed">összecsukva</String>
<String key="DepotConsistSources">Szerelvény forrásai</String>
<String key="DepotVehicleInfo">Jármű adatai</String>
<String key="DepotVehicleEdit">Jármű beállításai</String>
<String key="ScenarioDetails">Forgatókönyv részletei</String>
<String key="SectionLevel">Szakasz szintje</String>
<String key="SearchFound">Találatok: {0}</String>
<String key="SpinUp">Növelés</String>
<String key="SpinDown">Csökkentés</String>
<String key="ChromeMinimize">Kis méret</String>
<String key="ChromeMaximize">Teljes méret</String>
<String key="ChromeRestore">Előző méret</String>
<String key="ChromeClose">Bezárás</String>
<String key="ScrollLineUp">Sor fel</String>
<String key="ScrollLineDown">Sor le</String>
<String key="ScrollPageUp">Oldal fel</String>
<String key="ScrollPageDown">Oldal le</String>
<String key="ScrollColumnLeft">Oszlop balra</String>
<String key="ScrollColumnRight">Oszlop jobbra</String>
<String key="ScrollPageLeft">Oldal balra</String>
<String key="ScrollPageRight">Oldal jobbra</String>
<String key="ScrollPosition">Pozíció</String>
<String key="TapeKeysHelp">A bal és jobb nyíl a szalagon lépked, Ctrl-lel tízszer messzebb, a Home és az End a végeire ugrik, az Enter a fekete dobozt ehhez a pillanathoz viszi.</String>
<String key="ConsistSaidEmpty">A szerelvény üres</String>
<String key="ConsistSaidAdded">{0} hozzáadva, {1}. hely a(z) {2}-ből</String>
<String key="ConsistSaidRemoved">{0} eltávolítva, maradt jármű: {1}</String>
<String key="ConsistSaidTurned">{0} megfordítva</String>
<String key="ConsistSaidUnturned">{0} visszafordítva</String>
<String key="ConsistSaidTurnedMany">Megfordított járművek: {0}</String>
<String key="ConsistSaidMoved">{0} áthelyezve, {1}. hely a(z) {2}-ből</String>
<String key="ConsistSaidReordered">Sorrend megváltozott</String>
<String key="ConsistSaidReplaced">{0} helyett {1}</String>
<String key="ConsistSaidChangedMany">Megváltozott járművek: {0}, a szerelvényben: {1}</String>
<String key="ConsistSaidUndone">Visszavonva. {0}</String>
<String key="ConsistSaidRedone">Újra végrehajtva. {0}</String>
<String key="SceneryImage">A pálya képe</String>
<String key="PanelSplitter">Panelelválasztó</String>
<String key="SettingsCategories">Beállítási kategóriák</String>

View File

@@ -593,6 +593,40 @@
<String key="SettingsRestored">Przywrócono zapisane ustawienia</String>
<String key="TreeExpanded">rozwinięte</String>
<String key="TreeCollapsed">zwinięte</String>
<String key="DepotConsistSources">Źródła zestawienia</String>
<String key="DepotVehicleInfo">Informacje o pojeździe</String>
<String key="DepotVehicleEdit">Ustawienia pojazdu</String>
<String key="ScenarioDetails">Szczegóły scenariusza</String>
<String key="SectionLevel">Poziom sekcji</String>
<String key="SearchFound">Znaleziono: {0}</String>
<String key="SpinUp">Zwiększ</String>
<String key="SpinDown">Zmniejsz</String>
<String key="ChromeMinimize">Minimalizuj</String>
<String key="ChromeMaximize">Maksymalizuj</String>
<String key="ChromeRestore">Przywróć</String>
<String key="ChromeClose">Zamknij</String>
<String key="ScrollLineUp">Wiersz w górę</String>
<String key="ScrollLineDown">Wiersz w dół</String>
<String key="ScrollPageUp">Strona w górę</String>
<String key="ScrollPageDown">Strona w dół</String>
<String key="ScrollColumnLeft">Kolumna w lewo</String>
<String key="ScrollColumnRight">Kolumna w prawo</String>
<String key="ScrollPageLeft">Strona w lewo</String>
<String key="ScrollPageRight">Strona w prawo</String>
<String key="ScrollPosition">Położenie</String>
<String key="TapeKeysHelp">Strzałki w lewo i w prawo przesuwają po taśmie, z Ctrl dziesięć razy dalej, Home i End idą na jej końce, Enter przenosi czarną skrzynkę do tej chwili.</String>
<String key="ConsistSaidEmpty">Zestawienie puste</String>
<String key="ConsistSaidAdded">Dodano {0} na pozycji {1} z {2}</String>
<String key="ConsistSaidRemoved">Usunięto {0}, zostało pojazdów: {1}</String>
<String key="ConsistSaidTurned">{0} obrócony</String>
<String key="ConsistSaidUnturned">{0} obrócony z powrotem</String>
<String key="ConsistSaidTurnedMany">Obrócono pojazdów: {0}</String>
<String key="ConsistSaidMoved">{0} przesunięty na pozycję {1} z {2}</String>
<String key="ConsistSaidReordered">Zmieniono kolejność</String>
<String key="ConsistSaidReplaced">{0} zastąpiony przez {1}</String>
<String key="ConsistSaidChangedMany">Zmieniono pojazdów: {0}, w zestawieniu: {1}</String>
<String key="ConsistSaidUndone">Cofnięto. {0}</String>
<String key="ConsistSaidRedone">Przywrócono. {0}</String>
<String key="SceneryImage">Obraz scenerii</String>
<String key="PanelSplitter">Rozdzielacz paneli</String>
<String key="SettingsCategories">Kategorie ustawień</String>

View File

@@ -567,6 +567,40 @@
<String key="SettingsRestored">Восстановлены сохранённые настройки</String>
<String key="TreeExpanded">развёрнуто</String>
<String key="TreeCollapsed">свёрнуто</String>
<String key="DepotConsistSources">Источники состава</String>
<String key="DepotVehicleInfo">Сведения о единице</String>
<String key="DepotVehicleEdit">Настройки единицы</String>
<String key="ScenarioDetails">Подробности сценария</String>
<String key="SectionLevel">Уровень раздела</String>
<String key="SearchFound">Найдено: {0}</String>
<String key="SpinUp">Увеличить</String>
<String key="SpinDown">Уменьшить</String>
<String key="ChromeMinimize">Свернуть</String>
<String key="ChromeMaximize">Развернуть</String>
<String key="ChromeRestore">Восстановить</String>
<String key="ChromeClose">Закрыть</String>
<String key="ScrollLineUp">На строку вверх</String>
<String key="ScrollLineDown">На строку вниз</String>
<String key="ScrollPageUp">На страницу вверх</String>
<String key="ScrollPageDown">На страницу вниз</String>
<String key="ScrollColumnLeft">На столбец влево</String>
<String key="ScrollColumnRight">На столбец вправо</String>
<String key="ScrollPageLeft">На страницу влево</String>
<String key="ScrollPageRight">На страницу вправо</String>
<String key="ScrollPosition">Положение</String>
<String key="TapeKeysHelp">Стрелки влево и вправо двигают по ленте, с Ctrl в десять раз дальше, Home и End ведут к её концам, Enter переносит чёрный ящик в этот момент.</String>
<String key="ConsistSaidEmpty">Состав пуст</String>
<String key="ConsistSaidAdded">Добавлено {0} на позицию {1} из {2}</String>
<String key="ConsistSaidRemoved">Удалено {0}, осталось единиц: {1}</String>
<String key="ConsistSaidTurned">{0} развёрнут</String>
<String key="ConsistSaidUnturned">{0} развёрнут обратно</String>
<String key="ConsistSaidTurnedMany">Развёрнуто единиц: {0}</String>
<String key="ConsistSaidMoved">{0} перемещён на позицию {1} из {2}</String>
<String key="ConsistSaidReordered">Порядок изменён</String>
<String key="ConsistSaidReplaced">{0} заменён на {1}</String>
<String key="ConsistSaidChangedMany">Изменено единиц: {0}, в составе: {1}</String>
<String key="ConsistSaidUndone">Отменено. {0}</String>
<String key="ConsistSaidRedone">Повторено. {0}</String>
<String key="SceneryImage">Изображение сценерии</String>
<String key="PanelSplitter">Разделитель панелей</String>
<String key="SettingsCategories">Категории настроек</String>