diff --git a/OpenNest.Desktop.Tests/Interaction/PlaceToolTests.cs b/OpenNest.Desktop.Tests/Interaction/PlaceToolTests.cs new file mode 100644 index 00000000..38b04396 --- /dev/null +++ b/OpenNest.Desktop.Tests/Interaction/PlaceToolTests.cs @@ -0,0 +1,548 @@ +using System.Collections.Generic; +using System.Linq; +using OpenNest.CNC; +using OpenNest.CutOffs; +using OpenNest.Desktop.Interaction; +using OpenNest.Engine.Fill; +using OpenNest.Geometry; + +namespace OpenNest.Desktop.Tests.Interaction; + +public class PlaceToolTests +{ + private readonly Plate plate = InteractionFixtures.Plate(); + private readonly TestToolHost host; + private readonly PlateEdits edits; + private int orderReads; + + public PlaceToolTests() + { + host = new TestToolHost(plate); + edits = new PlateEdits(host) { Tools = host.Tools }; + } + + private SettleOrder Order() + { + orderReads++; + return SettleOrder.ClosestToCorner; + } + + private static void AssertAt(Vector expected, Vector actual) => + Assert.True(expected.DistanceTo(actual) < 1e-9, $"expected {expected}, was {actual}"); + + private List RealParts() => plate.Parts.Where(p => !p.BaseDrawing.IsCutOff).ToList(); + + private PlaceTool Copy(params Part[] parts) + { + host.Selection.Clear(); + host.Selection.Select(parts); + return PlateClipboard.Copy(host, host.Tools, Order); + } + + private static Part Triangle(double x, double y) + { + var program = new Program(); + program.Codes.Add(new RapidMove(new Vector(0, 0))); + program.Codes.Add(new LinearMove(new Vector(40, 0))); + program.Codes.Add(new LinearMove(new Vector(0, 40))); + program.Codes.Add(new LinearMove(new Vector(0, 0))); + return new Part(new Drawing("triangle", program), new Vector(x, y)); + } + + private static Part Square(double size, double x, double y) => + new(new Drawing("square", InteractionFixtures.Rect(size, size)), new Vector(x, y)); + + [Fact] + public void Previews_follow_the_pointer_by_their_lower_left_corner() + { + var tool = Copy(plate.Parts[2]); + + Assert.Same(tool, host.Tools.Current); + Assert.Equal("Clone Parts", host.Tools.Status); + Assert.True(tool.PointerMoved(host.At(30, 60, ToolButton.None))); + + Assert.Equal(2, tool.Previews.Count); + AssertAt(new Vector(30, 60), tool.Previews.GetBoundingBox().Location); + AssertAt(new Vector(30, 60), tool.Previews[0].Location); + AssertAt(new Vector(40.05, 60), tool.Previews[1].Location); + AssertAt(new Vector(40, 0), plate.Parts[2].Location); + Assert.True(host.Invalidations > 0); + } + + [Fact] + public void A_move_to_the_same_screen_point_keeps_a_nudge() + { + var tool = Copy(plate.Parts[1]); + tool.PointerMoved(host.At(30, 60)); + edits.NudgeBy(5, 0); + AssertAt(new Vector(35, 60), tool.Previews[0].Location); + + tool.PointerMoved(host.At(30, 60)); + AssertAt(new Vector(35, 60), tool.Previews[0].Location); + + tool.PointerMoved(host.At(31, 60)); + AssertAt(new Vector(31, 60), tool.Previews[0].Location); + } + + [Fact] + public void A_click_adds_copies_and_one_undo_removes_them() + { + var recorder = host.RecordHistory(); + var source = plate.Parts[1]; + var tool = Copy(source); + var count = plate.Parts.Count; + tool.PointerMoved(host.At(30, 60)); + + Assert.True(tool.PointerPressed(host.At(30, 60))); + tool.PointerMoved(host.At(60, 60)); + Assert.True(tool.PointerPressed(host.At(60, 60))); + + Assert.Equal(count + 2, plate.Parts.Count); + AssertAt(new Vector(20, 0), source.Location); + AssertAt(new Vector(30, 60), plate.Parts[count].Location); + AssertAt(new Vector(60, 60), plate.Parts[count + 1].Location); + Assert.DoesNotContain(tool.Previews[0], plate.Parts); + Assert.Equal(new[] { "Add Part", "Add Part" }, host.ChangeLabels); + Assert.Same(tool, host.Tools.Current); + + recorder.Undo(); + Assert.Equal(count + 1, recorder.Document.Nest.Plates[0].Parts.Count); + } + + [Fact] + public void Placing_several_parts_is_labelled_add_parts() + { + var tool = Copy(plate.Parts[1], plate.Parts[4]); + tool.PointerMoved(host.At(30, 60)); + + tool.Apply(ToolModifiers.None); + + Assert.Equal(new[] { "Add Parts" }, host.ChangeLabels); + } + + [Fact] + public void Other_buttons_do_not_place() + { + var tool = Copy(plate.Parts[1]); + var count = plate.Parts.Count; + + Assert.False(tool.PointerPressed(host.At(30, 60, ToolButton.Right))); + Assert.False(tool.PointerPressed(host.At(30, 60, ToolButton.Middle))); + + Assert.Equal(count, plate.Parts.Count); + } + + [Theory] + [InlineData(1, false, false)] + [InlineData(2, true, false)] + [InlineData(3, true, true)] + [InlineData(4, false, true)] + public void Shift_settles_toward_the_quadrant_corner(int quadrant, bool right, bool up) + { + var empty = new Plate(new Size(100, 100)) { Quadrant = quadrant }; + var emptyHost = new TestToolHost(empty); + var tool = new PlaceTool(emptyHost, new[] { Square(10, 0, 0) }, Order); + var center = empty.WorkArea().Center; + tool.PointerMoved(emptyHost.At(center.X, center.Y)); + + tool.Apply(ToolModifiers.Shift); + + var area = empty.WorkArea(); + var box = empty.Parts.Single().BoundingBox; + Assert.Equal(right ? area.Right : area.Left, right ? box.Right : box.Left, 9); + Assert.Equal(up ? area.Top : area.Bottom, up ? box.Top : box.Bottom, 9); + } + + [Fact] + public void Shift_settles_on_geometry_and_ctrl_on_bounding_boxes() + { + var shiftLocation = SettleBesideTriangle(ToolModifiers.Shift, out var shiftPlate); + var ctrlLocation = SettleBesideTriangle(ToolModifiers.Control, out _); + var bothLocation = SettleBesideTriangle(ToolModifiers.Shift | ToolModifiers.Control, out _); + + // Pushed left onto the hypotenuse x + y = 40, inside the triangle's box but clear of it. + AssertAt(new Vector(10, 30), shiftLocation); + // Boxes only: it starts inside the triangle's box, so it never nests into the shape. + AssertAt(new Vector(30, 30), ctrlLocation); + AssertAt(shiftLocation, bothLocation); + Assert.Equal(2, shiftPlate.Parts.Count); + Assert.Equal(3, orderReads); + } + + private Vector SettleBesideTriangle(ToolModifiers modifiers, out Plate triangles) + { + triangles = new Plate(new Size(100, 100)); + triangles.Parts.Add(Triangle(0, 0)); + var trianglesHost = new TestToolHost(triangles); + var tool = new PlaceTool(trianglesHost, new[] { Square(10, 0, 0) }, Order); + tool.PointerMoved(trianglesHost.At(30, 30)); + tool.Apply(modifiers); + AssertAt(triangles.Parts[1].Location, tool.Previews[0].Location); + return triangles.Parts[1].Location; + } + + [Fact] + public void The_placement_order_is_read_at_each_settling_click() + { + var tool = Copy(plate.Parts[1]); + Assert.Equal(0, orderReads); + tool.PointerMoved(host.At(30, 60)); + + tool.Apply(ToolModifiers.None); + Assert.Equal(0, orderReads); + tool.Apply(ToolModifiers.Shift); + tool.Apply(ToolModifiers.Control); + + Assert.Equal(2, orderReads); + } + + [Fact] + public void Copied_common_lines_join_the_placed_copies_with_the_source_kerf() + { + var tool = Copy(plate.Parts[2]); + tool.PointerMoved(host.At(20, 60)); + + tool.Apply(ToolModifiers.None); + + var placed = plate.Parts.Skip(plate.Parts.Count - 2).ToList(); + var group = plate.CommonLineGroupOf(placed[0]); + Assert.NotNull(group); + Assert.True(group.Contains(placed[1])); + Assert.Equal(0.05, group.Kerf, 12); + Assert.Equal(2, plate.CommonLines.Count); + } + + [Fact] + public void A_click_rebuilds_the_cut_offs_around_the_copy() + { + var before = PlateEditsTests.CutOffStrokes(plate); + var tool = Copy(plate.Parts[1]); + tool.PointerMoved(host.At(75, 40)); + + tool.Apply(ToolModifiers.None); + + Assert.NotEqual(before, PlateEditsTests.CutOffStrokes(plate)); + var twin = InteractionFixtures.Plate(); + twin.Parts.Add(new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40))); + twin.RegenerateCutOffs(new CutOffSettings()); + Assert.Equal(PlateEditsTests.CutOffStrokes(twin), PlateEditsTests.CutOffStrokes(plate)); + } + + [Fact] + public void Delete_removes_the_sources_and_selected_parts_as_one_step() + { + var recorder = host.RecordHistory(); + var source = plate.Parts[1]; + var other = plate.Parts[4]; + var tool = Copy(source); + host.Selection.Select(other); + + edits.Delete(); + + Assert.DoesNotContain(source, plate.Parts); + Assert.DoesNotContain(other, plate.Parts); + Assert.Equal(3, RealParts().Count); + Assert.True(host.Selection.IsEmpty); + Assert.Equal(new[] { "Delete" }, host.ChangeLabels); + Assert.Equal(1, recorder.History.UndoCount); + Assert.Single(tool.Previews); + Assert.Same(tool, host.Tools.Current); + } + + [Fact] + public void Delete_after_a_cut_records_nothing() + { + var recorder = host.RecordHistory(); + host.Selection.Select(plate.Parts[1]); + var tool = PlateClipboard.Cut(host, host.Tools, Order); + Assert.Equal(1, recorder.History.UndoCount); + + tool.DeleteSources(); + + Assert.Equal(1, recorder.History.UndoCount); + Assert.Equal("Cut", recorder.History.UndoLabel); + } + + [Fact] + public void Delete_with_no_source_left_keeps_the_cut_offs() + { + var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40)); + plate.Parts.Add(crossing); + plate.RegenerateCutOffs(host.CutOffSettings); + host.Selection.Select(crossing); + var tool = PlateClipboard.Cut(host, host.Tools, Order); + var strokes = PlateEditsTests.CutOffStrokes(plate); + // A rebuild now would give the cut-offs new programs: an unrecorded change. + host.ThrowOnCutOffSettings = true; + + tool.DeleteSources(); + + Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate)); + } + + [Fact] + public void Delete_rebuilds_the_cut_offs() + { + var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40)); + var expected = PlateEditsTests.CutOffStrokes(plate); + plate.Parts.Add(crossing); + plate.RegenerateCutOffs(host.CutOffSettings); + var tool = Copy(crossing); + + tool.DeleteSources(); + + Assert.Equal(expected, PlateEditsTests.CutOffStrokes(plate)); + } + + [Fact] + public void Cut_removes_the_sources_in_one_step_without_rebuilding_cut_offs() + { + var recorder = host.RecordHistory(); + var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40)); + plate.Parts.Add(crossing); + plate.RegenerateCutOffs(host.CutOffSettings); + var strokes = PlateEditsTests.CutOffStrokes(plate); + recorder.Reset(); + host.Selection.Select(crossing); + host.Selection.Select(plate.Parts[2]); + + var tool = PlateClipboard.Cut(host, host.Tools, Order); + + Assert.Same(tool, host.Tools.Current); + Assert.Equal(3, tool.Previews.Count); + Assert.DoesNotContain(crossing, plate.Parts); + Assert.Equal(3, RealParts().Count); + Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate)); + Assert.True(host.Selection.IsEmpty); + Assert.Equal(new[] { "Cut" }, host.ChangeLabels); + Assert.Equal(1, recorder.History.UndoCount); + + // The cut group is joined again among its copies. + tool.PointerMoved(host.At(10, 60)); + tool.Apply(ToolModifiers.None); + Assert.Single(plate.CommonLines); + + recorder.Undo(); + recorder.Undo(); + Assert.Equal(6, recorder.Document.Nest.Plates[0].Parts.Count(p => !p.BaseDrawing.IsCutOff)); + } + + [Fact] + public void Copy_and_cut_need_selected_parts_on_the_plate() + { + Assert.Null(PlateClipboard.Copy(host, host.Tools, Order)); + Assert.Null(PlateClipboard.Cut(host, host.Tools, Order)); + + host.Selection.Select(plate.Parts[1]); + plate.Parts.RemoveAt(1); + Assert.Null(PlateClipboard.Cut(host, host.Tools, Order)); + + Assert.IsType(host.Tools.Current); + Assert.Empty(host.ChangeLabels); + } + + [Fact] + public void Copy_keeps_the_sources_on_the_plate() + { + var count = plate.Parts.Count; + var tool = Copy(plate.Parts[1], plate.Parts[4]); + + Assert.Equal(count, plate.Parts.Count); + Assert.Equal(2, tool.Previews.Count); + Assert.Empty(host.ChangeLabels); + } + + [Fact] + public void Edits_move_the_previews_without_an_undo_step() + { + var recorder = host.RecordHistory(); + var tool = Copy(plate.Parts[1]); + tool.PointerMoved(host.At(30, 60)); + var before = RealParts().Select(p => p.Location).ToList(); + var strokes = PlateEditsTests.CutOffStrokes(plate); + Assert.True(edits.HasPartsToEdit); + + edits.Nudge(PushDirection.Right); + AssertAt(new Vector(40, 60), tool.Previews[0].Location); + edits.Push(PushDirection.Down); + AssertAt(new Vector(40, 10), tool.Previews[0].Location); + edits.Step(PushDirection.Up); + // A step adds a hair over the part's height. + Assert.True(new Vector(40, 20).DistanceTo(tool.Previews[0].Location) < 1e-4); + tool.Previews[0].Offset(new Vector(36, 0)); + // Rebuilding cut-offs would throw: previews are not on the plate. + host.ThrowOnCutOffSettings = true; + edits.RotateQuarterTurn(); + edits.RotateByWheel(1, fine: false); + + Assert.True(new Vector(76, 20).DistanceTo(tool.Previews[0].BoundingBox.Location) < 1e-4); + Assert.NotEqual(0, tool.Previews[0].Rotation, 6); + Assert.Equal(before, RealParts().Select(p => p.Location).ToList()); + Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate)); + Assert.Empty(host.ChangeLabels); + Assert.False(recorder.CanUndo); + } + + [Fact] + public void Without_tools_or_a_place_tool_edits_move_the_selection() + { + Assert.False(edits.HasPartsToEdit); + host.Selection.Select(plate.Parts[4]); + Assert.True(edits.HasPartsToEdit); + + edits.NudgeBy(1, 0); + + AssertAt(new Vector(21, 20), plate.Parts[4].Location); + Assert.Equal(new[] { "Nudge" }, host.ChangeLabels); + } + + [Fact] + public void Locked_edits_refuse_placing_deleting_cutting_and_copying() + { + var tool = Copy(plate.Parts[1]); + tool.PointerMoved(host.At(30, 60)); + var count = plate.Parts.Count; + host.Selection.Select(plate.Parts[4]); + host.EditsLocked = true; + + Assert.False(tool.PointerPressed(host.At(30, 60))); + // WinForms raises no mouse move while locked, so the copy stays put. + Assert.False(tool.PointerMoved(host.At(50, 20))); + tool.Apply(ToolModifiers.None); + tool.DeleteSources(); + edits.Delete(); + edits.NudgeBy(5, 0); + Assert.Null(PlateClipboard.Copy(host, host.Tools, Order)); + Assert.Null(PlateClipboard.Cut(host, host.Tools, Order)); + + Assert.Equal(count, plate.Parts.Count); + AssertAt(new Vector(30, 60), tool.Previews[0].Location); + Assert.Same(tool, host.Tools.Current); + Assert.Empty(host.ChangeLabels); + } + + [Fact] + public void Without_a_plate_a_click_does_nothing() + { + var tool = Copy(plate.Parts[1]); + host.Plate = null; + + Assert.False(tool.PointerPressed(host.At(30, 60))); + tool.Apply(ToolModifiers.None); + tool.DeleteSources(); + + Assert.Empty(host.ChangeLabels); + } + + [Fact] + public void The_tool_survives_a_plate_change_with_its_previews() + { + var tool = Copy(plate.Parts[2]); + var other = new Plate(new Size(100, 100)); + host.Plate = other; + host.Selection.Plate = other; + + host.Tools.OnPlateChanged(); + + Assert.Same(tool, host.Tools.Current); + Assert.Equal(2, tool.Previews.Count); + tool.PointerMoved(host.At(10, 10)); + tool.Apply(ToolModifiers.None); + Assert.Equal(2, other.Parts.Count); + Assert.Single(other.CommonLines); + } + + [Fact] + public void A_failing_settle_opens_no_step() + { + host.RecordHistory(); + host.Selection.Select(plate.Parts[1]); + var tool = new PlaceTool(host, host.Selection.Parts.ToList(), + () => throw new System.InvalidOperationException("settings unreadable")); + host.Tools.SetTool(tool); + var count = RealParts().Count; + + Assert.Throws(() => tool.Apply(ToolModifiers.Shift)); + + // Nothing touched the nest, so no step opened and no restore replaced its objects. + Assert.Empty(host.ChangeLabels); + Assert.Same(plate, host.Recorder.Document.Nest.Plates[0]); + Assert.Equal(count, RealParts().Count); + } + + [Fact] + public void A_failing_cut_off_rebuild_rolls_the_placement_back() + { + var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40)); + plate.Parts.Add(crossing); + plate.RegenerateCutOffs(host.CutOffSettings); + var recorder = host.RecordHistory(); + var count = RealParts().Count; + var tool = Copy(plate.Parts[2]); + host.ThrowOnCutOffSettings = true; + + Assert.ThrowsAny(() => tool.Apply(ToolModifiers.None)); + + Assert.Equal(0, recorder.History.UndoCount); + Assert.Equal(count, + recorder.Document.Nest.Plates[0].Parts.Count(p => !p.BaseDrawing.IsCutOff)); + // Whether the tool survives is the view's call: a rollback swaps the nest in, and the + // Avalonia view then ends the tool, as WinForms does. + } + + [Fact] + public void A_failing_cut_off_rebuild_rolls_the_delete_back() + { + var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40)); + plate.Parts.Add(crossing); + plate.RegenerateCutOffs(host.CutOffSettings); + var recorder = host.RecordHistory(); + var count = RealParts().Count; + var tool = Copy(crossing); + host.ThrowOnCutOffSettings = true; + + Assert.ThrowsAny(() => tool.DeleteSources()); + + Assert.Equal(0, recorder.History.UndoCount); + Assert.Equal(count, + recorder.Document.Nest.Plates[0].Parts.Count(p => !p.BaseDrawing.IsCutOff)); + } + + [Fact] + public void Turning_the_copy_after_a_click_leaves_the_placed_part() + { + var tool = Copy(plate.Parts[2]); + tool.PointerMoved(host.At(60, 60)); + tool.Apply(ToolModifiers.None); + var placed = plate.Parts[^1]; + var rotation = placed.Rotation; + var location = placed.Location; + + edits.RotateQuarterTurn(); + edits.NudgeBy(5, 0); + + Assert.Equal(rotation, placed.Rotation); + AssertAt(location, placed.Location); + } + + [Fact] + public void A_second_escape_resumes_the_tool() + { + var tool = Copy(plate.Parts[1]); + + host.Tools.Escape(); + host.Tools.Escape(); + + Assert.Same(tool, host.Tools.Current); + } + + [Fact] + public void Escape_ends_the_tool() + { + Copy(plate.Parts[1]); + + host.Tools.Escape(); + + Assert.IsType(host.Tools.Current); + } +} diff --git a/OpenNest.Desktop/Interaction/PlaceTool.cs b/OpenNest.Desktop/Interaction/PlaceTool.cs new file mode 100644 index 00000000..696cbead --- /dev/null +++ b/OpenNest.Desktop/Interaction/PlaceTool.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using OpenNest.Desktop.Rendering; +using OpenNest.Engine.Fill; +using OpenNest.Geometry; + +namespace OpenNest.Desktop.Interaction; + +/// +/// The WinForms Clone Parts action, toolkit-neutral: copies of the source parts follow the +/// pointer (their combined lower-left corner at it) and each left click places another copy on +/// the plate, as one "Add Part"/"Add Parts" undo step. Shift settles the copy toward the plate's +/// quadrant corner on the parts' geometry; Ctrl alone settles it on bounding boxes only. Copied +/// common-line groups are joined again among the placed copies, and cut-offs are rebuilt. The +/// tool stays active until Escape and survives a plate change; nudges, +/// pushes and rotates its while it is active, and its Delete removes the +/// sources (). +/// +public sealed class PlaceTool : PlateTool +{ + private readonly List previews; + private readonly List sources; + private readonly List<(int[] Members, double Kerf)> commonLines; + private readonly Func placementOrder; + private ScreenPoint? restingPoint; + + /// The parts copied; kept so Delete can remove them. + /// + /// Which way Shift+click and Ctrl+click settle the copy, read at each click so a changed + /// setting applies without restarting the tool. + /// + public PlaceTool( + IPlateToolHost host, IReadOnlyList sources, Func placementOrder) + : base(host) + { + ArgumentNullException.ThrowIfNull(sources); + ArgumentNullException.ThrowIfNull(placementOrder); + this.placementOrder = placementOrder; + this.sources = sources.ToList(); + previews = this.sources.Select(source => source.Clone() as Part).ToList(); + commonLines = CopiedCommonLines(host.Plate, this.sources); + } + + public override string Name => "Clone Parts"; + + public override bool IsBusy => false; + + public override bool SurvivesPlateChange => true; + + /// The copies following the pointer; they are not on the plate. + public IReadOnlyList Previews => previews; + + public override void Cancel() { } + + public override void OnPlateChanged() => Host.Invalidate(); + + // The common-line groups among the copied parts, by index into the copy, so each placement + // joins its copies the same way. Read now: Cut removes the sources, and their groups, next. + private static List<(int[] Members, double Kerf)> CopiedCommonLines( + Plate plate, List copied) + { + var groups = new List<(int[] Members, double Kerf)>(); + if (plate == null) + return groups; + + foreach (var group in plate.CommonLines) + { + var members = Enumerable.Range(0, copied.Count) + .Where(i => group.Contains(copied[i])) + .ToArray(); + if (members.Length >= 2) + groups.Add((members, group.Kerf)); + } + + return groups; + } + + /// + /// Moves the previews' lower-left corner to the pointer. A move to the screen point last seen + /// is ignored, as WinForms ignores the mouse moves posted when a dialog opens or closes, so + /// an arrow-key nudge of the previews is not thrown away. + /// + public override bool PointerMoved(ToolPointer pointer) + { + // The WinForms view raises no mouse move while its edits are locked. + if (Host.EditsLocked) + return false; + if (restingPoint == pointer.Screen) + return true; + + restingPoint = pointer.Screen; + if (previews.Count > 0) + { + var offset = pointer.World - previews.GetBoundingBox().Location; + foreach (var preview in previews) + preview.Offset(offset); + } + Host.Invalidate(); + return true; + } + + public override bool PointerPressed(ToolPointer pointer) + { + if (pointer.Button != ToolButton.Left || Host.Plate == null || Host.EditsLocked) + return false; + Apply(pointer.Modifiers); + return true; + } + + /// + /// Places a copy of the previews on the plate (see the class summary); the previews stay + /// where they settled, so the next click places another copy beside this one. + /// + public void Apply(ToolModifiers modifiers) + { + var plate = Host.Plate; + if (plate == null || Host.EditsLocked || previews.Count == 0) + return; + + // Settling moves only the previews, which are not on the nest, so it runs before the + // step opens: if reading the order or settling throws, there is nothing to roll back. + var shift = (modifiers & ToolModifiers.Shift) == ToolModifiers.Shift; + var boxesOnly = !shift && (modifiers & ToolModifiers.Control) == ToolModifiers.Control; + if (shift || boxesOnly) + { + var (horizontal, vertical) = SettleDirections(plate.Quadrant); + Compactor.SettlePlacement(previews, plate, horizontal, vertical, + order: placementOrder(), boundingBoxesOnly: boxesOnly); + Host.Invalidate(); + } + + using var change = Host.BeginChange(previews.Count == 1 ? "Add Part" : "Add Parts"); + change.MarkChanged(); + var placed = previews.Select(preview => preview.Clone() as Part).ToList(); + foreach (var part in placed) + plate.Parts.Add(part); + foreach (var (members, kerf) in commonLines) + plate.JoinCommonLine(members.Select(i => placed[i]), kerf); + + if (plate.CutOffs.Count > 0) + plate.RegenerateCutOffs(Host.CutOffSettings); + Host.Invalidate(); + change.Complete(); + } + + /// + /// Removes the source parts, and any parts selected on the plate (Select All while placing), + /// as one "Delete" undo step; the previews stay. Recorded only when any of them was still on + /// the plate. + /// + public void DeleteSources() + { + var plate = Host.Plate; + if (plate == null || Host.EditsLocked) + return; + + var doomed = sources.Concat(Host.Selection.Parts).ToList(); + using var change = Host.BeginChange("Delete"); + var removing = doomed.Any(plate.Parts.Contains); + if (removing) + change.MarkChanged(); + foreach (var part in doomed) + plate.Parts.Remove(part); + + // Only after a removal: a rebuild gives the cut-offs new programs, which would count as + // an unrecorded change (WinForms rebuilds either way). + if (removing && plate.CutOffs.Count > 0) + plate.RegenerateCutOffs(Host.CutOffSettings); + Host.Selection.Clear(); + Host.Invalidate(); + change.Complete(); + } + + // Toward the quadrant's origin corner, as WinForms: 1 lower-left, 2 lower-right, + // 3 upper-right, 4 upper-left. + private static (PushDirection Horizontal, PushDirection Vertical) SettleDirections( + int quadrant) => + quadrant switch + { + 2 => (PushDirection.Right, PushDirection.Down), + 3 => (PushDirection.Right, PushDirection.Up), + 4 => (PushDirection.Left, PushDirection.Up), + _ => (PushDirection.Left, PushDirection.Down), + }; +} diff --git a/OpenNest.Desktop/Interaction/PlateClipboard.cs b/OpenNest.Desktop/Interaction/PlateClipboard.cs new file mode 100644 index 00000000..279d09c5 --- /dev/null +++ b/OpenNest.Desktop/Interaction/PlateClipboard.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using OpenNest.Engine.Fill; + +namespace OpenNest.Desktop.Interaction; + +/// +/// Edit > Cut and Copy, toolkit-neutral: both start a with the parts +/// selected on the plate, in selection order. Neither does anything without a plate or selected +/// parts, or while the host's edits are locked. +/// +public static class PlateClipboard +{ + /// + /// Starts placing copies of the selected parts; null when nothing was started. + /// + public static PlaceTool Copy( + IPlateToolHost host, PlateToolManager tools, Func order) + { + var sources = Sources(host, tools); + if (sources == null) + return null; + var tool = new PlaceTool(host, sources, order); + tools.SetTool(tool); + return tool; + } + + /// + /// Starts placing copies of the selected parts, then removes them from the plate as one + /// "Cut" undo step. As in WinForms, the plate's cut-offs are not rebuilt here. + /// + public static PlaceTool Cut( + IPlateToolHost host, PlateToolManager tools, Func order) + { + var sources = Sources(host, tools); + if (sources == null) + return null; + // The tool reads the sources' common-line groups, which their removal ends. + var tool = new PlaceTool(host, sources, order); + tools.SetTool(tool); + + var plate = host.Plate; + using var change = host.BeginChange("Cut"); + change.MarkChanged(); + foreach (var part in sources) + plate.Parts.Remove(part); + host.Selection.Clear(); + host.Invalidate(); + change.Complete(); + return tool; + } + + private static List Sources(IPlateToolHost host, PlateToolManager tools) + { + ArgumentNullException.ThrowIfNull(host); + ArgumentNullException.ThrowIfNull(tools); + if (host.Plate == null || host.EditsLocked) + return null; + host.Selection.Prune(); + var sources = host.Selection.Parts.ToList(); + return sources.Count == 0 ? null : sources; + } +} diff --git a/OpenNest.Desktop/Interaction/PlateEdits.cs b/OpenNest.Desktop/Interaction/PlateEdits.cs index 1e90dc8f..d5828dc1 100644 --- a/OpenNest.Desktop/Interaction/PlateEdits.cs +++ b/OpenNest.Desktop/Interaction/PlateEdits.cs @@ -5,6 +5,7 @@ using System.Runtime.CompilerServices; using OpenNest.Engine.Fill; using OpenNest.Geometry; using OpenNest.Math; +using OpenNest.Undo; namespace OpenNest.Desktop.Interaction; @@ -14,6 +15,12 @@ namespace OpenNest.Desktop.Interaction; /// same parts, and wheel rotations, undo as one. Every edit does nothing without a plate or /// selected parts (Delete also acts on selected cut-offs alone) and redraws the view, and nothing /// at all while the host's edits are locked (). +/// +/// While a is active in , nudge, step, push and rotate +/// move its previews instead, which are not on the plate: no undo step is opened (WinForms +/// records an empty one) and cut-offs are not rebuilt. Delete then removes the tool's sources +/// (). +/// /// public sealed class PlateEdits { @@ -24,6 +31,21 @@ public sealed class PlateEdits public IPlateToolHost Host { get; } + /// + /// The view's tools, so edits can act on a place tool's previews; null for none. + /// + public PlateToolManager Tools { get; set; } + + /// + /// Whether nudge, push and rotate have parts to move: a place tool's previews, or selected + /// parts still on the plate. The view checks it before a middle click or Shift+wheel rotates. + /// + public bool HasPartsToEdit => + Placing is { Previews.Count: > 0 } + || (Host.Plate != null && Host.Selection.Parts.Any(Host.Plate.Parts.Contains)); + + private PlaceTool Placing => Tools?.Current as PlaceTool; + /// How far an arrow-key nudge moves the selection, in plate units. public double OffsetIncrement { get; set; } = 10; @@ -45,6 +67,11 @@ public sealed class PlateEdits var plate = Host.Plate; if (plate == null || Host.EditsLocked) return; + if (Placing is { } placing) + { + placing.DeleteSources(); + return; + } var selection = Host.Selection; selection.Prune(); var parts = selection.Parts.ToList(); @@ -85,10 +112,10 @@ public sealed class PlateEdits /// Moves the selection by (, ). public void NudgeBy(double dx, double dy) { - if (!TryGetSelectedParts(out var plate, out var parts)) + if (!TryGetEditParts(out var plate, out var parts, out var previews)) return; - using var change = Host.BeginChange("Nudge", new SelectionKey("Nudge", plate, parts)); + using var change = BeginEdit(previews, "Nudge", new SelectionKey("Nudge", plate, parts)); change.MarkChanged(); foreach (var part in parts) part.Offset(dx, dy); @@ -102,10 +129,10 @@ public sealed class PlateEdits /// public void Step(PushDirection direction) { - if (!TryGetSelectedParts(out var plate, out var parts)) + if (!TryGetEditParts(out var plate, out var parts, out var previews)) return; - using var change = Host.BeginChange("Nudge", new SelectionKey("Nudge", plate, parts)); + using var change = BeginEdit(previews, "Nudge", new SelectionKey("Nudge", plate, parts)); if (Compactor.Step(parts, plate, direction) > 0) change.MarkChanged(); Host.Invalidate(); @@ -117,10 +144,10 @@ public sealed class PlateEdits /// public void Push(PushDirection direction) { - if (!TryGetSelectedParts(out var plate, out var parts)) + if (!TryGetEditParts(out var plate, out var parts, out var previews)) return; - using var change = Host.BeginChange("Push"); + using var change = BeginEdit(previews, "Push"); change.MarkChanged(); Compactor.Push(parts, plate, direction); Host.Invalidate(); @@ -133,10 +160,10 @@ public sealed class PlateEdits /// public void Rotate(double radians, bool coalesce = false) { - if (!TryGetSelectedParts(out var plate, out var parts)) + if (!TryGetEditParts(out var plate, out var parts, out var previews)) return; - using var change = Host.BeginChange("Rotate", + using var change = BeginEdit(previews, "Rotate", coalesce ? new SelectionKey("Rotate", plate, parts) : null); change.MarkChanged(); var bounds = parts.GetBoundingBox(); @@ -149,7 +176,7 @@ public sealed class PlateEdits foreach (var part in parts) part.Offset(diff); - if (plate.CutOffs.Count > 0) + if (!previews && plate.CutOffs.Count > 0) plate.RegenerateCutOffs(Host.CutOffSettings); Host.Invalidate(); change.Complete(); @@ -173,17 +200,29 @@ public sealed class PlateEdits Rotate(angle, coalesce: true); } - private bool TryGetSelectedParts(out Plate plate, out List parts) + // The parts an edit moves: a place tool's previews (previews is true), else the selection. + private bool TryGetEditParts(out Plate plate, out List parts, out bool previews) { plate = Host.Plate; parts = null; + previews = false; if (plate == null || Host.EditsLocked) return false; + if (Placing is { } placing) + { + previews = true; + parts = placing.Previews.ToList(); + return parts.Count > 0; + } Host.Selection.Prune(); parts = Host.Selection.Parts.ToList(); return parts.Count > 0; } + // Previews are not on the nest, so moving them opens no undo step. + private ChangeScope BeginEdit(bool previews, string label, object coalesceKey = null) => + previews ? ChangeScope.Detached() : Host.BeginChange(label, coalesceKey); + /// /// Equal for the same edit of the same parts, in the same order, on the same plate, so /// repeated nudges or wheel turns coalesce into one undo entry.