前回の履歴のノードへ操作を再生して戻す処理を加える

このコミットが含まれているのは:
routersys committed 2026-11-01 17:47:16 +09:00
1 親 4abc96222f
コミット da87eecc3b
5ファイル変更
+584

検索条件に一致するファイルはありません

+327
ファイルの表示
@@ -0,0 +1,327 @@
using System.Text.Json;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Project;
using YukkuriMovieMaker.UndoRedo;
namespace UndoTree.Tests;
public sealed class UndoTreeRestoreTests
{
const string OpenHash = "H0";
const string SavedHash = "H2";
static UndoTreeHistory Track(UndoRedoManager manager, IUndoRedoable root)
=> new(manager, new AsyncAwaitStatus(), [root], 100, UndoRedoManagerReader.Create(manager));
static (UndoRedoManager Manager, Document Document, UndoTreeHistory History) Open(int x = 0, int y = 0, params string[] parts)
{
var document = new Document { X = x, Y = y };
foreach (var label in parts)
document.Parts.Add(new Part(label));
var manager = new UndoRedoManager();
manager.Subscribe(document);
return (manager, document, Track(manager, document));
}
static IReadOnlyList<UndoTreeNodeViewModel> Archive(UndoTreeHistory history)
{
var json = JsonSerializer.Serialize(history.ToRecord());
var nodes = UndoTreeArchive.Restore(JsonSerializer.Deserialize<UndoTreeRecord>(json)!);
nodes[0].SavedHash = OpenHash;
return nodes;
}
static async Task<IReadOnlyList<UndoTreeNodeViewModel>> Session()
{
var (manager, document, history) = Open(0, 0, "p");
using (history)
{
Histories.Edit(manager, () => document.X = 1);
Histories.Edit(manager, () => document.Y = 5);
await manager.UndoAsync();
Histories.Edit(manager, () => document.Parts.Add(new Part("q")));
var nodes = Archive(history);
nodes.Single(node => node.Label == "Document / Y").SavedHash = SavedHash;
return nodes;
}
}
static UndoTreeNodeViewModel Node(IReadOnlyList<UndoTreeNodeViewModel> nodes, string label) => nodes.Single(node => node.Label == label);
static UndoTreeNodeViewModel Branch(IReadOnlyList<UndoTreeNodeViewModel> nodes) => nodes.Single(node => node.Steps?.Any(step => step.Kind == nameof(StepKind.Collection)) == true);
[Fact]
public async Task ADescendantIsReachedByReplayingEveryOperationOnTheWayAsOneNode()
{
var nodes = await Session();
var (manager, document, history) = Open(0, 0, "p");
using var _ = history;
var plan = UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash);
var result = await history.RestoreAsync(plan);
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(2, result.Applied);
Assert.Equal((1, 5), (document.X, document.Y));
Assert.Equal(2, history.Count);
await manager.UndoAsync();
Assert.Equal((0, 0), (document.X, document.Y));
}
[Fact]
public async Task AnotherBranchIsReachedTheSameWay()
{
var nodes = await Session();
var (_, document, history) = Open(0, 0, "p");
using var _ = history;
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Branch(nodes), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal((1, 0), (document.X, document.Y));
Assert.Equal(["p", "q"], document.Parts.Select(part => part.Label));
}
[Fact]
public async Task AnAncestorOfTheSavedNodeIsReachedByUndoingTheOperations()
{
var nodes = await Session();
var (_, document, history) = Open(1, 5, "p");
using var _ = history;
var plan = UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / X"), SavedHash);
var result = await history.RestoreAsync(plan);
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal((1, 0), (document.X, document.Y));
}
[Fact]
public async Task TheOtherBranchOfTheSavedNodeIsReachedByUndoingAndThenReplaying()
{
var nodes = await Session();
var (_, document, history) = Open(1, 5, "p");
using var _ = history;
var plan = UndoTreeRestorePlan.For(nodes, Branch(nodes), SavedHash);
var result = await history.RestoreAsync(plan);
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal((1, 0), (document.X, document.Y));
Assert.Equal(["p", "q"], document.Parts.Select(part => part.Label));
}
[Fact]
public async Task TheSavedStateItselfNeedsNoOperationAndLeavesTheCursorAtTheRoot()
{
var nodes = await Session();
var (_, document, history) = Open(0, 0, "p");
using var _ = history;
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[0], OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(0, result.Applied);
Assert.Equal(1, history.Count);
Assert.Equal((0, 0), (document.X, document.Y));
}
[Fact]
public async Task EditsMadeSinceTheProjectWasOpenedAreUndoneFirstBecauseTheRecordStartsFromTheSavedState()
{
var nodes = await Session();
var (manager, document, history) = Open(0, 0, "p");
using var _ = history;
Histories.Edit(manager, () => document.X = 3);
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal((1, 5), (document.X, document.Y));
}
[Fact]
public async Task TheNearestAnchorIsUsedWhenSeveralNodesMatchTheProject()
{
var nodes = await Session();
Node(nodes, "Document / Y").SavedHash = OpenHash;
var plan = UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash);
Assert.True(plan.IsPossible);
Assert.Empty(plan.Undo);
Assert.Empty(plan.Redo);
}
[Fact]
public async Task AProjectThatDiffersFromTheRecordIsLeftUntouched()
{
var nodes = await Session();
var (manager, document, history) = Open(7, 0, "p");
using var _ = history;
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Conflict, result.Outcome);
Assert.Equal("X", result.Detail);
Assert.Equal((7, 0), (document.X, document.Y));
Assert.False(manager.IsUndoable);
Assert.False(manager.IsRedoable);
Assert.Equal(1, history.Count);
}
[Fact]
public async Task AFailureAfterSomeOperationsWereAppliedUndoesThemAll()
{
var nodes = await Session();
var (manager, document, history) = Open(0, 3, "p");
using var _ = history;
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Conflict, result.Outcome);
Assert.Equal("Y", result.Detail);
Assert.Equal(1, result.Applied);
Assert.Equal((0, 3), (document.X, document.Y));
Assert.False(manager.IsUndoable);
Assert.False(manager.IsRedoable);
}
[Fact]
public async Task ARootThatIsNotTheStateWhenTheProjectWasOpenedCannotBeRestoredInto()
{
var nodes = await Session();
var document = new Document();
document.Parts.Add(new Part("p"));
var manager = new UndoRedoManager { Capacity = 2 };
manager.Subscribe(document);
using var history = Track(manager, document);
Histories.Edit(manager, () => document.X = 1);
Histories.Edit(manager, () => document.X = 2);
Assert.False(history.RootIsOpenState);
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Unavailable, result.Outcome);
Assert.Equal(2, document.X);
}
[Fact]
public async Task ThePlanSaysWhyARestoreIsNotPossible()
{
var nodes = await Session();
var target = Node(nodes, "Document / Y");
Assert.Equal(UndoTreeRestoreBlock.NoProject, UndoTreeRestorePlan.For(nodes, target, string.Empty).Block);
Assert.Equal(UndoTreeRestoreBlock.NoAnchor, UndoTreeRestorePlan.For(nodes, target, "other").Block);
Assert.True(UndoTreeRestorePlan.For(nodes, target, OpenHash).IsPossible);
}
[Fact]
public void ANodeThatCannotBeReplayedBlocksEveryPathThroughIt()
{
var (manager, document, history) = Open();
using var _ = history;
Histories.Edit(manager, () => document.X = 1);
Histories.Edit(manager, () => manager.AddCommand(new UndoRedoActionCommand(() => { }, () => { })));
Histories.Edit(manager, () => document.Y = 2);
var nodes = Archive(history);
var plan = UndoTreeRestorePlan.For(nodes, nodes[^1], OpenHash);
Assert.Equal(UndoTreeRestoreBlock.NotReplayable, plan.Block);
Assert.Same(nodes[2], plan.Offending);
Assert.True(UndoTreeRestorePlan.For(nodes, nodes[1], OpenHash).IsPossible);
}
[Fact]
public async Task AnImmutableListIsRebuiltWithTheRecordedElements()
{
var (managerA, sheetA) = Histories.NewSheet("a", "b", "c");
using var historyA = Track(managerA, sheetA);
Histories.Edit(managerA, () => sheetA.Parts = sheetA.Parts.RemoveAt(1).Add(new Part("d")));
var nodes = Archive(historyA);
var (_, sheetB) = Histories.NewSheet("a", "b", "c");
var managerB = new UndoRedoManager();
managerB.Subscribe(sheetB);
using var historyB = Track(managerB, sheetB);
var result = await historyB.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[1], OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(["a", "c", "d"], sheetB.Parts.Select(part => part.Label));
}
[Fact]
public async Task ABatchOfOperationsIsUndoneInReverseOrder()
{
var (managerA, sheetA) = Histories.NewSheet("a", "b");
using var historyA = Track(managerA, sheetA);
Histories.Edit(managerA, () =>
{
sheetA.Parts = sheetA.Parts.Add(new Part("n"));
sheetA.Parts[^1].Value = 4;
});
var nodes = Archive(historyA);
nodes[1].SavedHash = SavedHash;
var sheetB = new Sheet();
var added = new Part("n") { Value = 4 };
sheetB.Seed([new Part("a"), new Part("b"), added]);
var managerB = new UndoRedoManager();
managerB.Subscribe(sheetB);
using var historyB = Track(managerB, sheetB);
var result = await historyB.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[0], SavedHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(["a", "b"], sheetB.Parts.Select(part => part.Label));
}
[Fact]
public async Task AnElementAddedAndChangedInOneEditComesBackWithItsValue()
{
var (managerA, documentA, historyA) = Open();
using (historyA)
{
Histories.Edit(managerA, () =>
{
var part = new Part("n");
documentA.Parts.Add(part);
part.Value = 3;
});
var nodes = Archive(historyA);
var (_, documentB, historyB) = Open();
using var _ = historyB;
var result = await historyB.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[1], OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(["n:3"], documentB.Parts.Select(part => part.ToString()));
}
}
[Fact]
public async Task ARecordedCallIsInvokedOnTheMatchingObject()
{
var first = new Speaker();
var managerA = new UndoRedoManager();
managerA.Subscribe(first);
using var historyA = Track(managerA, first);
Histories.Edit(managerA, () => managerA.AddCommand(new UndoRedoAsyncTaskCommand(first.SpeakLaterAsync, first.SpeakLaterAsync)));
var nodes = Archive(historyA);
var second = new Speaker();
var managerB = new UndoRedoManager();
managerB.Subscribe(second);
using var historyB = Track(managerB, second);
var result = await historyB.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[1], OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(1, second.Calls);
Assert.Equal(0, first.Calls);
}
}
+61
ファイルの表示
@@ -26,6 +26,7 @@ internal class UndoTreeHistory : IDisposable
UndoTreeSaveWatcher? saveWatcher;
UndoTreeOwners? owners;
string? rootHash;
bool rootTrimmed;
internal UndoTreeHistory(UndoRedoManager manager, AsyncAwaitStatus asyncAwaitStatus, IReadOnlyList<IUndoRedoable> roots, int capacity, UndoRedoManagerReader? reader, Action<Exception>? report = null)
{
@@ -184,6 +185,61 @@ internal class UndoTreeHistory : IDisposable
}
}
public bool RootIsOpenState => !rootTrimmed;
public async Task<UndoTreeRestoreResult> RestoreAsync(UndoTreeRestorePlan plan)
{
Reconcile();
if (source is null)
throw new UndoTreeOperationException(Texts.Unsupported);
if (!plan.IsPossible || rootTrimmed)
return new UndoTreeRestoreResult(UndoTreeRestoreOutcome.Unavailable, string.Empty, 0);
if (!ReferenceEquals(Cursor, Root))
await JumpAsync(Root);
var applied = 0;
isNavigating = true;
try
{
using (asyncAwaitStatus.Lock())
{
foreach (var (node, inverse) in plan.Undo.Select(node => (node, true)).Concat(plan.Redo.Select(node => (node, false))))
{
if (await UndoTreeReplayer.ApplyAsync(Roots, node.Steps!, inverse) is { } failure)
{
await DiscardAsync(source);
return new UndoTreeRestoreResult(UndoTreeRestoreOutcome.Conflict, failure, applied);
}
applied += node.Steps!.Count;
}
manager.Record();
}
}
finally
{
isNavigating = false;
Reconcile();
}
return new UndoTreeRestoreResult(UndoTreeRestoreOutcome.Done, string.Empty, applied);
}
async Task DiscardAsync(IUndoRedoHistory history)
{
var last = history.Undo.Count > 0 ? history.Undo[^1] : null;
manager.Record();
if (history.Undo.Count == 0 || ReferenceEquals(history.Undo[^1], last))
return;
await manager.UndoAsync();
if (history.CanRewriteRedo)
history.TrySetRedo([]);
}
public async Task<UndoTreeApplyResult> ApplyAsync(IReadOnlyList<UndoTreeNodeViewModel> sources, ConflictPolicy policy, bool inverse = false)
{
Reconcile();
@@ -457,6 +513,7 @@ internal class UndoTreeHistory : IDisposable
Root = CreateRoot();
Cursor = Root;
owners = null;
rootTrimmed = false;
}
void MoveCursor(UndoTreeNodeViewModel next)
@@ -510,6 +567,9 @@ internal class UndoTreeHistory : IDisposable
node = child;
}
if (undo.Count >= manager.Capacity)
rootTrimmed = true;
if (!ReferenceEquals(Cursor, node))
{
MoveCursor(node);
@@ -586,6 +646,7 @@ internal class UndoTreeHistory : IDisposable
void Promote(UndoTreeNodeViewModel node)
{
rootTrimmed = true;
var keep = new HashSet<UndoTreeNodeViewModel>(ReferenceEqualityComparer.Instance);
var pending = new Stack<UndoTreeNodeViewModel>();
pending.Push(node);
+141
ファイルの表示
@@ -0,0 +1,141 @@
using System.Collections;
using System.Collections.Immutable;
using System.Reflection;
using YukkuriMovieMaker.UndoRedo;
namespace UndoTree;
internal static class UndoTreeReplayer
{
const BindingFlags Instance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
static readonly MethodInfo CreateRange = typeof(ImmutableList).GetMethods().Single(method => method.Name == nameof(ImmutableList.CreateRange) && method.GetParameters().Length == 1);
public static async Task<string?> ApplyAsync(IReadOnlyList<IUndoRedoable> roots, IReadOnlyList<UndoTreeStep> steps, bool inverse)
{
var ordered = inverse ? steps.Reverse().ToArray() : steps.ToArray();
foreach (var pass in new[] { false, true })
{
foreach (var step in ordered.Where(step => step.Kind == nameof(StepKind.Call) == pass))
{
if (await ApplyOneAsync(roots, step, inverse) is { } failure)
return failure;
}
}
return null;
}
public static string Describe(UndoTreeStep step)
=> string.Join(" / ", step.Target.Skip(1).Select(hop => hop.Index >= 0 ? $"{hop.Property}[{hop.Index}]" : hop.Property).Append(step.Member).Where(part => part.Length > 0));
static async Task<string?> ApplyOneAsync(IReadOnlyList<IUndoRedoable> roots, UndoTreeStep step, bool inverse)
{
if (UndoTreeAddress.Resolve(roots, step.Target) is not { } target)
return Describe(step);
try
{
var applied = step.Kind switch
{
nameof(StepKind.Set) => ApplySet(target, step, inverse),
nameof(StepKind.Replace) => ApplyReplace(target, step, inverse),
nameof(StepKind.Collection) => ApplyCollection(target, step, inverse),
nameof(StepKind.Call) => await ApplyCallAsync(target, step),
_ => false,
};
return applied ? null : Describe(step);
}
catch (Exception exception) when (exception is TargetInvocationException or ArgumentException or InvalidCastException or NotSupportedException or InvalidOperationException)
{
return Describe(step);
}
}
static bool ApplySet(object target, UndoTreeStep step, bool inverse)
{
if (UndoTreeMembers.PropertyOf(target, step.Member) is not { CanWrite: true } property)
return false;
var declared = property.PropertyType;
var current = UndoTreeMembers.ValueOf(target, property);
if (!UndoTreeCodec.TryDecode(inverse ? step.After : step.Before, declared, out var expected) || !UndoTreeCodec.TryDecode(inverse ? step.Before : step.After, declared, out var next))
return false;
if (UndoTreeCodec.IsPlain(declared) ? !Equals(current, expected) : (current is null) != (expected is null))
return false;
property.SetValue(target, next);
return true;
}
static bool ApplyReplace(object target, UndoTreeStep step, bool inverse)
{
if (step.List is not { } change || UndoTreeMembers.PropertyOf(target, step.Member) is not { CanWrite: true } property || UndoTreeMembers.ElementOf(property.PropertyType) is not { } element)
return false;
if (UndoTreeMembers.ValueOf(target, property) is not IEnumerable current || !change.TryApply(current.Cast<object?>().ToArray(), inverse, element, out var result))
return false;
var items = Array.CreateInstance(element, result.Count);
for (var index = 0; index < result.Count; index++)
items.SetValue(result[index], index);
property.SetValue(target, CreateRange.MakeGenericMethod(element).Invoke(null, [items]));
return true;
}
static bool ApplyCollection(object target, UndoTreeStep step, bool inverse)
{
if (step.List is not { } change || target is not IList collection || UndoTreeMembers.ElementOf(collection.GetType()) is not { } element)
return false;
if (!change.TryApply(collection.Cast<object?>().ToArray(), inverse, element, out var result))
return false;
Reshape(collection, result);
return true;
}
static async Task<bool> ApplyCallAsync(object target, UndoTreeStep step)
{
if (target.GetType().GetMethod(step.Member, Instance, null, Type.EmptyTypes, null) is not { } method || method.Invoke(target, null) is not Task task)
return false;
await task;
return true;
}
static void Reshape(IList collection, IReadOnlyList<object?> wanted)
{
var keep = new HashSet<object?>(wanted, ReferenceEqualityComparer.Instance);
for (var index = collection.Count - 1; index >= 0; index--)
{
if (!keep.Contains(collection[index]))
collection.RemoveAt(index);
}
for (var index = 0; index < wanted.Count; index++)
{
if (index < collection.Count && ReferenceEquals(collection[index], wanted[index]))
continue;
var found = IndexOfFrom(collection, wanted[index], index + 1);
if (found >= 0)
collection.RemoveAt(found);
collection.Insert(index, wanted[index]);
}
}
static int IndexOfFrom(IList collection, object? item, int start)
{
for (var index = start; index < collection.Count; index++)
{
if (ReferenceEquals(collection[index], item))
return index;
}
return -1;
}
}
+45
ファイルの表示
@@ -0,0 +1,45 @@
namespace UndoTree;
internal enum UndoTreeRestoreBlock
{
None,
NoProject,
NoAnchor,
NotReplayable,
}
internal sealed record UndoTreeRestorePlan(IReadOnlyList<UndoTreeNodeViewModel> Undo, IReadOnlyList<UndoTreeNodeViewModel> Redo, UndoTreeRestoreBlock Block, UndoTreeNodeViewModel? Offending)
{
public bool IsPossible => Block == UndoTreeRestoreBlock.None;
public static UndoTreeRestorePlan For(IReadOnlyList<UndoTreeNodeViewModel> archived, UndoTreeNodeViewModel target, string projectHash)
{
if (projectHash.Length == 0)
return Blocked(UndoTreeRestoreBlock.NoProject, null);
var anchors = archived.Where(node => node.SavedHash == projectHash).ToArray();
if (anchors.Length == 0)
return Blocked(UndoTreeRestoreBlock.NoAnchor, null);
UndoTreeRestorePlan? best = null;
UndoTreeNodeViewModel? offending = null;
foreach (var anchor in anchors)
{
var ancestor = UndoTreeNodeViewModel.CommonAncestor(anchor, target);
var undo = anchor.StepsBelow(ancestor).Reverse().ToArray();
var redo = target.StepsBelow(ancestor);
if (undo.Concat(redo).FirstOrDefault(node => node.Steps is null) is { } stuck)
{
offending ??= stuck;
continue;
}
if (best is null || undo.Length + redo.Count < best.Undo.Count + best.Redo.Count)
best = new UndoTreeRestorePlan(undo, redo, UndoTreeRestoreBlock.None, null);
}
return best ?? Blocked(UndoTreeRestoreBlock.NotReplayable, offending);
}
static UndoTreeRestorePlan Blocked(UndoTreeRestoreBlock block, UndoTreeNodeViewModel? offending) => new([], [], block, offending);
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
namespace UndoTree;
internal enum UndoTreeRestoreOutcome
{
Done,
Unavailable,
Conflict,
}
internal sealed record UndoTreeRestoreResult(UndoTreeRestoreOutcome Outcome, string Detail, int Applied);