diff --git a/UndoTree.Tests/UndoTreeApplyTests.cs b/UndoTree.Tests/UndoTreeApplyTests.cs index 75cd69f..c4e7975 100644 --- a/UndoTree.Tests/UndoTreeApplyTests.cs +++ b/UndoTree.Tests/UndoTreeApplyTests.cs @@ -41,15 +41,15 @@ public sealed class UndoTreeApplyTests await history.JumpAsync(history.Root); Histories.Edit(manager, () => document.X = 2); - var independent = history.PredictConflicts([b], ConflictPolicy.Skip); - var skipped = history.PredictConflicts([a], ConflictPolicy.Skip); - var overwritten = history.PredictConflicts([a], ConflictPolicy.Apply); + var independent = history.PlanApply([b], ConflictPolicy.Skip); + var skipped = history.PlanApply([a], ConflictPolicy.Skip); + var overwritten = history.PlanApply([a], ConflictPolicy.Apply); - Assert.Empty(independent); - var skippedConflict = Assert.Single(skipped); - Assert.Equal(ConflictKind.SameProperty, skippedConflict.Kind); - Assert.False(skippedConflict.Resolved); - Assert.True(Assert.Single(overwritten).Resolved); + Assert.False(independent.NeedsReview); + var skippedConflict = Assert.Single(skipped.Items); + Assert.Equal(UndoTreePlanKind.Conflict, skippedConflict.Kind); + Assert.Equal(ConflictPolicy.Skip, skippedConflict.Choice); + Assert.Equal(ConflictPolicy.Apply, Assert.Single(overwritten.Items).Choice); Assert.Equal("X=2 Y=0 Parts=[p1:0]", document.Snapshot()); } @@ -65,10 +65,12 @@ public sealed class UndoTreeApplyTests foreach (var policy in new[] { ConflictPolicy.Skip, ConflictPolicy.Apply }) { - var predicted = history.PredictConflicts([a], policy); - var result = await history.ApplyAsync([a], policy); + var plan = history.PlanApply([a], policy); + var result = await history.ApplyAsync([a], policy, decisions: plan.Decisions); - Assert.Equal(predicted, result.Conflicts); + Assert.Equal( + plan.Items.Where(item => item.IsConflict).Select(item => (item.Text, item.Choice == ConflictPolicy.Apply)), + result.Conflicts.Select(conflict => (UndoTreeText.Join(conflict.TargetLabel, conflict.Member), conflict.Resolved))); } } @@ -85,10 +87,9 @@ public sealed class UndoTreeApplyTests await history.JumpAsync(a); Histories.Edit(manager, () => document.Parts.Remove(part)); - var predicted = Assert.Single(history.PredictConflicts([b], ConflictPolicy.Apply)); + var planned = Assert.Single(history.PlanApply([b], ConflictPolicy.Apply).Items); - Assert.Equal(ConflictKind.DeadTarget, predicted.Kind); - Assert.False(predicted.Resolved); + Assert.Equal(UndoTreePlanKind.Missing, planned.Kind); } [Fact] @@ -100,9 +101,9 @@ public sealed class UndoTreeApplyTests var a = history.Cursor; Histories.Edit(manager, () => document.X = 2); - var predicted = Assert.Single(history.PredictConflicts([a], ConflictPolicy.Skip, inverse: true)); + var planned = Assert.Single(history.PlanApply([a], ConflictPolicy.Skip, inverse: true).Items); - Assert.Equal(ConflictKind.SameProperty, predicted.Kind); + Assert.Equal(UndoTreePlanKind.Conflict, planned.Kind); Assert.Equal(ConflictKind.SameProperty, Assert.Single((await history.ApplyAsync([a], ConflictPolicy.Skip, inverse: true)).Conflicts).Kind); } @@ -113,7 +114,7 @@ public sealed class UndoTreeApplyTests using var history = Track(manager, document, withReader: false); Histories.Edit(manager, () => document.X = 1); - Assert.Empty(history.PredictConflicts([history.Cursor], ConflictPolicy.Skip)); + Assert.Empty(history.PlanApply([history.Cursor], ConflictPolicy.Skip).Items); } [Fact] diff --git a/UndoTree.Tests/UndoTreeMergeTests.cs b/UndoTree.Tests/UndoTreeMergeTests.cs index c55b63f..8cb35b9 100644 --- a/UndoTree.Tests/UndoTreeMergeTests.cs +++ b/UndoTree.Tests/UndoTreeMergeTests.cs @@ -42,10 +42,11 @@ public sealed class UndoTreeMergeTests await history.JumpAsync(history.Root); Histories.Edit(manager, () => document.X = 1); - var predicted = history.PredictConflicts(history.PathToMerge(theirs), ConflictPolicy.Skip, byValue: true); + var plan = history.PlanApply(history.PathToMerge(theirs), ConflictPolicy.Skip, byValue: true); var result = await history.ApplyAsync(history.PathToMerge(theirs), ConflictPolicy.Skip, byValue: true); - Assert.Empty(predicted); + Assert.False(plan.NeedsReview); + Assert.Equal(UndoTreePlanKind.Same, Assert.Single(plan.Items).Kind); Assert.Empty(result.Conflicts); Assert.Equal(0, result.Applied); Assert.Equal(1, document.X); @@ -82,15 +83,15 @@ public sealed class UndoTreeMergeTests await history.JumpAsync(history.Root); Histories.Edit(manager, () => document.X = 50); - var predicted = history.PredictConflicts(history.PathToMerge(theirs), policy, byValue: true); - var result = await history.ApplyAsync(history.PathToMerge(theirs), policy, byValue: true); + var plan = history.PlanApply(history.PathToMerge(theirs), policy, byValue: true); + var result = await history.ApplyAsync(history.PathToMerge(theirs), policy, byValue: true, decisions: plan.Decisions); - results[policy] = (document.X, result.Skipped, predicted.Count); + results[policy] = (document.X, result.Skipped, plan.ConflictCount); } Assert.Equal((50, 1, 1), results[ConflictPolicy.Skip]); Assert.Equal((10, 0, 1), results[ConflictPolicy.Apply]); - Assert.Equal((60, 0, 0), results[ConflictPolicy.Offset]); + Assert.Equal((60, 0, 1), results[ConflictPolicy.Offset]); } [Fact] @@ -105,10 +106,14 @@ public sealed class UndoTreeMergeTests await history.JumpAsync(history.Root); Histories.Edit(manager, () => document.Y = 1); - var predicted = history.PredictConflicts(history.PathToMerge(theirs), ConflictPolicy.Skip, byValue: true); + var plan = history.PlanApply(history.PathToMerge(theirs), ConflictPolicy.Skip, byValue: true); var result = await history.ApplyAsync(history.PathToMerge(theirs), ConflictPolicy.Skip, byValue: true); - Assert.Empty(predicted); + Assert.False(plan.NeedsReview); + var planned = Assert.Single(plan.Items); + Assert.Equal(UndoTreePlanKind.Change, planned.Kind); + Assert.Equal(3, planned.Count); + Assert.Equal("30", planned.ResultText); Assert.Empty(result.Conflicts); Assert.Equal(30, document.X); } @@ -124,10 +129,13 @@ public sealed class UndoTreeMergeTests await history.JumpAsync(history.Root); Histories.Edit(manager, () => document.X = 50); - var predicted = history.PredictConflicts(history.PathToMerge(theirs), ConflictPolicy.Skip, byValue: true); + var plan = history.PlanApply(history.PathToMerge(theirs), ConflictPolicy.Skip, byValue: true); var result = await history.ApplyAsync(history.PathToMerge(theirs), ConflictPolicy.Skip, byValue: true); - Assert.Equal(2, predicted.Count); + var planned = Assert.Single(plan.Items); + Assert.Equal(UndoTreePlanKind.Conflict, planned.Kind); + Assert.Equal(2, planned.Count); + Assert.Equal("50", planned.ResultText); Assert.Equal(2, result.Skipped); Assert.Equal(50, document.X); } @@ -143,10 +151,12 @@ public sealed class UndoTreeMergeTests await history.JumpAsync(history.Root); Histories.Edit(manager, () => document.X = 50); - var predicted = history.PredictConflicts(history.PathToMerge(theirs), ConflictPolicy.Apply, byValue: true); - await history.ApplyAsync(history.PathToMerge(theirs), ConflictPolicy.Apply, byValue: true); + var plan = history.PlanApply(history.PathToMerge(theirs), ConflictPolicy.Apply, byValue: true); + await history.ApplyAsync(history.PathToMerge(theirs), ConflictPolicy.Apply, byValue: true, decisions: plan.Decisions); - Assert.Single(predicted); + var planned = Assert.Single(plan.Items); + Assert.Equal(ConflictPolicy.Apply, planned.Choice); + Assert.Equal("20", planned.ResultText); Assert.Equal(20, document.X); } diff --git a/UndoTree.Tests/UndoTreeOffsetApplyTests.cs b/UndoTree.Tests/UndoTreeOffsetApplyTests.cs index 4a79e48..d6f7096 100644 --- a/UndoTree.Tests/UndoTreeOffsetApplyTests.cs +++ b/UndoTree.Tests/UndoTreeOffsetApplyTests.cs @@ -20,10 +20,13 @@ public sealed class UndoTreeOffsetApplyTests await history.JumpAsync(history.Root); Histories.Edit(manager, () => document.X = 200); - var predicted = history.PredictConflicts([move], ConflictPolicy.Offset); - var result = await history.ApplyAsync([move], ConflictPolicy.Offset); + var plan = history.PlanApply([move], ConflictPolicy.Offset); + var result = await history.ApplyAsync([move], ConflictPolicy.Offset, decisions: plan.Decisions); - Assert.Empty(predicted); + var planned = Assert.Single(plan.Items); + Assert.Equal(ConflictPolicy.Offset, planned.Choice); + Assert.Equal("200", planned.CurrentText); + Assert.Equal("210", planned.ResultText); Assert.Equal(210, document.X); Assert.Equal(1, result.Applied); Assert.Equal(0, result.Skipped); @@ -119,11 +122,14 @@ public sealed class UndoTreeOffsetApplyTests await history.JumpAsync(history.Root); Histories.Edit(manager, () => holder.Slot = other); - var predicted = history.PredictConflicts([change], ConflictPolicy.Offset); - var result = await history.ApplyAsync([change], ConflictPolicy.Offset); + var plan = history.PlanApply([change], ConflictPolicy.Offset); + var result = await history.ApplyAsync([change], ConflictPolicy.Offset, decisions: plan.Decisions); Assert.Same(other, holder.Slot); - Assert.Equal(ConflictKind.SameProperty, Assert.Single(predicted).Kind); + var planned = Assert.Single(plan.Items); + Assert.Equal(UndoTreePlanKind.Conflict, planned.Kind); + Assert.False(planned.CanOffset); + Assert.Equal(ConflictPolicy.Skip, planned.Choice); Assert.Equal(1, result.Skipped); Assert.Equal(0, result.Applied); } @@ -239,10 +245,12 @@ public sealed class UndoTreeOffsetApplyTests await history.JumpAsync(history.Root); Histories.Edit(manager, () => document.X = 1000); - var predicted = history.PredictConflicts([first, second, third], ConflictPolicy.Offset); - await history.ApplyAsync([first, second, third], ConflictPolicy.Offset); + var plan = history.PlanApply([first, second, third], ConflictPolicy.Offset); + await history.ApplyAsync([first, second, third], ConflictPolicy.Offset, decisions: plan.Decisions); - Assert.Empty(predicted); + var planned = Assert.Single(plan.Items); + Assert.Equal(3, planned.Count); + Assert.Equal("1125", planned.ResultText); Assert.Equal(1125, document.X); } } diff --git a/UndoTree.Tests/UndoTreePlanTests.cs b/UndoTree.Tests/UndoTreePlanTests.cs new file mode 100644 index 0000000..33ddf4a --- /dev/null +++ b/UndoTree.Tests/UndoTreePlanTests.cs @@ -0,0 +1,275 @@ +using YukkuriMovieMaker.Plugin; +using YukkuriMovieMaker.Project; +using YukkuriMovieMaker.UndoRedo; + +namespace UndoTree.Tests; + +public sealed class UndoTreePlanTests +{ + static UndoTreeHistory Track(UndoRedoManager manager, IUndoRedoable document) + => new(manager, new AsyncAwaitStatus(), [document], 100, UndoRedoManagerReader.Create(manager)); + + static async Task<(UndoTreeHistory History, Document Document, UndoTreeNodeViewModel[] Theirs)> Diverged(int x = 2, int y = 0) + { + var (manager, document) = Histories.NewDocument(); + var history = Track(manager, document); + Histories.Edit(manager, () => document.X = 1); + var first = history.Cursor; + Histories.Edit(manager, () => document.Y = 5); + var second = history.Cursor; + await history.JumpAsync(history.Root); + Histories.Edit(manager, () => document.X = x); + if (y != 0) + Histories.Edit(manager, () => document.Y = y); + + return (history, document, [first, second]); + } + + [Fact] + public async Task EachItemShowsItsCurrentValueAndWhatItBecomes() + { + var (history, _, theirs) = await Diverged(); + using var _ = history; + + var plan = history.PlanApply(theirs, ConflictPolicy.Skip); + + Assert.Equal(["Document / X", "Document / Y"], plan.Items.Select(item => item.Text)); + Assert.Equal([UndoTreePlanKind.Conflict, UndoTreePlanKind.Change], plan.Items.Select(item => item.Kind)); + Assert.Equal(["2", "0"], plan.Items.Select(item => item.CurrentText)); + Assert.Equal(["2", "5"], plan.Items.Select(item => item.ResultText)); + Assert.True(plan.NeedsReview); + Assert.Equal(1, plan.ConflictCount); + } + + [Fact] + public async Task AConflictOffersWhatEachWayOfResolvingItLeaves() + { + var (history, _, theirs) = await Diverged(); + using var _ = history; + var conflict = history.PlanApply(theirs, ConflictPolicy.Skip).Items[0]; + + Assert.Equal([ConflictPolicy.Skip, ConflictPolicy.Apply, ConflictPolicy.Offset], conflict.Choices.Select(choice => choice.Policy)); + Assert.Equal([Texts.ConflictSkip, Texts.ConflictApply, Texts.ConflictOffset], conflict.Choices.Select(choice => choice.Text)); + Assert.Equal("2", conflict.ResultText); + + conflict.Choice = ConflictPolicy.Apply; + Assert.Equal("1", conflict.ResultText); + + conflict.Choice = ConflictPolicy.Offset; + Assert.Equal("3", conflict.ResultText); + } + + [Fact] + public async Task ChangingTheChoiceTellsTheResultToTheView() + { + var (history, _, theirs) = await Diverged(); + using var _ = history; + var conflict = history.PlanApply(theirs, ConflictPolicy.Skip).Items[0]; + var changed = new List(); + conflict.PropertyChanged += (_, e) => changed.Add(e.PropertyName); + + conflict.Choice = ConflictPolicy.Apply; + + Assert.Contains(nameof(UndoTreePlanItem.Choice), changed); + Assert.Contains(nameof(UndoTreePlanItem.ResultText), changed); + } + + [Fact] + public async Task TheSettingIsTheChoiceAtFirst() + { + var (history, _, theirs) = await Diverged(); + using var _ = history; + + foreach (var policy in new[] { ConflictPolicy.Skip, ConflictPolicy.Apply, ConflictPolicy.Offset }) + Assert.Equal(policy, history.PlanApply(theirs, policy).Items[0].Choice); + } + + [Fact] + public async Task TheChoicesOfTheConflictsAreAppliedItemByItem() + { + var (history, document, theirs) = await Diverged(2, 7); + using var _ = history; + var plan = history.PlanApply(theirs, ConflictPolicy.Skip); + Assert.Equal([UndoTreePlanKind.Conflict, UndoTreePlanKind.Conflict], plan.Items.Select(item => item.Kind)); + plan.Items[0].Choice = ConflictPolicy.Apply; + plan.Items[1].Choice = ConflictPolicy.Offset; + + var result = await history.ApplyAsync(theirs, ConflictPolicy.Skip, decisions: plan.Decisions); + + Assert.Equal(1, document.X); + Assert.Equal(12, document.Y); + Assert.Equal(0, result.Skipped); + } + + [Fact] + public async Task AnItemLeftOnSkipStaysWhileTheOtherOneIsOverwritten() + { + var (history, document, theirs) = await Diverged(2, 7); + using var _ = history; + var plan = history.PlanApply(theirs, ConflictPolicy.Skip); + plan.Items[1].Choice = ConflictPolicy.Apply; + + var result = await history.ApplyAsync(theirs, ConflictPolicy.Skip, decisions: plan.Decisions); + + Assert.Equal(2, document.X); + Assert.Equal(5, document.Y); + Assert.Equal(1, result.Skipped); + } + + [Fact] + public async Task ChoosingForAllSetsEveryConflictAndKeepsSkipWhereTheAmountCannotBeAdded() + { + var (history, document, theirs) = await Diverged(2, 7); + using var _ = history; + var plan = history.PlanApply(theirs, ConflictPolicy.Skip); + + plan.ChooseAll(ConflictPolicy.Offset); + Assert.All(plan.Items, item => Assert.Equal(ConflictPolicy.Offset, item.Choice)); + + plan.ChooseAll(ConflictPolicy.Apply); + Assert.All(plan.Items, item => Assert.Equal(ConflictPolicy.Apply, item.Choice)); + Assert.Equal(2, plan.Decisions.Count); + Assert.Equal(2, document.X); + } + + [Fact] + public async Task TheChainOfChangesToOneItemIsOneRowWhoseResultFollowsTheChoice() + { + var (manager, document) = Histories.NewDocument(); + using var history = Track(manager, document); + Histories.Edit(manager, () => document.X = 10); + var first = history.Cursor; + Histories.Edit(manager, () => document.X = 20); + var second = history.Cursor; + await history.JumpAsync(history.Root); + Histories.Edit(manager, () => document.X = 50); + + var plan = history.PlanApply([first, second], ConflictPolicy.Skip, byValue: true); + + var row = Assert.Single(plan.Items); + Assert.Equal(2, row.Count); + Assert.Equal(string.Format(Texts.FoldedRun, "Document / X", 2), row.Text); + Assert.Equal("50", row.ResultText); + row.Choice = ConflictPolicy.Apply; + Assert.Equal("20", row.ResultText); + row.Choice = ConflictPolicy.Offset; + Assert.Equal("70", row.ResultText); + } + + [Fact] + public async Task AnItemWhoseTargetIsGoneCannotBeChosen() + { + var (manager, document) = Histories.NewDocument("p1"); + using var history = Track(manager, document); + Histories.Edit(manager, () => document.X = 1); + var a = history.Cursor; + var part = document.Parts[0]; + Histories.Edit(manager, () => part.Value = 10); + var b = history.Cursor; + await history.JumpAsync(a); + Histories.Edit(manager, () => document.Parts.Remove(part)); + + var plan = history.PlanApply([b], ConflictPolicy.Apply); + + var row = Assert.Single(plan.Items); + Assert.Equal(UndoTreePlanKind.Missing, row.Kind); + Assert.False(row.IsConflict); + Assert.Equal(1, plan.MissingCount); + Assert.True(plan.NeedsReview); + Assert.Empty(plan.Decisions); + Assert.Equal(Texts.ReviewMissing, row.StatusText); + + var review = new UndoTreeReviewViewModel(plan); + Assert.True(review.HasMissing); + Assert.False(review.HasConflicts); + Assert.Equal(string.Format(Texts.ReviewSummary, 0, 0), review.SummaryText); + Assert.Equal(string.Format(Texts.ReviewMissingNote, 1), review.MissingText); + } + + [Fact] + public async Task ChoosingToAddTheAmountOfChangeForAllLeavesTheItemsThatAreNotNumbersOnSkip() + { + var holder = new Holder(); + var manager = new UndoRedoManager(); + manager.Subscribe(holder); + using var history = Track(manager, holder); + var first = new Slot(); + var second = new Slot(); + Histories.Edit(manager, () => holder.Level = 5); + var level = history.Cursor; + Histories.Edit(manager, () => holder.Slot = first); + var slot = history.Cursor; + await history.JumpAsync(history.Root); + Histories.Edit(manager, () => holder.Level = 9); + Histories.Edit(manager, () => holder.Slot = second); + + var plan = history.PlanApply([level, slot], ConflictPolicy.Skip); + plan.ChooseAll(ConflictPolicy.Offset); + + Assert.Equal([UndoTreePlanKind.Conflict, UndoTreePlanKind.Conflict], plan.Items.Select(item => item.Kind)); + Assert.Equal([true, false], plan.Items.Select(item => item.CanOffset)); + Assert.Equal([ConflictPolicy.Offset, ConflictPolicy.Skip], plan.Items.Select(item => item.Choice)); + Assert.Equal([ConflictPolicy.Skip, ConflictPolicy.Apply], plan.Items[1].Choices.Select(choice => choice.Policy)); + Assert.True(new UndoTreeReviewViewModel(plan).CanOffsetAny); + } + + [Fact] + public async Task AdditionsToAListAreRowsOfTheirOwn() + { + var (manager, document) = Histories.NewDocument(); + using var history = Track(manager, document); + Histories.Edit(manager, () => document.Parts.Add(new Part("p2"))); + var added = history.Cursor; + await history.JumpAsync(history.Root); + + var plan = history.PlanApply([added], ConflictPolicy.Skip); + + var row = Assert.Single(plan.Items); + Assert.Equal(UndoTreePlanKind.Change, row.Kind); + Assert.Equal(Texts.ReviewChange, row.StatusText); + Assert.False(plan.NeedsReview); + } + + [Fact] + public void WithoutAnythingToApplyThereIsNothingToReview() + { + var (manager, document) = Histories.NewDocument(); + using var history = Track(manager, document); + + var plan = history.PlanApply([], ConflictPolicy.Skip); + + Assert.Empty(plan.Items); + Assert.False(plan.NeedsReview); + Assert.Empty(plan.Decisions); + } + + [Fact] + public async Task TheReviewWindowCountsTheItemsAndTheConflicts() + { + var (history, _, theirs) = await Diverged(); + using var _ = history; + var review = new UndoTreeReviewViewModel(history.PlanApply(theirs, ConflictPolicy.Skip)); + + Assert.Equal(string.Format(Texts.ReviewSummary, 2, 1), review.SummaryText); + Assert.True(review.HasConflicts); + Assert.False(review.HasMissing); + Assert.True(review.CanOffsetAny); + Assert.True(review.ChooseAllCommand.CanExecute("Apply")); + + review.ChooseAllCommand.Execute("Apply"); + + Assert.Equal(ConflictPolicy.Apply, review.Items[0].Choice); + } + + [Fact] + public async Task WithoutConflictsTheChooseAllButtonsHaveNothingToDo() + { + var (history, _, theirs) = await Diverged(); + using var _ = history; + var review = new UndoTreeReviewViewModel(history.PlanApply([theirs[1]], ConflictPolicy.Skip)); + + Assert.False(review.HasConflicts); + Assert.False(review.ChooseAllCommand.CanExecute("Skip")); + Assert.Equal(string.Format(Texts.ReviewSummary, 1, 0), review.SummaryText); + } +} diff --git a/UndoTree.Tests/UndoTreeViewModelTests.cs b/UndoTree.Tests/UndoTreeViewModelTests.cs index f36d674..4fcf47c 100644 --- a/UndoTree.Tests/UndoTreeViewModelTests.cs +++ b/UndoTree.Tests/UndoTreeViewModelTests.cs @@ -662,36 +662,6 @@ public sealed class UndoTreeViewModelTests return (model, manager, document); } - [Fact] - public void TheQuestionBeforeAConflictingApplicationCountsAndNamesTheConflicts() - { - var conflicts = new[] - { - new UndoTreeConflict(ConflictKind.SameProperty, "Document", "X", false), - new UndoTreeConflict(ConflictKind.SameProperty, "Document", "Y", true), - new UndoTreeConflict(ConflictKind.DeadTarget, "p1", "Value", false), - }; - - var question = UndoTreeViewModel.ConflictQuestionOf(conflicts); - - Assert.StartsWith(string.Format(Texts.ConfirmConflicts, 3, 2, 1), question); - Assert.Contains("Document / X", question); - Assert.Contains("p1 / Value", question); - Assert.DoesNotContain("…", question); - } - - [Fact] - public void AQuestionAboutManyConflictsListsOnlyTheFirstOnes() - { - var conflicts = Enumerable.Range(0, 8).Select(index => new UndoTreeConflict(ConflictKind.SameProperty, "t", $"m{index}", false)).ToArray(); - - var question = UndoTreeViewModel.ConflictQuestionOf(conflicts); - - Assert.Contains("t / m4", question); - Assert.DoesNotContain("t / m5", question); - Assert.EndsWith("…", question); - } - [Fact] public void DroppingTheSideBranchesRemovesThemWhenNothingAsksForConfirmation() { @@ -1646,6 +1616,83 @@ public sealed class UndoTreeViewModelTests Assert.All(Enum.GetValues(), move => Assert.False(model.MoveCommand.CanExecute(move))); } + static (UndoTreeViewModel Model, Document Document, UndoTreeNodeViewModel Theirs) Diverged(bool conflicting) + { + var (model, manager, document) = Open(); + Histories.Edit(manager, () => document.X = 1); + var theirs = model.Items[^1]; + manager.UndoAsync().GetAwaiter().GetResult(); + if (conflicting) + Histories.Edit(manager, () => document.X = 2); + else + Histories.Edit(manager, () => document.Y = 3); + + return (model, document, theirs); + } + + [Fact] + public void ACherryPickThatConflictsIsShownForReviewAndNothingIsAppliedWhenItIsRefused() + { + var (model, document, theirs) = Diverged(true); + var shown = new List(); + model.ReviewPlan = plan => + { + shown.Add(plan); + return false; + }; + + model.CherryPickCommand.Execute(theirs); + + var plan = Assert.Single(shown); + Assert.Equal(UndoTreePlanKind.Conflict, Assert.Single(plan.Items).Kind); + Assert.Equal(2, document.X); + } + + [Fact] + public void TheChoiceMadeInTheReviewDecidesWhatTheCherryPickDoesWithTheConflict() + { + var (model, document, theirs) = Diverged(true); + model.ReviewPlan = plan => + { + plan.ChooseAll(ConflictPolicy.Apply); + return true; + }; + + model.CherryPickCommand.Execute(theirs); + + Assert.Equal(1, document.X); + } + + [Fact] + public void ACherryPickWithoutAnythingToDecideRunsWithoutAskingAndAMergeAlwaysAsks() + { + var asked = 0; + var (model, document, theirs) = Diverged(false); + model.ReviewPlan = _ => + { + asked++; + return true; + }; + + model.CherryPickCommand.Execute(theirs); + + Assert.Equal(0, asked); + Assert.Equal(1, document.X); + + var (mergingModel, mergingDocument, mergedNode) = Diverged(false); + mergingModel.ReviewPlan = plan => + { + asked++; + Assert.False(plan.NeedsReview); + return false; + }; + + mergingModel.MergeIntoCurrentCommand.Execute(mergedNode); + + Assert.Equal(1, asked); + Assert.Equal(0, mergingDocument.X); + } + [Fact] public void CancellingATagEditKeepsTheOldTagAndCommittingTwiceDoesNothingMore() { diff --git a/UndoTree/Texts.csv b/UndoTree/Texts.csv index 4381f1b..809ee51 100644 --- a/UndoTree/Texts.csv +++ b/UndoTree/Texts.csv @@ -58,7 +58,6 @@ DiffHeader,,現在の状態からの変更点,Changes from the current state,与 DiffEmpty,,現在の状態との差はありません,There is no difference from the current state,与当前状态没有差异,與目前狀態沒有差異,현재 상태와 차이가 없습니다,No hay diferencias con el estado actual,لا يوجد فرق عن الحالة الحالية,Tidak ada selisih dari keadaan saat ini DiffOpaque,,内容を比べられない操作が{0}件あります,{0} operation(s) cannot be compared,有 {0} 项操作无法比较内容,有 {0} 項操作無法比較內容,내용을 비교할 수 없는 작업이 {0}개 있습니다,Hay {0} operaciones cuyo contenido no se puede comparar,توجد {0} عمليات لا يمكن مقارنة محتواها,Ada {0} operasi yang isinya tidak dapat dibandingkan ConfirmDropBranches,,他のブランチの操作{0}件を削除します。この操作は元に戻せません。よろしいですか?,Delete {0} operation(s) in other branches? This cannot be undone.,将删除其他分支中的 {0} 项操作。此操作无法撤销。是否继续?,將刪除其他分支中的 {0} 項操作。此操作無法復原。是否繼續?,다른 브랜치의 작업 {0}개를 삭제합니다. 이 작업은 되돌릴 수 없습니다. 계속하시겠습니까?,Se eliminarán {0} operaciones de otras ramas. Esta acción no se puede deshacer. ¿Continuar?,سيتم حذف {0} عملية من الفروع الأخرى. لا يمكن التراجع عن هذا الإجراء. هل تريد المتابعة؟,{0} operasi di cabang lain akan dihapus. Tindakan ini tidak dapat diurungkan. Lanjutkan? -ConfirmConflicts,,{0}件の操作が、現在の状態と競合します。{1}件をスキップし、{2}件を上書きします。続行しますか?,{0} operation(s) conflict with the current state. {1} will be skipped and {2} will be overwritten. Continue?,有 {0} 项操作与当前状态冲突。将跳过 {1} 项,覆盖 {2} 项。是否继续?,有 {0} 項操作與目前狀態衝突。將略過 {1} 項,覆蓋 {2} 項。是否繼續?,{0}개 작업이 현재 상태와 충돌합니다. {1}개는 건너뛰고 {2}개는 덮어씁니다. 계속하시겠습니까?,{0} operaciones entran en conflicto con el estado actual. Se omitirán {1} y se sobrescribirán {2}. ¿Continuar?,تتعارض {0} عملية مع الحالة الحالية. سيتم تخطي {1} والكتابة فوق {2}. هل تريد المتابعة؟,{0} operasi bertentangan dengan keadaan saat ini. {1} akan dilewati dan {2} akan ditimpa. Lanjutkan? SettingsHistorySection,,履歴の保存,Saving the history,保存历史记录,儲存歷史記錄,기록 저장,Guardado del historial,حفظ السجل,Penyimpanan riwayat SaveHistory,,履歴をファイルに保存する,Save the history to a file,将历史记录保存到文件,將歷史記錄儲存到檔案,기록을 파일에 저장,Guardar el historial en un archivo,حفظ السجل في ملف,Simpan riwayat ke berkas SaveHistoryDesc,,プロジェクトごとに、操作の名前と変更前後の値を、YMM4のユーザーフォルダーのcacheへ保存します。プロジェクトのファイルは変わりません。,"Saves the names of the operations and the values before and after each change to the cache folder of the YMM4 user folder, per project. The project file is not changed.",按项目将操作名称和更改前后的值保存到 YMM4 用户文件夹的 cache 中。项目文件不会改变。,依專案將操作名稱與變更前後的值儲存到 YMM4 使用者資料夾的 cache 中。專案檔案不會改變。,프로젝트별로 작업 이름과 변경 전후의 값을 YMM4 사용자 폴더의 cache에 저장합니다. 프로젝트 파일은 변경되지 않습니다.,Guarda por proyecto los nombres de las operaciones y los valores antes y después de cada cambio en la carpeta cache de la carpeta de usuario de YMM4. El archivo del proyecto no cambia.,يحفظ لكل مشروع أسماء العمليات والقيم قبل كل تغيير وبعده في مجلد cache ضمن مجلد مستخدم YMM4. لا يتغير ملف المشروع.,Menyimpan per proyek nama operasi serta nilai sebelum dan sesudah setiap perubahan ke folder cache di folder pengguna YMM4. Berkas proyek tidak berubah. @@ -591,3 +590,19 @@ MoveToPreviousCreated,,作成順で前の操作へ移動,Go to the previous oper MoveToNextCreated,,作成順で次の操作へ移動,Go to the next operation by creation order,按创建顺序移动到下一个操作,依建立順序移動到下一個操作,생성 순서로 다음 작업으로 이동,Ir a la operación siguiente por orden de creación,الانتقال إلى العملية التالية بترتيب الإنشاء,Pindah ke operasi berikutnya menurut urutan pembuatan MoveToPreviousBranch,,前のブランチの末端へ移動,Go to the end of the previous branch,移动到上一个分支的末端,移動到上一個分支的末端,이전 브랜치의 끝으로 이동,Ir al final de la rama anterior,الانتقال إلى نهاية الفرع السابق,Pindah ke ujung cabang sebelumnya MoveToNextBranch,,次のブランチの末端へ移動,Go to the end of the next branch,移动到下一个分支的末端,移動到下一個分支的末端,다음 브랜치의 끝으로 이동,Ir al final de la rama siguiente,الانتقال إلى نهاية الفرع التالي,Pindah ke ujung cabang berikutnya +ReviewTitle,,操作の適用の確認,Confirm applying operations,确认应用操作,確認套用操作,작업 적용 확인,Confirmar la aplicación de operaciones,تأكيد تطبيق العمليات,Konfirmasi penerapan operasi +ReviewSummary,,{0}件の項目が対象です。そのうち{1}件は、現在の値が操作の記録と合いません。,"{0} item(s) are affected. For {1} of them, the current value does not match the record of the operation.",涉及 {0} 个项目,其中 {1} 个项目的当前值与操作记录不一致。,涉及 {0} 個項目,其中 {1} 個項目的目前值與操作記錄不一致。,{0}개 항목이 대상입니다. 그중 {1}개는 현재 값이 작업의 기록과 맞지 않습니다.,"Hay {0} elemento(s) afectados. En {1} de ellos, el valor actual no coincide con el registro de la operación.",عدد العناصر المتأثرة: {0}. في {1} منها لا تتطابق القيمة الحالية مع سجل العملية.,"{0} item terpengaruh. Pada {1} di antaranya, nilai saat ini tidak cocok dengan catatan operasi." +ReviewMissingNote,,{0}件は、対象が無いため変更できません。,{0} item(s) cannot be changed because their target no longer exists.,{0} 个项目的对象已不存在,无法更改。,{0} 個項目的對象已不存在,無法變更。,{0}개 항목은 대상이 없어 변경할 수 없습니다.,{0} elemento(s) no se pueden cambiar porque su destino ya no existe.,لا يمكن تغيير {0} من العناصر لأن هدفها لم يعد موجودًا.,{0} item tidak dapat diubah karena targetnya tidak ada lagi. +ReviewTarget,,項目,Item,项目,項目,항목,Elemento,العنصر,Item +ReviewCurrent,,現在の値,Current value,当前值,目前的值,현재 값,Valor actual,القيمة الحالية,Nilai saat ini +ReviewResult,,結果,Result,结果,結果,결과,Resultado,النتيجة,Hasil +ReviewAction,,扱い,Handling,处理方式,處理方式,처리 방법,Tratamiento,المعالجة,Penanganan +ReviewChange,,変更する,Change,更改,變更,변경,Cambiar,تغيير,Ubah +ReviewSame,,すでに同じ値,Already the same value,值已相同,值已相同,이미 같은 값,Ya tiene el mismo valor,القيمة متطابقة بالفعل,Nilai sudah sama +ReviewMerged,,リストの追加と削除をマージする,Merge the additions and removals of the list,合并列表的添加和删除,合併清單的新增和刪除,목록의 추가와 삭제를 병합,Fusionar las adiciones y eliminaciones de la lista,دمج عمليات الإضافة والحذف في القائمة,Gabungkan penambahan dan penghapusan daftar +ReviewMissing,,対象が無いため変更できない,Cannot change: the target no longer exists,对象不存在,无法更改,對象不存在,無法變更,대상이 없어 변경할 수 없음,No se puede cambiar: el destino ya no existe,لا يمكن التغيير: الهدف غير موجود,Tidak dapat diubah: target tidak ada +ReviewSkipAll,,すべてスキップする,Skip all,全部跳过,全部略過,모두 건너뛰기,Omitir todo,تخطي الكل,Lewati semua +ReviewApplyAll,,すべて操作の値で上書きする,Overwrite all,全部覆盖,全部覆寫,모두 덮어쓰기,Sobrescribir todo,استبدال الكل,Timpa semua +ReviewOffsetAll,,すべて変化量を足す,Add change to all,全部加上变化量,全部加上變化量,모두 변화량 더하기,Sumar el cambio a todo,إضافة التغيير للكل,Tambah perubahan ke semua +ReviewApply,,適用,Apply,应用,套用,적용,Aplicar,تطبيق,Terapkan +ReviewCancel,,キャンセル,Cancel,取消,取消,취소,Cancelar,إلغاء,Batal diff --git a/UndoTree/UndoTreeDispatch.cs b/UndoTree/UndoTreeDispatch.cs index 0d24f55..125945e 100644 --- a/UndoTree/UndoTreeDispatch.cs +++ b/UndoTree/UndoTreeDispatch.cs @@ -25,4 +25,18 @@ internal static class UndoTreeDispatch public static bool Confirm(string message) => Application.Current is null || MessageBox.Show(message, Texts.UndoTree, MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes; + + public static bool Review(UndoTreePlan plan) + { + if (Application.Current is not { } application) + return true; + + var window = new UndoTreeReviewWindow(new UndoTreeReviewViewModel(plan)); + if (application.MainWindow is { IsVisible: true } owner) + window.Owner = owner; + else + window.WindowStartupLocation = WindowStartupLocation.CenterScreen; + + return window.ShowDialog() == true; + } } diff --git a/UndoTree/UndoTreeHistory.cs b/UndoTree/UndoTreeHistory.cs index e91fcb3..8e4f3ef 100644 --- a/UndoTree/UndoTreeHistory.cs +++ b/UndoTree/UndoTreeHistory.cs @@ -416,7 +416,7 @@ internal class UndoTreeHistory : IDisposable history.TrySetRedo([]); } - public async Task ApplyAsync(IReadOnlyList sources, ConflictPolicy policy, bool inverse = false, bool byValue = false) + public async Task ApplyAsync(IReadOnlyList sources, ConflictPolicy policy, bool inverse = false, bool byValue = false, IReadOnlyDictionary? decisions = null) { Reconcile(); if (source is null) @@ -446,7 +446,7 @@ internal class UndoTreeHistory : IDisposable { foreach (var node in sources) { - var result = await ReplayAsync(source, node.Handle!, true, policy, touched, inverse, byValue); + var result = await ReplayAsync(source, node.Handle!, true, policy, touched, inverse, byValue, decisions); applied += result.Applied; conflicts.AddRange(result.Conflicts); merged |= Merge(source.Undo, source.Redo); @@ -496,36 +496,98 @@ internal class UndoTreeHistory : IDisposable return new UndoTreeApplyResult(applied, conflicts); } - public IReadOnlyList PredictConflicts(IReadOnlyList sources, ConflictPolicy policy, bool inverse = false, bool byValue = false) + public UndoTreePlan PlanApply(IReadOnlyList sources, ConflictPolicy policy, bool inverse = false, bool byValue = false) { - var conflicts = new List(); if (source is not { CanReplay: true } || sources.Count == 0) - return conflicts; + return new UndoTreePlan([]); var touched = TouchedOnTheWayTo(sources[0]); - var apply = policy == ConflictPolicy.Apply; - var simulated = new Dictionary(); + var groups = new List>(); + var grouped = new Dictionary>(); foreach (var node in sources) { var commands = inverse ? source.CommandsOf(node.Handle!).Reverse().ToArray() : source.CommandsOf(node.Handle!); foreach (var command in commands.Where(command => !command.IsAction)) { var view = UndoRedoCommandView.Read(command); - var info = InContext(view.Describe()); - var verdict = Judge(view, touched, inverse, policy, byValue, simulated); - if (verdict is Verdict.DeadTarget) - conflicts.Add(new UndoTreeConflict(ConflictKind.DeadTarget, info.TargetLabel, info.Member, false)); - else if (verdict is Verdict.Unreadable or Verdict.SameProperty) - conflicts.Add(new UndoTreeConflict(verdict == Verdict.Unreadable ? ConflictKind.Unreadable : ConflictKind.SameProperty, info.TargetLabel, info.Member, apply)); + var entry = new PlanEntry(view, InContext(view.Describe())); + if (!grouped.TryGetValue(DecisionKeyOf(view), out var group)) + { + group = []; + grouped[DecisionKeyOf(view)] = group; + groups.Add(group); + } - if (view.Key is { } key && (byValue || policy == ConflictPolicy.Offset) && WritablePropertyOf(view) is { } property) - Simulate(simulated, key, view, property, verdict, inverse, apply); + group.Add(entry); } } - return conflicts; + return new UndoTreePlan([.. groups.Select(group => PlanItemOf(group, touched, policy, inverse, byValue))]); } + static UndoTreeChangeKey DecisionKeyOf(UndoRedoCommandView view) => view.Key ?? new UndoTreeChangeKey(view.Command, string.Empty); + + static UndoTreePlanItem PlanItemOf(List group, HashSet touched, ConflictPolicy policy, bool inverse, bool byValue) + { + var first = group[0]; + var key = DecisionKeyOf(first.View); + var baseline = Foresee(group, touched, policy, inverse, byValue); + var current = baseline.Tracked ? UndoRedoCommandView.TextOf(baseline.Current) : string.Empty; + var after = baseline.Tracked ? string.Empty : group[^1].Info.After; + UndoTreePlanItem Item(UndoTreePlanKind kind, string result, string? offsetResult = null, ConflictPolicy choice = ConflictPolicy.Skip) + => new(kind, key, first.Info.TargetLabel, first.Info.Member, group.Count, current, result, offsetResult, choice); + + if (baseline.Missing) + return Item(UndoTreePlanKind.Missing, string.Empty); + + if (baseline.Merged) + return Item(UndoTreePlanKind.Merged, string.Empty); + + if (!baseline.Conflict) + { + var result = baseline.Tracked ? UndoRedoCommandView.TextOf(baseline.Final) : after; + return Item(baseline.Tracked && Equals(baseline.Final, baseline.Current) ? UndoTreePlanKind.Same : UndoTreePlanKind.Change, result); + } + + var overwritten = Foresee(group, touched, ConflictPolicy.Apply, inverse, byValue); + var offset = Foresee(group, touched, ConflictPolicy.Offset, inverse, byValue); + var offsetResult = offset.Offsetted ? UndoRedoCommandView.TextOf(offset.Final) : null; + var choice = policy switch + { + ConflictPolicy.Apply => ConflictPolicy.Apply, + ConflictPolicy.Offset when offsetResult is not null => ConflictPolicy.Offset, + _ => ConflictPolicy.Skip, + }; + return Item(UndoTreePlanKind.Conflict, baseline.Tracked ? UndoRedoCommandView.TextOf(overwritten.Final) : after, offsetResult, choice); + } + + static Foresight Foresee(List group, HashSet touched, ConflictPolicy policy, bool inverse, bool byValue) + { + var first = group[0].View; + var property = first.Kind == CommandKind.Property ? WritablePropertyOf(first) : null; + var key = first.Key; + var tracked = property is not null && key is not null; + var current = tracked ? property!.GetValue(first.Target) : null; + var simulated = new Dictionary(); + bool missing = false, merged = false, conflict = false, offsetted = false; + foreach (var entry in group) + { + var verdict = Judge(entry.View, touched, inverse, policy, byValue, simulated); + missing |= verdict == Verdict.DeadTarget; + merged |= verdict == Verdict.Merged; + conflict |= verdict is Verdict.SameProperty or Verdict.Unreadable or Verdict.Offset; + offsetted |= verdict == Verdict.Offset; + if (tracked) + Simulate(simulated, key!, entry.View, property!, verdict, inverse, policy == ConflictPolicy.Apply); + } + + return new Foresight(missing, merged, conflict, offsetted, tracked, current, tracked && simulated.TryGetValue(key!, out var final) ? final : current); + } + + sealed record PlanEntry(UndoRedoCommandView View, UndoTreeCommandInfo Info); + + sealed record Foresight(bool Missing, bool Merged, bool Conflict, bool Offsetted, bool Tracked, object? Current, object? Final); + static void Simulate(Dictionary simulated, UndoTreeChangeKey key, UndoRedoCommandView view, PropertyInfo property, Verdict verdict, bool inverse, bool apply) { var from = inverse ? view.NewValue : view.OldValue; @@ -1149,7 +1211,7 @@ internal class UndoTreeHistory : IDisposable } } - async Task ReplayAsync(IUndoRedoHistory history, object handle, bool check, ConflictPolicy policy, HashSet touched, bool inverse, bool byValue = false) + async Task ReplayAsync(IUndoRedoHistory history, object handle, bool check, ConflictPolicy policy, HashSet touched, bool inverse, bool byValue = false, IReadOnlyDictionary? decisions = null) { var commands = inverse ? history.CommandsOf(handle).Reverse().ToArray() : history.CommandsOf(handle); var before = history.Undo; @@ -1161,7 +1223,7 @@ internal class UndoTreeHistory : IDisposable { foreach (var command in commands.Where(command => command.IsAction == pass)) { - if (await ReplayCommandAsync(command, check, policy, touched, conflicts, inverse, byValue)) + if (await ReplayCommandAsync(command, check, policy, touched, conflicts, inverse, byValue, decisions)) applied++; } } @@ -1176,7 +1238,7 @@ 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, bool inverse, bool byValue) + async Task ReplayCommandAsync(IUndoRedoCommandBase command, bool check, ConflictPolicy policy, HashSet touched, List conflicts, bool inverse, bool byValue, IReadOnlyDictionary? decisions) { if (command.IsAction) { @@ -1193,6 +1255,9 @@ internal class UndoTreeHistory : IDisposable var view = UndoRedoCommandView.Read(command); var info = InContext(view.Describe()); + if (decisions is not null && decisions.TryGetValue(DecisionKeyOf(view), out var decided)) + policy = decided; + var verdict = Judge(view, touched, inverse, policy, byValue, null); var apply = policy == ConflictPolicy.Apply; switch (verdict) diff --git a/UndoTree/UndoTreePlan.cs b/UndoTree/UndoTreePlan.cs new file mode 100644 index 0000000..1adf6fb --- /dev/null +++ b/UndoTree/UndoTreePlan.cs @@ -0,0 +1,104 @@ +using YukkuriMovieMaker.Commons; + +namespace UndoTree; + +internal enum UndoTreePlanKind +{ + Change, + Same, + Conflict, + Merged, + Missing, +} + +internal sealed record UndoTreePlanChoice(ConflictPolicy Policy, string Text); + +internal sealed class UndoTreePlanItem : Bindable +{ + readonly string setText; + readonly string? offsetText; + + public UndoTreePlanItem(UndoTreePlanKind kind, UndoTreeChangeKey key, string targetLabel, string member, int count, string currentText, string setText, string? offsetText, ConflictPolicy choice) + { + Kind = kind; + Key = key; + TargetLabel = targetLabel; + Member = member; + Count = count; + CurrentText = currentText; + this.setText = setText; + this.offsetText = offsetText; + Choice = choice; + } + + public UndoTreePlanKind Kind { get; } + + public UndoTreeChangeKey Key { get; } + + public string TargetLabel { get; } + + public string Member { get; } + + public int Count { get; } + + public string CurrentText { get; } + + public bool IsConflict => Kind == UndoTreePlanKind.Conflict; + + public bool CanOffset => offsetText is not null; + + public string Text => Count > 1 ? string.Format(Texts.FoldedRun, UndoTreeText.Join(TargetLabel, Member), Count) : UndoTreeText.Join(TargetLabel, Member); + + public ConflictPolicy Choice { get; set => Set(ref field, value, nameof(Choice), nameof(ResultText)); } + + public IReadOnlyList Choices => [ + new(ConflictPolicy.Skip, Texts.ConflictSkip), + new(ConflictPolicy.Apply, Texts.ConflictApply), + .. CanOffset ? [new UndoTreePlanChoice(ConflictPolicy.Offset, Texts.ConflictOffset)] : Array.Empty(), + ]; + + public string ResultText => Kind switch + { + UndoTreePlanKind.Conflict => Choice switch + { + ConflictPolicy.Apply => setText, + ConflictPolicy.Offset => offsetText ?? CurrentText, + _ => CurrentText, + }, + UndoTreePlanKind.Same => CurrentText, + UndoTreePlanKind.Missing => string.Empty, + _ => setText, + }; + + public string StatusText => Kind switch + { + UndoTreePlanKind.Change => Texts.ReviewChange, + UndoTreePlanKind.Same => Texts.ReviewSame, + UndoTreePlanKind.Merged => Texts.ReviewMerged, + UndoTreePlanKind.Missing => Texts.ReviewMissing, + _ => string.Empty, + }; + + public void ChooseAtMost(ConflictPolicy choice) => Choice = choice == ConflictPolicy.Offset && !CanOffset ? ConflictPolicy.Skip : choice; +} + +internal sealed class UndoTreePlan(IReadOnlyList items) +{ + public IReadOnlyList Items { get; } = items; + + public int ConflictCount => Items.Count(item => item.IsConflict); + + public int MissingCount => Items.Count(item => item.Kind == UndoTreePlanKind.Missing); + + public bool NeedsReview => ConflictCount > 0 || MissingCount > 0; + + public IReadOnlyDictionary Decisions => Items + .Where(item => item.IsConflict) + .ToDictionary(item => item.Key, item => item.Choice); + + public void ChooseAll(ConflictPolicy choice) + { + foreach (var item in Items.Where(item => item.IsConflict)) + item.ChooseAtMost(choice); + } +} diff --git a/UndoTree/UndoTreeReviewViewModel.cs b/UndoTree/UndoTreeReviewViewModel.cs new file mode 100644 index 0000000..bcfafac --- /dev/null +++ b/UndoTree/UndoTreeReviewViewModel.cs @@ -0,0 +1,34 @@ +using YukkuriMovieMaker.Commons; + +namespace UndoTree; + +internal sealed class UndoTreeReviewViewModel : Bindable +{ + public UndoTreeReviewViewModel(UndoTreePlan plan) + { + Plan = plan; + ChooseAllCommand = new ActionCommand( + _ => HasConflicts, + parameter => + { + if (parameter is string name && Enum.TryParse(name, out var choice)) + Plan.ChooseAll(choice); + }); + } + + public UndoTreePlan Plan { get; } + + public IReadOnlyList Items => Plan.Items; + + public bool HasConflicts => Plan.ConflictCount > 0; + + public bool HasMissing => Plan.MissingCount > 0; + + public bool CanOffsetAny => Plan.Items.Any(item => item.IsConflict && item.CanOffset); + + public string SummaryText => string.Format(Texts.ReviewSummary, Plan.Items.Count(item => item.Kind != UndoTreePlanKind.Missing), Plan.ConflictCount); + + public string MissingText => string.Format(Texts.ReviewMissingNote, Plan.MissingCount); + + public ActionCommand ChooseAllCommand { get; } +} diff --git a/UndoTree/UndoTreeReviewWindow.xaml b/UndoTree/UndoTreeReviewWindow.xaml new file mode 100644 index 0000000..851cd52 --- /dev/null +++ b/UndoTree/UndoTreeReviewWindow.xaml @@ -0,0 +1,136 @@ + + + + 110 + 200 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +