diff --git a/UndoTree.Tests/UndoTreeApplyTests.cs b/UndoTree.Tests/UndoTreeApplyTests.cs index 03672a0..a2484ca 100644 --- a/UndoTree.Tests/UndoTreeApplyTests.cs +++ b/UndoTree.Tests/UndoTreeApplyTests.cs @@ -29,6 +29,117 @@ public sealed class UndoTreeApplyTests Assert.Empty(result.Conflicts); } + [Fact] + public async Task RevertingAnOperationInTheMiddleKeepsTheLaterOnes() + { + var (manager, document) = Histories.NewDocument("p1"); + using var history = Track(manager, document); + Histories.Edit(manager, () => document.X = 1); + var a = history.Cursor; + Histories.Edit(manager, () => document.Parts[0].Value = 10); + Histories.Edit(manager, () => document.Y = 5); + + var result = await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true); + + Assert.Equal("X=0 Y=5 Parts=[p1:10]", document.Snapshot()); + Assert.Equal(1, result.Applied); + Assert.Empty(result.Conflicts); + Assert.Equal(4, history.Cursor.Depth); + } + + [Fact] + public async Task ARevertIsRecordedAsANewEditThatCanBeUndone() + { + var (manager, document) = Histories.NewDocument("p1"); + using var history = Track(manager, document); + Histories.Edit(manager, () => document.X = 1); + var a = history.Cursor; + Histories.Edit(manager, () => document.Y = 5); + await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true); + + await history.UndoAsync(); + + Assert.Equal("X=1 Y=5 Parts=[p1:0]", document.Snapshot()); + } + + [Fact] + public async Task RevertingAChangeThatALaterOperationChangedAgainIsAConflict() + { + var (manager, document) = Histories.NewDocument("p1"); + using var history = Track(manager, document); + Histories.Edit(manager, () => document.X = 1); + var a = history.Cursor; + Histories.Edit(manager, () => document.X = 2); + + var skipped = await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true); + + Assert.Equal("X=2 Y=0 Parts=[p1:0]", document.Snapshot()); + Assert.Equal(0, skipped.Applied); + Assert.Equal(ConflictKind.SameProperty, Assert.Single(skipped.Conflicts).Kind); + + var overwritten = await history.ApplyAsync([a], ConflictPolicy.Apply, inverse: true); + + Assert.Equal("X=0 Y=0 Parts=[p1:0]", document.Snapshot()); + Assert.Equal(1, overwritten.Applied); + } + + [Fact] + public async Task RevertingSeveralChangesOfOneOperationRestoresThemInReverseOrder() + { + var (manager, document) = Histories.NewDocument("p1"); + using var history = Track(manager, document); + Histories.Edit(manager, () => { document.X = 1; document.Y = 2; document.Parts[0].Value = 3; }); + var a = history.Cursor; + + var result = await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true); + + Assert.Equal("X=0 Y=0 Parts=[p1:0]", document.Snapshot()); + Assert.Equal(3, result.Applied); + } + + [Fact] + public async Task RevertingAListChangeRemovesTheAddedItem() + { + var (manager, document) = Histories.NewDocument("p1"); + using var history = Track(manager, document); + Histories.Edit(manager, () => document.Parts.Add(new Part("p2"))); + var a = history.Cursor; + Histories.Edit(manager, () => document.X = 1); + + await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true); + + Assert.Equal("X=1 Y=0 Parts=[p1:0]", document.Snapshot()); + } + + [Fact] + public async Task AnOperationWithAnActionCannotBeReverted() + { + var (manager, document) = Histories.NewDocument("p1"); + using var history = Track(manager, document); + manager.AddCommand(new UndoRedoActionCommand(() => { }, () => { })); + manager.Record(); + var a = history.Cursor; + + var failure = await Assert.ThrowsAsync(() => history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true)); + + Assert.Equal(Texts.RevertUnsupported, failure.Message); + } + + [Fact] + public async Task OnlyAnOperationOnTheCurrentPathCanBeReverted() + { + var (manager, document) = Histories.NewDocument("p1"); + using var history = Track(manager, document); + Histories.Edit(manager, () => document.X = 1); + var a = history.Cursor; + await history.JumpAsync(history.Root); + + var failure = await Assert.ThrowsAsync(() => history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true)); + + Assert.Equal(Texts.NothingToApply, failure.Message); + Assert.Equal("X=0 Y=0 Parts=[p1:0]", document.Snapshot()); + } + [Fact] public async Task ReplayedOperationsBecomeNewNodesBelowTheCursorAndTheSourceBranchStays() { diff --git a/UndoTree.Tests/UndoTreeViewModelTests.cs b/UndoTree.Tests/UndoTreeViewModelTests.cs index b14a9f3..f6d4a8a 100644 --- a/UndoTree.Tests/UndoTreeViewModelTests.cs +++ b/UndoTree.Tests/UndoTreeViewModelTests.cs @@ -321,6 +321,42 @@ public sealed class UndoTreeViewModelTests return (model, manager, document); } + [Fact] + public void OnlyANodeOnThePathOrTheCurrentOneCanBeReverted() + { + var (model, _, _, a, b, d) = Forked(); + + Assert.False(model.RevertCommand.CanExecute(model.Items[0])); + Assert.True(model.RevertCommand.CanExecute(a)); + Assert.True(model.RevertCommand.CanExecute(d)); + Assert.False(model.RevertCommand.CanExecute(b)); + } + + [Fact] + public void RevertingFromTheMenuUndoesTheOperationAsANewEditAndReportsIt() + { + var (model, _, document, a, _, _) = Forked(); + + model.RevertCommand.Execute(a); + + Assert.Equal("X=0 Y=7 Parts=[p1:0]", document.Snapshot()); + Assert.Equal(string.Format(Texts.ApplyResult, 1, 0), model.ResultText); + } + + [Fact] + public void AnOperationThatCannotBeRevertedIsReportedWithoutChangingAnything() + { + var (model, manager, document) = Open(); + manager.AddCommand(new UndoRedoActionCommand(() => { }, () => { })); + manager.Record(); + var node = model.Items[^1]; + + model.RevertCommand.Execute(node); + + Assert.Equal(Texts.RevertUnsupported, model.ResultText); + Assert.Equal("X=0 Y=0 Parts=[p1:0]", document.Snapshot()); + } + [Fact] public void ConsecutiveChangesToTheSameItemAreShownAsOneRowWithTheCount() { diff --git a/UndoTree/Texts.csv b/UndoTree/Texts.csv index 3206a25..bff0a21 100644 --- a/UndoTree/Texts.csv +++ b/UndoTree/Texts.csv @@ -38,6 +38,9 @@ SelectionOnly,,選択中のアイテムの履歴だけを表示,Show only the hi StatusFiltered,,{0}件中{1}件を表示,Showing {1} of {0},共 {0} 项,显示 {1} 项,共 {0} 項,顯示 {1} 項,{0}개 중 {1}개 표시,Mostrando {1} de {0},عرض {1} من {0},Menampilkan {1} dari {0} FoldRuns,,同じ項目の連続した変更をまとめる,Group consecutive changes to the same item,合并对同一项目的连续更改,合併對同一項目的連續變更,같은 항목의 연속된 변경을 묶기,Agrupar cambios consecutivos del mismo elemento,تجميع التغييرات المتتالية على العنصر نفسه,Kelompokkan perubahan berurutan pada item yang sama FoldedRun,,{0}({1}回),{0} ({1} times),{0}({1} 次),{0}({1} 次),{0} ({1}회),{0} ({1} veces),{0} ({1} مرات),{0} ({1} kali) +Revert,,この操作をリバート,Revert this operation,revert 此操作,revert 此操作,이 작업 리버트,Revertir esta operación,عكس هذه العملية (revert),Revert operasi ini +RevertTip,,この操作の変更を、現在の状態に対する新しい編集として打ち消します。,Undoes the changes of this operation as a new edit on the current state.,将此操作的更改作为对当前状态的新编辑撤销。,將此操作的變更作為對目前狀態的新編輯復原。,이 작업의 변경 내용을 현재 상태에 대한 새 편집으로 되돌립니다.,Deshace los cambios de esta operación como una edición nueva sobre el estado actual.,يتراجع عن تغييرات هذه العملية كتعديل جديد على الحالة الحالية.,Membatalkan perubahan operasi ini sebagai suntingan baru pada keadaan saat ini. +RevertUnsupported,,この操作には、リバートできない処理が含まれています。,This operation contains steps that cannot be reverted.,此操作包含无法 revert 的处理。,此操作包含無法 revert 的處理。,이 작업에는 리버트할 수 없는 처리가 포함되어 있습니다.,Esta operación contiene pasos que no se pueden revertir.,تحتوي هذه العملية على خطوات لا يمكن عكسها.,Operasi ini berisi langkah yang tidak dapat di-revert. ConflictDeadTarget,,{0} / {1}: 対象が存在しないためスキップしました,{0} / {1}: skipped because the target no longer exists,{0} / {1}:对象已不存在,已跳过,{0} / {1}:物件已不存在,已略過,{0} / {1}: 대상이 없어 건너뛰었습니다,{0} / {1}: omitido porque el objetivo ya no existe,{0} / {1}: تم التخطي لأن الهدف لم يعد موجودًا,{0} / {1}: dilewati karena target sudah tidak ada ConflictSameSkipped,,{0} / {1}: 現在の位置で既に変更されているためスキップしました,{0} / {1}: skipped because it was already changed here,{0} / {1}:已在当前位置更改,已跳过,{0} / {1}:已在目前位置變更,已略過,{0} / {1}: 현재 위치에서 이미 변경되어 건너뛰었습니다,{0} / {1}: omitido porque ya se modificó aquí,{0} / {1}: تم التخطي لأنه تغيّر هنا بالفعل,{0} / {1}: dilewati karena sudah diubah di sini ConflictSameApplied,,{0} / {1}: 現在の位置で既に変更されていたため、操作の値で上書きしました,"{0} / {1}: already changed here, overwritten with the value of the operation",{0} / {1}:已在当前位置更改,已用该操作的值覆盖,{0} / {1}:已在目前位置變更,已用該操作的值覆蓋,{0} / {1}: 현재 위치에서 이미 변경되어 작업의 값으로 덮어썼습니다,"{0} / {1}: ya se modificó aquí, sobrescrito con el valor de la operación",{0} / {1}: تغيّر هنا بالفعل وتمت الكتابة فوقه بقيمة العملية,"{0} / {1}: sudah diubah di sini, ditimpa dengan nilai operasi" diff --git a/UndoTree/UndoTreeHistory.cs b/UndoTree/UndoTreeHistory.cs index 772c60e..8ad4af5 100644 --- a/UndoTree/UndoTreeHistory.cs +++ b/UndoTree/UndoTreeHistory.cs @@ -156,7 +156,7 @@ internal class UndoTreeHistory : IDisposable } } - public async Task ApplyAsync(IReadOnlyList sources, ConflictPolicy policy) + public async Task ApplyAsync(IReadOnlyList sources, ConflictPolicy policy, bool inverse = false) { Reconcile(); if (source is null) @@ -165,6 +165,12 @@ internal class UndoTreeHistory : IDisposable if (!source.CanReplay) throw new UndoTreeOperationException(Texts.BranchUnavailable); + if (inverse && sources.Any(node => !(node.IsOnPath || node.IsCurrent) || node.IsRoot)) + throw new UndoTreeOperationException(Texts.NothingToApply); + + if (inverse && sources.Any(node => node.Commands.Any(command => command.Kind is CommandKind.Action or CommandKind.Other))) + throw new UndoTreeOperationException(Texts.RevertUnsupported); + var touched = new HashSet(); var applied = 0; var conflicts = new List(); @@ -182,7 +188,7 @@ internal class UndoTreeHistory : IDisposable { foreach (var node in sources) { - var result = await ReplayAsync(source, node.Handle!, true, policy, touched); + var result = await ReplayAsync(source, node.Handle!, true, policy, touched, inverse); applied += result.Applied; conflicts.AddRange(result.Conflicts); Merge(source.Undo, source.Redo); @@ -300,12 +306,22 @@ internal class UndoTreeHistory : IDisposable return commands.Count == 1 ? commands[0].Text : string.Format(Texts.OperationAndMore, commands[0].Text, commands.Count - 1); } - static async Task ExecuteAsync(IUndoRedoCommandBase command) + static async Task ExecuteAsync(IUndoRedoCommandBase command, bool inverse) { if (command is IUndoRedoCommand synchronous) - synchronous.Redo(); + { + if (inverse) + synchronous.Undo(); + else + synchronous.Redo(); + } else if (command is IUndoRedoAsyncCommand asynchronous) - await asynchronous.RedoAsync(); + { + if (inverse) + await asynchronous.UndoAsync(); + else + await asynchronous.RedoAsync(); + } } void Manager_HistoryChanged(object? sender, EventArgs e) @@ -561,7 +577,7 @@ internal class UndoTreeHistory : IDisposable foreach (var node in descent) { - var result = await ReplayAsync(history, node.Handle!, false, ConflictPolicy.Skip, []); + var result = await ReplayAsync(history, node.Handle!, false, ConflictPolicy.Skip, [], false); if (result.Handle is null) throw new InvalidOperationException(Texts.NothingToApply); @@ -571,9 +587,9 @@ internal class UndoTreeHistory : IDisposable } } - async Task ReplayAsync(IUndoRedoHistory history, object handle, bool check, ConflictPolicy policy, HashSet touched) + async Task ReplayAsync(IUndoRedoHistory history, object handle, bool check, ConflictPolicy policy, HashSet touched, bool inverse) { - var commands = history.CommandsOf(handle); + var commands = inverse ? history.CommandsOf(handle).Reverse().ToArray() : history.CommandsOf(handle); var before = history.Undo; var applied = 0; var conflicts = new List(); @@ -583,7 +599,7 @@ internal class UndoTreeHistory : IDisposable { foreach (var command in commands.Where(command => command.IsAction == pass)) { - if (await ReplayCommandAsync(command, check, policy, touched, conflicts)) + if (await ReplayCommandAsync(command, check, policy, touched, conflicts, inverse)) applied++; } } @@ -598,71 +614,85 @@ internal class UndoTreeHistory : IDisposable return new ReplayResult(recorded ? after[^1] : null, applied, conflicts); } - async Task ReplayCommandAsync(IUndoRedoCommandBase command, bool check, ConflictPolicy policy, HashSet touched, List conflicts) + async Task ReplayCommandAsync(IUndoRedoCommandBase command, bool check, ConflictPolicy policy, HashSet touched, List conflicts, bool inverse) { if (command.IsAction) { - await ExecuteAsync(command); + await ExecuteAsync(command, inverse); manager.AddCommand(command); return true; } if (!check) { - await ExecuteAsync(command); + await ExecuteAsync(command, inverse); return true; } var view = UndoRedoCommandView.Read(command); var info = view.Describe(); - if (view.Target is { } target && view.Kind is CommandKind.Property or CommandKind.Indexer && !UndoRedoCommandView.IsLive(target)) + var verdict = Judge(view, touched, inverse); + var apply = policy == ConflictPolicy.Apply; + switch (verdict) { - conflicts.Add(new UndoTreeConflict(ConflictKind.DeadTarget, info.TargetLabel, info.Member, false)); - return false; + case Verdict.DeadTarget: + conflicts.Add(new UndoTreeConflict(ConflictKind.DeadTarget, info.TargetLabel, info.Member, false)); + return false; + case Verdict.Merged: + conflicts.Add(new UndoTreeConflict(ConflictKind.CollectionMerged, info.TargetLabel, info.Member, true)); + TryMergeList(view, inverse, out var property, out var merged); + property!.SetValue(view.Target, merged); + return true; + case Verdict.Unreadable: + case Verdict.SameProperty: + conflicts.Add(new UndoTreeConflict(verdict == Verdict.Unreadable ? ConflictKind.Unreadable : ConflictKind.SameProperty, info.TargetLabel, info.Member, apply)); + if (apply) + await ExecuteAsync(command, inverse); + + return apply; + default: + await ExecuteAsync(command, inverse); + return true; } - - if (view.Kind is CommandKind.Property or CommandKind.Indexer && !view.IsReadable) - { - var apply = policy == ConflictPolicy.Apply; - conflicts.Add(new UndoTreeConflict(ConflictKind.Unreadable, info.TargetLabel, info.Member, apply)); - if (apply) - await ExecuteAsync(command); - - return apply; - } - - if (view.Kind == CommandKind.Property && TryMergeList(view)) - { - conflicts.Add(new UndoTreeConflict(ConflictKind.CollectionMerged, info.TargetLabel, info.Member, true)); - return true; - } - - if (view.Key is { } key && touched.Contains(key)) - { - var apply = policy == ConflictPolicy.Apply; - conflicts.Add(new UndoTreeConflict(ConflictKind.SameProperty, info.TargetLabel, info.Member, apply)); - if (apply) - await ExecuteAsync(command); - - return apply; - } - - await ExecuteAsync(command); - return true; } - static bool TryMergeList(UndoRedoCommandView view) + static Verdict Judge(UndoRedoCommandView view, HashSet touched, bool inverse) { - var property = view.Target!.GetType().GetProperty(view.Member, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (view.Kind is CommandKind.Property or CommandKind.Indexer) + { + if (view.Target is { } target && !UndoRedoCommandView.IsLive(target)) + return Verdict.DeadTarget; + + if (!view.IsReadable) + return Verdict.Unreadable; + } + + if (view.Kind == CommandKind.Property && TryMergeList(view, inverse, out _, out _)) + return Verdict.Merged; + + return view.Key is { } key && touched.Contains(key) ? Verdict.SameProperty : Verdict.Run; + } + + static bool TryMergeList(UndoRedoCommandView view, bool inverse, out PropertyInfo? property, out object? merged) + { + merged = null; + property = view.Target!.GetType().GetProperty(view.Member, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property is null || !property.CanRead || !property.CanWrite) return false; var current = property.GetValue(view.Target); - if (Equals(current, view.OldValue) || !UndoTreeListMerge.TryMerge(current, view.OldValue, view.NewValue, out var merged)) - return false; + var from = inverse ? view.NewValue : view.OldValue; + var to = inverse ? view.OldValue : view.NewValue; + return !Equals(current, from) && UndoTreeListMerge.TryMerge(current, from, to, out merged); + } - property.SetValue(view.Target, merged); - return true; + enum Verdict + { + Run, + DeadTarget, + Unreadable, + Merged, + SameProperty, } sealed record ReplayResult(object? Handle, int Applied, IReadOnlyList Conflicts); diff --git a/UndoTree/UndoTreeView.xaml b/UndoTree/UndoTreeView.xaml index a930de3..4ee3f74 100644 --- a/UndoTree/UndoTreeView.xaml +++ b/UndoTree/UndoTreeView.xaml @@ -21,6 +21,8 @@ + +