From 31a024266431fd22f2307947262304fe56adaead Mon Sep 17 00:00:00 2001 From: freezy Date: Wed, 2 Dec 2026 11:19:12 +0100 Subject: [PATCH 01/11] plugins: let a provider put its outputs back as a panel found them IPluginOutputSnapshots keeps what a field's outputs are and restores them, so the Player's output panel can undo what it changed with a Cancel. PluginSettingsSession wraps it like the other output calls. --- .../SetupSettingsTests.cs | 16 +++++++++- .../Configuration/PluginSchema.cs | 32 +++++++++++++++++++ .../Configuration/PluginSettingsSession.cs | 24 ++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) diff --git a/VisualPinball.Plugins.Test/SetupSettingsTests.cs b/VisualPinball.Plugins.Test/SetupSettingsTests.cs index 728fa275f..211e1cad8 100644 --- a/VisualPinball.Plugins.Test/SetupSettingsTests.cs +++ b/VisualPinball.Plugins.Test/SetupSettingsTests.cs @@ -152,6 +152,12 @@ public void OutputMapsComeFromTheProviderAndAreNeverStored() Assert.That(provider.Triggered, Is.EqualTo("ports:1=@t2_l8"), "nothing fires it in this game"); Assert.That(gameSession.HasEdits("outputs"), Is.False, "a trigger takes effect without the draft"); } + Assert.That(session.CanRestoreOutputs, Is.True); + var snapshot = session.SnapshotOutputsAsync("ports", default); PluginHostTests.Run(host, snapshot); + Assert.That(snapshot.Result, Is.EqualTo("ports@kept")); + var restore = session.RestoreOutputsAsync("ports", snapshot.Result!, default); PluginHostTests.Run(host, restore); + Assert.That(restore.Result.Success, Is.True); Assert.That(provider.Restored, Is.EqualTo("ports(() => host.CommitSettingAsync(factory, "outputs", new JValue("x"))); session.Reset(); Assert.That(session.HasEdits("outputs"), Is.False); var plain = new TestFactory("plain") { SettingsProvider = new PlainProvider() }; @@ -163,6 +169,9 @@ public void OutputMapsComeFromTheProviderAndAreNeverStored() Assert.That(plainSession.AddToyAsync("ports", "1", "Shaker", default).Result.Success, Is.False); using (var plainGame = new PluginSettingsSession(plain, Host(plain).Configuration, "windows", new GameIdentity("pinmame", "t2_l8"))) Assert.That(plainGame.SetOutputTriggerAsync("ports", "1", "S28", default).Result.Success, Is.False); + Assert.That(plainSession.CanRestoreOutputs, Is.False); + Assert.That(plainSession.SnapshotOutputsAsync("ports", default).Result, Is.Null); + Assert.That(plainSession.RestoreOutputsAsync("ports", "ports@kept", default).Result.Success, Is.False); var twice = new PluginOutputBoard("twice", "", new[] { new PluginOutput("1", 1, ""), new PluginOutput("1", 1, "") }); Assert.Throws(() => new PluginOutputMap(new[] { twice }), "a test could not tell the outputs apart"); var toys = new PluginOutputBoard("toys", "", new[] { new PluginOutput("1", 1, "Shaker") { Toy = "shaker" } }) { @@ -184,8 +193,13 @@ public Task RunActionAsync(string action, PluginChoiceReques private sealed class ProgressSink : IProgress { internal PluginActionProgress Last; public void Report(PluginActionProgress value) => Last = value; } private sealed class Provider : IPluginSettingsProvider, IPluginSettingsInfoProvider, IPluginOutputMapProvider, IPluginOutputRearranger, IPluginOutputAssigner, - IPluginOutputTriggerEditor + IPluginOutputTriggerEditor, IPluginOutputSnapshots { + internal string? Restored; + public Task SnapshotOutputsAsync(string provider, PluginChoiceRequest request, CancellationToken cancellation) + => Task.FromResult(provider + "@kept"); + public Task RestoreOutputsAsync(string provider, string snapshot, PluginChoiceRequest request, CancellationToken cancellation) + { Restored = provider + "<" + snapshot; return Task.FromResult(new PluginActionResult(true, "Restored")); } internal string? Triggered; public Task SetTriggerAsync(string provider, string output, string? trigger, PluginChoiceRequest request, CancellationToken cancellation) { Triggered = $"{provider}:{output}={trigger ?? "configuration"}@{request.Game?.Key}"; return Task.FromResult(new PluginActionResult(true, "Set")); } diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index 9b8bfb602..bf2aef763 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -1217,4 +1217,36 @@ public interface IPluginOutputTriggerEditor /// The result to show; is ignored. Task SetTriggerAsync(string provider, string output, string? trigger, PluginChoiceRequest request, CancellationToken cancellation); } + + /// + /// Implemented, in addition to or , by a provider + /// that can put its outputs back as they were: the Player keeps them as the panel that changes an output opens, and its + /// Cancel undoes what the user changed there. + /// + /// + /// The same threading rules as for apply. The Player waits for a call to finish before it + /// makes the next. + /// + public interface IPluginOutputSnapshots + { + /// + /// Keeps what a field's outputs are now: what they drive and, for a game, what fires them; whatever + /// and change for that field. + /// + /// The field's . + /// The game, table and draft settings; is empty. + /// Cancelled when the page is closed. + /// The outputs as they are, in a form only the plugin reads; throws when they can't be read. + Task SnapshotOutputsAsync(string provider, PluginChoiceRequest request, CancellationToken cancellation); + /// + /// Puts a field's outputs back as kept them. A call that fails or is cancelled changes + /// nothing. + /// + /// The field's . + /// What returned for the same provider. + /// The game, table and draft settings; is empty. + /// Cancelled when the page is closed. + /// The result to show; is ignored. + Task RestoreOutputsAsync(string provider, string snapshot, PluginChoiceRequest request, CancellationToken cancellation); + } } diff --git a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs index dd357bc8f..4b57f55f5 100644 --- a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs +++ b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs @@ -256,6 +256,30 @@ public Task SetOutputTriggerAsync(string provider, string ou => !Game.HasValue ? Task.FromResult(new PluginActionResult(false, "Choose a game first: a trigger is changed for one game.")) : (_factory.SettingsProvider as IPluginOutputTriggerEditor)?.SetTriggerAsync(provider, output, trigger?.Trim(), Request(Effective), cancellation) ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot change what makes its outputs fire.")); + /// Whether the plugin can put the outputs of a field back as they were, through . + public bool CanRestoreOutputs => _factory.SettingsProvider is IPluginOutputSnapshots; + /// + /// Keeps what the outputs of an field are now, through + /// , for . + /// + /// The field's . + /// Passed to the provider. + /// What the provider kept, or null when the plugin cannot put outputs back. + public async Task SnapshotOutputsAsync(string provider, CancellationToken cancellation) + => _factory.SettingsProvider is IPluginOutputSnapshots snapshots + ? await snapshots.SnapshotOutputsAsync(provider, Request(Effective), cancellation).ConfigureAwait(false) + : null; + /// + /// Puts the outputs of an field back as kept them, + /// through . Takes effect at once; the draft is not involved. + /// + /// The field's . + /// What returned. + /// Passed to the provider. + /// The provider's result, or a failure when the plugin cannot put outputs back. + public Task RestoreOutputsAsync(string provider, string snapshot, CancellationToken cancellation) + => (_factory.SettingsProvider as IPluginOutputSnapshots)?.RestoreOutputsAsync(provider, snapshot, Request(Effective), cancellation) + ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot put its outputs back.")); /// /// Runs the action of an action field through , such as PinUP locating /// LibVLC. When it succeeds and returns , the values of the fields editable in this From f67fe1e90dc7fb67dbfe850ba68b12c125aabc8f Mon Sep 17 00:00:00 2001 From: freezy Date: Wed, 2 Dec 2026 11:52:14 +0100 Subject: [PATCH 02/11] plugins: let a new toy be an RGB toy on its output and the next two --- VisualPinball.Plugins.Test/SetupSettingsTests.cs | 12 +++++++----- VisualPinball.Plugins/Configuration/PluginSchema.cs | 7 ++++--- .../Configuration/PluginSettingsSession.cs | 5 +++-- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/VisualPinball.Plugins.Test/SetupSettingsTests.cs b/VisualPinball.Plugins.Test/SetupSettingsTests.cs index 211e1cad8..e501b9325 100644 --- a/VisualPinball.Plugins.Test/SetupSettingsTests.cs +++ b/VisualPinball.Plugins.Test/SetupSettingsTests.cs @@ -137,9 +137,11 @@ public void OutputMapsComeFromTheProviderAndAreNeverStored() Assert.That(assign.Result.Success, Is.True); Assert.That(provider.Assigned, Is.EqualTo("ports:1=shaker")); assign = session.AssignOutputAsync("ports", "2", null, default); PluginHostTests.Run(host, assign); Assert.That(provider.Assigned, Is.EqualTo("ports:2=nothing")); - var add = session.AddToyAsync("ports", "2", " Gear motor ", default); PluginHostTests.Run(host, add); + var add = session.AddToyAsync("ports", "2", " Gear motor ", false, default); PluginHostTests.Run(host, add); Assert.That(add.Result.Success, Is.True); Assert.That(provider.Added, Is.EqualTo("ports:2+Gear motor"), "without the spaces around it"); - Assert.That(session.AddToyAsync("ports", "2", " ", default).Result.Success, Is.False, "a toy needs a name"); + Assert.That(session.AddToyAsync("ports", "2", " ", false, default).Result.Success, Is.False, "a toy needs a name"); + add = session.AddToyAsync("ports", "4", "Flasher", true, default); PluginHostTests.Run(host, add); + Assert.That(provider.Added, Is.EqualTo("ports:4+Flasher (RGB)"), "an RGB toy"); Assert.That(session.HasEdits("outputs"), Is.False, "an assignment takes effect without the draft"); var global = session.SetOutputTriggerAsync("ports", "1", "S28", default); Assert.That(global.Result.Success, Is.False, "a trigger is for a game"); Assert.That(provider.Triggered, Is.Null); @@ -166,7 +168,7 @@ public void OutputMapsComeFromTheProviderAndAreNeverStored() Assert.That(plainSession.TestOutputAsync("ports", "1", default).Result.Success, Is.False); Assert.That(plainSession.SwapOutputsAsync("ports", "1", "2", 1, default).Result.Success, Is.False); Assert.That(plainSession.AssignOutputAsync("ports", "1", null, default).Result.Success, Is.False); - Assert.That(plainSession.AddToyAsync("ports", "1", "Shaker", default).Result.Success, Is.False); + Assert.That(plainSession.AddToyAsync("ports", "1", "Shaker", false, default).Result.Success, Is.False); using (var plainGame = new PluginSettingsSession(plain, Host(plain).Configuration, "windows", new GameIdentity("pinmame", "t2_l8"))) Assert.That(plainGame.SetOutputTriggerAsync("ports", "1", "S28", default).Result.Success, Is.False); Assert.That(plainSession.CanRestoreOutputs, Is.False); @@ -209,8 +211,8 @@ public Task SetTriggerAsync(string provider, string output, internal string? Added; public Task AssignOutputAsync(string provider, string output, string? toy, PluginChoiceRequest request, CancellationToken cancellation) { Assigned = $"{provider}:{output}={toy ?? "nothing"}"; return Task.FromResult(new PluginActionResult(true, "Assigned")); } - public Task AddToyAsync(string provider, string output, string name, PluginChoiceRequest request, CancellationToken cancellation) - { Added = $"{provider}:{output}+{name}"; return Task.FromResult(new PluginActionResult(true, "Added")); } + public Task AddToyAsync(string provider, string output, string name, bool rgb, PluginChoiceRequest request, CancellationToken cancellation) + { Added = $"{provider}:{output}+{name}{(rgb ? " (RGB)" : "")}"; return Task.FromResult(new PluginActionResult(true, "Added")); } public Task SwapOutputsAsync(string provider, string first, string second, int count, PluginChoiceRequest request, CancellationToken cancellation) { Swapped = $"{provider}:{first}>{second}x{count}"; return Task.FromResult(new PluginActionResult(true, "Swapped")); } internal PluginOutputLeases? Leases; diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index bf2aef763..93d82d4b6 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -1181,16 +1181,17 @@ public interface IPluginOutputAssigner /// The result to show; is ignored. Task AssignOutputAsync(string provider, string output, string? toy, PluginChoiceRequest request, CancellationToken cancellation); /// - /// Gives an output a new toy of the name the user typed, on a board that ; - /// what the output drove before then drives nothing. The board lists the toy from then on. + /// Gives an output a new toy of the name the user typed, on a board that , + /// or an RGB toy on it and the next two; what they drove before then drives nothing. The board lists the toy from then on. /// /// The field's . /// The of the output. /// The toy's name, not empty. + /// Whether it is an RGB toy: its red on the output, its green and blue on the next two. /// The game, table and draft settings; is empty. /// Cancelled when the page is closed. /// The result to show; is ignored. - Task AddToyAsync(string provider, string output, string name, PluginChoiceRequest request, CancellationToken cancellation); + Task AddToyAsync(string provider, string output, string name, bool rgb, PluginChoiceRequest request, CancellationToken cancellation); } /// diff --git a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs index 4b57f55f5..e7362fe2c 100644 --- a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs +++ b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs @@ -234,11 +234,12 @@ public Task AssignOutputAsync(string provider, string output /// The field's . /// The of the output. /// The toy's name; surrounding spaces are left out. + /// Whether it is an RGB toy, on the output and the next two. /// Passed to the provider. /// The provider's result, or a failure for an empty name or when the plugin cannot add toys. - public Task AddToyAsync(string provider, string output, string name, CancellationToken cancellation) + public Task AddToyAsync(string provider, string output, string name, bool rgb, CancellationToken cancellation) => string.IsNullOrWhiteSpace(name) ? Task.FromResult(new PluginActionResult(false, "Type the toy's name.")) - : (_factory.SettingsProvider as IPluginOutputAssigner)?.AddToyAsync(provider, output, name.Trim(), Request(Effective), cancellation) + : (_factory.SettingsProvider as IPluginOutputAssigner)?.AddToyAsync(provider, output, name.Trim(), rgb, Request(Effective), cancellation) ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot add toys.")); /// /// Sets what makes an output of an field fire in the session's game, or gives it back to From 1d353cd6ca45de776565b8a5af668a4e1c2758ea Mon Sep 17 00:00:00 2001 From: freezy Date: Wed, 2 Dec 2026 12:37:49 +0100 Subject: [PATCH 03/11] plugins: switch a toy between RGB and one output, and test an RGB toy in a colour --- .../SetupSettingsTests.cs | 16 +++++++- .../Configuration/PluginSchema.cs | 39 +++++++++++++++++++ .../Configuration/PluginSettingsSession.cs | 28 +++++++++++++ 3 files changed, 82 insertions(+), 1 deletion(-) diff --git a/VisualPinball.Plugins.Test/SetupSettingsTests.cs b/VisualPinball.Plugins.Test/SetupSettingsTests.cs index e501b9325..960ec55e3 100644 --- a/VisualPinball.Plugins.Test/SetupSettingsTests.cs +++ b/VisualPinball.Plugins.Test/SetupSettingsTests.cs @@ -142,6 +142,11 @@ public void OutputMapsComeFromTheProviderAndAreNeverStored() Assert.That(session.AddToyAsync("ports", "2", " ", false, default).Result.Success, Is.False, "a toy needs a name"); add = session.AddToyAsync("ports", "4", "Flasher", true, default); PluginHostTests.Run(host, add); Assert.That(provider.Added, Is.EqualTo("ports:4+Flasher (RGB)"), "an RGB toy"); + var shape = session.SetToyRgbAsync("ports", "4", false, default); PluginHostTests.Run(host, shape); + Assert.That(provider.Shaped, Is.EqualTo("ports:4 single"), "an RGB toy made one of one output"); + Assert.That(session.CanTestColors, Is.True); + var colour = session.TestOutputColorAsync("ports", "2", 255, 128, 0, default); PluginHostTests.Run(host, colour); + Assert.That(provider.Tested, Is.EqualTo("ports:2#FF8000")); Assert.That(session.HasEdits("outputs"), Is.False, "an assignment takes effect without the draft"); var global = session.SetOutputTriggerAsync("ports", "1", "S28", default); Assert.That(global.Result.Success, Is.False, "a trigger is for a game"); Assert.That(provider.Triggered, Is.Null); @@ -169,6 +174,9 @@ public void OutputMapsComeFromTheProviderAndAreNeverStored() Assert.That(plainSession.SwapOutputsAsync("ports", "1", "2", 1, default).Result.Success, Is.False); Assert.That(plainSession.AssignOutputAsync("ports", "1", null, default).Result.Success, Is.False); Assert.That(plainSession.AddToyAsync("ports", "1", "Shaker", false, default).Result.Success, Is.False); + Assert.That(plainSession.SetToyRgbAsync("ports", "1", true, default).Result.Success, Is.False); + Assert.That(plainSession.CanTestColors, Is.False); + Assert.That(plainSession.TestOutputColorAsync("ports", "1", 255, 0, 0, default).Result.Success, Is.False); using (var plainGame = new PluginSettingsSession(plain, Host(plain).Configuration, "windows", new GameIdentity("pinmame", "t2_l8"))) Assert.That(plainGame.SetOutputTriggerAsync("ports", "1", "S28", default).Result.Success, Is.False); Assert.That(plainSession.CanRestoreOutputs, Is.False); @@ -195,7 +203,7 @@ public Task RunActionAsync(string action, PluginChoiceReques private sealed class ProgressSink : IProgress { internal PluginActionProgress Last; public void Report(PluginActionProgress value) => Last = value; } private sealed class Provider : IPluginSettingsProvider, IPluginSettingsInfoProvider, IPluginOutputMapProvider, IPluginOutputRearranger, IPluginOutputAssigner, - IPluginOutputTriggerEditor, IPluginOutputSnapshots + IPluginOutputTriggerEditor, IPluginOutputSnapshots, IPluginOutputColorTester { internal string? Restored; public Task SnapshotOutputsAsync(string provider, PluginChoiceRequest request, CancellationToken cancellation) @@ -213,6 +221,12 @@ public Task AssignOutputAsync(string provider, string output { Assigned = $"{provider}:{output}={toy ?? "nothing"}"; return Task.FromResult(new PluginActionResult(true, "Assigned")); } public Task AddToyAsync(string provider, string output, string name, bool rgb, PluginChoiceRequest request, CancellationToken cancellation) { Added = $"{provider}:{output}+{name}{(rgb ? " (RGB)" : "")}"; return Task.FromResult(new PluginActionResult(true, "Added")); } + internal string? Shaped; + public Task SetToyRgbAsync(string provider, string output, bool rgb, PluginChoiceRequest request, CancellationToken cancellation) + { Shaped = $"{provider}:{output} {(rgb ? "RGB" : "single")}"; return Task.FromResult(new PluginActionResult(true, "Shaped")); } + public Task TestOutputColorAsync(string provider, string output, byte red, byte green, byte blue, PluginChoiceRequest request, + CancellationToken cancellation) + { Tested = $"{provider}:{output}#{red:X2}{green:X2}{blue:X2}"; return Task.FromResult(new PluginActionResult(true, "Lit")); } public Task SwapOutputsAsync(string provider, string first, string second, int count, PluginChoiceRequest request, CancellationToken cancellation) { Swapped = $"{provider}:{first}>{second}x{count}"; return Task.FromResult(new PluginActionResult(true, "Swapped")); } internal PluginOutputLeases? Leases; diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index 93d82d4b6..b15ac9ac2 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -997,6 +997,11 @@ public sealed class PluginOutputToy public string Label { get; } /// Whether it is an RGB toy, which takes three outputs in a row: its red, green and blue. public bool Rgb { get; } + /// + /// Whether the user can make it an RGB toy or a toy of one output, through , + /// such as a toy the user added; a configuration's toys are as it has them. + /// + public bool RgbChangeable { get; set; } /// Creates a toy. /// What the assignment gets; see . /// Its name. @@ -1192,6 +1197,18 @@ public interface IPluginOutputAssigner /// Cancelled when the page is closed. /// The result to show; is ignored. Task AddToyAsync(string provider, string output, string name, bool rgb, PluginChoiceRequest request, CancellationToken cancellation); + /// + /// Makes the toy an output drives, one whose , an RGB toy on the output and the + /// next two, or a toy of the output alone; the outputs it no longer takes then drive nothing. The plugin refuses when the + /// next two outputs drive another toy. + /// + /// The field's . + /// The of an output that drives the toy, its first for an RGB toy. + /// Whether it is to be an RGB toy. + /// The game, table and draft settings; is empty. + /// Cancelled when the page is closed. + /// The result to show; is ignored. + Task SetToyRgbAsync(string provider, string output, bool rgb, PluginChoiceRequest request, CancellationToken cancellation); } /// @@ -1250,4 +1267,26 @@ public interface IPluginOutputSnapshots /// The result to show; is ignored. Task RestoreOutputsAsync(string provider, string snapshot, PluginChoiceRequest request, CancellationToken cancellation); } + + /// + /// Implemented, in addition to , by a provider that can test an RGB toy in a colour the + /// user picks, instead of only turning an output on. + /// + /// The same rules as for apply: one test at a time per plugin. + public interface IPluginOutputColorTester + { + /// + /// Lights the RGB toy an output drives in a colour for a moment, and says how it went. Returns when the test is over. + /// + /// The field's . + /// The of any of the toy's three outputs. + /// The red, 0 to 255. + /// The green, 0 to 255. + /// The blue, 0 to 255. + /// The game, table and draft settings; is empty. + /// Cancelled when the page is closed; leave the toy off and throw . + /// The result to show; is ignored. + Task TestOutputColorAsync(string provider, string output, byte red, byte green, byte blue, PluginChoiceRequest request, + CancellationToken cancellation); + } } diff --git a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs index e7362fe2c..5ac06dc63 100644 --- a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs +++ b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs @@ -201,6 +201,22 @@ public Task DescribeOutputsAsync(string provider, CancellationT public Task TestOutputAsync(string provider, string output, CancellationToken cancellation) => (_factory.SettingsProvider as IPluginOutputMapProvider)?.TestOutputAsync(provider, output, Request(Effective), cancellation) ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot test outputs.")); + /// Whether the plugin can test an RGB toy in a colour (). + public bool CanTestColors => _factory.SettingsProvider is IPluginOutputColorTester; + /// + /// Lights the RGB toy an output of an field drives in a colour, through + /// . + /// + /// The field's . + /// The of any of the toy's outputs. + /// The red, 0 to 255. + /// The green, 0 to 255. + /// The blue, 0 to 255. + /// Passed to the provider. + /// The provider's result, or a failure when the plugin can't test colours. + public Task TestOutputColorAsync(string provider, string output, byte red, byte green, byte blue, CancellationToken cancellation) + => (_factory.SettingsProvider as IPluginOutputColorTester)?.TestOutputColorAsync(provider, output, red, green, blue, Request(Effective), cancellation) + ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot test colours.")); /// /// Swaps what is wired to two runs of outputs of an field through /// . Takes effect at once; the draft is not involved. @@ -242,6 +258,18 @@ public Task AddToyAsync(string provider, string output, stri : (_factory.SettingsProvider as IPluginOutputAssigner)?.AddToyAsync(provider, output, name.Trim(), rgb, Request(Effective), cancellation) ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot add toys.")); /// + /// Makes the toy an output of an field drives an RGB toy or a toy of one output, through + /// . Takes effect at once; the draft is not involved. + /// + /// The field's . + /// The of the output. + /// Whether it is to be an RGB toy. + /// Passed to the provider. + /// The provider's result, or a failure when the plugin cannot change its toys. + public Task SetToyRgbAsync(string provider, string output, bool rgb, CancellationToken cancellation) + => (_factory.SettingsProvider as IPluginOutputAssigner)?.SetToyRgbAsync(provider, output, rgb, Request(Effective), cancellation) + ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot change its toys.")); + /// /// Sets what makes an output of an field fire in the session's game, or gives it back to /// the configuration, through . Takes effect at once; the draft is /// not involved. From e3e9d9be2f9879a98f0381e251c267d3f7090fd6 Mon Sep 17 00:00:00 2001 From: freezy Date: Wed, 2 Dec 2026 15:41:44 +0100 Subject: [PATCH 04/11] plugins: describe toys' triggers as rules a dialog can edit An outputs plugin can now read the triggers of its toys into rules (when, how long, colour, strength, area and movement) and write them back, through IPluginOutputTriggerSyntax. Outputs say what toy they drive (one output, RGB or an area with its size), the game's outputs say what they are and whether the configuration uses them, and the map carries the configuration's colours. --- .../Configuration/PluginOutputTriggers.cs | 206 ++++++++++++++++++ .../PluginOutputTriggers.cs.meta | 2 + .../Configuration/PluginSchema.cs | 19 ++ .../Configuration/PluginSettingsSession.cs | 5 + 4 files changed, 232 insertions(+) create mode 100644 VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs create mode 100644 VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs.meta diff --git a/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs b/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs new file mode 100644 index 000000000..76be1dc3a --- /dev/null +++ b/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs @@ -0,0 +1,206 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VisualPinball.Plugins +{ + /// What a toy is, which says what of a applies to it. + public enum PluginOutputToyKind + { + /// A toy of one output, such as a shaker, a contactor or a single-colour flasher: it has a strength, no colour. + Single, + /// An RGB toy, which takes three outputs: each trigger lights it in a colour. + Rgb, + /// An LED strip or matrix: each trigger lights an area of it in a colour, which may move. + Area + } + + /// What a is, which the Player groups them by. + public enum PluginGameOutputKind + { + /// Something else, such as an event of the table. + Other, + /// A solenoid or another driven output, such as a motor or a magnet. + Coil, + /// A lamp or a flasher. + Lamp, + /// A string of general illumination. + Gi, + /// A switch. + Switch + } + + /// How a blinks. + public enum PluginTriggerBlink + { + /// It doesn't. + None, + /// For as long as it is on, every . + WhileOn, + /// times, over . + Count + } + + /// Where an area that moves goes. + public enum PluginTriggerMove + { + None, + Left, + Right, + Up, + Down + } + + /// + /// One trigger of a toy in a game, as reads it from a + /// : what of the game fires it, and how the toy then turns on. What the Player shows no + /// control for is kept in , as written. + /// + public sealed class PluginTriggerRule + { + /// + /// What of the game fires it, any of them: s such as S12, or names the + /// plugin knows. Empty when or a fires it instead. + /// + public List Sources { get; set; } = new List(); + /// Whether it is on all the time the game runs, instead of fired by . + public bool Always { get; set; } + /// An expression of the game's outputs that fires it while it holds, as written, such as (S1 and not L5); empty for none. + public string Condition { get; set; } = ""; + /// The colour it lights an RGB toy or an area in, by name or as #RRGGBB; empty for none. + public string Color { get; set; } = ""; + /// For how long it turns the toy on once fired, in milliseconds; 0 for as long as what fires it is on. + public int Duration { get; set; } + /// How it blinks. + public PluginTriggerBlink Blink { get; set; } + /// For : the time of one blink, on and off, in milliseconds. + public int BlinkInterval { get; set; } = 1000; + /// For : how many times it blinks over . + public int BlinkCount { get; set; } + /// How much of a blink it is on, in percent from 1 to 99. + public int BlinkOn { get; set; } = 50; + /// How long it takes to turn fully on, in milliseconds; 0 at once. + public int FadeIn { get; set; } + /// How long it takes to turn fully off, in milliseconds; 0 at once. + public int FadeOut { get; set; } + /// How long it waits after it is fired before it turns on, in milliseconds. + public int Delay { get; set; } + /// How long it stays on at least, in milliseconds; 0 for the plugin's default. + public int MinDuration { get; set; } + /// How long it stays on at most, in milliseconds; 0 for no limit. + public int MaxDuration { get; set; } + /// How much longer it stays on than what fires it, in milliseconds. + public int Extend { get; set; } + /// For a toy: how strongly it turns on, from 0 to 255. + public int Strength { get; set; } = 255; + /// Whether it is on while what fires it is off, and off while it is on. + public bool Invert { get; set; } + /// + /// Which triggers it draws over: those of a lower layer. Null for its place among the toy's triggers, which the Player + /// changes by moving it. + /// + public int? Layer { get; set; } + /// + /// Whether it lights an area of an toy, even all of it: such a toy takes only these. + /// Set by any of the area's values; the Player sets it for a new trigger of such a toy. + /// + public bool Area { get; set; } + /// For an toy: the left of the area it lights, in percent of the toy's width. + public int AreaLeft { get; set; } + /// The top of the area, in percent of the toy's height. + public int AreaTop { get; set; } + /// The width of the area, in percent. + public int AreaWidth { get; set; } = 100; + /// The height of the area, in percent. + public int AreaHeight { get; set; } = 100; + /// Where the area moves while it is on. + public PluginTriggerMove Move { get; set; } + /// How fast the area moves, in percent of itself per second, from 1 to 100000. + public int MoveSpeed { get; set; } = 100; + /// What else it says, as written, such as effects the Player has no control for; empty for nothing. + public string Kept { get; set; } = ""; + /// + /// What the plugin needs to write it again as it was when nothing above changed, such as the text it read it from. Private to + /// the plugin; the Player copies it with the rest. + /// + public string Original { get; set; } = ""; + + /// Whether it lights an area smaller than the whole toy, or one that moves. + public bool HasArea => AreaLeft != 0 || AreaTop != 0 || AreaWidth != 100 || AreaHeight != 100 || Move != PluginTriggerMove.None; + + /// A copy, to change apart from this one. + public PluginTriggerRule Clone() + { + var copy = (PluginTriggerRule)MemberwiseClone(); + copy.Sources = new List(Sources); + return copy; + } + + /// Whether it says the same as another, aside. + public bool SameAs(PluginTriggerRule other) + => other != null && Sources.SequenceEqual(other.Sources, StringComparer.OrdinalIgnoreCase) && Always == other.Always + && Condition == other.Condition && string.Equals(Color, other.Color, StringComparison.OrdinalIgnoreCase) + && Duration == other.Duration && Blink == other.Blink && BlinkInterval == other.BlinkInterval && BlinkCount == other.BlinkCount + && BlinkOn == other.BlinkOn && FadeIn == other.FadeIn && FadeOut == other.FadeOut && Delay == other.Delay + && MinDuration == other.MinDuration && MaxDuration == other.MaxDuration && Extend == other.Extend && Strength == other.Strength + && Invert == other.Invert && Layer == other.Layer && Area == other.Area && AreaLeft == other.AreaLeft && AreaTop == other.AreaTop + && AreaWidth == other.AreaWidth && AreaHeight == other.AreaHeight && Move == other.Move && MoveSpeed == other.MoveSpeed + && Kept == other.Kept; + } + + /// A as read it. + public sealed class PluginTriggerParse + { + /// Its triggers, in order: a later one draws over an earlier one. + public IReadOnlyList Rules { get; } + /// + /// What of it couldn't be read, such as a part the plugin doesn't know, which the triggers leave out; empty when all of it + /// was. The Player then offers to edit it as text. + /// + public string Problem { get; } + /// Creates what a trigger was read as. + /// Its triggers. + /// What couldn't be read, or null. + public PluginTriggerParse(IReadOnlyList rules, string? problem = null) + { Rules = rules ?? Array.Empty(); Problem = problem ?? ""; } + } + + /// A colour a can name, as the plugin's configuration defines it. + public sealed class PluginNamedColor + { + /// Its name as written in a trigger, such as Dark_orange. + public string Name { get; } + public byte Red { get; } + public byte Green { get; } + public byte Blue { get; } + /// Creates a named colour. + public PluginNamedColor(string name, byte red, byte green, byte blue) { Name = name ?? ""; Red = red; Green = green; Blue = blue; } + } + + /// + /// Implemented, in addition to , by a provider whose triggers the Player can show as a + /// list of s to edit, instead of as text: it reads a into + /// them, and writes them back as the trigger takes. + /// + /// Both are called on the main thread as the user edits, so they must be quick and touch no files. + public interface IPluginOutputTriggerSyntax + { + /// Reads a trigger into its rules. + /// A , or what the user typed; empty for nothing. + /// The rules, and what of it couldn't be read. + PluginTriggerParse Parse(string trigger); + /// + /// Writes rules as a trigger: those that didn't change as they were read (by their ), + /// so what the user didn't touch stays as written. + /// + /// The rules, in order. + /// The trigger; empty for no rules. + string Format(IReadOnlyList rules); + } +} diff --git a/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs.meta b/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs.meta new file mode 100644 index 000000000..080ce3be2 --- /dev/null +++ b/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7b7755a954144a57af6ae1f101239d9f diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index b15ac9ac2..7f0242597 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -976,6 +976,17 @@ public sealed class PluginOutput public string Trigger { get; set; } = ""; /// Whether is the user's own for the game instead of the configuration's. public bool TriggerChanged { get; set; } + /// For a game: what the configuration says fires it, as has it; empty for nothing. + public string ConfiguredTrigger { get; set; } = ""; + /// + /// What the toy it drives is, which says what of a applies to it: of one output, an RGB toy + /// (as its says), or an LED strip or matrix. + /// + public PluginOutputToyKind ToyKind { get; set; } + /// Of an toy: how many lights it has across, or 0 when not known. + public int ToyColumns { get; set; } + /// Of an toy: how many lights it has down, or 0 when not known. + public int ToyRows { get; set; } /// Creates an output. /// What the test gets; see . /// The number on its board. @@ -1023,6 +1034,12 @@ public sealed class PluginGameOutput /// The trigger, such as S28. /// What the game calls it, or null for nothing. public PluginGameOutput(string trigger, string label) { Trigger = trigger ?? ""; Label = label ?? ""; } + /// What it is, for the Player to group it. + public PluginGameOutputKind Kind { get; set; } + /// Whether the configuration fires any toy with it in this game: one the user likely wants. + public bool Configured { get; set; } + /// Whether the game has it, for one the configuration uses that the game doesn't list; true when not known. + public bool Present { get; set; } = true; } /// A board of a and its outputs. @@ -1079,6 +1096,8 @@ public sealed class PluginOutputMap /// lamps by name, for the user to pick from instead of typing a trigger; may be empty. /// public IReadOnlyList GameOutputs { get; set; } = Array.Empty(); + /// The colours a can name, as the configuration defines them; may be empty. + public IReadOnlyList Colors { get; set; } = Array.Empty(); /// Creates the map of an field. /// The boards in display order. /// Shown when there are no boards. diff --git a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs index 5ac06dc63..53870d5db 100644 --- a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs +++ b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs @@ -204,6 +204,11 @@ public Task TestOutputAsync(string provider, string output, /// Whether the plugin can test an RGB toy in a colour (). public bool CanTestColors => _factory.SettingsProvider is IPluginOutputColorTester; /// + /// What reads the triggers of the plugin's outputs into rules to edit and writes them back (); + /// null when the plugin's triggers are edited as text only. + /// + public IPluginOutputTriggerSyntax? TriggerSyntax => _factory.SettingsProvider as IPluginOutputTriggerSyntax; + /// /// Lights the RGB toy an output of an field drives in a colour, through /// . /// From d588095c457a8f4e9e5dbabdfa905c613e44fb64 Mon Sep 17 00:00:00 2001 From: freezy Date: Wed, 2 Dec 2026 17:52:07 +0100 Subject: [PATCH 05/11] plugins: let a text field hide what it holds PluginField.Secret makes the Player show a text field, also inside a composite or collection, as dots, for keys and tokens. The value is stored like any other text. The .vpe package schema is not affected. --- VisualPinball.Plugins/Configuration/PluginSchema.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index 7f0242597..2ce9465c0 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -149,6 +149,11 @@ public sealed class PluginField /// PUPVideos library folder. /// public bool FullWidth { get; set; } + /// + /// For a field, also inside a composite or collection, or a collection of text: the Player shows what it holds as dots, for a key or a token that + /// shouldn't show on a screen or in a screenshot. The value is stored like any other text. + /// + public bool Secret { get; set; } /// The label of the button that adds an item to a , such as Add a controller; Add item when empty. public string AddLabel { get; set; } = ""; /// Optional previous setting in guided launch setup. Enables changing an earlier choice when setup resumes at this field. From 5d2c28d2d864fb7b3ebb8b06029e62840c69b479 Mon Sep 17 00:00:00 2001 From: freezy Date: Fri, 4 Dec 2026 01:17:46 +0100 Subject: [PATCH 06/11] plugins: wizard actions, file filters, board status and confirmations; drop output rearranging - An action can open a wizard (PluginWizard): several ways of doing one thing, each asking for a text, file or folder field and running its own action. The schema checks that each asked field exists, has a usable kind and is editable wherever the action is. - File fields take filters for the file dialog (PluginFileFilter). - Info cards carry a status line with a tone; PluginInfo.HiddenFields also hides the action buttons attached to the info row. - PluginSettingsSession.Saved takes a field's draft value as the stored one, for values saved on their own. - Output maps lose the rearrange mode (IPluginOutputRearranger, SwapOutputsAsync, PluginOutputBoard.Rearrangeable): assigning a toy to an output moves the toy it had to where the assigned one was. The .vpe package schema is not affected. --- .../SetupSettingsTests.cs | 50 +++- .../Configuration/PluginSchema.cs | 274 +++++++++++++++--- .../Configuration/PluginSettingsSession.cs | 34 ++- 3 files changed, 294 insertions(+), 64 deletions(-) diff --git a/VisualPinball.Plugins.Test/SetupSettingsTests.cs b/VisualPinball.Plugins.Test/SetupSettingsTests.cs index 960ec55e3..d40595f60 100644 --- a/VisualPinball.Plugins.Test/SetupSettingsTests.cs +++ b/VisualPinball.Plugins.Test/SetupSettingsTests.cs @@ -69,6 +69,46 @@ public void AttachedActionsMustNameAnotherFieldOfTheirGroup() Assert.Throws(() => Schema(new PluginField("name", "Name", SettingKind.Text) { Default = "", AttachTo = "zip" })); } [Test] + public void AWizardAsksForTextFileOrFolderFieldsOfTheSchema() + { + PluginSettingsSchema Schema(PluginField opener) => new PluginSettingsSchema(1, + new PluginSettingsGroup("Import", "", opener, new PluginField("zip", "Zip", SettingKind.File) { Default = "" }), + new PluginSettingsGroup("Other", "", new PluginField("key", "Key", SettingKind.Text) { Default = "", Secret = true }, + new PluginField("on", "On", SettingKind.Boolean) { Default = false })); + PluginField Opener(PluginWizardChoice choice) => new PluginField("import", "Import", SettingKind.Action) { Wizard = new PluginWizard("Import", null, choice) }; + Assert.DoesNotThrow(() => Schema(Opener(new PluginWizardChoice("By zip", "", "zip", "import-zip")))); + Assert.DoesNotThrow(() => Schema(Opener(new PluginWizardChoice("By key", "", "key", "download"))), "any group"); + Assert.Throws(() => Schema(Opener(new PluginWizardChoice("By nothing", "", "missing", "import")))); + Assert.Throws(() => Schema(Opener(new PluginWizardChoice("By toggle", "", "on", "import")))); + Assert.Throws(() => Schema(new PluginField("import", "Import", SettingKind.Text) { Default = "", + Wizard = new PluginWizard("Import", null, new PluginWizardChoice("By zip", "", "zip", "import-zip")) }), "only an action opens one"); + Assert.Throws(() => new PluginWizard("Import", null)); + // the field is set wherever the action runs: a game's page can't take a global-only one + Assert.Throws(() => Schema(new PluginField("import", "Import", SettingKind.Action) { Scope = ConfigurationScope.GlobalAndGame, + Wizard = new PluginWizard("Import", null, new PluginWizardChoice("By zip", "", "zip", "import-zip")) })); + } + [Test] + public void FileFiltersTakeExtensionsWithOrWithoutTheirPattern() + { + var zip = new PluginFileFilter("Zip files", "*.zip", ".7z"); + Assert.That(zip.Extensions, Is.EqualTo(new[] { "zip", "7z" })); + Assert.That((zip.Matches("a.ZIP"), zip.Matches("a.7z"), zip.Matches("zip"), zip.AllFiles), Is.EqualTo((true, true, false, false))); + var all = new PluginFileFilter("All files", "*"); + Assert.That((all.AllFiles, all.Matches("Cabinet.xml")), Is.EqualTo((true, true))); + Assert.Throws(() => new PluginFileFilter("None")); + } + [Test] + public void SavedTakesTheDraftValueAsTheStoredOne() + { + var factory = new TestFactory("setup") { SettingsProvider = new Provider(), Schema = new PluginSettingsSchema(1, new PluginSettingsGroup("Setup", "", + new PluginField("zip", "Zip", SettingKind.File) { Default = "" }, new PluginField("name", "Name", SettingKind.Text) { Default = "" })) }; + var host = Host(factory); using var session = new PluginSettingsSession(factory, host.Configuration, "windows"); + session.Set("zip", "a.zip"); session.Set("name", "edited"); + session.Saved("zip"); + Assert.That(session.HasEdits("zip"), Is.False); Assert.That(session.Draft.String("zip"), Is.EqualTo("a.zip")); + Assert.That(session.HasEdits("name"), Is.True, "the other edits stay pending"); + } + [Test] public void InfoFieldsAreTopLevelOnlyAndResetLeavesThemOut() { Assert.Throws(() => new PluginSettingsSchema(1, new PluginSettingsGroup("Ports", "", @@ -129,10 +169,6 @@ public void OutputMapsComeFromTheProviderAndAreNeverStored() Assert.That(provider.Later, Is.False, "a snapshot, safe to read on a worker thread"); } } - var swap = session.SwapOutputsAsync("ports", "1", "2", 1, default); PluginHostTests.Run(host, swap); - Assert.That(swap.Result.Success, Is.True); Assert.That(provider.Swapped, Is.EqualTo("ports:1>2x1")); - Assert.That(session.SwapOutputsAsync("ports", "1", "2", 0, default).Result.Success, Is.False, "nothing to swap"); - Assert.That(session.HasEdits("outputs"), Is.False, "a swap takes effect without the draft"); var assign = session.AssignOutputAsync("ports", "1", "shaker", default); PluginHostTests.Run(host, assign); Assert.That(assign.Result.Success, Is.True); Assert.That(provider.Assigned, Is.EqualTo("ports:1=shaker")); assign = session.AssignOutputAsync("ports", "2", null, default); PluginHostTests.Run(host, assign); @@ -171,7 +207,6 @@ public void OutputMapsComeFromTheProviderAndAreNeverStored() using var plainSession = new PluginSettingsSession(plain, Host(plain).Configuration, "windows"); Assert.That(plainSession.DescribeOutputsAsync("ports", default).Result.Boards, Is.Empty); Assert.That(plainSession.TestOutputAsync("ports", "1", default).Result.Success, Is.False); - Assert.That(plainSession.SwapOutputsAsync("ports", "1", "2", 1, default).Result.Success, Is.False); Assert.That(plainSession.AssignOutputAsync("ports", "1", null, default).Result.Success, Is.False); Assert.That(plainSession.AddToyAsync("ports", "1", "Shaker", false, default).Result.Success, Is.False); Assert.That(plainSession.SetToyRgbAsync("ports", "1", true, default).Result.Success, Is.False); @@ -202,7 +237,7 @@ public Task RunActionAsync(string action, PluginChoiceReques } private sealed class ProgressSink : IProgress { internal PluginActionProgress Last; public void Report(PluginActionProgress value) => Last = value; } - private sealed class Provider : IPluginSettingsProvider, IPluginSettingsInfoProvider, IPluginOutputMapProvider, IPluginOutputRearranger, IPluginOutputAssigner, + private sealed class Provider : IPluginSettingsProvider, IPluginSettingsInfoProvider, IPluginOutputMapProvider, IPluginOutputAssigner, IPluginOutputTriggerEditor, IPluginOutputSnapshots, IPluginOutputColorTester { internal string? Restored; @@ -214,7 +249,6 @@ public Task RestoreOutputsAsync(string provider, string snap public Task SetTriggerAsync(string provider, string output, string? trigger, PluginChoiceRequest request, CancellationToken cancellation) { Triggered = $"{provider}:{output}={trigger ?? "configuration"}@{request.Game?.Key}"; return Task.FromResult(new PluginActionResult(true, "Set")); } internal string? Tested; - internal string? Swapped; internal string? Assigned; internal string? Added; public Task AssignOutputAsync(string provider, string output, string? toy, PluginChoiceRequest request, CancellationToken cancellation) @@ -227,8 +261,6 @@ public Task SetToyRgbAsync(string provider, string output, b public Task TestOutputColorAsync(string provider, string output, byte red, byte green, byte blue, PluginChoiceRequest request, CancellationToken cancellation) { Tested = $"{provider}:{output}#{red:X2}{green:X2}{blue:X2}"; return Task.FromResult(new PluginActionResult(true, "Lit")); } - public Task SwapOutputsAsync(string provider, string first, string second, int count, PluginChoiceRequest request, CancellationToken cancellation) - { Swapped = $"{provider}:{first}>{second}x{count}"; return Task.FromResult(new PluginActionResult(true, "Swapped")); } internal PluginOutputLeases? Leases; internal bool Later; public Task DescribeOutputsAsync(string provider, PluginChoiceRequest request, CancellationToken cancellation) diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index 2ce9465c0..4186e69e6 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -172,7 +172,7 @@ public sealed class PluginField /// field, while names it. /// /// - /// An import button belongs next to the file it imports, and an undo button next to what it undoes: + /// An import button belongs next to the file it imports, and a clear button next to what it clears: /// /// new PluginField("ImportZip", "Config Tool zip", SettingKind.File) { Default = "" }, /// new PluginField("Import", "Import", SettingKind.Action) { Provider = "import-zip", AttachTo = "ImportZip" }, @@ -180,6 +180,17 @@ public sealed class PluginField /// public string AttachTo { get; set; } = ""; /// + /// For an field: a dialog its button opens instead of running , for a + /// one-time task the page shouldn't show all the time, such as importing a configuration in one of several ways. The user picks + /// a way, gives what it needs and runs it there. The fields the ways ask for aren't shown on the page. Null for a plain action. + /// + public PluginWizard? Wizard { get; set; } + /// + /// For a field: the kinds of files Browse offers, the first one selected, such as zip files + /// and then all files. Empty for any file. + /// + public IReadOnlyList FileFilters { get; set; } = Array.Empty(); + /// /// The editor style for and fields. Defaults to a number box. /// public PluginFieldPresentation Presentation { get; set; } @@ -392,7 +403,8 @@ public sealed class PluginSettingsSchema /// Two top-level fields share an , a composite or collection record has an /// field or a field with , or a top-level /// is set on a field that is not an action or names no other non-action field of the same - /// group. + /// group, or a is on a field that is not an action or asks for no text, file or folder field, + /// or for one not editable everywhere the action is. /// public PluginSettingsSchema(int version, params PluginSettingsGroup[] groups) { @@ -408,6 +420,18 @@ public PluginSettingsSchema(int version, params PluginSettingsGroup[] groups) if (!group.Fields.Any(target => target.Id == field.AttachTo && target.Kind != SettingKind.Action)) throw new ArgumentException("Plugin field " + field.Id + " is attached to " + field.AttachTo + ", which is no other field of its group."); } + foreach (var field in Fields) { + if (field.Wizard == null) continue; + if (field.Kind != SettingKind.Action) throw new ArgumentException("Only an action can open a wizard: " + field.Id + "."); + foreach (var choice in field.Wizard.Choices) { + var asked = Fields.FirstOrDefault(target => target.Id == choice.FieldId); + if (asked == null || (asked.Kind != SettingKind.Text && asked.Kind != SettingKind.File && asked.Kind != SettingKind.Folder)) + throw new ArgumentException("The wizard of " + field.Id + " asks for " + choice.FieldId + ", which is no text, file or folder field of the schema."); + // the value goes into the draft of the page the action is on, so it is editable wherever the action is + if (asked.Scope != ConfigurationScope.GlobalAndGame && asked.Scope != field.Scope) + throw new ArgumentException("The wizard of " + field.Id + " asks for " + choice.FieldId + ", which is not editable everywhere the action is."); + } + } } // A record's fields are values of the record, each in a row of its own: information has no value to keep there, and an // action is not attached to another field. @@ -721,6 +745,11 @@ public sealed class PluginChoiceRequest /// the host and by the settings session when the host gave it one; null otherwise. /// public PluginCapabilities? Capabilities { get; set; } + /// + /// For an action: the user agreed to the question the action asked before (), so it goes + /// ahead. False the first time. + /// + public bool Confirmed { get; set; } /// Creates a request. /// The game being configured, or null for global settings. /// The effective settings to work with. @@ -794,11 +823,166 @@ public readonly struct PluginActionResult /// editable in the current scope are taken, and the user still has to apply them. Ignored in other results. /// public PluginSettingsSnapshot? Changes { get; } + /// + /// For an action: the question the Player asks before the action does anything, such as whether an import may replace what is + /// there; null when it ran. The action did nothing. When the user confirms, the Player runs it again with + /// set; otherwise it shows nothing. Create it with . + /// + public PluginConfirmation? Confirmation { get; } + /// + /// For an action: a longer text the Player shows in a dialog, such as a report, besides under the row; + /// null for none. + /// + public PluginDetails? Details { get; } /// Creates a result. /// Whether the operation succeeded. /// A short message for the user. /// For an action, values to put into the draft; otherwise null. - public PluginActionResult(bool success, string message, PluginSettingsSnapshot? changes = null) { Success = success; Message = message; Changes = changes; } + public PluginActionResult(bool success, string message, PluginSettingsSnapshot? changes = null) : this(success, message, changes, null, null) { } + /// The result of an action that shows a text in a dialog. + /// Whether the action succeeded. + /// A short message for the user, under the row; may be empty. + /// The text to show in a dialog. + public static PluginActionResult WithDetails(bool success, string message, PluginDetails details) => new PluginActionResult(success, message, null, null, details); + private PluginActionResult(bool success, string message, PluginSettingsSnapshot? changes, PluginConfirmation? confirmation, PluginDetails? details) + { Success = success; Message = message; Changes = changes; Confirmation = confirmation; Details = details; } + /// + /// The result of an action that needs the user's go first, and did nothing: the Player asks, and runs the action again with + /// when the user agrees. + /// + /// The question. + /// + /// + /// if (store.Active != null && !request.Confirmed) + /// return PluginActionResult.Ask(new PluginConfirmation("Replace your configuration?", "Importing replaces the one imported on 2 December.", "Replace")); + /// + /// + public static PluginActionResult Ask(PluginConfirmation confirmation) => new PluginActionResult(false, "", null, confirmation, null); + } + + /// + /// The dialog of an action field with several ways of doing one thing (). It starts with the ways; + /// Next asks for what the picked one needs, and its button runs it. A question the action asks () + /// shows in the dialog; it closes once the action succeeded, and the result shows in the action's row. + /// + /// + /// + /// new PluginField("Import", "Import…", SettingKind.Action) { Wizard = new PluginWizard("Import a configuration", null, + /// new PluginWizardChoice("By zip file", "The zip you downloaded.", "ImportZip", "import-zip")) }, + /// new PluginField("ImportZip", "Zip file", SettingKind.File) { Default = "" }, + /// + /// + public sealed class PluginWizard + { + /// Creates the dialog. + /// The dialog's title. + /// What the dialog is for, under the title; null for none. + /// The ways, at least one, in order. + public PluginWizard(string title, string? description, params PluginWizardChoice[] choices) + { + Title = title ?? throw new ArgumentNullException(nameof(title)); + Description = description; + Choices = choices ?? throw new ArgumentNullException(nameof(choices)); + if (choices.Length == 0) throw new ArgumentException("A wizard needs a choice.", nameof(choices)); + } + /// The dialog's title. + public string Title { get; } + /// What the dialog is for, under the title; null for none. + public string? Description { get; } + /// The ways, in order. + public IReadOnlyList Choices { get; } + } + + /// A kind of file a field's Browse offers (). + public sealed class PluginFileFilter + { + /// Creates a kind of file. + /// Its name in the file dialog, such as "Zip files". + /// Its extensions without the dot, such as zip; * for all files. + public PluginFileFilter(string name, params string[] extensions) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + Extensions = (extensions ?? throw new ArgumentNullException(nameof(extensions))).Select(extension => extension.TrimStart('*', '.')).ToArray(); + if (Extensions.Count == 0) throw new ArgumentException("A file filter needs an extension.", nameof(extensions)); + } + /// Its name in the file dialog. + public string Name { get; } + /// Its extensions without the dot; an empty one for all files. + public IReadOnlyList Extensions { get; } + /// Whether it takes every file. + public bool AllFiles => Extensions.Any(extension => extension.Length == 0); + /// Whether it takes the given file. + public bool Matches(string path) => AllFiles || Extensions.Any(extension => (path ?? "").EndsWith("." + extension, StringComparison.OrdinalIgnoreCase)); + } + + /// One way of a : the value it asks for, and the action it runs with it. + public sealed class PluginWizardChoice + { + /// Creates a way. + /// Its name in the list, such as "By zip file". + /// What it is, under the name, and on its step. + /// + /// The top-level , or field it asks + /// for. The page doesn't show it; the dialog saves it once the action succeeded, so it is there the next time. + /// + /// The of the action it runs with the value. + /// Its button, such as "Import". + public PluginWizardChoice(string label, string description, string fieldId, string action, string runLabel = "Import") + { + Label = label ?? throw new ArgumentNullException(nameof(label)); + Description = description ?? ""; + FieldId = fieldId ?? throw new ArgumentNullException(nameof(fieldId)); + Action = action ?? throw new ArgumentNullException(nameof(action)); + RunLabel = runLabel ?? "Import"; + } + /// Its name in the list. + public string Label { get; } + /// What it is, under the name, and on its step. + public string Description { get; } + /// The field it asks for. + public string FieldId { get; } + /// The provider of the action it runs. + public string Action { get; } + /// Its button. + public string RunLabel { get; } + } + + /// The question a settings action asks before it does something that can't be taken back. See . + public sealed class PluginConfirmation + { + /// The question, such as "Replace your configuration?". + public string Title { get; } + /// What happens, and what is lost, in a sentence or two. + public string Message { get; } + /// The label of the button that goes ahead, such as "Replace"; the other one cancels. + public string ConfirmLabel { get; } + /// Creates a question. + /// The question. + /// What happens. + /// The label of the button that goes ahead. + public PluginConfirmation(string title, string message, string confirmLabel) + { + Title = title ?? ""; + Message = message ?? ""; + ConfirmLabel = string.IsNullOrWhiteSpace(confirmLabel) ? "Continue" : confirmLabel; + } + } + + /// A text an action shows in a dialog, such as an import report. See . + public sealed class PluginDetails + { + /// The dialog's title, such as "Import report". + public string Title { get; } + /// The text, in lines; the Player wraps long ones and scrolls. + public string Text { get; } + /// Creates a text for a dialog. + /// The dialog's title. + /// The text. + public PluginDetails(string title, string text) + { + Title = title ?? ""; + Text = text ?? ""; + } } /// @@ -896,15 +1080,20 @@ public sealed class PluginInfo public IReadOnlyList> Lines { get; } /// /// The ids of the actions attached to the field () that have nothing to act on in this - /// state, such as undo without a previous configuration. The Player shows their buttons disabled; other ids are ignored. + /// state, such as clearing without a configuration. The Player shows their buttons disabled; other ids are ignored. /// public IReadOnlyCollection UnavailableActions { get; } /// /// The ids of other top-level fields of the same group that have nothing to offer in this state, such as settings for - /// controllers the configuration does not have. The Player hides them, with the actions attached to them; other ids are - /// ignored. + /// controllers the configuration does not have. The Player hides them, with the actions attached to them. The ids of actions + /// attached to this field hide their buttons, for ones that make no sense in this state at all; other ids are ignored. /// public IReadOnlyCollection HiddenFields { get; set; } = Array.Empty(); + /// + /// Things the information is about, such as the connected boards, each shown as a card of its own between the headline and the + /// ; may be empty. + /// + public IReadOnlyList Cards { get; set; } = Array.Empty(); /// Creates the information of an field. /// The headline. /// How the headline is marked. @@ -919,6 +1108,42 @@ public PluginInfo(string summary, PluginInfoTone tone = PluginInfoTone.Neutral, } } + /// One thing a is about, such as a connected board, shown as a card. + public sealed class PluginInfoCard + { + /// What it is, such as "Pinscape Pico". + public string Title { get; } + /// A second line under the title, such as the name the device gives itself; may be empty. + public string Subtitle { get; } + /// The one fact to see at a glance, shown as a badge, such as "Device 20"; may be empty. + public string Badge { get; } + /// The details as label/value pairs, in order; may be empty. + public IReadOnlyList> Lines { get; } + /// Something the user may have to do about it, shown as a warning, such as a driver to install; may be empty. + public string Note { get; } + /// + /// Its state in one line, under the title with a dot in the colour of , such as whether the plugin uses + /// the board; may be empty. + /// + public string Status { get; set; } = ""; + /// How the Player marks the . + public PluginInfoTone StatusTone { get; set; } = PluginInfoTone.Neutral; + /// Creates a card. + /// What it is. + /// The line under the title, or null for none. + /// The fact to see at a glance, or null for none. + /// The label/value lines, or null for none. + /// What the user may have to do, or null for nothing. + public PluginInfoCard(string title, string? subtitle = null, string? badge = null, IReadOnlyList>? lines = null, string? note = null) + { + Title = title ?? ""; + Subtitle = subtitle ?? ""; + Badge = badge ?? ""; + Lines = lines ?? Array.Empty>(); + Note = note ?? ""; + } + } + /// /// Implemented, in addition to , by a settings provider whose schema has /// fields. @@ -1057,11 +1282,6 @@ public sealed class PluginOutputBoard /// The outputs in board order. public IReadOnlyList Outputs { get; } /// - /// Whether what is wired to its outputs can be moved between them, through ; for - /// cabling that differs from what the configuration says. - /// - public bool Rearrangeable { get; set; } - /// /// The toys its outputs can be given through , those no output drives included; empty /// when what its outputs drive can't be chosen. Each output names its own in . /// @@ -1159,39 +1379,15 @@ public interface IPluginOutputMapProvider Task TestOutputAsync(string provider, string output, PluginChoiceRequest request, CancellationToken cancellation); } - /// - /// Implemented, in addition to , by a provider whose boards can be rearranged - /// (): what is wired to outputs moves between them, such as a knocker the - /// configuration puts on output 16 but that is cabled to output 14. - /// - /// - /// A swap takes effect at once, like a test, without the settings page's Apply: the plugin keeps the arrangement itself, and - /// the Player draws the map again afterwards. The same threading rules as for apply. - /// - public interface IPluginOutputRearranger - { - /// - /// Swaps what is wired to two runs of outputs of one board: outputs from - /// on, in board order, with as many from on, such as the three of an RGB toy. The runs don't - /// overlap. - /// - /// The field's . - /// The where the first run starts. - /// The where the second run starts. - /// How many outputs each run has, at least 1. - /// The game, table and draft settings; is empty. - /// Cancelled when the page is closed. - /// The result to show; is ignored. - Task SwapOutputsAsync(string provider, string first, string second, int count, PluginChoiceRequest request, CancellationToken cancellation); - } - /// /// Implemented, in addition to , by a provider whose boards list the toys their outputs /// can be given (): the user picks what an output drives, such as the shaker on output 14, - /// or that it drives nothing. + /// or that it drives nothing. This is also how the outputs follow cabling that differs from the configuration, such as a + /// knocker the configuration puts on output 16 but that is cabled to output 14: giving output 14 the knocker moves what it + /// drove to output 16. /// /// - /// Like a swap, an assignment takes effect at once, without the settings page's Apply: the plugin keeps it itself, and the + /// Like a test, an assignment takes effect at once, without the settings page's Apply: the plugin keeps it itself, and the /// Player draws the map again afterwards. The same threading rules as for apply. /// Each call is one change: a call that fails or is cancelled leaves the outputs and the toys as they were, so the user /// can try again. The Player waits for a call to finish before it makes the next. diff --git a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs index 53870d5db..03ee44df6 100644 --- a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs +++ b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs @@ -134,6 +134,16 @@ public void RefreshUnedited(PluginSettingsSnapshot saved, IEnumerable fi } } /// + /// Marks the draft value of a field as saved, after the Player saved it on its own with , + /// such as the value a wizard asked for (): it is no longer a pending edit. + /// + /// The top-level field ID. + public void Saved(string fieldId) + { + _baseline.Set(fieldId, Draft.Value(fieldId)); + _resetFields.Remove(fieldId); + } + /// /// Empties the draft, so every field goes back to its inherited value (the global value in a game session, the default in a /// global session), and marks every field that stores a value and is editable in this scope as pending, so removes their stored /// values. Nothing is saved until then. The Player's Reset button calls it. @@ -223,20 +233,6 @@ public Task TestOutputColorAsync(string provider, string out => (_factory.SettingsProvider as IPluginOutputColorTester)?.TestOutputColorAsync(provider, output, red, green, blue, Request(Effective), cancellation) ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot test colours.")); /// - /// Swaps what is wired to two runs of outputs of an field through - /// . Takes effect at once; the draft is not involved. - /// - /// The field's . - /// The where the first run starts. - /// The where the second run starts. - /// How many outputs each run has. - /// Passed to the provider. - /// The provider's result, or a failure when the plugin cannot rearrange outputs. - public Task SwapOutputsAsync(string provider, string first, string second, int count, CancellationToken cancellation) - => count < 1 ? Task.FromResult(new PluginActionResult(false, "Nothing to swap.")) - : (_factory.SettingsProvider as IPluginOutputRearranger)?.SwapOutputsAsync(provider, first, second, count, Request(Effective), cancellation) - ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot rearrange outputs.")); - /// /// Gives an output of an field a toy of its board, or nothing, through /// . Takes effect at once; the draft is not involved. /// @@ -328,10 +324,16 @@ public Task RestoreOutputsAsync(string provider, string snap public Task RunActionAsync(string action, CancellationToken cancellation) => RunActionAsync(action, cancellation, null); /// Runs a settings action with optional progress reporting, without saving draft settings. - public async Task RunActionAsync(string action, CancellationToken cancellation, IProgress? progress) + public Task RunActionAsync(string action, CancellationToken cancellation, IProgress? progress) + => RunActionAsync(action, cancellation, progress, false); + /// + /// Runs a settings action with optional progress reporting, without saving draft settings; after + /// the user agreed to the question the action asked (). + /// + public async Task RunActionAsync(string action, CancellationToken cancellation, IProgress? progress, bool confirmed) { if (_factory.SettingsProvider == null) return new PluginActionResult(false, "This action is unavailable."); - var request = Request(Effective); request.Progress = progress; + var request = Request(Effective); request.Progress = progress; request.Confirmed = confirmed; var result = await _factory.SettingsProvider.RunActionAsync(action, request, cancellation); cancellation.ThrowIfCancellationRequested(); if (result.Success && result.Changes != null) foreach (var field in _factory.Schema.Fields) { From d96ced37368464c87a7b65872f90016fbf3412b4 Mon Sep 17 00:00:00 2001 From: freezy Date: Sat, 5 Dec 2026 22:24:17 +0100 Subject: [PATCH 07/11] plugins: let a plugin name what an output drives without rewiring it IPluginOutputDescriber names the toy an output drives: one of one output, an RGB toy on it and the next two, or no toy. What drives and fires the output stays. The settings session passes it on and says whether the plugin can. The .vpe items schema is not affected. --- .../Configuration/PluginSchema.cs | 21 +++++++++++++++++++ .../Configuration/PluginSettingsSession.cs | 15 +++++++++++++ 2 files changed, 36 insertions(+) diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index 4186e69e6..77cf4d63e 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -1431,6 +1431,27 @@ public interface IPluginOutputAssigner Task SetToyRgbAsync(string provider, string output, bool rgb, PluginChoiceRequest request, CancellationToken cancellation); } + /// + /// Implemented, in addition to , by a provider that can say what an output drives without + /// moving anything: for a configuration that names the toy on an output wrongly while its cabling is right. What drives the + /// output and what fires it stay as they are; only the name, and the outputs an RGB toy takes, change. + /// + public interface IPluginOutputDescriber + { + /// + /// Names the toy an output drives: a toy of one output, or an RGB toy on it and the next two; or no toy. The outputs keep + /// what drives them. + /// + /// The field's . + /// The of the output. + /// The toy's name, or empty for no toy. + /// Whether it is an RGB toy: its red on the output, its green and blue on the next two. + /// The game, table and draft settings; is empty. + /// Cancelled when the page is closed. + /// The result to show; is ignored. + Task DescribeOutputAsync(string provider, string output, string name, bool rgb, PluginChoiceRequest request, CancellationToken cancellation); + } + /// /// Implemented, in addition to , by a provider whose map lets the user change, for one /// game, what makes an output fire (), such as the shaker on a solenoid the diff --git a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs index 03ee44df6..7fbff3a3a 100644 --- a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs +++ b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs @@ -259,6 +259,19 @@ public Task AddToyAsync(string provider, string output, stri : (_factory.SettingsProvider as IPluginOutputAssigner)?.AddToyAsync(provider, output, name.Trim(), rgb, Request(Effective), cancellation) ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot add toys.")); /// + /// Names the toy an output of an field drives, without changing what drives the outputs, + /// through . Takes effect at once; the draft is not involved. + /// + /// The field's . + /// The of the output. + /// The toy's name, or empty for no toy; surrounding spaces are left out. + /// Whether it is an RGB toy, on the output and the next two. + /// Passed to the provider. + /// The provider's result, or a failure when the plugin cannot name what its outputs drive. + public Task DescribeOutputAsync(string provider, string output, string name, bool rgb, CancellationToken cancellation) + => (_factory.SettingsProvider as IPluginOutputDescriber)?.DescribeOutputAsync(provider, output, (name ?? "").Trim(), rgb, Request(Effective), cancellation) + ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot name what its outputs drive.")); + /// /// Makes the toy an output of an field drives an RGB toy or a toy of one output, through /// . Takes effect at once; the draft is not involved. /// @@ -288,6 +301,8 @@ public Task SetOutputTriggerAsync(string provider, string ou ?? Task.FromResult(new PluginActionResult(false, "This plugin cannot change what makes its outputs fire.")); /// Whether the plugin can put the outputs of a field back as they were, through . public bool CanRestoreOutputs => _factory.SettingsProvider is IPluginOutputSnapshots; + /// Whether the plugin can name what an output drives without moving anything (). + public bool CanDescribeOutputs => _factory.SettingsProvider is IPluginOutputDescriber; /// /// Keeps what the outputs of an field are now, through /// , for . From 5ba7db473bea614f24da4557290211524fae73e4 Mon Sep 17 00:00:00 2001 From: freezy Date: Sat, 5 Dec 2026 23:57:36 +0100 Subject: [PATCH 08/11] plugins: let a text field show what the plugin suggests A text field with a provider asks the plugin's catalog for a suggestion: while the field has no value, the box shows the first item, and the line under it that item's description. An emptied box removes the value again. The .vpe items schema is not affected. --- VisualPinball.Plugins/Configuration/PluginSchema.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index 77cf4d63e..017a1c055 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -233,7 +233,10 @@ public sealed class PluginField public double? Maximum { get; set; } /// /// The name the Player passes to the plugin's providers for this field: the catalog name for - /// ( and ), + /// ( and ; + /// for , a suggestion: while the field has no value, the box shows the catalog's first item's + /// , and under it that item's description, or the catalog's empty message without one; an emptied + /// box removes the value), /// the action name for (), the preview name /// (), or the information name for /// (). Empty for other kinds. The names are private to the plugin, such as PinUP's From 3dc4e6bbaab339b18a453c566d05fe905ed15c7f Mon Sep 17 00:00:00 2001 From: freezy Date: Sun, 6 Dec 2026 00:47:54 +0100 Subject: [PATCH 09/11] plugins: take the saved value as saved, no wizard in a record, rules by their names as written - PluginSettingsSession.Saved takes the value that was saved: an edit made while it was saved stays pending. - A field of a composite or collection record can't open a wizard: the schema refuses it, instead of its validation failing on what the wizard asks for. - PluginTriggerRule.SameAs compares sources and colours as written, so one written in other capitals is a change. The .vpe items schema is not affected. --- VisualPinball.Plugins.Test/SetupSettingsTests.cs | 9 ++++++++- .../Configuration/PluginOutputTriggers.cs | 9 ++++++--- VisualPinball.Plugins/Configuration/PluginSchema.cs | 3 ++- .../Configuration/PluginSettingsSession.cs | 10 ++++++---- 4 files changed, 22 insertions(+), 9 deletions(-) diff --git a/VisualPinball.Plugins.Test/SetupSettingsTests.cs b/VisualPinball.Plugins.Test/SetupSettingsTests.cs index d40595f60..41e867033 100644 --- a/VisualPinball.Plugins.Test/SetupSettingsTests.cs +++ b/VisualPinball.Plugins.Test/SetupSettingsTests.cs @@ -83,6 +83,10 @@ public void AWizardAsksForTextFileOrFolderFieldsOfTheSchema() Assert.Throws(() => Schema(new PluginField("import", "Import", SettingKind.Text) { Default = "", Wizard = new PluginWizard("Import", null, new PluginWizardChoice("By zip", "", "zip", "import-zip")) }), "only an action opens one"); Assert.Throws(() => new PluginWizard("Import", null)); + // a record's fields are values of the record: none opens a wizard + Assert.That(Assert.Throws(() => new PluginSettingsSchema(1, new PluginSettingsGroup("Import", "", new PluginField("zip", "Zip", SettingKind.File) { Default = "" }, + new PluginField("sources", "Sources", SettingKind.Composite) { Children = new[] { Opener(new PluginWizardChoice("By zip", "", "zip", "import-zip")) } }))).Message, + Does.Contain("top-level action can open a wizard")); // the field is set wherever the action runs: a game's page can't take a global-only one Assert.Throws(() => Schema(new PluginField("import", "Import", SettingKind.Action) { Scope = ConfigurationScope.GlobalAndGame, Wizard = new PluginWizard("Import", null, new PluginWizardChoice("By zip", "", "zip", "import-zip")) })); @@ -104,9 +108,12 @@ public void SavedTakesTheDraftValueAsTheStoredOne() new PluginField("zip", "Zip", SettingKind.File) { Default = "" }, new PluginField("name", "Name", SettingKind.Text) { Default = "" })) }; var host = Host(factory); using var session = new PluginSettingsSession(factory, host.Configuration, "windows"); session.Set("zip", "a.zip"); session.Set("name", "edited"); - session.Saved("zip"); + session.Saved("zip", "a.zip"); Assert.That(session.HasEdits("zip"), Is.False); Assert.That(session.Draft.String("zip"), Is.EqualTo("a.zip")); Assert.That(session.HasEdits("name"), Is.True, "the other edits stay pending"); + session.Set("zip", "b.zip"); + session.Saved("zip", "a.zip"); + Assert.That(session.HasEdits("zip"), Is.True, "an edit made while the value was saved stays pending"); } [Test] public void InfoFieldsAreTopLevelOnlyAndResetLeavesThemOut() diff --git a/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs b/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs index 76be1dc3a..b8d5fce28 100644 --- a/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs +++ b/VisualPinball.Plugins/Configuration/PluginOutputTriggers.cs @@ -142,10 +142,13 @@ public PluginTriggerRule Clone() return copy; } - /// Whether it says the same as another, aside. + /// + /// Whether it says the same as another, aside; names as written, so one only written differently, such + /// as in other capitals, is not the same. + /// public bool SameAs(PluginTriggerRule other) - => other != null && Sources.SequenceEqual(other.Sources, StringComparer.OrdinalIgnoreCase) && Always == other.Always - && Condition == other.Condition && string.Equals(Color, other.Color, StringComparison.OrdinalIgnoreCase) + => other != null && Sources.SequenceEqual(other.Sources, StringComparer.Ordinal) && Always == other.Always + && Condition == other.Condition && string.Equals(Color, other.Color, StringComparison.Ordinal) && Duration == other.Duration && Blink == other.Blink && BlinkInterval == other.BlinkInterval && BlinkCount == other.BlinkCount && BlinkOn == other.BlinkOn && FadeIn == other.FadeIn && FadeOut == other.FadeOut && Delay == other.Delay && MinDuration == other.MinDuration && MaxDuration == other.MaxDuration && Extend == other.Extend && Strength == other.Strength diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index 017a1c055..70f395330 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -404,7 +404,7 @@ public sealed class PluginSettingsSchema /// is less than 1. /// /// Two top-level fields share an , a composite or collection record has an - /// field or a field with , or a top-level + /// field or a field with or a , or a top-level /// is set on a field that is not an action or names no other non-action field of the same /// group, or a is on a field that is not an action or asks for no text, file or folder field, /// or for one not editable everywhere the action is. @@ -444,6 +444,7 @@ private static void CheckRecordFields(IReadOnlyList children) if (child.Kind == SettingKind.Info) throw new ArgumentException("Information can only be a top-level field: " + child.Id + "."); if (child.Kind == SettingKind.Outputs) throw new ArgumentException("Outputs can only be a top-level field: " + child.Id + "."); if (child.AttachTo.Length > 0) throw new ArgumentException("Only a top-level action can be attached to another field: " + child.Id + "."); + if (child.Wizard != null) throw new ArgumentException("Only a top-level action can open a wizard: " + child.Id + "."); CheckRecordFields(child.Children); } } diff --git a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs index 7fbff3a3a..54c5cdbd6 100644 --- a/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs +++ b/VisualPinball.Plugins/Configuration/PluginSettingsSession.cs @@ -134,13 +134,15 @@ public void RefreshUnedited(PluginSettingsSnapshot saved, IEnumerable fi } } /// - /// Marks the draft value of a field as saved, after the Player saved it on its own with , - /// such as the value a wizard asked for (): it is no longer a pending edit. + /// Takes a value as the field's saved one, after the Player saved it on its own with , + /// such as the value a wizard asked for (): a draft of that value is no longer a pending edit, + /// and one changed since stays one. /// /// The top-level field ID. - public void Saved(string fieldId) + /// The value that was saved, or null for none. + public void Saved(string fieldId, JToken? value) { - _baseline.Set(fieldId, Draft.Value(fieldId)); + _baseline.Set(fieldId, value?.DeepClone()); _resetFields.Remove(fieldId); } /// From c98e5750a9dbe093782ad50e9732f37a8bc8f8be Mon Sep 17 00:00:00 2001 From: freezy Date: Sun, 6 Dec 2026 01:52:33 +0100 Subject: [PATCH 10/11] plugins: say which of a game's outputs the game lists PluginGameOutput.Listed is false for an output only the configuration uses, so the Player can tell a kind the game lists, its unnamed outputs included, from one it doesn't. The .vpe items schema is not affected. --- .../Configuration/PluginSchema.cs | 169 +++++++++--------- 1 file changed, 87 insertions(+), 82 deletions(-) diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index 70f395330..eec26748b 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -1,9 +1,9 @@ -// Visual Pinball Engine -// Copyright (C) 2026 freezy and VPE Team -// -// SPDX-License-Identifier: MIT -// Licensed under MIT. See https://opensource.org/license/mit. - +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + using System; using System.Collections.Generic; using System.Linq; @@ -143,27 +143,27 @@ public sealed class PluginField public SettingKind Kind { get; } /// Help text shown below the editor. Empty (the default) shows none. public string Description { get; set; } = ""; - /// Places the label above the editor for long values; ordinary fields render inline. + /// Places the label above the editor for long values; ordinary fields render inline. /// /// Collection, composite, screen layout and preview fields always use the full width. Paths are a typical use, such as PinUP's /// PUPVideos library folder. /// - public bool FullWidth { get; set; } - /// - /// For a field, also inside a composite or collection, or a collection of text: the Player shows what it holds as dots, for a key or a token that - /// shouldn't show on a screen or in a screenshot. The value is stored like any other text. - /// - public bool Secret { get; set; } - /// The label of the button that adds an item to a , such as Add a controller; Add item when empty. - public string AddLabel { get; set; } = ""; - /// Optional previous setting in guided launch setup. Enables changing an earlier choice when setup resumes at this field. - public string SetupPrevious { get; set; } = ""; - /// For an Action field, runs it without another confirmation when a launch check requires it during guided setup. - /// Defaults to false. Normal settings pages still require pressing the action button. A failed action waits for an explicit retry. - public bool SetupAutoRun { get; set; } - /// Consecutive fields with the same non-empty hint share a row. The Player owns their sizing and appearance. + public bool FullWidth { get; set; } + /// + /// For a field, also inside a composite or collection, or a collection of text: the Player shows what it holds as dots, for a key or a token that + /// shouldn't show on a screen or in a screenshot. The value is stored like any other text. + /// + public bool Secret { get; set; } + /// The label of the button that adds an item to a , such as Add a controller; Add item when empty. + public string AddLabel { get; set; } = ""; + /// Optional previous setting in guided launch setup. Enables changing an earlier choice when setup resumes at this field. + public string SetupPrevious { get; set; } = ""; + /// For an Action field, runs it without another confirmation when a launch check requires it during guided setup. + /// Defaults to false. Normal settings pages still require pressing the action button. A failed action waits for an explicit retry. + public bool SetupAutoRun { get; set; } + /// Consecutive fields with the same non-empty hint share a row. The Player owns their sizing and appearance. /// The B2S plugin puts its fade-in and fade-out times on one row with Row = "fade". - public string Row { get; set; } = ""; + public string Row { get; set; } = ""; /// /// For a field, the of another field in the same group whose row shows the /// button, after its editor; the action then gets no row of its own, and its result is shown under that row. Empty (the default) @@ -477,21 +477,21 @@ public PluginSettingsSnapshot Defaults() { var values = new JObject(); foreach (var field in Fields) if (field.Default != null) values[field.Id] = field.Default.DeepClone(); - FillRecordDefaults(Fields, values); + FillRecordDefaults(Fields, values); return new PluginSettingsSnapshot(Version, values); } - internal static void FillRecordDefaults(IEnumerable fields, JObject values) - { - foreach (var field in fields) { - if (values[field.Id] == null && field.Default != null) values[field.Id] = field.Default.DeepClone(); - if (field.Kind == SettingKind.Composite) { - if (values[field.Id] == null) values[field.Id] = new JObject(); - if (values[field.Id] is JObject record) FillRecordDefaults(field.Children, record); - } else if (field.Kind == SettingKind.Collection && field.Children.Count > 0 && values[field.Id] is JArray records) { - foreach (var item in records.OfType()) FillRecordDefaults(field.Children, item); - } - } - } + internal static void FillRecordDefaults(IEnumerable fields, JObject values) + { + foreach (var field in fields) { + if (values[field.Id] == null && field.Default != null) values[field.Id] = field.Default.DeepClone(); + if (field.Kind == SettingKind.Composite) { + if (values[field.Id] == null) values[field.Id] = new JObject(); + if (values[field.Id] is JObject record) FillRecordDefaults(field.Children, record); + } else if (field.Kind == SettingKind.Collection && field.Children.Count > 0 && values[field.Id] is JArray records) { + foreach (var item in records.OfType()) FillRecordDefaults(field.Children, item); + } + } + } /// /// Checks values against the declared fields and returns every problem found. /// @@ -529,20 +529,20 @@ public IReadOnlyList Validate(PluginSettingsSnapshot snap } } if (field.Kind == SettingKind.Collection && value.Type != JTokenType.Array) error = "Expected a list."; - if (field.Kind == SettingKind.Composite && !(value is JObject)) error = "Expected a settings record."; - if (field.Children.Count > 0 && error == null) { - var nested = new PluginSettingsSchema(Version, new PluginSettingsGroup(field.Label, "", field.Children.ToArray())); - if (field.Kind == SettingKind.Composite && value is JObject record) { - var failures = nested.Validate(new PluginSettingsSnapshot(Version, record)); - if (failures.Count > 0) error = string.Join("; ", failures.Select(issue => issue.Field + ": " + issue.Message)); - } - if (field.Kind == SettingKind.Collection && value is JArray records) foreach (var item in records) { - if (!(item is JObject row)) { error = "Expected a list of settings records."; break; } - var failures = nested.Validate(new PluginSettingsSnapshot(Version, row)); - if (failures.Count > 0) { error = string.Join("; ", failures.Select(issue => issue.Field + ": " + issue.Message)); break; } - } - } - if (field.Kind == SettingKind.ScreenLayout) error = ScreenLayoutError(value); + if (field.Kind == SettingKind.Composite && !(value is JObject)) error = "Expected a settings record."; + if (field.Children.Count > 0 && error == null) { + var nested = new PluginSettingsSchema(Version, new PluginSettingsGroup(field.Label, "", field.Children.ToArray())); + if (field.Kind == SettingKind.Composite && value is JObject record) { + var failures = nested.Validate(new PluginSettingsSnapshot(Version, record)); + if (failures.Count > 0) error = string.Join("; ", failures.Select(issue => issue.Field + ": " + issue.Message)); + } + if (field.Kind == SettingKind.Collection && value is JArray records) foreach (var item in records) { + if (!(item is JObject row)) { error = "Expected a list of settings records."; break; } + var failures = nested.Validate(new PluginSettingsSnapshot(Version, row)); + if (failures.Count > 0) { error = string.Join("; ", failures.Select(issue => issue.Field + ": " + issue.Message)); break; } + } + } + if (field.Kind == SettingKind.ScreenLayout) error = ScreenLayoutError(value); if ((field.Kind == SettingKind.Text || field.Kind == SettingKind.File || field.Kind == SettingKind.Folder || field.Kind == SettingKind.Choice && !field.Multiple || field.Kind == SettingKind.Color) && value.Type != JTokenType.String) error = "Expected text."; if (field.Kind == SettingKind.Choice && field.Multiple && (!(value is JArray picked) || picked.Any(item => item.Type != JTokenType.String))) error = "Expected a list of choices."; if (field.Kind == SettingKind.Rectangle) { @@ -557,19 +557,19 @@ public IReadOnlyList Validate(PluginSettingsSnapshot snap } return issues; } - private static string? ScreenLayoutError(JToken value) - { - if (!(value is JArray screens)) return "Expected a screen layout."; - var ids = new HashSet(StringComparer.Ordinal); - foreach (var item in screens) { - if (!(item is JObject screen) || screen["screen"] == null || screen["screen"]!.Type != JTokenType.String && screen["screen"]!.Type != JTokenType.Integer || string.IsNullOrWhiteSpace(screen["screen"]!.ToString()) || !ids.Add(screen["screen"]!.ToString())) return "Each screen needs a unique identifier."; - foreach (string axis in new[] { "x", "y", "width", "height" }) { - var number = screen[axis]; - if (number?.Type != JTokenType.Integer || !int.TryParse(number.ToString(), out int coordinate) || (axis == "width" || axis == "height") && (coordinate < 1 || coordinate > 16384)) return "Use integer coordinates and dimensions from 1 to 16384 pixels."; - } - } - return null; - } + private static string? ScreenLayoutError(JToken value) + { + if (!(value is JArray screens)) return "Expected a screen layout."; + var ids = new HashSet(StringComparer.Ordinal); + foreach (var item in screens) { + if (!(item is JObject screen) || screen["screen"] == null || screen["screen"]!.Type != JTokenType.String && screen["screen"]!.Type != JTokenType.Integer || string.IsNullOrWhiteSpace(screen["screen"]!.ToString()) || !ids.Add(screen["screen"]!.ToString())) return "Each screen needs a unique identifier."; + foreach (string axis in new[] { "x", "y", "width", "height" }) { + var number = screen[axis]; + if (number?.Type != JTokenType.Integer || !int.TryParse(number.ToString(), out int coordinate) || (axis == "width" || axis == "height") && (coordinate < 1 || coordinate > 16384)) return "Use integer coordinates and dimensions from 1 to 16384 pixels."; + } + } + return null; + } } /// @@ -638,7 +638,7 @@ public IReadOnlyList Strings(string id) => Value(id) is JArray items /// /// The field ID. /// The value to return when the field is absent, not an integer or out of range. - public int Integer(string id, int fallback = 0) => Value(id)?.Type == JTokenType.Integer && int.TryParse(Value(id)!.ToString(), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int number) ? number : fallback; + public int Integer(string id, int fallback = 0) => Value(id)?.Type == JTokenType.Integer && int.TryParse(Value(id)!.ToString(), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int number) ? number : fallback; /// Returns a field's value if it is a JSON integer or floating-point number, otherwise . /// The field ID. /// The value to return when the field is absent or not a number. @@ -728,8 +728,8 @@ public sealed class PluginChoiceRequest public GameIdentity? Game { get; } /// The selected table package, when the request concerns one; null for global settings. public PluginPackageReference? Package { get; set; } - /// Optional progress sink for a user-requested action. Report from any thread; the caller owns dispatch. - public IProgress? Progress { get; set; } + /// Optional progress sink for a user-requested action. Report from any thread; the caller owns dispatch. + public IProgress? Progress { get; set; } /// /// The effective settings to work with, including unsaved edits from the settings page. Use these, not the saved values, so that /// catalogs follow what the user just changed (for example PinUP lists the packs of the library folder in the draft). @@ -777,16 +777,16 @@ public sealed class PluginChoiceCatalog public string Revision { get; } /// The items in display order, including unavailable ones. public IReadOnlyList Choices { get; } - /// Explains how to get choices when none are available; shown instead of an empty selector. - public string EmptyMessage { get; set; } = ""; + /// Explains how to get choices when none are available; shown instead of an empty selector. + public string EmptyMessage { get; set; } = ""; /// Optional guidance when selectable items exist, replacing empty-source instructions during launch setup. public string AvailableMessage { get; set; } = ""; - /// Explains a saved choice absent from an incomplete catalog, if the default offline-source message does not apply. - public string MissingSelectionMessage { get; set; } = ""; - /// Optional HTTPS page where the user can obtain the items this catalog requires. - public string SourceUrl { get; set; } = ""; - /// Label for the optional source-page button. - public string SourceLabel { get; set; } = "Open download page"; + /// Explains a saved choice absent from an incomplete catalog, if the default offline-source message does not apply. + public string MissingSelectionMessage { get; set; } = ""; + /// Optional HTTPS page where the user can obtain the items this catalog requires. + public string SourceUrl { get; set; } = ""; + /// Label for the optional source-page button. + public string SourceLabel { get; set; } = "Open download page"; /// False when a runtime-only catalog cannot be inspected while its game is stopped. /// /// A saved selection missing from an incomplete catalog is kept and not reported as an error. @@ -803,20 +803,20 @@ public sealed class PluginChoiceCatalog public PluginChoice? Find(string id) => Choices.FirstOrDefault(choice => choice.Id == id); } - /// Progress of a settings action, with a fraction from zero to one and a user-facing message. - public readonly struct PluginActionProgress - { - public double Fraction { get; } - public string Message { get; } - public PluginActionProgress(double fraction, string message) { Fraction = fraction; Message = message; } - } - + /// Progress of a settings action, with a fraction from zero to one and a user-facing message. + public readonly struct PluginActionProgress + { + public double Fraction { get; } + public string Message { get; } + public PluginActionProgress(double fraction, string message) { Fraction = fraction; Message = message; } + } + /// The outcome of a settings action, a reconfiguration or a settings commit. /// /// Plugins return it from , and /// . The host and the settings session return it when they save settings. /// - public readonly struct PluginActionResult + public readonly struct PluginActionResult { /// Whether the operation succeeded. A failed reconfiguration must leave the plugin as it was. public bool Success { get; } @@ -1274,6 +1274,11 @@ public sealed class PluginGameOutput public bool Configured { get; set; } /// Whether the game has it, for one the configuration uses that the game doesn't list; true when not known. public bool Present { get; set; } = true; + /// + /// Whether the game lists it, named or not; false for one only the configuration uses. Where the game lists others of the + /// same kind, such as its coils, the Player takes one of that kind it doesn't list as missing from the game. + /// + public bool Listed { get; set; } = true; } /// A board of a and its outputs. From e94604306a47265ae7fd52f3572d30ac460cadee Mon Sep 17 00:00:00 2001 From: freezy Date: Sun, 6 Dec 2026 02:01:17 +0100 Subject: [PATCH 11/11] plugins: a snapshot of outputs keeps their names and grouping too Documents that IPluginOutputSnapshots covers what IPluginOutputDescriber changes, so Cancel undoes a rename. The .vpe items schema is not affected. --- VisualPinball.Plugins/Configuration/PluginSchema.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/VisualPinball.Plugins/Configuration/PluginSchema.cs b/VisualPinball.Plugins/Configuration/PluginSchema.cs index eec26748b..9a7589b01 100644 --- a/VisualPinball.Plugins/Configuration/PluginSchema.cs +++ b/VisualPinball.Plugins/Configuration/PluginSchema.cs @@ -1498,8 +1498,9 @@ public interface IPluginOutputTriggerEditor public interface IPluginOutputSnapshots { /// - /// Keeps what a field's outputs are now: what they drive and, for a game, what fires them; whatever - /// and change for that field. + /// Keeps what a field's outputs are now: what they drive, what they and their toys are called and grouped as, and, for a + /// game, what fires them; whatever , and + /// change for that field, so Cancel undoes a rename too. /// /// The field's . /// The game, table and draft settings; is empty.