mirror of
https://github.com/MaSzyna-EU07/StarterNG.git
synced 2026-11-19 06:55:59 +01:00
Merge pull request #40 from MaSzyna-EU07/feature/blackbox
Black box player: the simulator's recording of a run on a map, with the cab, the timetable and a summary
This commit is contained in:
@@ -16,15 +16,21 @@ namespace StarterNG.Application;
|
||||
public sealed record TapeFile(string Path, string Vehicle, DateTime LastWriteUtc, long Size,
|
||||
TapeRole Role = TapeRole.Other);
|
||||
|
||||
/// <summary>One run of the simulator and what is left of its tapes: a later run overwrites those of the vehicles it has too.</summary>
|
||||
/// <summary>The black box of a run: the whole session in one file, a new one each run.</summary>
|
||||
public sealed record BlackBoxRecording(string Path, DateTime LastWriteUtc, long Size);
|
||||
|
||||
/// <summary>
|
||||
/// One run of the simulator and what is left of its tapes: a later run overwrites those of the
|
||||
/// vehicles it has too. Its black box stays, newest first should there be more.
|
||||
/// </summary>
|
||||
public sealed record TapeSession(TapeLaunch? Launch, DateTime StartedUtc, DateTime LastWrittenUtc, bool Running,
|
||||
IReadOnlyList<TapeFile> Tapes);
|
||||
IReadOnlyList<TapeFile> Tapes, IReadOnlyList<BlackBoxRecording> BlackBoxes);
|
||||
|
||||
/// <summary>What is known about a tape beyond its samples: the clock it started at, the recorder it is read as, the scenario and the train.</summary>
|
||||
public sealed record TapeContext(TimeSpan? StartClock, RecorderKind Recorder,
|
||||
string? Scenery = null, string? Train = null);
|
||||
|
||||
/// <summary>The tapes the simulator left in physicslog/ - one per driven vehicle, overwritten every run.</summary>
|
||||
/// <summary>The tapes the simulator left in physicslog/ - one per driven vehicle, overwritten every run - and the black boxes, one a run.</summary>
|
||||
public sealed class HaslerTapes
|
||||
{
|
||||
private const int RememberedLaunches = 30;
|
||||
@@ -221,7 +227,7 @@ public sealed class HaslerTapes
|
||||
|
||||
public TapeContext ContextOf(TapeFile file)
|
||||
{
|
||||
var launch = Launches().LastOrDefault(l => l.Covers(file.LastWriteUtc));
|
||||
var launch = LaunchOf(file, Launches(), ReadBlackBoxes());
|
||||
if (launch is null)
|
||||
return new TapeContext(null, Recorders.Guess(null, file.Vehicle));
|
||||
|
||||
@@ -237,8 +243,9 @@ public sealed class HaslerTapes
|
||||
|
||||
/// <summary>
|
||||
/// The runs the tapes came from, the running or latest one first. A tape belongs
|
||||
/// to the last launch before it was written; one written before any known launch
|
||||
/// goes with those written about the same time, as a run writes them all at its end.
|
||||
/// to the last launch before it was written, unless a run the starter didn't launch
|
||||
/// began between them; one with no launch goes with those written about the same
|
||||
/// time, as a run writes them all at its end.
|
||||
/// </summary>
|
||||
public IReadOnlyList<TapeSession> Sessions()
|
||||
{
|
||||
@@ -248,35 +255,54 @@ public sealed class HaslerTapes
|
||||
var tapes = _files.DirectoryExists(Folder)
|
||||
? _files.GetFiles(Folder, "*.dat").Select(ReadTape).ToList()
|
||||
: new List<TapeFile>();
|
||||
var behind = tapes.GroupBy(tape => launches.LastOrDefault(l => l.Covers(tape.LastWriteUtc)))
|
||||
var boxes = ReadBlackBoxes();
|
||||
var tapeLaunch = tapes.ToDictionary(tape => tape, tape => LaunchOf(tape, launches, boxes));
|
||||
var behind = tapes.GroupBy(tape => tapeLaunch[tape])
|
||||
.Where(group => group.Key is not null)
|
||||
.ToDictionary(group => group.Key!, group => group.ToList());
|
||||
var boxesBehind = boxes.GroupBy(box => LaunchOf(box, launches))
|
||||
.Where(group => group.Key is not null)
|
||||
.ToDictionary(group => group.Key!, group => group.ToList());
|
||||
|
||||
var sessions = new List<TapeSession>();
|
||||
foreach (var launch in launches)
|
||||
{
|
||||
bool last = ReferenceEquals(launch, launches[^1]);
|
||||
bool running = last && _simulatorRunning();
|
||||
if (!running && !behind.ContainsKey(launch))
|
||||
if (!running && !behind.ContainsKey(launch) && !boxesBehind.ContainsKey(launch))
|
||||
continue;
|
||||
|
||||
var player = last ? PlayerIn(launch) : launch.Player ?? PlayerVehicles.Unknown;
|
||||
sessions.Add(Session(launch, running, behind.GetValueOrDefault(launch, new List<TapeFile>())
|
||||
.Select(t => t with { Role = launch.RoleOf(t.Vehicle, player) })));
|
||||
.Select(t => t with { Role = launch.RoleOf(t.Vehicle, player) }),
|
||||
boxesBehind.GetValueOrDefault(launch, new List<BlackBoxRecording>())));
|
||||
}
|
||||
|
||||
// What no launch covers goes together by when it was written: a run writes it all at its end.
|
||||
var loose = tapes.Where(t => tapeLaunch[t] is null)
|
||||
.Select(t => (Written: t.LastWriteUtc, Tape: (TapeFile?)t, Box: (BlackBoxRecording?)null))
|
||||
.Concat(boxes.Where(b => LaunchOf(b, launches) is null)
|
||||
.Select(b => (Written: b.LastWriteUtc, Tape: (TapeFile?)null, Box: (BlackBoxRecording?)b)))
|
||||
.OrderBy(file => file.Written);
|
||||
var run = new List<TapeFile>();
|
||||
foreach (var tape in tapes.Where(t => !launches.Any(l => l.Covers(t.LastWriteUtc))).OrderBy(t => t.LastWriteUtc))
|
||||
var runBoxes = new List<BlackBoxRecording>();
|
||||
DateTime? lastWritten = null;
|
||||
foreach (var (written, tape, box) in loose)
|
||||
{
|
||||
if (run.Count > 0 && tape.LastWriteUtc - run[^1].LastWriteUtc > QuietBetweenRuns)
|
||||
if (lastWritten is { } before && written - before > QuietBetweenRuns)
|
||||
{
|
||||
sessions.Add(Session(null, running: false, run));
|
||||
sessions.Add(Session(null, running: false, run, runBoxes));
|
||||
run = new List<TapeFile>();
|
||||
runBoxes = new List<BlackBoxRecording>();
|
||||
}
|
||||
run.Add(tape);
|
||||
if (tape is not null)
|
||||
run.Add(tape);
|
||||
if (box is not null)
|
||||
runBoxes.Add(box);
|
||||
lastWritten = written;
|
||||
}
|
||||
if (run.Count > 0)
|
||||
sessions.Add(Session(null, running: false, run));
|
||||
if (lastWritten is not null)
|
||||
sessions.Add(Session(null, running: false, run, runBoxes));
|
||||
|
||||
return sessions.OrderByDescending(session => session.Running)
|
||||
.ThenByDescending(session => session.LastWrittenUtc)
|
||||
@@ -292,13 +318,97 @@ public sealed class HaslerTapes
|
||||
private TapeFile ReadTape(string path) =>
|
||||
new(path, Path.GetFileNameWithoutExtension(path), _files.GetLastWriteTimeUtc(path), _files.GetFileSize(path));
|
||||
|
||||
private List<BlackBoxRecording> ReadBlackBoxes() =>
|
||||
_files.DirectoryExists(Folder)
|
||||
? _files.GetFiles(Folder, "*.blackbox").Select(ReadBlackBox).ToList()
|
||||
: new List<BlackBoxRecording>();
|
||||
|
||||
/// <summary>
|
||||
/// The launch a tape came from. A tape tells nothing of its run but when it was written: the last launch
|
||||
/// before then, unless a black box shows another run, one the starter didn't launch, began between the two.
|
||||
/// That run wrote the tape, not the launch's.
|
||||
/// </summary>
|
||||
public static TapeLaunch? LaunchOf(TapeFile tape, IReadOnlyList<TapeLaunch> launches, IReadOnlyList<BlackBoxRecording> boxes)
|
||||
{
|
||||
var launch = launches.LastOrDefault(l => l.Covers(tape.LastWriteUtc));
|
||||
if (launch is null)
|
||||
return null;
|
||||
bool another = boxes.Any(box => NamedBy(box.Path) is { } named
|
||||
&& named.StartedUtc > launch.LaunchedUtc && named.StartedUtc < tape.LastWriteUtc
|
||||
&& LaunchOf(box, launches) != launch);
|
||||
return another ? null : launch;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The launch a black box came from. Unlike a tape, it says which: its name has the scenery and the moment
|
||||
/// the recording started. So it is the last launch before that moment, and only if that launch was of the
|
||||
/// same scenery; one the starter didn't launch, copied in or started on its own, goes with no launch.
|
||||
/// </summary>
|
||||
public static TapeLaunch? LaunchOf(BlackBoxRecording box, IReadOnlyList<TapeLaunch> launches)
|
||||
{
|
||||
if (NamedBy(box.Path) is not { } named)
|
||||
return launches.LastOrDefault(l => l.Covers(box.LastWriteUtc));
|
||||
var launch = launches.LastOrDefault(l => l.Covers(named.StartedUtc));
|
||||
return launch is not null && SameStem(SceneryStem(launch.Scenery), named.Scenery) ? launch : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Two stems of one scenery. The simulator turns each byte of a letter outside ASCII into '_': one for 'ł'
|
||||
/// on Windows, two where the name comes as UTF-8. Runs of '_' are taken as one, and the case doesn't count.
|
||||
/// </summary>
|
||||
public static bool SameStem(string a, string b) =>
|
||||
string.Equals(Squeezed(a), Squeezed(b), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static string Squeezed(string stem)
|
||||
{
|
||||
var text = new StringBuilder(stem.Length);
|
||||
foreach (char c in stem)
|
||||
if (c != '_' || text.Length == 0 || text[^1] != '_')
|
||||
text.Append(c);
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private const string BlackBoxStamp = "yyyy-MM-dd_HH-mm-ss";
|
||||
|
||||
/// <summary>
|
||||
/// The scenery and the start a black box is named by, <c>scenery_YYYY-MM-DD_HH-MM-SS</c> in the local time
|
||||
/// of the computer that ran it; null for a name not made so.
|
||||
/// </summary>
|
||||
public static (string Scenery, DateTime StartedUtc)? NamedBy(string path)
|
||||
{
|
||||
string name = Path.GetFileNameWithoutExtension(path);
|
||||
int stamp = BlackBoxStamp.Length;
|
||||
if (name.Length < stamp + 2 || name[^(stamp + 1)] != '_'
|
||||
|| !DateTime.TryParseExact(name[^stamp..], BlackBoxStamp, CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AssumeLocal, out var local))
|
||||
return null;
|
||||
return (name[..^(stamp + 1)], local.ToUniversalTime());
|
||||
}
|
||||
|
||||
/// <summary>A scenery's file as the simulator names its black box: no '$' in front, but for ASCII letters, digits, '-' and '_' all '_'.</summary>
|
||||
public static string SceneryStem(string scenery)
|
||||
{
|
||||
string stem = Path.GetFileNameWithoutExtension(scenery);
|
||||
if (stem.StartsWith('$'))
|
||||
stem = stem[1..];
|
||||
var text = new StringBuilder(stem.Length);
|
||||
foreach (char c in stem)
|
||||
text.Append(char.IsAsciiLetterOrDigit(c) || c is '-' or '_' ? c : '_');
|
||||
return text.Length == 0 ? "scenery" : text.ToString();
|
||||
}
|
||||
|
||||
private BlackBoxRecording ReadBlackBox(string path) =>
|
||||
new(path, _files.GetLastWriteTimeUtc(path), _files.GetFileSize(path));
|
||||
|
||||
/// <summary>The player's own tapes first: every manned vehicle leaves one.</summary>
|
||||
private static TapeSession Session(TapeLaunch? launch, bool running, IEnumerable<TapeFile> tapes)
|
||||
private static TapeSession Session(TapeLaunch? launch, bool running, IEnumerable<TapeFile> tapes,
|
||||
IEnumerable<BlackBoxRecording> boxes)
|
||||
{
|
||||
var listed = tapes.OrderByDescending(tape => tape.Role).ThenByDescending(tape => tape.LastWriteUtc).ToList();
|
||||
var started = launch?.LaunchedUtc ?? listed.Min(tape => tape.LastWriteUtc);
|
||||
return new TapeSession(launch, started, listed.Count > 0 ? listed.Max(tape => tape.LastWriteUtc) : started,
|
||||
running, listed);
|
||||
var recorded = boxes.OrderByDescending(box => box.LastWriteUtc).ToList();
|
||||
var written = listed.Select(tape => tape.LastWriteUtc).Concat(recorded.Select(box => box.LastWriteUtc)).ToList();
|
||||
var started = launch?.LaunchedUtc ?? written.Min();
|
||||
return new TapeSession(launch, started, written.Count > 0 ? written.Max() : started, running, listed, recorded);
|
||||
}
|
||||
|
||||
public HaslerTape? Load(TapeFile file)
|
||||
|
||||
@@ -37,6 +37,12 @@
|
||||
<PackageReference Include="Material.Icons.Avalonia" Version="3.0.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- The black box of the simulator: its reader and the window it is played back in. -->
|
||||
<ProjectReference Include="..\Eu07.BlackBox\Eu07.BlackBox.csproj" />
|
||||
<ProjectReference Include="..\Eu07.BlackBox.Views\Eu07.BlackBox.Views.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Assets\Logo\" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -6,11 +6,13 @@ using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Threading;
|
||||
using Eu07.BlackBox.Views;
|
||||
using StarterNG.Application;
|
||||
using StarterNG.Domain.Settings;
|
||||
using StarterNG.Domain.Tapes;
|
||||
@@ -57,8 +59,15 @@ public sealed class HaslerTapeWindow : Window
|
||||
private readonly Control _recordingOff;
|
||||
private readonly Control _logOff;
|
||||
private readonly Dictionary<DateTime, bool> _expanded = new();
|
||||
private readonly Dictionary<string, BlackBoxWindow> _blackBoxes = new(StringComparer.OrdinalIgnoreCase);
|
||||
private HashSet<string> _liveBlackBoxes = new(StringComparer.OrdinalIgnoreCase);
|
||||
private IReadOnlyList<TapeSession> _sessions = Array.Empty<TapeSession>();
|
||||
private readonly Dictionary<string, double> _wantedAt = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Action<TapeSample> _picked;
|
||||
|
||||
private TapeFile? _shown;
|
||||
/// <summary>The session picked that has no tape, so that a refresh of the list goes back to it and not to a tape of another.</summary>
|
||||
private DateTime? _tapeless;
|
||||
private string? _followed;
|
||||
private string _listed = "";
|
||||
private bool _running;
|
||||
@@ -84,8 +93,10 @@ public sealed class HaslerTapeWindow : Window
|
||||
_scale.Value = DefaultKmScale;
|
||||
_scale.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == RangeBase.ValueProperty)
|
||||
_view.Scale = _scale.Value;
|
||||
if (e.Property != RangeBase.ValueProperty)
|
||||
return;
|
||||
_view.Scale = _scale.Value;
|
||||
ShowMark(scrollTo: false);
|
||||
};
|
||||
_live.Content = App.Loc["HaslerLive"];
|
||||
ToolTip.SetShowOnDisabled(_live, true);
|
||||
@@ -102,18 +113,38 @@ public sealed class HaslerTapeWindow : Window
|
||||
ToolTip.SetTip(_startClock, App.Loc["HaslerStartClockTip"]);
|
||||
|
||||
ScrollViewer.SetHorizontalScrollBarVisibility(_list, ScrollBarVisibility.Disabled);
|
||||
_list.KeyDown += async (_, e) =>
|
||||
{
|
||||
if (e.Key == Key.Enter && _list.SelectedItem is TreeViewItem { Tag: BlackBoxRecording box })
|
||||
{
|
||||
e.Handled = true;
|
||||
await OpenBlackBoxAsync(box);
|
||||
}
|
||||
};
|
||||
_list.SelectionChanged += async (_, _) =>
|
||||
{
|
||||
// A session stands for its first tape, the player's own if it has one.
|
||||
if (_list.SelectedItem is TreeViewItem { Tag: TapeSession } session)
|
||||
session.IsExpanded = true;
|
||||
var file = _list.SelectedItem switch
|
||||
if (_list.SelectedItem is TreeViewItem { Tag: TapeSession } node)
|
||||
node.IsExpanded = true;
|
||||
// A black box opens in a window of its own on a click or Enter, not when the arrows go over it; the
|
||||
// tape beside it is one of its session's, the one shown if it is.
|
||||
var session = _list.SelectedItem switch
|
||||
{
|
||||
TreeViewItem { Tag: TapeFile tape } => tape,
|
||||
TreeViewItem { Tag: TapeSession { Tapes.Count: > 0 } run } => run.Tapes[0],
|
||||
TreeViewItem { Tag: TapeSession run } => run,
|
||||
TreeViewItem { Tag: BlackBoxRecording box } =>
|
||||
_sessions.FirstOrDefault(s => s.BlackBoxes.Any(b => b.Path == box.Path)),
|
||||
_ => null
|
||||
};
|
||||
if (file is null || file == _shown)
|
||||
if (_list.SelectedItem is TreeViewItem { Tag: BlackBoxRecording } && session?.Tapes.Any(t => t.Path == _shown?.Path) == true)
|
||||
return;
|
||||
var file = _list.SelectedItem is TreeViewItem { Tag: TapeFile tape } ? tape : session?.Tapes.FirstOrDefault();
|
||||
if (file is null)
|
||||
{
|
||||
if (session is not null)
|
||||
ShowNoTape(session);
|
||||
return;
|
||||
}
|
||||
if (file == _shown)
|
||||
return;
|
||||
|
||||
ApplyContext(_tapes.ContextOf(file));
|
||||
@@ -123,6 +154,8 @@ public sealed class HaslerTapeWindow : Window
|
||||
_view = NewView(RecorderKind.Hasler);
|
||||
_view.Scale = DefaultKmScale;
|
||||
_view.Hovered += ShowCursor;
|
||||
_picked = async sample => await PickOnTapeAsync(sample);
|
||||
_view.Picked += _picked;
|
||||
_scroll = new ScrollViewer
|
||||
{
|
||||
HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
|
||||
@@ -271,13 +304,16 @@ public sealed class HaslerTapeWindow : Window
|
||||
|
||||
var old = _view;
|
||||
old.Hovered -= ShowCursor;
|
||||
old.Picked -= _picked;
|
||||
_view = NewView(Recorder);
|
||||
_view.CopySettingsFrom(old);
|
||||
_view.Hovered += ShowCursor;
|
||||
_view.Picked += _picked;
|
||||
_scroll.Content = _view;
|
||||
// The other view is not as tall; an offset kept from it would hide its top rows.
|
||||
_scroll.Offset = new Vector(_scroll.Offset.X, 0);
|
||||
_cursor.Text = "";
|
||||
ShowMark(scrollTo: false);
|
||||
}
|
||||
|
||||
private async Task RefreshListAsync(bool toDriven = false) =>
|
||||
@@ -291,12 +327,14 @@ public sealed class HaslerTapeWindow : Window
|
||||
private static string Fingerprint(IEnumerable<TapeSession> sessions) =>
|
||||
string.Join('\n', sessions.Select(session =>
|
||||
$"{session.StartedUtc:O} {session.LastWrittenUtc:yyyyMMddHHmm} {session.Running} " +
|
||||
string.Join(' ', session.Tapes.Select(tape => $"{tape.Vehicle}:{tape.Role}"))));
|
||||
string.Join(' ', session.Tapes.Select(tape => $"{tape.Vehicle}:{tape.Role}")) + " " +
|
||||
string.Join(' ', session.BlackBoxes.Select(box => box.Path))));
|
||||
|
||||
/// <summary>Sessions newest first, the newest one open until the reader has said otherwise.</summary>
|
||||
private void ShowSessions(IReadOnlyList<TapeSession> sessions, bool toDriven)
|
||||
{
|
||||
_running = sessions.Any(session => session.Running);
|
||||
_sessions = sessions;
|
||||
_listed = Fingerprint(sessions);
|
||||
ShowWhatIsKnown();
|
||||
|
||||
@@ -304,17 +342,22 @@ public sealed class HaslerTapeWindow : Window
|
||||
if (toDriven)
|
||||
_followed = driven;
|
||||
string? selected = toDriven && driven is not null ? driven : _shown?.Path;
|
||||
DateTime? tapeless = toDriven && driven is not null ? null : _tapeless;
|
||||
FollowBlackBoxes(sessions);
|
||||
|
||||
foreach (var node in _list.Items.OfType<TreeViewItem>())
|
||||
_expanded[((TapeSession)node.Tag!).StartedUtc] = node.IsExpanded;
|
||||
_list.Items.Clear();
|
||||
|
||||
(TreeViewItem Node, TreeViewItem Tape)? first = null, pick = null;
|
||||
TreeViewItem? again = null;
|
||||
for (int i = 0; i < sessions.Count; i++)
|
||||
{
|
||||
var node = SessionItem(sessions[i], _expanded.GetValueOrDefault(sessions[i].StartedUtc, i == 0));
|
||||
_list.Items.Add(node);
|
||||
foreach (var tape in node.Items.OfType<TreeViewItem>())
|
||||
if (sessions[i].StartedUtc == tapeless)
|
||||
again = node;
|
||||
foreach (var tape in node.Items.OfType<TreeViewItem>().Where(item => item.Tag is TapeFile))
|
||||
{
|
||||
first ??= (node, tape);
|
||||
if (((TapeFile)tape.Tag!).Path == selected)
|
||||
@@ -324,11 +367,20 @@ public sealed class HaslerTapeWindow : Window
|
||||
|
||||
_empty.Text = string.Format(App.Loc["HaslerNoTapes"], _tapes.Folder);
|
||||
_empty.IsVisible = first is null;
|
||||
_scroll.IsVisible = first is not null;
|
||||
// Shown again only by a tape loaded into it: one picked again as it is, unreadable, stays hidden.
|
||||
if (first is null)
|
||||
_scroll.IsVisible = false;
|
||||
if (pick is null && again is not null)
|
||||
{
|
||||
// The session picked had no tape; picked again, it shows the tape it has now, or still none.
|
||||
_list.SelectedItem = again;
|
||||
return;
|
||||
}
|
||||
if ((pick ?? first) is not { } chosen)
|
||||
{
|
||||
_shown = null;
|
||||
_view.Tape = null;
|
||||
_view.Mark = null;
|
||||
_summary.Text = "";
|
||||
return;
|
||||
}
|
||||
@@ -337,7 +389,7 @@ public sealed class HaslerTapeWindow : Window
|
||||
_list.SelectedItem = chosen.Tape;
|
||||
}
|
||||
|
||||
private static TreeViewItem SessionItem(TapeSession session, bool open)
|
||||
private TreeViewItem SessionItem(TapeSession session, bool open)
|
||||
{
|
||||
string title = session.Launch is { } launch
|
||||
? string.Join(" · ", new[] { string.IsNullOrWhiteSpace(launch.SceneryName) ? launch.Scenery : launch.SceneryName, launch.Train }
|
||||
@@ -372,11 +424,155 @@ public sealed class HaslerTapeWindow : Window
|
||||
Tag = session,
|
||||
IsExpanded = open
|
||||
};
|
||||
foreach (var box in session.BlackBoxes)
|
||||
item.Items.Add(BlackBoxItem(box));
|
||||
foreach (var tape in session.Tapes)
|
||||
item.Items.Add(TapeItem(tape));
|
||||
return item;
|
||||
}
|
||||
|
||||
private TreeViewItem BlackBoxItem(BlackBoxRecording box)
|
||||
{
|
||||
var text = new StackPanel { Spacing = 1 };
|
||||
text.Children.Add(new TextBlock { Text = App.Loc["HaslerBlackBox"], FontWeight = FontWeight.SemiBold });
|
||||
text.Children.Add(new TextBlock
|
||||
{
|
||||
Text = $"{box.LastWriteUtc.ToLocalTime():HH:mm} · {box.Size / (1024.0 * 1024.0):0.0} MB",
|
||||
FontSize = 11,
|
||||
Opacity = 0.7
|
||||
});
|
||||
ToolTip.SetTip(text, App.Loc["HaslerBlackBoxTip"]);
|
||||
var item = new TreeViewItem { 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The black box in its window, read on while the session runs; one window a file. Given a moment, it opens
|
||||
/// there. Where it plays is marked on a tape of the same session.
|
||||
/// </summary>
|
||||
private async Task OpenBlackBoxAsync(BlackBoxRecording box, double? at = null)
|
||||
{
|
||||
if (_blackBoxes.TryGetValue(box.Path, out var open))
|
||||
{
|
||||
if (at is { } moment)
|
||||
SeekBlackBox(box, open, moment);
|
||||
open.Activate();
|
||||
return;
|
||||
}
|
||||
var window = new BlackBoxWindow(new StarterBlackBoxStrings())
|
||||
{
|
||||
CanOpenFiles = false,
|
||||
Live = _liveBlackBoxes.Contains(box.Path)
|
||||
};
|
||||
_blackBoxes[box.Path] = window;
|
||||
if (at is { } first)
|
||||
_wantedAt[box.Path] = first;
|
||||
void Follow(double t) => FollowBlackBox(box, window, t);
|
||||
window.TimeChanged += Follow;
|
||||
window.Closed += (_, _) =>
|
||||
{
|
||||
window.TimeChanged -= Follow;
|
||||
_blackBoxes.Remove(box.Path);
|
||||
_wantedAt.Remove(box.Path);
|
||||
ShowMark(scrollTo: false);
|
||||
};
|
||||
window.Show(this);
|
||||
await window.OpenAsync(box.Path);
|
||||
// The last moment asked for while the file was read; not a window closed meanwhile, whose file another reads.
|
||||
if (_blackBoxes.TryGetValue(box.Path, out var current) && current == window
|
||||
&& _wantedAt.Remove(box.Path, out double wanted))
|
||||
window.SeekTo(wanted);
|
||||
}
|
||||
|
||||
/// <summary>A window still reading its file has no moment to go to yet: it goes there once it has read it.</summary>
|
||||
private void SeekBlackBox(BlackBoxRecording box, BlackBoxWindow window, double t)
|
||||
{
|
||||
if (window.Recording is null)
|
||||
_wantedAt[box.Path] = t;
|
||||
else
|
||||
window.SeekTo(t);
|
||||
}
|
||||
|
||||
/// <summary>The session of the tape shown, with its black boxes; null for a tape no list has any more.</summary>
|
||||
private TapeSession? ShownSession =>
|
||||
_shown is { } shown
|
||||
? _sessions.FirstOrDefault(session => session.Tapes.Any(tape => tape.Path == shown.Path))
|
||||
: null;
|
||||
|
||||
/// <summary>
|
||||
/// A click on the tape takes the black box of its session to the same moment, opening it if no window has it.
|
||||
/// Both count seconds of the simulation from its start, so a tape's own time is the black box's. Also the click
|
||||
/// that brings this window back from the black box's: going back to the tape is to look at another moment.
|
||||
/// </summary>
|
||||
private async Task PickOnTapeAsync(TapeSample sample)
|
||||
{
|
||||
if (ShownSession is not { BlackBoxes.Count: > 0 } session)
|
||||
return;
|
||||
var open = session.BlackBoxes.Where(box => _blackBoxes.ContainsKey(box.Path)).ToList();
|
||||
if (open.Count == 0)
|
||||
{
|
||||
await OpenBlackBoxAsync(session.BlackBoxes[0], sample.Time);
|
||||
return;
|
||||
}
|
||||
foreach (var box in open)
|
||||
SeekBlackBox(box, _blackBoxes[box.Path], sample.Time);
|
||||
}
|
||||
|
||||
/// <summary>Where a black box of the session shown plays, on its tape, brought into view as it moves on.</summary>
|
||||
private void FollowBlackBox(BlackBoxRecording box, BlackBoxWindow window, double t)
|
||||
{
|
||||
if (!_blackBoxes.TryGetValue(box.Path, out var open) || open != window
|
||||
|| ShownSession?.BlackBoxes.Any(b => b.Path == box.Path) != true)
|
||||
return;
|
||||
// Played, it moves every frame: the tape is drawn again only when the mark moves on it.
|
||||
double? x = _view.XAt(t), was = _view.MarkX;
|
||||
if (x == was || (x is { } now && was is { } before && Math.Abs(now - before) < 0.5))
|
||||
return;
|
||||
_view.Mark = t;
|
||||
BringMarkIntoView();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The mark of an open black box of the session shown, or none: on a tape just shown, and on a view changed,
|
||||
/// where a mark held back while it stood still on the old one would stand wrong.
|
||||
/// </summary>
|
||||
private void ShowMark(bool scrollTo)
|
||||
{
|
||||
var window = ShownSession?.BlackBoxes.Select(box => _blackBoxes.GetValueOrDefault(box.Path))
|
||||
.FirstOrDefault(w => w?.Recording is not null);
|
||||
_view.Mark = window?.CurrentTime;
|
||||
if (scrollTo)
|
||||
BringMarkIntoView();
|
||||
}
|
||||
|
||||
private void BringMarkIntoView()
|
||||
{
|
||||
if (_view.MarkX is not { } x)
|
||||
return;
|
||||
double left = _scroll.Offset.X, width = _scroll.Viewport.Width;
|
||||
if (width <= 0 || (x >= left + 16 && x <= left + width - 16))
|
||||
return;
|
||||
_scroll.Offset = new Vector(Math.Max(0, x - width / 2), _scroll.Offset.Y);
|
||||
}
|
||||
|
||||
/// <summary>The newest black box of a running session is still written; once the session ends, its last part is read and that is all.</summary>
|
||||
private void FollowBlackBoxes(IReadOnlyList<TapeSession> sessions)
|
||||
{
|
||||
_liveBlackBoxes = sessions.Where(session => session.Running)
|
||||
.SelectMany(session => session.BlackBoxes.Take(1))
|
||||
.Select(box => box.Path)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var (path, window) in _blackBoxes)
|
||||
{
|
||||
if (!window.Live || _liveBlackBoxes.Contains(path))
|
||||
continue;
|
||||
window.ReadMore();
|
||||
window.Live = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static TreeViewItem TapeItem(TapeFile file)
|
||||
{
|
||||
var text = new StackPanel { Spacing = 1 };
|
||||
@@ -413,6 +609,19 @@ public sealed class HaslerTapeWindow : Window
|
||||
_recorder.SelectedIndex = context.Recorder == RecorderKind.Electronic ? 1 : 0;
|
||||
}
|
||||
|
||||
/// <summary>A session with no tape, a black box at most: no tape of another session left beside it.</summary>
|
||||
private void ShowNoTape(TapeSession session)
|
||||
{
|
||||
_shown = null;
|
||||
_tapeless = session.StartedUtc;
|
||||
_view.Tape = null;
|
||||
_view.Mark = null;
|
||||
// With no tape the view would still draw a strip of blank paper beside the words.
|
||||
_scroll.IsVisible = false;
|
||||
_cursor.Text = "";
|
||||
_summary.Text = App.Loc[session.BlackBoxes.Count > 0 ? "HaslerSessionNoTape" : "HaslerSessionEmpty"];
|
||||
}
|
||||
|
||||
private async Task ShowAsync(TapeFile file, bool scrollToEnd)
|
||||
{
|
||||
if (_loading)
|
||||
@@ -421,15 +630,20 @@ public sealed class HaslerTapeWindow : Window
|
||||
try
|
||||
{
|
||||
var tape = await Task.Run(() => _tapes.Load(file));
|
||||
bool another = file.Path != _shown?.Path;
|
||||
_shown = file;
|
||||
_tapeless = null;
|
||||
_scroll.IsVisible = tape is not null;
|
||||
if (tape is null)
|
||||
{
|
||||
_view.Tape = null;
|
||||
_view.Mark = null;
|
||||
_summary.Text = string.Format(App.Loc["HaslerUnreadable"], file.Path);
|
||||
return;
|
||||
}
|
||||
|
||||
_view.Tape = tape;
|
||||
ShowMark(scrollTo: another && !scrollToEnd);
|
||||
_summary.Text = string.Format(App.Loc["HaslerSummary"], file.Vehicle, TapeFigures.Clock(tape.Duration),
|
||||
TapeFigures.Clock(tape.RunningTime), TapeFigures.Clock(tape.StandingTime),
|
||||
tape.DistanceM / 1000.0, tape.MaxSpeedKmh, tape.AverageSpeedKmh,
|
||||
@@ -441,6 +655,8 @@ public sealed class HaslerTapeWindow : Window
|
||||
// The log counts seconds from the start: an hour comes only from what the starter noted.
|
||||
if (string.IsNullOrWhiteSpace(_startClock.Text))
|
||||
_summary.Text += " · " + App.Loc["HaslerClockUnknown"];
|
||||
if (ShownSession is { BlackBoxes.Count: > 0 })
|
||||
_summary.Text += " · " + App.Loc["HaslerClickBlackBox"];
|
||||
if (scrollToEnd)
|
||||
Dispatcher.UIThread.Post(() => _scroll.Offset = new Vector(double.MaxValue, _scroll.Offset.Y),
|
||||
DispatcherPriority.Background);
|
||||
@@ -497,6 +713,7 @@ public sealed class HaslerTapeWindow : Window
|
||||
_view.ByDistance = byDistance;
|
||||
_scale.Value = byDistance ? DefaultKmScale : DefaultMinuteScale;
|
||||
_scale.Maximum = byDistance ? 600 : 300;
|
||||
ShowMark(scrollTo: false);
|
||||
}
|
||||
|
||||
/// <summary>The whole tape, not just what is scrolled into view, drawn afresh at the chosen scale.</summary>
|
||||
@@ -517,6 +734,8 @@ public sealed class HaslerTapeWindow : Window
|
||||
|
||||
var copy = NewView(Recorder);
|
||||
copy.CopySettingsFrom(_view);
|
||||
// The paper alone, not where a black box happens to be.
|
||||
copy.Mark = null;
|
||||
// The trip it was asked for: a reload may have come in behind the file picker.
|
||||
copy.Tape = tape;
|
||||
copy.Measure(Size.Infinity);
|
||||
|
||||
21
StarterNG/Views/Tapes/StarterBlackBoxStrings.cs
Normal file
21
StarterNG/Views/Tapes/StarterBlackBoxStrings.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using Eu07.BlackBox.Views;
|
||||
|
||||
namespace StarterNG.Views.Tapes;
|
||||
|
||||
/// <summary>
|
||||
/// The texts of the black box window in the starter's language: a translation may give any of
|
||||
/// them as BlackBox + its key; the rest are the window's own, in Polish or else in English.
|
||||
/// </summary>
|
||||
internal sealed class StarterBlackBoxStrings : IBlackBoxStrings
|
||||
{
|
||||
private readonly DefaultBlackBoxStrings _own = new(App.Loc.CurrentLangCode);
|
||||
|
||||
public string this[string key]
|
||||
{
|
||||
get
|
||||
{
|
||||
string text = App.Loc.Opt("BlackBox" + key);
|
||||
return text.Length > 0 ? text : _own[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,12 +31,21 @@ public abstract class TapeView : Control
|
||||
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);
|
||||
AffectsRender<TapeView>(TapeProperty, ByDistanceProperty, ScaleProperty, StartClockProperty, MarkProperty);
|
||||
}
|
||||
|
||||
public HaslerTape? Tape
|
||||
@@ -63,9 +72,18 @@ public abstract class TapeView : Control
|
||||
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;
|
||||
@@ -86,6 +104,23 @@ public abstract class TapeView : Control
|
||||
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);
|
||||
|
||||
@@ -96,6 +131,7 @@ public abstract class TapeView : Control
|
||||
ByDistance = other.ByDistance;
|
||||
Scale = other.Scale;
|
||||
StartClock = other.StartClock;
|
||||
Mark = other.Mark;
|
||||
}
|
||||
|
||||
protected override Size MeasureOverride(Size availableSize) =>
|
||||
@@ -110,6 +146,7 @@ public abstract class TapeView : Control
|
||||
return;
|
||||
|
||||
DrawTape(context, tape);
|
||||
DrawMark(context);
|
||||
DrawCursor(context);
|
||||
}
|
||||
|
||||
@@ -133,6 +170,19 @@ public abstract class TapeView : Control
|
||||
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);
|
||||
@@ -141,6 +191,23 @@ public abstract class TapeView : Control
|
||||
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)
|
||||
|
||||
@@ -850,6 +850,11 @@
|
||||
<String key="HaslerSession">Relace</String>
|
||||
<String key="HaslerSessionTapes">pásek: {0}</String>
|
||||
<String key="HaslerSessionRunning">běží</String>
|
||||
<String key="HaslerBlackBox">Černá skříňka</String>
|
||||
<String key="HaslerBlackBoxTip">Celá relace na mapě: jízda oproti AI, povely, návěstidla, kabina</String>
|
||||
<String key="HaslerClickBlackBox">klikněte na pásku: černá skříňka v tom okamžiku</String>
|
||||
<String key="HaslerSessionNoTape">Tato relace nemá pásku, jen černou skříňku.</String>
|
||||
<String key="HaslerSessionEmpty">Tato relace zatím nemá pásku ani černou skříňku.</String>
|
||||
<String key="WarehouseSaved">Ve skladu: {0}</String>
|
||||
<String key="WarehouseNothingToAdd">Vyberte soupravu s vozidly</String>
|
||||
<String key="GfxGroupLevelTip">Úroveň jen pro tuto část grafiky</String>
|
||||
|
||||
@@ -1079,6 +1079,11 @@
|
||||
<String key="HaslerSession">Session</String>
|
||||
<String key="HaslerSessionTapes">tapes: {0}</String>
|
||||
<String key="HaslerSessionRunning">running</String>
|
||||
<String key="HaslerBlackBox">Black box</String>
|
||||
<String key="HaslerBlackBoxTip">The whole session on a map: the driving against the AI, the commands, the signals, the cab</String>
|
||||
<String key="HaslerClickBlackBox">click the tape: the black box at that moment</String>
|
||||
<String key="HaslerSessionNoTape">This session has no tape, only the black box.</String>
|
||||
<String key="HaslerSessionEmpty">This session has no tape or black box yet.</String>
|
||||
<String key="WarehouseSaved">In the warehouse: {0}</String>
|
||||
<String key="WarehouseNothingToAdd">Pick a consist with vehicles</String>
|
||||
<String key="GfxGroupLevelTip">Level for this part of the graphics only</String>
|
||||
|
||||
@@ -850,6 +850,11 @@
|
||||
<String key="HaslerSession">Munkamenet</String>
|
||||
<String key="HaslerSessionTapes">szalag: {0}</String>
|
||||
<String key="HaslerSessionRunning">folyamatban</String>
|
||||
<String key="HaslerBlackBox">Fekete doboz</String>
|
||||
<String key="HaslerBlackBoxTip">A teljes menet a térképen: vezetés az AI-hoz képest, parancsok, jelzők, vezetőfülke</String>
|
||||
<String key="HaslerClickBlackBox">kattintson a szalagra: a fekete doboz abban a pillanatban</String>
|
||||
<String key="HaslerSessionNoTape">Ebben a munkamenetben nincs szalag, csak a fekete doboz.</String>
|
||||
<String key="HaslerSessionEmpty">Ebben a munkamenetben még nincs se szalag, se fekete doboz.</String>
|
||||
<String key="WarehouseSaved">A raktárban: {0}</String>
|
||||
<String key="WarehouseNothingToAdd">Válassz járműveket tartalmazó szerelvényt</String>
|
||||
<String key="GfxGroupLevelTip">Csak a grafika ezen részének szintje</String>
|
||||
|
||||
@@ -901,6 +901,11 @@
|
||||
<String key="HaslerSession">Sesja</String>
|
||||
<String key="HaslerSessionTapes">taśm: {0}</String>
|
||||
<String key="HaslerSessionRunning">trwa</String>
|
||||
<String key="HaslerBlackBox">Czarna skrzynka</String>
|
||||
<String key="HaslerBlackBoxTip">Cała sesja na mapie: jazda względem AI, komendy, sygnalizatory, kabina</String>
|
||||
<String key="HaslerClickBlackBox">kliknij taśmę: czarna skrzynka w tym momencie</String>
|
||||
<String key="HaslerSessionNoTape">W tej sesji nie ma taśmy, jest tylko czarna skrzynka.</String>
|
||||
<String key="HaslerSessionEmpty">W tej sesji nie ma jeszcze ani taśmy, ani czarnej skrzynki.</String>
|
||||
<String key="WarehouseSaved">W magazynie: {0}</String>
|
||||
<String key="WarehouseNothingToAdd">Wybierz skład z pojazdami</String>
|
||||
<String key="GfxGroupLevelTip">Poziom tylko tej części grafiki</String>
|
||||
|
||||
@@ -850,6 +850,11 @@
|
||||
<String key="HaslerSession">Сеанс</String>
|
||||
<String key="HaslerSessionTapes">лент: {0}</String>
|
||||
<String key="HaslerSessionRunning">идёт</String>
|
||||
<String key="HaslerBlackBox">Чёрный ящик</String>
|
||||
<String key="HaslerBlackBoxTip">Вся сессия на карте: езда по сравнению с ИИ, команды, светофоры, кабина</String>
|
||||
<String key="HaslerClickBlackBox">щёлкните по ленте: чёрный ящик в этот момент</String>
|
||||
<String key="HaslerSessionNoTape">В этом сеансе нет ленты, только чёрный ящик.</String>
|
||||
<String key="HaslerSessionEmpty">В этом сеансе пока нет ни ленты, ни чёрного ящика.</String>
|
||||
<String key="WarehouseSaved">На складе: {0}</String>
|
||||
<String key="WarehouseNothingToAdd">Выберите состав с транспортом</String>
|
||||
<String key="GfxGroupLevelTip">Уровень только для этой части графики</String>
|
||||
|
||||
Reference in New Issue
Block a user