diff --git a/VisualPinball.Engine.DOF.Test/DofConfigToolClientTests.cs b/VisualPinball.Engine.DOF.Test/DofConfigToolClientTests.cs
new file mode 100644
index 0000000..df61a82
--- /dev/null
+++ b/VisualPinball.Engine.DOF.Test/DofConfigToolClientTests.cs
@@ -0,0 +1,252 @@
+// Visual Pinball Engine
+// Copyright (C) 2026 freezy and VPE Team
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.IO.Compression;
+using System.Net;
+using System.Net.Http;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using NUnit.Framework;
+using VisualPinball.Engine.DOF.Configuration;
+
+namespace VisualPinball.Engine.DOF.Test
+{
+ /// The Config Tool download, against answers like the Config Tool's; nothing is sent to it.
+ [TestFixture]
+ public class DofConfigToolClientTests
+ {
+ private const string Key = "AbCdEfGhIjKlMnOpQrSt";
+ private static readonly byte[] Zip = ZipOf("directoutputconfig30.ini", "tablemappings.xml");
+
+ private static byte[] ZipOf(params string[] entries)
+ {
+ using var memory = new MemoryStream();
+ using (var zip = new ZipArchive(memory, ZipArchiveMode.Create, true)) {
+ foreach (var entry in entries) {
+ using var writer = new StreamWriter(zip.CreateEntry(entry).Open());
+ writer.Write("content");
+ }
+ }
+ return memory.ToArray();
+ }
+
+ ///
+ /// A body that stops coming, after what it is given, and that doesn't end on a cancelled read either: only when it is
+ /// let go of, with an error or, as some runtimes do, as if it had ended.
+ ///
+ private sealed class Stalling : Stream
+ {
+ private readonly TaskCompletionSource _disposed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ private readonly byte[] _first;
+ private readonly bool _endsOnDispose;
+ private bool _given;
+
+ public Stalling(byte[] first = null, bool endsOnDispose = false)
+ {
+ _first = first;
+ _endsOnDispose = endsOnDispose;
+ }
+
+ public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellation)
+ {
+ if (_first != null && !_given) {
+ _given = true;
+ Array.Copy(_first, 0, buffer, offset, _first.Length);
+ return Task.FromResult(_first.Length);
+ }
+ return _disposed.Task;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, default).GetAwaiter().GetResult();
+
+ protected override void Dispose(bool disposing)
+ {
+ if (_endsOnDispose) {
+ _disposed.TrySetResult(0);
+ } else {
+ _disposed.TrySetException(new ObjectDisposedException(nameof(Stalling)));
+ }
+ base.Dispose(disposing);
+ }
+ public override bool CanRead => true;
+ public override bool CanSeek => false;
+ public override bool CanWrite => false;
+ public override long Length => throw new NotSupportedException();
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+ public override void Flush() { }
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+ public override void SetLength(long value) => throw new NotSupportedException();
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+ }
+
+ /// Answers every request with what a test says, and keeps the requests.
+ internal sealed class Answering : HttpMessageHandler
+ {
+ private readonly Func _answer;
+ public readonly List Requests = new List();
+
+ public Answering(Func answer) => _answer = answer;
+
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellation)
+ {
+ cancellation.ThrowIfCancellationRequested();
+ Requests.Add(request);
+ return Task.FromResult(_answer(request));
+ }
+ }
+
+ internal static HttpResponseMessage Answer(HttpStatusCode status, byte[] body) => new HttpResponseMessage(status) { Content = new ByteArrayContent(body) };
+
+ internal static HttpResponseMessage Answer(HttpStatusCode status, string body) => Answer(status, Encoding.UTF8.GetBytes(body));
+
+ private static byte[] Download(Answering handler, string key = Key)
+ {
+ using var client = new DofConfigToolClient("VisualPinballEngine-DOF/test", handler);
+ return client.DownloadAsync(key).GetAwaiter().GetResult();
+ }
+
+ private static string Refused(Answering handler, string key = Key)
+ {
+ var e = Assert.Throws(() => Download(handler, key));
+ Assert.That(e.Message, Does.Not.Contain(key.Trim()), "the key stays out of what is shown and logged");
+ return e.Message;
+ }
+
+ [Test]
+ public void DownloadsTheCabinetsZipWithItsKey()
+ {
+ var handler = new Answering(_ => Answer(HttpStatusCode.OK, Zip));
+ Assert.That(Download(handler, " " + Key + "\n"), Is.EqualTo(Zip));
+ var request = handler.Requests[0];
+ Assert.That(request.Method, Is.EqualTo(HttpMethod.Get));
+ Assert.That(request.RequestUri.ToString(), Is.EqualTo("https://configtool.vpuniverse.com/api.php?query=getconfig&apikey=" + Key));
+ Assert.That(request.Headers.UserAgent.ToString(), Is.EqualTo("VisualPinballEngine-DOF/test"));
+ }
+
+ [Test]
+ public void SendsTheKeyOnlyAsItsValue()
+ {
+ var handler = new Answering(_ => Answer(HttpStatusCode.OK, Zip));
+ Download(handler, "a&query=x#y");
+ Assert.That(handler.Requests[0].RequestUri.Query, Is.EqualTo("?query=getconfig&apikey=a%26query%3Dx%23y"));
+ }
+
+ [Test]
+ public void RefusesWhatIsNoKeyWithoutAsking()
+ {
+ var handler = new Answering(_ => Answer(HttpStatusCode.OK, Zip));
+ Assert.That(DofConfigToolClient.CheckKey(" "), Does.Contain("Cabinets page"));
+ Assert.That(DofConfigToolClient.CheckKey("two words"), Does.Contain("one word"));
+ Assert.That(DofConfigToolClient.CheckKey(new string('a', 257)), Is.Not.Null);
+ Assert.That(DofConfigToolClient.CheckKey(" " + Key + " "), Is.Null);
+ Assert.That(Assert.Throws(() => Download(handler, "")).Message, Does.Contain("Enter your cabinet's API key"));
+ Assert.That(handler.Requests, Is.Empty);
+ }
+
+ [Test]
+ public void SaysWhenTheConfigToolDoesNotKnowTheKey()
+ {
+ var message = Refused(new Answering(_ => Answer(HttpStatusCode.Unauthorized, "API Error: Invalid API key passed")));
+ Assert.That(message, Does.Contain("doesn't know this API key"));
+ }
+
+ [Test]
+ public void SaysWhenTheDownloadIsTurnedAway()
+ {
+ var challenge = Answer(HttpStatusCode.Forbidden, "Just a moment...");
+ challenge.Headers.Add("cf-mitigated", "challenge");
+ Assert.That(Refused(new Answering(_ => challenge)), Does.Contain("turned the download away").And.Contain("browser"));
+ Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.ServiceUnavailable, "down"))), Does.Contain("503"));
+ // the reason phrase is the server's: it may say anything, the key too
+ var echoing = Answer(HttpStatusCode.ServiceUnavailable, "down");
+ echoing.ReasonPhrase = "No cabinet " + Key;
+ Assert.That(Refused(new Answering(_ => echoing)), Does.Contain("status 503"));
+ }
+
+ [Test]
+ public void KeepsTheKeyOutOfACutAnswer()
+ {
+ // the key across the place the answer is cut at
+ var said = Refused(new Answering(_ => Answer(HttpStatusCode.OK, "API Error: " + new string('x', 180) + " " + Key + " " + new string('y', 100))));
+ Assert.That(said, Does.Not.Contain(Key.Substring(0, 6)));
+ }
+
+ [Test]
+ public void TakesNoZipWithoutIniFiles()
+ {
+ Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, ZipOf("tablemappings.xml")))), Does.Contain("without DOF ini files"));
+ Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, new byte[] { (byte)'P', (byte)'K', 3, 4, 1, 2 }))), Does.Contain("without DOF ini files"));
+ Assert.That(Download(new Answering(_ => Answer(HttpStatusCode.OK, ZipOf("Config/directoutputconfig.ini")))), Is.Not.Empty);
+ }
+
+ [Test]
+ public void GivesUpOnABodyThatStopsComing()
+ {
+ var handler = new Answering(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(new Stalling()) });
+ using var client = new DofConfigToolClient("test", handler, TimeSpan.FromMilliseconds(300));
+ var task = client.DownloadAsync(Key);
+ // the deadline covers the body
+ var e = Assert.Throws(() => task.Wait(TimeSpan.FromSeconds(10)));
+ Assert.That(e.InnerException, Is.InstanceOf().With.Message.Contain("in time"));
+
+ // a whole zip, then nothing until the deadline lets go of it, which reads as the end: still too late
+ handler = new Answering(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(new Stalling(Zip, true)) });
+ using var ending = new DofConfigToolClient("test", handler, TimeSpan.FromMilliseconds(300));
+ e = Assert.Throws(() => ending.DownloadAsync(Key).Wait(TimeSpan.FromSeconds(10)));
+ Assert.That(e.InnerException, Is.InstanceOf().With.Message.Contain("in time"));
+ }
+
+ [Test]
+ public void StopsABodyThatStopsComingWhenCancelled()
+ {
+ var handler = new Answering(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(new Stalling()) });
+ using var client = new DofConfigToolClient("test", handler);
+ using var cancellation = new CancellationTokenSource(300);
+ var task = client.DownloadAsync(Key, cancellation.Token);
+ Assert.That(() => task.Wait(TimeSpan.FromSeconds(10)), Throws.InstanceOf().With.InnerException.InstanceOf());
+ }
+
+ [Test]
+ public void TakesOnlyAZip()
+ {
+ // what the API says instead of a zip is shown, a web page isn't
+ Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, "API Error: no cabinet for " + Key))),
+ Does.Contain("sent no configuration: API Error: no cabinet for …"));
+ Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, "Maintenance"))),
+ Does.EndWith("sent no configuration."));
+ Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, Array.Empty()))), Does.Contain("sent no configuration"));
+ }
+
+ [Test]
+ public void StopsAtTheLimit()
+ {
+ var handler = new Answering(_ => Answer(HttpStatusCode.OK, new byte[2048]));
+ using var client = new DofConfigToolClient("test", handler) { MaxBytes = 1024 };
+ Assert.That(Assert.Throws(() => client.DownloadAsync(Key).GetAwaiter().GetResult()).Message, Does.Contain("larger than"));
+ }
+
+ [Test]
+ public void SaysWhenTheConfigToolCanNotBeReached()
+ {
+ var handler = new Answering(request => throw new HttpRequestException("No such host is known. (" + request.RequestUri + ")"));
+ var message = Refused(handler);
+ Assert.That(message, Does.StartWith("Could not reach the DOF Config Tool: No such host is known."));
+ }
+
+ [Test]
+ public void StopsWhenCancelled()
+ {
+ var handler = new Answering(_ => Answer(HttpStatusCode.OK, Zip));
+ using var client = new DofConfigToolClient("test", handler);
+ using var cancellation = new CancellationTokenSource();
+ cancellation.Cancel();
+ Assert.That(() => client.DownloadAsync(Key, cancellation.Token).GetAwaiter().GetResult(), Throws.InstanceOf());
+ }
+ }
+}
diff --git a/VisualPinball.Engine.DOF.Test/DofGameTriggersTests.cs b/VisualPinball.Engine.DOF.Test/DofGameTriggersTests.cs
index b994663..78510d6 100644
--- a/VisualPinball.Engine.DOF.Test/DofGameTriggersTests.cs
+++ b/VisualPinball.Engine.DOF.Test/DofGameTriggersTests.cs
@@ -145,5 +145,20 @@ public void KeepsTriggersPerRowDeviceAndPort()
reset.Save(_root);
Assert.That(File.Exists(Path.Combine(_root, DofGameTriggers.FileName)), Is.False, "no file for nothing changed");
}
+
+ [Test]
+ public void PutsOneGamesTriggersBackAndKeepsTheOthers()
+ {
+ var before = DofGameTriggers.None.With("afm", 30, 7, "S6").With("t2", 30, 1, "S1");
+ var now = before.With("afm", 30, 7, "S9").With("afm", 30, 2, "L3").With("t2", 30, 1, "S2").With("mm", 30, 4, "S4");
+ var back = now.WithRowsOf(before, new[] { "AFM " });
+ Assert.That(back.Of("afm", 30), Is.EqualTo(new[] { (7, "S6") }), "the game's as they were, the one it added gone");
+ Assert.That((back.SettingOf("t2", 30, 1), back.SettingOf("mm", 30, 4)), Is.EqualTo(("S2", "S4")), "the other games' as they are");
+ Assert.That(DofGameTriggers.Parse(back.Text).Text, Is.EqualTo(back.Text), "read as written");
+ Assert.That(DofGameTriggers.Parse("afm\t30\t7\tS6\r\n").SettingOf("afm", 30, 7), Is.EqualTo("S6"));
+ var cr = DofGameTriggers.Parse("afm\t30\t7\tS6\rt2\t30\t1\tS1\r");
+ Assert.That((cr.SettingOf("afm", 30, 7), cr.SettingOf("t2", 30, 1)), Is.EqualTo(("S6", "S1")), "a byte order mark and lines that end in CR alone");
+ Assert.That(DofGameTriggers.Parse(null).IsEmpty, Is.True);
+ }
}
}
diff --git a/VisualPinball.Engine.DOF.Test/DofImporterTests.cs b/VisualPinball.Engine.DOF.Test/DofImporterTests.cs
index e62d8e3..461b501 100644
--- a/VisualPinball.Engine.DOF.Test/DofImporterTests.cs
+++ b/VisualPinball.Engine.DOF.Test/DofImporterTests.cs
@@ -134,6 +134,44 @@ public void ImportsAConfigToolZip()
Assert.That(File.Exists(Path.Combine(revision.ConfigDir, "DirectOutputShapes.png")), Is.True);
}
+ [Test]
+ public void ImportsADownloadedZipAsAZipOfTheUser()
+ {
+ Accepted(_importer.Import(Folder("installed", ("directoutputconfig.ini", MainIni), ("Cabinet.xml", Cabinet)), DofImportMode.Replace));
+ var download = File.ReadAllBytes(Zip("download.zip", ("directoutputconfig.ini", Header + "afm,S7\r\n"), ("tablemappings.xml", Mappings)));
+ var report = Accepted(_importer.ImportDownload(download, DofConfigToolClient.Origin, new Dictionary { ["PinControl 1"] = "COM9" }));
+ var revision = _store.Active;
+ Assert.That(revision.ReadOrigin(), Is.EqualTo("the DOF Config Tool"));
+ Assert.That(Has(report, DofReportSeverity.Info, "Downloaded from the DOF Config Tool."), Is.True, report.ToString());
+ Assert.That(report.ToString(), Does.Not.Contain("Imported from"), "where it was kept for the import is no place of the user's");
+ // merged: the cabinet stays, with the ports
+ Assert.That(DofCatalog.Load(revision).Rows, Is.EqualTo(new[] { new DofRomRow(1, "afm") }));
+ Assert.That(File.ReadAllText(Path.Combine(revision.ConfigDir, "Cabinet.xml")), Does.Contain("COM9"));
+ Assert.That(Directory.GetFiles(Path.Combine(_dir, "store"), "*.zip", SearchOption.AllDirectories), Is.Empty, "the download isn't kept");
+
+ Rejected(_importer.ImportDownload(Array.Empty(), DofConfigToolClient.Origin, null), "empty");
+ Rejected(_importer.ImportDownload(Encoding.ASCII.GetBytes("PK not a zip"), DofConfigToolClient.Origin, null), "");
+ // an ini the import doesn't take is none: the merge would keep the old ones and say it imported
+ var noIni = File.ReadAllBytes(Zip("no-ini.zip", ("directoutputconfig-test.ini", MainIni), ("tablemappings.xml", Mappings)));
+ Rejected(_importer.ImportDownload(noIni, DofConfigToolClient.Origin, null), "has no DOF ini file");
+ // one that nobody waits for any more doesn't become active
+ using (var cancellation = new System.Threading.CancellationTokenSource()) {
+ cancellation.Cancel();
+ Rejected(_importer.ImportDownload(download, DofConfigToolClient.Origin, null, cancellation.Token), "stopped");
+ }
+ Assert.That(_store.Active.Id, Is.EqualTo(revision.Id));
+ }
+
+ [Test]
+ public void SaysWhichDevicesAMergeNoLongerConfigures()
+ {
+ Accepted(_importer.Import(Zip("before.zip", ("directoutputconfig30.ini", MainIni), ("directoutputconfig51.ini", SecondIni), ("directoutputconfig52.ini", SecondIni))));
+ var report = Accepted(_importer.Import(Zip("after.zip", ("directoutputconfig30.ini", MainIni))));
+ Assert.That(Has(report, DofReportSeverity.Warning, "Once imported, devices 51, 52 are no longer configured"), Is.True, report.ToString());
+ report = Accepted(_importer.Import(Zip("again.zip", ("directoutputconfig30.ini", MainIni))));
+ Assert.That(Has(report, DofReportSeverity.Warning, "no longer configured"), Is.False, report.ToString());
+ }
+
[Test]
public void CatalogKnowsTheOutputsTheCabinetMaps()
{
@@ -148,6 +186,38 @@ public void CatalogKnowsTheOutputsTheCabinetMaps()
Assert.That(catalog.Devices.Single().PortCount, Is.EqualTo(1), "the ini itself puts nothing past the knocker");
}
+ [Test]
+ public void AStripOfTheCabinetTakesThreeOutputs()
+ {
+ var cabinet = "\r\nTest"
+ + "Undercab160"
+ + "LedWizEquivalent 3030"
+ + "Undercab4"
+ + "\r\n";
+ // nothing lights the strip yet: the ini alone can't tell it from three single outputs
+ Accepted(_importer.Import(Folder("Strip", ("Config/cabinet.xml", cabinet), ("Config/directoutputconfig30.ini", Header + "#\"Rom\",\"Knocker\"\r\nrom,S1,0,0,0,0,0\r\n"))));
+ var catalog = DofCatalog.Load(_store.Active);
+ var device = catalog.Devices.Single();
+ Assert.That(device.RgbPorts, Is.EqualTo(new[] { 4 }));
+ // named as the cabinet names it, all three outputs on the board, so it can be given triggers
+ Assert.That(device.Ports[3], Is.EqualTo("Undercab"));
+ Assert.That(device.PortCount, Is.EqualTo(6));
+ }
+
+ [Test]
+ public void AStripDoesNotTakeOutputsTheConfigurationUses()
+ {
+ var cabinet = "\r\nTest"
+ + "Undercab160"
+ + "LedWizEquivalent 3030"
+ + "Undercab4"
+ + "\r\n";
+ // a solenoid on port 5, where the strip's green would be: the strip stays one output and the solenoid keeps its own
+ Accepted(_importer.Import(Folder("Strip", ("Config/cabinet.xml", cabinet), ("Config/directoutputconfig30.ini", Header + "#\"Rom\",\"Knocker\"\r\nrom,S1,0,0,0,S12,0\r\n"))));
+ var catalog = DofCatalog.Load(_store.Active);
+ Assert.That(catalog.Devices.Single().RgbPorts, Is.Empty);
+ }
+
[Test]
public void RelocatesAWindowsAuthoredConfiguration()
{
@@ -180,26 +250,23 @@ public void RelocatesAWindowsAuthoredConfiguration()
Assert.That(overridden.Revision, Is.Not.EqualTo(revision.Id));
Assert.That(DofCatalog.Load(_store.Active).SerialPorts, Is.EqualTo(new[] { "/dev/ttyACM0", "/dev/ttyACM1" }));
Assert.That(XDocument.Load(Path.Combine(_store.Active.ConfigDir, "cabinet.xml")).Root.Descendants("PinControl").Single().Element("ComPort").Value, Is.EqualTo("/dev/ttyACM0"));
- Assert.That(_store.Previous.Id, Is.EqualTo(revision.Id));
Rejected(_importer.ApplySerialOverrides(new Dictionary { ["ArtNet 1"] = "/dev/ttyACM1" }), "has no serial port");
Rejected(_importer.ApplySerialOverrides(new Dictionary { ["Nope"] = "/dev/ttyACM1" }), "no controller named");
}
[Test]
- public void SerialPortsGoIntoTheImportSoUndoRestoresTheConfigurationBeforeIt()
+ public void SerialPortsGoIntoTheImportItself()
{
Accepted(_importer.Import(Zip("before.zip", ("directoutputconfig.ini", MainIni))));
- var before = _store.Active.Id;
+ var before = _store.Active;
var report = Accepted(_importer.Import(Folder("ported",
("GlobalConfig_B2SServer.xml", WindowsGlobalConfig), ("cabinet.xml", Cabinet), ("directoutputconfig.ini", MainIni)),
DofImportMode.Replace, new Dictionary { ["PinControl 1"] = "/dev/ttyACM0", ["Nope"] = "/dev/ttyACM1" }));
Assert.That(XDocument.Load(Path.Combine(_store.Active.ConfigDir, "cabinet.xml")).Root.Descendants("PinControl").Single().Element("ComPort").Value, Is.EqualTo("/dev/ttyACM0"));
Assert.That(Has(report, DofReportSeverity.Warning, "no controller named \"Nope\""), Is.True, report.ToString());
- Assert.That(_store.Previous.Id, Is.EqualTo(before), "one revision for the import and its ports");
-
- Assert.That(_store.Rollback(), Is.True);
- Assert.That(_store.Active.Id, Is.EqualTo(before));
+ Assert.That(Directory.GetDirectories(_store.RevisionsDir), Is.EquivalentTo(new[] { Path.Combine(_store.RevisionsDir, _store.Active.Id) }), "one revision for the import and its ports");
+ Assert.That(Directory.Exists(before.BasePath), Is.False, "the configuration it replaced is gone");
}
[Test]
@@ -260,7 +327,7 @@ public void NamesControllersAsLibdofDoes()
+ "LW1"
+ "OtherCOM5"
+ "ignored1COM3"
- + "ignored"
+ + "ignored"
+ "\r\n";
Accepted(_importer.Import(Folder("named",
("GlobalConfig_B2SServer.xml", WindowsGlobalConfig), ("cabinet.xml", cabinet), ("directoutputconfig.ini", MainIni))));
@@ -272,6 +339,7 @@ public void NamesControllersAsLibdofDoes()
("PinControl", "PinControl", false),
("PacUIO", "PacUIO", false),
}));
+ Assert.That(catalog.Controllers.Select(c => c.Number), Is.EqualTo(new[] { 0, 1, 0, 1, 1 }), "a LedWiz's Number element, a Pac board's Id attribute");
// A port for a controller named by its attribute reaches it.
Accepted(_importer.ApplySerialOverrides(new Dictionary { ["Strip"] = "/dev/ttyACM1", ["PinControl"] = "/dev/ttyACM0" }));
@@ -622,22 +690,55 @@ public void FolderImportDoesNotFollowLinks()
}
[Test]
- public void RollbackAndLeasesKeepRevisionsAlive()
+ public void AnImportReplacesTheConfigurationAndLeasesKeepItAlive()
{
Accepted(_importer.Import(Zip("1.zip", ("directoutputconfig.ini", MainIni))));
var first = _store.Active;
using (var lease = _store.Acquire()) {
Assert.That(lease.Revision.Id, Is.EqualTo(first.Id));
Accepted(_importer.Import(Zip("2.zip", ("directoutputconfig.ini", SecondIni))));
+ var second = _store.Active;
+ Assert.That(Directory.Exists(second.BasePath), Is.True);
Accepted(_importer.Import(Zip("3.zip", ("directoutputconfig.ini", MainIni))));
Assert.That(Directory.Exists(first.BasePath), Is.True, "a leased revision is kept");
+ Assert.That(Directory.Exists(second.BasePath), Is.False, "replaced, not leased: pruned at once");
}
- Assert.That(Directory.Exists(first.BasePath), Is.False, "released, neither active nor previous: pruned");
+ Assert.That(Directory.Exists(first.BasePath), Is.False, "released and not active: pruned");
+ Assert.That(Directory.GetDirectories(_store.RevisionsDir).Select(Path.GetFileName), Is.EqualTo(new[] { _store.Active.Id }));
+ }
- var third = _store.Active.Id;
- var second = _store.Previous.Id;
- Assert.That(_store.Rollback(), Is.True);
- Assert.That((_store.Active.Id, _store.Previous.Id), Is.EqualTo((second, third)));
+ [Test]
+ public void ClearingRemovesTheConfiguration()
+ {
+ Assert.That(_store.Clear(), Is.False, "nothing to clear");
+ Accepted(_importer.Import(Zip("1.zip", ("directoutputconfig.ini", MainIni))));
+ var first = _store.Active;
+ Assert.That(_store.Clear("not-it"), Is.False, "another configuration than the one expected");
+ Assert.That(_store.Active.Id, Is.EqualTo(first.Id));
+ using (_store.Acquire()) {
+ Assert.That(_store.Clear(first.Id), Is.True);
+ Assert.That(_store.Active, Is.Null);
+ Assert.That(Directory.Exists(first.BasePath), Is.True, "the game that holds it keeps it");
+ }
+ Assert.That(Directory.Exists(first.BasePath), Is.False, "released: pruned");
+ // an import after it starts from nothing
+ Accepted(_importer.Import(Zip("2.zip", ("directoutputconfig.ini", SecondIni))));
+ Assert.That(_store.Active, Is.Not.Null);
+ }
+
+ [Test]
+ public void APreviousRevisionOfAnOlderPlayerIsPruned()
+ {
+ Accepted(_importer.Import(Zip("1.zip", ("directoutputconfig.ini", MainIni))));
+ var first = _store.Active;
+ // what the pointer file of an older Player kept: the configuration before, for its undo
+ var old = Path.Combine(_store.RevisionsDir, "20200101-000000-0000abcd");
+ Directory.CreateDirectory(Path.Combine(old, DofRevision.ConfigFolder));
+ File.WriteAllText(Path.Combine(_store.Root, "revisions.txt"), $"active={first.Id}\nprevious=20200101-000000-0000abcd\n");
+ Assert.That(_store.Active.Id, Is.EqualTo(first.Id));
+ _store.Prune();
+ Assert.That(Directory.Exists(old), Is.False);
+ Assert.That(Directory.Exists(first.BasePath), Is.True);
}
[Test]
@@ -880,6 +981,35 @@ public void BuildsAGameCopyWithTheUsersTriggers()
Assert.That(Directory.Exists(basePath), Is.False);
}
+ [Test]
+ public void BuildsAGameCopyThatFiresTheToysTheUserAdded()
+ {
+ Accepted(_importer.Import(Zip("config.zip", ("directoutputconfig.ini", MainIni), ("directoutputconfig51.ini", SecondIni),
+ ("DirectOutputShapes.xml", Shapes), ("DirectOutputShapes.png", "png"))));
+ var revision = _store.Active;
+ var catalog = DofCatalog.Load(revision);
+ var gear = DofToyNames.FirstPort;
+ var lamp = gear + 1;
+ var names = DofToyNames.None.With(1, gear, "Gear motor").With(1, lamp, "Lamp", true);
+ var triggers = DofGameTriggers.None.With("afm", 1, gear, "S28").With("afm", 1, lamp, "L5 Red");
+ var problems = new List();
+ var basePath = DofGameConfig.Build(revision, catalog, _store.Root, catalog.Match("afm_113b"), triggers, problems, names);
+ Assert.That(problems, Is.Empty, string.Join(Environment.NewLine, problems));
+ var row = DofIniRow.Read(Path.Combine(basePath, DofRevision.ConfigFolder, "directoutputconfig.ini"), "afm");
+ Assert.That(row.SettingOf(gear, 1), Is.EqualTo("S28"));
+ Assert.That(row.SettingOf(lamp, 3), Is.EqualTo("L5 Red"), "an RGB toy, on its port and the next two");
+ using (var dof = DofInstance.Create(basePath)) {
+ dof.Init(null, "afm_113b");
+ dof.Finish();
+ }
+
+ // without the names, the colour doesn't fit a port of one output
+ problems.Clear();
+ DofGameConfig.Build(revision, catalog, _store.Root, catalog.Match("afm_113b"), triggers, problems);
+ Assert.That(problems, NUnit.Framework.Has.Some.Contains($"Device 1, port {lamp}").And.Some.Contains("takes one output"));
+ DofGameConfig.Delete(_store.Root);
+ }
+
[Test]
public void ReportsTheSourceAndWhatItHeld()
{
diff --git a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs
index ab61f52..187de59 100644
--- a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs
+++ b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs
@@ -171,7 +171,7 @@ private void BoundedCleanup(DofInstance dof)
[Test]
public void ReportsAbiAndLibdofVersion()
{
- Assert.That(DofLibrary.NativeAbiVersion, Is.EqualTo(9));
+ Assert.That(DofLibrary.NativeAbiVersion, Is.EqualTo(10));
Assert.That(DofLibrary.LibdofVersion, Does.Match(@"^\d+\.\d+\.\d+"));
}
@@ -531,6 +531,36 @@ public void PortTestLightsTheToyAPortNames()
Assert.That(dof.TestToy(1, 9, 255, out _), Is.EqualTo(DofStatus.InvalidState), "after finish");
}
+ [Test]
+ public void PixelTestLightsSinglePointsAsGiven()
+ {
+ var strip = Unit("ArtNetStrip");
+ strip.Ports = false;
+ // a strip one point high in RGB order with libdof's Linear curve: the points are the LEDs on the wire
+ using var config = new TestConfig().GlobalConfig()
+ .Cabinet(8, new Dictionary { [1] = "Probe" }, TestConfig.LedStrip("Probe", strip, 6, 1), strip);
+ using var dof = DofInstance.Create(config.Root);
+ dof.SetOutputGate(false);
+ dof.SetConnectTests(false);
+ dof.Init(null, null);
+ Assert.That(dof.TestPixels("Probe", new byte[] { 255, 0, 0, 0, 255, 0, 0, 0, 200 }), Is.EqualTo(DofStatus.Ok));
+ var opening = _capture.Mark(strip.Universe);
+ WaitSettled(dof, dof.SetOutputGate(true));
+ var lit = ExpectIndex(strip.Universe, f => f[0] == 255 && f[4] == 255 && f[8] == 200, "red, green and blue on the first three LEDs", opening);
+ Assert.That(_capture.Frames(strip.Universe)[lit].Take(18), Is.EqualTo(new byte[] { 255, 0, 0, 0, 255, 0, 0, 0, 200, 0, 0, 0, 0, 0, 0, 0, 0, 0 }),
+ "nothing else, and nothing past them");
+
+ Assert.That(dof.TestPixels("Probe", null), Is.EqualTo(DofStatus.Ok));
+ var cleared = _capture.Mark(strip.Universe);
+ ExpectIndex(strip.Universe, f => f.Take(18).All(v => v == 0), "cleared, the strip is dark", Math.Max(cleared, lit + 1));
+
+ Assert.That(dof.TestPixels("Nothing", new byte[] { 1, 2, 3 }), Is.EqualTo(DofStatus.InvalidArgument), "no toy of the name");
+ Assert.That(dof.TestPixels("Probe", new byte[7 * 3]), Is.EqualTo(DofStatus.InvalidArgument), "more colours than points");
+ Assert.That(dof.TestPixels("LedWizEquivalent 1", new byte[] { 1, 2, 3 }), Is.EqualTo(DofStatus.NotSupported), "no colour matrix");
+ dof.Finish();
+ Assert.That(dof.TestPixels("Probe", null), Is.EqualTo(DofStatus.InvalidState), "after finish");
+ }
+
[Test]
public void PortTestKeepsTheStripsFadingCurve()
{
diff --git a/VisualPinball.Engine.DOF.Test/DofOutputWiringTests.cs b/VisualPinball.Engine.DOF.Test/DofOutputWiringTests.cs
index 36c0089..8b9ba6f 100644
--- a/VisualPinball.Engine.DOF.Test/DofOutputWiringTests.cs
+++ b/VisualPinball.Engine.DOF.Test/DofOutputWiringTests.cs
@@ -146,6 +146,30 @@ public void SavesAndLoadsPortsThatDriveNothing()
Assert.That(loaded.OutputOf(1, 40), Is.EqualTo(2));
}
+ [Test]
+ public void KeepsWhatTheUserSaysThePortsDrive()
+ {
+ var names = DofPortNames.None.With(1, 5, " Shaker\n ", false).With(1, 8, "Lamp", true).With(2, 3, "", true);
+ Assert.That(names.Of(1, 5), Is.EqualTo(("Shaker", false)), "on one line, without the spaces around it");
+ Assert.That(names.Of(2, 3), Is.EqualTo(("", false)), "no toy is no RGB toy");
+ Assert.That(names.Of(1, 6), Is.Null);
+ names.Save(_root);
+ Assert.That(File.ReadAllText(Path.Combine(_root, DofPortNames.FileName)), Is.EqualTo("1:5=Shaker\n1:8:rgb=Lamp\n2:3=\n"));
+ var loaded = DofPortNames.Load(_root);
+ Assert.That(loaded.Of(1, 5), Is.EqualTo(("Shaker", false)));
+ Assert.That(loaded.Of(1, 8), Is.EqualTo(("Lamp", true)));
+ Assert.That(loaded.Of(2, 3), Is.EqualTo(("", false)));
+ Assert.That(loaded.PortsOf(1), Is.EqualTo(new[] { 5, 8 }));
+ // lines that name no port are left out, and a later line of a port replaces an earlier one
+ File.AppendAllText(Path.Combine(_root, DofPortNames.FileName), "x:1=A\n1=B\n1:0=C\n1:2:red=D\n1:5=Gear\n");
+ loaded = DofPortNames.Load(_root);
+ Assert.That(loaded.PortsOf(1), Is.EqualTo(new[] { 5, 8 }));
+ Assert.That(loaded.Of(1, 5), Is.EqualTo(("Gear", false)));
+ loaded.Without(1, 5).Without(1, 8).Without(2, 3).Save(_root);
+ Assert.That(File.Exists(Path.Combine(_root, DofPortNames.FileName)), Is.False, "no file without a name");
+ Assert.That(DofPortNames.Load(_root).IsEmpty, Is.True);
+ }
+
[Test]
public void KeepsTheToysTheUserNamed()
{
@@ -155,6 +179,23 @@ public void KeepsTheToysTheUserNamed()
var loaded = DofToyNames.Load(_root);
Assert.That(loaded.NameOf(1, 40), Is.EqualTo("Gear motor"));
Assert.That(loaded.PortsOf(2), Is.EqualTo(new[] { 33 }));
+ // an RGB toy, on its port and the next two
+ Assert.Throws(() => loaded.With(1, DofOutputWiring.MaxOutput, "Lamp", true), "an RGB toy Load would leave out");
+ Assert.That(loaded.With(1, DofOutputWiring.MaxOutput, "Lamp").NameOf(1, DofOutputWiring.MaxOutput), Is.EqualTo("Lamp"));
+ var rgb = loaded.With(1, 50, "Lamp", true);
+ Assert.That((rgb.IsRgb(1, 50), rgb.StartOf(1, 52), rgb.StartOf(1, 53), rgb.StartOf(1, 40)), Is.EqualTo((true, 50, 0, 40)));
+ rgb.Save(_root);
+ Assert.That(File.ReadAllText(Path.Combine(_root, DofToyNames.FileName)), Does.Contain("1:50:rgb=Lamp"));
+ loaded = DofToyNames.Load(_root);
+ Assert.That((loaded.NameOf(1, 50), loaded.IsRgb(1, 50), loaded.IsRgb(1, 40)), Is.EqualTo(("Lamp", true, false)));
+ Assert.That(loaded.RgbPortsOf(1), Is.EqualTo(new[] { 50 }));
+ // a later line of the port replaces the toy, and an RGB one with a toy of one output
+ File.AppendAllText(Path.Combine(_root, DofToyNames.FileName), "1:50=Motor");
+ var replaced = DofToyNames.Load(_root);
+ Assert.That((replaced.NameOf(1, 50), replaced.IsRgb(1, 50), replaced.StartOf(1, 51)), Is.EqualTo(("Motor", false, 0)));
+ Assert.That(loaded.With(1, 50, "Lamp").IsRgb(1, 50), Is.False, "named again as a toy of one output");
+ loaded = loaded.With(1, 50, "");
+ Assert.That(loaded.IsRgb(1, 50), Is.False, "gone with its name");
loaded.With(1, 40, " ").With(2, 33, "").Save(_root);
Assert.That(File.Exists(Path.Combine(_root, DofToyNames.FileName)), Is.False, "no file without a name");
Assert.That(DofToyNames.Clean(new string('x', 100)).Length, Is.EqualTo(DofToyNames.MaxLength));
diff --git a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs
index 656d4ca..994e67e 100644
--- a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs
+++ b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs
@@ -140,7 +140,7 @@ public void TableConfigsDoNotSilenceTheIniRows()
{
// The player loads no table configs: one without AddLedControlConfig would replace the ini rows. A session
// passes no table file, so none is looked up, also in a revision whose global config still names a table
- // config pattern, as earlier imports wrote it, and after a rollback to one.
+ // config pattern, as earlier imports wrote it.
const int universe = 304;
var source = Path.Combine(_dir, "source");
Directory.CreateDirectory(source);
@@ -148,10 +148,8 @@ public void TableConfigsDoNotSilenceTheIniRows()
File.WriteAllText(Path.Combine(source, name + ".xml"),
$"\r\n\r\n");
}
- string earlier;
using (var lease = Import(universe, "vpetest,S1")) {
var revision = lease.Revision;
- earlier = revision.Id;
Assert.That(revision.TableConfigs, Is.EqualTo(new[] { "bound", "vpetest_l1" }));
var global = System.Xml.Linq.XDocument.Load(revision.GlobalConfigFile);
var patterns = global.Root.Element("TableConfigFilePatterns");
@@ -162,15 +160,6 @@ public void TableConfigsDoNotSilenceTheIniRows()
global.Save(revision.GlobalConfigFile);
DrivesTheIniRow(revision, universe, "a revision with a pattern");
}
-
- using (Import(universe, "vpetest,S2")) {
- }
- var store = new DofConfigStore(Path.Combine(_dir, "store"));
- Assert.That(store.Rollback(), Is.True);
- using (var lease = store.Acquire()) {
- Assert.That(lease.Revision.Id, Is.EqualTo(earlier));
- DrivesTheIniRow(lease.Revision, universe, "the revision a rollback restored");
- }
}
private void DrivesTheIniRow(DofRevision revision, int universe, string what)
diff --git a/VisualPinball.Engine.DOF.Test/DofTriggerConfigTests.cs b/VisualPinball.Engine.DOF.Test/DofTriggerConfigTests.cs
new file mode 100644
index 0000000..5fde905
--- /dev/null
+++ b/VisualPinball.Engine.DOF.Test/DofTriggerConfigTests.cs
@@ -0,0 +1,105 @@
+// Visual Pinball Engine
+// Copyright (C) 2026 freezy and VPE Team
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Xml.Linq;
+using NUnit.Framework;
+using VisualPinball.Engine.DOF.Configuration;
+
+namespace VisualPinball.Engine.DOF.Test
+{
+ /// What the trigger editor reads of a configuration: its colours, its strips, and its triggers as libdof reads them.
+ public class DofTriggerConfigTests
+ {
+ private const string Ini = "[version]\r\nversion=5302\r\n\r\n[Colors DOF]\r\nRed=#FF0000FF\r\nDark_orange=#FF8C00\r\nDim=24,0,48\r\nBroken=#12\r\n\r\n"
+ + "[Variables DOF]\r\n@flash@=W30 500\r\n\r\n"
+ + "[Config DOF]\r\nt2,0,0,0,L12 Blue/S3 Red,@flash@,0\r\n";
+
+ [Test]
+ public void ReadsColoursAsLibdofDoes()
+ {
+ Assert.That(DofColor.TryParse("Red=#FF0000FF", out var red), Is.True);
+ Assert.That((red.Name, red.Red, red.Green, red.Blue), Is.EqualTo(("Red", (byte)255, (byte)0, (byte)0)));
+ Assert.That(DofColor.TryParse("Dim = 24,0,48", out var dim), Is.True, "the 0 to 48 scale of the old files");
+ Assert.That((dim.Name, dim.Red, dim.Green, dim.Blue), Is.EqualTo(("Dim", (byte)127, (byte)0, (byte)255)));
+ Assert.That(DofColor.TryParse("Broken=#12", out _), Is.False);
+ Assert.That(DofColor.TryParse("=#FF0000", out _), Is.False);
+ Assert.That(DofColor.TryParse("Gold", out _), Is.False);
+ }
+
+ [Test]
+ public void TheIniFileListsItsColours()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "vpe-dof-colors-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(root);
+ try {
+ var path = Path.Combine(root, "directoutputconfig30.ini");
+ File.WriteAllText(path, Ini);
+ var ini = DofIniFile.Load(path);
+ Assert.That(ini.Colors.Select(c => c.Name), Is.EqualTo(new[] { "Red", "Dark_orange", "Dim" }), "a line it can't read left out");
+ } finally {
+ Directory.Delete(root, true);
+ }
+ }
+
+ [Test]
+ public void TheColoursAreTheFirstDofSectionsAsLibdofReadsThem()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "vpe-dof-colors-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(root);
+ try {
+ var path = Path.Combine(root, "directoutputconfig30.ini");
+ File.WriteAllText(path, "[Colors LedWiz]\r\nRed=#00FF00FF\r\nGreen=#00FF00FF\r\n[Colors DOF]\r\nRed=#FF0000FF\r\n[Config DOF]\r\nafm,S1\r\n");
+ var ini = DofIniFile.Load(path);
+ Assert.That(ini.Colors.Select(c => (c.Name, c.Red, c.Green)), Is.EqualTo(new[] { ("Red", (byte)255, (byte)0) }), "[Colors DOF] alone");
+ Assert.That(ini.HasColorSection, Is.True);
+ File.WriteAllText(path, "[Colors DOF]\r\n# none\r\n[Colors LedWiz]\r\nRed=#00FF00FF\r\n[Config DOF]\r\nafm,S1\r\n");
+ ini = DofIniFile.Load(path);
+ Assert.That((ini.HasColorSection, ini.Colors.Count), Is.EqualTo((false, 0)), "an empty [Colors DOF] is the one libdof reads, and it skips the file");
+ File.WriteAllText(path, "[Colors LedWiz]\r\nRed=#00FF00FF\r\n[colors dof]\r\n[Config DOF]\r\nafm,S1\r\n");
+ ini = DofIniFile.Load(path);
+ Assert.That((ini.HasColorSection, ini.Colors.Count), Is.EqualTo((true, 1)), "libdof finds sections by their exact header");
+ Assert.That(ini.HasConfigRows, Is.True);
+ File.WriteAllText(path, "[Colors DOF]\r\nRed=#FF0000FF\r\n[Config DOF]\r\n# none\r\n[Config outs]\r\nafm,S1\r\n");
+ ini = DofIniFile.Load(path);
+ Assert.That((ini.HasConfigRows, ini.Roms.Count), Is.EqualTo((false, 1)), "an empty [Config DOF] is the one libdof reads, and it skips the file");
+ File.WriteAllText(path, "[Colors DOF]\r\nRed=#FF0000FF\r\n[config dof]\r\nafm,S1\r\n");
+ ini = DofIniFile.Load(path);
+ Assert.That(ini.HasConfigRows, Is.False, "nor a section in other case");
+ } finally {
+ Directory.Delete(root, true);
+ }
+ }
+
+ [Test]
+ public void ReadsTriggersWithTheirVariablesReplaced()
+ {
+ var t2 = DofIniRow.Parse(Ini, "t2");
+ Assert.That(t2.SettingOf(7, 1), Is.EqualTo("@flash@"), "as written");
+ Assert.That(t2.ResolvedSettingOf(7, 1), Is.EqualTo("W30 500"), "as libdof reads it");
+ Assert.That(t2.ResolvedSettingOf(4, 3), Is.EqualTo("L12 Blue/S3 Red"));
+ Assert.That(t2.ResolvedSettings, Is.EqualTo(new[] { "", "", "", "L12 Blue/S3 Red", "W30 500", "" }), "one per column, nothing for a 0");
+ }
+
+ [Test]
+ public void FindsTheStripsACabinetWiresToItsOutputs()
+ {
+ var xml = XDocument.Parse(""
+ + "Left strip160TopDownLeftRight"
+ + "Matrix328"
+ + "30"
+ + "Left strip1"
+ + "Matrix4"
+ + "Shaker7"
+ + "");
+ var strips = DofCatalog.Strips(xml);
+ Assert.That(strips.Keys, Is.EquivalentTo(new[] { (30, 1), (30, 4) }), "the shaker is no strip");
+ Assert.That((strips[(30, 1)].Width, strips[(30, 1)].Height), Is.EqualTo((1, 60)));
+ Assert.That((strips[(30, 4)].Width, strips[(30, 4)].Height), Is.EqualTo((32, 8)));
+ }
+ }
+}
diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofHardware.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofHardware.cs
index 3a01f5b..69b367e 100644
--- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofHardware.cs
+++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofHardware.cs
@@ -204,6 +204,104 @@ internal static (bool Success, string Message) Pulse(DofConfigStore store, Plugi
});
}
+ ///
+ /// Lights the ports of a device at levels for a moment, such as an RGB toy's red, green and blue in a colour, as
+ /// turns one port on: with DOF dark and confirmed so first, the gate open only while they are set.
+ ///
+ /// Each port, from 1, and its level, 0 to 255.
+ internal static (bool Success, string Message) Light(DofConfigStore store, PluginOutputLeases leases, string pluginId, DofOutputWiring wiring, int device,
+ IReadOnlyList<(int Port, int Value)> values, TimeSpan duration, TimeSpan confirmTimeout, Func nativeFactory,
+ CancellationToken cancellation)
+ {
+ var outputs = values.Select(v => wiring.OutputOf(device, v.Port)).ToList();
+ var where = outputs.Count == 1 ? $"output {outputs[0]}" : "outputs " + string.Join(", ", outputs);
+ return Run(store, leases, pluginId, wiring, nativeFactory, confirmTimeout, cancellation, (native, dark) => {
+ if (cancellation.IsCancellationRequested) {
+ return (false, Cancelled);
+ }
+ if (!dark.Applied || dark.State.Pending > 0) {
+ return (false, $"{Units(dark.Units, "DOF")} did not confirm within {Seconds(confirmTimeout, "0.#")} s that {Their(dark.Units)} outputs "
+ + "are off, so nothing was turned on: a controller that is still connecting could run its own test.");
+ }
+ var devices = Devices(native);
+ if (dark.State.Written == 0) {
+ if (devices != null && !devices.Any(d => d.Number == device)) {
+ return (false, NotSettable(devices, dark.HasCabinet, device, values[0].Port, outputs[0]));
+ }
+ return (false, dark.State.Failed > 0
+ ? $"No controller can send the test: {Units(dark.Units, "every controller")} failed, so nothing was turned on."
+ : "No controller took part, so nothing was turned on.");
+ }
+ // A toy the cabinet names on the first port, such as an RGB toy of its own, has no levels of its own to set: it lights
+ // as a test of the port lights it, in its own colour.
+ if (devices != null && devices.Any(d => d.Number == device && d.KindOf(values[0].Port) == DofPortKind.Toy)) {
+ var status = native.TestToy(device, values[0].Port, 255, out var toy);
+ if (status != DofStatus.Ok) {
+ return (false, status == DofStatus.NotSupported
+ ? $"On device {device}, {What(values[0].Port, outputs[0])} names {ToyName(toy)}, which a test can't light."
+ : $"DOF could not light the toy on output {outputs[0]} of device {device} ({status}).");
+ }
+ // cancelled while the toy was set: not lit at all, not even for a moment
+ if (cancellation.IsCancellationRequested) {
+ native.TestToy(device, values[0].Port, 0, out _);
+ return (false, $"Cancelled: {ToyName(toy)} on output {outputs[0]} of device {device} was to be lit for {Seconds(duration)} s.");
+ }
+ var opened = native.SetOutputGate(true);
+ var stopped = cancellation.WaitHandle.WaitOne(duration);
+ native.SetOutputGate(false);
+ native.TestToy(device, values[0].Port, 0, out _);
+ var lit = opened >= 0 ? native.GetGateState(opened).Written : 0;
+ var lost = dark.State.Failed > 0 ? $" {Units(dark.Units, "A controller")} failed and took no part." : string.Empty;
+ if (stopped) {
+ return (false, $"Cancelled: {ToyName(toy)} on output {outputs[0]} of device {device} was to be lit for {Seconds(duration)} s.{lost}");
+ }
+ var asked = $"Requested to light {ToyName(toy)} on output {outputs[0]} of device {device} for {Seconds(duration)} s, in its own colour: "
+ + "the cabinet names the toy, so a test can't choose its colour";
+ return lit > 0
+ ? (true, $"{asked}. {Controllers(lit)} acknowledged the gate opening.{lost}")
+ : (false, $"{asked}, but no controller confirmed writing it.{lost}");
+ }
+ if (devices != null && values.Skip(1).Any(v => devices.Any(d => d.Number == device && d.KindOf(v.Port) == DofPortKind.Toy))) {
+ return (false, $"On device {device}, {where} name a toy, which a test can't light in a colour.");
+ }
+ void Off()
+ {
+ foreach (var (port, _) in values) {
+ native.TestOutput(device, port, 0);
+ }
+ }
+ foreach (var (port, value) in values) {
+ var status = native.TestOutput(device, port, value);
+ if (status != DofStatus.Ok) {
+ Off();
+ var output = wiring.OutputOf(device, port);
+ return (false, status == DofStatus.InvalidArgument
+ ? NotSettable(devices, dark.HasCabinet, device, port, output)
+ : $"DOF could not set output {output} of device {device} ({status}).");
+ }
+ }
+ if (cancellation.IsCancellationRequested) {
+ Off();
+ return (false, Cancelled);
+ }
+ var watch = Stopwatch.StartNew();
+ var opening = native.SetOutputGate(true);
+ var cancelled = cancellation.WaitHandle.WaitOne(duration);
+ native.SetOutputGate(false);
+ var open = watch.Elapsed;
+ Off();
+ var wrote = opening >= 0 ? native.GetGateState(opening).Written : 0;
+ var failed = dark.State.Failed > 0 ? $" {Units(dark.Units, "A controller")} failed and took no part." : string.Empty;
+ if (cancelled) {
+ return (false, $"Cancelled after {Seconds(open)} s: {where} of device {device} were to be lit for {Seconds(duration)} s.{failed}");
+ }
+ var requested = $"Requested to light {where} of device {device} for {Seconds(duration)} s";
+ return wrote > 0
+ ? (true, $"{requested}: {Controllers(wrote)} acknowledged the gate opening. Delivery to the toy is unconfirmed.{failed}")
+ : (false, $"{requested}, but no controller confirmed writing it.{failed}");
+ });
+ }
+
private const string Cancelled = "Cancelled; nothing was turned on.";
// The messages are English: seconds with a decimal point, whatever the culture.
diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs
index 54e6bbb..6560424 100644
--- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs
+++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs
@@ -132,7 +132,7 @@ public override async Task PrepareGameAsync(PluginGameContext game, Cancellation
var lamps = LampsOf(scene);
var gameName = components.Select(c => c.GameName).FirstOrDefault(n => !string.IsNullOrWhiteSpace(n));
// The ini rows drive the outputs: the session loads no table XML config (DofSession).
- (_rom, _romProblem) = DofGameSetup.ResolveRom(game.Settings.String("Rom", DofGameSetup.Auto), game.Identity, RunningRom(scene, game.Identity), gameName, catalog);
+ (_rom, _romProblem) = DofGameSetup.ResolveRom(game.Settings.String("Rom", ""), game.Identity, RunningRom(scene, game.Identity), gameName, catalog);
// One DOF instance per process: a previous game's may still be finishing.
var ownership = DofOwnership.TryAcquire();
@@ -484,11 +484,13 @@ private string GameConfig(DofRevision revision, DofCatalog catalog, PluginGameCo
try {
var rows = catalog.Match(_rom);
var triggers = DofGameTriggers.Load(root);
+ // the toys the user added tell their RGB toys; without them, a colour for one is a problem, the rest still applies
+ var names = DofPluginFactory.ReadNames(root) ?? DofToyNames.None;
// The settings page changes the rows of the ROM it finds without a running game. The game may play a compatible
// ROM, or have a name for DOF, with rows of their own: on a port where the user's trigger of those doesn't apply,
// the page's does, where it applies on the page.
var problems = new List();
- var (pageRom, _) = DofGameSetup.ResolveRom(game.Settings.String("Rom", DofGameSetup.Auto), game.Identity, null, null, catalog);
+ var (pageRom, _) = DofGameSetup.ResolveRom(game.Settings.String("Rom", ""), game.Identity, null, null, catalog);
foreach (var pageRow in pageRom != null ? catalog.Match(pageRom) : Array.Empty()) {
var device = catalog.Devices.FirstOrDefault(d => d.Number == pageRow.Device);
// the files are large: read only for a device the user changed
@@ -498,7 +500,7 @@ private string GameConfig(DofRevision revision, DofCatalog catalog, PluginGameCo
foreach (var row in rows.Where(r => device != null && r.Device == pageRow.Device && !string.Equals(r.Rom, pageRow.Rom, StringComparison.OrdinalIgnoreCase)).Take(1)) {
var path = Path.Combine(revision.ConfigDir, device.FileName);
var (own, page) = (DofIniRow.Read(path, row.Rom), DofIniRow.Read(path, pageRow.Rom));
- var rgb = DofGameConfig.RgbStarts(device);
+ var rgb = DofGameConfig.RgbStarts(device, names);
foreach (var (port, setting) in triggers.Of(pageRow.Rom, pageRow.Device)) {
var mine = triggers.SettingOf(row.Rom, row.Device, port);
if (own == null || page == null || mine != null && DofGameConfig.Change(own, rgb, port, mine, out _) != null) {
@@ -513,7 +515,7 @@ private string GameConfig(DofRevision revision, DofCatalog catalog, PluginGameCo
}
}
}
- var basePath = DofGameConfig.Build(revision, catalog, root, rows, triggers, problems);
+ var basePath = DofGameConfig.Build(revision, catalog, root, rows, triggers, problems, names);
foreach (var problem in problems) {
_application.Logger.Warn("A trigger you changed for this game is not applied: " + problem);
}
diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs
index eb69e02..22c63e5 100644
--- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs
+++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs
@@ -9,6 +9,7 @@
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@@ -28,7 +29,7 @@ namespace VisualPinball.Engine.DOF.Player
/// The DOF plugin: imports DOF configurations, runs DOF for each game and publishes the cabinet triggers, and
/// describes the settings the Player renders.
///
- internal sealed class DofPluginFactory : IPlayerPluginFactory, IPluginSettingsProvider, IPluginSettingsInfoProvider, IPluginOutputMapProvider, IPluginOutputRearranger, IPluginOutputAssigner, IPluginOutputTriggerEditor, IPluginSystemDefaults
+ internal sealed class DofPluginFactory : IPlayerPluginFactory, IPluginSettingsProvider, IPluginSettingsInfoProvider, IPluginOutputMapProvider, IPluginOutputAssigner, IPluginOutputDescriber, IPluginOutputTriggerEditor, IPluginOutputSnapshots, IPluginOutputColorTester, IPluginOutputTriggerSyntax, IPluginSystemDefaults
{
internal const string Id = "org.visualpinball.dof";
private const string PinMameId = "org.visualpinball.pinmame";
@@ -79,6 +80,9 @@ internal DofPluginFactory(string root)
/// Creates the DOF instance of games; tests replace it.
internal Func NativeFactory { get; set; }
+ /// Sends the requests to the DOF Config Tool; the system's when null. Tests answer them.
+ internal Func ConfigToolHandler { get; set; }
+
/// Creates the DOF instance of port tests; tests replace it.
internal Func TestNativeFactory { get; set; }
@@ -192,23 +196,35 @@ internal static NLog.LogLevel LogLevelOf(DofLogLevel level)
#region Schema
- private static PluginSettingsSchema BuildSchema() => new PluginSettingsSchema(1,
- new PluginSettingsGroup("Configuration", "Imports apply from the next game. VPE never contacts the DOF Config Tool.",
- new PluginField("ActiveConfig", "Active configuration", SettingKind.Info) { Provider = "configuration" },
+ // a property: the schema is built by a static field before the static fields after it
+ private static PluginWizard ImportWizard => new PluginWizard("Import a DOF configuration", "Where does your configuration come from?",
+ new PluginWizardChoice("By zip file", "Import the directoutputconfig.zip you downloaded from the DOF Config Tool at VPUniverse. It replaces the ini files and the other files it has; the rest stays, such as your cabinet file.",
+ "ImportZip", "import-zip"),
+ new PluginWizardChoice("By existing folder", "Import the configuration of a DOF installation on this computer. It replaces the whole configuration; the folder is copied, never changed.",
+ "ImportFolder", "import-folder"),
+ new PluginWizardChoice("By API key", "Download your configuration from the DOF Config Tool at VPUniverse directly, with your cabinet's API key. VPE contacts the Config Tool only for this.",
+ "ConfigToolKey", "import-config-tool", "Download and import"));
+
+ private static PluginSettingsSchema BuildSchema() => new PluginSettingsSchema(2,
+ new PluginSettingsGroup("Configuration", "What DOF drives your toys with: the files of the DOF Config Tool and your cabinet file. A new configuration applies from the next game.",
+ new PluginField("ActiveConfig", "Imported configuration", SettingKind.Info) { Provider = "configuration" },
+ new PluginField("Import", "Import", SettingKind.Action) { AttachTo = "ActiveConfig", Wizard = ImportWizard },
new PluginField("ShowImport", "Show details", SettingKind.Action) { Provider = "show-import", AttachTo = "ActiveConfig" },
- new PluginField("Rollback", "Undo last import", SettingKind.Action) { Provider = "rollback", AttachTo = "ActiveConfig" }),
- new PluginSettingsGroup("Import from the Config Tool", "Download your directoutputconfig.zip from the DOF Config Tool with your browser. Importing it replaces the files it contains and keeps the rest, such as your cabinet file.",
- new PluginField("ImportZip", "Zip or file", SettingKind.File) { Default = "", FullWidth = true,
+ new PluginField("ClearConfig", "Clear configuration", SettingKind.Action) { Provider = "clear-config", AttachTo = "ActiveConfig" },
+ // what the import wizard asks for; the page doesn't show them
+ // a single file, such as Cabinet.xml, imports too: all files come second
+ new PluginField("ImportZip", "Zip file", SettingKind.File) { Default = "",
+ FileFilters = new[] { new PluginFileFilter("Zip files", "zip"), new PluginFileFilter("All files", "*") },
Description = "A directoutputconfig.zip, or a single file such as Cabinet.xml." },
- new PluginField("ImportZipAction", "Import", SettingKind.Action) { Provider = "import-zip", AttachTo = "ImportZip" }),
- new PluginSettingsGroup("Import an existing installation", "A complete DOF configuration, such as the Config folder of DirectOutput. Importing it replaces the whole configuration; the folder is copied, never changed.",
- new PluginField("ImportFolder", "Configuration folder", SettingKind.Folder) { Default = "", FullWidth = true },
- new PluginField("ImportFolderAction", "Import", SettingKind.Action) { Provider = "import-folder", AttachTo = "ImportFolder" }),
- new PluginSettingsGroup("Hardware", "The connected boards DOF knows, found without opening them, and what the configuration wires to their outputs. Testing an output turns it on for a moment, outside a game; All off turns every output off, such as one a game that crashed left on. Where your cabling differs from the configuration, choose what an output drives or rearrange the outputs: games and tests use it at once, with every configuration you import.",
+ new PluginField("ImportFolder", "Configuration folder", SettingKind.Folder) { Default = "",
+ Description = "The folder with the directoutputconfig ini files, such as C:\\DirectOutput\\Config." },
+ new PluginField("ConfigToolKey", "API key", SettingKind.Text) { Default = "", Secret = true,
+ Description = "Your cabinet's API key, from the Cabinets page of the DOF Config Tool. It is kept in your settings on this computer and sent to the Config Tool when you download." }),
+ new PluginSettingsGroup("Hardware", "The connected boards DOF knows, found without opening them, and what the configuration wires to their outputs. Testing an output turns it on for a moment, outside a game; All off turns every output off, such as one a game that crashed left on. Where your cabling differs from the configuration, rewire an output: the toy it had moves to where the chosen one was, with what fires it. Where the configuration has the wrong toy on an output, only name what it drives. Games and tests use it at once, with every configuration you import.",
new PluginField("Devices", "Connected boards", SettingKind.Info) { Provider = "devices" },
new PluginField("Detect", "Detect again", SettingKind.Action) { Provider = "detect", AttachTo = "Devices" },
new PluginField("AllOff", "All off", SettingKind.Action) { Provider = "all-off", AttachTo = "Devices" },
- new PluginField("ResetWiring", "Undo rearranging", SettingKind.Action) { Provider = "reset-wiring", AttachTo = "Devices" },
+ new PluginField("ResetWiring", "Reset outputs", SettingKind.Action) { Provider = "reset-wiring", AttachTo = "Devices" },
new PluginField("Outputs", "Outputs", SettingKind.Outputs) { Provider = "outputs", FullWidth = true }),
new PluginSettingsGroup("Serial ports", "Changes the port of a controller in your cabinet file, for when the board got another port on this computer.",
new PluginField("SerialControllers", "Serial controllers", SettingKind.Info) { Provider = "serial-ports" },
@@ -220,10 +236,20 @@ internal static NLog.LogLevel LogLevelOf(DofLogLevel level)
} },
new PluginField("ApplySerialOverrides", "Apply ports", SettingKind.Action) { Provider = "apply-serial-overrides", AttachTo = "SerialOverrides" }),
new PluginSettingsGroup("This game", "Which configuration rows the game uses, and what of the game fires each toy.",
- new PluginField("Rom", "Game name", SettingKind.Choice) { Default = DofGameSetup.Auto, Scope = ConfigurationScope.GameOnly, Provider = "roms", FullWidth = true,
- Description = "Automatic uses the ROM the game plays, or the name the table sets for DOF. A table mapping for the table's name is offered here." },
+ new PluginField("Rom", "Game name", SettingKind.Text) { Default = "", Scope = ConfigurationScope.GameOnly, Provider = "rom",
+ Description = "The name the configuration's rows for this game go by, from the ROM the game plays or the name the table sets for DOF. DOF takes the rows of exactly this name, else the rows named like its start, such as t2 for t2_l8. Empty it to go back to the game's own." },
new PluginField("GameOutputs", "What fires the toys", SettingKind.Outputs) { Scope = ConfigurationScope.GameOnly, Provider = GameOutputsProvider, FullWidth = true,
- Description = "What the configuration's rows fire each toy with in this game. Choose a toy to fire it with something else: it applies to this game only, and stays when you import a configuration again." }));
+ Description = "What the configuration's rows fire each toy with in this game. Choose a toy to fire it with something else: it applies to this game only, and stays when you import a configuration again." })) {
+ // 2: the game name is typed, and an empty one is the game's own, which "auto" said before
+ Migrations = new Dictionary> {
+ [1] = values => {
+ if (values.Value("Rom") == DofGameSetup.Auto) {
+ values.Remove("Rom");
+ }
+ return values;
+ },
+ },
+ };
#endregion
@@ -253,34 +279,50 @@ private PluginChoiceCatalog Discover(string provider, PluginChoiceRequest reques
var id = revision?.Id ?? "none";
var choices = new List();
switch (provider) {
- case "roms": {
+ case "rom": {
+ // what the game name box shows while it has no name of the user's, and what the name gives
var game = request.Game;
- string automatic;
if (catalog == null || game == null) {
- automatic = "Uses the ROM the game plays, or the name the table sets for DOF.";
- } else {
- var (rom, problem) = DofGameSetup.ResolveRom(DofGameSetup.Auto, game.Value, null, null, catalog);
- automatic = rom == null ? problem : problem ?? DescribeRows(catalog, rom, "Uses " + rom);
+ return new PluginChoiceCatalog(id, choices) {
+ EmptyMessage = catalog == null ? "Import a DOF configuration first: its rows go by game names." : "Choose a game in the library first.",
+ };
}
- choices.Add(new PluginChoice(DofGameSetup.Auto, "Automatic", automatic));
+ var setting = request.Settings?.String("Rom", "") ?? "";
+ var own = setting.Trim().Length == 0 || string.Equals(setting, DofGameSetup.Auto, StringComparison.Ordinal);
+ var (rom, problem) = DofGameSetup.ResolveRom(setting, game.Value, null, null, catalog);
var mapping = DofGameSetup.TableMapping(catalog, DofGameSetup.TableNames(request.Package?.Path, request.Package?.Title));
- if (mapping != null) {
- // Table mappings go by the table's title, which another table can share: offered, never applied on their own.
- choices.Add(new PluginChoice(mapping.Value.Value, $"{mapping.Value.Value} (table mapping)",
- DescribeRows(catalog, mapping.Value.Value, $"The configuration maps \"{mapping.Value.Key}\" to it")));
+ // the configuration may know the table by its title: said, never used on its own, as another table can share it
+ var mapped = mapping != null && (rom == null || catalog.Match(rom).Count == 0)
+ ? $" The configuration maps the table \"{mapping.Value.Key}\" to {mapping.Value.Value}: type that to use it." : "";
+ if (rom == null) {
+ return new PluginChoiceCatalog(id, choices) { EmptyMessage = (problem ?? "") + mapped };
}
- if (catalog != null) {
- foreach (var group in catalog.Rows.GroupBy(r => r.Rom, StringComparer.OrdinalIgnoreCase).OrderBy(g => g.Key, StringComparer.OrdinalIgnoreCase)) {
- if (mapping != null && string.Equals(group.Key, mapping.Value.Value, StringComparison.OrdinalIgnoreCase)) {
- continue;
- }
- choices.Add(new PluginChoice(group.Key, group.Key, "Rows on " + Devices(catalog, group.Select(r => r.Device))));
- }
+ var rows = catalog.Match(rom);
+ // the game's own name shown as the rows go by it, such as t2 for t2_l8, where they all have that name
+ var names = rows.Select(r => r.Rom).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
+ var shown = own && names.Count == 1 ? names[0] : rom;
+ // what to check the name against: the game's ROM, the rows it takes, and the rows of games named alike that it
+ // doesn't, such as another game's of the same name, or a version the name is not specific enough for
+ var said = new StringBuilder();
+ var key = game.Value.Key?.Trim() ?? "";
+ said.Append(key.Length > 0 ? $"This game's ROM: {key}." : "This game has no ROM.");
+ // the table may name the game for DOF itself, which only shows as it runs
+ said.Append('\n').Append(rows.Count == 0
+ ? (own ? $"Matches no rows, unless the table names the game for DOF itself.{mapped}" : $"Matches no rows: nothing in the cabinet responds to this game.{mapped}")
+ : "Matches " + string.Join("; ", rows.GroupBy(r => r.Rom, StringComparer.OrdinalIgnoreCase)
+ .Select(g => $"{g.Key} on {Devices(catalog, g.Select(r => r.Device))}")) + ".");
+ // games named alike: rows that start like the name, the game's own ROM rather than one with the gamelogic in front
+ var stem = (own && key.Length > 0 ? key : rom).Split('_')[0];
+ var alike = catalog.Rows.Select(r => r.Rom)
+ .Where(n => stem.Length > 0 && n.StartsWith(stem, StringComparison.OrdinalIgnoreCase) && !names.Contains(n, StringComparer.OrdinalIgnoreCase))
+ .Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToList();
+ if (alike.Count > 0) {
+ const int most = 12;
+ var listed = string.Join(", ", alike.Take(most)) + (alike.Count > most ? $" and {alike.Count - most} more" : "");
+ said.Append('\n').Append($"Doesn't match {listed}: type one to use its rows.");
}
- return new PluginChoiceCatalog(id, choices) {
- EmptyMessage = "Import a DOF configuration first.",
- MissingSelectionMessage = "The configuration has no rows for this name any more.",
- };
+ choices.Add(new PluginChoice(shown, shown, said.ToString()));
+ return new PluginChoiceCatalog(id, choices);
}
case "serial-controllers": {
foreach (var controller in catalog?.Controllers.Where(c => c.UsesSerialPort) ?? Enumerable.Empty()) {
@@ -391,9 +433,8 @@ private PluginInfo DescribeConfiguration()
using var lease = Store.AcquireForReading();
var revision = lease?.Revision;
if (revision == null) {
- return new PluginInfo("No configuration imported", PluginInfoTone.Problem, new[] {
- Line("Next", "Import the zip you downloaded from the DOF Config Tool, or an existing DirectOutput folder, below."),
- }, new[] { "ShowImport", "Rollback" });
+ // Import alone: there is nothing to show or clear
+ return new PluginInfo("No configuration imported yet.", PluginInfoTone.Neutral) { HiddenFields = new[] { "ShowImport", "ClearConfig" } };
}
var catalog = CatalogOf(revision);
var warnings = revision.CountWarnings();
@@ -408,15 +449,9 @@ private PluginInfo DescribeConfiguration()
if (catalog.TableConfigs.Count > 0) {
lines.Add(Line("Table configs", $"{catalog.TableConfigs.Count}, kept but not loaded"));
}
- var previous = Store.Previous;
- if (previous != null) {
- lines.Add(Line("Undo", "Goes back to the configuration of " + When(previous)));
- }
- // without an earlier configuration, Undo has nothing to go back to
- var unavailable = previous == null ? new[] { "Rollback" } : Array.Empty();
return warnings == 0
- ? new PluginInfo("Active, without warnings", PluginInfoTone.Good, lines, unavailable)
- : new PluginInfo(warnings == 1 ? "Active, with 1 warning. Show details lists it." : $"Active, with {warnings} warnings. Show details lists them.", PluginInfoTone.Warning, lines, unavailable);
+ ? new PluginInfo("Imported, without warnings", PluginInfoTone.Good, lines)
+ : new PluginInfo(warnings == 1 ? "Imported, with 1 warning. Show details lists it." : $"Imported, with {warnings} warnings. Show details lists them.", PluginInfoTone.Warning, lines);
}
private PluginInfo DescribeDevices()
@@ -426,27 +461,193 @@ private PluginInfo DescribeDevices()
if (Store.Active == null) {
unavailable.Add("AllOff");
}
- if (Wiring.IsEmpty) {
- unavailable.Add("ResetWiring");
- }
+ // nothing to reset while no output is moved or named
+ var hidden = Wiring.IsEmpty && (ReadPortNames(Store.Root)?.IsEmpty ?? false) ? new[] { "ResetWiring" } : Array.Empty();
IReadOnlyList devices;
DateTime when;
try {
(devices, when) = Detection(false);
} catch (Exception e) when (e is DllNotFoundException || e is EntryPointNotFoundException || e is DofException) {
- return new PluginInfo("The native DOF library could not be loaded: " + e.Message, PluginInfoTone.Problem, null, unavailable);
+ return new PluginInfo("The native DOF library could not be loaded: " + e.Message, PluginInfoTone.Problem, null, unavailable) { HiddenFields = hidden };
+ }
+ var lines = new List> {
+ Line("Checked", when.ToLocalTime().ToString("HH:mm:ss", CultureInfo.InvariantCulture))
+ };
+ var use = BoardsInUse();
+ var cards = devices.Select(device => Card(device, use)).ToList();
+ return devices.Count == 0
+ ? new PluginInfo("No board DOF knows is connected", PluginInfoTone.Neutral, lines, unavailable) { HiddenFields = hidden }
+ : new PluginInfo(devices.Count == 1 ? "1 board connected" : $"{devices.Count} boards connected", PluginInfoTone.Good, lines, unavailable) { Cards = cards, HiddenFields = hidden };
+ }
+
+ /// What a game makes of the connected boards with the active configuration; null without one.
+ private BoardUse BoardsInUse()
+ {
+ // leased while it is read: an import may activate another one meanwhile, and a prune would delete this one
+ using var lease = Store.AcquireForReading();
+ var revision = lease?.Revision;
+ if (revision == null) {
+ return null;
+ }
+ var catalog = CatalogOf(revision);
+ return new BoardUse(catalog.HasCabinet, !catalog.HasCabinet || DofGameSetup.AutoConfigEnabled(revision),
+ catalog.Controllers.Select(c => (c.Type, c.Number)), catalog.Devices.Where(d => d.Loaded).Select(d => d.Number),
+ catalog.Devices.GroupBy(d => d.Number).ToDictionary(g => g.Key, g => g.First().FileName), catalog.Devices.Where(d => !d.Loaded).Select(d => d.Number));
+ }
+
+ ///
+ /// What libdof does with the boards it finds when a game starts: without a cabinet file, or with one that leaves its
+ /// automatic setup on, it sets up every board the cabinet file doesn't name itself, as the ini device of its number.
+ ///
+ internal sealed class BoardUse
+ {
+ public readonly bool HasCabinet;
+ public readonly bool AutoConfig;
+ /// The controllers the cabinet file names: their type, such as LedWiz, and number (0 for none).
+ public readonly HashSet<(string Type, int Number)> CabinetBoards;
+ /// The N of the configuration's directoutputconfigN.ini files that libdof loads.
+ public readonly HashSet IniDevices;
+ /// The N of the ones it skips, such as one without colours.
+ public readonly HashSet SkippedDevices;
+ private readonly IReadOnlyDictionary _files;
+
+ public BoardUse(bool hasCabinet, bool autoConfig, IEnumerable<(string Type, int Number)> cabinetBoards, IEnumerable iniDevices,
+ IReadOnlyDictionary files = null, IEnumerable skipped = null)
+ {
+ HasCabinet = hasCabinet;
+ AutoConfig = autoConfig;
+ CabinetBoards = new HashSet<(string, int)>(cabinetBoards);
+ IniDevices = new HashSet(iniDevices);
+ SkippedDevices = new HashSet(skipped ?? Enumerable.Empty());
+ _files = files ?? new Dictionary();
+ }
+
+ /// The name of the ini file of a device as the configuration has it, such as directoutputconfig.ini for device 1.
+ public string FileOf(int device) => _files.TryGetValue(device, out var name) && !string.IsNullOrEmpty(name) ? name : $"directoutputconfig{device}.ini";
+
+ ///
+ /// Whether the cabinet file names the board: by its number where libdof tells the boards of its type apart by one the
+ /// ini device gives away, by its type alone otherwise. Null where only the board knows its number, such as a Pinscape's
+ /// unit, and the cabinet file names one of its type.
+ ///
+ public bool? Names(string type, int device)
+ {
+ if (!CabinetBoards.Any(board => board.Type == type)) {
+ return false;
+ }
+ // the numbers libdof's automatic setup gives the boards, the other way round
+ var number = device <= 0 ? -1 : type switch {
+ "LedWiz" => device,
+ "PacLed64" => device - 19,
+ "PacUIO" => device - 27,
+ _ => 0,
+ };
+ // a PacUIO's units start at 0, which is one of them, not its type alone
+ return number < 0 ? (bool?)null : (number == 0 && type != "PacUIO") || CabinetBoards.Contains((type, number));
+ }
+ }
+
+ ///
+ /// Whether a game sets the board up and what drives it, as its card says: set up by the cabinet file that names its type,
+ /// or by DOF itself, and driven by the ini file of its number.
+ ///
+ internal static (string Text, PluginInfoTone Tone) Status(string type, int device, BoardUse use)
+ {
+ if (use == null) {
+ return ("Not in use: no configuration is imported", PluginInfoTone.Neutral);
+ }
+ var named = use.HasCabinet ? use.Names(type, device) : false;
+ if (named == true) {
+ return ("Set up by your cabinet file", PluginInfoTone.Good);
+ }
+ if (named == null && !use.AutoConfig) {
+ return ("Set up by your cabinet file if it names this board's unit; DOF's own setup is off", PluginInfoTone.Neutral);
+ }
+ if (!use.AutoConfig) {
+ return ("Not set up: your cabinet file doesn't name it and turns DOF's own setup off", PluginInfoTone.Warning);
+ }
+ var (from, to) = IniRange(type, device);
+ var files = use.IniDevices.Where(n => n >= from && n <= to).OrderBy(n => n).Select(use.FileOf).ToList();
+ var skipped = use.SkippedDevices.Where(n => n >= from && n <= to).OrderBy(n => n).Select(use.FileOf).ToList();
+ if (files.Count == 0 && skipped.Count > 0) {
+ return ($"Set up by DOF, but nothing drives it: DOF skips {string.Join(" and ", skipped)}, which {(skipped.Count == 1 ? "has" : "have")} no colours or no rows",
+ PluginInfoTone.Warning);
+ }
+ if (files.Count == 0) {
+ return (device > 0
+ ? $"Set up by DOF, but nothing drives it: the configuration has no directoutputconfig{device}.ini"
+ : $"Set up by DOF, but nothing drives it: the configuration has no ini file for devices {from}–{to}", PluginInfoTone.Warning);
+ }
+ if (device > 0) {
+ return ($"Set up by DOF, and games drive it with {files[0]}", PluginInfoTone.Good);
+ }
+ // only the board knows its unit number, which picks the file
+ return (files.Count == 1
+ ? $"Set up by DOF, and games drive it with {files[0]} if that is its unit"
+ : $"Set up by DOF, and games drive it with the one of {string.Join(", ", files)} of its unit", PluginInfoTone.Good);
+ }
+
+ // The ini devices a board can be: its own number, or the ones of its type where only the board knows its unit number.
+ private static (int From, int To) IniRange(string type, int device)
+ {
+ if (device > 0) {
+ return (device, device);
}
+ switch (type) {
+ case "Pinscape": return (51, 66);
+ case "PinscapePico": return (120, 135);
+ case "DudesCab": return (90, 94);
+ case "PinOne": return (11, 18);
+ default: return (0, -1);
+ }
+ }
+
+ ///
+ /// A detected board as the Player shows it: its name, the ini device it gets, whether a game sets it up and drives it, and
+ /// how it is connected.
+ ///
+ private static PluginInfoCard Card(DofDetectedDevice device, BoardUse use)
+ {
+ var info = device.Info;
+ var title = BoardName(device.Type);
+ // the name the board gives itself, where it says more than the type: "Virtual Pinscape KL25Z", not "PacLED64"
+ var product = Letters(info.Product);
+ var subtitle = product.Length > 0 && !product.StartsWith(Letters(device.Type), StringComparison.Ordinal) && !product.StartsWith(Letters(title), StringComparison.Ordinal)
+ ? info.Product.Trim() : null;
+ var badge = device.Device > 0 ? $"Device {device.Device}" : $"Devices {device.DeviceRange.Replace('-', '–')}";
var lines = new List>();
- foreach (var device in devices) {
- var what = (device.Device > 0 ? $"Device {device.Device}" : $"Devices {device.DeviceRange}") + ": " + device.Info;
- lines.Add(Line(device.Type, device.Notes.Count == 0 ? what : what + ". " + string.Join(" ", device.Notes)));
+ switch (info.Kind) {
+ case DofDeviceKind.Serial:
+ lines.Add(Line("Port", info.Description.Length > 0 ? $"{info.Path} · {info.Description}" : info.Path));
+ break;
+ case DofDeviceKind.Usb:
+ lines.Add(Line("USB", $"{info.VendorId:X4}:{info.ProductId:X4} · bus {info.Bus}, port {info.PortPath}"));
+ break;
+ default:
+ lines.Add(Line("USB", $"{info.VendorId:X4}:{info.ProductId:X4} · HID, interface {info.Interface}"));
+ break;
+ }
+ if (!string.IsNullOrWhiteSpace(info.SerialNumber)) {
+ lines.Add(Line("Serial number", info.SerialNumber.Trim()));
+ }
+ var (status, tone) = Status(device.Type, device.Device, use);
+ return new PluginInfoCard(title, subtitle, badge, lines, device.Notes.Count > 0 ? string.Join(" ", device.Notes) : null) { Status = status, StatusTone = tone };
+ }
+
+ private static string BoardName(string type)
+ {
+ switch (type) {
+ case "PinscapePico": return "Pinscape Pico";
+ case "LedWiz": return "LED-Wiz";
+ case "PacLed64": return "PacLED64";
+ case "DudesCab": return "Dude's Cab";
+ case "FT245RBitbangController": return "FT245R relay board";
+ default: return type;
}
- lines.Add(Line("Checked", when.ToLocalTime().ToString("HH:mm:ss", CultureInfo.InvariantCulture)));
- return devices.Count == 0
- ? new PluginInfo("No board DOF knows is connected", PluginInfoTone.Neutral, lines, unavailable)
- : new PluginInfo(devices.Count == 1 ? "1 board connected" : $"{devices.Count} boards connected", PluginInfoTone.Good, lines, unavailable);
}
+ private static string Letters(string text) => new string((text ?? "").Where(char.IsLetterOrDigit).Select(char.ToLowerInvariant).ToArray());
+
/// The boards last detected; detects them the first time, and again when asked to.
private (IReadOnlyList Devices, DateTime When) Detection(bool again)
{
@@ -461,17 +662,17 @@ private PluginInfo DescribeDevices()
private static string DescribeCabinet(DofRevision revision, DofCatalog catalog)
{
if (!catalog.HasCabinet) {
- return "No cabinet file: DOF sets up the boards it finds itself";
+ return "None, so DOF sets up the boards it finds itself. Hardware shows which.";
}
// as a game reads it: the cabinet file the global config names, its root and AutoConfigEnabled as libdof finds them
var autoConfig = DofGameSetup.AutoConfigEnabled(revision);
var controllers = string.Join(", ", catalog.Controllers.Select(c => c.SerialPort != null ? $"{c.Name} on {c.SerialPort}" : c.Name));
if (catalog.Controllers.Count == 0) {
return autoConfig
- ? "A cabinet file without controllers: DOF sets up the boards it finds"
- : "A cabinet file without controllers, and automatic setup is off: DOF drives no board";
+ ? "One without controllers, so DOF sets up the boards it finds itself. Hardware shows which."
+ : "One without controllers, and it turns DOF's own setup off: DOF drives no board";
}
- return autoConfig ? controllers + ", and the boards DOF finds itself" : controllers;
+ return autoConfig ? controllers + ", and DOF sets up the other boards it finds itself" : controllers;
}
private static string When(DofRevision revision)
@@ -513,40 +714,86 @@ public Task DescribeOutputsAsync(string provider, PluginChoiceR
internal const string GameOutputsProvider = "game-outputs";
///
- /// The boards a game has rows on, each toy with what fires it in the game; and for a PinMAME game, its solenoids, lamps
- /// and switches by the names the table gives them, to pick from.
+ /// The boards a game has rows on, each toy with what fires it in the game; and the game's solenoids, lamps and switches
+ /// by the names the table gives them, to pick from, with those the configuration uses in the game that it doesn't name.
///
private async Task DescribeGameOutputsAsync(PluginChoiceRequest request, PluginOutputLeases leases, CancellationToken cancellation)
{
- var map = await Task.Run(() => DescribeGameOutputs(request, leases, cancellation), cancellation).ConfigureAwait(false);
+ var (map, configured) = await Task.Run(() => DescribeGameOutputs(request, leases, cancellation), cancellation).ConfigureAwait(false);
+ if (!map.TriggersEditable) {
+ return map;
+ }
+ // a table's mappings name what a gamelogic engine numbers as the configuration does: those with a number
+ IReadOnlyList named = Array.Empty();
var path = request?.Package?.Path;
- if (map.TriggersEditable && request.Game?.Provider == "pinmame" && !string.IsNullOrEmpty(path)) {
+ if (!string.IsNullOrEmpty(path)) {
try {
- map.GameOutputs = GameOutputsOf(await PackagedGameInformation.ReadMappingsAsync(path, cancellation).ConfigureAwait(false));
+ named = GameOutputsOf(await PackagedGameInformation.ReadMappingsAsync(path, cancellation).ConfigureAwait(false));
} catch (Exception e) when (!(e is OperationCanceledException)) {
Logger.Warn(e, "[DOF] The switches, coils and lamps of " + path + " could not be read.");
}
}
+ map.GameOutputs = WithConfigured(named, configured);
return map;
}
- private PluginOutputMap DescribeGameOutputs(PluginChoiceRequest request, PluginOutputLeases leases, CancellationToken cancellation)
+ ///
+ /// The game's outputs, those the configuration fires a toy with marked, and those it uses that the game doesn't list
+ /// added: missing where the game lists others of their kind, else not known to be, such as the events a table fires itself.
+ ///
+ internal static IReadOnlyList WithConfigured(IReadOnlyList named, IEnumerable configured)
+ {
+ var used = new HashSet(configured ?? Enumerable.Empty(), StringComparer.OrdinalIgnoreCase);
+ var result = new List();
+ var listed = new HashSet(named.Where(o => o.Trigger.Length > 0).Select(o => char.ToUpperInvariant(o.Trigger[0])));
+ foreach (var output in named) {
+ output.Configured = used.Remove(output.Trigger);
+ result.Add(output);
+ }
+ foreach (var trigger in used.Where(t => t.Length > 1 && t[0] != '$').OrderBy(t => "SLGWE".IndexOf(char.ToUpperInvariant(t[0])))
+ .ThenBy(t => t.Length).ThenBy(t => t, StringComparer.Ordinal)) {
+ result.Add(new PluginGameOutput(trigger.ToUpperInvariant(), "") {
+ Kind = KindOf(trigger), Configured = true, Present = !listed.Contains(char.ToUpperInvariant(trigger[0])), Listed = false,
+ });
+ }
+ return result;
+ }
+
+ private static PluginGameOutputKind KindOf(string trigger) => char.ToUpperInvariant(trigger[0]) switch {
+ 'S' => PluginGameOutputKind.Coil,
+ 'L' => PluginGameOutputKind.Lamp,
+ 'G' => PluginGameOutputKind.Gi,
+ 'W' => PluginGameOutputKind.Switch,
+ _ => PluginGameOutputKind.Other
+ };
+
+ public PluginTriggerParse Parse(string trigger) => DofTriggerSyntax.Parse(trigger);
+
+ public string Format(IReadOnlyList rules) => DofTriggerSyntax.Format(rules);
+
+ // the map, and what of the game the configuration fires toys with in it
+ private (PluginOutputMap, IReadOnlyCollection) DescribeGameOutputs(PluginChoiceRequest request, PluginOutputLeases leases,
+ CancellationToken cancellation)
{
cancellation.ThrowIfCancellationRequested();
var store = Store;
using var lease = store.AcquireForReading();
var revision = lease?.Revision;
+ var none = Array.Empty();
if (revision == null) {
- return new PluginOutputMap(Array.Empty(), "Import a DOF configuration to see what fires the toys in this game.");
+ return (new PluginOutputMap(Array.Empty(), "Import a DOF configuration to see what fires the toys in this game."), none);
}
var catalog = CatalogOf(revision);
var (_, rows, problem) = GameRows(request, catalog);
if (rows.Count == 0) {
- return new PluginOutputMap(Array.Empty(), problem);
+ return (new PluginOutputMap(Array.Empty(), problem), none);
}
+ var configured = new HashSet(StringComparer.OrdinalIgnoreCase);
+ var colors = new List();
var detected = DetectedBoards(catalog);
var wiring = ReadWiring(store.Root) ?? DofOutputWiring.None;
var names = ReadNames(store.Root) ?? DofToyNames.None;
+ var described = ReadPortNames(store.Root) ?? DofPortNames.None;
var triggers = ReadTriggers(store.Root) ?? DofGameTriggers.None;
var boards = new List();
foreach (var row in rows) {
@@ -561,8 +808,15 @@ private PluginOutputMap DescribeGameOutputs(PluginChoiceRequest request, PluginO
Logger.Warn(e, "[DOF] The row of " + row.Rom + " could not be read from " + device.FileName + ".");
ini = null;
}
- var board = Board(device, detected, Reach(catalog, detected, device.Number), wiring, names);
- var rgb = DofGameConfig.RgbStarts(device);
+ // the names the user gave the outputs, not the RGB toys: the rows still have a column for each port of one
+ var board = Board(device, detected, Reach(catalog, detected, device.Number), wiring, names, described, false);
+ var rgb = DofGameConfig.RgbStarts(device, names);
+ foreach (var setting in ini?.ResolvedSettings ?? Enumerable.Empty()) {
+ configured.UnionWith(DofTriggerSyntax.Parse(setting).Rules.SelectMany(r => r.Sources));
+ }
+ foreach (var color in device.Colors.Where(c => colors.All(known => !string.Equals(known.Name, c.Name, StringComparison.OrdinalIgnoreCase)))) {
+ colors.Add(new PluginNamedColor(color.Name, color.Red, color.Green, color.Blue));
+ }
foreach (var output in board.Outputs) {
// what drives the output is chosen and shown on the global page; here only what fires it, a note saying when
// the user's trigger doesn't
@@ -579,18 +833,26 @@ private PluginOutputMap DescribeGameOutputs(PluginChoiceRequest request, PluginO
var applies = saved != null && ini != null && DofGameConfig.Change(ini, rgb, port, saved, out _) != null;
// one saved on the green or blue of an RGB toy, from before an import made one of it, is reset with the toy
var inside = width == 3 && (triggers.SettingOf(row.Rom, device.Number, port + 1) != null || triggers.SettingOf(row.Rom, device.Number, port + 2) != null);
- output.Trigger = applies ? DofIniRow.Fit(saved, width == 3, out _) : ini?.SettingOf(port, width) ?? "";
+ // as libdof reads it, the configuration's variables replaced: what the user's own can say too
+ output.ConfiguredTrigger = (ini == null ? null : SettingOfToy(ini, port, width, true)) ?? "";
+ output.Trigger = applies ? DofIniRow.Fit(saved, width == 3, out _) : output.ConfiguredTrigger;
output.TriggerChanged = saved != null || inside;
+ if (catalog.CabinetStrips.TryGetValue((device.Number, port), out var strip)) {
+ output.ToyKind = PluginOutputToyKind.Area;
+ output.ToyColumns = strip.Width;
+ output.ToyRows = strip.Height;
+ } else {
+ output.ToyKind = width == 3 ? PluginOutputToyKind.Rgb : PluginOutputToyKind.Single;
+ }
if (saved != null && !applies || inside) {
output.Note = "Yours doesn't fit";
}
}
- board.Rearrangeable = false;
board.Toys = Array.Empty();
board.AcceptsNewToys = false;
boards.Add(board);
}
- return new PluginOutputMap(boards, problem, leases == null ? NoTestsYet : "") { TriggersEditable = boards.Count > 0 };
+ return (new PluginOutputMap(boards, problem, leases == null ? NoTestsYet : "") { TriggersEditable = boards.Count > 0, Colors = colors }, configured);
}
///
@@ -603,10 +865,10 @@ private static (string Rom, IReadOnlyList Rows, string Problem) GameR
if (game == null) {
return (null, Array.Empty(), "Choose a game to see what fires the toys in it.");
}
- var setting = request.Settings?.String("Rom", DofGameSetup.Auto) ?? DofGameSetup.Auto;
+ var setting = request.Settings?.String("Rom", "") ?? "";
var (rom, problem) = DofGameSetup.ResolveRom(setting, game.Value, null, null, catalog);
if (rom == null) {
- return (null, Array.Empty(), problem ?? "The game has no name DOF knows: choose one under Game name.");
+ return (null, Array.Empty(), problem ?? "The game has no name DOF knows: type the one the configuration uses under Game name.");
}
var rows = catalog.Match(rom);
return (rom, rows, rows.Count == 0 ? $"The configuration has no rows for {rom}, so nothing fires the toys in this game." : "");
@@ -614,7 +876,7 @@ private static (string Rom, IReadOnlyList Rows, string Problem) GameR
///
- /// What of a game can fire a toy, from the table's mappings of a PinMAME game: its solenoids, flashers on solenoids,
+ /// What of a game can fire a toy, from the table's mappings of a game numbered as the configuration does: its solenoids, flashers on solenoids,
/// lamps, GI strings and switches, by number, each with the first name the table gives it.
///
internal static IReadOnlyList GameOutputsOf(MappingConfig mappings)
@@ -640,7 +902,7 @@ void Add(char letter, string id, string description)
.GroupBy(o => (o.Letter, o.Number))
.Select(g => (g.Key.Letter, g.Key.Number, Label: g.Select(o => o.Label).FirstOrDefault(l => l.Length > 0) ?? ""))
.OrderBy(o => order.IndexOf(o.Letter)).ThenBy(o => o.Number)
- .Select(o => new PluginGameOutput(o.Letter + o.Number.ToString(CultureInfo.InvariantCulture), o.Label))
+ .Select(o => new PluginGameOutput(o.Letter + o.Number.ToString(CultureInfo.InvariantCulture), o.Label) { Kind = KindOf(o.Letter.ToString()) })
.ToList();
}
@@ -700,7 +962,8 @@ private PluginActionResult SetTrigger(string id, string trigger, PluginChoiceReq
if (ini == null) {
return new PluginActionResult(false, $"{entry.FileName} has no row for {row.Rom} any more.");
}
- var rgb = DofGameConfig.RgbStarts(entry);
+ var names = ReadNames(store.Root) ?? DofToyNames.None;
+ var rgb = DofGameConfig.RgbStarts(entry, names);
var width = rgb.Contains(port) ? 3 : 1;
string setting = null;
if (trigger != null) {
@@ -714,13 +977,19 @@ private PluginActionResult SetTrigger(string id, string trigger, PluginChoiceReq
if (DofGameConfig.Change(ini, rgb, port, setting, out var unfit) == null) {
return new PluginActionResult(false, unfit);
}
- // what the configuration says is no change
- if (string.Equals(setting, ini.SettingOf(port, width), StringComparison.Ordinal)) {
+ // what the configuration says is no change, also with its variables replaced
+ if (SameAsConfigured(setting, ini, port, width)) {
setting = null;
+ } else if (setting.Length > 0) {
+ // kept as the user wrote it, fitted where it is used (DofGameConfig.Change): a colour that only fitting it to an RGB
+ // toy added doesn't keep it from firing the toy once it takes one output again
+ setting = new string(trigger.Select(c => char.IsControl(c) ? ' ' : c).ToArray()).Trim();
}
}
var header = port <= entry.Ports.Count ? entry.Ports[port - 1]?.Trim() ?? "" : "";
- var name = header.Length > 0 ? header : ReadNames(store.Root)?.NameOf(device, port) ?? "";
+ // what the user says is on the port, where the configuration says otherwise
+ header = (ReadPortNames(store.Root) ?? DofPortNames.None).Of(device, port)?.Name ?? header;
+ var name = header.Length > 0 ? header : names.NameOf(device, port) ?? "";
var toy = name.Length > 0 ? name : $"port {port} of device {device}";
lock (WiringFileLock) {
// a page left meanwhile changes nothing
@@ -769,7 +1038,8 @@ private PluginOutputMap DescribeOutputs(string provider, PluginOutputLeases leas
var detected = DetectedBoards(catalog);
var wiring = ReadWiring(store.Root) ?? DofOutputWiring.None;
var names = ReadNames(store.Root) ?? DofToyNames.None;
- var boards = catalog.Devices.Select(device => Board(device, detected, Reach(catalog, detected, device.Number), wiring, names)).ToList();
+ var described = ReadPortNames(store.Root) ?? DofPortNames.None;
+ var boards = catalog.Devices.Select(device => Board(device, detected, Reach(catalog, detected, device.Number), wiring, names, described)).ToList();
return new PluginOutputMap(boards, "The configuration has no ini files, so it assigns nothing to the outputs.", leases == null ? NoTestsYet : "");
}
@@ -825,11 +1095,13 @@ private static int FixedOutputs(string type)
/// has its number as a negative port.
///
/// The toys the user added, on ports past the configuration's.
+ /// What the user says the ports drive, where the configuration says otherwise.
+ /// Whether an RGB toy the user says is on a port takes the next two as well (see ).
internal static PluginOutputBoard Board(DofCatalogDevice device, IReadOnlyList detected, int mapped = 0, DofOutputWiring wiring = null,
- DofToyNames names = null)
+ DofToyNames names = null, DofPortNames described = null, bool shapes = true)
{
wiring ??= DofOutputWiring.None;
- var ports = new DevicePorts(device, mapped, wiring, names);
+ var ports = new DevicePorts(device, mapped, wiring, names, described, shapes);
var outputs = new List(ports.Outputs);
for (var number = 1; number <= ports.Outputs; number++) {
var port = wiring.PortOn(device.Number, number);
@@ -839,25 +1111,31 @@ internal static PluginOutputBoard Board(DofCatalogDevice device, IReadOnlyList 0 && ports.At(toy).Name.Length > 0 && device.Number <= DofOutputWiring.MaxDevice ? ToyId(toy) : "",
+ Note = was == null ? moved : moved.Length > 0 ? $"{moved} · {was}" : was,
+ // none for a device the board lists no toys for
+ Toy = toy > 0 && device.Number <= DofOutputWiring.MaxDevice ? ToyId(toy) : "",
});
}
var board = detected.FirstOrDefault(d => d.Device == device.Number);
var result = board != null
- ? new PluginOutputBoard($"{board.Type} {device.Number}", $"Device {device.Number} · {device.FileName}", outputs) { Rearrangeable = true }
- : new PluginOutputBoard($"Device {device.Number}", device.FileName, outputs) { Rearrangeable = true };
+ ? new PluginOutputBoard($"{board.Type} {device.Number}", $"Device {device.Number} · {device.FileName}", outputs)
+ : new PluginOutputBoard($"Device {device.Number}", device.FileName, outputs);
if (device.Number <= DofOutputWiring.MaxDevice) {
- result.Toys = ports.Toys.Where(t => t.Name.Length > 0).Select(t => new PluginOutputToy(ToyId(t.Port), t.Name, t.Rgb)).ToList();
+ // the user's own toys are RGB or not as the user says; the configuration's as it has them
+ // an RGB toy the header doesn't name goes by the outputs the configuration has it on
+ result.Toys = ports.Toys.Where(t => t.Name.Length > 0 || t.Rgb)
+ .Select(t => new PluginOutputToy(ToyId(t.Port), t.Name.Length > 0 ? t.Name : UnnamedRgbToy(t.Port), t.Rgb) { RgbChangeable = ports.Added(t.Port) }).ToList();
result.AcceptsNewToys = true;
}
return result;
}
+ internal static string UnnamedRgbToy(int port) => $"RGB toy of outputs {port}–{port + 2}";
+
// A toy by its first port: the red one of an RGB toy.
private static string ToyId(int port) => "p" + port.ToString(CultureInfo.InvariantCulture);
@@ -876,21 +1154,39 @@ private sealed class DevicePorts
private readonly int _device;
private readonly int _portCount;
private readonly DofToyNames _names;
- // what the configuration puts on each port, from port 1: the header's name and the colour of an RGB toy's port
+ private readonly IReadOnlyList _headers;
+ // where the configuration's rows start an RGB toy
+ private readonly HashSet _rgb;
+ // what is on each port, from port 1: the header's name, or the user's, and the colour of an RGB toy's port
private readonly List<(string Name, PluginOutputChannel Channel)> _ports;
-
- internal DevicePorts(DofCatalogDevice device, int mapped, DofOutputWiring wiring, DofToyNames names)
+ // the first ports of the toys the user named otherwise than the configuration does
+ private readonly HashSet _described = new HashSet();
+
+ /// What the user says the ports drive, where the configuration says otherwise.
+ ///
+ /// Whether an RGB toy the user says is on a port and the next two takes them, as the outputs show it; not as the game's
+ /// rows have them, which still have a column for each.
+ ///
+ internal DevicePorts(DofCatalogDevice device, int mapped, DofOutputWiring wiring, DofToyNames names, DofPortNames described = null, bool shapes = true)
{
_device = device.Number;
_portCount = device.PortCount;
_names = names ?? DofToyNames.None;
+ _headers = device.Ports;
+ described ??= DofPortNames.None;
var count = System.Math.Max(device.Number >= 1 && device.Number <= 16 ? System.Math.Max(device.PortCount, LedWizOutputs) : device.PortCount, mapped);
count = System.Math.Max(count, wiring.Extent(device.Number));
- var rgb = new HashSet(device.RgbPorts);
+ _rgb = new HashSet(device.RgbPorts);
_ports = new List<(string, PluginOutputChannel)>(count);
for (var port = 1; port <= count; port++) {
- var name = port <= device.Ports.Count ? device.Ports[port - 1]?.Trim() ?? "" : "";
- if (rgb.Contains(port) && port + 2 <= count) {
+ var said = described.Of(device.Number, port);
+ var name = said?.Name ?? HeaderOf(port);
+ // an RGB toy the user says is here doesn't take a port the configuration starts one on
+ var rgb = _rgb.Contains(port) || shapes && said?.Rgb == true && !_rgb.Contains(port + 1) && !_rgb.Contains(port + 2);
+ if (said != null) {
+ _described.Add(port);
+ }
+ if (rgb && port + 2 <= count) {
_ports.Add((name, PluginOutputChannel.Red));
_ports.Add((name, PluginOutputChannel.Green));
_ports.Add((name, PluginOutputChannel.Blue));
@@ -901,9 +1197,35 @@ internal DevicePorts(DofCatalogDevice device, int mapped, DofOutputWiring wiring
}
}
+ /// What the configuration's header names on a port; empty for none.
+ internal string HeaderOf(int port) => port >= 1 && port <= _headers.Count ? _headers[port - 1]?.Trim() ?? "" : "";
+
+ /// Whether the configuration's rows start an RGB toy on a port.
+ internal bool ConfiguredRgb(int port) => _rgb.Contains(port);
+
+ ///
+ /// What the configuration has on the first port of a toy the user named otherwise, said for its output; null for one
+ /// the user didn't name.
+ ///
+ internal string Was(int port)
+ {
+ if (!_described.Contains(port) || port < 1 || port > _ports.Count) {
+ return null;
+ }
+ var header = HeaderOf(port);
+ var (name, channel) = _ports[port - 1];
+ if (!string.Equals(name, header, StringComparison.Ordinal)) {
+ return header.Length > 0 ? $"Was {header}" : _rgb.Contains(port) ? "Was an RGB toy" : "Was nothing";
+ }
+ return channel == PluginOutputChannel.Red && !_rgb.Contains(port) ? "Was one output" : null;
+ }
+
/// How many outputs the board shows.
internal int Outputs => _ports.Count;
+ /// How many ports the configuration's rows have, named or not.
+ internal int PortCount => _portCount;
+
///
/// What is on a port: the header's name, or the user's past every port the configuration uses (a configuration that
/// came to use the port takes it), and the colour of an RGB toy's port.
@@ -911,7 +1233,20 @@ internal DevicePorts(DofCatalogDevice device, int mapped, DofOutputWiring wiring
internal (string Name, PluginOutputChannel Channel) At(int port)
{
var (name, channel) = port >= 1 && port <= _ports.Count ? _ports[port - 1] : ("", PluginOutputChannel.None);
- return name.Length > 0 || channel != PluginOutputChannel.None || port <= _portCount ? (name, channel) : (_names.NameOf(_device, port) ?? "", channel);
+ if (name.Length > 0 || channel != PluginOutputChannel.None || port <= _portCount) {
+ return (name, channel);
+ }
+ var start = AddedStart(port);
+ return start == 0 ? ("", channel)
+ : _names.IsRgb(_device, start) ? (_names.NameOf(_device, start), PluginOutputChannel.Red + (port - start))
+ : (_names.NameOf(_device, start), PluginOutputChannel.None);
+ }
+
+ // The first port of the toy the user added that a port is on, all of it past every port the configuration uses; 0 for none.
+ private int AddedStart(int port)
+ {
+ var start = _names.StartOf(_device, port);
+ return start > _portCount ? start : 0;
}
/// Whether the toy on these ports is on the board as a whole: each port on an output it shows, an RGB toy's in a row.
@@ -922,7 +1257,7 @@ internal bool Placed(DofOutputWiring wiring, IReadOnlyList toy)
}
/// Whether a port carries a toy the user added, past every port the configuration uses.
- internal bool Added(int port) => port > _portCount && _names.NameOf(_device, port) != null;
+ internal bool Added(int port) => port > _portCount && AddedStart(port) != 0;
/// The first port of the toy on a port: the red of an RGB toy, itself for a named one, 0 for none.
internal int ToyOf(int port)
@@ -949,21 +1284,27 @@ internal IReadOnlyList PortsOf(int port)
}
}
foreach (var port in _names.PortsOf(_device).Where(p => p > _ports.Count && p > _portCount)) {
- yield return (port, _names.NameOf(_device, port), false);
+ yield return (port, _names.NameOf(_device, port), _names.IsRgb(_device, port));
}
}
}
///
- /// A port for a new toy: far past every port a configuration uses and every output the board shows
- /// (), so no game drives it, a later configuration won't use it, and it drives no
- /// output yet; and that no toy has.
+ /// The first of ports in a row for a new toy: far past every port a configuration uses and
+ /// every output the board shows (), so no game drives them, a later configuration
+ /// won't use them, and they drive no output yet; and that no toy has, nor keeps free to become an RGB toy (the two
+ /// after a toy of one output). 0 for none.
///
- internal int FreePort(DofOutputWiring wiring)
+ internal int FreePorts(DofOutputWiring wiring, int count)
{
- for (var port = System.Math.Max(DofToyNames.FirstPort, System.Math.Max(_portCount, _ports.Count) + 1); port <= DofOutputWiring.MaxOutput; port++) {
+ bool Free(int port)
+ {
var output = wiring.OutputOf(_device, port);
- if (_names.NameOf(_device, port) == null && (output == port || output == DofOutputWiring.Nothing)) {
+ return _names.StartOf(_device, port) == 0 && _names.NameOf(_device, port - 1) == null && _names.NameOf(_device, port - 2) == null
+ && (output == port || output == DofOutputWiring.Nothing);
+ }
+ for (var port = System.Math.Max(DofToyNames.FirstPort, System.Math.Max(_portCount, _ports.Count) + 1); port + count - 1 <= DofOutputWiring.MaxOutput; port++) {
+ if (Enumerable.Range(port, count).All(Free)) {
return port;
}
}
@@ -1030,69 +1371,6 @@ private DofOutputWiring ReadWiring(string root)
}
}
- public Task SwapOutputsAsync(string provider, string first, string second, int count, PluginChoiceRequest request, CancellationToken cancellation)
- => Task.Run(() => provider != "outputs" ? new PluginActionResult(false, "Unknown DOF outputs.") : SwapOutputs(first, second, count, cancellation), cancellation);
-
- ///
- /// Swaps what drives two runs of outputs of a device, by where they show: the ids are ports, which drive the outputs the
- /// wiring gives them. An RGB toy's three outputs move together or not at all, unless they are apart already.
- ///
- private PluginActionResult SwapOutputs(string first, string second, int count, CancellationToken cancellation)
- {
- cancellation.ThrowIfCancellationRequested();
- if (!DofPortTest.TryParse(first, out var device, out var firstPort) || !DofPortTest.TryParse(second, out var other, out var secondPort)) {
- return new PluginActionResult(false, "Unknown output.");
- }
- // an output nothing drives has its number as a negative port
- if (device != other) {
- return new PluginActionResult(false, "Outputs move within their board only.");
- }
- if (device > DofOutputWiring.MaxDevice) {
- return new PluginActionResult(false, $"Device {device} can't be rearranged: DOF takes devices 1 to {DofOutputWiring.MaxDevice}.");
- }
- // one folder for the whole change, should the host move the store meanwhile
- var store = Store;
- using var lease = store.AcquireForReading();
- var revision = lease?.Revision;
- var catalog = revision != null ? CatalogOf(revision) : null;
- var entry = catalog?.Devices.FirstOrDefault(d => d.Number == device);
- if (entry == null) {
- return new PluginActionResult(false, "The configuration has no device " + device + ".");
- }
- lock (WiringFileLock) {
- var wiring = ReadWiring(store.Root);
- if (wiring == null) {
- return new PluginActionResult(false, "The output wiring could not be read, so nothing was changed. Try again.");
- }
- var ports = new DevicePorts(entry, Reach(catalog, DetectedBoards(catalog), device), wiring, null);
- var a = OutputAt(wiring, device, firstPort);
- var b = OutputAt(wiring, device, secondPort);
- if (count < 1 || a < 1 || b < 1 || a + count - 1 > ports.Outputs || b + count - 1 > ports.Outputs) {
- return new PluginActionResult(false, "The outputs are not all on the board.");
- }
- if (a < b + count && b < a + count) {
- return new PluginActionResult(false, "The outputs overlap.");
- }
- // An RGB toy on three outputs in a row: each run holds all three or none. One a new configuration put on outputs
- // apart moves an output at a time, so it can be put back together.
- var split = Split(ports, wiring, device, null, new[] { (a, count), (b, count) });
- if (split != null) {
- return new PluginActionResult(false, $"That would split {Toy(split)}: its red, green and blue move together.");
- }
- try {
- wiring.Swap(device, a, b, count).Save(store.Root);
- } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is ArgumentOutOfRangeException) {
- Logger.Warn(e, "[DOF] Saving the output wiring failed.");
- return new PluginActionResult(false, "Not rearranged: " + e.Message);
- } finally {
- ForgetWiring();
- }
- var moved = count == 1 ? $"outputs {a} and {b}" : $"outputs {a}–{a + count - 1} and {b}–{b + count - 1}";
- Logger.Info($"[DOF] Swapped {moved} of device {device}.");
- return new PluginActionResult(true, $"Swapped what drives {moved} of device {device}. {WhenItApplies()}");
- }
- }
-
// A game keeps the wiring it started with.
private static string WhenItApplies() => DofOwnership.InUse
? "The running game keeps the wiring it started with: it applies from the next game."
@@ -1130,14 +1408,22 @@ public Task AssignOutputAsync(string provider, string output
if (toy == null) {
return Empty(ports, wiring, names, device, number);
}
- return TryParseToy(toy, out var port) && ports.ToyOf(port) == port && ports.At(port).Name.Length > 0
+ return TryParseToy(toy, out var port) && ports.ToyOf(port) == port
? Give(ports, wiring, names, device, number, port)
: (false, "That toy is not on this board any more.", null, null);
}), cancellation);
- public Task AddToyAsync(string provider, string output, string name, PluginChoiceRequest request, CancellationToken cancellation)
+ public Task AddToyAsync(string provider, string output, string name, bool rgb, PluginChoiceRequest request, CancellationToken cancellation)
=> Task.Run(() => provider != "outputs" ? new PluginActionResult(false, "Unknown DOF outputs.")
- : ChangeOutput(output, cancellation, (ports, wiring, names, device, number) => Add(ports, wiring, names, device, number, name)), cancellation);
+ : ChangeOutput(output, cancellation, (ports, wiring, names, device, number) => Add(ports, wiring, names, device, number, name, rgb)), cancellation);
+
+ public Task SetToyRgbAsync(string provider, string output, bool rgb, PluginChoiceRequest request, CancellationToken cancellation)
+ => Task.Run(() => provider != "outputs" ? new PluginActionResult(false, "Unknown DOF outputs.")
+ : ChangeOutput(output, cancellation, (ports, wiring, names, device, number) => Shape(ports, wiring, names, device, number, rgb)), cancellation);
+
+ public Task DescribeOutputAsync(string provider, string output, string name, bool rgb, PluginChoiceRequest request, CancellationToken cancellation)
+ => Task.Run(() => provider != "outputs" ? new PluginActionResult(false, "Unknown DOF outputs.")
+ : ChangeOutput(output, cancellation, (ports, wiring, names, described, device, number) => Describe(ports, wiring, names, described, device, number, name, rgb)), cancellation);
///
/// Changes what an output of a device drives, by where it shows, as works it out from the
@@ -1146,6 +1432,17 @@ public Task AddToyAsync(string provider, string output, stri
///
private PluginActionResult ChangeOutput(string id, CancellationToken cancellation,
Func change)
+ => ChangeOutput(id, cancellation, (ports, wiring, names, described, device, number) => {
+ var (success, message, next, nextNames) = change(ports, wiring, names, device, number);
+ return (success, message, next, nextNames, null);
+ });
+
+ ///
+ /// Changes what an output of a device drives or what the user says it drives, as works it out;
+ /// saves what it returns, the toys and the names first, so a toy is never on an output without its name.
+ ///
+ private PluginActionResult ChangeOutput(string id, CancellationToken cancellation,
+ Func change)
{
cancellation.ThrowIfCancellationRequested();
if (!DofPortTest.TryParse(id, out var device, out var port)) {
@@ -1166,44 +1463,152 @@ private PluginActionResult ChangeOutput(string id, CancellationToken cancellatio
lock (WiringFileLock) {
var wiring = ReadWiring(store.Root);
var names = ReadNames(store.Root);
- if (wiring == null || names == null) {
+ var described = ReadPortNames(store.Root);
+ if (wiring == null || names == null || described == null) {
return new PluginActionResult(false, "The output wiring could not be read, so nothing was changed. Try again.");
}
- var ports = new DevicePorts(entry, Reach(catalog, DetectedBoards(catalog), device), wiring, names);
+ var ports = new DevicePorts(entry, Reach(catalog, DetectedBoards(catalog), device), wiring, names, described);
var number = OutputAt(wiring, device, port);
if (number < 1 || number > ports.Outputs) {
return new PluginActionResult(false, "That output is not on the board any more.");
}
- var (success, message, next, nextNames) = change(ports, wiring, names, device, number);
- if (!success || next == null && nextNames == null) {
+ var (success, message, next, nextNames, nextDescribed) = change(ports, wiring, names, described, device, number);
+ if (!success || next == null && nextNames == null && nextDescribed == null) {
return new PluginActionResult(success, message);
}
var namesSaved = false;
+ var describedSaved = false;
try {
if (nextNames != null) {
nextNames.Save(store.Root);
namesSaved = true;
}
+ if (nextDescribed != null) {
+ nextDescribed.Save(store.Root);
+ describedSaved = true;
+ }
next?.Save(store.Root);
} catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is ArgumentOutOfRangeException) {
Logger.Warn(e, "[DOF] Saving the output wiring failed.");
- if (namesSaved) {
- // a toy on no output would be left behind, and its name taken
- try {
+ // a toy on no output would be left behind, and its name taken; names of a change that didn't happen
+ try {
+ if (namesSaved) {
names.Save(store.Root);
- } catch (Exception again) when (again is IOException || again is UnauthorizedAccessException) {
- Logger.Warn(again, "[DOF] Putting the toys back failed.");
}
+ if (describedSaved) {
+ described.Save(store.Root);
+ }
+ } catch (Exception again) when (again is IOException || again is UnauthorizedAccessException) {
+ Logger.Warn(again, "[DOF] Putting the toys back failed.");
}
return new PluginActionResult(false, "Not changed: " + e.Message);
} finally {
ForgetWiring();
}
Logger.Info($"[DOF] Output {number} of device {device}: {message}");
- return new PluginActionResult(true, $"{message} {WhenItApplies()}");
+ // names alone change nothing a game drives
+ return new PluginActionResult(true, next == null && nextNames == null ? message : $"{message} {WhenItApplies()}");
}
}
+ ///
+ /// Output drives a toy of the name the user typed, an RGB toy on it and the next two, or no toy
+ /// for an empty name; for when the configuration has the wrong toy on it. Only names it: the port that drives the output
+ /// and what fires it stay. A toy the user added is renamed, and made an RGB toy or not.
+ ///
+ private static (bool, string, DofOutputWiring, DofToyNames, DofPortNames) Describe(DevicePorts ports, DofOutputWiring wiring, DofToyNames names,
+ DofPortNames described, int device, int number, string name, bool rgb)
+ {
+ var port = wiring.PortOn(device, number);
+ if (port == DofOutputWiring.Nothing) {
+ return (false, $"Nothing drives output {number}, so it has no toy to name. Turn on Rewire to give it one.", null, null, null);
+ }
+ var clean = DofToyNames.Clean(name);
+ rgb &= clean.Length > 0;
+ var (current, channel) = ports.At(port);
+ var start = ports.ToyOf(port);
+ if (channel == PluginOutputChannel.Green || channel == PluginOutputChannel.Blue) {
+ var red = wiring.OutputOf(device, start);
+ var on = red == DofOutputWiring.Nothing ? "its red output" : $"output {red}, its red";
+ return (false, $"Output {number} is the {(channel == PluginOutputChannel.Green ? "green" : "blue")} of {Toy(current)}: name the toy on {on}.", null, null, null);
+ }
+ var isRgb = channel == PluginOutputChannel.Red;
+ if (ports.Added(port)) {
+ if (clean.Length == 0) {
+ return (false, $"{Capital(current)} is a toy you added: turn on Rewire and choose Nothing to take it off the output.", null, null, null);
+ }
+ var same = ports.Toys.FirstOrDefault(t => t.Port != port && string.Equals(t.Name, clean, StringComparison.OrdinalIgnoreCase));
+ if (same.Port > 0) {
+ return (false, $"This board has {same.Name} already.", null, null, null);
+ }
+ if (clean == current && isRgb == rgb) {
+ return (true, $"Output {number} is {clean} already.", null, null, null);
+ }
+ DofOutputWiring shapedWiring = null;
+ var shapedNames = names;
+ var shapedText = "";
+ if (isRgb != rgb) {
+ var (shaped, text, nextWiring, nextNames) = Shape(ports, wiring, names, device, number, rgb);
+ if (!shaped) {
+ return (false, text, null, null, null);
+ }
+ shapedWiring = nextWiring;
+ shapedNames = nextNames ?? names;
+ shapedText = " " + text;
+ }
+ var renamed = clean == current ? "" : $"{Capital(current)} is called {clean} now.";
+ return (true, (renamed + shapedText).Trim(), shapedWiring, shapedNames.With(device, port, clean, rgb), null);
+ }
+ if (port > ports.PortCount) {
+ return (false, $"No configuration fires what output {number} drives, so there is nothing to name. Turn on Rewire to give it a toy.", null, null, null);
+ }
+ var configured = ports.ConfiguredRgb(port);
+ var header = ports.HeaderOf(port);
+ // the configuration's RGB toy its header doesn't name, as the toys list it, or no name for it: as the configuration has it
+ if (configured && header.Length == 0 && (clean.Length == 0 || clean == UnnamedRgbToy(port))) {
+ clean = "";
+ rgb = true;
+ }
+ if (configured && !rgb) {
+ return (false, clean.Length == 0 ? "The configuration's rows have an RGB toy here, so it stays one: give it a name."
+ : "The configuration's rows have an RGB toy here, so it stays one: name it with RGB on.", null, null, null);
+ }
+ // the toys of one output the configuration has on the next two, which the RGB toy takes
+ var taken = new List();
+ if (rgb && !configured) {
+ if (number + 2 > ports.Outputs) {
+ return (false, $"An RGB toy takes three outputs in a row, and the board ends at {ports.Outputs}.", null, null, null);
+ }
+ for (var i = 1; i <= 2; i++) {
+ var other = wiring.PortOn(device, number + i);
+ if (other != port + i) {
+ var has = other == DofOutputWiring.Nothing ? "drives nothing" : $"has what the configuration puts on output {other}";
+ return (false, $"An RGB toy here takes the outputs after it as they are, and output {number + i} {has}. Turn on Rewire to move the toy here.", null, null, null);
+ }
+ var toy = ports.ToyOf(port + i);
+ if (ports.At(port + i).Channel != PluginOutputChannel.None && toy != port) {
+ return (false, $"That would split {Toy(ports.At(toy).Name)}: its red, green and blue stay together.", null, null, null);
+ }
+ if (toy == port + i && ports.At(toy).Name.Length > 0) {
+ taken.Add(ports.At(toy).Name);
+ }
+ }
+ }
+ if (clean == current && isRgb == rgb) {
+ return (true, clean.Length == 0 ? $"Output {number} has no toy already." : $"Output {number} is {clean} already.", null, null, null);
+ }
+ // what the configuration says is nothing to keep
+ var next = clean == header && rgb == configured ? described.Without(device, port) : described.With(device, port, clean, rgb);
+ if (rgb) {
+ next = next.Without(device, port + 1).Without(device, port + 2);
+ }
+ var message = clean.Length == 0 && rgb ? $"Outputs {number} to {number + 2} are the configuration's RGB toy again."
+ : clean.Length == 0 ? $"Output {number} has no toy now."
+ : rgb ? $"Outputs {number} to {number + 2} are {clean} now, an RGB toy{(taken.Count == 0 ? "" : $", in place of {string.Join(" and ", taken)}")}."
+ : $"Output {number} is {clean} now.";
+ return (true, $"{message} What drives and fires {(rgb ? "them" : "it")} stays as it is.", null, null, next);
+ }
+
// Output `number` drives nothing: the toy on it is on no output then, all three outputs of an RGB toy.
private static (bool, string, DofOutputWiring, DofToyNames) Empty(DevicePorts ports, DofOutputWiring wiring, DofToyNames names, int device, int number)
{
@@ -1235,7 +1640,7 @@ private static (bool, string, DofOutputWiring, DofToyNames) Give(DevicePorts por
}
var split = Split(ports, wiring, device, toy, new[] { (number, moving.Count) });
if (split != null) {
- return (false, $"That would split {Toy(split)}: its red, green and blue move together. Swap them instead.", null, null);
+ return (false, $"That would split {Toy(split)}: its red, green and blue move together. Give it other outputs first, or Nothing.", null, null);
}
// a toy on no output, off the board or apart has no place to give back: what it displaces is on no output then,
// rather than off the board or apart in its turn
@@ -1244,8 +1649,10 @@ private static (bool, string, DofOutputWiring, DofToyNames) Give(DevicePorts por
return (true, where + Displaced(ports, wiring, next, device, number, moving), next, null);
}
- // Output `number` drives a new toy of the name the user typed; what it drove then drives nothing.
- private static (bool, string, DofOutputWiring, DofToyNames) Add(DevicePorts ports, DofOutputWiring wiring, DofToyNames names, int device, int number, string name)
+ // Output `number` drives a new toy of the name the user typed, and the next two an RGB one's green and blue; what they drove
+ // then drives nothing.
+ private static (bool, string, DofOutputWiring, DofToyNames) Add(DevicePorts ports, DofOutputWiring wiring, DofToyNames names, int device, int number, string name,
+ bool rgb)
{
var clean = DofToyNames.Clean(name);
if (clean.Length == 0) {
@@ -1255,18 +1662,73 @@ private static (bool, string, DofOutputWiring, DofToyNames) Add(DevicePorts port
if (same.Port > 0) {
return (false, $"This board has {same.Name} already: choose it from the list.", null, null);
}
- var split = Split(ports, wiring, device, null, new[] { (number, 1) });
+ var count = rgb ? 3 : 1;
+ if (number + count - 1 > ports.Outputs) {
+ return (false, $"An RGB toy takes three outputs in a row: output {number} is too close to the end of the board.", null, null);
+ }
+ var split = Split(ports, wiring, device, null, new[] { (number, count) });
if (split != null) {
return (false, $"That would split {Toy(split)}: its red, green and blue move together. Choose Nothing for it first.", null, null);
}
- var port = ports.FreePort(wiring);
+ // three ports for any toy, so one of one output can become an RGB toy where it is
+ var port = ports.FreePorts(wiring, 3);
if (port == 0) {
return (false, "This board has no port left for a new toy.", null, null);
}
- var next = wiring.Assign(device, new[] { port }, number, true);
- var withName = names.With(device, port, clean);
- var message = $"Output {number} drives {clean} now; no configuration drives it yet.";
- return (true, message + Displaced(ports, wiring, next, device, number, new[] { port }), next, withName);
+ var moving = Enumerable.Range(port, count).ToArray();
+ var next = wiring.Assign(device, moving, number, true);
+ var withName = names.With(device, port, clean, rgb);
+ var message = rgb ? $"Outputs {number} to {number + 2} drive {clean} now, an RGB toy; no configuration drives it yet."
+ : $"Output {number} drives {clean} now; no configuration drives it yet.";
+ return (true, message + Displaced(ports, wiring, next, device, number, moving), next, withName);
+ }
+
+ // The toy the user added on output `number` made an RGB toy on its output and the next two, or a toy of its output alone;
+ // the outputs it no longer takes drive nothing.
+ private static (bool, string, DofOutputWiring, DofToyNames) Shape(DevicePorts ports, DofOutputWiring wiring, DofToyNames names, int device, int number,
+ bool rgb)
+ {
+ var port = wiring.PortOn(device, number);
+ var start = port == DofOutputWiring.Nothing ? 0 : ports.ToyOf(port);
+ if (start == 0) {
+ return (false, $"Output {number} drives no toy.", null, null);
+ }
+ var name = ports.At(start).Name;
+ var isRgb = ports.At(start).Channel == PluginOutputChannel.Red;
+ if (!ports.Added(start)) {
+ return (false, $"The configuration makes {Toy(name)} {(isRgb ? "an RGB toy" : "a toy of one output")}.", null, null);
+ }
+ if (isRgb == rgb) {
+ return (true, $"{Toy(name)} is {(rgb ? "an RGB toy" : "a toy of one output")} already.", null, null);
+ }
+ var first = wiring.OutputOf(device, start);
+ if (!rgb) {
+ // its green and blue drive nothing then
+ var single = wiring.Remove(device, new[] { start + 1, start + 2 });
+ return (true, $"{Toy(name)} is a toy of output {first} alone now; outputs {first + 1} and {first + 2} drive nothing.", single,
+ names.With(device, start, name, false));
+ }
+ if (first < 1 || first + 2 > ports.Outputs) {
+ return (false, $"An RGB toy takes three outputs in a row, and the board ends at output {ports.Outputs}.", null, null);
+ }
+ for (var output = first + 1; output <= first + 2; output++) {
+ var other = wiring.PortOn(device, output);
+ var toy = other == DofOutputWiring.Nothing ? 0 : ports.ToyOf(other);
+ if (toy != 0) {
+ return (false, $"Output {output} drives {Toy(ports.At(toy).Name)}: choose Nothing for it first.", null, null);
+ }
+ }
+ // its green and blue are the two ports after its own, which toys added since keep free (see FreePorts)
+ if (start + 2 > DofOutputWiring.MaxOutput || names.StartOf(device, start + 1) != 0 || names.StartOf(device, start + 2) != 0) {
+ return (false, $"{Toy(name)} can't become an RGB toy where it is: add it again as an RGB toy.", null, null);
+ }
+ // outputs that drove a port no toy is named on, which a game may use, drive the toy then: said, as when it is added
+ var taken = Enumerable.Range(first + 1, 2).Where(o => wiring.PortOn(device, o) is var p && p != DofOutputWiring.Nothing && p <= ports.PortCount).ToList();
+ var next = wiring.Assign(device, new[] { start, start + 1, start + 2 }, first, true);
+ var said = taken.Count == 0 ? ""
+ : taken.Count == 1 ? $" Port {wiring.PortOn(device, taken[0])}, which output {taken[0]} drove, drives nothing now."
+ : $" Ports {wiring.PortOn(device, taken[0])} and {wiring.PortOn(device, taken[1])}, which outputs {taken[0]} and {taken[1]} drove, drive nothing now.";
+ return (true, $"Outputs {first} to {first + 2} drive {Toy(name)} now, an RGB toy.{said}", next, names.With(device, start, name, true));
}
// Where the toys the outputs from `number` on had went: to the outputs the moved ones left, or to none.
@@ -1292,7 +1754,7 @@ private static string Displaced(DevicePorts ports, DofOutputWiring before, DofOu
}
/// The toys the user added, of a folder, or null when their file can't be read, after a few tries.
- private static DofToyNames ReadNames(string root)
+ internal static DofToyNames ReadNames(string root)
{
for (var attempt = 1; ; attempt++) {
try {
@@ -1307,6 +1769,22 @@ private static DofToyNames ReadNames(string root)
}
}
+ /// What the user says the ports drive, of a folder, or null when its file can't be read, after a few tries.
+ internal static DofPortNames ReadPortNames(string root)
+ {
+ for (var attempt = 1; ; attempt++) {
+ try {
+ return DofPortNames.Load(root);
+ } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) {
+ if (attempt == 3) {
+ Logger.Warn(e, "[DOF] The names you gave the outputs could not be read.");
+ return null;
+ }
+ Thread.Sleep(20);
+ }
+ }
+ }
+
#endregion
#region Actions
@@ -1329,17 +1807,15 @@ private PluginActionResult RunActionUnlogged(string action, PluginChoiceRequest
{
try {
switch (action) {
- case "import-zip": return Import(request.Settings.String("ImportZip").Trim(), DofImportMode.Merge, request.Settings, "Choose the zip or file to import.");
- case "import-folder": return Import(request.Settings.String("ImportFolder").Trim(), DofImportMode.Replace, request.Settings, "Choose the folder to import.");
+ case "import-zip": return Import(request.Settings.String("ImportZip").Trim(), DofImportMode.Merge, request, "Choose the zip or file to import.");
+ case "import-folder": return Import(request.Settings.String("ImportFolder").Trim(), DofImportMode.Replace, request, "Choose the folder to import.");
+ case "import-config-tool": return ImportFromConfigTool(request, cancellation);
case "show-import": return ShowImport();
- case "rollback":
- return Store.Rollback()
- ? new PluginActionResult(true, "The previous configuration is active again. It applies from the next game.")
- : new PluginActionResult(false, "There is no previous configuration.");
+ case "clear-config": return ClearConfiguration(request);
case "apply-serial-overrides": return ApplySerialOverrides(request.Settings);
case "detect": return Detect();
case "all-off": return AllOff(leases, cancellation);
- case "reset-wiring": return ResetWiring();
+ case "reset-wiring": return ResetWiring(request);
default: return new PluginActionResult(false, "Unknown DOF action.");
}
} catch (DofException e) {
@@ -1348,19 +1824,134 @@ private PluginActionResult RunActionUnlogged(string action, PluginChoiceRequest
}
}
- private PluginActionResult Import(string source, DofImportMode mode, PluginSettingsSnapshot settings, string missing)
+ private PluginActionResult Import(string source, DofImportMode mode, PluginChoiceRequest request, string missing)
{
if (source.Length == 0) {
return new PluginActionResult(false, missing);
}
- // the ports go into the import itself, so undoing it restores the configuration before it
- var overrides = SerialOverrides(settings);
- var report = new DofImporter(Store).Import(source, mode, overrides);
+ // not asked about what isn't there
+ if (!File.Exists(source) && !Directory.Exists(source)) {
+ return new PluginActionResult(false, "Not found: " + source);
+ }
+ // one file other than a zip is that file alone, which may well be the cabinet file
+ var single = File.Exists(source) && !source.EndsWith(".zip", StringComparison.OrdinalIgnoreCase);
+ // a format of its own, braces and all
+ var file = Path.GetFileName(source).Replace("{", "{{").Replace("}", "}}");
+ // one folder from the question to the import, even if the host creates the plugin meanwhile
+ var store = Store;
+ var replacing = AskBeforeReplacing(store, request, mode == DofImportMode.Replace
+ ? "Importing the folder replaces the whole configuration imported {0}, your cabinet file and LED strips included."
+ : single && source.EndsWith(".ini", StringComparison.OrdinalIgnoreCase)
+ ? $"Importing {file} replaces all the ini files of the configuration imported {{0}}: a device it isn't the file of loses its own. Files it doesn't have stay, such as your cabinet file with its LED strips."
+ : single
+ ? $"Importing replaces {file} of the configuration imported {{0}}. Its other files stay."
+ : "Importing replaces the ini files of the configuration imported {0}, and the other files the import has. Files it doesn't have stay, such as your cabinet file with its LED strips.");
+ if (replacing != null) {
+ return replacing.Value;
+ }
+ // the ports go into the import itself
+ var overrides = SerialOverrides(request.Settings);
+ var report = new DofImporter(store).Import(source, mode, overrides);
Logger.Info("[DOF] Import of " + source + ":\n" + report);
+ return Imported(report, overrides, "Imported.");
+ }
+
+ /// Downloads the cabinet's configuration from the DOF Config Tool with its API key, and imports it as a zip of it.
+ private PluginActionResult ImportFromConfigTool(PluginChoiceRequest request, CancellationToken cancellation)
+ {
+ var settings = request.Settings;
+ var key = settings.String("ConfigToolKey").Trim();
+ var problem = DofConfigToolClient.CheckKey(key);
+ if (problem != null) {
+ return new PluginActionResult(false, problem);
+ }
+ // asked before the download: nothing is fetched for an import the user doesn't want
+ var store = Store;
+ var replacing = AskBeforeReplacing(store, request,
+ "The download replaces the ini files of the configuration imported {0}. Files it doesn't have stay, such as your cabinet file with its LED strips.");
+ if (replacing != null) {
+ return replacing.Value;
+ }
+ var agreed = Identity(store, store.Active);
+ byte[] zip;
+ using (var client = new DofConfigToolClient("VisualPinballEngine-DOF/" + Descriptor.Version, ConfigToolHandler?.Invoke())) {
+ // on a worker already (RunActionAsync)
+ zip = client.DownloadAsync(key, cancellation).GetAwaiter().GetResult();
+ }
+ // into what the user agreed to while the download ran: not another folder, nor a configuration imported meanwhile
+ if (!ReferenceEquals(Store, store) || Identity(store, store.Active) != agreed) {
+ return ChangedMeanwhile;
+ }
+ // the ports go into the import itself, as for a zip
+ var overrides = SerialOverrides(settings);
+ var report = new DofImporter(store).ImportDownload(zip, DofConfigToolClient.Origin, overrides, cancellation);
+ Logger.Info($"[DOF] Import of {zip.Length} bytes from {DofConfigToolClient.Origin}:\n{report}");
+ return Imported(report, overrides, "Downloaded and imported.");
+ }
+
+ ///
+ /// The question an import asks when there is a configuration it replaces, and the user hasn't agreed yet; null when it
+ /// can go ahead. There is no going back: the configuration it replaces is deleted.
+ ///
+ /// The action's request, confirmed or not.
+ /// What the import replaces, with {0} for when the configuration was imported.
+ private PluginActionResult? AskBeforeReplacing(DofConfigStore store, PluginChoiceRequest request, string what)
+ {
+ var active = store.Active;
+ if (request.Confirmed) {
+ // the one the user agreed to replace, in the folder it was in
+ var asked = Interlocked.Exchange(ref _replaceAsked, null);
+ return asked == null || asked == Identity(store, active) ? (PluginActionResult?)null : ChangedMeanwhile;
+ }
+ if (active == null) {
+ return null;
+ }
+ Volatile.Write(ref _replaceAsked, Identity(store, active));
+ return PluginActionResult.Ask(new PluginConfirmation("Replace your DOF configuration?",
+ string.Format(CultureInfo.InvariantCulture, what, When(active)) + " This can't be undone.", "Replace"));
+ }
+
+ // The folder and configuration the last Replace question was about: the user agreed to replace that one, not one in
+ // another folder (Create can move the store) or one imported meanwhile.
+ private string _replaceAsked;
+
+ // what an import goes into: the store's folder and its configuration then, none for an empty folder
+ private static string Identity(DofConfigStore store, DofRevision active) => store.Root + "\n" + active?.Id;
+
+ private static readonly PluginActionResult ChangedMeanwhile =
+ new PluginActionResult(false, "The configuration changed meanwhile, so nothing was imported. Look at it again, then import.");
+
+ // The configuration the last Clear question was about: the user agreed to clear that one, not one imported meanwhile, such
+ // as by another player using the same folder.
+ private string _clearAsked;
+
+ private PluginActionResult ClearConfiguration(PluginChoiceRequest request)
+ {
+ var active = Store.Active;
+ if (active == null) {
+ return new PluginActionResult(false, "No DOF configuration is imported.");
+ }
+ if (!request.Confirmed) {
+ Volatile.Write(ref _clearAsked, active.Id);
+ return PluginActionResult.Ask(new PluginConfirmation("Clear your DOF configuration?",
+ $"This removes the configuration imported {When(active)}, your cabinet file and LED strips included. DOF drives no toys from the next game until you import a configuration again. This can't be undone.",
+ "Clear"));
+ }
+ var asked = Interlocked.Exchange(ref _clearAsked, null);
+ // the one the user agreed to clear, not one an import activated since
+ if (asked != null && asked != active.Id || !Store.Clear(active.Id)) {
+ return new PluginActionResult(false, "The configuration changed meanwhile. Look at it again, then clear it.");
+ }
+ Logger.Info("[DOF] Configuration " + active.Id + " cleared.");
+ return new PluginActionResult(true, "Cleared. From the next game DOF drives no toys until you import a configuration.");
+ }
+
+ private static PluginActionResult Imported(DofImportReport report, IReadOnlyDictionary overrides, string done)
+ {
if (!report.Accepted) {
return new PluginActionResult(false, "Not imported: " + (report.RejectionReason ?? "the configuration could not be published."));
}
- var message = new StringBuilder("Imported. It applies from the next game.");
+ var message = new StringBuilder(done + " It applies from the next game.");
if (overrides.Count > 0) {
message.Append(" Your serial ports were applied where the cabinet has those controllers.");
}
@@ -1395,7 +1986,7 @@ private PluginActionResult ShowImport()
}
var report = revision.ReadReport();
text.Append(string.IsNullOrWhiteSpace(report) ? $"Revision {revision.Id} has no import report." : report.Trim());
- return new PluginActionResult(true, text.ToString());
+ return PluginActionResult.WithDetails(true, "", new PluginDetails("The imported configuration", text.ToString()));
}
private PluginActionResult ApplySerialOverrides(PluginSettingsSnapshot settings)
@@ -1441,6 +2032,56 @@ private PluginActionResult Detect()
return new PluginActionResult(true, detected.Count == 0 ? "No board DOF knows is connected." : detected.Count == 1 ? "Found 1 board." : $"Found {detected.Count} boards.");
}
+ public Task TestOutputColorAsync(string provider, string output, byte red, byte green, byte blue, PluginChoiceRequest request,
+ CancellationToken cancellation)
+ {
+ var leases = LeasesFor(request);
+ return Task.Run(() => {
+ if (provider != "outputs" && provider != GameOutputsProvider) {
+ return new PluginActionResult(false, "Unknown DOF outputs.");
+ }
+ try {
+ var result = LightToy(output, red, green, blue, leases, cancellation);
+ Logger.Info($"[DOF] Test of {output} in #{red:X2}{green:X2}{blue:X2}: {result.Message}");
+ return result;
+ } catch (DofException e) {
+ Logger.Warn(e, $"[DOF] Test of {output} failed: {e.Message}");
+ return new PluginActionResult(false, e.Message);
+ }
+ }, cancellation);
+ }
+
+ // Lights the RGB toy on a port, by any of its three, in a colour.
+ private PluginActionResult LightToy(string id, byte red, byte green, byte blue, PluginOutputLeases leases, CancellationToken cancellation)
+ {
+ if (!DofPortTest.TryParse(id, out var device, out var port)) {
+ return new PluginActionResult(false, "Unknown output " + id + ".");
+ }
+ if (port < 0) {
+ return new PluginActionResult(false, $"Nothing drives output {-port} now: give it a toy to test it.");
+ }
+ var store = Store;
+ DofOutputWiring wiring;
+ IReadOnlyList toy;
+ using (var lease = store.AcquireForReading()) {
+ var catalog = lease?.Revision != null ? CatalogOf(lease.Revision) : null;
+ var entry = catalog?.Devices.FirstOrDefault(d => d.Number == device);
+ if (entry == null) {
+ return new PluginActionResult(false, "The configuration has no device " + device + ".");
+ }
+ wiring = ReadWiring(store.Root) ?? DofOutputWiring.None;
+ var ports = new DevicePorts(entry, Reach(catalog, DetectedBoards(catalog), device), wiring, ReadNames(store.Root) ?? DofToyNames.None,
+ ReadPortNames(store.Root) ?? DofPortNames.None);
+ toy = ports.PortsOf(port);
+ }
+ if (toy.Count != 3) {
+ return new PluginActionResult(false, "The output drives no RGB toy, so it has no colour to test.");
+ }
+ var values = new[] { (toy[0], (int)red), (toy[1], (int)green), (toy[2], (int)blue) };
+ var (success, message) = DofPortTest.Light(store, leases, Id, wiring, device, values, PulseDuration, ConfirmTimeout, TestNativeFactory, cancellation);
+ return new PluginActionResult(success, message);
+ }
+
private PluginActionResult PulsePort(string id, PluginOutputLeases leases, CancellationToken cancellation)
{
if (!DofPortTest.TryParse(id, out var device, out var port)) {
@@ -1461,32 +2102,285 @@ private PluginActionResult AllOff(PluginOutputLeases leases, CancellationToken c
return new PluginActionResult(success, message);
}
- private PluginActionResult ResetWiring()
+ ///
+ /// What a row of the configuration sets on a toy, as written or with its variables replaced; null where its columns say more
+ /// than one setting. A strip the catalog made a toy of three outputs keeps a setting on its first column, with nothing on the
+ /// other two, as the configuration may have it for a toy of one output there.
+ ///
+ ///
+ /// Whether a trigger, fitted to the toy, is what the configuration sets on it, as written or with its variables replaced, and
+ /// fitted the same way: a setting on an RGB toy's first column alone is shown without the colour fitting adds.
+ ///
+ internal static bool SameAsConfigured(string fitted, DofIniRow row, int port, int width)
+ {
+ bool Same(string configured) => configured != null && (string.Equals(fitted, configured, StringComparison.Ordinal)
+ || width == 3 && string.Equals(fitted, DofIniRow.Fit(configured, true, out _), StringComparison.Ordinal));
+ return Same(SettingOfToy(row, port, width, false)) || Same(SettingOfToy(row, port, width, true));
+ }
+
+ internal static string SettingOfToy(DofIniRow row, int port, int width, bool resolved)
+ {
+ string Of(int p, int w) => resolved ? row.ResolvedSettingOf(p, w) : row.SettingOf(p, w);
+ var setting = Of(port, width);
+ if (setting != null || width != 3) {
+ return setting;
+ }
+ return Of(port + 1, 1) == "" && Of(port + 2, 1) == "" ? Of(port, 1) : null;
+ }
+
+ private PluginActionResult ResetWiring(PluginChoiceRequest request)
{
var root = Store.Root;
lock (WiringFileLock) {
+ // asked about what is reset, as read under the lock the reset holds
var wiring = ReadWiring(root);
- if (wiring == null) {
+ var described = ReadPortNames(root);
+ if (wiring == null || described == null) {
return new PluginActionResult(false, "The output wiring could not be read, so nothing was changed. Try again.");
}
- if (wiring.IsEmpty) {
- return new PluginActionResult(false, "No output is rearranged.");
+ if (wiring.IsEmpty && described.IsEmpty) {
+ return new PluginActionResult(false, "No output is moved or named.");
+ }
+ if (!request.Confirmed) {
+ return PluginActionResult.Ask(new PluginConfirmation("Reset the outputs?",
+ "Every output gets what the configuration puts on it again: the toys you moved go back, and the names you gave outputs go, on every board. This can't be undone.", "Reset"));
}
+ var wiringReset = false;
try {
DofOutputWiring.None.Save(root);
+ wiringReset = true;
+ DofPortNames.None.Save(root);
} catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) {
Logger.Warn(e, "[DOF] Removing the output wiring failed.");
- return new PluginActionResult(false, "Not undone: " + e.Message);
+ // all or nothing: the wiring back, should the names stay
+ if (wiringReset) {
+ try {
+ wiring.Save(root);
+ } catch (Exception again) when (again is IOException || again is UnauthorizedAccessException) {
+ Logger.Warn(again, "[DOF] Putting the output wiring back failed.");
+ }
+ }
+ return new PluginActionResult(false, "Not reset: " + e.Message);
} finally {
ForgetWiring();
}
}
- Logger.Info("[DOF] The output wiring was reset.");
+ Logger.Info("[DOF] The output wiring and names were reset.");
return new PluginActionResult(true, "Every output has what the configuration puts on it again. " + WhenItApplies());
}
#endregion
+ #region Snapshots
+
+ // the files are those of the folder it names: the store takes the host's folder once the plugin is created
+ private const string SnapshotHeader = "dof-outputs 2";
+
+ private static string SnapshotRoot(string root) => Convert.ToBase64String(Encoding.UTF8.GetBytes(root));
+
+ ///
+ /// The files a field's panel changes: the wiring, the toys the user added and the names given for the outputs, what fires them for the
+ /// game's; wiring before toys, so a toy put back on an output never goes without its name for long.
+ ///
+ private static string[] SnapshotFiles(string provider) => provider == "outputs" ? new[] { DofOutputWiring.FileName, DofToyNames.FileName, DofPortNames.FileName }
+ : provider == GameOutputsProvider ? new[] { DofGameTriggers.FileName }
+ : null;
+
+ public Task SnapshotOutputsAsync(string provider, PluginChoiceRequest request, CancellationToken cancellation)
+ => Task.Run(() => SnapshotOutputs(provider, cancellation), cancellation);
+
+ public Task RestoreOutputsAsync(string provider, string snapshot, PluginChoiceRequest request, CancellationToken cancellation)
+ => Task.Run(() => RestoreOutputs(provider, snapshot, request, cancellation), cancellation);
+
+ /// The field's files as they are, each as its bytes or as missing, under the provider's name.
+ private string SnapshotOutputs(string provider, CancellationToken cancellation)
+ {
+ cancellation.ThrowIfCancellationRequested();
+ var files = SnapshotFiles(provider) ?? throw new ArgumentException("Unknown DOF outputs.", nameof(provider));
+ var root = Store.Root;
+ var text = new StringBuilder(SnapshotHeader).Append('\n').Append(provider).Append('\n').Append(SnapshotRoot(root)).Append('\n');
+ lock (WiringFileLock) {
+ foreach (var file in files) {
+ var bytes = ReadSnapshotFile(Path.Combine(root, file));
+ text.Append(file).Append('\t').Append(bytes == null ? "-" : Convert.ToBase64String(bytes)).Append('\n');
+ }
+ }
+ return text.ToString();
+ }
+
+ /// Puts the field's files back as the snapshot has them: the ones that changed, all of them or none.
+ private PluginActionResult RestoreOutputs(string provider, string snapshot, PluginChoiceRequest request, CancellationToken cancellation)
+ {
+ cancellation.ThrowIfCancellationRequested();
+ var files = SnapshotFiles(provider);
+ if (files == null) {
+ return new PluginActionResult(false, "Unknown DOF outputs.");
+ }
+ var root = Store.Root;
+ var kept = ParseSnapshot(provider, snapshot, files, root, out var elsewhere);
+ if (elsewhere) {
+ return new PluginActionResult(false, "The outputs were in another folder then, so nothing was put back.");
+ }
+ if (kept == null) {
+ return new PluginActionResult(false, "What the outputs were is not known, so nothing was put back.");
+ }
+ // A game's triggers share their file with the other games': only the game's rows go back, and what was saved for
+ // another game meanwhile stays.
+ IReadOnlyList rows = null;
+ if (provider == GameOutputsProvider) {
+ using var lease = Store.AcquireForReading();
+ rows = lease?.Revision == null ? Array.Empty()
+ : GameRows(request, CatalogOf(lease.Revision)).Rows.Select(row => row.Rom).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
+ }
+ lock (WiringFileLock) {
+ cancellation.ThrowIfCancellationRequested();
+ // what changed, each file written next to its place first: a folder that can't take them changes nothing
+ var changed = new List<(string Path, byte[] Now, byte[] Before)>();
+ try {
+ if (rows != null) {
+ var then = DofGameTriggers.Parse(kept[DofGameTriggers.FileName] == null ? null : Encoding.UTF8.GetString(kept[DofGameTriggers.FileName]));
+ var merged = DofGameTriggers.Load(root).WithRowsOf(then, rows);
+ kept[DofGameTriggers.FileName] = merged.IsEmpty ? null : new UTF8Encoding(false).GetBytes(merged.Text);
+ }
+ foreach (var file in files) {
+ var path = Path.Combine(root, file);
+ var now = ReadSnapshotFile(path);
+ var before = kept[file];
+ if (now == null ? before == null : before != null && now.SequenceEqual(before)) {
+ continue;
+ }
+ changed.Add((path, now, before));
+ if (before != null) {
+ Directory.CreateDirectory(root);
+ File.WriteAllBytes(path + ".tmp", before);
+ }
+ }
+ } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) {
+ Logger.Warn(e, "[DOF] Putting the outputs back failed.");
+ foreach (var (path, _, _) in changed) {
+ TryDelete(path + ".tmp");
+ }
+ return new PluginActionResult(false, "Not put back: " + e.Message);
+ }
+ if (changed.Count == 0) {
+ return new PluginActionResult(true, "Nothing was changed.");
+ }
+ // a page left meanwhile changes nothing
+ if (cancellation.IsCancellationRequested) {
+ foreach (var (path, _, _) in changed) {
+ TryDelete(path + ".tmp");
+ }
+ cancellation.ThrowIfCancellationRequested();
+ }
+ var done = new List<(string Path, byte[] Now)>();
+ try {
+ foreach (var (path, now, before) in changed) {
+ PutSnapshotFile(path, before);
+ done.Add((path, now));
+ }
+ } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) {
+ Logger.Warn(e, "[DOF] Putting the outputs back failed.");
+ // what was put back already goes back to what it was, so nothing is half undone
+ foreach (var (path, now) in done.AsEnumerable().Reverse()) {
+ try {
+ if (now != null) {
+ File.WriteAllBytes(path + ".tmp", now);
+ }
+ PutSnapshotFile(path, now);
+ } catch (Exception again) when (again is IOException || again is UnauthorizedAccessException) {
+ Logger.Warn(again, $"[DOF] Undoing the putting back of {Path.GetFileName(path)} failed.");
+ }
+ }
+ foreach (var (path, _, _) in changed) {
+ TryDelete(path + ".tmp");
+ }
+ return new PluginActionResult(false, "Not put back: " + e.Message);
+ } finally {
+ ForgetWiring();
+ }
+ }
+ Logger.Info($"[DOF] The {(provider == "outputs" ? "outputs" : "game triggers")} are as they were again.");
+ return new PluginActionResult(true, provider == "outputs"
+ ? "The outputs drive what they did before. " + WhenItApplies()
+ : "The toys fire as they did before." + (DofOwnership.InUse ? " A running game keeps what it started with: it applies from the next game." : ""));
+ }
+
+ ///
+ /// The files of a snapshot of the provider, by name, null for a missing one; or null when it isn't one, or is one of another folder
+ /// than the root, which says.
+ ///
+ private static Dictionary ParseSnapshot(string provider, string snapshot, string[] files, string root, out bool elsewhere)
+ {
+ elsewhere = false;
+ var lines = (snapshot ?? "").Split('\n');
+ if (lines.Length != files.Length + 4 || lines[0] != SnapshotHeader || lines[1] != provider || lines[lines.Length - 1].Length != 0) {
+ return null;
+ }
+ if (lines[2] != SnapshotRoot(root)) {
+ elsewhere = true;
+ return null;
+ }
+ var kept = new Dictionary();
+ for (var i = 0; i < files.Length; i++) {
+ var parts = lines[i + 3].Split('\t');
+ if (parts.Length != 2 || parts[0] != files[i]) {
+ return null;
+ }
+ if (parts[1] == "-") {
+ kept[files[i]] = null;
+ continue;
+ }
+ try {
+ kept[files[i]] = Convert.FromBase64String(parts[1]);
+ } catch (FormatException) {
+ return null;
+ }
+ }
+ return kept;
+ }
+
+ // A file's bytes, or null when there is none; a few tries, as for the wiring.
+ private static byte[] ReadSnapshotFile(string path)
+ {
+ for (var attempt = 1; ; attempt++) {
+ try {
+ return File.Exists(path) ? File.ReadAllBytes(path) : null;
+ } catch (IOException) when (attempt < 3) {
+ Thread.Sleep(20);
+ }
+ }
+ }
+
+ // Puts a file written next to its place in it in one step, as the files save themselves, or deletes it for null.
+ private static void PutSnapshotFile(string path, byte[] bytes)
+ {
+ if (bytes == null) {
+ if (File.Exists(path)) {
+ File.Delete(path);
+ }
+ return;
+ }
+ var temp = path + ".tmp";
+ if (File.Exists(path)) {
+ File.Replace(temp, path, null);
+ } else {
+ File.Move(temp, path);
+ }
+ }
+
+ private static void TryDelete(string path)
+ {
+ try {
+ if (File.Exists(path)) {
+ File.Delete(path);
+ }
+ } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) {
+ Logger.Warn(e, $"[DOF] {Path.GetFileName(path)} could not be removed.");
+ }
+ }
+
+ #endregion
+
#region Validation and defaults
public IReadOnlyList Validate(PluginChoiceRequest request)
diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofTriggerSyntax.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofTriggerSyntax.cs
new file mode 100644
index 0000000..ca2aa44
--- /dev/null
+++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofTriggerSyntax.cs
@@ -0,0 +1,431 @@
+// Visual Pinball Engine
+// Copyright (C) 2026 freezy and VPE Team
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using VisualPinball.Plugins;
+
+namespace VisualPinball.Engine.DOF.Player
+{
+ ///
+ /// Reads a DOF setting, such as S12 Red M50 MAX50 AH80 ADU AS300 L1/W57 Red AT70 AH30 ADD, into
+ /// s and writes them back, as libdof reads it (TableConfigSetting::ParseSettingData): its
+ /// parts are separated by /, each a trigger and what follows it. What a rule has no field for is kept as written.
+ ///
+ internal static class DofTriggerSyntax
+ {
+ /// Reads a setting into its rules; a part libdof can't read is left out and said.
+ internal static PluginTriggerParse Parse(string setting)
+ {
+ var rules = new List();
+ var problems = new List();
+ foreach (var part in Split(Clean(setting), '/').Select(p => p.Trim()).Where(p => p.Length > 0)) {
+ var rule = ParsePart(part, out var problem);
+ if (rule != null) {
+ rules.Add(rule);
+ } else if (problem != null) {
+ problems.Add(problem);
+ }
+ }
+ return new PluginTriggerParse(rules, problems.Count == 0 ? null : string.Join(" ", problems));
+ }
+
+ /// Writes rules as a setting: those that say what they said when read, as they were written.
+ internal static string Format(IReadOnlyList rules)
+ => string.Join("/", (rules ?? Array.Empty()).Select(Format).Where(part => part.Length > 0));
+
+ /// One rule as a part of a setting.
+ internal static string Format(PluginTriggerRule rule)
+ {
+ if (rule == null) {
+ return "";
+ }
+ if (rule.Original.Length > 0 && ParsePart(rule.Original, out _) is { } read && read.SameAs(rule)) {
+ return rule.Original;
+ }
+ var trigger = rule.Condition.Length > 0 ? rule.Condition
+ : rule.Always ? "ON"
+ : string.Join("|", rule.Sources.Select(s => s.Trim()).Where(s => s.Length > 0));
+ if (trigger.Length == 0) {
+ return "";
+ }
+ var parts = new List { trigger };
+ if (rule.Color.Length > 0) {
+ parts.Add(rule.Color);
+ }
+ switch (rule.Blink) {
+ case PluginTriggerBlink.None:
+ if (rule.Duration > 0) {
+ parts.Add(Number(rule.Duration));
+ }
+ break;
+ case PluginTriggerBlink.WhileOn:
+ // a duration before Blink keeps its blink at a second
+ if (rule.Duration > 0) {
+ parts.Add(Number(rule.Duration));
+ parts.Add("Blink");
+ } else {
+ parts.Add("Blink");
+ if (rule.BlinkInterval != 1000) {
+ parts.Add(Number(System.Math.Max(1, rule.BlinkInterval)));
+ }
+ }
+ break;
+ case PluginTriggerBlink.Count:
+ parts.Add(Number(System.Math.Max(1, rule.Duration)));
+ parts.Add(Number(System.Math.Max(1, rule.BlinkCount)));
+ break;
+ }
+ if (rule.Blink != PluginTriggerBlink.None && rule.BlinkOn != 50) {
+ parts.Add("BPW" + Number(System.Math.Min(99, System.Math.Max(1, rule.BlinkOn))));
+ }
+ if (rule.FadeIn > 0 && rule.FadeIn == rule.FadeOut) {
+ parts.Add("F" + Number(rule.FadeIn));
+ } else {
+ if (rule.FadeIn > 0) {
+ parts.Add("FU" + Number(rule.FadeIn));
+ }
+ if (rule.FadeOut > 0) {
+ parts.Add("FD" + Number(rule.FadeOut));
+ }
+ }
+ if (rule.Delay > 0) {
+ parts.Add("W" + Number(rule.Delay));
+ }
+ if (rule.MinDuration > 0) {
+ parts.Add("M" + Number(rule.MinDuration));
+ }
+ if (rule.MaxDuration > 0) {
+ parts.Add("MAX" + Number(rule.MaxDuration));
+ }
+ if (rule.Extend > 0) {
+ parts.Add("E" + Number(rule.Extend));
+ }
+ if (rule.Strength != 255) {
+ parts.Add(Strength(rule.Strength));
+ }
+ if (rule.Invert) {
+ parts.Add("INVERT");
+ }
+ if (rule.AreaLeft != 0) {
+ parts.Add("AL" + Number(rule.AreaLeft));
+ }
+ if (rule.AreaTop != 0) {
+ parts.Add("AT" + Number(rule.AreaTop));
+ }
+ if (rule.AreaWidth != 100) {
+ parts.Add("AW" + Number(rule.AreaWidth));
+ }
+ if (rule.AreaHeight != 100) {
+ parts.Add("AH" + Number(rule.AreaHeight));
+ }
+ if (rule.Move != PluginTriggerMove.None) {
+ parts.Add("AD" + rule.Move.ToString().Substring(0, 1));
+ if (rule.MoveSpeed > 10000) {
+ // faster than AS takes: as the milliseconds it crosses the area in
+ parts.Add("ASS" + Number(System.Math.Max(1, 100000 / rule.MoveSpeed)) + "MS");
+ } else if (rule.MoveSpeed != 100) {
+ parts.Add("AS" + Number(System.Math.Max(1, rule.MoveSpeed)));
+ }
+ }
+ // all of a strip or matrix still names an area, or libdof doesn't take it for one
+ if (rule.Area && !parts.Any(IsAreaToken) && !rule.Kept.Split(' ').Any(IsAreaToken)) {
+ parts.Add("AW100");
+ }
+ if (rule.Layer is { } layer) {
+ parts.Add("L" + Number(layer));
+ }
+ if (rule.Kept.Trim().Length > 0) {
+ parts.Add(rule.Kept.Trim());
+ }
+ return string.Join(" ", parts);
+ }
+
+ // I takes 0 to 48, a 48th of full each; I# takes 0 to 255.
+ private static string Strength(int value)
+ {
+ value = System.Math.Min(255, System.Math.Max(0, value));
+ for (var step = 0; step <= 48; step++) {
+ if (StepValue(step) == value) {
+ return "I" + Number(step);
+ }
+ }
+ return "I#" + value.ToString("X2", CultureInfo.InvariantCulture);
+ }
+
+ private static int StepValue(int step) => (int)(System.Math.Min(48, System.Math.Max(0, step)) * 5.3125);
+
+ private static string Number(int value) => value.ToString(CultureInfo.InvariantCulture);
+
+ ///
+ /// A part of a setting as a rule, or null with why: libdof drops a part it can't read, and one fixed off (no problem then).
+ ///
+ internal static PluginTriggerRule ParsePart(string part, out string problem)
+ {
+ problem = null;
+ var text = (part ?? "").Trim();
+ var rule = new PluginTriggerRule { Original = text };
+ string rest;
+ if (text.StartsWith("(", StringComparison.Ordinal)) {
+ var close = Close(text);
+ if (close < 0) {
+ problem = $"The brackets of \"{text}\" don't match.";
+ return null;
+ }
+ rule.Condition = text.Substring(0, close + 1);
+ rest = text.Substring(close + 1);
+ } else {
+ // the trigger ends at the first space not after a |
+ var end = -1;
+ var last = '\0';
+ for (var i = 0; i < text.Length; i++) {
+ if (text[i] == ' ' && last != '|' && last != '\0') {
+ end = i;
+ break;
+ }
+ if (text[i] != ' ') {
+ last = text[i];
+ }
+ }
+ var trigger = (end < 0 ? text : text.Substring(0, end)).Trim();
+ rest = end < 0 ? "" : text.Substring(end);
+ var upper = trigger.ToUpperInvariant();
+ if (upper == "OFF" || upper == "0") {
+ return null;
+ }
+ if (upper == "ON" || upper == "1") {
+ rule.Always = true;
+ } else if (upper == "B" || upper == "BLINK") {
+ rule.Always = true;
+ rule.Blink = PluginTriggerBlink.WhileOn;
+ } else {
+ foreach (var element in trigger.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(e => e.Trim().ToUpperInvariant())) {
+ if (!IsElement(element)) {
+ problem = $"DOF doesn't know \"{trigger}\" as what fires a toy.";
+ return null;
+ }
+ rule.Sources.Add(element);
+ }
+ if (rule.Sources.Count == 0) {
+ problem = $"\"{text}\" names nothing that fires it.";
+ return null;
+ }
+ }
+ }
+
+ var kept = new List();
+ var numbers = 0;
+ foreach (var token in rest.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) {
+ var t = token.ToUpperInvariant();
+ if (token.IndexOf('@') >= 0) {
+ // a variable of the configuration, which stands for what libdof reads in its place
+ kept.Add(token);
+ } else if (t == "BLINK") {
+ // after a count of blinks, which libdof has already turned into blinks of a time, it blinks while on
+ if (rule.Blink == PluginTriggerBlink.Count) {
+ rule.Duration = 0;
+ rule.BlinkCount = 0;
+ }
+ rule.Blink = PluginTriggerBlink.WhileOn;
+ rule.BlinkInterval = 1000;
+ } else if (t == "INVERT") {
+ rule.Invert = true;
+ } else if (t == "NOBOOL" || Int(t, "APS") || Int(t, "APD") || t.Length > 3 && (t.StartsWith("APC", StringComparison.Ordinal) || t.StartsWith("SHP", StringComparison.Ordinal))
+ || Int(t, "ABT") || Int(t, "ABL") || Int(t, "ABW") || Int(t, "ABH") || Int(t, "ABF") || Int(t, "AAS") || Int(t, "AAC") || Int(t, "AAF")
+ || Sized(t, "AAD", 4) || Sized(t, "AAB", 4) || Int(t, "AFDEN") || Int(t, "AFMIN") || Int(t, "AFMAX") || Int(t, "AFFADE")) {
+ kept.Add(token);
+ } else if (Int(t, "AT", out var v)) {
+ rule.AreaTop = Clamp(v, 0, 100);
+ rule.Area = true;
+ } else if (Int(t, "AL", out v)) {
+ rule.AreaLeft = Clamp(v, 0, 100);
+ rule.Area = true;
+ } else if (Int(t, "AW", out v)) {
+ rule.AreaWidth = Clamp(v, 0, 100);
+ rule.Area = true;
+ } else if (Int(t, "AH", out v)) {
+ rule.AreaHeight = Clamp(v, 0, 100);
+ rule.Area = true;
+ } else if (Int(t, "AA") || Int(t, "ASA")) {
+ kept.Add(token);
+ } else if (Int(t, "AS", out v) || Int(t, "ASS", out v)) {
+ rule.MoveSpeed = Clamp(v, 1, 10000);
+ rule.Area = true;
+ } else if (t.Length > 5 && t.StartsWith("ASS", StringComparison.Ordinal) && t.EndsWith("MS", StringComparison.Ordinal)
+ && IsInteger(t.Substring(3, t.Length - 5))) {
+ // in how many milliseconds it crosses the area, as libdof turns it into a speed
+ var ms = ParseInt(t.Substring(3, t.Length - 5));
+ // a negative time as libdof takes it too: a speed below the least, so the least
+ rule.MoveSpeed = Clamp(ms != 0 ? 100000 / ms : 100000, 10, 100000);
+ rule.Area = true;
+ } else if (Sized(t, "AD", 3) || Sized(t, "ASD", 4)) {
+ var move = Move(t[t.Length - 1]);
+ if (move == PluginTriggerMove.None) {
+ kept.Add(token);
+ } else {
+ rule.Move = move;
+ }
+ rule.Area = true;
+ } else if (Int(t, "MAX", out v)) {
+ rule.MaxDuration = System.Math.Max(0, v);
+ } else if (Int(t, "BNP") || Int(t, "BNPW")) {
+ kept.Add(token);
+ } else if (Int(t, "BPW", out v)) {
+ rule.BlinkOn = Clamp(v, 1, 99);
+ } else if (t.Length > 3 && t.StartsWith("BL#", StringComparison.Ordinal) && IsHex(t.Substring(3)) || Int(t, "BL")) {
+ kept.Add(token);
+ } else if (Int(t, "E", out v)) {
+ rule.Extend = System.Math.Max(0, v);
+ } else if (t.Length > 2 && t.StartsWith("I#", StringComparison.Ordinal) && IsHex(t.Substring(2))) {
+ rule.Strength = Clamp(int.Parse(t.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture), 0, 255);
+ } else if (Int(t, "I", out v)) {
+ rule.Strength = StepValue(v);
+ } else if (Int(t, "L", out v)) {
+ rule.Layer = v;
+ } else if (Int(t, "W", out v)) {
+ rule.Delay = System.Math.Max(0, v);
+ } else if (Int(t, "M", out v)) {
+ rule.MinDuration = System.Math.Max(0, v);
+ } else if (Int(t, "F", out v)) {
+ rule.FadeIn = rule.FadeOut = System.Math.Max(0, v);
+ } else if (Int(t, "FU", out v)) {
+ rule.FadeIn = System.Math.Max(0, v);
+ } else if (Int(t, "FD", out v)) {
+ rule.FadeOut = System.Math.Max(0, v);
+ } else if (IsInteger(t)) {
+ // after Blink, the time of a blink; else the time it is on, then how often it blinks in it
+ v = ParseInt(t);
+ if (++numbers > 2) {
+ problem = $"\"{text}\" has more than two numbers of its own.";
+ return null;
+ }
+ if (rule.Blink == PluginTriggerBlink.WhileOn) {
+ if (numbers == 1) {
+ rule.BlinkInterval = System.Math.Max(1, v);
+ rule.Duration = 0;
+ }
+ } else if (numbers == 1) {
+ rule.Duration = System.Math.Max(1, v);
+ } else {
+ rule.Blink = PluginTriggerBlink.Count;
+ rule.BlinkCount = System.Math.Max(1, v);
+ }
+ } else if (IsHexColour(t) || t.Length > 2 && t.All(c => c >= 'A' && c <= 'Z' || c == '_')) {
+ rule.Color = token;
+ } else {
+ problem = $"DOF doesn't understand \"{token}\" in \"{text}\".";
+ return null;
+ }
+ }
+ // a count of blinks without a time to blink in is none
+ if (rule.Blink == PluginTriggerBlink.Count && rule.Duration <= 0) {
+ rule.Blink = PluginTriggerBlink.None;
+ rule.BlinkCount = 0;
+ }
+ // effects of an area it keeps as written make it one too
+ rule.Area |= kept.Any(IsAreaToken);
+ rule.Kept = string.Join(" ", kept);
+ return rule;
+ }
+
+ // a token by which libdof takes a part for one that lights an area
+ private static bool IsAreaToken(string token)
+ {
+ var t = token.ToUpperInvariant();
+ return Int(t, "AT") || Int(t, "AL") || Int(t, "AW") || Int(t, "AH") || Int(t, "AA") || Int(t, "ASA") || Int(t, "AS") || Int(t, "ASS")
+ || t.Length > 5 && t.StartsWith("ASS", StringComparison.Ordinal) && t.EndsWith("MS", StringComparison.Ordinal)
+ || Sized(t, "AD", 3) || Sized(t, "ASD", 4) || Int(t, "APS") || Int(t, "APD") || t.Length > 3 && (t.StartsWith("APC", StringComparison.Ordinal)
+ || t.StartsWith("SHP", StringComparison.Ordinal)) || Int(t, "ABT") || Int(t, "ABL") || Int(t, "ABW") || Int(t, "ABH") || Int(t, "ABF")
+ || Int(t, "AAS") || Int(t, "AAC") || Int(t, "AAF") || Sized(t, "AAD", 4) || Sized(t, "AAB", 4) || Int(t, "AFDEN") || Int(t, "AFMIN")
+ || Int(t, "AFMAX") || Int(t, "AFFADE");
+ }
+
+ private static PluginTriggerMove Move(char direction) => direction switch {
+ 'L' => PluginTriggerMove.Left,
+ 'R' => PluginTriggerMove.Right,
+ 'U' => PluginTriggerMove.Up,
+ 'D' => PluginTriggerMove.Down,
+ _ => PluginTriggerMove.None
+ };
+
+ /// libdof's trigger elements: S12 and the like, or a named one such as $beacon.
+ internal static bool IsElement(string element)
+ {
+ if (element.Length <= 1) {
+ return false;
+ }
+ if (element[0] == '$') {
+ return element.Skip(1).All(c => c < 128 && char.IsLetterOrDigit(c) || c == '_');
+ }
+ return "LWSGMNEDCB".IndexOf(char.ToUpperInvariant(element[0])) >= 0 && IsInteger(element.Substring(1));
+ }
+
+ private static bool Int(string token, string prefix) => Int(token, prefix, out _);
+
+ private static bool Int(string token, string prefix, out int value)
+ {
+ value = 0;
+ if (token.Length <= prefix.Length || !token.StartsWith(prefix, StringComparison.Ordinal) || !IsInteger(token.Substring(prefix.Length))) {
+ return false;
+ }
+ value = ParseInt(token.Substring(prefix.Length));
+ return true;
+ }
+
+ private static bool Sized(string token, string prefix, int length) => token.Length == length && token.StartsWith(prefix, StringComparison.Ordinal);
+
+ private static bool IsInteger(string s) => s.Length > 0 && s.Skip(s[0] == '-' ? 1 : 0).Any() && s.Skip(s[0] == '-' ? 1 : 0).All(c => c >= '0' && c <= '9');
+
+ // what doesn't fit an int is as large as one gets, as for libdof
+ private static int ParseInt(string s) => int.TryParse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var v) ? v
+ : s.StartsWith("-", StringComparison.Ordinal) ? int.MinValue : int.MaxValue;
+
+ private static bool IsHex(string s) => s.Length > 0 && s.Length <= 8 && s.All(Uri.IsHexDigit);
+
+ private static bool IsHexColour(string s) => (s.Length == 7 || s.Length == 9) && s[0] == '#' && s.Skip(1).All(Uri.IsHexDigit);
+
+ private static int Clamp(int value, int min, int max) => System.Math.Min(max, System.Math.Max(min, value));
+
+ // where the bracket a text starts with closes, or -1
+ private static int Close(string text)
+ {
+ var depth = 0;
+ for (var i = 0; i < text.Length; i++) {
+ depth += text[i] == '(' ? 1 : text[i] == ')' ? -1 : 0;
+ if (depth == 0) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ private static string Clean(string setting) => new string((setting ?? "").Select(c => char.IsControl(c) ? ' ' : c).ToArray()).Trim();
+
+ /// Splits at a separator outside of brackets, as libdof splits a column into settings.
+ private static List Split(string data, char separator)
+ {
+ var parts = new List();
+ int brackets = 0, start = 0;
+ for (var p = 0; p < data.Length; p++) {
+ if (data[p] == '(') {
+ brackets++;
+ } else if (data[p] == ')') {
+ brackets--;
+ }
+ if (data[p] == separator && brackets <= 0) {
+ parts.Add(data.Substring(start, p - start));
+ start = p + 1;
+ brackets = 0;
+ }
+ }
+ if (start < data.Length) {
+ parts.Add(data.Substring(start));
+ }
+ return parts;
+ }
+ }
+}
diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofTriggerSyntax.cs.meta b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofTriggerSyntax.cs.meta
new file mode 100644
index 0000000..13c8b09
--- /dev/null
+++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofTriggerSyntax.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d522ea7895314cef9d581e3c02581737
diff --git a/VisualPinball.Engine.DOF.Unity/Tests/DofGameSetupTests.cs b/VisualPinball.Engine.DOF.Unity/Tests/DofGameSetupTests.cs
index 3c09a18..be19c2d 100644
--- a/VisualPinball.Engine.DOF.Unity/Tests/DofGameSetupTests.cs
+++ b/VisualPinball.Engine.DOF.Unity/Tests/DofGameSetupTests.cs
@@ -65,7 +65,7 @@ public void TakesTheQualifiedRomThenTheRomThenTheDeclaredName()
}
[Test]
- public void OffersTheTableMappingAsAChoice()
+ public void TellsOfTheTableMappingForAGameWithoutRows()
{
using (var host = new DofTestHost()) {
host.Import(342, "mapped,S1\r\nother,S2");
@@ -73,10 +73,9 @@ public void OffersTheTableMappingAsAChoice()
var request = new PluginChoiceRequest(new GameIdentity("vpe", "nothing"), new PluginSettingsSnapshot(1), "windows") {
Package = new PluginPackageReference(@"C:\Tables\My Mapped Table.vpe", "My Mapped Table"),
};
- var catalog = host.Factory.DiscoverAsync("roms", request, CancellationToken.None).Result;
- Assert.That(catalog.Choices.Select(c => c.Id), Is.EqualTo(new[] { "auto", "mapped", "other" }));
- Assert.That(catalog.Choices[0].Description, Does.Contain("no rows for nothing"));
- Assert.That(catalog.Choices[1].Label, Does.Contain("table mapping"));
+ var catalog = host.Factory.DiscoverAsync("rom", request, CancellationToken.None).Result;
+ Assert.That(catalog.Choices.Select(c => c.Id), Is.EqualTo(new[] { "nothing" }), "the game's own name, not the mapped one");
+ Assert.That(catalog.Choices[0].Description, Does.Contain("Matches no rows").And.Contain("\"My Mapped Table\" to mapped: type that"));
}
}
diff --git a/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs b/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs
index d35db7a..658b4f4 100644
--- a/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs
+++ b/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs
@@ -445,30 +445,35 @@ public void TurnsEveryOutputOffOutsideAGame()
}
}
- private static PluginChoiceRequest Request(JObject settings = null) => new PluginChoiceRequest(null, new PluginSettingsSnapshot(1, settings ?? new JObject()), "windows");
+ private static PluginChoiceRequest Request(JObject settings = null, bool confirmed = false)
+ => new PluginChoiceRequest(null, new PluginSettingsSnapshot(1, settings ?? new JObject()), "windows") { Confirmed = confirmed };
- private static PluginActionResult Swap(DofTestHost host, string first, string second, int count = 1)
- => host.Factory.SwapOutputsAsync("outputs", first, second, count, Request(), CancellationToken.None).Result;
+ private static PluginActionResult ResetWiring(DofTestHost host, bool confirmed = true)
+ => host.Factory.RunActionAsync("reset-wiring", Request(confirmed: confirmed), CancellationToken.None).Result;
+
+ private static IReadOnlyCollection HiddenDeviceFields(DofTestHost host)
+ => host.Factory.DescribeAsync("devices", Request(), CancellationToken.None).Result.HiddenFields;
private static IReadOnlyList Outputs(DofTestHost host)
=> host.Factory.DescribeOutputsAsync("outputs", Request(), CancellationToken.None).Result.Boards.Single().Outputs;
[Test]
- public void RearrangesOutputsForTheMapAndTheTests()
+ public void MovesToysForTheMapAndTheTests()
{
var native = new RecordingTestNative();
var host = Host();
host.Factory.TestNativeFactory = _ => native;
host.Factory.PulseDuration = TimeSpan.FromMilliseconds(20);
host.Import(361, "vpetest,S1,0,E2 White", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\"");
- Assert.That(host.Factory.DescribeOutputsAsync("outputs", Request(), CancellationToken.None).Result.Boards.Single().Rearrangeable, Is.True);
- Assert.That(host.Factory.DescribeAsync("devices", Request(), CancellationToken.None).Result.UnavailableActions, Does.Contain("ResetWiring"), "nothing to undo yet");
+ Assert.That(HiddenDeviceFields(host), Does.Contain("ResetWiring"), "nothing to reset yet");
- var swapped = Swap(host, "1:1", "1:2");
- Assert.That(swapped.Success, Is.True, swapped.Message);
+ // the output a toy moves to gives what it drove to the output the toy leaves
+ var moved = Assign(host, "1:2", "p1");
+ Assert.That(moved.Success, Is.True, moved.Message);
var outputs = Outputs(host);
Assert.That(outputs.Take(2).Select(o => (o.Number, o.Id, o.Label, o.Note)), Is.EqualTo(new[] { (1, "1:2", "", "Moved from 2"), (2, "1:1", "Knocker", "Moved from 1") }));
Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofOutputWiring.FileName)), Is.True, "kept with the configurations");
+ Assert.That(HiddenDeviceFields(host), Does.Not.Contain("ResetWiring"));
// A test pulses the port, which DOF routes to the output it is cabled to.
var pulse = Pulse(host, "1:1");
@@ -477,38 +482,68 @@ public void RearrangesOutputsForTheMapAndTheTests()
Assert.That(pulse.Message, Does.Contain("on output 2 of device 1"), "named after the output it drives");
// An RGB toy moves as a whole.
- Assert.That(Swap(host, "1:3", "1:7").Message, Does.Contain("would split Flasher"));
- Assert.That(Swap(host, "1:3", "1:5", 3).Message, Does.Contain("overlap"));
- swapped = Swap(host, "1:3", "1:6", 3);
- Assert.That(swapped.Success, Is.True, swapped.Message);
+ Assert.That(Assign(host, "1:4", "p1").Message, Does.Contain("would split Flasher"));
+ moved = Assign(host, "1:6", "p3");
+ Assert.That(moved.Success, Is.True, moved.Message);
outputs = Outputs(host);
Assert.That(outputs.Skip(5).Take(3).Select(o => (o.Number, o.Label, o.Channel)), Is.EqualTo(new[] {
(6, "Flasher", PluginOutputChannel.Red), (7, "Flasher", PluginOutputChannel.Green), (8, "Flasher", PluginOutputChannel.Blue),
}));
Assert.That(outputs.Skip(2).Take(3).Select(o => o.Id), Is.EqualTo(new[] { "1:6", "1:7", "1:8" }));
- Assert.That(Swap(host, "1:1", "2:1").Success, Is.False, "within a board only");
- var reset = RunAction(host, "reset-wiring");
+ // it asks first, as it can't be undone
+ var reset = ResetWiring(host, false);
+ Assert.That(reset.Confirmation, Is.Not.Null);
+ Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofOutputWiring.FileName)), Is.True, "nothing reset before the user agrees");
+ reset = ResetWiring(host);
Assert.That(reset.Success, Is.True, reset.Message);
Assert.That(Outputs(host).Select(o => o.Id), Is.EqualTo(Enumerable.Range(1, 32).Select(p => "1:" + p)));
Assert.That(Outputs(host).All(o => o.Note.Length == 0), Is.True);
Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofOutputWiring.FileName)), Is.False);
- Assert.That(RunAction(host, "reset-wiring").Success, Is.False, "nothing left to undo");
+ Assert.That(HiddenDeviceFields(host), Does.Contain("ResetWiring"));
+ reset = ResetWiring(host, false);
+ Assert.That((reset.Success, reset.Confirmation), Is.EqualTo((false, (PluginConfirmation)null)), "nothing left to reset, nor to ask about");
+ }
+
+ [Test]
+ public void AnRgbToyTheHeaderDoesNotNameIsChosenByItsOutputs()
+ {
+ var host = Host();
+ host.Import(373, "vpetest,S1,0,E2 White", null, "\"Rom\",\"Knocker\"");
+ var board = Board(host);
+ Assert.That(board.Toys.Select(t => (t.Id, t.Label, t.Rgb)), Is.EqualTo(new[] { ("p1", "Knocker", false), ("p3", "RGB toy of outputs 3–5", true) }));
+ Assert.That(board.Outputs.Take(5).Select(o => o.Toy), Is.EqualTo(new[] { "p1", "", "p3", "p3", "p3" }));
+ var moved = Assign(host, "1:10", "p3");
+ Assert.That(moved.Success, Is.True, moved.Message);
+ Assert.That(Board(host).Outputs.Skip(9).Take(3).Select(o => (o.Id, o.Channel)), Is.EqualTo(new[] {
+ ("1:3", PluginOutputChannel.Red), ("1:4", PluginOutputChannel.Green), ("1:5", PluginOutputChannel.Blue) }));
+
+ // named without rewiring, and back to the configuration's by its name in the list, or no name
+ var named = host.Factory.DescribeOutputAsync("outputs", "1:3", "Undercab", true, Request(), CancellationToken.None).Result;
+ Assert.That(named.Success, Is.True, named.Message);
+ Assert.That(Board(host).Outputs[9].Note, Is.EqualTo("Moved from 3 · Was an RGB toy"));
+ named = host.Factory.DescribeOutputAsync("outputs", "1:3", "", false, Request(), CancellationToken.None).Result;
+ Assert.That((named.Success, named.Message), Is.EqualTo((true, "Outputs 10 to 12 are the configuration's RGB toy again. What drives and fires them stays as it is.")));
+ Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofPortNames.FileName)), Is.False);
+ Assert.That(host.Factory.DescribeOutputAsync("outputs", "1:3", "Undercab", true, Request(), CancellationToken.None).Result.Success, Is.True);
+ named = host.Factory.DescribeOutputAsync("outputs", "1:3", "RGB toy of outputs 3–5", true, Request(), CancellationToken.None).Result;
+ Assert.That(named.Success, Is.True, named.Message);
+ Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofPortNames.FileName)), Is.False);
}
[Test]
- public void AnRgbToyANewConfigurationPutsApartMovesAnOutputAtATime()
+ public void AnRgbToyANewConfigurationPutsApartIsPutBackTogether()
{
var host = Host();
- host.Import(364, "vpetest,S1");
- Assert.That(Swap(host, "1:2", "1:5").Success, Is.True);
+ host.Import(364, "vpetest,S1,S2", null, "\"Rom\",\"Knocker\",\"Shaker\"");
+ Assert.That(Assign(host, "1:5", "p2").Success, Is.True);
host.Import(364, "vpetest,E2 White", null, "\"Rom\",\"Flasher\"");
var outputs = Outputs(host);
Assert.That(outputs.Take(5).Select(o => o.Channel), Is.EqualTo(new[] {
PluginOutputChannel.Red, PluginOutputChannel.None, PluginOutputChannel.Blue, PluginOutputChannel.None, PluginOutputChannel.Green,
}), "the green drives output 5");
Assert.That(outputs[1].Id, Is.EqualTo("1:5"), "port 5 drives output 2");
- var moved = Swap(host, "1:2", "1:5");
+ var moved = Assign(host, "1:1", "p1");
Assert.That(moved.Success, Is.True, "the green goes back between its red and blue: " + moved.Message);
Assert.That(Outputs(host).Take(3).Select(o => o.Channel), Is.EqualTo(new[] { PluginOutputChannel.Red, PluginOutputChannel.Green, PluginOutputChannel.Blue }));
}
@@ -516,12 +551,102 @@ public void AnRgbToyANewConfigurationPutsApartMovesAnOutputAtATime()
private static PluginActionResult Assign(DofTestHost host, string output, string toy)
=> host.Factory.AssignOutputAsync("outputs", output, toy, Request(), CancellationToken.None).Result;
- private static PluginActionResult AddToy(DofTestHost host, string output, string name)
- => host.Factory.AddToyAsync("outputs", output, name, Request(), CancellationToken.None).Result;
+ private static PluginActionResult AddToy(DofTestHost host, string output, string name, bool rgb = false)
+ => host.Factory.AddToyAsync("outputs", output, name, rgb, Request(), CancellationToken.None).Result;
private static PluginOutputBoard Board(DofTestHost host)
=> host.Factory.DescribeOutputsAsync("outputs", Request(), CancellationToken.None).Result.Boards.Single();
+ private static PluginActionResult SetRgb(DofTestHost host, string output, bool rgb)
+ => host.Factory.SetToyRgbAsync("outputs", output, rgb, Request(), CancellationToken.None).Result;
+
+ private static PluginActionResult Light(DofTestHost host, string output, byte red, byte green, byte blue)
+ => host.Factory.TestOutputColorAsync("outputs", output, red, green, blue, Request(), CancellationToken.None).Result;
+
+ private static PluginActionResult Describe(DofTestHost host, string output, string name, bool rgb = false)
+ => host.Factory.DescribeOutputAsync("outputs", output, name, rgb, Request(), CancellationToken.None).Result;
+
+ [Test]
+ public void AnOutputIsNamedWithoutRewiring()
+ {
+ var host = Host();
+ host.Import(374, "vpetest,S1,0,E2 White,S2,S3", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\",\"\",\"\",\"Bumper\",\"Sling\"");
+ string Shown(int skip, int take) => string.Join(";", Board(host).Outputs.Skip(skip).Take(take).Select(o => $"{o.Id}={o.Label}/{o.Channel}/{o.Note}"));
+
+ // the configuration has the wrong toy on output 6: it is named, and the port still drives it
+ var named = Describe(host, "1:6", " Shaker ");
+ Assert.That(named.Success, Is.True, named.Message);
+ Assert.That(named.Message, Is.EqualTo("Output 6 is Shaker now. What drives and fires it stays as it is."));
+ Assert.That(Shown(5, 1), Is.EqualTo("1:6=Shaker/None/Was Bumper"));
+ Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofOutputWiring.FileName)), Is.False, "nothing rewired");
+ Assert.That(Board(host).Toys.Select(t => t.Label), Does.Contain("Shaker").And.Not.Contain("Bumper"));
+ Assert.That(HiddenDeviceFields(host), Does.Not.Contain("ResetWiring"), "a name to reset");
+ // the game's page names it too
+ Assert.That(GameOutputs(host).Boards.Single().Outputs.Single(o => o.Id == "1:6").Label, Is.EqualTo("Shaker"));
+
+ // an RGB toy takes the next two outputs, and gives them back as a toy of one output
+ named = Describe(host, "1:6", "Shaker", true);
+ Assert.That(named.Success, Is.True, named.Message);
+ Assert.That(named.Message, Does.StartWith("Outputs 6 to 8 are Shaker now, an RGB toy, in place of Sling."));
+ Assert.That(Shown(5, 3), Is.EqualTo("1:6=Shaker/Red/Was Bumper;1:7=Shaker/Green/;1:8=Shaker/Blue/"));
+ Assert.That(GameOutputs(host).Boards.Single().Outputs.Skip(5).Take(3).Select(o => (o.Label, o.Channel)), Is.EqualTo(new[] {
+ ("Shaker", PluginOutputChannel.None), ("Sling", PluginOutputChannel.None), ("", PluginOutputChannel.None) }), "the game's rows have a column for each");
+ Assert.That(Describe(host, "1:7", "Fan").Message, Is.EqualTo("Output 7 is the green of Shaker: name the toy on output 6, its red."));
+ Assert.That(Describe(host, "1:6", "Shaker").Success, Is.True);
+ Assert.That(Shown(5, 2), Is.EqualTo("1:6=Shaker/None/Was Bumper;1:7=Sling/None/"));
+
+ // the configuration's RGB toy stays one, and isn't split by one the user says is next to it
+ Assert.That(Describe(host, "1:3", "Flasher").Message, Does.Contain("stays one"));
+ Assert.That(Describe(host, "1:2", "Lamp", true).Message, Does.Contain("would split Flasher"));
+ named = Describe(host, "1:3", "Undercab", true);
+ Assert.That(named.Success, Is.True, named.Message);
+ Assert.That(Shown(2, 1), Is.EqualTo("1:3=Undercab/Red/Was Flasher"));
+ Assert.That(Describe(host, "1:31", "Lamp").Message, Does.StartWith("No configuration fires what output 31 drives"));
+
+ // one that isn't cabled in a row with the next two is rewired, not named
+ Assert.That(Assign(host, "1:9", "p1").Success, Is.True);
+ Assert.That(Describe(host, "1:7", "Lamp", true).Message, Does.Contain("output 9 has what the configuration puts on output 1. Turn on Rewire"));
+ // the name stays with the port where it moves
+ Assert.That(Assign(host, "1:10", "p6").Success, Is.True);
+ Assert.That(Board(host).Outputs.Single(o => o.Number == 10).Note, Is.EqualTo("Moved from 6 · Was Bumper"));
+ var nothing = Assign(host, "1:12", null);
+ Assert.That(nothing.Success, Is.True, nothing.Message);
+ Assert.That(Describe(host, "1:-12", "Fan").Message, Does.StartWith("Nothing drives output 12"));
+
+ // no toy; and what the configuration says is no name to keep
+ Assert.That(Describe(host, "1:7", "").Message, Is.EqualTo("Output 7 has no toy now. What drives and fires it stays as it is."));
+ Assert.That(Shown(6, 1), Is.EqualTo("1:7=/None/Was Sling"));
+ Assert.That(Describe(host, "1:7", "Sling").Success, Is.True);
+ Assert.That(Describe(host, "1:3", "Flasher", true).Success, Is.True);
+ Assert.That(DofPortNames.Load(host.Factory.Store.Root).PortsOf(1), Is.EqualTo(new[] { 6 }));
+
+ // a toy the user added is renamed
+ Assert.That(AddToy(host, "1:20", "Gear").Success, Is.True);
+ named = Describe(host, "1:" + DofToyNames.FirstPort, "Gear motor");
+ Assert.That(named.Success, Is.True, named.Message);
+ Assert.That(Board(host).Outputs.Single(o => o.Number == 20).Label, Is.EqualTo("Gear motor"));
+ Assert.That(Describe(host, "1:" + DofToyNames.FirstPort, "").Success, Is.False, "taken off with Rewire");
+
+ // the reset puts the names back too
+ var reset = ResetWiring(host);
+ Assert.That(reset.Success, Is.True, reset.Message);
+ Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofPortNames.FileName)), Is.False);
+ Assert.That(Shown(5, 1), Is.EqualTo("1:6=Bumper/None/"));
+ }
+
+ [Test]
+ public void PutsTheNamesBackAsThePanelFoundThem()
+ {
+ var host = Host();
+ host.Import(375, "vpetest,S1", null, "\"Rom\",\"Knocker\",\"Shaker\"");
+ var snapshot = host.Factory.SnapshotOutputsAsync("outputs", Request(), CancellationToken.None).Result;
+ Assert.That(Describe(host, "1:2", "Fan").Success, Is.True);
+ var restored = host.Factory.RestoreOutputsAsync("outputs", snapshot, Request(), CancellationToken.None).Result;
+ Assert.That(restored.Success, Is.True, restored.Message);
+ Assert.That(Board(host).Outputs[1].Label, Is.EqualTo("Shaker"));
+ Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofPortNames.FileName)), Is.False);
+ }
+
[Test]
public void AnOutputIsGivenAToyOrNothing()
{
@@ -578,7 +703,7 @@ public void AnOutputIsGivenAToyOrNothing()
Assert.That(Pulse(host, "1:6").Success, Is.True);
Assert.That(native.Calls.Single(c => c.StartsWith("map:1:")), Does.Contain("-1"));
- var reset = RunAction(host, "reset-wiring");
+ var reset = ResetWiring(host);
Assert.That(reset.Success, Is.True, reset.Message);
Assert.That(Board(host).Outputs.Take(6).Select(o => o.Label), Is.EqualTo(new[] { "Knocker", "", "Flasher", "Flasher", "Flasher", "Shaker" }));
}
@@ -603,7 +728,7 @@ public void AnOutputIsGivenANewToy()
// kept across imports, and on no output after the wiring is undone, where it drives nothing
host.Import(366, "vpetest,S1", null, "\"Rom\",\"Knocker\",\"Shaker\"");
Assert.That(Board(host).Outputs[1].Label, Is.EqualTo("Gear motor"));
- Assert.That(RunAction(host, "reset-wiring").Success, Is.True);
+ Assert.That(ResetWiring(host).Success, Is.True);
board = Board(host);
Assert.That(board.Outputs[1].Label, Is.EqualTo("Shaker"));
Assert.That(board.Toys.Select(t => t.Label), Does.Contain("Gear motor"));
@@ -619,6 +744,165 @@ public void AnOutputIsGivenANewToy()
Assert.That(Board(host).Toys.Select(t => t.Label), Does.Not.Contain("Gear motor"));
}
+ [Test]
+ public void PutsTheOutputsBackAsThePanelFoundThem()
+ {
+ var host = Host();
+ host.Import(369, "vpetest,S1,0,E2 White,S2", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\",\"\",\"\",\"Shaker\"");
+ Assert.That(Assign(host, "1:14", "p1").Success, Is.True);
+ string Shown() => string.Join(";", Board(host).Outputs.Select(o => $"{o.Id}={o.Toy}/{o.Note}")) + "|" + string.Join(";", Board(host).Toys.Select(t => t.Label));
+ var before = Shown();
+ var wiring = File.ReadAllBytes(Path.Combine(host.Factory.Store.Root, DofOutputWiring.FileName));
+ var snapshot = host.Factory.SnapshotOutputsAsync("outputs", Request(), CancellationToken.None).Result;
+
+ // what the panel changes: a toy moved, a new one added
+ Assert.That(Assign(host, "1:2", "p6").Success, Is.True);
+ Assert.That(AddToy(host, "1:6", "Gear motor").Success, Is.True);
+ Assert.That(Shown(), Is.Not.EqualTo(before));
+
+ var restored = host.Factory.RestoreOutputsAsync("outputs", snapshot, Request(), CancellationToken.None).Result;
+ Assert.That(restored.Success, Is.True, restored.Message);
+ Assert.That(restored.Message, Does.StartWith("The outputs drive what they did before."));
+ Assert.That(Shown(), Is.EqualTo(before), "the new toy is gone too");
+ Assert.That(File.ReadAllBytes(Path.Combine(host.Factory.Store.Root, DofOutputWiring.FileName)), Is.EqualTo(wiring));
+ Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofToyNames.FileName)), Is.False, "no toys were added before");
+ Assert.That(host.Factory.RestoreOutputsAsync("outputs", snapshot, Request(), CancellationToken.None).Result.Message, Is.EqualTo("Nothing was changed."));
+ // the store took another folder meanwhile: these files aren't its own
+ var elsewhere = new DofPluginFactory(Path.Combine(host.Factory.Store.Root, "elsewhere"));
+ var refused = elsewhere.RestoreOutputsAsync("outputs", snapshot, Request(), CancellationToken.None).Result;
+ Assert.That((refused.Success, refused.Message), Is.EqualTo((false, "The outputs were in another folder then, so nothing was put back.")));
+ Assert.That(File.Exists(Path.Combine(elsewhere.Store.Root, DofOutputWiring.FileName)), Is.False);
+
+ // a game's triggers, apart from the outputs
+ var triggers = host.Factory.SnapshotOutputsAsync(DofPluginFactory.GameOutputsProvider, GameRequest(), CancellationToken.None).Result;
+ Assert.That(SetTrigger(host, "1:1", "S28").Success, Is.True);
+ Assert.That(host.Factory.RestoreOutputsAsync("outputs", triggers, Request(), CancellationToken.None).Result.Success, Is.False, "another field's");
+ Assert.That(host.Factory.RestoreOutputsAsync(DofPluginFactory.GameOutputsProvider, "garbage", GameRequest(), CancellationToken.None).Result.Success, Is.False);
+ Assert.That(GameOutputs(host).Boards.Single().Outputs.Single(o => o.Id == "1:1").Trigger, Is.EqualTo("S28"), "nothing put back from what isn't a snapshot");
+ restored = host.Factory.RestoreOutputsAsync(DofPluginFactory.GameOutputsProvider, triggers, GameRequest(), CancellationToken.None).Result;
+ Assert.That(restored.Success, Is.True, restored.Message);
+ Assert.That(GameOutputs(host).Boards.Single().Outputs.Single(o => o.Id == "1:1").Trigger, Is.EqualTo("S1"));
+ Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofGameTriggers.FileName)), Is.False);
+ Assert.That(Shown(), Is.EqualTo(before), "the outputs stay as they are");
+
+ // another game's trigger saved meanwhile stays: the file is the games', the snapshot this one's
+ triggers = host.Factory.SnapshotOutputsAsync(DofPluginFactory.GameOutputsProvider, GameRequest(), CancellationToken.None).Result;
+ Assert.That(SetTrigger(host, "1:1", "S28").Success, Is.True);
+ DofGameTriggers.Load(host.Factory.Store.Root).With("othergame", 369, 2, "S5").Save(host.Factory.Store.Root);
+ restored = host.Factory.RestoreOutputsAsync(DofPluginFactory.GameOutputsProvider, triggers, GameRequest(), CancellationToken.None).Result;
+ Assert.That(restored.Success, Is.True, restored.Message);
+ Assert.That(GameOutputs(host).Boards.Single().Outputs.Single(o => o.Id == "1:1").Trigger, Is.EqualTo("S1"));
+ var kept = DofGameTriggers.Load(host.Factory.Store.Root);
+ Assert.That((kept.SettingOf("othergame", 369, 2), kept.Of("vpetest", 369).Count), Is.EqualTo(("S5", 0)));
+ }
+
+ [Test]
+ public void AnOutputIsGivenANewRgbToy()
+ {
+ var host = Host();
+ host.Import(370, "vpetest,S1", null, "\"Rom\",\"Knocker\",\"Shaker\"");
+ var lamp = DofToyNames.FirstPort;
+ var result = AddToy(host, "1:4", " Lamp ", true);
+ Assert.That(result.Success, Is.True, result.Message);
+ Assert.That(result.Message, Does.StartWith("Outputs 4 to 6 drive Lamp now, an RGB toy; no configuration drives it yet."));
+ var board = Board(host);
+ Assert.That(board.Outputs.Skip(3).Take(3).Select(o => (o.Id, o.Label, o.Channel)), Is.EqualTo(new[] {
+ ("1:" + lamp, "Lamp", PluginOutputChannel.Red), ("1:" + (lamp + 1), "Lamp", PluginOutputChannel.Green), ("1:" + (lamp + 2), "Lamp", PluginOutputChannel.Blue) }));
+ Assert.That(board.Toys.Single(t => t.Label == "Lamp").Rgb, Is.True);
+ Assert.That(File.ReadAllText(Path.Combine(host.Factory.Store.Root, DofToyNames.FileName)), Does.Contain($"1:{lamp}:rgb=Lamp"));
+
+ // a toy of one output takes a port past the RGB toy's three
+ Assert.That(AddToy(host, "1:8", "Gear motor").Success, Is.True);
+ Assert.That(Board(host).Outputs[7].Id, Is.EqualTo("1:" + (lamp + 3)));
+ Assert.That(AddToy(host, "1:31", "Beacon", true).Message, Does.Contain("too close to the end"));
+ Assert.That(AddToy(host, "1:" + (lamp + 1), "Beacon").Message, Does.Contain("would split Lamp"));
+
+ // it moves as a whole
+ result = Assign(host, "1:20", "p" + lamp);
+ Assert.That(result.Success, Is.True, result.Message);
+ Assert.That(Board(host).Outputs.Skip(19).Take(3).Select(o => o.Channel), Is.EqualTo(new[] {
+ PluginOutputChannel.Red, PluginOutputChannel.Green, PluginOutputChannel.Blue }));
+ Assert.That(Assign(host, Board(host).Outputs[20].Id, "p1").Message, Does.Contain("would split Lamp"));
+ Assert.That(Assign(host, Board(host).Outputs[0].Id, "p" + lamp).Success, Is.True, "all of it moves");
+ Assert.That(Board(host).Outputs.Take(3).Select(o => (o.Label, o.Channel)), Is.EqualTo(new[] {
+ ("Lamp", PluginOutputChannel.Red), ("Lamp", PluginOutputChannel.Green), ("Lamp", PluginOutputChannel.Blue) }));
+
+ // a game fires it with a colour, and the toy of one output without
+ result = SetTrigger(host, "1:" + lamp, "S5 Red");
+ Assert.That(result.Success, Is.True, result.Message);
+ Assert.That(SetTrigger(host, "1:" + (lamp + 3), "S28 Blink").Success, Is.True);
+ Assert.That(SetTrigger(host, "1:" + (lamp + 3), "S28 Red").Success, Is.False, "a colour fires an RGB toy only");
+ var outputs = GameOutputs(host).Boards.Single().Outputs;
+ Assert.That(outputs.Where(o => o.Label == "Lamp" && o.Channel == PluginOutputChannel.Red).Select(o => (o.Trigger, o.TriggerChanged)).Single(),
+ Is.EqualTo(("S5 Red", true)));
+ Assert.That(outputs.Single(o => o.Label == "Gear motor").Trigger, Is.EqualTo("S28 Blink"));
+ }
+
+ [Test]
+ public void AnAddedToyBecomesAnRgbToyAndBack()
+ {
+ var host = Host();
+ host.Import(370, "vpetest,S1", null, "\"Rom\",\"Knocker\",\"Shaker\"");
+ var first = DofToyNames.FirstPort;
+ Assert.That(AddToy(host, "1:4", "Beacon").Success, Is.True);
+ Assert.That(AddToy(host, "1:8", "Gear motor").Success, Is.True);
+ Assert.That(Board(host).Outputs[7].Id, Is.EqualTo("1:" + (first + 3)), "a toy of one output keeps the two ports after it free");
+ var toys = Board(host).Toys;
+ Assert.That(toys.Where(t => t.Label == "Beacon").Select(t => (t.Rgb, t.RgbChangeable)).Single(), Is.EqualTo((false, true)));
+ Assert.That(toys.Single(t => t.Label == "Knocker").RgbChangeable, Is.False, "the configuration's toys are as it has them");
+
+ var result = SetRgb(host, "1:" + first, true);
+ Assert.That(result.Success, Is.True, result.Message);
+ Assert.That(result.Message, Does.StartWith("Outputs 4 to 6 drive Beacon now, an RGB toy."));
+ Assert.That(Board(host).Outputs.Skip(3).Take(3).Select(o => (o.Label, o.Channel)), Is.EqualTo(new[] {
+ ("Beacon", PluginOutputChannel.Red), ("Beacon", PluginOutputChannel.Green), ("Beacon", PluginOutputChannel.Blue) }));
+ Assert.That(File.ReadAllText(Path.Combine(host.Factory.Store.Root, DofToyNames.FileName)), Does.Contain($"1:{first}:rgb=Beacon"));
+ Assert.That(SetRgb(host, "1:" + first, true).Message, Does.Contain("an RGB toy already"));
+ // a game's trigger without a colour fires it as an RGB toy and as one of one output
+ Assert.That(SetTrigger(host, "1:" + first, "S28").Success, Is.True);
+ Assert.That(GameOutputs(host).Boards.Single().Outputs.Single(o => o.Id == "1:" + first).Trigger, Is.EqualTo("S28 #FFFFFF"));
+
+ // back by its green, which drives nothing then, nor does its blue
+ result = SetRgb(host, "1:" + (first + 1), false);
+ Assert.That(result.Success, Is.True, result.Message);
+ var outputs = Board(host).Outputs;
+ Assert.That((outputs[3].Label, outputs[3].Channel, outputs[4].Toy, outputs[5].Toy, outputs[4].Id), Is.EqualTo(("Beacon", PluginOutputChannel.None, "", "", "1:-5")));
+ Assert.That(File.ReadAllText(Path.Combine(host.Factory.Store.Root, DofToyNames.FileName)), Does.Contain($"1:{first}=Beacon"));
+ var game = GameOutputs(host).Boards.Single().Outputs.Single(o => o.Id == "1:" + first);
+ Assert.That((game.Trigger, game.Note), Is.EqualTo(("S28", "")), "the trigger still fires it");
+
+ // not over another toy, nor past the board, nor a toy of the configuration
+ Assert.That(Assign(host, "1:-6", "p1").Success, Is.True);
+ Assert.That(SetRgb(host, "1:" + first, true).Message, Does.Contain("Output 6 drives Knocker"));
+ Assert.That(Assign(host, "1:31", "p" + first).Success, Is.True);
+ Assert.That(SetRgb(host, "1:" + first, true).Message, Does.Contain("the board ends at output 32"));
+ Assert.That(SetRgb(host, "1:2", true).Message, Does.Contain("The configuration makes Shaker a toy of one output"));
+ Assert.That(SetRgb(host, "1:-5", true).Success, Is.False, "an output that drives nothing");
+ }
+
+ [Test]
+ public void AnRgbToyIsTestedInAColour()
+ {
+ var native = new RecordingTestNative();
+ var host = Host();
+ host.Factory.TestNativeFactory = _ => native;
+ host.Factory.PulseDuration = TimeSpan.FromMilliseconds(20);
+ host.Import(333, "vpetest,S1", "COM10", "\"Rom\",\"Flasher\"");
+ var lamp = DofToyNames.FirstPort;
+ Assert.That(AddToy(host, "1:4", "Lamp", true).Success, Is.True);
+ native.Calls.Clear();
+
+ // by any of its three outputs
+ var result = Light(host, "1:" + (lamp + 1), 255, 128, 0);
+ Assert.That(result.Success, Is.True, result.Message);
+ Assert.That(native.Calls.SkipWhile(c => c != "confirmed").Skip(1).TakeWhile(c => c != "finish"), Is.EqualTo(new[] {
+ $"1:{lamp}=255", $"1:{lamp + 1}=128", $"1:{lamp + 2}=0", "gate:open", "gate:closed", $"1:{lamp}=0", $"1:{lamp + 1}=0", $"1:{lamp + 2}=0" }));
+ Assert.That(result.Message, Does.StartWith("Requested to light outputs 4, 5, 6 of device 1 for 0"));
+ Assert.That(host.Leases.Owner("serial:COM10"), Is.Null, "released after the test");
+
+ Assert.That(Light(host, "1:1", 255, 0, 0).Message, Does.Contain("drives no RGB toy"));
+ }
+
[Test]
public void TheSerialPortsFollowTheCabinet()
{
@@ -646,12 +930,12 @@ public void TheSerialPortsFollowTheCabinet()
}
[UnityTest]
- public IEnumerator GamesUseTheRearrangedOutputs()
+ public IEnumerator GamesUseTheMovedToys()
{
const int universe = 363;
var host = Host();
- host.Import(universe, "vpetest,S1,S2");
- Assert.That(Swap(host, "1:1", "1:2").Success, Is.True);
+ host.Import(universe, "vpetest,S1,S2", null, "\"Rom\",\"Knocker\",\"Shaker\"");
+ Assert.That(Assign(host, "1:2", "p1").Success, Is.True);
var feed = host.PublishFeed();
var game = host.Game();
yield return host.Await(host.Plugin.PrepareGameAsync(game, CancellationToken.None), "prepare");
@@ -976,7 +1260,7 @@ public void ShowsWhatFiresTheToysInAGame()
var map = GameOutputs(host);
Assert.That(map.TriggersEditable, Is.True);
var board = map.Boards.Single();
- Assert.That((board.Rearrangeable, board.Toys.Count, board.AcceptsNewToys), Is.EqualTo((false, 0, false)), "what drives an output is chosen for every game");
+ Assert.That((board.Toys.Count, board.AcceptsNewToys), Is.EqualTo((0, false)), "what drives an output is chosen for every game");
Assert.That(board.Outputs.All(o => o.Toy.Length == 0), Is.True);
Assert.That(board.Outputs.Take(5).Select(o => o.Trigger), Is.EqualTo(new[] { "S1", "", "E2 White", "", "" }), "an RGB toy's on its red");
Assert.That(board.Outputs.Any(o => o.TriggerChanged), Is.False);
@@ -1022,7 +1306,7 @@ public void ChangesWhatFiresAToyInAGame()
Assert.That(GameOutputs(host).Boards.Single().Outputs[5].Trigger, Is.EqualTo("S9"), "kept across imports");
// a colour on a toy an import made a single one: the configuration's fires it, and the user's stays to reset
- Assert.That(SetTrigger(host, "1:3", "L5").Success, Is.True);
+ Assert.That(SetTrigger(host, "1:3", "L5 Red").Success, Is.True);
host.Import(368, "vpetest,S1,0,S7", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\"");
var flasher = GameOutputs(host).Boards.Single().Outputs[2];
Assert.That((flasher.Trigger, flasher.TriggerChanged, flasher.Note), Is.EqualTo(("S7", true, "Yours doesn't fit")));
@@ -1091,13 +1375,32 @@ public IEnumerator FiresAToyWithWhatTheUserChoseForTheGame()
}
[Test]
- public void ListsTheRomsOfTheConfiguration()
+ public void SuggestsTheNameTheRowsGoBy()
{
var host = Host();
- host.Import(334, "vpetest,S1");
- var catalog = host.Factory.DiscoverAsync("roms", new PluginChoiceRequest(new GameIdentity("pinmame", "vpetest_l1"), new PluginSettingsSnapshot(1), "windows"), CancellationToken.None).Result;
- Assert.That(catalog.Choices.Select(c => c.Id), Is.EqualTo(new[] { "auto", "vpetest" }));
- Assert.That(catalog.Choices[0].Description, Does.Contain("vpetest_l1 has rows on 1"));
+ host.Import(334, "vpetest,S1\r\nvpetest_pro,S2\r\nother,S3");
+ PluginChoiceCatalog Suggest(string setting) => host.Factory.DiscoverAsync("rom", new PluginChoiceRequest(new GameIdentity("pinmame", "vpetest_l1"),
+ new PluginSettingsSnapshot(1, setting == null ? new JObject() : new JObject { ["Rom"] = setting }), "windows"), CancellationToken.None).Result;
+ // the ROM finds the rows by its start: shown as they go by it
+ var catalog = Suggest(null);
+ Assert.That(catalog.Choices.Select(c => c.Id), Is.EqualTo(new[] { "vpetest" }));
+ Assert.That(catalog.Choices[0].Description, Is.EqualTo("This game's ROM: vpetest_l1.\nMatches vpetest on 1 (directoutputconfig.ini).\n"
+ + "Doesn't match vpetest_pro: type one to use its rows."));
+ // the user's own name, as typed, and what it gives
+ catalog = Suggest("vpetest_x");
+ Assert.That(catalog.Choices.Select(c => c.Id), Is.EqualTo(new[] { "vpetest_x" }));
+ catalog = Suggest("missing");
+ Assert.That(catalog.Choices[0].Description, Does.Contain("Matches no rows"));
+ Assert.That(Suggest("vpetest_pro").Choices[0].Description, Does.Contain("Matches vpetest_pro on 1").And.Contain("Doesn't match vpetest:"));
+ Assert.That(Suggest("auto").Choices.Select(c => c.Id), Is.EqualTo(new[] { "vpetest" }), "saved by an earlier version: the game's own");
+ }
+
+ [Test]
+ public void ForgetsTheAutomaticGameNameOfEarlierVersions()
+ {
+ var schema = Host().Factory.Schema;
+ Assert.That(schema.Upgrade(new PluginSettingsSnapshot(1, new JObject { ["Rom"] = "auto" })).Values.ContainsKey("Rom"), Is.False, "empty is the game's own");
+ Assert.That(schema.Upgrade(new PluginSettingsSnapshot(1, new JObject { ["Rom"] = "t2" })).Values.Value("Rom"), Is.EqualTo("t2"));
}
[UnityTest]
@@ -1110,6 +1413,248 @@ public IEnumerator RunsWithoutDofWithoutAConfiguration()
yield return host.Await(host.Plugin.StopGameAsync(CancellationToken.None), "stop");
AssertDofIsFree("nothing is held");
}
+
+ #region Config Tool
+
+ /// Answers the requests to the Config Tool as a test says, and keeps them; nothing leaves the machine.
+ private sealed class ConfigTool : System.Net.Http.HttpMessageHandler
+ {
+ public readonly List Asked = new List();
+ public Func Answer;
+
+ protected override Task SendAsync(System.Net.Http.HttpRequestMessage request, CancellationToken cancellation)
+ {
+ lock (Asked) {
+ Asked.Add(request.RequestUri.ToString());
+ }
+ return Task.FromResult(Answer());
+ }
+ }
+
+ private static byte[] ConfigZip(string row)
+ {
+ using var memory = new MemoryStream();
+ using (var zip = new System.IO.Compression.ZipArchive(memory, System.IO.Compression.ZipArchiveMode.Create, true)) {
+ using var writer = new StreamWriter(zip.CreateEntry("directoutputconfig.ini").Open());
+ writer.Write("[version]\r\nversion=1\r\n\r\n[Colors DOF]\r\nWhite=#FFFFFFFF\r\n\r\n[Variables DOF]\r\n\r\n[Config DOF]\r\n" + row + "\r\n");
+ }
+ return memory.ToArray();
+ }
+
+ [Test]
+ public void DownloadsTheCabinetsConfigurationWithItsKey()
+ {
+ var host = Host();
+ host.Import(381, "vpetest,S1");
+ var before = host.Factory.Store.Active.Id;
+ var tool = new ConfigTool();
+ host.Factory.ConfigToolHandler = () => tool;
+ var field = DofPluginFactory.SettingsSchema.Groups.SelectMany(g => g.Fields).Single(f => f.Id == "ConfigToolKey");
+ Assert.That(field.Secret, Is.True, "the key shows as dots");
+
+ // no key: nothing is sent
+ var refused = host.Factory.RunActionAsync("import-config-tool", Request(), CancellationToken.None).Result;
+ Assert.That((refused.Success, refused.Message), Is.EqualTo((false, DofConfigToolClient.CheckKey(""))));
+ Assert.That(tool.Asked, Is.Empty);
+
+ // a configuration to replace: asked first, before anything is downloaded
+ var settings = new JObject { ["ConfigToolKey"] = " Key0123456789 " };
+ var asked = host.Factory.RunActionAsync("import-config-tool", Request(settings), CancellationToken.None).Result;
+ Assert.That(asked.Confirmation, Is.Not.Null);
+ Assert.That(asked.Confirmation.Message, Does.Contain("replaces the ini files").And.Contain("can't be undone"));
+ Assert.That(tool.Asked, Is.Empty);
+ Assert.That(host.Factory.Store.Active.Id, Is.EqualTo(before));
+
+ // a key the Config Tool doesn't know: the configuration stays
+ tool.Answer = () => new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized) {
+ Content = new System.Net.Http.StringContent("API Error: Invalid API key passed") };
+ var unknown = host.Factory.RunActionAsync("import-config-tool", Request(settings, true), CancellationToken.None).Result;
+ Assert.That(unknown.Success, Is.False);
+ Assert.That(unknown.Message, Does.Contain("doesn't know this API key").And.Not.Contain("Key0123456789"));
+ Assert.That(host.Factory.Store.Active.Id, Is.EqualTo(before));
+
+ // the cabinet's zip, merged as a zip the user imports: the cabinet file stays
+ tool.Answer = () => new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new System.Net.Http.ByteArrayContent(ConfigZip("vpetest,S2")) };
+ var result = host.Factory.RunActionAsync("import-config-tool", Request(settings, true), CancellationToken.None).Result;
+ Assert.That(result.Success, Is.True, result.Message);
+ Assert.That(result.Message, Does.StartWith("Downloaded and imported."));
+ Assert.That(Directory.Exists(Path.Combine(host.Factory.Store.Root, "revisions", before)), Is.False, "the configuration it replaced is gone");
+ Assert.That(tool.Asked.Last(), Is.EqualTo("https://configtool.vpuniverse.com/api.php?query=getconfig&apikey=Key0123456789"));
+ var revision = host.Factory.Store.Active;
+ Assert.That(revision.Id, Is.Not.EqualTo(before));
+ Assert.That(revision.ReadOrigin(), Is.EqualTo(DofConfigToolClient.Origin));
+ Assert.That(File.ReadAllText(Path.Combine(revision.ConfigDir, "directoutputconfig.ini")), Does.Contain("vpetest,S2"));
+ Assert.That(DofCatalog.Load(revision).HasCabinet, Is.True);
+ }
+
+ [Test]
+ public void ImportsOnlyIntoTheConfigurationTheUserAgreedToReplace()
+ {
+ var host = Host();
+ host.Import(381, "vpetest,S1");
+ var tool = new ConfigTool { Answer = () => new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new System.Net.Http.ByteArrayContent(ConfigZip("vpetest,S2")) } };
+ host.Factory.ConfigToolHandler = () => tool;
+ var settings = new JObject { ["ConfigToolKey"] = "Key0123456789" };
+
+ // asked about one, another imported before the user agreed: nothing is downloaded
+ Assert.That(host.Factory.RunActionAsync("import-config-tool", Request(settings), CancellationToken.None).Result.Confirmation, Is.Not.Null);
+ host.Import(381, "vpetest,S3");
+ var meanwhile = host.Factory.Store.Active.Id;
+ var refused = host.Factory.RunActionAsync("import-config-tool", Request(settings, true), CancellationToken.None).Result;
+ Assert.That((refused.Success, refused.Message), Is.EqualTo((false, "The configuration changed meanwhile, so nothing was imported. Look at it again, then import.")));
+ Assert.That(tool.Asked, Is.Empty);
+ Assert.That(host.Factory.Store.Active.Id, Is.EqualTo(meanwhile));
+
+ // another imported while it downloads: the download isn't imported over it
+ Assert.That(host.Factory.RunActionAsync("import-config-tool", Request(settings), CancellationToken.None).Result.Confirmation, Is.Not.Null);
+ string during = null;
+ tool.Answer = () => {
+ host.Import(381, "vpetest,S4");
+ during = host.Factory.Store.Active.Id;
+ return new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new System.Net.Http.ByteArrayContent(ConfigZip("vpetest,S2")) };
+ };
+ var overtaken = host.Factory.RunActionAsync("import-config-tool", Request(settings, true), CancellationToken.None).Result;
+ Assert.That(overtaken.Success, Is.False);
+ Assert.That(tool.Asked, Has.Count.EqualTo(1));
+ Assert.That(host.Factory.Store.Active.Id, Is.EqualTo(during));
+ Assert.That(File.ReadAllText(Path.Combine(host.Factory.Store.Active.ConfigDir, "directoutputconfig.ini")), Does.Contain("vpetest,S4"));
+ }
+
+ [Test]
+ public void AStripOfThreeOutputsKeepsASettingOnItsFirstColumn()
+ {
+ var row = DofIniRow.Parse("[Config DOF]\r\ngame,S1,0,0,S4 Red\r\n", "game");
+ Assert.That(DofPluginFactory.SettingOfToy(row, 1, 3, true), Is.EqualTo("S1"), "the first column's, the other two empty");
+ Assert.That(DofPluginFactory.SettingOfToy(row, 1, 1, true), Is.EqualTo("S1"));
+ Assert.That(DofPluginFactory.SettingOfToy(row, 2, 3, true), Is.Null, "more than one setting");
+ // saved unchanged, it is fitted to the RGB toy, and still the configuration's
+ var fitted = DofIniRow.Fit("S1", true, out _);
+ Assert.That(fitted, Is.Not.EqualTo("S1"), "fitting adds the colour");
+ Assert.That(DofPluginFactory.SameAsConfigured(fitted, row, 1, 3), Is.True);
+ Assert.That(DofPluginFactory.SameAsConfigured(DofIniRow.Fit("S2", true, out _), row, 1, 3), Is.False);
+ Assert.That(DofPluginFactory.SameAsConfigured("S1", row, 1, 1), Is.True, "one output as before");
+ }
+
+ [Test]
+ public void BoardCardsSayWhetherAGameSetsThemUp()
+ {
+ DofPluginFactory.BoardUse Use(bool cabinet, bool auto, (string, int)[] boards, params int[] inis) => new DofPluginFactory.BoardUse(cabinet, auto, boards, inis);
+ var none = new (string, int)[0];
+ Assert.That(DofPluginFactory.Status("LedWiz", 1, null), Is.EqualTo(("Not in use: no configuration is imported", PluginInfoTone.Neutral)));
+
+ // without a cabinet file, DOF sets up every board it finds, and its ini file drives it
+ Assert.That(DofPluginFactory.Status("PacLed64", 20, Use(false, true, none, 1, 20)),
+ Is.EqualTo(("Set up by DOF, and games drive it with directoutputconfig20.ini", PluginInfoTone.Good)));
+ Assert.That(DofPluginFactory.Status("PacLed64", 21, Use(false, true, none, 1, 20)),
+ Is.EqualTo(("Set up by DOF, but nothing drives it: the configuration has no directoutputconfig21.ini", PluginInfoTone.Warning)));
+ // a Pinscape knows its unit itself: the files of its range
+ Assert.That(DofPluginFactory.Status("Pinscape", -1, Use(false, true, none, 51)),
+ Is.EqualTo(("Set up by DOF, and games drive it with directoutputconfig51.ini if that is its unit", PluginInfoTone.Good)));
+ Assert.That(DofPluginFactory.Status("Pinscape", -1, Use(false, true, none, 51, 52, 30)).Text,
+ Is.EqualTo("Set up by DOF, and games drive it with the one of directoutputconfig51.ini, directoutputconfig52.ini of its unit"));
+ Assert.That(DofPluginFactory.Status("Pinscape", -1, Use(false, true, none, 30)).Text,
+ Is.EqualTo("Set up by DOF, but nothing drives it: the configuration has no ini file for devices 51–66"));
+
+ // a cabinet file sets up the boards it names; the others only while DOF's own setup is on
+ var ledWiz1 = new[] { ("LedWiz", 1) };
+ Assert.That(DofPluginFactory.Status("LedWiz", 1, Use(true, false, ledWiz1)), Is.EqualTo(("Set up by your cabinet file", PluginInfoTone.Good)));
+ Assert.That(DofPluginFactory.Status("PacDrive", 19, Use(true, true, ledWiz1, 19)).Tone, Is.EqualTo(PluginInfoTone.Good));
+ Assert.That(DofPluginFactory.Status("PacDrive", 19, Use(true, false, ledWiz1, 19)),
+ Is.EqualTo(("Not set up: your cabinet file doesn't name it and turns DOF's own setup off", PluginInfoTone.Warning)));
+ // by its number where libdof goes by one: LedWiz 2 isn't the cabinet file's LedWiz 1, PacLed64 Id 2 is device 21
+ Assert.That(DofPluginFactory.Status("LedWiz", 2, Use(true, false, ledWiz1, 2)).Tone, Is.EqualTo(PluginInfoTone.Warning));
+ Assert.That(DofPluginFactory.Status("PacLed64", 21, Use(true, false, new[] { ("PacLed64", 2) })).Tone, Is.EqualTo(PluginInfoTone.Good));
+ Assert.That(DofPluginFactory.Status("PacUIO", 28, Use(true, false, new[] { ("PacUIO", 0) })).Tone, Is.EqualTo(PluginInfoTone.Warning));
+ // a PacUIO's first unit is Id 0, one of them, not its type alone
+ Assert.That(DofPluginFactory.Status("PacUIO", 27, Use(true, false, new[] { ("PacUIO", 0) })).Tone, Is.EqualTo(PluginInfoTone.Good));
+ Assert.That(DofPluginFactory.Status("PacUIO", 27, Use(true, false, new[] { ("PacUIO", 1) })).Tone, Is.EqualTo(PluginInfoTone.Warning));
+ // the file as the configuration names it, and one DOF skips drives nothing
+ Assert.That(DofPluginFactory.Status("LedWiz", 1, new DofPluginFactory.BoardUse(false, true, none, new[] { 1 }, new Dictionary { [1] = "directoutputconfig.ini" })).Text,
+ Is.EqualTo("Set up by DOF, and games drive it with directoutputconfig.ini"));
+ Assert.That(DofPluginFactory.Status("Pinscape", -1, new DofPluginFactory.BoardUse(false, true, none, new int[0], null, new[] { 51 })),
+ Is.EqualTo(("Set up by DOF, but nothing drives it: DOF skips directoutputconfig51.ini, which has no colours or no rows", PluginInfoTone.Warning)));
+ // only a Pinscape knows its unit
+ Assert.That(DofPluginFactory.Status("Pinscape", -1, Use(true, false, new[] { ("Pinscape", 1) }, 51)),
+ Is.EqualTo(("Set up by your cabinet file if it names this board's unit; DOF's own setup is off", PluginInfoTone.Neutral)));
+ }
+
+ [Test]
+ public void ImportsThroughOneButtonWithAWizard()
+ {
+ var groups = DofPluginFactory.SettingsSchema.Groups;
+ var configuration = groups.Single(g => g.Title == "Configuration");
+ var import = configuration.Fields.Single(f => f.Id == "Import");
+ Assert.That((import.Kind, import.AttachTo), Is.EqualTo((SettingKind.Action, "ActiveConfig")));
+ Assert.That(import.Wizard, Is.Not.Null, "the button opens the wizard");
+ Assert.That(import.Wizard.Choices.Select(c => (c.Label, c.FieldId, c.Action)), Is.EqualTo(new[] {
+ ("By zip file", "ImportZip", "import-zip"),
+ ("By existing folder", "ImportFolder", "import-folder"),
+ ("By API key", "ConfigToolKey", "import-config-tool"),
+ }));
+ // Browse offers zip files first
+ var zip = DofPluginFactory.SettingsSchema.Fields.Single(f => f.Id == "ImportZip");
+ Assert.That(zip.FileFilters.Select(f => f.Name), Is.EqualTo(new[] { "Zip files", "All files" }));
+ Assert.That(zip.FileFilters[0].Matches(@"C:\Downloads\directoutputconfig.ZIP"), Is.True);
+ Assert.That(zip.FileFilters[0].Matches("Cabinet.xml"), Is.False);
+ Assert.That(zip.FileFilters[1].Matches("Cabinet.xml"), Is.True);
+
+ // the old way of showing every import on the page is gone
+ Assert.That(groups.Select(g => g.Title), Has.None.StartsWith("Import"));
+ Assert.That(groups.SelectMany(g => g.Fields).Select(f => f.Id), Has.None.EqualTo("ImportZipAction").And.None.EqualTo("ImportFolderAction").And.None.EqualTo("ConfigToolDownload"));
+
+ // each way runs: without its value, it says what is missing
+ var host = Host();
+ foreach (var choice in import.Wizard.Choices) {
+ var result = host.Factory.RunActionAsync(choice.Action, Request(), CancellationToken.None).Result;
+ Assert.That((result.Success, result.Confirmation), Is.EqualTo((false, (PluginConfirmation)null)), choice.Label);
+ Assert.That(result.Message, Is.Not.Empty, choice.Label);
+ }
+ }
+
+ [Test]
+ public void ClearsTheConfigurationOnceTheUserAgreed()
+ {
+ var host = Host();
+ var fields = DofPluginFactory.SettingsSchema.Groups.SelectMany(g => g.Fields).Select(f => f.Id).ToArray();
+ Assert.That(fields, Does.Contain("ClearConfig").And.Not.Contain("Rollback"));
+ var none = host.Factory.RunActionAsync("clear-config", Request(), CancellationToken.None).Result;
+ Assert.That((none.Success, none.Confirmation), Is.EqualTo((false, (PluginConfirmation)null)), "nothing to clear, nothing to ask");
+ var info = host.Factory.DescribeAsync("configuration", Request(), CancellationToken.None).Result;
+ // Import alone: nothing to show or clear
+ Assert.That(info.HiddenFields, Does.Contain("ClearConfig").And.Contain("ShowImport"));
+
+ host.Import(382, "vpetest,S1");
+ var active = host.Factory.Store.Active;
+ info = host.Factory.DescribeAsync("configuration", Request(), CancellationToken.None).Result;
+ Assert.That(info.UnavailableActions, Is.Empty);
+ Assert.That(info.HiddenFields, Is.Empty);
+ Assert.That(info.Summary, Does.StartWith("Imported"));
+
+ var asked = host.Factory.RunActionAsync("clear-config", Request(), CancellationToken.None).Result;
+ Assert.That(asked.Confirmation, Is.Not.Null);
+ Assert.That(asked.Confirmation.ConfirmLabel, Is.EqualTo("Clear"));
+ Assert.That(host.Factory.Store.Active.Id, Is.EqualTo(active.Id), "asking changes nothing");
+
+ var cleared = host.Factory.RunActionAsync("clear-config", Request(confirmed: true), CancellationToken.None).Result;
+ Assert.That(cleared.Success, Is.True, cleared.Message);
+ Assert.That(host.Factory.Store.Active, Is.Null);
+ Assert.That(Directory.Exists(active.BasePath), Is.False);
+ }
+
+ [Test]
+ public void ShowsTheImportInADialog()
+ {
+ var host = Host();
+ host.Import(383, "vpetest,S1");
+ var result = host.Factory.RunActionAsync("show-import", Request(), CancellationToken.None).Result;
+ Assert.That(result.Success, Is.True);
+ Assert.That(result.Message, Is.Empty, "nothing under the row: the dialog says it");
+ Assert.That(result.Details, Is.Not.Null);
+ Assert.That(result.Details.Title, Is.Not.Empty);
+ Assert.That(result.Details.Text, Is.Not.Empty);
+ }
+
+ #endregion
}
/// A port test's DOF instance that records its calls, with controller units that confirm the gate as told.
diff --git a/VisualPinball.Engine.DOF.Unity/Tests/DofTriggerSyntaxTests.cs b/VisualPinball.Engine.DOF.Unity/Tests/DofTriggerSyntaxTests.cs
new file mode 100644
index 0000000..35779bc
--- /dev/null
+++ b/VisualPinball.Engine.DOF.Unity/Tests/DofTriggerSyntaxTests.cs
@@ -0,0 +1,153 @@
+// Visual Pinball Engine
+// Copyright (C) 2026 freezy and VPE Team
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+using System.Linq;
+using NUnit.Framework;
+using VisualPinball.Engine.DOF.Player;
+using VisualPinball.Plugins;
+
+namespace VisualPinball.Engine.DOF.Unity.Tests
+{
+ /// How a DOF setting reads into rules the Player edits, and back.
+ public class DofTriggerSyntaxTests
+ {
+ private const string Strip = "S7 White f100 AL0 AT0 AW100 AH15 L1/S20 Yellow AL0 AT0 AW100 AH15 L2/W47 Green f200 AL0 AT0 AW100 AH15 L4"
+ + "/S12 Red M50 MAX50 AH80 ADU AS300 L1/W57 Red AT70 AH30 ADD AS300/S1|S2|S13 Red M50/W16 Green L0 APCYellow AL0 AW100 AT85 AH15"
+ + "/S30 Green AT0 AH15 AL0 AW100 ASDL ASS200 BLINK 490 BPW15 F50 L-19";
+
+ [Test]
+ public void ReadsWhatEachPartSays()
+ {
+ var parse = DofTriggerSyntax.Parse(Strip);
+ Assert.That(parse.Problem, Is.Empty);
+ var rules = parse.Rules;
+ Assert.That(rules, Has.Count.EqualTo(8));
+
+ Assert.That((rules[0].Sources.Single(), rules[0].Color, rules[0].FadeIn, rules[0].FadeOut, rules[0].AreaHeight, rules[0].Layer),
+ Is.EqualTo(("S7", "White", 100, 100, 15, (int?)1)));
+ Assert.That((rules[3].MinDuration, rules[3].MaxDuration, rules[3].AreaTop, rules[3].AreaHeight, rules[3].Move, rules[3].MoveSpeed),
+ Is.EqualTo((50, 50, 0, 80, PluginTriggerMove.Up, 300)));
+ Assert.That((rules[4].Sources.Single(), rules[4].AreaTop, rules[4].Move, rules[4].Layer), Is.EqualTo(("W57", 70, PluginTriggerMove.Down, (int?)null)),
+ "ADD moves down, it is no colour");
+ Assert.That(rules[5].Sources, Is.EqualTo(new[] { "S1", "S2", "S13" }));
+ Assert.That((rules[6].Kept, rules[6].Layer), Is.EqualTo(("APCYellow", (int?)0)), "what the rule has no field for is kept");
+ var blink = rules[7];
+ Assert.That((blink.Blink, blink.BlinkInterval, blink.BlinkOn, blink.Move, blink.MoveSpeed, blink.Layer),
+ Is.EqualTo((PluginTriggerBlink.WhileOn, 490, 15, PluginTriggerMove.Left, 200, (int?)-19)));
+ }
+
+ [Test]
+ public void WritesWhatDidntChangeAsItWas()
+ {
+ var rules = DofTriggerSyntax.Parse(Strip).Rules.Select(r => r.Clone()).ToList();
+ Assert.That(DofTriggerSyntax.Format(rules), Is.EqualTo(Strip));
+
+ // moved and one changed: the others as written, the changed one anew
+ rules[3].Color = "Blue";
+ var moved = rules[0];
+ rules.RemoveAt(0);
+ rules.Add(moved);
+ var parts = DofTriggerSyntax.Format(rules).Split('/');
+ Assert.That(parts[2], Is.EqualTo("S12 Blue M50 MAX50 AH80 ADU AS300 L1"));
+ Assert.That(parts.Last(), Is.EqualTo("S7 White f100 AL0 AT0 AW100 AH15 L1"));
+ Assert.That(DofTriggerSyntax.Parse(parts[2]).Rules.Single().SameAs(rules[2]), Is.True);
+ }
+
+ [Test]
+ public void BlinksAsLibdofReadsThem()
+ {
+ Rule("S1 Blink 500", r => Assert.That((r.Blink, r.BlinkInterval, r.Duration), Is.EqualTo((PluginTriggerBlink.WhileOn, 500, 0))));
+ Rule("S1 500 Blink", r => Assert.That((r.Blink, r.BlinkInterval, r.Duration), Is.EqualTo((PluginTriggerBlink.WhileOn, 1000, 500))),
+ "a time before Blink is how long it is on");
+ Rule("S1 500 3", r => Assert.That((r.Blink, r.BlinkCount, r.Duration), Is.EqualTo((PluginTriggerBlink.Count, 3, 500))));
+ Rule("B", r => Assert.That((r.Always, r.Blink), Is.EqualTo((true, PluginTriggerBlink.WhileOn))));
+ Rule("ON Red", r => Assert.That((r.Always, r.Color), Is.EqualTo((true, "Red"))));
+ Rule("S2 I24", r => Assert.That(r.Strength, Is.EqualTo(127)));
+ Rule("S2 I#80", r => Assert.That(r.Strength, Is.EqualTo(128)));
+ Rule("(S1 and not L5) Red 300", r => Assert.That((r.Condition, r.Color, r.Duration), Is.EqualTo(("(S1 and not L5)", "Red", 300))));
+ Rule("S2 @strblft@ 300 L11", r => Assert.That((r.Kept, r.Duration), Is.EqualTo(("@strblft@", 300))), "a variable is kept");
+ }
+
+ [Test]
+ public void WritesNewRules()
+ {
+ var rule = new PluginTriggerRule { Sources = { "S12" }, Color = "Red", Duration = 300, FadeIn = 50, FadeOut = 50, Area = true, AreaTop = 20, AreaHeight = 80,
+ Move = PluginTriggerMove.Up, MoveSpeed = 250 };
+ Assert.That(DofTriggerSyntax.Format(rule), Is.EqualTo("S12 Red 300 F50 AT20 AH80 ADU AS250"));
+ Assert.That(DofTriggerSyntax.Parse(DofTriggerSyntax.Format(rule)).Rules.Single().SameAs(rule), Is.True);
+
+ rule = new PluginTriggerRule { Sources = { "W25", "L3" }, Blink = PluginTriggerBlink.Count, Duration = 600, BlinkCount = 3, Strength = 127, Delay = 100 };
+ Assert.That(DofTriggerSyntax.Format(rule), Is.EqualTo("W25|L3 600 3 W100 I24"));
+ rule = new PluginTriggerRule { Sources = { "S1" }, Blink = PluginTriggerBlink.WhileOn, BlinkInterval = 300, BlinkOn = 25, FadeIn = 20 };
+ Assert.That(DofTriggerSyntax.Format(rule), Is.EqualTo("S1 Blink 300 BPW25 FU20"));
+ Assert.That(DofTriggerSyntax.Format(new PluginTriggerRule()), Is.Empty, "nothing fires it");
+ }
+
+ [Test]
+ public void ChangedRulesStayAsLibdofReadThem()
+ {
+ // all of a strip still names an area once something else of it changes, or libdof takes the column for no strip's
+ var whole = DofTriggerSyntax.Parse("S12 Red AW100").Rules.Single();
+ Assert.That(whole.Area, Is.True);
+ whole.Sources[0] = "S13";
+ Assert.That(DofTriggerSyntax.Format(whole), Is.EqualTo("S13 Red AW100"));
+ Assert.That(DofTriggerSyntax.Format(new PluginTriggerRule { Sources = { "L5" }, Color = "Blue", Area = true }), Is.EqualTo("L5 Blue AW100"));
+ Assert.That(DofTriggerSyntax.Format(new PluginTriggerRule { Sources = { "L5" }, Color = "Blue", Area = true, AreaTop = 50, AreaHeight = 50 }),
+ Is.EqualTo("L5 Blue AT50 AH50"), "an area of its own needs nothing more");
+ Assert.That(DofTriggerSyntax.Parse("S1 Red SHP0001").Rules.Single().Area, Is.True, "a shape is drawn on an area");
+
+ // libdof turns the count into blinks of a time before Blink makes it blink while on
+ var blink = DofTriggerSyntax.Parse("S1 500 3 BLINK").Rules.Single();
+ Assert.That((blink.Blink, blink.Duration, blink.BlinkInterval), Is.EqualTo((PluginTriggerBlink.WhileOn, 0, 1000)));
+ blink.Delay = 100;
+ Assert.That(DofTriggerSyntax.Parse(DofTriggerSyntax.Format(blink)).Rules.Single().SameAs(blink), Is.True);
+
+ // a crossing in milliseconds is a speed from 10 up
+ var slow = DofTriggerSyntax.Parse("S1 Red ADU ASS20000MS").Rules.Single();
+ Assert.That(slow.MoveSpeed, Is.EqualTo(10));
+ var fast = DofTriggerSyntax.Parse("S1 Red ADU ASS5MS").Rules.Single();
+ Assert.That(fast.MoveSpeed, Is.EqualTo(20000));
+ fast.Delay = 10;
+ Assert.That(DofTriggerSyntax.Parse(DofTriggerSyntax.Format(fast)).Rules.Single().MoveSpeed, Is.EqualTo(20000), "faster than AS takes");
+ Assert.That(DofTriggerSyntax.Parse("S1 Red ADU ASS-5MS").Rules.Single().MoveSpeed, Is.EqualTo(10), "a negative time is the least speed, as libdof takes it");
+ }
+
+ [Test]
+ public void SaysWhatItCantRead()
+ {
+ var parse = DofTriggerSyntax.Parse("S1 Red/!S2/S3 1 2 3/X4/(S1 Red/S5");
+ Assert.That(parse.Rules.Select(r => r.Original), Is.EqualTo(new[] { "S1 Red" }));
+ Assert.That(parse.Problem, Does.Contain("\"!S2\"").And.Contain("more than two numbers").And.Contain("\"X4\"").And.Contain("brackets"));
+ Assert.That(DofTriggerSyntax.Parse("0/OFF").Problem, Is.Empty, "parts fixed off are nothing");
+ }
+
+ [Test]
+ public void ListsWhatTheConfigurationUsesWithTheGamesOutputs()
+ {
+ var named = new[] {
+ new PluginGameOutput("S12", "Shield Motor") { Kind = PluginGameOutputKind.Coil },
+ new PluginGameOutput("L45", "Shoot Again") { Kind = PluginGameOutputKind.Lamp },
+ };
+ var outputs = DofPluginFactory.WithConfigured(named, new[] { "s12", "W30", "E101", "L7", "$named" });
+ Assert.That(outputs.Select(o => o.Trigger), Is.EqualTo(new[] { "S12", "L45", "L7", "W30", "E101" }),
+ "the game's first, then what only the configuration names, coils, lamps, switches and events, without names of its own");
+ Assert.That(outputs.Select(o => o.Configured), Is.EqualTo(new[] { true, false, true, true, true }));
+ Assert.That(outputs.Select(o => o.Present), Is.EqualTo(new[] { true, true, false, true, true }),
+ "missing where the game lists others of the kind: not a switch or event it lists none of, which the table may fire itself");
+ Assert.That(outputs.Select(o => o.Listed), Is.EqualTo(new[] { true, true, false, false, false }), "the game's, not those only the configuration uses");
+ Assert.That(outputs.Select(o => o.Kind).Skip(2), Is.EqualTo(new[] { PluginGameOutputKind.Lamp, PluginGameOutputKind.Switch, PluginGameOutputKind.Other }));
+ Assert.That(DofPluginFactory.WithConfigured(System.Array.Empty(), new[] { "S1" }).Single().Present, Is.True,
+ "a game that lists nothing may have it");
+ }
+
+ private static void Rule(string part, System.Action check, string message = null)
+ {
+ var parse = DofTriggerSyntax.Parse(part);
+ Assert.That(parse.Problem, Is.Empty, message ?? part);
+ check(parse.Rules.Single());
+ Assert.That(DofTriggerSyntax.Format(parse.Rules), Is.EqualTo(part), "written as it was");
+ }
+ }
+}
diff --git a/VisualPinball.Engine.DOF.Unity/Tests/DofTriggerSyntaxTests.cs.meta b/VisualPinball.Engine.DOF.Unity/Tests/DofTriggerSyntaxTests.cs.meta
new file mode 100644
index 0000000..2ddac2f
--- /dev/null
+++ b/VisualPinball.Engine.DOF.Unity/Tests/DofTriggerSyntaxTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 9d43e248aae24a299aa2940dadcd2191
diff --git a/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs b/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs
index 714e59e..9ecc524 100644
--- a/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs
+++ b/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs
@@ -20,14 +20,21 @@ public sealed class DofCatalogDevice
public IReadOnlyList Ports { get; }
/// The ROM names of its rows, in file order.
public IReadOnlyList Roms { get; }
- /// The ports (from 1) where an RGB toy starts, which takes it and the next two; see .
+ /// The ports (from 1) where an RGB toy starts, which takes it and the next two; see , and
+ /// those of the cabinet's strips.
public IReadOnlyList RgbPorts { get; }
/// How many ports the file uses: the header's, or as far as a row reaches when that is further.
public int PortCount { get; }
+ /// The colours the file defines, which its settings name.
+ public IReadOnlyList Colors { get; }
+ /// Whether libdof loads the file: it skips one without colours or without rows.
+ public bool Loaded { get; }
internal DofCatalogDevice(int number, string fileName, IReadOnlyList ports, IReadOnlyList roms,
- IReadOnlyList rgbPorts = null, int portExtent = 0)
+ IReadOnlyList rgbPorts = null, int portExtent = 0, IReadOnlyList colors = null, bool loaded = true)
{
+ Loaded = loaded;
+ Colors = colors ?? Array.Empty();
Number = number;
FileName = fileName;
Ports = ports;
@@ -56,10 +63,16 @@ public sealed class DofCatalogController
/// another transport (a PinOne on HID).
///
public bool UsesSerialPort { get; }
+ ///
+ /// The number libdof tells the boards of its type apart by (the Number element, or the Id attribute of a Pac
+ /// board), as the file gives it; 0 when it doesn't.
+ ///
+ public int Number { get; }
- internal DofCatalogController(string type, string name, string serialPort, bool usesSerialPort = false)
+ internal DofCatalogController(string type, string name, string serialPort, bool usesSerialPort = false, int number = 0)
{
Type = type;
+ Number = number;
Named = name != null;
Name = name ?? type;
SerialPort = serialPort;
@@ -67,6 +80,27 @@ internal DofCatalogController(string type, string name, string serialPort, bool
}
}
+ /// An LED strip or matrix of the cabinet file, which an output of a LedWiz equivalent names.
+ public sealed class DofCatalogStrip
+ {
+ /// Its name, which the LedWiz equivalent's output names.
+ public string Name { get; }
+ /// How many LEDs it has across; 0 when the file doesn't say.
+ public int Width { get; }
+ /// How many LEDs it has down; 0 when the file doesn't say.
+ public int Height { get; }
+ /// How its LEDs run, such as TopDownLeftRight, as written; empty when the file doesn't say.
+ public string Arrangement { get; }
+
+ internal DofCatalogStrip(string name, int width, int height, string arrangement)
+ {
+ Name = name;
+ Width = width;
+ Height = height;
+ Arrangement = arrangement ?? "";
+ }
+ }
+
/// What a revision contains, for the settings UI and the per-game bindings.
public sealed class DofCatalog
{
@@ -101,6 +135,12 @@ public sealed class DofCatalog
///
public IReadOnlyDictionary CabinetOutputs { get; private set; } = new Dictionary();
+ ///
+ /// The LED strips and matrices the cabinet file's LedWiz equivalents put on their outputs, by ini device and output: a
+ /// setting on that port lights an area of it.
+ ///
+ public IReadOnlyDictionary<(int Device, int Port), DofCatalogStrip> CabinetStrips { get; private set; } = new Dictionary<(int, int), DofCatalogStrip>();
+
///
/// The highest output a cabinet file's LedWiz equivalent counts for: larger numbers are no controller's, and would
/// size a board beyond anything shown. The native output map has the same limit.
@@ -136,6 +176,7 @@ public static DofCatalog Load(DofRevision revision)
var cabinetControllers = new List();
var hasCabinet = false;
var cabinetOutputs = new Dictionary();
+ var cabinetStrips = new Dictionary<(int, int), DofCatalogStrip>();
var cabinetDevices = new SortedSet();
var mappings = new List>();
var legacy = new List();
@@ -160,12 +201,18 @@ public static DofCatalog Load(DofRevision revision)
var type = DofXml.LiteralName(controller);
var portElement = DofXml.SerialPortElement(type);
var serial = portElement != null && !(type == "PinOne" && DofXml.Value(controller, portElement) == "HID");
- cabinetControllers.Add(new DofCatalogController(type, DofXml.ControllerName(controller), DofXml.SerialPortOf(controller), serial));
+ // as libdof reads it: a Pac board's Id attribute, the others' Number element
+ var numberText = type.StartsWith("Pac", StringComparison.Ordinal) ? controller.Attribute("Id")?.Value : DofXml.Value(controller, "Number");
+ int.TryParse(numberText?.Trim(), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var number);
+ cabinetControllers.Add(new DofCatalogController(type, DofXml.ControllerName(controller), DofXml.SerialPortOf(controller), serial, number));
}
foreach (var (device, output) in LedWizEquivalentOutputs(xml)) {
cabinetOutputs[device] = Math.Max(output, cabinetOutputs.TryGetValue(device, out var known) ? known : 0);
}
cabinetDevices.UnionWith(CabinetDevices(xml));
+ foreach (var pair in Strips(xml)) {
+ cabinetStrips[pair.Key] = pair.Value;
+ }
break;
case DofXmlKind.TableMappings:
foreach (var mapping in DofXml.Children(xml.Root, "Mapping")) {
@@ -182,7 +229,23 @@ public static DofCatalog Load(DofRevision revision)
var inis = current.Count > 0 ? current : legacy;
var rows = new List();
foreach (var ini in inis.OrderBy(i => i.Device)) {
- devices.Add(new DofCatalogDevice(ini.Device, ini.Name, ini.PortNames, ini.Roms, ini.RgbPorts, ini.PortExtent));
+ // a strip of the cabinet takes three outputs like an RGB toy, also where the configuration lights nothing on it yet, and
+ // is named as the cabinet names it where the configuration doesn't: where the configuration leaves its green and blue
+ // free, as libdof takes an RGB toy (see DofIniFile.RgbPorts), and no RGB toy of it overlaps
+ var rgbPorts = new SortedSet(ini.RgbPorts);
+ var names = ini.PortNames.ToList();
+ var extent = ini.PortExtent;
+ foreach (var pair in cabinetStrips.Where(s => s.Key.Item1 == ini.Device).OrderBy(s => s.Key.Item2)) {
+ var port = pair.Key.Item2;
+ if (!rgbPorts.Contains(port) && (ini.PortInUse(port + 1) || ini.PortInUse(port + 2) || rgbPorts.Any(p => System.Math.Abs(p - port) <= 2))) {
+ continue;
+ }
+ rgbPorts.Add(port);
+ while (names.Count < port) names.Add("");
+ if (string.IsNullOrWhiteSpace(names[port - 1])) names[port - 1] = pair.Value.Name;
+ extent = Math.Max(extent, port + 2);
+ }
+ devices.Add(new DofCatalogDevice(ini.Device, ini.Name, names, ini.Roms, rgbPorts.ToList(), extent, ini.Colors, ini.HasColorSection && ini.HasConfigRows));
rows.AddRange(ini.Roms.Select(r => new DofRomRow(ini.Device, r)));
}
// libdof lists the ini files in directory order, which differs between file systems; a stable sort by device
@@ -191,6 +254,7 @@ public static DofCatalog Load(DofRevision revision)
return new DofCatalog(revision, devices, effective ?? rows, effective != null, mappings, revision.TableConfigs, cabinetControllers) {
HasCabinet = hasCabinet,
CabinetOutputs = cabinetOutputs,
+ CabinetStrips = cabinetStrips,
CabinetDevicesWithoutIni = cabinetDevices.Where(d => devices.All(i => i.Number != d)).ToList(),
LegacyInis = current.Count == 0 && legacy.Count > 0,
};
@@ -227,6 +291,39 @@ internal static IReadOnlyList CabinetDevices(System.Xml.Linq.XDocument xml)
.ToList();
}
+ /// The LED strips of a cabinet file, by the LedWiz equivalent outputs that name them.
+ internal static IReadOnlyDictionary<(int Device, int Port), DofCatalogStrip> Strips(System.Xml.Linq.XDocument xml)
+ {
+ var result = new Dictionary<(int, int), DofCatalogStrip>();
+ if (xml.Root == null || DofXml.LiteralName(xml.Root) != "Cabinet") {
+ return result;
+ }
+ var toys = DofXml.FirstChild(xml.Root, "Toys")?.Elements().ToList() ?? new List();
+ // by the name as written, as libdof tells its toys apart
+ var strips = new Dictionary(StringComparer.Ordinal);
+ foreach (var toy in toys.Where(t => DofXml.LiteralName(t) == "LedStrip")) {
+ var name = DofXml.Value(toy, "Name")?.Trim();
+ if (string.IsNullOrEmpty(name) || strips.ContainsKey(name)) {
+ continue;
+ }
+ int.TryParse(DofXml.Value(toy, "Width"), out var width);
+ int.TryParse(DofXml.Value(toy, "Height"), out var height);
+ strips[name] = new DofCatalogStrip(name, Math.Max(0, width), Math.Max(0, height), DofXml.Value(toy, "LedStripArrangement")?.Trim());
+ }
+ foreach (var toy in toys.Where(t => DofXml.LiteralName(t) == "LedWizEquivalent")) {
+ if (!int.TryParse(DofXml.Value(toy, "LedWizNumber"), out var device)) {
+ continue;
+ }
+ foreach (var output in DofXml.Children(DofXml.FirstChild(toy, "Outputs"), "LedWizEquivalentOutput")) {
+ if (int.TryParse(DofXml.Value(output, "LedWizEquivalentOutputNumber"), out var number) && number > 0 && number <= MaxCabinetOutput
+ && strips.TryGetValue(DofXml.Value(output, "OutputName")?.Trim() ?? "", out var strip)) {
+ result[(device, number)] = strip;
+ }
+ }
+ }
+ return result;
+ }
+
/// The outputs a cabinet file's LedWiz equivalents map, each with the ini device it stands for.
private static IEnumerable<(int Device, int Output)> LedWizEquivalentOutputs(System.Xml.Linq.XDocument xml)
{
diff --git a/VisualPinball.Engine.DOF/Configuration/DofColor.cs b/VisualPinball.Engine.DOF/Configuration/DofColor.cs
new file mode 100644
index 0000000..38d01dc
--- /dev/null
+++ b/VisualPinball.Engine.DOF/Configuration/DofColor.cs
@@ -0,0 +1,68 @@
+// Visual Pinball Engine
+// Copyright (C) 2026 freezy and VPE Team
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+using System;
+using System.Globalization;
+using System.Linq;
+
+namespace VisualPinball.Engine.DOF.Configuration
+{
+ /// A colour an ini file defines, which its settings name.
+ public readonly struct DofColor
+ {
+ public string Name { get; }
+ public byte Red { get; }
+ public byte Green { get; }
+ public byte Blue { get; }
+
+ public DofColor(string name, byte red, byte green, byte blue)
+ {
+ Name = name;
+ Red = red;
+ Green = green;
+ Blue = blue;
+ }
+
+ ///
+ /// Reads a line of a colour section as libdof does (ColorConfig): Name=#RRGGBB or #RRGGBBAA, or
+ /// Name=r,g,b or r,g,b,a, each from 0 to 48.
+ ///
+ public static bool TryParse(string line, out DofColor color)
+ {
+ color = default;
+ var eq = line?.IndexOf('=') ?? -1;
+ if (eq <= 0) {
+ return false;
+ }
+ var name = line.Substring(0, eq).Trim();
+ var value = line.Substring(eq + 1).Trim();
+ if (name.Length == 0) {
+ return false;
+ }
+ if (value.StartsWith("#", StringComparison.Ordinal)) {
+ if ((value.Length != 7 && value.Length != 9) || !value.Skip(1).All(Uri.IsHexDigit)) {
+ return false;
+ }
+ color = new DofColor(name, Hex(value, 1), Hex(value, 3), Hex(value, 5));
+ return true;
+ }
+ var parts = value.Split(',');
+ if (parts.Length != 3 && parts.Length != 4) {
+ return false;
+ }
+ var levels = new byte[3];
+ for (var i = 0; i < 3; i++) {
+ if (!int.TryParse(parts[i].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var level)) {
+ return false;
+ }
+ levels[i] = (byte)(Math.Min(48, Math.Max(0, level)) * 5.3125);
+ }
+ color = new DofColor(name, levels[0], levels[1], levels[2]);
+ return true;
+ }
+
+ private static byte Hex(string value, int at) => byte.Parse(value.Substring(at, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
+ }
+}
diff --git a/VisualPinball.Engine.DOF/Configuration/DofConfigStore.cs b/VisualPinball.Engine.DOF/Configuration/DofConfigStore.cs
index c9edbe4..40c66f2 100644
--- a/VisualPinball.Engine.DOF/Configuration/DofConfigStore.cs
+++ b/VisualPinball.Engine.DOF/Configuration/DofConfigStore.cs
@@ -18,13 +18,13 @@ namespace VisualPinball.Engine.DOF.Configuration
/// Layout:
///
/// <root>/revisions/<id>/ one revision each (see )
- /// <root>/revisions.txt "active=<id>" and "previous=<id>" (the revision active before, for )
+ /// <root>/revisions.txt "active=<id>"
/// <root>/staging/ imports in progress
///
/// Switching revisions replaces the one pointer file in one step, so a failure or a crash leaves either the old or
- /// the new pair of revisions in place. A game holds a lease on the revision it started with ():
- /// imports and rollbacks apply to the next game, and a leased revision is never deleted, nor is one an import is
- /// still writing or checking.
+ /// the new revision in place. An import replaces the active revision, which is deleted then; there is no going back.
+ /// A game holds a lease on the revision it started with (): imports and clearing apply to the
+ /// next game, and a leased revision is never deleted, nor is one an import is still writing or checking.
///
public sealed class DofConfigStore
{
@@ -57,17 +57,7 @@ public DofRevision Active
{
get {
lock (_lock) {
- return Revision(ReadPointers().active);
- }
- }
- }
-
- /// The revision returns to, or null.
- public DofRevision Previous
- {
- get {
- lock (_lock) {
- return Revision(ReadPointers().previous);
+ return Revision(ReadPointers());
}
}
}
@@ -89,7 +79,7 @@ public DofRevision Previous
private DofRevisionLease Acquire(bool prune)
{
lock (_lock) {
- var revision = Revision(ReadPointers().active);
+ var revision = Revision(ReadPointers());
if (revision == null) {
return null;
}
@@ -115,18 +105,26 @@ internal void Release(DofRevision revision, bool prune)
}
}
- /// Makes the previous revision active again. The current one becomes the previous one.
- /// False if there is no previous revision.
- public bool Rollback()
+ ///
+ /// Removes the configuration: nothing is active then, and the revision is deleted once no game holds it. DOF drives
+ /// nothing from the next game until something is imported.
+ ///
+ ///
+ /// The revision that must be the active one, or null for any: false and nothing changes when another one is, such as
+ /// one an import activated meanwhile.
+ ///
+ /// False when nothing was active, or not the revision expected.
+ public bool Clear(string expectedActive = null)
{
lock (_lock) {
- var (active, previous) = ReadPointers();
- if (previous == null || Revision(previous) == null) {
+ var active = ReadPointers();
+ if (active == null || (expectedActive != null && active != expectedActive)) {
return false;
}
- WritePointers(previous, active);
- return true;
+ WritePointers(null);
}
+ Prune();
+ return true;
}
///
@@ -152,25 +150,34 @@ internal DofRevision CreateRevision()
}
///
- /// Makes a revision active; the active one becomes the previous one, older ones are deleted unless leased. Both
- /// change in one step: if it throws, nothing changed.
+ /// Makes a revision active; the one active before is deleted unless leased. The pointer changes in one step: if it
+ /// throws, nothing changed.
///
- internal void Activate(DofRevision revision)
+ /// The revision to make active.
+ ///
+ /// The revision that must be the active one, empty for none, or null for any: false and nothing changes when another
+ /// one is, such as one another Player sharing the folder activated meanwhile.
+ ///
+ internal bool Activate(DofRevision revision, string expectedActive = null, System.Threading.CancellationToken cancellation = default)
{
lock (_lock) {
- var (active, previous) = ReadPointers();
- WritePointers(revision.Id, active != null && active != revision.Id ? active : previous);
+ var active = ReadPointers();
+ // under the lock: what is stopped now never becomes active
+ if (cancellation.IsCancellationRequested || (expectedActive != null && (active ?? "") != expectedActive)) {
+ return false;
+ }
+ WritePointers(revision.Id);
_pending.Remove(revision.Id);
}
Prune();
+ return true;
}
/// Deletes a revision an import created and did not activate.
internal void Discard(DofRevision revision)
{
lock (_lock) {
- var (active, previous) = ReadPointers();
- if (revision.Id == active || revision.Id == previous) {
+ if (revision.Id == ReadPointers()) {
// It was published after all: deleting it would leave the pointer on a missing folder.
_pending.Remove(revision.Id);
return;
@@ -187,7 +194,7 @@ internal string CreateStaging()
return path;
}
- /// Deletes revisions that are neither active, previous nor leased, and staging folders left by a crash.
+ /// Deletes revisions that are neither active nor leased, nor still being imported.
public void Prune()
{
lock (_pruneLock) {
@@ -198,17 +205,14 @@ public void Prune()
}
var keep = new HashSet(_leases.Keys, StringComparer.Ordinal);
keep.UnionWith(_pending);
- var (active, previous) = ReadPointers();
+ var active = ReadPointers();
if (active != null) {
keep.Add(active);
}
- if (previous != null) {
- keep.Add(previous);
- }
remove = Directory.GetDirectories(RevisionsDir).Where(d => !keep.Contains(Path.GetFileName(d))).ToList();
}
// Outside the store's lock, so leases and imports do not wait for the deletion. A revision created
- // meanwhile has a name no listed folder had, and a listed one never becomes active or previous again.
+ // meanwhile has a name no listed folder had, and a listed one never becomes active again.
foreach (var dir in remove) {
TryDelete(dir);
}
@@ -234,25 +238,21 @@ private DofRevision Revision(string id)
return Directory.Exists(Path.Combine(path, DofRevision.ConfigFolder)) ? new DofRevision(id, path) : null;
}
- private (string active, string previous) ReadPointers()
+ /// The active revision's id, or null. A "previous" line of an older Player is ignored, and its revision pruned.
+ private string ReadPointers()
{
var path = Path.Combine(Root, PointerFile);
if (!File.Exists(path)) {
- return (null, null);
+ return null;
}
- string active = null, previous = null;
+ string active = null;
foreach (var line in File.ReadAllLines(path)) {
var separator = line.IndexOf('=');
- if (separator <= 0) {
- continue;
- }
- var id = Id(line.Substring(separator + 1));
- switch (line.Substring(0, separator).Trim()) {
- case "active": active = id; break;
- case "previous": previous = id; break;
+ if (separator > 0 && line.Substring(0, separator).Trim() == "active") {
+ active = Id(line.Substring(separator + 1));
}
}
- return (active, previous);
+ return active;
// An id is a folder name the store created; anything else is not followed.
string Id(string value)
@@ -263,12 +263,12 @@ string Id(string value)
}
/// Replaces the pointer file in one step.
- private void WritePointers(string active, string previous)
+ private void WritePointers(string active)
{
Directory.CreateDirectory(Root);
var path = Path.Combine(Root, PointerFile);
var temp = path + ".tmp";
- File.WriteAllText(temp, $"active={active}\nprevious={previous}\n");
+ File.WriteAllText(temp, $"active={active}\n");
if (File.Exists(path)) {
File.Replace(temp, path, null);
} else {
diff --git a/VisualPinball.Engine.DOF/Configuration/DofConfigToolClient.cs b/VisualPinball.Engine.DOF/Configuration/DofConfigToolClient.cs
new file mode 100644
index 0000000..eb5404a
--- /dev/null
+++ b/VisualPinball.Engine.DOF/Configuration/DofConfigToolClient.cs
@@ -0,0 +1,219 @@
+// Visual Pinball Engine
+// Copyright (C) 2026 freezy and VPE Team
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+using System;
+using System.IO;
+using System.IO.Compression;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace VisualPinball.Engine.DOF.Configuration
+{
+ ///
+ /// Downloads a cabinet's configuration from the DOF Config Tool with the cabinet's API key, through the Config Tool's
+ /// getconfig query: the zip a browser downloads, made from the cabinet's settings on the site. It sends the key
+ /// and nothing else, and only when asked.
+ ///
+ ///
+ /// The Config Tool answers an unknown key with 401. Its other query, version, only counts changes of the public
+ /// database, not of the user's own cabinet, so it can't tell whether a download would bring anything new.
+ ///
+ public sealed class DofConfigToolClient : IDisposable
+ {
+ public const string ApiUrl = "https://configtool.vpuniverse.com/api.php";
+ /// Where a download came from, as the configuration's details name it.
+ public const string Origin = "the DOF Config Tool";
+
+ private const int MaxKeyLength = 256;
+ private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(60);
+
+ private readonly HttpClient _http;
+ private readonly TimeSpan _timeout;
+
+ /// The largest download taken, in bytes; the importer's limit of a single file.
+ public long MaxBytes { get; set; } = new DofImportLimits().MaxFileBytes;
+
+ /// What the requests say they come from, such as VisualPinballEngine/0.1.
+ ///
+ /// What sends the requests, which stays the caller's to dispose; when null, the system's, which follows no redirect
+ /// (the key would go along) and takes compressed answers.
+ ///
+ /// How long a download may take from the request to its last byte; a minute when null.
+ public DofConfigToolClient(string userAgent, HttpMessageHandler handler = null, TimeSpan? timeout = null)
+ {
+ _http = handler != null
+ ? new HttpClient(handler, false)
+ : new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
+ // one deadline for the whole download, the body included, instead of HttpClient's for the headers
+ _timeout = timeout ?? RequestTimeout;
+ _http.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
+ if (!string.IsNullOrWhiteSpace(userAgent)) {
+ _http.DefaultRequestHeaders.UserAgent.TryParseAdd(userAgent);
+ }
+ }
+
+ public void Dispose() => _http.Dispose();
+
+ /// Why a key can't be sent, or null if it can. A key is trimmed first.
+ public static string CheckKey(string key)
+ {
+ key = key?.Trim() ?? "";
+ if (key.Length == 0) {
+ return "Enter your cabinet's API key. The DOF Config Tool shows it on its Cabinets page.";
+ }
+ if (key.Length > MaxKeyLength || key.Any(c => char.IsWhiteSpace(c) || char.IsControl(c))) {
+ return "That isn't an API key: a key is one word. Copy it again from the Cabinets page of the DOF Config Tool.";
+ }
+ return null;
+ }
+
+ /// Downloads the configuration zip of the cabinet whose API key this is.
+ /// The zip's bytes.
+ /// The key is refused, the Config Tool can't be reached, or it sent no zip; the message says so for the user.
+ /// The cancellation token was cancelled.
+ public async Task DownloadAsync(string apiKey, CancellationToken cancellation = default)
+ {
+ var key = apiKey?.Trim() ?? "";
+ var problem = CheckKey(key);
+ if (problem != null) {
+ throw new DofException(DofStatus.InvalidArgument, problem);
+ }
+ var url = ApiUrl + "?query=getconfig&apikey=" + Uri.EscapeDataString(key);
+ using (var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation)) {
+ deadline.CancelAfter(_timeout);
+ try {
+ return await DownloadAsync(url, key, deadline.Token).ConfigureAwait(false);
+ } catch (Exception e) when (!cancellation.IsCancellationRequested && deadline.IsCancellationRequested
+ && (e is OperationCanceledException || e is ObjectDisposedException || e is IOException || e is HttpRequestException || e is WebException)) {
+ throw new DofException(DofStatus.Error, "The DOF Config Tool didn't send the configuration in time. Try again later.");
+ } catch (Exception e) when (cancellation.IsCancellationRequested && !(e is OperationCanceledException)) {
+ // aborting the response ends a read with whatever the stream throws
+ throw new OperationCanceledException(cancellation);
+ }
+ }
+ }
+
+ private async Task DownloadAsync(string url, string key, CancellationToken cancellation)
+ {
+ HttpResponseMessage response;
+ try {
+ response = await _http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation).ConfigureAwait(false);
+ } catch (Exception e) when (!cancellation.IsCancellationRequested && (e is HttpRequestException || e is WebException)) {
+ throw new DofException(DofStatus.Error, "Could not reach the DOF Config Tool: " + Redact(Innermost(e), key));
+ }
+ using (response)
+ // a body that stops coming doesn't end a read on every runtime: the response is let go of when the time is up
+ using (cancellation.Register(response.Dispose)) {
+ var status = (int)response.StatusCode;
+ if (response.StatusCode == HttpStatusCode.Unauthorized) {
+ throw new DofException(DofStatus.InvalidArgument, "The DOF Config Tool doesn't know this API key. Copy it again from its Cabinets page: "
+ + "a key made there anew replaces the old one.");
+ }
+ if (status == 403 || status == 429 || response.Headers.Contains("cf-mitigated")) {
+ throw new DofException(DofStatus.Error, "The DOF Config Tool turned the download away. Download directoutputconfig.zip with your browser "
+ + "and import it below.");
+ }
+ if (!response.IsSuccessStatusCode) {
+ // the status alone: the reason phrase is the server's text
+ throw new DofException(DofStatus.Error, $"The DOF Config Tool answered with status {status}. Try again later, or download "
+ + "directoutputconfig.zip with your browser and import it below.");
+ }
+ if (response.Content.Headers.ContentLength > MaxBytes) {
+ throw new DofException(DofStatus.Error, TooLarge());
+ }
+ byte[] bytes;
+ try {
+ using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) {
+ bytes = await ReadAtMost(stream, MaxBytes, cancellation).ConfigureAwait(false);
+ }
+ } catch (Exception e) when (!cancellation.IsCancellationRequested && (e is IOException || e is HttpRequestException || e is WebException || e is InvalidDataException)) {
+ throw new DofException(DofStatus.Error, "The download from the DOF Config Tool broke off: " + Redact(Innermost(e), key));
+ }
+ // a body cut short by the deadline may read as complete
+ cancellation.ThrowIfCancellationRequested();
+ if (bytes == null) {
+ throw new DofException(DofStatus.Error, TooLarge());
+ }
+ if (bytes.Length < 4 || bytes[0] != (byte)'P' || bytes[1] != (byte)'K') {
+ var said = Said(bytes, key);
+ throw new DofException(DofStatus.Error, "The DOF Config Tool sent no configuration" + (said.Length > 0 ? ": " + said : "."));
+ }
+ if (!HasIni(bytes)) {
+ // a zip of the Config Tool always has them: without, the import would keep the ones of before and say it imported
+ throw new DofException(DofStatus.Error, "The DOF Config Tool sent a zip without DOF ini files. Check your cabinet's settings in the Config Tool.");
+ }
+ return bytes;
+ }
+ }
+
+ private string TooLarge() => $"The download from the DOF Config Tool is larger than {MaxBytes / (1024 * 1024)} MB, more than a configuration is.";
+
+ /// The stream's bytes, or null if there are more than .
+ private static async Task ReadAtMost(Stream stream, long max, CancellationToken cancellation)
+ {
+ using (var memory = new MemoryStream()) {
+ var buffer = new byte[81920];
+ int read;
+ while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, cancellation).ConfigureAwait(false)) > 0) {
+ if (memory.Length + read > max) {
+ return null;
+ }
+ memory.Write(buffer, 0, read);
+ }
+ return memory.ToArray();
+ }
+ }
+
+ /// Whether a zip has a DOF ini file (directoutputconfig.ini or directoutputconfigN.ini) somewhere; false if it isn't one.
+ private static bool HasIni(byte[] bytes)
+ {
+ try {
+ using (var zip = new ZipArchive(new MemoryStream(bytes, false), ZipArchiveMode.Read)) {
+ return zip.Entries.Any(e => e.Name.StartsWith("directoutputconfig", StringComparison.OrdinalIgnoreCase)
+ && e.Name.EndsWith(".ini", StringComparison.OrdinalIgnoreCase));
+ }
+ } catch (InvalidDataException) {
+ return false;
+ }
+ }
+
+ /// What a text answer says, short and on one line, such as the Config Tool's API errors.
+ private static string Said(byte[] bytes, string key)
+ {
+ // all of it, without the key, before it is cut: a cut can't leave a part of the key
+ var text = Redact(Encoding.UTF8.GetString(bytes), key);
+ if (text.TrimStart().StartsWith("<", StringComparison.Ordinal)) {
+ // a web page, not an answer of the API
+ return "";
+ }
+ text = new string(text.Take(300).Select(c => char.IsControl(c) ? ' ' : c).ToArray()).Trim();
+ if (text.Length > 200) {
+ text = text.Substring(0, 200) + "…";
+ }
+ return text;
+ }
+
+ private static string Innermost(Exception e)
+ {
+ while (e.InnerException != null) {
+ e = e.InnerException;
+ }
+ return e.Message;
+ }
+
+ /// A message without the key, should it name the address.
+ private static string Redact(string message, string key)
+ {
+ if (string.IsNullOrEmpty(message) || string.IsNullOrEmpty(key)) {
+ return message ?? "";
+ }
+ return message.Replace(key, "…").Replace(Uri.EscapeDataString(key), "…");
+ }
+ }
+}
diff --git a/VisualPinball.Engine.DOF/Configuration/DofGameConfig.cs b/VisualPinball.Engine.DOF/Configuration/DofGameConfig.cs
index 3a541ff..8eb098f 100644
--- a/VisualPinball.Engine.DOF/Configuration/DofGameConfig.cs
+++ b/VisualPinball.Engine.DOF/Configuration/DofGameConfig.cs
@@ -33,9 +33,11 @@ public static class DofGameConfig
/// The rows the game uses, one per device ().
/// What the user changed.
/// Gets a line per change that could not be made, such as a row that changed since.
+ /// The toys the user added, which tell their RGB toys.
/// The base path for libdof, or null when the user changed none of the rows, so the game uses the revision.
/// The copy can't be written, such as when another game still uses it.
- public static string Build(DofRevision revision, DofCatalog catalog, string root, IEnumerable rows, DofGameTriggers triggers, List problems)
+ public static string Build(DofRevision revision, DofCatalog catalog, string root, IEnumerable rows, DofGameTriggers triggers, List problems,
+ DofToyNames names = null)
{
var changes = (rows ?? Enumerable.Empty())
.Select(r => (Row: r, Settings: (triggers ?? DofGameTriggers.None).Of(r.Rom, r.Device)))
@@ -62,7 +64,7 @@ public static string Build(DofRevision revision, DofCatalog catalog, string root
if (changed == null) {
continue;
}
- var rgb = RgbStarts(device);
+ var rgb = RgbStarts(device, names);
foreach (var (port, setting) in settings) {
var next = Change(changed, rgb, port, setting, out var problem);
if (next == null) {
@@ -114,6 +116,21 @@ public static ISet RgbStarts(DofCatalogDevice device)
return starts;
}
+ ///
+ /// The ports where an RGB toy starts, as , with the RGB toys the user added past
+ /// every port the configuration uses (a configuration that came to use their ports takes them).
+ ///
+ public static ISet RgbStarts(DofCatalogDevice device, DofToyNames names)
+ {
+ var starts = RgbStarts(device);
+ foreach (var port in (names ?? DofToyNames.None).RgbPortsOf(device.Number)) {
+ if (port > device.PortCount) {
+ starts.Add(port);
+ }
+ }
+ return starts;
+ }
+
///
/// A row with the toy on a port fired by the user's setting, made fit for the toy as the configuration has it now: an
/// import may have made an RGB toy of a single one, or put the green or blue of one on the port. Null with why not.
diff --git a/VisualPinball.Engine.DOF/Configuration/DofGameTriggers.cs b/VisualPinball.Engine.DOF/Configuration/DofGameTriggers.cs
index a5cbe76..eea6a14 100644
--- a/VisualPinball.Engine.DOF/Configuration/DofGameTriggers.cs
+++ b/VisualPinball.Engine.DOF/Configuration/DofGameTriggers.cs
@@ -60,6 +60,17 @@ public DofGameTriggers With(string row, int device, int port, string setting)
return new DofGameTriggers(settings);
}
+ /// These triggers with those of the rows given as another has them, such as one game's as they were before.
+ public DofGameTriggers WithRowsOf(DofGameTriggers other, IEnumerable rows)
+ {
+ var names = new HashSet((rows ?? Enumerable.Empty()).Select(row => (row ?? "").Trim()), Key.Rows);
+ var settings = _settings.Where(e => !names.Contains(e.Key.Row)).ToDictionary(e => e.Key, e => e.Value);
+ foreach (var entry in other._settings.Where(e => names.Contains(e.Key.Row))) {
+ settings[entry.Key] = entry.Value;
+ }
+ return new DofGameTriggers(settings);
+ }
+
/// Reads the triggers of a store's folder; none when it has no file. A line that names no toy is left out.
public static DofGameTriggers Load(string root)
{
@@ -67,11 +78,20 @@ public static DofGameTriggers Load(string root)
if (Directory.Exists(path)) {
throw new IOException(path + " is a folder, not the game triggers.");
}
- if (!File.Exists(path)) {
+ return File.Exists(path) ? Parse(File.ReadAllText(path, Encoding.UTF8)) : None;
+ }
+
+ /// Reads the triggers as the file has them; none for null. A line that names no toy is left out.
+ public static DofGameTriggers Parse(string text)
+ {
+ if (string.IsNullOrEmpty(text)) {
return None;
}
var settings = new Dictionary();
- foreach (var line in File.ReadAllLines(path, Encoding.UTF8)) {
+ // as the file reads: without a byte order mark, and its lines however they end
+ using var reader = new StringReader(text[0] == '' ? text.Substring(1) : text);
+ string line;
+ while ((line = reader.ReadLine()) != null) {
var parts = line.Split('\t');
if (parts.Length != 4 || parts[0].Trim().Length == 0
|| !int.TryParse(parts[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var device)
@@ -84,6 +104,20 @@ public static DofGameTriggers Load(string root)
return new DofGameTriggers(settings);
}
+ /// The triggers as the file has them, one toy a line, in order.
+ public string Text
+ {
+ get
+ {
+ var text = new StringBuilder();
+ foreach (var entry in _settings.OrderBy(e => e.Key.Row, StringComparer.OrdinalIgnoreCase).ThenBy(e => e.Key.Device).ThenBy(e => e.Key.Port)) {
+ text.Append(entry.Key.Row).Append('\t').Append(entry.Key.Device.ToString(CultureInfo.InvariantCulture)).Append('\t')
+ .Append(entry.Key.Port.ToString(CultureInfo.InvariantCulture)).Append('\t').Append(entry.Value).Append('\n');
+ }
+ return text.ToString();
+ }
+ }
+
/// Replaces the triggers file of a store's folder in one step; deletes it when nothing is changed.
public void Save(string root)
{
@@ -95,13 +129,8 @@ public void Save(string root)
return;
}
Directory.CreateDirectory(root);
- var text = new StringBuilder();
- foreach (var entry in _settings.OrderBy(e => e.Key.Row, StringComparer.OrdinalIgnoreCase).ThenBy(e => e.Key.Device).ThenBy(e => e.Key.Port)) {
- text.Append(entry.Key.Row).Append('\t').Append(entry.Key.Device.ToString(CultureInfo.InvariantCulture)).Append('\t')
- .Append(entry.Key.Port.ToString(CultureInfo.InvariantCulture)).Append('\t').Append(entry.Value).Append('\n');
- }
var temp = path + ".tmp";
- File.WriteAllText(temp, text.ToString(), new UTF8Encoding(false));
+ File.WriteAllText(temp, Text, new UTF8Encoding(false));
if (File.Exists(path)) {
File.Replace(temp, path, null);
} else {
diff --git a/VisualPinball.Engine.DOF/Configuration/DofImporter.cs b/VisualPinball.Engine.DOF/Configuration/DofImporter.cs
index ed1c772..04105c7 100644
--- a/VisualPinball.Engine.DOF/Configuration/DofImporter.cs
+++ b/VisualPinball.Engine.DOF/Configuration/DofImporter.cs
@@ -10,6 +10,7 @@
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
+using System.Threading;
using System.Xml.Linq;
namespace VisualPinball.Engine.DOF.Configuration
@@ -93,6 +94,45 @@ public DofImporter(DofConfigStore store)
/// without a serial port, is reported and skipped.
///
public DofImportReport Import(string source, DofImportMode mode, IReadOnlyDictionary serialOverrides)
+ => Import(source, mode, serialOverrides, null, CancellationToken.None);
+
+ ///
+ /// Imports a Config Tool zip that was downloaded rather than chosen as a file, such as with the cabinet's API key
+ /// (see ). It is merged as a zip the user imports is.
+ ///
+ /// The zip's bytes.
+ /// Where it came from, for the configuration's details, such as .
+ /// As for .
+ /// Stops the import before it becomes the active configuration.
+ public DofImportReport ImportDownload(byte[] zip, string origin, IReadOnlyDictionary serialOverrides, CancellationToken cancellation = default)
+ {
+ // a download, named or not: it has to bring ini files
+ origin = string.IsNullOrWhiteSpace(origin) ? "the download" : origin;
+ if (zip == null || zip.Length == 0) {
+ var empty = new DofImportReport { Origin = origin };
+ empty.Error("The download is empty.");
+ return empty;
+ }
+ string holder = null;
+ try {
+ holder = _store.CreateStaging();
+ var path = Path.Combine(holder, "directoutputconfig.zip");
+ File.WriteAllBytes(path, zip);
+ return Import(path, DofImportMode.Merge, serialOverrides, origin, cancellation);
+ } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) {
+ var failed = new DofImportReport { Origin = origin };
+ failed.Error($"Keeping the download failed: {e.Message}");
+ return failed;
+ } finally {
+ if (holder != null) {
+ DofConfigStore.TryDelete(holder);
+ }
+ }
+ }
+
+ /// Where a downloaded zip came from, which the report names instead of the file it was kept in; null for a file of the user.
+ private DofImportReport Import(string source, DofImportMode mode, IReadOnlyDictionary serialOverrides, string downloadedFrom,
+ CancellationToken cancellation)
{
var report = new DofImportReport();
if (string.IsNullOrEmpty(source) || (!File.Exists(source) && !Directory.Exists(source))) {
@@ -104,9 +144,14 @@ public DofImportReport Import(string source, DofImportMode mode, IReadOnlyDictio
if (name.Length == 0) {
name = source;
}
- report.Origin = Directory.Exists(source) ? $"the folder {name}" : name;
- // the whole path: a report must tell which of two folders of the same name it was
- report.Info(DofReportTopic.Files, $"Imported from {Path.GetFullPath(source)}.");
+ if (downloadedFrom != null) {
+ report.Origin = downloadedFrom;
+ report.Info(DofReportTopic.Files, $"Downloaded from {downloadedFrom}.");
+ } else {
+ report.Origin = Directory.Exists(source) ? $"the folder {name}" : name;
+ // the whole path: a report must tell which of two folders of the same name it was
+ report.Info(DofReportTopic.Files, $"Imported from {Path.GetFullPath(source)}.");
+ }
var staging = _store.CreateStaging();
try {
var input = Path.Combine(staging, "in");
@@ -126,7 +171,14 @@ public DofImportReport Import(string source, DofImportMode mode, IReadOnlyDictio
if (report.HasErrors) {
return report;
}
- var active = _store.Active;
+ if (downloadedFrom != null && imported.Inis.Count == 0) {
+ // a zip of the Config Tool always has them: without, the merge would keep the ones of before and say it imported
+ report.Error($"The download from {downloadedFrom} has no DOF ini file (directoutputconfig.ini or directoutputconfigN.ini) to import.");
+ return report;
+ }
+ // held until Write copied them: an import published meanwhile must not prune the revision the merge keeps files of
+ using var lease = _store.AcquireForReading();
+ var active = lease?.Revision;
var config = Merge(imported, mode == DofImportMode.Merge ? active : null, active != null, report);
if (report.HasErrors) {
return report;
@@ -146,7 +198,12 @@ public DofImportReport Import(string source, DofImportMode mode, IReadOnlyDictio
// Write adds it here, once libdof accepted the configuration: a rejected one leaves the previous one in use.
// Ahead of what validation adds: the import's confirmation shows the first warning.
var replaced = mode == DofImportMode.Replace && active != null ? Replaced(active, config) : null;
- Write(config, report, replaced, report.Entries.Count);
+ if (cancellation.IsCancellationRequested) {
+ // nobody waits for it any more, such as the settings that were left
+ report.Error(Stopped);
+ return report;
+ }
+ Write(config, report, replaced, report.Entries.Count, cancellation: cancellation, retained: lease);
return report;
} catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is InvalidDataException || e is DofException) {
report.Error($"Reading the import failed: {e.Message}");
@@ -194,6 +251,8 @@ public DofImportReport ApplySerialOverrides(IReadOnlyDictionary
}
}
+ private const string Stopped = "The import was stopped.";
+
///
/// Sets the serial port of the cabinet's controllers in a copy of the cabinet file in the staging folder. Strict, a
/// controller that can't take its port is an error and nothing is set; otherwise it is a warning and skipped.
@@ -920,6 +979,14 @@ private static ConfigSet Merge(ConfigSet imported, DofRevision previous, bool ha
if (old.Inis.Count > 0) {
kept.Add("the ini files");
}
+ } else {
+ // the ini files go together: a device the import has none for is no longer driven
+ var dropped = old.Inis.Keys.Where(device => !imported.Inis.ContainsKey(device)).ToList();
+ if (dropped.Count > 0) {
+ // said before the import is checked: it may still be refused
+ report.Warning(DofReportTopic.Files, "Once imported, " + (dropped.Count == 1 ? $"device {dropped[0]} is" : $"devices {string.Join(", ", dropped)} are")
+ + " no longer configured: the import has no ini file for " + (dropped.Count == 1 ? "it" : "them") + ", and its ini files replace all of the previous ones.");
+ }
}
if (imported.GlobalConfig == null && old.GlobalConfig != null) {
imported.GlobalConfig = old.GlobalConfig;
@@ -983,7 +1050,7 @@ private static string Replaced(DofRevision active, ConfigSet config)
return null;
}
return $"Importing a folder replaces the whole configuration: {string.Join(", ", dropped)} of the previous one ({origin}) "
- + "are no longer used. \"Undo last import\" brings them back.";
+ + "are no longer used.";
}
/// The files of an existing revision as a configuration set, for merging.
@@ -1034,6 +1101,8 @@ private static void Analyse(ConfigSet config, bool windowsPorts, DofImportReport
foreach (var ini in config.Inis.Values) {
if (!ini.Ini.HasColorSection) {
report.Warning(DofReportTopic.General, $"{ini.Name} has no colours ([Colors DOF] section), so DOF skips the whole file and device {ini.Ini.Device} stays dark.");
+ } else if (!ini.Ini.HasConfigRows) {
+ report.Warning(DofReportTopic.General, $"{ini.Name} has no rows in its [Config DOF] section (or [Config outs] without one), so DOF skips the whole file and device {ini.Ini.Device} stays dark.");
}
if (!ini.Ini.HasVersionSection) {
report.Warning(DofReportTopic.General, $"{ini.Name} has no [version] section; it may be an old or hand-made file.");
@@ -1205,7 +1274,12 @@ private static void AnalyseRomMatching(IReadOnlyList rows, DofImportR
/// A warning that only holds once the revision is active, see .
/// Where in the report it goes.
- private void Write(ConfigSet config, DofImportReport report, string replaced = null, int replacedAt = 0)
+ ///
+ /// The lease on the revision the configuration keeps files of, released once they are copied: the revision this one
+ /// replaces is pruned once it is published.
+ ///
+ private void Write(ConfigSet config, DofImportReport report, string replaced = null, int replacedAt = 0, CancellationToken cancellation = default,
+ IDisposable retained = null)
{
var revision = _store.CreateRevision();
var published = false;
@@ -1249,6 +1323,7 @@ private void Write(ConfigSet config, DofImportReport report, string replaced = n
Directory.CreateDirectory(source);
File.Copy(config.GlobalConfig.Path, Path.Combine(source, DofGlobalConfig.FileName));
}
+ retained?.Dispose();
XDocument global;
try {
global = DofGlobalConfig.Build(config.GlobalConfig?.Xml, revision.ConfigDir, revision.TablesDir, cabinetName, shapesName);
@@ -1278,7 +1353,10 @@ private void Write(ConfigSet config, DofImportReport report, string replaced = n
if (!string.IsNullOrEmpty(report.Origin)) {
File.WriteAllText(Path.Combine(revision.BasePath, DofRevision.OriginFile), report.Origin, new UTF8Encoding(false));
}
- _store.Activate(revision);
+ if (!_store.Activate(revision, cancellation: cancellation)) {
+ report.Error(Stopped);
+ return;
+ }
published = true;
report.Revision = revision.Id;
} finally {
diff --git a/VisualPinball.Engine.DOF/Configuration/DofIniFile.cs b/VisualPinball.Engine.DOF/Configuration/DofIniFile.cs
index 057e992..573c366 100644
--- a/VisualPinball.Engine.DOF/Configuration/DofIniFile.cs
+++ b/VisualPinball.Engine.DOF/Configuration/DofIniFile.cs
@@ -46,12 +46,25 @@ public sealed class DofIniFile
public IReadOnlyList RgbPorts { get; private set; } = Array.Empty();
/// The last port (from 1) the header names or a row reaches, counted like ; 0 without either.
public int PortExtent { get; private set; }
+ // the ports (from 1) where a row puts a setting libdof keeps
+ private HashSet _usedPorts = new();
+
+ /// Whether the configuration takes a port (from 1): the header names it, or a row puts a setting on it that libdof keeps.
+ public bool PortInUse(int port) => port >= 1 && (port <= PortNames.Count && !string.IsNullOrWhiteSpace(PortNames[port - 1]) || _usedPorts.Contains(port));
/// Sections libdof does not know; their lines are ignored.
public IReadOnlyList UnknownSections { get; private set; } = Array.Empty();
public bool HasVersionSection { get; private set; }
/// Whether the file has a [Colors DOF] or [Colors LedWiz] section. Without one, DOF skips the whole file.
public bool HasColorSection { get; private set; }
+ /// Whether the config section libdof reads has a line. Without one, DOF skips the whole file.
+ public bool HasConfigRows { get; private set; }
+ ///
+ /// The colours its colour sections define, in file order, the first of a name only: Name=#RRGGBB, or
+ /// Name=r,g,b with each from 0 to 48, as libdof reads them (ColorConfig).
+ ///
+ public IReadOnlyList Colors { get; private set; } = Array.Empty();
+
private DofIniFile(string name, int device, bool legacy)
{
Name = name;
@@ -124,9 +137,15 @@ private void Parse(string text, string name)
var roms = new List();
// libdof reads the first [Config DOF] section, or else the first [Config outs] one
List configDof = null, configOuts = null, rows = null;
+ // the lines libdof keeps of them, which are more than the rows: it drops only those starting with #
+ List keptDof = null, keptOuts = null, kept = null;
IReadOnlyList dofHeader = null, outsHeader = null;
var variables = new List();
var tableVariables = new List();
+ var colors = new List();
+ // libdof reads the colours of the first [Colors DOF] section, or else of the first [Colors LedWiz] one, even when it is empty;
+ // it finds both by their exact header, as the config sections
+ List colorsDof = null, colorsLedWiz = null, colorLines = null;
var unknown = new List();
string section = null;
var configFound = false;
@@ -150,10 +169,19 @@ private void Parse(string text, string name)
expectHeader = Array.Exists(ConfigSections, s => string.Equals(s, line, StringComparison.OrdinalIgnoreCase));
configFound |= expectHeader;
rows = null;
- if (string.Equals(line, ConfigSections[0], StringComparison.OrdinalIgnoreCase) && configDof == null) {
+ kept = null;
+ colorLines = null;
+ if (string.Equals(line, "[Colors DOF]", StringComparison.Ordinal) && colorsDof == null) {
+ colorLines = colorsDof = new List();
+ } else if (string.Equals(line, "[Colors LedWiz]", StringComparison.Ordinal) && colorsLedWiz == null) {
+ colorLines = colorsLedWiz = new List();
+ }
+ if (string.Equals(line, ConfigSections[0], StringComparison.Ordinal) && configDof == null) {
rows = configDof = new List();
- } else if (string.Equals(line, ConfigSections[1], StringComparison.OrdinalIgnoreCase) && configOuts == null) {
+ kept = keptDof = new List();
+ } else if (string.Equals(line, ConfigSections[1], StringComparison.Ordinal) && configOuts == null) {
rows = configOuts = new List();
+ kept = keptOuts = new List();
}
continue;
}
@@ -173,9 +201,10 @@ private void Parse(string text, string name)
}
continue;
}
- // DOF reads the colours only from a section with at least one line, comments not counted.
- if (line[0] != '#' && (string.Equals(section, "[Colors DOF]", StringComparison.OrdinalIgnoreCase) || string.Equals(section, "[Colors LedWiz]", StringComparison.OrdinalIgnoreCase))) {
- HasColorSection = true;
+ if (string.Equals(section, "[Colors DOF]", StringComparison.OrdinalIgnoreCase) || string.Equals(section, "[Colors LedWiz]", StringComparison.OrdinalIgnoreCase)) {
+ if (line[0] != '#') {
+ colorLines?.Add(line);
+ }
continue;
}
if (line[0] != '#' && string.Equals(section, "[Variables DOF]", StringComparison.OrdinalIgnoreCase)) {
@@ -189,6 +218,9 @@ private void Parse(string text, string name)
if (!Array.Exists(ConfigSections, s => string.Equals(s, section, StringComparison.OrdinalIgnoreCase))) {
continue;
}
+ if (line[0] != '#') {
+ kept?.Add(line);
+ }
if (line[0] == '#' || line.StartsWith("//", StringComparison.Ordinal)) {
if (expectHeader) {
// the header of the section the rows are read from, not of a later one libdof ignores
@@ -210,6 +242,15 @@ private void Parse(string text, string name)
rows?.Add(line);
}
}
+ // DOF skips a file whose colour section has no line, comments not counted
+ var colorData = colorsDof ?? colorsLedWiz;
+ HasColorSection = colorData != null && colorData.Count > 0;
+ HasConfigRows = ((configDof != null ? keptDof : keptOuts)?.Count ?? 0) > 0;
+ foreach (var line in colorData ?? new List()) {
+ if (DofColor.TryParse(line, out var color) && colors.All(c => !string.Equals(c.Name, color.Name, StringComparison.OrdinalIgnoreCase))) {
+ colors.Add(color);
+ }
+ }
PortNames = (configDof != null ? dofHeader : outsHeader) ?? Array.Empty();
ReadPorts(configDof ?? configOuts ?? new List(), Variables(variables), TableVariables(tableVariables));
if (!configFound) {
@@ -217,6 +258,7 @@ private void Parse(string text, string name)
}
Roms = roms;
UnknownSections = unknown;
+ Colors = colors;
}
private void ReadPorts(IEnumerable rows, IReadOnlyList> variables,
@@ -226,6 +268,7 @@ private void ReadPorts(IEnumerable rows, IReadOnlyList Starts)>();
+ var used = new HashSet();
var roms = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (var row in rows) {
var columns = Split(Resolve(row, variables, tableVariables), ',');
@@ -247,6 +290,9 @@ private void ReadPorts(IEnumerable rows, IReadOnlyList c != null)) {
+ used.Add(port);
+ }
port += colour ? 3 : 1;
// a column of settings libdof drops, such as 0, numbers its port but puts nothing on it: past the header, the
// Config Tool's 0s say nothing about the board
@@ -258,6 +304,7 @@ private void ReadPorts(IEnumerable rows, IReadOnlyList
/// The toy's first port.
/// How many ports it takes: 3 for an RGB toy, else 1.
- public string SettingOf(int port, int width)
+ public string SettingOf(int port, int width) => SettingOf(port, width, _shown);
+
+ ///
+ /// As , with the configuration's variables replaced by what they stand for, as libdof
+ /// reads it: what a user's own trigger can say.
+ ///
+ public string ResolvedSettingOf(int port, int width) => SettingOf(port, width, _resolved);
+
+ /// The settings of all its columns, the variables replaced; one per column, empty for a column with none.
+ public IEnumerable ResolvedSettings => _resolved.Skip(1).Select(column => IsNothing(column) ? "" : column.Trim());
+
+ private string SettingOf(int port, int width, IReadOnlyList columns)
{
if (!TryCover(port, width, out var first, out var count)) {
return null;
}
- if (count == 0 || Enumerable.Range(first, count).All(i => IsNothing(_shown[i]))) {
+ if (count == 0 || Enumerable.Range(first, count).All(i => IsNothing(columns[i]))) {
return "";
}
- return count == 1 ? _shown[first].Trim() : null;
+ return count == 1 ? columns[first].Trim() : null;
}
///
@@ -324,9 +335,10 @@ private static (List<(int Start, int Length)> Rows, List Variables, List
if (line.Length > 2 && line[0] == '[' && line[line.Length - 1] == ']') {
section = line;
rows = null;
- if (string.Equals(line, "[Config DOF]", StringComparison.OrdinalIgnoreCase) && dof == null) {
+ // by the exact header, as libdof and DofIniFile
+ if (string.Equals(line, "[Config DOF]", StringComparison.Ordinal) && dof == null) {
rows = dof = new List<(int, int)>();
- } else if (string.Equals(line, "[Config outs]", StringComparison.OrdinalIgnoreCase) && outs == null) {
+ } else if (string.Equals(line, "[Config outs]", StringComparison.Ordinal) && outs == null) {
rows = outs = new List<(int, int)>();
}
continue;
diff --git a/VisualPinball.Engine.DOF/Configuration/DofPortNames.cs b/VisualPinball.Engine.DOF/Configuration/DofPortNames.cs
new file mode 100644
index 0000000..9299f19
--- /dev/null
+++ b/VisualPinball.Engine.DOF/Configuration/DofPortNames.cs
@@ -0,0 +1,118 @@
+// Visual Pinball Engine
+// Copyright (C) 2026 freezy and VPE Team
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+
+namespace VisualPinball.Engine.DOF.Configuration
+{
+ ///
+ /// What the user says the configuration's ports drive, where its header says otherwise, such as a shaker on a port the DOF
+ /// Config Tool calls a bumper: a name for a port, an RGB toy on it and the next two, or no toy. Only names: the outputs
+ /// the ports drive and what fires them stay as they are.
+ ///
+ ///
+ /// Kept next to the revisions, the output wiring and the toy names (<root>/port-names.txt, one
+ /// device:port=name line per port, device:port:rgb=name for an RGB toy on the port and the next two, an empty
+ /// name for no toy), for every configuration. Immutable; changes return new names.
+ ///
+ public sealed class DofPortNames
+ {
+ public const string FileName = "port-names.txt";
+
+ public static readonly DofPortNames None = new DofPortNames(new Dictionary<(int, int), (string, bool)>());
+
+ private readonly IReadOnlyDictionary<(int Device, int Port), (string Name, bool Rgb)> _names;
+
+ private DofPortNames(IReadOnlyDictionary<(int, int), (string, bool)> names) { _names = names; }
+
+ /// Whether the user named no port.
+ public bool IsEmpty => _names.Count == 0;
+
+ /// What the user says a port drives: a name, empty for no toy, and whether it's an RGB toy from the port on; null for nothing said.
+ public (string Name, bool Rgb)? Of(int device, int port) => _names.TryGetValue((device, port), out var named) ? named : ((string, bool)?)null;
+
+ /// The ports of a device the user named, in order.
+ public IReadOnlyList PortsOf(int device) => _names.Keys.Where(k => k.Device == device).Select(k => k.Port).OrderBy(p => p).ToList();
+
+ /// The names with a port of a device named, an RGB toy on it and the next two, or no toy for an empty name.
+ public DofPortNames With(int device, int port, string name, bool rgb)
+ {
+ var names = _names.ToDictionary(e => e.Key, e => e.Value);
+ var clean = DofToyNames.Clean(name);
+ names[(device, port)] = (clean, rgb && clean.Length > 0);
+ return new DofPortNames(names);
+ }
+
+ /// The names without what the user said of a port of a device: it drives what the configuration says again.
+ public DofPortNames Without(int device, int port)
+ {
+ if (!_names.ContainsKey((device, port))) {
+ return this;
+ }
+ var names = _names.ToDictionary(e => e.Key, e => e.Value);
+ names.Remove((device, port));
+ return new DofPortNames(names);
+ }
+
+ /// Reads the names of a store's folder; none when it has no file. A line that names no port is left out.
+ public static DofPortNames Load(string root)
+ {
+ var path = Path.Combine(root, FileName);
+ if (Directory.Exists(path)) {
+ throw new IOException(path + " is a folder, not the port names.");
+ }
+ if (!File.Exists(path)) {
+ return None;
+ }
+ var names = new Dictionary<(int, int), (string, bool)>();
+ foreach (var line in File.ReadAllLines(path, Encoding.UTF8)) {
+ var colon = line.IndexOf(':');
+ var equals = line.IndexOf('=');
+ // device:port=name, or device:port:rgb=name for an RGB toy
+ var place = colon > 0 && equals > colon + 1 ? line.Substring(colon + 1, equals - colon - 1).Split(':') : new string[0];
+ var colour = place.Length == 2 && place[1].Trim() == "rgb";
+ if (place.Length == 0 || place.Length > 2 || place.Length == 2 && !colour
+ || !int.TryParse(line.Substring(0, colon).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var device)
+ || !int.TryParse(place[0].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var port)
+ || device < 1 || device > DofOutputWiring.MaxDevice || port < 1 || port > DofOutputWiring.MaxOutput - (colour ? 2 : 0)) {
+ continue;
+ }
+ var name = DofToyNames.Clean(line.Substring(equals + 1));
+ // a later line of the port replaces what an earlier one said
+ names[(device, port)] = (name, colour && name.Length > 0);
+ }
+ return new DofPortNames(names);
+ }
+
+ /// Replaces the names file of a store's folder in one step; deletes it when no port is named.
+ public void Save(string root)
+ {
+ var path = Path.Combine(root, FileName);
+ if (IsEmpty) {
+ if (File.Exists(path)) {
+ File.Delete(path);
+ }
+ return;
+ }
+ Directory.CreateDirectory(root);
+ var text = new StringBuilder();
+ foreach (var entry in _names.OrderBy(e => e.Key.Device).ThenBy(e => e.Key.Port)) {
+ text.Append(entry.Key.Device.ToString(CultureInfo.InvariantCulture)).Append(':')
+ .Append(entry.Key.Port.ToString(CultureInfo.InvariantCulture)).Append(entry.Value.Rgb ? ":rgb" : "").Append('=').Append(entry.Value.Name).Append('\n');
+ }
+ var temp = path + ".tmp";
+ File.WriteAllText(temp, text.ToString(), new UTF8Encoding(false));
+ if (File.Exists(path)) {
+ File.Replace(temp, path, null);
+ } else {
+ File.Move(temp, path);
+ }
+ }
+ }
+}
diff --git a/VisualPinball.Engine.DOF/Configuration/DofToyNames.cs b/VisualPinball.Engine.DOF/Configuration/DofToyNames.cs
index f7ce5e4..2af0122 100644
--- a/VisualPinball.Engine.DOF/Configuration/DofToyNames.cs
+++ b/VisualPinball.Engine.DOF/Configuration/DofToyNames.cs
@@ -19,7 +19,8 @@ namespace VisualPinball.Engine.DOF.Configuration
///
///
/// Kept next to the revisions and the output wiring (<root>/toy-names.txt, one device:port=name line
- /// per toy), for every configuration. Immutable; changes return new names.
+ /// per toy, device:port:rgb=name for an RGB toy on the port and the next two), for every configuration. Immutable;
+ /// changes return new names.
///
public sealed class DofToyNames
{
@@ -31,11 +32,13 @@ public sealed class DofToyNames
/// The first port a toy is added on: half of what the native layer takes, far past any board's.
public const int FirstPort = DofOutputWiring.MaxOutput / 2 + 1;
- public static readonly DofToyNames None = new DofToyNames(new Dictionary<(int, int), string>());
+ public static readonly DofToyNames None = new DofToyNames(new Dictionary<(int, int), string>(), new HashSet<(int, int)>());
private readonly IReadOnlyDictionary<(int Device, int Port), string> _names;
+ // the named ports whose toy is an RGB toy, which takes the port and the next two
+ private readonly HashSet<(int Device, int Port)> _rgb;
- private DofToyNames(IReadOnlyDictionary<(int, int), string> names) { _names = names; }
+ private DofToyNames(IReadOnlyDictionary<(int, int), string> names, HashSet<(int, int)> rgb) { _names = names; _rgb = rgb; }
/// Whether the user named no toy.
public bool IsEmpty => _names.Count == 0;
@@ -43,6 +46,26 @@ public sealed class DofToyNames
/// The name the user gave a port, or null.
public string NameOf(int device, int port) => _names.TryGetValue((device, port), out var name) ? name : null;
+ /// Whether the toy the user named on a port is an RGB toy, on the port (its red) and the next two.
+ public bool IsRgb(int device, int port) => _rgb.Contains((device, port));
+
+ /// The port the user named for the toy a port is on: itself, or the red of an RGB toy; 0 for none.
+ public int StartOf(int device, int port)
+ {
+ if (_names.ContainsKey((device, port))) {
+ return port;
+ }
+ for (var start = port - 1; start >= port - 2; start--) {
+ if (_rgb.Contains((device, start))) {
+ return start;
+ }
+ }
+ return 0;
+ }
+
+ /// The ports of a device where an RGB toy the user named starts, in order.
+ public IReadOnlyList RgbPortsOf(int device) => _rgb.Where(k => k.Device == device).Select(k => k.Port).OrderBy(p => p).ToList();
+
/// The ports of a device the user named, in order.
public IReadOnlyList PortsOf(int device) => _names.Keys.Where(k => k.Device == device).Select(k => k.Port).OrderBy(p => p).ToList();
@@ -65,17 +88,30 @@ internal static string Truncate(string text, int length)
return text.Substring(0, length).TrimEnd();
}
- /// The names with a port of a device named, or its name removed for an empty one.
- public DofToyNames With(int device, int port, string name)
+ ///
+ /// The names with a port of a device named, for an RGB toy on it and the next two; or its name removed for an empty one.
+ ///
+ public DofToyNames With(int device, int port, string name, bool rgb = false)
{
- var names = _names.ToDictionary(e => e.Key, e => e.Value);
var clean = Clean(name);
+ // what Load would leave out again
+ if (rgb && clean.Length > 0 && port > DofOutputWiring.MaxOutput - 2) {
+ throw new ArgumentOutOfRangeException(nameof(port), $"An RGB toy takes three outputs in a row: port {port} is too close to the last, {DofOutputWiring.MaxOutput}.");
+ }
+ var names = _names.ToDictionary(e => e.Key, e => e.Value);
+ var colours = new HashSet<(int, int)>(_rgb);
if (clean.Length == 0) {
names.Remove((device, port));
+ colours.Remove((device, port));
} else {
names[(device, port)] = clean;
+ if (rgb) {
+ colours.Add((device, port));
+ } else {
+ colours.Remove((device, port));
+ }
}
- return new DofToyNames(names);
+ return new DofToyNames(names, colours);
}
/// Reads the names of a store's folder; none when it has no file. A line that names no port is left out.
@@ -89,21 +125,31 @@ public static DofToyNames Load(string root)
return None;
}
var names = new Dictionary<(int, int), string>();
+ var rgb = new HashSet<(int, int)>();
foreach (var line in File.ReadAllLines(path, Encoding.UTF8)) {
var colon = line.IndexOf(':');
var equals = line.IndexOf('=');
- if (colon <= 0 || equals <= colon + 1
+ // device:port=name, or device:port:rgb=name for an RGB toy
+ var place = colon > 0 && equals > colon + 1 ? line.Substring(colon + 1, equals - colon - 1).Split(':') : Array.Empty();
+ var colour = place.Length == 2 && place[1].Trim() == "rgb";
+ if (place.Length == 0 || place.Length > 2 || place.Length == 2 && !colour
|| !int.TryParse(line.Substring(0, colon).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var device)
- || !int.TryParse(line.Substring(colon + 1, equals - colon - 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var port)
- || device < 1 || device > DofOutputWiring.MaxDevice || port < 1 || port > DofOutputWiring.MaxOutput) {
+ || !int.TryParse(place[0].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var port)
+ || device < 1 || device > DofOutputWiring.MaxDevice || port < 1 || port > DofOutputWiring.MaxOutput - (colour ? 2 : 0)) {
continue;
}
var name = Clean(line.Substring(equals + 1));
if (name.Length > 0) {
+ // a later line of the port replaces the toy, RGB or not
names[(device, port)] = name;
+ if (colour) {
+ rgb.Add((device, port));
+ } else {
+ rgb.Remove((device, port));
+ }
}
}
- return new DofToyNames(names);
+ return new DofToyNames(names, rgb);
}
/// Replaces the names file of a store's folder in one step; deletes it when no toy is named.
@@ -120,7 +166,7 @@ public void Save(string root)
var text = new StringBuilder();
foreach (var entry in _names.OrderBy(e => e.Key.Device).ThenBy(e => e.Key.Port)) {
text.Append(entry.Key.Device.ToString(CultureInfo.InvariantCulture)).Append(':')
- .Append(entry.Key.Port.ToString(CultureInfo.InvariantCulture)).Append('=').Append(entry.Value).Append('\n');
+ .Append(entry.Key.Port.ToString(CultureInfo.InvariantCulture)).Append(_rgb.Contains(entry.Key) ? ":rgb" : "").Append('=').Append(entry.Value).Append('\n');
}
var temp = path + ".tmp";
File.WriteAllText(temp, text.ToString(), new UTF8Encoding(false));
diff --git a/VisualPinball.Engine.DOF/DofInstance.cs b/VisualPinball.Engine.DOF/DofInstance.cs
index cd8f68d..4ee1b94 100644
--- a/VisualPinball.Engine.DOF/DofInstance.cs
+++ b/VisualPinball.Engine.DOF/DofInstance.cs
@@ -488,6 +488,39 @@ public DofStatus TestToy(int device, int port, int value, out DofToy toy)
return (DofStatus)status;
}
+ ///
+ /// Lights single points of a colour matrix toy of the cabinet, such as an LED strip, by its name, through the output
+ /// gate: the colours (red, green, blue for each point) go to the points from the top left along the rows, on the layer
+ /// uses, and the points after them are transparent; no colours clears it. The strip's
+ /// arrangement, colour order, brightness and fading curve apply, so a strip one point high with the arrangement
+ /// LeftRightTopDown, colour order RGB, brightness 100 and fading curve Linear sends the colours to its LEDs as given.
+ /// Nothing is dimmed: light only a few points brightly.
+ ///
+ /// Only for an instance initialized without a table and ROM, as .
+ /// The toy's name in the cabinet file.
+ /// Three bytes for each point; its length is a multiple of three.
+ ///
+ /// for no toy of the name or more colours than points;
+ /// for a toy that is no colour matrix; before
+ /// init, after finish, or on an instance initialized with a table or ROM.
+ ///
+ public DofStatus TestPixels(string toy, byte[] rgb)
+ {
+ if (toy == null) {
+ throw new ArgumentNullException(nameof(toy));
+ }
+ rgb ??= Array.Empty();
+ if (rgb.Length % 3 != 0) {
+ throw new ArgumentException("Three bytes for each point.", nameof(rgb));
+ }
+ EnterOrThrow();
+ try {
+ return (DofStatus)DofNative.TestPixels(_dof, Utf8.Encode(toy), rgb, rgb.Length / 3);
+ } finally {
+ Leave();
+ }
+ }
+
/// The output controllers and toys, after .
public DofCabinetDescription Describe()
{
diff --git a/VisualPinball.Engine.DOF/Native/DofNative.cs b/VisualPinball.Engine.DOF/Native/DofNative.cs
index cd6c5de..729a1a0 100644
--- a/VisualPinball.Engine.DOF/Native/DofNative.cs
+++ b/VisualPinball.Engine.DOF/Native/DofNative.cs
@@ -15,7 +15,7 @@ namespace VisualPinball.Engine.DOF.Native
internal static class DofNative
{
public const string Library = "VpeDof";
- public const int AbiVersion = 9;
+ public const int AbiVersion = 10;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void LogCallback(int level, IntPtr message, IntPtr user);
@@ -80,6 +80,9 @@ internal static class DofNative
[DllImport(Library, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vpe_dof_test_toy")]
public static extern int TestToy(IntPtr dof, int device, int port, int value, byte[] toy, int toySize);
+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vpe_dof_test_pixels")]
+ public static extern int TestPixels(IntPtr dof, byte[] toy, byte[] rgb, int count);
+
[DllImport(Library, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vpe_dof_describe")]
public static extern int Describe(IntPtr dof, StringCallback callback, IntPtr user);
diff --git a/native/include/vpe_dof.h b/native/include/vpe_dof.h
index 1897695..fbb8718 100644
--- a/native/include/vpe_dof.h
+++ b/native/include/vpe_dof.h
@@ -36,7 +36,7 @@ extern "C" {
#endif
/// Version of this ABI. Bumped on every incompatible change; the managed binding refuses a library with another one.
-#define VPE_DOF_ABI_VERSION 9
+#define VPE_DOF_ABI_VERSION 10
enum vpe_dof_status
{
@@ -165,6 +165,18 @@ VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_test_output(vpe_dof* dof, int32_t devic
/// init, after finish, or with a table.
VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_test_toy(vpe_dof* dof, int32_t device, int32_t port, int32_t value, char* toy, int32_t toy_size);
+/// Lights single points of a colour matrix toy of the cabinet, such as an LED strip, by its name, for setting up strips:
+/// `count` colours of three bytes each (red, green, blue) for the points from the top left along the rows (x = i % width,
+/// y = i / width), on the layer vpe_dof_test_toy uses, and the points after them transparent; a count of 0 clears it.
+/// The strip's arrangement, colour order, brightness and fading curve apply as they do to effects, so a strip one point
+/// high with the arrangement LeftRightTopDown, colour order RGB, brightness 100 and fading curve Linear sends the colours
+/// as given to its LEDs in their order. Nothing is dimmed: light only a few points brightly. Runs on DOF's main thread,
+/// whose cabinet update sends it, and goes through the output gate. Only for an instance initialized without a table and
+/// ROM, as vpe_dof_test_toy. VPE_DOF_INVALID_ARGUMENT for no toy of the name, a negative count, more colours than points
+/// or no colours for a count; VPE_DOF_NOT_SUPPORTED for a toy that is no colour matrix; VPE_DOF_INVALID_STATE before
+/// init, after finish, or with a table.
+VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_test_pixels(vpe_dof* dof, const char* toy_name, const uint8_t* rgb, int32_t count);
+
/// Routes the ports of an ini device (the N of directoutputconfigN.ini) to other outputs of its LedWiz equivalent, for
/// cabling that differs from the configuration: port i + 1 drives the output port targets[i] drives in the cabinet, its
/// own for 0 or i + 1, and nothing for a negative target. A port whose target the equivalent has no output for drives
diff --git a/native/src/vpe_dof.cpp b/native/src/vpe_dof.cpp
index 02b2b1b..0e73ee9 100644
--- a/native/src/vpe_dof.cpp
+++ b/native/src/vpe_dof.cpp
@@ -807,6 +807,35 @@ VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_test_toy(vpe_dof* dof, int32_t device,
}
}
+VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_test_pixels(vpe_dof* dof, const char* toy_name, const uint8_t* rgb, int32_t count)
+{
+ // as vpe_dof_test_toy: only without a table, whose effects could use the test's layer
+ if (!IsRunning(dof) || dof->hasTable)
+ return VPE_DOF_INVALID_STATE;
+ if (!toy_name || !*toy_name || count < 0 || (count > 0 && !rgb))
+ return VPE_DOF_INVALID_ARGUMENT;
+ try
+ {
+ DOF::Cabinet* cabinet = dof->pinball->GetCabinet();
+ DOF::ToyList* toys = cabinet ? cabinet->GetToys() : nullptr;
+ // the cabinet's toys and their size are fixed after init
+ DOF::IToy* target = toys ? toys->FindByName(toy_name) : nullptr;
+ if (!target)
+ return VPE_DOF_INVALID_ARGUMENT;
+ auto* matrix = dynamic_cast*>(target);
+ if (!matrix)
+ return VPE_DOF_NOT_SUPPORTED;
+ if (static_cast(count) > static_cast(matrix->GetWidth()) * matrix->GetHeight())
+ return VPE_DOF_INVALID_ARGUMENT;
+ std::vector colours(rgb, rgb + static_cast(count) * 3);
+ return dof->pinball->Post([target, colours = std::move(colours)]() { vpe_dof_toys::SetPixels(target, colours); }) ? VPE_DOF_OK : VPE_DOF_INVALID_STATE;
+ }
+ catch (...)
+ {
+ return VPE_DOF_ERROR;
+ }
+}
+
VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_set_output_map(vpe_dof* dof, int32_t device, const int32_t* targets, int32_t count)
{
if (!dof || device < 1 || device > 999 || count < 0 || count > 4096 || (count > 0 && !targets))
diff --git a/native/src/vpe_dof_toys.h b/native/src/vpe_dof_toys.h
index ca53e38..2b7ca45 100644
--- a/native/src/vpe_dof_toys.h
+++ b/native/src/vpe_dof_toys.h
@@ -6,6 +6,8 @@
#pragma once
#include
+#include
+#include
#include "cab/toys/IAnalogAlphaToy.h"
#include "cab/toys/IMatrixToy.h"
@@ -70,6 +72,34 @@ template void Fill(DOF::IMatrixToy* matrix, const El
}
}
+// Sets the test layer of a colour matrix, such as an LED strip, to colours, three bytes (red, green, blue) for each point
+// from the top left along the rows (x = i % width, y = i / width); the points after them are transparent, so no colours
+// clears it. Run on DOF's main thread, as Light. Returns false for a toy that is no colour matrix.
+inline bool SetPixels(DOF::IToy* toy, const std::vector& rgb)
+{
+ auto* matrix = dynamic_cast*>(toy);
+ if (!matrix)
+ return false;
+ const int width = matrix->GetWidth();
+ const int height = matrix->GetHeight();
+ const int count = static_cast(rgb.size() / 3);
+ for (int y = 0; y < height; y++)
+ {
+ for (int x = 0; x < width; x++)
+ {
+ const int i = y * width + x;
+ matrix->SetElement(TestLayer, x, y, i < count ? DOF::RGBAColor(rgb[i * 3], rgb[i * 3 + 1], rgb[i * 3 + 2], 255) : DOF::RGBAColor());
+ }
+ }
+ // as Light: a group passes its layers on when it updates
+ if (dynamic_cast(toy))
+ {
+ if (auto* group = dynamic_cast(toy))
+ group->UpdateToy();
+ }
+ return true;
+}
+
// Sets the toy's test layer for `value` (0 to 255), or clears it with 0, as KindOf says. Run on DOF's main thread: its
// cabinet update then sends the toy's outputs to the controllers. Returns false for a toy the test can't light.
// A cleared layer stays, transparent: a strip with no layer sends nothing, so it would keep what the test lit.