feat(desktop): undo and redo the most-used nest edits

Whole-nest snapshots make undo safe without a hand-written inverse per
operation: each recorded edit stores one NestSnapshot in the document's
history, and Undo/Redo read one back and swap it into the open window.

- Document.History is reset with the opened nest; Save and database
  saves mark the save point instead of clearing it.
- EditNestForm.BeginChange opens a scope: nested scopes merge into the
  outermost, Complete commits one entry, and leaving it incomplete rolls
  a changed nest back. No-ops are detected by the scope's changed flag,
  not by comparing bytes (copies are not byte-stable).
- RestoreNest shares the per-nest binding with the constructor and keeps
  the Document, the nest's identity, the plate index, the viewport and
  the selection. It ends the action, closes Cutting Inspection, side
  panels and the remnant viewer, rebuilds the PlateManager, reapplies
  the view's cut-off settings and recolours the drawings, because each
  of those holds or derives from the old nest's objects.
- An edit no scope recorded (Phase 3 sites) is detected by a cheap
  fingerprint and committed as its own "Change" entry before a scope,
  Undo or Redo, so it is never silently discarded; DEBUG builds also
  warn about it on idle.
- Edit > Undo/Redo name the next entry. Ctrl+Z/Ctrl+Y/Ctrl+Shift+Z go
  to focused text editors first, then to an action's own step-back
  (Sequence by Path), then to the nest. They wait for jobs, fills,
  background saves and busy actions, but not for a plain selection.
- Recorded: delete, drag, arrow nudges (coalesced), rotate, align,
  push, expand spacing, add part (drop and clone), cut, add and remove
  plate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-10-26 12:11:45 -04:00
1 parent fe31a3f8ec
commit d1270f5208
23 files changed
+1194 -31

No files matched your search

@@ -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<TextBoxBase>().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<Env> 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) { }
}
}
+9
View File
@@ -42,5 +42,14 @@ namespace OpenNest.Actions
public abstract void CancelAction();
public abstract bool IsBusy();
/// <summary>Whether Undo and Redo must wait: by default, while the action is busy.</summary>
public virtual bool BlocksUndo => IsBusy();
/// <summary>
/// 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.
/// </summary>
public virtual bool TryUndoStep() => false;
}
}
+20 -7
View File
@@ -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()
+27
View File
@@ -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)
+9
View File
@@ -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)
+3
View File
@@ -244,6 +244,9 @@ namespace OpenNest.Controls
DrawingPickedUp?.Invoke(this, pressedDrawing);
}
/// <summary>Forgets a drawing pressed but not yet dragged, e.g. when the nest is swapped.</summary>
internal void CancelPickup() => pressedDrawing = null;
protected override void OnMouseUp(MouseEventArgs e)
{
pressedDrawing = null;
+20 -9
View File
@@ -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
/// </summary>
internal Func<Nest> ClampNest { get; set; }
/// <summary>
/// Opens an undo scope in the nest document this view shows; null when the view is not a
/// nest window, and then <see cref="BeginChange"/> records nothing.
/// </summary>
internal Func<string, object, ChangeScope> BeginChangeHandler { get; set; }
/// <summary>Opens a scope that records one undoable edit of this view's nest.</summary>
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<Part> parts) => previewManager.SetActiveParts(parts);
+84 -1
View File
@@ -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();
}
/// <summary>
/// Moves the selection by (<paramref name="dx"/>, <paramref name="dy"/>); repeated
/// nudges of the same selection undo as one move.
/// </summary>
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)
/// <summary>
/// Rotates the selection by <paramref name="angle"/> about its centre, keeping its
/// lower-left corner; with <paramref name="coalesce"/>, quick repeats undo as one.
/// </summary>
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();
}
/// <summary>
@@ -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();
}
/// <summary>
/// Equal for the same edit of the same parts on the same plate, so repeated nudges or
/// wheel turns coalesce into one undo entry.
/// </summary>
private sealed class SelectionKey : IEquatable<SelectionKey>
{
private readonly string operation;
private readonly Plate plate;
private readonly Part[] parts;
public SelectionKey(string operation, Plate plate, IEnumerable<LayoutPart> 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);
}
}
}
+13
View File
@@ -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; }
/// <summary>
/// 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.
/// </summary>
public UndoHistory<NestUndoState> 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();
}
/// <summary>Serializes the current nest to a .nest archive in memory.</summary>
@@ -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;
}
}
+226
View File
@@ -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;
/// <summary>Raised after <see cref="RestoreNest"/> swapped a nest in, for windows that show it.</summary>
public event EventHandler NestRestored;
public UndoHistory<NestUndoState> History => Document.History;
/// <summary>True while a change scope is open or a nest is being swapped in.</summary>
public bool IsChangeInProgress => openChange != null || restoringNest;
/// <summary>
/// Opens a scope that records one undoable edit named <paramref name="label"/>. Mark it
/// changed and complete it; a scope opened inside another merges into the outermost one.
/// Repeated edits with an equal <paramref name="coalesceKey"/> within a second undo as one.
/// </summary>
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;
}
/// <summary>Whether <see cref="Undo"/> would step back: no edit or inspection is open.</summary>
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);
}
/// <summary>
/// Reads <paramref name="state"/> back and swaps it in; when the copy cannot be read the
/// live nest is untouched, so <paramref name="moveBack"/> points the history back at it.
/// </summary>
private void Restore(NestUndoState state, Func<NestUndoState> 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);
}
/// <summary>
/// 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.
/// </summary>
private void RecordUnrecordedChange()
{
if (History.Current != null && NestFingerprint.Compute(Nest) != recordedFingerprint)
Commit("Change", null);
}
/// <summary>
/// Replaces the document's nest with <paramref name="restored"/>, 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.
/// </summary>
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
}
}
+45 -12
View File
@@ -41,7 +41,8 @@ namespace OpenNest.Forms
set => PlateView.OverlapDisplay = value;
}
public readonly PlateManager PlateManager;
/// <summary>Navigates the current nest's plates; replaced whenever an undo swaps the nest.</summary>
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();
}
/// <summary>
/// Binds this window to <paramref name="nest"/>, 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.
/// </summary>
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)
+31 -1
View File
@@ -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;
+1
View File
@@ -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)
+10
View File
@@ -59,6 +59,16 @@ namespace OpenNest.Forms
/// </summary>
private bool IsNestJobBusy() => IsJobRunning || storage.IsSaving;
/// <summary>
/// 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.
/// </summary>
internal bool IsUndoBusy(EditNestForm editForm) =>
IsNestJobBusy()
|| editForm.IsChangeInProgress
|| ViewsOf(editForm.Nest).Any(v => v.IsFillInProgress || v.Actions.CurrentAction?.BlocksUndo == true);
/// <summary>
/// Refuses with <paramref name="message"/> while plate work on <paramref name="nest"/>
/// is busy; otherwise returns every view of the nest to selection and returns true.
+1 -1
View File
@@ -15,7 +15,7 @@ namespace OpenNest.Forms
{
if (activeForm == null)
return;
activeForm.Nest.CreatePlate();
activeForm.AddPlate();
NavigationEnableCheck();
}
+135
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>
/// 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.
/// </summary>
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();
/// <summary>Follows <paramref name="form"/>'s history in the Edit menu.</summary>
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();
}
}
}
+3
View File
@@ -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();
}
}
+3
View File
@@ -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);
+3
View File
@@ -67,6 +67,9 @@ namespace OpenNest.Forms
return base.ProcessDialogKey(keyData);
}
/// <summary>The plate view whose plate's remnants are listed.</summary>
internal PlateView PlateView => plateView;
public void LoadRemnants(RemnantFinder finder, double minDim, PlateView view)
{
plateView = view;
+72
View File
@@ -0,0 +1,72 @@
using System;
namespace OpenNest.Undo
{
/// <summary>
/// Records one undoable edit. Call <see cref="MarkChanged"/> once the nest is (about to be)
/// changed and <see cref="Complete"/> when the edit succeeded; disposing then commits one
/// history entry. Disposing without <see cref="Complete"/> (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.
/// </summary>
public sealed class ChangeScope : IDisposable
{
private readonly ChangeScope root;
private readonly Action<ChangeScope> end;
private bool completed;
private bool disposed;
private bool changed;
private bool failed;
private ChangeScope(string label, object coalesceKey, ChangeScope root, Action<ChangeScope> end)
{
Label = label;
CoalesceKey = coalesceKey;
this.root = root;
this.end = end;
}
/// <summary>A scope with no history behind it, for views that are not a nest document.</summary>
public static ChangeScope Detached() => new(null, null, null, null);
/// <summary>An outermost scope; <paramref name="end"/> runs once when it is disposed.</summary>
internal static ChangeScope Root(string label, object coalesceKey, Action<ChangeScope> end) =>
new(label, coalesceKey, null, end);
/// <summary>A scope inside <paramref name="outer"/>; it merges into the outermost one.</summary>
internal static ChangeScope Nested(ChangeScope outer) => new(outer.Label, null, outer.Outermost, null);
public string Label { get; }
/// <summary>Repeated edits with an equal key shortly after each other undo as one.</summary>
public object CoalesceKey { get; }
internal ChangeScope Outermost => root ?? this;
/// <summary>True once this scope or any scope merged into it marked the nest changed.</summary>
public bool IsChanged => Outermost.changed;
/// <summary>True when the outermost scope completed and no merged scope was left incomplete.</summary>
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);
}
}
}
+57
View File
@@ -0,0 +1,57 @@
using System;
using System.Runtime.CompilerServices;
namespace OpenNest.Undo
{
/// <summary>
/// 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.
/// </summary>
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();
}
}
}
+11
View File
@@ -0,0 +1,11 @@
using OpenNest.Data;
using OpenNest.IO;
namespace OpenNest.Undo
{
/// <summary>One whole-nest state in a document's undo history.</summary>
public sealed record NestUndoState(NestSnapshot Snapshot) : IUndoState
{
public long SizeInBytes => Snapshot.SizeInBytes;
}
}
+4
View File
@@ -24,6 +24,10 @@ namespace OpenNest
string filePath
);
/// <summary>The window with keyboard focus on this thread, or zero.</summary>
[DllImport("user32.dll")]
public static extern IntPtr GetFocus();
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);