Compare commits

...

74 Commits

Author SHA1 Message Date
cfea240243 Merge pull request #53 from MaSzyna-EU07/fix/scenery-file-events
fix: scenery files are looked at when they change, not every two seconds
2026-11-16 16:00:36 +00:00
maj00r
2a85ca384a refactor(scenery): the looks at the scenery files timed by a class of their own, under test
When the main window looks at the scenery files - once the reports of a
save stop, back at the window, now and then anyway, seldom where the
system reports changes and often where it does not - is FolderLooks now,
on TimeProvider timers, so the tests drive the clock. The window keeps
only the look itself. A report coming as the window closes leaves the
disposed timers be.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:55:22 +01:00
maj00r
100bbea83e fix(tests): the black box text tests wait their turn with the other Avalonia ones
EventTextsTests and SecurityBrakingTests from #55 ran beside the Avalonia
controls collection; their AppBuilder setup raced it and 28 UI tests failed
with "Setup was already called" on every runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:42:56 +01:00
maj00r
c370d1509e Merge main into fix/scenery-file-events
Conflict in MainWindow.axaml.cs, the Activated handler: main (#52) refreshes the list of simulators when
the settings are shown, this branch looks at the scenery files through _sceneryLook. Both kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:02:45 +01:00
3c9b578e6b Merge pull request #55 from MaSzyna-EU07/feat/command-descriptions
Black box: commands described, the protection's buzzer apart from its braking
2026-11-16 09:16:55 +00:00
952618be13 Merge pull request #52 from MaSzyna-EU07/fix/exe-list-refresh
fix: a simulator copied in while the starter runs is on the list
2026-11-16 09:16:17 +00:00
156af3fdd1 Merge pull request #51 from MaSzyna-EU07/fix/noavx2-exe
fix: without AVX2 the starter starts the simulator built without it
2026-11-16 09:16:05 +00:00
49b76aa66c Merge pull request #49 from MaSzyna-EU07/fix/reshade-beside-starter
fix: graphics wrappers beside the starter no longer reach its window
2026-11-16 09:15:52 +00:00
9b1523ef78 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
2026-11-16 09:15:39 +00:00
1d5b0ea1f4 Merge pull request #46 from MaSzyna-EU07/fix/linux-file-case
fix: find game data whatever the case of its names on Linux
2026-11-16 09:14:44 +00:00
maj00r
8baf2149ea fix(blackbox): a buzzer named by the lamps of its buzzing samples only 2026-11-16 02:21:23 +01:00
maj00r
aebfaf34ac fix(blackbox): a buzzer cut by the power or the protection switched off is not acknowledged, and is named by every lamp it had
The keys tab's English names the train brake's positions and the dashboard light as the black box does.
2026-11-16 02:20:34 +01:00
maj00r
5bc5da3fbf feat(blackbox): the train protection's buzzer told apart from its braking
The buzzer has a colour of its own on the timeline and in the cab, no longer the braking's red, and an event of its
own: acknowledged after how long, or not acknowledged when the braking follows. The alerter's buzzer needs its lamp,
since a protection with one acknowledgement tells the cab signalling's buzzer as the alerter's too. Braking with no
lamp, the protection with no power, is not shown as the driver's on the timeline and in the cab either.
2026-11-16 02:17:57 +01:00
maj00r
e4d092ab3e fix(blackbox): the command texts set right, and in the old starter's languages as the keys tab has them
Spelling and wording fixed (świateł, piasecznica, dezaktywacja, podgrzewacz wody, the dashboard light, the
locomotive brake), and the train brake's service and full service positions told by what they set, not as the key
file swaps them. In Czech, Hungarian and Russian the commands are named in the old starter's key descriptions.
2026-11-16 02:17:57 +01:00
maj00r
632e1003ee fix(blackbox): the protection braking with no power not counted as the driver's
TSecuritySystem brakes whenever it has no power, a cab not yet started or a power cut, with no lamp
lit. Only braking with the alerter or the cab signalling lamp is the driver's not acknowledging.
2026-11-16 02:04:22 +01:00
maj00r
34ee131d61 feat(blackbox): the commands in the events and on the timeline told by what they do
Every command of a vehicle the simulator can record (input/command.cpp) has a Polish and an English
text: those with a key take the key file's and the starter's own, the rest are written out. A command
with no text keeps its name.
2026-11-16 02:04:22 +01:00
maj00r
3f4a20097e fix: Sonar's remarks on the screen reader work, and tests for it
The cab panel's drawing and the consist narration are split into smaller
steps, with plain switches and concrete return types where Sonar asked.

Tests drive the black box panels, both tape views, the key bindings, the
windows opened over another, the search count and the themed tree
entries, sliders, number boxes, pickers and settings sections headless,
as someone at the keyboard with a screen reader meets them.
2026-11-15 22:06:55 +01:00
maj00r
38802845c7 test: no-AVX2 build names carry the date as the simulator writes it, 2026-11-15 2026-11-15 21:35:58 +01:00
maj00r
bba9e3ef48 fix: without AVX2 the starter starts the simulator built without it
The simulator now also comes built without AVX2, its file name ending in
_noavx2 (eu07-x64_<date>_<hash>_noavx2.exe, eu07_noavx2 on Linux), and both
builds can lie side by side in the game folder. The automatic choice took
eu07.exe or the shortest name and never that one, so a processor without
AVX2 got a simulator that stops at its first instruction and a notice
telling it to build its own.

Without AVX2 the automatic choice now takes the newest _noavx2 build, even
one through Wine before a native build that would not run. With AVX2 the
build made for it stays first and a _noavx2 one is used only when it is all
there is.

The notice comes only when what would start still needs AVX2. With a
_noavx2 build in the folder but another chosen by hand it names both and
offers to go back to the automatic choice; with none it says what such a
build is called and that the starter picks it up from the game folder.
2026-11-15 21:28:47 +01:00
maj00r
31fc4c3fdc fix: scenery files are looked at when they change, not every two seconds
The starter compared every file of every scenery each two seconds: on a full
installation 175 sceneries and 378 files, 15-18 ms a look, thirty looks a
minute with nothing changed. The system now reports changes in the scenery
folder and a look follows once the burst of a save has passed, 400 ms after
the last report.

The reports are only a hint. A look still comes on coming back to the window
and right after the simulator or its editor closes, and every 30 seconds
anyway, for network drives, Wine and Linux past its limit of watches, where
reports may not come. Where the folder cannot be watched at all the look
stays every two seconds as before. A change reported during a look is not
lost: one more look follows it.
2026-11-15 21:18:20 +01:00
maj00r
f29ce10f5c fix: a simulator copied in while the starter runs is on the list
The list of simulators in the settings was filled when they opened, so a new
eu07*.exe from CI or one's own build stayed missing until the starter was
reopened, and the older file was easy to start by mistake. The folder is now
looked at again when the settings page is shown, when the list takes focus
and when the window comes back to the front.

Looking again never changes the choice: a file picked from elsewhere, or one
since removed, stays chosen rather than falling back to automatic, and
nothing waits for Save after it. A list that did not change is left alone.

Closes #48
2026-11-15 21:13:53 +01:00
maj00r
ff5228555e fix: a blind player can bind keys, build a consist and read the tapes
A review against WCAG 2.2 AA left places a screen reader user could not work:

- Key bindings: a key's button says the command and the key, the clear button
  which command it clears; a new key is said aloud and focus comes back to its
  row. The on-screen keyboard is reached with Tab and walked with the arrows.
- Number fields read their label; the spin buttons are named and left out of Tab.
- Dialogs: Enter presses the main button, Esc closes, focus starts on the first
  button and the message is read with it.
- Consist: every change is said - added, removed, turned, moved, replaced,
  undone - and the strip is a named list; a turned card says so.
- Searches say how many entries are left once typing pauses.
- Hasler tapes, the black box timeline, timetable and cab panel take focus, work
  from the keyboard, read their value as it changes and draw a focus frame.
- Section reset and level controls, the crew button and the tabs carry names;
  English names from Avalonia's templates are read in the starter's language;
  sort and crew menus are radio items.
- Input borders reach 3:1 against the panels; Tab starts at the top bar; the
  splash screen has a title and its progress reads the loading step.
2026-11-15 20:46:55 +01:00
maj00r
07bd3d27fb fix: a tree entry tells its state wherever the mouse is on its row
Windows passes over the parts of a template when it looks for what lies under the
mouse, so the gaps beside the arrow and after the name led to the entry, which
told no state: NVDA said "Całkowo" there and "Całkowo zwinięte" on the name.
The row is now a control and is found in those gaps.
2026-11-15 20:07:26 +01:00
maj00r
ee6da4c8ee fix: nothing under the mouse is silent: dividers, previews, class pictures, categories
A page swept point by point left a few places a reader heard nothing: the panel
dividers, the vehicle preview in the depot and the texture base, the picture by
a vehicle class and the empty part of the settings categories. Each now has a
name; a picture with a caption beside it reads as the caption.

The tests that build controls run one after another: a control belongs to the
thread that made the first one, and side by side they now and then failed.
2026-11-15 20:01:25 +01:00
maj00r
184629b544 fix: NVDA hears a tree entry open, a list's new choice and the pictures and figures
Under the mouse a reader hears only what lies there. The row of a tree entry now
carries whether it is open, an arrow or icon in it its name; a picture takes the
name of the button or card it sits in, the scenery picture says what it shows; a
consist figure is one text, label and value together.

Avalonia tells Windows of a closed list's new value only for a list one types
into, so going through the weathers with the arrows was silent; the new choice
is now said aloud.
2026-11-15 19:39:09 +01:00
maj00r
95f1cd2398 fix: NVDA reads the tree entry, slider and help button under the mouse
The tree entry listed the entries under it as its own children, so the controls
inside it lost their way up and Windows failed every lookup there. It now only
points up to the entry it hangs under, which is all the level needs.

The buttons and knob of a slider's track had no name; they now say the slider's
name and value. A button showing only a sign such as "?" takes its tooltip.
2026-11-15 19:07:20 +01:00
maj00r
edd530cb4b fix: NVDA says the section focus enters, a setting's explanation and each fog step
NVDA passes over a group that is not content as well as control, so titled
panels and the landmarks are now both. A setting's explanation and the note on
why the simulator ignores it are read after its name. The key under each setting
is no longer a silent stop for Tab, and a step of the fog slider moves the shown
distance.
2026-11-15 18:45:06 +01:00
maj00r
d2b8cdf3ba fix: a screen reader hears which sceneries lie under a group
Avalonia hung the entries under a group on the panel inside it, so NVDA counted
every scenery at level one and the tree sounded flat. An open group now gives its
entries as its own, and each entry names its group as its parent: Całkowo is
level one, calkowo_lotos under it level two.
2026-11-15 18:36:23 +01:00
maj00r
099ff3603e fix: a field without a name is read by the label beside it
A list, box, slider or picker with no name of its own takes the text a sighted
reader sees next to it: to its left in a grid row, above it in a grid column, or
just before it in a panel. The name follows the label into another language.
2026-11-15 18:09:13 +01:00
maj00r
6c696b44e0 fix: a screen reader finds its way by landmarks and hears what a click changed
Titled panels are named groups, so the reader says which one focus went into.
The tab bar and the settings categories are navigation, the page is the main
part, the search boxes are search. A quality level, a section put back to its
defaults, settings reloaded, the weather put back or its time set to now are
spoken, as is the save status.
2026-11-15 18:05:26 +01:00
maj00r
a0a6ebdffa fix: a screen reader reads a slider as the value shown beside it
NVDA read a slider's bare number as a share of its length, so -5 °C was 45 and
the fog was where the knob stood on its scale. Sliders now give the text shown
next to them: the weather's temperature and visibility, and every setting row.
2026-11-15 17:59:04 +01:00
maj00r
5883376762 fix: a screen reader says what the date and time hold and that a tree group opens
The date and time pickers were read as a grid: the button inside them now carries
the field's label and its value. A scenery group in the tree says whether it is
open or closed, and the weather fields are named by their labels.
2026-11-15 17:49:44 +01:00
maj00r
a83bb4a7eb fix: a screen reader names every control and Tab survives adding a vehicle
NVDA read icon buttons as "Material.Icons.Avalonia.MaterialIcon" and the
sceneries in the tree as nothing. Icon buttons are now named by their
tooltip, list and tree entries by the text they show, fields by the hint in
them, and the inputs of a setting row by its label. The lists, the tree and
the language and profile pickers have names, and a consist card says its
place and vehicles.

Adding a vehicle rebuilt the browser list and switched the add button off
for a moment, and focus fell out of the window: Tab did nothing until
something was clicked. Focus goes back to the button or the list, and Tab
with nothing focused starts from the first control. The splitters are no
longer Tab stops.
2026-11-15 17:40:51 +01:00
maj00r
6e2dbf9eac test: the system graphics libraries and the software render switch
Taking the libraries and the switch's options are apart from Main, so they are
tested on every system, not only where Windows has them to load.
2026-11-15 17:30:13 +01:00
maj00r
91c496ab48 fix: graphics wrappers beside the starter no longer reach its window
ReShade installed for Direct3D as dxgi.dll in the simulator's folder was
loaded into the starter as well, and its window came up empty. The system
dxgi, d3d11, d3d9 and opengl32 are loaded first, and the window code's own
imports are handed those. The simulator still finds its wrappers.

--software-render draws the window on the processor, on Windows and X11,
for a machine on which it still comes up empty.
2026-11-15 14:41:48 +01:00
maj00r
7cd3ef8f1a test: the in-memory disk has the root of an absolute Linux path 2026-11-13 17:44:26 +01:00
maj00r
1b41ef752a chore: version 1.6
Data names are now found whatever their letter case on Linux.
2026-11-13 16:23:47 +01:00
maj00r
42f702a096 fix: an include in other letter case is no fault, as eu07 opens it
eu07 now finds files whatever the case of their names on Linux too
(MaSzyna-EU07/maszyna#362), so the starter no longer folds an include or a
scenery's .sbt to lower case to judge whether the simulator opens it: it
looks them up through CaseInsensitivePaths. The IncludeLetterCase fault and
its texts go, being a false alarm now, and the parser takes a plain yes or
no for each include.
2026-11-13 16:23:47 +01:00
maj00r
7f57160aae fix: open a livery's folder whatever the case of its name
"Open texture folder" finds the folder under dynamic, or from the game
folder, through CaseInsensitivePaths, so on Linux it opens the folder
when textures.txt names it in other letter case.
2026-11-13 16:23:47 +01:00
maj00r
2efae83b57 fix: find the loading screen logo whatever the case of its name
The textures/logo folder and a trainset's or scenery's logo in it are
looked up through CaseInsensitivePaths, with extensions in any case, so
on Linux the chosen logo is shown instead of a random one or none. The
lookup takes the file system, so it is tested.
2026-11-13 16:23:47 +01:00
maj00r
34f2ce99e8 fix: list files whatever the case of their extensions on Linux
PhysicalFileSystem matches a search pattern case-insensitively, as on
Windows, so X.SCN, .BMP minis and .FIZ files of data made on Windows are
listed on Linux as well.
2026-11-13 16:23:47 +01:00
maj00r
52408a9931 fix: follow .fiz includes and check vehicle files whatever their case
An include in a .fiz is looked up in the vehicle's folder through
CaseInsensitivePaths, so its physics are read on Linux when the include
names the file in other letter case. The missing-asset scan finds skins and
models the same way, with extensions in any case, instead of reporting
files that are there.
2026-11-13 16:23:47 +01:00
maj00r
290b753f40 fix: open a scenery's attachments whatever the case of their names
A //$f attachment is looked up from the game folder through the new
AttachmentLocator, so on Linux its button is enabled and opens the file
when the scenery names it in other letter case or with backslashes.
2026-11-13 16:23:47 +01:00
maj00r
6279228a7d fix: find a scenery's i18n tables whatever the case of their names
The i18n folder and its <scenery>_<language>.json tables are looked up
through CaseInsensitivePaths, so on Linux a scenery's texts are translated
when the table is named in other letter case than the scenery file.
2026-11-13 16:23:47 +01:00
maj00r
d4975796a8 fix: find a scenery's image and timetables whatever the case of their names
The //$i image and a trainset's timetable are looked up through
CaseInsensitivePaths, so on Linux they show when the scenery names them in
other letter case than the disk has. A timetable written with backslashes
is found there too, and with it the train number of a Hasler tape.
2026-11-13 16:23:47 +01:00
maj00r
48af11b4b2 refactor: share the case-insensitive lookup of data files
The scenery repository's include lookup becomes CaseInsensitivePaths, which
takes any folder over IFileSystem and gives a name as it is on disk. Of
folders named alike in other case it now tries each, not only the first.
A name is joined to the folder as the simulator joins it, a leading slash
counting for nothing. IFileSystem tells whether the disk ignores case; there,
as on Windows, a name missed as written is not looked for any further, so
no folder is listed.
2026-11-13 16:23:47 +01:00
maj00r
744720d922 Merge pull request #44 from MaSzyna-EU07/fix/dotted-model-names
fix: a dot in a model name is part of the name, not an extension
2026-11-12 21:33:51 +01:00
maj00r
b5ba67430f fix: a dot in a model name is part of the name, not an extension
The 9-107 and 9-110 coal wagons (9-107.13.fiz and the like) found no physics, so no load could be set on them.
2026-11-12 20:57:36 +01:00
maj00r
c261d4b0ab Merge pull request #43 from MaSzyna-EU07/fix/version-no-suffix
fix: the version is the number alone, with no public beta after it
2026-11-12 19:41:31 +01:00
maj00r
3aa6a256a5 fix: the version is the number alone, with no public beta after it 2026-11-12 19:38:11 +01:00
maj00r
95c510b3ac Merge pull request #41 from MaSzyna-EU07/fix/version-in-title
The version in the window's title
2026-11-12 17:44:17 +01:00
maj00r
5af567be7f 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
2026-11-12 17:44:02 +01:00
maj00r
b201b6f7ab Merge pull request #42 from MaSzyna-EU07/fix/consist-strip-selection
fix(scenarios): frame the vehicle started in, no background line between vehicles
2026-11-12 17:43:46 +01:00
maj00r
3a19fd5da2 Merge pull request #38 from MaSzyna-EU07/feat/sonarcloud-analysis
ci: analyse with SonarQube Cloud
2026-11-11 20:16:17 +01:00
maj00r
59dbd9cc0d fix(tapes): a refresh of the list leaves the paper of an unreadable tape hidden 2026-11-11 18:51:47 +01:00
maj00r
3ef630459c fix(tapes): a session with no tape shows no blank paper beside the words 2026-11-11 18:51:04 +01:00
maj00r
b7eefcd0ed fix(tapes): a session picked with no tape stays picked when the list refreshes, and an empty one says it has no black box either 2026-11-11 18:25:54 +01:00
maj00r
9b5848042a fix(tapes): a tape written after another run began is not the launch's before it, and a session with only a black box shows no other session's tape 2026-11-11 18:21:27 +01:00
maj00r
ef551a4ee7 fix(tapes): a scenery named with letters outside ASCII matches its black box on Linux too, where each byte of them is a '_' 2026-11-11 18:14:44 +01:00
maj00r
cf5cea26ad fix(tapes): a black box goes with the launch it started after and of its own scenery, not every one written after the last launch 2026-11-11 18:12:11 +01:00
maj00r
91158ebf72 fix(tapes): the moment asked while a file is read goes to the window still open, not one closed meanwhile 2026-11-11 18:05:45 +01:00
maj00r
cdc35c44e5 fix(tapes): no mark from a closed black box, the mark kept right through a view changed or a stop, the moment asked while a file is read kept, no jump back on a live re-read, the hint where it fits 2026-11-11 18:04:43 +01:00
maj00r
fa36284de1 feat(tapes): a click on the tape takes the black box of its session to that moment, and where the black box plays is marked on the tape 2026-11-11 17:55:56 +01:00
maj00r
da5a1efea1 fix: the version in the window's title, where it has room at any width 2026-11-11 17:53:01 +01:00
maj00r
9872b316c2 fix(blackbox): the traction's values in two columns, each whole in its cell 2026-11-11 03:19:14 +01:00
maj00r
ed9c1394bd fix(blackbox): the driver's valve as its gauge shows, no clash of the traction's labels, fewer self-made events
- The pressure of the driver's valve is named as what its gauge shows
  (the equalizing reservoir, the FV4a's time reservoir), alike in both
  languages.
- The traction's values are clipped to their columns, and the torque
  converter's label is shorter: it ran into the oil pressure's.
- The doors in two columns, the radio's label shorter: the names were cut.
- The compressor and the motor fans go on and off by themselves: no
  events for them.
- The summary of HeadCodes.Right back above it.
2026-11-11 02:55:42 +01:00
maj00r
0d16524953 feat(blackbox): the cab panel as fits the vehicle, every switch the driver worked in the events
- The rest of the cab record is read when written: what drives the
  vehicle, the doors' permits and departure signal, the brakes of the
  whole train, a diesel's oil and temperatures, the cruise control and
  the rest.
- Cab panel: the traction as fits what drives the vehicle (voltage and
  current of an electric one; revolutions, oil pressure and temperatures
  of a diesel; clutch or torque converter of a mechanical or hydraulic
  one; nothing for a draisine), the equalizing reservoir, the main
  reservoir pipe and the most braked cylinder of the train, the brakes'
  setting and mode, a group of the doors, the pumps of a diesel where an
  electric vehicle has its pantographs, the hand brake, the releaser, the
  horn's tone, the radio's channel, the integrated handle of a unit.
- Events: every switch on and off, doors opened and closed, the departure
  signal, the hand brake, the brakes' setting, the radio channel, the
  cruise control's speed; moving with the doors open and an overheating
  engine as faults.
- A vehicle with no lamps at an end (a draisine) is not judged on its
  lights, and one which never had a voltage shows none.
2026-11-11 02:43:51 +01:00
maj00r
4dcfd1c4e3 fix(blackbox): the timeline's labels on a narrow timeline, marks out of view, the cab on a short window
- The hover label and the clock bubble keep to the left edge on a
  narrow timeline instead of throwing in Render.
- A mark is told under the pointer only when it is drawn: within the
  plot and the time shown.
- The device groups are clipped at their own width, not 4 px short.
- On a short window the cab card scrolls, so the list above it keeps
  room for a few rows.
2026-11-11 01:50:40 +01:00
maj00r
9ee059bc16 feat(blackbox): a readable map legend, a key for the timeline's marks, the cab panel in titled parts
- Map legend: a title for each part, the texts in the text colour, the
  speed bands said in full ("up to 5 km/h faster than the AI").
- Timeline: the key names every mark (station, W6, signal passed,
  coupling, autopilot, command), the row of marks has its name, and the
  mark under the pointer is told in a label. The key no longer sits on
  the station plates.
- Cab panel: titled parts (controls, brakes, traction, lights, devices);
  the AI's speed and the next limit no longer run into the controllers;
  the lights of each end with the signal they show, and the one they are
  to show when it differs; the devices in three groups (power, driving,
  safety) instead of one long list.
2026-11-11 01:45:40 +01:00
maj00r
88adf5ee0f Black box: the test of an older recording's light pattern checks the lights were judged 2026-11-11 01:09:46 +01:00
maj00r
de3f088ba8 Black box: older recordings read as before, single vehicles told apart, each platform end its own tolerance
- A light pattern asked for in a recording made before the lamps were
  written is checked as the signal it shows, as before.
- Whether the couplings were written is told by the format (the
  movement in the cab samples), not by there being any: a recording
  where every train is a single vehicle has none, and the user going
  over to another vehicle left the timetable shown.
- The 2 m a train may stand off the platform is at each end, not for
  both together.
2026-11-11 01:05:59 +01:00
maj00r
532875fc7b Black box: the queries of the user's train worked out once a read, lights as the driver checks them
- The stations, the signals passed, the horn points, the couplings, the
  consists and the timetable progress of the user's train are kept until
  a read adds something; the views asked for them every frame, which on
  a long session with many trains took the window down. A read that adds
  nothing no longer counts as a change.
- The lights are checked against the lamps the vehicles at the ends have
  (written by the simulator from now on), as its driver checks them: Pc 1
  without the upper headlight, with the auxiliary lamps, Pc 5 with the
  rear-end signals. Only while the user drives: the autopilot's lights
  are its own.
- A train off the platform counts at both ends: its head past the stop
  point as well as its tail before the platform's end.
- A recording without the couplings keeps the timetable for any vehicle
  of the user.
- A signal passed at danger is ringed on the map only once it was.
- In the tapes window a black box opens on a click or Enter, not when
  the arrow keys go over it.
- The viewer's screenshot of a window not laid out saves nothing and
  still closes.
2026-11-11 00:57:57 +01:00
maj00r
e530b95352 Play back the black box of the simulator: map, cab, timeline, timetable and a summary
The simulator writes a black box of each run to physicslog/*.blackbox
(blackbox_doc.md in the maszyna repository). Three new projects read and
show it:

- Eu07.BlackBox: the reader of the records, the recording as a whole
  (the user's vehicle and consist at a time, the timetable shown, the
  progress along it with arrival and departure delays, whether the
  train stood at the platform), the light patterns Pc 1, Pc 2, Pc 5 and
  Tb 1 with the ones the run asks for, and a summary of the driving.
- Eu07.BlackBox.Views: the player window, with the scenery map (tracks,
  signals, W4 stop points with their heading and W32, the train, the
  cameras), the cab, the timeline of speed against the AI's reference,
  the events, the timetable and the summary.
- Eu07.BlackBox.Viewer: the window on its own, with options for the
  time, following the train and screenshots.

The tapes window of the starter lists the black boxes of each session
beside the Hasler tapes and opens them in the player.
2026-11-11 00:39:35 +01:00
jerrrrycho
e5330d91a6 ci: analyse with SonarQube Cloud
Runs SonarScanner for .NET around a full build and the tests, with
OpenCover coverage from coverlet, on pushes to main and on pull requests
from branches of this repository. Fork and Dependabot pull requests are
skipped: the C# analysis runs inside the build, so the token and the
built code cannot be kept on separate machines as in maszyna.

The scanner is pinned in .config/dotnet-tools.json for Dependabot.
2026-11-07 06:27:16 +01:00
146 changed files with 15180 additions and 471 deletions

13
.config/dotnet-tools.json Normal file
View File

@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-sonarscanner": {
"version": "12.1.0",
"commands": [
"dotnet-sonarscanner"
],
"rollForward": true
}
}
}

114
.github/workflows/sonar.yml vendored Normal file
View File

@@ -0,0 +1,114 @@
# .github/workflows/sonar.yml
# Has SONAR_TOKEN, so it only ever builds code that is already trusted: pushes to
# main and pull requests opened from a branch of this repository.
#
# Unlike the C++ analysis of maszyna, this one cannot be split into an untrusted
# build and a trusted scan. The C# analyzers run inside the compiler, and the
# scanner's begin step, which needs the token, has to run before the build on the
# same machine. A fork's build could leave a process behind to read the token from
# the end step, so fork pull requests are not analysed here. GitHub withholds the
# secret from them (and from Dependabot) anyway.
#
# The scanner is pinned in .config/dotnet-tools.json, where Dependabot updates it.
# SonarScanner for .NET takes its settings on the command line only; it refuses
# to run next to a sonar-project.properties, so there is none.
name: SonarQube Cloud
on:
# Main branch only: analysing other branches is a paid feature, pull requests
# are not.
push:
branches:
- main
pull_request:
branches:
- main
- staging
types: [ opened, reopened, synchronize ]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: sonar-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
env:
DOTNET_CLI_TELEMETRY_OPTOUT: 1
DOTNET_NOLOGO: true
SOLUTION_PATH: StarterNG.sln
TEST_PROJECT_PATH: StarterNG.Tests/StarterNG.Tests.csproj
jobs:
sonar:
name: Analyze
if: >
github.event_name != 'pull_request' ||
(github.event.pull_request.head.repo.full_name == github.repository &&
github.actor != 'dependabot[bot]')
runs-on: ubuntu-22.04
timeout-minutes: 30
steps:
# Full history, so new code and blame are told apart correctly.
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Setup .NET 9
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
dotnet-version: 9.0.x
- name: Restore tools
run: dotnet tool restore
# sonar.qualitygate.wait=true blocks the end step until the server has
# processed the report, so the job's result is the quality gate's.
- name: Begin analysis
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: >
dotnet tool run dotnet-sonarscanner begin
/k:"MaSzyna-EU07_StarterNG"
/o:"maszyna-eu07"
/n:"StarterNG"
/d:sonar.host.url="https://sonarcloud.io"
/d:sonar.token="$SONAR_TOKEN"
/d:sonar.scm.revision="${{ github.event.pull_request.head.sha || github.sha }}"
/d:sonar.cs.opencover.reportsPaths="TestResults/**/coverage.opencover.xml"
/d:sonar.cs.vstest.reportsPaths="TestResults/*.trx"
/d:sonar.qualitygate.wait=true
# A full, non-incremental build: the analyzers only see what is compiled.
- name: Build
run: >
dotnet build "${{ env.SOLUTION_PATH }}"
-c Release
--no-incremental
# Coverlet is already referenced by the test project; OpenCover is the
# format the C# analyzer reads.
- name: Test with coverage
run: >
dotnet test "${{ env.TEST_PROJECT_PATH }}"
-c Release
--no-build
--results-directory TestResults
--logger trx
--collect "XPlat Code Coverage"
--
DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover
- name: End analysis
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: >
dotnet tool run dotnet-sonarscanner end
/d:sonar.token="$SONAR_TOKEN"

View File

@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- The black box on its own, without the starter: opens the file given on the
command line, or one picked. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<PublishTrimmed>true</PublishTrimmed>
<IsAotCompatible>true</IsAotCompatible>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationIcon>..\StarterNG\Assets\starter.ico</ApplicationIcon>
<AssemblyName>BlackBoxViewer</AssemblyName>
<RootNamespace>Eu07.BlackBox.Viewer</RootNamespace>
<VersionPrefix>1.0</VersionPrefix>
<Company>eu07.pl</Company>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="12.1.4" />
<PackageReference Include="Avalonia.Desktop" Version="12.1.4" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="12.1.4" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="12.1.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Eu07.BlackBox.Views\Eu07.BlackBox.Views.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,109 @@
using System;
using System.IO;
using System.Linq;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Styling;
using Avalonia.Themes.Fluent;
using Eu07.BlackBox.Views;
namespace Eu07.BlackBox.Viewer;
/// <summary>
/// BlackBoxViewer [file.blackbox] [--live] [--time seconds] [--follow] [--timetable | --summary] [--screenshot out.png]
/// --live follows a file the simulator still writes; --screenshot saves the window
/// at the moment given and quits, for documentation and checks.
/// </summary>
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
return BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
public static AppBuilder BuildAvaloniaApp() =>
AppBuilder.Configure<ViewerApp>()
.UsePlatformDetect()
.WithInterFont();
}
internal sealed class ViewerApp : Application
{
public override void Initialize()
{
Styles.Add(new FluentTheme());
RequestedThemeVariant = ThemeVariant.Dark;
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var options = ViewerOptions.Parse(desktop.Args ?? Array.Empty<string>());
var window = new BlackBoxWindow { WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen };
window.Live = options.Live;
desktop.MainWindow = window;
window.Opened += async (_, _) =>
{
if (options.File is { } file)
await window.OpenAsync(Path.GetFullPath(file));
window.ShowTimetable = options.Timetable;
if (options.Summary)
window.SummaryShown = true;
if (options.Screenshot is { } shot)
{
await Screenshot.SaveAsync(window, shot, options.Time, options.Follow);
return;
}
if (options.Time is { } time)
window.SeekTo(time);
window.FollowTrain = options.Follow;
};
}
base.OnFrameworkInitializationCompleted();
}
}
internal sealed record ViewerOptions(string? File, bool Live, double? Time, string? Screenshot, bool Follow, bool Timetable,
bool Summary = false)
{
public static ViewerOptions Parse(string[] args)
{
string? file = null, screenshot = null;
double? time = null;
bool live = false, follow = false, timetable = false, summary = false;
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "--live":
live = true;
break;
case "--follow":
follow = true;
break;
case "--timetable":
timetable = true;
break;
case "--summary":
summary = true;
break;
case "--time" when i + 1 < args.Length &&
double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out var t):
time = t;
++i;
break;
case "--screenshot" when i + 1 < args.Length:
screenshot = args[++i];
break;
default:
if (!args[i].StartsWith("--", StringComparison.Ordinal))
file ??= args[i];
break;
}
}
return new ViewerOptions(file, live, time, screenshot, follow, timetable, summary);
}
}

View File

@@ -0,0 +1,29 @@
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media.Imaging;
using Eu07.BlackBox.Views;
namespace Eu07.BlackBox.Viewer;
/// <summary>The window as it shows a moment, saved to a PNG; then the viewer closes.</summary>
internal static class Screenshot
{
public static async Task SaveAsync(BlackBoxWindow window, string path, double? time, bool follow)
{
if (time is { } t)
window.SeekTo(t);
window.FollowTrain = follow;
// A few frames for the layout and the first render.
await Task.Delay(1000);
// Not laid out (a minimised window): nothing to save, and the viewer still closes.
if (window.Content is Control content && content.Bounds.Width >= 1 && content.Bounds.Height >= 1)
{
var size = new PixelSize((int)content.Bounds.Width, (int)content.Bounds.Height);
using var bitmap = new RenderTargetBitmap(size);
bitmap.Render(content);
bitmap.Save(path, new PngBitmapEncoderOptions());
}
window.Close();
}
}

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<!-- This manifest is used on Windows only.
Don't remove it as it might cause problems with window transparency and embedded controls.
For more details visit https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests -->
<assemblyIdentity version="1.0.0.0" name="Eu07.BlackBoxViewer"/>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- A list of the Windows versions that this application has been tested on
and is designed to work with. Uncomment the appropriate elements
and Windows will automatically select the most compatible environment. -->
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
</assembly>

View File

@@ -0,0 +1,601 @@
using System.Collections.Generic;
using System.Globalization;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The texts of the window, by key. The starter gives its own translations; on its
/// own the window speaks Polish or English, as the system does.
/// </summary>
public interface IBlackBoxStrings
{
string this[string key] { get; }
}
public sealed class DefaultBlackBoxStrings : IBlackBoxStrings
{
private static readonly Dictionary<string, string> English = new()
{
["Title"] = "Black box",
["TitleOf"] = "Black box – {0}",
["Open"] = "Open…",
["Reload"] = "Reload",
["Live"] = "Follow the file",
["LiveTip"] = "Reads what the simulator adds to the file every 2 seconds",
["Play"] = "Play",
["Pause"] = "Pause",
["PlaySpeed"] = "Playback speed",
["TimelineHelp"] = "The arrows go 10 seconds back or on, with Ctrl a minute, Page Up and Page Down ten minutes, Home and End to the start and the end.",
["TimetableHelp"] = "The up and down arrows go through the stations, Enter goes to the moment the train was there.",
["MapHelp"] = "The map of the run. What it shows is also in the events and the timetable, and on the run below it.",
["Follow"] = "Follow the train",
["Fit"] = "Whole map",
["NoFile"] = "Open a black box: physicslog/*.blackbox, written with the physics logs on.",
["Unreadable"] = "Can't read {0}: {1}",
["Reading"] = "Reading {0}…",
["Summary"] = "{0} · {1:0.0} km · max {2:0} km/h · driven {3} · autopilot {4} · over the AI {5} ({6} by more than {7:0} km/h, at most +{8:0} km/h) · signals {9} · at danger {10} · commands {11}",
["NotComplete"] = "still being written, or cut short",
["Cursor"] = "{0} · {1:0} km/h · AI {2} · limit {3}",
["CursorNoAi"] = "{0} · {1:0} km/h · no AI data",
["CursorOut"] = "{0} · not in a vehicle",
["None"] = "–",
["LimitAt"] = "{0:0} km/h in {1:0} m",
["EventCommand"] = "{0}",
["EventAutopilotOn"] = "Autopilot on",
["EventAutopilotOff"] = "Autopilot off",
["EventPassed"] = "Signal {0}: {1}, {2:0} km/h",
["EventDanger"] = "PASSED AT DANGER {0}, {1:0} km/h, {2:0} m beyond",
["EventInVehicle"] = "In {0}",
["EventOutside"] = "Out of the cab of {0}",
["EventNoVehicle"] = "Not in any vehicle",
["EventEnd"] = "End of the recording",
["AspectStop"] = "stop",
["AspectFree"] = "go",
["AspectSpeed"] = "{0:0}/{1}",
["LegendTitle"] = "The train's way: its speed against the AI's",
["LegendWithin"] = "no faster than the AI",
["LegendSlightly"] = "up to {0:0} km/h faster than the AI",
["LegendOver"] = "over {0:0} km/h faster than the AI",
["LegendAutopilot"] = "the autopilot drove",
["LegendNoData"] = "no AI to compare with",
["LegendMarks"] = "Signs on the map",
["TimelineSpeed"] = "speed",
["TimelineTarget"] = "AI",
["TimelineLimit"] = "next limit",
["BandEvents"] = "events",
["KeyStation"] = "station",
["KeyHorn"] = "W6 horn",
["KeySignal"] = "signal passed",
["KeyCoupling"] = "coupling",
["KeyDriver"] = "autopilot on/off",
["KeyCommand"] = "command",
["TlSignal"] = "signal {0} passed: {1}",
["TlSignalDanger"] = "signal {0} passed at stop",
["TlCoupled"] = "coupled",
["TlUncoupled"] = "uncoupled",
["TlCouplingChanged"] = "a coupling changed",
["TlAutopilotOn"] = "the autopilot switched on",
["TlAutopilotOff"] = "the user takes over",
["TlStationStopped"] = "{0}: stopped",
["TlStationPassed"] = "{0}: passed",
["TlStationMissed"] = "{0}: missed",
["TlHornSounded"] = "W6: the horn sounded",
["TlHornSilent"] = "W6: no horn",
["TlCommand"] = "command: {0}",
["BandDriving"] = "driving",
["BandBrakes"] = "brakes",
["BandAlerter"] = "alerter",
["BandController"] = "controller",
["Cab"] = "Cab",
["CabNoData"] = "The user was in no vehicle then.",
["CabController"] = "Master controller",
["CabShunt"] = "Field shunting",
["CabReverser"] = "Reverser",
["CabForward"] = "forward",
["CabBackward"] = "backward",
["CabNeutral"] = "0",
["CabTrainBrake"] = "Driver's brake valve",
["CabLocalBrake"] = "Local brake",
["CabReservoir"] = "Main reservoir",
["CabCylinder"] = "Brake cylinders",
["CabPipe"] = "Brake pipe",
["CabCurrent"] = "Current",
["CabVoltage"] = "Voltage",
["CabRpm"] = "Revolutions",
["CabLights"] = "Lights",
["CabLightsFront"] = "front",
["CabLightsRear"] = "rear",
["DevBattery"] = "Battery",
["DevMainBreaker"] = "Main breaker",
["DevPantographFront"] = "Front pantograph",
["DevPantographRear"] = "Rear pantograph",
["DevConverter"] = "Converter",
["DevCompressor"] = "Compressor",
["DevLineContactors"] = "Line contactors",
["DevHeating"] = "Train heating",
["DevRadio"] = "Radio",
["DevShuntMode"] = "Shunting mode",
["DevDoorsLeft"] = "Left doors open",
["DevDoorsRight"] = "Right doors open",
["DevSanding"] = "Sanding",
["DevHorn"] = "Horn",
["DevSpringBrake"] = "Spring brake",
["DevAlerter"] = "Alerter",
["DevWheelSlip"] = "Wheel slip",
["DevOverloadRelay"] = "Overload relay",
["DevRadioStop"] = "Radio-stop",
["DevAlarmChain"] = "Emergency brake",
["TabEvents"] = "Events",
["TabTimetable"] = "Timetable",
["TabSummary"] = "Summary",
["PanelMap"] = "Map",
["PanelTimeline"] = "Run",
["Relation"] = "{0} → {1}",
["StatDistance"] = "Distance",
["StatMaxSpeed"] = "Top speed",
["StatDriven"] = "Driven by the user",
["StatAutopilotSub"] = "autopilot {0}",
["StatOverAi"] = "Over the AI",
["StatOverAiSub"] = "{0} by >{1:0} km/h · up to +{2:0}",
["StatSignals"] = "Signals",
["StatSignalsSub"] = "{0} at danger",
["StatStops"] = "Stops",
["StatStopsSub"] = "{0} missed",
["StatDelay"] = "Largest delay",
["StatDelaySub"] = "leaving a station: {0} at most",
["StatPlatform"] = "Stops off the platform",
["StatLights"] = "Head and tail signals",
["StatLightsRight"] = "right",
["StatLightsSub"] = "as required all the {0} on the move",
["StatLightsHead"] = "head {0} instead of {1}",
["StatLightsTail"] = "tail {0} instead of {1}",
["StatPlatformAt"] = "{0} {1:0.0} m",
["StatPlatformNone"] = "the whole train along the platform at every stop",
["StatHorn"] = "Horn at W6",
["StatHornSub"] = "{0} without the horn",
["StatAcceleration"] = "Acceleration",
["StatAccelerationSub"] = "lateral up to {0:0.00} m/s²",
["StatSecurity"] = "CA/SHP braking",
["StatRecording"] = "Recording",
["StatComplete"] = "complete",
["StatIncomplete"] = "being written or cut short",
["Minutes"] = "{0:+0.0;−0.0;0} min",
["OnTime"] = "on time",
["DelayNow"] = "delay {0}",
["DelayStanding"] = "{0} standing at {1}",
["DelayAfter"] = "{0} after {1}",
["TimetableNone"] = "The user's train had no timetable.",
["TtArrived"] = "arr. {0}",
["TtDeparted"] = "dep. {0}",
["TtPassed"] = "passed {0}",
["TtMissed"] = "stop missed",
["TtLeftEarly"] = "left early",
["TtStopShort"] = "{0:0.0} m short",
["TtStopPast"] = "{0:0.0} m past",
["TtStopExact"] = "on the spot",
["TtOnPlatform"] = "along the platform",
["TtOffPlatform"] = "{0:0.0} m of the train off the platform",
["TtTechnical"] = "technical stop",
["TtStanding"] = "standing",
["EventStopped"] = "Stop at {0}, {1}",
["EventStationPassed"] = "Passed {0}",
["EventStationMissed"] = "STOP MISSED: {0}",
["EventReady"] = "{0}: time to leave",
["EventHornSounded"] = "W6: horn sounded",
["EventHornMissed"] = "W6: NO HORN",
["EventCab"] = "Cab {0} of {1}",
["EventSecurityBraking"] = "BRAKING BY {0}",
["EventSecurityAlarm"] = "{0} buzzer",
["EventSecurityAlarmAcknowledged"] = "{0} buzzer, acknowledged after {1:0.0} s",
["EventSecurityAlarmMissed"] = "{0} buzzer, not acknowledged",
["EventTimetable"] = "Timetable {0}, {1}",
["CabSpeed"] = "Speed",
["CabAiTarget"] = "AI {0:0} km/h",
["CabAcceleration"] = "Along",
["CabLateral"] = "Lateral",
["CabEndFront"] = "A",
["CabEndRear"] = "B",
["CabDriverUser"] = "user drives",
["CabDriverAi"] = "autopilot",
["CabOutside"] = "outside the cab",
["CabLightsHead"] = "head",
["CabLightsTail"] = "tail",
["CabSectionBrakes"] = "Brakes",
["CabSectionDrive"] = "Traction",
["CabSectionControls"] = "Controls",
["CabSectionDevices"] = "Devices",
["CabGroupPower"] = "Power",
["CabGroupDriving"] = "Driving",
["CabGroupSafety"] = "Safety",
["CabLightsWant"] = "{0}, should be {1}",
["CabLightsNone"] = "no lamps",
["CabBrakeSetting"] = "setting {0}",
["CabDriverValve"] = "Driver's valve",
["CabFeedPipe"] = "Main reservoir pipe",
["CabConsistCylinder"] = "Cylinders, train max",
["CabPower"] = "Power",
["CabSpeedControl"] = "Cruise control",
["CabOilPressure"] = "Oil pressure",
["CabWater"] = "Water",
["CabOil"] = "Oil",
["CabEngine"] = "Engine",
["CabNoDrive"] = "no drive of its own",
["CabClutch"] = "Clutch",
["CabConverterFill"] = "Converter",
["CabIntegrated"] = "Driving handle",
["CabGroupDoors"] = "Doors",
["DevDoorPermitLeft"] = "Left doors permitted",
["DevDoorPermitRight"] = "Right doors permitted",
["DevDepartureSignal"] = "Departure signal",
["DevDoorStep"] = "Steps",
["DevDoorLock"] = "Door lock",
["DevDoorsLocked"] = "Doors locked",
["DevBrakeReleaser"] = "Brake releaser",
["DevFuelPump"] = "Fuel pump",
["DevOilPump"] = "Oil pump",
["DevMotorBlowers"] = "Motor fans",
["DevEngineHot"] = "Engine overheating",
["DevSpeedControl"] = "Cruise control",
["DevRadioChannel"] = "Radio, channel {0}",
["DevHandBrake"] = "Hand brake",
["DevHornTone"] = "Horn ({0})",
["HornLow"] = "low",
["HornHigh"] = "high",
["HornBoth"] = "both",
["EventDeviceOn"] = "{0}: on",
["EventDeviceOff"] = "{0}: off",
["EventDoorsLeftClosed"] = "Left doors closed",
["EventDoorsRightClosed"] = "Right doors closed",
["EventMovingDoorsOpen"] = "Moving with the doors open ({0:0} km/h)",
["EventHandBrakeOn"] = "Hand brake applied",
["EventHandBrakeOff"] = "Hand brake released",
["EventBrakeSetting"] = "Brake setting: {0}",
["EventRadioChannel"] = "Radio: channel {0}",
["EventSpeedControlSet"] = "Cruise control: {0:0} km/h",
["DevVigilance"] = "CA",
["DevCabSignal"] = "SHP",
["DevSecurityBraking"] = "CA/SHP braking",
["LegendStopPoint"] = "W4 stop point",
["LegendShortStop"] = "W32 stop for shorter trains",
["ShortStopHover"] = "W32 {0}",
["LegendHorn"] = "W6 horn point",
["BandVigilance"] = "CA",
["BandCabSignal"] = "SHP",
["StopPointHover"] = "W4 {0}",
["PlatformHover"] = "platform {0:0} m",
["ShortTrainsHover"] = "for trains up to {0:0} m",
["StopHeadHover"] = "the head to stop {0:0} m before it",
["StopMiddleHover"] = "the middle of the train to stop {0:0} m before it",
["HornHover"] = "W6 {0} · {1:0} s",
["ZoomIn"] = "Zoom in",
["ZoomOut"] = "Zoom out",
["EventCamera"] = "Camera: {0}",
["CameraCab"] = "in the cab",
["CameraExternal"] = "outside view",
["CameraFree"] = "free camera",
["CameraDebug"] = "debug camera",
["EventCoupled"] = "Coupled {0} to {1}",
["EventUncoupled"] = "Uncoupled {0} from {1}",
["EventCouplingChanged"] = "{0} – {1}: {2}",
["CouplingCoupler"] = "coupler",
["CouplingBrakePipe"] = "brake pipe",
["CouplingControl"] = "control",
["CouplingPower"] = "high voltage",
["CouplingGangway"] = "gangway",
["CouplingMainPipe"] = "main pipe",
["CouplingHeating"] = "heating",
["CouplingNothing"] = "nothing",
["BandCamera"] = "camera",
["LegendCamera"] = "camera",
["Events"] = "Events",
["OnlyUser"] = "only the user's",
["FileFilter"] = "Black box"
};
private static readonly Dictionary<string, string> Polish = new()
{
["Title"] = "Czarna skrzynka",
["TitleOf"] = "Czarna skrzynka – {0}",
["Open"] = "Otwórz…",
["Reload"] = "Odśwież",
["Live"] = "Śledź plik",
["LiveTip"] = "Co 2 sekundy doczytuje to, co symulator dopisał do pliku",
["Play"] = "Odtwarzaj",
["Pause"] = "Pauza",
["PlaySpeed"] = "Prędkość odtwarzania",
["TimelineHelp"] = "Strzałki przesuwają o 10 sekund, z Ctrl o minutę, Page Up i Page Down o dziesięć minut, Home i End na początek i koniec.",
["TimetableHelp"] = "Strzałki w górę i w dół przechodzą po stacjach, Enter przenosi do chwili, gdy pociąg tam był.",
["MapHelp"] = "Mapa przejazdu. To, co pokazuje, jest też w zdarzeniach, w rozkładzie i na przebiegu jazdy pod nią.",
["Follow"] = "Śledź pociąg",
["Fit"] = "Cała mapa",
["NoFile"] = "Otwórz czarną skrzynkę: physicslog/*.blackbox, zapisywaną razem z logami fizyki.",
["Unreadable"] = "Nie można odczytać {0}: {1}",
["Reading"] = "Czytanie {0}…",
["Summary"] = "{0} · {1:0.0} km · maks. {2:0} km/h · jazda {3} · autopilot {4} · ponad AI {5} (w tym {6} o więcej niż {7:0} km/h, najwyżej +{8:0} km/h) · sygnalizatory {9} · minięte na „Stój” {10} · komendy {11}",
["NotComplete"] = "wciąż zapisywana albo ucięta",
["Cursor"] = "{0} · {1:0} km/h · AI {2} · ograniczenie {3}",
["CursorNoAi"] = "{0} · {1:0} km/h · brak danych AI",
["CursorOut"] = "{0} · poza pojazdem",
["None"] = "–",
["LimitAt"] = "{0:0} km/h za {1:0} m",
["EventCommand"] = "{0}",
["EventAutopilotOn"] = "Autopilot włączony",
["EventAutopilotOff"] = "Autopilot wyłączony",
["EventPassed"] = "Sygnalizator {0}: {1}, {2:0} km/h",
["EventDanger"] = "MINIĘTY NA „STÓJ” {0}, {1:0} km/h, {2:0} m za nim",
["EventInVehicle"] = "W {0}",
["EventOutside"] = "Poza kabiną {0}",
["EventNoVehicle"] = "Poza pojazdami",
["EventEnd"] = "Koniec nagrania",
["AspectStop"] = "stój",
["AspectFree"] = "wolna droga",
["AspectSpeed"] = "{0:0}/{1}",
["LegendTitle"] = "Ślad pociągu: prędkość wobec AI",
["LegendWithin"] = "nie szybciej niż AI",
["LegendSlightly"] = "do {0:0} km/h szybciej niż AI",
["LegendOver"] = "ponad {0:0} km/h szybciej niż AI",
["LegendAutopilot"] = "prowadził autopilot",
["LegendNoData"] = "brak AI do porównania",
["LegendMarks"] = "Znaki na mapie",
["TimelineSpeed"] = "prędkość",
["TimelineTarget"] = "AI",
["TimelineLimit"] = "następne ograniczenie",
["BandEvents"] = "zdarzenia",
["KeyStation"] = "stacja",
["KeyHorn"] = "W6 trąbienie",
["KeySignal"] = "minięty semafor",
["KeyCoupling"] = "sprzęg",
["KeyDriver"] = "autopilot wł./wył.",
["KeyCommand"] = "polecenie",
["TlSignal"] = "semafor {0} minięty: {1}",
["TlSignalDanger"] = "semafor {0} minięty na „Stój”",
["TlCoupled"] = "sprzęg połączony",
["TlUncoupled"] = "sprzęg rozłączony",
["TlCouplingChanged"] = "zmiana na sprzęgu",
["TlAutopilotOn"] = "autopilot włączony",
["TlAutopilotOff"] = "prowadzenie przejmuje użytkownik",
["TlStationStopped"] = "{0}: postój",
["TlStationPassed"] = "{0}: przejazd",
["TlStationMissed"] = "{0}: pominięta",
["TlHornSounded"] = "W6: zatrąbiono",
["TlHornSilent"] = "W6: bez trąbienia",
["TlCommand"] = "polecenie: {0}",
["BandDriving"] = "jazda",
["BandBrakes"] = "hamulce",
["BandAlerter"] = "czuwak",
["BandController"] = "nastawnik",
["Cab"] = "Kabina",
["CabNoData"] = "Użytkownik nie był wtedy w żadnym pojeździe.",
["CabController"] = "Nastawnik",
["CabShunt"] = "Bocznik",
["CabReverser"] = "Kierunek",
["CabForward"] = "naprzód",
["CabBackward"] = "wstecz",
["CabNeutral"] = "0",
["CabTrainBrake"] = "Hamulec zespolony",
["CabLocalBrake"] = "Hamulec pomocniczy",
["CabReservoir"] = "Zbiornik główny",
["CabCylinder"] = "Cylindry",
["CabPipe"] = "Przewód główny",
["CabCurrent"] = "Prąd",
["CabVoltage"] = "Napięcie",
["CabRpm"] = "Obroty",
["CabLights"] = "Światła",
["CabLightsFront"] = "przód",
["CabLightsRear"] = "tył",
["DevBattery"] = "Baterie",
["DevMainBreaker"] = "WS",
["DevPantographFront"] = "Pantograf przedni",
["DevPantographRear"] = "Pantograf tylny",
["DevConverter"] = "Przetwornica",
["DevCompressor"] = "Sprężarka",
["DevLineContactors"] = "Styczniki liniowe",
["DevHeating"] = "Ogrzewanie",
["DevRadio"] = "Radiotelefon",
["DevShuntMode"] = "Jazda manewrowa",
["DevDoorsLeft"] = "Drzwi lewe otwarte",
["DevDoorsRight"] = "Drzwi prawe otwarte",
["DevSanding"] = "Piasecznica",
["DevHorn"] = "Syrena",
["DevSpringBrake"] = "Hamulec sprężynowy",
["DevAlerter"] = "Czuwak",
["DevWheelSlip"] = "Poślizg",
["DevOverloadRelay"] = "Nadmiarowy",
["DevRadioStop"] = "Radiostop",
["DevAlarmChain"] = "Hamulec bezpieczeństwa",
["TabEvents"] = "Zdarzenia",
["TabTimetable"] = "Rozkład",
["TabSummary"] = "Podsumowanie",
["PanelMap"] = "Mapa",
["PanelTimeline"] = "Przebieg jazdy",
["Relation"] = "{0} → {1}",
["StatDistance"] = "Dystans",
["StatMaxSpeed"] = "Prędkość maks.",
["StatDriven"] = "Jazda użytkownika",
["StatAutopilotSub"] = "autopilot {0}",
["StatOverAi"] = "Ponad AI",
["StatOverAiSub"] = "{0} o >{1:0} km/h · do +{2:0}",
["StatSignals"] = "Sygnalizatory",
["StatSignalsSub"] = "{0} na „Stój”",
["StatStops"] = "Postoje",
["StatStopsSub"] = "{0} pominięte",
["StatDelay"] = "Największe opóźnienie",
["StatDelaySub"] = "przy odjeździe: najwyżej {0}",
["StatPlatform"] = "Postoje poza peronem",
["StatLights"] = "Sygnały czoła i końca",
["StatLightsRight"] = "zgodne",
["StatLightsSub"] = "jak trzeba przez całe {0} jazdy",
["StatLightsHead"] = "czoło {0} zamiast {1}",
["StatLightsTail"] = "koniec {0} zamiast {1}",
["StatPlatformAt"] = "{0} {1:0.0} m",
["StatPlatformNone"] = "na każdym postoju cały skład przy peronie",
["StatHorn"] = "Trąbienie na W6",
["StatHornSub"] = "{0} bez trąbienia",
["StatAcceleration"] = "Przyspieszenie",
["StatAccelerationSub"] = "boczne do {0:0.00} m/s²",
["StatSecurity"] = "Hamowania CA/SHP",
["StatRecording"] = "Nagranie",
["StatComplete"] = "pełne",
["StatIncomplete"] = "w trakcie zapisu lub ucięte",
["Minutes"] = "{0:+0.0;−0.0;0} min",
["OnTime"] = "planowo",
["DelayNow"] = "opóźnienie {0}",
["DelayStanding"] = "{0} stoi w: {1}",
["DelayAfter"] = "{0} za: {1}",
["TimetableNone"] = "Pociąg użytkownika nie miał rozkładu.",
["TtArrived"] = "przyj. {0}",
["TtDeparted"] = "odj. {0}",
["TtPassed"] = "przejazd {0}",
["TtMissed"] = "pominięty postój",
["TtLeftEarly"] = "odjazd przed czasem",
["TtStopShort"] = "{0:0.0} m przed miejscem",
["TtStopPast"] = "{0:0.0} m za miejscem",
["TtStopExact"] = "w punkt",
["TtOnPlatform"] = "cały przy peronie",
["TtOffPlatform"] = "{0:0.0} m składu poza peronem",
["TtTechnical"] = "postój techniczny",
["TtStanding"] = "stoi",
["EventStopped"] = "Postój: {0}, {1}",
["EventStationPassed"] = "Przejazd: {0}",
["EventStationMissed"] = "POMINIĘTY POSTÓJ: {0}",
["EventReady"] = "{0}: czas odjazdu",
["EventHornSounded"] = "W6: zatrąbił",
["EventHornMissed"] = "W6: BEZ TRĄBIENIA",
["EventCab"] = "Kabina {0} w {1}",
["EventSecurityBraking"] = "HAMOWANIE PRZEZ {0}",
["EventSecurityAlarm"] = "Brzęczyk {0}",
["EventSecurityAlarmAcknowledged"] = "Brzęczyk {0}, potwierdzony po {1:0.0} s",
["EventSecurityAlarmMissed"] = "Brzęczyk {0}, bez potwierdzenia",
["EventTimetable"] = "Rozkład {0}, {1}",
["CabSpeed"] = "Prędkość",
["CabAiTarget"] = "AI {0:0} km/h",
["CabAcceleration"] = "Wzdłużne",
["CabLateral"] = "Boczne",
["CabEndFront"] = "A",
["CabEndRear"] = "B",
["CabDriverUser"] = "prowadzi użytkownik",
["CabDriverAi"] = "autopilot",
["CabOutside"] = "poza kabiną",
["CabLightsHead"] = "czoło",
["CabLightsTail"] = "koniec",
["CabSectionBrakes"] = "Hamulce",
["CabSectionDrive"] = "Napęd",
["CabSectionControls"] = "Nastawniki",
["CabSectionDevices"] = "Urządzenia",
["CabGroupPower"] = "Zasilanie",
["CabGroupDriving"] = "Jazda",
["CabGroupSafety"] = "Bezpieczeństwo",
["CabLightsWant"] = "{0}, a ma być {1}",
["CabLightsNone"] = "brak lamp",
["CabBrakeSetting"] = "nastawa {0}",
["CabDriverValve"] = "Zawór maszynisty",
["CabFeedPipe"] = "Przewód zasilający",
["CabConsistCylinder"] = "Cylindry, skład max",
["CabPower"] = "Moc",
["CabSpeedControl"] = "Tempomat",
["CabOilPressure"] = "Ciśn. oleju",
["CabWater"] = "Woda",
["CabOil"] = "Olej",
["CabEngine"] = "Silnik",
["CabNoDrive"] = "brak własnego napędu",
["CabClutch"] = "Sprzęgło",
["CabConverterFill"] = "Przekładnia",
["CabIntegrated"] = "Zadajnik",
["CabGroupDoors"] = "Drzwi",
["DevDoorPermitLeft"] = "Zezwolenie lewe",
["DevDoorPermitRight"] = "Zezwolenie prawe",
["DevDepartureSignal"] = "Sygnał odjazdu",
["DevDoorStep"] = "Stopień",
["DevDoorLock"] = "Blokada drzwi",
["DevDoorsLocked"] = "Drzwi zablokowane",
["DevBrakeReleaser"] = "Odluźniacz",
["DevFuelPump"] = "Pompa paliwa",
["DevOilPump"] = "Pompa oleju",
["DevMotorBlowers"] = "Wentylatory silników",
["DevEngineHot"] = "Przegrzanie silnika",
["DevSpeedControl"] = "Tempomat",
["DevRadioChannel"] = "Radio, kanał {0}",
["DevHandBrake"] = "Hamulec ręczny",
["DevHornTone"] = "Syrena ({0})",
["HornLow"] = "niski",
["HornHigh"] = "wysoki",
["HornBoth"] = "oba",
["EventDeviceOn"] = "{0}: wł.",
["EventDeviceOff"] = "{0}: wył.",
["EventDoorsLeftClosed"] = "Drzwi lewe zamknięte",
["EventDoorsRightClosed"] = "Drzwi prawe zamknięte",
["EventMovingDoorsOpen"] = "Jazda z otwartymi drzwiami ({0:0} km/h)",
["EventHandBrakeOn"] = "Hamulec ręczny zaciągnięty",
["EventHandBrakeOff"] = "Hamulec ręczny zwolniony",
["EventBrakeSetting"] = "Nastawa hamulca: {0}",
["EventRadioChannel"] = "Radiotelefon: kanał {0}",
["EventSpeedControlSet"] = "Tempomat: {0:0} km/h",
["DevVigilance"] = "CA",
["DevCabSignal"] = "SHP",
["DevSecurityBraking"] = "Hamowanie CA/SHP",
["LegendStopPoint"] = "W4 – wskaźnik zatrzymania",
["LegendShortStop"] = "W32 – zatrzymanie krótszych pociągów",
["ShortStopHover"] = "W32 {0}",
["LegendHorn"] = "W6 – „trąbić”",
["BandVigilance"] = "CA",
["BandCabSignal"] = "SHP",
["StopPointHover"] = "W4 {0}",
["PlatformHover"] = "peron {0:0} m",
["ShortTrainsHover"] = "dla pociągów do {0:0} m",
["StopHeadHover"] = "czoło ma stanąć {0:0} m przed W4",
["StopMiddleHover"] = "środek składu ma stanąć {0:0} m przed W4",
["HornHover"] = "W6 {0} · {1:0} s",
["ZoomIn"] = "Przybliż",
["ZoomOut"] = "Oddal",
["EventCamera"] = "Kamera: {0}",
["CameraCab"] = "w kabinie",
["CameraExternal"] = "widok zewnętrzny",
["CameraFree"] = "wolna kamera",
["CameraDebug"] = "kamera debugowania",
["EventCoupled"] = "Sprzęgnięto {0} z {1}",
["EventUncoupled"] = "Rozprzęgnięto {0} od {1}",
["EventCouplingChanged"] = "{0} – {1}: {2}",
["CouplingCoupler"] = "sprzęg",
["CouplingBrakePipe"] = "przewód hamulcowy",
["CouplingControl"] = "sterowanie",
["CouplingPower"] = "WN",
["CouplingGangway"] = "mostek",
["CouplingMainPipe"] = "przewód zasilający",
["CouplingHeating"] = "ogrzewanie",
["CouplingNothing"] = "nic",
["BandCamera"] = "kamera",
["LegendCamera"] = "kamera",
["Events"] = "Zdarzenia",
["OnlyUser"] = "tylko użytkownika",
["FileFilter"] = "Czarna skrzynka"
};
/// <summary>The key of the text of a simulator's command: <see cref="CommandPrefix"/> and its name.</summary>
public const string CommandPrefix = "Cmd.";
private readonly Dictionary<string, string> _texts;
private readonly string _languageCode;
public DefaultBlackBoxStrings() : this(CultureInfo.CurrentUICulture)
{
}
public DefaultBlackBoxStrings(CultureInfo culture) : this(culture.TwoLetterISOLanguageName)
{
}
/// <summary>Polish for "pl", English for any other language.</summary>
public DefaultBlackBoxStrings(string languageCode)
{
_languageCode = languageCode;
_texts = languageCode == "pl" ? Polish : English;
}
/// <summary>The keys there are texts for, for a translation to give them all.</summary>
public static IEnumerable<string> Keys => English.Keys;
/// <summary>A key of <see cref="CommandPrefix"/> gives what the command does (<see cref="CommandTexts"/>).</summary>
public string this[string key] =>
key.StartsWith(CommandPrefix, System.StringComparison.Ordinal) ? CommandTexts.Of(key[CommandPrefix.Length..], _languageCode)
: _texts.TryGetValue(key, out var text) ? text : English.GetValueOrDefault(key, key);
}

View File

@@ -0,0 +1,584 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
namespace Eu07.BlackBox.Views;
/// <summary>
/// Replays a black box. Above: the train and the scenery, playing and how late the train
/// was. In the middle the map at the moment played, the timeline of the user's train under
/// it; beside them the events, the timetable or the figures of the driving, and the cab. A file
/// the simulator still writes can be followed: what it adds is read every two seconds, and
/// playing at its end keeps up with it.
/// </summary>
public sealed class BlackBoxWindow : Window
{
private static readonly double[] Speeds = { 1, 2, 5, 10, 30, 60 };
private readonly IBlackBoxStrings _strings;
private readonly MapView _map;
private readonly TimelineView _timeline;
private readonly EventList _events;
private readonly TimetablePanel _timetable;
private readonly ScrollViewer _timetableScroll;
private readonly ScrollViewer _summaryScroll;
private readonly CabPanel _cab;
private readonly UiKit.Segmented _tabs;
private readonly TextBlock _title = new() { FontSize = 14, FontWeight = FontWeight.SemiBold, Foreground = Palette.Text, TextTrimming = TextTrimming.CharacterEllipsis };
private readonly TextBlock _subtitle = new() { FontSize = 11, Foreground = Palette.DimText, TextTrimming = TextTrimming.CharacterEllipsis };
private readonly TextBlock _clock = new() { VerticalAlignment = VerticalAlignment.Center, FontSize = 18, FontWeight = FontWeight.SemiBold, Foreground = Palette.Text, MinWidth = 86, TextAlignment = TextAlignment.Center };
private readonly TextBlock _delayText = new() { FontSize = 12, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center, MinWidth = 120 };
private readonly TextBlock _readout = new() { VerticalAlignment = VerticalAlignment.Center, FontSize = 11, Foreground = Palette.DimText, TextTrimming = TextTrimming.CharacterEllipsis };
private readonly TextBlock _fileState = new() { VerticalAlignment = VerticalAlignment.Center, FontSize = 11, Foreground = Palette.FaintText };
private readonly TextBlock _message = new() { FontSize = 14, Foreground = Palette.DimText, TextWrapping = TextWrapping.Wrap, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Center, Margin = new Thickness(40) };
private readonly StackPanel _tiles = new();
private readonly UiKit.Tile _distance, _maxSpeed, _driven, _overAi, _signals, _stops, _delay, _platform, _lights, _horn, _acceleration, _security, _state;
private readonly Button _open;
private readonly Button _play;
private readonly ComboBox _speed = new() { VerticalAlignment = VerticalAlignment.Center, MinWidth = 64, FontSize = 12, Padding = new Thickness(8, 3) };
private readonly Avalonia.Controls.Primitives.ToggleButton _follow;
private readonly Avalonia.Controls.Primitives.ToggleButton _live;
private readonly DispatcherTimer _tick = new() { Interval = TimeSpan.FromMilliseconds(40) };
private readonly DispatcherTimer _reload = new() { Interval = TimeSpan.FromSeconds(2) };
private readonly Stopwatch _played = new();
private BlackBoxReader? _reader;
private string? _path;
private double _time;
private bool _reading;
public BlackBoxWindow() : this(null)
{
}
public BlackBoxWindow(IBlackBoxStrings? strings)
{
_strings = strings ?? new DefaultBlackBoxStrings();
Title = _strings["Title"];
Width = 1440;
Height = 900;
MinWidth = 960;
MinHeight = 600;
Background = Palette.Background;
UiKit.Accent(this);
WindowStartupLocation = WindowStartupLocation.CenterOwner;
_map = new MapView { Strings = _strings };
_timeline = new TimelineView { Strings = _strings };
_events = new EventList { Strings = _strings, Background = Brushes.Transparent };
_timetable = new TimetablePanel { Strings = _strings };
_timetableScroll = new ScrollViewer { Content = _timetable, IsVisible = false };
_summaryScroll = new ScrollViewer { Content = _tiles, IsVisible = false };
_cab = new CabPanel { Strings = _strings };
// ----- the bar on top: the train, playing, the switches -----
_open = UiKit.Button(_strings["Open"]);
_open.Click += async (_, _) => await PickAsync();
var reload = UiKit.Button(_strings["Reload"]);
reload.Click += (_, _) => ReadMore();
var fit = UiKit.Button(_strings["Fit"]);
fit.Click += (_, _) => ShowWhole();
_follow = UiKit.Toggle(_strings["Follow"]);
_follow.IsCheckedChanged += (_, _) => _map.Follow = _follow.IsChecked == true;
_map.FollowStopped += () => _follow.IsChecked = false;
_live = UiKit.Toggle(_strings["Live"], _strings["LiveTip"]);
_live.IsCheckedChanged += (_, _) =>
{
if (_live.IsChecked == true)
_reload.Start();
else
_reload.Stop();
};
_play = UiKit.PlayButton();
_play.Content = UiKit.PlayGlyph(false);
ToolTip.SetTip(_play, _strings["Play"]);
_play.Click += (_, _) => Playing = !Playing;
_speed.ItemsSource = Speeds.Select(s => $"×{s.ToString(CultureInfo.InvariantCulture)}").ToArray();
_speed.SelectedIndex = 3;
// What a screen reader calls the parts that have no label of their own on the screen.
AutomationProperties.SetName(_speed, _strings["PlaySpeed"]);
AutomationProperties.SetName(_timeline, _strings["PanelTimeline"]);
AutomationProperties.SetName(_timetable, _strings["TabTimetable"]);
AutomationProperties.SetName(_cab, _strings["Cab"]);
AutomationProperties.SetName(_map, _strings["PanelMap"]);
AutomationProperties.SetHelpText(_map, _strings["MapHelp"]);
var titles = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Children = { _title, _subtitle } };
var transport = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { _play, _clock, _speed, _delayText } };
var switches = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, VerticalAlignment = VerticalAlignment.Center, Children = { _follow, _live, fit, reload, _open } };
var header = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,*") };
Place(header, titles, 0, 0);
Place(header, transport, 0, 1);
switches.HorizontalAlignment = HorizontalAlignment.Right;
Place(header, switches, 0, 2);
titles.Margin = new Thickness(0, 0, 16, 0);
var headerBar = new Border
{
Background = Palette.Panel,
BorderBrush = Palette.CardBorder,
BorderThickness = new Thickness(0, 0, 0, 1),
Padding = new Thickness(8, 0),
Height = 44,
Child = header
};
// ----- the figures, a table in a tab of their own -----
_distance = Tile("StatDistance");
_maxSpeed = Tile("StatMaxSpeed");
_driven = Tile("StatDriven");
_overAi = Tile("StatOverAi");
_signals = Tile("StatSignals");
_stops = Tile("StatStops");
_delay = Tile("StatDelay");
_platform = Tile("StatPlatform");
_lights = Tile("StatLights");
_horn = Tile("StatHorn");
_acceleration = Tile("StatAcceleration");
_security = Tile("StatSecurity");
_state = Tile("StatRecording");
_timeline.Seek += t => SetTime(t);
_timeline.Hovered += ShowReadout;
_events.Seek += t => SetTime(t);
_timetable.Seek += t => SetTime(t);
_tick.Tick += (_, _) => Advance();
_reload.Tick += (_, _) => ReadMore();
// ----- the map with its zoom, the timeline, the side -----
var zoomIn = MapButton("+", _strings["ZoomIn"], () => _map.ZoomBy(1.6));
var zoomOut = MapButton("−", _strings["ZoomOut"], () => _map.ZoomBy(1 / 1.6));
var zoomFit = MapButton("⤢", _strings["Fit"], ShowWhole);
var zoom = new StackPanel
{
Spacing = 1,
Margin = new Thickness(8),
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Top,
Children = { zoomIn, zoomOut, zoomFit }
};
var mapArea = new Panel { Children = { _map, zoom, _message } };
_map.ClipToBounds = true;
_tabs = new UiKit.Segmented(_strings["TabEvents"], _strings["TabTimetable"], _strings["TabSummary"]);
_tabs.SelectedChanged += index =>
{
_events.IsVisible = index == 0;
_timetableScroll.IsVisible = index == 1;
_summaryScroll.IsVisible = index == 2;
};
var side = new DockPanel();
DockPanel.SetDock(_tabs, Dock.Top);
side.Children.Add(_tabs);
side.Children.Add(new Panel { Children = { _events, _timetableScroll, _summaryScroll } });
var cabCard = UiKit.Group(_strings["Cab"], new ScrollViewer { Content = _cab, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled });
cabCard.Margin = new Thickness(0, UiKit.Gap, 0, 0);
var sideColumn = new DockPanel();
// On a short window the cab scrolls, so the list above keeps room for a few rows.
sideColumn.SizeChanged += (_, e) => cabCard.MaxHeight = Math.Max(160, e.NewSize.Height - 160);
DockPanel.SetDock(cabCard, Dock.Bottom);
sideColumn.Children.Add(cabCard);
sideColumn.Children.Add(UiKit.Frame(side));
var body = new Grid
{
ColumnDefinitions = new ColumnDefinitions($"*,{UiKit.Gap.ToString(CultureInfo.InvariantCulture)},400"),
RowDefinitions = new RowDefinitions($"*,{UiKit.Gap.ToString(CultureInfo.InvariantCulture)},230")
};
Place(body, UiKit.Group(_strings["PanelMap"], mapArea), 0, 0);
Place(body, new GridSplitter { Background = Brushes.Transparent, ResizeDirection = GridResizeDirection.Rows, MinHeight = UiKit.Gap }, 1, 0);
Place(body, UiKit.Group(_strings["PanelTimeline"], _timeline), 2, 0);
var columns = new GridSplitter { Background = Brushes.Transparent, ResizeDirection = GridResizeDirection.Columns, MinWidth = UiKit.Gap };
Place(body, columns, 0, 1);
Grid.SetRowSpan(columns, 3);
Place(body, sideColumn, 0, 2);
Grid.SetRowSpan(sideColumn, 3);
// ----- the line at the bottom: the moment under the pointer, the state of the file -----
var status = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
Place(status, _readout, 0, 0);
Place(status, _fileState, 0, 1);
var statusBar = new Border
{
Background = Palette.Panel,
BorderBrush = Palette.CardBorder,
BorderThickness = new Thickness(0, 1, 0, 0),
Padding = new Thickness(12, 3),
Child = status
};
body.Margin = new Thickness(UiKit.Gap);
var root = new DockPanel { Background = Palette.Background };
DockPanel.SetDock(headerBar, Dock.Top);
DockPanel.SetDock(statusBar, Dock.Bottom);
root.Children.Add(headerBar);
root.Children.Add(statusBar);
root.Children.Add(body);
Content = root;
_title.Text = _strings["Title"];
_subtitle.Text = _strings["NoFile"];
_message.Text = _strings["NoFile"];
Closed += (_, _) =>
{
_tick.Stop();
_reload.Stop();
};
}
// When and at which end the signals were wrong: "10:55:12 head Tb 1 instead of Pc 1".
private string LightsFaultText(Recording recording, LightsFault fault, CultureInfo culture)
{
var ends = new List<string>();
if (fault.HeadWrong)
ends.Add(string.Format(culture, _strings["StatLightsHead"], HeadCodes.Name(fault.Head), HeadCodes.Name(fault.HeadRequired)));
if (fault.TailWrong)
ends.Add(string.Format(culture, _strings["StatLightsTail"], HeadCodes.Name(fault.Tail), HeadCodes.Name(fault.TailRequired)));
return $"{Clock(recording.ClockAt(fault.Start).TotalSeconds)} {string.Join(", ", ends)}";
}
private UiKit.Tile Tile(string key)
{
var tile = new UiKit.Tile(_strings[key]);
_tiles.Children.Add(tile);
return tile;
}
private static Button MapButton(string text, string tip, Action action)
{
var button = UiKit.Button(text, tip);
button.Width = 28;
button.Height = 28;
button.Padding = new Thickness(0);
button.FontSize = 15;
button.HorizontalContentAlignment = HorizontalAlignment.Center;
button.VerticalContentAlignment = VerticalAlignment.Center;
button.Background = Palette.Panel;
button.Click += (_, _) => action();
return button;
}
private static void Place(Grid grid, Control control, int row, int column)
{
Grid.SetRow(control, row);
Grid.SetColumn(control, column);
grid.Children.Add(control);
}
/// <summary>The button for opening another file: the starter opens the one picked in its list.</summary>
public bool CanOpenFiles
{
get => _open.IsVisible;
set => _open.IsVisible = value;
}
/// <summary>Reads what the simulator adds to the file every two seconds.</summary>
public bool Live
{
get => _live.IsChecked == true;
set => _live.IsChecked = value;
}
public string? FilePath => _path;
public Recording? Recording => _reader?.Recording;
public double CurrentTime => _time;
/// <summary>Goes to a moment of the recording, in seconds from its start.</summary>
public void SeekTo(double t) => SetTime(t);
/// <summary>The moment shown has changed: played on, sought or read further.</summary>
public event Action<double>? TimeChanged;
/// <summary>Keeps the user's train in the middle of the map.</summary>
public bool FollowTrain
{
get => _follow.IsChecked == true;
set => _follow.IsChecked = value;
}
/// <summary>The timetable beside the map instead of the events.</summary>
public bool ShowTimetable
{
get => _tabs.Selected == 1;
set => _tabs.Selected = value ? 1 : 0;
}
/// <summary>The summary of the driving beside the map instead of the events.</summary>
public bool SummaryShown
{
get => _tabs.Selected == 2;
set => _tabs.Selected = value ? 2 : 0;
}
private bool Playing
{
get => _tick.IsEnabled;
set
{
if (value == _tick.IsEnabled)
return;
if (value)
{
if (Recording is { } r && _time >= r.Duration - 0.05 && !Live)
SetTime(0);
_played.Restart();
_tick.Start();
}
else
_tick.Stop();
_play.Content = UiKit.PlayGlyph(value);
ToolTip.SetTip(_play, _strings[value ? "Pause" : "Play"]);
}
}
private void ShowWhole()
{
_follow.IsChecked = false;
_map.Fit();
_timeline.Fit();
}
/// <summary>Opens a black box, read whole on another thread.</summary>
public async Task OpenAsync(string path)
{
Playing = false;
ShowMessage(string.Format(CultureInfo.CurrentCulture, _strings["Reading"], Path.GetFileName(path)));
try
{
var reader = await Task.Run(() =>
{
var r = new BlackBoxReader();
r.ReadMore(path);
return r;
});
_reader = reader;
_path = path;
Title = string.Format(CultureInfo.CurrentCulture, _strings["TitleOf"], Path.GetFileName(path));
_map.Recording = reader.Recording;
_timeline.Recording = reader.Recording;
_events.Recording = reader.Recording;
_timetable.Recording = reader.Recording;
_cab.Recording = reader.Recording;
_message.IsVisible = false;
// A file still written opens at its end, where the train is now.
SetTime(Live ? reader.Recording.Duration : 0);
ShowSummary();
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
ShowMessage(string.Format(CultureInfo.CurrentCulture, _strings["Unreadable"], path, ex.Message));
}
}
private void ShowMessage(string text)
{
_message.Text = text;
_message.IsVisible = true;
_subtitle.Text = text;
_fileState.Text = "";
}
/// <summary>What the simulator added since the last read. Small, so read here, between frames.</summary>
public void ReadMore()
{
if (_reader is not { } reader || _path is null || _reading)
return;
_reading = true;
try
{
bool atEnd = _time >= reader.Recording.Duration - 0.5;
if (reader.ReadMore(_path) == 0)
return;
_events.Refresh();
if (atEnd && !Playing)
SetTime(reader.Recording.Duration);
else
SetTime(_time);
ShowSummary();
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
ShowMessage(string.Format(CultureInfo.CurrentCulture, _strings["Unreadable"], _path, ex.Message));
}
finally
{
_reading = false;
}
}
private async Task PickAsync()
{
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
Title = _strings["Open"],
AllowMultiple = false,
FileTypeFilter = new[] { new FilePickerFileType(_strings["FileFilter"]) { Patterns = new[] { "*.blackbox" } } }
});
if (files.Count > 0 && files[0].TryGetLocalPath() is { } path)
await OpenAsync(path);
}
private void Advance()
{
if (Recording is not { } recording)
return;
double real = _played.Elapsed.TotalSeconds;
_played.Restart();
double speed = Speeds[Math.Clamp(_speed.SelectedIndex, 0, Speeds.Length - 1)];
double next = _time + real * speed;
if (next >= recording.Duration)
{
next = recording.Duration;
// At the end of a file still written it waits for more.
if (!Live)
Playing = false;
}
SetTime(next);
}
private void SetTime(double t)
{
var recording = Recording;
double duration = recording?.Duration ?? 0;
_time = Math.Clamp(t, 0, duration);
_map.Time = _time;
_timeline.Time = _time;
_cab.Time = _time;
_timetable.Time = _time;
if (recording is null)
return;
_clock.Text = recording.ClockAt(_time).ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture);
_events.ShowTime(_time);
ShowReadout(null);
_timeline.Spoken = _readout.Text;
ShowDelay(recording);
TimeChanged?.Invoke(_time);
}
/// <summary>How late the user's train was at the moment played, by the clock.</summary>
private void ShowDelay(Recording recording)
{
if (StationProgress.DelayAt(recording, _time) is not { } delay)
{
_delayText.Text = "";
return;
}
var culture = CultureInfo.CurrentCulture;
var brush = Palette.Delay(delay.Minutes);
_delayText.Text = Math.Abs(delay.Minutes) < 0.5
? _strings["OnTime"]
: string.Format(culture, _strings["DelayNow"], string.Format(culture, _strings["Minutes"], delay.Minutes));
_delayText.Foreground = brush;
ToolTip.SetTip(_delayText, string.Format(culture, _strings[delay.Standing ? "DelayStanding" : "DelayAfter"], delay.Train,
StationNames.Display(delay.Station)));
}
/// <summary>The user's train at the moment under the pointer of the timeline, or at the moment played.</summary>
private void ShowReadout(double? hovered)
{
if (Recording is not { } recording)
return;
double t = hovered ?? _time;
string clock = recording.ClockAt(t).ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture);
var culture = CultureInfo.CurrentCulture;
if (recording.CabAt(t) is not { } s || t - s.Time > 1.0)
{
_readout.Text = string.Format(culture, _strings["CursorOut"], clock);
return;
}
if (!s.AiValid)
{
_readout.Text = string.Format(culture, _strings["CursorNoAi"], clock, s.AbsSpeedKmh);
return;
}
string limit = s.Ai.HasNextLimit
? string.Format(culture, _strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance)
: _strings["None"];
_readout.Text = string.Format(culture, _strings["Cursor"], clock, s.AbsSpeedKmh,
s.Ai.TargetKmh.ToString("0", culture) + " km/h", limit);
}
private void ShowSummary()
{
if (Recording is not { } recording)
return;
var summary = recording.Summarize();
var culture = CultureInfo.CurrentCulture;
// The scenery, the train and the vehicle the user started in.
string scenery = recording.Info?.Scenery ?? Path.GetFileName(_path) ?? "";
_title.Text = Path.GetFileNameWithoutExtension(scenery.TrimStart('$'));
var timetable = recording.TimetableAt(_time);
string vehicle = recording.Cab.Count > 0 ? recording.Vehicle(recording.Cab[^1].Vehicle)?.Name ?? "" : recording.Info?.StartVehicle ?? "";
var parts = new[]
{
timetable is null ? null : $"{timetable.Category} {timetable.Train}".Trim(),
timetable is null || timetable.From.Length + timetable.To.Length == 0 ? null : string.Format(culture, _strings["Relation"], timetable.From, timetable.To),
vehicle,
recording.Info?.Started.Replace('T', ' ')
};
_subtitle.Text = string.Join(" · ", parts.Where(p => !string.IsNullOrWhiteSpace(p)));
_distance.Show($"{summary.DistanceKm:0.0} km");
_maxSpeed.Show($"{summary.MaxSpeedKmh:0} km/h");
_driven.Show(Clock(summary.DrivenSeconds), string.Format(culture, _strings["StatAutopilotSub"], Clock(summary.AutopilotSeconds)));
_overAi.Show(Clock(summary.OverAiSeconds),
string.Format(culture, _strings["StatOverAiSub"], Clock(summary.WellOverAiSeconds), DrivingSummary.DefaultTolerance, summary.MaxOverAiKmh),
summary.WellOverAiSeconds > 0 ? Palette.Bad : summary.OverAiSeconds > 0 ? Palette.Warn : Palette.Good);
_signals.Show(summary.SignalsPassed.ToString(culture), string.Format(culture, _strings["StatSignalsSub"], summary.PassedAtDanger.Count),
summary.PassedAtDanger.Count > 0 ? Palette.Bad : null);
_stops.IsVisible = recording.Timetables.Count > 0;
_stops.Show(summary.Stops.ToString(culture), string.Format(culture, _strings["StatStopsSub"], summary.StopsMissed),
summary.StopsMissed > 0 ? Palette.Bad : null);
_delay.IsVisible = summary.MaxDelayMinutes is not null;
if (summary.MaxDelayMinutes is { } delay)
_delay.Show(string.Format(culture, _strings["Minutes"], delay),
summary.MaxDepartureDelayMinutes is { } departure
? string.Format(culture, _strings["StatDelaySub"], string.Format(culture, _strings["Minutes"], departure))
: null,
Palette.Delay(delay));
_platform.IsVisible = summary.Stops > 0;
_platform.Show(summary.OffPlatform.Count.ToString(culture),
summary.OffPlatform.Count > 0
? string.Join(" · ", summary.OffPlatform.Select(p => string.Format(culture, _strings["StatPlatformAt"], p.Station, p.Metres)))
: _strings["StatPlatformNone"],
summary.OffPlatform.Count > 0 ? Palette.Bad : Palette.Good);
_lights.IsVisible = summary.LightsJudgedSeconds > 0;
_lights.Show(summary.WrongLightsSeconds > 0 ? Clock(summary.WrongLightsSeconds) : _strings["StatLightsRight"],
summary.LightsFaults.Count > 0
? string.Join(" · ", summary.LightsFaults.Take(3).Select(f => LightsFaultText(recording, f, culture)))
+ (summary.LightsFaults.Count > 3 ? " …" : "")
: string.Format(culture, _strings["StatLightsSub"], Clock(summary.LightsJudgedSeconds)),
summary.WrongLightsSeconds > 0 ? Palette.Bad : Palette.Good);
_horn.IsVisible = summary.HornPoints > 0;
_horn.Show($"{summary.HornPoints - summary.HornsMissed}/{summary.HornPoints}", string.Format(culture, _strings["StatHornSub"], summary.HornsMissed),
summary.HornsMissed > 0 ? Palette.Bad : Palette.Good);
_acceleration.Show($"+{summary.MaxAcceleration:0.00} / −{summary.MaxDeceleration:0.00}",
string.Format(culture, _strings["StatAccelerationSub"], summary.MaxLateralAcceleration));
_security.Show(summary.SecurityBrakings.ToString(culture), null, summary.SecurityBrakings > 0 ? Palette.Bad : Palette.Good);
_state.Show(Clock(recording.Duration), _strings[recording.Complete ? "StatComplete" : "StatIncomplete"],
recording.Complete ? null : Palette.Warn);
_fileState.Text = $"{Path.GetFileName(_path)} · {Clock(recording.Duration)} · {_strings[recording.Complete ? "StatComplete" : "StatIncomplete"]}";
}
private static string Clock(double seconds)
{
var span = TimeSpan.FromSeconds(Math.Round(seconds));
return span.TotalHours >= 1
? span.ToString(@"h\:mm\:ss", CultureInfo.InvariantCulture)
: span.ToString(@"m\:ss", CultureInfo.InvariantCulture);
}
}

View File

@@ -0,0 +1,700 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The cab of the user's train at the moment played, for checking what the driver did: the
/// speed against the AI's, the accelerations, the controllers, the brakes (the pressures as
/// gauges, the setting), the traction as fits what drives the vehicle (the voltage and the
/// current of an electric one, the oil and the temperatures of a diesel), the lights at the
/// head and the tail of the train with what they are to show, and a lamp for every device in
/// groups (power, driving, safety, doors), the alerter (CA) and the cab signalling (SHP) apart.
/// </summary>
public sealed class CabPanel : Control
{
private const double Pad = 14;
private const double LampRow = 14;
private const int DoorColumns = 2;
private const double DriveRow = 34;
private Recording? _recording;
private double _time;
private int _measured = -1;
private int _controllerTop = 1;
private readonly HashSet<int> _powered = new();
private readonly HashSet<int> _feedPipe = new();
private readonly HashSet<int> _integrated = new();
private readonly HashSet<int> _hydraulic = new();
public CabPanel()
{
ClipToBounds = true;
Height = 696;
// Reached with Tab, where a screen reader reads what the panel shows.
Focusable = true;
}
// What the panel showed when last drawn, a line a figure, as a screen reader is told it.
private List<string>? _saying;
private string? _said;
/// <summary>What the panel shows, said in words: the figures and the lamps that are lit.</summary>
public string? Said => _said;
private void Say(string text)
{
if (!string.IsNullOrWhiteSpace(text))
_saying?.Add(text.Trim());
}
protected override AutomationPeer OnCreateAutomationPeer() =>
new SpokenPeer(this, AutomationControlType.Pane, () => null, () => _said);
protected override void OnGotFocus(FocusChangedEventArgs e)
{
base.OnGotFocus(e);
InvalidateVisual();
}
protected override void OnLostFocus(FocusChangedEventArgs e)
{
base.OnLostFocus(e);
InvalidateVisual();
}
public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings();
public Recording? Recording
{
get => _recording;
set
{
_recording = value;
_measured = -1;
InvalidateVisual();
}
}
public double Time
{
get => _time;
set
{
_time = value;
InvalidateVisual();
}
}
public override void Render(DrawingContext context)
{
_saying = new List<string>();
try
{
DrawPanel(context);
}
finally
{
_said = string.Join(". ", _saying);
_saying = null;
}
if (IsFocused)
context.DrawRectangle(null, Palette.FocusPen, new Rect(Bounds.Size).Deflate(1));
}
private void DrawPanel(DrawingContext context)
{
var size = Bounds.Size;
double width = size.Width - 2 * Pad, right = size.Width - Pad;
// The last sample, unless the train was out of sight for longer than a moment.
if (_recording is not { } recording || recording.CabAt(_time) is not { } s || _time - s.Time > 1.5)
{
context.DrawText(MapView.Text(Strings["CabNoData"], Palette.DimText, 12), new Point(Pad, 40));
Say(Strings["CabNoData"]);
return;
}
Measure(recording);
var culture = CultureInfo.CurrentCulture;
DrawHeader(context, recording.Vehicle(s.Vehicle)?.Name ?? "", s, right);
DrawSpeed(context, s, width, right, culture);
DrawControls(context, s, width, right, culture);
double y = DrawBrakes(context, s, width, right, culture);
// The traction at the left, as fits what drives the vehicle; the lights of both ends of the train at the right.
double half = Pad + width / 2;
double driveTop = y + BrakeRow + 4;
double top = Section(context, Strings["CabSectionDrive"], Pad, driveTop, half - 10);
Section(context, Strings["CabLights"], half + 4, driveTop, right);
DrawDrive(context, s, top, half - 10 - Pad, culture);
DrawLights(context, s, new Rect(half, top, right - half, 0), culture);
top = DrawDevices(context, s, new Rect(Pad, top + 3 * DriveRow + 6, width, size.Height), culture);
DrawDoors(context, s, top, width, size.Height);
}
private const double BrakeRow = 17;
/// <summary>The vehicle at the left; who drives, from which cab, at the right.</summary>
private void DrawHeader(DrawingContext context, string name, CabSample s, double right)
{
string? end = s.CabEnd == 0 ? null : Strings[s.CabEnd > 0 ? "CabEndFront" : "CabEndRear"];
double chipX = right;
if (end is not null)
chipX -= ChipLeft(context, end, Palette.Text, chipX, 4) + 5;
var (driverText, driverBrush) = DriverChip(s);
chipX -= ChipLeft(context, driverText, driverBrush, chipX, 4) + 10;
Say(name);
Say(driverText);
if (end is not null)
Say(end);
using (context.PushClip(new Rect(Pad, 0, Math.Max(0, chipX - Pad), 28)))
context.DrawText(MapView.Text(name, Palette.Text, 12, FontWeight.SemiBold), new Point(Pad, 6));
}
private (string Text, IBrush Brush) DriverChip(CabSample s)
{
if (!s.InCab)
return (Strings["CabOutside"], Palette.DimText);
return s.Driving == Driver.Ai ? (Strings["CabDriverAi"], Palette.Autopilot) : (Strings["CabDriverUser"], Palette.UserTrain);
}
/// <summary>The speed, large, what the AI would do under it, the accelerations at the right.</summary>
private void DrawSpeed(DrawingContext context, CabSample s, double width, double right, CultureInfo culture)
{
string kmh = s.AbsSpeedKmh.ToString("0", culture);
var speed = MapView.Text(kmh, SpeedBrush(DrivingSummary.Judge(s)), 36, FontWeight.SemiBold);
context.DrawText(speed, new Point(Pad, 24));
Say($"{kmh} km/h");
context.DrawText(MapView.Text("km/h", Palette.DimText, 12), new Point(Pad + speed.Width + 4, 24 + speed.Height - 21));
double gaugeX = Pad + Math.Max(150, width * 0.42);
if (s.AiValid)
{
using (context.PushClip(new Rect(Pad, 76, gaugeX - Pad - 8, 40)))
{
string target = string.Format(culture, Strings["CabAiTarget"], s.Ai.TargetKmh);
context.DrawText(MapView.Text(target, Palette.Target, 12), new Point(Pad, 76));
Say(target);
if (s.Ai.HasNextLimit)
{
string limit = string.Format(culture, Strings["LimitAt"], s.Ai.NextLimitKmh, s.Ai.NextLimitDistance);
Say(limit);
context.DrawText(MapView.Text(limit, Palette.Limit, 11), new Point(Pad, 93));
}
}
}
double gaugeWidth = right - gaugeX;
Balance(context, Strings["CabAcceleration"], s.Acceleration, 1.5, gaugeX, 34, gaugeWidth);
Balance(context, Strings["CabLateral"], s.LateralAcceleration, 1.5, gaugeX, 70, gaugeWidth);
}
private static IBrush SpeedBrush(SpeedJudgement judgement) => judgement switch
{
SpeedJudgement.Over => Palette.Bad,
SpeedJudgement.Slightly => Palette.Warn,
_ => Palette.Text
};
/// <summary>The controllers.</summary>
private void DrawControls(DrawingContext context, CabSample s, double width, double right, CultureInfo culture)
{
double top = Section(context, Strings["CabSectionControls"], Pad, 118, right);
double column = width / 4;
Value(context, Strings["CabController"], s.MainController.ToString(culture), Pad, top);
Steps(context, s.MainController, _controllerTop, Pad, top + 34, column - 14);
if (s.Extra is { } handle && _integrated.Contains(s.Vehicle))
Value(context, Strings["CabIntegrated"], (handle.IntegratedController * 100).ToString("+0;−0;0", culture) + " %", Pad + column, top);
else
Value(context, Strings["CabShunt"], s.ScndController.ToString(culture), Pad + column, top);
string reverser = s.Reverser switch { > 0 => "CabForward", < 0 => "CabBackward", _ => "CabNeutral" };
Value(context, Strings["CabReverser"], Strings[reverser], Pad + 2 * column, top);
Value(context, Strings["CabTrainBrake"], s.TrainBrake.ToString("0.0", culture), Pad + 3 * column, top);
}
/// <summary>The brakes, as gauges, the setting (G, P, R) at the right of the title.</summary>
/// <returns>Where the last gauge stands.</returns>
private double DrawBrakes(DrawingContext context, CabSample s, double width, double right, CultureInfo culture)
{
var extra = s.Extra;
string? setting = extra is { } e && (e.BrakeDelay | e.BrakeMode) != 0
? string.Format(culture, Strings["CabBrakeSetting"], string.Join(" · ", new[] { BrakeSetting(e.BrakeDelay), BrakeMode(e.BrakeMode) }.Where(t => t.Length > 0)))
: null;
double y = Section(context, Strings["CabSectionBrakes"], Pad, 180, right, setting);
var gauges = new List<GaugeReading>
{
new(Strings["CabPipe"], s.BrakePipe, 6, 5, $"{s.BrakePipe:0.00} bar", Palette.Station)
};
// what the driver's brake valve shows: its equalizing reservoir, the FV4a's time reservoir
if (extra is { } valve)
gauges.Add(new(Strings["CabDriverValve"], valve.DriverValve, 6, null, $"{valve.DriverValve:0.00} bar", Palette.Target));
gauges.Add(new(Strings["CabCylinder"], s.BrakeCylinder, 6, null, $"{s.BrakeCylinder:0.0} bar", Palette.Brakes));
// the most braked vehicle of the train
if (extra is { } most)
gauges.Add(new(Strings["CabConsistCylinder"], most.ConsistBrakeCylinder, 6, null, $"{most.ConsistBrakeCylinder:0.0} bar", Palette.Brakes));
gauges.Add(new(Strings["CabReservoir"], s.MainReservoir, 10, null, $"{s.MainReservoir:0.0} bar", Palette.Controller));
if (extra is { } feed)
gauges.Add(FeedPipe(s, feed));
gauges.Add(new(Strings["CabLocalBrake"], s.LocalBrake, 1, null, $"{s.LocalBrake * 100:0} %", Palette.Brakes));
for (int i = 0; i < gauges.Count; i++)
{
if (i > 0)
y += BrakeRow;
Gauge(context, gauges[i], Pad, y, width);
}
return y;
}
private GaugeReading FeedPipe(CabSample s, CabExtra feed) => _feedPipe.Contains(s.Vehicle)
? new(Strings["CabFeedPipe"], feed.FeedPipe, 10, null, $"{feed.FeedPipe:0.0} bar", Palette.Controller)
: new(Strings["CabFeedPipe"], 0, 10, null, "—", Palette.Controller);
/// <summary>The lights of both ends: the signal shown, green as it is to be, red otherwise with the one it is to show.</summary>
/// <param name="area">Left edge, top and width of the column; its height is not used.</param>
private void DrawLights(DrawingContext context, CabSample s, Rect area, CultureInfo culture)
{
double half = area.X, right = area.Right, row = area.Y;
foreach (var (key, lights, equipped, required, isRight) in new[]
{
("CabLightsHead", s.LightsHead, s.EquippedHead, HeadCodes.RequiredHead(s), HeadCodes.HeadRight(s)),
("CabLightsTail", s.LightsTail, s.EquippedTail, HeadCodes.RequiredTail(s), HeadCodes.TailRight(s))
})
{
DrawFace(context, lights, new Point(half + 4 + 17, row + 15));
string text = LightsText(HeadCodes.Of(lights), HeadCodes.NoLamps(equipped), required, isRight, culture);
IBrush brush = isRight switch { null => Palette.DimText, true => Palette.Good, false => Palette.Bad };
Say($"{Strings[key]}: {text}");
using (context.PushClip(new Rect(half + 44, row, right - half - 44, 28)))
{
context.DrawText(MapView.Text(Strings[key], Palette.DimText, 10), new Point(half + 46, row));
context.DrawText(MapView.Text(text, brush, 12, FontWeight.SemiBold), new Point(half + 46, row + 11));
}
row += 27;
}
}
private string LightsText(HeadCode shown, bool noLamps, HeadCode? required, bool? isRight, CultureInfo culture)
{
if (noLamps)
return Strings["CabLightsNone"];
if (isRight == false && required is { } want)
return string.Format(culture, Strings["CabLightsWant"], HeadCodes.Name(shown), HeadCodes.Name(want));
return isRight == true && required is { } met ? HeadCodes.Name(met) : HeadCodes.Name(shown);
}
/// <summary>The devices, in three groups side by side: lit as their lamps are in the cab, the ones off faint.</summary>
/// <param name="area">Left edge, top, width and the height of the whole panel.</param>
/// <returns>Where the doors go, under them.</returns>
private double DrawDevices(DrawingContext context, CabSample s, Rect area, CultureInfo culture)
{
double width = area.Width, height = area.Height;
double top = Section(context, Strings["CabSectionDevices"], area.X, area.Y, area.X + width);
var groups = Devices(s, culture);
var widths = new double[groups.Length];
for (int g = 0; g < groups.Length; g++)
{
widths[g] = MapView.Text(Strings[groups[g].Title], Palette.DimText, 10, FontWeight.SemiBold).Width;
foreach (var (text, _) in groups[g].Lamps)
widths[g] = Math.Max(widths[g], 14 + MapView.Text(text, Palette.Text, 10.5).Width);
}
// each group as wide as its longest name, what is left shared between them
double spare = (width - widths.Sum()) / groups.Length;
double x = area.X, bottom = top;
for (int g = 0; g < groups.Length; g++)
{
double groupWidth = Math.Max(20, widths[g] + spare);
using (context.PushClip(new Rect(x, top, groupWidth, height - top)))
bottom = Math.Max(bottom, DrawGroup(context, groups[g], x, top));
x += groupWidth;
}
return Math.Max(bottom, top + 16 + 9 * LampRow) + 6;
}
/// <returns>Where the group ends.</returns>
private double DrawGroup(DrawingContext context, (string Title, (string Text, IBrush? Lit)[] Lamps) group, double x, double top)
{
context.DrawText(MapView.Text(Strings[group.Title], Palette.DimText, 10, FontWeight.SemiBold), new Point(x, top));
Say(Strings[group.Title]);
double lampY = top + 16;
foreach (var (text, brush) in group.Lamps)
{
Lamp(context, text, brush, x, lampY);
lampY += LampRow;
}
return lampY;
}
/// <summary>The doors, in two columns: open, permitted, the departure signal, the steps and the lock.</summary>
private void DrawDoors(DrawingContext context, CabSample s, double top, double width, double height)
{
context.DrawText(MapView.Text(Strings["CabGroupDoors"], Palette.DimText, 10, FontWeight.SemiBold), new Point(Pad, top));
Say(Strings["CabGroupDoors"]);
var doors = Doors(s);
double doorColumn = width / DoorColumns;
for (int i = 0; i < doors.Length; i++)
{
double doorX = Pad + i % DoorColumns * doorColumn;
using (context.PushClip(new Rect(doorX, top, doorColumn, height - top)))
Lamp(context, doors[i].Text, doors[i].Lit, doorX, top + 16 + i / DoorColumns * LampRow);
}
}
/// <summary>
/// The traction, in two columns, as fits what drives the vehicle: the voltage, the current, the revolutions,
/// the power and the cruise control of an electric one; the revolutions, the current (or the clutch, or the
/// torque converter), the oil pressure and the temperatures of a diesel. A recording made before the engine
/// was written: those of an electric one it had then, no voltage for a vehicle which never had any.
/// </summary>
private void DrawDrive(DrawingContext context, CabSample s, double top, double width, CultureInfo culture)
{
var cells = new List<(string Label, string Value, IBrush? Brush)>();
void Add(string key, string value, IBrush? brush = null) => cells.Add((Strings[key], value, brush));
string voltage = _powered.Contains(s.Vehicle) ? $"{s.Voltage:0} V" : "—";
switch (s.Extra?.Engine)
{
case null:
Add("CabVoltage", voltage);
Add("CabCurrent", $"{s.MotorCurrent:0} A");
Add("CabRpm", $"{s.EngineRpm:0}");
break;
case EngineKind.Electric:
case EngineKind.ElectricInduction:
{
var e = s.Extra.Value;
Add("CabVoltage", voltage);
Add("CabCurrent", $"{s.MotorCurrent:0} A");
Add("CabRpm", $"{s.EngineRpm:0}");
Add("CabPower", $"{e.EnginePower:0} kW");
Add("CabSpeedControl", s.Has(CabDevices.SpeedControl) ? $"{e.SpeedControlKmh:0} km/h" : "—");
break;
}
case EngineKind.DieselElectric:
case EngineKind.Diesel:
{
var e = s.Extra.Value;
Add("CabRpm", $"{s.EngineRpm:0}");
if (e.Engine == EngineKind.DieselElectric)
Add("CabCurrent", $"{s.MotorCurrent:0} A");
else if (_hydraulic.Contains(s.Vehicle))
Add("CabConverterFill", $"{e.ConverterFill * 100:0} %");
else
Add("CabClutch", $"{e.Clutch * 100:0} %");
Add("CabOilPressure", string.Format(culture, "{0:0.00} MPa", e.OilPressure));
// the temperatures, warm when the engine is too hot
var heat = s.Has(CabDevices.EngineHot) ? Palette.Bad : null;
Add("CabWater", $"{e.WaterTemperature:0} °C", heat);
Add("CabOil", $"{e.OilTemperature:0} °C", heat);
Add("CabEngine", $"{e.EngineTemperature:0} °C", heat);
break;
}
case EngineKind.Steam:
Add("CabRpm", $"{s.EngineRpm:0}");
break;
default:
context.DrawText(MapView.Text(Strings["CabNoDrive"], Palette.DimText, 11), new Point(Pad, top + 2));
Say(Strings["CabNoDrive"]);
return;
}
double column = width / 2;
for (int i = 0; i < cells.Count; i++)
{
double x = Pad + i % 2 * column, y = top + i / 2 * DriveRow;
using (context.PushClip(new Rect(x, y, column - 4, DriveRow)))
Value(context, cells[i].Label, cells[i].Value, x, y, cells[i].Brush);
}
}
/// <summary>The setting of the brakes from its bits: G, P, R, R+Mg.</summary>
public static string BrakeSetting(byte bits)
{
var parts = new List<string>();
if ((bits & 1) != 0)
parts.Add("G");
if ((bits & 2) != 0)
parts.Add("P");
if ((bits & 4) != 0)
parts.Add("R");
if ((bits & 8) != 0)
parts.Add("Mg");
return string.Join("+", parts);
}
/// <summary>The mode of the brakes from its bits: PS, PN, EP, MED.</summary>
public static string BrakeMode(byte bits)
{
var parts = new List<string>();
if ((bits & 1) != 0)
parts.Add("PS");
if ((bits & 2) != 0)
parts.Add("PN");
if ((bits & 4) != 0)
parts.Add("EP");
if ((bits & 8) != 0)
parts.Add("MED");
return string.Join("+", parts);
}
/// <summary>The title of a part of the panel, with a line from it to the right (and a note at its end); the top of the part returned.</summary>
private double Section(DrawingContext context, string title, double x, double y, double right, string? note = null)
{
Say(note is null ? title : $"{title}, {note}");
var text = MapView.Text(title.ToUpper(CultureInfo.CurrentCulture), Palette.DimText, 9, FontWeight.SemiBold);
context.DrawText(text, new Point(x, y));
double end = right;
if (note is not null)
{
var noted = MapView.Text(note, Palette.Text, 10, FontWeight.SemiBold);
end = right - noted.Width - 8;
context.DrawText(noted, new Point(right - noted.Width, y + (text.Height - noted.Height) / 2));
}
double line = Math.Round(y + text.Height / 2) + 0.5;
if (x + text.Width + 8 < end)
context.DrawLine(new Pen(Palette.Grid, 1), new Point(x + text.Width + 8, line), new Point(end, line));
return y + 17;
}
/// <summary>
/// What is the same all the recording long for each vehicle: the highest step of the controller used, for
/// its bar, and which vehicles ever had a voltage, a main reservoir pipe, an integrated controller moved off
/// nought and a torque converter filled, to show the field shunting, the clutch or none for the others.
/// </summary>
private void Measure(Recording recording)
{
if (_measured == recording.Revision)
return;
int top = 1;
_powered.Clear();
_feedPipe.Clear();
_integrated.Clear();
_hydraulic.Clear();
foreach (var sample in recording.Cab)
{
top = Math.Max(top, sample.MainController);
if (sample.Voltage > 1)
_powered.Add(sample.Vehicle);
if (sample.Extra is not { } e)
continue;
if (e.FeedPipe > 0.1f)
_feedPipe.Add(sample.Vehicle);
if (Math.Abs(e.IntegratedController) > 0.01f)
_integrated.Add(sample.Vehicle);
if (e.ConverterFill > 0.01f)
_hydraulic.Add(sample.Vehicle);
}
_controllerTop = top;
_measured = recording.Revision;
}
private void Value(DrawingContext context, string label, string value, double x, double y, IBrush? brush = null)
{
Say($"{label}: {value}");
context.DrawText(MapView.Text(label, Palette.DimText, 10), new Point(x, y));
context.DrawText(MapView.Text(value, brush ?? Palette.Text, 14, FontWeight.SemiBold), new Point(x, y + 13));
}
/// <summary>The steps of the controller as a row of cells, lit up to the one it stands at.</summary>
private static void Steps(DrawingContext context, int step, int top, double x, double y, double width)
{
int cells = Math.Clamp(top, 1, 40);
double cell = width / cells;
for (int i = 0; i < cells; i++)
context.DrawRectangle(i < step ? Palette.Controller : Palette.LampOff, null,
new Rect(x + i * cell, y, Math.Max(1, cell - (cells > 20 ? 0.5 : 1.5)), 4), 1, 1);
}
/// <summary>A gauge: its name, a bar up to the value against the scale, a mark where it should stand, the value.</summary>
private void Gauge(DrawingContext context, GaugeReading reading, double x, double y, double width)
{
var (label, value, scale, mark, text, brush) = reading;
Say($"{label}: {text}");
const double labelWidth = 118, valueWidth = 64;
context.DrawText(MapView.Text(label, Palette.DimText, 11), new Point(x, y));
double barX = x + labelWidth, barWidth = width - labelWidth - valueWidth;
var track = new Rect(barX, y + 5, barWidth, 6);
context.DrawRectangle(Palette.LampOff, null, track, 3, 3);
double filled = Math.Clamp(value / scale, 0, 1) * barWidth;
if (filled > 0.5)
context.DrawRectangle(brush, null, new Rect(barX, y + 5, filled, 6), 3, 3);
if (mark is { } m)
{
double mx = barX + m / scale * barWidth;
context.DrawLine(new Pen(Palette.Text, 1.5), new Point(mx, y + 2), new Point(mx, y + 14));
}
var v = MapView.Text(text, Palette.Text, 11, FontWeight.SemiBold);
context.DrawText(v, new Point(x + width - v.Width, y));
}
/// <summary>A value either way of nought: a bar from the middle, to the right above it.</summary>
private void Balance(DrawingContext context, string label, float value, double scale, double x, double y, double width)
{
var culture = CultureInfo.CurrentCulture;
Say($"{label}: {value.ToString("+0.00;−0.00;0.00", culture)} m/s²");
context.DrawText(MapView.Text(label, Palette.DimText, 10), new Point(x, y));
var v = MapView.Text($"{value.ToString("+0.00;−0.00;0.00", culture)} m/s²", Palette.Text, 11, FontWeight.SemiBold);
context.DrawText(v, new Point(x + width - v.Width, y));
double barY = y + 17, middle = x + width / 2;
context.DrawRectangle(Palette.LampOff, null, new Rect(x, barY, width, 5), 2.5, 2.5);
double length = Math.Clamp(value / scale, -1, 1) * width / 2;
var brush = Math.Abs(value) > scale * 0.7 ? Palette.Bad : value >= 0 ? Palette.Good : Palette.Brakes;
if (Math.Abs(length) > 0.5)
context.DrawRectangle(brush, null, new Rect(Math.Min(middle, middle + length), barY, Math.Abs(length), 5), 2.5, 2.5);
context.DrawLine(new Pen(Palette.DimText, 1), new Point(middle, barY - 2), new Point(middle, barY + 7));
}
/// <summary>A chip ending at x, its width returned.</summary>
private static double ChipLeft(DrawingContext context, string text, IBrush brush, double right, double y)
{
var label = MapView.Text(text, brush, 11, FontWeight.SemiBold);
var box = new Rect(right - label.Width - 12, y, label.Width + 12, label.Height + 4);
context.DrawRectangle(Palette.Faded(brush, 0.14), null, box, 4, 4);
context.DrawText(label, new Point(box.X + 6, y + 2));
return box.Width;
}
/// <summary>The lights of an end as they sit on the front of a locomotive: one up in the middle, two below.</summary>
private static void DrawFace(DrawingContext context, Lights lights, Point center)
{
context.DrawRectangle(null, new Pen(Palette.Grid, 1), new Rect(center.X - 17, center.Y - 15, 34, 22), 5, 5);
bool rearEnd = lights.HasFlag(Lights.RearEndSignals);
Light(context, center + new Vector(0, -8), lights.HasFlag(Lights.HeadlightUpper), false, false);
Light(context, center + new Vector(-10, 1), lights.HasFlag(Lights.HeadlightLeft) || lights.HasFlag(Lights.AuxiliaryLeft),
lights.HasFlag(Lights.RedMarkerLeft) || rearEnd, lights.HasFlag(Lights.HighBeamLeft));
Light(context, center + new Vector(10, 1), lights.HasFlag(Lights.HeadlightRight) || lights.HasFlag(Lights.AuxiliaryRight),
lights.HasFlag(Lights.RedMarkerRight) || rearEnd, lights.HasFlag(Lights.HighBeamRight));
}
private static void Light(DrawingContext context, Point center, bool white, bool red, bool high)
{
var fill = white ? Palette.LightWhite : red ? Palette.LightRed : Palette.LampOff;
double radius = high ? 4.5 : 3.5;
if (white || red)
context.DrawEllipse(Palette.Faded(fill, 0.25), null, center, radius + 3, radius + 3);
context.DrawEllipse(fill, null, center, radius, radius);
}
/// <summary>A device's lamp and its name: lit in its colour, the name bright; off, both faint.</summary>
private void Lamp(DrawingContext context, string text, IBrush? lit, double x, double y)
{
// Only the lamps that are lit are told: the dark ones are the panel, not the moment.
if (lit is not null)
Say(text);
var center = new Point(x + 4, y + 7);
if (lit is not null)
context.DrawEllipse(Palette.Faded(lit, 0.3), null, center, 6, 6);
context.DrawEllipse(lit ?? Palette.LampOff, null, center, 3.5, 3.5);
context.DrawText(MapView.Text(text, lit is null ? Palette.FaintText : Palette.Text, 10.5), new Point(x + 14, y));
}
/// <summary>
/// Every device but the doors, with the colour of its lamp if it was on, in the groups the panel shows. A
/// diesel has its pumps where an electric vehicle has its pantographs; a recording made before the engine
/// was written has the devices it had then.
/// </summary>
private (string Title, (string Text, IBrush? Lit)[] Lamps)[] Devices(CabSample s, CultureInfo culture)
{
(string, IBrush?) On(string key, CabDevices device, IBrush colour) => (Strings[key], s.Has(device) ? colour : null);
(string, IBrush?) Flag(string key, CabFlags flag, IBrush colour) => (Strings[key], (s.Flags & flag) != 0 ? colour : null);
IBrush? Security(SecurityFlags flag, IBrush colour) => s.Has(flag) ? colour : null;
var extra = s.Extra;
bool diesel = extra is { Engine: EngineKind.Diesel or EngineKind.DieselElectric };
(string, IBrush?) Horn()
{
if (!s.Has(CabDevices.Horn))
return (Strings["DevHorn"], null);
string? tone = extra?.Horn switch
{
1 => Strings["HornLow"],
2 => Strings["HornHigh"],
3 => Strings["HornBoth"],
_ => null
};
return (tone is null ? Strings["DevHorn"] : string.Format(culture, Strings["DevHornTone"], tone), Palette.LampWarning);
}
bool electric = extra is null or { Engine: EngineKind.Electric or EngineKind.ElectricInduction };
var power = new List<(string, IBrush?)> { On("DevBattery", CabDevices.Battery, Palette.LampOn), On("DevMainBreaker", CabDevices.MainBreaker, Palette.LampOn) };
if (electric)
{
power.Add(On("DevPantographFront", CabDevices.PantographFront, Palette.LampOn));
power.Add(On("DevPantographRear", CabDevices.PantographRear, Palette.LampOn));
}
if (diesel)
{
power.Add(On("DevFuelPump", CabDevices.FuelPump, Palette.LampOn));
power.Add(On("DevOilPump", CabDevices.OilPump, Palette.LampOn));
}
power.Add(On("DevConverter", CabDevices.Converter, Palette.LampOn));
power.Add(On("DevCompressor", CabDevices.Compressor, Palette.LampOn));
power.Add(On("DevLineContactors", CabDevices.LineContactors, Palette.LampOn));
if (extra is not null)
power.Add(On("DevMotorBlowers", CabDevices.MotorBlowers, Palette.LampOn));
power.Add(On("DevHeating", CabDevices.Heating, Palette.LampOn));
// the radio with its channel
var radio = extra is { RadioChannel: > 0 } r
? (string.Format(culture, Strings["DevRadioChannel"], r.RadioChannel), s.Has(CabDevices.Radio) ? Palette.LampOn : null)
: On("DevRadio", CabDevices.Radio, Palette.LampOn);
var driving = new List<(string, IBrush?)>
{
On("DevShuntMode", CabDevices.ShuntMode, Palette.LampOn), radio,
On("DevSanding", CabDevices.Sanding, Palette.LampWarning), Horn(),
On("DevSpringBrake", CabDevices.SpringBrake, Palette.LampWarning)
};
if (extra is not null)
{
driving.Add((Strings["DevHandBrake"], extra.Value.HandBrake > 0 ? Palette.LampWarning : null));
driving.Add(On("DevBrakeReleaser", CabDevices.BrakeReleaser, Palette.LampWarning));
driving.Add(On("DevSpeedControl", CabDevices.SpeedControl, Palette.LampOn));
}
var safety = new List<(string, IBrush?)>();
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
{
// A recording which tells them apart.
safety.Add((Strings["DevVigilance"], s.VigilanceBuzzer ? Palette.Buzzer : Security(SecurityFlags.Vigilance, Palette.Vigilance)));
safety.Add((Strings["DevCabSignal"], s.CabSignalBuzzer ? Palette.Buzzer : Security(SecurityFlags.CabSignal, Palette.CabSignal)));
safety.Add((Strings["DevSecurityBraking"], s.ProtectionBraking ? Palette.LampAlarm : null));
}
else
safety.Add((Strings["DevAlerter"], (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.LampWarning : null));
safety.Add(Flag("DevWheelSlip", CabFlags.WheelSlip, Palette.LampAlarm));
safety.Add(On("DevOverloadRelay", CabDevices.OverloadRelay, Palette.LampAlarm));
safety.Add(Flag("DevRadioStop", CabFlags.RadioStop, Palette.LampAlarm));
safety.Add(Flag("DevAlarmChain", CabFlags.AlarmChain, Palette.LampAlarm));
if (diesel)
safety.Add(On("DevEngineHot", CabDevices.EngineHot, Palette.LampAlarm));
return [("CabGroupPower", power.ToArray()), ("CabGroupDriving", driving.ToArray()), ("CabGroupSafety", safety.ToArray())];
}
/// <summary>The doors of the vehicle the user is in, in rows of two: open, the lock, the permits, the steps, the departure signal.</summary>
private (string Text, IBrush? Lit)[] Doors(CabSample s)
{
(string, IBrush?) On(string key, CabDevices device, IBrush colour) => (Strings[key], s.Has(device) ? colour : null);
var doors = new List<(string, IBrush?)>
{
On("DevDoorsLeft", CabDevices.DoorsLeft, Palette.LampWarning), On("DevDoorsRight", CabDevices.DoorsRight, Palette.LampWarning)
};
if (s.Extra is null)
return doors.ToArray();
doors.Add(On("DevDoorLock", CabDevices.DoorLock, Palette.LampOn));
doors.Add(On("DevDoorPermitLeft", CabDevices.DoorPermitLeft, Palette.LampOn));
doors.Add(On("DevDoorPermitRight", CabDevices.DoorPermitRight, Palette.LampOn));
doors.Add(On("DevDoorsLocked", CabDevices.DoorsLocked, Palette.LampOn));
doors.Add(On("DevDoorStep", CabDevices.DoorStep, Palette.LampOn));
doors.Add(On("DevDepartureSignal", CabDevices.DepartureSignal, Palette.LampWarning));
return doors.ToArray();
}
/// <summary>What one gauge shows: its name, the value against the scale, the mark, the value written out.</summary>
private readonly record struct GaugeReading(string Label, float Value, double Scale, double? Mark, string Text, IBrush Brush);
}

View File

@@ -0,0 +1,378 @@
using System.Collections.Generic;
namespace Eu07.BlackBox.Views;
/// <summary>
/// What the simulator's commands of a vehicle do, as the black box names them (input/command.cpp): Polish
/// and English. Those with a key carry the texts of the key file (eu07_input-keyboard.ini) and of the starter's
/// English; the rest, worked by the mouse in the cab or by scripts, are written here.
/// </summary>
public static class CommandTexts
{
private static readonly Dictionary<string, (string Polish, string English)> Texts = new()
{
["aidriverenable"] = ("Aktywacja automechanika", "Engage the AI driver"),
["aidriverdisable"] = ("Dezaktywacja automechanika", "Disengage the AI driver"),
["jointcontrollerset"] = ("Ustawienie nastawnika zespolonego", "Set the combined controller"),
["mastercontrollerincrease"] = ("Zwiększenie nastawnika głównego", "Master controller up"),
["mastercontrollerincreasefast"] = ("Szybkie zwiększenie nastawnika głównego", "Master controller up, fast"),
["mastercontrollerdecrease"] = ("Zmniejszenie nastawnika głównego", "Master controller down"),
["mastercontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawnika głównego", "Master controller down, fast"),
["mastercontrollerset"] = ("Ustawienie nastawnika głównego", "Set the master controller"),
["dynamicbrakecontrollerincrease"] = ("Zwiększenie nastawy hamulca elektrodynamicznego", "Increase the dynamic brake"),
["dynamicbrakecontrollerdecrease"] = ("Zmniejszenie nastawy hamulca elektrodynamicznego", "Decrease the dynamic brake"),
["dynamicbrakecontrollerset"] = ("Ustawienie hamulca elektrodynamicznego", "Set the dynamic brake"),
["dynamicbrakecontrollerincreasefast"] = ("Szybkie zwiększenie nastawy hamulca elektrodynamicznego", "Increase the dynamic brake fast"),
["dynamicbrakecontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawy hamulca elektrodynamicznego", "Decrease the dynamic brake fast"),
["secondcontrollerincrease"] = ("Zwiększenie nastawnika boczników", "Shunt controller up"),
["secondcontrollerincreasefast"] = ("Szybkie zwiększenie nastawnika boczników", "Shunt controller up, fast"),
["secondcontrollerdecrease"] = ("Zmniejszenie nastawnika boczników", "Shunt controller down"),
["secondcontrollerdecreasefast"] = ("Szybkie zmniejszenie nastawnika boczników", "Shunt controller down, fast"),
["secondcontrollerset"] = ("Ustawienie nastawnika boczników", "Set the shunt controller"),
["mucurrentindicatorothersourceactivate"] = ("Zmiana członu dla wskaźnika prądu", "Switch the current gauge to the other unit"),
["independentbrakeincrease"] = ("Zwiększenie nastawy hamulca lokomotywy", "Apply more locomotive brake"),
["independentbrakeincreasefast"] = ("Szybkie zwiększenie nastawy hamulca lokomotywy", "Apply more locomotive brake, fast"),
["independentbrakedecrease"] = ("Zmniejszenie nastawy hamulca lokomotywy", "Release locomotive brake"),
["independentbrakedecreasefast"] = ("Szybkie zmniejszenie nastawy hamulca lokomotywy", "Release locomotive brake, fast"),
["independentbrakeset"] = ("Ustawienie hamulca lokomotywy", "Set the locomotive brake"),
["independentbrakebailoff"] = ("Odluźniacz", "Bail off the locomotive brake"),
["universalbrakebutton1"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 1", "Universal brake button 1"),
["universalbrakebutton2"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 2", "Universal brake button 2"),
["universalbrakebutton3"] = ("Aktywacja zdefiniowanych elementów hamulca zespolonego nr 3", "Universal brake button 3"),
["trainbrakeincrease"] = ("Zwiększenie stopnia hamowania zaworu maszynisty", "Train brake valve: more braking"),
["trainbrakedecrease"] = ("Zmniejszenie stopnia hamowania zaworu maszynisty", "Train brake valve: less braking"),
["trainbrakeset"] = ("Ustawienie hamulca zespolonego", "Set the train brake"),
["trainbrakecharging"] = ("Napełnianie uderzeniowe przewodu głównego", "Train brake valve: overcharge the brake pipe"),
["trainbrakerelease"] = ("Ustawienie zaworu maszynisty w pozycji jazdy", "Train brake valve: running position"),
["trainbrakefirstservice"] = ("Pozycja pierwszego stopnia hamowania", "Train brake valve: first braking step"),
["trainbrakeservice"] = ("Pozycja hamowania służbowego", "Train brake valve: service braking"),
["trainbrakefullservice"] = ("Pozycja hamowania pełnego", "Train brake valve: full service"),
["trainbrakehandleoff"] = ("Pozycja odcięcia", "Train brake valve: lap position"),
["trainbrakeemergency"] = ("Hamowanie nagłe", "Emergency braking"),
["trainbrakebasepressureincrease"] = ("Zwiększenie poziomu ciśnienia w przewodzie głównym", "Raise the brake pipe pressure level"),
["trainbrakebasepressuredecrease"] = ("Zmniejszenie poziomu ciśnienia w przewodzie głównym", "Lower the brake pipe pressure level"),
["trainbrakebasepressurereset"] = ("Domyślny poziom ciśnienia w przewodzie głównym", "Default brake pipe pressure level"),
["trainbrakeoperationtoggle"] = ("Przełączenie stanu hamulca pojazdu", "Toggle the vehicle's brake"),
["manualbrakeincrease"] = ("Zwiększenie nastawy hamulca ręcznego", "Apply more hand brake"),
["manualbrakedecrease"] = ("Zmniejszenie nastawy hamulca ręcznego", "Release hand brake"),
["alarmchaintoggle"] = ("Przełączenie stanu hamulca bezpieczeństwa", "Toggle the emergency brake"),
["alarmchainenable"] = ("Pociągnięcie hamulca bezpieczeństwa", "Pull the alarm chain"),
["alarmchaindisable"] = ("Zwolnienie hamulca bezpieczeństwa", "Release the alarm chain"),
["wheelspinbrakeactivate"] = ("Aktywacja podhamowania przeciwpoślizgowego", "Anti-slip brake"),
["sandboxactivate"] = ("Aktywacja piasecznicy", "Sander"),
["autosandboxtoggle"] = ("Przełączenie automatycznej piasecznicy", "Toggle the automatic sander"),
["autosandboxactivate"] = ("Włączenie automatycznej piasecznicy", "Turn the automatic sander on"),
["autosandboxdeactivate"] = ("Wyłączenie automatycznej piasecznicy", "Turn the automatic sander off"),
["reverserincrease"] = ("Zwiększenie pozycji nastawnika kierunku", "Reverser up"),
["reverserdecrease"] = ("Zmniejszenie pozycji nastawnika kierunku", "Reverser down"),
["reverserforwardhigh"] = ("Pozycja jazdy do przodu II nastawnika kierunku", "Reverser: forward II"),
["reverserforward"] = ("Pozycja jazdy do przodu nastawnika kierunku", "Reverser: forward"),
["reverserneutral"] = ("Pozycja neutralna nastawnika kierunku", "Reverser: neutral"),
["reverserbackward"] = ("Pozycja jazdy do tyłu nastawnika kierunku", "Reverser: backward"),
["waterpumpbreakertoggle"] = ("Przełączenie stanu wyłącznika samoczynnego pompy wody", "Toggle the water pump circuit breaker"),
["waterpumpbreakerclose"] = ("Załączenie wyłącznika pompy wody", "Close the water pump breaker"),
["waterpumpbreakeropen"] = ("Wyłączenie wyłącznika pompy wody", "Open the water pump breaker"),
["waterpumptoggle"] = ("Przełączenie stanu pompy wody", "Toggle the water pump"),
["waterpumpenable"] = ("Włączenie pompy wody", "Turn the water pump on"),
["waterpumpdisable"] = ("Wyłączenie pompy wody", "Turn the water pump off"),
["waterheaterbreakertoggle"] = ("Przełączenie stanu wyłącznika samoczynnego podgrzewacza wody", "Toggle the water heater circuit breaker"),
["waterheaterbreakerclose"] = ("Załączenie wyłącznika podgrzewacza wody", "Close the water heater breaker"),
["waterheaterbreakeropen"] = ("Wyłączenie wyłącznika podgrzewacza wody", "Open the water heater breaker"),
["waterheatertoggle"] = ("Przełączenie stanu podgrzewacza wody", "Toggle the water heater"),
["waterheaterenable"] = ("Włączenie podgrzewacza wody", "Turn the water heater on"),
["waterheaterdisable"] = ("Wyłączenie podgrzewacza wody", "Turn the water heater off"),
["watercircuitslinktoggle"] = ("Przełączenie stanu połączenia obiegów wody", "Toggle the link between the water circuits"),
["watercircuitslinkenable"] = ("Połączenie obiegów wody", "Link the water circuits"),
["watercircuitslinkdisable"] = ("Rozłączenie obiegów wody", "Unlink the water circuits"),
["fuelpumptoggle"] = ("Przełączenie stanu pompy paliwa", "Toggle the fuel pump"),
["fuelpumpenable"] = ("Włączenie pompy paliwa", "Turn the fuel pump on"),
["fuelpumpdisable"] = ("Wyłączenie pompy paliwa", "Turn the fuel pump off"),
["oilpumptoggle"] = ("Przełączenie stanu pompy oleju", "Toggle the oil pump"),
["oilpumpenable"] = ("Włączenie pompy oleju", "Turn the oil pump on"),
["oilpumpdisable"] = ("Wyłączenie pompy oleju", "Turn the oil pump off"),
["linebreakertoggle"] = ("Przełączenie stanu wyłącznika szybkiego", "Toggle the line breaker"),
["linebreakeropen"] = ("Wyłączenie wyłącznika szybkiego", "Open the line breaker"),
["linebreakerclose"] = ("Załączenie wyłącznika szybkiego", "Close the line breaker"),
["convertertoggle"] = ("Przełączenie stanu przetwornicy", "Toggle the converter"),
["converterenable"] = ("Włączenie przetwornicy", "Turn the converter on"),
["converterdisable"] = ("Wyłączenie przetwornicy", "Turn the converter off"),
["convertertogglelocal"] = ("Przełączenie stanu przetwornicy w obsadzonym członie", "Toggle the converter in the occupied unit"),
["converteroverloadrelayreset"] = ("Odblokowanie przekaźnika nadmiarowego przetwornicy", "Reset the converter overload relay"),
["compressortoggle"] = ("Przełączenie stanu sprężarki", "Toggle the compressor"),
["compressorenable"] = ("Włączenie sprężarki", "Turn the compressor on"),
["compressordisable"] = ("Wyłączenie sprężarki", "Turn the compressor off"),
["compressortogglelocal"] = ("Przełączenie stanu sprężarki w obsadzonym członie", "Toggle the compressor in the occupied unit"),
["compressorpresetactivatenext"] = ("Następny tryb pracy sprężarek", "Next compressor mode"),
["compressorpresetactivateprevious"] = ("Poprzedni tryb pracy sprężarek", "Previous compressor mode"),
["compressorpresetactivatedefault"] = ("Domyślny tryb pracy sprężarek", "Default compressor mode"),
["motoroverloadrelaythresholdtoggle"] = ("Przełączenie rozruchu niskiego/wysokiego", "Switch between low and high starting current"),
["motoroverloadrelaythresholdsetlow"] = ("Niski próg przekaźnika nadmiarowego silników", "Motor overload relay threshold low"),
["motoroverloadrelaythresholdsethigh"] = ("Wysoki próg przekaźnika nadmiarowego silników", "Motor overload relay threshold high"),
["motoroverloadrelayreset"] = ("Odblokowanie przekaźnika nadmiarowego silników", "Reset the traction motor overload relay"),
["universalrelayreset1"] = ("Odblokowanie zdefiniowanych przekaźników nr 1", "Reset the defined relays, set 1"),
["universalrelayreset2"] = ("Odblokowanie zdefiniowanych przekaźników nr 2", "Reset the defined relays, set 2"),
["universalrelayreset3"] = ("Odblokowanie zdefiniowanych przekaźników nr 3", "Reset the defined relays, set 3"),
["notchingrelaytoggle"] = ("Przełączenie stanu przekaźnika samoczynnego rozruchu", "Toggle the automatic notching relay"),
["epbrakecontroltoggle"] = ("Przełączenie stanu hamulca elektropneumatycznego", "Toggle the electro-pneumatic brake"),
["epbrakecontrolenable"] = ("Włączenie hamulca elektropneumatycznego", "Turn the electro-pneumatic brake on"),
["epbrakecontroldisable"] = ("Wyłączenie hamulca elektropneumatycznego", "Turn the electro-pneumatic brake off"),
["trainbrakeoperationmodeincrease"] = ("Zmiana trybu pracy hamulca na bardziej efektywny", "Brake operation mode: more effective"),
["trainbrakeoperationmodedecrease"] = ("Zmiana trybu pracy hamulca na prostszy", "Brake operation mode: simpler"),
["brakeactingspeedincrease"] = ("Wybór szybszego trybu działania hamulca pociągu", "Faster train brake acting speed"),
["brakeactingspeeddecrease"] = ("Wybór wolniejszego trybu działania hamulca pociągu", "Slower train brake acting speed"),
["brakeactingspeedsetcargo"] = ("Wybór trybu hamulca dla pociągu towarowego", "Brake acting speed for a freight train"),
["brakeactingspeedsetpassenger"] = ("Wybór trybu hamulca dla pociągu osobowego", "Brake acting speed for a passenger train"),
["brakeactingspeedsetrapid"] = ("Wybór trybu hamulca dla pociągu pospiesznego", "Brake acting speed for an express train"),
["brakeloadcompensationincrease"] = ("Wybór wyższego przełożenia hamulca", "Higher brake load setting"),
["brakeloadcompensationdecrease"] = ("Wybór niższego przełożenia hamulca", "Lower brake load setting"),
["mubrakingindicatortoggle"] = ("Przełączenie stanu wskaźnika hamowania członów EZT", "Toggle the EMU unit braking indicator"),
["alerteracknowledge"] = ("Wygaszenie czuwaka i SHP", "Acknowledge the vigilance device and cab signalling"),
["cabsignalacknowledge"] = ("Wygaszenie SHP", "Acknowledge the cab signalling"),
["hornlowactivate"] = ("Aktywacja syreny niskotonowej", "Low-tone horn"),
["hornhighactivate"] = ("Aktywacja syreny wysokotonowej", "High-tone horn"),
["whistleactivate"] = ("Aktywacja gwizdka", "Whistle"),
["radiotoggle"] = ("Przełączenie stanu radiotelefonu", "Toggle the radio"),
["radioenable"] = ("Włączenie radiotelefonu", "Turn the radio on"),
["radiodisable"] = ("Wyłączenie radiotelefonu", "Turn the radio off"),
["radiochannelincrease"] = ("Wybór kolejnego kanału radia", "Next radio channel"),
["radiochanneldecrease"] = ("Wybór poprzedniego kanału radia", "Previous radio channel"),
["radiochannelset"] = ("Ustawienie kanału radiotelefonu", "Set the radio channel"),
["radiostopsend"] = ("Emisja radiostopu", "Send radio-stop"),
["radiostopenable"] = ("Włączenie sygnału Radio-Stop", "Send Radio-Stop"),
["radiostopdisable"] = ("Wyłączenie sygnału Radio-Stop", "Stop sending Radio-Stop"),
["radiostoptest"] = ("Lokalny test radiostopu", "Local radio-stop test"),
["radiocall1send"] = ("Wywołanie radiowe 1", "Radio call 1"),
["radiocall3send"] = ("Emisja sygnału zew3", "Send the call-3 signal"),
["radiovolumeincrease"] = ("Zwiększenie głośności radia", "Radio volume up"),
["radiovolumedecrease"] = ("Zmniejszenie głośności radia", "Radio volume down"),
["radiovolumeset"] = ("Ustawienie głośności radiotelefonu", "Set the radio volume"),
["radiofusetoggle"] = ("Przełączenie bezpiecznika radiotelefonu", "Toggle the radio fuse"),
["radiofuseenable"] = ("Załączenie bezpiecznika radiotelefonu", "Close the radio fuse"),
["radiofusedisable"] = ("Wyłączenie bezpiecznika radiotelefonu", "Open the radio fuse"),
["cabchangeforward"] = ("Przejście do sąsiedniego pomieszczenia w kierunku czoła pociągu", "Move to the next compartment towards the front"),
["cabchangebackward"] = ("Przejście do sąsiedniego pomieszczenia w kierunku tyłu pociągu", "Move to the next compartment towards the rear"),
["modernlightdimmerdecrease"] = ("Przyciemnienie oświetlenia", "Dim the lights"),
["modernlightdimmerincrease"] = ("Rozjaśnienie oświetlenia", "Brighten the lights"),
["nearestcarcouplingincrease"] = ("Łączenie sprzęgów", "Couple"),
["nearestcarcouplingdisconnect"] = ("Rozłączenie sprzęgów", "Uncouple"),
["nearestcarcoupleradapterattach"] = ("Nałożenie półsprzęgu", "Attach the coupler adapter"),
["nearestcarcoupleradapterremove"] = ("Demontaż półsprzęgu", "Remove the coupler adapter"),
["occupiedcarcouplingdisconnect"] = ("Rozłączenie sprzęgów po stronie obsadzonej kabiny", "Uncouple at the occupied cab's end"),
["occupiedcarcouplingdisconnectback"] = ("Rozłączenie sprzęgu z tyłu zajmowanego pojazdu", "Uncouple at the back of the occupied car"),
["doortoggleleft"] = ("Przełączenie stanu drzwi lewych", "Toggle the left doors"),
["doortoggleright"] = ("Przełączenie stanu drzwi prawych", "Toggle the right doors"),
["doorpermitleft"] = ("Zezwolenie na otwarcie drzwi lewych", "Permit opening the left doors"),
["doorpermitright"] = ("Zezwolenie na otwarcie drzwi prawych", "Permit opening the right doors"),
["doorpermitpresetactivatenext"] = ("Aktywacja kolejnej konfiguracji zezwolenia na otwarcie drzwi", "Next door permit preset"),
["doorpermitpresetactivateprevious"] = ("Aktywacja poprzedniej konfiguracji zezwolenia na otwarcie drzwi", "Previous door permit preset"),
["dooropenleft"] = ("Otwarcie drzwi z lewej", "Open the left doors"),
["dooropenright"] = ("Otwarcie drzwi z prawej", "Open the right doors"),
["dooropenall"] = ("Otwarcie drzwi z zezwoleniem", "Open the permitted doors"),
["doorcloseleft"] = ("Zamknięcie drzwi lewych", "Close the left doors"),
["doorcloseright"] = ("Zamknięcie drzwi prawych", "Close the right doors"),
["doorcloseall"] = ("Zamknięcie wszystkich drzwi", "Close all doors"),
["doorsteptoggle"] = ("Przełączenie stanu stopnia drzwi", "Toggle the door steps"),
["doormodetoggle"] = ("Przełączenie trybu działania drzwi", "Toggle the door operation mode"),
["mirrorstoggle"] = ("Złożenie lub rozłożenie lusterek", "Fold or unfold the mirrors"),
["departureannounce"] = ("Sygnał odjazdu", "Departure signal"),
["doorlocktoggle"] = ("Przełączenie stanu blokady drzwi", "Toggle the door lock"),
["pantographcompressorvalvetoggle"] = ("Przełączenie stanu kurka trójdrogowego", "Toggle the three-way pantograph valve"),
["pantographcompressorvalveenable"] = ("Otwarcie zaworu sprężarki pantografów", "Open the pantograph compressor valve"),
["pantographcompressorvalvedisable"] = ("Zamknięcie zaworu sprężarki pantografów", "Close the pantograph compressor valve"),
["pantographcompressoractivate"] = ("Aktywacja sprężarki pomocniczej", "Auxiliary pantograph compressor"),
["pantographtogglefront"] = ("Przełączenie stanu pantografu przedniego", "Toggle the front pantograph"),
["pantographtogglerear"] = ("Przełączenie stanu pantografu tylnego", "Toggle the rear pantograph"),
["pantographraisefront"] = ("Podniesienie przedniego pantografu", "Raise the front pantograph"),
["pantographraiserear"] = ("Podniesienie tylnego pantografu", "Raise the rear pantograph"),
["pantographlowerfront"] = ("Opuszczenie przedniego pantografu", "Lower the front pantograph"),
["pantographlowerrear"] = ("Opuszczenie tylnego pantografu", "Lower the rear pantograph"),
["pantographlowerall"] = ("Opuszczenie wszystkich pantografów", "Lower all pantographs"),
["pantographselectnext"] = ("Aktywacja kolejnej konfiguracji wyboru pantografów", "Next pantograph selection preset"),
["pantographselectprevious"] = ("Aktywacja poprzedniej konfiguracji wyboru pantografów", "Previous pantograph selection preset"),
["pantographtoggleselected"] = ("Przełączenie stanu wybranych pantografów", "Toggle the selected pantographs"),
["pantographraiseselected"] = ("Podniesienie wybranych pantografów", "Raise the selected pantographs"),
["pantographlowerselected"] = ("Opuszczenie wybranych pantografów", "Lower the selected pantographs"),
["pantographvalvesupdate"] = ("Ustawienie zaworów pantografów", "Set the pantograph valves"),
["pantographvalvesoff"] = ("Zamknięcie zaworów pantografów", "Close the pantograph valves"),
["heatingtoggle"] = ("Przełączenie stanu ogrzewania pociągu", "Toggle train heating"),
["heatingenable"] = ("Włączenie ogrzewania pociągu", "Turn the train heating on"),
["heatingdisable"] = ("Wyłączenie ogrzewania pociągu", "Turn the train heating off"),
["lightspresetactivatenext"] = ("Aktywacja kolejnej konfiguracji reflektorów", "Next headlight preset"),
["lightspresetactivateprevious"] = ("Aktywacja poprzedniej konfiguracji reflektorów", "Previous headlight preset"),
["headlighttoggleleft"] = ("Przełączenie stanu lewego reflektora", "Toggle the left headlight"),
["headlightenableleft"] = ("Włączenie lewego reflektora z przodu", "Turn the front left headlight on"),
["headlightdisableleft"] = ("Wyłączenie lewego reflektora z przodu", "Turn the front left headlight off"),
["headlighttoggleright"] = ("Przełączenie stanu prawego reflektora", "Toggle the right headlight"),
["headlightenableright"] = ("Włączenie prawego reflektora z przodu", "Turn the front right headlight on"),
["headlightdisableright"] = ("Wyłączenie prawego reflektora z przodu", "Turn the front right headlight off"),
["headlighttoggleupper"] = ("Przełączenie stanu górnego reflektora", "Toggle the upper headlight"),
["headlightenableupper"] = ("Włączenie górnego reflektora z przodu", "Turn the front upper headlight on"),
["headlightdisableupper"] = ("Wyłączenie górnego reflektora z przodu", "Turn the front upper headlight off"),
["redmarkertoggleleft"] = ("Przełączenie lewego światła czerwonego", "Toggle the left red marker"),
["redmarkerenableleft"] = ("Włączenie lewego sygnału końcowego z przodu", "Turn the front left red marker on"),
["redmarkerdisableleft"] = ("Wyłączenie lewego sygnału końcowego z przodu", "Turn the front left red marker off"),
["redmarkertoggleright"] = ("Przełączenie prawego światła czerwonego", "Toggle the right red marker"),
["redmarkerenableright"] = ("Włączenie prawego sygnału końcowego z przodu", "Turn the front right red marker on"),
["redmarkerdisableright"] = ("Wyłączenie prawego sygnału końcowego z przodu", "Turn the front right red marker off"),
["headlighttogglerearleft"] = ("Przełączenie stanu lewego tylnego reflektora", "Toggle the rear left headlight"),
["headlightenablerearleft"] = ("Włączenie lewego reflektora z tyłu", "Turn the rear left headlight on"),
["headlightdisablerearleft"] = ("Wyłączenie lewego reflektora z tyłu", "Turn the rear left headlight off"),
["headlighttogglerearright"] = ("Przełączenie stanu prawego tylnego reflektora", "Toggle the rear right headlight"),
["headlightenablerearright"] = ("Włączenie prawego reflektora z tyłu", "Turn the rear right headlight on"),
["headlightdisablerearright"] = ("Wyłączenie prawego reflektora z tyłu", "Turn the rear right headlight off"),
["headlighttogglerearupper"] = ("Przełączenie stanu górnego tylnego reflektora", "Toggle the rear upper headlight"),
["headlightenablerearupper"] = ("Włączenie górnego reflektora z tyłu", "Turn the rear upper headlight on"),
["headlightdisablerearupper"] = ("Wyłączenie górnego reflektora z tyłu", "Turn the rear upper headlight off"),
["redmarkertogglerearleft"] = ("Przełączenie lewego tylnego światła czerwonego", "Toggle the rear left red marker"),
["redmarkerenablerearleft"] = ("Włączenie lewego sygnału końcowego z tyłu", "Turn the rear left red marker on"),
["redmarkerdisablerearleft"] = ("Wyłączenie lewego sygnału końcowego z tyłu", "Turn the rear left red marker off"),
["redmarkertogglerearright"] = ("Przełączenie prawego tylnego światła czerwonego", "Toggle the rear right red marker"),
["redmarkerenablerearright"] = ("Włączenie prawego sygnału końcowego z tyłu", "Turn the rear right red marker on"),
["redmarkerdisablerearright"] = ("Wyłączenie prawego sygnału końcowego z tyłu", "Turn the rear right red marker off"),
["redmarkerstoggle"] = ("Przełączenie świateł końca pociągu", "Toggle the end-of-train lights"),
["endsignalstoggle"] = ("Przełączenie tabliczek końca pociągu", "Toggle the end-of-train plates"),
["headlightsdimtoggle"] = ("Przełączenie przyciemnienia reflektorów", "Toggle headlight dimming"),
["headlightsdimenable"] = ("Przyciemnienie reflektorów", "Dim the headlights"),
["headlightsdimdisable"] = ("Pełne światło reflektorów", "Headlights at full"),
["motorconnectorsopen"] = ("Rozłączenie styczników liniowych", "Open the line contactors"),
["motorconnectorsclose"] = ("Załączenie styczników liniowych", "Close the line contactors"),
["motordisconnect"] = ("Odłączenie uszkodzonych silników", "Cut out the damaged motors"),
["interiorlighttoggle"] = ("Przełączenie stanu oświetlenia kabiny", "Toggle the cab light"),
["interiorlightenable"] = ("Włączenie oświetlenia kabiny", "Turn the cab light on"),
["interiorlightdisable"] = ("Wyłączenie oświetlenia kabiny", "Turn the cab light off"),
["interiorlightdimtoggle"] = ("Przełączenie przyciemnienia oświetlenia kabiny", "Toggle cab light dimming"),
["interiorlightdimenable"] = ("Przyciemnienie oświetlenia kabiny", "Dim the cab light"),
["interiorlightdimdisable"] = ("Pełne oświetlenie kabiny", "Cab light at full"),
["compartmentlightstoggle"] = ("Przełączenie stanu oświetlenia przedziałów", "Toggle the compartment lights"),
["compartmentlightsenable"] = ("Włączenie oświetlenia przedziałów", "Turn the compartment lights on"),
["compartmentlightsdisable"] = ("Wyłączenie oświetlenia przedziałów", "Turn the compartment lights off"),
["instrumentlighttoggle"] = ("Przełączenie stanu oświetlenia przyrządów", "Toggle the instrument lights"),
["instrumentlightenable"] = ("Włączenie oświetlenia przyrządów", "Turn the instrument lights on"),
["instrumentlightdisable"] = ("Wyłączenie oświetlenia przyrządów", "Turn the instrument lights off"),
["dashboardlighttoggle"] = ("Przełączenie stanu oświetlenia pulpitu", "Toggle the dashboard light"),
["dashboardlightenable"] = ("Włączenie oświetlenia pulpitu", "Turn the dashboard light on"),
["dashboardlightdisable"] = ("Wyłączenie oświetlenia pulpitu", "Turn the dashboard light off"),
["timetablelighttoggle"] = ("Przełączenie stanu oświetlenia rozkładu jazdy", "Toggle the timetable light"),
["timetablelightenable"] = ("Włączenie oświetlenia rozkładu jazdy", "Turn the timetable light on"),
["timetablelightdisable"] = ("Wyłączenie oświetlenia rozkładu jazdy", "Turn the timetable light off"),
["generictoggle0"] = ("Przełączenie elementu uniwersalnego nr 0", "Generic switch 0"),
["generictoggle1"] = ("Przełączenie elementu uniwersalnego nr 1", "Generic switch 1"),
["generictoggle2"] = ("Przełączenie elementu uniwersalnego nr 2", "Generic switch 2"),
["generictoggle3"] = ("Przełączenie elementu uniwersalnego nr 3", "Generic switch 3"),
["generictoggle4"] = ("Przełączenie elementu uniwersalnego nr 4", "Generic switch 4"),
["generictoggle5"] = ("Przełączenie elementu uniwersalnego nr 5", "Generic switch 5"),
["generictoggle6"] = ("Przełączenie elementu uniwersalnego nr 6", "Generic switch 6"),
["generictoggle7"] = ("Przełączenie elementu uniwersalnego nr 7", "Generic switch 7"),
["generictoggle8"] = ("Przełączenie elementu uniwersalnego nr 8", "Generic switch 8"),
["generictoggle9"] = ("Przełączenie elementu uniwersalnego nr 9", "Generic switch 9"),
["generictoggle10"] = ("Przełączenie elementu uniwersalnego nr 10", "Generic switch 10"),
["generictoggle11"] = ("Przełączenie elementu uniwersalnego nr 11", "Generic switch 11"),
["generictoggle12"] = ("Przełączenie elementu uniwersalnego nr 12", "Generic switch 12"),
["generictoggle13"] = ("Przełączenie elementu uniwersalnego nr 13", "Generic switch 13"),
["generictoggle14"] = ("Przełączenie elementu uniwersalnego nr 14", "Generic switch 14"),
["generictoggle15"] = ("Przełączenie elementu uniwersalnego nr 15", "Generic switch 15"),
["generictoggle16"] = ("Przełączenie elementu uniwersalnego nr 16", "Generic switch 16"),
["generictoggle17"] = ("Przełączenie elementu uniwersalnego nr 17", "Generic switch 17"),
["generictoggle18"] = ("Przełączenie elementu uniwersalnego nr 18", "Generic switch 18"),
["generictoggle19"] = ("Przełączenie elementu uniwersalnego nr 19", "Generic switch 19"),
["generictoggle20"] = ("Przełączenie elementu uniwersalnego nr 20", "Generic switch 20"),
["generictoggle21"] = ("Przełączenie elementu uniwersalnego nr 21", "Generic switch 21"),
["generictoggle22"] = ("Przełączenie elementu uniwersalnego nr 22", "Generic switch 22"),
["generictoggle23"] = ("Przełączenie elementu uniwersalnego nr 23", "Generic switch 23"),
["generictoggle24"] = ("Przełączenie elementu uniwersalnego nr 24", "Generic switch 24"),
["generictoggle25"] = ("Przełączenie elementu uniwersalnego nr 25", "Generic switch 25"),
["generictoggle26"] = ("Przełączenie elementu uniwersalnego nr 26", "Generic switch 26"),
["generictoggle27"] = ("Przełączenie elementu uniwersalnego nr 27", "Generic switch 27"),
["generictoggle28"] = ("Przełączenie elementu uniwersalnego nr 28", "Generic switch 28"),
["generictoggle29"] = ("Przełączenie elementu uniwersalnego nr 29", "Generic switch 29"),
["batterytoggle"] = ("Przełączenie stanu akumulatorów", "Toggle the batteries"),
["batteryenable"] = ("Włączenie baterii", "Turn the battery on"),
["batterydisable"] = ("Wyłączenie baterii", "Turn the battery off"),
["cabactivationtoggle"] = ("Przełączenie stanu aktywacji kabiny", "Toggle cab activation"),
["cabactivationenable"] = ("Aktywacja kabiny", "Activate the cab"),
["cabactivationdisable"] = ("Dezaktywacja kabiny", "Deactivate the cab"),
["motorblowerstogglefront"] = ("Przełączenie stanu wentylatorów przednich silników trakcyjnych", "Toggle the front traction motor blowers"),
["motorblowerstogglerear"] = ("Przełączenie stanu wentylatorów tylnych silników trakcyjnych", "Toggle the rear traction motor blowers"),
["motorblowersdisableall"] = ("Wyłączenie wszystkich wentylatorów silników trakcyjnych", "Switch off all traction motor blowers"),
["coolingfanstoggle"] = ("Przełączenie stanu wentylatorów oporów rozruchowych", "Toggle the starting resistor fans"),
["tempomattoggle"] = ("Przełączenie stanu tempomatu", "Toggle the cruise control"),
["springbraketoggle"] = ("Przełączenie stanu hamulca sprężynowego", "Toggle the spring brake"),
["springbrakeenable"] = ("Załączenie hamulca sprężynowego", "Apply the spring brake"),
["springbrakedisable"] = ("Zwolnienie hamulca sprężynowego", "Release the spring brake"),
["springbrakeshutofftoggle"] = ("Przełączenie stanu kurka odcinającego hamulca sprężynowego", "Toggle the spring brake shut-off cock"),
["springbrakeshutoffenable"] = ("Odcięcie hamulca sprężynowego", "Cut the spring brake off"),
["springbrakeshutoffdisable"] = ("Przywrócenie hamulca sprężynowego", "Cut the spring brake back in"),
["springbrakerelease"] = ("Luzowanie hamulca sprężynowego", "Release the spring brake"),
["distancecounteractivate"] = ("Załączenie miernika przejechanego dystansu", "Start the distance counter"),
["speedcontrolincrease"] = ("Zwiększenie prędkości utrzymywanej przez tempomat", "Cruise control speed up"),
["speedcontroldecrease"] = ("Zmniejszenie prędkości utrzymywanej przez tempomat", "Cruise control speed down"),
["speedcontrolpowerincrease"] = ("Zwiększenie maksymalnego poziomu mocy dostępnej dla tempomatu", "More power for the cruise control"),
["speedcontrolpowerdecrease"] = ("Zmniejszenie maksymalnego poziomu mocy dostępnej dla tempomatu", "Less power for the cruise control"),
["speedcontrolbutton0"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 0", "Cruise control preset speed 0"),
["speedcontrolbutton1"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 1", "Cruise control preset speed 1"),
["speedcontrolbutton2"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 2", "Cruise control preset speed 2"),
["speedcontrolbutton3"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 3", "Cruise control preset speed 3"),
["speedcontrolbutton4"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 4", "Cruise control preset speed 4"),
["speedcontrolbutton5"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 5", "Cruise control preset speed 5"),
["speedcontrolbutton6"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 6", "Cruise control preset speed 6"),
["speedcontrolbutton7"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 7", "Cruise control preset speed 7"),
["speedcontrolbutton8"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 8", "Cruise control preset speed 8"),
["speedcontrolbutton9"] = ("Ustalenie dla tempomatu zdefiniowanej prędkości nr 9", "Cruise control preset speed 9"),
["inverterenable1"] = ("Włączenie falownika 1", "Turn inverter 1 on"),
["inverterenable2"] = ("Włączenie falownika 2", "Turn inverter 2 on"),
["inverterenable3"] = ("Włączenie falownika 3", "Turn inverter 3 on"),
["inverterenable4"] = ("Włączenie falownika 4", "Turn inverter 4 on"),
["inverterenable5"] = ("Włączenie falownika 5", "Turn inverter 5 on"),
["inverterenable6"] = ("Włączenie falownika 6", "Turn inverter 6 on"),
["inverterenable7"] = ("Włączenie falownika 7", "Turn inverter 7 on"),
["inverterenable8"] = ("Włączenie falownika 8", "Turn inverter 8 on"),
["inverterenable9"] = ("Włączenie falownika 9", "Turn inverter 9 on"),
["inverterenable10"] = ("Włączenie falownika 10", "Turn inverter 10 on"),
["inverterenable11"] = ("Włączenie falownika 11", "Turn inverter 11 on"),
["inverterenable12"] = ("Włączenie falownika 12", "Turn inverter 12 on"),
["inverterdisable1"] = ("Wyłączenie falownika 1", "Turn inverter 1 off"),
["inverterdisable2"] = ("Wyłączenie falownika 2", "Turn inverter 2 off"),
["inverterdisable3"] = ("Wyłączenie falownika 3", "Turn inverter 3 off"),
["inverterdisable4"] = ("Wyłączenie falownika 4", "Turn inverter 4 off"),
["inverterdisable5"] = ("Wyłączenie falownika 5", "Turn inverter 5 off"),
["inverterdisable6"] = ("Wyłączenie falownika 6", "Turn inverter 6 off"),
["inverterdisable7"] = ("Wyłączenie falownika 7", "Turn inverter 7 off"),
["inverterdisable8"] = ("Wyłączenie falownika 8", "Turn inverter 8 off"),
["inverterdisable9"] = ("Wyłączenie falownika 9", "Turn inverter 9 off"),
["inverterdisable10"] = ("Wyłączenie falownika 10", "Turn inverter 10 off"),
["inverterdisable11"] = ("Wyłączenie falownika 11", "Turn inverter 11 off"),
["inverterdisable12"] = ("Wyłączenie falownika 12", "Turn inverter 12 off"),
["invertertoggle1"] = ("Przełączenie falownika 1", "Toggle inverter 1"),
["invertertoggle2"] = ("Przełączenie falownika 2", "Toggle inverter 2"),
["invertertoggle3"] = ("Przełączenie falownika 3", "Toggle inverter 3"),
["invertertoggle4"] = ("Przełączenie falownika 4", "Toggle inverter 4"),
["invertertoggle5"] = ("Przełączenie falownika 5", "Toggle inverter 5"),
["invertertoggle6"] = ("Przełączenie falownika 6", "Toggle inverter 6"),
["invertertoggle7"] = ("Przełączenie falownika 7", "Toggle inverter 7"),
["invertertoggle8"] = ("Przełączenie falownika 8", "Toggle inverter 8"),
["invertertoggle9"] = ("Przełączenie falownika 9", "Toggle inverter 9"),
["invertertoggle10"] = ("Przełączenie falownika 10", "Toggle inverter 10"),
["invertertoggle11"] = ("Przełączenie falownika 11", "Toggle inverter 11"),
["invertertoggle12"] = ("Przełączenie falownika 12", "Toggle inverter 12"),
["vehiclemoveforwards"] = ("Przesunięcie pojazdu do przodu", "Move the vehicle forwards"),
["vehiclemovebackwards"] = ("Przesunięcie pojazdu do tyłu", "Move the vehicle backwards"),
["vehicleboost"] = ("Przyspieszenie pojazdu", "Boost the vehicle"),
["wiperswitchincrease"] = ("Szybsza praca wycieraczek", "Wipers faster"),
["wiperswitchdecrease"] = ("Wolniejsza praca wycieraczek", "Wipers slower"),
["lightsset"] = ("Ustawienie świateł", "Set the lights"),
["oilfuelpumptoggle"] = ("Przełączenie pomp oleju i paliwa", "Toggle the oil and fuel pumps"),
["linebreakertoggleb"] = ("Przełączenie wyłącznika szybkiego B", "Toggle line breaker B"),
["linebreakeropenb"] = ("Wyłączenie wyłącznika szybkiego B", "Open line breaker B"),
["linebreakercloseb"] = ("Załączenie wyłącznika szybkiego B", "Close line breaker B"),
["linebreakertogglec"] = ("Przełączenie wyłącznika szybkiego C", "Toggle line breaker C"),
["linebreakeropenc"] = ("Wyłączenie wyłącznika szybkiego C", "Open line breaker C"),
["linebreakerclosec"] = ("Załączenie wyłącznika szybkiego C", "Close line breaker C"),
};
/// <summary>The text of <paramref name="command"/>, Polish for "pl", else English; its name when unknown.</summary>
public static string Of(string command, string languageCode) =>
Texts.TryGetValue(command, out var text) ? languageCode == "pl" ? text.Polish : text.English : command;
/// <summary>The commands there are texts for.</summary>
public static IEnumerable<string> Commands => Texts.Keys;
}

View File

@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- The window that replays a black box: the map, the timeline, the events. Code
only, no XAML loaded at run time, so it goes through NativeAOT and trimming
in the starter and in the viewer alike. -->
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<IsAotCompatible>true</IsAotCompatible>
<IsTrimmable>true</IsTrimmable>
<RootNamespace>Eu07.BlackBox.Views</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="12.1.4" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="StarterNG.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Eu07.BlackBox\Eu07.BlackBox.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,416 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
/// <summary>One line of the list of events.</summary>
public sealed record BlackBoxEvent(double Time, string Text, IBrush Brush, bool Important);
/// <summary>
/// What happened to the user's train, by the clock: the commands, the autopilot, the
/// signals passed, the stations, the horn points, the couplings, the train protection,
/// the cab and the camera of the user. A click goes to its moment.
/// </summary>
public sealed class EventList : ListBox
{
private Recording? _recording;
private int _shownRevision = -1;
private List<BlackBoxEvent> _events = new();
private bool _picking;
public event Action<double>? Seek;
// The look of a list box: a control of a type of its own has no theme otherwise, and shows nothing.
protected override Type StyleKeyOverride => typeof(ListBox);
public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings();
public EventList()
{
SelectionMode = SelectionMode.Single;
Padding = new Thickness(4, 0, 4, 6);
// The picked line in the starter's green.
Resources["ListBoxItemBackgroundSelected"] = Palette.AccentFill;
Resources["ListBoxItemBackgroundSelectedPointerOver"] = Palette.AccentFillHover;
Resources["ListBoxItemBackgroundSelectedPressed"] = Palette.AccentFill;
Resources["ListBoxItemBackgroundPointerOver"] = Palette.CardHover;
SelectionChanged += (_, _) =>
{
if (!_picking && SelectedIndex >= 0 && SelectedIndex < _events.Count)
Seek?.Invoke(_events[SelectedIndex].Time);
};
}
public Recording? Recording
{
get => _recording;
set
{
_recording = value;
_shownRevision = -1;
Refresh();
}
}
public IReadOnlyList<BlackBoxEvent> Events => _events;
/// <summary>Takes in what the recording gained; the list grows at its end, so what is scrolled to stays.</summary>
public void Refresh()
{
if (_recording is not { } recording)
{
_events.Clear();
Items.Clear();
return;
}
if (recording.Revision == _shownRevision)
return;
_shownRevision = recording.Revision;
var events = Collect(recording, Strings);
bool grown = events.Count >= _events.Count &&
_events.Select((e, i) => e == events[i]).All(same => same);
if (!grown)
Items.Clear();
for (int i = grown ? _events.Count : 0; i < events.Count; i++)
Items.Add(new ListBoxItem
{
Content = Line(recording, events[i]),
Padding = new Thickness(8, 4),
MinHeight = 0,
CornerRadius = new CornerRadius(6),
Margin = new Thickness(0, 1)
});
_events = events;
}
/// <summary>The event at or just before t picked, without going to it.</summary>
public void ShowTime(double t)
{
int index = -1;
for (int i = 0; i < _events.Count && _events[i].Time <= t + 0.05; i++)
index = i;
if (index == SelectedIndex)
return;
_picking = true;
try
{
SelectedIndex = index;
if (index >= 0)
ScrollIntoView(index);
}
finally
{
_picking = false;
}
}
private static Control Line(Recording recording, BlackBoxEvent e)
{
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("58,14,*") };
var time = new TextBlock
{
Text = recording.ClockAt(e.Time).ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture),
Foreground = Palette.FaintText,
FontSize = 11.5,
VerticalAlignment = VerticalAlignment.Top,
Margin = new Thickness(0, 1, 0, 0)
};
var dot = new Border
{
Width = e.Important ? 8 : 6,
Height = e.Important ? 8 : 6,
CornerRadius = new CornerRadius(4),
Background = e.Brush,
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(0, e.Important ? 5 : 6, 0, 0)
};
var text = new TextBlock
{
Text = e.Text,
Foreground = e.Important ? Palette.Text : Palette.DimText,
FontSize = 12.5,
FontWeight = e.Important ? FontWeight.SemiBold : FontWeight.Normal,
TextWrapping = TextWrapping.Wrap,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetColumn(dot, 1);
Grid.SetColumn(text, 2);
grid.Children.Add(time);
grid.Children.Add(dot);
grid.Children.Add(text);
return grid;
}
/// <summary>The events of the user's train, in the order they happened.</summary>
public static List<BlackBoxEvent> Collect(Recording recording, IBlackBoxStrings strings)
{
var culture = CultureInfo.CurrentCulture;
var events = new List<BlackBoxEvent>();
foreach (var c in recording.UserCommands())
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCommand"],
strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]),
Palette.Command, false));
foreach (var d in recording.DriverChanges)
{
if (recording.CabAt(d.Time + 0.5) is not { } s || s.Vehicle != d.Vehicle)
continue;
events.Add(new BlackBoxEvent(d.Time, strings[d.Driving == Driver.Ai ? "EventAutopilotOn" : "EventAutopilotOff"],
Palette.Autopilot, true));
}
foreach (var p in recording.UserPassings())
{
string name = recording.Signal(p.Signal)?.Name ?? p.Event;
events.Add(p.AtDanger
? new BlackBoxEvent(p.Time, string.Format(culture, strings["EventDanger"], name, Math.Abs(p.SpeedKmh), p.Overrun), Palette.Over, true)
: new BlackBoxEvent(p.Time, string.Format(culture, strings["EventPassed"], name, MapView.AspectText(strings, p.Speed1, p.Speed2),
Math.Abs(p.SpeedKmh)), Palette.Of(new AspectChange(p.Time, p.Signal, p.Speed1, p.Speed2, "")), false));
}
AddUserVehicles(recording, strings, events, culture);
AddStations(recording, strings, events, culture);
foreach (var horn in recording.UserHornChecks())
events.Add(new BlackBoxEvent(horn.Request.Time, strings[horn.Sounded ? "EventHornSounded" : "EventHornMissed"],
horn.Sounded ? Palette.HornPoint : Palette.Bad, !horn.Sounded));
AddSecurity(recording, strings, events, culture);
AddCameras(recording, strings, events, culture);
AddCouplings(recording, strings, events, culture);
AddCabChanges(recording, strings, events, culture);
foreach (var t in recording.Timetables)
events.Add(new BlackBoxEvent(t.Time, string.Format(culture, strings["EventTimetable"], $"{t.Category} {t.Train}".Trim(),
string.Format(culture, strings["Relation"], t.From, t.To)), Palette.Station, false));
if (recording.EndTime is { } end)
events.Add(new BlackBoxEvent(end, strings["EventEnd"], Palette.FaintText, false));
// Stable: what happened at the same moment stays in the order of its kind.
return events.OrderBy(e => e.Time).ToList();
}
/// <summary>
/// The train protection: its buzzer, acknowledged or not, and the braking apart. A lamp acknowledged before the
/// buzzer is the driving as usual, not told.
/// </summary>
private static void AddSecurity(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
{
var brakings = recording.SecurityBrakings();
foreach (var span in recording.SecurityAlarms())
{
// The lamps of all its buzzing samples: one buzzer for both, the other may join it before it's acknowledged.
var lamps = recording.Cab.Where(c => c.Time >= span.Start && c.Time <= span.End && (c.VigilanceBuzzer || c.CabSignalBuzzer))
.Aggregate(SecurityFlags.None, (all, c) => all | c.Security);
string who = ProtectionName(lamps);
var before = recording.CabAt(span.Start);
string text = brakings.Any(b => b.Start >= span.Start && b.Start <= span.End)
? string.Format(culture, strings["EventSecurityAlarmMissed"], who)
// Acknowledged when the sample it ended at buzzes no more and doesn't brake, in the same vehicle: not
// the end of the recording or a gap in it, nor the power cut or the protection switched off.
: recording.CabAt(span.End) is { } after && !after.VigilanceBuzzer && !after.CabSignalBuzzer
&& !after.Has(SecurityFlags.Braking) && after.Vehicle == before?.Vehicle
? string.Format(culture, strings["EventSecurityAlarmAcknowledged"], who, span.End - span.Start)
: string.Format(culture, strings["EventSecurityAlarm"], who);
events.Add(new BlackBoxEvent(span.Start, text, Palette.Buzzer, false));
}
foreach (var span in brakings)
events.Add(new BlackBoxEvent(span.Start, string.Format(culture, strings["EventSecurityBraking"],
ProtectionName(recording.CabAt(span.Start)?.Security ?? SecurityFlags.None)),
Palette.Bad, true));
}
/// <summary>Which of them it was: the lamps blinking.</summary>
private static string ProtectionName(SecurityFlags lamps) =>
(lamps & (SecurityFlags.CabSignal | SecurityFlags.Vigilance)) switch
{
SecurityFlags.CabSignal | SecurityFlags.Vigilance => "CA/SHP",
SecurityFlags.CabSignal => "SHP",
_ => "CA"
};
private static void AddUserVehicles(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
{
UserVehicleChange? before = null;
foreach (var u in recording.UserVehicles)
{
string vehicle = recording.Vehicle(u.Vehicle)?.Name ?? "";
// Only the cab changed: told as such.
if (before is { } b && b.Vehicle == u.Vehicle && b.InCab == u.InCab && b.CabEnd != u.CabEnd && u.CabEnd != 0)
events.Add(new BlackBoxEvent(u.Time, string.Format(culture, strings["EventCab"], strings[u.CabEnd > 0 ? "CabEndFront" : "CabEndRear"], vehicle),
Palette.UserTrain, true));
else
{
string text = u.Vehicle == 0
? strings["EventNoVehicle"]
: string.Format(culture, strings[u.InCab ? "EventInVehicle" : "EventOutside"], vehicle);
events.Add(new BlackBoxEvent(u.Time, text, u.InCab ? Palette.UserTrain : Palette.DimText, true));
}
before = u;
}
}
private static void AddStations(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
{
foreach (var st in recording.UserStations())
{
switch (st.Kind)
{
case StationKind.Stopped:
{
float error = st.StopError;
string where = Math.Abs(error) < 1
? strings["TtStopExact"]
: string.Format(culture, strings[error > 0 ? "TtStopShort" : "TtStopPast"], Math.Abs(error));
events.Add(new BlackBoxEvent(st.Time, string.Format(culture, strings["EventStopped"], StationNames.Display(st.Station), where), Palette.Station, true));
break;
}
case StationKind.Passed:
events.Add(new BlackBoxEvent(st.Time, string.Format(culture, strings["EventStationPassed"], StationNames.Display(st.Station)), Palette.Station, false));
break;
case StationKind.Missed:
events.Add(new BlackBoxEvent(st.Time, string.Format(culture, strings["EventStationMissed"], StationNames.Display(st.Station)), Palette.Bad, true));
break;
case StationKind.Ready:
events.Add(new BlackBoxEvent(st.Time, string.Format(culture, strings["EventReady"], StationNames.Display(st.Station)), Palette.Station, false));
break;
}
}
}
/// <summary>The camera of the user going to another mode: the cab, outside, free.</summary>
private static void AddCameras(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
{
CameraMode? mode = null;
foreach (var c in recording.Cameras)
{
if (c.Mode == mode)
continue;
if (mode is not null)
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCamera"], strings[CameraKey(c.Mode)]), Palette.DimText, false));
mode = c.Mode;
}
}
public static string CameraKey(CameraMode mode) => mode switch
{
CameraMode.Cab => "CameraCab",
CameraMode.External => "CameraExternal",
CameraMode.Debug => "CameraDebug",
_ => "CameraFree"
};
/// <summary>
/// The switches the driver worked, as the cab tells them: what came on and went off. Not the compressor and the
/// motor fans, which go on and off by themselves.
/// </summary>
private static readonly (CabDevices Device, string Key)[] Switched =
[
(CabDevices.MainBreaker, "DevMainBreaker"), (CabDevices.PantographFront, "DevPantographFront"),
(CabDevices.PantographRear, "DevPantographRear"), (CabDevices.FuelPump, "DevFuelPump"), (CabDevices.OilPump, "DevOilPump"),
(CabDevices.Converter, "DevConverter"),
(CabDevices.Heating, "DevHeating"), (CabDevices.Radio, "DevRadio"), (CabDevices.ShuntMode, "DevShuntMode"),
(CabDevices.SpringBrake, "DevSpringBrake"), (CabDevices.BrakeReleaser, "DevBrakeReleaser"),
(CabDevices.DoorPermitLeft, "DevDoorPermitLeft"), (CabDevices.DoorPermitRight, "DevDoorPermitRight"),
(CabDevices.DoorStep, "DevDoorStep"), (CabDevices.DoorLock, "DevDoorLock"), (CabDevices.SpeedControl, "DevSpeedControl")
];
/// <summary>
/// What the driver did in the cab, from one look to the next in the same vehicle: the switches on and off, the
/// doors opened and closed, the departure signal, the hand brake, the brakes' setting, the radio's channel, the
/// speed the cruise control is set to; and, as faults, moving with the doors open and the engine overheating.
/// </summary>
private static void AddCabChanges(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
{
CabSample? last = null;
bool movingOpen = false;
foreach (var s in recording.Cab)
{
if (last is not { } b || b.Vehicle != s.Vehicle)
{
last = s;
movingOpen = false;
continue;
}
bool Came(CabDevices device) => !b.Has(device) && s.Has(device);
bool Went(CabDevices device) => b.Has(device) && !s.Has(device);
foreach (var (device, key) in Switched)
{
if (Came(device))
events.Add(new BlackBoxEvent(s.Time, string.Format(culture, strings["EventDeviceOn"], strings[key]), Palette.LampOn, false));
else if (Went(device))
events.Add(new BlackBoxEvent(s.Time, string.Format(culture, strings["EventDeviceOff"], strings[key]), Palette.FaintText, false));
}
foreach (var (device, open, closed) in new[] { (CabDevices.DoorsLeft, "DevDoorsLeft", "EventDoorsLeftClosed"), (CabDevices.DoorsRight, "DevDoorsRight", "EventDoorsRightClosed") })
{
if (Came(device))
events.Add(new BlackBoxEvent(s.Time, strings[open], Palette.LampWarning, false));
else if (Went(device))
events.Add(new BlackBoxEvent(s.Time, strings[closed], Palette.FaintText, false));
}
if (Came(CabDevices.DepartureSignal))
events.Add(new BlackBoxEvent(s.Time, strings["DevDepartureSignal"], Palette.LampWarning, false));
if (Came(CabDevices.EngineHot))
events.Add(new BlackBoxEvent(s.Time, strings["DevEngineHot"], Palette.Bad, true));
// moving with the doors open: once, until they are closed or the train stands
bool doorsOpen = s.Has(CabDevices.DoorsLeft) || s.Has(CabDevices.DoorsRight);
if (doorsOpen && s.AbsSpeedKmh > 2 && !movingOpen)
{
events.Add(new BlackBoxEvent(s.Time, string.Format(culture, strings["EventMovingDoorsOpen"], s.AbsSpeedKmh), Palette.Bad, true));
movingOpen = true;
}
else if (!doorsOpen || s.AbsSpeedKmh < 0.5)
movingOpen = false;
if (b.Extra is { } x && s.Extra is { } y)
{
if (x.HandBrake <= 0 && y.HandBrake > 0)
events.Add(new BlackBoxEvent(s.Time, strings["EventHandBrakeOn"], Palette.LampWarning, false));
else if (x.HandBrake > 0 && y.HandBrake <= 0)
events.Add(new BlackBoxEvent(s.Time, strings["EventHandBrakeOff"], Palette.FaintText, false));
if (x.BrakeDelay != y.BrakeDelay || x.BrakeMode != y.BrakeMode)
{
string setting = string.Join(" · ", new[] { CabPanel.BrakeSetting(y.BrakeDelay), CabPanel.BrakeMode(y.BrakeMode) }.Where(t => t.Length > 0));
events.Add(new BlackBoxEvent(s.Time, string.Format(culture, strings["EventBrakeSetting"], setting), Palette.Brakes, false));
}
if (x.RadioChannel != y.RadioChannel && y.RadioChannel > 0)
events.Add(new BlackBoxEvent(s.Time, string.Format(culture, strings["EventRadioChannel"], y.RadioChannel), Palette.LampOn, false));
// the speed set, while the cruise control holds one
if (s.Has(CabDevices.SpeedControl) && (Came(CabDevices.SpeedControl) || Math.Abs(x.SpeedControlKmh - y.SpeedControlKmh) >= 1))
events.Add(new BlackBoxEvent(s.Time, string.Format(culture, strings["EventSpeedControlSet"], y.SpeedControlKmh), Palette.Target, false));
}
last = s;
}
}
private static void AddCouplings(Recording recording, IBlackBoxStrings strings, List<BlackBoxEvent> events, CultureInfo culture)
{
string Name(int id) => recording.Vehicle(id)?.Name ?? id.ToString(culture);
foreach (var c in recording.UserCouplings())
{
if (c.Coupled)
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCoupled"], Name(c.Vehicle), Name(c.Other)), Palette.Good, true));
else if (c.Uncoupled)
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventUncoupled"], Name(c.Vehicle), Name(c.PreviousOther)), Palette.Warn, true));
else
events.Add(new BlackBoxEvent(c.Time, string.Format(culture, strings["EventCouplingChanged"], Name(c.Vehicle), Name(c.Other),
CouplingText(strings, c.Flags)), Palette.DimText, false));
}
}
/// <summary>What a coupling joins, in words.</summary>
public static string CouplingText(IBlackBoxStrings strings, CouplingFlags flags)
{
var parts = new List<string>();
foreach (var (flag, key) in new[]
{
(CouplingFlags.Coupler, "CouplingCoupler"), (CouplingFlags.BrakePipe, "CouplingBrakePipe"),
(CouplingFlags.MainPipe, "CouplingMainPipe"), (CouplingFlags.Control, "CouplingControl"),
(CouplingFlags.Power, "CouplingPower"), (CouplingFlags.Heating, "CouplingHeating"),
(CouplingFlags.Gangway, "CouplingGangway")
})
if ((flags & flag) != 0)
parts.Add(strings[key]);
return parts.Count == 0 ? strings["CouplingNothing"] : string.Join(", ", parts);
}
}

View File

@@ -0,0 +1,766 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The map of the scenery at a moment of the recording: the rail tracks with the switches
/// as they lay, the signals in the colour of what they showed, every vehicle where it was,
/// and the way the user's train went, coloured by how its speed stood against the AI's.
/// North is up, as on the map in the simulator. Dragged to move, the wheel zooms, a
/// double click shows it all.
/// </summary>
public sealed class MapView : Control
{
private const double MinScale = 0.002;
private const double MaxScale = 40;
private const double FollowScale = 1.2;
private Recording? _recording;
private int _builtRevision = -1;
private int _builtTracks = -1;
private StreamGeometry? _tracks;
private readonly List<(int Index, int Branch, StreamGeometry Way)> _switchWays = new();
private readonly StreamGeometry?[] _trail = new StreamGeometry?[5];
private Rect _world;
private double _centerX, _centerZ;
private double _scale = 0.2; // pixels per metre
private bool _fitted;
private Point? _dragFrom;
private (double X, double Z) _dragCenter;
private Point? _pointer;
private double _time;
private bool _follow;
/// <summary>The user moved the map away from the train: following is off.</summary>
public event Action? FollowStopped;
public MapView()
{
ClipToBounds = true;
Focusable = true;
}
public Recording? Recording
{
get => _recording;
set
{
_recording = value;
_builtRevision = -1;
_builtTracks = -1;
_fitted = false;
InvalidateVisual();
}
}
public double Time
{
get => _time;
set
{
_time = value;
InvalidateVisual();
}
}
/// <summary>Keeps the user's train in the middle.</summary>
public bool Follow
{
get => _follow;
set
{
// Close enough to see the train go, unless already closer.
if (value && !_follow)
_scale = Math.Max(_scale, FollowScale);
_follow = value;
InvalidateVisual();
}
}
public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings();
/// <summary>Closer by the factor given, about the middle.</summary>
public void ZoomBy(double factor)
{
_scale = Math.Clamp(_scale * factor, MinScale, MaxScale);
InvalidateVisual();
}
/// <summary>The map as a whole in view.</summary>
public void Fit()
{
FitWorld();
InvalidateVisual();
}
// Also from the render, which must not ask for another one.
private void FitWorld()
{
if (_world.Width <= 0 && _world.Height <= 0)
return;
var size = Bounds.Size;
if (size.Width <= 0 || size.Height <= 0)
return;
_centerX = -_world.Center.X;
_centerZ = -_world.Center.Y;
_scale = Math.Clamp(Math.Min(size.Width / Math.Max(_world.Width, 50), size.Height / Math.Max(_world.Height, 50)) * 0.92,
MinScale, MaxScale);
if (_follow)
_scale = Math.Max(_scale, FollowScale);
_fitted = true;
}
// The map's plane as the simulator's map draws it, seen from above: x to the left (the game's x runs the
// other way than a map's east), z up the screen.
private static Point Plane(double x, double z) => new(-x, -z);
private Point ToScreen(double x, double z) =>
new((_centerX - x) * _scale + Bounds.Width / 2, (_centerZ - z) * _scale + Bounds.Height / 2);
private (double X, double Z) ToWorld(Point screen) =>
(_centerX - (screen.X - Bounds.Width / 2) / _scale, _centerZ - (screen.Y - Bounds.Height / 2) / _scale);
private void Build(Recording recording)
{
if (recording.Tracks.Count != _builtTracks)
{
_builtTracks = recording.Tracks.Count;
_switchWays.Clear();
var tracks = new StreamGeometry();
double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue;
using (var g = tracks.Open())
{
foreach (var track in recording.Tracks)
{
if (track.Points.Count < 2)
continue;
foreach (var p in track.Points)
{
left = Math.Min(left, -p.X);
right = Math.Max(right, -p.X);
top = Math.Min(top, -p.Z);
bottom = Math.Max(bottom, -p.Z);
}
if (track.Kind == TrackKind.SwitchBranch)
{
var way = new StreamGeometry();
using (var w = way.Open())
Polyline(w, track.Points);
_switchWays.Add((track.Index, track.Branch, way));
}
else
Polyline(g, track.Points);
}
}
_tracks = tracks;
_world = left <= right ? new Rect(new Point(left, top), new Point(right, bottom)) : default;
}
BuildTrail(recording);
_builtRevision = recording.Revision;
}
private static void Polyline(StreamGeometryContext g, IReadOnlyList<System.Numerics.Vector3> points)
{
g.BeginFigure(Plane(points[0].X, points[0].Z), false);
for (int i = 1; i < points.Count; i++)
g.LineTo(Plane(points[i].X, points[i].Z));
g.EndFigure(false);
}
/// <summary>The way the user's train went, a geometry for each judgement of its speed.</summary>
private void BuildTrail(Recording recording)
{
var lines = new List<List<Point>>[_trail.Length];
for (int i = 0; i < lines.Length; i++)
lines[i] = new List<List<Point>>();
var cab = recording.Cab;
int open = -1;
for (int i = 1; i < cab.Count; i++)
{
var before = cab[i - 1];
var sample = cab[i];
if (sample.Vehicle != before.Vehicle || sample.Time - before.Time > 1.0)
{
open = -1;
continue;
}
if (before.Position.DistanceTo(sample.Position) < 0.5 && open >= 0)
continue;
int kind = (int)DrivingSummary.Judge(sample);
if (kind != open)
{
lines[kind].Add(new List<Point> { Plane(before.Position.X, before.Position.Z) });
open = kind;
}
lines[kind][^1].Add(Plane(sample.Position.X, sample.Position.Z));
}
for (int kind = 0; kind < _trail.Length; kind++)
{
if (lines[kind].Count == 0)
{
_trail[kind] = null;
continue;
}
var geometry = new StreamGeometry();
using (var g = geometry.Open())
{
foreach (var line in lines[kind].Where(l => l.Count > 1))
{
g.BeginFigure(line[0], false);
foreach (var p in line.Skip(1))
g.LineTo(p);
g.EndFigure(false);
}
}
_trail[kind] = geometry;
}
}
public override void Render(DrawingContext context)
{
var size = Bounds.Size;
context.FillRectangle(Palette.MapBackground, new Rect(size));
var recording = _recording;
if (recording is null)
return;
if (recording.Revision != _builtRevision)
Build(recording);
if (!_fitted)
FitWorld();
if (_follow && recording.CabPositionAt(_time) is { } followed)
{
_centerX = followed.X;
_centerZ = followed.Z;
}
var toScreen = Matrix.CreateTranslation(_centerX, _centerZ) * Matrix.CreateScale(_scale, _scale) *
Matrix.CreateTranslation(size.Width / 2, size.Height / 2);
double pixel = 1 / _scale;
using (context.PushTransform(toScreen))
{
// The tracks on a dark casing, so they stand out where they cross and run close.
var casing = new Pen(Palette.TrackCasing, 5 * pixel, lineCap: PenLineCap.Round);
if (_tracks is not null)
context.DrawGeometry(null, casing, _tracks);
foreach (var (_, _, way) in _switchWays)
context.DrawGeometry(null, casing, way);
if (_tracks is not null)
context.DrawGeometry(null, new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round), _tracks);
var off = new Pen(Palette.SwitchOff, 1.7 * pixel, lineCap: PenLineCap.Round);
var on = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round);
// The ways not taken under those taken.
foreach (var (index, branch, way) in _switchWays)
{
int state = recording.SwitchAt(index, _time);
if (state >= 0 && state != branch)
context.DrawGeometry(null, off, way);
}
foreach (var (index, branch, way) in _switchWays)
{
int state = recording.SwitchAt(index, _time);
if (state < 0 || state == branch)
context.DrawGeometry(null, on, way);
}
// The way the train went, in the colour of the judgement.
for (int kind = 0; kind < _trail.Length; kind++)
if (_trail[kind] is { } trail)
context.DrawGeometry(null, new Pen(Palette.Of((SpeedJudgement)kind), 3.5 * pixel, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round), trail);
}
DrawStopPoints(context, recording);
DrawHornPoints(context, recording);
DrawSignals(context, recording);
DrawPassings(context, recording);
DrawVehicles(context, recording);
DrawUserTrain(context, recording);
DrawCamera(context, recording);
DrawScale(context, size);
DrawLegend(context, size);
DrawHover(context, recording);
}
private bool Visible(Point p, double margin = 20) =>
p.X >= -margin && p.Y >= -margin && p.X <= Bounds.Width + margin && p.Y <= Bounds.Height + margin;
private void DrawSignals(DrawingContext context, Recording recording)
{
double radius = _scale > 0.5 ? 4.5 : _scale > 0.1 ? 3.5 : 2.5;
var outline = new Pen(Palette.Background, 1);
foreach (var signal in recording.Signals)
{
var p = ToScreen(signal.Position.X, signal.Position.Z);
if (!Visible(p))
continue;
context.DrawEllipse(Palette.Of(recording.AspectAt(signal.Index, _time)), outline, p, radius, radius);
}
}
/// <summary>
/// The stop points (W4): a white plate, blue where the user's train stopped, red where it
/// missed the stop; the name of the station once close enough to read it.
/// </summary>
// The way the trains a stop point is for go: a wedge ahead of the plate, as a train sees the W4 coming.
private static void DrawStopWay(DrawingContext context, Point plate, float heading, double size, IBrush fill, IPen outline)
{
// the map shows x to the left, z up: a heading from +z towards +x turns up the screen and to the left
var ahead = new Vector(-Math.Sin(heading), -Math.Cos(heading));
var across = new Vector(-ahead.Y, ahead.X);
var tip = plate + ahead * (size * 4.2);
var root = plate + ahead * (size * 1.8);
var geometry = new StreamGeometry();
using (var g = geometry.Open())
{
g.BeginFigure(tip, true);
g.LineTo(root + across * (size * 1.3));
g.LineTo(root - across * (size * 1.3));
g.EndFigure(true);
}
context.DrawGeometry(fill, outline, geometry);
}
private void DrawStopPoints(DrawingContext context, Recording recording)
{
if (recording.StopPoints.Count == 0)
return;
var outcomes = new Dictionary<(double, double), StationKind>();
foreach (var station in recording.UserStations())
{
if (station.Time > _time || station.Kind is not (StationKind.Stopped or StationKind.Missed))
continue;
var key = (Math.Round(station.Position.X, 1), Math.Round(station.Position.Z, 1));
if (!outcomes.TryGetValue(key, out var was) || was != StationKind.Missed)
outcomes[key] = station.Kind;
}
// Close up every plate is named; from afar each station once, where the names don't cover each other.
bool near = _scale > 0.35;
double size = _scale > 0.5 ? 4 : 3;
var outline = new Pen(Palette.MapBackground, 1);
var labels = new List<(Point At, string Name, IBrush Fill)>();
foreach (var point in recording.StopPoints)
{
var p = ToScreen(point.Position.X, point.Position.Z);
if (!Visible(p))
continue;
var fill = outcomes.TryGetValue((Math.Round(point.Position.X, 1), Math.Round(point.Position.Z, 1)), out var kind)
? kind == StationKind.Missed ? Palette.Bad : Palette.Station
: Palette.StopPoint;
var plate = new Rect(p.X - size, p.Y - size * 1.3, size * 2, size * 2.6);
// a W32 hollow, in the colour a W4 would be filled with
if (point.ForShortTrains)
context.DrawRectangle(Palette.MapBackground, new Pen(fill, 1.5), plate, 1.5, 1.5);
else
context.DrawRectangle(fill, outline, plate, 1.5, 1.5);
if (point.HasHeading)
DrawStopWay(context, p, point.Heading, size, fill, outline);
labels.Add((p, StationNames.Display(point.Station), fill));
}
var delays = StationProgress.StationDelays(recording, _time);
var named = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var taken = new List<Rect>();
// The label of the user's train stays clear.
if (recording.CabPositionAt(_time) is { } train)
{
var mark = ToScreen(train.X, train.Z);
taken.Add(new Rect(mark.X - 10, mark.Y - 24, 170, 34));
}
var culture = System.Globalization.CultureInfo.CurrentCulture;
foreach (var (p, name, fill) in labels)
{
if (!near && !named.Add(name))
continue;
var text = Text(name, Palette.Text, near ? 11 : 10);
FormattedText? late = delays.TryGetValue(name, out var minutes)
? Text(string.Format(culture, Strings["Minutes"], minutes), Palette.Delay(minutes), near ? 11 : 10)
: null;
double width = text.Width + (late is null ? 0 : late.Width + 6) + 8;
var box = new Rect(p.X + size + 3, p.Y - text.Height / 2 - 1, width, text.Height + 2);
if (taken.Exists(r => r.Inflate(2).Intersects(box)))
continue;
taken.Add(box);
context.DrawRectangle(Palette.Faded(Palette.MapBackground, 0.8), null, box);
context.DrawText(text, new Point(box.X + 4, box.Y + 1));
if (late is not null)
context.DrawText(late, new Point(box.X + 4 + text.Width + 6, box.Y + 1));
}
}
/// <summary>The horn points (W6): a diamond, green where the user sounded the horn, red where not.</summary>
private void DrawHornPoints(DrawingContext context, Recording recording)
{
if (recording.HornPoints.Count == 0)
return;
var checks = recording.UserHornChecks().Where(c => c.Request.Time <= _time).ToList();
double size = _scale > 0.5 ? 5 : 3.5;
var outline = new Pen(Palette.MapBackground, 1);
foreach (var point in recording.HornPoints)
{
var p = ToScreen(point.Position.X, point.Position.Z);
if (!Visible(p))
continue;
var check = checks.LastOrDefault(c => c.Request.Position.DistanceTo(point.Position) < 1);
var fill = check is null ? Palette.HornPoint : check.Sounded ? Palette.Good : Palette.Bad;
context.DrawGeometry(fill, outline, Diamond(p, size));
}
}
internal static StreamGeometry Diamond(Point p, double size)
{
var geometry = new StreamGeometry();
using (var g = geometry.Open())
{
g.BeginFigure(p + new Vector(0, -size), true);
g.LineTo(p + new Vector(size, 0));
g.LineTo(p + new Vector(0, size));
g.LineTo(p + new Vector(-size, 0));
g.EndFigure(true);
}
return geometry;
}
/// <summary>Where the user looked from, when not from the cab: a dot with a wedge of where it looked.</summary>
private void DrawCamera(DrawingContext context, Recording recording)
{
if (recording.CameraAt(_time) is not { } camera || camera.Mode == CameraMode.Cab)
return;
var p = ToScreen(camera.Position.X, camera.Position.Z);
if (!Visible(p, 60))
return;
// The heading from +z towards +x: up the screen and to the left.
const double reach = 46, half = 0.45;
var geometry = new StreamGeometry();
using (var g = geometry.Open())
{
g.BeginFigure(p, true);
g.LineTo(p + new Vector(-Math.Sin(camera.Heading - half), -Math.Cos(camera.Heading - half)) * reach);
g.ArcTo(p + new Vector(-Math.Sin(camera.Heading + half), -Math.Cos(camera.Heading + half)) * reach, new Size(reach, reach), 0,
false, SweepDirection.CounterClockwise);
g.EndFigure(true);
}
context.DrawGeometry(Palette.Faded(Palette.HornPoint, 0.18), new Pen(Palette.Faded(Palette.HornPoint, 0.5), 1), geometry);
context.DrawEllipse(Palette.HornPoint, new Pen(Palette.MapBackground, 1.5), p, 4.5, 4.5);
}
/// <summary>Where the user's train passed signals; those at danger ringed red.</summary>
private void DrawPassings(DrawingContext context, Recording recording)
{
var passed = new Pen(Palette.Within, 1.5);
var danger = new Pen(Palette.Over, 2.5);
foreach (var passing in recording.UserPassings())
{
if (passing.Time > _time)
continue;
var p = ToScreen(passing.Position.X, passing.Position.Z);
if (!Visible(p))
continue;
if (passing.AtDanger)
context.DrawEllipse(null, danger, p, 10, 10);
else
context.DrawEllipse(null, passed, p, 7, 7);
}
}
private void DrawVehicles(DrawingContext context, Recording recording)
{
int user = recording.CabAt(_time) is { } sample && _time - sample.Time < 1.5 ? sample.Vehicle : 0;
foreach (var state in recording.VehiclesAt(_time))
{
var info = recording.Vehicle(state.Id);
var brush = state.Id == user ? Palette.UserTrain : state.Driving == Driver.Ai ? Palette.VehicleAi : Palette.Vehicle;
DrawVehicle(context, state.Position.X, state.Position.Z, state.Heading, info?.Length ?? 15, info?.Width ?? 3, brush);
}
}
private void DrawVehicle(DrawingContext context, double x, double z, double heading, double length, double width,
IBrush brush)
{
var center = ToScreen(x, z);
if (!Visible(center, length * _scale + 10))
return;
// The front from +z towards +x: up the screen and to the left.
double fx = Math.Sin(heading), fz = Math.Cos(heading);
double half = Math.Max(length * _scale, 5) / 2, side = Math.Max(width * _scale, 3) / 2;
var front = new Vector(-fx, -fz);
var left = new Vector(-fz, fx);
var geometry = new StreamGeometry();
using (var g = geometry.Open())
{
g.BeginFigure(center + front * half + left * side, true);
g.LineTo(center + front * half - left * side);
g.LineTo(center - front * half - left * side);
g.LineTo(center - front * half + left * side);
g.EndFigure(true);
}
context.DrawGeometry(brush, new Pen(Palette.Background, 0.8), geometry);
}
/// <summary>The head of the user's train between its samples, ten a second, on top of everything.</summary>
private void DrawUserTrain(DrawingContext context, Recording recording)
{
if (recording.CabPositionAt(_time) is not { } position)
return;
var p = ToScreen(position.X, position.Z);
context.DrawEllipse(Palette.MapBackground, new Pen(Palette.UserTrain, 2), p, 7, 7);
context.DrawEllipse(Palette.UserTrain, null, p, 3, 3);
// The train and how late it is, by its mark.
if (StationProgress.DelayAt(recording, _time) is not { } delay)
return;
var culture = System.Globalization.CultureInfo.CurrentCulture;
var train = Text(delay.Train, Palette.UserTrain, 11, FontWeight.SemiBold);
var late = Text(Math.Abs(delay.Minutes) < 0.5 ? Strings["OnTime"] : string.Format(culture, Strings["Minutes"], delay.Minutes),
Palette.Delay(delay.Minutes), 11, FontWeight.SemiBold);
var box = TrainLabel(p, train, late);
context.DrawRectangle(Palette.Faded(Palette.MapBackground, 0.85), null, box);
context.DrawText(train, new Point(box.X + 4, box.Y + 2));
context.DrawText(late, new Point(box.X + train.Width + 12, box.Y + 2));
}
/// <summary>Where the label of the user's train goes, by its mark.</summary>
private static Rect TrainLabel(Point mark, FormattedText train, FormattedText late) =>
new(mark.X + 12, mark.Y - 22, train.Width + late.Width + 16, train.Height + 4);
private void DrawScale(DrawingContext context, Size size)
{
double metres = Nice(120 / _scale);
double length = metres * _scale;
var y = size.Height - 14;
var pen = new Pen(Palette.DimText, 1.5);
context.DrawLine(pen, new Point(size.Width - 16 - length, y), new Point(size.Width - 16, y));
context.DrawLine(pen, new Point(size.Width - 16 - length, y - 4), new Point(size.Width - 16 - length, y + 1));
context.DrawLine(pen, new Point(size.Width - 16, y - 4), new Point(size.Width - 16, y + 1));
var text = Text(metres >= 1000 ? $"{metres / 1000:0.#} km" : $"{metres:0} m", Palette.DimText, 11);
context.DrawText(text, new Point(size.Width - 16 - length / 2 - text.Width / 2, y - 18));
}
private void DrawLegend(DrawingContext context, Size size)
{
var rows = new (IBrush Brush, string Text)[]
{
(Palette.Within, Strings["LegendWithin"]),
(Palette.Slightly, string.Format(CultureInfo.CurrentCulture, Strings["LegendSlightly"], DrivingSummary.DefaultTolerance)),
(Palette.Over, string.Format(CultureInfo.CurrentCulture, Strings["LegendOver"], DrivingSummary.DefaultTolerance)),
(Palette.Autopilot, Strings["LegendAutopilot"]),
(Palette.NoData, Strings["LegendNoData"])
};
var marks = new List<(IBrush Brush, string Text, int Shape)>();
if (_recording is { } r)
{
if (r.StopPoints.Any(point => !point.ForShortTrains))
marks.Add((Palette.StopPoint, Strings["LegendStopPoint"], 0));
if (r.StopPoints.Any(point => point.ForShortTrains))
marks.Add((Palette.StopPoint, Strings["LegendShortStop"], 3));
if (r.HornPoints.Count > 0)
marks.Add((Palette.HornPoint, Strings["LegendHorn"], 1));
if (r.Cameras.Count > 0)
marks.Add((Palette.HornPoint, Strings["LegendCamera"], 2));
}
// Each part under a title of its own, in the text's colour: the dim one is hard to read on the map.
var title = Text(Strings["LegendTitle"], Palette.DimText, 11);
var marksTitle = Text(Strings["LegendMarks"], Palette.DimText, 11);
var texts = rows.Select(row => Text(row.Text, Palette.Text, 12)).Concat(marks.Select(m => Text(m.Text, Palette.Text, 12))).ToList();
const double line = 19, heading = 18, gap = 8;
double width = Math.Max(texts.Max(t => t.Width) + 44, Math.Max(title.Width, marks.Count > 0 ? marksTitle.Width : 0) + 24);
double height = 10 + heading + rows.Length * line + (marks.Count > 0 ? gap + heading + marks.Count * line : 0) + 6;
var box = new Rect(10, size.Height - height - 10, width, height);
context.DrawRectangle(Palette.Faded(Palette.Card, 0.96), new Pen(Palette.CardBorder, 1), box, 3, 3);
double y = box.Top + 8;
context.DrawText(title, new Point(box.Left + 12, y));
y += heading;
for (int i = 0; i < rows.Length; i++, y += line)
{
context.DrawLine(new Pen(rows[i].Brush, 5, lineCap: PenLineCap.Round), new Point(box.Left + 13, y + 9), new Point(box.Left + 27, y + 9));
context.DrawText(texts[i], new Point(box.Left + 36, y));
}
if (marks.Count > 0)
{
y += gap;
context.DrawLine(new Pen(Palette.Grid, 1), new Point(box.Left + 10, y - gap / 2), new Point(box.Right - 10, y - gap / 2));
context.DrawText(marksTitle, new Point(box.Left + 12, y));
y += heading;
}
for (int i = 0; i < marks.Count; i++, y += line)
{
var c = new Point(box.Left + 20, y + 9);
if (marks[i].Shape == 0)
context.DrawRectangle(marks[i].Brush, null, new Rect(c.X - 3, c.Y - 4, 6, 8), 1.5, 1.5);
else if (marks[i].Shape == 3)
context.DrawRectangle(null, new Pen(marks[i].Brush, 1.5), new Rect(c.X - 3, c.Y - 4, 6, 8), 1.5, 1.5);
else if (marks[i].Shape == 1)
context.DrawGeometry(marks[i].Brush, null, Diamond(c, 4.5));
else
context.DrawEllipse(marks[i].Brush, null, c, 4, 4);
context.DrawText(texts[rows.Length + i], new Point(box.Left + 36, y));
}
}
/// <summary>The name of the signal or the vehicle under the pointer.</summary>
private void DrawHover(DrawingContext context, Recording recording)
{
if (_pointer is not { } pointer || _dragFrom is not null)
return;
string? label = null;
double best = 10;
foreach (var signal in recording.Signals)
{
double d = Distance(ToScreen(signal.Position.X, signal.Position.Z), pointer);
if (d < best)
{
best = d;
var aspect = recording.AspectAt(signal.Index, _time);
label = aspect is { } a ? $"{signal.Name} · {AspectText(Strings, a.Speed1, a.Speed2)}" : signal.Name;
}
}
var culture = CultureInfo.CurrentCulture;
foreach (var point in recording.StopPoints)
{
double d = Distance(ToScreen(point.Position.X, point.Position.Z), pointer);
if (d < best)
{
best = d;
label = string.Format(culture, Strings[point.ForShortTrains ? "ShortStopHover" : "StopPointHover"], StationNames.Display(point.Station));
if (point.Platform > 0)
label += " · " + string.Format(culture, Strings["PlatformHover"], point.PlatformLength);
else if (point.Platform < 0)
label += " · " + string.Format(culture, Strings["ShortTrainsHover"], point.PlatformLength);
// the preferred place to stop, as the driver reads it: the head, or the middle of the train
if (point.StopAt < 0)
label += " · " + string.Format(culture, Strings["StopHeadHover"], -point.StopAt);
else if (point.StopAt > 0)
label += " · " + string.Format(culture, Strings["StopMiddleHover"], point.StopAt);
}
}
foreach (var point in recording.HornPoints)
{
double d = Distance(ToScreen(point.Position.X, point.Position.Z), pointer);
if (d < best)
{
best = d;
label = string.Format(culture, Strings["HornHover"], point.Name, point.Duration);
}
}
foreach (var state in recording.VehiclesAt(_time))
{
double d = Distance(ToScreen(state.Position.X, state.Position.Z), pointer);
if (d < best && recording.Vehicle(state.Id) is { } info)
{
best = d;
label = string.IsNullOrEmpty(info.Train)
? $"{info.Name} · {Math.Abs(state.SpeedKmh):0} km/h"
: $"{info.Name} ({info.Train}) · {Math.Abs(state.SpeedKmh):0} km/h";
}
}
if (label is null)
return;
var text = Text(label, Palette.Text, 12);
var box = new Rect(pointer.X + 14, pointer.Y - 12 - text.Height, text.Width + 16, text.Height + 8);
context.DrawRectangle(Palette.Faded(Palette.Card, 0.95), new Pen(Palette.CardBorder, 1), box, 6, 6);
context.DrawText(text, new Point(box.Left + 8, box.Top + 4));
}
/// <summary>An aspect as the speeds it gives: stop, a speed, or go.</summary>
public static string AspectText(IBlackBoxStrings strings, float speed1, float speed2)
{
if (speed1 == 0)
return strings["AspectStop"];
if (speed1 < 0 && speed2 < 0)
return strings["AspectFree"];
string first = speed1 < 0 ? "∞" : speed1.ToString("0", CultureInfo.InvariantCulture);
string second = speed2 < 0 ? "∞" : speed2.ToString("0", CultureInfo.InvariantCulture);
return $"{first}/{second}";
}
private static double Distance(Point a, Point b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
private static double Nice(double value)
{
double power = Math.Pow(10, Math.Floor(Math.Log10(value)));
double unit = value / power;
return (unit < 2 ? 1 : unit < 5 ? 2 : 5) * power;
}
internal static FormattedText Text(string text, IBrush brush, double size, FontWeight weight = FontWeight.Normal) =>
new(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
weight == FontWeight.Normal ? Typeface.Default : new Typeface(Typeface.Default.FontFamily, FontStyle.Normal, weight),
size, brush);
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
var point = e.GetCurrentPoint(this);
if (!point.Properties.IsLeftButtonPressed)
return;
if (e.ClickCount == 2)
{
if (_follow)
StopFollowing();
Fit();
return;
}
_dragFrom = point.Position;
_dragCenter = (_centerX, _centerZ);
e.Pointer.Capture(this);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
var position = e.GetPosition(this);
_pointer = position;
if (_dragFrom is { } from)
{
var moved = position - from;
if (_follow && (Math.Abs(moved.X) > 3 || Math.Abs(moved.Y) > 3))
StopFollowing();
if (!_follow)
{
_centerX = _dragCenter.X + moved.X / _scale;
_centerZ = _dragCenter.Z + moved.Y / _scale;
}
}
InvalidateVisual();
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
_dragFrom = null;
e.Pointer.Capture(null);
}
protected override void OnPointerExited(PointerEventArgs e)
{
base.OnPointerExited(e);
_pointer = null;
InvalidateVisual();
}
protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
{
base.OnPointerWheelChanged(e);
var at = e.GetPosition(this);
var (x, z) = ToWorld(at);
_scale = Math.Clamp(_scale * Math.Pow(1.25, e.Delta.Y), MinScale, MaxScale);
if (!_follow)
{
// The place under the pointer stays under it.
_centerX = x + (at.X - Bounds.Width / 2) / _scale;
_centerZ = z + (at.Y - Bounds.Height / 2) / _scale;
}
InvalidateVisual();
e.Handled = true;
}
private void StopFollowing()
{
_follow = false;
FollowStopped?.Invoke();
}
}

View File

@@ -0,0 +1,117 @@
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The colours the map, the timeline and the panels share: those of the starter's Carbon
/// look for the window, its green for what is picked, and colours of their own for the data.
/// </summary>
public static class Palette
{
// The window, the cards on it and the lines between.
public static readonly IBrush Background = Brush("#15171B");
public static readonly IBrush Panel = Brush("#1E2327");
public static readonly IBrush Card = Brush("#1E2327");
public static readonly IBrush CardHover = Brush("#2A3036");
public static readonly IBrush CardBorder = Brush("#3A424A");
public static readonly IBrush Grid = Brush("#2A3036");
public static readonly IBrush MapBackground = Brush("#121417");
public static readonly IBrush Text = Brush("#E6E8EA");
public static readonly IBrush DimText = Brush("#9098A0");
public static readonly IBrush FaintText = Brush("#646C74");
/// <summary>The headers of the panels, as the group boxes of the starter.</summary>
public static readonly IBrush Header = Brush("#2A3036");
/// <summary>The green of what is picked or on: bright for lines and text, deep for fills.</summary>
public static readonly IBrush Accent = Brush("#41C400");
public static readonly IBrush AccentFill = Brush("#177F00");
public static readonly IBrush AccentFillHover = Brush("#1E9000");
public static readonly IBrush AccentText = Brush("#FFFFFF");
/// <summary>The ring round a drawn control that has the keyboard, in the green of the starter's own.</summary>
public static readonly IPen FocusPen = new Pen(Accent, 2);
public static readonly IBrush Good = Brush("#4cc46e");
/// <summary>A delay: green on time, yellow a little late, red late, blue early.</summary>
public static IBrush Delay(double? minutes) => minutes switch
{
null => Good,
> 3 => Bad,
> 0.5 => Warn,
< -0.5 => Station,
_ => Good
};
public static readonly IBrush Warn = Brush("#e8c547");
public static readonly IBrush Bad = Brush("#f0584a");
public static readonly IBrush Track = Brush("#6f7b88");
public static readonly IBrush TrackCasing = Brush("#1d232b");
public static readonly IBrush SwitchOff = Brush("#323a44");
public static readonly IBrush Vehicle = Brush("#c9a26b");
public static readonly IBrush VehicleAi = Brush("#9fb0c3");
public static readonly IBrush UserTrain = Brush("#ff9d1c");
public static readonly IBrush Cursor = Brush("#ffb000");
public static readonly IBrush Within = Brush("#4cc46e");
public static readonly IBrush Slightly = Brush("#e8c547");
public static readonly IBrush Over = Brush("#f0584a");
public static readonly IBrush Autopilot = Brush("#4a90e2");
public static readonly IBrush NoData = Brush("#5f6871");
public static readonly IBrush Speed = Brush("#f2f4f6");
public static readonly IBrush SpeedFill = new SolidColorBrush(Color.Parse("#f2f4f6"), 0.06).ToImmutable();
public static readonly IBrush Target = Brush("#4cc46e");
public static readonly IBrush Limit = Brush("#ff8c2a");
public static readonly IBrush SignalStop = Brush("#ff3b30");
public static readonly IBrush SignalLimited = Brush("#ffcc00");
public static readonly IBrush SignalFree = Brush("#34c759");
public static readonly IBrush SignalShunt = Brush("#e8f0ff");
public static readonly IBrush SignalShuntStop = Brush("#4a6cff");
public static readonly IBrush SignalUnknown = Brush("#808890");
public static readonly IBrush StopPoint = Brush("#f4f6f8");
public static readonly IBrush Station = Brush("#5aa9ff");
public static readonly IBrush HornPoint = Brush("#b9a6ff");
public static readonly IBrush Brakes = Brush("#e05a52");
public static readonly IBrush Controller = Brush("#2bb3a3");
public static readonly IBrush Vigilance = Brush("#e8c547");
public static readonly IBrush CabSignal = Brush("#f08a3a");
public static readonly IBrush LampOff = Brush("#252c35");
public static readonly IBrush LampOn = Brush("#4cc46e");
public static readonly IBrush LampWarning = Brush("#e8c547");
public static readonly IBrush LampAlarm = Brush("#f0584a");
/// <summary>The train protection's buzzer: still to be acknowledged, not braking yet.</summary>
public static readonly IBrush Buzzer = Brush("#c77dff");
public static readonly IBrush LightWhite = Brush("#fff6d8");
public static readonly IBrush LightRed = Brush("#ff3b30");
public static readonly IBrush Command = Brush("#8b96a3");
public static IBrush Of(SpeedJudgement judgement) => judgement switch
{
SpeedJudgement.Within => Within,
SpeedJudgement.Slightly => Slightly,
SpeedJudgement.Over => Over,
SpeedJudgement.Autopilot => Autopilot,
_ => NoData
};
/// <summary>What a signal shows: the colour of its main light, as the in-game map draws it.</summary>
public static IBrush Of(AspectChange? aspect)
{
if (aspect is not { } a)
return SignalUnknown;
bool shunt = a.Command.StartsWith("Shunt", System.StringComparison.OrdinalIgnoreCase);
if (a.Speed1 == 0)
return shunt ? SignalShuntStop : SignalStop;
if (shunt)
return SignalShunt;
return a.Speed1 < 0 && a.Speed2 != 0 ? SignalFree : SignalLimited;
}
/// <summary>A colour seen through: for fills under lines and glows.</summary>
public static IBrush Faded(IBrush brush, double opacity) =>
new SolidColorBrush(((ISolidColorBrush)brush).Color, opacity).ToImmutable();
private static IBrush Brush(string color) => new SolidColorBrush(Color.Parse(color)).ToImmutable();
}

View File

@@ -0,0 +1,47 @@
using System;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
namespace Eu07.BlackBox.Views;
/// <summary>
/// What a screen reader is told of a control that draws itself: a name, the moment or
/// the row it stands at as its value - read again whenever it changes under the focus,
/// as a slider's is - and a description of what it shows or how to work it.
/// </summary>
internal sealed class SpokenPeer : ControlAutomationPeer, IValueProvider
{
private readonly AutomationControlType _type;
private readonly Func<string?> _value;
private readonly Func<string?> _help;
public SpokenPeer(Control owner, AutomationControlType type, Func<string?> value, Func<string?> help) : base(owner)
{
_type = type;
_value = value;
_help = help;
}
/// <summary>Tells the reader the value changed, so it reads the new one.</summary>
public void Told(string? before, string? now)
{
if (before != now)
RaisePropertyChangedEvent(ValuePatternIdentifiers.ValueProperty, before, now);
}
protected override AutomationControlType GetAutomationControlTypeCore() => _type;
protected override string? GetHelpTextCore() => base.GetHelpTextCore() is { Length: > 0 } own ? own : _help();
protected override bool IsContentElementCore() => true;
protected override bool IsControlElementCore() => true;
string? IValueProvider.Value => _value();
bool IValueProvider.IsReadOnly => true;
void IValueProvider.SetValue(string? value) => throw new InvalidOperationException("The value is read only.");
}

View File

@@ -0,0 +1,769 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The user's train over the time of the recording, by the clock of the simulation: its
/// speed, the speed the AI would hold and the next limit it saw, below them bands of who
/// drove and how against the AI, of the controller, the brakes, the alerter (CA), the cab
/// signalling (SHP) and the camera, and marks of the commands, the signals passed, the
/// stations, the horn points and the couplings. A click goes to its moment; the wheel zooms
/// the time, dragging moves it.
/// </summary>
public sealed class TimelineView : Control
{
private const double Left = 56;
private const double Right = 12;
private const double Top = 36;
private const double BandHeight = 8;
private const double BandGap = 3;
private const double MarksHeight = 16;
private const double AxisHeight = 20;
private const int Bands = 6;
private Recording? _recording;
private double _time;
private double _start;
private double _secondsPerPixel = -1;
private Point? _pressed;
private double _pressedStart;
private bool _dragged;
private double? _hover;
private Point? _pointer;
private int _measured = -1;
private Recording? _measuredOf;
private double _speedTop = 40;
private int _controllerTop = 1;
/// <summary>A moment was clicked.</summary>
public event Action<double>? Seek;
/// <summary>The moment under the pointer, null once it leaves.</summary>
public event Action<double?>? Hovered;
public TimelineView()
{
ClipToBounds = true;
MinHeight = 160;
// Walked from the keyboard too: the arrows step through the time.
Focusable = true;
}
private string? _spoken;
/// <summary>
/// What the moment played is said as - the clock, the speed, what the AI held - the
/// value a screen reader reads, again whenever it changes.
/// </summary>
public string? Spoken
{
get => _spoken;
set
{
string? before = _spoken;
_spoken = value;
(ControlAutomationPeer.FromElement(this) as SpokenPeer)?.Told(before, value);
}
}
protected override AutomationPeer OnCreateAutomationPeer() =>
new SpokenPeer(this, AutomationControlType.Slider, () => _spoken, () => Strings["TimelineHelp"]);
/// <summary>How far one press of an arrow goes, in seconds: Ctrl a minute, Page Up and Down ten.</summary>
public const double Step = 10, CtrlStep = 60, PageStep = 600;
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (_recording is not { } recording || recording.Duration <= 0)
return;
bool ctrl = e.KeyModifiers.HasFlag(KeyModifiers.Control);
double? to = e.Key switch
{
Key.Left => _time - (ctrl ? CtrlStep : Step),
Key.Right => _time + (ctrl ? CtrlStep : Step),
Key.PageUp => _time - PageStep,
Key.PageDown => _time + PageStep,
Key.Home => 0,
Key.End => recording.Duration,
_ => null
};
if (to is not { } t)
return;
Seek?.Invoke(Math.Clamp(t, 0, recording.Duration));
e.Handled = true;
}
protected override void OnGotFocus(FocusChangedEventArgs e)
{
base.OnGotFocus(e);
InvalidateVisual();
}
protected override void OnLostFocus(FocusChangedEventArgs e)
{
base.OnLostFocus(e);
InvalidateVisual();
}
public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings();
public Recording? Recording
{
get => _recording;
set
{
_recording = value;
_secondsPerPixel = -1;
_start = 0;
InvalidateVisual();
}
}
public double Time
{
get => _time;
set
{
_time = value;
// Kept in view while it plays.
if (_secondsPerPixel > 0 && _recording is not null)
{
double end = _start + PlotWidth * _secondsPerPixel;
if (value > end || value < _start)
_start = Math.Max(0, value - PlotWidth * _secondsPerPixel * 0.1);
}
InvalidateVisual();
}
}
/// <summary>All of the recording in view.</summary>
public void Fit()
{
_secondsPerPixel = -1;
_start = 0;
InvalidateVisual();
}
private double PlotWidth => Math.Max(10, Bounds.Width - Left - Right);
private double ChartBottom => Bounds.Height - AxisHeight - MarksHeight - Bands * (BandHeight + BandGap) - 6;
private double X(double t) => Left + (t - _start) / _secondsPerPixel;
private double TimeAt(double x) => _start + (x - Left) * _secondsPerPixel;
public override void Render(DrawingContext context)
{
var size = Bounds.Size;
if (IsFocused)
context.DrawRectangle(null, Palette.FocusPen, new Rect(size).Deflate(1));
var recording = _recording;
if (recording is null || recording.Duration <= 0)
return;
if (_secondsPerPixel <= 0)
_secondsPerPixel = Math.Max(recording.Duration, 60) / PlotWidth;
double end = _start + PlotWidth * _secondsPerPixel;
double chartBottom = ChartBottom;
Measure(recording);
double top = _speedTop;
double Y(double kmh) => chartBottom - Math.Clamp(kmh / top, 0, 1.05) * (chartBottom - Top);
using (context.PushClip(new Rect(Left, 0, PlotWidth, size.Height)))
{
DrawGrid(context, top, Y, size);
DrawCurves(context, recording, Y, end);
double bands = chartBottom + 6;
DrawBands(context, recording, bands, end);
DrawMarks(context, recording, bands + Bands * (BandHeight + BandGap), end);
DrawAxis(context, recording, size.Height - AxisHeight, end);
if (_hover is { } hover)
context.DrawLine(new Pen(Palette.DimText, 1, new DashStyle(new double[] { 2, 3 }, 0)),
new Point(X(hover), Top), new Point(X(hover), size.Height - AxisHeight));
double cursor = X(_time);
context.DrawLine(new Pen(Palette.Cursor, 1.5), new Point(cursor, Top - 6), new Point(cursor, size.Height - AxisHeight));
// The moment played, on the axis.
var clock = MapView.Text(recording.ClockAt(_time).ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture), Palette.Cursor, 10, FontWeight.SemiBold);
var bubble = new Rect(Math.Max(Left, Math.Min(cursor - clock.Width / 2 - 5, size.Width - Right - clock.Width - 10)), size.Height - AxisHeight + 2,
clock.Width + 10, clock.Height + 2);
context.DrawRectangle(Palette.Card, new Pen(Palette.Cursor, 1), bubble);
context.DrawText(clock, new Point(bubble.X + 5, bubble.Y + 1));
}
DrawSpeedLabels(context, top, Y);
DrawBandLabels(context, chartBottom + 6);
DrawKey(context);
if (MarkUnderPointer(recording, chartBottom) is { } mark)
DrawMarkLabel(context, mark, size);
}
/// <summary>The top of the speed scale and the highest step of the controller, once a reading.</summary>
private void Measure(Recording recording)
{
if (_measured == recording.Revision && ReferenceEquals(_measuredOf, recording))
return;
float max = 40;
int controller = 1;
foreach (var s in recording.Cab)
{
max = Math.Max(max, s.AbsSpeedKmh);
if (s.AiValid)
max = Math.Max(max, s.Ai.TargetKmh);
controller = Math.Max(controller, (int)s.MainController);
}
_speedTop = Math.Ceiling(max * 1.1 / 20) * 20;
_controllerTop = controller;
_measured = recording.Revision;
_measuredOf = recording;
}
private void DrawGrid(DrawingContext context, double top, Func<double, double> y, Size size)
{
var pen = new Pen(Palette.Grid, 1);
for (double v = 0; v <= top; v += top > 160 ? 40 : 20)
context.DrawLine(pen, new Point(Left, y(v)), new Point(size.Width - Right, y(v)));
}
private void DrawSpeedLabels(DrawingContext context, double top, Func<double, double> y)
{
for (double v = 0; v <= top; v += top > 160 ? 40 : 20)
{
var text = MapView.Text(v.ToString("0", CultureInfo.InvariantCulture), Palette.DimText, 10);
context.DrawText(text, new Point(Left - 6 - text.Width, y(v) - text.Height / 2));
}
}
/// <summary>
/// Each curve by columns of pixels: in a column the lowest and the highest speed,
/// so an hour draws as fast as a minute.
/// </summary>
private void DrawCurves(DrawingContext context, Recording recording, Func<double, double> y, double end)
{
var cab = recording.Cab;
int first = Math.Max(0, recording.CabIndexAt(_start));
var speed = new Curve();
var target = new Curve();
var limits = new List<Point>();
int column = int.MinValue;
CabSample? before = null;
for (int i = first; i < cab.Count; i++)
{
var s = cab[i];
if (s.Time > end + _secondsPerPixel * 2)
break;
bool gap = before is { } b && (s.Time - b.Time > 1.0 || s.Vehicle != b.Vehicle);
if (gap)
{
speed.Break();
target.Break();
}
int c = (int)Math.Round(X(s.Time));
speed.Add(c, y(s.AbsSpeedKmh));
// Under the autopilot too: what it aimed at.
if (s.AiValid)
target.Add(c, y(s.Ai.TargetKmh));
else
target.Break();
if (c != column && s.AiValid && s.Ai.HasNextLimit)
limits.Add(new Point(c, y(s.Ai.NextLimitKmh)));
column = c;
before = s;
}
if (speed.Fill(y(0)) is { } fill)
context.DrawGeometry(Palette.SpeedFill, null, fill);
if (target.Geometry() is { } t)
context.DrawGeometry(null, new Pen(Palette.Target, 1.5), t);
var limitPen = new Pen(Palette.Limit, 2);
foreach (var p in limits)
context.DrawLine(limitPen, p, p + new Vector(1, 0));
if (speed.Geometry() is { } v)
context.DrawGeometry(null, new Pen(Palette.Speed, 1.5), v);
}
private void DrawBands(DrawingContext context, Recording recording, double top, double end)
{
var cab = recording.Cab;
int first = Math.Max(0, recording.CabIndexAt(_start));
var cameras = recording.Cameras;
int camera = -1;
var rows = new BandRun[Bands];
for (int row = 0; row < rows.Length; row++)
rows[row] = new BandRun(context, top + row * (BandHeight + BandGap));
for (int i = first; i < cab.Count; i++)
{
var s = cab[i];
if (s.Time > end)
break;
double next = i + 1 < cab.Count && cab[i + 1].Time - s.Time <= 1.0 ? cab[i + 1].Time : s.Time + 0.1;
double x0 = X(s.Time), x1 = Math.Max(X(next), x0 + 0.6);
rows[0].Add(x0, x1, Palette.Of(DrivingSummary.Judge(s)), BandHeight);
// The controller as high as its step stands against the highest one used.
rows[1].Add(x0, x1, s.MainController > 0 ? Palette.Controller : null,
Math.Max(1.5, BandHeight * s.MainController / _controllerTop));
rows[2].Add(x0, x1, s.BrakeCylinder > 0.2f ? BrakeShade(s.BrakeCylinder) : null, BandHeight);
if (s.Security != SecurityFlags.None || s.CabEnd != 0)
{
// The alerter and the cab signalling apart: the lamp, then its buzzer, red when it braked.
rows[3].Add(x0, x1, s.VigilanceBuzzer ? Palette.Buzzer
: s.Has(SecurityFlags.Vigilance) ? Palette.Vigilance : null, BandHeight);
rows[4].Add(x0, x1, s.CabSignalBuzzer ? Palette.Buzzer
: s.Has(SecurityFlags.CabSignal) ? Palette.CabSignal : null, BandHeight);
if (s.ProtectionBraking)
rows[s.Has(SecurityFlags.CabSignal) && !s.Has(SecurityFlags.Vigilance) ? 4 : 3].Add(x0, x1, Palette.Bad, BandHeight);
}
else
rows[3].Add(x0, x1, (s.Flags & CabFlags.AlerterBeeping) != 0 ? Palette.Buzzer
: (s.Flags & CabFlags.AlerterBlinking) != 0 ? Palette.Vigilance : null, BandHeight);
// Where the user looked from: the samples go on in time, and so does the camera.
while (camera + 1 < cameras.Count && cameras[camera + 1].Time <= s.Time)
camera++;
rows[5].Add(x0, x1, camera < 0 ? null : CameraBrush(cameras[camera].Mode), BandHeight);
}
foreach (var row in rows)
row.Flush();
}
private static readonly IBrush CameraCab = Palette.Faded(Palette.UserTrain, 0.45);
private static readonly IBrush CameraOutside = Palette.Faded(Palette.HornPoint, 0.75);
private static readonly IBrush CameraFree = Palette.Faded(Palette.Station, 0.75);
private static IBrush CameraBrush(CameraMode mode) => mode switch
{
CameraMode.Cab => CameraCab,
CameraMode.External => CameraOutside,
_ => CameraFree
};
private static readonly IBrush[] BrakeShades = Shades(Palette.Brakes, 8);
private static IBrush[] Shades(IBrush brush, int count)
{
var colour = ((ISolidColorBrush)brush).Color;
var shades = new IBrush[count];
for (int i = 0; i < count; i++)
shades[i] = new SolidColorBrush(colour, 0.35 + 0.65 * i / (count - 1));
return shades;
}
/// <summary>The harder the brakes hold, the deeper the red.</summary>
private static IBrush BrakeShade(float cylinderBar) =>
BrakeShades[(int)Math.Round(Math.Clamp(cylinderBar / 5.0, 0, 1) * (BrakeShades.Length - 1))];
/// <summary>
/// The samples of a band drawn as few rectangles as the band changes: ten a second, each
/// narrower than a pixel, they would leave seams between them.
/// </summary>
private sealed class BandRun(DrawingContext context, double top)
{
private IBrush? _brush;
private double _height, _from, _to;
public void Add(double x0, double x1, IBrush? brush, double height)
{
if (brush is not null && ReferenceEquals(brush, _brush) && height == _height && x0 <= _to + 0.5)
{
_to = Math.Max(_to, x1);
return;
}
Flush();
_brush = brush;
_height = height;
_from = x0;
_to = x1;
}
public void Flush()
{
if (_brush is not null)
context.FillRectangle(_brush, new Rect(_from, top + BandHeight - _height, _to - _from, _height));
_brush = null;
}
}
private void DrawBandLabels(DrawingContext context, double top)
{
string[] names = { Strings["BandDriving"], Strings["BandController"], Strings["BandBrakes"], Strings["BandVigilance"],
Strings["BandCabSignal"], Strings["BandCamera"] };
for (int i = 0; i < names.Length; i++)
{
double y = top + i * (BandHeight + BandGap);
context.DrawRectangle(Palette.Faded(Palette.Grid, 0.5), null, new Rect(Left, y, Bounds.Width - Left - Right, BandHeight));
var text = MapView.Text(names[i], Palette.FaintText, 9);
context.DrawText(text, new Point(Left - 6 - text.Width, y + (BandHeight - text.Height) / 2));
}
var events = MapView.Text(Strings["BandEvents"], Palette.FaintText, 9);
double marks = top + Bands * (BandHeight + BandGap);
context.DrawText(events, new Point(Left - 6 - events.Width, marks + (MarksHeight - events.Height) / 2));
}
/// <summary>
/// The commands as short grey ticks, the autopilot switched in blue, the signals passed in
/// green, at danger tall and red; the stations as blue plates, the horn points as diamonds
/// green or red as the horn sounded, the couplings as yellow ticks.
/// </summary>
private void DrawMarks(DrawingContext context, Recording recording, double top, double end)
{
foreach (var station in recording.UserStations())
{
if (station.Time < _start || station.Time > end || station.Kind == StationKind.Ready)
continue;
double x = X(station.Time);
var brush = station.Kind == StationKind.Missed ? Palette.Bad : Palette.Station;
context.DrawLine(new Pen(Palette.Faded(brush, 0.35), 1), new Point(x, Top), new Point(x, top));
context.DrawRectangle(brush, null, new Rect(x - 3, Top - 13, 6, 8), 1.5, 1.5);
}
foreach (var horn in recording.UserHornChecks())
{
if (horn.Request.Time < _start || horn.Request.Time > end)
continue;
double x = X(horn.Request.Time);
var brush = horn.Sounded ? Palette.Good : Palette.Bad;
var geometry = new StreamGeometry();
using (var g = geometry.Open())
{
g.BeginFigure(new Point(x, Top - 14), true);
g.LineTo(new Point(x + 4, Top - 10));
g.LineTo(new Point(x, Top - 6));
g.LineTo(new Point(x - 4, Top - 10));
g.EndFigure(true);
}
context.DrawGeometry(brush, null, geometry);
}
var coupling = new Pen(Palette.Warn, 2);
foreach (var c in recording.UserCouplings())
if (c.Time >= _start && c.Time <= end)
context.DrawLine(coupling, new Point(X(c.Time), top + 1), new Point(X(c.Time), top + MarksHeight));
var command = new Pen(Palette.Command, 1);
foreach (var c in recording.UserCommands())
if (c.Time >= _start && c.Time <= end)
context.DrawLine(command, new Point(X(c.Time), top + MarksHeight - 5), new Point(X(c.Time), top + MarksHeight));
var autopilot = new Pen(Palette.Autopilot, 2);
foreach (var d in recording.DriverChanges)
if (d.Time >= _start && d.Time <= end)
context.DrawLine(autopilot, new Point(X(d.Time), top + 2), new Point(X(d.Time), top + MarksHeight));
foreach (var p in recording.UserPassings())
{
if (p.Time < _start || p.Time > end)
continue;
double x = X(p.Time);
if (p.AtDanger)
{
var geometry = new StreamGeometry();
using (var g = geometry.Open())
{
g.BeginFigure(new Point(x, Top - 4), true);
g.LineTo(new Point(x - 5, Top - 13));
g.LineTo(new Point(x + 5, Top - 13));
g.EndFigure(true);
}
context.DrawGeometry(Palette.Over, null, geometry);
context.DrawLine(new Pen(Palette.Over, 1.5), new Point(x, Top - 4), new Point(x, top + MarksHeight));
}
else
context.DrawLine(new Pen(Palette.Within, 1.5), new Point(x, top + 1), new Point(x, top + MarksHeight - 6));
}
}
private void DrawAxis(DrawingContext context, Recording recording, double y, double end)
{
double[] steps = { 10, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200 };
double step = steps[^1];
foreach (double candidate in steps)
if (candidate / _secondsPerPixel >= 80)
{
step = candidate;
break;
}
var pen = new Pen(Palette.DimText, 1);
// On the clock of the simulation: the marks fall on whole minutes and hours of it.
double offset = recording.ClockAt(0).TotalSeconds;
double first = Math.Ceiling((_start + offset) / step) * step - offset;
for (double t = first; t <= end; t += step)
{
double x = X(t);
context.DrawLine(pen, new Point(x, y), new Point(x, y + 4));
var clock = recording.ClockAt(t);
string label = step < 60 ? clock.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture) : clock.ToString(@"hh\:mm", CultureInfo.InvariantCulture);
var text = MapView.Text(label, Palette.DimText, 10);
context.DrawText(text, new Point(x - text.Width / 2, y + 4));
}
}
private void DrawKey(DrawingContext context)
{
const double y = 10;
double x = Left + 4, limit = Bounds.Width - Right;
bool Room(string key) => x + 18 + MapView.Text(Strings[key], Palette.DimText, 10).Width <= limit;
void Name(string key)
{
var text = MapView.Text(Strings[key], Palette.DimText, 10);
context.DrawText(text, new Point(x + 18, y - text.Height / 2));
x += 18 + text.Width + 14;
}
foreach (var (brush, key) in new[] { (Palette.Speed, "TimelineSpeed"), (Palette.Target, "TimelineTarget"), (Palette.Limit, "TimelineLimit") })
{
if (!Room(key))
return;
context.DrawLine(new Pen(brush, 2), new Point(x, y), new Point(x + 14, y));
Name(key);
}
// the marks, as they are drawn above the chart and in the row of the events
if (Room("KeyStation"))
{
context.DrawRectangle(Palette.Station, null, new Rect(x + 4, y - 4, 6, 8), 1.5, 1.5);
Name("KeyStation");
}
if (Room("KeyHorn"))
{
context.DrawGeometry(Palette.Good, null, MapView.Diamond(new Point(x + 7, y), 4));
Name("KeyHorn");
}
foreach (var (brush, key) in new[] { (Palette.Within, "KeySignal"), (Palette.Warn, "KeyCoupling"), (Palette.Autopilot, "KeyDriver"), (Palette.Command, "KeyCommand") })
{
if (!Room(key))
return;
context.DrawLine(new Pen(brush, 2), new Point(x + 7, y - 5), new Point(x + 7, y + 5));
Name(key);
}
}
/// <summary>What the mark under the pointer is: the nearest within a few pixels, in the row of the events or the plates above.</summary>
private string? MarkUnderPointer(Recording recording, double chartBottom)
{
if (_pointer is not { } pointer)
return null;
double marks = chartBottom + 6 + Bands * (BandHeight + BandGap);
bool inPlates = pointer.Y >= Top - 16 && pointer.Y <= Top - 2;
bool inMarks = pointer.Y >= marks - 2 && pointer.Y <= marks + MarksHeight + 2;
if (!inPlates && !inMarks || pointer.X < Left || pointer.X > Left + PlotWidth)
return null;
double end = _start + PlotWidth * _secondsPerPixel;
var culture = CultureInfo.CurrentCulture;
string? found = null;
double best = 5;
void Consider(double time, Func<string> text)
{
if (time < _start || time > end)
return;
double d = Math.Abs(X(time) - pointer.X);
if (d < best)
{
best = d;
found = text();
}
}
if (inPlates)
{
foreach (var station in recording.UserStations())
if (station.Kind != StationKind.Ready)
Consider(station.Time, () => string.Format(culture, Strings[station.Kind switch
{
StationKind.Stopped => "TlStationStopped",
StationKind.Missed => "TlStationMissed",
_ => "TlStationPassed"
}], StationNames.Display(station.Station)));
foreach (var horn in recording.UserHornChecks())
Consider(horn.Request.Time, () => Strings[horn.Sounded ? "TlHornSounded" : "TlHornSilent"]);
}
foreach (var p in recording.UserPassings())
{
if (!inMarks && !p.AtDanger)
continue;
Consider(p.Time, () =>
{
string name = recording.Signal(p.Signal)?.Name ?? p.Event;
return p.AtDanger
? string.Format(culture, Strings["TlSignalDanger"], name)
: string.Format(culture, Strings["TlSignal"], name, MapView.AspectText(Strings, p.Speed1, p.Speed2));
});
}
if (inMarks)
{
foreach (var c in recording.UserCouplings())
Consider(c.Time, () => Strings[c.Coupled ? "TlCoupled" : c.Uncoupled ? "TlUncoupled" : "TlCouplingChanged"]);
foreach (var d in recording.DriverChanges)
Consider(d.Time, () => Strings[d.Driving == Driver.Ai ? "TlAutopilotOn" : "TlAutopilotOff"]);
foreach (var c in recording.UserCommands())
Consider(c.Time, () => string.Format(culture, Strings["TlCommand"],
Strings[DefaultBlackBoxStrings.CommandPrefix + c.Name]));
}
return found;
}
private void DrawMarkLabel(DrawingContext context, string text, Size size)
{
if (_pointer is not { } pointer)
return;
var label = MapView.Text(text, Palette.Text, 11);
double x = Math.Max(Left, Math.Min(pointer.X + 10, size.Width - Right - label.Width - 12));
double y = Math.Max(2, pointer.Y - label.Height - 12);
var box = new Rect(x, y, label.Width + 12, label.Height + 6);
context.DrawRectangle(Palette.Card, new Pen(Palette.CardBorder, 1), box, 3, 3);
context.DrawText(label, new Point(x + 6, y + 3));
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
return;
if (e.ClickCount == 2)
{
Fit();
return;
}
_pressed = e.GetPosition(this);
_pressedStart = _start;
_dragged = false;
e.Pointer.Capture(this);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
if (_recording is null || _secondsPerPixel <= 0)
return;
var position = e.GetPosition(this);
if (_pressed is { } from)
{
double moved = position.X - from.X;
if (Math.Abs(moved) > 3)
_dragged = true;
if (_dragged)
_start = Math.Clamp(_pressedStart - moved * _secondsPerPixel, 0, Math.Max(0, _recording.Duration - PlotWidth * _secondsPerPixel * 0.5));
}
_hover = position.X >= Left ? Math.Clamp(TimeAt(position.X), 0, _recording.Duration) : null;
_pointer = position;
Hovered?.Invoke(_hover);
InvalidateVisual();
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (_pressed is not null && !_dragged && _recording is not null && _secondsPerPixel > 0)
Seek?.Invoke(Math.Clamp(TimeAt(e.GetPosition(this).X), 0, _recording.Duration));
_pressed = null;
e.Pointer.Capture(null);
}
protected override void OnPointerExited(PointerEventArgs e)
{
base.OnPointerExited(e);
_hover = null;
_pointer = null;
Hovered?.Invoke(null);
InvalidateVisual();
}
protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
{
base.OnPointerWheelChanged(e);
if (_recording is null || _secondsPerPixel <= 0)
return;
double x = e.GetPosition(this).X;
double at = TimeAt(x);
double whole = Math.Max(_recording.Duration, 60) / PlotWidth;
_secondsPerPixel = Math.Clamp(_secondsPerPixel / Math.Pow(1.3, e.Delta.Y), 0.02, whole);
_start = Math.Max(0, at - (x - Left) * _secondsPerPixel);
InvalidateVisual();
e.Handled = true;
}
/// <summary>A line through columns of pixels: in each the first, the lowest, the highest and the last value.</summary>
private sealed class Curve
{
private readonly List<List<Point>> _lines = new();
private List<Point>? _line;
private int _column = int.MinValue;
private double _first, _low, _high, _last;
public void Add(int column, double y)
{
if (column != _column)
{
Flush();
_column = column;
_first = _low = _high = y;
}
_low = Math.Min(_low, y);
_high = Math.Max(_high, y);
_last = y;
}
public void Break()
{
Flush();
_line = null;
_column = int.MinValue;
}
private void Flush()
{
if (_column == int.MinValue)
return;
if (_line is null)
_lines.Add(_line = new List<Point>());
var (a, b) = _first <= _last ? (_low, _high) : (_high, _low);
_line.Add(new Point(_column, _first));
if (Math.Abs(_high - _low) > 0.5)
{
_line.Add(new Point(_column, a));
_line.Add(new Point(_column, b));
}
_line.Add(new Point(_column, _last));
}
/// <summary>The area under the line down to the bottom given, for a soft fill.</summary>
public StreamGeometry? Fill(double bottom)
{
Flush();
_column = int.MinValue;
var geometry = new StreamGeometry();
bool any = false;
using (var g = geometry.Open())
{
foreach (var line in _lines)
{
if (line.Count < 2)
continue;
g.BeginFigure(new Point(line[0].X, bottom), true);
foreach (var point in line)
g.LineTo(point);
g.LineTo(new Point(line[^1].X, bottom));
g.EndFigure(true);
any = true;
}
}
return any ? geometry : null;
}
public StreamGeometry? Geometry()
{
Flush();
_column = int.MinValue;
var geometry = new StreamGeometry();
bool any = false;
using (var g = geometry.Open())
{
foreach (var line in _lines)
{
if (line.Count < 2)
continue;
g.BeginFigure(line[0], false);
for (int i = 1; i < line.Count; i++)
g.LineTo(line[i]);
g.EndFigure(false);
any = true;
}
}
return any ? geometry : null;
}
}
}

View File

@@ -0,0 +1,353 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The timetable of the user's train, a row a station: what the timetable said and what
/// happened, by the end of the recording read so far. A stop shows the time of arrival and
/// of departure with the delay, how well the train was stopped against the stop point and
/// whether it stood along the platform; a station passed through the time of passing. The
/// station of the moment played is marked; a click goes to the moment the train was there.
/// </summary>
public sealed class TimetablePanel : Control
{
private const double Pad = 12;
private const double HeaderHeight = 50;
private const double RowHeight = 54;
private Recording? _recording;
private double _time;
private int _builtRevision = -1;
private IReadOnlyList<StationProgress> _rows = Array.Empty<StationProgress>();
private Timetable? _timetable;
private int _hover = -1;
public event Action<double>? Seek;
public IBlackBoxStrings Strings { get; set; } = new DefaultBlackBoxStrings();
public TimetablePanel()
{
ClipToBounds = true;
Cursor = new Cursor(StandardCursorType.Hand);
// The stations walked from the keyboard as well: the arrows go up and down the rows,
// Enter goes to the moment as a click does.
Focusable = true;
}
// The row the keyboard stands at; -1 until it is moved, when the station played is meant.
private int _keyRow = -1;
private string? _spoken;
protected override AutomationPeer OnCreateAutomationPeer() =>
new SpokenPeer(this, AutomationControlType.List, () => _spoken ?? RowText(KeyRow), () => Strings["TimetableHelp"]);
private int KeyRow => _keyRow >= 0 && _keyRow < _rows.Count ? _keyRow : Current();
/// <summary>A row as it is read: the station, the times of the timetable, the kilometre and what happened there.</summary>
private string? RowText(int i)
{
if (_timetable is null)
return Strings["TimetableNone"];
if (i < 0 || i >= _rows.Count)
return null;
var row = _rows[i];
var culture = CultureInfo.CurrentCulture;
string planned = row.Row.IsStop
? $"{Minutes(row.Row.Arrival)} – {Minutes(row.Row.Departure)}"
: Minutes(row.Row.Departure);
var parts = new List<string> { StationNames.Display(row.Row.Station), planned };
if (row.Row.Km > 0 || i > 0)
parts.Add($"km {row.Row.Km.ToString("0.0", culture)}");
parts.AddRange(Chips(row, culture).Select(c => c.Text));
return $"{i + 1}/{_rows.Count}. {string.Join(", ", parts)}";
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (_rows.Count == 0)
return;
int at = KeyRow;
int? to = e.Key switch
{
Key.Up => at - 1,
Key.Down => at + 1,
Key.Home => 0,
Key.End => _rows.Count - 1,
_ => null
};
if (e.Key == Key.Enter && at >= 0 && (_rows[at].ArrivedAt ?? _rows[at].DepartedAt) is { } t)
{
Seek?.Invoke(Math.Max(0, t - 5));
e.Handled = true;
return;
}
if (to is not { } row)
return;
_keyRow = Math.Clamp(row, 0, _rows.Count - 1);
string? before = _spoken;
_spoken = RowText(_keyRow);
(ControlAutomationPeer.FromElement(this) as SpokenPeer)?.Told(before, _spoken);
this.BringIntoView(new Rect(0, HeaderHeight + _keyRow * RowHeight, Bounds.Width, RowHeight));
InvalidateVisual();
e.Handled = true;
}
protected override void OnGotFocus(FocusChangedEventArgs e)
{
base.OnGotFocus(e);
_spoken = null;
InvalidateVisual();
}
protected override void OnLostFocus(FocusChangedEventArgs e)
{
base.OnLostFocus(e);
_keyRow = -1;
InvalidateVisual();
}
public Recording? Recording
{
get => _recording;
set
{
_recording = value;
_builtRevision = -1;
Rebuild();
}
}
public double Time
{
get => _time;
set
{
_time = value;
Rebuild();
InvalidateVisual();
}
}
private void Rebuild()
{
if (_recording is not { } recording)
{
_rows = Array.Empty<StationProgress>();
_timetable = null;
InvalidateMeasure();
return;
}
var timetable = recording.TimetableAt(_time);
if (recording.Revision == _builtRevision && ReferenceEquals(timetable, _timetable))
return;
_builtRevision = recording.Revision;
_timetable = timetable;
_rows = StationProgress.Of(recording, _time);
InvalidateMeasure();
InvalidateVisual();
}
protected override Size MeasureOverride(Size availableSize) =>
new(0, _timetable is null ? 80 : HeaderHeight + _rows.Count * RowHeight + Pad);
/// <summary>The row of the station the train was at, or made for, at the moment played.</summary>
private int Current()
{
int current = -1;
for (int i = 0; i < _rows.Count; i++)
{
var row = _rows[i];
double? at = row.ArrivedAt ?? row.DepartedAt;
if (at is { } t && t <= _time + 0.05)
current = i;
}
// Still standing there, or on the way to the next one.
if (current >= 0 && _rows[current].DepartedAt is { } left && left <= _time && current + 1 < _rows.Count)
return current + 1;
return current < 0 ? (_rows.Count > 0 ? 0 : -1) : current;
}
public override void Render(DrawingContext context)
{
var size = Bounds.Size;
var culture = CultureInfo.CurrentCulture;
if (IsFocused)
context.DrawRectangle(null, Palette.FocusPen, new Rect(size).Deflate(1));
if (_timetable is not { } timetable)
{
context.DrawText(MapView.Text(Strings["TimetableNone"], Palette.DimText, 12), new Point(Pad, Pad));
return;
}
// The train: its number and category, from where to where.
var train = MapView.Text($"{timetable.Category} {timetable.Train}".Trim(), Palette.Text, 15, FontWeight.SemiBold);
context.DrawText(train, new Point(Pad, 6));
string relation = string.Format(culture, Strings["Relation"], timetable.From, timetable.To);
if (timetable.Vmax > 0)
relation += $" · {timetable.Vmax:0} km/h";
context.DrawText(MapView.Text(relation, Palette.DimText, 11), new Point(Pad, 6 + train.Height + 1));
int current = Current();
double rail = Pad + 6;
for (int i = 0; i < _rows.Count; i++)
{
double top = HeaderHeight + i * RowHeight;
var row = _rows[i];
if (i == current)
{
context.DrawRectangle(Palette.CardHover, null, new Rect(0, top, size.Width, RowHeight - 1));
context.DrawRectangle(Palette.Accent, null, new Rect(0, top, 2, RowHeight - 1));
}
else if (i == _hover)
context.DrawRectangle(Palette.Faded(Palette.CardHover, 0.6), null, new Rect(0, top, size.Width, RowHeight - 1));
if (IsFocused && i == KeyRow)
context.DrawRectangle(null, Palette.FocusPen, new Rect(1, top + 1, size.Width - 2, RowHeight - 3));
// The line of the route through the stations, a dot each: hollow ahead, filled when done.
var outcome = row.Outcome;
var colour = outcome switch
{
StationOutcome.Missed => Palette.Bad,
StationOutcome.Ahead => Palette.FaintText,
_ => DelayBrush(row.ArrivalDelay ?? row.DepartureDelay)
};
double dotY = top + 15;
if (i + 1 < _rows.Count)
context.DrawLine(new Pen(Palette.Grid, 2), new Point(rail, dotY), new Point(rail, dotY + RowHeight));
bool stop = row.Row.IsStop;
double radius = stop ? 5.5 : 3.5;
context.DrawEllipse(outcome == StationOutcome.Ahead ? Palette.Card : colour, new Pen(colour, 2), new Point(rail, dotY), radius, radius);
// The station and what the timetable said.
double x = rail + 16;
var name = MapView.Text(StationNames.Display(row.Row.Station), outcome == StationOutcome.Ahead ? Palette.DimText : Palette.Text, 13,
stop ? FontWeight.SemiBold : FontWeight.Normal);
context.DrawText(name, new Point(x, dotY - name.Height / 2));
string planned = stop
? $"{Minutes(row.Row.Arrival)} → {Minutes(row.Row.Departure)}"
: Minutes(row.Row.Departure);
var plan = MapView.Text(planned, Palette.DimText, 12);
context.DrawText(plan, new Point(size.Width - Pad - plan.Width, dotY - plan.Height / 2));
if (row.Row.Km > 0 || i > 0)
{
var km = MapView.Text($"km {row.Row.Km:0.0}", Palette.FaintText, 10);
double kmX = size.Width - Pad - plan.Width - 12 - km.Width;
if (kmX > x + name.Width + 8)
context.DrawText(km, new Point(kmX, dotY - km.Height / 2));
}
// What happened there, under it: each part in its colour, on to a second line when long.
double partX = x, partY = top + 25;
bool first = true;
foreach (var (text, brush) in Chips(row, culture))
{
var part = MapView.Text(first ? text : "· " + text, brush, 11);
if (!first && partX + part.Width > size.Width - Pad)
{
partX = x;
partY += 14;
part = MapView.Text(text, brush, 11);
}
context.DrawText(part, new Point(partX, partY));
partX += part.Width + 6;
first = false;
}
}
}
/// <summary>What happened at a station, each part with its colour.</summary>
private IEnumerable<(string Text, IBrush Brush)> Chips(StationProgress row, CultureInfo culture)
{
switch (row.Outcome)
{
case StationOutcome.Ahead:
if (row.Row.Maintenance)
yield return (Strings["TtTechnical"], Palette.FaintText);
yield break;
case StationOutcome.Passed:
yield return (string.Format(culture, Strings["TtPassed"], Clock(row.DepartureClock)), Palette.DimText);
if (row.DepartureDelay is { } passDelay)
yield return (string.Format(culture, Strings["Minutes"], passDelay), DelayBrush(passDelay));
yield break;
}
if (row.ArrivedAt is null)
{
yield return (Strings["TtMissed"], Palette.Bad);
yield break;
}
yield return (string.Format(culture, Strings["TtArrived"], Clock(row.ArrivalClock)), Palette.DimText);
if (row.ArrivalDelay is { } arrival)
yield return (string.Format(culture, Strings["Minutes"], arrival), DelayBrush(arrival));
if (row.Outcome == StationOutcome.Missed)
yield return (Strings["TtLeftEarly"], Palette.Bad);
else if (row.DepartedAt is not null)
{
yield return (string.Format(culture, Strings["TtDeparted"], Clock(row.DepartureClock)), Palette.DimText);
if (row.DepartureDelay is { } departure)
yield return (string.Format(culture, Strings["Minutes"], departure), DelayBrush(departure));
}
else
yield return (Strings["TtStanding"], Palette.Station);
if (row.StopError is { } error)
yield return Math.Abs(error) < 1
? (Strings["TtStopExact"], Palette.Good)
: (string.Format(culture, Strings[error > 0 ? "TtStopShort" : "TtStopPast"], Math.Abs(error)),
Math.Abs(error) <= 5 ? Palette.Good : Math.Abs(error) <= 15 ? Palette.Warn : Palette.Bad);
if (row.OnPlatform is { } along)
yield return along
? (Strings["TtOnPlatform"], Palette.Good)
: (string.Format(culture, Strings["TtOffPlatform"], row.OffPlatform ?? 0), Palette.Bad);
}
private static IBrush DelayBrush(double? minutes) => Palette.Delay(minutes);
private static string Minutes(float minutes) =>
minutes < 0 ? "–" : TimeSpan.FromMinutes(minutes).ToString(@"hh\:mm", CultureInfo.InvariantCulture);
private static string Clock(double? minutes) =>
minutes is { } m ? TimeSpan.FromMinutes(m % 1440).ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture) : "–";
private int RowAt(Point p)
{
int i = (int)Math.Floor((p.Y - HeaderHeight) / RowHeight);
return p.Y >= HeaderHeight && i >= 0 && i < _rows.Count ? i : -1;
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
int hover = RowAt(e.GetPosition(this));
if (hover != _hover)
{
_hover = hover;
InvalidateVisual();
}
}
protected override void OnPointerExited(PointerEventArgs e)
{
base.OnPointerExited(e);
_hover = -1;
InvalidateVisual();
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
int i = RowAt(e.GetPosition(this));
if (i >= 0 && (_rows[i].ArrivedAt ?? _rows[i].DepartedAt) is { } t)
Seek?.Invoke(Math.Max(0, t - 5));
}
}

View File

@@ -0,0 +1,337 @@
using System;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The pieces the window is built of, in one plain look: flat panels side by side, flat
/// buttons, a table of figures and tabs underlined.
/// </summary>
internal static class UiKit
{
/// <summary>The gutter between the panels.</summary>
public const double Gap = 6;
public static readonly CornerRadius Small = new(2);
/// <summary>
/// The theme's accent (the slider, the picked lines, the focus) in the orange of the viewer
/// instead of the system colour, for the window given and everything in it.
/// </summary>
public static void Accent(Control control)
{
// As the starter's App.axaml sets them, for the viewer on its own.
(string Key, string Colour)[] accents =
{
("SystemAccentColor", "#177f00"), ("SystemAccentColorDark1", "#136B00"), ("SystemAccentColorDark2", "#0F5600"),
("SystemAccentColorDark3", "#0B4200"), ("SystemAccentColorLight1", "#2A9A0F"), ("SystemAccentColorLight2", "#41C400"),
("SystemAccentColorLight3", "#5FD42A")
};
foreach (var (key, colour) in accents)
control.Resources[key] = Color.Parse(colour);
control.Resources["AccentFillColorDefaultBrush"] = Palette.AccentFill;
control.Resources["AccentFillColorSecondaryBrush"] = Palette.AccentFillHover;
control.Resources["SystemControlHighlightListAccentLowBrush"] = Palette.AccentFill;
control.Resources["SystemControlHighlightListAccentMediumBrush"] = Palette.AccentFillHover;
control.Resources["ListBoxItemBackgroundSelected"] = Palette.AccentFill;
control.Resources["ListBoxItemBackgroundSelectedPointerOver"] = Palette.AccentFillHover;
control.Resources["ListBoxItemBackgroundSelectedPressed"] = Palette.AccentFill;
control.Resources["ListBoxItemBackgroundPointerOver"] = Palette.CardHover;
}
/// <summary>A panel with its title on a bar, as the group boxes of the starter; what goes right of the title, if anything.</summary>
public static Border Group(string title, Control content, Control? tag = null)
{
var bar = new DockPanel();
if (tag is not null)
{
DockPanel.SetDock(tag, Dock.Right);
tag.VerticalAlignment = VerticalAlignment.Center;
bar.Children.Add(tag);
}
bar.Children.Add(new TextBlock
{
Text = title,
FontSize = 12,
FontWeight = FontWeight.SemiBold,
Foreground = Palette.Text,
TextTrimming = TextTrimming.CharacterEllipsis,
VerticalAlignment = VerticalAlignment.Center
});
var header = new Border
{
Background = Palette.Header,
BorderBrush = Palette.CardBorder,
BorderThickness = new Thickness(0, 0, 0, 1),
Padding = new Thickness(8, 3),
MinHeight = 24,
Child = bar
};
var panel = new DockPanel();
DockPanel.SetDock(header, Dock.Top);
panel.Children.Add(header);
panel.Children.Add(content);
return Frame(panel);
}
/// <summary>A panel in the frame of the starter's group boxes, without a title.</summary>
public static Border Frame(Control content) => new()
{
Background = Palette.Panel,
BorderBrush = Palette.CardBorder,
BorderThickness = new Thickness(1),
CornerRadius = Small,
ClipToBounds = true,
Child = content
};
/// <summary>A flat panel the views sit on.</summary>
public static Border Card(Control content, Thickness? padding = null) => new()
{
Background = Palette.Card,
Padding = padding ?? new Thickness(0),
ClipToBounds = true,
Child = content
};
/// <summary>A button of the toolbar: text on the bar, a lighter ground under the pointer.</summary>
public static Button Button(string text, string? tip = null)
{
var button = new Button
{
Content = text,
Padding = new Thickness(10, 2),
MinHeight = 25,
CornerRadius = Small,
FontSize = 12,
VerticalContentAlignment = VerticalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
if (tip is not null)
ToolTip.SetTip(button, tip);
return button;
}
/// <summary>The button of playing.</summary>
public static Button PlayButton()
{
var button = new Button
{
Width = 32,
Height = 25,
CornerRadius = Small,
Background = Palette.AccentFill,
Padding = new Thickness(0),
BorderThickness = new Thickness(0),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
// As the starter's start button: its green, brighter under the pointer.
Hover(button, Palette.Accent, Brushes.White);
return button;
}
/// <summary>The glyph of play or pause.</summary>
public static Control PlayGlyph(bool playing)
{
var geometry = playing
? Geometry.Parse("M0,0 H4 V12 H0 Z M7,0 H11 V12 H7 Z")
: Geometry.Parse("M1,0 L11,6 L1,12 Z");
return new Avalonia.Controls.Shapes.Path
{
Data = geometry,
Fill = Brushes.White,
Width = 12,
Height = 12,
Stretch = Stretch.None,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
}
/// <summary>A toggle of the toolbar: on, its text takes the accent.</summary>
public static ToggleButton Toggle(string text, string? tip = null)
{
var toggle = new ToggleButton
{
Content = text,
Padding = new Thickness(10, 2),
MinHeight = 25,
CornerRadius = Small,
FontSize = 12,
VerticalContentAlignment = VerticalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
foreach (var state in new[] { "", "PointerOver", "Pressed" })
{
toggle.Resources["ToggleButtonBackgroundChecked" + state] = state == "PointerOver" ? Palette.AccentFillHover : Palette.AccentFill;
toggle.Resources["ToggleButtonForegroundChecked" + state] = Brushes.White;
}
if (tip is not null)
ToolTip.SetTip(toggle, tip);
return toggle;
}
// The theme takes its own colours under the pointer and when pressed, unless the control gives them.
private static void Hover(Control control, IBrush background, IBrush foreground)
{
foreach (var kind in new[] { "Button", "ToggleButton" })
{
control.Resources[kind + "BackgroundPointerOver"] = background;
control.Resources[kind + "BackgroundPressed"] = background;
control.Resources[kind + "ForegroundPointerOver"] = foreground;
control.Resources[kind + "ForegroundPressed"] = foreground;
control.Resources[kind + "BorderBrushPointerOver"] = Brushes.Transparent;
control.Resources[kind + "BorderBrushPressed"] = Brushes.Transparent;
}
}
/// <summary>A line of the table of figures: what it is on the left, its value on the right, a note under it.</summary>
public sealed class Tile : Border
{
private readonly TextBlock _value = new() { FontSize = 12, FontWeight = FontWeight.SemiBold, Foreground = Palette.Text, HorizontalAlignment = HorizontalAlignment.Right };
private readonly TextBlock _sub = new() { FontSize = 11, Foreground = Palette.FaintText, TextTrimming = TextTrimming.CharacterEllipsis };
public Tile(string caption)
{
BorderBrush = Palette.Grid;
BorderThickness = new Thickness(0, 0, 0, 1);
Padding = new Thickness(8, 4);
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), RowDefinitions = new RowDefinitions("Auto,Auto") };
var name = new TextBlock { Text = caption, FontSize = 12, Foreground = Palette.DimText, VerticalAlignment = VerticalAlignment.Center };
Grid.SetColumn(_value, 1);
Grid.SetRow(_sub, 1);
Grid.SetColumnSpan(_sub, 2);
grid.Children.Add(name);
grid.Children.Add(_value);
grid.Children.Add(_sub);
Child = grid;
}
public void Show(string value, string? sub = null, IBrush? brush = null)
{
_value.Text = value;
_value.Foreground = brush ?? Palette.Text;
_sub.Text = sub ?? "";
_sub.IsVisible = !string.IsNullOrEmpty(sub);
}
}
/// <summary>Tabs side by side as the starter's: the one on on the panel's ground, with a bar of the accent on top.</summary>
public sealed class Segmented : Border
{
private readonly StackPanel _row = new() { Orientation = Orientation.Horizontal };
private int _selected = -1;
public event Action<int>? SelectedChanged;
public Segmented(params string[] choices)
{
Background = Palette.Background;
BorderBrush = Palette.CardBorder;
BorderThickness = new Thickness(0, 0, 0, 1);
Child = _row;
// Read as the tabs they are, which of them is picked.
AutomationProperties.SetControlTypeOverride(_row, AutomationControlType.Tab);
AutomationProperties.SetAccessibilityView(_row, AccessibilityView.Content);
for (int i = 0; i < choices.Length; i++)
{
int index = i;
var button = new SegmentButton
{
Content = choices[i],
Padding = new Thickness(14, 3),
MinHeight = 24,
CornerRadius = new CornerRadius(0),
FontSize = 12,
BorderThickness = new Thickness(0, 2, 0, 0)
};
button.Resources["ButtonBackgroundPointerOver"] = Palette.CardHover;
button.Resources["ButtonBackgroundPressed"] = Palette.CardHover;
button.Resources["ButtonForegroundPointerOver"] = Palette.Text;
button.Resources["ButtonForegroundPressed"] = Palette.Text;
button.Click += (_, _) => Selected = index;
_row.Children.Add(button);
}
Selected = 0;
}
public int Selected
{
get => _selected;
set
{
if (value == _selected)
return;
_selected = value;
for (int i = 0; i < _row.Children.Count; i++)
{
var button = (SegmentButton)_row.Children[i];
bool on = i == value;
button.IsOn = on;
var line = on ? Palette.Accent : Brushes.Transparent;
button.Background = on ? Palette.Panel : Brushes.Transparent;
button.BorderBrush = line;
button.Resources["ButtonBorderBrushPointerOver"] = line;
button.Resources["ButtonBorderBrushPressed"] = line;
button.Foreground = on ? Palette.Text : Palette.DimText;
}
SelectedChanged?.Invoke(value);
}
}
}
/// <summary>
/// A choice of <see cref="Segmented"/>: a button to look at, a tab to a screen reader,
/// which says whether it is the one picked.
/// </summary>
private sealed class SegmentButton : Button
{
private bool _on;
protected override Type StyleKeyOverride => typeof(Button);
public bool IsOn
{
get => _on;
set
{
if (_on == value)
return;
_on = value;
(ControlAutomationPeer.FromElement(this) as Peer)?.Told(!value, value);
}
}
public void Pick() => OnClick();
protected override AutomationPeer OnCreateAutomationPeer() => new Peer(this);
private sealed class Peer(SegmentButton owner) : ButtonAutomationPeer(owner), ISelectionItemProvider
{
public void Told(bool before, bool now) =>
RaisePropertyChangedEvent(SelectionItemPatternIdentifiers.IsSelectedProperty, before, now);
protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.TabItem;
public bool IsSelected => owner.IsOn;
public ISelectionProvider? SelectionContainer => null;
public void Select() => owner.Pick();
public void AddToSelection() => owner.Pick();
public void RemoveFromSelection()
{
}
}
}
}

View File

@@ -0,0 +1,331 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Text;
namespace Eu07.BlackBox;
/// <summary>
/// Reads a black box into a <see cref="Recording"/>, as much of it as is there. A file
/// the simulator still writes is read again from where the last read stopped: a record
/// cut short waits for the next read, so a running session can be followed every few
/// seconds without reading it from the start.
/// </summary>
public sealed class BlackBoxReader
{
public static ReadOnlySpan<byte> Magic => "EU07BBX\0"u8;
public const int FormatVersion = 1;
public const int HeaderSize = 12;
public const int RecordHeaderSize = 5;
private long _offset;
public Recording Recording { get; } = new();
/// <summary>Bytes taken so far: the header and the whole records.</summary>
public long Offset => _offset;
/// <summary>Opens the file shared, as the simulator may be writing it, and reads what is new.</summary>
public int ReadMore(string path)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
return ReadMore(stream);
}
/// <summary>Reads the whole records added since the last read. Returns how many were read.</summary>
/// <exception cref="InvalidDataException">Not a black box, or of a version this reader doesn't know.</exception>
public int ReadMore(Stream stream)
{
if (stream.CanSeek)
{
if (stream.Length < _offset)
throw new InvalidDataException("The black box got shorter than what was read of it: it was written anew.");
stream.Seek(_offset, SeekOrigin.Begin);
}
using var added = new MemoryStream();
stream.CopyTo(added);
var bytes = added.GetBuffer().AsSpan(0, (int)added.Length);
int at = 0;
if (_offset == 0)
{
if (bytes.Length < HeaderSize)
return 0;
ReadHeader(bytes[..HeaderSize]);
at = HeaderSize;
}
int read = 0;
while (bytes.Length - at >= RecordHeaderSize)
{
var type = (RecordType)bytes[at];
uint length = BinaryPrimitives.ReadUInt32LittleEndian(bytes.Slice(at + 1, 4));
if (length > int.MaxValue || bytes.Length - at - RecordHeaderSize < length)
break;
var payload = bytes.Slice(at + RecordHeaderSize, (int)length);
try
{
Take(type, new PayloadReader(payload));
}
catch (EndOfStreamException)
{
// Shorter than its type says: passed over, as one of an unknown type is.
Recording.Malformed++;
}
at += RecordHeaderSize + (int)length;
++read;
}
_offset += at;
if (read > 0)
Recording.Changed();
return read;
}
/// <summary>Reads a whole file at once.</summary>
public static Recording Read(string path)
{
var reader = new BlackBoxReader();
reader.ReadMore(path);
return reader.Recording;
}
public static Recording Read(Stream stream)
{
var reader = new BlackBoxReader();
reader.ReadMore(stream);
return reader.Recording;
}
/// <summary>Whether the bytes start as a black box does.</summary>
public static bool LooksLikeBlackBox(ReadOnlySpan<byte> start) => start.Length >= Magic.Length && start[..Magic.Length].SequenceEqual(Magic);
private void ReadHeader(ReadOnlySpan<byte> header)
{
if (!LooksLikeBlackBox(header))
throw new InvalidDataException("Not a black box of the simulator.");
int version = BinaryPrimitives.ReadUInt16LittleEndian(header.Slice(8, 2));
if (version != FormatVersion)
throw new InvalidDataException($"A black box of version {version}, this reader knows version {FormatVersion}.");
Recording.Version = version;
}
private void Take(RecordType type, PayloadReader r)
{
var rec = Recording;
switch (type)
{
case RecordType.Info:
rec.Info = new RecordingInfo(r.Text(), r.Text(), r.U16(), r.U16(), r.F64(), r.Text(), r.Text(),
r.F32(), r.F32(), r.F32());
break;
case RecordType.Track:
{
int index = (int)r.U32();
string name = r.Text();
var kind = (TrackKind)r.U8();
int branch = r.U8();
int category = r.U8();
uint count = r.U32();
if (count > r.Remaining / 12)
throw new EndOfStreamException();
var points = new Vector3[count];
for (int i = 0; i < points.Length; i++)
points[i] = r.Vec3();
rec.AddTrack(new MapTrack(index, name, kind, branch, category, points));
break;
}
case RecordType.Signal:
rec.AddSignal(new MapSignal((int)r.U32(), r.Text(), r.DVec3()));
break;
case RecordType.Vehicle:
rec.AddVehicle(new VehicleInfo((int)r.U32(), r.Text(), r.Text(), r.Text(), r.F32(), r.F32(), r.U8()));
break;
case RecordType.VehicleRemoved:
rec.RemoveVehicle(r.F64(), (int)r.U32());
break;
case RecordType.Cab:
{
var sample = new CabSample(r.F64(), (int)r.U32(), r.DVec3(), r.F32(), r.F32(), r.F32(), (Driver)r.U8(),
(CabFlags)r.U8(), r.I8(), r.I8(), r.I8(), r.F32(), r.F32(), r.F32(), r.F32(),
r.F32(),
new AiReference(r.F32(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32()),
(CabDevices)r.U32(), r.F32(), r.F32(), r.F32(), (Lights)r.U16(), (Lights)r.U16());
// The cab, the train protection and the lateral acceleration came later: a recording
// made before them ends here.
if (r.Remaining >= 6)
sample = sample with { CabEnd = r.I8(), Security = (SecurityFlags)r.U8(), LateralAcceleration = r.F32() };
// What the driver went by and the lights asked for came later still.
if (r.Remaining >= 5)
sample = sample with { Movement = (Movement)r.U8(), LightHintHead = (short)r.U16(), LightHintTail = (short)r.U16() };
// The lamps the vehicles at the ends have, which a pattern is checked against, later again.
if (r.Remaining >= 4)
sample = sample with { EquippedHead = (Lights)r.U16(), EquippedTail = (Lights)r.U16() };
// What drives it, the doors' permits and the rest, later again; the arguments are read in their order.
if (r.Remaining >= 54)
sample = sample with
{
Extra = new CabExtra((EngineKind)r.U8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32(),
r.F32(), r.F32(), r.F32(), r.I8(), r.U8(), r.U8(), r.F32(), r.F32(), r.F32(), r.F32())
};
rec.AddCab(sample);
break;
}
case RecordType.StopPoint:
{
var point = new MapStopPoint((int)r.U32(), r.Text(), r.DVec3(), r.F32(), r.F32());
// The heading came later: a recording made before it ends here.
if (r.Remaining >= 4)
point = point with { Heading = r.F32() };
rec.AddStopPoint(point);
break;
}
case RecordType.HornPoint:
rec.AddHornPoint(new MapHornPoint((int)r.U32(), r.Text(), r.DVec3(), r.F32(), r.F32()));
break;
case RecordType.Timetable:
{
double time = r.F64();
int vehicle = (int)r.U32();
string train = r.Text(), category = r.Text(), from = r.Text(), to = r.Text();
float vmax = r.F32();
uint count = r.U32();
// A row holds at least its empty name, four numbers and a flag.
if (count > r.Remaining / 18)
throw new EndOfStreamException();
var rows = new TimetableRow[count];
for (int i = 0; i < rows.Length; i++)
rows[i] = new TimetableRow(r.Text(), r.F32(), r.F32(), r.F32(), r.F32(), r.U8() != 0);
rec.AddTimetable(new Timetable(time, vehicle, train, category, from, to, vmax, rows));
break;
}
case RecordType.Station:
rec.AddStation(new StationEvent(r.F64(), (int)r.U32(), (StationKind)r.U8(), r.U16(), r.Text(), r.DVec3(),
r.F32(), r.F32(), r.F32(), r.F32(), r.F32(), r.F32()));
break;
case RecordType.Camera:
rec.AddCamera(new CameraState(r.F64(), (CameraMode)r.U8(), r.U8(), (int)r.U32(), r.DVec3(), r.F32(), r.F32()));
break;
case RecordType.Coupling:
rec.AddCoupling(new CouplingChange(r.F64(), (int)r.U32(), r.U8(), (int)r.U32(), r.U8(), (CouplingFlags)r.U8(),
(CouplingFlags)r.U8(), (int)r.U32(), r.DVec3()));
break;
case RecordType.HornRequest:
rec.AddHornRequest(new HornRequest(r.F64(), (int)r.U32(), r.F32(), r.F32(), r.DVec3()));
break;
case RecordType.Vehicles:
{
double time = r.F64();
bool keyframe = r.U8() != 0;
uint count = r.U32();
if (count > r.Remaining / 25)
throw new EndOfStreamException();
var states = new VehicleState[count];
for (int i = 0; i < states.Length; i++)
states[i] = new VehicleState((int)r.U32(), r.Vec3(), r.F32(), r.F32(), (Driver)r.U8());
rec.AddLook(new VehicleLook(time, keyframe, states));
break;
}
case RecordType.SwitchState:
rec.AddSwitch(new SwitchChange(r.F64(), (int)r.U32(), r.U8()));
break;
case RecordType.SignalAspect:
rec.AddAspect(new AspectChange(r.F64(), (int)r.U32(), r.F32(), r.F32(), r.Text()));
break;
case RecordType.Command:
{
double time = r.F64();
int vehicle = (int)r.U32();
bool pressed = r.U8() != 0;
double param1 = r.F64(), param2 = r.F64();
rec.AddCommand(new CommandEntry(time, vehicle, pressed, param1, param2, r.Text()));
break;
}
case RecordType.DriverChange:
rec.AddDriverChange(new DriverChange(r.F64(), (int)r.U32(), (Driver)r.U8()));
break;
case RecordType.SignalPassed:
{
double time = r.F64();
int vehicle = (int)r.U32();
int signal = unchecked((int)r.U32());
rec.AddPassing(new SignalPassing(time, vehicle, signal, r.Text(), r.DVec3(), r.F32(), r.F32(), r.F32(),
r.F32(), (PassingFlags)r.U8()));
break;
}
case RecordType.UserVehicle:
{
var change = new UserVehicleChange(r.F64(), (int)r.U32(), r.U8() != 0);
if (r.Remaining >= 1)
change = change with { CabEnd = r.I8() };
rec.AddUserVehicle(change);
break;
}
case RecordType.Clock:
rec.AddClock(new ClockEntry(r.F64(), r.U16(), r.U16(), r.F64()));
break;
case RecordType.End:
rec.EndTime = r.F64();
break;
default:
// A type of a later version: its length lets it be passed over.
rec.Unknown++;
break;
}
}
/// <summary>The fields of a record in the order they come, little-endian. A field past the end throws.</summary>
private ref struct PayloadReader
{
private readonly ReadOnlySpan<byte> _bytes;
private int _at;
public PayloadReader(ReadOnlySpan<byte> bytes)
{
_bytes = bytes;
_at = 0;
}
public int Remaining => _bytes.Length - _at;
private ReadOnlySpan<byte> Take(int count)
{
if (Remaining < count)
throw new EndOfStreamException();
var span = _bytes.Slice(_at, count);
_at += count;
return span;
}
public byte U8() => Take(1)[0];
public sbyte I8() => unchecked((sbyte)Take(1)[0]);
public ushort U16() => BinaryPrimitives.ReadUInt16LittleEndian(Take(2));
public uint U32() => BinaryPrimitives.ReadUInt32LittleEndian(Take(4));
public float F32() => BinaryPrimitives.ReadSingleLittleEndian(Take(4));
public double F64() => BinaryPrimitives.ReadDoubleLittleEndian(Take(8));
public Vector3 Vec3() => new(F32(), F32(), F32());
public Position DVec3() => new(F64(), F64(), F64());
/// <summary>UTF-8 after its length in 7 bit groups, low first, as BinaryWriter writes a string.</summary>
public string Text()
{
int length = 0;
for (int shift = 0; ; shift += 7)
{
if (shift > 28)
throw new EndOfStreamException();
byte b = U8();
length |= (b & 0x7f) << shift;
if (b < 0x80)
break;
}
if (length < 0)
throw new EndOfStreamException();
return length == 0 ? "" : Encoding.UTF8.GetString(Take(length));
}
}
}

View File

@@ -0,0 +1,196 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Eu07.BlackBox;
/// <summary>How a sample of the user's train stands against what the AI would have done.</summary>
public enum SpeedJudgement
{
/// <summary>Nothing to set it against: the consist not started, or the user out of the cab.</summary>
NoData,
/// <summary>The AI drove.</summary>
Autopilot,
/// <summary>At most the speed the AI would hold.</summary>
Within,
/// <summary>Faster, by no more than the tolerance.</summary>
Slightly,
/// <summary>Faster by more than the tolerance.</summary>
Over
}
/// <summary>What the user's driving came to, set against the AI's.</summary>
public sealed record DrivingSummary(
double Duration,
double DrivenSeconds,
double AutopilotSeconds,
double DistanceKm,
float MaxSpeedKmh,
double OverAiSeconds,
double WellOverAiSeconds,
float MaxOverAiKmh,
double MaxOverAiAt,
int SignalsPassed,
IReadOnlyList<SignalPassing> PassedAtDanger,
int Commands,
int AutopilotSwitches,
float MaxAcceleration,
float MaxDeceleration,
float MaxLateralAcceleration,
int Stops,
int StopsMissed,
double? MaxDelayMinutes,
int HornPoints,
int HornsMissed,
int SecurityBrakings)
{
/// <summary>The largest delay the user's train left a station or passed it with [min], null without any.</summary>
public double? MaxDepartureDelayMinutes { get; init; }
/// <summary>How long the train moved with its light signals known to be right or wrong [s].</summary>
public double LightsJudgedSeconds { get; init; }
/// <summary>How long of that its head or its tail showed other signals than it was to [s].</summary>
public double WrongLightsSeconds { get; init; }
/// <summary>Each stretch the train moved with the wrong signals, as they were.</summary>
public IReadOnlyList<LightsFault> LightsFaults { get; init; } = Array.Empty<LightsFault>();
/// <summary>The stops where the train did not fit along the platform, and how far its tail stood off it [m].</summary>
public IReadOnlyList<(string Station, double Metres)> OffPlatform { get; init; } = Array.Empty<(string, double)>();
/// <summary>[km/h] over the speed of the AI before it counts as well over.</summary>
public const float DefaultTolerance = 5f;
/// <summary>
/// The speeds are whole km/h for the AI and the needle of the user's train shakes:
/// half a km/h over is still within.
/// </summary>
private const float Rounding = 0.5f;
public static SpeedJudgement Judge(CabSample sample, float tolerance = DefaultTolerance)
{
if (sample.Driving == Driver.Ai)
return SpeedJudgement.Autopilot;
if (!sample.AiValid || sample.Driving != Driver.Human)
return SpeedJudgement.NoData;
float over = sample.AbsSpeedKmh - sample.Ai.TargetKmh;
return over <= Rounding ? SpeedJudgement.Within : over <= tolerance ? SpeedJudgement.Slightly : SpeedJudgement.Over;
}
internal static DrivingSummary Of(Recording recording, float tolerance)
{
var cab = recording.Cab;
double driven = 0, autopilot = 0, distance = 0, over = 0, wellOver = 0, maxOverAt = 0;
float maxSpeed = 0, maxOver = 0, maxAcceleration = 0, maxDeceleration = 0, maxLateral = 0;
// The accelerations over half a second: a sample alone jumps with each jolt of the couplers.
var window = new Queue<(float Along, float Across)>();
float sumAlong = 0, sumAcross = 0;
double lightsJudged = 0, lightsWrong = 0;
var faults = new List<LightsFault>();
// A step longer than this is a gap in the samples, not driving.
double gap = (recording.Info is { CabInterval: > 0 } info ? info.CabInterval : 0.1) * 5;
for (int i = 1; i < cab.Count; i++)
{
var before = cab[i - 1];
var sample = cab[i];
double step = sample.Time - before.Time;
if (step <= 0 || step > gap || sample.Vehicle != before.Vehicle)
{
window.Clear();
sumAlong = sumAcross = 0;
continue;
}
distance += (before.AbsSpeedKmh + sample.AbsSpeedKmh) / 2 / 3.6 * step / 1000;
window.Enqueue((sample.Acceleration, sample.LateralAcceleration));
sumAlong += sample.Acceleration;
sumAcross += sample.LateralAcceleration;
if (window.Count > 5)
{
var (along, across) = window.Dequeue();
sumAlong -= along;
sumAcross -= across;
}
if (window.Count == 5 && sample.AbsSpeedKmh > 1)
{
maxAcceleration = Math.Max(maxAcceleration, sumAlong / 5);
maxDeceleration = Math.Max(maxDeceleration, -sumAlong / 5);
maxLateral = Math.Max(maxLateral, Math.Abs(sumAcross / 5));
}
maxSpeed = Math.Max(maxSpeed, sample.AbsSpeedKmh);
if (sample.Driving == Driver.Ai)
autopilot += step;
else if (sample.Driving == Driver.Human && sample.AbsSpeedKmh > Rounding)
driven += step;
// the light signals at both ends, while the user drives the train and it moves: the autopilot's are its own
if (sample.Driving == Driver.Human && sample.AbsSpeedKmh > 1 &&
HeadCodes.HeadRight(sample) is { } headRight && HeadCodes.TailRight(sample) is { } tailRight)
{
lightsJudged += step;
if (!headRight || !tailRight)
{
lightsWrong += step;
var fault = new LightsFault(before.Time, sample.Time, HeadCodes.Of(sample.LightsHead), HeadCodes.RequiredHead(sample)!.Value,
!headRight, HeadCodes.Of(sample.LightsTail), HeadCodes.RequiredTail(sample)!.Value, !tailRight);
if (faults.Count > 0 && faults[^1].SameAs(fault) && fault.Start - faults[^1].End < 2)
faults[^1] = faults[^1] with { End = sample.Time };
else
faults.Add(fault);
}
}
var judgement = Judge(sample, tolerance);
if (judgement is SpeedJudgement.Slightly or SpeedJudgement.Over)
over += step;
if (judgement == SpeedJudgement.Over)
wellOver += step;
if (judgement is SpeedJudgement.Slightly or SpeedJudgement.Over)
{
float by = sample.AbsSpeedKmh - sample.Ai.TargetKmh;
if (by > maxOver)
{
maxOver = by;
maxOverAt = sample.Time;
}
}
}
var passed = recording.UserPassings().ToList();
int switches = recording.DriverChanges.Count(change =>
recording.CabAt(change.Time + 0.5) is { } s && s.Vehicle == change.Vehicle);
// Every timetable the user's train had, as one going on from another at a terminus.
var stations = recording.Timetables.SelectMany(timetable => StationProgress.Of(recording, timetable)).ToList();
// the largest delay at any station, coming to it or leaving it
var delays = stations.SelectMany(s => new[] { s.ArrivalDelay, s.DepartureDelay }).OfType<double>().ToList();
var departures = stations.Select(s => s.DepartureDelay).OfType<double>().ToList();
var offPlatform = stations.Where(s => s.OnPlatform == false)
.Select(s => (StationNames.Display(s.Row.Station), s.OffPlatform ?? 0))
.ToList();
var horns = recording.UserHornChecks().ToList();
return new DrivingSummary(recording.Duration, driven, autopilot, distance, maxSpeed, over, wellOver, maxOver,
maxOverAt, passed.Count, passed.Where(p => p.AtDanger).ToList(),
recording.UserCommands().Count(), switches, maxAcceleration, maxDeceleration, maxLateral,
stations.Count(s => s.Outcome == StationOutcome.Stopped),
stations.Count(s => s.Outcome == StationOutcome.Missed),
delays.Count > 0 ? delays.Max() : null,
horns.Count, horns.Count(h => !h.Sounded), recording.SecurityBrakings().Count)
{
MaxDepartureDelayMinutes = departures.Count > 0 ? departures.Max() : null,
LightsJudgedSeconds = lightsJudged,
WrongLightsSeconds = lightsWrong,
LightsFaults = faults,
OffPlatform = offPlatform
};
}
}
/// <summary>A stretch the user's train moved with other light signals than it was to show, at its head and its tail.</summary>
public sealed record LightsFault(double Start, double End, HeadCode Head, HeadCode HeadRequired, bool HeadWrong,
HeadCode Tail, HeadCode TailRequired, bool TailWrong)
{
public bool SameAs(LightsFault other) =>
Head == other.Head && HeadRequired == other.HeadRequired && HeadWrong == other.HeadWrong &&
Tail == other.Tail && TailRequired == other.TailRequired && TailWrong == other.TailWrong;
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Reads the black box the simulator writes to physicslog/*.blackbox. Only the
base library: the starter, the viewer and any other program can use it, and
it goes through NativeAOT and trimming as they do. -->
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<IsAotCompatible>true</IsAotCompatible>
<IsTrimmable>true</IsTrimmable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<RootNamespace>Eu07.BlackBox</RootNamespace>
</PropertyGroup>
</Project>

167
Eu07.BlackBox/HeadCodes.cs Normal file
View File

@@ -0,0 +1,167 @@
using System;
namespace Eu07.BlackBox;
/// <summary>What the driver of the user's train went by: the lights it is to show depend on it.</summary>
public enum Movement : byte
{
/// <summary>No driver, or standing by.</summary>
Other = 0,
/// <summary>A train run: Pc 1 or Pc 2 at the head, Pc 5 at the tail.</summary>
Train = 1,
/// <summary>Shunting: Tb 1 at both ends.</summary>
Shunting = 2,
/// <summary>A recording made before it was written.</summary>
Unknown = 0xFF
}
/// <summary>The light signals at an end of a train.</summary>
public enum HeadCode
{
Off,
/// <summary>The head of a train: both headlights and the upper one.</summary>
Pc1,
/// <summary>The head of a train on the wrong track: the left red marker, the right headlight and the upper one.</summary>
Pc2,
/// <summary>The tail of a train: both red markers.</summary>
Pc5,
/// <summary>Shunting: one headlight.</summary>
Tb1,
/// <summary>Any other pattern.</summary>
Other
}
/// <summary>The light signals a train shows and those it is to show, as the simulator's driver sets them.</summary>
public static class HeadCodes
{
private const Lights Signals = Lights.HeadlightLeft | Lights.RedMarkerLeft | Lights.HeadlightUpper | Lights.HeadlightRight |
Lights.RedMarkerRight | Lights.RearEndSignals;
/// <summary>The signal the lamps given show; the high beams and the auxiliary lamps tell nothing.</summary>
public static HeadCode Of(Lights lights)
{
var lit = lights & Signals;
if ((lit & Lights.RearEndSignals) != 0)
lit = (lit & ~Lights.RearEndSignals) | Lights.RedMarkerLeft | Lights.RedMarkerRight;
return lit switch
{
Lights.None => HeadCode.Off,
Lights.HeadlightLeft | Lights.HeadlightRight | Lights.HeadlightUpper => HeadCode.Pc1,
Lights.RedMarkerLeft | Lights.HeadlightRight | Lights.HeadlightUpper => HeadCode.Pc2,
Lights.RedMarkerLeft | Lights.RedMarkerRight => HeadCode.Pc5,
Lights.HeadlightLeft or Lights.HeadlightRight => HeadCode.Tb1,
_ => HeadCode.Other
};
}
/// <summary>The signal the head of the train is to show, null when nothing tells it.</summary>
public static HeadCode? RequiredHead(CabSample sample) => sample.Movement switch
{
Movement.Train => sample.LightHintHead < 0 ? HeadCode.Pc1 : Of((Lights)sample.LightHintHead),
Movement.Shunting => HeadCode.Tb1,
_ => null
};
/// <summary>The signal the tail of the train is to show, null when nothing tells it.</summary>
public static HeadCode? RequiredTail(CabSample sample) => sample.Movement switch
{
Movement.Train => sample.LightHintTail < 0 ? HeadCode.Pc5 : Of((Lights)sample.LightHintTail),
Movement.Shunting => HeadCode.Tb1,
_ => null
};
/// <summary>Whether the head of the train showed what it was to; null when nothing tells it.</summary>
public static bool? HeadRight(CabSample sample) => NoLamps(sample.EquippedHead) ? null : sample.Movement switch
{
Movement.Train => Meets(sample.LightsHead, sample.EquippedHead, sample.LightHintHead, HeadCode.Pc1),
Movement.Shunting => Shows(HeadCode.Tb1, sample.LightsHead, sample.EquippedHead),
_ => null
};
/// <summary>Whether the tail of the train showed what it was to; null when nothing tells it.</summary>
public static bool? TailRight(CabSample sample) => NoLamps(sample.EquippedTail) ? null : sample.Movement switch
{
Movement.Train => Meets(sample.LightsTail, sample.EquippedTail, sample.LightHintTail, HeadCode.Pc5),
Movement.Shunting => Shows(HeadCode.Tb1, sample.LightsTail, sample.EquippedTail),
_ => null
};
/// <summary>
/// An end with no lamp at all, a draisine's: the simulator still asks it for a signal it can't show, so it
/// is not judged. A recording made before the lamps were written can't tell.
/// </summary>
public static bool NoLamps(Lights? equipped) => equipped == Lights.None;
/// <summary>Whether both ends showed what they were to; null when nothing tells it.</summary>
public static bool? Right(CabSample sample) =>
HeadRight(sample) is { } head && TailRight(sample) is { } tail ? head && tail : null;
private const Lights HighBeams = Lights.HighBeamLeft | Lights.HighBeamRight;
private const Lights Auxiliary = Lights.AuxiliaryLeft | Lights.AuxiliaryRight;
// the pattern asked for at an end, the usual one when none is: the driver sets one asked for as it is
private static bool Meets(Lights lit, Lights? equipped, short hint, HeadCode usual)
{
if (hint < 0)
return Shows(usual, lit, equipped);
var pattern = (Lights)hint;
if (usual == HeadCode.Pc1 && pattern == (Lights.RedMarkerLeft | Lights.HeadlightRight | Lights.HeadlightUpper))
return Shows(HeadCode.Pc2, lit, equipped);
// a recording made before the lamps were written: the signal the pattern shows, as before
return equipped is { } lamps ? (lit & ~HighBeams) == (pattern & lamps) : Of(lit) == Of(pattern);
}
/// <summary>
/// Whether the lamps lit at an end show the signal, as the simulator's driver checks it against the lamps
/// the vehicle has there: a vehicle without the upper headlight shows Pc 1 with the two others, one with
/// auxiliary lamps may show them instead, and one with no lamps for it the rear-end signals. A recording
/// made before the lamps were written has the pattern alone. The high beams tell nothing.
/// </summary>
public static bool Shows(HeadCode code, Lights lit, Lights? equipped)
{
if (equipped is not { } lamps)
return Of(lit) == code;
lit &= ~HighBeams;
bool auxiliary = (lamps & Auxiliary) != 0;
switch (code)
{
case HeadCode.Pc1:
{
var pattern = lamps & (Lights.HeadlightLeft | Lights.HeadlightRight | Lights.HeadlightUpper);
var fallback = lamps & (Auxiliary | Lights.HeadlightUpper);
return (pattern != 0 && lit == pattern) || (auxiliary && lit == fallback) ||
(pattern == 0 && fallback == 0 && lit == Lights.RearEndSignals);
}
case HeadCode.Pc2:
{
var pattern = lamps & (Lights.RedMarkerLeft | Lights.HeadlightRight | Lights.HeadlightUpper);
var fallback = lamps & (Lights.RedMarkerLeft | Lights.AuxiliaryRight | Lights.HeadlightUpper);
return lit == pattern || (auxiliary && lit == fallback);
}
case HeadCode.Pc5:
{
var pattern = lamps & (Lights.RedMarkerLeft | Lights.RedMarkerRight);
var fallback = lamps & Lights.RearEndSignals;
return (pattern != 0 && lit == pattern) || (fallback != 0 && lit == fallback);
}
case HeadCode.Tb1:
// one headlight, of those there are
return lit == (lamps & Lights.HeadlightLeft) || lit == (lamps & Lights.HeadlightRight);
case HeadCode.Off:
return lit == Lights.None;
default:
return false;
}
}
/// <summary>The name of a signal as the rules give it.</summary>
public static string Name(HeadCode code) => code switch
{
HeadCode.Pc1 => "Pc 1",
HeadCode.Pc2 => "Pc 2",
HeadCode.Pc5 => "Pc 5",
HeadCode.Tb1 => "Tb 1",
HeadCode.Off => "—",
_ => "?"
};
}

538
Eu07.BlackBox/Recording.cs Normal file
View File

@@ -0,0 +1,538 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace Eu07.BlackBox;
/// <summary>A span of time, start included, end not.</summary>
public readonly record struct TimeSpanRange(double Start, double End)
{
public double Length => End - Start;
public bool Contains(double t) => t >= Start && t < End;
}
/// <summary>
/// What a black box holds, as far as it has been read: the map, the vehicles and what
/// happened to them over the time of the recording, which runs from 0 in seconds of
/// simulation. The lists grow as more of a file still written is read; the queries
/// answer for any moment of the time read so far.
/// </summary>
public sealed class Recording
{
private readonly List<MapTrack> _tracks = new();
private readonly Dictionary<int, List<MapTrack>> _trackIndex = new();
private readonly List<MapSignal> _signals = new();
private readonly Dictionary<int, MapSignal> _signalIndex = new();
private readonly Dictionary<int, VehicleInfo> _vehicles = new();
private readonly List<CabSample> _cab = new();
private readonly List<VehicleLook> _looks = new();
private readonly Dictionary<int, List<(double Time, VehicleState State)>> _history = new();
private readonly List<SwitchChange> _switches = new();
private readonly Dictionary<int, List<SwitchChange>> _switchIndex = new();
private readonly List<AspectChange> _aspects = new();
private readonly Dictionary<int, List<AspectChange>> _aspectIndex = new();
private readonly List<CommandEntry> _commands = new();
private readonly List<DriverChange> _driverChanges = new();
private readonly List<SignalPassing> _passings = new();
private readonly List<UserVehicleChange> _userVehicles = new();
private readonly List<ClockEntry> _clocks = new();
private readonly List<MapStopPoint> _stopPoints = new();
private readonly List<MapHornPoint> _hornPoints = new();
private readonly List<Timetable> _timetables = new();
private readonly List<StationEvent> _stations = new();
private readonly List<HornRequest> _hornRequests = new();
private readonly List<CameraState> _cameras = new();
private readonly List<CouplingChange> _couplings = new();
private double _lastTime;
public int Version { get; internal set; }
public RecordingInfo? Info { get; internal set; }
/// <summary>The time of the end record: null while the simulator still writes, or if it didn't end the recording.</summary>
public double? EndTime { get; internal set; }
public bool Complete => EndTime is not null;
/// <summary>Records of types this reader doesn't know, passed over.</summary>
public int Unknown { get; internal set; }
/// <summary>Records shorter than their type says, passed over.</summary>
public int Malformed { get; internal set; }
/// <summary>Goes up with every read that added something, for views to tell they have to look again.</summary>
public int Revision { get; private set; }
public IReadOnlyList<MapTrack> Tracks => _tracks;
public IReadOnlyList<MapSignal> Signals => _signals;
public IReadOnlyDictionary<int, VehicleInfo> Vehicles => _vehicles;
public IReadOnlyList<CabSample> Cab => _cab;
public IReadOnlyList<VehicleLook> Looks => _looks;
public IReadOnlyList<SwitchChange> Switches => _switches;
public IReadOnlyList<AspectChange> Aspects => _aspects;
public IReadOnlyList<CommandEntry> Commands => _commands;
public IReadOnlyList<DriverChange> DriverChanges => _driverChanges;
public IReadOnlyList<SignalPassing> Passings => _passings;
public IReadOnlyList<UserVehicleChange> UserVehicles => _userVehicles;
public IReadOnlyList<ClockEntry> Clocks => _clocks;
public IReadOnlyList<MapStopPoint> StopPoints => _stopPoints;
public IReadOnlyList<MapHornPoint> HornPoints => _hornPoints;
public IReadOnlyList<Timetable> Timetables => _timetables;
public IReadOnlyList<StationEvent> Stations => _stations;
public IReadOnlyList<HornRequest> HornRequests => _hornRequests;
public IReadOnlyList<CameraState> Cameras => _cameras;
public IReadOnlyList<CouplingChange> Couplings => _couplings;
/// <summary>The time the recording covers so far.</summary>
public double Duration => Math.Max(EndTime ?? 0, _lastTime);
/// <summary>The seconds between two looks at the vehicles.</summary>
public double LookInterval => Info is { VehiclesInterval: > 0 } info ? info.VehiclesInterval : 1.0;
// ----- filled by the reader -----
internal void Changed()
{
++Revision;
_memo.Clear();
_consists.Clear();
}
// What the questions about the user's train worked out, kept until a read adds something: the views ask them every frame.
private readonly Dictionary<object, object> _memo = new();
private readonly Dictionary<(int Vehicle, int Coupling), IReadOnlySet<int>> _consists = new();
private static readonly object UserStationsKey = new(), UserPassingsKey = new(), UserHornChecksKey = new(), UserCouplingsKey = new();
/// <summary>What make gives, worked out once until the recording changes.</summary>
internal T Memo<T>(object key, Func<T> make) where T : class
{
if (_memo.TryGetValue(key, out var kept))
return (T)kept;
var made = make();
_memo[key] = made;
return made;
}
private void Saw(double time) => _lastTime = Math.Max(_lastTime, time);
internal void AddTrack(MapTrack track)
{
_tracks.Add(track);
if (!_trackIndex.TryGetValue(track.Index, out var ways))
_trackIndex[track.Index] = ways = new List<MapTrack>(1);
ways.Add(track);
}
internal void AddSignal(MapSignal signal)
{
_signals.Add(signal);
_signalIndex[signal.Index] = signal;
}
internal void AddVehicle(VehicleInfo vehicle) => _vehicles[vehicle.Id] = vehicle;
internal void RemoveVehicle(double time, int id)
{
Saw(time);
if (_vehicles.TryGetValue(id, out var vehicle))
vehicle.RemovedAt = time;
}
internal void AddCab(CabSample sample)
{
Saw(sample.Time);
_cab.Add(sample);
}
internal void AddLook(VehicleLook look)
{
Saw(look.Time);
_looks.Add(look);
foreach (var state in look.States)
{
if (!_history.TryGetValue(state.Id, out var history))
_history[state.Id] = history = new List<(double, VehicleState)>();
history.Add((look.Time, state));
}
}
internal void AddSwitch(SwitchChange change)
{
Saw(change.Time);
_switches.Add(change);
if (!_switchIndex.TryGetValue(change.Track, out var list))
_switchIndex[change.Track] = list = new List<SwitchChange>();
list.Add(change);
}
internal void AddAspect(AspectChange change)
{
Saw(change.Time);
_aspects.Add(change);
if (!_aspectIndex.TryGetValue(change.Signal, out var list))
_aspectIndex[change.Signal] = list = new List<AspectChange>();
list.Add(change);
}
internal void AddCommand(CommandEntry command)
{
Saw(command.Time);
_commands.Add(command);
}
internal void AddDriverChange(DriverChange change)
{
Saw(change.Time);
_driverChanges.Add(change);
}
internal void AddPassing(SignalPassing passing)
{
Saw(passing.Time);
_passings.Add(passing);
}
internal void AddUserVehicle(UserVehicleChange change)
{
Saw(change.Time);
_userVehicles.Add(change);
}
internal void AddClock(ClockEntry clock)
{
Saw(clock.Time);
_clocks.Add(clock);
}
internal void AddStopPoint(MapStopPoint point) => _stopPoints.Add(point);
internal void AddHornPoint(MapHornPoint point) => _hornPoints.Add(point);
internal void AddTimetable(Timetable timetable)
{
Saw(timetable.Time);
_timetables.Add(timetable);
}
internal void AddStation(StationEvent station)
{
Saw(station.Time);
_stations.Add(station);
}
internal void AddCamera(CameraState camera)
{
Saw(camera.Time);
_cameras.Add(camera);
}
internal void AddCoupling(CouplingChange change)
{
Saw(change.Time);
_couplings.Add(change);
}
internal void AddHornRequest(HornRequest request)
{
Saw(request.Time);
_hornRequests.Add(request);
}
// ----- queries -----
public IReadOnlyList<MapTrack> TrackWays(int index) =>
_trackIndex.TryGetValue(index, out var ways) ? ways : Array.Empty<MapTrack>();
public MapSignal? Signal(int index) => _signalIndex.GetValueOrDefault(index);
public VehicleInfo? Vehicle(int id) => _vehicles.GetValueOrDefault(id);
/// <summary>The last of a list sorted by time at or before t: -1 if none is.</summary>
private static int LastAtOrBefore<T>(IReadOnlyList<T> list, double t, Func<T, double> time)
{
int low = 0, high = list.Count - 1, found = -1;
while (low <= high)
{
int middle = low + (high - low) / 2;
if (time(list[middle]) <= t)
{
found = middle;
low = middle + 1;
}
else
high = middle - 1;
}
return found;
}
/// <summary>The index of the sample of the user's train at or before t, -1 before the first.</summary>
public int CabIndexAt(double t) => LastAtOrBefore(_cab, t, s => s.Time);
/// <summary>The sample of the user's train at or before t.</summary>
public CabSample? CabAt(double t) => CabIndexAt(t) is var i and >= 0 ? _cab[i] : null;
/// <summary>
/// Where the user's train was at t, between the two samples around it. Null before
/// the first sample, and in a gap: the user out of any vehicle.
/// </summary>
public Position? CabPositionAt(double t)
{
int i = CabIndexAt(t);
if (i < 0)
return null;
var before = _cab[i];
if (i + 1 >= _cab.Count)
return t - before.Time <= 1.0 ? before.Position : null;
var after = _cab[i + 1];
if (after.Vehicle != before.Vehicle || after.Time - before.Time > 1.0)
return t - before.Time <= 1.0 ? before.Position : null;
double f = (t - before.Time) / Math.Max(1e-9, after.Time - before.Time);
return Position.Lerp(before.Position, after.Position, Math.Clamp(f, 0, 1));
}
/// <summary>
/// Every vehicle on the scenery at t, where it was. A vehicle is listed only when it
/// moved, so between two listings far apart it stood at the first place until the
/// look before the second.
/// </summary>
public IReadOnlyList<VehicleState> VehiclesAt(double t)
{
var states = new List<VehicleState>(_history.Count);
double interval = LookInterval;
foreach (var (id, history) in _history)
{
if (_vehicles.TryGetValue(id, out var info) && info.RemovedAt is { } removed && removed <= t)
continue;
int i = LastAtOrBefore(history, t, entry => entry.Time);
if (i < 0)
continue;
var (time, state) = history[i];
if (i + 1 < history.Count)
{
var (nextTime, next) = history[i + 1];
double from = Math.Max(time, nextTime - interval * 1.5);
if (t > from)
state = Lerp(state, next, (t - from) / Math.Max(1e-9, nextTime - from));
}
states.Add(state);
}
return states;
}
private static VehicleState Lerp(VehicleState a, VehicleState b, double f)
{
float k = (float)Math.Clamp(f, 0, 1);
float turn = b.Heading - a.Heading;
while (turn > MathF.PI) turn -= 2 * MathF.PI;
while (turn < -MathF.PI) turn += 2 * MathF.PI;
return a with
{
Position = Vector3.Lerp(a.Position, b.Position, k),
Heading = a.Heading + turn * k,
SpeedKmh = a.SpeedKmh + (b.SpeedKmh - a.SpeedKmh) * k,
Driving = k < 0.5f ? a.Driving : b.Driving
};
}
/// <summary>The aspect a signal showed at t, null before it was first seen.</summary>
public AspectChange? AspectAt(int signal, double t) =>
_aspectIndex.TryGetValue(signal, out var list) && LastAtOrBefore(list, t, c => c.Time) is var i and >= 0
? list[i]
: null;
/// <summary>The position of a switch at t, -1 if unknown.</summary>
public int SwitchAt(int track, double t) =>
_switchIndex.TryGetValue(track, out var list) && LastAtOrBefore(list, t, c => c.Time) is var i and >= 0
? list[i].State
: -1;
/// <summary>The time of day of the simulation at t.</summary>
public TimeSpan ClockAt(double t)
{
int i = LastAtOrBefore(_clocks, t, c => c.Time);
double second = i >= 0
? _clocks[i].SecondOfDay + (t - _clocks[i].Time)
: (Info?.SecondOfDay ?? 0) + t;
second %= 86400;
if (second < 0)
second += 86400;
return TimeSpan.FromSeconds(second);
}
/// <summary>The vehicle the user was in at t, and whether in its cab; null before it was known.</summary>
public UserVehicleChange? UserVehicleAt(double t) =>
LastAtOrBefore(_userVehicles, t, c => c.Time) is var i and >= 0 ? _userVehicles[i] : null;
/// <summary>The stretches of the samples of the user's train the condition holds over.</summary>
public IReadOnlyList<TimeSpanRange> CabSpans(Func<CabSample, bool> condition)
{
var spans = new List<TimeSpanRange>();
double? start = null;
double gap = (Info is { CabInterval: > 0 } info ? info.CabInterval : 0.1) * 5;
for (int i = 0; i < _cab.Count; i++)
{
var sample = _cab[i];
bool holds = condition(sample);
bool broken = i > 0 && sample.Time - _cab[i - 1].Time > gap;
if (start is { } open && (!holds || broken))
{
spans.Add(new TimeSpanRange(open, broken ? _cab[i - 1].Time : sample.Time));
start = null;
}
if (holds && start is null)
start = sample.Time;
}
if (start is { } last && _cab.Count > 0)
spans.Add(new TimeSpanRange(last, _cab[^1].Time));
return spans;
}
/// <summary>When the AI drove the user's train: the autopilot.</summary>
public IReadOnlyList<TimeSpanRange> AutopilotSpans() => CabSpans(s => s.Driving == Driver.Ai);
/// <summary>The signals the user's train passed: those passed by the vehicle the samples are of at the time.</summary>
public IReadOnlyList<SignalPassing> UserPassings() =>
Memo(UserPassingsKey, () => _passings.Where(p => IsUserTrain(p.Time + 0.5, p.Vehicle, p.Position, Math.Max(0, p.Overrun) + 250)).ToList());
/// <summary>
/// Whether a vehicle was of the user's train at t. The records of a train give the
/// vehicle at its head, which is not the one the user is in when the train is driven
/// from its other end or from a car in the middle: those count when the place the
/// record is about lies within reach of the user's vehicle.
/// </summary>
public bool IsUserTrain(double t, int vehicle, Position place, double reach)
{
if (CabAt(t) is not { } s || t - s.Time > 1.5)
return false;
if (s.Vehicle == vehicle)
return true;
// The couplings tell the train exactly; a recording made before them has the distance only.
return CouplingsWritten ? ConsistAt(s.Vehicle, t).Contains(vehicle) : s.Position.DistanceTo(place) <= reach;
}
/// <summary>
/// Whether the couplings were written: a recording made since has the movement in its cab samples, and one with
/// no train of more than one vehicle has no coupling at all.
/// </summary>
private bool CouplingsWritten => _couplings.Count > 0 || (_cab.Count > 0 && _cab[0].Movement != Movement.Unknown);
/// <summary>The vehicles coupled into one train with the one given at t, itself included.</summary>
public IReadOnlySet<int> ConsistAt(int vehicle, double t)
{
// The trains change only at a coupling: the consist is the same until the next one.
int last = LastAtOrBefore(_couplings, t, c => c.Time);
if (_consists.TryGetValue((vehicle, last), out var kept))
return kept;
var consist = Consist(vehicle, last);
_consists[(vehicle, last)] = consist;
return consist;
}
private HashSet<int> Consist(int vehicle, int last)
{
// What each coupler held after the coupling given: the couplings in the order written, each telling both ends.
var held = new Dictionary<(int Vehicle, int Side), (int Other, int OtherSide)>();
for (int i = 0; i <= last; i++)
{
var change = _couplings[i];
if (held.Remove((change.Vehicle, change.Side), out var before))
held.Remove((before.Other, before.OtherSide));
if (change.Other != 0 && (change.Flags & CouplingFlags.Coupler) != 0)
{
held[(change.Vehicle, change.Side)] = (change.Other, change.OtherSide);
held[(change.Other, change.OtherSide)] = (change.Vehicle, change.Side);
}
}
var consist = new HashSet<int> { vehicle };
var open = new Stack<int>();
open.Push(vehicle);
while (open.Count > 0)
{
int at = open.Pop();
for (int side = 0; side < 2; side++)
if (held.TryGetValue((at, side), out var next) && consist.Add(next.Other))
open.Push(next.Other);
}
return consist;
}
/// <summary>Where the user looked from at t, null before it was known.</summary>
public CameraState? CameraAt(double t) =>
LastAtOrBefore(_cameras, t, c => c.Time) is var i and >= 0 ? _cameras[i] : null;
/// <summary>
/// The couplings made and undone after the start: those at t = 0 are what the trains
/// were made of, not something done.
/// </summary>
public IEnumerable<CouplingChange> CouplingEvents() =>
_couplings.Where(c => c.Time > 0.01 && (c.Coupled || c.Uncoupled || c.Flags != c.PreviousFlags));
/// <summary>The couplings the user's train took part in, before or after them.</summary>
public IReadOnlyList<CouplingChange> UserCouplings() =>
Memo(UserCouplingsKey, () => CouplingEvents().Where(c => CabAt(c.Time) is { } s && c.Time - s.Time <= 1.5 &&
(ConsistAt(s.Vehicle, c.Time - 0.01).Contains(c.Vehicle) ||
ConsistAt(s.Vehicle, c.Time + 0.01).Contains(c.Vehicle)))
.ToList());
/// <summary>
/// The timetable of the train the user was in at t: the last one written by then, else the first; none when the
/// user had gone over to a vehicle of another consist, a train without a timetable or one standing on its own.
/// </summary>
public Timetable? TimetableAt(double t)
{
var timetable = LastAtOrBefore(_timetables, t, x => x.Time) is var i and >= 0 ? _timetables[i] : _timetables.FirstOrDefault();
// A recording made before the couplings were written can't tell the trains apart: the timetable stays.
if (timetable is null || CabAt(t) is not { } sample || sample.Vehicle == timetable.Vehicle || !CouplingsWritten)
return timetable;
// another vehicle of the same train (the other cab, a car of it) keeps the timetable
return ConsistAt(sample.Vehicle, t).Contains(timetable.Vehicle) ? timetable : null;
}
/// <summary>The stations of the timetable of the user's train, as it came to them.</summary>
public IReadOnlyList<StationEvent> UserStations() =>
Memo(UserStationsKey, () => _stations.Where(s => IsUserTrain(s.Time, s.Vehicle, s.Position, Math.Max(s.TrainLength, 50) + 150)).ToList());
/// <summary>The horn points the user's train passed, and whether the horn sounded there.</summary>
public IReadOnlyList<HornCheck> UserHornChecks() => Memo(UserHornChecksKey, () => HornChecks().ToList());
private IEnumerable<HornCheck> HornChecks()
{
foreach (var request in _hornRequests)
{
if (!IsUserTrain(request.Time, request.Vehicle, request.Position, 300))
continue;
bool autopilot = CabAt(request.Time) is { Driving: Driver.Ai };
yield return new HornCheck(request, HornSounded(request), autopilot);
}
}
/// <summary>The time given to sound the horn after a horn point, beyond how long it is to sound.</summary>
public const double HornGrace = 8;
/// <summary>Whether the horn of the user's train sounded from just before the horn point until a while after.</summary>
private bool HornSounded(HornRequest request)
{
double until = request.Time + Math.Max(request.Duration, 1) + HornGrace;
for (int i = Math.Max(0, CabIndexAt(request.Time - 2)); i < _cab.Count && _cab[i].Time <= until; i++)
if (_cab[i].Has(CabDevices.Horn))
return true;
return false;
}
/// <summary>When the train protection braked the user's train: the alerter or the cab signalling not acknowledged.</summary>
public IReadOnlyList<TimeSpanRange> SecurityBrakings() => CabSpans(s => s.ProtectionBraking);
/// <summary>
/// When the train protection's buzzer sounded in the user's cab: a lamp not acknowledged in time, the braking to
/// follow unless acknowledged on. Until it ends, braking included.
/// </summary>
public IReadOnlyList<TimeSpanRange> SecurityAlarms() => CabSpans(s => s.VigilanceBuzzer || s.CabSignalBuzzer);
/// <summary>The commands the user gave in a vehicle, presses only.</summary>
public IEnumerable<CommandEntry> UserCommands() => _commands.Where(c => c.Pressed && c.Vehicle != 0);
public DrivingSummary Summarize(float tolerance = DrivingSummary.DefaultTolerance) => DrivingSummary.Of(this, tolerance);
}
/// <summary>A horn point the user's train passed: whether the horn sounded, and whether the autopilot drove then.</summary>
public sealed record HornCheck(HornRequest Request, bool Sounded, bool Autopilot);

421
Eu07.BlackBox/Records.cs Normal file
View File

@@ -0,0 +1,421 @@
using System;
using System.Collections.Generic;
using System.Numerics;
namespace Eu07.BlackBox;
/// <summary>The types of the records, as the simulator writes them (blackbox_doc.md in its repository).</summary>
public enum RecordType : byte
{
Info = 0x01,
Track = 0x10,
Signal = 0x11,
Vehicle = 0x12,
VehicleRemoved = 0x13,
StopPoint = 0x14,
HornPoint = 0x15,
Cab = 0x20,
Vehicles = 0x21,
SwitchState = 0x22,
SignalAspect = 0x23,
Timetable = 0x24,
Camera = 0x25,
Command = 0x30,
DriverChange = 0x31,
SignalPassed = 0x32,
UserVehicle = 0x33,
Clock = 0x34,
Station = 0x35,
HornRequest = 0x36,
Coupling = 0x37,
End = 0x3f
}
/// <summary>Who drives a vehicle.</summary>
public enum Driver : byte
{
None = 0,
Human = 1,
Ai = 2
}
[Flags]
public enum CabFlags : byte
{
None = 0,
/// <summary>The user is in the cab, not looking around outside.</summary>
InCab = 0x01,
/// <summary>The consist is started, so what the AI would do is worked out.</summary>
AiValid = 0x02,
/// <summary>The alerter or the cab signalling blinks.</summary>
AlerterBlinking = 0x04,
/// <summary>The alerter or the cab signalling beeps.</summary>
AlerterBeeping = 0x08,
WheelSlip = 0x10,
RadioStop = 0x20,
AlarmChain = 0x40
}
/// <summary>What is switched on in the user's train.</summary>
[Flags]
public enum CabDevices : uint
{
None = 0,
Battery = 0x0001,
MainBreaker = 0x0002,
PantographFront = 0x0004,
PantographRear = 0x0008,
Converter = 0x0010,
Compressor = 0x0020,
/// <summary>The motors are connected.</summary>
LineContactors = 0x0040,
/// <summary>Tripped.</summary>
OverloadRelay = 0x0080,
Sanding = 0x0100,
Horn = 0x0200,
DoorsLeft = 0x0400,
DoorsRight = 0x0800,
Radio = 0x1000,
Heating = 0x2000,
/// <summary>Applied.</summary>
SpringBrake = 0x4000,
ShuntMode = 0x8000,
/// <summary>Sounding.</summary>
DepartureSignal = 0x0001_0000,
/// <summary>The doors may be opened.</summary>
DoorPermitLeft = 0x0002_0000,
DoorPermitRight = 0x0004_0000,
/// <summary>The steps come out with the doors.</summary>
DoorStep = 0x0008_0000,
/// <summary>The doors lock above a speed.</summary>
DoorLock = 0x0010_0000,
/// <summary>Locked now.</summary>
DoorsLocked = 0x0020_0000,
/// <summary>Releasing the brakes of the vehicle.</summary>
BrakeReleaser = 0x0040_0000,
FuelPump = 0x0080_0000,
OilPump = 0x0100_0000,
/// <summary>The fans of the traction motors.</summary>
MotorBlowers = 0x0200_0000,
/// <summary>The diesel engine is over its temperature.</summary>
EngineHot = 0x0400_0000,
/// <summary>The cruise control holds a speed.</summary>
SpeedControl = 0x0800_0000
}
/// <summary>What drives the vehicle whose motors the cab drives.</summary>
public enum EngineKind : byte
{
/// <summary>Nothing of its own: a draisine, a car.</summary>
None = 0,
Electric = 1,
ElectricInduction = 2,
/// <summary>With a mechanical or a hydraulic transmission.</summary>
Diesel = 3,
DieselElectric = 4,
Steam = 5
}
/// <summary>
/// The rest of a look at the user's train, written from the same version as the doors' permits: what drives it,
/// the brakes' setting and mode, the hand brake, the radio, the horn, the pressure the driver's brake valve shows
/// (its equalizing reservoir, the FV4a's time reservoir) and that of the main reservoir pipe, a diesel's oil, temperatures, clutch and torque converter, the cruise control,
/// the power and the integrated controller of a unit, the highest brake cylinder pressure of the train. The
/// temperatures and the oil mean something for a diesel only.
/// </summary>
public readonly record struct CabExtra(EngineKind Engine, byte BrakeDelay, byte RadioChannel, float DriverValve,
float FeedPipe, float OilPressure, float WaterTemperature, float OilTemperature,
float EngineTemperature, float SpeedControlKmh, float EnginePower, sbyte HandBrake,
byte BrakeMode, byte Horn, float IntegratedController, float Clutch, float ConverterFill,
float ConsistBrakeCylinder);
/// <summary>The train protection: the alerter (CA) and the cab signalling (SHP) apart.</summary>
[Flags]
public enum SecurityFlags : byte
{
None = 0,
/// <summary>The alerter lamp blinks: the driver is to acknowledge.</summary>
Vigilance = 0x01,
/// <summary>The cab signalling lamp blinks: an SHP magnet was passed.</summary>
CabSignal = 0x02,
VigilanceBeeping = 0x04,
CabSignalBeeping = 0x08,
/// <summary>Not acknowledged in time: the train protection brakes the train.</summary>
Braking = 0x10
}
/// <summary>What a train did at a station of its timetable.</summary>
public enum StationKind : byte
{
/// <summary>Stopped at the stop point of a stop of its timetable.</summary>
Stopped = 1,
/// <summary>Passed a station where the timetable has no stop.</summary>
Passed = 2,
/// <summary>Left the stop point behind before it was time to go: without stopping, or leaving early.</summary>
Missed = 3,
/// <summary>Still at the stop point when it was time to go.</summary>
Ready = 4
}
/// <summary>The lights lit at an end of a vehicle.</summary>
[Flags]
public enum Lights : ushort
{
None = 0,
HeadlightLeft = 0x001,
RedMarkerLeft = 0x002,
HeadlightUpper = 0x004,
HeadlightRight = 0x010,
RedMarkerRight = 0x020,
RearEndSignals = 0x040,
AuxiliaryLeft = 0x080,
AuxiliaryRight = 0x100,
HighBeamLeft = 0x200,
HighBeamRight = 0x400
}
[Flags]
public enum PassingFlags : byte
{
None = 0,
/// <summary>A shunting signal.</summary>
Shunt = 0x01,
/// <summary>Passed showing stop: a signal passed at danger.</summary>
AtStop = 0x02,
/// <summary>Stop of an automatic block signal, which may be passed slowly after a stop.</summary>
AutomaticBlock = 0x04
}
public enum TrackKind : byte
{
Normal = 0,
SwitchBranch = 1
}
/// <summary>A position in the frame of the scenery: metres, y up.</summary>
public readonly record struct Position(double X, double Y, double Z)
{
public static Position Lerp(Position a, Position b, double f) =>
new(a.X + (b.X - a.X) * f, a.Y + (b.Y - a.Y) * f, a.Z + (b.Z - a.Z) * f);
public double DistanceTo(Position other)
{
double dx = X - other.X, dy = Y - other.Y, dz = Z - other.Z;
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
}
public sealed record RecordingInfo(string Scenery, string Started, int Year, int YearDay, double SecondOfDay,
string StartVehicle, string SimulatorVersion, float CabInterval,
float VehiclesInterval, float KeyframeInterval)
{
/// <summary>The time of day the simulation started at.</summary>
public TimeSpan StartClock => TimeSpan.FromSeconds(SecondOfDay);
}
/// <summary>One rail track of the map, or one of the two ways of a switch, which share the number.</summary>
public sealed record MapTrack(int Index, string Name, TrackKind Kind, int Branch, int Category,
IReadOnlyList<Vector3> Points);
public sealed record MapSignal(int Index, string Name, Position Position);
/// <summary>
/// A stop point of a passenger train (W4). StopAt: below 0 the head stops that many metres
/// before it, above 0 the middle of the train. Platform: above 0 its length, below 0 the
/// stop is for trains shorter than that (W32), 0 not given; its last digit also tells the side of
/// the platform (see <see cref="Platforms"/>).
/// </summary>
public sealed record MapStopPoint(int Index, string Station, Position Position, float StopAt, float Platform)
{
/// <summary>
/// The heading of the trains it is for [rad, from +z towards +x], NaN when not known: on no track, on tracks of
/// both ways, or in a recording made before it was written.
/// </summary>
public float Heading { get; init; } = float.NaN;
public bool HasHeading => !float.IsNaN(Heading);
public bool HasPlatform => Platform > 0;
/// <summary>A W32: the stop of the trains shorter than its length; the longer ones go on to another stop point.</summary>
public bool ForShortTrains => Platform < 0;
/// <summary>The length of the platform, or of the trains a W32 is for [m].</summary>
public double PlatformLength => Platforms.Length(Platform);
}
/// <summary>
/// The second value of a stop point, as the simulator's driver reads it: the whole of it the metres of the
/// platform, and its last digit, besides, the side the doors open on (1, 2, both 3); 201 is 201 m.
/// </summary>
public static class Platforms
{
public static double Length(float value) => Math.Abs(value);
public static int Side(float value) => (int)Math.Floor(Math.Abs(value)) % 10;
}
/// <summary>A horn point (W6): the trains passing it are to sound the horn this long, in this tone (1 low, 2 high).</summary>
public sealed record MapHornPoint(int Index, string Name, Position Position, float Duration, float Tone);
/// <summary>A station of a timetable; the times in minutes of the day, below 0 none.</summary>
public sealed record TimetableRow(string Station, float Km, float Vmax, float Arrival, float Departure, bool Maintenance)
{
/// <summary>The train stops there: a station passed through has a departure only.</summary>
public bool IsStop => Arrival >= 0;
}
/// <summary>The timetable of the train the user was in. The rows are numbered from 1, the station records give their number.</summary>
public sealed record Timetable(double Time, int Vehicle, string Train, string Category, string From, string To, float Vmax,
IReadOnlyList<TimetableRow> Rows)
{
public TimetableRow? Row(int number) => number >= 1 && number <= Rows.Count ? Rows[number - 1] : null;
}
/// <summary>
/// A train at a station of its timetable, at its stop point. Distance: of its head before
/// the stop point, below 0 past it; StopAt: where the head was to stop, that many metres before it.
/// </summary>
public sealed record StationEvent(double Time, int Vehicle, StationKind Kind, int Row, string Station, Position Position,
float Distance, float StopAt, float TrainLength, float Platform, float Arrival,
float Departure)
{
/// <summary>How far from the place it was to stop the head stood: above 0 short of it, below 0 past it.</summary>
public float StopError => Distance - StopAt;
/// <summary>
/// Whether the whole train stood along the platform, when its length is known: as the driver takes it, the length of
/// the trains a W32 is for is the room it has there too.
/// </summary>
public bool? OnPlatform => Platform != 0 ? -Distance <= PlatformTolerance && Distance + TrainLength - PlatformLength <= PlatformTolerance : null;
/// <summary>How far off the platform a train may stand at either end and still count as along it [m].</summary>
public const double PlatformTolerance = 2;
/// <summary>The length of the platform [m], without the digit of its side.</summary>
public double PlatformLength => Platforms.Length(Platform);
/// <summary>How much of the train stood off the platform [m]: the head past the stop point, the tail before the platform's end; 0 along it.</summary>
public double OffPlatform => Platform != 0 ? Math.Max(0, -Distance) + Math.Max(0, Distance + TrainLength - PlatformLength) : 0;
}
public enum CameraMode : byte
{
/// <summary>From the cab of the vehicle the user is in.</summary>
Cab = 0,
/// <summary>One of the outside views of the user's train.</summary>
External = 1,
/// <summary>The free camera.</summary>
Free = 2,
Debug = 3
}
/// <summary>Where the user looked from. Heading as that of a vehicle: towards (sin, cos) in (x, z).</summary>
public readonly record struct CameraState(double Time, CameraMode Mode, int View, int Vehicle, Position Position,
float Heading, float Pitch);
/// <summary>What a coupling joins: the bits of the simulator's coupling.</summary>
[Flags]
public enum CouplingFlags : byte
{
None = 0,
Coupler = 0x01,
BrakePipe = 0x02,
Control = 0x04,
Power = 0x08,
Gangway = 0x10,
MainPipe = 0x20,
Heating = 0x40,
/// <summary>Not undone in shunting: between the cars of a unit.</summary>
Permanent = 0x80
}
/// <summary>A coupler coupled, uncoupled, or its hoses and cables changed. Side 0 the front coupler, 1 the rear one.</summary>
public sealed record CouplingChange(double Time, int Vehicle, int Side, int Other, int OtherSide, CouplingFlags Flags,
CouplingFlags PreviousFlags, int PreviousOther, Position Position)
{
public bool Coupled => Other != 0 && (Flags & CouplingFlags.Coupler) != 0 && PreviousOther != Other;
public bool Uncoupled => Other == 0 && PreviousOther != 0;
}
/// <summary>A train told to sound the horn at a horn point.</summary>
public readonly record struct HornRequest(double Time, int Vehicle, float Duration, float Tone, Position Position);
/// <summary>A vehicle as it is first seen. Id 0 is no vehicle.</summary>
public sealed record VehicleInfo(int Id, string Name, string Type, string Train, float Length, float Width,
int Category)
{
public double? RemovedAt { get; internal set; }
}
/// <summary>What the AI driver would do at that moment, from that place and at that speed.</summary>
public readonly record struct AiReference(float TargetKmh, float NextLimitKmh, float NextLimitDistance,
float Acceleration, float BrakingDistance, float TimetableVmaxKmh,
float TrackVmaxKmh)
{
public bool HasNextLimit => NextLimitKmh >= 0 && NextLimitDistance >= 0;
}
/// <summary>One look at the user's train, ten a second.</summary>
public readonly record struct CabSample(double Time, int Vehicle, Position Position, float SpeedKmh,
float Acceleration, float OdometerKm, Driver Driving, CabFlags Flags,
sbyte MainController, sbyte ScndController, sbyte Reverser,
float TrainBrake, float LocalBrake, float BrakeCylinder, float BrakePipe,
float MotorCurrent, AiReference Ai, CabDevices Devices,
float MainReservoir, float Voltage, float EngineRpm,
Lights LightsHead, Lights LightsTail, sbyte CabEnd = 0,
SecurityFlags Security = SecurityFlags.None, float LateralAcceleration = 0,
Movement Movement = Movement.Unknown, short LightHintHead = -1, short LightHintTail = -1,
Lights? EquippedHead = null, Lights? EquippedTail = null, CabExtra? Extra = null)
{
public bool Has(CabDevices device) => (Devices & device) == device;
public bool Has(SecurityFlags flag) => (Security & flag) == flag;
/// <summary>
/// The alerter's buzzer: its lamp not acknowledged in time. A protection with one acknowledgement for both tells
/// the cab signalling's buzzer as the alerter's too, so the alerter's lamp has to blink with it.
/// </summary>
public bool VigilanceBuzzer => Has(SecurityFlags.VigilanceBeeping) && Has(SecurityFlags.Vigilance);
/// <summary>The cab signalling's buzzer: its lamp not acknowledged in time.</summary>
public bool CabSignalBuzzer => Has(SecurityFlags.CabSignalBeeping);
/// <summary>
/// The train protection braking for an alarm not acknowledged, its lamp blinking. Braking with no lamp is the
/// protection with no power (TSecuritySystem::is_braking), a cab not started or a power cut: no driver's fault.
/// </summary>
public bool ProtectionBraking => Has(SecurityFlags.Braking) && (Has(SecurityFlags.Vigilance) || Has(SecurityFlags.CabSignal));
public bool AiValid => (Flags & CabFlags.AiValid) != 0;
public bool InCab => (Flags & CabFlags.InCab) != 0;
public float AbsSpeedKmh => Math.Abs(SpeedKmh);
}
/// <summary>One vehicle in a look at the vehicles.</summary>
public readonly record struct VehicleState(int Id, Vector3 Position, float Heading, float SpeedKmh, Driver Driving);
/// <summary>A look at the vehicles: those which moved, or all of them in a keyframe.</summary>
public sealed record VehicleLook(double Time, bool Keyframe, IReadOnlyList<VehicleState> States);
public readonly record struct SwitchChange(double Time, int Track, int State);
/// <summary>What a signal shows: the speeds its memory cell holds, 0 stop, -1 no limit, and the command.</summary>
public readonly record struct AspectChange(double Time, int Signal, float Speed1, float Speed2, string Command);
public sealed record CommandEntry(double Time, int Vehicle, bool Pressed, double Param1, double Param2, string Name);
public readonly record struct DriverChange(double Time, int Vehicle, Driver Driving);
public sealed record SignalPassing(double Time, int Vehicle, int Signal, string Event, Position Position,
float Speed1, float Speed2, float SpeedKmh, float Overrun, PassingFlags Flags)
{
/// <summary>No signal of the map: the passing came from an event the map doesn't hold.</summary>
public const int NoSignal = -1;
public bool AtDanger => (Flags & PassingFlags.AtStop) != 0;
}
/// <summary>The vehicle the user was in, whether in its cab, and which cab: 1 the front one, -1 the rear one, 0 none.</summary>
public readonly record struct UserVehicleChange(double Time, int Vehicle, bool InCab, sbyte CabEnd = 0);
public readonly record struct ClockEntry(double Time, int Year, int YearDay, double SecondOfDay);

View File

@@ -0,0 +1,13 @@
namespace Eu07.BlackBox;
/// <summary>The names of the stations as shown: the scenery tells the stop points of one station apart after a <c>#</c>.</summary>
public static class StationNames
{
/// <summary>The name up to a <c>#</c>, with the underscores of the scenery as spaces.</summary>
public static string Display(string name)
{
int hash = name.IndexOf('#');
var shown = hash >= 0 ? name[..hash] : name;
return shown.Replace('_', ' ').Trim();
}
}

View File

@@ -0,0 +1,188 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Eu07.BlackBox;
/// <summary>How the user's train kept to a station of its timetable.</summary>
public enum StationOutcome
{
/// <summary>Not reached yet in the recording.</summary>
Ahead,
/// <summary>Stopped where the timetable has a stop.</summary>
Stopped,
/// <summary>Passed where the timetable has no stop.</summary>
Passed,
/// <summary>Left a stop behind without stopping, or before the departure.</summary>
Missed
}
/// <summary>How late the user's train was at a moment [min, above 0 late], after the station named, standing there or not.</summary>
public sealed record TrainDelay(string Train, double Minutes, string Station, bool Standing);
/// <summary>
/// A row of the timetable of the user's train, with what happened there. The times are
/// minutes of the day, as in the timetable; the delays are in minutes, above 0 late.
/// </summary>
public sealed record StationProgress(
int Number,
TimetableRow Row,
StationOutcome Outcome,
double? ArrivedAt,
double? DepartedAt,
double? ArrivalClock,
double? DepartureClock,
StationEvent? Event)
{
public double? ArrivalDelay => Delay(ArrivalClock, Row.Arrival);
/// <summary>Of the departure, or of the pass for a station passed through.</summary>
public double? DepartureDelay => Delay(DepartureClock, Row.Departure);
/// <summary>Above 0 the head stood short of where it was to stop, below 0 past it [m].</summary>
public float? StopError => Outcome == StationOutcome.Stopped && Event is { } e ? e.StopError : null;
public bool? OnPlatform => Outcome == StationOutcome.Stopped ? Event?.OnPlatform : null;
/// <summary>How far the tail stood off the platform [m], when it stopped.</summary>
public double? OffPlatform => Outcome == StationOutcome.Stopped ? Event?.OffPlatform : null;
/// <summary>The difference of two times of the day in minutes, across midnight the short way.</summary>
internal static double? Delay(double? actual, float planned)
{
if (actual is not { } a || planned < 0)
return null;
double d = a - planned;
if (d > 720) d -= 1440;
if (d < -720) d += 1440;
return d;
}
/// <summary>
/// The rows of the timetable the user's train had at t, each with what the train did
/// there by the end of the recording read so far.
/// </summary>
public static IReadOnlyList<StationProgress> Of(Recording recording, double t) =>
recording.TimetableAt(t) is { } timetable ? Of(recording, timetable) : Array.Empty<StationProgress>();
/// <summary>The rows of a timetable of the recording, each with what the train did there.</summary>
public static IReadOnlyList<StationProgress> Of(Recording recording, Timetable timetable) =>
recording.Memo((typeof(StationProgress), timetable), () => Work(recording, timetable));
private static IReadOnlyList<StationProgress> Work(Recording recording, Timetable timetable)
{
// The records of this train: from its timetable on, until another one is written. A train given its next
// timetable may come to the first station of it at once, and a recording made before the simulator wrote the
// timetable first has that station up to a look (1 s) before it: it goes with the timetable after.
int next = IndexOf(recording.Timetables, timetable) + 1;
double until = next < recording.Timetables.Count ? recording.Timetables[next].Time - 1 : double.MaxValue;
var events = recording.UserStations()
.Where(e => e.Time >= timetable.Time - 1 && e.Time < until)
.ToList();
var rows = new List<StationProgress>(timetable.Rows.Count);
for (int number = 1; number <= timetable.Rows.Count; number++)
{
var row = timetable.Rows[number - 1];
var mine = events.Where(e => e.Row == number).ToList();
var stopped = mine.FirstOrDefault(e => e.Kind == StationKind.Stopped);
var passed = mine.FirstOrDefault(e => e.Kind == StationKind.Passed);
var missed = mine.FirstOrDefault(e => e.Kind == StationKind.Missed);
if (stopped is not null)
{
double? departed = DepartureAfter(recording, stopped.Time);
rows.Add(new StationProgress(number, row, missed is not null ? StationOutcome.Missed : StationOutcome.Stopped,
stopped.Time, departed, Minutes(recording, stopped.Time),
departed is { } d ? Minutes(recording, d) : null, stopped));
}
else if (passed is not null)
rows.Add(new StationProgress(number, row, StationOutcome.Passed, null, passed.Time, null,
Minutes(recording, passed.Time), passed));
else if (missed is not null)
rows.Add(new StationProgress(number, row, StationOutcome.Missed, null, missed.Time, null,
Minutes(recording, missed.Time), missed));
else
rows.Add(new StationProgress(number, row, StationOutcome.Ahead, null, null, null, null, null));
}
return rows;
}
/// <summary>When the user's train got moving again after a stop, null while it still stood.</summary>
private static double? DepartureAfter(Recording recording, double stoppedAt)
{
var cab = recording.Cab;
for (int i = Math.Max(0, recording.CabIndexAt(stoppedAt)); i < cab.Count; i++)
if (cab[i].Time > stoppedAt && cab[i].AbsSpeedKmh > 2)
return cab[i].Time;
return null;
}
/// <summary>
/// The delay of the user's train at t, from the last station of its timetable it had come to
/// by then: of the departure or the pass once it left, of the arrival while it stands, growing
/// while it stands past the departure, and growing on the way once it is past the time it was
/// to be at the next station. Null before the first station or without a timetable.
/// </summary>
public static TrainDelay? DelayAt(Recording recording, double t)
{
if (recording.TimetableAt(t) is not { } timetable || t < timetable.Time - 1)
return null;
double clock = recording.ClockAt(t).TotalMinutes;
TrainDelay? delay = null;
var rows = Of(recording, timetable);
int reached = -1;
for (int i = 0; i < rows.Count; i++)
{
var row = rows[i];
if (row.DepartedAt is { } departed && departed <= t)
delay = new TrainDelay(timetable.Train, row.DepartureDelay ?? row.ArrivalDelay ?? delay?.Minutes ?? 0, row.Row.Station, false);
else if (row.ArrivedAt is { } arrived && arrived <= t)
{
double minutes = row.ArrivalDelay ?? delay?.Minutes ?? 0;
if (Delay(clock, row.Row.Departure) is { } overdue)
minutes = Math.Max(minutes, overdue);
delay = new TrainDelay(timetable.Train, minutes, row.Row.Station, true);
}
else
continue;
reached = i;
}
// On the way, past the time it was to be at the next station: at least that late, and more as it stays away.
if (delay is { Standing: false } && reached + 1 < rows.Count)
{
var next = rows[reached + 1].Row;
if (Delay(clock, next.Arrival >= 0 ? next.Arrival : next.Departure) is { } overdue && overdue > delay.Minutes)
delay = delay with { Minutes = overdue };
}
return delay;
}
/// <summary>The delays the user's train had at the stations it had left or stood at by t, by the name shown.</summary>
public static IReadOnlyDictionary<string, double> StationDelays(Recording recording, double t)
{
var delays = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase);
foreach (var timetable in recording.Timetables)
{
if (timetable.Time > t)
break;
foreach (var row in Of(recording, timetable))
{
double? at = row.ArrivedAt ?? row.DepartedAt;
double? delay = row.DepartedAt <= t ? row.DepartureDelay ?? row.ArrivalDelay : row.ArrivalDelay;
if (at <= t && delay is { } d)
delays[StationNames.Display(row.Row.Station)] = d;
}
}
return delays;
}
private static int IndexOf(IReadOnlyList<Timetable> timetables, Timetable timetable)
{
for (int i = 0; i < timetables.Count; i++)
if (ReferenceEquals(timetables[i], timetable))
return i;
return -1;
}
private static double Minutes(Recording recording, double t) => recording.ClockAt(t).TotalMinutes;
}

View File

@@ -0,0 +1,125 @@
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.VisualTree;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class AnnouncerTests
{
private DateTime _now = new(2026, 11, 15, 12, 0, 0, DateTimeKind.Utc);
private Announcer NewAnnouncer() => new(() => _now);
[Fact]
public void A_message_is_read_while_fresh_and_then_forgotten()
{
var announcer = NewAnnouncer();
announcer.Say(" Jakość grafiki: Wysoka ");
Assert.Equal("Jakość grafiki: Wysoka", announcer.Message);
_now += Announcer.Shown;
Assert.Null(announcer.Message);
}
[Fact]
public void Nothing_to_say_says_nothing()
{
var announcer = NewAnnouncer();
announcer.Say("Zapisano ustawienia");
announcer.Say(" ");
Assert.Equal("Zapisano ustawienia", announcer.Message);
}
[Fact]
public void A_control_inside_says_it_through_the_window_announcer()
{
var button = new Button();
var announcer = NewAnnouncer();
announcer.Child = new Border { Child = button };
Announcer.Say(button, "Godzina: 07:05");
Assert.Equal("Godzina: 07:05", announcer.Message);
}
[Fact]
public void A_control_outside_any_announcer_is_not_heard()
{
var button = new Button();
var thrown = Record.Exception(() => Announcer.Say(button, "Godzina: 07:05"));
Assert.Null(thrown);
Assert.Null(button.FindAncestorOfType<Announcer>());
}
[Fact]
public void A_marked_text_is_read_when_it_changes()
{
var status = new TextBlock();
Announcer.SetChanges(status, true);
var plain = new TextBlock();
var announcer = NewAnnouncer();
announcer.Child = new StackPanel { Children = { status, plain } };
plain.Text = "Ścieżka";
Assert.Null(announcer.Message);
status.Text = "Niezapisane zmiany";
Assert.True(Announcer.GetChanges(status));
Assert.Equal("Niezapisane zmiany", announcer.Message);
}
[Fact]
public void A_screen_reader_hears_it_as_a_polite_live_region()
{
var announcer = NewAnnouncer();
var peer = ControlAutomationPeer.CreatePeerForElement(announcer);
announcer.Say("Przywrócono domyślne");
Assert.Equal("Przywrócono domyślne", peer.GetName());
Assert.Equal(AutomationLiveSetting.Polite, peer.GetLiveSetting());
Assert.Equal(AutomationControlType.Group, peer.GetAutomationControlType());
}
}
[Collection(AvaloniaControls.Name)]
public class NamedGroupTests
{
static NamedGroupTests() => ScreenReaderNames.Install();
[Fact]
public void A_panel_with_a_title_is_a_group_named_by_it()
{
var panel = new HeaderedContentControl { Header = "Scenerie" };
Assert.Equal("Scenerie", AutomationProperties.GetName(panel));
Assert.Equal(AutomationControlType.Group, AutomationProperties.GetControlTypeOverride(panel));
Assert.Equal(AccessibilityView.Content, AutomationProperties.GetAccessibilityView(panel));
}
[Fact]
public void A_panel_whose_title_goes_is_no_longer_a_group()
{
var panel = new HeaderedContentControl { Header = "Skład" };
panel.Header = null;
Assert.Null(AutomationProperties.GetName(panel));
Assert.Null(AutomationProperties.GetControlTypeOverride(panel));
Assert.Equal(AccessibilityView.Default, AutomationProperties.GetAccessibilityView(panel));
}
[Fact]
public void A_tab_keeps_its_own_way_of_speaking()
{
var tab = new TabItem { Header = "Pogoda" };
Assert.Null(AutomationProperties.GetName(tab));
Assert.Equal(AutomationControlType.TabItem, AutomationProperties.GetControlTypeOverride(tab));
}
}

View File

@@ -0,0 +1,11 @@
namespace StarterNG.Tests;
/// <summary>
/// Tests that build Avalonia controls run one after another: a control belongs to the
/// thread that made the first one, and run side by side they now and then failed.
/// </summary>
[CollectionDefinition(Name)]
public sealed class AvaloniaControls
{
public const string Name = "Avalonia controls";
}

View File

@@ -0,0 +1,397 @@
using System.Numerics;
using System.Text;
using Eu07.BlackBox;
namespace StarterNG.Tests.BlackBox;
/// <summary>
/// Writes a black box the way the simulator does (blackbox_doc.md of its repository),
/// field by field, so the reader is checked against the layout and not against itself.
/// </summary>
internal sealed class BlackBoxFile
{
private readonly MemoryStream _bytes = new();
private readonly BinaryWriter _file;
public BlackBoxFile(ushort version = 1, bool header = true)
{
_file = new BinaryWriter(_bytes, Encoding.UTF8, leaveOpen: true);
if (header)
{
_file.Write("EU07BBX\0"u8);
_file.Write(version);
_file.Write((ushort)0);
}
}
public byte[] Bytes => _bytes.ToArray();
public MemoryStream Stream() => new(Bytes);
/// <summary>A record of a type, its length and what the writer puts in it.</summary>
public BlackBoxFile Record(byte type, Action<BinaryWriter> payload)
{
using var body = new MemoryStream();
using (var w = new BinaryWriter(body, Encoding.UTF8, leaveOpen: true))
payload(w);
_file.Write(type);
_file.Write((uint)body.Length);
_file.Write(body.ToArray());
return this;
}
public BlackBoxFile Info(double secondOfDay = 10 * 3600 + 34 * 60, string scenery = "td.scn") =>
Record(0x01, w =>
{
w.Write(scenery);
w.Write("2026-11-08T22:56:30");
w.Write((ushort)2026);
w.Write((ushort)312);
w.Write(secondOfDay);
w.Write("ep07-bb");
w.Write("EU07 test");
w.Write(0.1f);
w.Write(1.0f);
w.Write(60.0f);
});
public BlackBoxFile Track(uint index, string name, params Vector3[] points) =>
Track(index, name, 0, 0, points);
public BlackBoxFile Track(uint index, string name, byte kind, byte branch, params Vector3[] points) =>
Record(0x10, w =>
{
w.Write(index);
w.Write(name);
w.Write(kind);
w.Write(branch);
w.Write((byte)1);
w.Write((uint)points.Length);
foreach (var p in points)
{
w.Write(p.X);
w.Write(p.Y);
w.Write(p.Z);
}
});
public BlackBoxFile Signal(uint index, string name, double x, double y, double z) =>
Record(0x11, w =>
{
w.Write(index);
w.Write(name);
w.Write(x);
w.Write(y);
w.Write(z);
});
public BlackBoxFile Vehicle(uint id, string name, string train = "", float length = 16.3f) =>
Record(0x12, w =>
{
w.Write(id);
w.Write(name);
w.Write("303e-ep-tv");
w.Write(train);
w.Write(length);
w.Write(2.9f);
w.Write((byte)1);
});
public BlackBoxFile Removed(double time, uint id) =>
Record(0x13, w =>
{
w.Write(time);
w.Write(id);
});
public BlackBoxFile Cab(double time, uint vehicle, double z, float speed, byte driving = 1, byte flags = 0x03,
float target = 40, float nextLimit = -1, float nextDistance = -1, float brakeCylinder = 0,
uint devices = 0x0007, bool extended = true, sbyte cabEnd = 1, byte security = 0,
float lateral = 0.2f, ushort lightsHead = 0x15, ushort lightsTail = 0x22, byte? movement = null,
short hintHead = -1, short hintTail = -1, ushort? equippedHead = null, ushort? equippedTail = null,
byte? engine = null, float oilTemperature = 70) =>
Record(0x20, w =>
{
w.Write(time);
w.Write(vehicle);
w.Write(5.0);
w.Write(0.4);
w.Write(z);
w.Write(speed);
w.Write(0.1f); // acceleration
w.Write(1.5f); // odometer
w.Write(driving);
w.Write(flags);
w.Write((sbyte)3); // main controller
w.Write((sbyte)0);
w.Write((sbyte)1);
w.Write(0.0f); // train brake
w.Write(0.0f);
w.Write(brakeCylinder);
w.Write(5.0f); // brake pipe
w.Write(320.0f); // current
w.Write(target);
w.Write(nextLimit);
w.Write(nextDistance);
w.Write(0.3f);
w.Write(150.0f);
w.Write(60.0f);
w.Write(-1.0f);
w.Write(devices);
w.Write(8.5f); // main reservoir
w.Write(3000.0f); // voltage
w.Write(1100.0f); // revolutions
w.Write(lightsHead); // lights at the head of the train
w.Write(lightsTail);
// The cab, the train protection and the lateral acceleration: a recording made before them ends above.
if (extended)
{
w.Write(cabEnd);
w.Write(security);
w.Write(lateral);
// what the driver goes by and the lights asked for: a recording made before them ends above
if (movement is { } kind)
{
w.Write(kind);
w.Write(hintHead);
w.Write(hintTail);
// the lamps the vehicles at the ends have: a recording made before them ends above
if (equippedHead is { } head)
{
w.Write(head);
w.Write(equippedTail ?? head);
// what drives it and the rest: a recording made before them ends above
if (engine is { } kind2)
{
w.Write(kind2);
w.Write((byte)2); // brake setting P
w.Write((byte)3); // radio channel
w.Write(4.8f); // equalizing reservoir
w.Write(8.0f); // main reservoir pipe
w.Write(0.45f); // oil pressure
w.Write(75.0f); // water
w.Write(oilTemperature);
w.Write(80.0f); // engine
w.Write(0.0f); // cruise control
w.Write(900.0f); // power
w.Write((sbyte)0); // hand brake
w.Write((byte)1); // brake mode
w.Write((byte)0); // horn
w.Write(0.5f); // integrated controller
w.Write(1.0f); // clutch
w.Write(0.0f); // torque converter
w.Write(2.5f); // the highest brake cylinder of the train
}
}
}
}
});
public BlackBoxFile Vehicles(double time, bool keyframe, params (uint Id, float X, float Z, float Speed)[] states) =>
Record(0x21, w =>
{
w.Write(time);
w.Write((byte)(keyframe ? 1 : 0));
w.Write((uint)states.Length);
foreach (var s in states)
{
w.Write(s.Id);
w.Write(s.X);
w.Write(0.4f);
w.Write(s.Z);
w.Write(0.0f); // heading
w.Write(s.Speed);
w.Write((byte)2);
}
});
public BlackBoxFile Switch(double time, uint track, byte state) =>
Record(0x22, w =>
{
w.Write(time);
w.Write(track);
w.Write(state);
});
public BlackBoxFile Aspect(double time, uint signal, float speed1, float speed2, string command = "SetVelocity") =>
Record(0x23, w =>
{
w.Write(time);
w.Write(signal);
w.Write(speed1);
w.Write(speed2);
w.Write(command);
});
public BlackBoxFile Command(double time, uint vehicle, bool pressed, string name) =>
Record(0x30, w =>
{
w.Write(time);
w.Write(vehicle);
w.Write((byte)(pressed ? 1 : 0));
w.Write(1.0);
w.Write(2.0);
w.Write(name);
});
public BlackBoxFile Driver(double time, uint vehicle, byte driving) =>
Record(0x31, w =>
{
w.Write(time);
w.Write(vehicle);
w.Write(driving);
});
public BlackBoxFile Passed(double time, uint vehicle, uint signal, string name, float speed1, float speed,
byte flags = 0, double z = 1300) =>
Record(0x32, w =>
{
w.Write(time);
w.Write(vehicle);
w.Write(signal);
w.Write(name);
w.Write(5.0);
w.Write(0.4);
w.Write(z);
w.Write(speed1);
w.Write(-1.0f);
w.Write(speed);
w.Write(2.5f);
w.Write(flags);
});
public BlackBoxFile User(double time, uint vehicle, bool inCab, sbyte? cabEnd = null) =>
Record(0x33, w =>
{
w.Write(time);
w.Write(vehicle);
w.Write((byte)(inCab ? 1 : 0));
if (cabEnd is { } end)
w.Write(end);
});
public BlackBoxFile StopPoint(uint index, string station, double z, float stopAt, float platform, float? heading = null) =>
Record(0x14, w =>
{
w.Write(index);
w.Write(station);
w.Write(5.0);
w.Write(0.4);
w.Write(z);
w.Write(stopAt);
w.Write(platform);
if (heading is { } way)
w.Write(way);
});
public BlackBoxFile HornPoint(uint index, string name, double z, float duration = 2, float tone = 1) =>
Record(0x15, w =>
{
w.Write(index);
w.Write(name);
w.Write(5.0);
w.Write(0.4);
w.Write(z);
w.Write(duration);
w.Write(tone);
});
public BlackBoxFile Timetable(double time, uint vehicle, string train, string from, string to,
params (string Station, float Arrival, float Departure)[] rows) =>
Record(0x24, w =>
{
w.Write(time);
w.Write(vehicle);
w.Write(train);
w.Write("ROJ");
w.Write(from);
w.Write(to);
w.Write(100.0f);
w.Write((uint)rows.Length);
float km = 0;
foreach (var row in rows)
{
w.Write(row.Station);
w.Write(km += 2.5f);
w.Write(100.0f);
w.Write(row.Arrival);
w.Write(row.Departure);
w.Write((byte)0);
}
});
public BlackBoxFile Station(double time, uint vehicle, byte kind, ushort row, string station, double z,
float distance = 1, float stopAt = 0, float trainLength = 87, float platform = 150,
float arrival = -1, float departure = -1) =>
Record(0x35, w =>
{
w.Write(time);
w.Write(vehicle);
w.Write(kind);
w.Write(row);
w.Write(station);
w.Write(5.0);
w.Write(0.4);
w.Write(z);
w.Write(distance);
w.Write(stopAt);
w.Write(trainLength);
w.Write(platform);
w.Write(arrival);
w.Write(departure);
});
public BlackBoxFile HornRequest(double time, uint vehicle, double z, float duration = 2) =>
Record(0x36, w =>
{
w.Write(time);
w.Write(vehicle);
w.Write(duration);
w.Write(1.0f);
w.Write(5.0);
w.Write(0.4);
w.Write(z);
});
public BlackBoxFile Camera(double time, byte mode, uint vehicle, double z, byte view = 0, float heading = 0.5f) =>
Record(0x25, w =>
{
w.Write(time);
w.Write(mode);
w.Write(view);
w.Write(vehicle);
w.Write(5.0);
w.Write(2.4);
w.Write(z);
w.Write(heading);
w.Write(-0.1f);
});
public BlackBoxFile Coupling(double time, uint vehicle, byte side, uint other, byte otherSide, byte flags,
byte previousFlags, uint previousOther) =>
Record(0x37, w =>
{
w.Write(time);
w.Write(vehicle);
w.Write(side);
w.Write(other);
w.Write(otherSide);
w.Write(flags);
w.Write(previousFlags);
w.Write(previousOther);
w.Write(5.0);
w.Write(0.4);
w.Write(1150.0);
});
public BlackBoxFile Clock(double time, double secondOfDay) =>
Record(0x34, w =>
{
w.Write(time);
w.Write((ushort)2026);
w.Write((ushort)312);
w.Write(secondOfDay);
});
public BlackBoxFile End(double time) => Record(0x3f, w => w.Write(time));
}

View File

@@ -0,0 +1,253 @@
using Eu07.BlackBox;
namespace StarterNG.Tests.BlackBox;
/// <summary>
/// A journey of two timetables one after another: the stations, the horn points, the train
/// protection, the camera and the couplings, as the simulator writes them, and what the
/// recording tells of them.
/// </summary>
public class BlackBoxJourneyTests
{
private const uint Head = 1, Car = 2, Tail = 3, Stranger = 9;
private const byte Coupled = 0x83;
/// <summary>
/// The user in vehicle 1 of a unit 1-2-3, the clock at 10:34 (634 min). ROJ1 stands at A, stops at B
/// at t = 60 until 70, passes C at 100 without stopping; ROJ2 from t = 110 stops at D at 115.
/// </summary>
private static Recording Journey()
{
var f = new BlackBoxFile().Info()
.StopPoint(0, "Stacja_B#1", 1300, 10, 150)
.StopPoint(1, "Stacja_B#2", 1310, 10, 150)
.HornPoint(0, "w6_1", 1200)
.User(0, Head, true, -1)
.Coupling(0, Head, 1, Car, 0, Coupled, 0, 0)
.Coupling(0, Car, 1, Tail, 0, Coupled, 0, 0)
.Camera(0, 0, Head, 1150)
.Timetable(0, Head, "ROJ1", "A", "C", ("A", -1, 634), ("Stacja_B", 635, 635.5f), ("C", 637.5f, 638))
.Station(1, Head, 4, 1, "A", 1150);
for (double t = 0; t <= 130; t += 0.5)
{
float speed = t is >= 55 and < 70 || t >= 112 && t < 120 ? 0 : 40;
uint devices = 0x0007 | (t is >= 22 and < 24 ? 0x0200u : 0);
byte security = (byte)(t is >= 30 and < 32 ? 0x11 : 0x01);
f.Cab(t, Head, 1150 + t * 10, speed, devices: devices, security: security, lateral: t is >= 45 and < 48 ? 1.2f : 0.1f);
}
f.HornRequest(20, Head, 1200)
.HornRequest(40, Head, 1550)
.Camera(50, 2, 0, 1650)
.Station(60, Head, 1, 2, "Stacja_B#2", 1300)
.Station(60, Stranger, 1, 2, "Stacja_B#1", 9000)
.Coupling(80, Car, 1, 0, 0, 0, Coupled, Tail)
.Station(100, Head, 3, 3, "C", 2150)
.Timetable(110, Head, "ROJ2", "C", "D", ("C", -1, 638), ("D", 640, -1))
.Station(115, Head, 1, 2, "D", 2300);
return BlackBoxReader.Read(f.End(130).Stream());
}
[Fact]
public void The_new_records_are_read_field_by_field()
{
var r = Journey();
Assert.Equal(0, r.Unknown);
Assert.Equal(0, r.Malformed);
Assert.Equal(2, r.StopPoints.Count);
Assert.Equal("Stacja_B#2", r.StopPoints[1].Station);
Assert.Equal(10f, r.StopPoints[1].StopAt);
Assert.Equal(150f, r.StopPoints[1].Platform);
Assert.Equal("w6_1", Assert.Single(r.HornPoints).Name);
Assert.Equal(2, r.Timetables.Count);
Assert.Equal("ROJ2", r.Timetables[1].Train);
Assert.Equal(640f, r.Timetables[1].Row(2)!.Arrival);
Assert.False(r.Timetables[1].Row(2)!.Maintenance);
Assert.Equal(5, r.Stations.Count);
Assert.Equal(StationKind.Missed, r.Stations.Single(s => s.Row == 3 && s.Vehicle == Head).Kind);
Assert.Equal(2, r.HornRequests.Count);
Assert.Equal(2, r.Cameras.Count);
Assert.Equal(CameraMode.Free, r.Cameras[1].Mode);
Assert.Equal(-0.1f, r.Cameras[1].Pitch);
Assert.Equal(3, r.Couplings.Count);
Assert.True(r.Couplings[2].Uncoupled);
Assert.Equal(-1, Assert.Single(r.UserVehicles).CabEnd);
var cab = r.Cab[0];
Assert.Equal(1, cab.CabEnd);
Assert.Equal(SecurityFlags.Vigilance, cab.Security);
Assert.Equal(0.1f, cab.LateralAcceleration);
Assert.Equal(Lights.HeadlightLeft | Lights.HeadlightUpper | Lights.HeadlightRight, cab.LightsHead);
}
[Fact]
public void A_cab_written_before_the_protection_and_the_lateral_acceleration_is_still_read()
{
var r = BlackBoxReader.Read(new BlackBoxFile().Info().Cab(0, Head, 1150, 40, extended: false).User(0, Head, true).End(1).Stream());
var cab = Assert.Single(r.Cab);
Assert.Equal(0, cab.CabEnd);
Assert.Equal(SecurityFlags.None, cab.Security);
Assert.Equal(0f, cab.LateralAcceleration);
Assert.Equal(0, Assert.Single(r.UserVehicles).CabEnd);
Assert.Equal(0, r.Malformed);
}
[Fact]
public void The_couplings_tell_the_train_at_any_moment()
{
var r = Journey();
Assert.Equal(new HashSet<int> { 1, 2, 3 }, r.ConsistAt((int)Head, 79));
Assert.Equal(new HashSet<int> { 1, 2 }, r.ConsistAt((int)Head, 81));
Assert.Equal(new HashSet<int> { 3 }, r.ConsistAt((int)Tail, 81));
// What the trains were made of at the start is no coupling done.
var change = Assert.Single(r.CouplingEvents());
Assert.Equal(80, change.Time);
Assert.Single(r.UserCouplings());
}
[Fact]
public void The_stations_of_someone_else_s_train_are_not_the_user_s()
{
var r = Journey();
Assert.DoesNotContain(r.UserStations(), s => s.Vehicle == Stranger);
Assert.Equal(4, r.UserStations().Count());
}
[Fact]
public void The_timetable_shown_is_the_one_the_train_had_then()
{
var r = Journey();
Assert.Equal("ROJ1", r.TimetableAt(100)!.Train);
Assert.Equal("ROJ2", r.TimetableAt(110)!.Train);
var first = StationProgress.Of(r, 50);
Assert.Equal(3, first.Count);
Assert.Equal(StationOutcome.Stopped, first[1].Outcome);
Assert.Equal(60, first[1].ArrivedAt);
Assert.Equal(70, first[1].DepartedAt);
Assert.Equal(0, first[1].ArrivalDelay!.Value, 2);
Assert.Equal(-1 / 3.0, first[1].DepartureDelay!.Value, 2);
Assert.Equal(StationOutcome.Missed, first[2].Outcome);
Assert.Equal(StationOutcome.Stopped, StationProgress.Of(r, 120)[1].Outcome);
}
[Fact]
public void The_delay_follows_the_train_from_station_to_station()
{
var r = Journey();
Assert.Null(StationProgress.DelayAt(r, 0.5));
var standing = StationProgress.DelayAt(r, 65)!;
Assert.True(standing.Standing);
Assert.Equal("Stacja_B", standing.Station);
Assert.Equal(0, standing.Minutes, 2);
var left = StationProgress.DelayAt(r, 80)!;
Assert.False(left.Standing);
Assert.Equal(-1 / 3.0, left.Minutes, 2);
// At D, arrived at 10:35:55 for 10:40: early, and nothing to depart by.
var second = StationProgress.DelayAt(r, 118)!;
Assert.Equal("ROJ2", second.Train);
Assert.True(second.Minutes < -4);
// Left B at 10:35:10, C planned 10:37:30: by 10:35:50 (t = 110 of ROJ1's time) not yet overdue.
Assert.Equal(-1 / 3.0, StationProgress.DelayAt(r, 90)!.Minutes, 2);
var delays = StationProgress.StationDelays(r, 80);
Assert.Equal(-1 / 3.0, delays["Stacja B"], 2);
}
[Fact]
public void The_names_of_the_stations_are_shown_without_what_tells_their_stop_points_apart()
{
Assert.Equal("Bałtyk Główny", StationNames.Display("Bałtyk_Główny#2"));
Assert.Equal("Turów", StationNames.Display("Turów"));
Assert.Equal("Psie Pole po", StationNames.Display("Psie_Pole_po#"));
}
[Fact]
public void The_horn_counts_when_it_sounded_after_the_horn_point()
{
var checks = Journey().UserHornChecks().ToList();
Assert.Equal(2, checks.Count);
Assert.True(checks[0].Sounded);
Assert.False(checks[1].Sounded);
}
[Fact]
public void The_camera_is_known_from_its_first_record()
{
var r = Journey();
Assert.Null(r.CameraAt(-1));
Assert.Equal(CameraMode.Cab, r.CameraAt(49)!.Value.Mode);
Assert.Equal(CameraMode.Free, r.CameraAt(51)!.Value.Mode);
}
[Fact]
public void The_summary_counts_the_stops_of_every_timetable_the_horns_and_the_protection()
{
var summary = Journey().Summarize();
Assert.Equal(2, summary.Stops);
Assert.Equal(1, summary.StopsMissed);
Assert.Equal(2, summary.HornPoints);
Assert.Equal(1, summary.HornsMissed);
Assert.Equal(1, summary.SecurityBrakings);
// Taken over half a second, as the lateral acceleration jumps from sample to sample.
Assert.Equal(1.2f, summary.MaxLateralAcceleration, 3);
}
}
public class TrainDelayTests
{
[Fact]
public void A_train_held_on_the_way_grows_late_by_the_time_of_the_next_station()
{
// Clock 10:34 at t = 0. Departs A at 10:35 (t = 60) on time, held short of B planned at 10:37.
var f = new BlackBoxFile().Info()
.Timetable(0, 1, "ROJ9", "A", "B", ("A", -1, 635), ("B", 637, 638))
.Station(1, 1, 1, 1, "A", 1150);
for (double t = 0; t <= 400; t += 0.5)
f.Cab(t, 1, 1150 + Math.Max(0, Math.Min(t, 90) - 60) * 10, t is > 60 and < 90 ? 40 : 0);
var r = BlackBoxReader.Read(f.End(400).Stream());
Assert.Equal(0, StationProgress.DelayAt(r, 100)!.Minutes, 1);
// 10:40 at t = 360: three minutes past B's arrival, and not there.
var held = StationProgress.DelayAt(r, 360)!;
Assert.False(held.Standing);
Assert.Equal(3, held.Minutes, 2);
}
}
/// <summary>A train given its next timetable, one recording holding both.</summary>
public class NextTimetableTests
{
[Fact]
public void A_station_written_just_before_the_next_timetable_goes_with_it()
{
// ROJ1 stops at A and ends at B; at B it is given ROJ2, which starts there. A recording made before
// the simulator wrote the timetable first has B of ROJ2 half a second ahead of ROJ2 itself (here left behind,
// which on ROJ1 would mark A missed).
var f = new BlackBoxFile().Info()
.Timetable(0, 1, "ROJ1", "A", "B", ("A", -1, 635), ("B", 637, -1))
.Station(1, 1, 1, 1, "A", 1150)
.Station(50, 1, 1, 2, "B", 1150)
.Station(99.5, 1, 3, 1, "B", 1150)
.Timetable(100, 1, "ROJ2", "B", "C", ("B", -1, 640), ("C", 645, -1));
for (double t = 0; t <= 120; t += 0.5)
f.Cab(t, 1, 1150, 0);
var r = BlackBoxReader.Read(f.End(120).Stream());
var first = StationProgress.Of(r, r.Timetables[0]);
Assert.Equal(StationOutcome.Stopped, first[0].Outcome);
Assert.Equal(1, first[0].Event!.Time);
var second = StationProgress.Of(r, r.Timetables[1]);
Assert.Equal(StationOutcome.Missed, second[0].Outcome);
Assert.Equal(99.5, second[0].Event!.Time);
}
}

View File

@@ -0,0 +1,180 @@
using StarterNG.Domain.Tapes;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests.BlackBox;
public class BlackBoxListingTests
{
private static readonly DateTime Launched = new(2025, 12, 31, 23, 0, 0, DateTimeKind.Utc);
private static string Log(string name) => TestInstallation.At("physicslog", name);
/// <summary>A black box's name: the simulator stamps it with the local time it started at.</summary>
private static string Box(string scenery, DateTime startedUtc) =>
$"{scenery}_{startedUtc.ToLocalTime():yyyy-MM-dd_HH-mm-ss}.blackbox";
[Fact]
public void Each_run_keeps_its_own_black_box_next_to_its_tapes()
{
string first = Box("td", Launched.AddSeconds(5)), second = Box("td", Launched.AddHours(1).AddSeconds(5));
var files = new InMemoryFileSystem()
.WithFile(Log("ra.dat"), "t")
.WithFile(Log(first), "b")
.WithFile(Log(second), "b");
var installation = new TestInstallation(files);
var tapes = installation.Tapes;
installation.Clock.Now = Launched;
tapes.RecordLaunch("td.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "ra", new[] { "ra" }, "A");
installation.Clock.Now = Launched.AddHours(1);
tapes.RecordLaunch("td.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "ra", new[] { "ra" }, "B");
files.WrittenAt(Log(first), Launched.AddMinutes(30))
.WrittenAt(Log(second), Launched.AddMinutes(90))
.WrittenAt(Log("ra.dat"), Launched.AddMinutes(90));
var sessions = tapes.Sessions();
Assert.Equal(new[] { "B", "A" }, sessions.Select(session => session.Launch!.SceneryName));
Assert.EndsWith(second, Assert.Single(sessions[0].BlackBoxes).Path);
Assert.Single(sessions[0].Tapes);
// The tape of the first run was written over by the second; its black box was not.
Assert.EndsWith(first, Assert.Single(sessions[1].BlackBoxes).Path);
Assert.Empty(sessions[1].Tapes);
Assert.Equal(Launched.AddMinutes(30), sessions[1].LastWrittenUtc);
}
[Fact]
public void A_black_box_is_not_taken_for_a_tape()
{
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Log("ra.dat"), "t")
.WithFile(Log("td_2026-03-01_12-00-00.blackbox"), "b"));
var session = Assert.Single(installation.Tapes.Sessions());
Assert.Equal("ra", Assert.Single(session.Tapes).Vehicle);
Assert.Single(session.BlackBoxes);
Assert.Equal("ra", Assert.Single(installation.Tapes.List()).Vehicle);
}
[Fact]
public void Black_boxes_with_no_launch_noted_go_with_the_tapes_written_about_the_same_time()
{
var early = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Log("a.dat"), "t")
.WithFile(Log("td_2026-03-01_11-00-00.blackbox"), "b")
.WithFile(Log("td_2026-03-01_12-30-00.blackbox"), "b")
.WrittenAt(Log("a.dat"), early)
.WrittenAt(Log("td_2026-03-01_11-00-00.blackbox"), early.AddSeconds(2))
.WrittenAt(Log("td_2026-03-01_12-30-00.blackbox"), early.AddHours(1)));
var sessions = installation.Tapes.Sessions();
Assert.Equal(2, sessions.Count);
Assert.All(sessions, session => Assert.Null(session.Launch));
// Newest first: the black box on its own, then the run with the tape.
Assert.Empty(sessions[0].Tapes);
Assert.EndsWith("12-30-00.blackbox", Assert.Single(sessions[0].BlackBoxes).Path);
Assert.Single(sessions[1].Tapes);
Assert.EndsWith("11-00-00.blackbox", Assert.Single(sessions[1].BlackBoxes).Path);
Assert.Equal(early, sessions[1].StartedUtc);
}
[Fact]
public void The_black_box_of_a_running_session_is_listed_while_it_is_written()
{
var files = new InMemoryFileSystem();
var installation = new TestInstallation(files);
installation.Clock.Now = Launched;
var tapes = installation.Tapes;
tapes.RecordLaunch("td.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "ra");
string box = Box("td", Launched.AddSeconds(20));
files.WithFile(Log(box), "b")
.WrittenAt(Log(box), Launched.AddMinutes(5));
installation.SimulatorRunning = true;
var running = Assert.Single(tapes.Sessions());
Assert.True(running.Running);
Assert.Empty(running.Tapes);
Assert.Single(running.BlackBoxes);
}
[Fact]
public void A_black_box_of_another_scenery_written_after_a_launch_is_not_taken_for_its_run()
{
// Copied in, or a run started without the starter: written after the last launch, but of another scenery.
var files = new InMemoryFileSystem();
var installation = new TestInstallation(files);
installation.Clock.Now = Launched;
installation.Tapes.RecordLaunch("$baltyk.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "ra", new[] { "ra" }, "Bałtyk");
string own = Box("baltyk", Launched.AddSeconds(10)), other = Box("l053_poludnie", Launched.AddHours(3));
files.WithFile(Log(own), "b").WrittenAt(Log(own), Launched.AddMinutes(40))
.WithFile(Log(other), "b").WrittenAt(Log(other), Launched.AddHours(4));
var sessions = installation.Tapes.Sessions();
Assert.Equal(2, sessions.Count);
var loose = Assert.Single(sessions, session => session.Launch is null);
Assert.EndsWith(other, Assert.Single(loose.BlackBoxes).Path);
var launched = Assert.Single(sessions, session => session.Launch is not null);
Assert.EndsWith(own, Assert.Single(launched.BlackBoxes).Path);
}
[Fact]
public void A_tape_written_after_another_run_began_is_not_taken_for_the_launch_before()
{
// The starter launched Bałtyk; later a run of another scenery, not launched from it, wrote its tape and black box.
var files = new InMemoryFileSystem();
var installation = new TestInstallation(files);
installation.Clock.Now = Launched;
installation.Tapes.RecordLaunch("baltyk.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "ep07", new[] { "ep07" }, "Bałtyk");
string box = Box("td", Launched.AddHours(5));
files.WithFile(Log("ep07.dat"), "t").WrittenAt(Log("ep07.dat"), Launched.AddMinutes(50))
.WithFile(Log("bb-su45.dat"), "t").WrittenAt(Log("bb-su45.dat"), Launched.AddHours(5).AddMinutes(8))
.WithFile(Log(box), "b").WrittenAt(Log(box), Launched.AddHours(5).AddMinutes(8));
var sessions = installation.Tapes.Sessions();
var baltyk = Assert.Single(sessions, session => session.Launch is not null);
Assert.Equal("ep07", Assert.Single(baltyk.Tapes).Vehicle);
Assert.Empty(baltyk.BlackBoxes);
var other = Assert.Single(sessions, session => session.Launch is null);
Assert.Equal("bb-su45", Assert.Single(other.Tapes).Vehicle);
Assert.Single(other.BlackBoxes);
Assert.Null(installation.Tapes.ContextOf(other.Tapes[0]).StartClock);
}
[Fact]
public void A_black_box_started_before_a_launch_is_not_taken_for_it()
{
// Started earlier, and only finished writing after the starter launched the same scenery again.
var files = new InMemoryFileSystem();
var installation = new TestInstallation(files);
installation.Clock.Now = Launched;
installation.Tapes.RecordLaunch("td.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "ra");
string early = Box("td", Launched.AddHours(-2));
files.WithFile(Log(early), "b").WrittenAt(Log(early), Launched.AddMinutes(1));
var session = Assert.Single(installation.Tapes.Sessions());
Assert.Null(session.Launch);
Assert.Single(session.BlackBoxes);
}
[Theory]
[InlineData("$td.scn", "td")]
[InlineData("l053_poludnie.scn", "l053_poludnie")]
[InlineData("Bałtyk zima.scn", "Ba_tyk_zima")]
public void The_scenery_is_named_as_the_simulator_names_the_black_box(string scenery, string stem) =>
Assert.Equal(stem, StarterNG.Application.HaslerTapes.SceneryStem(scenery));
[Theory]
[InlineData("Ba_tyk_zima", true)] // Windows: 'ł' is one byte of its code page
[InlineData("Ba__tyk_zima", true)] // Linux: two bytes of UTF-8
[InlineData("BA__TYK_ZIMA", true)]
[InlineData("Baltyk_zima", false)]
public void A_letter_outside_ascii_matches_however_many_bytes_it_was(string named, bool same) =>
Assert.Equal(same, StarterNG.Application.HaslerTapes.SameStem(
StarterNG.Application.HaslerTapes.SceneryStem("Bałtyk zima.scn"), named));
}

View File

@@ -0,0 +1,229 @@
using System.Numerics;
using Eu07.BlackBox;
namespace StarterNG.Tests.BlackBox;
public class BlackBoxReaderTests
{
private static BlackBoxFile Session() => new BlackBoxFile()
.Info()
.Track(0, "start", new Vector3(5, 0.4f, 1100), new Vector3(5, 0.4f, 1200))
.Track(1, "zwr01", 1, 0, new Vector3(5, 0.4f, 1200), new Vector3(5, 0.4f, 1234))
.Track(1, "zwr01", 1, 1, new Vector3(5, 0.4f, 1200), new Vector3(8, 0.4f, 1234))
.Signal(0, "stacja1_a", 2.5, 3.0, 1300)
.Vehicle(1, "ep07-bb", "ROJ65113")
.Vehicle(2, "bdnu")
.Switch(0, 1, 0)
.Aspect(0, 0, 0, -1)
.Clock(0, 10 * 3600 + 34 * 60)
.User(0, 1, true)
.Vehicles(0, true, (1, 5, 1150, 0), (2, 5, 1130, 0))
.Cab(0.1, 1, 1150, 0)
.Command(1.0, 1, true, "aidriverenable")
.Command(1.1, 1, false, "aidriverenable")
.Driver(1.0, 1, 2)
.Aspect(2.0, 0, 40, -1)
.Switch(3.0, 1, 1)
.Passed(4.0, 1, 0, "stacja1_a_sem", 40, 38.5f, 0x01)
.Removed(5.0, 2)
.End(6.0);
[Fact]
public void Every_record_of_a_session_is_read_as_the_simulator_wrote_it()
{
var r = BlackBoxReader.Read(Session().Stream());
Assert.Equal(1, r.Version);
Assert.Equal("td.scn", r.Info!.Scenery);
Assert.Equal(new TimeSpan(10, 34, 0), r.Info.StartClock);
Assert.Equal(60f, r.Info.KeyframeInterval);
Assert.Equal(3, r.Tracks.Count);
Assert.Equal(2, r.TrackWays(1).Count);
Assert.Equal(TrackKind.SwitchBranch, r.TrackWays(1)[1].Kind);
Assert.Equal(new Vector3(8, 0.4f, 1234), r.TrackWays(1)[1].Points[1]);
Assert.Equal("stacja1_a", r.Signal(0)!.Name);
Assert.Equal(1300, r.Signal(0)!.Position.Z);
Assert.Equal("ROJ65113", r.Vehicle(1)!.Train);
Assert.Equal(5.0, r.Vehicle(2)!.RemovedAt);
var cab = Assert.Single(r.Cab);
Assert.Equal(1, cab.Vehicle);
Assert.Equal(new Position(5, 0.4, 1150), cab.Position);
Assert.Equal(Driver.Human, cab.Driving);
Assert.True(cab.AiValid);
Assert.Equal(3, cab.MainController);
Assert.Equal(5.0f, cab.BrakePipe);
Assert.Equal(40f, cab.Ai.TargetKmh);
Assert.Equal(60f, cab.Ai.TimetableVmaxKmh);
Assert.False(cab.Ai.HasNextLimit);
Assert.Equal(CabDevices.Battery | CabDevices.MainBreaker | CabDevices.PantographFront, cab.Devices);
Assert.True(cab.Has(CabDevices.MainBreaker));
Assert.False(cab.Has(CabDevices.Compressor));
Assert.Equal(8.5f, cab.MainReservoir);
Assert.Equal(3000f, cab.Voltage);
Assert.Equal(1100f, cab.EngineRpm);
Assert.Equal(Lights.HeadlightLeft | Lights.HeadlightUpper | Lights.HeadlightRight, cab.LightsHead);
Assert.Equal(Lights.RedMarkerLeft | Lights.RedMarkerRight, cab.LightsTail);
Assert.Equal(2, r.Commands.Count);
Assert.Equal("aidriverenable", r.Commands[0].Name);
Assert.True(r.Commands[0].Pressed);
Assert.Equal(2.0, r.Commands[0].Param2);
Assert.Equal(Driver.Ai, Assert.Single(r.DriverChanges).Driving);
var passed = Assert.Single(r.Passings);
Assert.Equal("stacja1_a_sem", passed.Event);
Assert.Equal(PassingFlags.Shunt, passed.Flags);
Assert.Equal(38.5f, passed.SpeedKmh);
Assert.False(passed.AtDanger);
Assert.True(r.Complete);
Assert.Equal(6.0, r.Duration);
Assert.Equal(0, r.Unknown);
Assert.Equal(0, r.Malformed);
}
[Fact]
public void The_switches_and_the_aspects_answer_for_any_moment()
{
var r = BlackBoxReader.Read(Session().Stream());
Assert.Equal(0, r.SwitchAt(1, 2.9));
Assert.Equal(1, r.SwitchAt(1, 3.0));
Assert.Equal(-1, r.SwitchAt(7, 3.0));
Assert.Equal(0f, r.AspectAt(0, 1.9)!.Value.Speed1);
Assert.Equal(40f, r.AspectAt(0, 2.0)!.Value.Speed1);
Assert.Null(r.AspectAt(3, 2.0));
}
[Fact]
public void A_file_still_written_is_read_on_from_where_the_last_read_stopped()
{
var bytes = Session().Bytes;
var whole = BlackBoxReader.Read(new MemoryStream(bytes));
// Cut at every byte: a record cut short waits for the rest, nothing is read twice.
for (int cut = 0; cut <= bytes.Length; cut++)
{
var reader = new BlackBoxReader();
reader.ReadMore(new MemoryStream(bytes, 0, cut));
Assert.False(reader.Recording.Complete && cut < bytes.Length);
reader.ReadMore(new MemoryStream(bytes));
Assert.Equal(whole.Tracks.Count, reader.Recording.Tracks.Count);
Assert.Equal(whole.Commands.Count, reader.Recording.Commands.Count);
Assert.Equal(whole.Cab.Count, reader.Recording.Cab.Count);
Assert.Equal(whole.Aspects.Count, reader.Recording.Aspects.Count);
Assert.True(reader.Recording.Complete);
Assert.Equal(bytes.Length, reader.Offset);
}
}
[Fact]
public void A_record_of_a_later_version_is_passed_over_by_its_length()
{
var file = new BlackBoxFile().Info()
.Record(0x7e, w => w.Write(new byte[40]))
.Command(1.0, 1, true, "hornhighactivate")
.End(2.0);
var r = BlackBoxReader.Read(file.Stream());
Assert.Equal(1, r.Unknown);
Assert.Equal("hornhighactivate", Assert.Single(r.Commands).Name);
Assert.True(r.Complete);
}
[Fact]
public void A_record_shorter_than_its_type_is_passed_over_and_counted()
{
var file = new BlackBoxFile().Record(0x20, w => w.Write(1.0)).Clock(1.0, 3600).End(2.0);
var r = BlackBoxReader.Read(file.Stream());
Assert.Empty(r.Cab);
Assert.Equal(1, r.Malformed);
Assert.Single(r.Clocks);
}
[Fact]
public void Texts_longer_than_a_byte_can_count_and_letters_beyond_ascii_read_back()
{
string name = "żółw_" + new string('x', 300);
var r = BlackBoxReader.Read(new BlackBoxFile().Signal(0, name, 0, 0, 0).Signal(1, "", 1, 1, 1).Stream());
Assert.Equal(name, r.Signal(0)!.Name);
Assert.Equal("", r.Signal(1)!.Name);
}
[Fact]
public void Something_else_than_a_black_box_or_a_version_not_known_is_refused()
{
Assert.Throws<InvalidDataException>(() => BlackBoxReader.Read(new MemoryStream("Time[s] Velocity[m/s]\r\n"u8.ToArray())));
Assert.Throws<InvalidDataException>(() => BlackBoxReader.Read(new BlackBoxFile(version: 2).Stream()));
}
[Fact]
public void A_file_written_anew_under_the_reader_is_told_so()
{
var reader = new BlackBoxReader();
reader.ReadMore(Session().Stream());
Assert.Throws<InvalidDataException>(() => reader.ReadMore(new BlackBoxFile().Info().Stream()));
}
[Fact]
public void A_vehicle_listed_only_when_it_moved_stands_until_the_look_before_it_was_seen_moving()
{
var r = BlackBoxReader.Read(new BlackBoxFile()
.Info()
.Vehicle(2, "et22")
.Vehicles(0, true, (2, 0, 0, 0))
.Vehicles(60, true, (2, 0, 0, 0))
.Vehicles(90, false, (2, 0, 10, 36))
.Vehicles(91, false, (2, 0, 20, 36))
.Stream());
Assert.Equal(0f, r.VehiclesAt(30).Single().Position.Z);
// Not listed from 60 to 90: it stood until 88.5, the look interval and a half before.
Assert.Equal(0f, r.VehiclesAt(88).Single().Position.Z);
Assert.InRange(r.VehiclesAt(89.25).Single().Position.Z, 4.9f, 5.1f);
Assert.InRange(r.VehiclesAt(90.5).Single().Position.Z, 14.9f, 15.1f);
Assert.Equal(20f, r.VehiclesAt(200).Single().Position.Z);
}
[Fact]
public void A_vehicle_removed_is_on_the_map_no_more()
{
var r = BlackBoxReader.Read(Session().Stream());
Assert.Equal(2, r.VehiclesAt(4.9).Count);
Assert.Equal(1, Assert.Single(r.VehiclesAt(5.0)).Id);
}
[Fact]
public void The_clock_goes_on_from_the_last_tick_and_over_midnight()
{
var r = BlackBoxReader.Read(new BlackBoxFile()
.Info(secondOfDay: 86390)
.Clock(0, 86390)
.Clock(1, 86391)
.Stream());
Assert.Equal(new TimeSpan(23, 59, 51), r.ClockAt(1));
Assert.Equal(86395.5, r.ClockAt(5.5).TotalSeconds, 3);
Assert.Equal(1.0, r.ClockAt(11).TotalSeconds, 3);
}
[Fact]
public void The_position_of_the_train_runs_between_its_samples_and_not_across_a_gap()
{
var r = BlackBoxReader.Read(new BlackBoxFile()
.Cab(0.0, 1, 100, 36)
.Cab(0.1, 1, 101, 36)
.Cab(5.0, 1, 200, 36)
.Stream());
Assert.Equal(100.5, r.CabPositionAt(0.05)!.Value.Z, 6);
Assert.Null(r.CabPositionAt(3.0));
Assert.Null(r.CabPositionAt(-1));
}
}

View File

@@ -0,0 +1,247 @@
using System.Linq;
using Eu07.BlackBox;
namespace StarterNG.Tests.BlackBox;
/// <summary>The light signals at the head and the tail of the user's train, against those it was to show.</summary>
public class HeadCodeTests
{
[Theory]
[InlineData(Lights.HeadlightLeft | Lights.HeadlightRight | Lights.HeadlightUpper, HeadCode.Pc1)]
[InlineData(Lights.HeadlightLeft | Lights.HeadlightRight | Lights.HeadlightUpper | Lights.HighBeamLeft | Lights.HighBeamRight, HeadCode.Pc1)]
[InlineData(Lights.RedMarkerLeft | Lights.HeadlightRight | Lights.HeadlightUpper, HeadCode.Pc2)]
[InlineData(Lights.RedMarkerLeft | Lights.RedMarkerRight, HeadCode.Pc5)]
[InlineData(Lights.RearEndSignals, HeadCode.Pc5)]
[InlineData(Lights.HeadlightRight, HeadCode.Tb1)]
[InlineData(Lights.HeadlightLeft, HeadCode.Tb1)]
[InlineData(Lights.None, HeadCode.Off)]
[InlineData(Lights.HeadlightLeft | Lights.HeadlightRight, HeadCode.Other)]
public void The_lamps_lit_tell_the_signal(Lights lights, HeadCode code) => Assert.Equal(code, HeadCodes.Of(lights));
private const ushort Pc1 = 0x15, Pc5 = 0x22, Tb1 = 0x10;
private static Recording Drive(params (double From, double To, ushort Head, ushort Tail, byte Movement, short HintHead)[] stretches)
{
var f = new BlackBoxFile().Info();
foreach (var (from, to, head, tail, movement, hint) in stretches)
for (double t = from; t < to; t += 0.5)
f.Cab(t, 1, 1000 + t * 10, 40, lightsHead: head, lightsTail: tail, movement: movement, hintHead: hint);
return BlackBoxReader.Read(f.End(stretches[^1].To).Stream());
}
[Fact]
public void A_train_run_is_to_show_Pc1_and_Pc5()
{
var summary = Drive((0, 60, Pc1, Pc5, 1, -1)).Summarize();
Assert.True(summary.LightsJudgedSeconds > 55);
Assert.Equal(0, summary.WrongLightsSeconds);
Assert.Empty(summary.LightsFaults);
}
[Fact]
public void Shunting_lights_on_a_train_run_count_as_wrong_once_for_the_whole_stretch()
{
var summary = Drive((0, 30, Pc1, Pc5, 1, -1), (30, 60, Tb1, Tb1, 1, -1), (60, 90, Pc1, Pc5, 1, -1)).Summarize();
Assert.Equal(30, summary.WrongLightsSeconds, 0);
var fault = Assert.Single(summary.LightsFaults);
Assert.Equal(HeadCode.Tb1, fault.Head);
Assert.Equal(HeadCode.Pc1, fault.HeadRequired);
Assert.True(fault.HeadWrong && fault.TailWrong);
}
[Fact]
public void Shunting_is_to_show_Tb1()
{
var summary = Drive((0, 30, Tb1, Tb1, 2, -1), (30, 40, Pc1, Pc5, 2, -1)).Summarize();
var fault = Assert.Single(summary.LightsFaults);
Assert.Equal(HeadCode.Tb1, fault.HeadRequired);
}
[Fact]
public void The_pattern_the_timetable_asks_for_is_the_one_to_show()
{
// Pc 2 asked for at the head: the left red marker, the right headlight and the upper one.
const short pc2 = 0x16;
var summary = Drive((0, 30, Pc1, Pc5, 1, pc2)).Summarize();
var fault = Assert.Single(summary.LightsFaults);
Assert.Equal(HeadCode.Pc2, fault.HeadRequired);
Assert.False(fault.TailWrong);
}
private static Recording DriveWith(ushort head, ushort tail, ushort equippedHead, ushort equippedTail, byte movement = 1, byte driving = 1)
{
var f = new BlackBoxFile().Info();
for (double t = 0; t < 30; t += 0.5)
f.Cab(t, 1, 1000 + t * 10, 40, driving: driving, lightsHead: head, lightsTail: tail, movement: movement,
equippedHead: equippedHead, equippedTail: equippedTail);
return BlackBoxReader.Read(f.End(30).Stream());
}
[Fact]
public void The_lamps_the_vehicles_have_are_read()
{
var sample = DriveWith(Pc1, Pc5, 0x1B5, 0x22).Cab[0];
Assert.Equal((Lights)0x1B5, sample.EquippedHead);
Assert.Equal((Lights)0x22, sample.EquippedTail);
}
[Theory]
// without the upper headlight Pc 1 is the two others
[InlineData(0x11, 0x11)]
// with auxiliary lamps, those and the upper headlight
[InlineData(0x184, 0x1B5)]
// a vehicle with no lamps for it: the rear-end signals
[InlineData(0x40, 0x40)]
public void Pc1_is_what_the_vehicle_can_show_of_it(ushort lit, ushort equipped)
{
var summary = DriveWith(lit, Pc5, equipped, Pc5).Summarize();
Assert.True(summary.LightsJudgedSeconds > 25);
Assert.Empty(summary.LightsFaults);
}
[Fact]
public void A_tail_with_the_rear_end_signals_only_shows_Pc5_with_them()
{
Assert.Empty(DriveWith(Pc1, 0x40, Pc1, 0x40).Summarize().LightsFaults);
var fault = Assert.Single(DriveWith(Pc1, 0x00, Pc1, 0x40).Summarize().LightsFaults);
Assert.False(fault.HeadWrong);
Assert.True(fault.TailWrong);
}
[Fact]
public void What_drives_the_train_and_the_rest_are_read_when_written()
{
var f = new BlackBoxFile().Info();
f.Cab(0, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 4, oilTemperature: 71.5f);
f.Cab(0.5, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22);
var cab = BlackBoxReader.Read(f.End(1).Stream()).Cab;
var extra = Assert.NotNull(cab[0].Extra);
Assert.Equal(EngineKind.DieselElectric, extra.Engine);
Assert.Equal(3, extra.RadioChannel);
Assert.Equal(71.5f, extra.OilTemperature);
Assert.Equal(1.0f, extra.Clutch);
Assert.Equal(2.5f, extra.ConsistBrakeCylinder);
// an older sample has none
Assert.Null(cab[1].Extra);
}
[Fact]
public void A_vehicle_with_no_lamps_is_not_judged()
{
var recording = DriveWith(0, 0, 0, 0);
Assert.Null(HeadCodes.HeadRight(recording.Cab[0]));
Assert.Null(HeadCodes.TailRight(recording.Cab[0]));
var summary = recording.Summarize();
Assert.Equal(0, summary.LightsJudgedSeconds);
Assert.Empty(summary.LightsFaults);
}
[Fact]
public void A_vehicle_with_all_the_lamps_is_to_light_all_three_for_Pc1()
{
var fault = Assert.Single(DriveWith(0x11, Pc5, 0x35, Pc5).Summarize().LightsFaults);
Assert.True(fault.HeadWrong);
Assert.Equal(HeadCode.Pc1, fault.HeadRequired);
}
[Fact]
public void The_lights_the_autopilot_sets_are_not_the_users()
{
var summary = DriveWith(Tb1, Tb1, Pc1, Pc5, driving: 2).Summarize();
Assert.Equal(0, summary.LightsJudgedSeconds);
Assert.Empty(summary.LightsFaults);
}
[Fact]
public void An_older_recording_reads_a_pattern_asked_for_as_the_signal_it_shows()
{
// Pc 5 asked for at the tail, the rear-end signals lit, no lamps written: Pc 5 as before
var f = new BlackBoxFile().Info();
for (double t = 0; t < 30; t += 0.5)
f.Cab(t, 1, 1000 + t * 10, 40, lightsHead: Pc1, lightsTail: 0x40, movement: 1, hintTail: 0x22);
var summary = BlackBoxReader.Read(f.End(30).Stream()).Summarize();
Assert.True(summary.LightsJudgedSeconds > 25);
Assert.Empty(summary.LightsFaults);
}
[Fact]
public void An_older_recording_tells_nothing_of_the_signals()
{
var f = new BlackBoxFile().Info();
for (double t = 0; t < 30; t += 0.5)
f.Cab(t, 1, 1000 + t * 10, 40, lightsHead: Tb1);
var summary = BlackBoxReader.Read(f.End(30).Stream()).Summarize();
Assert.Equal(0, summary.LightsJudgedSeconds);
}
}
/// <summary>The user going over to another vehicle: the timetable of the train is the one of the train the user is in.</summary>
public class UserVehicleTests
{
private const byte Coupled = 0x83;
[Fact]
public void Another_vehicle_of_the_same_train_keeps_its_timetable_another_train_has_none()
{
// The user in vehicle 1 of the unit 1-2 with ROJ1; at t = 50 over to the other cab, at t = 100 into vehicle 9, on its own.
var f = new BlackBoxFile().Info()
.Coupling(0, 1, 1, 2, 0, Coupled, 0, 0)
.Timetable(0, 1, "ROJ1", "A", "B", ("A", -1, 635), ("B", 640, -1));
for (double t = 0; t < 150; t += 0.5)
f.Cab(t, t < 50 ? 1u : t < 100 ? 2u : 9u, 1000, 0);
var r = BlackBoxReader.Read(f.End(150).Stream());
Assert.Equal("ROJ1", r.TimetableAt(20)!.Train);
Assert.Equal("ROJ1", r.TimetableAt(70)!.Train);
Assert.Null(r.TimetableAt(120));
}
[Fact]
public void Single_vehicles_with_no_coupling_written_are_still_told_apart()
{
// A recording made with the movement written, where no train is longer than one vehicle: no coupling at all.
var f = new BlackBoxFile().Info()
.Timetable(0, 1, "ROJ1", "A", "B", ("A", -1, 635), ("B", 640, -1));
for (double t = 0; t < 100; t += 0.5)
f.Cab(t, t < 50 ? 1u : 9u, 1000, 0, movement: 1);
var r = BlackBoxReader.Read(f.End(100).Stream());
Assert.Equal("ROJ1", r.TimetableAt(20)!.Train);
Assert.Null(r.TimetableAt(70));
}
[Fact]
public void An_older_recording_with_no_coupling_keeps_the_timetable()
{
var f = new BlackBoxFile().Info()
.Timetable(0, 1, "ROJ1", "A", "B", ("A", -1, 635), ("B", 640, -1));
for (double t = 0; t < 100; t += 0.5)
f.Cab(t, t < 50 ? 1u : 2u, 1000, 0);
var r = BlackBoxReader.Read(f.End(100).Stream());
Assert.Equal("ROJ1", r.TimetableAt(70)!.Train);
}
}
/// <summary>The departures and the platforms in the summary.</summary>
public class StationSummaryTests
{
[Fact]
public void The_summary_tells_the_largest_delay_leaving_and_the_stops_off_the_platform()
{
// Clock 10:34 at t = 0, leaves A at once. Stops at B (10:36 to 10:37) from t = 120, leaves at t = 240 (10:38): a minute late.
var f = new BlackBoxFile().Info()
.Timetable(0, 1, "ROJ1", "A", "C", ("A", -1, 634), ("B", 636, 637), ("C", 640, -1))
.Station(1, 1, 1, 1, "A", 1000)
.Station(120, 1, 1, 2, "Stacja_B", 1000, distance: 74.7f, trainLength: 129.8f, platform: 201);
for (double t = 0; t < 300; t += 0.5)
f.Cab(t, 1, 1000, t is >= 120 and < 240 or < 2 ? 0 : 40);
var r = BlackBoxReader.Read(f.End(300).Stream());
var summary = r.Summarize();
Assert.Equal(1, summary.MaxDepartureDelayMinutes!.Value, 1);
var off = Assert.Single(summary.OffPlatform);
Assert.Equal("B", off.Station);
Assert.Equal(3.5, off.Metres, 1);
}
}

View File

@@ -0,0 +1,284 @@
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.VisualTree;
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
/// <summary>
/// The black box's own drawn panels as a screen reader user meets them: reached with Tab,
/// walked with the keys, their value and description read, what they show said aloud.
/// </summary>
[Collection(AvaloniaControls.Name)]
public class BlackBoxViewsTests
{
private const uint Head = 1;
/// <summary>
/// The user in vehicle 1 from t = 0 to 120: timetable ROJ1 standing at A, stopping at B
/// from 60 to 70, passing C at 100; the clock at 10:34 (634 min).
/// </summary>
private static Recording Journey(bool extended = true, byte? engine = null)
{
var f = new BlackBoxFile().Info()
.Vehicle(Head, "EU07-005", "ROJ1")
.User(0, Head, true, 1)
.Timetable(0, Head, "ROJ1", "A", "C", ("A", -1, 634), ("Stacja_B", 635, 635.5f), ("C", 637.5f, 638))
.Station(1, Head, 4, 1, "A", 1150);
for (double t = 0; t <= 120; t += 0.5)
{
float speed = t is >= 55 and < 70 ? 0 : 40;
f.Cab(t, Head, 1150 + t * 10, speed, extended: extended, engine: engine, nextLimit: 60, nextDistance: 500,
brakeCylinder: t is >= 50 and < 70 ? 2.5f : 0, devices: 0x0207);
}
f.Station(60, Head, 1, 2, "Stacja_B", 1300)
.Station(100, Head, 3, 3, "C", 2150);
return BlackBoxReader.Read(f.End(120).Stream());
}
private static IValueProvider Value(Control control) =>
Assert.IsAssignableFrom<IValueProvider>(Controls.Peer(control));
// --- timeline ---
[Fact]
public void The_timeline_is_a_slider_read_as_the_moment_with_how_to_walk_it()
{
var timeline = new TimelineView { Spoken = "10:35:12, 40 km/h" };
var peer = Controls.Peer(timeline);
var value = Value(timeline);
Assert.Equal(AutomationControlType.Slider, peer.GetAutomationControlType());
Assert.Equal("10:35:12, 40 km/h", value.Value);
Assert.True(value.IsReadOnly);
Assert.False(string.IsNullOrEmpty(peer.GetHelpText()));
Assert.True(peer.IsContentElement());
Assert.True(peer.IsControlElement());
Assert.Throws<InvalidOperationException>(() => value.SetValue("x"));
timeline.Spoken = "10:35:22, 40 km/h";
Assert.Equal("10:35:22, 40 km/h", value.Value);
}
[Fact]
public void A_description_set_on_the_timeline_wins_over_its_own()
{
var timeline = new TimelineView();
AutomationProperties.SetHelpText(timeline, "own words");
Assert.Equal("own words", Controls.Peer(timeline).GetHelpText());
}
[Theory]
[InlineData(Key.Right, KeyModifiers.None, 70)]
[InlineData(Key.Left, KeyModifiers.None, 50)]
[InlineData(Key.Right, KeyModifiers.Control, 120)]
[InlineData(Key.Left, KeyModifiers.Control, 0)]
[InlineData(Key.PageDown, KeyModifiers.None, 120)]
[InlineData(Key.PageUp, KeyModifiers.None, 0)]
[InlineData(Key.Home, KeyModifiers.None, 0)]
[InlineData(Key.End, KeyModifiers.None, 120)]
public void The_keys_take_the_timeline_through_the_recording(Key key, KeyModifiers modifiers, double expected)
{
var timeline = new TimelineView { Recording = Journey(), Time = 60 };
double? sought = null;
timeline.Seek += t => sought = t;
Assert.True(Controls.Press(timeline, key, modifiers));
Assert.Equal(expected, sought);
}
[Fact]
public void Other_keys_and_an_empty_timeline_are_left_alone()
{
var empty = new TimelineView();
var timeline = new TimelineView { Recording = Journey(), Time = 60 };
bool sought = false;
empty.Seek += _ => sought = true;
timeline.Seek += _ => sought = true;
Assert.False(Controls.Press(empty, Key.Right));
Assert.False(Controls.Press(timeline, Key.A));
Assert.False(sought);
}
[Fact]
public void The_timeline_draws_with_and_without_the_focus()
{
var timeline = new TimelineView { Recording = Journey(), Time = 60 };
var window = Controls.Show(timeline, 900, 300);
try
{
timeline.Fit();
Controls.Draw(timeline);
Assert.True(timeline.IsFocused);
timeline.Time = 119;
Controls.Draw(timeline);
window.Focus();
Controls.Draw(timeline);
}
finally
{
window.Close();
}
}
// --- timetable ---
[Fact]
public void The_timetable_is_a_list_read_row_by_row_from_the_keys()
{
var table = new TimetablePanel { Recording = Journey(), Time = 30 };
var peer = Controls.Peer(table);
var value = Value(table);
Assert.Equal(AutomationControlType.List, peer.GetAutomationControlType());
Assert.False(string.IsNullOrEmpty(peer.GetHelpText()));
Assert.StartsWith("1/3. A", value.Value);
Assert.True(Controls.Press(table, Key.Down));
Assert.StartsWith("2/3. Stacja B", value.Value);
Assert.True(Controls.Press(table, Key.Up));
Assert.StartsWith("1/3. A", value.Value);
Assert.True(Controls.Press(table, Key.End));
Assert.StartsWith("3/3. C", value.Value);
Assert.True(Controls.Press(table, Key.Down));
Assert.StartsWith("3/3. C", value.Value);
Assert.True(Controls.Press(table, Key.Home));
Assert.StartsWith("1/3. A", value.Value);
Assert.Contains("km 2.5", value.Value.Replace(',', '.'));
Assert.False(Controls.Press(table, Key.A));
}
[Fact]
public void Enter_on_a_station_passed_goes_to_a_little_before_it()
{
var table = new TimetablePanel { Recording = Journey(), Time = 110 };
double? sought = null;
table.Seek += t => sought = t;
Controls.Press(table, Key.Home);
Controls.Press(table, Key.Down);
Assert.True(Controls.Press(table, Key.Enter));
Assert.Equal(55, sought);
}
[Fact]
public void A_recording_without_a_timetable_says_so_and_ignores_the_keys()
{
var recording = BlackBoxReader.Read(new BlackBoxFile().Info().Vehicle(Head, "EU07-005")
.Cab(0, Head, 1150, 40).End(1).Stream());
var table = new TimetablePanel { Recording = recording, Time = 0 };
Assert.False(string.IsNullOrEmpty(Value(table).Value));
Assert.False(Controls.Press(table, Key.Down));
table.Recording = null;
Controls.Lay(table);
Controls.Draw(table);
}
[Fact]
public void The_timetable_draws_its_rows_and_the_one_the_keys_stand_at()
{
var table = new TimetablePanel { Recording = Journey(), Time = 65 };
var window = Controls.Show(table, 600, 400);
try
{
Controls.Draw(table);
Controls.Press(table, Key.Down);
Controls.Draw(table);
window.Focus();
Controls.Draw(table);
}
finally
{
window.Close();
}
}
// --- cab ---
[Theory]
[InlineData(true, null)]
[InlineData(true, (byte)1)]
[InlineData(true, (byte)2)]
[InlineData(false, null)]
public void The_cab_says_what_it_draws(bool extended, byte? engine)
{
var cab = new CabPanel { Recording = Journey(extended, engine), Time = 30 };
Controls.Lay(cab, 600, 900);
Controls.Draw(cab);
Assert.NotNull(cab.Said);
Assert.Contains("EU07-005", cab.Said);
Assert.Contains("40 km/h", cab.Said);
Assert.Equal(AutomationControlType.Pane, Controls.Peer(cab).GetAutomationControlType());
Assert.Equal(cab.Said, Controls.Peer(cab).GetHelpText());
}
[Fact]
public void The_cab_stopped_under_the_brakes_and_out_of_the_recording()
{
var cab = new CabPanel { Recording = Journey(), Time = 60 };
var window = Controls.Show(cab, 600, 900);
try
{
Controls.Draw(cab);
Assert.Contains("0 km/h", cab.Said);
cab.Time = 500;
Controls.Draw(cab);
Assert.DoesNotContain("km/h", cab.Said);
}
finally
{
window.Close();
}
}
[Fact]
public void An_empty_cab_says_there_is_nothing_to_show()
{
var cab = new CabPanel();
Controls.Lay(cab);
Controls.Draw(cab);
Assert.False(string.IsNullOrEmpty(cab.Said));
}
// --- segmented choice ---
[Fact]
public void A_segmented_choice_is_a_row_of_tabs_one_of_them_selected()
{
var choice = new UiKit.Segmented("Mapa", "Profil", "Rozkład");
int? picked = null;
choice.SelectedChanged += i => picked = i;
var tabs = choice.GetVisualDescendants().OfType<Button>().ToList();
if (tabs.Count == 0)
tabs = ((Panel)choice.Child!).Children.OfType<Button>().ToList();
var second = Assert.IsAssignableFrom<ISelectionItemProvider>(Controls.Peer(tabs[1]));
Assert.Equal(AutomationControlType.TabItem, Controls.Peer(tabs[1]).GetAutomationControlType());
Assert.Null(second.SelectionContainer);
second.Select();
Assert.Equal(1, picked);
Assert.True(second.IsSelected);
Assert.Equal(1, choice.Selected);
var third = Assert.IsAssignableFrom<ISelectionItemProvider>(Controls.Peer(tabs[2]));
third.AddToSelection();
Assert.Equal(2, choice.Selected);
Assert.False(second.IsSelected);
third.RemoveFromSelection();
Assert.Equal(2, choice.Selected);
}
}

View File

@@ -0,0 +1,98 @@
using Eu07.BlackBox;
namespace StarterNG.Tests.BlackBox;
public class DrivingSummaryTests
{
private static Recording Drive(Func<BlackBoxFile, BlackBoxFile> more)
{
var file = new BlackBoxFile().Info();
return BlackBoxReader.Read(more(file).Stream());
}
/// <summary>Ten samples a second from t, at a speed against an AI holding target.</summary>
private static BlackBoxFile Stretch(BlackBoxFile file, double from, double seconds, float speed, float target,
byte driving = 1, byte flags = 0x03)
{
for (int i = 0; i < seconds * 10; i++)
file.Cab(from + i * 0.1, 1, 1000 + (from + i * 0.1) * speed / 3.6, speed, driving, flags, target);
return file;
}
[Theory]
[InlineData(40f, 40f, SpeedJudgement.Within)]
[InlineData(40.4f, 40f, SpeedJudgement.Within)]
[InlineData(44f, 40f, SpeedJudgement.Slightly)]
[InlineData(46f, 40f, SpeedJudgement.Over)]
[InlineData(-46f, 40f, SpeedJudgement.Over)]
public void A_sample_is_judged_by_how_much_faster_than_the_AI_it_went(float speed, float target, SpeedJudgement expected)
{
var r = Drive(f => f.Cab(0, 1, 0, speed, target: target));
Assert.Equal(expected, DrivingSummary.Judge(r.Cab[0]));
}
[Fact]
public void Without_the_AI_worked_out_or_with_the_AI_driving_there_is_nothing_to_judge()
{
var r = Drive(f => f.Cab(0, 1, 0, 80, flags: 0x01, target: 40).Cab(0.1, 1, 0, 80, driving: 2, target: 40));
Assert.Equal(SpeedJudgement.NoData, DrivingSummary.Judge(r.Cab[0]));
Assert.Equal(SpeedJudgement.Autopilot, DrivingSummary.Judge(r.Cab[1]));
}
[Fact]
public void The_summary_counts_the_time_over_the_AI_the_autopilot_and_the_signals_passed_at_danger()
{
var r = Drive(f =>
{
Stretch(f, 0, 10, 40, 40);
Stretch(f, 10, 10, 50, 40);
Stretch(f, 20, 10, 43, 40);
Stretch(f, 30, 10, 60, 60, driving: 2);
f.Passed(15, 1, 0, "s1", 0, 50, 0x02);
f.Passed(25, 1, 1, "s2", 40, 43);
// Another train, on a track of its own far away.
f.Passed(25, 7, 2, "someone else's", 0, 20, 0x02, z: 9000);
f.Command(5, 1, true, "mastercontrollerincrease");
f.Command(5.1, 1, false, "mastercontrollerincrease");
f.Command(6, 0, true, "timejump");
return f.Driver(30, 1, 2);
});
var summary = r.Summarize();
Assert.Equal(20, summary.OverAiSeconds, 0);
Assert.Equal(10, summary.WellOverAiSeconds, 0);
Assert.Equal(10, summary.MaxOverAiKmh, 3);
Assert.InRange(summary.MaxOverAiAt, 10, 20);
Assert.Equal(10, summary.AutopilotSeconds, 0);
Assert.Equal(30, summary.DrivenSeconds, 0);
Assert.Equal(60, summary.MaxSpeedKmh);
Assert.Equal(2, summary.SignalsPassed);
Assert.Equal("s1", Assert.Single(summary.PassedAtDanger).Event);
Assert.Equal(1, summary.Commands);
Assert.Equal(1, summary.AutopilotSwitches);
// 10 s at 40, 50, 43 and 60 km/h.
Assert.InRange(summary.DistanceKm, 0.530, 0.540);
}
[Fact]
public void The_autopilot_is_told_as_spans_of_time()
{
var r = Drive(f =>
{
Stretch(f, 0, 5, 40, 40);
Stretch(f, 5, 5, 40, 40, driving: 2);
Stretch(f, 10, 5, 40, 40);
return Stretch(f, 15, 2, 40, 40, driving: 2);
});
var spans = r.AutopilotSpans();
Assert.Equal(2, spans.Count);
Assert.Equal(5, spans[0].Start, 3);
Assert.Equal(10, spans[0].End, 3);
Assert.Equal(15, spans[1].Start, 3);
}
}

View File

@@ -0,0 +1,44 @@
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
[Collection(AvaloniaControls.Name)]
public class EventTextsTests
{
[Theory]
[InlineData("pl", "aidriverenable", "Aktywacja automechanika")]
[InlineData("en", "aidriverenable", "Engage the AI driver")]
[InlineData("pl", "mastercontrollerset", "Ustawienie nastawnika głównego")]
[InlineData("pl", "headlightenablerearleft", "Włączenie lewego reflektora z tyłu")]
[InlineData("cz", "batteryenable", "Turn the battery on")]
public void A_command_is_told_by_what_it_does(string language, string command, string text) =>
Assert.Equal(text, new DefaultBlackBoxStrings(language)[DefaultBlackBoxStrings.CommandPrefix + command]);
[Fact]
public void A_command_with_no_text_keeps_its_name() =>
Assert.Equal("somethingnew", new DefaultBlackBoxStrings("pl")[DefaultBlackBoxStrings.CommandPrefix + "somethingnew"]);
[Fact]
public void Every_command_has_both_texts_starting_with_a_capital()
{
foreach (string command in CommandTexts.Commands)
foreach (string language in new[] { "pl", "en" })
{
string text = CommandTexts.Of(command, language);
Assert.NotEqual(command, text);
Assert.True(char.IsUpper(text[0]), $"{command} ({language}): {text}");
}
}
[Fact]
public void The_events_name_the_commands_by_what_they_do()
{
var recording = BlackBoxReader.Read(new BlackBoxFile().Info()
.Vehicle(1, "EP07-424").User(0, 1, true).Command(12.0, 1, true, "batteryenable").Stream());
var events = EventList.Collect(recording, new DefaultBlackBoxStrings("pl"));
Assert.Contains(events, e => e.Text == "Włączenie baterii");
}
}

View File

@@ -0,0 +1,106 @@
using System.IO;
using Eu07.BlackBox;
namespace StarterNG.Tests.BlackBox;
/// <summary>The second value of a stop point as the driver reads it: all of it the metres, the last digit also the side.</summary>
public class PlatformTests
{
[Theory]
[InlineData(201f, 201, 1)]
[InlineData(242f, 242, 2)]
[InlineData(553f, 553, 3)]
[InlineData(150f, 150, 0)]
[InlineData(-151f, 151, 1)]
public void The_whole_value_is_metres_and_the_last_digit_the_side(float value, double length, int side)
{
Assert.Equal(length, Platforms.Length(value));
Assert.Equal(side, Platforms.Side(value));
}
private static StationEvent Stop(float distance, float length, float platform) =>
new(0, 1, StationKind.Stopped, 1, "Swoszowice", new Position(0, 0, 0), distance, 63.2f, length, platform, 600, 601);
[Fact]
public void A_train_whose_tail_reaches_past_the_platform_of_201_is_off_it()
{
// Two EN57 at Swoszowice: the head 74.7 m before the W4, the tail 204.5 m, the platform 201 m.
var stop = Stop(74.7f, 129.8f, 201);
Assert.False(stop.OnPlatform);
Assert.Equal(3.5, stop.OffPlatform, 1);
Assert.Equal(201, stop.PlatformLength);
}
[Fact]
public void A_train_whose_head_stands_past_the_stop_point_is_off_the_platform_by_that_much()
{
var stop = Stop(-5f, 129.8f, 201);
Assert.False(stop.OnPlatform);
Assert.Equal(5, stop.OffPlatform, 1);
}
[Fact]
public void A_metre_off_still_counts_as_along_the_platform()
{
var stop = Stop(-1f, 129.8f, 201);
Assert.True(stop.OnPlatform);
Assert.Equal(1, stop.OffPlatform, 1);
}
[Fact]
public void Each_end_has_its_own_tolerance()
{
// the head 1.5 m past the stop point, the tail 1.5 m past the platform's end
var stop = Stop(-1.5f, 204f, 201);
Assert.True(stop.OnPlatform);
Assert.Equal(3, stop.OffPlatform, 1);
}
[Fact]
public void A_train_within_the_platform_is_along_it()
{
var stop = Stop(63.2f, 129.8f, 201);
Assert.True(stop.OnPlatform);
Assert.Equal(0, stop.OffPlatform);
}
}
/// <summary>The way a stop point faces and the W32, as the simulator writes them.</summary>
public class StopPointRecordTests
{
[Fact]
public void A_stop_point_tells_the_way_of_the_trains_it_is_for()
{
var recording = BlackBoxReader.Read(new MemoryStream(new BlackBoxFile().Info().StopPoint(0, "Swoszowice", 100, 201, 201, 1.25f).End(10).Bytes));
var point = Assert.Single(recording.StopPoints);
Assert.True(point.HasHeading);
Assert.Equal(1.25f, point.Heading);
}
[Fact]
public void A_stop_point_of_an_older_recording_has_no_way()
{
var recording = BlackBoxReader.Read(new MemoryStream(new BlackBoxFile().Info().StopPoint(0, "Swoszowice", 100, 201, 201).End(10).Bytes));
Assert.False(Assert.Single(recording.StopPoints).HasHeading);
}
[Fact]
public void A_stop_point_on_tracks_of_both_ways_has_no_way()
{
var recording = BlackBoxReader.Read(new MemoryStream(new BlackBoxFile().Info().StopPoint(0, "Swoszowice", 100, 201, 201, float.NaN).End(10).Bytes));
Assert.False(Assert.Single(recording.StopPoints).HasHeading);
}
[Fact]
public void A_W32_is_for_the_trains_shorter_than_its_length_and_that_is_their_room()
{
var recording = BlackBoxReader.Read(new MemoryStream(new BlackBoxFile().Info().StopPoint(0, "Tumlin_po", 100, -1, -121).End(10).Bytes));
var point = Assert.Single(recording.StopPoints);
Assert.True(point.ForShortTrains);
Assert.False(point.HasPlatform);
Assert.Equal(121, point.PlatformLength);
var stop = new StationEvent(0, 1, StationKind.Stopped, 1, "Tumlin_po", new Position(0, 0, 0), 60, 50, 64.9f, -121, 600, 601);
Assert.False(stop.OnPlatform);
Assert.Equal(3.9, stop.OffPlatform, 1);
}
}

View File

@@ -0,0 +1,89 @@
using System.Globalization;
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
[Collection(AvaloniaControls.Name)]
public class SecurityBrakingTests
{
// as the simulator writes them: one acknowledgement for both, so the cab signalling's buzzer is the alerter's too
private const byte CabSignal = 0x02, CabSignalBuzzing = 0x0e, CabSignalBraking = 0x1e, NoPower = 0x10;
private static Recording Drive(System.Func<double, byte> security)
{
var file = new BlackBoxFile().Info().Vehicle(1, "EP07-424").User(0, 1, true);
for (double t = 0; t <= 20; t += 0.5)
file.Cab(t, 1, 100, 0, security: security(t));
return BlackBoxReader.Read(file.Stream());
}
private static List<string> Events(Recording recording)
{
var culture = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
try
{
return EventList.Collect(recording, new DefaultBlackBoxStrings("pl")).Select(e => e.Text).ToList();
}
finally
{
CultureInfo.CurrentCulture = culture;
}
}
[Fact]
public void The_protection_braking_with_no_power_is_not_the_drivers_fault()
{
// no power for the first seconds, then the cab signalling not acknowledged
var recording = Drive(t => t < 5 ? NoPower : t is >= 10 and < 12 ? (byte)0x1a : (byte)0);
var braking = Assert.Single(recording.SecurityBrakings());
Assert.Equal(10, braking.Start, 6);
}
[Fact]
public void A_buzzer_acknowledged_in_time_is_told_apart_from_braking()
{
var recording = Drive(t => t is >= 2 and < 4 ? CabSignal : t is >= 4 and < 5.5 ? CabSignalBuzzing : (byte)0);
var events = Events(recording);
Assert.Contains("Brzęczyk SHP, potwierdzony po 1.5 s", events);
Assert.DoesNotContain(events, e => e.StartsWith("HAMOWANIE", System.StringComparison.Ordinal));
Assert.Empty(recording.SecurityBrakings());
}
[Fact]
public void A_buzzer_cut_by_the_power_is_not_acknowledged()
{
var recording = Drive(t => t is >= 2 and < 4 ? CabSignalBuzzing : t is >= 4 and < 8 ? NoPower : (byte)0);
var events = Events(recording);
Assert.Contains("Brzęczyk SHP", events);
Assert.DoesNotContain(events, e => e.Contains("potwierdzony", System.StringComparison.Ordinal));
}
[Fact]
public void A_buzzer_the_other_joins_is_named_by_both()
{
// the alerter's buzzer, then a magnet passed before it's acknowledged
var recording = Drive(t => t is >= 2 and < 4 ? (byte)0x05 : t is >= 4 and < 5 ? (byte)0x0f : (byte)0);
Assert.Contains("Brzęczyk CA/SHP, potwierdzony po 3.0 s", Events(recording));
}
[Fact]
public void A_buzzer_not_acknowledged_is_followed_by_the_braking()
{
// the cab signalling at the start: the buzzer at once, braking when not acknowledged
var recording = Drive(t => t < 3 ? CabSignalBuzzing : t < 6 ? CabSignalBraking : (byte)0);
var events = Events(recording);
Assert.Equal(["Brzęczyk SHP, bez potwierdzenia", "HAMOWANIE PRZEZ SHP"],
events.Where(e => e.Contains("SHP", System.StringComparison.Ordinal)));
Assert.DoesNotContain(events, e => e.Contains("CA", System.StringComparison.Ordinal));
}
}

View File

@@ -0,0 +1,119 @@
using StarterNG.Infrastructure;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class CaseInsensitivePathsTests
{
private static InMemoryFileSystem Disk() => new InMemoryFileSystem(caseSensitive: true)
.WithFile("game/scenery/Braniewo/Base.ctr", "")
.WithFile("game/scenery/Braniewo/rozklady/TGS3657.txt", "")
.WithDirectory("game/textures/mini");
[Theory]
[InlineData("braniewo/base.ctr", "Braniewo/Base.ctr")]
[InlineData(@"BRANIEWO\Rozklady\tgs3657.TXT", "Braniewo/rozklady/TGS3657.txt")]
[InlineData("Braniewo/Base.ctr", "Braniewo/Base.ctr")]
[InlineData("braniewo//base.ctr", "Braniewo/Base.ctr")]
[InlineData("/braniewo/base.ctr", "Braniewo/Base.ctr")]
[InlineData(@"\Braniewo\Base.ctr", "Braniewo/Base.ctr")]
public void A_name_in_any_case_is_given_as_it_is_on_disk(string name, string onDisk) =>
Assert.Equal(onDisk, new CaseInsensitivePaths(Disk()).Resolve("game/scenery", name));
[Theory]
[InlineData("braniewo/brak.ctr")]
[InlineData("brak/base.ctr")]
[InlineData("")]
public void A_name_nothing_answers_to_is_not_found(string name) =>
Assert.Null(new CaseInsensitivePaths(Disk()).Resolve("game/scenery", name));
[Fact]
public void A_folder_is_found_only_when_one_is_asked_for()
{
var names = new CaseInsensitivePaths(Disk());
Assert.Equal("Braniewo/rozklady", names.Resolve("game/scenery", "braniewo/ROZKLADY", directory: true));
Assert.Null(names.Resolve("game/scenery", "braniewo/ROZKLADY"));
Assert.Null(names.Resolve("game/scenery", "braniewo/base.ctr", directory: true));
}
[Fact]
public void The_name_written_as_on_disk_wins_over_one_in_other_case()
{
var files = Disk().WithFile("game/scenery/braniewo/base.ctr", "");
var names = new CaseInsensitivePaths(files);
Assert.Equal("braniewo/base.ctr", names.Resolve("game/scenery", "braniewo/base.ctr"));
Assert.Equal("Braniewo/Base.ctr", names.Resolve("game/scenery", "Braniewo/base.CTR"));
}
[Fact]
public void Of_folders_named_alike_the_one_holding_the_file_is_taken()
{
var files = Disk().WithFile("game/scenery/braniewo/tory.scm", "");
var names = new CaseInsensitivePaths(files);
Assert.Equal("Braniewo/Base.ctr", names.Resolve("game/scenery", "braniewo/base.ctr"));
Assert.Equal("braniewo/tory.scm", names.Resolve("game/scenery", "Braniewo/Tory.scm"));
}
[Fact]
public void The_full_path_joins_the_folder_and_the_name_on_disk() =>
Assert.Equal(Path.Combine("game/scenery", "Braniewo", "Base.ctr"),
new CaseInsensitivePaths(Disk()).Find("game/scenery", "BRANIEWO/BASE.CTR"));
[Fact]
public void A_full_path_is_found_from_its_own_root()
{
string scenery = Path.GetFullPath(Path.Combine("game", "scenery"));
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(Path.Combine(scenery, "Braniewo", "Base.ctr"), "");
Assert.Equal(Path.Combine(scenery, "Braniewo", "Base.ctr"),
new CaseInsensitivePaths(files).Find("elsewhere", Path.Combine(scenery, "BRANIEWO", "base.CTR")));
}
[Fact]
public void A_disk_that_ignores_case_gives_the_name_back_as_written()
{
var files = new InMemoryFileSystem().WithFile("game/scenery/Braniewo/Base.ctr", "");
var names = new CaseInsensitivePaths(files);
Assert.Equal("BRANIEWO/base.CTR", names.Resolve("game/scenery", "BRANIEWO/base.CTR"));
Assert.Null(names.Resolve("game/scenery", "braniewo/brak.ctr"));
}
[Fact]
public void Kept_listings_hold_until_forgotten()
{
var files = Disk();
var names = new CaseInsensitivePaths(files, keepListings: true);
Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm"));
files.WithFile("game/scenery/Braniewo/Nowy.scm", "");
Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm"));
names.Forget();
Assert.Equal("Braniewo/Nowy.scm", names.Resolve("game/scenery", "braniewo/nowy.scm"));
}
[Fact]
public void Listings_not_kept_see_a_file_added_since()
{
var files = Disk();
var names = new CaseInsensitivePaths(files);
Assert.Null(names.Resolve("game/scenery", "braniewo/nowy.scm"));
files.WithFile("game/scenery/Braniewo/Nowy.scm", "");
Assert.Equal("Braniewo/Nowy.scm", names.Resolve("game/scenery", "braniewo/nowy.scm"));
}
[Fact]
public void A_folder_that_cannot_be_listed_holds_nothing_to_find()
{
var files = Disk().DenyListing("game/scenery");
Assert.Null(new CaseInsensitivePaths(files).Resolve("game/scenery", "braniewo/base.ctr"));
}
}

View File

@@ -0,0 +1,101 @@
using StarterNG.Views;
using Unit = StarterNG.Views.ConsistNarration.Unit;
namespace StarterNG.Tests;
public class ConsistNarrationTests
{
// Each text shows its key and its arguments, so a test sees which sentence was picked and with what.
private static string Loc(string key) => key switch
{
"ConsistSaidEmpty" => "empty",
"ConsistSaidAdded" => "added {0} at {1}/{2}",
"ConsistSaidRemoved" => "removed {0}, {1} left",
"ConsistSaidTurned" => "turned {0}",
"ConsistSaidUnturned" => "unturned {0}",
"ConsistSaidTurnedMany" => "turned {0}",
"ConsistSaidMoved" => "moved {0} to {1}/{2}",
"ConsistSaidReordered" => "reordered",
"ConsistSaidReplaced" => "replaced {0} with {1}",
"ConsistSaidChangedMany" => "changed {0}, {1} now",
_ => throw new KeyNotFoundException(key)
};
private static Unit[] Units(params string[] labels) =>
labels.Select(l => new Unit(l.TrimEnd('^'), l.EndsWith('^'))).ToArray();
private static string? Say(string[] before, string[] after, int? vehicles = null) =>
ConsistNarration.Describe(Units(before), Units(after), vehicles ?? after.Length, Loc);
[Fact]
public void Nothing_changed_says_nothing() =>
Assert.Null(Say(["EU07", "Bdhpumn"], ["EU07", "Bdhpumn"]));
[Fact]
public void An_empty_consist_staying_empty_says_nothing() =>
Assert.Null(Say([], []));
[Fact]
public void Clearing_the_consist_says_it_is_empty() =>
Assert.Equal("empty", Say(["EU07", "Bdhpumn"], []));
[Fact]
public void A_vehicle_added_at_the_end_is_named_with_its_place() =>
Assert.Equal("added Bdhpumn at 2/2", Say(["EU07"], ["EU07", "Bdhpumn"]));
[Fact]
public void A_vehicle_added_in_the_middle_is_named_with_its_place() =>
Assert.Equal("added WRmnouz at 2/3", Say(["EU07", "Bdhpumn"], ["EU07", "WRmnouz", "Bdhpumn"]));
[Fact]
public void Two_vehicles_added_at_once_are_both_named() =>
Assert.Equal("added A, B at 1/3", Say(["EU07"], ["A", "B", "EU07"]));
[Fact]
public void A_removed_vehicle_is_named_with_the_count_left() =>
Assert.Equal("removed WRmnouz, 2 left", Say(["EU07", "WRmnouz", "Bdhpumn"], ["EU07", "Bdhpumn"]));
[Fact]
public void The_count_left_counts_vehicles_not_units() =>
Assert.Equal("removed EU07, 3 left", Say(["EU07", "EN57"], ["EN57"], vehicles: 3));
[Fact]
public void A_vehicle_turned_round_is_named() =>
Assert.Equal("turned Bdhpumn", Say(["EU07", "Bdhpumn"], ["EU07", "Bdhpumn^"]));
[Fact]
public void A_vehicle_turned_back_is_told_apart_from_one_turned() =>
Assert.Equal("unturned Bdhpumn", Say(["EU07", "Bdhpumn^"], ["EU07", "Bdhpumn"]));
[Fact]
public void Several_turned_at_once_are_counted() =>
Assert.Equal("turned 3", Say(["A", "B", "C"], ["A^", "B^", "C^"]));
[Fact]
public void A_vehicle_moved_towards_the_end_is_named_with_its_new_place() =>
Assert.Equal("moved A to 3/4", Say(["A", "B", "C", "D"], ["B", "C", "A", "D"]));
[Fact]
public void A_vehicle_moved_towards_the_front_is_named_with_its_new_place() =>
Assert.Equal("moved C to 1/4", Say(["A", "B", "C", "D"], ["C", "A", "B", "D"]));
[Fact]
public void Neighbours_swapped_are_told_as_one_moved() =>
Assert.Equal("moved A to 2/2", Say(["A", "B"], ["B", "A"]));
[Fact]
public void The_same_vehicles_shuffled_are_told_as_a_new_order() =>
Assert.Equal("reordered", Say(["A", "B", "C", "D"], ["B", "A", "D", "C"]));
[Fact]
public void One_vehicle_swapped_for_another_names_both() =>
Assert.Equal("replaced B with X", Say(["A", "B", "C"], ["A", "X", "C"]));
[Fact]
public void A_bigger_change_counts_the_vehicles_it_touched() =>
Assert.Equal("changed 2, 3 now", Say(["A", "B", "C"], ["A", "X", "Y"]));
[Fact]
public void Same_named_vehicles_next_to_each_other_still_count_one_added() =>
Assert.Equal("added Bdhpumn at 3/3", Say(["EU07", "Bdhpumn"], ["EU07", "Bdhpumn", "Bdhpumn"]));
}

View File

@@ -0,0 +1,75 @@
using Avalonia;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Themes.Fluent;
using Avalonia.Threading;
namespace StarterNG.Tests;
/// <summary>Keys, focus, layout and drawing for the tests of controls, with no one at the keyboard.</summary>
internal static class Controls
{
/// <summary>Presses a key on the control as the keyboard would; true when the control took it.</summary>
public static bool Press(Control control, Key key, KeyModifiers modifiers = KeyModifiers.None)
{
var e = new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Key = key, KeyModifiers = modifiers, Source = control };
control.RaiseEvent(e);
return e.Handled;
}
/// <summary>
/// The control in a window of its own, shown, laid out and focused if it can be;
/// themed, its parts are built from the templates the application uses.
/// </summary>
public static Window Show(Control control, double width = 640, double height = 720, bool themed = false)
{
HeadlessDrawing.Ensure();
if (themed)
Theme();
var window = new Window { Width = width, Height = height, Content = control };
window.Show();
window.UpdateLayout();
Settle();
if (control.Focusable)
control.Focus();
return window;
}
/// <summary>Lays the control out alone at the size given.</summary>
public static void Lay(Control control, double width = 640, double height = 720)
{
HeadlessDrawing.Ensure();
control.Measure(new Size(width, height));
control.Arrange(new Rect(0, 0, width, height));
}
/// <summary>Has the control draw itself once.</summary>
public static void Draw(Control control)
{
HeadlessDrawing.Ensure();
var group = new DrawingGroup();
using var context = group.Open();
control.Render(context);
}
private static bool _themed;
// Where the application keeps it: given to a window alone, a slider or a number box was left without its parts.
private static void Theme()
{
if (_themed)
return;
Avalonia.Application.Current!.Styles.Add(new FluentTheme());
_themed = true;
}
/// <summary>Runs what was left for the dispatcher to do later, such as naming a row once it is laid out.</summary>
public static void Settle() => Dispatcher.UIThread.RunJobs();
public static AutomationPeer Peer(Control control) => ControlAutomationPeer.CreatePeerForElement(control);
public static RoutedEventArgs Click() => new(Button.ClickEvent);
}

View File

@@ -0,0 +1,376 @@
using Avalonia;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.VisualTree;
using StarterNG.Controls;
namespace StarterNG.Tests;
/// <summary>
/// Windows opened over another, searches and the starter's own controls as someone at the
/// keyboard with a screen reader meets them, in windows built as the application builds them.
/// </summary>
[Collection(AvaloniaControls.Name)]
public class DialogControlsTests
{
static DialogControlsTests()
{
HeadlessDrawing.Ensure();
DialogKeyboard.Install();
ScreenReaderNames.Install();
}
private static (Window Owner, Window Dialog) Dialog(Control content, bool escapeCloses = true)
{
var owner = new Window();
owner.Show();
var dialog = new Window { Width = 300, Height = 200, Content = content };
DialogKeyboard.SetEscapeCloses(dialog, escapeCloses);
_ = dialog.ShowDialog(owner);
// Headless a window says it opened before it is given its owner; it says so again once it has one.
Assert.Same(owner, dialog.Owner);
dialog.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Window.WindowOpenedEvent));
Controls.Settle();
return (owner, dialog);
}
// --- windows over another ---
[Fact]
public void A_dialog_opens_on_its_default_button_and_esc_closes_it()
{
var other = new Button { Content = "Nie" };
var yes = new Button { Content = "Tak", IsDefault = true };
var (owner, dialog) = Dialog(new StackPanel { Children = { other, yes } });
bool closed = false;
dialog.Closed += (_, _) => closed = true;
Assert.True(yes.IsFocused);
Assert.False(Controls.Press(dialog, Key.Escape, KeyModifiers.Shift));
Assert.True(Controls.Press(dialog, Key.Escape));
Assert.True(closed);
owner.Close();
}
[Fact]
public void Without_a_default_button_focus_goes_to_the_first_control()
{
var first = new TextBox();
var (owner, dialog) = Dialog(new StackPanel { Children = { first, new Button { Content = "OK" } } });
Assert.True(first.IsFocused);
dialog.Close();
owner.Close();
}
[Fact]
public void A_window_that_placed_the_focus_itself_keeps_it()
{
var first = new Button { Content = "1" };
var chosen = new Button { Content = "2" };
var (owner, dialog) = Dialog(new StackPanel { Children = { first, chosen } });
chosen.Focus();
Assert.False(first.IsFocused);
DialogKeyboard.FocusFirst(dialog);
Assert.True(chosen.IsFocused);
dialog.Close();
owner.Close();
}
[Fact]
public void Esc_does_not_close_a_window_that_stays_beside_the_main_one()
{
var (owner, dialog) = Dialog(new Button { Content = "OK" }, escapeCloses: false);
bool closed = false;
dialog.Closed += (_, _) => closed = true;
Assert.False(DialogKeyboard.GetEscapeCloses(dialog));
Assert.False(Controls.Press(dialog, Key.Escape));
Assert.False(closed);
dialog.Close();
owner.Close();
}
[Fact]
public void Tab_with_only_the_window_focused_starts_from_the_first_control()
{
var first = new Button { Content = "1" };
// Opened with nothing to focus, its controls put in afterwards.
var (owner, dialog) = Dialog(new TextBlock { Text = "…" });
dialog.Content = new StackPanel { Children = { first, new Button { Content = "2" } } };
dialog.UpdateLayout();
Assert.False(first.IsFocused);
Assert.True(Controls.Press(dialog, Key.Tab));
Assert.True(first.IsFocused);
dialog.Close();
owner.Close();
}
[Fact]
public void A_window_of_its_own_is_left_to_its_own_ways()
{
var button = new Button { Content = "1" };
var window = Controls.Show(button);
Assert.False(Controls.Press(window, Key.Escape));
window.Close();
}
// --- searches ---
[Fact]
public void A_search_says_how_many_entries_are_left_once_typing_pauses()
{
var box = new TextBox();
var announcer = new Announcer { Child = box };
var window = Controls.Show(announcer);
try
{
var teller = new SearchResultsTeller(box, () => 3);
box.Focus();
box.Text = "EU07";
teller.Changed();
Thread.Sleep(SearchResultsTeller.Pause + TimeSpan.FromMilliseconds(300));
Controls.Settle();
Assert.NotNull(announcer.Message);
}
finally
{
window.Close();
}
}
[Fact]
public void An_empty_search_or_one_left_says_nothing()
{
var box = new TextBox();
var elsewhere = new Button { Content = "x" };
var announcer = new Announcer { Child = new StackPanel { Children = { box, elsewhere } } };
var window = Controls.Show(announcer);
try
{
var teller = new SearchResultsTeller(box, () => 3);
box.Focus();
box.Text = " ";
teller.Changed();
Thread.Sleep(SearchResultsTeller.Pause + TimeSpan.FromMilliseconds(300));
Controls.Settle();
Assert.Null(announcer.Message);
box.Text = "EU07";
elsewhere.Focus();
teller.Changed();
Thread.Sleep(SearchResultsTeller.Pause + TimeSpan.FromMilliseconds(300));
Controls.Settle();
Assert.Null(announcer.Message);
}
finally
{
window.Close();
}
}
// --- tree entries ---
[Fact]
public void Every_part_of_a_row_tells_whether_the_entry_is_open()
{
var words = ExpandableTreeViewItem.StateWords;
ExpandableTreeViewItem.StateWords = s => s switch
{
ExpandCollapseState.Expanded => "rozwinięte",
ExpandCollapseState.Collapsed => "zwinięte",
_ => null
};
var child = new ExpandableTreeViewItem { Header = "test32" };
var group = new ExpandableTreeViewItem { Header = "Całkowo", Items = { child } };
AutomationProperties.SetName(group, "Całkowo");
var tree = new TreeView { Items = { group } };
var window = Controls.Show(tree, themed: true);
try
{
var row = group.GetVisualDescendants().OfType<Control>().First(c => c.Name == "PART_LayoutRoot");
Assert.Equal("zwinięte", AutomationProperties.GetHelpText(row));
Assert.Equal("Całkowo", AutomationProperties.GetName(row));
var peer = Controls.Peer(group);
((IExpandCollapseProvider)peer).Expand();
Controls.Settle();
Assert.Equal("rozwinięte", AutomationProperties.GetHelpText(row));
AutomationProperties.SetName(group, "Całkowo i okolice");
Assert.Equal("Całkowo i okolice", AutomationProperties.GetName(row));
group.Header = "Całkowo 2";
Controls.Settle();
window.UpdateLayout();
Assert.Same(group, child.ReadableParent);
Assert.Same(peer, Controls.Peer(child).GetParent());
var leafRow = child.GetVisualDescendants().OfType<Control>().First(c => c.Name == "PART_LayoutRoot");
Assert.Null(AutomationProperties.GetHelpText(leafRow));
tree.Items.Clear();
Controls.Settle();
}
finally
{
ExpandableTreeViewItem.StateWords = words;
window.Close();
}
}
// --- sliders and number boxes ---
[Fact]
public void The_track_and_knob_of_a_slider_are_named_with_its_value()
{
var fog = new ReadableSlider { Minimum = 0, Maximum = 1000, Value = 500, ValueText = "2,4 km" };
AutomationProperties.SetName(fog, "Widoczność");
var window = Controls.Show(fog, themed: true);
try
{
var track = fog.GetVisualDescendants().OfType<Avalonia.Controls.Primitives.Track>().Single();
Assert.Equal("Widoczność: 2,4 km", AutomationProperties.GetName(track));
fog.ValueText = "3 km";
Assert.Equal("Widoczność: 3 km", AutomationProperties.GetName(track));
var value = Assert.IsAssignableFrom<IValueProvider>(Controls.Peer(fog));
Assert.False(value.IsReadOnly);
Assert.Equal("Slider", Controls.Peer(fog).GetClassName());
Assert.Throws<ArgumentException>(() => value.SetValue("duĹĽo"));
}
finally
{
window.Close();
}
}
[Fact]
public void A_number_box_gives_its_name_to_the_text_inside_and_its_arrows_say_what_they_do()
{
var box = new NumericUpDown { Value = 3 };
AutomationProperties.SetName(box, "Liczba wagonĂłw");
var window = Controls.Show(box, themed: true);
try
{
var text = box.GetVisualDescendants().OfType<TextBox>().Single();
Assert.Equal("Liczba wagonĂłw", AutomationProperties.GetName(text));
var arrows = box.GetVisualDescendants().OfType<Control>()
.Where(c => c.Name is "PART_IncreaseButton" or "PART_DecreaseButton").ToList();
Assert.NotEmpty(arrows);
Assert.All(arrows, a => Assert.False(KeyboardNavigation.GetIsTabStop(a)));
Assert.All(arrows, a => Assert.False(string.IsNullOrEmpty(AutomationProperties.GetName(a))));
}
finally
{
window.Close();
}
}
[Fact]
public void A_picker_is_reached_through_its_button_named_with_the_label_and_value()
{
var date = new DatePicker { SelectedDate = new DateTimeOffset(2026, 11, 15, 0, 0, 0, TimeSpan.Zero) };
var time = new TimePicker { SelectedTime = new TimeSpan(7, 5, 0) };
AutomationProperties.SetName(date, "Data");
AutomationProperties.SetName(time, "Godzina");
var window = Controls.Show(new StackPanel { Children = { date, time } }, themed: true);
try
{
var dateButton = date.GetVisualDescendants().OfType<Button>().First(b => b.Name == "PART_FlyoutButton");
var timeButton = time.GetVisualDescendants().OfType<Button>().First(b => b.Name == "PART_FlyoutButton");
Assert.StartsWith("Data", AutomationProperties.GetName(dateButton));
Assert.StartsWith("Godzina", AutomationProperties.GetName(timeButton));
time.SelectedTime = new TimeSpan(8, 0, 0);
Assert.StartsWith("Godzina", AutomationProperties.GetName(timeButton));
}
finally
{
window.Close();
}
}
[Fact]
public void A_list_says_its_new_choice_when_the_arrows_change_it()
{
var combo = new ComboBox { ItemsSource = new[] { "Niska", "Ĺšrednia", "Wysoka" }, SelectedIndex = 0 };
var announcer = new Announcer { Child = combo };
var window = Controls.Show(announcer, themed: true);
try
{
combo.Focus();
combo.SelectedIndex = 2;
Assert.Equal("Wysoka", announcer.Message);
}
finally
{
window.Close();
}
}
// --- settings sections ---
private static SettingsSection Section() => new()
{
Template = new FuncControlTemplate<SettingsSection>((_, scope) =>
{
var reset = new Button { Name = "PART_Reset" };
scope.Register(reset.Name, reset);
return reset;
})
};
[Fact]
public void A_sections_reset_button_says_which_section_it_puts_back()
{
var section = Section();
section.Header = "Grafika";
section.ResetLabel = "Przywróć";
SettingsSection? asked = null;
section.ResetRequested += s => asked = s;
Controls.Lay(section);
section.ApplyTemplate();
var reset = (Button)section.GetVisualChildren().Single();
Assert.Equal("Przywróć: Grafika", AutomationProperties.GetName(reset));
section.Header = "Dźwięk";
Assert.Equal("Przywróć: Dźwięk", AutomationProperties.GetName(reset));
section.ResetLabel = null;
section.Header = null;
Assert.True(string.IsNullOrEmpty(AutomationProperties.GetName(reset)));
reset.RaiseEvent(Controls.Click());
Assert.Same(section, asked);
section.Template = Section().Template;
section.ApplyTemplate();
Assert.Null(section.ToggleKey);
Assert.Null(section.Toggle);
}
[Fact]
public void A_sections_list_of_levels_is_named_as_the_level_of_that_section()
{
var level = new ComboBox();
var section = new SettingsSection { Level = level, Header = "Grafika", ToggleKey = "shadows", Toggle = new CheckBox() };
Assert.EndsWith("Grafika", AutomationProperties.GetName(level));
Assert.Same(level, section.Level);
Assert.Equal("shadows", section.ToggleKey);
}
}

View File

@@ -0,0 +1,53 @@
using StarterNG.Views;
namespace StarterNG.Tests;
public class ExecutableListTests
{
[Fact]
public void A_build_copied_in_joins_the_list_and_the_choice_stays()
{
var (entries, chosen) = ExecutableList.Refreshed(["eu07_new.exe", "eu07.exe"], "eu07.exe");
Assert.Equal(new[] { "eu07_new.exe", "eu07.exe" }, entries);
Assert.Equal(1, chosen);
}
[Fact]
public void Automatic_stays_automatic()
{
var (entries, chosen) = ExecutableList.Refreshed(["eu07_new.exe", "eu07.exe"], null);
Assert.Equal(new[] { "eu07_new.exe", "eu07.exe" }, entries);
Assert.Equal(-1, chosen);
}
[Fact]
public void A_simulator_picked_from_elsewhere_stays_on_the_list_and_chosen()
{
const string picked = @"D:\build\eu07.exe";
var (entries, chosen) = ExecutableList.Refreshed(["eu07.exe"], picked);
Assert.Equal(new[] { "eu07.exe", picked }, entries);
Assert.Equal(1, chosen);
}
[Fact]
public void A_chosen_file_since_removed_stays_chosen_rather_than_switch_silently()
{
var (entries, chosen) = ExecutableList.Refreshed(["eu07.exe"], "eu07_old.exe");
Assert.Equal(new[] { "eu07.exe", "eu07_old.exe" }, entries);
Assert.Equal(1, chosen);
}
[Fact]
public void The_choice_is_found_whatever_the_case_of_its_name()
{
var (entries, chosen) = ExecutableList.Refreshed(["EU07.exe"], "eu07.exe");
Assert.Equal(new[] { "EU07.exe" }, entries);
Assert.Equal(0, chosen);
}
}

View File

@@ -0,0 +1,82 @@
using StarterNG.Domain.Settings;
using StarterNG.Infrastructure.Settings;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class ExecutableNoAvx2Tests
{
private const string Elf = "\u007fELF binary";
private static readonly DateTime Older = new(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly DateTime Newer = new(2026, 11, 15, 0, 0, 0, DateTimeKind.Utc);
private static InMemoryFileSystem With(params string[] names)
{
var files = new InMemoryFileSystem();
foreach (string name in names)
files.WithExecutable(TestInstallation.At(name), Elf);
return files;
}
private static string Automatic(InMemoryFileSystem files, bool lacksAvx2) =>
Path.GetFileName(new TestInstallation(files, lacksAvx2: lacksAvx2).Executables
.Resolve(new SimulatorSettings(), out _));
[Theory]
[InlineData("eu07_noavx2", true)]
[InlineData("eu07-x64_2026-11-15_abc1234_noavx2.exe", true)]
[InlineData("EU07_NOAVX2.EXE", true)]
[InlineData("eu07", false)]
[InlineData("eu07-x64_2026-11-15_abc1234.exe", false)]
[InlineData("eu07_noavx2_old.exe", false)]
public void A_build_without_avx2_is_known_by_the_end_of_its_name(string name, bool noAvx2) =>
Assert.Equal(noAvx2, ExecutableLocator.IsNoAvx2(name));
[Fact]
public void Without_avx2_the_build_without_it_is_chosen_over_the_canonical_one() =>
Assert.Equal("eu07_noavx2", Automatic(With("eu07", "eu07_noavx2"), lacksAvx2: true));
[Fact]
public void With_avx2_the_build_made_for_it_stays_first() =>
Assert.Equal("eu07", Automatic(With("eu07", "eu07_noavx2"), lacksAvx2: false));
[Fact]
public void With_avx2_a_build_without_it_is_used_when_it_is_the_only_one() =>
Assert.Equal("eu07_noavx2", Automatic(With("eu07_noavx2"), lacksAvx2: false));
[Fact]
public void Without_avx2_the_newest_build_without_it_is_chosen()
{
var files = With("eu07_2026-11-01_aaa_noavx2", "eu07_2026-11-15_bbb_noavx2")
.WrittenAt(TestInstallation.At("eu07_2026-11-01_aaa_noavx2"), Older)
.WrittenAt(TestInstallation.At("eu07_2026-11-15_bbb_noavx2"), Newer);
Assert.Equal("eu07_2026-11-15_bbb_noavx2", Automatic(files, lacksAvx2: true));
}
[Fact]
public void Without_avx2_and_no_build_without_it_the_usual_choice_stands() =>
Assert.Equal("eu07", Automatic(With("eu07-dev", "eu07"), lacksAvx2: true));
[Fact]
public void Only_a_build_with_avx2_on_a_processor_without_it_will_not_run()
{
var lacking = new TestInstallation(lacksAvx2: true).Executables;
var able = new TestInstallation(lacksAvx2: false).Executables;
Assert.True(lacking.WillNotRunHere("eu07.exe"));
Assert.False(lacking.WillNotRunHere("eu07-x64_noavx2.exe"));
Assert.False(able.WillNotRunHere("eu07.exe"));
}
[Fact]
public void The_newest_build_without_avx2_is_offered_by_name()
{
var files = With("eu07", "eu07_2026-11-01_aaa_noavx2", "eu07_2026-11-15_bbb_noavx2")
.WrittenAt(TestInstallation.At("eu07_2026-11-01_aaa_noavx2"), Older)
.WrittenAt(TestInstallation.At("eu07_2026-11-15_bbb_noavx2"), Newer);
Assert.Equal("eu07_2026-11-15_bbb_noavx2", new TestInstallation(files).Executables.NewestNoAvx2());
Assert.Null(new TestInstallation(With("eu07")).Executables.NewestNoAvx2());
}
}

View File

@@ -0,0 +1,63 @@
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class ExpandableTreeViewItemTests
{
private static IExpandCollapseProvider Peer(ExpandableTreeViewItem item) =>
Assert.IsAssignableFrom<IExpandCollapseProvider>(ControlAutomationPeer.CreatePeerForElement(item));
[Fact]
public void A_scenery_with_nothing_under_it_is_a_leaf()
{
var peer = Peer(new ExpandableTreeViewItem { Header = "test32" });
Assert.Equal(ExpandCollapseState.LeafNode, peer.ExpandCollapseState);
Assert.False(peer.ShowsMenu);
}
[Fact]
public void A_group_says_whether_it_is_open()
{
Assert.Equal(ExpandCollapseState.Collapsed, ExpandableTreeViewItem.StateFor(hasChildren: true, expanded: false));
Assert.Equal(ExpandCollapseState.Expanded, ExpandableTreeViewItem.StateFor(hasChildren: true, expanded: true));
Assert.Equal(ExpandCollapseState.LeafNode, ExpandableTreeViewItem.StateFor(hasChildren: false, expanded: true));
}
[Fact]
public void A_screen_reader_can_open_and_close_an_entry()
{
var item = new ExpandableTreeViewItem { Header = "Całkowo" };
var peer = Peer(item);
peer.Expand();
Assert.True(item.IsExpanded);
peer.Collapse();
Assert.False(item.IsExpanded);
}
[Fact]
public void An_entry_on_its_own_has_nothing_over_it()
{
var item = new ExpandableTreeViewItem { Header = "Całkowo", IsExpanded = true };
var peer = ControlAutomationPeer.CreatePeerForElement(item);
Assert.Null(item.ReadableParent);
Assert.Null(peer.GetParent());
}
[Fact]
public void The_row_under_the_mouse_is_told_open_or_closed_and_a_leaf_nothing()
{
static string Loc(string key) => key == "TreeExpanded" ? "rozwinięte" : "zwinięte";
Assert.Equal("rozwinięte", ExpandableTreeViewItem.WordFor(ExpandCollapseState.Expanded, Loc));
Assert.Equal("zwinięte", ExpandableTreeViewItem.WordFor(ExpandCollapseState.Collapsed, Loc));
Assert.Null(ExpandableTreeViewItem.WordFor(ExpandCollapseState.LeafNode, Loc));
}
}

View File

@@ -97,6 +97,8 @@ public sealed class InMemoryFileSystem : IFileSystem
return this;
}
public bool IgnoresCase => _comparison == StringComparison.OrdinalIgnoreCase;
public bool FileExists(string path) => _files.ContainsKey(Normalize(path));
/// <summary>A link counts as the directory it points at, as the disk has it.</summary>
@@ -273,6 +275,9 @@ public sealed class InMemoryFileSystem : IFileSystem
return;
slash = key.LastIndexOf('/');
}
// An absolute Unix path's parent is the root, "/", which normalises to "".
if (slash == 0)
_directories.Add("");
}
private static string Normalize(string path) =>

View File

@@ -14,7 +14,7 @@ public sealed class TestInstallation
{
public const string Root = "game";
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null)
public TestInstallation(InMemoryFileSystem? files = null, DateTime? now = null, bool lacksAvx2 = false)
{
Files = files ?? new InMemoryFileSystem();
Paths = new GamePaths(Root);
@@ -35,7 +35,8 @@ public sealed class TestInstallation
SettingsPaths.VehicleCacheDirectory());
Library = new GameLibrary(VehicleCache, Sceneries, MiniTextures, Physics, Log);
Executables = new ExecutableLocator(Files, Paths, Environment, Log);
// The processor of the machine running the tests is not the one tested.
Executables = new ExecutableLocator(Files, Paths, Environment, Log, lacksAvx2);
SettingsStore = new SettingsStore(Files, Clock, Log, SettingsPaths, new SettingsSerializer(), Executables);
Tapes = new HaslerTapes(Files, Paths, Log, Clock, new TimetableLocator(Files), () => SimulatorRunning);
}

View File

@@ -0,0 +1,98 @@
using Avalonia.Automation;
using Avalonia.Controls;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class FieldLabelTests
{
static FieldLabelTests() => ScreenReaderNames.Install();
private static T At<T>(T control, int row, int column) where T : Control
{
Grid.SetRow(control, row);
Grid.SetColumn(control, column);
return control;
}
[Fact]
public void A_field_is_named_by_the_nearest_label_left_of_it_in_its_row()
{
var far = At(new TextBlock { Text = "Pogoda" }, 0, 0);
var near = At(new TextBlock { Text = "Temperatura" }, 0, 1);
var value = At(new TextBlock { Text = "-5 °C" }, 0, 3);
var other = At(new TextBlock { Text = "Widoczność" }, 1, 1);
var slider = At(new Slider(), 0, 2);
_ = new Grid { Children = { far, near, value, other, slider } };
ScreenReaderNames.NameByLabel(slider);
Assert.Equal("Temperatura", AutomationProperties.GetName(slider));
}
[Fact]
public void A_field_with_nothing_to_its_left_is_named_by_the_label_above()
{
var label = At(new TextBlock { Text = "Klasa" }, 0, 1);
var combo = At(new ComboBox(), 1, 1);
_ = new Grid { Children = { label, combo } };
Assert.Same(label, ScreenReaderNames.LabelOf(combo));
}
[Fact]
public void In_a_panel_the_label_is_the_text_just_before_the_field()
{
var label = new TextBlock { Text = "Profil" };
var box = new TextBox();
var after = new TextBox();
_ = new StackPanel { Children = { label, box, new Button(), after } };
ScreenReaderNames.NameByLabel(box);
Assert.Equal("Profil", AutomationProperties.GetName(box));
Assert.Null(ScreenReaderNames.LabelOf(after));
}
[Fact]
public void A_hidden_text_or_a_long_description_is_no_label()
{
var hidden = new TextBlock { Text = "Ukryte", IsVisible = false };
var first = new ComboBox();
var description = new TextBlock { Text = new string('x', 61) };
var second = new ComboBox();
_ = new StackPanel { Children = { hidden, first, description, second } };
Assert.Null(ScreenReaderNames.LabelOf(first));
Assert.Null(ScreenReaderNames.LabelOf(second));
Assert.Null(ScreenReaderNames.LabelOf(new ComboBox()));
}
[Fact]
public void The_name_follows_the_label_into_another_language()
{
var label = new TextBlock { Text = "Data" };
var picker = new DatePicker();
_ = new DockPanel { Children = { label, picker } };
ScreenReaderNames.NameByLabel(picker);
ScreenReaderNames.NameByLabel(picker);
label.Text = "Date";
Assert.Equal("Date", AutomationProperties.GetName(picker));
}
[Fact]
public void A_name_given_on_purpose_beats_the_label()
{
var label = new TextBlock { Text = "Szukaj" };
var box = new TextBox();
AutomationProperties.SetName(box, "Szukaj pojazdów");
_ = new StackPanel { Children = { label, box } };
ScreenReaderNames.NameByLabel(box);
Assert.Equal("Szukaj pojazdów", AutomationProperties.GetName(box));
}
}

View File

@@ -0,0 +1,65 @@
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Tests;
public sealed class FolderChangesTests : IDisposable
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10);
private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-changes-" + Guid.NewGuid().ToString("N"));
public FolderChangesTests() => Directory.CreateDirectory(Path.Combine(_root, "sub"));
public void Dispose() => Directory.Delete(_root, recursive: true);
private static async Task<bool> Reported(FolderChanges changes, Action change)
{
var told = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
changes.Changed += () => told.TrySetResult();
change();
return await Task.WhenAny(told.Task, Task.Delay(Patience)) == told.Task;
}
[Fact]
public async Task A_file_written_below_the_folder_is_reported()
{
string file = Path.Combine(_root, "sub", "a.scm");
File.WriteAllText(file, "old");
using var changes = new FolderChanges(_root);
Assert.True(changes.Watching);
Assert.True(await Reported(changes, () => File.WriteAllText(file, "new text")));
}
[Fact]
public async Task A_save_through_a_renamed_temp_file_is_reported()
{
string file = Path.Combine(_root, "test.scn");
File.WriteAllText(file, "old");
using var changes = new FolderChanges(_root);
Assert.True(await Reported(changes, () =>
{
string temp = file + ".tmp";
File.WriteAllText(temp, "new");
File.Move(temp, file, overwrite: true);
}));
}
[Fact]
public async Task A_file_removed_is_reported()
{
string file = Path.Combine(_root, "gone.scn");
File.WriteAllText(file, "x");
using var changes = new FolderChanges(_root);
Assert.True(await Reported(changes, () => File.Delete(file)));
}
[Fact]
public void A_missing_folder_is_not_watched_and_does_not_throw()
{
using var changes = new FolderChanges(Path.Combine(_root, "nowhere"));
Assert.False(changes.Watching);
}
}

View File

@@ -0,0 +1,192 @@
using Avalonia.Controls;
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public sealed class FolderLooksTests : IDisposable
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(10);
private readonly string _root = Path.Combine(Path.GetTempPath(), "folder-looks-" + Guid.NewGuid().ToString("N"));
private readonly ManualTime _time = new();
private readonly Window _window;
private int _looks;
public FolderLooksTests()
{
Directory.CreateDirectory(_root);
HeadlessDrawing.Ensure();
_window = new Window();
}
public void Dispose()
{
_window.Close();
Directory.Delete(_root, recursive: true);
}
private FolderLooks Opened(string folder)
{
var looks = new FolderLooks(_window, () => folder, () =>
{
_looks++;
return Task.CompletedTask;
}, _time);
_window.Show();
Controls.Settle();
_looks = 0;
return looks;
}
private ManualTimer Quiet => _time.Timers.Single(t => t.Period == Timeout.InfiniteTimeSpan);
private ManualTimer Often => _time.Timers.Single(t => t.Period != Timeout.InfiniteTimeSpan);
// Waited for without leaving the thread: the window belongs to it.
private static void Until(Func<bool> condition) => Assert.True(SpinWait.SpinUntil(condition, Patience), "waited too long");
[Fact]
public void Nothing_is_watched_before_the_window_opens()
{
_ = new FolderLooks(_window, () => _root, () => Task.CompletedTask, _time);
Assert.Empty(_time.Timers);
}
[Fact]
public void A_watched_folder_is_looked_at_anyway_seldom()
{
var looks = Opened(_root);
Assert.True(looks.Watching);
Assert.Equal(FolderLooks.Watched, Often.Due);
Assert.Equal(FolderLooks.Watched, Often.Period);
Assert.Equal(Timeout.InfiniteTimeSpan, Quiet.Due);
}
[Fact]
public void A_folder_the_system_reports_nothing_of_is_looked_at_often()
{
var looks = Opened(Path.Combine(_root, "nowhere"));
Assert.False(looks.Watching);
Assert.Equal(FolderLooks.Unwatched, Often.Period);
}
[Fact]
public void A_tick_looks_on_the_ui_thread_once_it_gets_there()
{
Opened(_root);
Often.Fire();
Assert.Equal(0, _looks);
Controls.Settle();
Assert.Equal(1, _looks);
}
[Fact]
public void A_change_is_looked_at_once_the_reports_stop()
{
Opened(_root);
File.WriteAllText(Path.Combine(_root, "test.scn"), "new");
Until(() => Quiet.Due == FolderLooks.Quiet);
Controls.Settle();
Assert.Equal(0, _looks);
Quiet.Fire();
Controls.Settle();
Assert.Equal(1, _looks);
}
[Fact]
public void Coming_back_to_the_window_looks()
{
Opened(_root);
_window.Activate();
Controls.Settle();
Assert.Equal(1, _looks);
}
[Fact]
public void Asked_it_looks()
{
var looks = Opened(_root);
Assert.True(looks.LookAsync().IsCompletedSuccessfully);
Assert.Equal(1, _looks);
}
[Fact]
public void Closed_it_stops_the_timers()
{
Opened(_root);
_window.Close();
Assert.Equal(2, _time.Timers.Count);
Assert.All(_time.Timers, t => Assert.True(t.Disposed));
}
private sealed class ManualTime : TimeProvider
{
private readonly List<ManualTimer> _timers = new();
public IReadOnlyList<ManualTimer> Timers
{
get
{
lock (_timers)
return _timers.ToList();
}
}
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
var timer = new ManualTimer(() => callback(state), dueTime, period);
lock (_timers)
_timers.Add(timer);
return timer;
}
}
private sealed class ManualTimer : ITimer
{
private readonly Action _tick;
private long _dueTicks;
public ManualTimer(Action tick, TimeSpan due, TimeSpan period)
{
_tick = tick;
_dueTicks = due.Ticks;
Period = period;
}
public TimeSpan Due => TimeSpan.FromTicks(Interlocked.Read(ref _dueTicks));
public TimeSpan Period { get; private set; }
public bool Disposed { get; private set; }
public void Fire() => _tick();
public bool Change(TimeSpan dueTime, TimeSpan period)
{
if (Disposed)
throw new ObjectDisposedException(nameof(ManualTimer));
Interlocked.Exchange(ref _dueTicks, dueTime.Ticks);
Period = period;
return true;
}
public void Dispose() => Disposed = true;
public ValueTask DisposeAsync()
{
Dispose();
return ValueTask.CompletedTask;
}
}
}

View File

@@ -0,0 +1,27 @@
using Avalonia;
using Avalonia.Headless;
namespace StarterNG.Tests;
/// <summary>
/// Text and drawing for tests of controls that draw themselves: the headless platform
/// with its stand-in fonts, set up once, on the thread the control tests run on.
/// </summary>
public static class HeadlessDrawing
{
private static readonly object Gate = new();
private static bool _ready;
public static void Ensure()
{
lock (Gate)
{
if (_ready)
return;
AppBuilder.Configure<Avalonia.Application>()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = true })
.SetupWithoutStarting();
_ready = true;
}
}
}

View File

@@ -0,0 +1,105 @@
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.VisualTree;
using StarterNG.Application;
using StarterNG.Classes;
using StarterNG.Controls;
using StarterNG.Tests.Fakes;
using StarterNG.Views;
namespace StarterNG.Tests;
/// <summary>The key bindings as someone at the keyboard binds a key: the list of commands, and the keyboard drawn beside it walked with the arrows.</summary>
[Collection(AvaloniaControls.Name)]
public class KeyBindingsTabTests
{
static KeyBindingsTabTests()
{
if (AppServices.CurrentOrNull is null)
{
var installation = new TestInstallation(new InMemoryFileSystem());
AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
}
}
private sealed record Shown(Window Window, KeyBindingsTab Tab, Grid Host, Announcer Announcer) : IDisposable
{
public List<Border> Caps() =>
Host.GetVisualDescendants().OfType<Border>().Where(b => b.Classes.Contains("KeyCap")).ToList();
public void Dispose() => Window.Close();
}
private static Shown Open()
{
KeyboardConfig.Instance.Parse("hornhighactivate a\nhornlowactivate none\n");
var host = new Grid();
var search = new TextBox();
var tab = new KeyBindingsTab(host, search);
var announcer = new Announcer { Child = new DockPanel { Children = { search, host } } };
var window = Controls.Show(announcer, 1600, 1000, themed: true);
window.AddHandler(InputElement.KeyDownEvent, tab.OnKeyDown, Avalonia.Interactivity.RoutingStrategies.Tunnel);
tab.Build();
window.UpdateLayout();
Controls.Settle();
return new Shown(window, tab, host, announcer);
}
[Fact]
public void The_arrows_walk_the_keys_as_they_lie()
{
using var shown = Open();
var caps = shown.Caps();
Assert.True(caps.Count > 50);
Assert.All(caps, c => Assert.False(string.IsNullOrEmpty(AutomationProperties.GetName(c))));
caps[0].Focus();
Assert.True(Controls.Press(caps[0], Key.Right));
Assert.True(caps[1].IsFocused);
Assert.True(Controls.Press(caps[1], Key.Left));
Assert.True(caps[0].IsFocused);
Assert.True(Controls.Press(caps[0], Key.Left));
Assert.True(caps[0].IsFocused);
Assert.True(Controls.Press(caps[0], Key.End));
Assert.True(caps[^1].IsFocused);
Assert.True(Controls.Press(caps[^1], Key.Right));
Assert.True(caps[^1].IsFocused);
Assert.True(Controls.Press(caps[^1], Key.Home));
Assert.True(caps[0].IsFocused);
Assert.True(Controls.Press(caps[0], Key.Down));
var below = caps.Single(c => c.IsFocused);
Assert.NotSame(caps[0], below);
Assert.True(Controls.Press(below, Key.Up));
var above = caps.Single(c => c.IsFocused);
Assert.NotSame(below, above);
Assert.True(Controls.Press(above, Key.Up));
Assert.True(above.IsFocused);
Assert.False(Controls.Press(caps[0], Key.F24));
}
[Fact]
public void A_binding_takes_the_next_key_pressed_and_esc_gives_up_waiting()
{
using var shown = Open();
Assert.True(shown.Tab.ShownCount >= 2);
var combos = shown.Host.GetVisualDescendants().OfType<Button>()
.Where(b => b.Classes.Contains("Flat") && b.MinWidth == 140).ToList();
Assert.NotEmpty(combos);
combos[0].RaiseEvent(Controls.Click());
Assert.True(shown.Tab.IsCapturing);
Assert.True(Controls.Press(combos[0], Key.Escape));
Assert.False(shown.Tab.IsCapturing);
combos[0].RaiseEvent(Controls.Click());
Assert.False(Controls.Press(combos[0], Key.LeftShift));
Assert.True(shown.Tab.IsCapturing);
Assert.True(Controls.Press(combos[0], Key.J, KeyModifiers.Control | KeyModifiers.Shift));
Assert.False(shown.Tab.IsCapturing);
Assert.True(KeyboardConfig.Instance.Dirty);
}
}

View File

@@ -0,0 +1,40 @@
using Avalonia.Controls;
using Avalonia.Input;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class KeyboardFocusTests
{
private readonly Button _window = new();
private readonly Button _first = new();
private readonly Button _last = new();
private IInputElement? Tab(Key key, KeyModifiers modifiers, IInputElement? focused) =>
KeyboardFocus.TabFromNowhere(key, modifiers, focused, _window, () => _first, () => _last);
[Fact]
public void Tab_with_nothing_focused_starts_from_the_first_control()
{
Assert.Same(_first, Tab(Key.Tab, KeyModifiers.None, null));
}
[Fact]
public void Shift_tab_with_only_the_window_focused_starts_from_the_last_control()
{
Assert.Same(_last, Tab(Key.Tab, KeyModifiers.Shift, _window));
}
[Fact]
public void Tab_from_a_focused_control_is_left_to_the_usual_order()
{
Assert.Null(Tab(Key.Tab, KeyModifiers.None, new TextBox()));
}
[Fact]
public void Other_keys_are_left_alone()
{
Assert.Null(Tab(Key.Enter, KeyModifiers.None, null));
}
}

View File

@@ -0,0 +1,28 @@
using StarterNG.Infrastructure;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class LoadingScreenLogoTests
{
private static InMemoryFileSystem Logos() => new InMemoryFileSystem(caseSensitive: true)
.WithFile("game/Textures/Logo/EP09_Logo.PNG", "png")
.WithFile("game/Textures/Logo/Braniewo.JPG", "jpg")
.WithFile("game/Textures/Logo/Logo1.BMP", "bmp")
.WithFile("game/Textures/Logo/notes.txt", "");
[Theory]
[InlineData("ep09_logo", null, "EP09_Logo.PNG")]
[InlineData("ep09_logo.bmp", "braniewo", "EP09_Logo.PNG")]
[InlineData(null, "braniewo", "Braniewo.JPG")]
[InlineData("brak", "brak", "Logo1.BMP")]
public void The_logo_is_found_whatever_the_case_of_its_name_and_extension(string? logo, string? scenery,
string onDisk) =>
Assert.Equal(Path.GetFullPath(Path.Combine("game", "Textures", "Logo", onDisk)),
Path.GetFullPath(LoadingScreen.FindSource(Logos(), "game", logo, scenery, new Random(1))!));
[Fact]
public void With_no_logo_folder_there_is_no_logo() =>
Assert.Null(LoadingScreen.FindSource(new InMemoryFileSystem(caseSensitive: true), "game", "x", "y",
new Random(1)));
}

View File

@@ -0,0 +1,102 @@
using Avalonia.Automation;
using Avalonia.Controls;
using StarterNG.Controls;
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class MouseReadingTests
{
static MouseReadingTests() => ScreenReaderNames.Install();
[Fact]
public void A_picture_on_a_button_is_read_as_the_button()
{
var logo = new Image();
var button = new Button { Content = logo };
ScreenReaderNames.NamePicture(logo);
Assert.Same(button, AutomationProperties.GetLabeledBy(logo));
}
[Fact]
public void A_picture_beside_a_caption_is_read_as_the_caption()
{
var mini = new Image();
var caption = new TextBlock { Text = "EU07" };
_ = new StackPanel { Children = { mini, new TextBlock { IsVisible = false, Text = "ukryte" }, caption } };
ScreenReaderNames.NamePicture(mini);
Assert.Same(caption, AutomationProperties.GetLabeledBy(mini));
}
[Fact]
public void A_picture_in_a_card_is_read_as_the_card_tooltip()
{
var mini = new Image();
var card = new Border { Child = new Panel { Children = { mini } } };
ToolTip.SetTip(card, "EP09-018");
ScreenReaderNames.NamePicture(mini);
Assert.Equal("EP09-018", AutomationProperties.GetName(mini));
}
[Fact]
public void A_picture_named_on_purpose_or_far_from_any_name_is_left_alone()
{
var named = new Image();
AutomationProperties.SetName(named, "Obraz scenerii: baltyk");
var far = new Image();
var outer = new Border { Child = new Border { Child = new Border { Child = new Border { Child = far } } } };
ToolTip.SetTip(outer, "Opis");
_ = new Button { Content = named };
ScreenReaderNames.NamePicture(named);
ScreenReaderNames.NamePicture(far);
Assert.Equal("Obraz scenerii: baltyk", AutomationProperties.GetName(named));
Assert.Null(AutomationProperties.GetLabeledBy(named));
Assert.Null(AutomationProperties.GetName(far));
}
[Fact]
public void A_list_entry_is_read_as_its_text()
{
var named = new ComboBoxItem { Content = "Lato" };
AutomationProperties.SetName(named, "Pora: lato");
Assert.Equal("Pogodnie", ScreenReaderNames.SpokenItem(new ComboBoxItem { Content = "Pogodnie" }));
Assert.Equal("Pora: lato", ScreenReaderNames.SpokenItem(named));
Assert.Equal("12", ScreenReaderNames.SpokenItem(12));
Assert.Null(ScreenReaderNames.SpokenItem(null));
}
[Fact]
public void A_list_not_in_focus_says_nothing_of_its_new_choice()
{
var combo = new ComboBox();
var announcer = new Announcer();
announcer.Child = combo;
ScreenReaderNames.TellChoice(combo);
Assert.Null(announcer.Message);
}
[Fact]
public void A_figure_says_its_label_and_its_value_together()
{
var host = new StackPanel();
StatsBar.Fill(host, new[] { ("Masa [t]:", "440"), ("Tor:", "tor0325") });
var figure = Assert.IsType<TextBlock>(host.Children[0]);
Assert.Equal("Masa [t]: 440", figure.Inlines!.Text);
Assert.Equal(22, figure.Margin.Right);
Assert.Equal(0, ((TextBlock)host.Children[1]).Margin.Right);
}
}

View File

@@ -0,0 +1,80 @@
using StarterNG.Application;
namespace StarterNG.Tests;
public class OneAtATimeTests
{
private static async Task Until(Func<bool> condition)
{
var giveUp = DateTime.UtcNow.AddSeconds(5);
while (!condition())
{
Assert.True(DateTime.UtcNow < giveUp, "waited too long");
await Task.Delay(10);
}
}
[Fact]
public async Task Asked_once_it_runs_once()
{
int runs = 0;
var once = new OneAtATime(() => { runs++; return Task.CompletedTask; });
await once.RunAsync();
Assert.Equal(1, runs);
Assert.False(once.IsRunning);
}
[Fact]
public async Task Asked_while_running_it_runs_once_more_after_not_alongside()
{
int runs = 0, together = 0, most = 0;
var gates = new Queue<TaskCompletionSource>();
var once = new OneAtATime(async () =>
{
runs++;
most = Math.Max(most, ++together);
var gate = new TaskCompletionSource();
gates.Enqueue(gate);
await gate.Task;
together--;
});
var first = once.RunAsync();
// Three requests during the first run make one more run, not three.
await once.RunAsync();
await once.RunAsync();
await once.RunAsync();
Assert.Equal(1, runs);
gates.Dequeue().SetResult();
await Until(() => Volatile.Read(ref runs) == 2);
await Until(() => gates.Count == 1);
gates.Dequeue().SetResult();
await first;
Assert.Equal(2, runs);
Assert.Equal(1, most);
Assert.False(once.IsRunning);
}
[Fact]
public async Task A_failed_run_does_not_keep_it_busy()
{
bool fail = true;
int runs = 0;
var once = new OneAtATime(() =>
{
runs++;
return fail ? Task.FromException(new IOException("locked")) : Task.CompletedTask;
});
await Assert.ThrowsAsync<IOException>(once.RunAsync);
fail = false;
await once.RunAsync();
Assert.Equal(2, runs);
Assert.False(once.IsRunning);
}
}

View File

@@ -21,6 +21,20 @@ public sealed class PhysicalFileSystemTests : IDisposable
Assert.Equal(new[] { path }, Directory.GetFiles(_root));
}
[Fact]
public void A_pattern_lists_names_in_any_letter_case()
{
Directory.CreateDirectory(Path.Combine(_root, "PKP", "EP09"));
foreach (string name in new[] { "Braniewo.SCN", "kato.scn", "notes.txt", Path.Combine("PKP", "EP09", "EP09.FIZ"),
Path.Combine("PKP", "EP09", "ep09dumb.fiz") })
File.WriteAllText(Path.Combine(_root, name), "");
Assert.Equal(new[] { "Braniewo.SCN", "kato.scn" },
_files.GetFiles(_root, "*.scn").Select(Path.GetFileName).Order(StringComparer.Ordinal));
Assert.Equal(new[] { "EP09.FIZ", "ep09dumb.fiz" },
_files.GetFilesRecursive(_root, "*.fiz").Select(Path.GetFileName).Order(StringComparer.Ordinal));
}
[Fact]
public void An_atomic_write_that_cannot_finish_leaves_what_stood_there()
{

View File

@@ -65,6 +65,32 @@ public class PhysicsAndAssetsTests
Assert.Equal(125, physics.VMax);
}
[Fact]
public void An_include_named_in_other_case_is_followed()
{
var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true)
.WithFile(Fiz("pkp", "ep07", "ep07"), "include Common.FIZ 84000 end")
.WithFile(TestInstallation.At("dynamic", "pkp", "ep07", "common.fiz"), "Param: M=(1) Vmax=125"));
var physics = installation.Physics.For("pkp/ep07/", "ep07")!;
Assert.Equal(84000, physics.Mass);
Assert.Equal(125, physics.VMax);
}
[Fact]
public void A_dot_in_the_model_name_is_part_of_the_name()
{
// As in the game: cd/9-107_v1 holds 9-107.13.fiz, 9-107.6.fiz and more.
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Fiz("cd", "9-107_v1", "9-107.13"), "Load: LoadAccepted=coal MaxLoad=58")
.WithFile(Fiz("cd", "9-107_v1", "9-107.6"), "Load: LoadAccepted=coal MaxLoad=55"));
Assert.Equal(58, installation.Physics.For("cd/9-107_v1/", "9-107.13")!.MaxLoad);
Assert.Equal(55, installation.Physics.For("cd/9-107_v1/", "9-107.6")!.MaxLoad);
Assert.Equal(58, installation.Physics.For("cd/9-107_v1/", "9-107.13.e3d")!.MaxLoad);
}
[Fact]
public void A_dumb_variant_stands_in_when_the_model_has_no_fiz_of_its_own()
{
@@ -189,4 +215,31 @@ public class PhysicsAndAssetsTests
Assert.Empty(installation.MissingAssets.Scan(installation.Library.Vehicles));
}
[Fact]
public void A_livery_with_no_folder_is_looked_for_in_dynamic_itself()
{
var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("dynamic", "EP09.bmp"), "bitmap")
.WithFile(TestInstallation.At("dynamic", "ep09.e3d"), "model"));
var catalog = new StarterNG.Domain.Vehicles.VehicleCatalog(installation.MiniTextures);
catalog.Textures.Add(new StarterNG.Domain.Vehicles.VehicleTexture { Directory = "", Skinfile = "ep09", Model = "EP09" });
Assert.Empty(installation.MissingAssets.Scan(catalog));
}
[Fact]
public void A_skin_and_model_on_disk_in_other_case_are_not_reported()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "textures.txt"),
"EP09-014.mat=ep09.e3d,ep09")
.WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "ep09-014.BMP"), "bitmap")
.WithFile(TestInstallation.At("dynamic", "PKP", "EP09", "EP09.E3D"), "model");
var installation = new TestInstallation(files);
installation.Vehicles.Load(installation.Library.Vehicles);
Assert.NotEmpty(installation.Library.Vehicles.Textures);
Assert.Empty(installation.MissingAssets.Scan(installation.Library.Vehicles));
}
}

View File

@@ -0,0 +1,76 @@
using System.Globalization;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Controls;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class ReadableSliderTests
{
[Fact]
public void The_track_under_the_mouse_says_the_name_and_the_value()
{
var fog = new ReadableSlider { ValueText = "2,4 km" };
Assert.Equal("2,4 km", fog.TrackText);
AutomationProperties.SetName(fog, "Widoczność ");
Assert.Equal("Widoczność: 2,4 km", fog.TrackText);
}
[Fact]
public void A_slider_is_read_as_the_value_shown_beside_it()
{
var fog = new ReadableSlider { Minimum = 0, Maximum = 1000, Value = 523, ValueText = " 2,4 km " };
Assert.Equal("2,4 km", fog.SpokenValue);
}
[Fact]
public void Without_a_shown_value_the_number_itself_is_read()
{
var before = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("pl-PL");
try
{
Assert.Equal("-5", ReadableSlider.SpokenText(null, -5));
Assert.Equal("1,25", ReadableSlider.SpokenText(" ", 1.25));
}
finally
{
CultureInfo.CurrentCulture = before;
}
}
[Fact]
public void A_setting_row_gives_its_value_to_the_slider_in_it()
{
var slider = new ReadableSlider { Minimum = 0, Maximum = 100, Value = 40 };
var row = new SettingRow { Content = new Border { Child = slider } };
row.ValueText = "40%";
Assert.Equal("40%", slider.SpokenValue);
row.ValueText = null;
Assert.Equal("40", slider.SpokenValue);
}
[Fact]
public void A_screen_reader_is_given_the_text_and_may_set_a_number()
{
var slider = new ReadableSlider { Minimum = 0, Maximum = 1000, Value = 523, ValueText = "2 km" };
var peer = ControlAutomationPeer.CreatePeerForElement(slider);
var value = Assert.IsAssignableFrom<IValueProvider>(peer);
Assert.Equal(AutomationControlType.Slider, peer.GetAutomationControlType());
Assert.Equal("Slider", peer.GetClassName());
Assert.Equal("2 km", value.Value);
Assert.False(value.IsReadOnly);
value.SetValue("300");
Assert.Equal(300, slider.Value);
Assert.Throws<ArgumentException>(() => value.SetValue("dużo"));
}
}

View File

@@ -182,6 +182,20 @@ public class TimetableLocatorTests
Assert.NotNull(new TimetableLocator(files).Resolve(scenery, "r1.txt"));
}
[Theory]
[InlineData(@"rozklady\tgs3657")]
[InlineData("ROZKLADY/TGS3657.TXT")]
public void A_timetable_named_in_other_case_or_with_backslashes_is_found_as_on_disk(string name)
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("scenery", "Braniewo.scn"), "//$n Braniewo")
.WithFile(TestInstallation.At("scenery", "Rozklady", "TGS3657.txt"), "rozkład");
var scenery = Assert.Single(new TestInstallation(files).Sceneries.LoadAll());
Assert.Equal(TestInstallation.At("scenery", "Rozklady", "TGS3657.txt"),
new TimetableLocator(files).Resolve(scenery, name));
}
[Fact]
public void The_formats_none_and_a_missing_file_both_resolve_to_nothing()
{
@@ -195,3 +209,26 @@ public class TimetableLocatorTests
Assert.Null(locator.Resolve(scenery, null));
}
}
public class AttachmentLocatorTests
{
[Theory]
[InlineData(@"scenery\Braniewo\opis.PDF")]
[InlineData("SCENERY/braniewo/Opis.pdf")]
public void An_attachment_named_in_other_case_is_found_as_on_disk(string named)
{
var installation = new TestInstallation(new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("scenery", "Braniewo", "Opis.pdf"), "%PDF"));
Assert.Equal(TestInstallation.At("scenery", "Braniewo", "Opis.pdf"),
new AttachmentLocator(installation.Files, installation.Paths)
.Resolve(new SceneryAttachment { FilePath = named }));
}
[Theory]
[InlineData("scenery/brak.pdf")]
[InlineData("")]
public void An_attachment_that_is_not_there_is_not_found(string named) =>
Assert.Null(new AttachmentLocator(new InMemoryFileSystem(caseSensitive: true), new TestInstallation().Paths)
.Resolve(new SceneryAttachment { FilePath = named }));
}

View File

@@ -89,6 +89,23 @@ public class SceneryRepositoryTests
Assert.Equal(Path.Combine("game", "scenery", "images", "kato.jpg"), image);
}
[Theory]
[InlineData("calkowo_v2_kopalniaA.jpg", "game/scenery/images/calkowo_v2_kopalniaA.jpg")]
[InlineData(@"Images\Calkowo_V2_KopalniaA.JPG", "game/scenery/images/calkowo_v2_kopalniaA.jpg")]
[InlineData("CALKOWO_V2.JPG", "game/scenery/Calkowo_v2.jpg")]
public void The_preview_image_is_found_whatever_the_case_it_is_named_in(string named, string onDisk)
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile("game/scenery/calkowo.scn", "//$i " + named)
.WithFile("game/scenery/images/calkowo_v2_kopalniaA.jpg", "binary")
.WithFile("game/scenery/Calkowo_v2.jpg", "binary");
var scenery = Assert.Single(Build(files, out _).LoadAll());
string? image = new SceneryImageLocator(files).Resolve(scenery);
Assert.Equal(Path.GetFullPath(onDisk), Path.GetFullPath(image!));
}
[Fact]
public void A_scenery_without_an_image_directive_resolves_to_nothing()
{

View File

@@ -273,7 +273,7 @@ public class ScenerySyntaxTests
include koniec.scm
""";
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => new IncludeLookup(true));
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => true);
Assert.Empty(scenery.Faults);
Assert.Equal("td/rozklad", Assert.Single(scenery.Trainsets).Name);
@@ -326,7 +326,7 @@ public class ScenerySyntaxTests
endoptional
""";
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, name => new IncludeLookup(name is "tory.scm" or "budynek.inc")).Faults;
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn, name => name is "tory.scm" or "budynek.inc").Faults;
Assert.Equal((SceneryFaultKind.MissingInclude, "x.scn", 2, null, "brak.scm"), Seen(Assert.Single(faults)));
}
@@ -347,9 +347,9 @@ public class ScenerySyntaxTests
}
[Fact]
public void An_include_on_disk_only_in_other_letter_case_is_what_linux_misses()
public void An_include_on_disk_in_other_letter_case_is_no_fault()
{
// The simulator folds the name to lower case and opens it so.
// The simulator finds the file whatever the case of its letters, on Linux too.
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile("game/scenery/braniewo_szeroki.scn",
"include braniewo/base.ctr end\ninclude Braniewo/Tory.SCM end\n")
@@ -357,21 +357,20 @@ public class ScenerySyntaxTests
.WithFile("game/scenery/braniewo/tory.scm", "");
var repository = TestScenery.Repository(files);
var faults = repository.Load("game/scenery/braniewo_szeroki.scn")!.Faults;
Assert.Equal((SceneryFaultKind.IncludeLetterCase, "braniewo_szeroki.scn", 1, "Braniewo/Base.ctr", "braniewo/base.ctr"),
Seen(Assert.Single(faults)));
Assert.Empty(repository.Load("game/scenery/braniewo_szeroki.scn")!.Faults);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_missing_terrain_file_is_no_fault_while_the_scenery_has_its_own_sbt(bool sbt)
[InlineData(null)]
[InlineData("lk2_sandbox.sbt")]
[InlineData("Lk2_Sandbox.SBT")]
public void A_missing_terrain_file_is_no_fault_while_the_scenery_has_its_own_sbt(string? sbtOnDisk)
{
bool sbt = sbtOnDisk is not null;
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile("game/scenery/Lk2_Sandbox.scn", "include nmt/nmt100_mazowieckie_ter.scm end\nFirstInit\n");
if (sbt)
files.WithFile("game/scenery/lk2_sandbox.sbt", "EU07");
files.WithFile("game/scenery/" + sbtOnDisk, "EU07");
var repository = TestScenery.Repository(files);
var scenery = repository.Load("game/scenery/Lk2_Sandbox.scn")!;

View File

@@ -39,6 +39,24 @@ public class SceneryTranslationsTests
Assert.Equal("Polski", scenery.LocalizedDescription(translations));
}
[Fact]
public void The_tables_are_found_whatever_the_case_of_their_names()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("scenery", "Braniewo.scn"), "//$d @brief")
.WithFile(Path.Combine(Path.GetFullPath(TestInstallation.At("scenery")), "I18N", "braniewo_en.json"),
"""{ "brief": "English" }""")
.WithFile(Path.Combine(Path.GetFullPath(TestInstallation.At("scenery")), "I18N", "BRANIEWO_PL.json"),
"""{ "brief": "Polski" }""");
var installation = new TestInstallation(files);
var scenery = Assert.Single(installation.Sceneries.LoadAll());
var translations = new SceneryTranslations(files, installation.Log);
translations.LoadFor(scenery, "Polski");
Assert.Equal("Polski", scenery.LocalizedDescription(translations));
}
[Fact]
public void Literal_text_and_unknown_keys_are_left_alone()
{

View File

@@ -0,0 +1,229 @@
using System.Globalization;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class ScreenReaderNamesTests
{
static ScreenReaderNamesTests() => ScreenReaderNames.Install();
private static StackPanel Row(params Control[] children)
{
var panel = new StackPanel();
panel.Children.AddRange(children);
return panel;
}
[Fact]
public void An_icon_button_is_named_by_its_tooltip()
{
var button = new Button { Content = new Image() };
ToolTip.SetTip(button, "Otwórz ostatni log symulatora");
Assert.Equal("Otwórz ostatni log symulatora", AutomationProperties.GetName(button));
}
[Fact]
public void A_button_without_a_tooltip_is_named_by_the_text_it_shows()
{
var button = new Button { Content = Row(new Image(), new TextBlock { Text = "Dodaj" }) };
Assert.Equal("Dodaj", AutomationProperties.GetName(button));
}
[Fact]
public void A_button_with_text_of_its_own_keeps_it()
{
var button = new Button { Content = "Zapisz" };
ToolTip.SetTip(button, "Zapisz ustawienia");
Assert.Null(AutomationProperties.GetName(button));
}
[Fact]
public void A_name_given_on_purpose_is_left_alone()
{
var button = new Button();
AutomationProperties.SetName(button, "Discord");
button.Content = new Image();
ToolTip.SetTip(button, "Dołącz do nas");
Assert.Equal("Discord", AutomationProperties.GetName(button));
}
[Fact]
public void A_new_tooltip_replaces_the_name_it_gave()
{
var button = new Button { Content = new Image() };
ToolTip.SetTip(button, "Undo");
ToolTip.SetTip(button, "Cofnij");
Assert.Equal("Cofnij", AutomationProperties.GetName(button));
}
[Fact]
public void Text_put_on_a_button_later_takes_back_the_name_it_was_given()
{
var button = new Button { Content = new Image() };
ToolTip.SetTip(button, "Pomoc");
button.Content = "Pomoc";
Assert.Null(AutomationProperties.GetName(button));
}
[Fact]
public void A_button_with_only_a_sign_on_it_is_named_by_its_tooltip()
{
var button = new Button { Content = "?" };
ToolTip.SetTip(button, "Pomoc");
Assert.Equal("Pomoc", AutomationProperties.GetName(button));
}
[Fact]
public void A_tree_entry_is_named_by_the_visible_text_of_its_header()
{
var hidden = new TextBlock { Text = "ukryte", IsVisible = false };
var item = new TreeViewItem
{
Header = Row(new Image(), new TextBlock { Text = "baltyk_cargo" }, hidden, new TextBlock { Text = " " })
};
Assert.Equal("baltyk_cargo", AutomationProperties.GetName(item));
}
[Fact]
public void A_list_entry_joins_the_texts_it_shows()
{
var item = new ListBoxItem
{
Content = new Border { Child = Row(new TextBlock { Text = "PKPIC" }, new TextBlock { Text = "303E-EP-426" }) }
};
Assert.Equal("PKPIC, 303E-EP-426", AutomationProperties.GetName(item));
}
[Fact]
public void Text_made_of_runs_is_read_whole()
{
var block = new TextBlock();
block.Inlines!.Add(new Run("EP07"));
block.Inlines.Add(new LineBreak());
block.Inlines.Add(new Span { Inlines = { new Run("544") } });
Assert.Equal("EP07 544", ScreenReaderNames.TextOf(block));
}
[Fact]
public void Nothing_to_read_gives_no_name()
{
Assert.Null(ScreenReaderNames.TextOf(null));
Assert.Null(ScreenReaderNames.TextOf(new Image()));
Assert.Null(ScreenReaderNames.TextOf(" "));
Assert.Equal("Opis", ScreenReaderNames.TextOf(new ContentControl { Content = " Opis " }));
}
[Fact]
public void A_field_is_named_by_the_hint_written_in_it()
{
var search = new TextBox { PlaceholderText = "Szukaj…" };
var category = new ComboBox { PlaceholderText = "Kategoria" };
Assert.Equal("Szukaj…", AutomationProperties.GetName(search));
Assert.Equal("Kategoria", AutomationProperties.GetName(category));
}
[Fact]
public void A_setting_row_names_its_inputs_by_its_label()
{
var combo = new ComboBox();
var slider = new Slider();
var browse = new Button { Content = "Wybierz plik…" };
var row = new SettingRow { Content = new Border { Child = Row(combo, slider, browse) } };
row.Label = "Wybór exe";
Assert.Equal("Wybór exe", AutomationProperties.GetName(combo));
Assert.Equal("Wybór exe", AutomationProperties.GetName(slider));
Assert.Null(AutomationProperties.GetName(browse));
}
[Fact]
public void A_setting_row_describes_its_inputs_with_its_explanation()
{
var check = new CheckBox { Content = "Tryb pełnoekranowy" };
var slider = new Slider();
var row = new SettingRow { Label = "Ekran", Content = Row(check, slider) };
row.Description = "Gra zajmie cały ekran.";
row.IdleNote = "Ten symulator nie zna tego ustawienia.";
Assert.Equal("Gra zajmie cały ekran., Ten symulator nie zna tego ustawienia.", AutomationProperties.GetHelpText(check));
Assert.Equal(AutomationProperties.GetHelpText(check), AutomationProperties.GetHelpText(slider));
Assert.Null(AutomationProperties.GetName(check));
row.Description = null;
row.IdleNote = null;
Assert.Null(AutomationProperties.GetHelpText(check));
}
[Fact]
public void A_description_given_on_purpose_is_left_alone()
{
var box = new TextBox();
AutomationProperties.SetHelpText(box, "Ścieżka do exe");
_ = new SettingRow { Content = box, Description = "Plik symulatora" };
Assert.Equal("Ścieżka do exe", AutomationProperties.GetHelpText(box));
}
[Fact]
public void A_setting_row_without_a_label_leaves_its_input_unnamed()
{
var box = new TextBox();
_ = new SettingRow { Content = box };
Assert.Null(AutomationProperties.GetName(box));
}
}
[Collection(AvaloniaControls.Name)]
public class PickerNameTests
{
[Fact]
public void A_picker_is_read_as_its_label_and_its_value()
{
Assert.Equal("Godzina: 07:05", ScreenReaderNames.PickerText("Godzina", "07:05"));
Assert.Equal("Data", ScreenReaderNames.PickerText("Data", null));
Assert.Equal("07:05", ScreenReaderNames.PickerText(null, "07:05"));
Assert.Null(ScreenReaderNames.PickerText("", null));
}
[Fact]
public void A_date_is_read_in_words_with_the_year_only_when_shown()
{
var before = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("pl-PL");
try
{
var date = new DateTimeOffset(2026, 10, 27, 0, 0, 0, TimeSpan.FromHours(1));
Assert.Equal("27 października", ScreenReaderNames.DateText(date, withYear: false));
Assert.Equal("wtorek, 27 października 2026", ScreenReaderNames.DateText(date, withYear: true));
Assert.Null(ScreenReaderNames.DateText(null, withYear: false));
}
finally
{
CultureInfo.CurrentCulture = before;
}
}
[Fact]
public void A_time_is_read_as_hours_and_minutes()
{
Assert.Equal("07:05", ScreenReaderNames.TimeText(new TimeSpan(7, 5, 30)));
Assert.Null(ScreenReaderNames.TimeText(null));
}
}

View File

@@ -0,0 +1,45 @@
using Avalonia;
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
public class SoftwareRenderTests
{
[Theory]
[InlineData("--software-render")]
[InlineData("--Software-Render")]
public void The_switch_asks_for_it_in_any_case(string arg)
{
Assert.True(SoftwareRender.AskedIn(new[] { "--other", arg }));
}
[Fact]
public void Without_the_switch_the_graphics_card_draws()
{
Assert.False(SoftwareRender.AskedIn(Array.Empty<string>()));
Assert.False(SoftwareRender.AskedIn(new[] { "--software" }));
}
[Fact]
public void Windows_draws_on_the_processor_into_a_plain_window_surface()
{
var options = SoftwareRender.Win32Options;
Assert.Equal(new[] { Win32RenderingMode.Software }, options.RenderingMode);
Assert.Equal(new[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode);
}
[Fact]
public void X11_draws_on_the_processor()
{
Assert.Equal(new[] { X11RenderingMode.Software }, SoftwareRender.X11Options.RenderingMode);
}
[Fact]
public void Both_platforms_options_go_to_the_same_builder()
{
var builder = AppBuilder.Configure<Avalonia.Application>();
Assert.Same(builder, SoftwareRender.ApplyTo(builder));
}
}

View File

@@ -8,6 +8,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="12.1.4" />
<PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
@@ -20,6 +21,7 @@
<ItemGroup>
<ProjectReference Include="..\StarterNG\StarterNG.csproj" />
<ProjectReference Include="..\Eu07.BlackBox\Eu07.BlackBox.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,98 @@
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
public class SystemGraphicsLibrariesTests
{
private const string System32 = @"C:\Windows\System32";
private const string Game = @"E:\SteamLibrary\steamapps\common\MaSzyna";
private static readonly IntPtr Dxgi = new(0x1000);
private static readonly IntPtr D3d11 = new(0x2000);
private static SystemGraphicsLibraries Take(Func<string, bool> beside, Dictionary<string, IntPtr> system)
{
return SystemGraphicsLibraries.Take(System32, Game, beside, Load);
bool Load(string path, out IntPtr handle)
{
handle = system.GetValueOrDefault(Path.GetFileName(path));
return handle != IntPtr.Zero;
}
}
private static SystemGraphicsLibraries WithDxgiAndD3d11(Func<string, bool> beside) =>
Take(beside, new Dictionary<string, IntPtr> { ["dxgi.dll"] = Dxgi, ["d3d11.dll"] = D3d11 });
[Fact]
public void An_import_by_name_gets_the_system_library_with_or_without_its_extension()
{
var taken = WithDxgiAndD3d11(_ => false);
Assert.Equal(Dxgi, taken.Resolve("dxgi"));
Assert.Equal(Dxgi, taken.Resolve("dxgi.dll"));
Assert.Equal(D3d11, taken.Resolve("D3D11.DLL"));
}
[Fact]
public void Other_libraries_and_ones_the_system_lacks_are_left_to_the_usual_search()
{
var taken = WithDxgiAndD3d11(_ => false);
Assert.Equal(IntPtr.Zero, taken.Resolve("user32.dll"));
Assert.Equal(IntPtr.Zero, taken.Resolve("opengl32"));
}
[Fact]
public void They_are_loaded_from_the_system_folder_dxgi_first()
{
var asked = new List<string>();
SystemGraphicsLibraries.Take(System32, Game, _ => false, Load);
Assert.Equal(SystemGraphicsLibraries.Names.Select(n => Path.Combine(System32, n + ".dll")), asked);
Assert.Equal("dxgi", SystemGraphicsLibraries.Names[0]);
bool Load(string path, out IntPtr handle)
{
asked.Add(path);
handle = IntPtr.Zero;
return false;
}
}
[Fact]
public void A_wrapper_beside_the_starter_is_noted()
{
var taken = WithDxgiAndD3d11(path => path == Path.Combine(Game, "dxgi.dll"));
Assert.Equal(new[] { "dxgi.dll" }, taken.Shadowed);
Assert.Contains("dxgi.dll", taken.Note);
}
[Fact]
public void With_nothing_beside_the_starter_there_is_nothing_to_note()
{
var taken = WithDxgiAndD3d11(_ => false);
Assert.Empty(taken.Shadowed);
Assert.Null(taken.Note);
}
[Fact]
public void Only_windows_has_system_libraries_to_take()
{
var taken = SystemGraphicsLibraries.TakeOnWindows();
Assert.Equal(OperatingSystem.IsWindows(), taken is not null);
}
[Fact]
public void An_assembly_with_a_resolver_of_its_own_keeps_it()
{
var taken = WithDxgiAndD3d11(_ => false);
var assembly = typeof(SystemGraphicsLibrariesTests).Assembly;
Assert.True(taken.ServeTo(assembly));
Assert.False(taken.ServeTo(assembly));
}
}

View File

@@ -130,6 +130,17 @@ public class TapeLaunchTests
Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem())
.TrainNumber(new StarterNG.Domain.Sceneries.Scenery(TestInstallation.At("scenery", "td.scn"), ""), name));
[Fact]
public void The_train_number_comes_from_a_timetable_named_in_other_case_with_backslashes()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile(TestInstallation.At("scenery", "Baltyk", "EIE1531.txt"), "[ Rodzaj i numer pociagu | EIE1531 ]\r\n");
Assert.Equal("EIE1531", new StarterNG.Infrastructure.Sceneries.TimetableLocator(files)
.TrainNumber(new StarterNG.Domain.Sceneries.Scenery(TestInstallation.At("scenery", "td.scn"), ""),
@"baltyk\eie1531"));
}
[Fact]
public void A_timetable_that_is_not_there_gives_no_train_number() =>
Assert.Null(new StarterNG.Infrastructure.Sceneries.TimetableLocator(new InMemoryFileSystem())

View File

@@ -0,0 +1,175 @@
using Avalonia.Automation.Peers;
using Avalonia.Automation.Provider;
using Avalonia.Input;
using StarterNG.Application;
using StarterNG.Domain.Tapes;
using StarterNG.Tests.Fakes;
using StarterNG.Views.Tapes;
namespace StarterNG.Tests;
/// <summary>A recorded trip walked from the keyboard and read by a screen reader, on both ways of drawing it.</summary>
[Collection(AvaloniaControls.Name)]
public class TapeViewTests
{
// The electronic tape writes its legend in the starter's language.
static TapeViewTests()
{
if (AppServices.CurrentOrNull is null)
{
var installation = new TestInstallation(new InMemoryFileSystem());
AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
}
}
public static TheoryData<string> Views => new() { "hasler", "electronic" };
private static TapeView View(string kind) => kind == "hasler" ? new HaslerTapeView() : new ElectronicTapeView();
/// <summary>Two minutes, a sample a second, 15 m a second; running from 10 s to 110 s, braking after 100 s.</summary>
private static HaslerTape Trip() =>
new(Enumerable.Range(0, 121)
.Select(i => new TapeSample(i, i is > 10 and < 110 ? 54 : 0, i * 15.0, i > 100 ? 2 : 0, 5,
i < 50 ? 300 : 0, i == 70))
.ToList());
private static (TapeView View, List<TapeSample?> Hovered) Walking(string kind, bool byDistance = true)
{
var view = View(kind);
view.Tape = Trip();
view.ByDistance = byDistance;
var hovered = new List<TapeSample?>();
view.Hovered += s => hovered.Add(s);
return (view, hovered);
}
[Theory]
[MemberData(nameof(Views))]
public void The_trip_is_a_slider_read_as_the_moment_under_the_cursor(string kind)
{
var view = View(kind);
var peer = Controls.Peer(view);
var value = Assert.IsAssignableFrom<IValueProvider>(peer);
view.Spoken = "10:00:12, km 0,2, 54 km/h";
Assert.Equal(AutomationControlType.Slider, peer.GetAutomationControlType());
Assert.True(peer.IsContentElement());
Assert.True(peer.IsControlElement());
Assert.Equal("10:00:12, km 0,2, 54 km/h", value.Value);
Assert.True(value.IsReadOnly);
Assert.Throws<InvalidOperationException>(() => value.SetValue("x"));
view.Spoken = "10:00:13, km 0,2, 54 km/h";
Assert.Equal("10:00:13, km 0,2, 54 km/h", value.Value);
}
[Theory]
[MemberData(nameof(Views))]
public void The_first_arrow_starts_at_the_beginning_and_the_next_go_a_hundred_metres(string kind)
{
var (view, hovered) = Walking(kind);
Assert.True(Controls.Press(view, Key.Right));
Assert.Equal(0, hovered[^1]!.Value.Time);
Assert.True(Controls.Press(view, Key.Right));
Assert.InRange(hovered[^1]!.Value.DistanceM, TapeView.DistanceStep - 15, TapeView.DistanceStep + 15);
Assert.True(Controls.Press(view, Key.Right, KeyModifiers.Control));
Assert.True(hovered[^1]!.Value.DistanceM >= TapeView.DistanceStep * TapeView.CtrlTimes - 15);
Assert.True(Controls.Press(view, Key.Left, KeyModifiers.Control));
Assert.True(hovered[^1]!.Value.DistanceM <= TapeView.DistanceStep + 15);
Assert.True(Controls.Press(view, Key.End));
Assert.Equal(120, hovered[^1]!.Value.Time);
Assert.True(Controls.Press(view, Key.Right));
Assert.Equal(120, hovered[^1]!.Value.Time);
Assert.True(Controls.Press(view, Key.Home));
Assert.Equal(0, hovered[^1]!.Value.Time);
Assert.True(Controls.Press(view, Key.Left));
Assert.Equal(0, hovered[^1]!.Value.Time);
}
[Theory]
[MemberData(nameof(Views))]
public void By_time_an_arrow_goes_ten_seconds(string kind)
{
var (view, hovered) = Walking(kind, byDistance: false);
Controls.Press(view, Key.Left);
Assert.Equal(0, hovered[^1]!.Value.Time);
Controls.Press(view, Key.Right);
Assert.Equal(TapeView.TimeStep, hovered[^1]!.Value.Time);
Controls.Press(view, Key.Left);
Assert.Equal(0, hovered[^1]!.Value.Time);
}
[Theory]
[MemberData(nameof(Views))]
public void Enter_picks_the_sample_the_keys_stand_at_once_they_have_moved(string kind)
{
var (view, _) = Walking(kind);
TapeSample? picked = null;
view.Picked += s => picked = s;
Assert.False(Controls.Press(view, Key.Enter));
Assert.Null(picked);
Controls.Press(view, Key.End);
Assert.True(Controls.Press(view, Key.Enter));
Assert.Equal(120, picked!.Value.Time);
}
[Theory]
[MemberData(nameof(Views))]
public void A_new_trip_starts_the_keys_from_its_beginning(string kind)
{
var (view, hovered) = Walking(kind);
Controls.Press(view, Key.End);
view.Tape = Trip();
Controls.Press(view, Key.Right);
Assert.Equal(0, hovered[^1]!.Value.Time);
}
[Theory]
[MemberData(nameof(Views))]
public void Other_keys_and_an_empty_trip_are_left_alone(string kind)
{
var (view, hovered) = Walking(kind);
var empty = View(kind);
var blank = View(kind);
blank.Tape = new HaslerTape([]);
Assert.False(Controls.Press(view, Key.A));
Assert.False(Controls.Press(empty, Key.Right));
Assert.False(Controls.Press(blank, Key.Right));
Assert.Empty(hovered);
}
[Theory]
[MemberData(nameof(Views))]
public void The_trip_draws_with_and_without_the_focus(string kind)
{
var (view, _) = Walking(kind);
view.Mark = 60;
var window = Controls.Show(view, 1200, 600);
try
{
Assert.True(view.Focusable);
view.Focus();
Controls.Press(view, Key.Right);
Controls.Settle();
window.Focus();
Controls.Settle();
}
finally
{
window.Close();
}
}
}

View File

@@ -0,0 +1,22 @@
using StarterNG.Domain.Vehicles;
using StarterNG.Infrastructure.Vehicles;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class TextureFolderTests
{
private static readonly TestInstallation Installation = new(new InMemoryFileSystem(caseSensitive: true)
.WithFile("game/dynamic/PKP/EP09_v1/textures.txt", "")
.WithDirectory("game/Other/Folder"));
[Theory]
[InlineData("pkp/ep09_v1/", "dynamic/PKP/EP09_v1")]
[InlineData(@"PKP\EP09_V1", "dynamic/PKP/EP09_v1")]
[InlineData("other/folder/", "Other/Folder")]
[InlineData("pkp/brak/", "pkp/brak")]
public void A_liverys_folder_is_found_as_it_is_named_on_disk(string named, string onDisk) =>
Assert.Equal(Path.GetFullPath(Path.Combine("game", onDisk)),
Path.GetFullPath(TextureFolder.Of(Installation.Files, Installation.Paths,
new VehicleTexture { Directory = named })));
}

View File

@@ -1,42 +1,93 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 18
VisualStudioVersion = 18.1.11312.151 d18.0
VisualStudioVersion = 18.1.11312.151
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StarterNG", "StarterNG\StarterNG.csproj", "{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StarterNG.Tests", "StarterNG.Tests\StarterNG.Tests.csproj", "{00B068D7-2F49-4CAA-BC21-506503EBDFC8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Eu07.BlackBox", "Eu07.BlackBox\Eu07.BlackBox.csproj", "{B94F5951-3DC8-4DD8-A694-133B76395A5A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Eu07.BlackBox.Views", "Eu07.BlackBox.Views\Eu07.BlackBox.Views.csproj", "{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Eu07.BlackBox.Viewer", "Eu07.BlackBox.Viewer\Eu07.BlackBox.Viewer.csproj", "{0C131487-66CE-42B9-8BB6-93AAD8C47719}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Debug|x64.ActiveCfg = Debug|x64
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Debug|x64.Build.0 = Debug|x64
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Debug|x86.ActiveCfg = Debug|Any CPU
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Debug|x86.Build.0 = Debug|Any CPU
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Release|Any CPU.Build.0 = Release|Any CPU
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Release|x64.ActiveCfg = Release|x64
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Release|x64.Build.0 = Release|x64
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Release|x86.ActiveCfg = Release|Any CPU
{D1E8A3A3-3269-415A-94AD-D6F370D7E4FD}.Release|x86.Build.0 = Release|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Debug|x64.ActiveCfg = Debug|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Debug|x64.Build.0 = Debug|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Debug|x86.ActiveCfg = Debug|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Debug|x86.Build.0 = Debug|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Release|Any CPU.Build.0 = Release|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Release|x64.ActiveCfg = Release|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Release|x64.Build.0 = Release|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Release|x86.ActiveCfg = Release|Any CPU
{00B068D7-2F49-4CAA-BC21-506503EBDFC8}.Release|x86.Build.0 = Release|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Debug|x64.ActiveCfg = Debug|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Debug|x64.Build.0 = Debug|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Debug|x86.ActiveCfg = Debug|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Debug|x86.Build.0 = Debug|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Release|Any CPU.Build.0 = Release|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Release|x64.ActiveCfg = Release|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Release|x64.Build.0 = Release|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Release|x86.ActiveCfg = Release|Any CPU
{B94F5951-3DC8-4DD8-A694-133B76395A5A}.Release|x86.Build.0 = Release|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Debug|x64.ActiveCfg = Debug|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Debug|x64.Build.0 = Debug|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Debug|x86.ActiveCfg = Debug|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Debug|x86.Build.0 = Debug|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Release|Any CPU.Build.0 = Release|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Release|x64.ActiveCfg = Release|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Release|x64.Build.0 = Release|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Release|x86.ActiveCfg = Release|Any CPU
{7A522978-9E79-4ADC-A3F2-1FEFD196C41E}.Release|x86.Build.0 = Release|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Debug|x64.ActiveCfg = Debug|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Debug|x64.Build.0 = Debug|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Debug|x86.ActiveCfg = Debug|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Debug|x86.Build.0 = Debug|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Release|Any CPU.Build.0 = Release|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Release|x64.ActiveCfg = Release|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Release|x64.Build.0 = Release|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Release|x86.ActiveCfg = Release|Any CPU
{0C131487-66CE-42B9-8BB6-93AAD8C47719}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(RiderSharedRunConfigurations) = postSolution
File = linuix.run\StarterNG (linux64).run.xml
File = windows.run\StarterNG (win64).run.xml
EndGlobalSection
EndGlobal

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();
@@ -202,8 +207,12 @@ public partial class App : Avalonia.Application
if (check.ExecutableMissing())
await main.OfferExecutablePickAsync();
if (CpuFeatures.LacksAvx2 && AppServices.Current.Settings.CpuNotice)
await main.ShowCpuNoticeAsync();
// A build without AVX2 in the folder is started instead, and needs no notice.
var services = AppServices.Current;
if (services.Settings.CpuNotice
&& services.Executables.Resolve(services.Settings, out _) is var executable
&& services.Executables.WillNotRunHere(executable))
await main.ShowCpuNoticeAsync(executable);
});
});
}

View File

@@ -13,6 +13,6 @@ public static class AppInfo
#if DEBUG
text += " (DEBUG)";
#endif
return text + " public beta";
return text;
}
}

View File

@@ -7,6 +7,9 @@ namespace StarterNG.Application.Abstractions;
public interface IFileSystem
{
/// <summary>Whether a name finds its file whatever the case of its letters, as on Windows and macOS.</summary>
bool IgnoresCase { get; }
bool FileExists(string path);
bool DirectoryExists(string path);

View File

@@ -56,6 +56,7 @@ public sealed class AppServices
var missingAssets = new MissingAssetScanner(files, paths);
SceneryTexts = new SceneryTranslations(files, log);
Timetables = new TimetableLocator(files);
Attachments = new AttachmentLocator(files, paths);
LoadWeights = new LoadWeightsRepository(files, paths, log);
Library = new GameLibrary(Vehicles, Sceneries, MiniTextures, Physics, log);
State = new AppState();
@@ -80,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)
{
@@ -119,6 +123,8 @@ public sealed class AppServices
public TimetableLocator Timetables { get; }
public AttachmentLocator Attachments { get; }
public LoadWeightsRepository LoadWeights { get; }
public GameLibrary Library { get; }

View File

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

View File

@@ -0,0 +1,45 @@
using System;
using System.Threading.Tasks;
namespace StarterNG.Application;
/// <summary>
/// Runs a piece of work one at a time. Asked again while it runs, it does not start a
/// second one alongside, nor forget the request: it runs once more when the first ends,
/// however many times it was asked meanwhile. For the UI thread, which calls it alone.
/// </summary>
public sealed class OneAtATime
{
private readonly Func<Task> _work;
private bool _running;
private bool _again;
public OneAtATime(Func<Task> work) => _work = work;
public bool IsRunning => _running;
public async Task RunAsync()
{
if (_running)
{
_again = true;
return;
}
_running = true;
try
{
do
{
_again = false;
await _work();
}
while (_again);
}
finally
{
_running = false;
_again = false;
}
}
}

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

@@ -61,13 +61,6 @@ public enum SceneryFaultKind
/// <summary>An include whose file is not there; <see cref="SceneryFault.Token"/> names it.</summary>
MissingInclude,
/// <summary>
/// An include whose file is there only under a name in other letter case: the
/// simulator looks for it in lower case, which on Linux misses it. The
/// <see cref="SceneryFault.Subject"/> holds the name on disk.
/// </summary>
IncludeLetterCase,
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
IncludeNotClosed,

View File

@@ -5,12 +5,6 @@ using System.Linq;
namespace StarterNG.Domain.Sceneries;
/// <summary>
/// What the simulator makes of an include: whether it opens the file - and when
/// it does not, the file that is there under a name differing only in letter case.
/// </summary>
public readonly record struct IncludeLookup(bool Opens, string? OnDisk = null);
/// <summary>
/// Goes through a scenery's text for the parts the starter reads - trainsets,
/// vehicles, includes - finding where each trainset and loose vehicle is, and
@@ -35,17 +29,17 @@ public static class ScenerySyntax
/// <param name="text">The scenery's text, its includes put in place.</param>
/// <param name="file">The scenery's file name, for faults in its own text.</param>
/// <param name="findInclude">
/// What the simulator makes of an include, named as the include names it; null
/// <param name="opensInclude">
/// Whether the simulator opens an include, named as the include names it; null
/// leaves includes unchecked.
/// </param>
public static Result Scan(string text, string file, Func<string, IncludeLookup>? findInclude = null)
public static Result Scan(string text, string file, Func<string, bool>? opensInclude = null)
{
string code = SceneryCode.Mask(text, out int unclosed);
var tokens = SceneryCode.Tokens(code);
var lines = new SceneryLines(text, file);
var simulator = new Reading(tokens, lines, findInclude, asSimulator: true);
var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true);
simulator.Run();
var author = new Reading(tokens, lines, null, asSimulator: false);
author.Run();
@@ -116,7 +110,7 @@ public static class ScenerySyntax
}
private sealed class Reading(
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, IncludeLookup>? findInclude, bool asSimulator)
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator)
{
public readonly List<(int Start, int End, string Name)> Trainsets = new();
public readonly List<(int, int)> Loose = new();
@@ -375,13 +369,8 @@ public static class ScenerySyntax
return stop < tokens.Count && tokens[stop].Is("end") ? stop : stop - 1;
}
if (findInclude is not null && Plain(name) && findInclude(name) is { Opens: false } lookup)
{
if (lookup.OnDisk is { } onDisk)
Fault(SceneryFaultKind.IncludeLetterCase, token.Index, onDisk, name);
else
Fault(SceneryFaultKind.MissingInclude, token.Index, token: name);
}
if (opensInclude is not null && Plain(name) && !opensInclude(name))
Fault(SceneryFaultKind.MissingInclude, token.Index, token: name);
// The simulator takes its parameters up to the word "end", written just so,
// whatever comes before it.

View File

@@ -0,0 +1,55 @@
using System;
using System.IO;
namespace StarterNG.Infrastructure.Adapters;
/// <summary>
/// Tells when anything in a folder or below it is written, made, removed or renamed, as
/// the system reports it. Only a hint that it is time to look: a save comes as several
/// reports, and on a network drive, under Wine or past the system's limit of watches it
/// may come as none, so whoever listens still looks now and then on its own.
/// </summary>
public sealed class FolderChanges : IDisposable
{
private readonly FileSystemWatcher? _watcher;
/// <summary>Something changed, or the reports were lost and anything may have: on a thread of the pool.</summary>
public event Action? Changed;
/// <param name="folder">Watched with everything below it; a missing one is not watched.</param>
public FolderChanges(string folder)
{
try
{
if (!Directory.Exists(folder))
return;
var watcher = new FileSystemWatcher(folder)
{
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName
| NotifyFilters.LastWrite | NotifyFilters.Size,
// Unpacking an update changes hundreds of files at once.
InternalBufferSize = 64 * 1024
};
watcher.Changed += (_, _) => Changed?.Invoke();
watcher.Created += (_, _) => Changed?.Invoke();
watcher.Deleted += (_, _) => Changed?.Invoke();
watcher.Renamed += (_, _) => Changed?.Invoke();
// Too many at once for the buffer: which ones is lost, so all are looked at.
watcher.Error += (_, _) => Changed?.Invoke();
watcher.EnableRaisingEvents = true;
_watcher = watcher;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException
or PlatformNotSupportedException)
{
// Out of watches on Linux, or a drive that gives none: the slow look alone stays.
}
}
/// <summary>Whether the system reports changes here at all.</summary>
public bool Watching => _watcher is not null;
public void Dispose() => _watcher?.Dispose();
}

View File

@@ -10,6 +10,9 @@ public sealed class PhysicalFileSystem : IFileSystem
{
public const string TempSuffix = ".starter.tmp";
// Their disks as they come; a Linux one tells case apart.
public bool IgnoresCase { get; } = OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();
public bool FileExists(string path) => File.Exists(path);
public bool DirectoryExists(string path) => Directory.Exists(path);
@@ -88,8 +91,18 @@ public sealed class PhysicalFileSystem : IFileSystem
public void CopyFile(string sourcePath, string destinationPath, bool overwrite) =>
File.Copy(sourcePath, destinationPath, overwrite);
// The pattern matches names in any letter case, as on Windows: the game's data,
// made there, has X.SCN as well as x.scn.
public IReadOnlyList<string> GetFiles(string path, string searchPattern = "*") =>
Directory.Exists(path) ? Directory.GetFiles(path, searchPattern) : Array.Empty<string>();
Directory.Exists(path)
? Directory.GetFiles(path, searchPattern, new EnumerationOptions
{
IgnoreInaccessible = false,
AttributesToSkip = 0,
MatchType = MatchType.Win32,
MatchCasing = MatchCasing.CaseInsensitive
})
: Array.Empty<string>();
// A folder it may not enter costs what is in it, not the whole listing.
public IReadOnlyList<string> GetFilesRecursive(string path, string searchPattern) =>
@@ -99,7 +112,8 @@ public sealed class PhysicalFileSystem : IFileSystem
RecurseSubdirectories = true,
IgnoreInaccessible = true,
AttributesToSkip = 0,
MatchType = MatchType.Win32
MatchType = MatchType.Win32,
MatchCasing = MatchCasing.CaseInsensitive
})
: Array.Empty<string>();

View File

@@ -0,0 +1,132 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using StarterNG.Application.Abstractions;
namespace StarterNG.Infrastructure;
/// <summary>
/// Finds a file or folder of the game's data by a name whose letters may stand in
/// another case than on disk, as Windows, Wine and the simulator find it, and gives
/// the name as the disk has it. The data is made on Windows: its names and the
/// names written in it seldom agree letter for letter, which on Linux matters.
/// </summary>
public sealed class CaseInsensitivePaths
{
private readonly IFileSystem _files;
private readonly Func<(string Folder, bool Files), ILookup<string, string>> _list;
/// <summary>Each folder's files and folders by name, listed once until <see cref="Forget"/>; null lists every time.</summary>
private readonly ConcurrentDictionary<(string Folder, bool Files), ILookup<string, string>>? _listings;
/// <param name="keepListings">
/// Lists each folder once, for many names looked up in data that stays as it is
/// meanwhile, until <see cref="Forget"/>.
/// </param>
public CaseInsensitivePaths(IFileSystem files, bool keepListings = false)
{
_files = files;
_list = List;
if (keepListings)
_listings = new ConcurrentDictionary<(string, bool), ILookup<string, string>>();
}
/// <summary>Lets the next lookups list the folders again.</summary>
public void Forget() => _listings?.Clear();
/// <summary>
/// The file named so under <paramref name="folder"/> as it is named on disk, relative
/// to the folder with forward slashes; null when nothing there answers to it. A name
/// written with its letters as on disk wins over one differing only in their case;
/// a disk that does not tell case apart gives it back as written.
/// </summary>
/// <param name="name">
/// A name under the folder, with either slash, joined to it as the simulator joins
/// it: a slash ahead of it counts for nothing.
/// </param>
/// <param name="directory">Looks for a folder instead of a file.</param>
public string? Resolve(string folder, string name, bool directory = false)
{
string[] parts = name.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
return null;
string exact = string.Join('/', parts);
string whole = Path.Combine(folder, exact);
if (directory ? _files.DirectoryExists(whole) : _files.FileExists(whole))
return exact;
// Where case does not matter, missed as written is missed in any case.
if (_files.IgnoresCase)
return null;
var found = new string[parts.Length];
return Walk(folder, parts, 0, directory, found) ? string.Join('/', found) : null;
}
/// <summary>
/// The full path of the file named so, its letters as on disk; null when there is
/// none. A name given in full is looked up from its own root, any other under
/// <paramref name="folder"/> as <see cref="Resolve"/> does.
/// </summary>
public string? Find(string folder, string name, bool directory = false)
{
if (Path.IsPathFullyQualified(name))
{
folder = Path.GetPathRoot(name)!;
name = name[folder.Length..];
}
return Resolve(folder, name, directory) is { } found
? Path.Combine(folder, found.Replace('/', Path.DirectorySeparatorChar))
: null;
}
/// <summary>
/// Finds the parts from <paramref name="at"/> on under <paramref name="current"/>. Of
/// folders named alike in other case - two copies of the data on Linux - each is
/// tried, the one written as on disk first.
/// </summary>
private bool Walk(string current, string[] parts, int at, bool directory, string[] found)
{
if (at == parts.Length)
return true;
string part = parts[at];
if (part is "." or "..")
{
found[at] = part;
return Walk(Path.Combine(current, part), parts, at + 1, directory, found);
}
bool last = at == parts.Length - 1;
var matches = Listing(current, files: last && !directory)[part]
.OrderBy(entry => string.Equals(Path.GetFileName(entry), part, StringComparison.Ordinal) ? 0 : 1);
foreach (string match in matches)
{
found[at] = Path.GetFileName(match);
if (Walk(match, parts, at + 1, directory, found))
return true;
}
return false;
}
private ILookup<string, string> Listing(string folder, bool files) =>
_listings is null ? List((folder, files)) : _listings.GetOrAdd((folder, files), _list);
// A folder that cannot be listed holds nothing to be found.
private ILookup<string, string> List((string Folder, bool Files) key)
{
var entries = Array.Empty<string>();
try
{
if (_files.DirectoryExists(key.Folder))
entries = (key.Files ? _files.GetFiles(key.Folder) : _files.GetDirectories(key.Folder)).ToArray();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Nothing listed, nothing found.
}
return entries.ToLookup(entry => Path.GetFileName(entry), StringComparer.OrdinalIgnoreCase);
}
}

View File

@@ -0,0 +1,96 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Threading;
using StarterNG.Application;
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Infrastructure;
/// <summary>
/// Looks at a folder's files for a window, one look at a time on the UI thread: when the system
/// reports a change, once the burst a save makes has passed; when the window comes back to the
/// front; when asked; and now and then anyway, for the drives and systems where the reports do
/// not come - often where none come at all. From the window's opening to its closing.
/// </summary>
public sealed class FolderLooks
{
/// <summary>How long the reports have to stop for: a save comes as several of them.</summary>
public static readonly TimeSpan Quiet = TimeSpan.FromMilliseconds(400);
/// <summary>How often it looks anyway where the system reports the changes.</summary>
public static readonly TimeSpan Watched = TimeSpan.FromSeconds(30);
/// <summary>How often it looks where the system reports nothing.</summary>
public static readonly TimeSpan Unwatched = TimeSpan.FromSeconds(2);
private readonly Func<string> _folder;
private readonly OneAtATime _look;
private readonly TimeProvider _time;
private readonly object _gate = new();
private bool _closed;
private ITimer? _quiet;
private ITimer? _often;
private FolderChanges? _changes;
/// <param name="window">Looked for from its opening to its closing.</param>
/// <param name="folder">The folder, as it is when the window opens.</param>
/// <param name="look">The look itself; it knows when it is no time to look.</param>
/// <param name="time">The clock of the timers, the system's when not given.</param>
public FolderLooks(Window window, Func<string> folder, Func<Task> look, TimeProvider? time = null)
{
_folder = folder;
_look = new OneAtATime(look);
_time = time ?? TimeProvider.System;
window.Opened += (_, _) => Watch();
window.Activated += async (_, _) => await LookAsync();
window.Closed += (_, _) => Close();
}
/// <summary>Whether the system reports the folder's changes; not before the window opens.</summary>
public bool Watching => _changes?.Watching == true;
/// <summary>Looks now, or once more after the look that runs.</summary>
public Task LookAsync() => _look.RunAsync();
private void Watch()
{
var changes = new FolderChanges(_folder());
var often = changes.Watching ? Watched : Unwatched;
lock (_gate)
{
_changes = changes;
_quiet = _time.CreateTimer(_ => LookLater(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
_often = _time.CreateTimer(_ => LookLater(), null, often, often);
}
changes.Changed += PutOff;
}
// Each report puts the look off again, so a save of many files is one look after it. The
// reports come on threads of the pool, and may come still as the window closes.
private void PutOff()
{
lock (_gate)
{
if (!_closed)
_quiet?.Change(Quiet, Timeout.InfiniteTimeSpan);
}
}
// The timers tick on threads of the pool; the look belongs on the UI thread.
private void LookLater() => Dispatcher.UIThread.Post(() => _ = LookAsync());
private void Close()
{
FolderChanges? changes;
lock (_gate)
{
_closed = true;
_quiet?.Dispose();
_often?.Dispose();
changes = _changes;
}
changes?.Dispose();
}
}

View File

@@ -5,16 +5,21 @@ using System.Runtime.InteropServices;
using Avalonia;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using StarterNG.Application.Abstractions;
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Infrastructure;
public static class LoadingScreen
{
private static readonly string[] Extensions = { ".bmp", ".jpg", ".jpeg", ".png" };
public static void Prepare(string? logoKey, string? sceneryName = null)
{
try
{
string? src = ResolveSource(logoKey) ?? ResolveSource(sceneryName) ?? PickRandom();
string? src = FindSource(new PhysicalFileSystem(), Directory.GetCurrentDirectory(), logoKey, sceneryName,
Random.Shared);
if (src is null) return;
string destDir = Path.Combine(Directory.GetCurrentDirectory(), "textures");
@@ -35,32 +40,36 @@ public static class LoadingScreen
}
}
private static string? ResolveSource(string? key)
/// <summary>
/// The picture of textures/logo under <paramref name="root"/> to show: the trainset's,
/// else the scenery's, else one of logo*.* at random; its name and extension in any
/// letter case. Null when there is none.
/// </summary>
public static string? FindSource(IFileSystem files, string root, string? logoKey, string? sceneryName,
Random random)
{
var names = new CaseInsensitivePaths(files);
if (names.Find(root, "textures/logo", directory: true) is not { } dir)
return null;
return Named(names, dir, logoKey) ?? Named(names, dir, sceneryName) ?? PickRandom(files, dir, random);
}
private static string? Named(CaseInsensitivePaths names, string dir, string? key)
{
if (string.IsNullOrWhiteSpace(key)) return null;
key = Path.GetFileNameWithoutExtension(key.Trim());
string dir = Path.Combine(Directory.GetCurrentDirectory(), "textures", "logo");
foreach (string ext in new[] { ".bmp", ".jpg", ".jpeg", ".png" })
{
string path = Path.Combine(dir, key + ext);
if (File.Exists(path)) return path;
}
return null;
if (key.Length == 0) return null;
return Extensions.Select(ext => names.Find(dir, key + ext)).FirstOrDefault(path => path is not null);
}
private static string? PickRandom()
private static string? PickRandom(IFileSystem files, string dir, Random random)
{
string dir = Path.Combine(Directory.GetCurrentDirectory(), "textures", "logo");
if (!Directory.Exists(dir)) return null;
var files = Directory.GetFiles(dir, "logo*.*")
.Where(f =>
{
string e = Path.GetExtension(f).ToLowerInvariant();
return e is ".bmp" or ".jpg" or ".jpeg" or ".png";
})
var logos = files.GetFiles(dir, "logo*.*")
.Where(f => Extensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase))
.Order(StringComparer.Ordinal)
.ToArray();
if (files.Length == 0) return null;
return files[Random.Shared.Next(files.Length)];
if (logos.Length == 0) return null;
return logos[random.Next(logos.Length)];
}
private static void WriteBmp(string sourcePath, string destPath)

View File

@@ -0,0 +1,24 @@
using StarterNG.Application.Abstractions;
using StarterNG.Domain.Sceneries;
namespace StarterNG.Infrastructure.Sceneries;
/// <summary>Where the file a scenery attaches (<c>//$f</c>) is on disk.</summary>
public sealed class AttachmentLocator
{
private readonly IGamePaths _paths;
private readonly CaseInsensitivePaths _names;
public AttachmentLocator(IFileSystem files, IGamePaths paths)
{
_paths = paths;
_names = new CaseInsensitivePaths(files);
}
/// <summary>
/// The attachment's file, named from the game's folder or in full, with its letters
/// as on disk; null when it is not there.
/// </summary>
public string? Resolve(SceneryAttachment attachment) =>
string.IsNullOrWhiteSpace(attachment.FilePath) ? null : _names.Find(_paths.Root, attachment.FilePath.Trim());
}

View File

@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using StarterNG.Application.Abstractions;
using StarterNG.Domain.Sceneries;
@@ -8,11 +9,13 @@ namespace StarterNG.Infrastructure.Sceneries;
public sealed class SceneryImageLocator
{
private readonly IFileSystem _files;
private readonly CaseInsensitivePaths _names;
private readonly Dictionary<string, string?> _cache = new();
public SceneryImageLocator(IFileSystem files)
{
_files = files;
_names = new CaseInsensitivePaths(files);
}
public string? Resolve(Scenery scenery)
@@ -34,22 +37,23 @@ public sealed class SceneryImageLocator
return null;
string name = scenery.ImageName.Replace('\\', '/').Trim();
if (Path.IsPathFullyQualified(name))
return _names.Find("", name);
if (_files.FileExists(name))
return name;
string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? ".";
string root = Path.GetDirectoryName(sceneryDir) ?? ".";
string[] candidates =
(string Folder, string Name)[] candidates =
{
name,
Path.Combine(root, name),
Path.Combine(sceneryDir, name),
Path.Combine(sceneryDir, "images", name),
Path.Combine(root, "scenery", "images", name)
(root, name),
(sceneryDir, name),
(sceneryDir, "images/" + name),
(root, "scenery/images/" + name)
};
foreach (string candidate in candidates)
if (_files.FileExists(candidate))
return candidate;
return null;
return candidates.Select(candidate => _names.Find(candidate.Folder, candidate.Name))
.FirstOrDefault(found => found is not null);
}
}

View File

@@ -20,11 +20,11 @@ public sealed class SceneryParser
_random = random;
}
/// <param name="findInclude">
/// What the simulator makes of an include, as the include names it; null leaves
/// <param name="opensInclude">
/// Whether the simulator opens an include, as the include names it; null leaves
/// includes unchecked.
/// </param>
public Scenery Parse(string path, string content, Func<string, IncludeLookup>? findInclude = null)
public Scenery Parse(string path, string content, Func<string, bool>? opensInclude = null)
{
string original = content;
@@ -38,7 +38,7 @@ public sealed class SceneryParser
// Read from the text with its optional includes blanked, which keeps every
// place where it was, so a fault's line is the line in the file.
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), findInclude);
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), opensInclude);
var faults = syntax.Faults.ToList();
var inlined = SceneryIncludes.Ranges(content);

View File

@@ -23,7 +23,7 @@ public sealed class SceneryRepository : ISceneryRepository
private readonly SceneryParser _parser;
/// <summary>The scenery folders' files and folders, listed once per load of them all.</summary>
private readonly ConcurrentDictionary<(string, bool), IReadOnlyList<string>> _listings = new();
private readonly CaseInsensitivePaths _names;
public SceneryRepository(IFileSystem files, IGamePaths paths, IDiagnosticsLog log, SceneryParser parser)
{
@@ -31,11 +31,12 @@ public sealed class SceneryRepository : ISceneryRepository
_paths = paths;
_log = log;
_parser = parser;
_names = new CaseInsensitivePaths(files, keepListings: true);
}
public IReadOnlyList<Scenery> LoadAll(IProgress<SceneryLoadProgress>? progress = null)
{
_listings.Clear();
_names.Forget();
var files = SceneryFiles().ToList();
var loaded = new ConcurrentBag<Scenery>();
int total = Math.Max(1, files.Count);
@@ -58,7 +59,7 @@ public sealed class SceneryRepository : ISceneryRepository
public Scenery? Load(string path)
{
_listings.Clear();
_names.Forget();
return LoadOne(path);
}
@@ -79,10 +80,8 @@ public sealed class SceneryRepository : ISceneryRepository
// With its own .sbt the scenery's terrain comes from it, and the simulator
// passes its terrain includes over without opening them.
bool binaryTerrain = Opens(Path.GetFileNameWithoutExtension(path) + ".sbt");
IncludeLookup FindInclude(string name) =>
Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm"))
? new IncludeLookup(true)
: new IncludeLookup(false, ResolveInclude(name));
bool OpensInclude(string name) =>
Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm"));
(string File, string Text)? ReadInclude(string name)
{
@@ -99,7 +98,7 @@ public sealed class SceneryRepository : ISceneryRepository
string own = LegacyText.Decode(_files.ReadAllBytes(path), out var ownEncoding);
string text = SceneryIncludes.Inline(own, ReadInclude);
var scenery = _parser.Parse(path, text, FindInclude);
var scenery = _parser.Parse(path, text, OpensInclude);
scenery.HasCompanionTimetable = binaryTerrain;
scenery.Sources = sources;
scenery.TextEncoding = ownEncoding;
@@ -114,11 +113,11 @@ public sealed class SceneryRepository : ISceneryRepository
}
/// <summary>
/// Whether the simulator opens a file of the scenery folder named so: by the
/// name in lower case, which on Linux has to be how it is named on disk.
/// Whether the simulator opens a file of the scenery folder named so: whatever the
/// case of its letters, on Linux too. A shade more lenient than eu07 there, which
/// folds only the letters A to Z and of two folders named alike takes the first.
/// </summary>
private bool Opens(string name) =>
_files.FileExists(Path.Combine(_paths.Scenery, SimulatorNames.Lower(name.Replace('\\', '/'))));
private bool Opens(string name) => ResolveInclude(name) is not null;
/// <summary>
/// An include's file as it is named on disk, from the scenery folder, whatever
@@ -126,44 +125,7 @@ public sealed class SceneryRepository : ISceneryRepository
/// copy written for a start carries in place of the include, so they come along
/// on Linux too.
/// </summary>
private string? ResolveInclude(string name)
{
string relative = name.Replace('\\', '/');
if (_files.FileExists(Path.Combine(_paths.Scenery, relative)))
return relative;
string[] parts = relative.Split('/', StringSplitOptions.RemoveEmptyEntries);
string directory = _paths.Scenery;
var found = new List<string>();
for (int i = 0; i < parts.Length; i++)
{
if (parts[i] is "." or "..")
{
directory = Path.Combine(directory, parts[i]);
found.Add(parts[i]);
continue;
}
bool last = i == parts.Length - 1;
string? match = Listing(directory, last)
.FirstOrDefault(entry => string.Equals(Path.GetFileName(entry), parts[i],
StringComparison.OrdinalIgnoreCase));
if (match is null)
return null;
directory = match;
found.Add(Path.GetFileName(match));
}
return string.Join('/', found);
}
private IReadOnlyList<string> Listing(string directory, bool files) =>
_listings.GetOrAdd((directory, files), key =>
{
if (!_files.DirectoryExists(key.Item1))
return Array.Empty<string>();
return key.Item2 ? _files.GetFiles(key.Item1) : _files.GetDirectories(key.Item1);
});
private string? ResolveInclude(string name) => _names.Resolve(_paths.Scenery, name);
private IEnumerable<string> SceneryFiles() =>
_files.GetFiles(_paths.Scenery, "*.scn")

View File

@@ -14,12 +14,14 @@ public sealed class SceneryTranslations : ISceneryTranslations
private const string BaseLanguage = "en";
private readonly IFileSystem _files;
private readonly CaseInsensitivePaths _names;
private readonly IDiagnosticsLog _log;
private readonly Dictionary<string, string> _map = new(StringComparer.OrdinalIgnoreCase);
public SceneryTranslations(IFileSystem files, IDiagnosticsLog log)
{
_files = files;
_names = new CaseInsensitivePaths(files);
_log = log;
}
@@ -29,12 +31,11 @@ public sealed class SceneryTranslations : ISceneryTranslations
string sceneryDir = Path.GetDirectoryName(Path.GetFullPath(scenery.Path)) ?? "scenery";
string id = Path.GetFileNameWithoutExtension(scenery.Path);
string i18nDir = Path.Combine(sceneryDir, "i18n");
string language = NormalizeLanguage(langCode);
TryLoad(Path.Combine(i18nDir, $"{id}_{BaseLanguage}.json"));
TryLoad(_names.Find(sceneryDir, $"i18n/{id}_{BaseLanguage}.json"));
if (!string.Equals(language, BaseLanguage, StringComparison.OrdinalIgnoreCase))
TryLoad(Path.Combine(i18nDir, $"{id}_{language}.json"));
TryLoad(_names.Find(sceneryDir, $"i18n/{id}_{language}.json"));
}
public string Translate(string? text)
@@ -50,9 +51,9 @@ public sealed class SceneryTranslations : ISceneryTranslations
return _map.TryGetValue(key, out string? translated) ? translated : text;
}
private void TryLoad(string path)
private void TryLoad(string? path)
{
if (!_files.FileExists(path))
if (path is null)
return;
try

View File

@@ -17,10 +17,12 @@ public sealed class TimetableLocator
RegexOptions.Multiline | RegexOptions.IgnoreCase);
private readonly IFileSystem _files;
private readonly CaseInsensitivePaths _names;
public TimetableLocator(IFileSystem files)
{
_files = files;
_names = new CaseInsensitivePaths(files);
}
public string? Resolve(Scenery scenery, string? name)
@@ -30,17 +32,19 @@ public sealed class TimetableLocator
string sceneryDir = Path.GetDirectoryName(scenery.Path) ?? ".";
string root = Path.GetDirectoryName(sceneryDir) ?? ".";
name = name.Replace('\\', '/');
string[] candidates =
(string Folder, string Name)[] candidates =
{
Path.Combine(root, "timetables", name + ".txt"),
Path.Combine(sceneryDir, name + ".txt"),
Path.Combine(root, "scenario", name + ".txt"),
Path.Combine(root, "timetables", name),
Path.Combine(sceneryDir, name)
(root, "timetables/" + name + ".txt"),
(sceneryDir, name + ".txt"),
(root, "scenario/" + name + ".txt"),
(root, "timetables/" + name),
(sceneryDir, name)
};
return candidates.FirstOrDefault(_files.FileExists);
return candidates.Select(candidate => _names.Find(candidate.Folder, candidate.Name))
.FirstOrDefault(found => found is not null);
}
/// <summary>The number the timetable gives its train; null with no timetable or no such heading in it.</summary>

Some files were not shown because too many files have changed in this diff Show More