diff --git a/VisualPinball.Engine.DOF.Test/DofImporterTests.cs b/VisualPinball.Engine.DOF.Test/DofImporterTests.cs index fe4e014..e62d8e3 100644 --- a/VisualPinball.Engine.DOF.Test/DofImporterTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofImporterTests.cs @@ -427,6 +427,86 @@ public void RejectsTwoDifferentFilesWithOneName() Accepted(_importer.Import(Zip("same.zip", ("a/directoutputconfig.ini", MainIni), ("b/directoutputconfig.ini", MainIni)))); } + [Test] + public void SkipsExamplesAndOtherConfigurations() + { + // DOF's config folder often has an Examples folder in it, with files of the same names. + var report = Accepted(_importer.Import(Folder("Config", + ("GlobalConfig_B2SServer.xml", WindowsGlobalConfig), ("cabinet.xml", Cabinet), ("directoutputconfig.ini", MainIni), + ("Examples/GlobalConfig_B2SServer.xml", ""), ("Examples/cabinet.xml", ""), ("Examples/more/directoutputconfig51.ini", SecondIni)), + DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Info, "Skipped the folder Examples: it holds DOF's examples."), Is.True, report.ToString()); + var catalog = DofCatalog.Load(_store.Active); + Assert.That(catalog.Devices.Select(d => d.Number), Is.EqualTo(new[] { 1 })); + Assert.That(catalog.Controllers.Select(c => c.Name), Is.EqualTo(new[] { "PinControl 1", "Teensy 1", "ArtNet 1" })); + + // In a folder around it, the shallowest folder with an ini file is the configuration, or the one named Config. + // Other folders with ini files are other configurations; files elsewhere, such as a cabinet, still count. + report = Accepted(_importer.Import(Folder("DirectOutput", + ("Config/directoutputconfig51.ini", MainIni), ("Config/Old/directoutputconfig51.ini", SecondIni), + ("Backup/directoutputconfig51.ini", SecondIni), ("Backup/cabinet.xml", ""), ("Hardware/cabinet.xml", Cabinet)), + DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Info, "Skipped the folder Backup (2 files): it is not the configuration folder, which is Config."), Is.True, report.ToString()); + Assert.That(Has(report, DofReportSeverity.Info, "Skipped the folder Config/Old (1 file)"), Is.True, report.ToString()); + Assert.That(File.ReadAllText(Path.Combine(_store.Active.ConfigDir, "directoutputconfig51.ini")), Is.EqualTo(MainIni)); + Assert.That(DofCatalog.Load(_store.Active).HasCabinet, Is.True); + + // The configuration folder's own file wins over one of the same name elsewhere. + report = Accepted(_importer.Import(Folder("own", + ("directoutputconfig.ini", MainIni), ("cabinet.xml", Cabinet), ("Saved/cabinet.xml", "Saved")), + DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Info, "Skipped Saved/cabinet.xml: the configuration folder has its own cabinet.xml."), Is.True, report.ToString()); + Assert.That(DofCatalog.Load(_store.Active).Controllers, NUnit.Framework.Has.Count.EqualTo(3)); + + // A directoutputconfig ini deeper down is the configuration, not a ledcontrol one above it. + report = Accepted(_importer.Import(Folder("legacy", + ("ledcontrol.ini", "[Colors LedWiz]\r\nRed=48,0,0\r\n\r\n[Config outs]\r\nafm,S1\r\n"), ("Config/directoutputconfig30.ini", MainIni)), + DofImportMode.Replace)); + Assert.That(DofCatalog.Load(_store.Active).Devices.Select(d => d.Number), Is.EqualTo(new[] { 30 }), report.ToString()); + + // An example is never the configuration, even a current one next to a ledcontrol configuration. + report = Accepted(_importer.Import(Folder("examples", + ("ledcontrol.ini", "[Colors LedWiz]\r\nRed=48,0,0\r\n\r\n[Config outs]\r\nafm,S1\r\n"), ("Examples/directoutputconfig51.ini", MainIni)), + DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Info, "Skipped the folder Examples: it holds DOF's examples."), Is.True, report.ToString()); + Assert.That(DofCatalog.Load(_store.Active).Devices.Select(d => d.Number), Is.EqualTo(new[] { 1 }), report.ToString()); + + // Nor are examples read when only they have ini files: a cabinet merged in keeps the ini files it had. + report = Accepted(_importer.Import(Folder("cabinet only", ("cabinet.xml", Cabinet), ("Examples/directoutputconfig51.ini", MainIni)))); + Assert.That(Has(report, DofReportSeverity.Info, "Skipped the folder Examples: it holds DOF's examples."), Is.True, report.ToString()); + Assert.That(DofCatalog.Load(_store.Active).Devices.Select(d => d.Number), Is.EqualTo(new[] { 1 }), report.ToString()); + + // Examples are skipped before the limits: an oversized one doesn't stop the configuration, in a folder or a zip. + _importer.Limits.MaxFileBytes = 1000; + try { + var big = new string('x', 2000); + report = Accepted(_importer.Import(Folder("big examples", ("directoutputconfig.ini", MainIni), ("Examples/Sub/cabinet.xml", big)), DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Info, "Skipped the folder Examples: it holds DOF's examples."), Is.True, report.ToString()); + report = Accepted(_importer.Import(Zip("big examples.zip", ("Config/directoutputconfig.ini", MainIni), ("Config/examples/cabinet.xml", big)))); + Assert.That(Has(report, DofReportSeverity.Info, "Skipped the folder Config/examples: it holds DOF's examples."), Is.True, report.ToString()); + // nor do a zip's examples count as entries, or against the depth + _importer.Limits.MaxEntries = 2; + _importer.Limits.MaxDepth = 2; + Accepted(_importer.Import(Zip("many examples.zip", ("directoutputconfig.ini", MainIni), + ("Examples/a.xml", Mappings), ("Examples/b.xml", Mappings), ("Examples/c/d/e/f.xml", Mappings)))); + // nor does a folder's examples folder itself + _importer.Limits.MaxEntries = 1; + Accepted(_importer.Import(Folder("examples beside", ("directoutputconfig.ini", MainIni), ("Examples/a.xml", Mappings)), DofImportMode.Replace)); + // a zip or a folder lists a few of its examples folders, and counts the rest + _importer.Limits.MaxEntries = 5000; + var sets = new[] { ("directoutputconfig.ini", MainIni) }.Concat(Enumerable.Range(0, 12).Select(i => ($"Set{i:00}/Examples/a.xml", Mappings))).ToArray(); + foreach (var import in new[] { Zip("example sets.zip", sets), Folder("example sets", sets) }) { + report = Accepted(_importer.Import(import, DofImportMode.Replace)); + Assert.That(report.Entries.Count(e => e.Message.EndsWith(": it holds DOF's examples.", StringComparison.Ordinal)), Is.EqualTo(10), report.ToString()); + Assert.That(Has(report, DofReportSeverity.Info, "Skipped 2 more folders of DOF's examples."), Is.True, report.ToString()); + } + } finally { + _importer.Limits.MaxFileBytes = 64L * 1024 * 1024; + _importer.Limits.MaxEntries = 5000; + _importer.Limits.MaxDepth = 8; + } + } + [Test] public void RejectsAnImportWithoutIniFiles() { @@ -799,5 +879,74 @@ public void BuildsAGameCopyWithTheUsersTriggers() DofGameConfig.Delete(_store.Root); Assert.That(Directory.Exists(basePath), Is.False); } + + [Test] + public void ReportsTheSourceAndWhatItHeld() + { + var folder = Folder("Config", ("directoutputconfig.ini", MainIni), ("cabinet.xml", Cabinet), ("notes.txt", "hi")); + var report = Accepted(_importer.Import(folder, DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Info, $"Imported from {Path.GetFullPath(folder)}."), Is.True, report.ToString()); + Assert.That(Has(report, DofReportSeverity.Info, "Found 2 files: cabinet.xml, directoutputconfig.ini."), Is.True, report.ToString()); + Assert.That(_store.Active.ReadReport(), Does.Contain("Imported from " + Path.GetFullPath(folder))); + } + + [Test] + public void WarnsWhenAFolderDropsTheIniFilesOfAZip() + { + Accepted(_importer.Import(Zip("config.zip", ("directoutputconfig.ini", MainIni), ("directoutputconfig51.ini", SecondIni)))); + // an old folder with a ledcontrol file and a cabinet, imported over the zip's files + var report = Accepted(_importer.Import(Folder("Config64", ("ledcontrol.ini", MainIni), ("cabinet.xml", Cabinet)), DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Warning, "directoutputconfig.ini, directoutputconfig51.ini of the previous one (config.zip) are no longer used"), Is.True, report.ToString()); + + // a merge keeps what it doesn't bring, and a replace that brings the same files drops nothing + report = Accepted(_importer.Import(Zip("again.zip", ("directoutputconfig.ini", MainIni), ("directoutputconfig51.ini", SecondIni)))); + Assert.That(Has(report, DofReportSeverity.Warning, "no longer used"), Is.False, report.ToString()); + report = Accepted(_importer.Import(Folder("Same", ("directoutputconfig.ini", MainIni), ("directoutputconfig51.ini", SecondIni), ("cabinet.xml", Cabinet)), DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Warning, "no longer used"), Is.False, report.ToString()); + + // a cabinet the replacing folder lacks is said too + report = Accepted(_importer.Import(Folder("NoCabinet", ("directoutputconfig.ini", MainIni), ("directoutputconfig51.ini", SecondIni)), DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Warning, "its cabinet file of the previous one"), Is.True, report.ToString()); + } + + [Test] + public void AFolderWithOnlyTheCabinetSaysToImportTheFile() + { + var cabinetOnly = Folder("Config", ("cabinet.xml", Cabinet), ("Examples/directoutputconfig.ini", MainIni)); + // nothing active yet: only the reason + var report = Rejected(_importer.Import(cabinetOnly, DofImportMode.Replace), "has no DOF ini file"); + Assert.That(report.RejectionReason, Does.Not.Contain("import cabinet.xml itself")); + Accepted(_importer.Import(Zip("config.zip", ("directoutputconfig.ini", MainIni)))); + report = Rejected(_importer.Import(cabinetOnly, DofImportMode.Replace), "import cabinet.xml itself instead of the folder"); + // a rejected import replaced nothing + Assert.That(Has(report, DofReportSeverity.Warning, "no longer used"), Is.False, report.ToString()); + Assert.That(Has(report, DofReportSeverity.Info, "Found 1 file: cabinet.xml."), Is.True, report.ToString()); + // and that works + Accepted(_importer.Import(Path.Combine(cabinetOnly, "cabinet.xml"))); + Assert.That(DofCatalog.Load(_store.Active).HasCabinet, Is.True); + } + + [Test] + public void WarnsAboutACabinetDeviceWithoutIni() + { + // the cabinet sets up device 1 (Cabinet) and device 30, but the configuration only has device 51 + var cabinet = Cabinet.Replace("", "LedWizEquivalent 3030"); + var report = Accepted(_importer.Import(Folder("Config", ("directoutputconfig51.ini", SecondIni), ("cabinet.xml", cabinet)), DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Warning, DofCatalog.CabinetDeviceWithoutIni(1, false)), Is.True, report.ToString()); + Assert.That(Has(report, DofReportSeverity.Warning, DofCatalog.CabinetDeviceWithoutIni(30, false)), Is.True, report.ToString()); + Assert.That(DofCatalog.Load(_store.Active).CabinetDevicesWithoutIni, Is.EqualTo(new[] { 1, 30 })); + + // a legacy ledcontrol.ini is device 1 + report = Accepted(_importer.Import(Folder("Legacy", ("ledcontrol.ini", MainIni), ("cabinet.xml", Cabinet)), DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Warning, "but no ini file is device"), Is.False, report.ToString()); + Assert.That(DofCatalog.Load(_store.Active).CabinetDevicesWithoutIni, Is.Empty); + // and next to ledcontrol files the missing device is named as one: a directoutputconfig file would hide them all + report = Accepted(_importer.Import(Folder("Legacy30", ("ledcontrol.ini", MainIni), ("cabinet.xml", cabinet)), DofImportMode.Replace)); + Assert.That(Has(report, DofReportSeverity.Warning, DofCatalog.CabinetDeviceWithoutIni(30, true)), Is.True, report.ToString()); + Assert.That(DofCatalog.CabinetDeviceWithoutIni(30, true), Does.Contain("(ledcontrol30.ini)")); + var catalog = DofCatalog.Load(_store.Active); + Assert.That(catalog.LegacyInis, Is.True); + Assert.That(catalog.CabinetDevicesWithoutIni, Is.EqualTo(new[] { 30 })); + } } } diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofGameSession.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofGameSession.cs index 8109595..f996a29 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofGameSession.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofGameSession.cs @@ -4,6 +4,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using VisualPinball.Engine.DOF.Session; @@ -166,16 +167,19 @@ public void PulseNamed(string name) #region Lifecycle - /// Starts DOF. Returns why it did not start (null when it runs) and a description of the cabinet it drives. - public async Task<(string Error, string Cabinet)> StartAsync() + /// + /// Starts DOF. Returns why it did not start (null when it runs), a description of the cabinet it drives, and the ini + /// devices it set up (null when unknown). + /// + public async Task<(string Error, string Cabinet, IReadOnlyList Devices)> StartAsync() { var result = await _session.StartAsync().ConfigureAwait(false); if (!result.Started) { - return (result.Error ?? "DOF did not start.", null); + return (result.Error ?? "DOF did not start.", null, null); } var cabinet = result.Cabinet; if (cabinet == null) { - return (null, null); + return (null, null, null); } var controllers = new string[cabinet.Controllers.Count]; for (var i = 0; i < controllers.Length; i++) { @@ -183,7 +187,7 @@ public void PulseNamed(string name) controllers[i] = $"{controller.Name} ({controller.Type}, {controller.Outputs} outputs)"; } var summary = controllers.Length == 0 ? "no output controllers" : string.Join(", ", controllers); - return (null, cabinet.Toys.Count == 1 ? summary + ", 1 toy" : $"{summary}, {cabinet.Toys.Count} toys"); + return (null, cabinet.Toys.Count == 1 ? summary + ", 1 toy" : $"{summary}, {cabinet.Toys.Count} toys", cabinet.Devices); } /// diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs index beebe75..fb4829a 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs @@ -59,10 +59,15 @@ internal sealed class DofPlugin : PlayerPlugin, IPluginEmergencyStop, IPluginDef private volatile string _cabinet; private volatile bool _ending; private string _revision; + /// What the game's configuration was imported from, such as the zip's name; null when unknown. + private string _origin; private string _rom; private string _romProblem; private string _feed = "none"; private int _boundTriggers; + // the game's rows, whose ports are compared with the devices DOF sets up once it runs + private IReadOnlyList _rowSources = Array.Empty(); + private bool _hasCabinet; private bool _diagnostics; private string _publishedState; @@ -98,7 +103,9 @@ public override async Task PrepareGameAsync(PluginGameContext game, Cancellation _triggers = null; _cabinet = null; _ending = false; - _revision = _rom = _romProblem = null; + _revision = _origin = _rom = _romProblem = null; + _rowSources = Array.Empty(); + _hasCabinet = false; _leaseKeys.Clear(); _feed = "none"; _boundTriggers = 0; @@ -205,6 +212,21 @@ public override async Task PrepareGameAsync(PluginGameContext game, Cancellation if (_romProblem != null) { _application.Logger.Warn(_romProblem); } + _hasCabinet = catalog.HasCabinet; + _application.Logger.Info("DOF configuration: " + (catalog.HasCabinet + ? "a cabinet file sets up the devices" + : "no cabinet file, so DOF sets up only the boards it finds") + "; device files: " + + (catalog.Devices.Count == 0 ? "none" : string.Join(", ", catalog.Devices.Select(d => d.FileName))) + "."); + foreach (var device in catalog.CabinetDevicesWithoutIni) { + _application.Logger.Warn(DofCatalog.CabinetDeviceWithoutIni(device, catalog.LegacyInis)); + } + LogImport(revision); + // the rows as the game has them, with what the user changed; read once DOF runs, off this thread + _rowSources = _rom == null ? Array.Empty() : catalog.Match(_rom) + .Select(r => (Row: r, Device: catalog.Devices.FirstOrDefault(d => d.Number == r.Device))) + .Where(r => r.Device != null) + .Select(r => new DofRowSource(r.Row.Device, r.Row.Rom, r.Device.FileName, Path.Combine(basePath, DofRevision.ConfigFolder, r.Device.FileName))) + .ToList(); _diagnostics = true; PublishDiagnostics(true); } catch { @@ -220,6 +242,28 @@ public override async Task PrepareGameAsync(PluginGameContext game, Cancellation } } + /// + /// Logs where the game's configuration came from and what its import found, so a report needs no questions about + /// it. A file that can't be read is said, and never keeps DOF from starting. + /// + private void LogImport(DofRevision revision) + { + try { + _origin = revision.ReadOrigin(); + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { + _application.Logger.Warn($"Where DOF revision {revision.Id} was imported from could not be read.", e); + } + string importReport; + try { + importReport = revision.ReadReport(); + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { + _application.Logger.Warn($"The import report of DOF revision {revision.Id} could not be read.", e); + return; + } + _application.Logger.Info($"DOF configuration of revision {revision.Id}, imported from {_origin ?? "an unknown source"}" + + (string.IsNullOrWhiteSpace(importReport) ? "; it has no import report." : ". Its import report:\n" + importReport.TrimEnd())); + } + private bool Reserve(PluginGameContext game, DofRevision revision, DofCatalog catalog, DofNativeHold hold) { var leases = game.Capabilities.Find(UnityPluginCapability.Outputs); @@ -291,7 +335,20 @@ public override async Task StartGameAsync(CancellationToken cancellation) _status = "Starting"; // Published before the wait: a start that hangs in a controller shows as starting, not as ready. PublishDiagnostics(true); - var (error, cabinet) = await WithCancellation(session.StartAsync(), cancellation).ConfigureAwait(false); + // the game's rows, for the log: the ini files are large, so they are read off the main thread while DOF starts, + // and done with before the game runs, which owns its copy of the configuration + var sources = _rowSources; + var reading = Task.Run(() => ReadRows(sources)); + (string Error, string Cabinet, IReadOnlyList Devices) started; + try { + started = await WithCancellation(session.StartAsync(), cancellation).ConfigureAwait(false); + } catch { + // a cancelled start still lets go of the files first + await reading.ConfigureAwait(false); + throw; + } + var (error, cabinet, devices) = started; + var (rows, readProblem) = await reading.ConfigureAwait(false); await _application.Scheduler.Switch(); if (error != null) { _status = "DOF did not start: " + error; @@ -305,6 +362,18 @@ public override async Task StartGameAsync(CancellationToken cancellation) _cabinet = cabinet; _status = "Running"; _application.Logger.Info("DOF runs" + (cabinet != null ? ": " + cabinet : "") + "."); + if (readProblem != null) { + _application.Logger.Warn("The game's DOF rows could not be read for the log.", readProblem); + } + foreach (var row in rows) { + _application.Logger.Info($"DOF row {row.Rom} of {row.FileName} puts toys on {Ports(row.Columns.SelectMany(c => Enumerable.Range(c.Port, c.Width)).ToList())}."); + } + if (devices != null) { + _application.Logger.Info("DOF devices: " + (devices.Count == 0 ? "none" : string.Join(", ", devices.Select(d => $"{d.Number} ({d.Count}{(d.Truncated ? "+" : "")} ports)"))) + "."); + foreach (var problem in Unreachable(rows, devices, _hasCabinet)) { + _application.Logger.Warn(problem); + } + } PublishDiagnostics(true); } @@ -458,6 +527,160 @@ private string GameConfig(DofRevision revision, DofCatalog catalog, PluginGameCo } } + /// A row of the game, in the ini file the game's DOF reads. + internal readonly struct DofRowSource + { + public readonly int Device; + public readonly string Rom; + public readonly string FileName; + public readonly string Path; + + public DofRowSource(int device, string rom, string fileName, string path) + { + Device = device; + Rom = rom; + FileName = fileName; + Path = path; + } + } + + /// The columns a row of the game puts something on, by their first port and how many ports they take. + internal readonly struct DofRowPorts + { + public readonly int Device; + public readonly string Rom; + public readonly string FileName; + public readonly IReadOnlyList<(int Port, int Width)> Columns; + + public DofRowPorts(int device, string rom, string fileName, IReadOnlyList<(int Port, int Width)> columns) + { + Device = device; + Rom = rom; + FileName = fileName; + Columns = columns; + } + } + + /// The columns of the game's rows, for the log; never throws, the rows read before a problem and the problem. + private static (IReadOnlyList Rows, Exception Problem) ReadRows(IReadOnlyList sources) + { + var rows = new List(); + try { + foreach (var source in sources) { + var ini = DofIniRow.Read(source.Path, source.Rom); + if (ini != null) { + rows.Add(new DofRowPorts(source.Device, source.Rom, source.FileName, Columns(ini))); + } + } + return (rows, null); + } catch (Exception e) { + return (rows, e); + } + } + + /// + /// The columns a row puts something on: one port each, three for a colour. A column of 0, OFF or only + /// those puts nothing; a variable counts as something, as it is written. + /// + internal static IReadOnlyList<(int Port, int Width)> Columns(DofIniRow row) + { + var columns = new List<(int, int)>(); + var port = 1; + while (port <= row.Extent) { + // null for a port of a wider column; a colour takes three + var single = row.SettingOf(port, 1); + if (single != null) { + if (Fires(single)) { + columns.Add((port, 1)); + } + port++; + continue; + } + var colour = row.SettingOf(port, 3); + if (colour == null) { + port++; + continue; + } + if (Fires(colour)) { + columns.Add((port, 3)); + } + port += 3; + } + return columns; + } + + // a part that starts with 0 or OFF is fixed off, whatever follows: libdof discards it + private static bool Fires(string setting) => setting.Split('/') + .Select(s => s.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? "") + .Any(s => s.Length > 0 && s != DofIniRow.Nothing && !s.Equals("off", StringComparison.OrdinalIgnoreCase)); + + /// + /// Why toys of the game's rows don't fire on the devices DOF set up: a device it has none of, or columns whose ports + /// drive nothing on it, such as ports past its last. A toy a column's first port names takes the whole column. + /// + internal static IEnumerable Unreachable(IReadOnlyList rows, IReadOnlyList devices, bool hasCabinet) + { + foreach (var row in rows) { + if (row.Columns.Count == 0) { + continue; + } + DofDevicePorts? found = null; + foreach (var d in devices) { + if (d.Number == row.Device) { + found = d; + break; + } + } + if (found == null) { + yield return $"DOF row {row.Rom} of {row.FileName} puts toys on device {row.Device}, which DOF did not set up, so none of them fire: " + + (hasCabinet + ? $"neither the cabinet file nor a board DOF found sets up a device {row.Device}." + : $"there is no cabinet file, and DOF found no board that is device {row.Device}."); + continue; + } + var device = found.Value; + var none = new List(); + foreach (var (port, width) in row.Columns) { + // past what the description lists, nothing is known + if (device.Truncated && port > device.Count) { + continue; + } + var first = device.KindOf(port); + if (first == DofPortKind.Toy) { + continue; + } + // of a colour on outputs, the described ports that drive nothing + var last = device.Truncated ? Math.Min(port + width - 1, device.Count) : port + width - 1; + none.AddRange(Enumerable.Range(port, last - port + 1).Where(p => device.KindOf(p) == DofPortKind.None)); + } + if (none.Count == 0) { + continue; + } + yield return $"DOF row {row.Rom} of {row.FileName} puts toys on {Ports(none)} of device {row.Device}, which drive nothing " + + (device.Truncated ? $"(the description of device {row.Device} ends at port {device.Count})" : $"(device {row.Device} goes up to port {device.Count})") + + ", so those toys don't fire" + + (hasCabinet ? "." : ". Without a cabinet file DOF sets up a board with the outputs it has; a cabinet file can give the device more."); + } + } + + /// Ports in ranges: "port 7", "ports 1-4, 7", "no ports". + internal static string Ports(IReadOnlyList ports) + { + if (ports.Count == 0) { + return "no ports"; + } + var parts = new List(); + for (var i = 0; i < ports.Count;) { + var j = i; + while (j + 1 < ports.Count && ports[j + 1] == ports[j] + 1) { + j++; + } + parts.Add(j > i ? $"{ports[i]}-{ports[j]}" : ports[i].ToString(System.Globalization.CultureInfo.InvariantCulture)); + i = j + 1; + } + return (ports.Count == 1 ? "port " : "ports ") + string.Join(", ", parts); + } + /// The ROM the gamelogic engine plays, which PinMAME prepares first; null for other engines. private static string RunningRom(IUnityGameScene scene, GameIdentity game) { @@ -560,6 +783,9 @@ public void Describe(DiagnosticsWriter writer) writer.Add("plugin", DofPluginFactory.Id); writer.Add("status", State); writer.Add("revision", _revision ?? "none"); + if (_origin != null) { + writer.Add("revision.origin", _origin); + } writer.Add("rom", _rom ?? "none"); if (_romProblem != null) { writer.Add("rom.problem", _romProblem); diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs index 640deff..eb69e02 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs @@ -979,9 +979,12 @@ public Task TestOutputAsync(string provider, string output, return new PluginActionResult(false, "Unknown DOF outputs."); } try { - return PulsePort(output, leases, cancellation); + var result = PulsePort(output, leases, cancellation); + // what the test said, for a report; device:port, as the page names the output + Logger.Info($"[DOF] Test of {output}: {result.Message}"); + return result; } catch (DofException e) { - Logger.Warn(e, "[DOF] Testing output " + output + " failed."); + Logger.Warn(e, $"[DOF] Test of {output} failed: {e.Message}"); return new PluginActionResult(false, e.Message); } }, cancellation); @@ -1315,6 +1318,14 @@ public Task RunActionAsync(string action, PluginChoiceReques } private PluginActionResult RunAction(string action, PluginChoiceRequest request, PluginOutputLeases leases, CancellationToken cancellation) + { + var result = RunActionUnlogged(action, request, leases, cancellation); + // what the page said, for a report: an action that changes nothing writes nothing else + Logger.Info($"[DOF] {action}: {(result.Success ? "" : "refused: ")}{result.Message}"); + return result; + } + + private PluginActionResult RunActionUnlogged(string action, PluginChoiceRequest request, PluginOutputLeases leases, CancellationToken cancellation) { try { switch (action) { diff --git a/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs b/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs index 1f98a42..d35db7a 100644 --- a/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs +++ b/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs @@ -283,6 +283,55 @@ public void TestsAPortOutsideAGame() } } + [Test] + public void LogsTheToysAGameCantFire() + { + // a Pinscape with 16 outputs and no cabinet file, a row with toys up to port 22, as a tester had it + var row = DofIniRow.Parse("[Config DOF]\nt2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,S4/S5/S9,S6/S8,S46,S48,0,S2 600 I25\n", "t2"); + var columns = DofPlugin.Columns(row); + Assert.That(columns, Is.EqualTo(new[] { (17, 1), (18, 1), (19, 1), (20, 1), (22, 1) })); + var rows = new[] { + new DofPlugin.DofRowPorts(51, "t2", "directoutputconfig51.ini", columns), + new DofPlugin.DofRowPorts(30, "t2", "directoutputconfig30.ini", new[] { (1, 3) }), + }; + var devices = new[] { new DofDevicePorts(51, new string('o', 16)) }; + Assert.That(DofPlugin.Unreachable(rows, devices, false), Is.EqualTo(new[] { + "DOF row t2 of directoutputconfig51.ini puts toys on ports 17-20, 22 of device 51, which drive nothing (device 51 goes up to port 16), so those toys " + + "don't fire. Without a cabinet file DOF sets up a board with the outputs it has; a cabinet file can give the device more.", + "DOF row t2 of directoutputconfig30.ini puts toys on device 30, which DOF did not set up, so none of them fire: there is no cabinet file, and DOF " + + "found no board that is device 30.", + })); + // what a cabinet file maps fires; a toy a column's first port names takes the whole column + devices = new[] { new DofDevicePorts(51, new string('o', 20) + "tt"), new DofDevicePorts(30, "t") }; + Assert.That(DofPlugin.Unreachable(rows, devices, true), Is.Empty); + Assert.That(DofPlugin.Unreachable(rows, new[] { new DofDevicePorts(51, new string('o', 16) + "-o-ooo") }, true), Is.EqualTo(new[] { + "DOF row t2 of directoutputconfig51.ini puts toys on ports 17, 19 of device 51, which drive nothing (device 51 goes up to port 22), so those toys don't fire.", + "DOF row t2 of directoutputconfig30.ini puts toys on device 30, which DOF did not set up, so none of them fire: neither the cabinet file nor a board " + + "DOF found sets up a device 30.", + })); + // a colour on outputs needs all three; past a truncated description nothing is said + var colour = new[] { new DofPlugin.DofRowPorts(1, "t2", "directoutputconfig.ini", new[] { (1, 3), (4, 3) }) }; + Assert.That(DofPlugin.Unreachable(colour, new[] { new DofDevicePorts(1, "ooooo") }, true), Is.EqualTo(new[] { + "DOF row t2 of directoutputconfig.ini puts toys on port 6 of device 1, which drive nothing (device 1 goes up to port 5), so those toys don't fire.", + })); + Assert.That(DofPlugin.Unreachable(colour, new[] { new DofDevicePorts(1, "ooooo+") }, true), Is.Empty); + Assert.That(DofPlugin.Unreachable(colour, new[] { new DofDevicePorts(1, "o-oooo+") }, true), Is.EqualTo(new[] { + "DOF row t2 of directoutputconfig.ini puts toys on port 2 of device 1, which drive nothing (the description of device 1 ends at port 6), so those toys don't fire.", + })); + // a colour across the end of a truncated description: its described ports still count + Assert.That(DofPlugin.Unreachable(colour, new[] { new DofDevicePorts(1, "oooo-+") }, true), Is.EqualTo(new[] { + "DOF row t2 of directoutputconfig.ini puts toys on port 5 of device 1, which drive nothing (the description of device 1 ends at port 5), so those toys don't fire.", + })); + Assert.That(DofPlugin.Unreachable(colour, new[] { new DofDevicePorts(1, "ooot-+") }, true), Is.Empty); + + // 0, OFF and only those fire nothing, whatever follows them; a colour takes three ports + row = DofIniRow.Parse("[Config DOF]\nr,OFF 100,0/0,S1 Red,0 50,S2\n", "r"); + Assert.That(DofPlugin.Columns(row), Is.EqualTo(new[] { (3, 3), (7, 1) })); + Assert.That(DofPlugin.Ports(new[] { 17, 18, 19, 20, 22 }), Is.EqualTo("ports 17-20, 22")); + Assert.That(DofPlugin.Ports(new[] { 6 }), Is.EqualTo("port 6")); + Assert.That(DofPlugin.Ports(new int[0]), Is.EqualTo("no ports")); + } + [Test] public void SaysWhyATestCantSetAPort() { diff --git a/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs b/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs index a8ec84a..714e59e 100644 --- a/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs +++ b/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs @@ -136,6 +136,7 @@ public static DofCatalog Load(DofRevision revision) var cabinetControllers = new List(); var hasCabinet = false; var cabinetOutputs = new Dictionary(); + var cabinetDevices = new SortedSet(); var mappings = new List>(); var legacy = new List(); var current = new List(); @@ -164,6 +165,7 @@ public static DofCatalog Load(DofRevision revision) foreach (var (device, output) in LedWizEquivalentOutputs(xml)) { cabinetOutputs[device] = Math.Max(output, cabinetOutputs.TryGetValue(device, out var known) ? known : 0); } + cabinetDevices.UnionWith(CabinetDevices(xml)); break; case DofXmlKind.TableMappings: foreach (var mapping in DofXml.Children(xml.Root, "Mapping")) { @@ -189,9 +191,42 @@ public static DofCatalog Load(DofRevision revision) return new DofCatalog(revision, devices, effective ?? rows, effective != null, mappings, revision.TableConfigs, cabinetControllers) { HasCabinet = hasCabinet, CabinetOutputs = cabinetOutputs, + CabinetDevicesWithoutIni = cabinetDevices.Where(d => devices.All(i => i.Number != d)).ToList(), + LegacyInis = current.Count == 0 && legacy.Count > 0, }; } + /// + /// The devices the cabinet file's LedWiz equivalents stand for that no ini file of the configuration is: no row puts + /// anything on them, so their toys never fire. + /// + public IReadOnlyList CabinetDevicesWithoutIni { get; private set; } = Array.Empty(); + + /// Whether the configuration's ini files are ledcontrol files, which libdof reads only without directoutputconfig ones. + public bool LegacyInis { get; private set; } + + /// + /// Why a device the cabinet file sets up drives nothing. Names the file of the configuration's kind: next to ledcontrol + /// files a directoutputconfig file would make libdof ignore them all. + /// + public static string CabinetDeviceWithoutIni(int device, bool legacy) + => $"The cabinet file sets up device {device}, but no ini file is device {device} ({(legacy ? "ledcontrol" : "directoutputconfig")}{device}.ini), so no toy of device {device} fires."; + + /// The ini devices a cabinet file's LedWiz equivalents stand for, with outputs or without. + internal static IReadOnlyList CabinetDevices(System.Xml.Linq.XDocument xml) + { + if (xml.Root == null || DofXml.LiteralName(xml.Root) != "Cabinet") { + return Array.Empty(); + } + return (DofXml.FirstChild(xml.Root, "Toys")?.Elements() ?? Enumerable.Empty()) + .Where(t => DofXml.LiteralName(t) == "LedWizEquivalent") + .Select(t => int.TryParse(DofXml.Value(t, "LedWizNumber"), out var device) ? device : -1) + .Where(d => d >= 0) + .Distinct() + .OrderBy(d => d) + .ToList(); + } + /// 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/DofImportReport.cs b/VisualPinball.Engine.DOF/Configuration/DofImportReport.cs index 0a58458..f32c05a 100644 --- a/VisualPinball.Engine.DOF/Configuration/DofImportReport.cs +++ b/VisualPinball.Engine.DOF/Configuration/DofImportReport.cs @@ -82,6 +82,8 @@ public string RejectionReason internal void Info(DofReportTopic topic, string message) => _entries.Add(new DofReportEntry(DofReportSeverity.Info, topic, message)); internal void Warning(DofReportTopic topic, string message) => _entries.Add(new DofReportEntry(DofReportSeverity.Warning, topic, message)); internal void Error(string message) => _entries.Add(new DofReportEntry(DofReportSeverity.Error, DofReportTopic.General, message)); + internal void InsertWarning(int index, DofReportTopic topic, string message) => _entries.Insert(index, new DofReportEntry(DofReportSeverity.Warning, topic, message)); + internal void RemoveAt(int index) => _entries.RemoveAt(index); public override string ToString() => Format(Revision); diff --git a/VisualPinball.Engine.DOF/Configuration/DofImporter.cs b/VisualPinball.Engine.DOF/Configuration/DofImporter.cs index b3f0876..ed1c772 100644 --- a/VisualPinball.Engine.DOF/Configuration/DofImporter.cs +++ b/VisualPinball.Engine.DOF/Configuration/DofImporter.cs @@ -105,6 +105,8 @@ public DofImportReport Import(string source, DofImportMode mode, IReadOnlyDictio 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)}."); var staging = _store.CreateStaging(); try { var input = Path.Combine(staging, "in"); @@ -119,12 +121,13 @@ public DofImportReport Import(string source, DofImportMode mode, IReadOnlyDictio if (report.HasErrors) { return report; } + report.Info(DofReportTopic.Files, Found(input)); var imported = Classify(input, report); if (report.HasErrors) { return report; } - var previous = mode == DofImportMode.Merge ? _store.Active : null; - var config = Merge(imported, previous, report); + var active = _store.Active; + var config = Merge(imported, mode == DofImportMode.Merge ? active : null, active != null, report); if (report.HasErrors) { return report; } @@ -140,7 +143,10 @@ public DofImportReport Import(string source, DofImportMode mode, IReadOnlyDictio if (report.HasErrors) { return report; } - Write(config, report); + // 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); 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}"); @@ -238,16 +244,24 @@ private static bool SetSerialPorts(ConfigSet config, IReadOnlyDictionary Limits.MaxEntries) { - report.Error($"The zip has {zip.Entries.Count} entries, more than the {Limits.MaxEntries} a DOF configuration can have."); - return; - } long total = 0; + var entries = 0; + var examples = new SortedSet(StringComparer.Ordinal); foreach (var entry in zip.Entries) { var name = entry.FullName.Replace('\\', '/'); if (name.EndsWith("/", StringComparison.Ordinal)) { continue; } + // before any limit: an example is never the configuration, and it is not unpacked + var example = OutermostExamples(Parent(name)); + if (example != null) { + examples.Add(example); + continue; + } + if (++entries > Limits.MaxEntries) { + report.Error($"The zip has more than {Limits.MaxEntries} entries, more than a DOF configuration can have."); + return; + } var relative = SafeRelativePath(name, report); if (relative == null) { return; @@ -284,6 +298,21 @@ private void StageZip(string zipPath, string input, DofImportReport report) return; } } + ReportExamples(examples.Take(MaxListedExamples).ToList(), examples.Count, report); + } + } + + /// + /// A line per skipped folder of examples, but not a line for each of the folders an import can make up: they + /// count against no limit. + /// + private static void ReportExamples(IReadOnlyCollection listed, int count, DofImportReport report) + { + foreach (var folder in listed) { + report.Info(DofReportTopic.Files, $"Skipped the folder {folder}: it holds DOF's examples."); + } + if (count > listed.Count) { + report.Info(DofReportTopic.Files, $"Skipped {count - listed.Count} more folders of DOF's examples."); } } @@ -292,11 +321,21 @@ private void StageFolder(string folder, string input, DofImportReport report) var root = Path.GetFullPath(folder); var seen = 0; long total = 0; + // the first few, for the report: the others are only counted, as they count against no limit + var examples = new List(); + var exampleCount = 0; var pending = new Stack<(string dir, int depth)>(); pending.Push((root, 0)); while (pending.Count > 0) { var (dir, depth) = pending.Pop(); foreach (var entry in new DirectoryInfo(dir).EnumerateFileSystemInfos()) { + // before it counts against the limits, as its files don't: it's never the configuration + if (entry is DirectoryInfo example && IsExamples(example.Name) && (entry.Attributes & FileAttributes.ReparsePoint) == 0) { + if (exampleCount++ < MaxListedExamples) { + examples.Add(Relative(root, example.FullName)); + } + continue; + } if (++seen > Limits.MaxEntries) { report.Error($"{folder} has more than {Limits.MaxEntries} files and folders; choose the folder that holds the DOF configuration."); return; @@ -307,9 +346,12 @@ private void StageFolder(string folder, string input, DofImportReport report) continue; } if (entry is DirectoryInfo sub) { + if (Ignored(sub.Name)) { + continue; + } if (depth + 1 > Limits.MaxDepth) { report.Info(DofReportTopic.Files, $"Skipped {Relative(root, sub.FullName)}: nested too deep."); - } else if (!Ignored(sub.Name)) { + } else { pending.Push((sub.FullName, depth + 1)); } continue; @@ -347,6 +389,7 @@ private void StageFolder(string folder, string input, DofImportReport report) file.CopyTo(target); } } + ReportExamples(examples, exampleCount, report); } // the root object's first member, as the tool writes it: a "type" deeper in another file is not its @@ -441,6 +484,24 @@ private static long CopyBounded(Stream from, Stream to, long max) return copied; } + /// How many staged files a report lists by name. + internal const int FoundListed = 100; + + /// The files staged for the import, so a report shows what the source held and not only what was used. + private static string Found(string input) + { + var files = Directory.GetFiles(input, "*", SearchOption.AllDirectories) + .Select(f => Relative(input, f)) + .OrderBy(f => f, StringComparer.OrdinalIgnoreCase) + .ToList(); + if (files.Count == 0) { + return "Found no DOF configuration files."; + } + var listed = string.Join(", ", files.Take(FoundListed)); + var more = files.Count > FoundListed ? $", and {files.Count - FoundListed} more" : ""; + return (files.Count == 1 ? "Found 1 file: " : $"Found {files.Count} files: ") + listed + more + "."; + } + /// A path below root with '/' separators, for messages. Only the platform's separators are replaced. private static string Relative(string root, string path) { @@ -489,6 +550,121 @@ private sealed class ConfigFile public XDocument Xml; } + /// + /// The files the import reads, those of the configuration folder first. The configuration folder is the shallowest + /// one with a directoutputconfig ini file (a ledcontrol one if there is none), or the one named Config among several. + /// Other folders with ini files are other configurations and an Examples folder holds DOF's examples: they are + /// skipped, so their files of the same names don't clash with the configuration's. Without a single configuration + /// folder, all files are read. + /// + private static (IReadOnlyList Files, string Config) ConfigFiles(string input, DofImportReport report) + { + var files = Directory.GetFiles(input, "*", SearchOption.AllDirectories).OrderBy(p => p, StringComparer.Ordinal).ToList(); + var inis = files + .Select(f => (Folder: Relative(input, System.IO.Path.GetDirectoryName(f)), Name: System.IO.Path.GetFileName(f))) + .Where(f => DofIniFile.IsIniName(f.Name) && DofIniFile.DeviceOf(f.Name, out _) >= 0) + .Select(f => (f.Folder, Legacy: DofIniFile.DeviceOf(f.Name, out var legacy) >= 0 && legacy)) + .ToList(); + var folders = inis.Select(i => i.Folder).Distinct(StringComparer.Ordinal).ToList(); + // DOF's examples are never the configuration + var own = inis.Where(i => !InExamples(i.Folder)).ToList(); + var current = own.Where(i => !i.Legacy).Select(i => i.Folder).Distinct(StringComparer.Ordinal).ToList(); + var candidates = current.Count > 0 ? current : own.Select(i => i.Folder).Distinct(StringComparer.Ordinal).ToList(); + if (candidates.Count == 0) { + return (WithoutExamples(input, files, report), null); + } + var depth = candidates.Min(Depth); + var shallowest = candidates.Where(f => Depth(f) == depth).ToList(); + // next to others, the one DOF's installer makes + if (shallowest.Count > 1) { + shallowest = shallowest.Where(f => string.Equals(LastSegment(f), "Config", StringComparison.OrdinalIgnoreCase)).ToList(); + } + if (shallowest.Count != 1) { + return (WithoutExamples(input, files, report), null); + } + var config = shallowest[0]; + var mine = new List(); + var others = new List(); + var skipped = new SortedDictionary(StringComparer.Ordinal); + foreach (var file in files) { + var folder = Relative(input, System.IO.Path.GetDirectoryName(file)); + if (folder == config) { + mine.Add(file); + continue; + } + // the outermost folder on the file's way that is another configuration or examples, below where the ways part + string other = null; + for (var f = folder; f.Length > 0 && !IsWithin(config, f); f = Parent(f)) { + if (folders.Contains(f) || IsExamples(f)) { + other = f; + } + } + if (other == null) { + others.Add(file); + continue; + } + skipped[other] = skipped.TryGetValue(other, out var count) ? count + 1 : 1; + } + var where = config.Length == 0 ? "the imported folder itself" : config; + foreach (var pair in skipped) { + report.Info(DofReportTopic.Files, $"Skipped the folder {pair.Key} ({(pair.Value == 1 ? "1 file" : $"{pair.Value} files")}): it is not the configuration folder, which is {where}."); + } + mine.AddRange(others); + return (mine, config); + } + + /// All files but DOF's examples, for an import without a single configuration folder. + private static IReadOnlyList WithoutExamples(string input, List files, DofImportReport report) + { + var skipped = new SortedDictionary(StringComparer.Ordinal); + var kept = new List(); + foreach (var file in files) { + string examples = null; + for (var f = Relative(input, System.IO.Path.GetDirectoryName(file)); f.Length > 0; f = Parent(f)) { + if (IsExamples(f)) { + examples = f; + } + } + if (examples == null) { + kept.Add(file); + } else { + skipped[examples] = skipped.TryGetValue(examples, out var count) ? count + 1 : 1; + } + } + foreach (var pair in skipped) { + report.Info(DofReportTopic.Files, $"Skipped the folder {pair.Key} ({(pair.Value == 1 ? "1 file" : $"{pair.Value} files")}): it holds DOF's examples."); + } + return kept; + } + + private static string Parent(string relative) => relative.LastIndexOf('/') < 0 ? "" : relative.Substring(0, relative.LastIndexOf('/')); + + private static string LastSegment(string relative) => relative.Substring(relative.LastIndexOf('/') + 1); + + private const int MaxListedExamples = 10; + + private static bool IsExamples(string relative) => LastSegment(relative).Equals("Examples", StringComparison.OrdinalIgnoreCase) || LastSegment(relative).Equals("Example", StringComparison.OrdinalIgnoreCase); + + private static bool InExamples(string relative) => OutermostExamples(relative) != null; + + /// The outermost examples folder is or lies in, or null. + private static string OutermostExamples(string relative) + { + string examples = null; + for (var f = relative; f.Length > 0; f = Parent(f)) { + if (IsExamples(f)) { + examples = f; + } + } + return examples; + } + + /// Whether a relative folder is or lies below it. + private static bool IsWithin(string path, string folder) => folder.Length == 0 || path == folder || path.StartsWith(folder + "/", StringComparison.Ordinal); + + /// How many folders deep a relative folder is; the root is 0. + private static int Depth(string relative) => relative.Length == 0 ? 0 : relative.Count(c => c == '/') + 1; + private ConfigSet Classify(string input, DofImportReport report) { var set = new ConfigSet(); @@ -498,7 +674,8 @@ private ConfigSet Classify(string input, DofImportReport report) var shapes = new List(); var mappings = new List(); - foreach (var path in Directory.GetFiles(input, "*", SearchOption.AllDirectories).OrderBy(p => p, StringComparer.Ordinal)) { + var (paths, config) = ConfigFiles(input, report); + foreach (var path in paths) { var origin = Relative(input, path); var name = System.IO.Path.GetFileName(path); if (name.Any(c => c >= 128)) { @@ -507,6 +684,13 @@ private ConfigSet Classify(string input, DofImportReport report) } // One configuration is one folder: the same name twice must be the same file. if (byName.TryGetValue(name, out var existing)) { + // the configuration folder's own file comes first and wins + if (config != null && Relative(input, System.IO.Path.GetDirectoryName(existing.Path)) == config && Relative(input, System.IO.Path.GetDirectoryName(path)) != config) { + if (!File.ReadAllBytes(existing.Path).SequenceEqual(File.ReadAllBytes(path))) { + report.Info(DofReportTopic.Files, $"Skipped {origin}: the configuration folder has its own {name}."); + } + continue; + } if (!File.ReadAllBytes(existing.Path).SequenceEqual(File.ReadAllBytes(path))) { report.Error($"The import has two different files named {name} ({existing.Origin} and {origin}). Import the folder of one configuration."); return set; @@ -712,12 +896,18 @@ private static ConfigFile Pick(List files, string what, FuncThe active configuration to merge into, or null when the import replaces it. + /// Whether a configuration is active, merged into or not. + private static ConfigSet Merge(ConfigSet imported, DofRevision previous, bool hasActive, DofImportReport report) { if (previous == null) { SelectCabinet(imported, null, report); if (imported.Inis.Count == 0) { - report.Error("The import has no DOF ini file (directoutputconfig.ini or directoutputconfigN.ini), so DOF would have nothing to do."); + // a folder with only the cabinet is the common case: it can still be added to the active configuration + report.Error("The import has no DOF ini file (directoutputconfig.ini or directoutputconfigN.ini), so DOF would have nothing to do." + + (hasActive && imported.Cabinets.Count == 1 + ? $" To add its cabinet file to the active configuration, import {imported.Cabinets[0].Origin} itself instead of the folder." + : "")); } return imported; } @@ -767,6 +957,35 @@ private static ConfigSet Merge(ConfigSet imported, DofRevision previous, DofImpo return imported; } + /// + /// The warning about the ini files and the cabinet of the active configuration that an import replacing it no longer + /// has, or null: importing a folder after a zip drops the zip's ini files, which is easy to miss. + /// + private static string Replaced(DofRevision active, ConfigSet config) + { + DofCatalog old; + string origin; + try { + old = DofCatalog.Load(active); + origin = active.ReadOrigin() ?? $"revision {active.Id}"; + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is FormatException || e is System.Xml.XmlException || e is InvalidOperationException) { + // a damaged old revision is no reason to refuse a good import; only the warning is lost + return null; + } + var dropped = old.Devices + .Select(d => d.FileName) + .Where(n => !config.Inis.Values.Any(f => string.Equals(f.Name, n, StringComparison.OrdinalIgnoreCase))) + .ToList(); + if (old.HasCabinet && config.Cabinet == null) { + dropped.Add("its cabinet file"); + } + if (dropped.Count == 0) { + 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."; + } + /// The files of an existing revision as a configuration set, for merging. private static ConfigSet Read(DofRevision revision) { @@ -886,6 +1105,10 @@ private static void Analyse(ConfigSet config, bool windowsPorts, DofImportReport if (config.Cabinet != null) { AnalyseCabinet(config.Cabinet, windowsPorts, report); + var legacy = config.Inis.Values.Any(f => DofIniFile.DeviceOf(f.Name, out var isLegacy) >= 0 && isLegacy); + foreach (var device in DofCatalog.CabinetDevices(config.Cabinet.Xml).Where(d => !config.Inis.ContainsKey(d))) { + report.Warning(DofReportTopic.General, DofCatalog.CabinetDeviceWithoutIni(device, legacy)); + } } foreach (var table in config.TableConfigs.Values) { report.Warning(DofReportTopic.Unsupported, $"Table config {table.Name} is kept but not loaded: the player does not load table configs yet, so the ini rows drive the outputs instead."); @@ -980,10 +1203,13 @@ private static void AnalyseRomMatching(IReadOnlyList rows, DofImportR #region Writing - private void Write(ConfigSet config, DofImportReport report) + /// 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) { var revision = _store.CreateRevision(); var published = false; + var replacedEntry = -1; try { Directory.CreateDirectory(revision.ConfigDir); Directory.CreateDirectory(revision.TablesDir); @@ -1044,6 +1270,10 @@ private void Write(ConfigSet config, DofImportReport report) rows = config.Inis.SelectMany(p => p.Value.Ini.Roms.Select(r => new DofRomRow(p.Key, r))).ToList(); } AnalyseRomMatching(rows, report); + if (replaced != null) { + replacedEntry = Math.Min(replacedAt, report.Entries.Count); + report.InsertWarning(replacedEntry, DofReportTopic.Files, replaced); + } File.WriteAllText(Path.Combine(revision.BasePath, DofRevision.ReportFile), report.Format(revision.Id)); if (!string.IsNullOrEmpty(report.Origin)) { File.WriteAllText(Path.Combine(revision.BasePath, DofRevision.OriginFile), report.Origin, new UTF8Encoding(false)); @@ -1053,6 +1283,10 @@ private void Write(ConfigSet config, DofImportReport report) report.Revision = revision.Id; } finally { if (!published) { + // the previous configuration stays in use after all + if (replacedEntry >= 0) { + report.RemoveAt(replacedEntry); + } _store.Discard(revision); } }