From 4e831ab6f8daadb4f67e314b82dfaf3e716ed11c Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sun, 29 Nov 2026 20:11:38 -0500 Subject: [PATCH] feat(desktop): share the plate list and plate commands PlateCommands ports the WinForms nest window's plate commands, each one undo step under its WinForms label: Remove Plate, Remove Empty Plates, Duplicate Plate (the copy current, with its own cutting parameters), Move Plate and its Alt+Up/Alt+Down target, Rotate Plate (90 degrees either way or 180), Resize Plate to its parts by the auto-size factor, Set Nest Default Plate, and Edit Plate's commit, where an empty plate's new settings become the nest's defaults and the nested quantities are counted again. NewNestDefaults is what Set as Default saves for new nests: the plate, the saved common-line usage and the nest's machine. PlateEditValues is what Edit Plate edits (quantity, size, part and edge spacing, quadrant, outline), when Done applies and how it writes the plate; SheetOutlineImport reads an outline from a CAD file, and SvgScale holds the scale prompt for an SVG that does not state its size. PlateListRow is the Plates list's row text and its drag drop slots; QuadrantPick the quadrant picker's hit test and cells. The WinForms nest window, plate list, Edit Plate dialog, quadrant picker, SVG scale prompt and Save Current as Defaults delegate to them with unchanged behavior. Co-Authored-By: Claude Opus 5.5 --- .../Plates/PlateCommandsTests.cs | 293 ++++++++++++++++++ .../Plates/PlateEditValuesTests.cs | 101 ++++++ .../Plates/PlateListRowTests.cs | 64 ++++ .../Plates/QuadrantPickTests.cs | 28 ++ .../Plates/SheetOutlineImportTests.cs | 71 +++++ OpenNest.Desktop/PlateCommands.cs | 232 ++++++++++++++ OpenNest.Desktop/PlateEditValues.cs | 114 +++++++ OpenNest.Desktop/PlateListRow.cs | 56 ++++ OpenNest.Desktop/QuadrantPick.cs | 37 +++ OpenNest.Desktop/SheetOutlineImport.cs | 87 ++++++ OpenNest/Controls/PlateListBox.cs | 19 +- OpenNest/Controls/QuadrantSelect.cs | 13 +- OpenNest/Forms/EditNestForm.PlateOrder.cs | 27 +- OpenNest/Forms/EditNestForm.cs | 34 +- OpenNest/Forms/EditPlateForm.cs | 93 ++---- OpenNest/Forms/MainForm.Tools.cs | 4 +- OpenNest/Forms/SvgScaleForm.cs | 9 +- 17 files changed, 1146 insertions(+), 136 deletions(-) create mode 100644 OpenNest.Desktop.Tests/Plates/PlateCommandsTests.cs create mode 100644 OpenNest.Desktop.Tests/Plates/PlateEditValuesTests.cs create mode 100644 OpenNest.Desktop.Tests/Plates/PlateListRowTests.cs create mode 100644 OpenNest.Desktop.Tests/Plates/QuadrantPickTests.cs create mode 100644 OpenNest.Desktop.Tests/Plates/SheetOutlineImportTests.cs create mode 100644 OpenNest.Desktop/PlateCommands.cs create mode 100644 OpenNest.Desktop/PlateEditValues.cs create mode 100644 OpenNest.Desktop/PlateListRow.cs create mode 100644 OpenNest.Desktop/QuadrantPick.cs create mode 100644 OpenNest.Desktop/SheetOutlineImport.cs diff --git a/OpenNest.Desktop.Tests/Plates/PlateCommandsTests.cs b/OpenNest.Desktop.Tests/Plates/PlateCommandsTests.cs new file mode 100644 index 00000000..a0c8fb92 --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/PlateCommandsTests.cs @@ -0,0 +1,293 @@ +using OpenNest.CNC; +using OpenNest.CommonLines; +using OpenNest.Data; +using OpenNest.Geometry; +using OpenNest.Undo; + +namespace OpenNest.Desktop.Tests.Plates; + +public class PlateCommandsTests +{ + /// + /// A nest window's state: three plates with one part each, then the trailing empty plate the + /// manager keeps, and a history started on it. + /// + private sealed class Env + { + public Env(int platesWithParts = 3) + { + var nest = TestNests.OneSquare(); + nest.PlateDefaults.Size = new Size(48, 96); + var drawing = nest.Drawings.First(); + if (platesWithParts == 0) + nest.Plates.Clear(); + else + nest.Plates[0].Quantity = 1; + for (var i = 1; i < platesWithParts; i++) + { + var plate = new Plate(new Size(48 + i, 96 + i)) { Quantity = 1 }; + plate.Parts.Add(new Part(drawing)); + nest.Plates.Add(plate); + } + nest.UpdateDrawingQuantities(); + Document = new Document { Nest = nest }; + Plates = new PlateManager(nest); + Plates.EnsureSentinel(); + Undo = new NestUndoRecorder(Document); + Undo.Reset(); + } + + public Document Document { get; } + public Nest Nest => Document.Nest; + public PlateManager Plates { get; } + public NestUndoRecorder Undo { get; } + + public ChangeScope BeginChange(string label) => Undo.BeginChange(label); + + public int Steps => Undo.History.UndoCount; + + public IReadOnlyList Lengths => Nest.Plates.Select(p => p.Size.Length).ToList(); + } + + private static Part Square(Drawing drawing, double x, double y) => new(drawing, new Vector(x, y)); + + [Fact] + public void RemoveCurrentPlate_IsOneRemovePlateStep_AndUndoes() + { + var env = new Env(); + env.Plates.LoadAt(1); + + PlateCommands.RemoveCurrentPlate(env.Plates, env.BeginChange); + + Assert.Equal([96, 98], env.Lengths.Take(2)); + Assert.Equal(3, env.Nest.Plates.Count); + Assert.Equal("Undo Remove Plate", env.Undo.UndoText); + env.Undo.Undo(); + Assert.Equal([96, 97, 98, 96], env.Lengths); + } + + [Fact] + public void RemoveCurrentPlate_WithOnePlate_RecordsNothing() + { + var env = new Env(platesWithParts: 0); + Assert.Single(env.Nest.Plates); + + PlateCommands.RemoveCurrentPlate(env.Plates, env.BeginChange); + + Assert.Single(env.Nest.Plates); + Assert.False(env.Undo.CanUndo); + } + + [Fact] + public void RemoveEmptyPlates_RemovesEmptyPlatesButKeepsTheTrailingOne() + { + var env = new Env(); + env.Nest.Plates[1].Parts.Clear(); + env.Undo.Reset(); + Assert.True(PlateCommands.HasEmptyPlatesToRemove(env.Nest)); + + PlateCommands.RemoveEmptyPlates(env.Nest, env.BeginChange); + + Assert.Equal([96, 98, 96], env.Lengths); + Assert.Empty(env.Nest.Plates[^1].Parts); + Assert.Equal("Undo Remove Empty Plates", env.Undo.UndoText); + Assert.False(PlateCommands.HasEmptyPlatesToRemove(env.Nest)); + } + + [Fact] + public void RemoveEmptyPlates_WithNoneToRemove_RecordsNothing() + { + var env = new Env(); + + PlateCommands.RemoveEmptyPlates(env.Nest, env.BeginChange); + + Assert.Equal(4, env.Nest.Plates.Count); + Assert.False(env.Undo.CanUndo); + } + + [Fact] + public void DuplicatePlate_InsertsACopyThatBecomesCurrent_WithItsOwnCuttingParameters() + { + var env = new Env(); + var source = env.Nest.Plates[0]; + source.CuttingParameters = new CNC.CuttingStrategy.CuttingParameters(); + env.Undo.Reset(); + + var copy = PlateCommands.DuplicatePlate(env.Plates, 0, 1, env.BeginChange); + + Assert.NotNull(copy); + Assert.Same(copy, env.Nest.Plates[1]); + Assert.Equal(1, env.Plates.CurrentIndex); + Assert.Equal(source.Parts.Count, copy.Parts.Count); + Assert.NotSame(source.CuttingParameters, copy.CuttingParameters); + Assert.Equal(5, env.Nest.Plates.Count); + Assert.Equal(1, env.Steps); + Assert.Equal("Undo Duplicate Plate", env.Undo.UndoText); + } + + [Fact] + public void DuplicatePlate_OfTheTrailingEmptyPlate_IsRefused() + { + var env = new Env(); + + Assert.Null(PlateCommands.DuplicatePlate(env.Plates, 3, 0, env.BeginChange)); + Assert.False(env.Undo.CanUndo); + } + + [Fact] + public void MovePlate_ReordersAsOneStep_KeepingItCurrent() + { + var env = new Env(); + env.Plates.LoadAt(2); + + Assert.True(PlateCommands.MovePlate(env.Plates, 2, 0, env.BeginChange)); + + Assert.Equal([98, 96, 97, 96], env.Lengths); + Assert.Equal(0, env.Plates.CurrentIndex); + Assert.Equal("Undo Move Plate", env.Undo.UndoText); + env.Undo.Undo(); + Assert.Equal([96, 97, 98, 96], env.Lengths); + } + + [Theory] + [InlineData(1, 1)] + [InlineData(0, 3)] + [InlineData(3, 0)] + [InlineData(-1, 0)] + public void MovePlate_ThatChangesNothingOrPassesTheTrailingPlate_IsRefused(int from, int to) + { + var env = new Env(); + + Assert.False(PlateCommands.MovePlate(env.Plates, from, to, env.BeginChange)); + Assert.False(env.Undo.CanUndo); + } + + [Theory] + [InlineData(2, true, 1)] + [InlineData(2, false, 3)] + public void StepTarget_IsOnePlaceUpOrDown(int current, bool up, int expected) => + Assert.Equal(expected, PlateCommands.StepTarget(current, up)); + + [Theory] + [InlineData(PlateRotation.Clockwise)] + [InlineData(PlateRotation.CounterClockwise)] + public void Rotate_AQuarterTurn_SwapsTheSheetsSides(PlateRotation rotation) + { + var env = new Env(); + var plate = env.Nest.Plates[0]; + + PlateCommands.Rotate(plate, rotation, env.BeginChange); + + Assert.Equal(new Size(96, 48), plate.Size); + Assert.Equal("Undo Rotate Plate", env.Undo.UndoText); + env.Undo.Undo(); + Assert.Equal(new Size(48, 96), env.Nest.Plates[0].Size); + } + + [Fact] + public void Rotate_HalfTurn_KeepsTheSizeAndMovesTheParts() + { + var env = new Env(); + var plate = env.Nest.Plates[0]; + var before = plate.Parts[0].BoundingBox.Center; + + PlateCommands.Rotate(plate, PlateRotation.HalfTurn, env.BeginChange); + + Assert.Equal(new Size(48, 96), plate.Size); + Assert.NotEqual(before, plate.Parts[0].BoundingBox.Center); + Assert.Equal("Undo Rotate Plate", env.Undo.UndoText); + } + + [Fact] + public void ResizeToFit_ShrinksThePlateToItsPartsRoundedUp() + { + var env = new Env(); + var plate = env.Nest.Plates[0]; + plate.Parts.Add(Square(env.Nest.Drawings.First(), 20, 30)); + + PlateCommands.ResizeToFit(plate, 4, env.BeginChange); + + Assert.True(plate.Size.Length < 96); + Assert.Equal(0, plate.Size.Length % 4, 6); + Assert.Equal(0, plate.Size.Width % 4, 6); + Assert.Equal("Undo Resize Plate", env.Undo.UndoText); + } + + [Fact] + public void SetAsNestDefault_MakesThePlateTheNestDefault_AndTheTrailingPlateFollows() + { + var env = new Env(); + var plate = env.Nest.Plates[1]; + plate.PartSpacing = 0.375; + env.Undo.Reset(); + + PlateCommands.SetAsNestDefault(env.Nest, env.Plates, plate, env.BeginChange); + + Assert.Equal(plate.Size, env.Nest.PlateDefaults.Size); + Assert.Equal(0.375, env.Nest.PlateDefaults.PartSpacing); + Assert.Equal(plate.Size, env.Nest.Plates[^1].Size); + Assert.Equal("Undo Set Nest Default Plate", env.Undo.UndoText); + } + + [Fact] + public void NewNestDefaults_TakeThePlateTheSavedCommonLineUsageAndTheNestsMachine() + { + var nest = TestNests.OneSquare(); + nest.Units = Units.Millimeters; + var machine = Guid.NewGuid(); + nest.Machine = new NestMachine(machine, "Laser"); + var plate = nest.Plates[0]; + plate.Quadrant = 3; + var saved = new NestDefaults { CommonLineUsage = CommonLineUsage.Whenever, MachineId = Guid.NewGuid() }; + + var defaults = PlateCommands.NewNestDefaults(nest, plate, saved); + + Assert.Equal(Units.Millimeters, defaults.Units); + Assert.Equal(plate.Size, defaults.Size); + Assert.Equal(3, defaults.Quadrant); + Assert.Equal(CommonLineUsage.Whenever, defaults.CommonLineUsage); + Assert.Equal(machine, defaults.MachineId); + + nest.Machine = null; + Assert.Equal(saved.MachineId, PlateCommands.NewNestDefaults(nest, plate, saved).MachineId); + } + + [Fact] + public void EditPlate_WritesTheValuesAsOneStep_AndCountsQuantitiesAgain() + { + var env = new Env(); + var plate = env.Nest.Plates[0]; + var values = PlateEditValues.FromPlate(plate) with { Quantity = 3, PartSpacing = 0.5 }; + + PlateCommands.EditPlate(env.Nest, env.Plates, plate, values, env.BeginChange); + + Assert.Equal(3, plate.Quantity); + Assert.Equal(0.5, plate.PartSpacing); + // Three sheets of plate 1 and one each of plates 2 and 3. + Assert.Equal(5, env.Nest.Drawings.First().Quantity.Nested); + Assert.Equal("Undo Edit Plate", env.Undo.UndoText); + } + + [Fact] + public void EditPlate_Cancelled_RecordsNothing() + { + var env = new Env(); + + PlateCommands.EditPlate(env.Nest, env.Plates, env.Nest.Plates[0], null, env.BeginChange); + + Assert.False(env.Undo.CanUndo); + } + + [Fact] + public void EditPlate_OfAnEmptyPlate_MakesItsSettingsTheNestDefaults() + { + var env = new Env(); + var trailing = env.Nest.Plates[^1]; + var values = PlateEditValues.FromPlate(trailing) with { Size = new Size(60, 120), Quadrant = 2 }; + + PlateCommands.EditPlate(env.Nest, env.Plates, trailing, values, env.BeginChange); + + Assert.Equal(new Size(60, 120), env.Nest.PlateDefaults.Size); + Assert.Equal(2, env.Nest.PlateDefaults.Quadrant); + } +} diff --git a/OpenNest.Desktop.Tests/Plates/PlateEditValuesTests.cs b/OpenNest.Desktop.Tests/Plates/PlateEditValuesTests.cs new file mode 100644 index 00000000..99a93e97 --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/PlateEditValuesTests.cs @@ -0,0 +1,101 @@ +using OpenNest.Geometry; + +namespace OpenNest.Desktop.Tests.Plates; + +public class PlateEditValuesTests +{ + private static SheetOutline Ell() => new(new[] + { + new Vector(0, 0), new Vector(96, 0), new Vector(96, 24), new Vector(48, 24), new Vector(48, 48), new Vector(0, 48), + }); + + [Fact] + public void FromPlate_ReadsEveryValue_AndApplyToWritesThemBack() + { + var plate = new Plate(new Size(48, 96)) { Quantity = 4, PartSpacing = 0.25, Quadrant = 3 }; + plate.EdgeSpacing.Left = 1; + plate.EdgeSpacing.Top = 2; + plate.EdgeSpacing.Right = 3; + plate.EdgeSpacing.Bottom = 4; + + var values = PlateEditValues.FromPlate(plate); + Assert.Equal(new Size(48, 96), values.Size); + Assert.Equal(4, values.Quantity); + Assert.Equal(0.25, values.PartSpacing); + Assert.Equal(3, values.Quadrant); + Assert.Equal((1, 2, 3, 4), (values.LeftSpacing, values.TopSpacing, values.RightSpacing, values.BottomSpacing)); + Assert.Null(values.Outline); + + var other = new Plate(new Size(10, 10)); + values.ApplyTo(other); + Assert.Equal(PlateEditValues.FromPlate(plate), PlateEditValues.FromPlate(other)); + } + + [Theory] + [InlineData(1, 1, 1, 1, true)] + [InlineData(48, 48, 1, 1, false)] // left + right reach the length + [InlineData(1, 1, 24, 24, false)] // top + bottom reach the width + public void CanApply_NeedsRoomOnTheSheetBothWays(double left, double right, double top, double bottom, bool expected) + { + var values = new PlateEditValues + { + Size = new Size(48, 96), + LeftSpacing = left, + RightSpacing = right, + TopSpacing = top, + BottomSpacing = bottom, + }; + + Assert.Equal(expected, values.CanApply); + } + + [Fact] + public void CanApplyWithSize_NeedsASizeThatParses() + { + var values = new PlateEditValues(); + + Assert.True(values.CanApplyWithSize("48 x 96", out var size)); + Assert.Equal(new Size(48, 96), size); + Assert.False(values.CanApplyWithSize("48 by", out _)); + Assert.False(values.CanApplyWithSize("0 x 0", out _)); + } + + [Fact] + public void AnOutline_SetsTheSize_AndApplyKeepsIt() + { + var plate = new Plate(new Size(60, 120)); + var values = PlateEditValues.FromPlate(plate).WithOutline(Ell()); + + Assert.Equal(new Size(48, 96), values.Size); + values.ApplyTo(plate); + + Assert.Equal(Ell(), plate.Outline); + Assert.Equal(new Size(48, 96), plate.Size); + } + + [Fact] + public void ClearingTheOutline_LeavesARectangleOfTheSameSize() + { + var plate = new Plate { Outline = Ell(), Quadrant = 2 }; + var values = PlateEditValues.FromPlate(plate).WithOutline(null); + + values.ApplyTo(plate); + + Assert.Null(plate.Outline); + Assert.Equal(new Size(48, 96), plate.Size); + Assert.Equal(2, plate.Quadrant); + } + + [Fact] + public void OutlineText_DescribesTheSheet() + { + Assert.Equal("Rectangular sheet", PlateEditValues.OutlineText(null)); + Assert.Equal("6 vertices", PlateEditValues.OutlineText(Ell())); + } + + [Theory] + [InlineData(Units.Inches, 0.25)] + [InlineData(Units.Millimeters, 1)] + public void SpacingIncrement_IsAQuarterInchOrAMillimeter(Units units, double expected) => + Assert.Equal(expected, PlateEditValues.SpacingIncrement(units)); +} diff --git a/OpenNest.Desktop.Tests/Plates/PlateListRowTests.cs b/OpenNest.Desktop.Tests/Plates/PlateListRowTests.cs new file mode 100644 index 00000000..48eee7b8 --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/PlateListRowTests.cs @@ -0,0 +1,64 @@ +using OpenNest.Geometry; + +namespace OpenNest.Desktop.Tests.Plates; + +public class PlateListRowTests +{ + [Fact] + public void APlateWithParts_ShowsItsNumberSizePartsAndUtilization() + { + var nest = TestNests.OneSquare(); + nest.Plates[0].Quantity = 3; + nest.Plates.Add(new Plate(new Size(48, 96))); + + var rows = PlateListRow.For(nest.Plates); + + Assert.Equal("Plate 1", rows[0].Name); + Assert.Equal(nest.Plates[0].Size.ToString(4), rows[0].Size); + Assert.Equal("1 part", rows[0].Parts); + Assert.Equal($"{nest.Plates[0].Utilization():P0} utilized", rows[0].Utilization); + Assert.Equal("×3", rows[0].Quantity); + } + + [Fact] + public void TheTrailingEmptyPlate_IsTheNewPlate() + { + var nest = TestNests.OneSquare(); + nest.Plates.Add(new Plate(new Size(48, 96))); + + var row = PlateListRow.For(nest.Plates, 1); + + Assert.Equal("New plate", row.Name); + Assert.Equal("Empty", row.Parts); + Assert.Equal("", row.Utilization); + Assert.Equal("", row.Quantity); + } + + [Fact] + public void AnEmptyPlateBeforeTheEnd_IsNumbered() + { + var nest = TestNests.OneSquare(); + nest.Plates.Insert(0, new Plate(new Size(48, 96))); + + var row = PlateListRow.For(nest.Plates, 0); + + Assert.Equal("Plate 1", row.Name); + Assert.Equal("0 parts", row.Parts); + } + + [Theory] + [InlineData(0, true, 3, 0)] + [InlineData(0, false, 3, 1)] + [InlineData(2, false, 3, 3)] + [InlineData(3, true, 3, 3)] // the new-plate row + [InlineData(-1, false, 3, 3)] // below the rows + public void DropSlot_IsBeforeOrAfterTheRowUnderThePointer(int row, bool upper, int movable, int expected) => + Assert.Equal(expected, PlateListRow.DropSlot(row, upper, movable)); + + [Theory] + [InlineData(0, 3, 2)] + [InlineData(2, 0, 0)] + [InlineData(1, 1, 1)] + public void DropTarget_AccountsForTheDraggedPlatesOwnPlace(int from, int slot, int expected) => + Assert.Equal(expected, PlateListRow.DropTarget(from, slot)); +} diff --git a/OpenNest.Desktop.Tests/Plates/QuadrantPickTests.cs b/OpenNest.Desktop.Tests/Plates/QuadrantPickTests.cs new file mode 100644 index 00000000..946bfbcf --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/QuadrantPickTests.cs @@ -0,0 +1,28 @@ +namespace OpenNest.Desktop.Tests.Plates; + +public class QuadrantPickTests +{ + [Theory] + [InlineData(150, 20, 1)] + [InlineData(20, 20, 2)] + [InlineData(20, 150, 3)] + [InlineData(150, 150, 4)] + public void At_NumbersTheQuadrantsAsOnAGraph(double x, double y, int expected) => + Assert.Equal(expected, QuadrantPick.At(x, y, 200, 200)); + + [Theory] + [InlineData(0, 1)] + [InlineData(5, 1)] + [InlineData(3, 3)] + public void Normalize_KeepsOneToFour(int value, int expected) => + Assert.Equal(expected, QuadrantPick.Normalize(value)); + + [Fact] + public void Cell_IsTheQuadrantsQuarter() + { + Assert.Equal((100.0, 0.0, 100.0, 50.0), QuadrantPick.Cell(1, 200, 100)); + Assert.Equal((0.0, 0.0, 100.0, 50.0), QuadrantPick.Cell(2, 200, 100)); + Assert.Equal((0.0, 50.0, 100.0, 50.0), QuadrantPick.Cell(3, 200, 100)); + Assert.Equal((100.0, 50.0, 100.0, 50.0), QuadrantPick.Cell(4, 200, 100)); + } +} diff --git a/OpenNest.Desktop.Tests/Plates/SheetOutlineImportTests.cs b/OpenNest.Desktop.Tests/Plates/SheetOutlineImportTests.cs new file mode 100644 index 00000000..ae2b309b --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/SheetOutlineImportTests.cs @@ -0,0 +1,71 @@ +namespace OpenNest.Desktop.Tests.Plates; + +public sealed class SheetOutlineImportTests : IDisposable +{ + private readonly string directory = Path.Combine(Path.GetTempPath(), "opennest-outline-" + Guid.NewGuid().ToString("N")); + + public SheetOutlineImportTests() => Directory.CreateDirectory(directory); + + public void Dispose() => Directory.Delete(directory, recursive: true); + + private string Write(string name, string svg) + { + var path = Path.Combine(directory, name); + File.WriteAllText(path, svg); + return path; + } + + // A 96 x 48 sheet with a 10 x 10 hole. + private const string Body = + ""; + + [Fact] + public void Read_TakesTheLargestContourAsTheSheetAndTheOthersAsObstacles() + { + var path = Write("sheet.svg", + $"{Body}"); + + Assert.Null(SvgScale.SizeToAsk(path)); + var outline = SheetOutlineImport.Read(path, Units.Inches); + + Assert.Equal(96, outline.Size.Length, 3); + Assert.Equal(48, outline.Size.Width, 3); + Assert.Single(outline.Obstacles); + } + + [Fact] + public void AnSvgWithoutAStatedSize_AsksForItsScale() + { + var path = Write("bare.svg", $"{Body}"); + + var size = SvgScale.SizeToAsk(path); + + Assert.NotNull(size); + var outline = SheetOutlineImport.Read(path, Units.Inches, svgUserUnitsPerInch: 1); + Assert.Equal(96, outline.Size.Length, 3); + } + + [Fact] + public void AFileWithNoClosedContour_IsAReadFailure() + { + var path = Write("line.svg", + ""); + + var error = Record.Exception(() => SheetOutlineImport.Read(path, Units.Inches)); + + Assert.NotNull(error); + Assert.True(SheetOutlineImport.IsReadFailure(error)); + Assert.StartsWith("The file does not hold a sheet outline: ", SheetOutlineImport.FailureText(error)); + } + + [Fact] + public void ADxfIsNeverAskedForAScale() => + Assert.Null(SvgScale.SizeToAsk(Path.Combine(directory, "sheet.dxf"))); + + [Fact] + public void ImportedSizeText_ShowsTheSizeInTheNestsUnits() + { + Assert.Equal("Imported size: 1.000 x 0.500 in", SvgScale.ImportedSizeText(96, 48, 96, Units.Inches)); + Assert.Equal("Imported size: 25.4 x 12.7 mm", SvgScale.ImportedSizeText(96, 48, 96, Units.Millimeters)); + } +} diff --git a/OpenNest.Desktop/PlateCommands.cs b/OpenNest.Desktop/PlateCommands.cs new file mode 100644 index 00000000..05db9624 --- /dev/null +++ b/OpenNest.Desktop/PlateCommands.cs @@ -0,0 +1,232 @@ +using System; +using System.Linq; +using OpenNest.Collections; +using OpenNest.Data; +using OpenNest.IO; +using OpenNest.Undo; + +namespace OpenNest.Desktop; + +/// +/// The nest window's plate commands, toolkit-neutral: the Plates list's Remove, Duplicate and +/// Move, Nest > Remove Empty Plates and the Plate menu's Set as Default, Rotate, Resize to +/// Fit and Edit. Each one is one undo step under the WinForms label, opened with +/// (the window's BeginChange). The plate manager keeps the +/// trailing empty plate inside the step and says which plate is current afterwards. +/// +public static class PlateCommands +{ + /// + /// Removes the current plate as one "Remove Plate" step. With fewer than two plates nothing + /// is removed and nothing is recorded; the empty plate removed from the end comes back. + /// + public static void RemoveCurrentPlate(PlateManager plates, Func beginChange) + { + ArgumentNullException.ThrowIfNull(plates); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange("Remove Plate"); + if (plates.Count >= 2) + change.MarkChanged(); + plates.RemoveCurrent(); + change.Complete(); + } + + /// + /// Whether would remove a plate: an empty one before the + /// trailing empty plate, which comes back as the new-plate sentinel. + /// + public static bool HasEmptyPlatesToRemove(Nest nest) + { + ArgumentNullException.ThrowIfNull(nest); + return nest.Plates.Count >= 2 && nest.Plates.SkipLast(1).Any(plate => plate.Parts.Count == 0); + } + + /// Nest > Remove Empty Plates, as one "Remove Empty Plates" step. + public static void RemoveEmptyPlates(Nest nest, Func beginChange) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange("Remove Empty Plates"); + if (HasEmptyPlatesToRemove(nest)) + change.MarkChanged(); + nest.Plates.RemoveEmptyPlates(); + change.Complete(); + } + + /// + /// Inserts a copy of the plate at so it lands at + /// , as one "Duplicate Plate" step; the copy becomes the current + /// plate and gets its own cutting parameters, so editing one sheet's leaves the other's alone. + /// + /// The copy, or null when the plate cannot be copied there (nothing is recorded). + public static Plate DuplicatePlate( + PlateManager plates, int fromIndex, int toIndex, Func beginChange) + { + ArgumentNullException.ThrowIfNull(plates); + ArgumentNullException.ThrowIfNull(beginChange); + if (!plates.CanDuplicatePlate(fromIndex, toIndex)) + return null; + + using var change = beginChange("Duplicate Plate"); + change.MarkChanged(); + var copy = plates.DuplicatePlate(fromIndex, toIndex); + if (copy.CuttingParameters != null) + copy.CuttingParameters = CuttingParametersSerializer.FromDto( + CuttingParametersSerializer.ToDto(copy.CuttingParameters)); + change.Complete(); + return copy; + } + + /// + /// Moves the plate at to as one + /// "Move Plate" step, keeping it the current plate. + /// + /// Whether the order changed; when it would not, nothing is recorded. + public static bool MovePlate( + PlateManager plates, int fromIndex, int toIndex, Func beginChange) + { + ArgumentNullException.ThrowIfNull(plates); + ArgumentNullException.ThrowIfNull(beginChange); + if (!plates.CanMovePlate(fromIndex, toIndex)) + return false; + + using var change = beginChange("Move Plate"); + change.MarkChanged(); + plates.MovePlate(fromIndex, toIndex); + change.Complete(); + return true; + } + + /// + /// The plate Alt+Up () or Alt+Down moves the current plate to: one + /// place earlier or later. + /// + public static int StepTarget(int currentIndex, bool up) => up ? currentIndex - 1 : currentIndex + 1; + + /// + /// Plate > Rotate: the plate and its parts turned a quarter turn either way or a half + /// turn, keeping the quadrant, as one "Rotate Plate" step. + /// + public static void Rotate(Plate plate, PlateRotation rotation, Func beginChange) + { + ArgumentNullException.ThrowIfNull(plate); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange("Rotate Plate"); + change.MarkChanged(); + switch (rotation) + { + case PlateRotation.Clockwise: + plate.Rotate90(RotationType.CW); + break; + case PlateRotation.CounterClockwise: + plate.Rotate90(RotationType.CCW); + break; + case PlateRotation.HalfTurn: + plate.Rotate180(); + break; + default: + throw new ArgumentOutOfRangeException(nameof(rotation)); + } + change.Complete(); + } + + /// + /// Plate > Resize to Fit: the plate shrunk to its parts, rounded up to + /// (Tools > Options' auto-size factor), as one + /// "Resize Plate" step. + /// + public static void ResizeToFit(Plate plate, double roundingFactor, Func beginChange) + { + ArgumentNullException.ThrowIfNull(plate); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange("Resize Plate"); + change.MarkChanged(); + plate.AutoSize(roundingFactor); + change.Complete(); + } + + /// + /// Plate > Set as Default, the nest's part: 's size, quadrant and + /// spacing become the nest's plate defaults, saved with the nest, as one "Set Nest Default + /// Plate" step. The trailing empty plate follows them while untouched. The front end then + /// saves the plate as the defaults new nests start from (). + /// + public static void SetAsNestDefault( + Nest nest, PlateManager plates, Plate plate, Func beginChange) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(plates); + ArgumentNullException.ThrowIfNull(plate); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange("Set Nest Default Plate"); + change.MarkChanged(); + plates.ChangePlateDefaults(() => nest.PlateDefaults.SetFromExisting(plate)); + change.Complete(); + } + + /// + /// The defaults new nests start from after Plate > Set as Default (or Tools > Save + /// Current as Defaults): the plate's size, quadrant and spacing in the nest's units, the + /// saved common-line usage (a plate holds none), and the nest's machine, or the saved choice + /// for a nest without one. + /// + public static NestDefaults NewNestDefaults(Nest nest, Plate plate, NestDefaults saved) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(plate); + ArgumentNullException.ThrowIfNull(saved); + var defaults = NestDefaults.FromPlate(nest.Units, plate, saved); + defaults.MachineId = nest.Machine?.Id ?? saved.MachineId; + return defaults; + } + + /// + /// Plate > Edit's commit: written to the plate as one "Edit + /// Plate" step (null, a cancelled dialog, records nothing). An empty plate's new settings + /// become the nest's plate defaults (), and the drawings' + /// nested quantities are counted again, the plate's quantity being one of their factors. + /// + public static void EditPlate( + Nest nest, PlateManager plates, Plate plate, PlateEditValues settings, Func beginChange) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(plates); + ArgumentNullException.ThrowIfNull(plate); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange("Edit Plate"); + if (settings != null) + { + change.MarkChanged(); + settings.ApplyTo(plate); + FollowEditedPlate(nest, plates, plate); + } + nest.UpdateDrawingQuantities(); + change.Complete(); + } + + /// + /// After Edit Plate wrote : an empty plate's settings become the + /// nest's plate defaults, the trailing empty plate following them while untouched. + /// + public static void FollowEditedPlate(Nest nest, PlateManager plates, Plate plate) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(plates); + ArgumentNullException.ThrowIfNull(plate); + if (plate.Parts.Count == 0) + plates.ChangePlateDefaults(() => nest.PlateDefaults.SetFromExisting(plate)); + } +} + +/// The turns of Plate > Rotate. +public enum PlateRotation +{ + /// 90° CW. + Clockwise, + + /// 90° CCW. + CounterClockwise, + + /// 180°. + HalfTurn, +} diff --git a/OpenNest.Desktop/PlateEditValues.cs b/OpenNest.Desktop/PlateEditValues.cs new file mode 100644 index 00000000..2813162c --- /dev/null +++ b/OpenNest.Desktop/PlateEditValues.cs @@ -0,0 +1,114 @@ +using System; +using OpenNest.Geometry; + +namespace OpenNest.Desktop; + +/// +/// What the Edit Plate dialog edits: quantity, size, part and edge spacing, quadrant and the +/// sheet outline. reads a plate, is when the +/// dialog's Done button is enabled and writes the plate as Done does. +/// +public sealed record PlateEditValues +{ + /// The range of the dialog's quantity and spacing boxes (the WinForms box defaults). + public const double BoxMinimum = 0; + + public const double BoxMaximum = 100; + + /// Decimals the spacing boxes show. + public const int SpacingDecimals = 4; + + public Size Size { get; init; } + + public int Quantity { get; init; } = 1; + + public double PartSpacing { get; init; } + + public double LeftSpacing { get; init; } + + public double TopSpacing { get; init; } + + public double RightSpacing { get; init; } + + public double BottomSpacing { get; init; } + + /// The plate origin's quadrant, 1 to 4. + public int Quadrant { get; init; } = 1; + + /// + /// The sheet outline the plate gets: null for a rectangular sheet. An outlined sheet's size + /// is its outline's bounds (). + /// + public SheetOutline Outline { get; init; } + + /// The plate's current settings. + public static PlateEditValues FromPlate(Plate plate) + { + ArgumentNullException.ThrowIfNull(plate); + return new PlateEditValues + { + Size = plate.Size, + Quantity = plate.Quantity, + PartSpacing = plate.PartSpacing, + LeftSpacing = plate.EdgeSpacing.Left, + TopSpacing = plate.EdgeSpacing.Top, + RightSpacing = plate.EdgeSpacing.Right, + BottomSpacing = plate.EdgeSpacing.Bottom, + Quadrant = plate.Quadrant, + Outline = plate.Outline, + }; + } + + /// + /// These settings with (null clears it, keeping the size); an + /// outline sets the size to its bounds. + /// + public PlateEditValues WithOutline(SheetOutline outline) => + outline == null + ? this with { Outline = null } + : this with { Outline = outline, Size = outline.Size }; + + /// + /// Whether Done applies: the edge spacings leave room on the sheet both ways. + /// + public bool CanApply => + LeftSpacing + RightSpacing < Size.Length && TopSpacing + BottomSpacing < Size.Width; + + /// + /// Whether Done applies with typed in the size box: it must + /// parse as a size ("width x length"), and then holds for it. + /// + public bool CanApplyWithSize(string sizeText, out Size size) => + Size.TryParse(sizeText, out size) && (this with { Size = size }).CanApply; + + /// Writes the settings to , as the dialog's Done does. + public void ApplyTo(Plate plate) + { + ArgumentNullException.ThrowIfNull(plate); + // The outline carries its own size; setting the size would drop it. + if (Outline != null) + plate.Outline = Outline; + else + { + plate.Size = Size; + plate.Outline = null; + } + plate.EdgeSpacing.Left = LeftSpacing; + plate.EdgeSpacing.Top = TopSpacing; + plate.EdgeSpacing.Right = RightSpacing; + plate.EdgeSpacing.Bottom = BottomSpacing; + plate.PartSpacing = PartSpacing; + plate.Quantity = Quantity; + plate.Quadrant = Quadrant; + } + + /// The dialog's outline line: "Rectangular sheet" or its vertices and obstacles. + public static string OutlineText(SheetOutline outline) => + outline == null + ? "Rectangular sheet" + : $"{outline.Points.Count} vertices" + + (outline.Obstacles.Count == 0 ? "" : $", {outline.Obstacles.Count} obstacle(s)"); + + /// The step of the spacing boxes: a quarter inch, or one millimeter. + public static double SpacingIncrement(Units units) => units == Units.Inches ? 0.25 : 1; +} diff --git a/OpenNest.Desktop/PlateListRow.cs b/OpenNest.Desktop/PlateListRow.cs new file mode 100644 index 00000000..a9033c23 --- /dev/null +++ b/OpenNest.Desktop/PlateListRow.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace OpenNest.Desktop; + +/// +/// One row of the Plates tab list, as the WinForms list draws it: the plate's number ("New +/// plate" for the trailing empty plate), its size, part count ("Empty" for the new plate), +/// utilization once it holds parts, and how many sheets are cut from it when more than one. +/// +public sealed record PlateListRow(string Name, string Size, string Parts, string Utilization, string Quantity) +{ + /// The row of the plate at among . + public static PlateListRow For(IList plates, int index) + { + ArgumentNullException.ThrowIfNull(plates); + var plate = plates[index]; + var isNewPlate = IsNewPlate(plates, index); + var partCount = plate.Parts.Count(part => !part.BaseDrawing.IsCutOff); + return new PlateListRow( + isNewPlate ? "New plate" : $"Plate {index + 1}", + plate.Size.ToString(4), + isNewPlate ? "Empty" : $"{partCount} {(partCount == 1 ? "part" : "parts")}", + partCount > 0 ? $"{plate.Utilization():P0} utilized" : "", + plate.Quantity > 1 ? $"×{plate.Quantity}" : ""); + } + + /// Every plate's row, in order. + public static IReadOnlyList For(IList plates) + { + ArgumentNullException.ThrowIfNull(plates); + return Enumerable.Range(0, plates.Count).Select(i => For(plates, i)).ToList(); + } + + /// The trailing empty plate the list shows as "New plate". + public static bool IsNewPlate(IList plates, int index) => + index == plates.Count - 1 && plates[index].Parts.Count == 0; + + /// + /// The gap a plate row dragged in the list is dropped into, 0 (before the first plate) + /// through (after the last movable plate): before the row + /// under the pointer when in its upper half, after it otherwise. The new-plate row and below + /// ( -1) drop after the last plate. + /// + public static int DropSlot(int rowIndex, bool upperHalf, int movableCount) + { + if (rowIndex < 0) + return movableCount; + var slot = upperHalf ? rowIndex : rowIndex + 1; + return System.Math.Min(slot, movableCount); + } + + /// The index a plate dragged from lands at when dropped in . + public static int DropTarget(int from, int slot) => slot > from ? slot - 1 : slot; +} diff --git a/OpenNest.Desktop/QuadrantPick.cs b/OpenNest.Desktop/QuadrantPick.cs new file mode 100644 index 00000000..13f3959e --- /dev/null +++ b/OpenNest.Desktop/QuadrantPick.cs @@ -0,0 +1,37 @@ +namespace OpenNest.Desktop; + +/// +/// The Edit Plate dialog's quadrant picker: a square split in four, the plate origin's +/// quadrant numbered as on a graph (1 upper right, 2 upper left, 3 lower left, 4 lower right). +/// Coordinates are the control's, y growing down. +/// +public static class QuadrantPick +{ + /// when it is 1 to 4, otherwise 1, as the picker accepts it. + public static int Normalize(int value) => value is >= 1 and <= 4 ? value : 1; + + /// The quadrant a click at (, ) picks. + public static int At(double x, double y, double width, double height) + { + var left = x < width / 2; + var top = y < height / 2; + return left ? (top ? 2 : 3) : (top ? 1 : 4); + } + + /// + /// The highlighted cell of : its left and top edges and size, + /// in the control's coordinates. + /// + public static (double X, double Y, double Width, double Height) Cell(int quadrant, double width, double height) + { + var midX = width / 2; + var midY = height / 2; + return Normalize(quadrant) switch + { + 1 => (midX, 0, width - midX, midY), + 2 => (0, 0, midX, midY), + 3 => (0, midY, midX, height - midY), + _ => (midX, midY, width - midX, height - midY), + }; + } +} diff --git a/OpenNest.Desktop/SheetOutlineImport.cs b/OpenNest.Desktop/SheetOutlineImport.cs new file mode 100644 index 00000000..460bffeb --- /dev/null +++ b/OpenNest.Desktop/SheetOutlineImport.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.IO; +using OpenNest.IO; + +namespace OpenNest.Desktop; + +/// +/// Edit Plate's Outline button: a sheet outline read from a DXF, DWG or SVG file, the largest +/// closed contour being the sheet and every other closed contour an obstacle, in the file's +/// units as drawings import. An SVG that does not state its real-world size needs the user to +/// say what its units are first (); import never guesses a scale. +/// +public static class SheetOutlineImport +{ + /// + /// Reads the outline. is the scale the user chose + /// for an SVG without a stated size, null otherwise. + /// + /// The file holds no closed contour with an area. + /// The file cannot be read. + public static SheetOutline Read(string path, Units units, double? svgUserUnitsPerInch = null) + { + ArgumentNullException.ThrowIfNull(path); + var options = new CadImportOptions { DrawingUnits = units, SvgUserUnitsPerInch = svgUserUnitsPerInch }; + return SheetOutline.FromGeometry(CadImporter.Import(path, options).Entities); + } + + /// + /// Whether a failed read is the file not holding an outline (told to the user), rather than + /// a fault in the app. + /// + public static bool IsReadFailure(Exception exception) => + exception is ArgumentException or IOException or InvalidOperationException or InvalidDataException; + + /// What the user is told when fails. + public static string FailureText(Exception exception) => + $"The file does not hold a sheet outline: {exception?.Message}"; +} + +/// +/// The scale prompt for an SVG that does not state its real-world size: what one of its units +/// is, with the size each choice gives, so a wrong one is obvious before importing. +/// +public static class SvgScale +{ + /// The choices, in the order offered; the first (CSS pixels) is the default. + public static IReadOnlyList<(string Text, double UserUnitsPerInch)> Choices { get; } = new[] + { + ("1/96 inch (web and Inkscape pixels)", 96.0), + ("1/72 inch (Illustrator points)", 72.0), + ("1 millimeter", 25.4), + ("1 inch", 1.0), + }; + + /// + /// The SVG's width and height in its own units when the scale must be asked; null when the + /// file is not an SVG, states its size, or cannot be read (the import then reports it). + /// + public static (double Width, double Height)? SizeToAsk(string path) + { + if (!Svg.IsSvg(path)) + return null; + try + { + return Svg.UndeclaredSize(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + } + + /// The prompt's question. + public static string Question(string fileName) => + $"\"{fileName}\" does not state its real-world size. What is one of its units?"; + + /// The size the file imports at with , in . + public static string ImportedSizeText(double width, double height, double userUnitsPerInch, Units units) + { + var perInch = units == Units.Millimeters ? 25.4 : 1; + var scale = perInch / userUnitsPerInch; + var format = units == Units.Millimeters ? "F1" : "F3"; + var unit = UnitsHelper.GetShortString(units); + return $"Imported size: {(width * scale).ToString(format)} x {(height * scale).ToString(format)} {unit}"; + } +} diff --git a/OpenNest/Controls/PlateListBox.cs b/OpenNest/Controls/PlateListBox.cs index 755e6e64..a871e2a0 100644 --- a/OpenNest/Controls/PlateListBox.cs +++ b/OpenNest/Controls/PlateListBox.cs @@ -111,18 +111,13 @@ namespace OpenNest.Controls g.DrawImage(GetPreview(plate), e.Bounds.X + 5, e.Bounds.Y + 5); - var isSentinel = e.Index == Items.Count - 1 && plate.Parts.Count == 0; + var row = Desktop.PlateListRow.For(Items.Cast().ToList(), e.Index); var pt = new PointF(e.Bounds.X + imageSize.Width + 15, e.Bounds.Y + 5); - g.DrawString(isSentinel ? "New plate" : $"Plate {e.Index + 1}", nameFont, Brushes.Black, pt); + g.DrawString(row.Name, nameFont, Brushes.Black, pt); - var partCount = plate.Parts.Count(part => !part.BaseDrawing.IsCutOff); - var lines = new List - { - plate.Size.ToString(4), - isSentinel ? "Empty" : $"{partCount} {(partCount == 1 ? "part" : "parts")}", - }; - if (partCount > 0) - lines.Add($"{plate.Utilization():P0} utilized"); + var lines = new List { row.Size, row.Parts }; + if (row.Utilization.Length > 0) + lines.Add(row.Utilization); foreach (var line in lines) { @@ -131,7 +126,7 @@ namespace OpenNest.Controls } // How many sheets are cut from this layout, large at the right edge of the row. - if (plate.Quantity > 1) + if (row.Quantity.Length > 0) { var quantityBounds = new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width - 12, e.Bounds.Height); using var format = new StringFormat @@ -139,7 +134,7 @@ namespace OpenNest.Controls Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Center, }; - g.DrawString($"×{plate.Quantity}", quantityFont, Brushes.Gray, quantityBounds, format); + g.DrawString(row.Quantity, quantityFont, Brushes.Gray, quantityBounds, format); } using var separatorPen = new Pen(Color.LightGray); diff --git a/OpenNest/Controls/QuadrantSelect.cs b/OpenNest/Controls/QuadrantSelect.cs index 29e81331..1ae6451e 100644 --- a/OpenNest/Controls/QuadrantSelect.cs +++ b/OpenNest/Controls/QuadrantSelect.cs @@ -1,4 +1,4 @@ -using System.Drawing; +using System.Drawing; using System.Windows.Forms; namespace OpenNest.Controls @@ -12,7 +12,7 @@ namespace OpenNest.Controls public int Quadrant { get { return quadrant; } - set { quadrant = value <= 4 && value > 0 ? value : 1; } + set { quadrant = Desktop.QuadrantPick.Normalize(value); } } protected override void OnPaint(PaintEventArgs e) @@ -67,13 +67,8 @@ namespace OpenNest.Controls { base.OnMouseClick(e); - var midx = Width / 2; - var midy = Height / 2; - - if (e.X < midx) - Quadrant = e.Y < midy ? 2 : 3; - else - Quadrant = e.Y < midy ? 1 : 4; + // Whole pixels, as the control has always split itself. + Quadrant = Desktop.QuadrantPick.At(e.X, e.Y, Width / 2 * 2, Height / 2 * 2); Invalidate(); } diff --git a/OpenNest/Forms/EditNestForm.PlateOrder.cs b/OpenNest/Forms/EditNestForm.PlateOrder.cs index dc50ce8f..b28b2bc1 100644 --- a/OpenNest/Forms/EditNestForm.PlateOrder.cs +++ b/OpenNest/Forms/EditNestForm.PlateOrder.cs @@ -1,6 +1,7 @@ using System; using System.Drawing; using System.Windows.Forms; +using OpenNest.Desktop; namespace OpenNest.Forms { @@ -119,16 +120,8 @@ namespace OpenNest.Forms if (IsInspecting || !PlateManager.CanDuplicatePlate(fromIndex, toIndex)) return false; - using (var change = BeginChange("Duplicate Plate")) - { - change.MarkChanged(); - var copy = PlateManager.DuplicatePlate(fromIndex, toIndex); - // The copy gets its own parameters, so editing one sheet's leaves the other's alone. - if (copy.CuttingParameters != null) - copy.CuttingParameters = IO.CuttingParametersSerializer.FromDto( - IO.CuttingParametersSerializer.ToDto(copy.CuttingParameters)); - change.Complete(); - } + // The copy gets its own parameters, so editing one sheet's leaves the other's alone. + PlateCommands.DuplicatePlate(PlateManager, fromIndex, toIndex, label => BeginChange(label)); FirePlateChanged(); return true; @@ -151,12 +144,7 @@ namespace OpenNest.Forms if (IsInspecting || !PlateManager.CanMovePlate(fromIndex, toIndex)) return false; - using (var change = BeginChange("Move Plate")) - { - change.MarkChanged(); - PlateManager.MovePlate(fromIndex, toIndex); - change.Complete(); - } + PlateCommands.MovePlate(PlateManager, fromIndex, toIndex, label => BeginChange(label)); // Navigation and the status bar read the current plate's index. FirePlateChanged(); @@ -169,7 +157,7 @@ namespace OpenNest.Forms return; var from = PlateManager.CurrentIndex; - var to = e.KeyCode == Keys.Up ? from - 1 : from + 1; + var to = PlateCommands.StepTarget(from, e.KeyCode == Keys.Up); MovePlate(from, to); e.Handled = true; e.SuppressKeyPress = true; @@ -269,12 +257,11 @@ namespace OpenNest.Forms } var bounds = platesListView.GetItemRectangle(index); - var slot = client.Y < bounds.Top + bounds.Height / 2 ? index : index + 1; - return System.Math.Min(slot, movable); + return PlateListRow.DropSlot(index, client.Y < bounds.Top + bounds.Height / 2, movable); } /// The index a plate dragged from lands at when dropped in . - internal static int PlateDropTarget(int from, int slot) => slot > from ? slot - 1 : slot; + internal static int PlateDropTarget(int from, int slot) => PlateListRow.DropTarget(from, slot); private void ShowPlateDropIndicator(int slot) { diff --git a/OpenNest/Forms/EditNestForm.cs b/OpenNest/Forms/EditNestForm.cs index 4e98eb66..78381648 100644 --- a/OpenNest/Forms/EditNestForm.cs +++ b/OpenNest/Forms/EditNestForm.cs @@ -915,19 +915,19 @@ namespace OpenNest.Forms public void RotateCw() { - RecordChange("Rotate Plate", () => PlateView.Plate.Rotate90(RotationType.CW)); + PlateCommands.Rotate(PlateView.Plate, PlateRotation.Clockwise, label => BeginChange(label)); PlateView.ZoomToFit(); } public void RotateCcw() { - RecordChange("Rotate Plate", () => PlateView.Plate.Rotate90(RotationType.CCW)); + PlateCommands.Rotate(PlateView.Plate, PlateRotation.CounterClockwise, label => BeginChange(label)); PlateView.ZoomToFit(); } public void Rotate180() { - RecordChange("Rotate Plate", () => PlateView.Plate.Rotate180()); + PlateCommands.Rotate(PlateView.Plate, PlateRotation.HalfTurn, label => BeginChange(label)); PlateView.ZoomToFit(); } @@ -1040,7 +1040,7 @@ namespace OpenNest.Forms public void ResizePlateToFitParts() { - RecordChange("Resize Plate", () => PlateView.Plate.AutoSize(Settings.Default.AutoSizePlateFactor)); + PlateCommands.ResizeToFit(PlateView.Plate, Settings.Default.AutoSizePlateFactor, label => BeginChange(label)); PlateView.ZoomToPlate(); PlateView.Refresh(); UpdatePlateList(); @@ -1103,8 +1103,7 @@ namespace OpenNest.Forms // The defaults are saved with the nest and the trailing empty plate follows them. public void SetCurrentPlateAsNestDefault() => - RecordChange("Set Nest Default Plate", - () => PlateManager.ChangePlateDefaults(() => Nest.PlateDefaults.SetFromExisting(PlateView.Plate))); + PlateCommands.SetAsNestDefault(Nest, PlateManager, PlateView.Plate, label => BeginChange(label)); public void EditPlate() { @@ -1121,8 +1120,7 @@ namespace OpenNest.Forms UpdatePlateList(); // An empty plate's new settings become the nest's defaults. - if (PlateView.Plate.Parts.Count == 0) - PlateManager.ChangePlateDefaults(() => Nest.PlateDefaults.SetFromExisting(PlateView.Plate)); + PlateCommands.FollowEditedPlate(Nest, PlateManager, PlateView.Plate); } Nest.UpdateDrawingQuantities(); @@ -1172,14 +1170,7 @@ namespace OpenNest.Forms change.Complete(); } - public void RemoveCurrentPlate() - { - using var change = BeginChange("Remove Plate"); - if (PlateManager.Count >= 2) - change.MarkChanged(); - PlateManager.RemoveCurrent(); - change.Complete(); - } + public void RemoveCurrentPlate() => PlateCommands.RemoveCurrentPlate(PlateManager, label => BeginChange(label)); public void ClearNest() { @@ -1190,15 +1181,8 @@ namespace OpenNest.Forms change.Complete(); } - public void RemoveEmptyPlates() - { - using var change = BeginChange("Remove Empty Plates"); - // The trailing empty plate comes back as the new-plate sentinel. - if (Nest.Plates.Count >= 2 && Nest.Plates.SkipLast(1).Any(plate => plate.Parts.Count == 0)) - change.MarkChanged(); - Nest.Plates.RemoveEmptyPlates(); - change.Complete(); - } + // The trailing empty plate comes back as the new-plate sentinel. + public void RemoveEmptyPlates() => PlateCommands.RemoveEmptyPlates(Nest, label => BeginChange(label)); public void AutoSequenceCurrentPlate() { diff --git a/OpenNest/Forms/EditPlateForm.cs b/OpenNest/Forms/EditPlateForm.cs index 4829e718..041f26f9 100644 --- a/OpenNest/Forms/EditPlateForm.cs +++ b/OpenNest/Forms/EditPlateForm.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Windows.Forms; +using OpenNest.Desktop; using OpenNest.IO; using Timer = System.Windows.Forms.Timer; @@ -54,12 +55,7 @@ namespace OpenNest.Forms private void SetUnits(Units units) { string suffix = " " + UnitsHelper.GetShortString(units); - decimal increment; - - if (units == Units.Inches) - increment = 0.25m; - else - increment = 1; + var increment = (decimal)PlateEditValues.SpacingIncrement(units); var controls = new[] { @@ -141,71 +137,46 @@ namespace OpenNest.Forms buttonClearOutline.Enabled = value != null; if (value != null) textBoxSize.Text = value.Size.ToString(4); - labelOutline.Text = value == null - ? "Rectangular sheet" - : $"{value.Points.Count} vertices" + (value.Obstacles.Count == 0 ? "" : $", {value.Obstacles.Count} obstacle(s)"); + labelOutline.Text = PlateEditValues.OutlineText(value); EnableCheck(); } } - public void EnableCheck() + public void EnableCheck() => applyButton.Enabled = Values.CanApplyWithSize(SizeString, out _); + + // The values but the size, which the size box holds as typed. + private PlateEditValues Values => new() { - OpenNest.Geometry.Size size; - - if (!OpenNest.Geometry.Size.TryParse(SizeString, out size)) - { - applyButton.Enabled = false; - return; - } - - if (LeftSpacing + RightSpacing >= size.Length) - { - applyButton.Enabled = false; - return; - } - - if (TopSpacing + BottomSpacing >= size.Width) - { - applyButton.Enabled = false; - return; - } - - applyButton.Enabled = true; - } + LeftSpacing = LeftSpacing, + TopSpacing = TopSpacing, + RightSpacing = RightSpacing, + BottomSpacing = BottomSpacing, + PartSpacing = PartSpacing, + Quantity = Quantity, + Quadrant = Quadrant, + Outline = Outline, + }; private new void Load(Plate plate) { - textBoxSize.Text = plate.Size.ToString(); - LeftSpacing = plate.EdgeSpacing.Left; - TopSpacing = plate.EdgeSpacing.Top; - RightSpacing = plate.EdgeSpacing.Right; - BottomSpacing = plate.EdgeSpacing.Bottom; - PartSpacing = plate.PartSpacing; - Quantity = plate.Quantity; - Quadrant = plate.Quadrant; - Outline = plate.Outline; + var values = PlateEditValues.FromPlate(plate); + textBoxSize.Text = values.Size.ToString(); + LeftSpacing = values.LeftSpacing; + TopSpacing = values.TopSpacing; + RightSpacing = values.RightSpacing; + BottomSpacing = values.BottomSpacing; + PartSpacing = values.PartSpacing; + Quantity = values.Quantity; + Quadrant = values.Quadrant; + Outline = values.Outline; } /// Writes the dialog's values to the plate, as Done does. internal void Apply() => Save(); - private void Save() - { - // The outline carries its own size; a parsed size would drop it. - if (Outline != null) - plate.Outline = Outline; - else - plate.Size = OpenNest.Geometry.Size.Parse(SizeString); - if (Outline == null) - plate.Outline = null; - plate.EdgeSpacing.Left = LeftSpacing; - plate.EdgeSpacing.Top = TopSpacing; - plate.EdgeSpacing.Right = RightSpacing; - plate.EdgeSpacing.Bottom = BottomSpacing; - plate.PartSpacing = PartSpacing; - plate.Quantity = Quantity; - plate.Quadrant = Quadrant; - } + // The outline carries its own size; a parsed size would drop it. + private void Save() => + (Values with { Size = Outline?.Size ?? OpenNest.Geometry.Size.Parse(SizeString) }).ApplyTo(plate); private void textBox1_TextChanged(object sender, EventArgs e) { @@ -241,11 +212,11 @@ namespace OpenNest.Forms var options = new CadImportOptions { DrawingUnits = Units }; if (!SvgScaleForm.TryResolve(this, dialog.FileName, options)) return; - Outline = SheetOutline.FromGeometry(CadImporter.Import(dialog.FileName, options).Entities); + Outline = SheetOutlineImport.Read(dialog.FileName, Units, options.SvgUserUnitsPerInch); } - catch (Exception exception) when (exception is ArgumentException or IOException or InvalidOperationException or InvalidDataException) + catch (Exception exception) when (SheetOutlineImport.IsReadFailure(exception)) { - MessageBox.Show(this, $"The file does not hold a sheet outline: {exception.Message}", + MessageBox.Show(this, SheetOutlineImport.FailureText(exception), "Import Sheet Outline", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } diff --git a/OpenNest/Forms/MainForm.Tools.cs b/OpenNest/Forms/MainForm.Tools.cs index 46cca508..2508e6a4 100644 --- a/OpenNest/Forms/MainForm.Tools.cs +++ b/OpenNest/Forms/MainForm.Tools.cs @@ -267,8 +267,8 @@ namespace OpenNest.Forms return; // A plate holds no common-line usage, so the saved defaults keep theirs. - MachineSettings.SaveNestDefaults(this, NestDefaults.FromPlate(activeForm.Nest.Units, activeForm.PlateView.Plate, - MachineSettings.LoadSavedNestDefaults(out _)), activeForm.Nest.Machine); + MachineSettings.SaveNestDefaults(this, Desktop.PlateCommands.NewNestDefaults(activeForm.Nest, + activeForm.PlateView.Plate, MachineSettings.LoadSavedNestDefaults(out _))); } private void MachineConfig_Click(object sender, EventArgs e) => ShowMachineConfig(null); diff --git a/OpenNest/Forms/SvgScaleForm.cs b/OpenNest/Forms/SvgScaleForm.cs index 6490266c..cbb1cef3 100644 --- a/OpenNest/Forms/SvgScaleForm.cs +++ b/OpenNest/Forms/SvgScaleForm.cs @@ -26,7 +26,7 @@ namespace OpenNest.Forms fileWidth = width; fileHeight = height; this.units = units; - labelMessage.Text = $"\"{fileName}\" does not state its real-world size. What is one of its units?"; + labelMessage.Text = Desktop.SvgScale.Question(fileName); UpdateSize(this, EventArgs.Empty); } @@ -82,12 +82,7 @@ namespace OpenNest.Forms private void UpdateSize(object sender, EventArgs e) { - var perInch = units == Units.Millimeters ? 25.4 : 1; - var scale = perInch / UserUnitsPerInch; - var format = units == Units.Millimeters ? "F1" : "F3"; - var unit = UnitsHelper.GetShortString(units); - labelSize.Text = - $"Imported size: {(fileWidth * scale).ToString(format)} x {(fileHeight * scale).ToString(format)} {unit}"; + labelSize.Text = Desktop.SvgScale.ImportedSizeText(fileWidth, fileHeight, UserUnitsPerInch, units); } } }