diff --git a/OpenNest.WinForms.Tests/Forms/UndoRedoTests.cs b/OpenNest.WinForms.Tests/Forms/UndoRedoTests.cs new file mode 100644 index 00000000..95294ef5 --- /dev/null +++ b/OpenNest.WinForms.Tests/Forms/UndoRedoTests.cs @@ -0,0 +1,407 @@ +using System.Drawing; +using System.Reflection; +using System.Windows.Forms; +using OpenNest.Controls; +using OpenNest.Forms; +using OpenNest.Geometry; +using Size = OpenNest.Geometry.Size; + +namespace OpenNest.WinForms.Tests.Forms; + +// Undo swaps whole nests into the window. Reads Application.OpenForms through the busy +// guards, so it must not overlap fill-lifetime tests. +[Collection("Fill operation lifetime")] +public class UndoRedoTests +{ + [Fact] + public void UndoKeepsThePlateTheViewportAndTheSelection() => Run(env => + { + var editor = env.Editor; + var view = editor.PlateView; + editor.PlateManager.LoadAt(1); + view.SelectAll(); + var before = view.Plate.Parts.Select(p => p.Location).ToArray(); + view.Selection.NudgeSelected(5, 0); + view.RestoreViewport((2.5f, new PointF(13, 17))); + + Assert.True(env.Host.TryUndo(editor)); + + Assert.Equal(1, editor.PlateManager.CurrentIndex); + Assert.Same(editor.Nest.Plates[1], view.Plate); + Assert.Equal((2.5f, new PointF(13, 17)), view.CaptureViewport()); + Assert.Equal(before, view.Plate.Parts.Select(p => p.Location).ToArray()); + Assert.Equal(view.Plate.Parts, view.SelectedParts.Select(p => p.BasePart)); + Assert.All(view.SelectedParts, layout => Assert.True(layout.IsSelected)); + }); + + [Fact] + public void UndoKeepsTheNestIdentityAndTheDocument() => Run(env => + { + var editor = env.Editor; + var document = editor.Document; + editor.PlateManager.LoadAt(0); + editor.PlateView.SelectAll(); + editor.PlateView.Selection.DeleteSelected(); + editor.Nest.Name = "renamed"; + editor.Nest.Status = NestStatus.HasBeenCut; + + Assert.True(env.Host.TryUndo(editor)); + + Assert.Same(document, editor.Document); + Assert.Equal("renamed", editor.Nest.Name); + Assert.Equal(NestStatus.HasBeenCut, editor.Nest.Status); + Assert.Equal(2, editor.Nest.Plates[0].Parts.Count); + }); + + [Fact] + public void EachCommandRecordsOneEntryAndRedoRepeatsIt() => Run(env => + { + var editor = env.Editor; + var view = editor.PlateView; + editor.PlateManager.LoadAt(0); + view.SelectAll(); + + view.RotateSelectedParts(System.Math.PI / 2); + Assert.Equal(1, editor.History.UndoCount); + Assert.Equal("Rotate", editor.History.UndoLabel); + + view.PushSelected(PushDirection.Left); + view.AlignSelected(AlignType.Bottom); + view.Selection.DeleteSelected(); + Assert.Equal(4, editor.History.UndoCount); + Assert.Equal("Delete", editor.History.UndoLabel); + Assert.Empty(editor.Nest.Plates[0].Parts); + + Assert.True(env.Host.TryUndo(editor)); + Assert.Equal(2, editor.Nest.Plates[0].Parts.Count); + Assert.Equal("Delete", editor.History.RedoLabel); + Assert.True(env.Host.TryRedo(editor)); + Assert.Empty(editor.Nest.Plates[0].Parts); + }); + + [Fact] + public void ACommandThatChangesNothingRecordsNothing() => Run(env => + { + var editor = env.Editor; + editor.PlateManager.LoadAt(0); + editor.PlateView.DeselectAll(); + + editor.PlateView.Selection.DeleteSelected(); + editor.PlateView.RotateSelectedParts(1); + + Assert.Equal(0, editor.History.UndoCount); + }); + + [Fact] + public void NudgesOfOneSelectionUndoAsOne() => Run(env => + { + var editor = env.Editor; + editor.PlateManager.LoadAt(0); + editor.PlateView.SelectAll(); + var start = editor.Nest.Plates[0].Parts[0].Location; + + for (var i = 0; i < 3; i++) + editor.PlateView.Selection.NudgeSelected(1, 0); + + Assert.Equal(1, editor.History.UndoCount); + Assert.Equal("Nudge", editor.History.UndoLabel); + Assert.True(env.Host.TryUndo(editor)); + Assert.Equal(start, editor.Nest.Plates[0].Parts[0].Location); + }); + + [Fact] + public void ADragRecordsOneEntry() => Run(env => + { + var editor = env.Editor; + var view = editor.PlateView; + editor.PlateManager.LoadAt(0); + view.ZoomToFit(); + var part = view.Plate.Parts[0]; + var start = part.Location; + var grab = view.PointWorldToControl(part.BoundingBox.Center); + + Mouse(view, "OnMouseMove", MouseButtons.None, grab); + Mouse(view, "OnMouseDown", MouseButtons.Left, grab); + for (var step = 1; step <= 5; step++) + Mouse(view, "OnMouseMove", MouseButtons.Left, new Point(grab.X + step * 4, grab.Y)); + Mouse(view, "OnMouseUp", MouseButtons.Left, new Point(grab.X + 20, grab.Y)); + + Assert.NotEqual(start, part.Location); + Assert.Equal(1, editor.History.UndoCount); + Assert.Equal("Move", editor.History.UndoLabel); + Assert.True(env.Host.TryUndo(editor)); + Assert.Equal(start, editor.Nest.Plates[0].Parts[0].Location); + }); + + [Fact] + public void AClickWithoutMovingRecordsNothing() => Run(env => + { + var editor = env.Editor; + var view = editor.PlateView; + editor.PlateManager.LoadAt(0); + view.ZoomToFit(); + var grab = view.PointWorldToControl(view.Plate.Parts[0].BoundingBox.Center); + + Mouse(view, "OnMouseMove", MouseButtons.None, grab); + Mouse(view, "OnMouseDown", MouseButtons.Left, grab); + Mouse(view, "OnMouseUp", MouseButtons.Left, grab); + + Assert.Single(view.SelectedParts); + Assert.Equal(0, editor.History.UndoCount); + }); + + [Fact] + public void AScopeLeftIncompleteRollsBack() => Run(env => + { + var editor = env.Editor; + var start = editor.Nest.Plates[0].Parts[0].Location; + + using (var change = editor.BeginChange("Broken")) + { + using (var inner = editor.BeginChange("Inner")) + { + inner.MarkChanged(); + editor.Nest.Plates[0].Parts[0].Offset(7, 0); + inner.Complete(); + } + // Not completed: an exception or a cancellation. + } + + Assert.Equal(start, editor.Nest.Plates[0].Parts[0].Location); + Assert.Equal(0, editor.History.UndoCount); + Assert.False(editor.IsChangeInProgress); + }); + + [Fact] + public void AnIncompleteInnerScopeRollsBackTheWholeEdit() => Run(env => + { + var editor = env.Editor; + var start = editor.Nest.Plates[0].Parts[0].Location; + + using (var change = editor.BeginChange("Outer")) + { + change.MarkChanged(); + editor.Nest.Plates[0].Parts[0].Offset(7, 0); + using (editor.BeginChange("Inner")) { } + change.Complete(); + } + + Assert.Equal(start, editor.Nest.Plates[0].Parts[0].Location); + Assert.Equal(0, editor.History.UndoCount); + }); + + [Fact] + public void AnUnrecordedEditBecomesItsOwnEntryBeforeUndo() => Run(env => + { + var editor = env.Editor; + editor.PlateManager.LoadAt(0); + editor.PlateView.SelectAll(); + editor.PlateView.RotateSelectedParts(System.Math.PI); + var rotated = editor.Nest.Plates[0].Parts[0].Location; + editor.Nest.Plates[0].Parts[0].Offset(3, 0); // An edit no scope recorded. + + Assert.True(env.Host.TryUndo(editor)); + + Assert.Equal(rotated, editor.Nest.Plates[0].Parts[0].Location); + Assert.Equal("Rotate", editor.History.UndoLabel); + Assert.Equal("Change", editor.History.RedoLabel); + }); + + [Fact] + public void UndoWaitsForAFillAndABackgroundSave() => Run(env => + { + var editor = env.Editor; + editor.PlateManager.LoadAt(0); + editor.PlateView.SelectAll(); + editor.PlateView.Selection.DeleteSelected(); + + SetBackingField(editor.PlateView, "IsFillInProgress", true); + try + { + Assert.True(env.Host.IsUndoBusy(editor)); + Assert.False(env.Host.TryUndo(editor)); + } + finally + { + SetBackingField(editor.PlateView, "IsFillInProgress", false); + } + + var storage = typeof(MainForm).GetField("storage", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(env.Host)!; + SetBackingField(storage, "IsSaving", true); + try + { + Assert.False(env.Host.TryUndo(editor)); + Assert.Empty(editor.Nest.Plates[0].Parts); + } + finally + { + SetBackingField(storage, "IsSaving", false); + } + + // A selection alone is not busy work for undo. + editor.PlateView.SelectAll(); + Assert.True(env.Host.TryUndo(editor)); + Assert.Equal(2, editor.Nest.Plates[0].Parts.Count); + }); + + [Fact] + public void TextEditorsKeepTheirOwnUndo() + { + using var panel = new Panel(); + var text = new TextBox(); + panel.Controls.Add(text); + using var numeric = new System.Windows.Forms.NumericUpDown(); + var edit = numeric.Controls.OfType().Single(); + using var list = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList }; + using var view = new PlateView(); + + Assert.True(MainForm.KeepsOwnUndo(text)); + Assert.True(MainForm.KeepsOwnUndo(edit)); + Assert.True(MainForm.KeepsOwnUndo(numeric)); + Assert.False(MainForm.KeepsOwnUndo(list)); + Assert.False(MainForm.KeepsOwnUndo(view)); + Assert.False(MainForm.KeepsOwnUndo(null)); + } + + [Fact] + public void CtrlZInAFocusedTextBoxLeavesTheNestAlone() => Run(env => + { + var editor = env.Editor; + editor.PlateManager.LoadAt(0); + editor.PlateView.SelectAll(); + editor.PlateView.Selection.DeleteSelected(); + var box = new TextBox(); + editor.Controls.Add(box); + box.Focus(); + Application.DoEvents(); + if (!box.Focused) + return; // No interactive focus in this session; KeepsOwnUndo covers the rule. + + var handled = (bool)typeof(MainForm).GetMethod("ProcessUndoKeys", BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(env.Host, new object[] { Keys.Control | Keys.Z })!; + + Assert.False(handled); + Assert.Empty(editor.Nest.Plates[0].Parts); + Assert.Equal(1, editor.History.UndoCount); + }); + + [Fact] + public void UndoWithAnEmptyPlateInTheMiddleLandsOnTheSamePlate() => Run(env => + { + var editor = env.Editor; + var nest = editor.Nest; + // Plates: 0 parts, 1 parts, 2 empty, 3 parts, then the empty sentinel. + Assert.Empty(nest.Plates[2].Parts); + editor.PlateManager.LoadAt(3); + editor.PlateView.SelectAll(); + var start = nest.Plates[3].Parts[0].Location; + editor.PlateView.Selection.NudgeSelected(0, 4); + + Assert.True(env.Host.TryUndo(editor)); + + // A copy that dropped the empty plate would shift this one to index 2. + Assert.Equal(5, editor.Nest.Plates.Count); + Assert.Equal(3, editor.PlateManager.CurrentIndex); + Assert.Same(editor.Nest.Plates[3], editor.PlateView.Plate); + Assert.Equal(start, Assert.Single(editor.PlateView.Plate.Parts).Location); + Assert.Empty(editor.Nest.Plates[2].Parts); + }); + + [Fact] + public void AddingAndRemovingPlatesUndo() => Run(env => + { + var editor = env.Editor; + var count = editor.Nest.Plates.Count; + editor.AddPlate(); + Assert.Equal("Add Plate", editor.History.UndoLabel); + Assert.True(env.Host.TryUndo(editor)); + Assert.Equal(count, editor.Nest.Plates.Count); + + editor.PlateManager.LoadAt(1); + editor.RemoveCurrentPlate(); + Assert.Equal(count - 1, editor.Nest.Plates.Count); + Assert.True(env.Host.TryUndo(editor)); + Assert.Equal(count, editor.Nest.Plates.Count); + Assert.Equal(1, editor.PlateManager.CurrentIndex); + }); + + [Fact] + public void TheEditMenuNamesTheNextUndoAndRedo() => Run(env => + { + var editor = env.Editor; + editor.PlateManager.LoadAt(0); + editor.PlateView.SelectAll(); + editor.PlateView.Selection.DeleteSelected(); + + var undo = MenuItem(env.Host, "mnuEditUndo"); + var redo = MenuItem(env.Host, "mnuEditRedo"); + Assert.Equal("Undo Delete", undo.Text); + Assert.True(undo.Enabled); + Assert.False(redo.Enabled); + + env.Host.TryUndo(editor); + Assert.Equal("Undo", undo.Text); + Assert.False(undo.Enabled); + Assert.Equal("Redo Delete", redo.Text); + Assert.True(redo.Enabled); + }); + + private sealed record Env(MainForm Host, EditNestForm Editor); + + private static void Run(Action body) => StaTestThread.Run(() => + { + using var host = new Host(); + host.Show(); + using var editor = new EditNestForm(BuildNest()) { MdiParent = host }; + editor.PlateView.SetOverlapAutoCheck(null); + editor.Show(); + editor.Activate(); + body(new Env(host, editor)); + }, TimeSpan.FromMinutes(1), "The STA test did not complete."); + + private static Nest BuildNest() + { + var nest = new Nest("undo"); + var square = new Drawing("square", Square()); + nest.Drawings.Add(square); + int[] partsPerPlate = { 2, 2, 0, 1 }; + foreach (var count in partsPerPlate) + { + var plate = nest.CreatePlate(); + plate.Size = new Size(100, 100); + for (var i = 0; i < count; i++) + plate.Parts.Add(new Part(square, new Vector(5 + i * 20, 5))); + } + return nest; + } + + private static ToolStripMenuItem MenuItem(MainForm host, string name) => + (ToolStripMenuItem)typeof(MainForm).GetField(name, BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(host)!; + + private static void Mouse(PlateView view, string method, MouseButtons button, Point location) => + typeof(PlateView).GetMethod(method, BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(view, new object[] { new MouseEventArgs(button, 1, location.X, location.Y, 0) }); + + private static void SetBackingField(object target, string property, object value) => + target.GetType() + .GetField($"<{property}>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic)! + .SetValue(target, value); + + private static CNC.Program Square() + { + var program = new CNC.Program(); + program.MoveTo(0, 0); + program.LineTo(0, 10); + program.LineTo(10, 10); + program.LineTo(10, 0); + program.LineTo(0, 0); + return program; + } + + private sealed class Host : MainForm + { + // No startup migrations/automatic new document, and no settings save at close. + protected override void OnLoad(EventArgs e) { } + protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { } + } +} diff --git a/OpenNest/Actions/Action.cs b/OpenNest/Actions/Action.cs index ba11a239..1d5562a4 100644 --- a/OpenNest/Actions/Action.cs +++ b/OpenNest/Actions/Action.cs @@ -42,5 +42,14 @@ namespace OpenNest.Actions public abstract void CancelAction(); public abstract bool IsBusy(); + + /// Whether Undo and Redo must wait: by default, while the action is busy. + public virtual bool BlocksUndo => IsBusy(); + + /// + /// Steps back within the action, for Ctrl+Z before the whole-nest Undo; false when the + /// action has nothing of its own to step back. + /// + public virtual bool TryUndoStep() => false; } } diff --git a/OpenNest/Actions/ActionClone.cs b/OpenNest/Actions/ActionClone.cs index 6a5f4bca..c3605ce7 100644 --- a/OpenNest/Actions/ActionClone.cs +++ b/OpenNest/Actions/ActionClone.cs @@ -5,6 +5,7 @@ using System.Windows.Forms; using OpenNest.Controls; using OpenNest.Engine.Fill; using OpenNest.Geometry; +using OpenNest.Undo; namespace OpenNest.Actions { @@ -66,13 +67,7 @@ namespace OpenNest.Actions break; case Keys.Delete: - foreach (var part in sourceParts) - plateView.Plate.Parts.Remove(part); - - if (plateView.Plate.CutOffs.Count > 0) - plateView.Plate.RegenerateCutOffs(plateView.CutOffSettings); - - plateView.Invalidate(); + DeleteSources(); break; case Keys.F: @@ -145,8 +140,25 @@ namespace OpenNest.Actions return false; } + private void DeleteSources() + { + using var change = plateView.BeginChange("Delete"); + if (sourceParts.Any(plateView.Plate.Parts.Contains)) + change.MarkChanged(); + foreach (var part in sourceParts) + plateView.Plate.Parts.Remove(part); + + if (plateView.Plate.CutOffs.Count > 0) + plateView.Plate.RegenerateCutOffs(plateView.CutOffSettings); + + plateView.Invalidate(); + change.Complete(); + } + public void Apply() { + using var change = plateView.BeginChange(parts.Count == 1 ? "Add Part" : "Add Parts"); + change.MarkChanged(); if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) { var movingParts = parts.Select(p => p.BasePart).ToList(); @@ -187,6 +199,7 @@ namespace OpenNest.Actions if (plateView.Plate.CutOffs.Count > 0) plateView.Plate.RegenerateCutOffs(plateView.CutOffSettings); + change.Complete(); } private void Fill() diff --git a/OpenNest/Actions/ActionSelect.cs b/OpenNest/Actions/ActionSelect.cs index 066c736c..d804bac3 100644 --- a/OpenNest/Actions/ActionSelect.cs +++ b/OpenNest/Actions/ActionSelect.cs @@ -3,6 +3,7 @@ using System.Drawing; using System.Windows.Forms; using OpenNest.Controls; using OpenNest.Geometry; +using OpenNest.Undo; namespace OpenNest.Actions { @@ -22,6 +23,9 @@ namespace OpenNest.Actions private Status status; + // Open from the press on a selected part to the release: a drag undoes as one move. + private ChangeScope drag; + public ActionSelect(PlateView plateView) : base(plateView) { @@ -43,6 +47,7 @@ namespace OpenNest.Actions public override void DisconnectEvents() { + EndDrag(); plateView.MouseDown -= plateView_MouseDown; plateView.MouseUp -= plateView_MouseUp; plateView.MouseMove -= plateView_MouseMove; @@ -51,6 +56,8 @@ namespace OpenNest.Actions public override void CancelAction() { + // Parts already dragged stay where they are, so the move is recorded. + EndDrag(); status = Status.SetFirstPoint; plateView.CutOffs.EndDrag(); @@ -64,6 +71,19 @@ namespace OpenNest.Actions || plateView.Selection.SelectedCutOffs.Count > 0; } + // A selection is not work in progress for undo; a part drag holds its own scope. + public override bool BlocksUndo => plateView.CutOffs.IsDragging; + + private void EndDrag() + { + var scope = drag; + drag = null; + if (scope == null) + return; + scope.Complete(); + scope.Dispose(); + } + private void plateView_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) @@ -81,6 +101,7 @@ namespace OpenNest.Actions var offset = plateView.CurrentPoint - plateView.LastPoint; + drag?.MarkChanged(); foreach (var part in plateView.SelectedParts) part.Offset(offset.X, offset.Y); } @@ -104,7 +125,11 @@ namespace OpenNest.Actions } if (SelectPartAtCurrentPoint()) + { + EndDrag(); + drag = plateView.BeginChange("Move"); return; + } if (status == Status.SetFirstPoint) { @@ -141,6 +166,8 @@ namespace OpenNest.Actions if (plateView.Plate.CutOffs.Count > 0) plateView.Plate.RegenerateCutOffs(plateView.CutOffSettings); } + + EndDrag(); } private void plateView_Paint(object sender, PaintEventArgs e) diff --git a/OpenNest/Actions/ActionSequenceByPath.cs b/OpenNest/Actions/ActionSequenceByPath.cs index 366afc10..9eb59c4f 100644 --- a/OpenNest/Actions/ActionSequenceByPath.cs +++ b/OpenNest/Actions/ActionSequenceByPath.cs @@ -155,6 +155,15 @@ namespace OpenNest.Actions } } + // The main window's Ctrl+Z reaches here first; with no line left it undoes the nest. + public override bool TryUndoStep() + { + if (lines.Count == 0) + return false; + RemoveLastLine(); + return true; + } + private void RemoveLastLine() { if (lines.Count == 0) diff --git a/OpenNest/Controls/DrawingListBox.cs b/OpenNest/Controls/DrawingListBox.cs index 159d66ae..bd613d7e 100644 --- a/OpenNest/Controls/DrawingListBox.cs +++ b/OpenNest/Controls/DrawingListBox.cs @@ -244,6 +244,9 @@ namespace OpenNest.Controls DrawingPickedUp?.Invoke(this, pressedDrawing); } + /// Forgets a drawing pressed but not yet dragged, e.g. when the nest is swapped. + internal void CancelPickup() => pressedDrawing = null; + protected override void OnMouseUp(MouseEventArgs e) { pressedDrawing = null; diff --git a/OpenNest/Controls/PlateView.cs b/OpenNest/Controls/PlateView.cs index ddec1fa1..a7ef1ac1 100644 --- a/OpenNest/Controls/PlateView.cs +++ b/OpenNest/Controls/PlateView.cs @@ -17,6 +17,7 @@ using OpenNest.Engine.Jobs.Placement; using OpenNest.Forms; using OpenNest.Geometry; using OpenNest.Math; +using OpenNest.Undo; using Timer = System.Timers.Timer; namespace OpenNest.Controls @@ -174,6 +175,16 @@ namespace OpenNest.Controls /// internal Func ClampNest { get; set; } + /// + /// Opens an undo scope in the nest document this view shows; null when the view is not a + /// nest window, and then records nothing. + /// + internal Func BeginChangeHandler { get; set; } + + /// Opens a scope that records one undoable edit of this view's nest. + internal ChangeScope BeginChange(string label, object coalesceKey = null) => + BeginChangeHandler?.Invoke(label, coalesceKey) ?? ChangeScope.Detached(); + public bool AllowZoom { get; set; } public bool AllowSelect { get; set; } @@ -530,7 +541,8 @@ namespace OpenNest.Controls var angle = Angle.ToRadians((e.Delta > 0 ? -increment : increment) * multiplier); - selection.RotateSelectedParts(angle); + // A turn of the wheel is many steps; they undo as one rotation. + selection.RotateSelectedParts(angle, coalesce: true); } else { @@ -694,8 +706,7 @@ namespace OpenNest.Controls break; case Keys.Left: - SelectedParts.ForEach(part => part.Offset(-OffsetIncrementDistance, 0)); - Invalidate(); + selection.NudgeSelected(-OffsetIncrementDistance, 0); break; case Keys.X: @@ -719,18 +730,15 @@ namespace OpenNest.Controls break; case Keys.Right: - SelectedParts.ForEach(part => part.Offset(OffsetIncrementDistance, 0)); - Invalidate(); + selection.NudgeSelected(OffsetIncrementDistance, 0); break; case Keys.Up: - SelectedParts.ForEach(part => part.Offset(0, OffsetIncrementDistance)); - Invalidate(); + selection.NudgeSelected(0, OffsetIncrementDistance); break; case Keys.Down: - SelectedParts.ForEach(part => part.Offset(0, -OffsetIncrementDistance)); - Invalidate(); + selection.NudgeSelected(0, -OffsetIncrementDistance); break; } @@ -871,7 +879,10 @@ namespace OpenNest.Controls part.Location.Y - part.BoundingBox.Center.Y ); + using var change = BeginChange("Add Part"); + change.MarkChanged(); Plate.Parts.Add(part); + change.Complete(); } public void SetActiveParts(List parts) => previewManager.SetActiveParts(parts); diff --git a/OpenNest/Controls/SelectionManager.cs b/OpenNest/Controls/SelectionManager.cs index 4024a556..df9a5318 100644 --- a/OpenNest/Controls/SelectionManager.cs +++ b/OpenNest/Controls/SelectionManager.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Linq; +using System.Runtime.CompilerServices; using System.Threading; using OpenNest.CNC; using OpenNest.Engine.Fill; @@ -61,8 +62,11 @@ namespace OpenNest.Controls public void DeleteSelected() { + using var change = view.BeginChange("Delete"); var regenerateCutOffs = view.Plate.CutOffs.Count > 0 && (selectedCutOffs.Count > 0 || selectedParts.Count > 0); + if (selectedCutOffs.Count > 0) + change.MarkChanged(); foreach (var cutOff in selectedCutOffs) view.Plate.CutOffs.Remove(cutOff); @@ -71,15 +75,36 @@ namespace OpenNest.Controls RemoveSelectedParts(); if (regenerateCutOffs) view.Plate.RegenerateCutOffs(view.CutOffSettings); + change.Complete(); } public void RemoveSelectedParts() { + using var change = view.BeginChange("Delete"); + if (selectedParts.Count > 0) + change.MarkChanged(); foreach (var part in selectedParts) view.Plate.Parts.Remove(part.BasePart); DeselectAll(); view.Invalidate(); + change.Complete(); + } + + /// + /// Moves the selection by (, ); repeated + /// nudges of the same selection undo as one move. + /// + public void NudgeSelected(double dx, double dy) + { + if (selectedParts.Count == 0) + return; + + using var change = view.BeginChange("Nudge", new SelectionKey("Nudge", view.Plate, selectedParts)); + change.MarkChanged(); + selectedParts.ForEach(part => part.Offset(dx, dy)); + view.Invalidate(); + change.Complete(); } public void AlignSelected(AlignType alignType) @@ -92,6 +117,11 @@ namespace OpenNest.Controls public void AlignSelected(AlignType alignType, LayoutPart fixedPart) { + if (selectedParts.Count == 0) + return; + + using var change = view.BeginChange("Align"); + change.MarkChanged(); switch (alignType) { case AlignType.Bottom: @@ -132,15 +162,28 @@ namespace OpenNest.Controls ); break; default: + // An unknown alignment moves nothing; completing records nothing either. + change.Complete(); return; } selectedParts.ForEach(p => p.IsDirty = true); view.Invalidate(); + change.Complete(); } - public void RotateSelectedParts(double angle) + /// + /// Rotates the selection by about its centre, keeping its + /// lower-left corner; with , quick repeats undo as one. + /// + public void RotateSelectedParts(double angle, bool coalesce = false) { + if (selectedParts.Count == 0) + return; + + using var change = view.BeginChange("Rotate", + coalesce ? new SelectionKey("Rotate", view.Plate, selectedParts) : null); + change.MarkChanged(); var parts = selectedParts.Select(p => p.BasePart).ToList(); var bounds = parts.GetBoundingBox(); var center = bounds.Center; @@ -156,14 +199,21 @@ namespace OpenNest.Controls if (view.Plate.CutOffs.Count > 0) view.Plate.RegenerateCutOffs(view.CutOffSettings); + change.Complete(); } public void PushSelected(PushDirection direction) { + if (selectedParts.Count == 0) + return; + + using var change = view.BeginChange("Push"); + change.MarkChanged(); var movingParts = selectedParts.Select(p => p.BasePart).ToList(); Compactor.Push(movingParts, view.Plate, direction); selectedParts.ForEach(p => p.IsDirty = true); view.Invalidate(); + change.Complete(); } /// @@ -186,14 +236,17 @@ namespace OpenNest.Controls Expander.Result Work(CancellationToken token) => Expander.Expand(movingParts, plate, null, token); + using var change = view.BeginChange("Expand Spacing"); var result = run != null ? run(Work) : Work(CancellationToken.None); if (result.Cancelled) { view.Status = "Expand Spacing cancelled - no parts were moved"; + change.Complete(); return true; } + change.MarkChanged(); selectedParts.ForEach(p => p.IsDirty = true); if (view.Plate.CutOffs.Count > 0) @@ -205,6 +258,7 @@ namespace OpenNest.Controls $"Expanded spacing to {result.AchievedSpacing:0.###}" + (result.Violations.Count > 0 ? $" - {result.Violations.Count} blocked pairs" : ""); + change.Complete(); return true; } @@ -352,5 +406,34 @@ namespace OpenNest.Controls selectedParts.Clear(); selectedCutOffs.Clear(); } + + /// + /// Equal for the same edit of the same parts on the same plate, so repeated nudges or + /// wheel turns coalesce into one undo entry. + /// + private sealed class SelectionKey : IEquatable + { + private readonly string operation; + private readonly Plate plate; + private readonly Part[] parts; + + public SelectionKey(string operation, Plate plate, IEnumerable selection) + { + this.operation = operation; + this.plate = plate; + parts = selection.Select(p => p.BasePart).ToArray(); + } + + public bool Equals(SelectionKey other) => + other != null + && operation == other.operation + && ReferenceEquals(plate, other.plate) + && parts.Length == other.parts.Length + && parts.Zip(other.parts).All(pair => ReferenceEquals(pair.First, pair.Second)); + + public override bool Equals(object obj) => Equals(obj as SelectionKey); + + public override int GetHashCode() => HashCode.Combine(operation, RuntimeHelpers.GetHashCode(plate), parts.Length); + } } } diff --git a/OpenNest/Document.cs b/OpenNest/Document.cs index 93c82aed..cff023b6 100644 --- a/OpenNest/Document.cs +++ b/OpenNest/Document.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using OpenNest.Data; using OpenNest.Engine.BestFit; using OpenNest.IO; +using OpenNest.Undo; namespace OpenNest { @@ -12,6 +13,12 @@ namespace OpenNest { public Nest Nest { get; set; } + /// + /// This document's undo history: whole-nest states, reset with the first one when the + /// nest window opens. Saving marks a save point; it never clears the history. + /// + public UndoHistory History { get; } = new(); + public DateTime LastSaveDate { get; private set; } public string LastSavePath { get; private set; } @@ -53,6 +60,8 @@ namespace OpenNest var writer = new NestWriter(Nest) { BestFitStore = BestFitCacheStore.Shared }; writer.Write(path); + if (History.Current != null) + History.MarkSaved(); } /// Serializes the current nest to a .nest archive in memory. @@ -69,9 +78,13 @@ namespace OpenNest CancellationToken cancellationToken = default) { var bytes = Serialize(); + // The save point is the state serialized here, unless an edit was recorded since. + var state = History.Current; var saved = await remoteSession.SaveAsync( repository, serverUrl, Nest, bytes, saveCopy, cancellationToken); LastSaveDate = DateTime.Now; + if (state != null && ReferenceEquals(History.Current, state)) + History.MarkSaved(); return saved; } } diff --git a/OpenNest/Forms/EditNestForm.Undo.cs b/OpenNest/Forms/EditNestForm.Undo.cs new file mode 100644 index 00000000..727abe8a --- /dev/null +++ b/OpenNest/Forms/EditNestForm.Undo.cs @@ -0,0 +1,226 @@ +using System; +using System.Diagnostics; +using System.Linq; +using System.Windows.Forms; +using OpenNest.Actions; +using OpenNest.Data; +using OpenNest.IO; +using OpenNest.Undo; + +namespace OpenNest.Forms +{ + // Undo and Redo: the history holds whole-nest copies and a restore swaps one in. + public partial class EditNestForm + { + private ChangeScope openChange; + private int recordedFingerprint; + private bool restoringNest; + + /// Raised after swapped a nest in, for windows that show it. + public event EventHandler NestRestored; + + public UndoHistory History => Document.History; + + /// True while a change scope is open or a nest is being swapped in. + public bool IsChangeInProgress => openChange != null || restoringNest; + + /// + /// Opens a scope that records one undoable edit named . Mark it + /// changed and complete it; a scope opened inside another merges into the outermost one. + /// Repeated edits with an equal within a second undo as one. + /// + public ChangeScope BeginChange(string label, object coalesceKey = null) + { + ArgumentException.ThrowIfNullOrEmpty(label); + if (openChange != null) + return ChangeScope.Nested(openChange); + // Swapping a nest in rebinds the view; nothing it does is an edit. + if (restoringNest) + return ChangeScope.Detached(); + + RecordUnrecordedChange(); + openChange = ChangeScope.Root(label, coalesceKey, EndChange); + return openChange; + } + + /// Whether would step back: no edit or inspection is open. + public bool CanUndo => History.CanUndo && CanRestore; + + public bool CanRedo => History.CanRedo && CanRestore; + + private bool CanRestore => !IsChangeInProgress && CuttingInspection == null; + + public void Undo() + { + if (!CanRestore) + return; + RecordUnrecordedChange(); + if (History.CanUndo) + Restore(History.Undo(), History.Redo); + } + + public void Redo() + { + if (!CanRestore) + return; + // An edit made since the undo drops what could be redone. + RecordUnrecordedChange(); + if (History.CanRedo) + Restore(History.Redo(), History.Undo); + } + + /// + /// Reads back and swaps it in; when the copy cannot be read the + /// live nest is untouched, so points the history back at it. + /// + private void Restore(NestUndoState state, Func moveBack) + { + Nest restored; + try + { + restored = state.Snapshot.Restore(Nest); + } + catch + { + moveBack(); + throw; + } + RestoreNest(restored); + } + + private void InitializeHistory() + { + History.Reset(new NestUndoState(NestSnapshot.Capture(Nest))); + recordedFingerprint = NestFingerprint.Compute(Nest); +#if DEBUG + Application.Idle += CheckForUnrecordedChange; + FormClosed += (_, _) => Application.Idle -= CheckForUnrecordedChange; +#endif + } + + private void EndChange(ChangeScope scope) + { + openChange = null; + if (!scope.IsChanged) + return; + if (scope.Succeeded) + Commit(scope.Label, scope.CoalesceKey); + else + RestoreNest(History.Current.Snapshot.Restore(Nest)); + } + + private void Commit(string label, object coalesceKey) + { + History.Commit(label, new NestUndoState(NestSnapshot.Capture(Nest)), coalesceKey); + recordedFingerprint = NestFingerprint.Compute(Nest); + } + + /// + /// Commits an edit no scope recorded as its own entry, so a rollback, Undo or Redo + /// does not silently discard it. Detected by fingerprint, so best effort. + /// + private void RecordUnrecordedChange() + { + if (History.Current != null && NestFingerprint.Compute(Nest) != recordedFingerprint) + Commit("Change", null); + } + + /// + /// Replaces the document's nest with , a copy read back from + /// the history, and rebinds everything that held the old one. The document, the nest's + /// identity (name, status, author, creation date), the plate shown, the viewport and the + /// selection (by part index) are kept. + /// + public void RestoreNest(Nest restored) + { + ArgumentNullException.ThrowIfNull(restored); + // Apply after a restore would commit to plates no longer in the nest. + CuttingInspection?.RequestClose(); + if (CuttingInspection != null) + throw new InvalidOperationException("Close Cutting Inspection before undoing."); + + var live = Nest; + restored.Name = live.Name; + restored.Status = live.Status; + restored.MadeBy = live.MadeBy; + restored.DateCreated = live.DateCreated; + + var plateIndex = PlateManager.CurrentIndex; + var partCount = PlateView.Plate?.Parts.Count ?? 0; + var selected = PlateView.SelectedParts + .Select(layout => PlateView.Plate.Parts.IndexOf(layout.BasePart)) + .Where(index => index >= 0) + .ToArray(); + var viewport = PlateView.CaptureViewport(); + + restoringNest = true; + try + { + // Actions, previews and side panels hold parts and plates of the old nest. + PlateView.EndAction(); + PlateView.ClearPreviewParts(); + PlateView.CancelOverlapCheck(); + drawingListBox1.CancelPickup(); + addPart = false; + if (IsSidePanelVisible) + HideSidePanel(); + + UnbindNest(); + Document.Nest = restored; + BindNest(restored); + // Reading regenerates cut-offs with default settings; the view's apply here. + foreach (var plate in restored.Plates.Where(plate => plate.CutOffs.Count > 0)) + plate.RegenerateCutOffs(PlateView.CutOffSettings); + ColorSchemeRegistry.RecolorDrawings(restored); + + // Loading a plate zooms to fit; an undo keeps the view where it was. + PlateManager.LoadAt(System.Math.Clamp(plateIndex, 0, System.Math.Max(0, PlateManager.Count - 1))); + PlateView.RestoreViewport(viewport); + if (PlateView.Plate.Parts.Count == partCount && selected.Length > 0) + Reselect(selected); + + UpdatePlateList(); + UpdatePlateHeader(); + UpdateRemovePlateButton(); + PlateView.Invalidate(); + } + finally + { + restoringNest = false; + } + + recordedFingerprint = NestFingerprint.Compute(Nest); + NestRestored?.Invoke(this, EventArgs.Empty); + } + + private void Reselect(int[] indices) + { + var layouts = PlateView.LayoutParts; + foreach (var index in indices) + { + var layout = layouts[index]; + layout.IsSelected = true; + PlateView.SelectedParts.Add(layout); + } + PlateView.NotifySelectionChanged(); + } + +#if DEBUG + private DateTime nextUnrecordedCheck; + private int warnedFingerprint; + + // Every edit should open a change scope; one that does not folds into the next entry. + private void CheckForUnrecordedChange(object sender, EventArgs e) + { + if (IsDisposed || IsChangeInProgress || PlateView.IsFillInProgress || DateTime.UtcNow < nextUnrecordedCheck) + return; + nextUnrecordedCheck = DateTime.UtcNow.AddMilliseconds(500); + var fingerprint = NestFingerprint.Compute(Nest); + if (fingerprint == recordedFingerprint || fingerprint == warnedFingerprint) + return; + warnedFingerprint = fingerprint; + Debug.WriteLine($"Undo: '{Nest.Name}' changed outside a change scope; the edit is not recorded yet."); + } +#endif + } +} diff --git a/OpenNest/Forms/EditNestForm.cs b/OpenNest/Forms/EditNestForm.cs index d4b25fe2..7fd6d39e 100644 --- a/OpenNest/Forms/EditNestForm.cs +++ b/OpenNest/Forms/EditNestForm.cs @@ -41,7 +41,8 @@ namespace OpenNest.Forms set => PlateView.OverlapDisplay = value; } - public readonly PlateManager PlateManager; + /// Navigates the current nest's plates; replaced whenever an undo swaps the nest. + public PlateManager PlateManager { get; private set; } public Nest Nest => Document.Nest; @@ -440,6 +441,29 @@ namespace OpenNest.Forms HoldStatus = new NestHoldStatus(Document); HoldStatus.CloseoutNoteRequested += HoldStatus_CloseoutNoteRequested; FormClosed += (_, _) => HoldStatus.Dispose(); + + BindNest(nest); + PlateManager.LoadFirst(); + + drawingListBox1.DeleteRequested += drawingListBox1_DeleteRequested; + drawingListBox1.SaveToLibraryRequested += drawingListBox1_SaveToLibraryRequested; + drawingListBox1.AddToSetRequested += drawingListBox1_AddToSetRequested; + drawingListBox1.OpenInConverterRequested += drawingListBox1_OpenInConverterRequested; + drawingListBox1.DrawingPickedUp += drawingListBox1_DrawingPickedUp; + drawingListBox1.DrawingDropped += drawingListBox1_DrawingDropped; + Activated += (_, _) => UpdateDrawingLibraryCommand(); + UpdateDrawingLibraryCommand(); + PlateView.BeginChangeHandler = BeginChange; + InitializeHistory(); + } + + /// + /// Binds this window to , the document's nest: the view's + /// per-nest settings, a plate manager for its plates and the plate and drawing lists. + /// Opening and undo share it; neither loads a plate yet. + /// + private void BindNest(Nest nest) + { // Units are read when each check starts, matching the manual command. PlateView.SetOverlapAutoCheck(() => Nest.Units); CutOffHeadLockDefaults.Load(PlateView.CutOffSettings, nest.Units); @@ -455,18 +479,15 @@ namespace OpenNest.Forms UpdateDrawingList(); UpdateRemovePlateButton(); - PlateManager.LoadFirst(); - Text = Nest.Name; drawingListBox1.Units = Nest.Units; - drawingListBox1.DeleteRequested += drawingListBox1_DeleteRequested; - drawingListBox1.SaveToLibraryRequested += drawingListBox1_SaveToLibraryRequested; - drawingListBox1.AddToSetRequested += drawingListBox1_AddToSetRequested; - drawingListBox1.OpenInConverterRequested += drawingListBox1_OpenInConverterRequested; - drawingListBox1.DrawingPickedUp += drawingListBox1_DrawingPickedUp; - drawingListBox1.DrawingDropped += drawingListBox1_DrawingDropped; - Activated += (_, _) => UpdateDrawingLibraryCommand(); - UpdateDrawingLibraryCommand(); + } + + private void UnbindNest() + { + PlateManager.CurrentPlateChanged -= PlateManager_CurrentPlateChanged; + PlateManager.PlateListChanged -= PlateManager_PlateListChanged; + PlateManager.Dispose(); } public void UpdatePlateList() @@ -958,9 +979,21 @@ namespace OpenNest.Forms Process.Start(path); } + public void AddPlate() + { + using var change = BeginChange("Add Plate"); + change.MarkChanged(); + Nest.CreatePlate(); + change.Complete(); + } + public void RemoveCurrentPlate() { + using var change = BeginChange("Remove Plate"); + if (PlateManager.Count >= 2) + change.MarkChanged(); PlateManager.RemoveCurrent(); + change.Complete(); } public void ClearNest() @@ -1147,7 +1180,7 @@ namespace OpenNest.Forms private void AddPlate_Click(object sender, EventArgs e) { - Nest.CreatePlate(); + AddPlate(); } private void EditSelectedPlate_Click(object sender, EventArgs e) diff --git a/OpenNest/Forms/MainForm.Designer.cs b/OpenNest/Forms/MainForm.Designer.cs index 6188dad6..2a0a542c 100644 --- a/OpenNest/Forms/MainForm.Designer.cs +++ b/OpenNest/Forms/MainForm.Designer.cs @@ -51,6 +51,9 @@ namespace OpenNest.Forms toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); mnuFileExit = new System.Windows.Forms.ToolStripMenuItem(); mnuEdit = new System.Windows.Forms.ToolStripMenuItem(); + mnuEditUndo = new System.Windows.Forms.ToolStripMenuItem(); + mnuEditRedo = new System.Windows.Forms.ToolStripMenuItem(); + mnuEditUndoSeparator = new System.Windows.Forms.ToolStripSeparator(); mnuEditCut = new System.Windows.Forms.ToolStripMenuItem(); mnuEditCopy = new System.Windows.Forms.ToolStripMenuItem(); mnuEditPaste = new System.Windows.Forms.ToolStripMenuItem(); @@ -326,10 +329,34 @@ namespace OpenNest.Forms // // mnuEdit // - mnuEdit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { mnuEditCut, mnuEditCopy, mnuEditPaste, toolStripMenuItem4, mnuEditSelectAll }); + mnuEdit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { mnuEditUndo, mnuEditRedo, mnuEditUndoSeparator, mnuEditCut, mnuEditCopy, mnuEditPaste, toolStripMenuItem4, mnuEditSelectAll }); mnuEdit.Name = "mnuEdit"; mnuEdit.Size = new System.Drawing.Size(39, 20); mnuEdit.Text = "&Edit"; + mnuEdit.DropDownOpening += EditMenu_DropDownOpening; + // + // mnuEditUndo + // + mnuEditUndo.Enabled = false; + mnuEditUndo.Name = "mnuEditUndo"; + mnuEditUndo.ShortcutKeyDisplayString = "Ctrl+Z"; + mnuEditUndo.Size = new System.Drawing.Size(164, 22); + mnuEditUndo.Text = "Undo"; + mnuEditUndo.Click += EditUndo_Click; + // + // mnuEditRedo + // + mnuEditRedo.Enabled = false; + mnuEditRedo.Name = "mnuEditRedo"; + mnuEditRedo.ShortcutKeyDisplayString = "Ctrl+Y"; + mnuEditRedo.Size = new System.Drawing.Size(164, 22); + mnuEditRedo.Text = "Redo"; + mnuEditRedo.Click += EditRedo_Click; + // + // mnuEditUndoSeparator + // + mnuEditUndoSeparator.Name = "mnuEditUndoSeparator"; + mnuEditUndoSeparator.Size = new System.Drawing.Size(161, 6); // // mnuEditCut // @@ -1375,6 +1402,9 @@ namespace OpenNest.Forms private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem mnuFileExit; private System.Windows.Forms.ToolStripMenuItem mnuEdit; + private System.Windows.Forms.ToolStripMenuItem mnuEditUndo; + private System.Windows.Forms.ToolStripMenuItem mnuEditRedo; + private System.Windows.Forms.ToolStripSeparator mnuEditUndoSeparator; private System.Windows.Forms.ToolStripMenuItem mnuEditCut; private System.Windows.Forms.ToolStripMenuItem mnuEditCopy; private System.Windows.Forms.ToolStripMenuItem mnuEditPaste; diff --git a/OpenNest/Forms/MainForm.File.cs b/OpenNest/Forms/MainForm.File.cs index 62a4803d..7858b22c 100644 --- a/OpenNest/Forms/MainForm.File.cs +++ b/OpenNest/Forms/MainForm.File.cs @@ -255,6 +255,7 @@ namespace OpenNest.Forms storageModeMenu.Enabled = !storage.IsBusy; mnuToolsOptions.Enabled = !storage.IsBusy; EnableCheck(); + UpdateUndoMenu(); } private void StorageMode_Click(object sender, EventArgs e) diff --git a/OpenNest/Forms/MainForm.Guards.cs b/OpenNest/Forms/MainForm.Guards.cs index 3baa7fb5..44cfd984 100644 --- a/OpenNest/Forms/MainForm.Guards.cs +++ b/OpenNest/Forms/MainForm.Guards.cs @@ -59,6 +59,16 @@ namespace OpenNest.Forms /// private bool IsNestJobBusy() => IsJobRunning || storage.IsSaving; + /// + /// The guard for Undo and Redo, which replace the whole nest: any nest job or background + /// save, a fill or a busy action on a view of the nest (a selection does not count), or + /// an edit still being recorded. + /// + internal bool IsUndoBusy(EditNestForm editForm) => + IsNestJobBusy() + || editForm.IsChangeInProgress + || ViewsOf(editForm.Nest).Any(v => v.IsFillInProgress || v.Actions.CurrentAction?.BlocksUndo == true); + /// /// Refuses with while plate work on /// is busy; otherwise returns every view of the nest to selection and returns true. diff --git a/OpenNest/Forms/MainForm.Plate.cs b/OpenNest/Forms/MainForm.Plate.cs index 874120b5..e0f4c164 100644 --- a/OpenNest/Forms/MainForm.Plate.cs +++ b/OpenNest/Forms/MainForm.Plate.cs @@ -15,7 +15,7 @@ namespace OpenNest.Forms { if (activeForm == null) return; - activeForm.Nest.CreatePlate(); + activeForm.AddPlate(); NavigationEnableCheck(); } diff --git a/OpenNest/Forms/MainForm.Undo.cs b/OpenNest/Forms/MainForm.Undo.cs new file mode 100644 index 00000000..dd5fa7b5 --- /dev/null +++ b/OpenNest/Forms/MainForm.Undo.cs @@ -0,0 +1,135 @@ +using System; +using System.Linq; +using System.Windows.Forms; +using OpenNest.Controls; + +namespace OpenNest.Forms +{ + public partial class MainForm + { + private const Keys UndoKeys = Keys.Control | Keys.Z; + private const Keys RedoKeys = Keys.Control | Keys.Y; + private const Keys RedoAlternateKeys = Keys.Control | Keys.Shift | Keys.Z; + + // The window whose history the Edit menu follows. + private EditNestForm undoSource; + + /// + /// Handles Ctrl+Z, Ctrl+Y and Ctrl+Shift+Z for the active nest. A focused text editor + /// keeps them, and an action with its own step-back (Sequence by Path) gets Ctrl+Z first. + /// + private bool ProcessUndoKeys(Keys keyData) + { + if (keyData is not (UndoKeys or RedoKeys or RedoAlternateKeys) || activeForm == null) + return false; + if (KeepsOwnUndo(FocusedControl())) + return false; + + if (keyData == UndoKeys) + { + if (activeForm.PlateView.Actions.CurrentAction?.TryUndoStep() != true) + TryUndo(activeForm); + } + else + TryRedo(activeForm); + return true; + } + + private static Control FocusedControl() + { + var handle = Win32.GetFocus(); + return handle == IntPtr.Zero ? null : Control.FromChildHandle(handle); + } + + /// + /// True for controls that undo their own typing: text boxes (the editing control of a + /// grid or numeric box is one), editable combo boxes, numeric boxes, a grid in edit + /// mode and the program editor. + /// + internal static bool KeepsOwnUndo(Control focused) + { + for (var control = focused; control != null; control = control.Parent) + { + switch (control) + { + case TextBoxBase: + case System.Windows.Forms.NumericUpDown: + case ComboBox { DropDownStyle: not ComboBoxStyle.DropDownList }: + case DataGridView { IsCurrentCellInEditMode: true }: + case ProgramEditorControl: + return true; + } + } + return false; + } + + internal bool TryUndo(EditNestForm form) + { + if (!CanUndoOrRedo(form) || !form.CanUndo) + return false; + form.Undo(); + return true; + } + + internal bool TryRedo(EditNestForm form) + { + if (!CanUndoOrRedo(form) || !form.CanRedo) + return false; + form.Redo(); + return true; + } + + private bool CanUndoOrRedo(EditNestForm form) => form is { IsDisposed: false } && !IsUndoBusy(form); + + private void EditUndo_Click(object sender, EventArgs e) => WithActive(form => TryUndo(form)); + + private void EditRedo_Click(object sender, EventArgs e) => WithActive(form => TryRedo(form)); + + // Busy states have no change event of their own; check them whenever the menu opens. + private void EditMenu_DropDownOpening(object sender, EventArgs e) => UpdateUndoMenu(); + + /// Follows 's history in the Edit menu. + private void BindUndoMenu(EditNestForm form) + { + if (undoSource != null) + { + undoSource.History.Changed -= History_Changed; + undoSource.NestRestored -= EditForm_NestRestored; + } + undoSource = form; + if (undoSource != null) + { + undoSource.History.Changed += History_Changed; + undoSource.NestRestored += EditForm_NestRestored; + } + UpdateUndoMenu(); + } + + private void History_Changed(object sender, EventArgs e) => UpdateUndoMenu(); + + internal void UpdateUndoMenu() + { + var form = activeForm; + var available = form != null && CanUndoOrRedo(form); + var history = form?.History; + mnuEditUndo.Enabled = available && form.CanUndo; + mnuEditRedo.Enabled = available && form.CanRedo; + mnuEditUndo.Text = history?.UndoLabel is { } undo ? $"Undo {undo}" : "Undo"; + mnuEditRedo.Text = history?.RedoLabel is { } redo ? $"Redo {redo}" : "Redo"; + } + + private void EditForm_NestRestored(object sender, EventArgs e) + { + var form = (EditNestForm)sender; + // The remnant list was found on a plate no longer in the nest. + if (remnantViewer is { IsDisposed: false } viewer && ReferenceEquals(viewer.PlateView, form.PlateView)) + viewer.Close(); + if (!ReferenceEquals(form, activeForm)) + return; + EnableCheck(); + UpdateOverlapMenu(); + statusBar.UpdateAll(); + UpdateUndoMenu(); + } + } +} diff --git a/OpenNest/Forms/MainForm.View.cs b/OpenNest/Forms/MainForm.View.cs index ac61d8e9..e01d11bf 100644 --- a/OpenNest/Forms/MainForm.View.cs +++ b/OpenNest/Forms/MainForm.View.cs @@ -22,8 +22,11 @@ namespace OpenNest.Forms var partsToClone = selectedParts.Select(p => p.BasePart).ToList(); activeForm.PlateView.SetAction(typeof(ActionClone), partsToClone); + using var change = activeForm.BeginChange("Cut"); + change.MarkChanged(); foreach (var part in partsToClone) activeForm.PlateView.Plate.Parts.Remove(part); + change.Complete(); } } diff --git a/OpenNest/Forms/MainForm.cs b/OpenNest/Forms/MainForm.cs index a01db659..775b03f0 100644 --- a/OpenNest/Forms/MainForm.cs +++ b/OpenNest/Forms/MainForm.cs @@ -98,6 +98,8 @@ namespace OpenNest.Forms activeForm.PlateView.ProcessEscapeKey(); return true; } + if (ProcessUndoKeys(keyData)) + return true; return base.ProcessCmdKey(ref msg, keyData); } @@ -247,6 +249,7 @@ namespace OpenNest.Forms activeForm = ActiveMdiChild as EditNestForm; UpdateOverlapMenu(); + BindUndoMenu(activeForm); EnableCheck(); statusBar.Bind(activeForm); diff --git a/OpenNest/Forms/RemnantViewerForm.cs b/OpenNest/Forms/RemnantViewerForm.cs index d2631db3..28f6ea61 100644 --- a/OpenNest/Forms/RemnantViewerForm.cs +++ b/OpenNest/Forms/RemnantViewerForm.cs @@ -67,6 +67,9 @@ namespace OpenNest.Forms return base.ProcessDialogKey(keyData); } + /// The plate view whose plate's remnants are listed. + internal PlateView PlateView => plateView; + public void LoadRemnants(RemnantFinder finder, double minDim, PlateView view) { plateView = view; diff --git a/OpenNest/Undo/ChangeScope.cs b/OpenNest/Undo/ChangeScope.cs new file mode 100644 index 00000000..9303796f --- /dev/null +++ b/OpenNest/Undo/ChangeScope.cs @@ -0,0 +1,72 @@ +using System; + +namespace OpenNest.Undo +{ + /// + /// Records one undoable edit. Call once the nest is (about to be) + /// changed and when the edit succeeded; disposing then commits one + /// history entry. Disposing without (an exception, a cancellation) + /// rolls a changed nest back to the last recorded state. A scope opened while another is + /// open merges into the outermost one: its changes join that entry, and leaving it + /// incomplete rolls back the whole entry. A scope with nothing marked changed records and + /// restores nothing. + /// + public sealed class ChangeScope : IDisposable + { + private readonly ChangeScope root; + private readonly Action end; + private bool completed; + private bool disposed; + private bool changed; + private bool failed; + + private ChangeScope(string label, object coalesceKey, ChangeScope root, Action end) + { + Label = label; + CoalesceKey = coalesceKey; + this.root = root; + this.end = end; + } + + /// A scope with no history behind it, for views that are not a nest document. + public static ChangeScope Detached() => new(null, null, null, null); + + /// An outermost scope; runs once when it is disposed. + internal static ChangeScope Root(string label, object coalesceKey, Action end) => + new(label, coalesceKey, null, end); + + /// A scope inside ; it merges into the outermost one. + internal static ChangeScope Nested(ChangeScope outer) => new(outer.Label, null, outer.Outermost, null); + + public string Label { get; } + + /// Repeated edits with an equal key shortly after each other undo as one. + public object CoalesceKey { get; } + + internal ChangeScope Outermost => root ?? this; + + /// True once this scope or any scope merged into it marked the nest changed. + public bool IsChanged => Outermost.changed; + + /// True when the outermost scope completed and no merged scope was left incomplete. + internal bool Succeeded => completed && !failed; + + public void MarkChanged() => Outermost.changed = true; + + public void Complete() => completed = true; + + public void Dispose() + { + if (disposed) + return; + disposed = true; + if (root != null) + { + if (!completed) + root.failed = true; + return; + } + end?.Invoke(this); + } + } +} diff --git a/OpenNest/Undo/NestFingerprint.cs b/OpenNest/Undo/NestFingerprint.cs new file mode 100644 index 00000000..cf798f32 --- /dev/null +++ b/OpenNest/Undo/NestFingerprint.cs @@ -0,0 +1,57 @@ +using System; +using System.Runtime.CompilerServices; + +namespace OpenNest.Undo +{ + /// + /// A cheap hash of what edits usually change: plates, their parts' poses, programs and + /// cut-offs, and the drawings with their required quantities. Two equal fingerprints do not + /// prove two nests equal; a differing one means the nest changed since it was taken. Objects + /// count by reference, so compare fingerprints of one live nest, never across a restore. + /// Derived values (nested counts, colours, the modified date) are left out. + /// + internal static class NestFingerprint + { + public static int Compute(Nest nest) + { + var hash = new HashCode(); + hash.Add(nest.Plates.Count); + foreach (var plate in nest.Plates) + { + hash.Add(plate.Size.Width); + hash.Add(plate.Size.Length); + hash.Add(plate.Quantity); + hash.Add(plate.PartSpacing); + hash.Add(RuntimeHelpers.GetHashCode(plate.CuttingParameters)); + hash.Add(plate.ClampZones.Count); + hash.Add(plate.Parts.Count); + foreach (var part in plate.Parts) + { + hash.Add(RuntimeHelpers.GetHashCode(part.BaseDrawing)); + hash.Add(RuntimeHelpers.GetHashCode(part.Program)); + hash.Add(part.Location.X); + hash.Add(part.Location.Y); + hash.Add(part.Rotation); + hash.Add(part.HasManualLeadIns); + hash.Add(part.LeadInsLocked); + } + hash.Add(plate.CutOffs.Count); + foreach (var cutOff in plate.CutOffs) + { + hash.Add(cutOff.Position.X); + hash.Add(cutOff.Position.Y); + hash.Add(cutOff.Axis); + } + } + + hash.Add(nest.Drawings.Count); + foreach (var drawing in nest.Drawings) + { + hash.Add(RuntimeHelpers.GetHashCode(drawing)); + hash.Add(RuntimeHelpers.GetHashCode(drawing.Program)); + hash.Add(drawing.Quantity.Required); + } + return hash.ToHashCode(); + } + } +} diff --git a/OpenNest/Undo/NestUndoState.cs b/OpenNest/Undo/NestUndoState.cs new file mode 100644 index 00000000..d5cf9e4b --- /dev/null +++ b/OpenNest/Undo/NestUndoState.cs @@ -0,0 +1,11 @@ +using OpenNest.Data; +using OpenNest.IO; + +namespace OpenNest.Undo +{ + /// One whole-nest state in a document's undo history. + public sealed record NestUndoState(NestSnapshot Snapshot) : IUndoState + { + public long SizeInBytes => Snapshot.SizeInBytes; + } +} diff --git a/OpenNest/Win32.cs b/OpenNest/Win32.cs index 52194443..94033a5c 100644 --- a/OpenNest/Win32.cs +++ b/OpenNest/Win32.cs @@ -24,6 +24,10 @@ namespace OpenNest string filePath ); + /// The window with keyboard focus on this thread, or zero. + [DllImport("user32.dll")] + public static extern IntPtr GetFocus(); + [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex);