diff --git a/EvenBetterFastSim.Tests/NodeMillisecondsViewModelTests.cs b/EvenBetterFastSim.Tests/NodeMillisecondsViewModelTests.cs new file mode 100644 index 0000000..a8364c5 --- /dev/null +++ b/EvenBetterFastSim.Tests/NodeMillisecondsViewModelTests.cs @@ -0,0 +1,210 @@ +using System.Collections.Generic; +using EvenBetterFastSim.Services; +using EvenBetterFastSim.Window_Helpers; +using EvenBetterFastSim.WPF.ViewModels; +using EvenBetterFastSim.WPF.ViewModels.Graph; +using SecsGemScenarioEngine.Models; +using Xunit; + +namespace EvenBetterFastSim.Tests; + +/// +/// The editor for a node's time in milliseconds (GitLab secsgem/evencoolerfastsim#18). It only lets a whole number in +/// digits through, because the engine takes everything else as "no wait" without an error. +/// +public class NodeMillisecondsViewModelTests +{ + [Fact] + public void Ok_writes_the_new_time_into_the_node() + { + var node = WaitNode("1500"); + var editor = NodeMillisecondsViewModel.ForWait(node); + var closed = 0; + editor.CloseAction = () => closed++; + Assert.Equal("Wait", editor.HeaderText); + Assert.Equal("1500", editor.Text); + Assert.Null(editor.Error); + + editor.Text = " 2500 "; + Assert.True(editor.AcceptButtonClickCommand.CanExecute(null)); + editor.AcceptButtonClickCommand.Execute(null); + editor.ApplyTo(node); + + Assert.True(editor.Accepted); + Assert.Equal(2500, editor.Milliseconds); + Assert.Equal(1, closed); + Assert.Equal("2500", node.TransactionName); + Assert.Equal("Wait 2500 ms", node.Title); + } + + [Theory] + [InlineData("")] + [InlineData("0")] + [InlineData("-1")] + [InlineData("+5")] + [InlineData("1.5")] + [InlineData("12,6")] + [InlineData("12.600")] + [InlineData("20 s")] + [InlineData("1 500")] + [InlineData("2147483648")] + [InlineData("99999999999")] + [InlineData("1500")] + public void Anything_but_a_whole_number_above_zero_cannot_be_confirmed(string text) + { + var node = WaitNode("1500"); + var editor = NodeMillisecondsViewModel.ForWait(node); + var closed = 0; + editor.CloseAction = () => closed++; + + editor.Text = text; + + Assert.NotNull(editor.Error); + Assert.False(editor.AcceptButtonClickCommand.CanExecute(null)); + // Enter in the dialog executes the command only if it can; a direct call must not get through either. + editor.AcceptButtonClickCommand.Execute(null); + editor.ApplyTo(node); + Assert.False(editor.Accepted); + Assert.Equal(0, closed); + Assert.Equal("1500", node.TransactionName); + } + + [Theory] + [InlineData("1", 1)] + [InlineData("0001500", 1500)] + [InlineData("2147483647", int.MaxValue)] + public void Whole_numbers_above_zero_are_accepted(string text, int milliseconds) + { + var node = WaitNode("7"); + var editor = NodeMillisecondsViewModel.ForWait(node); + + editor.Text = text; + editor.AcceptButtonClickCommand.Execute(null); + editor.ApplyTo(node); + + Assert.Equal(milliseconds, editor.Milliseconds); + Assert.Equal(milliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture), node.TransactionName); + } + + /// A node from a file with "20 s" opens with that text and says what is wrong; correcting it clears the error. + [Fact] + public void Invalid_time_from_a_file_is_shown_and_can_be_corrected() + { + var node = WaitNode("20 s"); + var editor = NodeMillisecondsViewModel.ForWait(node); + var changed = new List(); + editor.PropertyChanged += (_, e) => changed.Add(e.PropertyName); + var requeried = 0; + editor.AcceptButtonClickCommand.CanExecuteChanged += (_, _) => requeried++; + Assert.Equal("20 s", editor.Text); + Assert.NotNull(editor.Error); + Assert.False(editor.AcceptButtonClickCommand.CanExecute(null)); + + editor.Text = "20000"; + + Assert.Null(editor.Error); + Assert.Contains(nameof(NodeMillisecondsViewModel.Error), changed); + // The OK button asks CanExecute again only when the command says so; without it the button stays grey. + Assert.Equal(1, requeried); + Assert.True(editor.AcceptButtonClickCommand.CanExecute(null)); + editor.AcceptButtonClickCommand.Execute(null); + editor.ApplyTo(node); + Assert.Equal("20000", node.TransactionName); + } + + /// + /// A value from a file with characters nobody can see around the digits (a non-breaking space, a zero-width + /// space, a byte order mark). The editor opens with the bare digits, and OK repairs the value. + /// + [Theory] + [InlineData("\u00A01500\u00A0")] + [InlineData("1500\u200B")] + [InlineData("\uFEFF1500")] + [InlineData(" \t1500\r\n ")] + public void Time_with_characters_nobody_can_see_around_it_is_repaired_by_ok(string fromFile) + { + var node = WaitNode(fromFile); + var editor = NodeMillisecondsViewModel.ForWait(node); + Assert.Equal("1500", editor.Text); + Assert.Null(editor.Error); + + editor.AcceptButtonClickCommand.Execute(null); + editor.ApplyTo(node); + + Assert.Equal("1500", node.TransactionName); + Assert.Equal("Wait 1500 ms", node.Title); + } + + /// The same characters typed or pasted into the box: OK writes the bare digits. + [Fact] + public void Pasted_time_with_characters_nobody_can_see_around_it_is_accepted() + { + var node = WaitNode("7"); + var editor = NodeMillisecondsViewModel.ForWait(node); + + editor.Text = "\u00A02500\u200B"; + Assert.Null(editor.Error); + editor.AcceptButtonClickCommand.Execute(null); + editor.ApplyTo(node); + + Assert.Equal("2500", node.TransactionName); + } + + /// + /// Such a character inside the number: the box shows "1500", but it is not a number. The message has to say + /// why, "use digits only" would not help. + /// + [Fact] + public void Character_nobody_can_see_inside_the_number_is_named_in_the_message() + { + var node = WaitNode("15\u200B00"); + var editor = NodeMillisecondsViewModel.ForWait(node); + + Assert.Equal("15\u200B00", editor.Text); + Assert.False(editor.AcceptButtonClickCommand.CanExecute(null)); + Assert.Equal( + "The text contains characters that cannot be seen: 15[U+200B]00. Type the number again, in digits only.", + editor.Error); + + editor.Text = "1 500"; + Assert.Equal("This is not a whole number from 1 to 2147483647. Use digits only, for example 1500.", editor.Error); + + editor.Text = "1500"; + Assert.Null(editor.Error); + Assert.True(editor.AcceptButtonClickCommand.CanExecute(null)); + } + + /// Without the mapping a double-click on a Wait node ends in an exception of WindowManager. + [Fact] + public void Editor_opens_in_the_shared_dialog_window() + { + var editor = NodeMillisecondsViewModel.ForWait(WaitNode("1500")); + + Assert.Equal(typeof(DialogWindow), new WindowMapper().GetWindowTypeForViewModel(editor)); + } + + [Fact] + public void Cancel_leaves_the_node_as_it_is() + { + var node = WaitNode("1500"); + var editor = NodeMillisecondsViewModel.ForWait(node); + + editor.Text = "9000"; + editor.ApplyTo(node); + + Assert.False(editor.Accepted); + Assert.Equal("1500", node.TransactionName); + } + + /// The minimum is a parameter: a later node type may allow 0. + [Fact] + public void Minimum_decides_whether_zero_is_allowed() + { + Assert.False(new NodeMillisecondsViewModel("t", "l", "0", minimum: 1).AcceptButtonClickCommand.CanExecute(null)); + Assert.True(new NodeMillisecondsViewModel("t", "l", "0", minimum: 0).AcceptButtonClickCommand.CanExecute(null)); + Assert.Contains(" 0 ", new NodeMillisecondsViewModel("t", "l", null, minimum: 0).Hint); + Assert.Contains(" 1 ", new NodeMillisecondsViewModel("t", "l", null, minimum: 1).Error); + } + + private static ScenarioNodeViewModel WaitNode(string? time) => new() { Type = NodeType.Wait, TransactionName = time }; +} diff --git a/EvenBetterFastSim.Tests/WaitNodeTests.cs b/EvenBetterFastSim.Tests/WaitNodeTests.cs new file mode 100644 index 0000000..69bebc9 --- /dev/null +++ b/EvenBetterFastSim.Tests/WaitNodeTests.cs @@ -0,0 +1,172 @@ +using System.Globalization; +using System.Linq; +using System.Text.Json; +using System.Windows; +using EvenBetterFastSim.WPF.ViewModels; +using EvenBetterFastSim.WPF.ViewModels.Graph; +using MessagePack; +using SecsGemScenarioEngine.Models; +using Xunit; + +namespace EvenBetterFastSim.Tests; + +/// +/// A Wait node can be made on the canvas and shows its time (GitLab secsgem/evencoolerfastsim#18). The time is text in +/// TransactionName; the engine waits only for a whole number greater than 0 and takes anything else as "no wait" +/// without an error, so the title has to say when the value is not a time. +/// +public class WaitNodeTests +{ + [Theory] + [InlineData("1500", "Wait 1500 ms")] + [InlineData("12600", "Wait 12600 ms")] + [InlineData(" 250 ", "Wait 250 ms")] + [InlineData("0", "Wait 0 ms")] + [InlineData("20 s", "Wait (invalid: 20 s)")] + [InlineData("12,6", "Wait (invalid: 12,6)")] + [InlineData("12.600", "Wait (invalid: 12.600)")] + [InlineData("-5", "Wait (invalid: -5)")] + [InlineData("99999999999", "Wait (invalid: 99999999999)")] + [InlineData("2147483647", "Wait 2147483647 ms")] + [InlineData("2147483648", "Wait (invalid: 2147483648)")] + [InlineData("\t250\r\n", "Wait 250 ms")] + [InlineData("\t20 s\r\n", "Wait (invalid: 20 s)")] + [InlineData("", "Wait (no time set)")] + [InlineData(" ", "Wait (no time set)")] + [InlineData(null, "Wait (no time set)")] + public void Title_shows_the_time_or_what_is_wrong_with_it(string? text, string title) + { + var node = new ScenarioNodeViewModel { Type = NodeType.Wait, TransactionName = text }; + + Assert.Equal(title, node.Title); + } + + /// + /// The engine skips only space, tab and line ends around the number. Any other character nobody can see (a + /// non-breaking space from a hand-edited file) makes the value invalid, so the title has to show it: + /// "Wait (invalid: 1500)" would look like a valid time. + /// + [Theory] + [InlineData("\u00A01500", "Wait (invalid: [U+00A0]1500)")] + [InlineData("1500\u200B", "Wait (invalid: 1500[U+200B])")] + [InlineData("\uFEFF1500", "Wait (invalid: [U+FEFF]1500)")] + [InlineData("12\t600", "Wait (invalid: 12[U+0009]600)")] + [InlineData(" 1 500 ", "Wait (invalid: 1 500)")] + public void Title_shows_characters_nobody_can_see(string text, string title) + { + var node = new ScenarioNodeViewModel { Type = NodeType.Wait, TransactionName = text }; + + Assert.Equal(title, node.Title); + } + + /// + /// A leading sign is the one thing the engine versions read differently: up to package 1.0.0-build-0027 with + /// the culture of the computer, later with the invariant culture. The culture decides which characters are the + /// signs: Windows takes them from the regional settings of the user, and ICU data write the plus sign of Persian + /// or Hebrew with a direction mark in front (U+200E U+002B). On a computer with such a plus sign "+5" is a + /// number for one engine and not for the other, so the title must not promise a wait. The culture is made by + /// hand, so the test does not depend on the culture data of the computer it runs on. + /// + [Fact] + public void Title_promises_a_wait_only_if_every_engine_version_reads_the_time() + { + var withMark = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + withMark.NumberFormat.PositiveSign = "\u200E+"; + var before = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + Assert.Equal("Wait 5 ms", WaitTime.Title("+5")); + + CultureInfo.CurrentCulture = withMark; + // The culture is in effect: a read with the culture of the computer takes the other spelling. + Assert.False(int.TryParse("+5", out _)); + Assert.True(int.TryParse("\u200E+5", out _)); + + Assert.Equal("Wait (invalid: +5)", WaitTime.Title("+5")); + Assert.Equal("Wait (invalid: [U+200E]+5)", WaitTime.Title("\u200E+5")); + Assert.Equal("Wait 12600 ms", WaitTime.Title("12600")); + } + finally + { + CultureInfo.CurrentCulture = before; + } + } + + /// Until #18 a DisplayName replaced the number, so the node did not show how long it waits. + [Fact] + public void Title_follows_the_time_and_is_not_replaced_by_a_display_name() + { + var node = new ScenarioNodeViewModel { Type = NodeType.Wait, TransactionName = "1500", DisplayName = "Pause" }; + Assert.Equal("Wait 1500 ms", node.Title); + + node.TransactionName = "250"; + + Assert.Equal("Wait 250 ms", node.Title); + } + + [Fact] + public void Wait_node_from_the_palette_starts_with_one_second() + { + var node = ScenarioNodeViewModel.CreateStructural(NodeType.Wait, new Point(120, 80)); + + Assert.Equal(NodeType.Wait, node.Type); + Assert.Equal("1000", node.TransactionName); + Assert.Equal("Wait 1000 ms", node.Title); + Assert.Equal(new Point(120, 80), node.Location); + Assert.Single(node.Input); + Assert.Equal(["Done"], node.Output.Select(connector => connector.Title)); + Assert.True(node.IsDeletable); + } + + [Fact] + public void And_node_from_the_palette_has_no_parameter() + { + var node = ScenarioNodeViewModel.CreateStructural(NodeType.And, new Point(10, 20)); + + Assert.Equal(NodeType.And, node.Type); + Assert.Null(node.TransactionName); + Assert.Equal("AND", node.Title); + Assert.Equal(new Point(10, 20), node.Location); + } + + /// The time survives saving and loading as a MessagePack file (.msgpack). + [Fact] + public void Time_survives_saving_and_loading_as_MessagePack() + { + var node = ScenarioNodeViewModel.CreateStructural(NodeType.Wait, new Point(5, 6)); + node.TransactionName = "12600"; + var graph = new ScenarioGraph { Name = "s", Nodes = [node.ToModel()] }; + + var cancellation = TestContext.Current.CancellationToken; + var bytes = MessagePackSerializer.Serialize(ScenarioGraphDto.From(graph), cancellationToken: cancellation); + var loaded = MessagePackSerializer.Deserialize(bytes, cancellationToken: cancellation).ToModel(); + var reloaded = ScenarioNodeViewModel.FromModel(loaded.Nodes.Single()); + + Assert.Equal(NodeType.Wait, reloaded.Type); + Assert.Equal("12600", reloaded.TransactionName); + Assert.Equal("Wait 12600 ms", reloaded.Title); + Assert.Equal(node.Id, reloaded.Id); + } + + /// + /// The same as a JSON file, written and read with the calls of ScenariosViewModel (every other extension than + /// .msgpack, and the export). + /// + [Fact] + public void Time_survives_saving_and_loading_as_JSON() + { + var node = ScenarioNodeViewModel.CreateStructural(NodeType.Wait, new Point(5, 6)); + node.TransactionName = "12600"; + var graph = new ScenarioGraph { Name = "s", Nodes = [node.ToModel()] }; + + var json = JsonSerializer.Serialize(graph, new JsonSerializerOptions { WriteIndented = true }); + var loaded = JsonSerializer.Deserialize(json)!; + var reloaded = ScenarioNodeViewModel.FromModel(loaded.Nodes.Single()); + + Assert.Equal(NodeType.Wait, reloaded.Type); + Assert.Equal("12600", reloaded.TransactionName); + Assert.Equal("Wait 12600 ms", reloaded.Title); + Assert.Equal(node.Id, reloaded.Id); + } +} diff --git a/EvenBetterFastSim/Services/WindowMapper.cs b/EvenBetterFastSim/Services/WindowMapper.cs index dc24bdb..be9cff9 100644 --- a/EvenBetterFastSim/Services/WindowMapper.cs +++ b/EvenBetterFastSim/Services/WindowMapper.cs @@ -28,6 +28,7 @@ public WindowMapper() RegisterMapping(); RegisterMapping(); RegisterMapping(); + RegisterMapping(); } /// diff --git a/EvenBetterFastSim/WPF/ViewModels/Graph/ScenarioNodeViewModel.cs b/EvenBetterFastSim/WPF/ViewModels/Graph/ScenarioNodeViewModel.cs index 14ce21f..f1a19d4 100644 --- a/EvenBetterFastSim/WPF/ViewModels/Graph/ScenarioNodeViewModel.cs +++ b/EvenBetterFastSim/WPF/ViewModels/Graph/ScenarioNodeViewModel.cs @@ -95,6 +95,17 @@ public string? BindingSummary /// Start and End are structural — they can't be deleted from the canvas. public bool IsDeletable => Type is not (NodeType.Start or NodeType.End); + /// + /// A node dragged from the palette (And, Wait). A Wait node starts with + /// ; double-click it to change the time. + /// + public static ScenarioNodeViewModel CreateStructural(NodeType type, Point location) => new() + { + Type = type, + TransactionName = type == NodeType.Wait ? WaitTime.Format(WaitTime.DefaultMilliseconds) : null, + Location = location + }; + public ScenarioNodeViewModel() { InitializeConnectors(); @@ -179,7 +190,7 @@ private void UpdateTitleFromType() NodeType.SendAndWait => label ?? "Send & Wait", NodeType.Send => label ?? "Send", NodeType.Condition => label ?? "If", - NodeType.Wait => label ?? "Wait", + NodeType.Wait => WaitTime.Title(TransactionName), NodeType.Receive => label ?? "Receive", NodeType.And => "AND", _ => label ?? Type.ToString() diff --git a/EvenBetterFastSim/WPF/ViewModels/Graph/WaitTime.cs b/EvenBetterFastSim/WPF/ViewModels/Graph/WaitTime.cs new file mode 100644 index 0000000..951e214 --- /dev/null +++ b/EvenBetterFastSim/WPF/ViewModels/Graph/WaitTime.cs @@ -0,0 +1,84 @@ +using System.Globalization; +using System.Text; + +namespace EvenBetterFastSim.WPF.ViewModels.Graph; + +/// +/// The time of a Wait node. It is kept as text in ScenarioNode.TransactionName, in milliseconds. +/// +public static class WaitTime +{ + /// The time a Wait node gets when it is dragged from the palette. + public const int DefaultMilliseconds = 1000; + + /// The characters int.TryParse skips around a number: space, tab, line feed, vertical tab, form feed, carriage return. + private static readonly char[] SkippedByTheEngine = [' ', '\t', '\n', '\v', '\f', '\r']; + + /// + /// True for a text that every version of the scenario engine reads as the same whole number (int.TryParse + /// in ExecuteWaitAsync): the digits 0-9, within the range of an int, with spaces around them and a leading sign + /// allowed. The engine waits only if that number is greater than 0; anything else is no wait, without an error. + /// + /// + /// The engine up to package 1.0.0-build-0027 reads with the culture of the computer, a later one with the + /// invariant culture. The two can differ only in the sign, because the culture decides which characters are the + /// plus and the minus sign (Windows takes them from the regional settings of the user). "+5" is then a number + /// for one engine and not for the other. Such a text does not count as a time here, so the title never promises + /// a wait that the engine in use skips. On a computer where the plus sign is "+" this changes nothing. + /// + public static bool TryRead(string? text, out int milliseconds) => + int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out milliseconds) && + int.TryParse(text, NumberStyles.Integer, CultureInfo.CurrentCulture, out _); + + public static string Format(int milliseconds) => milliseconds.ToString(CultureInfo.InvariantCulture); + + /// + /// The node's title: "Wait 12600 ms", or what is wrong with the value. Until GitLab secsgem/evencoolerfastsim#18 + /// the node showed only its DisplayName or the bare number, and nothing showed that "20 s" means no wait at all. + /// + public static string Title(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + return "Wait (no time set)"; + return TryRead(text, out var milliseconds) && milliseconds >= 0 + ? $"Wait {Format(milliseconds)} ms" + : $"Wait (invalid: {Visible(text.Trim(SkippedByTheEngine))})"; + } + + /// + /// A character nobody can see in a title or a text box: white space other than the space, control characters and + /// format characters (a non-breaking space, a tab, a zero-width space, a byte order mark). + /// + public static bool IsHidden(char character) => + character != ' ' && + (char.IsWhiteSpace(character) || char.IsControl(character) || + char.GetUnicodeCategory(character) == UnicodeCategory.Format); + + /// + /// Writes characters nobody can see as [U+00A0]. A value from a hand-edited file with a non-breaking space or a + /// zero-width character in it would otherwise show as "Wait (invalid: 1500)", which looks like a valid time. + /// + public static string Visible(string text) + { + var visible = new StringBuilder(text.Length); + foreach (var character in text) + { + if (IsHidden(character)) + visible.Append(CultureInfo.InvariantCulture, $"[U+{(int)character:X4}]"); + else + visible.Append(character); + } + return visible.ToString(); + } + + /// The text without the spaces and the characters nobody can see at its two ends. + public static string TrimEnds(string? text) + { + if (text is null) return string.Empty; + var start = 0; + var end = text.Length; + while (start < end && (text[start] == ' ' || IsHidden(text[start]))) start++; + while (end > start && (text[end - 1] == ' ' || IsHidden(text[end - 1]))) end--; + return text[start..end]; + } +} diff --git a/EvenBetterFastSim/WPF/ViewModels/NodeMillisecondsViewModel.cs b/EvenBetterFastSim/WPF/ViewModels/NodeMillisecondsViewModel.cs new file mode 100644 index 0000000..22678ae --- /dev/null +++ b/EvenBetterFastSim/WPF/ViewModels/NodeMillisecondsViewModel.cs @@ -0,0 +1,105 @@ +using System; +using System.Globalization; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using EvenBetterFastSim.WPF.ViewModels.Graph; + +namespace EvenBetterFastSim.WPF.ViewModels; + +/// +/// Editor for a scenario node's parameter in milliseconds, such as the time of a Wait node. Hosted in the shared +/// DialogWindow, whose OK button binds to +/// (GitLab secsgem/evencoolerfastsim#18). +/// +/// +/// +/// The engine reads a Wait node's time with int.TryParse and treats everything it cannot read as "no wait", without an +/// error. So the editor only accepts a whole number written in digits, and the node stores it in that form. +/// +/// +/// Not an ObservableValidator on purpose: DialogWindow binds its content to the view model itself, and WPF then draws +/// its red validation frame around the whole dialog for a view model that reports data errors. The message under the +/// field is enough. +/// +/// +public partial class NodeMillisecondsViewModel : ObservableObject, IBaseViewModel +{ + private readonly int minimum; + + public Action? CloseAction { get; set; } + + /// True when the user confirmed with OK (vs. cancelling / closing the dialog). + public bool Accepted { get; private set; } + + /// The value the user confirmed; valid once is true. + public int Milliseconds { get; private set; } + + /// Title of the dialog. + public string HeaderText { get; } + + /// Label in front of the input field. + public string Label { get; } + + /// Says which values are allowed. + public string Hint { get; } + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(Error))] + [NotifyCanExecuteChangedFor(nameof(AcceptButtonClickCommand))] + private string text; + + /// What is wrong with , or null. + public string? Error + { + get + { + if (TryParse(Text, minimum, out _)) return null; + // A character nobody can see inside the number (from a file or pasted): the box shows "1500", so say why. + var entered = WaitTime.TrimEnds(Text); + var visible = WaitTime.Visible(entered); + return visible != entered + ? $"The text contains characters that cannot be seen: {visible}. Type the number again, in digits only." + : $"This is not a whole number from {minimum} to {int.MaxValue}. Use digits only, for example 1500."; + } + } + + /// Smallest value the editor accepts (1 for a time that has to be greater than 0). + public NodeMillisecondsViewModel(string headerText, string label, string? text, int minimum) + { + HeaderText = headerText; + Label = label; + this.minimum = minimum; + Hint = $"Whole number from {minimum} to {int.MaxValue}."; + this.text = WaitTime.TrimEnds(text); + } + + /// The editor for the time of a Wait node; it starts with the node's current text, also when that is invalid. + public static NodeMillisecondsViewModel ForWait(ScenarioNodeViewModel node) => + new("Wait", "Wait time (ms)", node.TransactionName, minimum: 1); + + /// + /// Digits only, within the range of an int and not below the minimum. Spaces and characters nobody can see at + /// the two ends are ignored (); OK writes the bare digits. + /// + public static bool TryParse(string? text, int minimum, out int milliseconds) => + int.TryParse(WaitTime.TrimEnds(text), NumberStyles.None, CultureInfo.InvariantCulture, out milliseconds) && + milliseconds >= minimum; + + [RelayCommand(CanExecute = nameof(CanAccept))] + private void AcceptButtonClick() + { + if (!TryParse(Text, minimum, out var milliseconds)) return; + Milliseconds = milliseconds; + Accepted = true; + CloseAction?.Invoke(); + } + + private bool CanAccept() => Error is null; + + /// Writes the confirmed value into the node; does nothing if the dialog was cancelled. + public void ApplyTo(ScenarioNodeViewModel node) + { + if (Accepted) + node.TransactionName = WaitTime.Format(Milliseconds); + } +} diff --git a/EvenBetterFastSim/WPF/ViewModels/ScenariosViewModel.cs b/EvenBetterFastSim/WPF/ViewModels/ScenariosViewModel.cs index 77791e1..24e4459 100644 --- a/EvenBetterFastSim/WPF/ViewModels/ScenariosViewModel.cs +++ b/EvenBetterFastSim/WPF/ViewModels/ScenariosViewModel.cs @@ -553,7 +553,7 @@ private void AddNodeToCanvas(object? parameter) /// /// Opens the editor for a node: match conditions for a Receive node, response values for a - /// Send node. Invoked by right-click / double-click / Enter on the canvas. + /// Send node, the time for a Wait node. Invoked by right-click / double-click / Enter on the canvas. /// [RelayCommand] private void OpenNodeEditor(ScenarioNodeViewModel? node) @@ -575,6 +575,13 @@ private void OpenNodeEditor(ScenarioNodeViewModel? node) windowManager.ShowDialog(vm); break; } + case NodeType.Wait: + { + var vm = NodeMillisecondsViewModel.ForWait(node); + windowManager.ShowDialog(vm); + vm.ApplyTo(node); + break; + } } } @@ -637,12 +644,7 @@ private void EditSelectedNode() => /// Drops a structural node (e.g. an AND join) at the given canvas point. public void AddStructuralNode(NodeType type, Point canvasPosition) { - var node = new ScenarioNodeViewModel - { - Type = type, - Location = canvasPosition - }; - Nodes.Add(node); + Nodes.Add(ScenarioNodeViewModel.CreateStructural(type, canvasPosition)); LogInfo($"Added {type} node to scenario"); } diff --git a/EvenBetterFastSim/WPF/Windows/MainWindow.xaml b/EvenBetterFastSim/WPF/Windows/MainWindow.xaml index f19e6ff..f9ceb91 100644 --- a/EvenBetterFastSim/WPF/Windows/MainWindow.xaml +++ b/EvenBetterFastSim/WPF/Windows/MainWindow.xaml @@ -613,6 +613,10 @@ + + + + @@ -784,6 +788,14 @@ ToolTip="Join: continues only when every incoming connection has arrived"> + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/EvenBetterFastSim/WPF/Windows/NodeMillisecondsView.xaml.cs b/EvenBetterFastSim/WPF/Windows/NodeMillisecondsView.xaml.cs new file mode 100644 index 0000000..671b0c1 --- /dev/null +++ b/EvenBetterFastSim/WPF/Windows/NodeMillisecondsView.xaml.cs @@ -0,0 +1,21 @@ +using System.Windows.Controls; + +namespace EvenBetterFastSim.WPF.Windows; + +/// +/// Interaction logic for NodeMillisecondsView.xaml — editor content for a node parameter in milliseconds, +/// hosted inside the shared DialogWindow. +/// +public partial class NodeMillisecondsView : UserControl +{ + public NodeMillisecondsView() + { + InitializeComponent(); + // Ready to type: the value is selected, Enter confirms (DialogWindow). + Loaded += (_, _) => + { + ValueBox.Focus(); + ValueBox.SelectAll(); + }; + } +} diff --git a/EvenBetterFastSim/Window Helpers/DialogWindow.xaml b/EvenBetterFastSim/Window Helpers/DialogWindow.xaml index 04001f9..04d4b20 100644 --- a/EvenBetterFastSim/Window Helpers/DialogWindow.xaml +++ b/EvenBetterFastSim/Window Helpers/DialogWindow.xaml @@ -42,6 +42,9 @@ + + + diff --git a/EvenBetterFastSim/Window Helpers/DialogWindow.xaml.cs b/EvenBetterFastSim/Window Helpers/DialogWindow.xaml.cs index 39968c4..dddb1bc 100644 --- a/EvenBetterFastSim/Window Helpers/DialogWindow.xaml.cs +++ b/EvenBetterFastSim/Window Helpers/DialogWindow.xaml.cs @@ -1,4 +1,5 @@ using System.Windows.Input; +using EvenBetterFastSim.WPF.ViewModels; using EvenBetterFastSim.WPF.ViewModels.Responders; using Wpf.Ui.Controls; @@ -20,6 +21,12 @@ public DialogWindow() MinWidth = 560; MinHeight = 460; } + // A single field: the default form size would be mostly empty. + else if (e.NewValue is NodeMillisecondsViewModel) + { + Width = 460; + Height = 300; + } }; } diff --git a/README.md b/README.md index 17b3ccd..81395f9 100644 --- a/README.md +++ b/README.md @@ -98,8 +98,12 @@ The **Scenarios** section is a visual node graph for multi-step exchanges. Drag transaction from the **DRAG TO CANVAS** palette onto the canvas, wire nodes from **Start** to **End**, and press **Run** to execute them in order against the live connection. -Node types: **Send**, **Send & Wait** (send and wait for the reply), **Receive** (wait for a -matching incoming message, 30 s timeout) and **Wait** (a fixed delay). Scenarios are saved per instance and can be exported / imported. +Node types: **Send** and **Send & Wait** (both send the message and go on at once; neither waits for the +reply), **Receive** (waits for a matching incoming message until the run's **Timeout (s)** is over; with 0 it +waits until the message arrives or you press **Cancel**) and **Wait** (a fixed delay). To wait for a reply, put +a Receive node after the Send node. Drag **WAIT** from the **NODES** palette onto the canvas and double-click +the node to set its time in milliseconds; the node shows it as "Wait 1500 ms". +Scenarios are saved per instance and can be exported / imported. ### 7. Two instances talking diff --git a/specification/dialog_pattern.md b/specification/dialog_pattern.md index 44ba044..6b7961b 100644 --- a/specification/dialog_pattern.md +++ b/specification/dialog_pattern.md @@ -28,6 +28,8 @@ Related docs: [patterns.md](patterns.md), [project_overview.md](project_overview | `AddReportViewModel` | `AddReportView` | Done | | `AddEquipmentVariableViewModel` | `AddEquipmentVariableView` | Done | | `InstanceProfileViewModel` | `InstanceProfileView` | Done | +| `NodeResponderViewModel` | `NodeResponderView` | Done | +| `NodeMillisecondsViewModel` | `NodeMillisecondsView` | Done (constructed by the caller, not registered in DI) | | `SetUpViewModel` | `SetUpWindow` | Done | ## ViewModel conventions diff --git a/specification/features.md b/specification/features.md index 25759ed..0fad530 100644 --- a/specification/features.md +++ b/specification/features.md @@ -2,6 +2,36 @@ Related docs: [project_overview.md](project_overview.md), [secsgembase_library.md](secsgembase_library.md), [dialog_pattern.md](dialog_pattern.md), [SESSION_REFACTORING_LOG.md](../SESSION_REFACTORING_LOG.md) +## Wait node on the canvas + +A Wait node can be made and edited in the app (internal board, issue 18). Until then it only came from an imported +file, its time could only be changed in the file, and a value the engine cannot read ("20 s", "12,6") silently meant +"no wait" while the node only showed its name or the bare number. + +**Files:** `WPF/ViewModels/Graph/WaitTime.cs`, `WPF/ViewModels/Graph/ScenarioNodeViewModel.cs` (`CreateStructural`, +title), `WPF/ViewModels/NodeMillisecondsViewModel.cs`, `WPF/Windows/NodeMillisecondsView.xaml`, +`WPF/ViewModels/ScenariosViewModel.cs` (`OpenNodeEditor`, `AddStructuralNode`), `WPF/Windows/MainWindow.xaml` (palette +chip, node colour), `Window Helpers/DialogWindow.xaml` and `.xaml.cs`, `Services/WindowMapper.cs`. + +- **Palette:** the chip **WAIT** next to AND. Dropping it on the canvas makes a Wait node with 1000 ms. +- **Editor:** double-click, right-click or Enter on the node opens the dialog "Wait" with the field "Wait time (ms)". + It accepts a whole number from 1 to 2147483647 written in digits; OK or Enter writes it to the node's + `TransactionName`, where the engine reads it. Spaces and characters nobody can see at the ends of the text are + ignored; inside the number the message under the field names them. +- **Title:** "Wait 1500 ms". A value the engine cannot read shows as "Wait (invalid: 20 s)", a missing one as + "Wait (no time set)". A character nobody can see in such a value (a non-breaking space from a hand-edited file) + shows as "[U+00A0]". A `DisplayName` from a file no longer replaces the time. +- A time with a leading sign ("+5", only possible in a hand-edited file) shows as valid only if the culture of the + computer reads it too: the engine up to package `1.0.0-build-0027` reads with that culture, a later one with the + invariant culture (`WaitTime.TryRead`). Where the plus sign of the regional settings is "+", the two agree. +- `NodeMillisecondsViewModel` takes its title, label and minimum, so other node types with a time in ms can use it. + It is not an `ObservableValidator`: `DialogWindow` binds its content to the view model, and WPF then draws its red + validation frame around the whole dialog. +- The engine in SecsGemBase logs a warning for a time it cannot read once its change for this issue + ([SecsGemBase pull request 12](https://github.com/Pre-Se/SecsGemBase/pull/12)) is published and the app's packages + are raised to it. Every package up to `1.0.0-build-0027` skips the wait silently (the app pinned + `1.0.0-build-0018` when this was written), and the title is then the only sign. + ## Scenario runs leave the UI thread A scenario (Run or a loop) now executes on the thread pool. Until then every node ran on the WPF UI thread, because