Merge pull request #50 from MaSzyna-EU07/fix/screen-reader-names

fix: a screen reader user can find, hear and work every part of the starter
This commit is contained in:
2026-11-16 09:15:39 +00:00
committed by GitHub
73 changed files with 4429 additions and 311 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,10 @@ 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();
DialogKeyboard.Install();
AvaloniaXamlLoader.Load(this);
AppServices.Current.SettingsStore.Load();

View File

@@ -81,6 +81,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,89 @@
using System;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.VisualTree;
namespace StarterNG.Controls;
/// <summary>
/// Says what a click changed out of sight, such as a quality level that moved a dozen
/// sliders or a time set to now. It wraps the whole window: a screen reader learns of
/// an element only on its way to the focused one, and this lies on every such way.
/// A text marked <see cref="ChangesProperty"/> is read whenever it changes.
/// </summary>
public class Announcer : Decorator
{
/// <summary>How long a message stays its name, so it is not read again later on.</summary>
public static readonly TimeSpan Shown = TimeSpan.FromSeconds(3);
public static readonly AttachedProperty<bool> ChangesProperty =
AvaloniaProperty.RegisterAttached<Announcer, TextBlock, bool>("Changes");
public static bool GetChanges(TextBlock block) => block.GetValue(ChangesProperty);
public static void SetChanges(TextBlock block, bool value) => block.SetValue(ChangesProperty, value);
static Announcer()
{
TextBlock.TextProperty.Changed.AddClassHandler<TextBlock>((block, _) =>
{
if (GetChanges(block))
Say(block, block.Text);
});
}
private readonly Func<DateTime> _now;
private string? _message;
private DateTime _saidAt;
public Announcer() : this(() => DateTime.UtcNow)
{
}
public Announcer(Func<DateTime> now) => _now = now;
/// <summary>The message while it is fresh, then nothing.</summary>
public string? Message => _message is not null && _now() - _saidAt < Shown ? _message : null;
/// <summary>Says the text through the announcer of the window <paramref name="from"/> is in.</summary>
public static void Say(Visual from, string? text)
{
var announcer = from as Announcer ?? from.FindAncestorOfType<Announcer>();
announcer?.Say(text);
}
public void Say(string? text)
{
if (string.IsNullOrWhiteSpace(text))
return;
string? before = Message;
_message = text.Trim();
_saidAt = _now();
// Its name changing is what makes a live region speak.
if (ControlAutomationPeer.CreatePeerForElement(this) is Peer peer)
peer.Told(before, _message);
}
protected override AutomationPeer OnCreateAutomationPeer() => new Peer(this);
private sealed class Peer : ControlAutomationPeer
{
public Peer(Announcer owner) : base(owner)
{
}
private Announcer Announcer => (Announcer)Owner;
public void Told(string? before, string now) =>
RaisePropertyChangedEvent(AutomationElementIdentifiers.NameProperty, before, now);
protected override string? GetNameCore() => Announcer.Message;
protected override AutomationLiveSetting GetLiveSettingCore() => AutomationLiveSetting.Polite;
protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Group;
}
}

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

@@ -0,0 +1,157 @@
using System;
using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Avalonia.VisualTree;
using StarterNG.Application;
namespace StarterNG.Controls;
/// <summary>
/// A tree entry that tells a screen reader whether it opens and what lies under it.
/// Avalonia's own says only that it is an entry, and hangs the entries under a group
/// on the panel inside the group, so a reader heard every scenery at level one: a
/// group such as Całkowo sounded like a scenery, and what was in it like its neighbours.
/// Under the mouse a reader hears only what lies there, the name in the row; the row
/// is told the state as well, so the mouse also hears that an entry opens.
/// </summary>
public class ExpandableTreeViewItem : TreeViewItem
{
protected override Type StyleKeyOverride => typeof(TreeViewItem);
protected override AutomationPeer OnCreateAutomationPeer() => new Peer(this);
/// <summary>The words for an open and a closed entry, in the starter's language.</summary>
public static Func<ExpandCollapseState, string?> StateWords { get; set; } = DefaultStateWords;
private static string? DefaultStateWords(ExpandCollapseState state) =>
AppServices.Current?.Localization is { } loc
? WordFor(state, key => loc[key])
: null;
public static string? WordFor(ExpandCollapseState state, Func<string, string> loc) => state switch
{
ExpandCollapseState.Expanded => loc("TreeExpanded"),
ExpandCollapseState.Collapsed => loc("TreeCollapsed"),
_ => null,
};
private Control? _row;
private string? _rowName;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_row = e.NameScope.Find<Control>("PART_LayoutRoot");
// A part of a template is passed over when Windows looks for what lies under the
// mouse, so the gaps beside the arrow and the name led to the entry, which told no
// state. As a control the row itself is found there.
if (_row is not null)
AutomationProperties.SetAccessibilityView(_row, AccessibilityView.Control);
TellRowLater();
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
if (AppServices.Current?.Localization is { } loc)
loc.LanguageChanged += TellRowLater;
TellRow();
}
protected override void OnUnloaded(RoutedEventArgs e)
{
base.OnUnloaded(e);
if (AppServices.Current?.Localization is { } loc)
loc.LanguageChanged -= TellRowLater;
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == IsExpandedProperty || change.Property == ItemCountProperty
|| change.Property == AutomationProperties.NameProperty)
TellRow();
else if (change.Property == HeaderProperty)
TellRowLater();
}
// A new header is laid out only after it is set.
private void TellRowLater() => Dispatcher.UIThread.Post(TellRow, DispatcherPriority.Loaded);
/// <summary>
/// Gives whatever the mouse may point at in the row the entry's state, and its name
/// where it shows no text of its own, such as the arrow or an icon.
/// </summary>
private void TellRow()
{
if (_row is null)
return;
string? state = StateWords(ExpandState);
string? name = AutomationProperties.GetName(this);
foreach (var part in _row.GetVisualDescendants().OfType<Control>().Prepend(_row))
{
if (string.IsNullOrEmpty(state))
part.ClearValue(AutomationProperties.HelpTextProperty);
else
AutomationProperties.SetHelpText(part, state);
if (part is TextBlock)
continue;
string? had = AutomationProperties.GetName(part);
if (string.IsNullOrEmpty(had) || had == _rowName)
AutomationProperties.SetName(part, name);
}
_rowName = name;
}
/// <summary>What a screen reader is told: a leaf, or open or closed.</summary>
public ExpandCollapseState ExpandState => StateFor(ItemCount > 0, IsExpanded);
public static ExpandCollapseState StateFor(bool hasChildren, bool expanded) => (hasChildren, expanded) switch
{
(false, _) => ExpandCollapseState.LeafNode,
(true, true) => ExpandCollapseState.Expanded,
(true, false) => ExpandCollapseState.Collapsed
};
/// <summary>The entry this one hangs under, or null at the top of the tree.</summary>
public ExpandableTreeViewItem? ReadableParent => ItemsControlFromItemContainer(this) as ExpandableTreeViewItem;
private sealed class Peer : TreeViewItemAutomationPeer, IExpandCollapseProvider
{
private readonly ExpandableTreeViewItem _item;
public Peer(ExpandableTreeViewItem item) : base(item)
{
_item = item;
item.PropertyChanged += (_, e) =>
{
if (e.Property == IsExpandedProperty && e.OldValue is bool was && e.NewValue is bool now)
RaisePropertyChangedEvent(ExpandCollapsePatternIdentifiers.ExpandCollapseStateProperty,
StateFor(item.ItemCount > 0, was), StateFor(item.ItemCount > 0, now));
};
}
// Only the way up changes: a reader counts the entries over this one to tell its
// level. The way down stays the controls on screen, so whatever the mouse points
// at still leads up through its entry to the window.
protected override AutomationPeer? GetParentCore() =>
_item.ReadableParent is { } parent ? GetOrCreate(parent) : base.GetParentCore();
public ExpandCollapseState ExpandCollapseState => _item.ExpandState;
public bool ShowsMenu => false;
public void Expand() => _item.IsExpanded = true;
public void Collapse() => _item.IsExpanded = false;
}
}

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,108 @@
using System;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
namespace StarterNG.Controls;
/// <summary>
/// A slider that tells a screen reader the value it shows beside it. Avalonia's own
/// gives only the bare number, which NVDA reads as a share of the slider's length:
/// -5 °C was read as 45, a fog of 2 km as wherever the knob stood on its scale.
/// The track under the mouse says the same, where its bare buttons and knob said nothing.
/// </summary>
public class ReadableSlider : Slider
{
public static readonly StyledProperty<string?> ValueTextProperty =
AvaloniaProperty.Register<ReadableSlider, string?>(nameof(ValueText));
/// <summary>The value as written for the reader, such as "2,4 km"; the number when unset.</summary>
public string? ValueText
{
get => GetValue(ValueTextProperty);
set => SetValue(ValueTextProperty, value);
}
protected override Type StyleKeyOverride => typeof(Slider);
protected override AutomationPeer OnCreateAutomationPeer() => new Peer(this);
/// <summary>What a screen reader is told the slider holds.</summary>
public string SpokenValue => SpokenText(ValueText, Value);
public static string SpokenText(string? valueText, double value) =>
string.IsNullOrWhiteSpace(valueText)
? value.ToString("0.##", CultureInfo.CurrentCulture)
: valueText.Trim();
/// <summary>What the mouse finds over the track: the slider's name and its value.</summary>
public string TrackText =>
AutomationProperties.GetName(this) is { } name && !string.IsNullOrWhiteSpace(name)
? $"{name.Trim()}: {SpokenValue}"
: SpokenValue;
private Track? _track;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_track = e.NameScope.Find<Track>("PART_Track");
NameTrack();
}
// The knob gets its own template only when first laid out.
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
NameTrack();
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == ValueProperty || change.Property == ValueTextProperty
|| change.Property == AutomationProperties.NameProperty)
NameTrack();
}
private void NameTrack()
{
if (_track is null)
return;
string text = TrackText;
foreach (var part in _track.GetVisualDescendants().OfType<Control>().Prepend(_track))
AutomationProperties.SetName(part, text);
}
private sealed class Peer : RangeBaseAutomationPeer, IValueProvider
{
private readonly ReadableSlider _slider;
// A moved knob is told by the range peer already; the reader then asks for this
// text, set by then. Telling the text's change too would have it spoken twice.
public Peer(ReadableSlider slider) : base(slider) => _slider = slider;
protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Slider;
protected override string GetClassNameCore() => "Slider";
string? IValueProvider.Value => _slider.SpokenValue;
bool IValueProvider.IsReadOnly => !_slider.IsEnabled;
void IValueProvider.SetValue(string? value)
{
if (!double.TryParse(value, NumberStyles.Float, CultureInfo.CurrentCulture, out double number))
throw new ArgumentException($"Not a number: {value}", nameof(value));
_slider.Value = number;
}
}
}

View File

@@ -0,0 +1,433 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
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)));
HeaderedContentControl.HeaderProperty.Changed.AddClassHandler<HeaderedContentControl>((c, _) => NameGroup(c));
ComboBox.PlaceholderTextProperty.Changed.AddClassHandler<ComboBox>((c, _) => Give(c, c.PlaceholderText));
TextBox.PlaceholderTextProperty.Changed.AddClassHandler<TextBox>((t, _) => Give(t, t.PlaceholderText));
SelectingItemsControl.SelectionChangedEvent.AddClassHandler<ComboBox>((c, _) => TellChoice(c));
Control.LoadedEvent.AddClassHandler<ComboBox>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<TextBox>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<Slider>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<NumericUpDown>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<DatePicker>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<TimePicker>((c, _) => NameByLabel(c));
Control.LoadedEvent.AddClassHandler<Image>((i, _) => NamePicture(i));
Control.LoadedEvent.AddClassHandler<PathIcon>((i, _) => NamePicture(i));
TemplatedControl.TemplateAppliedEvent.AddClassHandler<DatePicker>((p, e) => KeepPickerButton(p, e));
TemplatedControl.TemplateAppliedEvent.AddClassHandler<TimePicker>((p, e) => KeepPickerButton(p, e));
DatePicker.SelectedDateProperty.Changed.AddClassHandler<DatePicker>((p, _) => NamePicker(p));
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
// "Avalonia.Controls.Grid": its texts are filled in only after the name is looked for.
private static readonly ConditionalWeakTable<TemplatedControl, Button> PickerButtons = new();
private static void KeepPickerButton(TemplatedControl picker, TemplateAppliedEventArgs e)
{
if (e.NameScope.Find<Button>("PART_FlyoutButton") is not { } button)
return;
PickerButtons.AddOrUpdate(picker, button);
NamePicker(picker);
}
private static void NamePicker(TemplatedControl picker)
{
if (!PickerButtons.TryGetValue(picker, out var button))
return;
string? value = picker switch
{
DatePicker date => DateText(date.SelectedDate, date.YearVisible),
TimePicker time => TimeText(time.SelectedTime),
_ => null
};
AutomationProperties.SetName(button, PickerText(AutomationProperties.GetName(picker), value));
}
/// <summary>The picker's label and what it holds, as the button inside it is read.</summary>
public static string? PickerText(string? label, string? value)
{
if (string.IsNullOrEmpty(label))
return value;
return string.IsNullOrEmpty(value) ? label : $"{label}: {value}";
}
/// <summary>Day and month in words, the year too when the picker shows one.</summary>
public static string? DateText(DateTimeOffset? date, bool withYear) =>
date?.ToString(withYear ? "D" : "M", CultureInfo.CurrentCulture);
public static string? TimeText(TimeSpan? time) =>
time?.ToString(@"hh\:mm", CultureInfo.InvariantCulture);
// The labels already followed, so a label read again is not followed twice.
private static readonly ConditionalWeakTable<TextBlock, Control> Followed = new();
/// <summary>Longer than this, a text beside a field is a description, not its label.</summary>
private const int LabelLength = 60;
/// <summary>
/// A field named by the label a sighted reader sees beside it, and named again when
/// the label changes with the language. A name given otherwise is left alone.
/// </summary>
public static void NameByLabel(Control input)
{
if (LabelOf(input) is not { } label)
return;
Give(input, TextOf(label));
if (Followed.TryAdd(label, input))
label.PropertyChanged += (_, e) =>
{
if (e.Property == TextBlock.TextProperty)
Give(input, TextOf(label));
};
}
/// <summary>
/// The text that labels a field: to its left in the same grid row, above it in the
/// same grid column, or just before it in any other panel. Null when there is none.
/// </summary>
public static TextBlock? LabelOf(Control input)
{
if (input.Parent is not Panel panel)
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);
return labels.Where(t => Grid.GetRow(t) == row && Grid.GetColumn(t) < column)
.OrderByDescending(Grid.GetColumn).FirstOrDefault()
?? labels.FirstOrDefault(t => Grid.GetColumn(t) == column && Grid.GetRow(t) == row - 1);
}
int at = panel.Children.IndexOf(input);
return at > 0 && panel.Children[at - 1] is TextBlock before && labels.Contains(before) ? before : null;
}
private static bool IsLabel(TextBlock block) =>
block.IsVisible && TextOf(block) is { Length: <= LabelLength };
/// <summary>
/// A panel with a title, such as Scenerie or Skład, made a named group: the reader
/// says where focus went in, where before the panel was not there for it at all.
/// Tabs and expanders, which are panels with a title too, speak for themselves.
/// </summary>
private static void NameGroup(HeaderedContentControl panel)
{
if (panel.GetType() != typeof(HeaderedContentControl) && panel is not SettingsSection)
return;
string? name = TextOf(panel.Header);
Give(panel, name);
AutomationProperties.SetControlTypeOverride(panel, name is null ? null : AutomationControlType.Group);
// Content as well as control: NVDA passes over a group that is not both.
AutomationProperties.SetAccessibilityView(panel, name is null ? AccessibilityView.Default : AccessibilityView.Content);
}
// How far up a picture looks for what it shows: the button or card it sits in,
// not the panel around them.
private const int PictureReach = 3;
/// <summary>
/// Names a picture after the caption beside it or the button or card it lies in. Under the mouse a reader
/// hears what lies there, and a bare picture said nothing: a vehicle in the consist,
/// the logo, an icon on a button.
/// </summary>
public static void NamePicture(Control picture)
{
if ((!string.IsNullOrEmpty(AutomationProperties.GetName(picture)) && !Given.TryGetValue(picture, out _))
|| AutomationProperties.GetLabeledBy(picture) is not null)
return;
// A caption beside it says what it shows, such as a vehicle class by its picture.
if (picture.Parent is Panel row
&& row.Children.OfType<TextBlock>().FirstOrDefault(t => t.IsVisible && !string.IsNullOrWhiteSpace(t.Text)) is { } caption)
{
AutomationProperties.SetLabeledBy(picture, caption);
return;
}
var holder = picture.Parent as Control;
for (int i = 0; i < PictureReach && holder is not null; i++, holder = holder.Parent as Control)
{
if (!string.IsNullOrEmpty(AutomationProperties.GetName(holder)) || holder is Button)
{
AutomationProperties.SetLabeledBy(picture, holder);
return;
}
if (TextOf(ToolTip.GetTip(holder)) is { } tip)
{
Give(picture, tip);
return;
}
}
}
/// <summary>
/// Says what a closed list now holds when the arrow keys change it. Avalonia tells
/// Windows of a new value only for a list one types into, so NVDA said nothing.
/// </summary>
public static void TellChoice(ComboBox combo)
{
if (combo.IsKeyboardFocusWithin && !combo.IsDropDownOpen && !combo.IsEditable)
Announcer.Say(combo, SpokenItem(combo.SelectedItem));
}
/// <summary>What a reader is told a list entry is, as Avalonia tells it.</summary>
public static string? SpokenItem(object? item) => item switch
{
null => null,
Control c when AutomationProperties.GetName(c) is { Length: > 0 } name => name,
ContentControl c => TextOf(c.Content) ?? c.Content?.ToString(),
_ => TextOf(item) ?? item.ToString(),
};
// A sign such as "?" says nothing read aloud; its tooltip says what it does.
private static void NameButton(Button button) =>
Give(button, button.Content is string text && text.Any(char.IsLetterOrDigit)
? null
: TextOf(ToolTip.GetTip(button)) ?? TextOf(button.Content));
// The descriptions given here, so a later one replaces it but nothing else.
private static readonly ConditionalWeakTable<StyledElement, string> Described = new();
/// <summary>
/// The inputs of a setting row, described by the row's explanation and the note on
/// why the simulator would pass it over: a reader hears them after the name, where
/// a sighted one sees them under it.
/// </summary>
public static void DescribeInputs(object? content, params string?[] notes)
{
string? text = Join(notes) is { Length: > 0 } joined ? joined : null;
foreach (var input in DescribedInputs(content))
Describe(input, text);
}
private static void Describe(StyledElement target, string? text)
{
string? current = AutomationProperties.GetHelpText(target);
bool ours = Described.TryGetValue(target, out string? given) && current == given;
if (!string.IsNullOrEmpty(current) && !ours)
return;
if (string.IsNullOrEmpty(text))
{
if (ours)
target.ClearValue(AutomationProperties.HelpTextProperty);
Described.Remove(target);
return;
}
AutomationProperties.SetHelpText(target, text);
Described.AddOrUpdate(target, text);
}
/// <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);
}
/// <summary>
/// The value a setting row shows, given to the slider in it, so the reader hears
/// "100%" or "Wyłączone" and not where the knob stands.
/// </summary>
public static void TellValue(object? content, string? valueText)
{
foreach (var slider in Inputs(content).OfType<ReadableSlider>())
slider.ValueText = valueText;
}
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>()
};
// A check box says its own text, so it is described but never named by the row.
private static IEnumerable<Control> DescribedInputs(object? content) => content switch
{
CheckBox box => new[] { (Control)box },
Panel panel => panel.Children.SelectMany(DescribedInputs),
Decorator decorator => DescribedInputs(decorator.Child),
_ => Inputs(content)
};
/// <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,
// 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),
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

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

@@ -1,5 +1,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace StarterNG.Controls;
@@ -73,6 +74,25 @@ 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);
if (change.Property == ValueTextProperty || change.Property == ContentProperty)
ScreenReaderNames.TellValue(Content, ValueText);
if (change.Property == DescriptionProperty || change.Property == IdleNoteProperty ||
change.Property == ContentProperty)
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
}
// 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);
ScreenReaderNames.TellValue(Content, ValueText);
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
}
private void UpdatePseudoClasses()

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

@@ -1,6 +1,8 @@
using System.Collections.Generic;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Layout;
using Avalonia.Markup.Xaml.MarkupExtensions;
using Avalonia.Media;
namespace StarterNG.Infrastructure;
@@ -13,31 +15,34 @@ public static class StatsBar
for (int i = 0; i < fields.Count; i++)
{
var (label, value) = fields[i];
var pair = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 5,
// no trailing gap on the last pair - these sit in a panel title,
// flush with its right edge
Margin = new Avalonia.Thickness(0, 0, i == fields.Count - 1 ? 0 : 22, 0),
VerticalAlignment = VerticalAlignment.Center
};
pair.Children.Add(new TextBlock
{
Text = label,
FontSize = 12,
Opacity = 0.65,
VerticalAlignment = VerticalAlignment.Center
});
pair.Children.Add(new TextBlock
{
Text = value,
FontSize = 12,
FontWeight = FontWeight.SemiBold,
VerticalAlignment = VerticalAlignment.Center,
TextTrimming = TextTrimming.CharacterEllipsis
});
host.Children.Add(pair);
host.Children.Add(Figure(label, value, last: i == fields.Count - 1));
}
}
/// <summary>
/// One text holding the label and the value: under the mouse a reader hears the
/// text that lies there, and with two it heard "Masa [t]:" without the mass.
/// </summary>
public static TextBlock Figure(string label, string value, bool last)
{
var name = new Run(label);
// The label dimmed, as the panel titles' other labels.
name.Bind(TextElement.ForegroundProperty, new DynamicResourceExtension("CarbonFgDim"));
return new TextBlock
{
FontSize = 12,
// no trailing gap on the last pair - these sit in a panel title,
// flush with its right edge
Margin = new Avalonia.Thickness(0, 0, last ? 0 : 22, 0),
VerticalAlignment = VerticalAlignment.Center,
TextTrimming = TextTrimming.CharacterEllipsis,
Inlines = new InlineCollection
{
name,
new Run(" "),
new Run(value) { FontWeight = FontWeight.SemiBold },
},
};
}
}

View File

@@ -8,124 +8,129 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:views="clr-namespace:StarterNG.Views"
xmlns:starterNg="clr-namespace:StarterNG"
xmlns:ctl="clr-namespace:StarterNG.Controls"
Title="Starter MaSzyna"
Icon="/Assets/starter.ico"
Width="1010" Height="768" MinWidth="1010" MinHeight="666"
WindowStartupLocation="CenterScreen">
<DockPanel LastChildFill="True">
<!-- Says what a click changed out of sight; see Announcer. -->
<ctl:Announcer>
<DockPanel LastChildFill="True">
<Border x:Name="TopBar" DockPanel.Dock="Top"
Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderThickness="0,0,0,1"
PointerPressed="TitleBar_OnPointerPressed">
<Grid RowDefinitions="44">
<Border x:Name="TopBar" DockPanel.Dock="Top" TabIndex="0"
Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}"
BorderThickness="0,0,0,1"
PointerPressed="TitleBar_OnPointerPressed">
<Grid RowDefinitions="44">
<Grid ColumnDefinitions="Auto,*,Auto" Background="Transparent">
<Grid ColumnDefinitions="Auto,*,Auto" Background="Transparent">
<StackPanel x:Name="TopBarLeft" Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Stretch">
<RadioButton x:Name="NavScenarios" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="scenarios" IsChecked="True"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavScenarios], Source={x:Static starterNg:App.Loc}}" />
<RadioButton x:Name="NavDepot" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="depot"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavDepot], Source={x:Static starterNg:App.Loc}}" />
<RadioButton x:Name="NavSettings" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="settings"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavSettings], Source={x:Static starterNg:App.Loc}}" />
<Button Classes="Basic" Click="openLastLogClick" Width="48" Cursor="Hand"
HorizontalContentAlignment="Center"
ToolTip.Tip="{Binding [ShowLatestLogTooltip], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="FileDocument" Height="16" Width="16" />
</Button>
<Button Classes="Basic" Click="openHaslerTapesClick" Width="48" Cursor="Hand"
HorizontalContentAlignment="Center"
ToolTip.Tip="{Binding [HaslerTapesTooltip], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChartLine" Height="16" Width="16" />
</Button>
<Button x:Name="HelpButton" Classes="Basic" Width="48" Cursor="Hand"
ToolTip.Tip="{Binding [Help], Source={x:Static starterNg:App.Loc}}"
Click="HelpButton_OnClick"
Content="?" FontWeight="Bold" FontSize="16"
HorizontalContentAlignment="Center" />
</StackPanel>
<StackPanel x:Name="TopBarRight" Grid.Column="2" Orientation="Horizontal"
VerticalAlignment="Center" Margin="0,0,3,0" Spacing="0">
<StackPanel x:Name="VersionPanel" Orientation="Vertical" VerticalAlignment="Center" Margin="0,0,6,0">
<Label Content="{Binding [Version], Source={x:Static starterNg:App.Loc}}"
FontSize="12" Foreground="{StaticResource CarbonFgDim}" Padding="0" />
<Label Content="{x:Static starterNg:AppInfo.Version}"
FontSize="12" Foreground="{StaticResource CarbonFg}" Padding="0" />
<StackPanel x:Name="TopBarLeft" Grid.Column="0" AutomationProperties.LandmarkType="Navigation" AutomationProperties.ControlTypeOverride="Group" AutomationProperties.AccessibilityView="Content" Orientation="Horizontal" VerticalAlignment="Stretch">
<RadioButton x:Name="NavScenarios" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="scenarios" IsChecked="True"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavScenarios], Source={x:Static starterNg:App.Loc}}" />
<RadioButton x:Name="NavDepot" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="depot"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavDepot], Source={x:Static starterNg:App.Loc}}" />
<RadioButton x:Name="NavSettings" GroupName="nav" Theme="{StaticResource NavTab}"
Tag="settings"
IsCheckedChanged="Nav_OnCheckedChanged"
Content="{Binding [NavSettings], Source={x:Static starterNg:App.Loc}}" />
<Button Classes="Basic" Click="openLastLogClick" Width="48" Cursor="Hand"
HorizontalContentAlignment="Center"
ToolTip.Tip="{Binding [ShowLatestLogTooltip], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="FileDocument" Height="16" Width="16" />
</Button>
<Button Classes="Basic" Click="openHaslerTapesClick" Width="48" Cursor="Hand"
HorizontalContentAlignment="Center"
ToolTip.Tip="{Binding [HaslerTapesTooltip], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChartLine" Height="16" Width="16" />
</Button>
<Button x:Name="HelpButton" Classes="Basic" Width="48" Cursor="Hand"
ToolTip.Tip="{Binding [Help], Source={x:Static starterNg:App.Loc}}"
Click="HelpButton_OnClick"
Content="?" FontWeight="Bold" FontSize="16"
HorizontalContentAlignment="Center" />
</StackPanel>
<ComboBox x:Name="LangCombo" Width="96" VerticalAlignment="Center"
SelectionChanged="LangCombo_OnSelectionChanged" />
<StackPanel x:Name="TopBarRight" Grid.Column="2" Orientation="Horizontal"
VerticalAlignment="Center" Margin="0,0,3,0" Spacing="0">
<StackPanel x:Name="VersionPanel" Orientation="Vertical" VerticalAlignment="Center" Margin="0,0,6,0">
<Label Content="{Binding [Version], Source={x:Static starterNg:App.Loc}}"
FontSize="12" Foreground="{StaticResource CarbonFgDim}" Padding="0" />
<Label Content="{x:Static starterNg:AppInfo.Version}"
FontSize="12" Foreground="{StaticResource CarbonFg}" Padding="0" />
</StackPanel>
<Button Classes="Basic" Cursor="Hand" Tag="https://discord.gg/eu07" Click="linkClick"
ToolTip.Tip="Discord">
<PathIcon Data="{StaticResource DiscordLogo}" Height="12" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://www.facebook.com/MaSzynaeu07pl" Click="linkClick"
ToolTip.Tip="Facebook">
<materialIcons:MaterialIcon Kind="Facebook" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://www.youtube.com/@eu07official" Click="linkClick"
ToolTip.Tip="YouTube">
<materialIcons:MaterialIcon Kind="Youtube" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://github.com/MaSzyna-EU07/" Click="linkClick"
ToolTip.Tip="GitHub">
<materialIcons:MaterialIcon Kind="Github" />
</Button>
<ComboBox x:Name="LangCombo" Width="96" VerticalAlignment="Center"
AutomationProperties.Name="{Binding [Language], Source={x:Static starterNg:App.Loc}}"
SelectionChanged="LangCombo_OnSelectionChanged" />
<Button x:Name="LogoLink" Classes="Basic" Cursor="Hand" Tag="http://eu07.pl/" Click="linkClick"
Padding="6,0" Margin="4,0,0,0"
ToolTip.Tip="eu07.pl">
<Image Source="/Assets/Logo/maszyna_white.png" Height="26" />
</Button>
</StackPanel>
<Button Classes="Basic" Cursor="Hand" Tag="https://discord.gg/eu07" Click="linkClick"
ToolTip.Tip="Discord">
<PathIcon Data="{StaticResource DiscordLogo}" Height="12" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://www.facebook.com/MaSzynaeu07pl" Click="linkClick"
ToolTip.Tip="Facebook">
<materialIcons:MaterialIcon Kind="Facebook" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://www.youtube.com/@eu07official" Click="linkClick"
ToolTip.Tip="YouTube">
<materialIcons:MaterialIcon Kind="Youtube" />
</Button>
<Button Classes="Basic" Cursor="Hand" Tag="http://github.com/MaSzyna-EU07/" Click="linkClick"
ToolTip.Tip="GitHub">
<materialIcons:MaterialIcon Kind="Github" />
</Button>
<Button x:Name="LogoLink" Classes="Basic" Cursor="Hand" Tag="http://eu07.pl/" Click="linkClick"
Padding="6,0" Margin="4,0,0,0"
ToolTip.Tip="eu07.pl">
<Image Source="/Assets/Logo/maszyna_white.png" Height="26" />
</Button>
</StackPanel>
</Grid>
</Grid>
</Border>
<!-- The other ways to start - without saving, free fly - were only under the
right button; the arrow beside it says they exist. The editor is not one
of them: it opens the scenery itself, so it has a button of its own. -->
<Grid DockPanel.Dock="Bottom" ColumnDefinitions="*,Auto,Auto,Auto" ColumnSpacing="4" Margin="3">
<Button Name="startButton" Classes="Start" Height="42"
TabIndex="9"
Click="StartButton_OnClick"
Content="{Binding [Start], Source={x:Static starterNg:App.Loc}}" />
<Button Name="startMoreButton" Grid.Column="1" Classes="Start" Width="36" Height="42"
TabIndex="10" Cursor="Hand"
Click="StartMoreButton_OnClick"
ToolTip.Tip="{Binding [StartMore], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChevronUp" Width="20" Height="20" />
</Button>
<Button Name="startEditorButton" Grid.Column="2" Classes="Flat" Height="42" Padding="14,0"
TabIndex="11" Cursor="Hand" VerticalContentAlignment="Center"
Click="StartEditorButton_OnClick" />
<Button Name="startEditorMoreButton" Grid.Column="3" Classes="Flat" Width="36" Height="42" Padding="0"
TabIndex="12" Cursor="Hand" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
Click="StartEditorMoreButton_OnClick"
ToolTip.Tip="{Binding [StartEditorWizard], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChevronUp" Width="20" Height="20" />
</Button>
</Grid>
</Border>
<!-- The other ways to start - without saving, free fly - were only under the
right button; the arrow beside it says they exist. The editor is not one
of them: it opens the scenery itself, so it has a button of its own. -->
<Grid DockPanel.Dock="Bottom" ColumnDefinitions="*,Auto,Auto,Auto" ColumnSpacing="4" Margin="3">
<Button Name="startButton" Classes="Start" Height="42"
TabIndex="9"
Click="StartButton_OnClick"
Content="{Binding [Start], Source={x:Static starterNg:App.Loc}}" />
<Button Name="startMoreButton" Grid.Column="1" Classes="Start" Width="36" Height="42"
TabIndex="10" Cursor="Hand"
Click="StartMoreButton_OnClick"
ToolTip.Tip="{Binding [StartMore], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChevronUp" Width="20" Height="20" />
</Button>
<Button Name="startEditorButton" Grid.Column="2" Classes="Flat" Height="42" Padding="14,0"
TabIndex="11" Cursor="Hand" VerticalContentAlignment="Center"
Click="StartEditorButton_OnClick" />
<Button Name="startEditorMoreButton" Grid.Column="3" Classes="Flat" Width="36" Height="42" Padding="0"
TabIndex="12" Cursor="Hand" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
Click="StartEditorMoreButton_OnClick"
ToolTip.Tip="{Binding [StartEditorWizard], Source={x:Static starterNg:App.Loc}}">
<materialIcons:MaterialIcon Kind="ChevronUp" Width="20" Height="20" />
</Button>
</Grid>
<!-- Scrolls only below the size the pages are laid out for; see KeepPagesUsable. -->
<ScrollViewer x:Name="PageScroll" Margin="3,3,3,0" TabIndex="1"
HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled">
<Panel x:Name="PageHost">
<views:Scenarios x:Name="ScenariosView" />
<views:Depot x:Name="DepotView" IsVisible="False" />
<views:Settings x:Name="SettingsView" IsVisible="False" />
</Panel>
</ScrollViewer>
</DockPanel>
<!-- Scrolls only below the size the pages are laid out for; see KeepPagesUsable. -->
<ScrollViewer x:Name="PageScroll" AutomationProperties.LandmarkType="Main" AutomationProperties.AccessibilityView="Content" Margin="3,3,3,0" TabIndex="1"
HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled">
<Panel x:Name="PageHost">
<views:Scenarios x:Name="ScenariosView" />
<views:Depot x:Name="DepotView" IsVisible="False" />
<views:Settings x:Name="SettingsView" IsVisible="False" />
</Panel>
</ScrollViewer>
</DockPanel>
</ctl:Announcer>
</Window>

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

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

@@ -43,6 +43,10 @@
<ProjectReference Include="..\Eu07.BlackBox.Views\Eu07.BlackBox.Views.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="StarterNG.Tests" />
</ItemGroup>
<ItemGroup>
<Folder Include="Assets\Logo\" />
</ItemGroup>

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

@@ -61,8 +61,10 @@
with no label hides PART_Label, and without this the
column would collapse onto the key and every
explanation would start at a different place again. -->
<!-- Selectable for copying, but no stop for Tab: a reader found
nothing there to say between one setting and the next. -->
<SelectableTextBlock Name="PART_ConfigKey"
Grid.Row="1" Grid.Column="0"
Grid.Row="1" Grid.Column="0" IsTabStop="False"
Text="{TemplateBinding ConfigKey}"
FontFamily="Consolas, DejaVu Sans Mono, Liberation Mono, Menlo, Courier New"
FontSize="11"

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

@@ -81,11 +81,12 @@
PointerWheelChanged="Combo_OnPointerWheel"
SelectionChanged="ClassCombo_OnSelectionChanged" />
<TextBox Name="searchBox" Grid.Row="3" Margin="0,0,0,6"
<TextBox Name="searchBox" AutomationProperties.LandmarkType="Search" Grid.Row="3" Margin="0,0,0,6"
PlaceholderText="{Binding [SearchAllVehicles], Source={x:Static starterNg:App.Loc}}"
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" />
@@ -126,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">
@@ -145,6 +147,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 +163,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>
@@ -195,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" />
@@ -213,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
@@ -318,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,102 @@
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");
var (head, tail) = Common(before, after);
var gone = before.Skip(head).Take(before.Count - head - tail).ToList();
var come = after.Skip(head).Take(after.Count - head - tail).ToList();
if (gone.Count == 0 && come.Count == 0)
return null;
if (gone.Count == 0)
return string.Format(loc("ConsistSaidAdded"), Labels(come), head + 1, after.Count);
if (come.Count == 0)
return string.Format(loc("ConsistSaidRemoved"), Labels(gone), vehicles);
if (gone.Count == come.Count && SameCount(gone, come, head, after.Count, loc) is { } said)
return said;
return string.Format(loc("ConsistSaidChangedMany"), Math.Max(gone.Count, come.Count), vehicles);
}
/// <summary>How many units at the front and at the back stayed as they were.</summary>
private static (int Head, int Tail) Common(IReadOnlyList<Unit> before, IReadOnlyList<Unit> after)
{
int head = 0;
while (head < before.Count && head < after.Count && before[head] == after[head])
head++;
int tail = 0;
while (tail < before.Count - head && tail < after.Count - head
&& before[before.Count - 1 - tail] == after[after.Count - 1 - tail])
tail++;
return (head, tail);
}
/// <summary>A change that left as many units as there were: turned, moved, reordered or one replaced; or null.</summary>
private static string? SameCount(List<Unit> gone, List<Unit> come, int head, int count, Func<string, string> loc)
{
// The same vehicles in the same places: some of them turned round.
if (gone.Select(u => u.Label).SequenceEqual(come.Select(u => u.Label)))
return Turned(gone, come, loc);
// One vehicle taken out and put back elsewhere: the rest keep their order.
if (MovedOne(gone, come) is { } moved)
return string.Format(loc("ConsistSaidMoved"), moved.Unit.Label, head + moved.To + 1, count);
if (gone.OrderBy(u => u.Label, StringComparer.Ordinal).SequenceEqual(
come.OrderBy(u => u.Label, StringComparer.Ordinal)))
return loc("ConsistSaidReordered");
return gone.Count == 1 ? string.Format(loc("ConsistSaidReplaced"), gone[0].Label, come[0].Label) : null;
}
private static string Turned(List<Unit> gone, List<Unit> come, Func<string, string> loc)
{
var turned = come.Where((u, i) => u.Turned != gone[i].Turned).ToList();
if (turned.Count != 1)
return string.Format(loc("ConsistSaidTurnedMany"), turned.Count);
string key = turned[0].Turned ? "ConsistSaidTurned" : "ConsistSaidUnturned";
return string.Format(loc(key), turned[0].Label);
}
/// <summary>The unit and the place it went to when one alone moved, or null.</summary>
private static (Unit Unit, int To)? MovedOne(List<Unit> gone, List<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

@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Input;
@@ -59,6 +60,8 @@ public sealed class VehicleBrowser
private DispatcherTimer? _searchTimer;
private readonly SearchResultsTeller _searchResults;
private Func<string?, bool>? _categoryFilter;
private string? _classFilter;
@@ -81,6 +84,7 @@ public sealed class VehicleBrowser
vehicleListBox.ContextRequested += List_OnContextRequested;
_searchResults = new SearchResultsTeller(searchBox, () => vehicleListBox.ItemCount);
_searchTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(220) };
_searchTimer.Tick += (_, _) =>
{
@@ -338,6 +342,7 @@ public sealed class VehicleBrowser
Selected = null;
miniPreview.Source = null;
miniPreview.ClearValue(AutomationProperties.NameProperty);
addVehicleButton.IsEnabled = false;
vehicleListBox.Items.Clear();
@@ -381,10 +386,12 @@ public sealed class VehicleBrowser
public void VehicleListBox_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (vehicleListBox.SelectedItem is ListBoxItem { Tag: VehicleTexture texture })
if (vehicleListBox.SelectedItem is ListBoxItem { Tag: VehicleTexture texture } row)
{
Selected = texture;
miniPreview.Source = _minis.Get(_db.ResolveMiniName(texture), MiniPreviewHeight);
// Under the mouse a reader hears which vehicle the picture shows.
AutomationProperties.SetName(miniPreview, ScreenReaderNames.TextOf(row.Content));
addVehicleButton.IsEnabled = true;
SyncCombosTo(texture);
@@ -397,6 +404,7 @@ public sealed class VehicleBrowser
{
Selected = null;
miniPreview.Source = null;
miniPreview.ClearValue(AutomationProperties.NameProperty);
addVehicleButton.IsEnabled = false;
}
}
@@ -559,6 +567,7 @@ public sealed class VehicleBrowser
if (_suppress || _searchTimer is null) return;
_searchTimer.Stop();
_searchTimer.Start();
_searchResults.Changed();
}
public void HideArchivalCheck_OnChanged(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
@@ -578,12 +587,29 @@ public sealed class VehicleBrowser
var set = _db.ResolveSet(texture);
var browserTex = set is { Count: > 0 } ? set[0] : texture;
WhileSyncing(() =>
KeepingKeyboardFocus(() => WhileSyncing(() =>
{
ApplyFilters(VehicleInfo.CategoryOf(browserTex), VehicleInfo.ClassOf(browserTex));
Rebuild();
SelectListEntry(browserTex);
});
}));
}
/// <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 +617,7 @@ public sealed class VehicleBrowser
if (_syncingCombos || !ApplyFilters(VehicleInfo.CategoryOf(texture), VehicleInfo.ClassOf(texture)))
return;
PostSyncing(() => { Rebuild(); SelectListEntry(texture); });
PostSyncing(() => KeepingKeyboardFocus(() => { Rebuild(); SelectListEntry(texture); }));
}
private void WhileSyncing(Action work)

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;
@@ -13,6 +15,7 @@ using Material.Icons.Avalonia;
using StarterNG.Classes;
using StarterNG.Domain;
using StarterNG.Domain.Vehicles;
using StarterNG.Controls;
namespace StarterNG.Views;
@@ -146,6 +149,10 @@ public sealed class VehicleCards
Focusable = true
};
card.Classes.Add("ConsistCard");
// The card shows pictures only; without a name a screen reader said nothing on it.
AutomationProperties.SetName(card, CardName(item, index));
AutomationProperties.SetControlTypeOverride(card, AutomationControlType.ListItem);
AutomationProperties.SetIsControlElementOverride(card, true);
card.GotFocus += (_, _) => Select(item, null);
card.KeyDown += (_, e) => OnCardKey(card, item, e);
card.PointerPressed += (_, e) =>
@@ -179,6 +186,11 @@ public sealed class VehicleCards
return card;
}
/// <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)))}"
+ (item.Flipped ? $", {App.Loc["Reversed"]}" : string.Empty);
private string CardCaption(ConsistItem item, Dynamic car, int index) =>
TrainsetDisplay.VehicleLabel(car,
head: index == 0 && ReferenceEquals(car, Consist.HeadCar(item)) && TrainsetDisplay.IsPowered(car));
@@ -411,12 +423,22 @@ public sealed class VehicleCards
panel.Children.Add(apply);
var flyout = new Flyout { Content = panel, Placement = PlacementMode.Top };
apply.Click += (_, _) =>
void Apply()
{
_consist.SetWagonNumber(car, (int)(num.Value ?? 0));
flyout.Hide();
}
apply.Click += (_, _) => Apply();
// As the flyout for several vehicles does: typed into at once, Enter sets it.
num.KeyDown += (_, e) =>
{
if (e.Key != Key.Enter) return;
e.Handled = true;
Apply();
};
flyout.ShowAt(anchor);
num.Focus();
}
/// <summary>
@@ -623,6 +645,10 @@ public sealed class VehicleCards
btn.Content = glyph;
btn.Foreground = new SolidColorBrush(Color.Parse(color));
// "2" alone said nothing read aloud: the reader hears who rides in it.
int choice = CrewChoices.IndexOf(type);
AutomationProperties.SetName(btn, ScreenReaderNames.PickerText(
App.Loc["CrewLabel"], choice >= 0 ? App.Loc[CrewChoices.All[choice].Key] : glyph));
}
/// <summary>
@@ -668,7 +694,7 @@ public sealed class VehicleCards
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
foreach (var (type, key) in CrewChoices.All)
crew.AddItem((item.Driver == type ? "● " : "○ ") + App.Loc[key], () => _consist.SetCrew(item, type));
crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type)));
menu.Items.Add(crew);
// The member the panels show, not always the first car of a unit.

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 StackPanel 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 Border 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

@@ -4,6 +4,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:starterNg="clr-namespace:StarterNG"
xmlns:infra="clr-namespace:StarterNG.Infrastructure"
xmlns:ctl="clr-namespace:StarterNG.Controls"
xmlns:materialIcons="clr-namespace:Material.Icons.Avalonia;assembly=Material.Icons.Avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="StarterNG.Views.Scenarios"
@@ -33,6 +34,7 @@
IsCheckedChanged="ArchivalSwitch_OnChanged"
Content="{Binding [HideArchivalSceneries], Source={x:Static starterNg:App.Loc}}" />
<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 +51,7 @@
</DockPanel>
</HeaderedContentControl>
<GridSplitter Grid.Column="1" Grid.Row="0" Width="6"
<GridSplitter IsTabStop="False" AutomationProperties.Name="{Binding [PanelSplitter], Source={x:Static starterNg:App.Loc}}" Grid.Column="1" Grid.Row="0" Width="6"
Background="Transparent" ResizeDirection="Columns" />
<Grid Grid.Column="2" Grid.Row="0">
@@ -70,13 +72,14 @@
</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" 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">
@@ -108,11 +111,11 @@
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Date], Source={x:Static starterNg:App.Loc}}" />
<Grid Grid.Row="0" Grid.Column="2" ColumnDefinitions="150,10,150,10,*">
<DatePicker Grid.Column="0" Name="weatherDate"
<DatePicker Grid.Column="0" Name="weatherDate" AutomationProperties.Name="{Binding [Date], Source={x:Static starterNg:App.Loc}}"
YearVisible="False" MinWidth="0"
VerticalAlignment="Center" HorizontalAlignment="Stretch"
SelectedDateChanged="WeatherDate_OnChanged" />
<ComboBox Grid.Column="2" Name="weatherSeason" Classes="Localized"
<ComboBox Grid.Column="2" Name="weatherSeason" AutomationProperties.Name="{Binding [Season], Source={x:Static starterNg:App.Loc}}" Classes="Localized"
HorizontalAlignment="Stretch" VerticalAlignment="Center"
SelectionChanged="WeatherSeason_OnChanged">
<ComboBoxItem Tag="0" Content="{Binding [SeasonNow], Source={x:Static starterNg:App.Loc}}" />
@@ -130,7 +133,7 @@
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Time], Source={x:Static starterNg:App.Loc}}" />
<Grid Grid.Row="2" Grid.Column="2" ColumnDefinitions="150,8,*">
<TimePicker Grid.Column="0" Name="weatherTime"
<TimePicker Grid.Column="0" Name="weatherTime" AutomationProperties.Name="{Binding [Time], Source={x:Static starterNg:App.Loc}}"
ClockIdentifier="24HourClock" MinuteIncrement="1"
MinWidth="0" VerticalAlignment="Center"
HorizontalAlignment="Stretch"
@@ -145,7 +148,7 @@
<TextBlock Grid.Row="4" Grid.Column="0" VerticalAlignment="Center"
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Temperature], Source={x:Static starterNg:App.Loc}}" />
<Slider Grid.Row="4" Grid.Column="2" Name="weatherTemp"
<ctl:ReadableSlider Grid.Row="4" Grid.Column="2" Name="weatherTemp" AutomationProperties.Name="{Binding [Temperature], Source={x:Static starterNg:App.Loc}}"
Minimum="-50" Maximum="50"
TickFrequency="1" IsSnapToTickEnabled="True"
ValueChanged="Weather_OnSliderChanged" />
@@ -162,8 +165,8 @@
<TextBlock Grid.Row="7" Grid.Column="0" VerticalAlignment="Center"
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Visibility], Source={x:Static starterNg:App.Loc}}" />
<Slider Grid.Row="7" Grid.Column="2" Name="weatherFog"
Minimum="0" Maximum="1000"
<ctl:ReadableSlider Grid.Row="7" Grid.Column="2" Name="weatherFog" AutomationProperties.Name="{Binding [Visibility], Source={x:Static starterNg:App.Loc}}"
Minimum="0" Maximum="1000" SmallChange="20" LargeChange="100"
TickFrequency="1" IsSnapToTickEnabled="True"
ValueChanged="Weather_OnSliderChanged" />
<TextBlock Grid.Row="7" Grid.Column="4" Name="weatherFogLabel"
@@ -180,7 +183,7 @@
<TextBlock Grid.Row="10" Grid.Column="0" VerticalAlignment="Center"
Foreground="{StaticResource CarbonFgDim}"
Text="{Binding [Overcast], Source={x:Static starterNg:App.Loc}}" />
<ComboBox Grid.Row="10" Grid.Column="2" Name="weatherOvercast" Classes="Localized"
<ComboBox Grid.Row="10" Grid.Column="2" Name="weatherOvercast" AutomationProperties.Name="{Binding [Overcast], Source={x:Static starterNg:App.Loc}}" Classes="Localized"
HorizontalAlignment="Stretch"
SelectionChanged="Weather_OnSelectionChanged">
<ComboBoxItem Tag="random" Content="{Binding [OvercastRandom], Source={x:Static starterNg:App.Loc}}" />

View File

@@ -8,6 +8,7 @@ using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Animation;
using Avalonia.Controls;
using Avalonia.Input;
@@ -17,6 +18,7 @@ using Avalonia.Media.Imaging;
using Avalonia.Threading;
using Avalonia.VisualTree;
using StarterNG.Classes;
using StarterNG.Controls;
using StarterNG.Domain;
using StarterNG.Application;
using StarterNG.Domain.Sceneries;
@@ -99,9 +101,9 @@ public partial class Scenarios : UserControl
sceneryList.Items.Add(ToTreeItem(node, expandGroups));
}
private TreeViewItem ToTreeItem(SceneryTreeNode node, bool expandGroups)
private ExpandableTreeViewItem ToTreeItem(SceneryTreeNode node, bool expandGroups)
{
var item = new TreeViewItem
var item = new ExpandableTreeViewItem
{
Header = node.IsGroup ? node.Label : SceneryHeader(node.Label, Sceneries[node.SceneryIndex]),
Tag = node.IsGroup ? null : node.SceneryIndex,
@@ -409,6 +411,8 @@ public partial class Scenarios : UserControl
sceneryDescription.Text = scenery.LocalizedDescription(AppServices.Current.SceneryTexts);
string? imagePath = AppServices.Current.SceneryImages.Resolve(scenery);
// Under the mouse a reader hears what the picture is of.
AutomationProperties.SetName(sceneryImage, $"{App.Loc["SceneryImage"]}: {scenery.Name}");
if (imagePath is not null)
{
try
@@ -759,6 +763,8 @@ public partial class Scenarios : UserControl
{
weatherTempLabel.Text = $"{(int)weatherTemp.Value} °C";
weatherFogLabel.Text = FogScale2(FogScale.ToMetres(weatherFog.Value));
weatherTemp.ValueText = weatherTempLabel.Text;
weatherFog.ValueText = weatherFogLabel.Text;
weatherDayDate.Text = string.Format(LanguageCulture, App.Loc["DayOfYear"], SelectedDayOfYear());
weatherRestore.IsEnabled = _currentScenery?.Weather.Changed ?? false;
@@ -831,6 +837,7 @@ public partial class Scenarios : UserControl
{
var now = DateTime.Now;
weatherTime.SelectedTime = new TimeSpan(now.Hour, now.Minute, 0);
Announcer.Say(this, ScreenReaderNames.PickerText(App.Loc["Time"], ScreenReaderNames.TimeText(weatherTime.SelectedTime)));
}
private void WeatherRestore_OnClick(object? sender, RoutedEventArgs e)
@@ -838,8 +845,18 @@ public partial class Scenarios : UserControl
if (_currentScenery is null) return;
_currentScenery.Weather.Restore();
ShowWeather(_currentScenery);
Announcer.Say(this, WeatherSummary());
}
/// <summary>The weather as a reader hears it once put back: every field and its value.</summary>
private string WeatherSummary() => string.Join(", ",
ScreenReaderNames.PickerText(App.Loc["Date"], ScreenReaderNames.DateText(weatherDate.SelectedDate, weatherDate.YearVisible)),
ScreenReaderNames.PickerText(App.Loc["Season"], ScreenReaderNames.TextOf(weatherSeason.SelectedItem)),
ScreenReaderNames.PickerText(App.Loc["Time"], ScreenReaderNames.TimeText(weatherTime.SelectedTime)),
ScreenReaderNames.PickerText(App.Loc["Temperature"], weatherTempLabel.Text),
ScreenReaderNames.PickerText(App.Loc["Visibility"], weatherFogLabel.Text),
ScreenReaderNames.PickerText(App.Loc["Overcast"], ScreenReaderNames.TextOf(weatherOvercast.SelectedItem)));
private static TimeSpan? ParseTime(string? text)
{
if (string.IsNullOrWhiteSpace(text))

View File

@@ -22,7 +22,7 @@
TextTrimming="LeadingCharacterEllipsis" />
</DockPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="12" HorizontalAlignment="Right">
<TextBlock x:Name="SaveStatus" VerticalAlignment="Center" Opacity="0.8" Text="" />
<TextBlock x:Name="SaveStatus" ctl:Announcer.Changes="True" VerticalAlignment="Center" Opacity="0.8" Text="" />
<Button x:Name="ChangesButton" Classes="Flat" Click="ChangesButton_OnClick"
Content="{Binding [IniChangesButton], Source={x:Static starterNg:App.Loc}}" />
<Button x:Name="ResetButton" Classes="Flat" Click="ResetButton_OnClick"
@@ -40,14 +40,15 @@
<Border Grid.Column="0" Background="{StaticResource CarbonPanelBg}"
BorderBrush="{StaticResource CarbonBorderLight}" BorderThickness="0,0,1,0">
<DockPanel Margin="8,10,8,10">
<TextBox x:Name="SettingsSearch" DockPanel.Dock="Top" Margin="0,0,0,10"
<TextBox x:Name="SettingsSearch" AutomationProperties.LandmarkType="Search" DockPanel.Dock="Top" Margin="0,0,0,10"
PlaceholderText="{Binding [Search], Source={x:Static starterNg:App.Loc}}"
TextChanged="SettingsSearch_OnTextChanged" />
<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}}"
@@ -68,7 +69,7 @@
Click="ExportIniButton_OnClick" />
</StackPanel>
<ListBox x:Name="CategoryList" Classes="SettingsNav" SelectedIndex="0"
<ListBox x:Name="CategoryList" AutomationProperties.LandmarkType="Navigation" AutomationProperties.Name="{Binding [SettingsCategories], Source={x:Static starterNg:App.Loc}}" Classes="SettingsNav" SelectedIndex="0"
ItemContainerTheme="{StaticResource SettingsNavItem}"
SelectionChanged="CategoryList_OnSelectionChanged">
<ListBoxItem Tag="general" Content="{Binding [General], Source={x:Static starterNg:App.Loc}}" />
@@ -93,7 +94,7 @@
<TextBlock VerticalAlignment="Center" FontWeight="Bold"
Text="{Binding [GfxColPresets], Source={x:Static starterNg:App.Loc}}" />
<StackPanel x:Name="PresetButtons" Grid.Column="1" Orientation="Horizontal" Spacing="6" />
<TextBlock x:Name="PresetStateText" Grid.Column="2" VerticalAlignment="Center" FontSize="12"
<TextBlock x:Name="PresetStateText" ctl:Announcer.Changes="True" Grid.Column="2" VerticalAlignment="Center" FontSize="12"
Foreground="{StaticResource CarbonFgDim}" />
</Grid>
<Grid ColumnDefinitions="Auto,*" ColumnSpacing="10">
@@ -141,7 +142,7 @@
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="mousescale" x:Name="CursorSensitivityRow"
Label="{Binding [CursorSensitivity], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="CursorSensitivitySlider" Minimum="1" Maximum="5" TickFrequency="1"
<ctl:ReadableSlider x:Name="CursorSensitivitySlider" Minimum="1" Maximum="5" TickFrequency="1"
IsSnapToTickEnabled="True" Value="3"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
@@ -258,13 +259,13 @@
Label="{Binding [BufforResolution], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [BufforResolutionDesc], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #bufferScale.Value, StringFormat='{}{0:0}%'}">
<Slider Name="bufferScale" Minimum="25" Maximum="200" TickFrequency="1"
<ctl:ReadableSlider Name="bufferScale" Minimum="25" Maximum="200" TickFrequency="1"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="fieldofview" Label="{Binding [FieldOfView], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [FieldOfViewDesc], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #fovSlider.Value, StringFormat='{}{0:0}°'}">
<Slider Name="fovSlider" Minimum="10" Maximum="75" TickFrequency="5"
<ctl:ReadableSlider Name="fovSlider" Minimum="10" Maximum="75" TickFrequency="5"
IsSnapToTickEnabled="True" Value="45" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="gfx.antialiasing, multisampling"
@@ -296,7 +297,7 @@
Description="{Binding [FpsLimitDesc], Source={x:Static starterNg:App.Loc}}">
<StackPanel Spacing="4">
<!-- Moves through no limit and Steps.FrameRateLimits; see SliderSteps. -->
<Slider x:Name="FpsLimitSlider" ValueChanged="QualitySlider_OnValueChanged" />
<ctl:ReadableSlider x:Name="FpsLimitSlider" ValueChanged="QualitySlider_OnValueChanged" />
<!-- The screens found, each with a button to match the limit to it. -->
<WrapPanel x:Name="MonitorRates" IsVisible="False" />
</StackPanel>
@@ -312,14 +313,14 @@
Label="{Binding [RenderRange], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [RenderRangeDesc], Source={x:Static starterNg:App.Loc}}">
<!-- Moves through Steps.DrawRangeFactors; see SliderSteps. -->
<Slider x:Name="RenderRangeSlider"
<ctl:ReadableSlider x:Name="RenderRangeSlider"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:KeySlot Key="sleeperdistance" />
<ctl:SettingRow ConfigKey="splinefidelity" x:Name="TrackCurvesRow"
Label="{Binding [TrackCurvesQuality], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [TrackCurvesQualityDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="TrackCurvesSlider" Minimum="1" Maximum="4" TickFrequency="1"
<ctl:ReadableSlider x:Name="TrackCurvesSlider" Minimum="1" Maximum="4" TickFrequency="1"
IsSnapToTickEnabled="True" Value="4"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
@@ -330,13 +331,13 @@
<StackPanel>
<ctl:SettingRow ConfigKey="maxtexturesize" x:Name="TexResolutionRow"
Label="{Binding [MaxTexResolution], Source={x:Static starterNg:App.Loc}}">
<Slider Name="textureResolutionSlider" Minimum="6" Maximum="13" TickFrequency="1"
<ctl:ReadableSlider Name="textureResolutionSlider" Minimum="6" Maximum="13" TickFrequency="1"
IsSnapToTickEnabled="True" Value="12"
ValueChanged="TextureResolutionSlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="maxcabtexturesize" x:Name="CabTexResolutionRow"
Label="{Binding [MaxTexCabResolution], Source={x:Static starterNg:App.Loc}}">
<Slider Name="cabTextureResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
<ctl:ReadableSlider Name="cabTextureResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
IsSnapToTickEnabled="True" Value="12"
ValueChanged="CabTextureResolutionSlider_OnValueChanged" />
</ctl:SettingRow>
@@ -344,7 +345,7 @@
Label="{Binding [TexFilteringQuality], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [TexFilteringQualityDesc], Source={x:Static starterNg:App.Loc}}">
<!-- Moves through Steps.Anisotropy; see SliderSteps. -->
<Slider x:Name="TexFilteringSlider"
<ctl:ReadableSlider x:Name="TexFilteringSlider"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:KeySlot Key="gfx.textures.streaming" />
@@ -397,7 +398,7 @@
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="shadowtune" x:Name="ShadowResolutionRow"
Label="{Binding [ShadowsResolution], Source={x:Static starterNg:App.Loc}}">
<Slider Name="shaderResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
<ctl:ReadableSlider Name="shaderResolutionSlider" Minimum="9" Maximum="13" TickFrequency="1"
IsSnapToTickEnabled="True" Value="12"
ValueChanged="shaderResolutionSlider_OnValueChanged" />
</ctl:SettingRow>
@@ -405,14 +406,14 @@
Label="{Binding [ShaderRange], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [ShaderRangeDesc], Source={x:Static starterNg:App.Loc}}">
<!-- The simulator's floor follows the map size: see shaderResolutionSlider_OnValueChanged. -->
<Slider Name="shaderRange" Minimum="75" Maximum="600" TickFrequency="5"
<ctl:ReadableSlider Name="shaderRange" Minimum="75" Maximum="600" TickFrequency="5"
IsSnapToTickEnabled="True" Value="150"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="gfx.shadows.cab.range" x:Name="CabShadowRangeRow"
Label="{Binding [CabShadowsRange], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [CabShadowsRangeDesc], Source={x:Static starterNg:App.Loc}}">
<Slider Name="cabShaderSourceRange" Minimum="0" Maximum="100" TickFrequency="10"
<ctl:ReadableSlider Name="cabShaderSourceRange" Minimum="0" Maximum="100" TickFrequency="10"
IsSnapToTickEnabled="True" Value="30"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
@@ -420,7 +421,7 @@
Label="{Binding [ShadowAngleLimit], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [ShadowAngleLimitDesc], Source={x:Static starterNg:App.Loc}}">
<StackPanel>
<Slider x:Name="ShadowAngleLimitSlider" Minimum="0.2" Maximum="1.0"
<ctl:ReadableSlider x:Name="ShadowAngleLimitSlider" Minimum="0.2" Maximum="1.0"
TickFrequency="0.05" IsSnapToTickEnabled="True" Value="0.2" HorizontalAlignment="Stretch"
ValueChanged="QualitySlider_OnValueChanged" />
<DockPanel>
@@ -438,7 +439,7 @@
<StackPanel>
<ctl:SettingRow x:Name="DynamicLightsRow" Description="{Binding [DynamicLightsDesc], Source={x:Static starterNg:App.Loc}}" ConfigKey="dynamiclights" Label="{Binding [DynamicLights], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #DynamicLightsSlider.Value, StringFormat='{}{0:0}'}">
<Slider x:Name="DynamicLightsSlider" Minimum="0" Maximum="7" TickFrequency="1"
<ctl:ReadableSlider x:Name="DynamicLightsSlider" Minimum="0" Maximum="7" TickFrequency="1"
IsSnapToTickEnabled="True" Value="7" />
</ctl:SettingRow>
</StackPanel>
@@ -462,7 +463,7 @@
Label="{Binding [ReflectionsFramerate], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [ReflectionsFramerateDesc], Source={x:Static starterNg:App.Loc}}">
<!-- Moves through Steps.ReflectionUpdates; see SliderSteps. -->
<Slider Name="reflectionsFramerate"
<ctl:ReadableSlider Name="reflectionsFramerate"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:KeySlot Key="gfx.reflections.range_instances" />
@@ -491,7 +492,7 @@
<ctl:SettingRow ConfigKey="gfx.smoke.fidelity" x:Name="SmokeParticlesRow"
Label="{Binding [SmokeParticlesMultiplier], Source={x:Static starterNg:App.Loc}}"
IsEnabled="{Binding #SmokeDisplayCb.IsChecked}">
<Slider x:Name="SmokeParticlesSlider" Minimum="1" Maximum="4" TickFrequency="1"
<ctl:ReadableSlider x:Name="SmokeParticlesSlider" Minimum="1" Maximum="4" TickFrequency="1"
IsSnapToTickEnabled="True" Value="2"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
@@ -511,27 +512,27 @@
<StackPanel IsEnabled="{Binding #EnableSoundsCb.IsChecked}">
<ctl:SettingRow ConfigKey="sound.volume" Label="{Binding [Volume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #VolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="VolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="VolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="sound.volume.radio" Label="{Binding [RadiophoneVolume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #RadioVolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="RadioVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="RadioVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="sound.volume.vehicle" Label="{Binding [VehiclesVolume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #VehiclesVolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="VehiclesVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="VehiclesVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="sound.volume.positional" Label="{Binding [PositionedSoundsVolume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #PositionalVolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="PositionalVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="PositionalVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="sound.volume.ambient" Label="{Binding [AmbientVolume], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #AmbientVolumeSlider.Value, StringFormat='{}{0:0}%'}">
<Slider x:Name="AmbientVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
<ctl:ReadableSlider x:Name="AmbientVolumeSlider" Minimum="0" Maximum="100" TickFrequency="5"
IsSnapToTickEnabled="True" Value="100" />
</ctl:SettingRow>
</StackPanel>
@@ -574,17 +575,17 @@
<ctl:SettingRow ConfigKey="friction" x:Name="FrictionRow" Label="{Binding [Friction], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [FrictionDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="FrictionSlider" Minimum="0.1" Maximum="3.0" TickFrequency="0.1" Value="1.0"
<ctl:ReadableSlider x:Name="FrictionSlider" Minimum="0.1" Maximum="3.0" TickFrequency="0.1" Value="1.0"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="brakestep" x:Name="BrakeStepRow" Label="{Binding [BrakeStep], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [BrakeStepDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="BrakeStepSlider" Minimum="0.4" Maximum="3.0" TickFrequency="0.1" Value="1.0"
<ctl:ReadableSlider x:Name="BrakeStepSlider" Minimum="0.4" Maximum="3.0" TickFrequency="0.1" Value="1.0"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="brakespeed" x:Name="BrakeSpeedRow" Label="{Binding [BrakeSpeed], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [BrakeSpeedDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="BrakeSpeedSlider" Minimum="0.4" Maximum="3.0" TickFrequency="0.1" Value="1.0"
<ctl:ReadableSlider x:Name="BrakeSpeedSlider" Minimum="0.4" Maximum="3.0" TickFrequency="0.1" Value="1.0"
ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
</StackPanel>
@@ -699,7 +700,7 @@
<ctl:SettingRow ConfigKey="async.trainThreads" x:Name="TrainThreadsRow"
Label="{Binding [TrainPhysicsThreads], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [TrainPhysicsThreadsDesc], Source={x:Static starterNg:App.Loc}}">
<Slider x:Name="TrainThreadsSlider" Minimum="0" Maximum="16" TickFrequency="1"
<ctl:ReadableSlider x:Name="TrainThreadsSlider" Minimum="0" Maximum="16" TickFrequency="1"
IsSnapToTickEnabled="True" ValueChanged="QualitySlider_OnValueChanged" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="starter.ignoreirrelevant" Description="{Binding [IgnoreIrrelevantTrainsDesc], Source={x:Static starterNg:App.Loc}}">
@@ -774,7 +775,7 @@
<ctl:SettingRow x:Name="RayTracingRangeRow" ConfigKey="gfx.raytracing.range"
Label="{Binding [RayTracingRange], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #RayTracingRangeSlider.Value, StringFormat='{}{0:0} m'}">
<Slider x:Name="RayTracingRangeSlider" Minimum="50" Maximum="2000" TickFrequency="50" IsSnapToTickEnabled="True" Value="500" />
<ctl:ReadableSlider x:Name="RayTracingRangeSlider" Minimum="50" Maximum="2000" TickFrequency="50" IsSnapToTickEnabled="True" Value="500" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="gfx.ssr" Label="{Binding [Ssr], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [SsrDesc], Source={x:Static starterNg:App.Loc}}">
@@ -851,7 +852,7 @@
Label="{Binding [CabProbeBounce], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [CabProbeBounceDesc], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #CabProbeBounceSlider.Value, StringFormat='{}{0:0.0}'}">
<Slider x:Name="CabProbeBounceSlider" Minimum="0" Maximum="4" TickFrequency="0.1" IsSnapToTickEnabled="True" Value="1" />
<ctl:ReadableSlider x:Name="CabProbeBounceSlider" Minimum="0" Maximum="4" TickFrequency="0.1" IsSnapToTickEnabled="True" Value="1" />
</ctl:SettingRow>
<ctl:SettingRow x:Name="CabProbeReflectionsRow" ConfigKey="gfx.cabprobe.reflections" Description="{Binding [CabProbeReflectionsDesc], Source={x:Static starterNg:App.Loc}}">
<CheckBox x:Name="CabProbeReflectionsCb" Content="{Binding [CabProbeReflections], Source={x:Static starterNg:App.Loc}}" />
@@ -892,12 +893,12 @@
<ctl:SettingRow x:Name="GrassDistanceRow" ConfigKey="gfx.grass.distance, gfx.grass.fadedistance"
Label="{Binding [GrassDistance], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #GrassDistanceSlider.Value, StringFormat='{}{0:0} m'}">
<Slider x:Name="GrassDistanceSlider" Minimum="20" Maximum="300" TickFrequency="10" IsSnapToTickEnabled="True" Value="60" />
<ctl:ReadableSlider x:Name="GrassDistanceSlider" Minimum="20" Maximum="300" TickFrequency="10" IsSnapToTickEnabled="True" Value="60" />
</ctl:SettingRow>
<ctl:SettingRow x:Name="GrassDensityRow" ConfigKey="gfx.grass.density"
Label="{Binding [GrassDensity], Source={x:Static starterNg:App.Loc}}"
ValueText="{Binding #GrassDensitySlider.Value, StringFormat='{}{0:0.00}'}">
<Slider x:Name="GrassDensitySlider" Minimum="0.25" Maximum="2.0" TickFrequency="0.25" IsSnapToTickEnabled="True" Value="1.0" />
<ctl:ReadableSlider x:Name="GrassDensitySlider" Minimum="0.25" Maximum="2.0" TickFrequency="0.25" IsSnapToTickEnabled="True" Value="1.0" />
</ctl:SettingRow>
<ctl:SettingRow ConfigKey="gfx.precipitation.particles" Label="{Binding [Precipitation], Source={x:Static starterNg:App.Loc}}"
Description="{Binding [PrecipitationDesc], Source={x:Static starterNg:App.Loc}}">

View File

@@ -580,6 +580,7 @@ public partial class Settings : UserControl, ISettingsCapture
// Chosen as a whole, its values are choices, not ones the screen could not show.
ForgetShown(applied.ChosenKeys);
UpdatePresetMarks();
Announcer.Say(this, ScreenReaderNames.PickerText(App.Loc["GfxColPresets"], App.Loc[preset.NameKey]));
}
/// <summary>Puts one part at a level, as edits waiting for Save.</summary>
@@ -747,6 +748,7 @@ public partial class Settings : UserControl, ISettingsCapture
// Put back by hand, a value is a choice like any other.
ForgetShown(keys);
Announcer.Say(this, ScreenReaderNames.PickerText(ScreenReaderNames.TextOf(section.Header), App.Loc["DefaultsRestored"]));
}
// ── Values the screen shows otherwise than the file has them ─────────────
@@ -1147,6 +1149,7 @@ public partial class Settings : UserControl, ISettingsCapture
_keyBindings.Reload();
_dirty = false;
UpdateSaveState();
Announcer.Say(this, App.Loc["SettingsRestored"]);
}
/// <summary>The list as <see cref="ResolutionChoices"/> has it for the monitors there are now, with the size selected.</summary>
@@ -1323,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
@@ -1347,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;
@@ -1366,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

@@ -70,7 +70,7 @@ internal sealed class SimulatorKeyRows
Control input = key.Kind switch
{
SimulatorKeyKind.Toggle => new CheckBox(),
SimulatorKeyKind.Number => new Slider
SimulatorKeyKind.Number => new ReadableSlider
{
Minimum = key.Minimum,
Maximum = key.Maximum,

View File

@@ -14,6 +14,7 @@ using Avalonia.Platform.Storage;
using Avalonia.Threading;
using Eu07.BlackBox.Views;
using StarterNG.Application;
using StarterNG.Controls;
using StarterNG.Domain.Settings;
using StarterNG.Domain.Tapes;
@@ -85,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;
@@ -285,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
@@ -389,7 +399,7 @@ public sealed class HaslerTapeWindow : Window
_list.SelectedItem = chosen.Tape;
}
private TreeViewItem SessionItem(TapeSession session, bool open)
private ExpandableTreeViewItem SessionItem(TapeSession session, bool open)
{
string title = session.Launch is { } launch
? string.Join(" · ", new[] { string.IsNullOrWhiteSpace(launch.SceneryName) ? launch.Scenery : launch.SceneryName, launch.Train }
@@ -418,7 +428,7 @@ public sealed class HaslerTapeWindow : Window
var name = new TextBlock { Text = title, FontWeight = FontWeight.SemiBold, TextTrimming = TextTrimming.CharacterEllipsis };
ToolTip.SetTip(name, title);
var item = new TreeViewItem
var item = new ExpandableTreeViewItem
{
Header = new StackPanel { Spacing = 1, Children = { name, details } },
Tag = session,
@@ -431,7 +441,7 @@ public sealed class HaslerTapeWindow : Window
return item;
}
private TreeViewItem BlackBoxItem(BlackBoxRecording box)
private ExpandableTreeViewItem BlackBoxItem(BlackBoxRecording box)
{
var text = new StackPanel { Spacing = 1 };
text.Children.Add(new TextBlock { Text = App.Loc["HaslerBlackBox"], FontWeight = FontWeight.SemiBold });
@@ -442,7 +452,7 @@ public sealed class HaslerTapeWindow : Window
Opacity = 0.7
});
ToolTip.SetTip(text, App.Loc["HaslerBlackBoxTip"]);
var item = new TreeViewItem { Header = text, Tag = box };
var item = new ExpandableTreeViewItem { Header = text, Tag = box };
// Also when it is the one picked already, and its window was closed since.
item.Tapped += async (_, _) => await OpenBlackBoxAsync(box);
return item;
@@ -466,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;
@@ -573,7 +585,7 @@ public sealed class HaslerTapeWindow : Window
}
}
private static TreeViewItem TapeItem(TapeFile file)
private static ExpandableTreeViewItem TapeItem(TapeFile file)
{
var text = new StackPanel { Spacing = 1 };
text.Children.Add(new TextBlock
@@ -592,7 +604,7 @@ public sealed class HaslerTapeWindow : Window
};
if (role is not null)
text.Children.Add(new TextBlock { Text = role, FontSize = 11, Opacity = 0.7 });
return new TreeViewItem { Header = text, Tag = file };
return new ExpandableTreeViewItem { Header = text, Tag = file };
}
/// <summary>
@@ -769,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

@@ -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" AutomationProperties.Name="{Binding [PanelSplitter], Source={x:Static starterNg:App.Loc}}" 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" AutomationProperties.Name="{Binding [PanelSplitter], Source={x:Static starterNg:App.Loc}}" Grid.Column="1" Width="3" Background="Transparent" ResizeDirection="Columns" />
<Border Grid.Column="2" Classes="Panel">
<Grid RowDefinitions="Auto,*">

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
@@ -180,6 +181,7 @@ public partial class VehicleBaseWindow : Window
if (row is null)
{
preview.Source = null;
preview.ClearValue(AutomationProperties.NameProperty);
detailTitle.Text = "";
detailText.Text = App.Loc["TextureBasePick"];
ToolTip.SetTip(detailText, null);
@@ -188,6 +190,7 @@ public partial class VehicleBaseWindow : Window
preview.Source = _minis.Get(_db.ResolveMiniName(row.Texture), PreviewHeight);
detailTitle.Text = string.Join(" · ", new[] { row.Skin, row.Class, row.Operator }.Where(s => s.Length > 0));
AutomationProperties.SetName(preview, detailTitle.Text);
var lines = new[]
{

View File

@@ -563,6 +563,47 @@
<String key="Save">Uložit</String>
<String key="Reset">Obnovit</String>
<String key="SettingsSaved">Nastavení uloženo</String>
<String key="DefaultsRestored">Výchozí hodnoty obnoveny</String>
<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>
<String key="SettingsNotSaved">Nastavení se nepodařilo uložit</String>
<String key="UnsavedChanges">Neuložené změny</String>

View File

@@ -589,6 +589,47 @@
<String key="Save">Save</String>
<String key="Reset">Reset</String>
<String key="SettingsSaved">Settings saved</String>
<String key="DefaultsRestored">Defaults restored</String>
<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>
<String key="SettingsNotSaved">Could not save the settings</String>
<String key="UnsavedChanges">Unsaved changes</String>

View File

@@ -563,6 +563,47 @@
<String key="Save">Mentés</String>
<String key="Reset">Visszaállítás</String>
<String key="SettingsSaved">A beállítások elmentve</String>
<String key="DefaultsRestored">Alapértékek visszaállítva</String>
<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>
<String key="SettingsNotSaved">A beállításokat nem sikerült elmenteni</String>
<String key="UnsavedChanges">Nem mentett módosítások</String>

View File

@@ -589,6 +589,47 @@
<String key="Save">Zapisz</String>
<String key="Reset">Przywróć</String>
<String key="SettingsSaved">Zapisano ustawienia</String>
<String key="DefaultsRestored">Przywrócono domyślne</String>
<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>
<String key="SettingsNotSaved">Nie udało się zapisać ustawień</String>
<String key="UnsavedChanges">Niezapisane zmiany</String>

View File

@@ -563,6 +563,47 @@
<String key="Save">Сохранить</String>
<String key="Reset">Сбросить</String>
<String key="SettingsSaved">Настройки сохранены</String>
<String key="DefaultsRestored">Восстановлены значения по умолчанию</String>
<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>
<String key="SettingsNotSaved">Не удалось сохранить настройки</String>
<String key="UnsavedChanges">Несохранённые изменения</String>