Files
StarterNG/StarterNG/Views/Tapes/TapeView.cs
maj00r 195f358e55 refactor(tapes): the line of a tape drawn by a class of its own, so Sonar sees a figure ended after a gap
Sonar (S2583, the reliability rating of #54) took the end of a figure after a gap in Trace for code
never run: begun was changed by the local function Flush, and its analysis doesn't follow a local
changed that way. Nothing was wrong in what was drawn.

The columns of the line are kept by ColumnLine, in its fields, and drawn through the three calls it is
given, the figure begun, a line to the next point and its end; Trace hands it those of the
StreamGeometry. What is drawn is the same. Tests: a column entered where it started and left where it
ended through its lowest and highest, a break ending the figure and the next point beginning another,
a break with nothing drawn ending nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:06:58 +01:00

359 lines
12 KiB
C#

using System;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using StarterNG.Domain.Tapes;
namespace StarterNG.Views.Tapes;
/// <summary>
/// What every way of drawing a recorded trip shares: the trip, how it is laid
/// along the x axis - by distance or by time, at a scale - the clock it started
/// at, and the pointer read-out.
/// </summary>
public abstract class TapeView : Control
{
public static readonly StyledProperty<HaslerTape?> TapeProperty =
AvaloniaProperty.Register<TapeView, HaslerTape?>(nameof(Tape));
public static readonly StyledProperty<bool> ByDistanceProperty =
AvaloniaProperty.Register<TapeView, bool>(nameof(ByDistance), true);
/// <summary>Pixels per kilometre when fed by distance, per minute when fed by time.</summary>
public static readonly StyledProperty<double> ScaleProperty =
AvaloniaProperty.Register<TapeView, double>(nameof(Scale), 40);
/// <summary>
/// The time of day the recording started at. The log only counts seconds, so
/// without it the clock counts from the start of the trip.
/// </summary>
public static readonly StyledProperty<TimeSpan> StartClockProperty =
AvaloniaProperty.Register<TapeView, TimeSpan>(nameof(StartClock));
/// <summary>
/// The moment a black box of the same run is at, in the tape's own seconds: both count the simulation from
/// its start, paused or not. Null draws nothing.
/// </summary>
public static readonly StyledProperty<double?> MarkProperty =
AvaloniaProperty.Register<TapeView, double?>(nameof(Mark));
private static readonly IPen CursorPen = new Pen(new SolidColorBrush(Color.Parse("#FFB000")), 1);
private static readonly IBrush MarkBrush = new SolidColorBrush(Color.Parse("#4FC3F7"));
private static readonly IPen MarkPen = new Pen(MarkBrush, 2);
static TapeView()
{
AffectsMeasure<TapeView>(TapeProperty, ByDistanceProperty, ScaleProperty);
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);
set => SetValue(TapeProperty, value);
}
public bool ByDistance
{
get => GetValue(ByDistanceProperty);
set => SetValue(ByDistanceProperty, value);
}
public double Scale
{
get => GetValue(ScaleProperty);
set => SetValue(ScaleProperty, value);
}
public TimeSpan StartClock
{
get => GetValue(StartClockProperty);
set => SetValue(StartClockProperty, value);
}
public double? Mark
{
get => GetValue(MarkProperty);
set => SetValue(MarkProperty, value);
}
/// <summary>The sample under the pointer, or null once it leaves the tape.</summary>
public event Action<TapeSample?>? Hovered;
/// <summary>The sample clicked on.</summary>
public event Action<TapeSample>? Picked;
protected abstract double LeftMargin { get; }
private const double RightMargin = 24;
protected abstract double TapeHeight { get; }
protected double? CursorX { get; private set; }
protected double TopSpeed => TapeFigures.TopSpeed(Tape?.MaxSpeedKmh ?? 0);
protected double Length => Tape is null ? 0 : ByDistance ? Tape.DistanceM / 1000.0 : Tape.Duration / 60.0;
protected double TapeRight => LeftMargin + Length * Scale;
protected double XOf(TapeSample s) =>
LeftMargin + (ByDistance ? s.DistanceM / 1000.0 : (s.Time - (Tape?.StartTime ?? 0)) / 60.0) * Scale;
private double PositionOf(double x) =>
ByDistance ? (x - LeftMargin) / Scale * 1000.0 : (x - LeftMargin) / Scale * 60.0 + (Tape?.StartTime ?? 0);
/// <summary>
/// Where the mark stands across the tape; null with no mark or outside the trip. By distance it is where the
/// train was at that moment, so through a stop the mark stands still.
/// </summary>
public double? MarkX => Mark is { } t ? XAt(t) : null;
/// <summary>Where a moment of the trip stands across the tape; null outside the trip.</summary>
public double? XAt(double t)
{
var tape = Tape;
if (tape is null || tape.IsEmpty || t < tape.StartTime || t > tape.Samples[^1].Time)
return null;
return ByDistance
? XOf(tape.Samples[tape.IndexAt(t, byDistance: false)])
: LeftMargin + (t - tape.StartTime) / 60.0 * Scale;
}
/// <summary>Seconds since midnight at the sample, by the clock the trip started at.</summary>
public double ClockAt(TapeSample s) => StartClock.TotalSeconds + s.Time - (Tape?.StartTime ?? 0);
/// <summary>What the view shows, for another one to show the same.</summary>
public void CopySettingsFrom(TapeView other)
{
Tape = other.Tape;
ByDistance = other.ByDistance;
Scale = other.Scale;
StartClock = other.StartClock;
Mark = other.Mark;
}
protected override Size MeasureOverride(Size availableSize) =>
new(TapeRight + RightMargin, TapeHeight);
public sealed override void Render(DrawingContext context)
{
DrawBlank(context);
var tape = Tape;
if (tape is null || tape.IsEmpty)
return;
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>
protected abstract void DrawBlank(DrawingContext context);
/// <summary>A trip with something in it, over the blank.</summary>
protected abstract void DrawTape(DrawingContext context, HaslerTape tape);
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
var tape = Tape;
if (tape is null || tape.IsEmpty)
return;
double x = Math.Clamp(e.GetPosition(this).X, LeftMargin, TapeRight);
int index = tape.IndexAt(PositionOf(x), ByDistance);
CursorX = x;
InvalidateVisual();
Hovered?.Invoke(index < 0 ? null : tape.Samples[index]);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
var tape = Tape;
if (tape is null || tape.IsEmpty || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
return;
double x = Math.Clamp(e.GetPosition(this).X, LeftMargin, TapeRight);
int index = tape.IndexAt(PositionOf(x), ByDistance);
if (index >= 0)
Picked?.Invoke(tape.Samples[index]);
}
protected override void OnPointerExited(PointerEventArgs e)
{
base.OnPointerExited(e);
CursorX = null;
InvalidateVisual();
Hovered?.Invoke(null);
}
/// <summary>A line across the tape with a notch on top, in a colour of its own: not the pointer's.</summary>
private void DrawMark(DrawingContext context)
{
if (MarkX is not { } x)
return;
context.DrawLine(MarkPen, new Point(x, 0), new Point(x, TapeHeight));
var notch = new StreamGeometry();
using (var g = notch.Open())
{
g.BeginFigure(new Point(x - 5, 0), true);
g.LineTo(new Point(x + 5, 0));
g.LineTo(new Point(x, 7));
g.EndFigure(true);
}
context.DrawGeometry(MarkBrush, null, notch);
}
private void DrawCursor(DrawingContext context)
{
if (CursorX is { } x)
context.DrawLine(CursorPen, new Point(x, 0), new Point(x, TapeHeight));
}
/// <summary>
/// A record as one line, one column of pixels at a time: per column the
/// lowest and highest point in it, so a long trip draws as fast as a short
/// one and what happens during a stop on a distance-fed tape still shows as
/// one stroke.
/// </summary>
protected StreamGeometry Trace(HaslerTape tape, Func<TapeSample, double> y)
{
var geometry = new StreamGeometry();
using var g = geometry.Open();
var line = new ColumnLine(p => g.BeginFigure(p, false), p => g.LineTo(p), () => g.EndFigure(false));
double? before = null;
foreach (var s in tape.Samples)
{
// A gap, the player in another vehicle, is not drawn as if the train drove or stood through it: the
// line breaks off there.
if (before is { } previous && s.Time - previous > tape.GapSeconds)
line.Break();
before = s.Time;
line.Add((int)Math.Round(XOf(s)), y(s));
}
line.Break();
return geometry;
}
}