From 27736546048d635f541482d885cfb9919846386f Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sun, 29 Nov 2026 20:37:17 -0500 Subject: [PATCH 1/4] test(posts): mask post time stamps when comparing outputs PlannedDoor_PostsExactlyItsCutsAndNeverTheOutline posts the same nest twice; the Cincinnati header stamps the clock to the second, so CI failed when the two posts straddled a second boundary. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Tests/CuttingPlanning/DisplayPerimeterPostTests.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/OpenNest.Tests/CuttingPlanning/DisplayPerimeterPostTests.cs b/OpenNest.Tests/CuttingPlanning/DisplayPerimeterPostTests.cs index c2792e83..1c8a77eb 100644 --- a/OpenNest.Tests/CuttingPlanning/DisplayPerimeterPostTests.cs +++ b/OpenNest.Tests/CuttingPlanning/DisplayPerimeterPostTests.cs @@ -1,4 +1,5 @@ using System.Text; +using System.Text.RegularExpressions; using OpenNest.CNC; using OpenNest.CNC.CuttingPlanning; using OpenNest.Diagnostics; @@ -31,7 +32,10 @@ public class DisplayPerimeterPostTests poly.Layer + ":" + string.Join(";", poly.Points.Select(v => FormattableString.Invariant($"{v.X:R},{v.Y:R}"))))); using var stream = new MemoryStream(); Post(post).Post(nest, stream); - return Encoding.UTF8.GetString(stream.ToArray()); + // Posts stamp the wall clock (Cincinnati to the second, CI Fiber to the minute), so two + // posts of the same nest can straddle a boundary. + return Regex.Replace(Encoding.UTF8.GetString(stream.ToArray()), + @"(\d{2}-\d{2}-\d{4}|[A-Z][a-z]+ \d{1,2}, \d{4}) +\d{2}:\d{2}(:\d{2})? [AP]M", ""); } private static (Nest Nest, Part Part) DoorNest() From e78fc451495c3c26dbccc5e85357f45a79255c80 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sun, 29 Nov 2026 21:43:20 -0500 Subject: [PATCH 2/4] test(ui): start the grid tooltip timer the dispose test relies on DisposingAGridStopsItsShowingKeyboardToolTip expected ShowKeyboardToolTip to leave an auto-pop timer running. On Windows 11 and later keyboard tooltips are persistent and start none, and showing one hooks the form's Deactivate, which stops the timer whenever the form loses activation (it flaked on CI's Server 2022 runner). Set up the running timer explicitly; the test still fails without GridStyle's dispose hook. Co-Authored-By: Claude Opus 5.5 --- OpenNest.WinForms.Tests/Controls/GridStyleTests.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/OpenNest.WinForms.Tests/Controls/GridStyleTests.cs b/OpenNest.WinForms.Tests/Controls/GridStyleTests.cs index b60f94b2..ca9858cd 100644 --- a/OpenNest.WinForms.Tests/Controls/GridStyleTests.cs +++ b/OpenNest.WinForms.Tests/Controls/GridStyleTests.cs @@ -94,10 +94,17 @@ public class GridStyleTests form.Show(); Pump(grid); - // As when the keyboard moves to a cell in the embedded version history. + // As when the keyboard moves to a cell in the embedded version history. On Windows 11 + // and later a keyboard tooltip is persistent and starts no timer, so make it behave as + // it does on earlier Windows, where the timer exists. var toolTip = (ToolTip)typeof(DataGridView).GetProperty("KeyboardToolTip", members).GetValue(grid); + typeof(ToolTip).GetProperty("IsPersistent", members).SetValue(toolTip, false); typeof(ToolTip).GetMethod("ShowKeyboardToolTip", members) .Invoke(toolTip, new object[] { "2", grid.Rows[0].Cells[0], 3000 }); + // Showing hooks the form's Deactivate, which hides the tip and stops its timer; losing + // activation to another window (a parallel test's form) is not the case under test, so + // make sure the auto-pop timer is running before the grid goes. + typeof(ToolTip).GetMethod("StartTimer", members).Invoke(toolTip, new object[] { grid, 3000 }); var timer = typeof(ToolTip).GetField("_timer", members); Assert.NotNull(timer.GetValue(toolTip)); From 5b67d78ac7ad3f2f850e0ddfc8e812e795ddf962 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Mon, 30 Nov 2026 06:35:30 -0500 Subject: [PATCH 3/4] fix(ui): return the placing preview to the cursor after a settled click Shift/Ctrl+click settles the preview onto the plate, then copies it. The preview stayed on the settled copy until the mouse moved, so clicking again without moving settled from inside that copy and stacked the next part on it. The preview now goes back to where it was clicked, keeping any arrow nudge. Co-Authored-By: Claude Opus 5.5 --- .../Controls/ActionCloneTests.cs | 26 +++++++++++++++++++ OpenNest/Actions/ActionClone.cs | 13 +++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/OpenNest.WinForms.Tests/Controls/ActionCloneTests.cs b/OpenNest.WinForms.Tests/Controls/ActionCloneTests.cs index 48082853..9c91a9de 100644 --- a/OpenNest.WinForms.Tests/Controls/ActionCloneTests.cs +++ b/OpenNest.WinForms.Tests/Controls/ActionCloneTests.cs @@ -114,6 +114,32 @@ public class ActionCloneTests Assert.Equal(0, copy.Bottom, 6); }, TimeSpan.FromMinutes(1), "The STA test did not complete."); + [Theory] + [InlineData(Keys.Shift)] + [InlineData(Keys.Control)] + public void RepeatedModifiedClicksWithoutMovingStackNoCopies(Keys modifiers) => StaTestThread.Run(() => + { + var plate = new Plate(48, 96) { PartSpacing = 0 }; + using var view = new PlateView { Plate = plate, Size = new System.Drawing.Size(600, 600) }; + view.ZoomToFit(); + view.SetAction(typeof(ActionClone), Square("new")); + var action = Assert.IsType(view.Actions.CurrentAction); + action.PlacementOrder = OpenNest.Engine.Fill.SettleOrder.VerticalFirst; + var preview = Assert.Single(view.SelectedParts); + preview.BasePart.Location = new Vector(1, 20); + + action.Apply(modifiers); + Assert.Equal(new Vector(1, 20), preview.BasePart.BoundingBox.Location); + action.Apply(modifiers); + action.Apply(modifiers); + + Assert.Equal(3, plate.Parts.Count); + var bottoms = plate.Parts.Select(p => p.BoundingBox.Bottom).OrderBy(y => y).ToList(); + Assert.Equal(0, bottoms[0], 6); + Assert.InRange(bottoms[1], 4, 4.01); + Assert.InRange(bottoms[2], 8, 8.02); + }, TimeSpan.FromMinutes(1), "The STA test did not complete."); + [Fact] public void ADialogsFakeMouseMoveLeavesNudgedPreviewsInPlace() => StaTestThread.Run(() => { diff --git a/OpenNest/Actions/ActionClone.cs b/OpenNest/Actions/ActionClone.cs index de7eb48b..03c54af3 100644 --- a/OpenNest/Actions/ActionClone.cs +++ b/OpenNest/Actions/ActionClone.cs @@ -209,7 +209,9 @@ namespace OpenNest.Actions change.MarkChanged(); var shift = (modifiers & Keys.Shift) == Keys.Shift; var boxesOnly = !shift && (modifiers & Keys.Control) == Keys.Control; - if (shift || boxesOnly) + var settles = shift || boxesOnly; + var home = parts.GetBoundingBox().Location; + if (settles) { var movingParts = parts.Select(p => p.BasePart).ToList(); @@ -251,6 +253,15 @@ namespace OpenNest.Actions foreach (var (members, kerf) in commonLines) plateView.Plate.JoinCommonLine(members.Select(i => placed[i]), kerf); + // Put the previews back where they were clicked: left on the settled copy, the + // next click without moving the mouse would settle from inside it and stack on it. + if (settles) + { + var back = home - parts.GetBoundingBox().Location; + parts.ForEach(p => p.Offset(back)); + plateView.Invalidate(); + } + if (plateView.Plate.CutOffs.Count > 0) plateView.Plate.RegenerateCutOffs(plateView.CutOffSettings); change.Complete(); From 2503c05d7141ce057b9a6cb6d78312fc3a1eeaa2 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Mon, 30 Nov 2026 11:35:06 -0500 Subject: [PATCH 4/4] feat(ui): copy and paste parts between nests Two nests that should have been one (a thickness saved as 0.1196 instead of 0.12 kept N26-2CN and N26-2CH apart in Auto Nest) could only be joined by re-importing drawings and re-nesting. Copy and Cut now also remember the selected parts, and Paste (Ctrl+V) and Paste in Place (Ctrl+Shift+V) put them into whichever nest is active. A paste adds an exact copy of each drawing the target lacks, with its required quantity, uses a same-named drawing with the same geometry, and refuses a different drawing with the same name, since a nest cannot hold two. Drawings are captured at copy time, so later edits or undo in the source do not change what is pasted. Clipboard keys in text boxes now edit the text instead of acting on parts. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + OpenNest.Core/Part.cs | 20 ++ OpenNest.IO.Tests/CopiedPartsTests.cs | 200 +++++++++++++++ OpenNest.IO/CopiedParts.cs | 234 ++++++++++++++++++ .../Forms/UndoRecordingTests.cs | 88 +++++++ OpenNest/Actions/ActionClone.cs | 10 +- OpenNest/Forms/MainForm.Designer.cs | 17 +- OpenNest/Forms/MainForm.View.cs | 114 +++++++++ OpenNest/Forms/MainForm.cs | 3 + docs/copy-paste-parts.md | 49 ++++ docs/undo-redo.md | 4 +- 11 files changed, 735 insertions(+), 5 deletions(-) create mode 100644 OpenNest.IO.Tests/CopiedPartsTests.cs create mode 100644 OpenNest.IO/CopiedParts.cs create mode 100644 docs/copy-paste-parts.md diff --git a/AGENTS.md b/AGENTS.md index 88fc5b67..ee0031c9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,6 +67,7 @@ Read the relevant contract before changing its behavior: - [Nest file format](docs/nest-file-format.md) - [SVG import and export](docs/svg-import-export.md): SVG numbers are not drawing units; import never guesses a scale. It also covers the CAD Converter's DXF/DWG/SVG export, whose bends import reads back +- [Copying parts between nests](docs/copy-paste-parts.md): Copy/Cut remember parts; Paste and Paste in Place put them in any open nest, adding exact drawing copies, reusing same-geometry drawings by name and refusing a different drawing with the same name - [Separating parts](docs/separate-parts.md): the CAD Converter splits a file drawing several parts into one drawing per part (`PartBodies`), keeping IDs and refusing a breakoff or tabbed cutout that spans parts - [Irregular stock](docs/irregular-stock.md): outlined sheets, what honors the outline and what refuses it - [Directional slides](docs/geometry/directional-slides.md) and [pair-spacing limits](docs/geometry/pair-spacing.md) diff --git a/OpenNest.Core/Part.cs b/OpenNest.Core/Part.cs index 8600ab89..d6f3bfac 100644 --- a/OpenNest.Core/Part.cs +++ b/OpenNest.Core/Part.cs @@ -432,6 +432,26 @@ namespace OpenNest return part; } + /// + /// A deep copy, like , that places instead of + /// this part's drawing. must hold the same program, such as an + /// exact copy of the drawing in another nest: the placed program is copied as it is. + /// + public Part CloneFor(Drawing drawing) + { + System.ArgumentNullException.ThrowIfNull(drawing); + var part = new Part( + drawing, + (Program)Program.Clone(), + Location, + new Box(BoundingBox.X, BoundingBox.Y, BoundingBox.Length, BoundingBox.Width) + ); + part.ownsProgram = true; + part.CopyLeadInStateFrom(this); + + return part; + } + /// /// Creates an offset copy of the part. Clones from the already-rotated /// program (skips re-rotation) and computes the bounding box arithmetically diff --git a/OpenNest.IO.Tests/CopiedPartsTests.cs b/OpenNest.IO.Tests/CopiedPartsTests.cs new file mode 100644 index 00000000..fd3282c7 --- /dev/null +++ b/OpenNest.IO.Tests/CopiedPartsTests.cs @@ -0,0 +1,200 @@ +using OpenNest.CNC; +using OpenNest.CutOffs; +using OpenNest.Geometry; + +namespace OpenNest.IO.Tests; + +/// Parts copied from one nest paste into another with exact copies of their drawings. +public class CopiedPartsTests +{ + private const double Kerf = 0.012; + + private static Drawing Rectangle(string name, double length = 6) + { + var program = new Program(); + program.Codes.Add(new RapidMove(0, 0)); + program.Codes.Add(new LinearMove(length, 0)); + program.Codes.Add(new LinearMove(length, 12)); + program.Codes.Add(new LinearMove(0, 12)); + program.Codes.Add(new LinearMove(0, 0)); + return new Drawing(name, program); + } + + private static (Nest Nest, Plate Plate, Drawing Drawing) Source() + { + var nest = new Nest("N26-2CH") { Units = Units.Inches, Thickness = 0.1196 }; + var drawing = Rectangle("bracket"); + drawing.Quantity.Required = 7; + drawing.Customer = "acme"; + drawing.Priority = 3; + nest.Drawings.Add(drawing); + var plate = nest.CreatePlate(); + plate.Size = new Geometry.Size(48, 96); + var rotated = new Part(drawing, new Vector(20, 30)); + rotated.Rotate(OpenNest.Math.Angle.HalfPI); + plate.Parts.Add(new Part(drawing, new Vector(1, 1))); + plate.Parts.Add(rotated); + return (nest, plate, drawing); + } + + private static Nest Target(Units units = Units.Inches) + { + var nest = new Nest("N26-2CN") { Units = units, Thickness = 0.12 }; + nest.Drawings.Add(Rectangle("other", 9)); + var plate = nest.CreatePlate(); + plate.Size = new Geometry.Size(48, 96); + return nest; + } + + [Fact] + public void PasteIntoAnotherNest_AddsAnExactCopyOfTheDrawing_AndPlacesThePartsWhereTheyWere() + { + var (source, plate, drawing) = Source(); + var copied = CopiedParts.Capture(source, plate, plate.Parts)!; + var target = Target(); + + var paste = copied.PlanPaste(target); + var placed = paste.PlaceInPlace(target.Plates[0]); + + Assert.False(paste.IsRefused); + var copy = Assert.Single(paste.AddedDrawings); + Assert.NotSame(drawing, copy); + Assert.Contains(copy, target.Drawings); + Assert.Equal("bracket", copy.Name); + Assert.Equal("acme", copy.Customer); + Assert.Equal(3, copy.Priority); + Assert.Equal(7, copy.Quantity.Required); + Assert.Equal(2, copy.Quantity.Nested); + Assert.Equal(2, drawing.Quantity.Nested); + Assert.Equal(plate.Parts.Select(p => (p.Location, p.Rotation, p.BoundingBox.Width, p.BoundingBox.Length)), + placed.Select(p => (p.Location, p.Rotation, p.BoundingBox.Width, p.BoundingBox.Length))); + Assert.All(placed, p => Assert.Same(copy, p.BaseDrawing)); + Assert.Equal(placed, target.Plates[0].Parts); + } + + [Fact] + public void ASecondPasteUsesTheDrawingTheFirstAdded() + { + var (source, plate, _) = Source(); + var copied = CopiedParts.Capture(source, plate, plate.Parts)!; + var target = Target(); + copied.PlanPaste(target).PlaceInPlace(target.Plates[0]); + var added = target.Drawings.Single(d => d.Name == "bracket"); + + var second = copied.PlanPaste(target); + + Assert.Empty(second.AddedDrawings); + Assert.Same(added, Assert.Single(second.MatchedDrawings)); + Assert.All(second.Parts, p => Assert.Same(added, p.BaseDrawing)); + Assert.Equal(7, added.Quantity.Required); + } + + [Fact] + public void TheSameDrawingInTheTarget_IsUsed_WhateverItsQuantityAndSettings() + { + var (source, plate, _) = Source(); + var copied = CopiedParts.Capture(source, plate, plate.Parts)!; + var target = Target(); + var own = Rectangle("bracket"); + own.Quantity.Required = 2; + own.Priority = 0; + target.Drawings.Add(own); + + var paste = copied.PlanPaste(target); + + Assert.Empty(paste.AddedDrawings); + Assert.Same(own, Assert.Single(paste.MatchedDrawings)); + Assert.All(paste.Parts, p => Assert.Same(own, p.BaseDrawing)); + Assert.Equal(2, own.Quantity.Required); + } + + [Fact] + public void ADifferentDrawingWithTheSameName_RefusesThePaste() + { + var (source, plate, _) = Source(); + var copied = CopiedParts.Capture(source, plate, plate.Parts)!; + var target = Target(); + target.Drawings.Add(Rectangle("bracket", 8)); + var before = target.Drawings.Count; + + var paste = copied.PlanPaste(target); + + Assert.True(paste.IsRefused); + Assert.Contains("'bracket'", paste.Refusal); + Assert.Empty(paste.Parts); + Assert.Throws(paste.AddDrawings); + Assert.Equal(before, target.Drawings.Count); + } + + [Fact] + public void OtherUnits_RefuseThePaste() + { + var (source, plate, _) = Source(); + var copied = CopiedParts.Capture(source, plate, plate.Parts)!; + + var paste = copied.PlanPaste(Target(Units.Millimeters)); + + Assert.True(paste.IsRefused); + Assert.Contains("millimeters", paste.Refusal); + } + + [Fact] + public void EditsToTheSourceAfterCopying_DoNotReachThePaste() + { + var (source, plate, drawing) = Source(); + var copied = CopiedParts.Capture(source, plate, plate.Parts)!; + drawing.Quantity.Required = 99; + drawing.Customer = "changed"; + plate.Parts[0].Offset(10, 10); + + var paste = copied.PlanPaste(Target()); + + var copy = Assert.Single(paste.AddedDrawings); + Assert.Equal(7, copy.Quantity.Required); + Assert.Equal("acme", copy.Customer); + Assert.Equal(new Vector(1, 1), paste.Parts[0].Location); + } + + [Fact] + public void PartStateAndCommonLinesComeAlong_AndCutOffsStayBehind() + { + var nest = new Nest("source") { Units = Units.Inches }; + var drawing = Rectangle("rect"); + nest.Drawings.Add(drawing); + var plate = nest.CreatePlate(); + plate.Size = new Geometry.Size(60, 60); + var left = new Part(drawing, new Vector(1, 1)) { LeadInsLocked = true, DrawingPinsOff = true }; + var right = new Part(drawing, new Vector(7 + Kerf, 1)); + plate.Parts.Add(left); + plate.Parts.Add(right); + plate.CutOffs.Add(new CutOff(new Vector(40, 0), CutOffAxis.Vertical)); + plate.RegenerateCutOffs(new CutOffSettings()); + plate.JoinCommonLine(new[] { left, right }, Kerf); + Assert.Contains(plate.Parts, p => p.BaseDrawing.IsCutOff); + + var copied = CopiedParts.Capture(nest, plate, plate.Parts)!; + var target = Target(); + var placed = copied.PlanPaste(target).PlaceInPlace(target.Plates[0]); + + Assert.Equal(2, copied.Count); + Assert.Equal(new[] { "rect" }, copied.DrawingNames); + Assert.True(placed[0].LeadInsLocked); + Assert.True(placed[0].DrawingPinsOff); + var group = Assert.Single(target.Plates[0].CommonLines); + Assert.Equal(Kerf, group.Kerf); + Assert.Equal(placed, group.Members); + Assert.DoesNotContain(target.Drawings, d => d.IsCutOff); + } + + [Fact] + public void OnlyCutOffsSelected_CopiesNothing() + { + var nest = new Nest("source") { Units = Units.Inches }; + var plate = nest.CreatePlate(); + plate.Size = new Geometry.Size(60, 60); + plate.CutOffs.Add(new CutOff(new Vector(40, 0), CutOffAxis.Vertical)); + plate.RegenerateCutOffs(new CutOffSettings()); + + Assert.Null(CopiedParts.Capture(nest, plate, plate.Parts)); + } +} diff --git a/OpenNest.IO/CopiedParts.cs b/OpenNest.IO/CopiedParts.cs new file mode 100644 index 00000000..674f0546 --- /dev/null +++ b/OpenNest.IO/CopiedParts.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using OpenNest.CommonLines; + +namespace OpenNest.IO +{ + /// + /// Parts copied from a plate (Edit > Copy or Cut) for pasting into any open nest, the one they + /// came from or another. Each part is cloned as it was copied, with its placed program, lead-ins + /// and the common-line groups among the copied parts; each drawing is kept as the nest file saves + /// it, so editing or closing the source nest afterwards changes nothing here. Cut-off parts are + /// plate definitions, not parts, and are never copied. See docs/copy-paste-parts.md. + /// + public sealed class CopiedParts + { + // A .nest archive holding the copied drawings and no plates. + private readonly byte[] drawingsArchive; + private readonly List<(Part Part, string DrawingName)> parts; + // Drawing name -> DrawingPackage.GeometryKey, in order of first use. + private readonly List<(string Name, string GeometryKey)> drawings; + + private CopiedParts(byte[] drawingsArchive, List<(Part, string)> parts, + List<(string, string)> drawings, List<(int[] Members, double Kerf)> commonLines, Units units) + { + this.drawingsArchive = drawingsArchive; + this.parts = parts; + this.drawings = drawings; + CommonLines = commonLines; + Units = units; + } + + /// The units the copied drawings are drawn in. + public Units Units { get; } + + public int Count => parts.Count; + + /// The names of the copied parts' drawings, each once, in the order the parts use them. + public IReadOnlyList DrawingNames => drawings.Select(d => d.Name).ToList(); + + /// The common-line groups among the copied parts, by index into the copy. + public IReadOnlyList<(int[] Members, double Kerf)> CommonLines { get; } + + /// + /// Copies from of . + /// Cut-off parts are left out; null when nothing else was selected. + /// + public static CopiedParts Capture(Nest nest, Plate plate, IEnumerable selected) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(selected); + + var sources = selected.Where(p => p != null && !p.BaseDrawing.IsCutOff).ToList(); + if (sources.Count == 0) + return null; + + var byName = new Dictionary(StringComparer.Ordinal); + var order = new List(); + foreach (var part in sources) + { + var name = part.BaseDrawing.Name ?? ""; + if (!byName.TryGetValue(name, out var known)) + { + byName.Add(name, part.BaseDrawing); + order.Add(part.BaseDrawing); + } + else if (!ReferenceEquals(known, part.BaseDrawing)) + { + throw new InvalidOperationException($"Two different drawings are named '{name}'."); + } + } + + var holder = new Nest(nest.Name) { Units = nest.Units }; + foreach (var drawing in order) + holder.Drawings.Add(drawing); + using var stream = new MemoryStream(); + new NestWriter(holder).Write(stream); + + var keyed = order.Select(d => (d.Name ?? "", GeometryKey(d, nest.Units))).ToList(); + var copies = sources.Select(p => ((Part)p.Clone(), p.BaseDrawing.Name ?? "")).ToList(); + var commonLines = CommonLineGroup.AmongParts(plate, sources); + return new CopiedParts(stream.ToArray(), copies, keyed, commonLines, nest.Units); + } + + /// + /// Plans pasting the copy into without changing it. A drawing the + /// nest already has under the same name is used when it is the same drawing (same geometry, + /// whatever its quantities, color or nesting settings); otherwise the paste is refused, since + /// a nest cannot hold two drawings with one name. A drawing the nest lacks is added as an + /// exact copy, with the required quantity it had where it was copied from. + /// + public PartsPaste PlanPaste(Nest target) + { + ArgumentNullException.ThrowIfNull(target); + if (target.Units != Units) + return PartsPaste.Refuse(target, $"The copied parts are drawn in {UnitName(Units)} and this nest " + + $"is in {UnitName(target.Units)}. Converting units is not supported."); + + var conflicts = new List(); + var map = new Dictionary(StringComparer.Ordinal); + var matched = new List(); + var missing = new List(); + foreach (var (name, key) in drawings) + { + var existing = target.Drawings.FirstOrDefault(d => string.Equals(d.Name ?? "", name, StringComparison.Ordinal)); + if (existing == null) + missing.Add(name); + else if (existing.IsCutOff || GeometryKey(existing, target.Units) != key) + conflicts.Add(name); + else + { + map[name] = existing; + matched.Add(existing); + } + } + + if (conflicts.Count > 0) + return PartsPaste.Refuse(target, conflicts.Count == 1 + ? $"This nest already has a different drawing named '{conflicts[0]}'. Rename one of them first." + : "This nest already has different drawings with these names; rename them first:" + + Environment.NewLine + string.Join(Environment.NewLine, conflicts.Select(n => "- " + n))); + + var added = new List(); + if (missing.Count > 0) + { + var copies = new NestReader(new MemoryStream(drawingsArchive, writable: false)).Read().Drawings + .ToDictionary(d => d.Name ?? "", StringComparer.Ordinal); + // The next palette slots, as reopening the nest would give them. + var slot = target.Drawings.Count(d => !d.IsCutOff); + foreach (var name in missing) + { + // Read from an archive with no plates: nothing is nested yet. + var copy = copies[name]; + if (!copy.HasCustomColor) + copy.Color = Drawing.GetPartColor(slot); + slot++; + map[name] = copy; + added.Add(copy); + } + } + + var placed = parts.Select(p => p.Part.CloneFor(map[p.DrawingName])).ToList(); + return new PartsPaste(target, added, matched, placed, CommonLines); + } + + private static string GeometryKey(Drawing drawing, Units units) => + DrawingPackage.GeometryKey(DrawingPackage.Write(drawing, units)); + + private static string UnitName(Units units) => units.ToString().ToLowerInvariant(); + } + + /// + /// How enter one nest: the drawings to add, the drawings it already + /// has, and the parts bound to them at the positions they were copied from; or a refusal. + /// + public sealed class PartsPaste + { + private bool drawingsAdded; + + internal PartsPaste(Nest nest, IReadOnlyList added, IReadOnlyList matched, + IReadOnlyList parts, IReadOnlyList<(int[] Members, double Kerf)> commonLines) + { + Nest = nest; + AddedDrawings = added; + MatchedDrawings = matched; + Parts = parts; + CommonLines = commonLines; + Refusal = ""; + } + + private PartsPaste(Nest nest, string refusal) + { + Nest = nest; + AddedDrawings = Array.Empty(); + MatchedDrawings = Array.Empty(); + Parts = Array.Empty(); + CommonLines = Array.Empty<(int[], double)>(); + Refusal = refusal; + } + + internal static PartsPaste Refuse(Nest nest, string refusal) => new(nest, refusal); + + public Nest Nest { get; } + + /// Exact copies of drawings the nest lacks, which adds. + public IReadOnlyList AddedDrawings { get; } + + /// The nest's own drawings the copied parts turned out to be. + public IReadOnlyList MatchedDrawings { get; } + + /// The copied parts bound to this nest's drawings, where they were copied from; not on any plate. + public IReadOnlyList Parts { get; } + + /// The common-line groups among , by index. + public IReadOnlyList<(int[] Members, double Kerf)> CommonLines { get; } + + /// Why nothing may be pasted; empty unless . + public string Refusal { get; } + + public bool IsRefused => Refusal.Length > 0; + + /// Adds to the nest; call before placing any part, once. + public void AddDrawings() + { + if (IsRefused) + throw new InvalidOperationException(Refusal); + if (drawingsAdded) + return; + foreach (var drawing in AddedDrawings) + { + if (!Nest.Drawings.Add(drawing)) + throw new InvalidOperationException($"This nest already has a drawing named '{drawing.Name}'."); + } + drawingsAdded = true; + } + + /// + /// Adds the drawings when they are not yet added and places a copy of every part on + /// exactly where it was copied from, joined in its common-line + /// groups again. Returns the placed parts. + /// + public IReadOnlyList PlaceInPlace(Plate plate) + { + ArgumentNullException.ThrowIfNull(plate); + AddDrawings(); + var placed = Parts.Select(p => (Part)p.Clone()).ToList(); + placed.ForEach(plate.Parts.Add); + foreach (var (members, kerf) in CommonLines) + plate.JoinCommonLine(members.Select(i => placed[i]), kerf); + return placed; + } + } +} diff --git a/OpenNest.WinForms.Tests/Forms/UndoRecordingTests.cs b/OpenNest.WinForms.Tests/Forms/UndoRecordingTests.cs index bb2516f3..2afb5db2 100644 --- a/OpenNest.WinForms.Tests/Forms/UndoRecordingTests.cs +++ b/OpenNest.WinForms.Tests/Forms/UndoRecordingTests.cs @@ -568,6 +568,94 @@ public class UndoRecordingTests Assert.Equal(0, env.Editor.History.UndoCount); }); + // Copying parts between nests + + [Fact] + public void PasteInPlaceIntoAnotherNestRecordsOneEntry() => UndoTestEnv.Run(env => + { + CopyPlateOne(env); + using var target = OpenOtherNest(env); + + var selected = 0; + target.AssertOneUndoableEdit("Paste in Place", () => + { + Assert.True(env.Host.PasteCopiedParts(inPlace: true)); + selected = target.View.SelectedParts.Count; + }); + + var copy = target.Nest.Drawings.Single(d => d.Name == "square"); + Assert.NotSame(env.Nest.Drawings.Single(), copy); + var parts = target.Nest.Plates[0].Parts; + Assert.Equal(new[] { new Vector(5, 5), new Vector(25, 5) }, parts.Select(p => p.Location)); + Assert.All(parts, p => Assert.Same(copy, p.BaseDrawing)); + Assert.Equal(2, selected); + Assert.Equal(2, env.Nest.Plates[0].Parts.Count); + }); + + [Fact] + public void PasteIntoAnotherNestAddsTheDrawingsThenPlacesWithTheCursor() => UndoTestEnv.Run(env => + { + CopyPlateOne(env); + using var target = OpenOtherNest(env); + + target.AssertOneUndoableEdit("Paste", () => Assert.True(env.Host.PasteCopiedParts(inPlace: false))); + // Undo and Redo end the placing; pasting again finds the drawing already added. + var entries = target.Env.Editor.History.UndoCount; + Assert.True(env.Host.PasteCopiedParts(inPlace: false)); + + Assert.Equal(entries, target.Env.Editor.History.UndoCount); + var copy = target.Nest.Drawings.Single(d => d.Name == "square"); + Assert.Empty(target.Nest.Plates[0].Parts); + Assert.IsType(target.View.Actions.CurrentAction); + Assert.All(target.View.SelectedParts, p => Assert.Same(copy, p.BasePart.BaseDrawing)); + target.AssertOneUndoableEdit("Add Parts", () => ((ActionClone)target.View.Actions.CurrentAction).Apply()); + Assert.Equal(2, target.Nest.Plates[0].Parts.Count); + }); + + [Fact] + public void PasteIsOffUntilPartsAreCopied() => UndoTestEnv.Run(env => + { + Assert.False(UndoTestEnv.MenuItem(env.Host, "mnuEditPaste").Enabled); + Assert.False(env.Host.PasteCopiedParts(inPlace: true)); + + CopyPlateOne(env); + + Assert.True(UndoTestEnv.MenuItem(env.Host, "mnuEditPaste").Enabled); + Assert.True(UndoTestEnv.MenuItem(env.Host, "mnuEditPasteInPlace").Enabled); + }); + + private static void CopyPlateOne(UndoTestEnv env) + { + env.Editor.PlateManager.LoadAt(0); + env.Editor.SelectAllParts(); + env.Click("EditCopy_Click"); + env.View.SetAction(typeof(ActionSelect)); + } + + private sealed class OtherNest(UndoTestEnv env) : IDisposable + { + public UndoTestEnv Env { get; } = env; + public Nest Nest => Env.Nest; + public PlateView View => Env.View; + public void AssertOneUndoableEdit(string label, System.Action edit) => Env.AssertOneUndoableEdit(label, edit); + public void Dispose() => Env.Editor.Dispose(); + } + + // A second nest window, active, on an empty plate of a nest with its own drawing. + private static OtherNest OpenOtherNest(UndoTestEnv env) + { + var nest = new Nest("other"); + nest.Drawings.Add(new Drawing("round", UndoTestEnv.Square(4))); + nest.CreatePlate().Size = new Geometry.Size(100, 100); + var editor = new EditNestForm(nest) { MdiParent = env.Host }; + editor.PlateView.SetOverlapAutoCheck(null); + editor.Show(); + editor.Activate(); + editor.PlateManager.LoadAt(0); + Assert.Same(editor, env.Host.ActiveMdiChild); + return new OtherNest(new UndoTestEnv(env.Host, editor)); + } + private static void Click(PlateView view, System.Drawing.Point at) { UndoTestEnv.Mouse(view, "OnMouseMove", MouseButtons.None, at); diff --git a/OpenNest/Actions/ActionClone.cs b/OpenNest/Actions/ActionClone.cs index 03c54af3..7c1503b4 100644 --- a/OpenNest/Actions/ActionClone.cs +++ b/OpenNest/Actions/ActionClone.cs @@ -25,6 +25,14 @@ namespace OpenNest.Actions : this(plateView, new List { new Part(drawing) }) { } public ActionClone(PlateView plateView, List partsToClone) + : this(plateView, partsToClone, CopiedCommonLines(plateView.Plate, partsToClone)) { } + + /// + /// Places copies of , which need not be on the plate (parts + /// pasted from another nest), joining each copy in , groups + /// given by index into . + /// + public ActionClone(PlateView plateView, List partsToClone, List<(int[] Members, double Kerf)> commonLines) : base(plateView) { plateView.KeyDown += plateView_KeyDown; @@ -41,7 +49,7 @@ namespace OpenNest.Actions for (int i = 0; i < partsToClone.Count; i++) parts.Add(LayoutPart.Create(partsToClone[i].Clone() as Part, plateView)); - commonLines = CopiedCommonLines(plateView.Plate, partsToClone); + this.commonLines = commonLines; SelectPreviews(); } diff --git a/OpenNest/Forms/MainForm.Designer.cs b/OpenNest/Forms/MainForm.Designer.cs index 2299eea1..870cdaf1 100644 --- a/OpenNest/Forms/MainForm.Designer.cs +++ b/OpenNest/Forms/MainForm.Designer.cs @@ -62,6 +62,7 @@ namespace OpenNest.Forms mnuEditCut = new System.Windows.Forms.ToolStripMenuItem(); mnuEditCopy = new System.Windows.Forms.ToolStripMenuItem(); mnuEditPaste = new System.Windows.Forms.ToolStripMenuItem(); + mnuEditPasteInPlace = new System.Windows.Forms.ToolStripMenuItem(); toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); mnuEditSelectAll = new System.Windows.Forms.ToolStripMenuItem(); mnuView = new System.Windows.Forms.ToolStripMenuItem(); @@ -351,7 +352,7 @@ namespace OpenNest.Forms // // mnuEdit // - mnuEdit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { mnuEditUndo, mnuEditRedo, mnuEditUndoSeparator, mnuEditCut, mnuEditCopy, mnuEditPaste, toolStripMenuItem4, mnuEditSelectAll }); + mnuEdit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { mnuEditUndo, mnuEditRedo, mnuEditUndoSeparator, mnuEditCut, mnuEditCopy, mnuEditPaste, mnuEditPasteInPlace, toolStripMenuItem4, mnuEditSelectAll }); mnuEdit.Name = "mnuEdit"; mnuEdit.Size = new System.Drawing.Size(39, 20); mnuEdit.Text = "&Edit"; @@ -401,9 +402,18 @@ namespace OpenNest.Forms mnuEditPaste.Enabled = false; mnuEditPaste.Name = "mnuEditPaste"; mnuEditPaste.ShortcutKeys = System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V; - mnuEditPaste.Size = new System.Drawing.Size(164, 22); + mnuEditPaste.Size = new System.Drawing.Size(212, 22); mnuEditPaste.Text = "Paste"; - mnuEditPaste.Visible = false; + mnuEditPaste.Click += EditPaste_Click; + // + // mnuEditPasteInPlace + // + mnuEditPasteInPlace.Enabled = false; + mnuEditPasteInPlace.Name = "mnuEditPasteInPlace"; + mnuEditPasteInPlace.ShortcutKeys = System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.V; + mnuEditPasteInPlace.Size = new System.Drawing.Size(212, 22); + mnuEditPasteInPlace.Text = "Paste in Place"; + mnuEditPasteInPlace.Click += EditPasteInPlace_Click; // // toolStripMenuItem4 // @@ -1462,6 +1472,7 @@ namespace OpenNest.Forms private System.Windows.Forms.ToolStripMenuItem mnuEditCut; private System.Windows.Forms.ToolStripMenuItem mnuEditCopy; private System.Windows.Forms.ToolStripMenuItem mnuEditPaste; + private System.Windows.Forms.ToolStripMenuItem mnuEditPasteInPlace; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem mnuEditSelectAll; private System.Windows.Forms.ToolStripMenuItem mnuView; diff --git a/OpenNest/Forms/MainForm.View.cs b/OpenNest/Forms/MainForm.View.cs index 02f3f544..9bc2bad2 100644 --- a/OpenNest/Forms/MainForm.View.cs +++ b/OpenNest/Forms/MainForm.View.cs @@ -1,8 +1,12 @@ using System; +using System.Collections.Generic; using System.Drawing; using System.Linq; +using System.Windows.Forms; using OpenNest.Actions; +using OpenNest.Controls; using OpenNest.Diagnostics; +using OpenNest.IO; namespace OpenNest.Forms { @@ -10,6 +14,9 @@ namespace OpenNest.Forms { #region Edit Menu Events + // What Copy or Cut last took, for Paste into this or any other open nest. + private CopiedParts copiedParts; + private void EditCut_Click(object sender, EventArgs e) { if (activeForm == null) @@ -20,6 +27,7 @@ namespace OpenNest.Forms if (selectedParts.Count > 0) { var partsToClone = selectedParts.Select(p => p.BasePart).ToList(); + RememberCopiedParts(partsToClone); activeForm.PlateView.SetAction(typeof(ActionClone), partsToClone); using var change = activeForm.BeginChange("Cut"); @@ -40,10 +48,116 @@ namespace OpenNest.Forms if (selectedParts.Count > 0) { var partsToClone = selectedParts.Select(p => p.BasePart).ToList(); + RememberCopiedParts(partsToClone); activeForm.PlateView.SetAction(typeof(ActionClone), partsToClone); } } + // Read before Cut removes the parts: their common-line groups go with them. + private void RememberCopiedParts(List parts) + { + var copy = CopiedParts.Capture(activeForm.Nest, activeForm.PlateView.Plate, parts); + if (copy == null) + return; + copiedParts = copy; + UpdatePasteMenu(); + } + + private static bool IsClipboardKey(Keys keyData) => + keyData is (Keys.Control | Keys.C) or (Keys.Control | Keys.X) or (Keys.Control | Keys.V) + or (Keys.Control | Keys.Shift | Keys.V); + + private void UpdatePasteMenu() + { + mnuEditPaste.Enabled = copiedParts != null; + mnuEditPasteInPlace.Enabled = copiedParts != null; + } + + private void EditPaste_Click(object sender, EventArgs e) => PasteCopiedParts(inPlace: false); + + private void EditPasteInPlace_Click(object sender, EventArgs e) => PasteCopiedParts(inPlace: true); + + /// + /// Pastes the copied parts into the active nest, which may be another nest than the one + /// they came from: drawings it lacks are added as exact copies first. Paste places them + /// with the cursor like Copy; Paste in Place puts them on the current plate where they + /// were copied from and selects them. See docs/copy-paste-parts.md. + /// + internal bool PasteCopiedParts(bool inPlace) + { + var form = activeForm; + var plate = form?.PlateView.Plate; + if (copiedParts == null || plate == null) + return false; + + var caption = inPlace ? "Paste in Place" : "Paste"; + if (IsNestFillBusy(form.Nest) || form.IsChangeInProgress) + { + MessageBox.Show(this, "Finish or cancel the current nesting or plate action first.", + caption, MessageBoxButtons.OK, MessageBoxIcon.Information); + return false; + } + + var paste = copiedParts.PlanPaste(form.Nest); + if (paste.IsRefused) + { + MessageBox.Show(this, paste.Refusal, caption, MessageBoxButtons.OK, MessageBoxIcon.Information); + return false; + } + + if (inPlace) + { + form.PlateView.SetAction(typeof(ActionSelect)); + using (var change = form.BeginChange(caption)) + { + change.MarkChanged(); + var placed = paste.PlaceInPlace(plate); + if (plate.CutOffs.Count > 0) + plate.RegenerateCutOffs(form.PlateView.CutOffSettings); + change.Complete(); + SelectPlacedParts(form.PlateView, placed); + } + } + else if (paste.AddedDrawings.Count > 0) + { + // The drawings come first, as their own step: each click then adds parts. + using var change = form.BeginChange(caption); + change.MarkChanged(); + paste.AddDrawings(); + change.Complete(); + } + + if (paste.AddedDrawings.Count > 0) + form.UpdateDrawingList(); + if (!inPlace) + form.PlateView.SetAction(typeof(ActionClone), paste.Parts.ToList(), paste.CommonLines.ToList()); + + statusLabel1.Text = DescribePaste(paste); + return true; + } + + private static void SelectPlacedParts(PlateView view, IReadOnlyList placed) + { + var set = placed.ToHashSet(); + view.Selection.DeselectAll(); + foreach (var layout in view.LayoutParts.Where(l => set.Contains(l.BasePart))) + view.Selection.Select(layout); + view.Selection.NotifySelectionChanged(); + view.Invalidate(); + } + + private static string DescribePaste(PartsPaste paste) + { + var count = paste.Parts.Count; + var text = $"Pasted {count} part{(count == 1 ? "" : "s")}"; + if (paste.AddedDrawings.Count > 0) + { + var added = paste.AddedDrawings.Count; + text += $"; added {added} drawing{(added == 1 ? "" : "s")} with their required quantities"; + } + return text; + } + private void EditSelectAll_Click(object sender, EventArgs e) => WithActive(f => f.SelectAllParts()); #endregion Edit Menu Events diff --git a/OpenNest/Forms/MainForm.cs b/OpenNest/Forms/MainForm.cs index fff399c6..4cd990c1 100644 --- a/OpenNest/Forms/MainForm.cs +++ b/OpenNest/Forms/MainForm.cs @@ -103,6 +103,9 @@ namespace OpenNest.Forms } if (ProcessUndoKeys(keyData)) return true; + // In a text box the clipboard keys cut, copy and paste its text, not parts. + if (IsClipboardKey(keyData) && KeepsOwnUndo(FocusedControl())) + return false; return base.ProcessCmdKey(ref msg, keyData); } diff --git a/docs/copy-paste-parts.md b/docs/copy-paste-parts.md new file mode 100644 index 00000000..9eb02d42 --- /dev/null +++ b/docs/copy-paste-parts.md @@ -0,0 +1,49 @@ +# Copying parts between nests + +Edit > Copy (Ctrl+C) and Cut (Ctrl+X) remember the selected parts as well as starting the +usual placement on the current plate. Edit > Paste (Ctrl+V) and Paste in Place (Ctrl+Shift+V) +put them into whichever nest window is active, the one they came from or another. This is how +two nests that should have been one (for example a thickness saved as 0.1196 instead of 0.12) +are joined by hand. + +| Piece | Where | +|---|---| +| Capture and paste plan (drawing matching, refusals) | `OpenNest.IO/CopiedParts.cs` | +| Menu commands, guards, status text | `OpenNest/Forms/MainForm.View.cs` (`PasteCopiedParts`) | +| Placing with the cursor | `OpenNest/Actions/ActionClone.cs` | +| Tests | `OpenNest.IO.Tests/CopiedPartsTests.cs`; menu and undo in `OpenNest.WinForms.Tests/Forms/UndoRecordingTests.cs` | + +## What is copied + +- Each part as it is: placed program, rotation, lead-ins and their lock, drawing pins off, cutting + parameters, and the common-line groups among the copied parts. +- Each part's drawing as the nest file saves it (`NestWriter`), so later edits, Undo or closing + the source nest do not change what is pasted. +- Cut-off parts are plate definitions and are never copied. + +## How a paste resolves drawings + +For each copied drawing, by name in the target nest: + +- **Missing**: an exact copy is added with everything the file saves, including its required + quantity, customer, priority and library link. A palette color takes the nest's next slot. +- **Same drawing** (equal `DrawingPackage.GeometryKey`: geometry and geometry-bound data, not + name, quantity, color or nesting settings): the nest's drawing is used and its required + quantity is kept, so pasting the parts of several plates brings the demand over once. +- **Different drawing with the same name**: the paste is refused; a nest cannot hold two drawings + with one name. Rename one first. + +Different units refuse the paste. Material and thickness are the nest's, not the drawing's, so +they never block it. + +## Placing and undo + +- Paste adds any missing drawings as one undo step ("Paste") and then places with the cursor like + Copy; each click is an "Add Parts" step. +- Paste in Place puts the parts on the current plate exactly where they were copied from, selects + them and records one "Paste in Place" step, drawings included. Nothing checks fit: the overlap + display shows any collisions. +- Both refuse while a fill or nest job runs on the target nest. + +In a text box (and the other controls that undo their own typing) Ctrl+C, Ctrl+X, Ctrl+V and +Ctrl+Shift+V edit the text and never reach the parts commands. diff --git a/docs/undo-redo.md b/docs/undo-redo.md index ebcec6b1..c0b993f0 100644 --- a/docs/undo-redo.md +++ b/docs/undo-redo.md @@ -20,7 +20,9 @@ once its entry point records it. Everything stored in the nest: -- parts: add, delete, cut, move, drag, nudge, rotate, align, push, center, expand spacing, fix spacing, clone; +- parts: add, delete, cut, move, drag, nudge, rotate, align, push, center, expand spacing, fix spacing, clone, paste and paste in place + (from this nest or another, with the drawings a paste adds; see + [copying parts between nests](copy-paste-parts.md)); - placement: fill, fill area, pattern tile, best-fit placement, Auto Nest, Clear Nest; - plates: add, remove, remove empty plates, Duplicate Plate (Ctrl+dragging a row in the Plates list or its right-click menu), Move Plate (dragging a row in the Plates list or