From 021af042225155fdd6e9c62e9c39bc30ffcc53b5 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sun, 29 Nov 2026 20:10:34 -0500 Subject: [PATCH 1/2] feat(desktop): share the status bar text, machine list and plate-work guard MainStatusText words the main window's location, machine, material, utilization and version labels as WinForms does, with the labels' tooltips and the StatusBarLocationFollowsMouse setting both apps keep. MachineMenu lists the machines for Nest > Machine and the machine label (by name, the nest's checked, one no longer on file checked and disabled), and MachineSettingsSource.ApplyMachine assigns one with its support grid, cut-off defaults and spacing. PlateWorkGuard holds the "Finish or cancel the current nesting or plate action first." check. The WinForms main window delegates to them unchanged. Co-Authored-By: Claude Opus 5.5 --- .../Forms/MachineMenuTests.cs | 60 +++++++++++ .../Forms/MainStatusTextTests.cs | 91 +++++++++++++++++ .../MachineSettingsSourceTests.cs | 29 ++++++ OpenNest.Desktop/Forms/MachineMenu.cs | 51 ++++++++++ OpenNest.Desktop/Forms/MainStatusText.cs | 99 +++++++++++++++++++ OpenNest.Desktop/Forms/PlateWorkGuard.cs | 21 ++++ OpenNest.Desktop/MachineSettingsSource.cs | 17 ++++ OpenNest/Forms/MainForm.Guards.cs | 2 +- OpenNest/Forms/MainForm.Nest.cs | 28 ++---- OpenNest/Forms/MainStatusBar.cs | 39 ++------ OpenNest/Forms/UpdaterStatus.cs | 4 +- OpenNest/UpdaterService.cs | 10 +- 12 files changed, 386 insertions(+), 65 deletions(-) create mode 100644 OpenNest.Desktop.Tests/Forms/MachineMenuTests.cs create mode 100644 OpenNest.Desktop.Tests/Forms/MainStatusTextTests.cs create mode 100644 OpenNest.Desktop/Forms/MachineMenu.cs create mode 100644 OpenNest.Desktop/Forms/MainStatusText.cs create mode 100644 OpenNest.Desktop/Forms/PlateWorkGuard.cs diff --git a/OpenNest.Desktop.Tests/Forms/MachineMenuTests.cs b/OpenNest.Desktop.Tests/Forms/MachineMenuTests.cs new file mode 100644 index 00000000..49f57a8e --- /dev/null +++ b/OpenNest.Desktop.Tests/Forms/MachineMenuTests.cs @@ -0,0 +1,60 @@ +using OpenNest.Data; +using OpenNest.Forms; + +namespace OpenNest.Desktop.Tests.Forms; + +public class MachineMenuTests +{ + private static MachineConfig Machine(string name) => new() { Name = name }; + + [Fact] + public void NoNest_ListsOnlyADisabledNote() + { + var item = Assert.Single(MachineMenu.Items(null!, new[] { Machine("Laser") })); + + Assert.Equal(MachineMenu.NoNestText, item.Text); + Assert.False(item.Enabled); + Assert.Null(item.Machine); + } + + [Fact] + public void Machines_AreListedByNameWithTheNestsChecked() + { + var laser = Machine("laser"); + var fiber = Machine("Fiber"); + var nest = new Nest { Machine = new NestMachine(laser.Id, laser.Name) }; + + var items = MachineMenu.Items(nest, new[] { laser, fiber }); + + Assert.Equal(new[] { "Fiber", "laser" }, items.Select(i => i.Text)); + Assert.Equal(new[] { false, true }, items.Select(i => i.Checked)); + Assert.All(items, i => Assert.True(i.Enabled)); + Assert.Same(fiber, items[0].Machine); + Assert.True(MachineMenu.IsAssigned(nest, laser)); + Assert.False(MachineMenu.IsAssigned(nest, fiber)); + } + + [Fact] + public void AMachineNoLongerOnFile_StaysCheckedAndDisabled() + { + var nest = new Nest { Machine = new NestMachine(Guid.NewGuid(), "Old Plasma") }; + + var items = MachineMenu.Items(nest, new[] { Machine("Laser") }); + + Assert.Equal(2, items.Count); + var gone = items[1]; + Assert.Equal("Old Plasma (not on file)", gone.Text); + Assert.True(gone.Checked); + Assert.False(gone.Enabled); + Assert.Null(gone.Machine); + } + + [Fact] + public void NoMachines_PointsToMachineConfiguration() + { + var item = Assert.Single(MachineMenu.Items(new Nest(), Array.Empty())); + + Assert.Equal(MachineMenu.NoMachinesText, item.Text); + Assert.False(item.Enabled); + } +} diff --git a/OpenNest.Desktop.Tests/Forms/MainStatusTextTests.cs b/OpenNest.Desktop.Tests/Forms/MainStatusTextTests.cs new file mode 100644 index 00000000..11cef2e6 --- /dev/null +++ b/OpenNest.Desktop.Tests/Forms/MainStatusTextTests.cs @@ -0,0 +1,91 @@ +using System.Globalization; +using System.Reflection; +using OpenNest.Desktop.Interaction; +using OpenNest.Desktop.Tests.Interaction; +using OpenNest.Forms; +using OpenNest.Geometry; + +namespace OpenNest.Desktop.Tests.Forms; + +public sealed class MainStatusTextTests : IDisposable +{ + private readonly CultureInfo previous = CultureInfo.CurrentCulture; + + public MainStatusTextTests() => CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + + public void Dispose() => CultureInfo.CurrentCulture = previous; + + [Fact] + public void Location_ShowsBothCoordinatesToFourPlaces() => + Assert.Equal("Location: [1,234.5000, -0.1250]", MainStatusText.Location(new Vector(1234.5, -0.125))); + + [Fact] + public void Utilization_ShowsOnePlaceOfPercent() => + Assert.Equal("Util: 61.3 %", MainStatusText.Utilization(0.6125)); + + [Fact] + public void Material_ShowsNameGradeAndThicknessWithUnits() + { + Assert.Equal("Material: Steel A36 · 0.25 in", MainStatusText.Material("Steel", " A36 ", 0.25, Units.Inches)); + Assert.Equal("Material: 304 SS · 3 mm", MainStatusText.Material(" 304 SS ", "", 3, Units.Millimeters)); + Assert.Equal("Material: 0.1875 in", MainStatusText.Material(null, null, 0.1875, Units.Inches)); + Assert.Equal("Material: (none)", MainStatusText.Material("", " ", 0, Units.Inches)); + } + + [Fact] + public void Material_ReadsTheNest() + { + var nest = new Nest { Thickness = 0.5, Units = Units.Inches, Material = new Material("Mild Steel", "A36", 0.2836) }; + + Assert.Equal("Material: Mild Steel A36 · 0.5 in", MainStatusText.Material(nest)); + } + + [Fact] + public void Machine_ShowsTheNestsMachine() + { + Assert.Equal("Machine: CL-980", MainStatusText.Machine(new NestMachine(Guid.NewGuid(), " CL-980 "))); + Assert.Equal("Machine: (unnamed)", MainStatusText.Machine(new NestMachine(Guid.NewGuid(), ""))); + Assert.Equal("Machine: (none)", MainStatusText.Machine(null!)); + } + + [Fact] + public void Version_DropsBuildMetadata() + { + Assert.Equal("v1.2.3", MainStatusText.Version("1.2.3")); + Assert.DoesNotContain("+", MainStatusText.DisplayVersion(typeof(MainStatusText).Assembly)); + Assert.Equal( + typeof(MainStatusText).Assembly.GetCustomAttribute()! + .InformationalVersion.Split('+')[0], + MainStatusText.DisplayVersion(typeof(MainStatusText).Assembly)); + } + + [Fact] + public void LocationMode_FollowsTheMouseUnlessSavedOff() + { + var settings = new Dictionary(); + Assert.True(MainStatusText.ReadLocationFollowsMouse(settings)); + + MainStatusText.WriteLocationFollowsMouse(settings, false); + Assert.Equal("False", settings[MainStatusText.LocationFollowsMouseName]); + Assert.False(MainStatusText.ReadLocationFollowsMouse(settings)); + + settings[MainStatusText.LocationFollowsMouseName] = "nonsense"; + Assert.True(MainStatusText.ReadLocationFollowsMouse(settings)); + } + + [Fact] + public void PlateWork_IsBusyWhileAJobRunsOrAToolIsMidTask() + { + var plate = InteractionFixtures.Plate(); + var host = new TestToolHost(plate); + var tools = new[] { host.Tools.Current }; + + Assert.False(PlateWorkGuard.IsBusy(false, tools)); + Assert.True(PlateWorkGuard.IsBusy(true, tools)); + + // As the WinForms select action: a selection is work in progress. + host.Selection.Select(plate.Parts[0]); + Assert.True(PlateWorkGuard.IsBusy(false, tools)); + Assert.False(PlateWorkGuard.IsBusy(false, Array.Empty())); + } +} diff --git a/OpenNest.Desktop.Tests/MachineSettingsSourceTests.cs b/OpenNest.Desktop.Tests/MachineSettingsSourceTests.cs index 8a5f6004..aa9e68d9 100644 --- a/OpenNest.Desktop.Tests/MachineSettingsSourceTests.cs +++ b/OpenNest.Desktop.Tests/MachineSettingsSourceTests.cs @@ -330,4 +330,33 @@ public sealed class MachineSettingsSourceTests : IDisposable Assert.Equal(0.75, settings.PartClearance); } + + [Fact] + public void ApplyMachine_AssignsItAndGivesTheViewsAndTheUntouchedSheetItsDefaults() + { + var machine = CuttingMachine(); + var thickness = machine.Materials[0].Thicknesses[0]; + thickness.CutOff = new CutOffConfig { PartClearance = 0.75 }; + thickness.PartSpacing = 0.3; + new LocalJsonProvider(MachinesDirectory).SaveMachine(machine); + var nest = NestFor(machine, 0.25); + nest.Machine = null; + var used = nest.CreatePlate(); + used.PartSpacing = 0.1; + used.Parts.Add(new Part(new Drawing("square", new CNC.Program()))); + using var plates = new PlateManager(nest); + plates.EnsureSentinel(); + var sentinel = nest.Plates[^1]; + var views = new[] { new CutOffSettings { PartClearance = 0.1 }, new CutOffSettings { PartClearance = 0.2 } }; + + Machines().ApplyMachine(nest, machine, plates, views); + + Assert.Equal(machine.Id, nest.Machine!.Id); + Assert.Equal("Fiber 1", nest.Machine.Name); + Assert.All(views, settings => Assert.Equal(0.75, settings.PartClearance)); + Assert.Equal(0.3, nest.PlateDefaults.PartSpacing); + Assert.Equal(0.3, sentinel.PartSpacing); + // A sheet in use keeps its own spacing. + Assert.Equal(0.1, used.PartSpacing); + } } diff --git a/OpenNest.Desktop/Forms/MachineMenu.cs b/OpenNest.Desktop/Forms/MachineMenu.cs new file mode 100644 index 00000000..9c8e0361 --- /dev/null +++ b/OpenNest.Desktop/Forms/MachineMenu.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using OpenNest.Data; + +namespace OpenNest.Forms +{ + /// + /// One entry of the machine list: is the machine to assign when it is + /// chosen, or null for an entry that only informs. + /// + public sealed record MachineMenuItem(string Text, MachineConfig Machine, bool Checked, bool Enabled); + + /// + /// The machines listed by Nest > Machine and the status bar's machine label: those on + /// file by name, the active nest's checked; one assigned but no longer on file is shown + /// checked and disabled so the nest still says what it was made for. + /// + public static class MachineMenu + { + public const string NoNestText = "(no nest open)"; + public const string NoMachinesText = "(no machines; see Tools > Machine Configuration)"; + + /// The entries for (null when no nest is open). + public static IReadOnlyList Items(Nest nest, IEnumerable machines) + { + if (nest == null) + return new[] { new MachineMenuItem(NoNestText, null, false, false) }; + + var sorted = (machines ?? Enumerable.Empty()) + .OrderBy(m => m.Name, StringComparer.CurrentCultureIgnoreCase) + .ToList(); + var items = sorted + .Select(m => new MachineMenuItem(m.Name, m, m.Id == nest.Machine?.Id, true)) + .ToList(); + if (nest.Machine is { } assigned && sorted.All(m => m.Id != assigned.Id)) + items.Add(new MachineMenuItem($"{assigned.Name} (not on file)", null, true, false)); + if (items.Count == 0) + items.Add(new MachineMenuItem(NoMachinesText, null, false, false)); + return items; + } + + /// Whether is already the nest's, so choosing it changes nothing. + public static bool IsAssigned(Nest nest, MachineConfig machine) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(machine); + return nest.Machine?.Id == machine.Id; + } + } +} diff --git a/OpenNest.Desktop/Forms/MainStatusText.cs b/OpenNest.Desktop/Forms/MainStatusText.cs new file mode 100644 index 00000000..91282ebe --- /dev/null +++ b/OpenNest.Desktop/Forms/MainStatusText.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Reflection; +using OpenNest.Desktop; +using OpenNest.Geometry; + +namespace OpenNest.Forms +{ + /// + /// The main window's status bar text, worded as the WinForms main window words it: cursor + /// location, nest machine and material, plate utilization and the version, with the labels' + /// tooltips and the location display mode both desktop apps keep in user-settings.json. + /// Numbers are in the current culture. + /// + public static class MainStatusText + { + /// The user setting: true while the location follows the mouse, false while it shows the last left click. + public const string LocationFollowsMouseName = "StatusBarLocationFollowsMouse"; + + public const string MachineToolTip = "Click or right-click to change the machine"; + public const string MaterialToolTip = "Click to edit nest info; right-click for more"; + public const string VersionToolTip = "OpenNest version"; + + /// Whether the location follows the mouse (the WinForms default) rather than only left clicks. + public static bool ReadLocationFollowsMouse(IReadOnlyDictionary settings) + { + ArgumentNullException.ThrowIfNull(settings); + return UserSettingText.ReadBool(settings, LocationFollowsMouseName, true); + } + + /// Stores the location mode in the WinForms format. + public static void WriteLocationFollowsMouse(IDictionary settings, bool followsMouse) + { + ArgumentNullException.ThrowIfNull(settings); + settings[LocationFollowsMouseName] = UserSettingText.Format(followsMouse); + } + + /// "Location: [x, y]", to four places. + public static string Location(Vector point) => + string.Format( + "Location: [{0}, {1}]", + point.X.ToString("n4"), + point.Y.ToString("n4")); + + /// "Util: 61.3%", the plate's utilization to one place. + public static string Utilization(double utilization) => + string.Format("Util: {0:P1}", utilization); + + /// Status text for the nest's machine, e.g. "Machine: Generic Laser". + public static string Machine(NestMachine machine) + { + if (machine == null) + return "Machine: (none)"; + return "Machine: " + (string.IsNullOrWhiteSpace(machine.Name) ? "(unnamed)" : machine.Name.Trim()); + } + + /// The material text for (see ). + public static string Material(Nest nest) + { + ArgumentNullException.ThrowIfNull(nest); + return Material(nest.Material?.Name, nest.Material?.Grade, nest.Thickness, nest.Units); + } + + /// + /// Status text for the nest's material, grade and thickness, e.g. "Material: Steel A36 · 0.25 in". + /// + public static string Material(string name, string grade, double thickness, Units units) + { + var parts = new List(); + var description = string.Join(" ", new[] { name?.Trim(), grade?.Trim() } + .Where(s => !string.IsNullOrEmpty(s))); + if (description.Length > 0) + parts.Add(description); + if (thickness > 0) + parts.Add(thickness.ToString("0.####", CultureInfo.CurrentCulture) + " " + UnitsHelper.GetShortString(units)); + + return "Material: " + (parts.Count == 0 ? "(none)" : string.Join(" · ", parts)); + } + + /// The version label: "v" and the version. + public static string Version(string version) => "v" + version; + + /// + /// The informational version of without its "+commit" build + /// metadata, else its version, else "unknown". + /// + public static string DisplayVersion(Assembly assembly) + { + ArgumentNullException.ThrowIfNull(assembly); + var version = assembly.GetCustomAttribute()?.InformationalVersion + ?? assembly.GetName().Version?.ToString() + ?? "unknown"; + var metadata = version.IndexOf('+'); + return metadata < 0 ? version : version.Substring(0, metadata); + } + } +} diff --git a/OpenNest.Desktop/Forms/PlateWorkGuard.cs b/OpenNest.Desktop/Forms/PlateWorkGuard.cs new file mode 100644 index 00000000..756b4707 --- /dev/null +++ b/OpenNest.Desktop/Forms/PlateWorkGuard.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Linq; +using OpenNest.Desktop.Interaction; + +namespace OpenNest.Forms +{ + /// + /// The guard for plate commands (WinForms IsPlateWorkBusy): a running nesting job, or a + /// busy active tool on any view of the nest. The Select tool counts as busy while anything + /// is selected, as the WinForms select action does. + /// + public static class PlateWorkGuard + { + /// What a refused plate command tells the user. + public const string BusyMessage = "Finish or cancel the current nesting or plate action first."; + + /// Whether a plate command must wait: , or a busy tool among . + public static bool IsBusy(bool jobRunning, IEnumerable tools) => + jobRunning || (tools ?? Enumerable.Empty()).Any(tool => tool?.IsBusy == true); + } +} diff --git a/OpenNest.Desktop/MachineSettingsSource.cs b/OpenNest.Desktop/MachineSettingsSource.cs index 7ded1634..6d17a9d5 100644 --- a/OpenNest.Desktop/MachineSettingsSource.cs +++ b/OpenNest.Desktop/MachineSettingsSource.cs @@ -218,6 +218,23 @@ public sealed class MachineSettingsSource nest.SetSupportBed(grid.Enabled ? grid.BedFor(nest.Units) : null); } + /// + /// Nest > Machine: assigns with its support grid + /// (), gives each of (the nest's + /// views) its cut-off defaults and the nest its spacing. Plates' own cutting parameters are + /// kept, and of the sheets only an untouched trailing one takes the spacing. The caller + /// records it as one nest edit. + /// + public void ApplyMachine(Nest nest, MachineConfig machine, PlateManager plates, IEnumerable cutOffSettings) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(plates); + AssignMachine(nest, machine); + foreach (var settings in cutOffSettings ?? Enumerable.Empty()) + ApplyCutOffDefaults(settings, nest); + plates.ChangePlateDefaults(() => MachineCuttingDefaults.ApplySpacingTo(nest, machine)); + } + /// /// The cutting parameters a plate of without its own starts from: /// the last ones applied (or the built-in defaults), with the lead-ins, lead-outs and kerf diff --git a/OpenNest/Forms/MainForm.Guards.cs b/OpenNest/Forms/MainForm.Guards.cs index 19438a40..becf52e6 100644 --- a/OpenNest/Forms/MainForm.Guards.cs +++ b/OpenNest/Forms/MainForm.Guards.cs @@ -34,7 +34,7 @@ namespace OpenNest.Forms { if (!IsPlateWorkBusy(views)) return false; - MessageBox.Show(this, "Finish or cancel the current nesting or plate action first.", + MessageBox.Show(this, PlateWorkGuard.BusyMessage, caption, MessageBoxButtons.OK, MessageBoxIcon.Information); return true; } diff --git a/OpenNest/Forms/MainForm.Nest.cs b/OpenNest/Forms/MainForm.Nest.cs index 6b949819..b06eafc0 100644 --- a/OpenNest/Forms/MainForm.Nest.cs +++ b/OpenNest/Forms/MainForm.Nest.cs @@ -59,25 +59,13 @@ namespace OpenNest.Forms { items.Clear(); var nest = activeForm?.Nest; - if (nest == null) + foreach (var entry in MachineMenu.Items(nest, nest == null ? null : MachineSettings.LoadMachines())) { - items.Add(new ToolStripMenuItem("(no nest open)") { Enabled = false }); - return; - } - - var machines = MachineSettings.LoadMachines() - .OrderBy(m => m.Name, StringComparer.CurrentCultureIgnoreCase) - .ToList(); - foreach (var machine in machines) - { - var item = new ToolStripMenuItem(machine.Name) { Checked = machine.Id == nest.Machine?.Id }; - item.Click += (_, _) => AssignMachine(machine); + var item = new ToolStripMenuItem(entry.Text) { Checked = entry.Checked, Enabled = entry.Enabled }; + if (entry.Machine is { } machine) + item.Click += (_, _) => AssignMachine(machine); items.Add(item); } - if (nest.Machine is { } assigned && machines.All(m => m.Id != assigned.Id)) - items.Add(new ToolStripMenuItem($"{assigned.Name} (not on file)") { Checked = true, Enabled = false }); - if (items.Count == 0) - items.Add(new ToolStripMenuItem("(no machines; see Tools > Machine Configuration)") { Enabled = false }); } // Assigning a machine also puts every sheet on that machine's support grid, gives the @@ -86,7 +74,7 @@ namespace OpenNest.Forms private void AssignMachine(MachineConfig machine) { var editForm = activeForm; - if (editForm == null || editForm.Nest.Machine?.Id == machine.Id) + if (editForm == null || MachineMenu.IsAssigned(editForm.Nest, machine)) return; var nest = editForm.Nest; @@ -96,10 +84,8 @@ namespace OpenNest.Forms editForm.RecordChange("Machine", () => { - MachineSettings.AssignMachine(nest, machine); - foreach (var view in views) - MachineSettings.ApplyCutOffDefaults(view, nest); - editForm.PlateManager.ChangePlateDefaults(() => MachineCuttingDefaults.ApplySpacingTo(nest, machine)); + MachineSettings.Source.ApplyMachine(nest, machine, editForm.PlateManager, + views.Select(view => view.CutOffSettings)); }); foreach (var view in views) view.Invalidate(); diff --git a/OpenNest/Forms/MainStatusBar.cs b/OpenNest/Forms/MainStatusBar.cs index 945479c4..f1e78d2e 100644 --- a/OpenNest/Forms/MainStatusBar.cs +++ b/OpenNest/Forms/MainStatusBar.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.Globalization; using System.Linq; using System.Windows.Forms; using OpenNest.Collections; @@ -203,11 +202,7 @@ namespace OpenNest.Forms return; } - var text = string.Format( - "Location: [{0}, {1}]", - form.PlateView.CurrentPoint.X.ToString("n4"), - form.PlateView.CurrentPoint.Y.ToString("n4") - ); + var text = MainStatusText.Location(form.PlateView.CurrentPoint); if (location.Text != text) location.Text = text; } @@ -226,35 +221,15 @@ namespace OpenNest.Forms machine.Text = FormatMachine(nest.Machine); material.Text = FormatMaterial(nest.Material?.Name, nest.Material?.Grade, nest.Thickness, nest.Units); - plateUtil.Text = string.Format( - "Util: {0:P1}", - form.PlateView.Plate.Utilization() - ); + plateUtil.Text = MainStatusText.Utilization(form.PlateView.Plate.Utilization()); } - /// Status text for the nest's machine, e.g. "Machine: Generic Laser". - internal static string FormatMachine(NestMachine machine) - { - if (machine == null) - return "Machine: (none)"; - return "Machine: " + (string.IsNullOrWhiteSpace(machine.Name) ? "(unnamed)" : machine.Name.Trim()); - } + /// Status text for the nest's machine (see ). + internal static string FormatMachine(NestMachine machine) => MainStatusText.Machine(machine); - /// - /// Status text for the nest's material, grade and thickness, e.g. "Material: Steel A36 · 0.25 in". - /// - internal static string FormatMaterial(string name, string grade, double thickness, Units units) - { - var parts = new List(); - var description = string.Join(" ", new[] { name?.Trim(), grade?.Trim() } - .Where(s => !string.IsNullOrEmpty(s))); - if (description.Length > 0) - parts.Add(description); - if (thickness > 0) - parts.Add(thickness.ToString("0.####", CultureInfo.CurrentCulture) + " " + UnitsHelper.GetShortString(units)); - - return "Material: " + (parts.Count == 0 ? "(none)" : string.Join(" · ", parts)); - } + /// Status text for the nest's material (see ). + internal static string FormatMaterial(string name, string grade, double thickness, Units units) => + MainStatusText.Material(name, grade, thickness, units); public void UpdateSelection() { diff --git a/OpenNest/Forms/UpdaterStatus.cs b/OpenNest/Forms/UpdaterStatus.cs index e8aeb2c8..93aab05c 100644 --- a/OpenNest/Forms/UpdaterStatus.cs +++ b/OpenNest/Forms/UpdaterStatus.cs @@ -36,8 +36,8 @@ namespace OpenNest.Forms statusStrip.Items.Add(new ToolStripStatusLabel { - Text = "v" + CurrentVersion, - ToolTipText = "OpenNest version", + Text = MainStatusText.Version(CurrentVersion), + ToolTipText = MainStatusText.VersionToolTip, ForeColor = SystemColors.GrayText, }); diff --git a/OpenNest/UpdaterService.cs b/OpenNest/UpdaterService.cs index ca6fba55..6a065cfb 100644 --- a/OpenNest/UpdaterService.cs +++ b/OpenNest/UpdaterService.cs @@ -121,15 +121,7 @@ namespace OpenNest } /// The assembly's informational version without the "+commit" build metadata. - public static string DisplayVersion() - { - var assembly = typeof(UpdaterService).Assembly; - var version = assembly.GetCustomAttribute()?.InformationalVersion - ?? assembly.GetName().Version?.ToString() - ?? "unknown"; - var metadata = version.IndexOf('+'); - return metadata < 0 ? version : version.Substring(0, metadata); - } + public static string DisplayVersion() => Forms.MainStatusText.DisplayVersion(typeof(UpdaterService).Assembly); public void Start() { From ac894bbd9db315c8732fad41842e9a67a9acd210 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sun, 29 Nov 2026 20:10:34 -0500 Subject: [PATCH 2/2] feat(avalonia): add the engine list, status bar and Nest > Machine The toolbar's Engine list shows each engine's description beside its name and its tooltip, and saves the choice through EngineSelection. The status bar follows the WinForms strip: the tool's name and hint with the last notice, the location (a click switches between following the mouse and showing left clicks, saved for both apps), the selection, the nest's machine (either button lists the machines to assign), material, plate utilization and the version. Nest > Machine assigns a machine as one undoable step, refused while Auto Nest works on the nest or the plate's tool is busy; Auto Nest is enabled only with a plate to nest on. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Avalonia/DesktopSettings.cs | 17 ++ OpenNest.Avalonia/MainWindow.StatusBar.cs | 307 ++++++++++++++++++++++ OpenNest.Avalonia/MainWindow.axaml | 48 +++- OpenNest.Avalonia/MainWindow.axaml.cs | 36 +-- OpenNest.Avalonia/NestView.axaml.cs | 16 +- 5 files changed, 390 insertions(+), 34 deletions(-) create mode 100644 OpenNest.Avalonia/MainWindow.StatusBar.cs diff --git a/OpenNest.Avalonia/DesktopSettings.cs b/OpenNest.Avalonia/DesktopSettings.cs index f8aa2b99..8b005d16 100644 --- a/OpenNest.Avalonia/DesktopSettings.cs +++ b/OpenNest.Avalonia/DesktopSettings.cs @@ -97,6 +97,23 @@ namespace OpenNest.Avalonia return notices.Count == 0 ? null : string.Join(" ", notices); }); + /// + /// Reads the machines again off the UI thread, as the WinForms machine lists read them + /// each time they open; a failed read keeps the last list. Returns the list. + /// + public static Task> RefreshMachinesAsync() => Task.Run(() => + { + try + { + MachineConfigs = Machines.LoadMachines(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // The list read at startup (or last time) stays. + } + return MachineConfigs; + }); + private static string OneLine(string text) => string.Join(" ", text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); } diff --git a/OpenNest.Avalonia/MainWindow.StatusBar.cs b/OpenNest.Avalonia/MainWindow.StatusBar.cs new file mode 100644 index 00000000..abb7492f --- /dev/null +++ b/OpenNest.Avalonia/MainWindow.StatusBar.cs @@ -0,0 +1,307 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using OpenNest.Avalonia.Controls; +using OpenNest.Data; +using OpenNest.Desktop; +using OpenNest.Forms; +using OpenNest.Geometry; + +namespace OpenNest.Avalonia +{ + /// + /// The toolbar's engine list and the status bar, as the WinForms main window has them: the + /// message (the active tool's name and hint, then the last notice), the cursor location (a + /// click switches between following the mouse and showing the last left click, kept in the + /// user settings both apps share), the selection, the nest's machine (a click or right-click + /// lists the machines to assign, as Nest > Machine does), its material, the plate's + /// utilization and the version. Commands that need a plate, or no running Auto Nest on the + /// nest, are enabled accordingly. + /// + public partial class MainWindow + { + private static readonly IBrush LocationFollowing = Brushes.Black; + private static readonly IBrush LocationOnClick = Brushes.Gray; + + // Each plate view's last shown location, kept while the cursor is elsewhere, as WinForms + // keeps each view's current point. + private readonly ConditionalWeakTable> locations = new(); + private bool locationFollowsMouse = true; + private bool loadingEngines; + // Utilization changes only when parts are added or removed: computed once per plate and count. + private (Plate Plate, int Parts, string Text) utilization; + + private void InitializeStatusBar() + { + locationFollowsMouse = MainStatusText.ReadLocationFollowsMouse( + UserSettingsFile.Read(UserSettingsFile.DefaultPath)); + LocationStatusText.Foreground = locationFollowsMouse ? LocationFollowing : LocationOnClick; + ToolTip.SetTip(MachineStatus, MainStatusText.MachineToolTip); + VersionStatusText.Text = MainStatusText.Version(MainStatusText.DisplayVersion(typeof(MainWindow).Assembly)); + ToolTip.SetTip(VersionStatusText, MainStatusText.VersionToolTip); + InitializeEngineCombo(); + } + + /// + /// Every registered engine, with its description beside its name in the open list (the + /// closed box shows the name alone), selecting the saved engine. + /// + private void InitializeEngineCombo() + { + var names = EngineSelection.UiEngineNames.ToList(); + EngineComboBox.ItemTemplate = new FuncDataTemplate((name, _) => EngineRow(name)); + EngineComboBox.SelectionBoxItemTemplate = new FuncDataTemplate((name, _) => + new TextBlock { Text = name, VerticalAlignment = VerticalAlignment.Center }); + loadingEngines = true; + try + { + EngineComboBox.ItemsSource = names; + EngineComboBox.SelectedItem = names.FirstOrDefault(n => n == EngineSelection.EngineName) + ?? names.FirstOrDefault(n => string.Equals(n, EngineSelection.EngineName, StringComparison.OrdinalIgnoreCase)); + } + finally + { + loadingEngines = false; + } + SetEngineToolTip(EngineSelection.EngineName); + } + + private static Control EngineRow(string name) + { + var row = new Grid { ColumnDefinitions = new ColumnDefinitions("140,Auto") }; + row.Children.Add(new TextBlock { Text = name, VerticalAlignment = VerticalAlignment.Center }); + var description = new TextBlock + { + Text = EngineSelection.Description(name), + Foreground = Brushes.Gray, + MaxWidth = 480, + TextTrimming = TextTrimming.CharacterEllipsis, + VerticalAlignment = VerticalAlignment.Center, + }; + Grid.SetColumn(description, 1); + row.Children.Add(description); + var tip = EngineSelection.ToolTip(name); + if (!string.IsNullOrEmpty(tip)) + ToolTip.SetTip(row, tip); + return row; + } + + private void SetEngineToolTip(string name) + { + var tip = EngineSelection.ToolTip(name); + ToolTip.SetTip(EngineComboBox, string.IsNullOrEmpty(tip) ? null : tip); + } + + // A user's choice is saved for the next launch (engine-selection.json, both apps). + private void OnEngineSelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (loadingEngines || EngineComboBox.SelectedItem is not string name) + return; + EngineSelection.EngineName = name; + SetEngineToolTip(name); + } + + private void WatchLocationClicks(NestView view) + { + var canvas = view.PlateView; + canvas.AddHandler(PointerPressedEvent, (_, e) => + { + if (locationFollowsMouse || !e.GetCurrentPoint(canvas).Properties.IsLeftButtonPressed) + return; + if (canvas.CursorWorld is { } at) + Location(canvas).Value = at; + if (view == ActiveView) + UpdateStatus(); + }, RoutingStrategies.Bubble, handledEventsToo: true); + } + + private StrongBox Location(PlateCanvas canvas) => + locations.GetValue(canvas, _ => new StrongBox(new Vector(0, 0))); + + // A left click switches the location between following the mouse and showing clicks. + private void OnLocationStatusReleased(object sender, PointerReleasedEventArgs e) + { + if (e.InitialPressMouseButton != MouseButton.Left) + return; + locationFollowsMouse = !locationFollowsMouse; + UserSettingsFile.Update(UserSettingsFile.DefaultPath, + settings => MainStatusText.WriteLocationFollowsMouse(settings, locationFollowsMouse)); + LocationStatusText.Foreground = locationFollowsMouse ? LocationFollowing : LocationOnClick; + UpdateStatus(); + } + + private void UpdateStatus() + { + var view = ActiveView; + var canvas = view?.PlateView; + UpdateCommandState(view); + if (view == null) + { + Show(Status, notice ?? "Create a new nest or open a .nest file to begin."); + ToolTip.SetTip(Status, null); + Show(LocationStatusText, ""); + Show(SelectionStatusText, ""); + Show(MachineStatusText, ""); + Show(MaterialStatusText, ""); + Show(UtilizationStatusText, ""); + return; + } + + // The active tool's name and hint first, as the WinForms status label shows them. + var message = canvas.Tools.Status; + if (notice != null) + message += " | " + notice; + Show(Status, message); + ToolTip.SetTip(Status, message); + + var location = Location(canvas); + if (locationFollowsMouse && canvas.CursorWorld is { } at) + location.Value = at; + Show(LocationStatusText, MainStatusText.Location(location.Value)); + + var plate = canvas.Plate; + var selected = plate == null + ? new List() + : canvas.Selection.Parts.Where(plate.Parts.Contains).ToList(); + Show(SelectionStatusText, Desktop.Interaction.SelectionStatus.Text(selected)); + + var nest = view.Tab.Document.Nest; + Show(MachineStatusText, MainStatusText.Machine(nest.Machine)); + Show(MaterialStatusText, MainStatusText.Material(nest)); + Show(UtilizationStatusText, UtilizationText(plate)); + } + + private string UtilizationText(Plate plate) + { + if (plate == null) + return ""; + if (!ReferenceEquals(utilization.Plate, plate) || utilization.Parts != plate.Parts.Count) + utilization = (plate, plate.Parts.Count, MainStatusText.Utilization(plate.Utilization())); + return utilization.Text; + } + + // Sets a label's text; a label with none is hidden with its border. + private static void Show(TextBlock label, string text) + { + if (label.Text != text) + label.Text = text; + if (label.Parent is Border border && border.Classes.Contains("status")) + border.IsVisible = !string.IsNullOrEmpty(text); + } + + /// The status bar's labels, for --snapshot's text file. + private string StatusBarText() => + string.Join(" ", new[] + { + Status, LocationStatusText, SelectionStatusText, MachineStatusText, + MaterialStatusText, UtilizationStatusText, VersionStatusText, + } + .Select(label => label.Text) + .Where(text => !string.IsNullOrEmpty(text))); + + /// + /// As the WinForms toolbar: Auto Nest needs a plate (while it runs it is the Stop + /// command), and the machine cannot change while Auto Nest works on the nest. + /// + private void UpdateCommandState(NestView view) + { + var canNest = nesting != null || view?.PlateView.Plate != null; + AutoNestButton.IsEnabled = canNest; + AutoNestMenuItem.IsEnabled = canNest; + var canAssign = view != null && view.Tab != nestingTab; + NestMachineMenuItem.IsEnabled = canAssign; + MachineStatus.IsEnabled = canAssign; + } + + // Nest > Machine lists the machines each time it opens. + private async void OnNestMachineMenuOpened(object sender, RoutedEventArgs e) + { + if (!ReferenceEquals(e.Source, NestMachineMenuItem)) + return; + var view = ActiveView; + FillMachineItems(NestMachineMenuItem.Items, view, DesktopSettings.MachineConfigs); + // Read again, as the WinForms menu reads them, and shown if the menu is still open. + var machines = await DesktopSettings.RefreshMachinesAsync(); + if (NestMachineMenuItem.IsSubMenuOpen && view == ActiveView) + FillMachineItems(NestMachineMenuItem.Items, view, machines); + } + + // Either button lists the machines above the label, as Nest > Machine does. + private async void OnMachineStatusReleased(object sender, PointerReleasedEventArgs e) + { + var view = ActiveView; + if (view == null || view.Tab == nestingTab + || e.InitialPressMouseButton is not (MouseButton.Left or MouseButton.Right)) + return; + e.Handled = true; + var flyout = new MenuFlyout { Placement = PlacementMode.TopEdgeAlignedLeft }; + FillMachineItems(flyout.Items, view, DesktopSettings.MachineConfigs); + flyout.ShowAt(MachineStatus); + var machines = await DesktopSettings.RefreshMachinesAsync(); + if (flyout.IsOpen && view == ActiveView) + FillMachineItems(flyout.Items, view, machines); + } + + private void FillMachineItems(ItemCollection items, NestView view, IEnumerable machines) + { + items.Clear(); + var nest = view?.Tab.Document.Nest; + foreach (var entry in MachineMenu.Items(nest, nest == null ? null : machines)) + { + var item = new MenuItem + { + // A name's underscores are shown as typed, not taken as access keys. + Header = entry.Text.Replace("_", "__"), + ToggleType = MenuItemToggleType.CheckBox, + IsChecked = entry.Checked, + IsEnabled = entry.Enabled, + }; + if (entry.Machine is { } machine) + item.Click += (_, _) => AssignMachine(view, machine); + items.Add(item); + } + } + + /// + /// Assigns to the view's nest as one "Machine" step, as the + /// WinForms Nest > Machine does: its support grid on every sheet, its cut-off settings + /// for the view and its spacing for the nest's defaults and untouched trailing sheet. + /// Refused while Auto Nest works on the nest or the plate's tool is busy. + /// + private async void AssignMachine(NestView view, MachineConfig machine) + { + var tab = view.Tab; + if (!tabs.Tabs.Contains(tab) || MachineMenu.IsAssigned(tab.Document.Nest, machine)) + return; + if (PlateWorkGuard.IsBusy(tab == nestingTab, new[] { view.PlateView.Tools.Current })) + { + await ConfirmDialog.ShowAsync(this, "Machine", PlateWorkGuard.BusyMessage); + return; + } + + var nest = tab.Document.Nest; + try + { + using var change = tab.Undo.BeginChange("Machine"); + change.MarkChanged(); + DesktopSettings.Machines.ApplyMachine(nest, machine, view.Plates, new[] { view.PlateView.CutOffSettings }); + change.Complete(); + } + catch (Exception ex) + { + // The step rolled the nest back to its last recorded state. + ShowNotice($"Could not assign the machine {machine.Name}: {ex.Message}"); + } + // The sheets' support grid and spacing may have changed. + view.RefreshInPlace(); + UpdateStatus(); + } + } +} diff --git a/OpenNest.Avalonia/MainWindow.axaml b/OpenNest.Avalonia/MainWindow.axaml index d70d4cb0..658893b2 100644 --- a/OpenNest.Avalonia/MainWindow.axaml +++ b/OpenNest.Avalonia/MainWindow.axaml @@ -35,6 +35,10 @@ + + + + @@ -78,12 +82,52 @@