mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-11-20 22:47:43 -05:00
refactor(desktop): share undo recording and stepping as NestUndoRecorder
Scopes, the fingerprint safety net, Undo/Redo stepping, the unsaved check, identity carry-over and the Edit menu labels move from EditNestForm to OpenNest.Desktop. The WinForms window keeps only its rebinding swap-in and its guards; behavior is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
09357ca95d
commit
9663f341dd
4 files changed
+581
-151
No files matched your search
@@ -0,0 +1,258 @@
|
||||
using OpenNest.Geometry;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Desktop.Tests.Undo;
|
||||
|
||||
public class NestUndoRecorderTests
|
||||
{
|
||||
private static NestUndoRecorder Open(out Document document)
|
||||
{
|
||||
document = new Document { Nest = TestNests.OneSquare() };
|
||||
var recorder = new NestUndoRecorder(document);
|
||||
recorder.Reset();
|
||||
return recorder;
|
||||
}
|
||||
|
||||
private static Vector FirstPartLocation(Document document) =>
|
||||
document.Nest.Plates[0].Parts[0].Location;
|
||||
|
||||
[Fact]
|
||||
public void RecordedEdit_UndoesAndRedoesUnderItsLabel()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
var start = FirstPartLocation(document);
|
||||
|
||||
recorder.RecordChange("Move", () => document.Nest.Plates[0].Parts[0].Offset(5, 0));
|
||||
var moved = FirstPartLocation(document);
|
||||
|
||||
Assert.Equal("Undo Move", recorder.UndoText);
|
||||
Assert.Equal("Redo", recorder.RedoText);
|
||||
Assert.True(recorder.CanUndo);
|
||||
|
||||
recorder.Undo();
|
||||
|
||||
Assert.Equal(start, FirstPartLocation(document));
|
||||
Assert.Equal("Undo", recorder.UndoText);
|
||||
Assert.Equal("Redo Move", recorder.RedoText);
|
||||
|
||||
recorder.Redo();
|
||||
|
||||
Assert.Equal(moved, FirstPartLocation(document));
|
||||
Assert.Equal("Undo Move", recorder.UndoText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Undo_SwapsTheRestoredCopyInThroughTheView_KeepingTheNestsIdentity()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
var live = document.Nest;
|
||||
Nest swapped = null;
|
||||
var restoringDuringSwap = false;
|
||||
recorder.SwapIn = restored =>
|
||||
{
|
||||
restoringDuringSwap = recorder.IsRestoring && recorder.IsChangeInProgress;
|
||||
// Rebinding the view is not an edit.
|
||||
using (var change = recorder.BeginChange("Rebind"))
|
||||
{
|
||||
change.MarkChanged();
|
||||
change.Complete();
|
||||
}
|
||||
swapped = restored;
|
||||
document.Nest = restored;
|
||||
};
|
||||
var restoredEvents = 0;
|
||||
recorder.Restored += (_, _) => restoredEvents++;
|
||||
recorder.RecordChange("Move", () => live.Plates[0].Parts[0].Offset(5, 0));
|
||||
live.Name = "renamed";
|
||||
live.Status = NestStatus.HasBeenCut;
|
||||
|
||||
recorder.Undo();
|
||||
|
||||
Assert.True(restoringDuringSwap);
|
||||
Assert.NotSame(live, document.Nest);
|
||||
Assert.Same(swapped, document.Nest);
|
||||
Assert.Equal("renamed", document.Nest.Name);
|
||||
Assert.Equal(NestStatus.HasBeenCut, document.Nest.Status);
|
||||
Assert.Equal(1, restoredEvents);
|
||||
Assert.False(recorder.IsRestoring);
|
||||
Assert.Equal(0, recorder.History.UndoCount);
|
||||
Assert.Equal(1, recorder.History.RedoCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASwapInThatRefuses_LeavesTheLiveNest()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
recorder.RecordChange("Move", () => document.Nest.Plates[0].Parts[0].Offset(5, 0));
|
||||
var live = document.Nest;
|
||||
recorder.SwapIn = _ => throw new InvalidOperationException("busy");
|
||||
|
||||
Assert.Throws<InvalidOperationException>(recorder.Undo);
|
||||
|
||||
Assert.Same(live, document.Nest);
|
||||
Assert.False(recorder.IsChangeInProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EditOutsideAScope_IsCommittedAsChangeBeforeUndo_SoRedoBringsItBack()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
var start = FirstPartLocation(document);
|
||||
|
||||
// An entry point that forgot its scope.
|
||||
document.Nest.Plates[0].Parts[0].Offset(3, 0);
|
||||
var moved = FirstPartLocation(document);
|
||||
|
||||
Assert.True(recorder.HasUnrecordedChange);
|
||||
Assert.False(recorder.History.CanUndo);
|
||||
|
||||
recorder.Undo();
|
||||
|
||||
Assert.Equal(start, FirstPartLocation(document));
|
||||
Assert.Equal("Redo Change", recorder.RedoText);
|
||||
recorder.Redo();
|
||||
Assert.Equal(moved, FirstPartLocation(document));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BeginChange_FirstCommitsAnEditNoScopeRecorded()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
document.Nest.Drawings.First().Quantity.Required = 7;
|
||||
|
||||
recorder.RecordChange("Rotate", () => document.Nest.Plates[0].Parts[0].Rotate(System.Math.PI / 2));
|
||||
|
||||
Assert.Equal(2, recorder.History.UndoCount);
|
||||
Assert.Equal("Undo Rotate", recorder.UndoText);
|
||||
recorder.Undo();
|
||||
Assert.Equal("Undo Change", recorder.UndoText);
|
||||
Assert.Equal(7, document.Nest.Drawings.First().Quantity.Required);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasUnsavedChanges_FollowsTheSavePointAndUnrecordedEdits()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
Assert.False(recorder.HasUnsavedChanges);
|
||||
|
||||
document.Nest.Plates[0].Parts[0].Offset(1, 0);
|
||||
Assert.True(recorder.HasUnsavedChanges);
|
||||
|
||||
recorder.Undo();
|
||||
Assert.False(recorder.HasUnsavedChanges);
|
||||
|
||||
recorder.Redo();
|
||||
Assert.True(recorder.HasUnsavedChanges);
|
||||
|
||||
recorder.MarkSaved();
|
||||
Assert.False(recorder.HasUnsavedChanges);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MarkSaved_RecordsAnUnrecordedEditFirst_SoTheSavePointCoversIt()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
document.Nest.Plates[0].Parts[0].Offset(1, 0);
|
||||
|
||||
recorder.MarkSaved();
|
||||
|
||||
Assert.False(recorder.HasUnsavedChanges);
|
||||
Assert.Equal("Undo Change", recorder.UndoText);
|
||||
Assert.True(recorder.History.IsAtSavePoint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AScopeLeftIncomplete_RollsTheNestBack()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
var start = FirstPartLocation(document);
|
||||
|
||||
using (var change = recorder.BeginChange("Push"))
|
||||
{
|
||||
change.MarkChanged();
|
||||
document.Nest.Plates[0].Parts[0].Offset(9, 0);
|
||||
// An exception or a cancellation: never completed.
|
||||
}
|
||||
|
||||
Assert.Equal(start, FirstPartLocation(document));
|
||||
Assert.False(recorder.History.CanUndo);
|
||||
Assert.False(recorder.HasUnsavedChanges);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AScopeThatChangedNothing_RecordsNothing()
|
||||
{
|
||||
var recorder = Open(out _);
|
||||
var changed = 0;
|
||||
recorder.Changed += (_, _) => changed++;
|
||||
|
||||
using (var change = recorder.BeginChange("Fill"))
|
||||
change.Complete();
|
||||
|
||||
Assert.False(recorder.History.CanUndo);
|
||||
Assert.Equal(0, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NestedScopes_UndoAsOneEntryUnderTheOuterLabel()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
|
||||
using (var outer = recorder.BeginChange("Auto Nest"))
|
||||
{
|
||||
Assert.True(recorder.IsChangeInProgress);
|
||||
Assert.False(recorder.CanUndo);
|
||||
recorder.RecordChange("Add Plate", () => document.Nest.CreatePlate());
|
||||
outer.MarkChanged();
|
||||
document.Nest.Plates[0].Parts[0].Offset(2, 0);
|
||||
outer.Complete();
|
||||
}
|
||||
|
||||
Assert.Equal(1, recorder.History.UndoCount);
|
||||
Assert.Equal("Undo Auto Nest", recorder.UndoText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UndoAndRedo_DoNothingWhileAScopeIsOpen()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
recorder.RecordChange("Move", () => document.Nest.Plates[0].Parts[0].Offset(5, 0));
|
||||
var live = document.Nest;
|
||||
|
||||
using (var change = recorder.BeginChange("Rotate"))
|
||||
{
|
||||
recorder.Undo();
|
||||
Assert.Same(live, document.Nest);
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
Assert.Equal(1, recorder.History.UndoCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeUnrecordedChangeWarning_ReportsEachUnrecordedEditOnce()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
Assert.False(recorder.TakeUnrecordedChangeWarning());
|
||||
|
||||
document.Nest.Plates[0].Parts[0].Offset(1, 0);
|
||||
|
||||
Assert.True(recorder.TakeUnrecordedChangeWarning());
|
||||
Assert.False(recorder.TakeUnrecordedChangeWarning());
|
||||
document.Nest.Plates[0].Parts[0].Offset(1, 0);
|
||||
Assert.True(recorder.TakeUnrecordedChangeWarning());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MenuText_NamesTheNextStep()
|
||||
{
|
||||
var recorder = Open(out var document);
|
||||
Assert.Equal("Undo", recorder.UndoText);
|
||||
Assert.Equal("Redo", recorder.RedoText);
|
||||
Assert.Equal("Undo", NestUndoRecorder.UndoMenuText<NestUndoState>(null));
|
||||
|
||||
recorder.RecordChange("Fill", () => document.Nest.Plates[0].Parts[0].Offset(1, 0));
|
||||
|
||||
Assert.Equal("Undo Fill", recorder.UndoText);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
using System;
|
||||
using OpenNest.Data;
|
||||
using OpenNest.IO;
|
||||
|
||||
namespace OpenNest.Undo
|
||||
{
|
||||
/// <summary>
|
||||
/// Records a document's nest edits into its undo history and steps through it, for any
|
||||
/// desktop front end. Edits go through <see cref="BeginChange"/> or
|
||||
/// <see cref="RecordChange"/>; an edit made outside a scope is found by fingerprint before
|
||||
/// the next scope, Undo, Redo or save and committed as "Change". Undo and Redo read a
|
||||
/// whole-nest copy back and hand it to <see cref="SwapIn"/>, which the view sets to rebind
|
||||
/// everything that held the old nest.
|
||||
/// </summary>
|
||||
public sealed class NestUndoRecorder
|
||||
{
|
||||
/// <summary>The label of an edit no scope recorded, found by fingerprint.</summary>
|
||||
public const string UnrecordedChangeLabel = "Change";
|
||||
|
||||
private readonly Document document;
|
||||
private ChangeScope openChange;
|
||||
private int recordedFingerprint;
|
||||
private int warnedFingerprint;
|
||||
|
||||
public NestUndoRecorder(Document document)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(document);
|
||||
this.document = document;
|
||||
document.History.Changed += (_, _) => Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised after the history or the recorded state changed: a commit, an Undo or Redo,
|
||||
/// a save point or a restore. Unsaved-change marks and Edit menu labels follow it.
|
||||
/// </summary>
|
||||
public event EventHandler Changed;
|
||||
|
||||
/// <summary>Raised after <see cref="RestoreNest"/> swapped a nest in.</summary>
|
||||
public event EventHandler Restored;
|
||||
|
||||
public Document Document => document;
|
||||
|
||||
public UndoHistory<NestUndoState> History => document.History;
|
||||
|
||||
/// <summary>
|
||||
/// Puts a nest read back from the history in the document and rebinds the view to it.
|
||||
/// It must set <see cref="OpenNest.Document.Nest"/>; the default does only that. A view
|
||||
/// that cannot take the nest now throws and the live nest stays.
|
||||
/// </summary>
|
||||
public Action<Nest> SwapIn { get; set; }
|
||||
|
||||
/// <summary>True while <see cref="RestoreNest"/> swaps a nest in.</summary>
|
||||
public bool IsRestoring { get; private set; }
|
||||
|
||||
/// <summary>True while a change scope is open or a nest is being swapped in.</summary>
|
||||
public bool IsChangeInProgress => openChange != null || IsRestoring;
|
||||
|
||||
/// <summary>Whether <see cref="Undo"/> would step back: there is a step and no edit is open.</summary>
|
||||
public bool CanUndo => History.CanUndo && !IsChangeInProgress;
|
||||
|
||||
public bool CanRedo => History.CanRedo && !IsChangeInProgress;
|
||||
|
||||
/// <summary>"Undo Rotate", or "Undo" when there is nothing to undo.</summary>
|
||||
public string UndoText => UndoMenuText(History);
|
||||
|
||||
/// <summary>"Redo Fill", or "Redo" when there is nothing to redo.</summary>
|
||||
public string RedoText => RedoMenuText(History);
|
||||
|
||||
public static string UndoMenuText<TState>(UndoHistory<TState> history)
|
||||
where TState : class, IUndoState =>
|
||||
history?.UndoLabel is { } label ? $"Undo {label}" : "Undo";
|
||||
|
||||
public static string RedoMenuText<TState>(UndoHistory<TState> history)
|
||||
where TState : class, IUndoState =>
|
||||
history?.RedoLabel is { } label ? $"Redo {label}" : "Redo";
|
||||
|
||||
/// <summary>
|
||||
/// True when the nest differs from the state last saved (or opened): the history has
|
||||
/// moved off its save point, or an edit no scope recorded is pending.
|
||||
/// </summary>
|
||||
public bool HasUnsavedChanges =>
|
||||
History.Current != null
|
||||
&& (!History.IsAtSavePoint || NestFingerprint.Compute(document.Nest) != recordedFingerprint);
|
||||
|
||||
/// <summary>True when the nest changed since the last recorded state without a scope.</summary>
|
||||
public bool HasUnrecordedChange =>
|
||||
History.Current != null && NestFingerprint.Compute(document.Nest) != recordedFingerprint;
|
||||
|
||||
/// <summary>
|
||||
/// Starts the history over from the nest as it stands, as opening it does. The state is
|
||||
/// treated as saved.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
History.Reset(new NestUndoState(NestSnapshot.Capture(document.Nest)));
|
||||
recordedFingerprint = NestFingerprint.Compute(document.Nest);
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <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 (IsRestoring)
|
||||
return ChangeScope.Detached();
|
||||
|
||||
RecordUnrecordedChange();
|
||||
openChange = ChangeScope.Root(label, coalesceKey, EndChange);
|
||||
return openChange;
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="edit"/>, which changes the nest, as one undoable step.</summary>
|
||||
public void RecordChange(string label, Action edit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(edit);
|
||||
using var change = BeginChange(label);
|
||||
change.MarkChanged();
|
||||
edit();
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
/// <summary>Steps back one edit; does nothing while an edit or restore is in progress.</summary>
|
||||
public void Undo()
|
||||
{
|
||||
if (IsChangeInProgress)
|
||||
return;
|
||||
RecordUnrecordedChange();
|
||||
if (History.CanUndo)
|
||||
Restore(History.Undo(), History.Redo);
|
||||
}
|
||||
|
||||
/// <summary>Repeats the next undone edit; does nothing while an edit or restore is in progress.</summary>
|
||||
public void Redo()
|
||||
{
|
||||
if (IsChangeInProgress)
|
||||
return;
|
||||
// An edit made since the undo drops what could be redone.
|
||||
RecordUnrecordedChange();
|
||||
if (History.CanRedo)
|
||||
Restore(History.Redo(), History.Undo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the nest as it stands saved, committing any edit no scope recorded first so
|
||||
/// the save point covers it.
|
||||
/// </summary>
|
||||
public void MarkSaved()
|
||||
{
|
||||
RecordUnrecordedChange();
|
||||
if (History.Current != null)
|
||||
History.MarkSaved();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Commits an edit no scope recorded as its own entry, so a rollback, Undo or Redo
|
||||
/// does not silently discard it, and a save marks it saved. Detected by fingerprint, so
|
||||
/// best effort.
|
||||
/// </summary>
|
||||
public void RecordUnrecordedChange()
|
||||
{
|
||||
if (HasUnrecordedChange)
|
||||
Commit(UnrecordedChangeLabel, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True the first time an unrecorded edit is seen, for a debug warning that an entry
|
||||
/// point forgot its scope; false while a scope is open or for the edit already reported.
|
||||
/// </summary>
|
||||
public bool TakeUnrecordedChangeWarning()
|
||||
{
|
||||
if (IsChangeInProgress || History.Current == null)
|
||||
return false;
|
||||
var fingerprint = NestFingerprint.Compute(document.Nest);
|
||||
if (fingerprint == recordedFingerprint || fingerprint == warnedFingerprint)
|
||||
return false;
|
||||
warnedFingerprint = fingerprint;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the document's nest with <paramref name="restored"/>, a copy read back from
|
||||
/// the history, through <see cref="SwapIn"/>. The nest's identity (name, status, author,
|
||||
/// creation date) is carried over from the live nest; nothing it does is recorded.
|
||||
/// </summary>
|
||||
public void RestoreNest(Nest restored)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(restored);
|
||||
var live = document.Nest;
|
||||
restored.Name = live.Name;
|
||||
restored.Status = live.Status;
|
||||
restored.MadeBy = live.MadeBy;
|
||||
restored.DateCreated = live.DateCreated;
|
||||
|
||||
IsRestoring = true;
|
||||
try
|
||||
{
|
||||
if (SwapIn != null)
|
||||
SwapIn(restored);
|
||||
else
|
||||
document.Nest = restored;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsRestoring = false;
|
||||
}
|
||||
|
||||
recordedFingerprint = NestFingerprint.Compute(document.Nest);
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
Restored?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <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(document.Nest);
|
||||
}
|
||||
catch
|
||||
{
|
||||
moveBack();
|
||||
throw;
|
||||
}
|
||||
RestoreNest(restored);
|
||||
}
|
||||
|
||||
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(document.Nest));
|
||||
}
|
||||
|
||||
private void Commit(string label, object coalesceKey)
|
||||
{
|
||||
History.Commit(label, new NestUndoState(NestSnapshot.Capture(document.Nest)), coalesceKey);
|
||||
recordedFingerprint = NestFingerprint.Compute(document.Nest);
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,107 +5,60 @@ using System.Windows.Forms;
|
||||
using OpenNest.Actions;
|
||||
using OpenNest.CutOffs;
|
||||
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.
|
||||
// Undo and Redo: the history holds whole-nest copies and a restore swaps one in. Recording,
|
||||
// the fingerprint check and stepping are the shared NestUndoRecorder; this window rebinds.
|
||||
public partial class EditNestForm
|
||||
{
|
||||
private ChangeScope openChange;
|
||||
private int recordedFingerprint;
|
||||
private bool restoringNest;
|
||||
private NestUndoRecorder undo;
|
||||
|
||||
/// <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>The shared recorder of this window's nest edits.</summary>
|
||||
internal NestUndoRecorder UndoRecorder => undo ??= CreateRecorder();
|
||||
|
||||
/// <summary>True while a change scope is open or a nest is being swapped in.</summary>
|
||||
public bool IsChangeInProgress => openChange != null || restoringNest;
|
||||
public bool IsChangeInProgress => UndoRecorder.IsChangeInProgress;
|
||||
|
||||
/// <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;
|
||||
}
|
||||
public ChangeScope BeginChange(string label, object coalesceKey = null) =>
|
||||
UndoRecorder.BeginChange(label, coalesceKey);
|
||||
|
||||
/// <summary>Runs <paramref name="edit"/>, which changes the nest, as one undoable step.</summary>
|
||||
public void RecordChange(string label, System.Action edit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(edit);
|
||||
using var change = BeginChange(label);
|
||||
change.MarkChanged();
|
||||
edit();
|
||||
change.Complete();
|
||||
}
|
||||
public void RecordChange(string label, System.Action edit) => UndoRecorder.RecordChange(label, edit);
|
||||
|
||||
/// <summary>Whether <see cref="Undo"/> would step back: no edit or inspection is open.</summary>
|
||||
public bool CanUndo => History.CanUndo && CanRestore;
|
||||
public bool CanUndo => UndoRecorder.CanUndo && !IsInspecting;
|
||||
|
||||
public bool CanRedo => History.CanRedo && CanRestore;
|
||||
|
||||
private bool CanRestore => !IsChangeInProgress && !IsInspecting;
|
||||
public bool CanRedo => UndoRecorder.CanRedo && !IsInspecting;
|
||||
|
||||
public void Undo()
|
||||
{
|
||||
if (!CanRestore)
|
||||
return;
|
||||
RecordUnrecordedChange();
|
||||
if (History.CanUndo)
|
||||
Restore(History.Undo(), History.Redo);
|
||||
if (!IsInspecting)
|
||||
UndoRecorder.Undo();
|
||||
}
|
||||
|
||||
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);
|
||||
if (!IsInspecting)
|
||||
UndoRecorder.Redo();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the nest differs from the state last saved (or opened): the history has
|
||||
/// moved off its save point, or an edit no scope recorded is pending.
|
||||
/// </summary>
|
||||
public bool HasUnsavedChanges =>
|
||||
History.Current != null
|
||||
&& (!History.IsAtSavePoint || NestFingerprint.Compute(Nest) != recordedFingerprint);
|
||||
public bool HasUnsavedChanges => UndoRecorder.HasUnsavedChanges;
|
||||
|
||||
/// <summary>
|
||||
/// Marks the nest as it stands saved, for a nest something else wrote to the server
|
||||
@@ -113,54 +66,36 @@ namespace OpenNest.Forms
|
||||
/// </summary>
|
||||
internal void MarkSaved()
|
||||
{
|
||||
RecordUnrecordedChange();
|
||||
if (History.Current != null)
|
||||
History.MarkSaved();
|
||||
UndoRecorder.MarkSaved();
|
||||
UpdateTitle();
|
||||
}
|
||||
|
||||
/// <summary>Shows the nest's name, marked with an asterisk while it has unsaved changes.</summary>
|
||||
internal void UpdateTitle() => Text = HasUnsavedChanges ? $"{Nest.Name} *" : Nest.Name;
|
||||
|
||||
private NestUndoRecorder CreateRecorder()
|
||||
{
|
||||
var recorder = new NestUndoRecorder(Document) { SwapIn = SwapInRestoredNest };
|
||||
recorder.Changed += (_, _) => UpdateTitle();
|
||||
recorder.Restored += (_, _) => NestRestored?.Invoke(this, EventArgs.Empty);
|
||||
return recorder;
|
||||
}
|
||||
|
||||
private void InitializeHistory()
|
||||
{
|
||||
History.Reset(new NestUndoState(NestSnapshot.Capture(Nest)));
|
||||
recordedFingerprint = NestFingerprint.Compute(Nest);
|
||||
History.Changed += (_, _) => UpdateTitle();
|
||||
UndoRecorder.Reset();
|
||||
#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);
|
||||
UpdateTitle();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Commits an edit no scope recorded as its own entry, so a rollback, Undo or Redo
|
||||
/// does not silently discard it, and a save marks it saved. Detected by fingerprint, so
|
||||
/// best effort.
|
||||
/// </summary>
|
||||
internal void RecordUnrecordedChange()
|
||||
{
|
||||
if (History.Current != null && NestFingerprint.Compute(Nest) != recordedFingerprint)
|
||||
Commit("Change", null);
|
||||
}
|
||||
internal void RecordUnrecordedChange() => UndoRecorder.RecordUnrecordedChange();
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the document's nest with <paramref name="restored"/>, a copy read back from
|
||||
@@ -168,20 +103,16 @@ namespace OpenNest.Forms
|
||||
/// 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)
|
||||
public void RestoreNest(Nest restored) => UndoRecorder.RestoreNest(restored);
|
||||
|
||||
// The recorder's swap-in, run with the identity already carried over and nothing recorded.
|
||||
private void SwapInRestoredNest(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
|
||||
@@ -190,55 +121,43 @@ namespace OpenNest.Forms
|
||||
.ToArray();
|
||||
var viewport = PlateView.CaptureViewport();
|
||||
|
||||
restoringNest = true;
|
||||
// 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.
|
||||
// Regenerating empties a cut-off-only plate for a moment, so the batch keeps
|
||||
// the new-plate sentinel from adding or dropping plates until all are done.
|
||||
PlateManager.BeginBatch();
|
||||
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.
|
||||
// Regenerating empties a cut-off-only plate for a moment, so the batch keeps
|
||||
// the new-plate sentinel from adding or dropping plates until all are done.
|
||||
PlateManager.BeginBatch();
|
||||
try
|
||||
{
|
||||
foreach (var plate in restored.Plates.Where(plate => plate.CutOffs.Count > 0).ToArray())
|
||||
plate.RegenerateCutOffs(PlateView.CutOffSettings);
|
||||
}
|
||||
finally
|
||||
{
|
||||
PlateManager.EndBatch();
|
||||
}
|
||||
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();
|
||||
foreach (var plate in restored.Plates.Where(plate => plate.CutOffs.Count > 0).ToArray())
|
||||
plate.RegenerateCutOffs(PlateView.CutOffSettings);
|
||||
}
|
||||
finally
|
||||
{
|
||||
restoringNest = false;
|
||||
PlateManager.EndBatch();
|
||||
}
|
||||
ColorSchemeRegistry.RecolorDrawings(restored);
|
||||
|
||||
recordedFingerprint = NestFingerprint.Compute(Nest);
|
||||
UpdateTitle();
|
||||
NestRestored?.Invoke(this, EventArgs.Empty);
|
||||
// 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();
|
||||
}
|
||||
|
||||
private void Reselect(int[] indices)
|
||||
@@ -255,7 +174,6 @@ namespace OpenNest.Forms
|
||||
|
||||
#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)
|
||||
@@ -263,11 +181,8 @@ namespace OpenNest.Forms
|
||||
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.");
|
||||
if (UndoRecorder.TakeUnrecordedChangeWarning())
|
||||
Debug.WriteLine($"Undo: '{Nest.Name}' changed outside a change scope; the edit is not recorded yet.");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
using OpenNest.Controls;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Forms
|
||||
{
|
||||
@@ -119,8 +120,8 @@ namespace OpenNest.Forms
|
||||
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";
|
||||
mnuEditUndo.Text = NestUndoRecorder.UndoMenuText(history);
|
||||
mnuEditRedo.Text = NestUndoRecorder.RedoMenuText(history);
|
||||
}
|
||||
|
||||
private void EditForm_NestRestored(object sender, EventArgs e)
|
||||
|
||||
Reference in new issue
Block a user