From b300cb052feba5a9a84f6fa27641cbbc0ac4869e Mon Sep 17 00:00:00 2001 From: routersys Date: Sun, 1 Nov 2026 20:33:46 +0900 Subject: [PATCH] =?UTF-8?q?=E5=90=8D=E5=89=8D=E3=82=92=E4=BB=98=E3=81=91?= =?UTF-8?q?=E3=81=9F=E3=83=96=E3=83=A9=E3=83=B3=E3=83=81=E3=82=92=E3=80=81?= =?UTF-8?q?=E5=B1=A5=E6=AD=B4=E3=81=A7=E6=89=B1=E3=81=88=E3=82=8B=E3=82=88?= =?UTF-8?q?=E3=81=86=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- UndoTree.Tests/UndoTreeLineTests.cs | 437 ++++++++++++++++++++++++++++ UndoTree.Tests/UndoTreeTextTests.cs | 8 +- UndoTree/Texts.csv | 2 + UndoTree/UndoTreeExport.cs | 2 +- UndoTree/UndoTreeHistory.cs | 128 +++++++- UndoTree/UndoTreeLine.cs | 17 ++ UndoTree/UndoTreeNodeViewModel.cs | 4 +- UndoTree/UndoTreeText.cs | 4 +- 8 files changed, 593 insertions(+), 9 deletions(-) create mode 100644 UndoTree.Tests/UndoTreeLineTests.cs create mode 100644 UndoTree/UndoTreeLine.cs diff --git a/UndoTree.Tests/UndoTreeLineTests.cs b/UndoTree.Tests/UndoTreeLineTests.cs new file mode 100644 index 0000000..5ef3016 --- /dev/null +++ b/UndoTree.Tests/UndoTreeLineTests.cs @@ -0,0 +1,437 @@ +using YukkuriMovieMaker.Plugin; +using YukkuriMovieMaker.Project; +using YukkuriMovieMaker.UndoRedo; + +namespace UndoTree.Tests; + +public sealed class UndoTreeLineTests +{ + static UndoTreeHistory Track(UndoRedoManager manager, IUndoRedoable document, bool withReader = true, int capacity = 100) + => new(manager, new AsyncAwaitStatus(), [document], capacity, withReader ? UndoRedoManagerReader.Create(manager) : null); + + static (UndoRedoManager Manager, Document Document, UndoTreeHistory History, UndoTreeNodeViewModel[] Nodes) Chain(int length, int capacity = 100) + { + var (manager, document) = Histories.NewDocument("p1"); + var history = Track(manager, document, capacity: capacity); + var nodes = new UndoTreeNodeViewModel[length]; + for (var index = 0; index < length; index++) + { + Histories.Edit(manager, () => document.X = index + 1); + nodes[index] = history.Cursor; + } + + return (manager, document, history, nodes); + } + + static async Task UndoAll(UndoRedoManager manager) + { + while (manager.IsUndoable) + await manager.UndoAsync(); + } + + [Fact] + public async Task AStartedLineIsActiveAndBeginsAtTheNodeItWasStartedFrom() + { + var (manager, document, history, nodes) = Chain(2); + using var _ = history; + + var line = await history.StartLineAsync(history.Cursor); + + Assert.Same(line, history.ActiveLine); + Assert.Same(line, Assert.Single(history.Lines)); + Assert.Same(nodes[1], line.Base); + Assert.Same(nodes[1], line.Head); + Assert.Same(nodes[1], history.Floor); + Assert.Equal(string.Format(Texts.LineDefaultName, 1), line.Name); + Assert.False(manager.IsUndoable); + Assert.Equal(2, document.X); + } + + [Fact] + public async Task UndoInsideALineStopsAtItsStart() + { + var (manager, document, history, nodes) = Chain(2); + using var _ = history; + await history.StartLineAsync(history.Cursor); + Histories.Edit(manager, () => document.X = 3); + Histories.Edit(manager, () => document.X = 4); + + await UndoAll(manager); + + Assert.Equal(2, document.X); + Assert.Same(nodes[1], history.Cursor); + Assert.Equal(5, history.Count); + } + + [Fact] + public async Task TwoLinesStartedFromTheSameNodeKeepTheirOwnStates() + { + var (manager, document, history, nodes) = Chain(2); + using var _ = history; + var first = await history.StartLineAsync(nodes[1]); + Histories.Edit(manager, () => document.X = 10); + var second = await history.StartLineAsync(nodes[1]); + Histories.Edit(manager, () => document.X = 20); + + var atSecond = document.X; + await history.SwitchToAsync(first); + var atFirst = document.X; + await UndoAll(manager); + var floorOfFirst = document.X; + await history.SwitchToAsync(second); + + Assert.Equal(20, atSecond); + Assert.Equal(10, atFirst); + Assert.Equal(2, floorOfFirst); + Assert.Equal(20, document.X); + Assert.Same(second, history.ActiveLine); + Assert.Equal(2, history.Lines.Count); + } + + [Fact] + public async Task LeavingALineReturnsToWhereTheWholeHistoryWasLeft() + { + var (manager, document, history, nodes) = Chain(2); + using var _ = history; + await history.StartLineAsync(nodes[0]); + + await history.SwitchToAsync(null); + var back = document.X; + await UndoAll(manager); + + Assert.Equal(2, back); + Assert.Equal(0, document.X); + Assert.Null(history.ActiveLine); + Assert.Same(history.Root, history.Floor); + } + + [Fact] + public async Task ALineRemembersWhereYouLeftIt() + { + var (manager, document, history, nodes) = Chain(2); + using var _ = history; + var line = await history.StartLineAsync(nodes[1]); + Histories.Edit(manager, () => document.X = 3); + var third = history.Cursor; + Histories.Edit(manager, () => document.X = 4); + await manager.UndoAsync(); + + await history.SwitchToAsync(null); + var outside = document.X; + await history.SwitchToAsync(line); + var inside = document.X; + await manager.RedoAsync(); + + Assert.Equal(2, outside); + Assert.Equal(3, inside); + Assert.Equal(4, document.X); + Assert.Same(third, line.Head); + } + + [Fact] + public async Task JumpingOutOfALineLeavesItAndRemembersTheHead() + { + var (manager, document, history, nodes) = Chain(2); + using var _ = history; + var line = await history.StartLineAsync(nodes[1]); + Histories.Edit(manager, () => document.X = 3); + var third = history.Cursor; + + await history.JumpAsync(nodes[0]); + var leftAt = (history.ActiveLine, history.Floor, line.Head); + await history.SwitchToAsync(line); + + Assert.Null(leftAt.ActiveLine); + Assert.Same(history.Root, leftAt.Floor); + Assert.Same(third, leftAt.Head); + Assert.Same(third, history.Cursor); + Assert.Same(line, history.ActiveLine); + Assert.Same(nodes[1], history.Floor); + } + + [Fact] + public async Task SwitchingToTheLineThatIsAlreadyActiveChangesNothing() + { + var (_, _, history, nodes) = Chain(2); + using var _ = history; + var line = await history.StartLineAsync(nodes[1]); + var announced = 0; + history.Changed += (_, _) => announced++; + + await history.SwitchToAsync(line); + + Assert.Equal(0, announced); + } + + [Fact] + public async Task RenamingTrimsTheNameAndRefusesAnEmptyOrUnchangedOne() + { + var (_, _, history, nodes) = Chain(1); + using var _ = history; + var line = await history.StartLineAsync(nodes[0]); + var announced = 0; + history.Changed += (_, _) => announced++; + + var renamed = history.RenameLine(line, " Colors "); + var empty = history.RenameLine(line, " "); + var same = history.RenameLine(line, "Colors"); + + Assert.True(renamed); + Assert.False(empty); + Assert.False(same); + Assert.Equal("Colors", line.Name); + Assert.Equal(1, announced); + } + + [Fact] + public async Task DeletingTheActiveLineKeepsTheStateAndLiftsTheFloor() + { + var (manager, document, history, nodes) = Chain(2); + using var _ = history; + var line = await history.StartLineAsync(nodes[1]); + Histories.Edit(manager, () => document.X = 3); + var tip = history.Cursor; + + var deleted = history.DeleteLine(line); + await UndoAll(manager); + + Assert.True(deleted); + Assert.Empty(history.Lines); + Assert.Null(history.ActiveLine); + Assert.Same(history.Root, history.Floor); + Assert.Equal(0, document.X); + Assert.Equal(4, history.Count); + Assert.NotNull(tip); + } + + [Fact] + public async Task DeletingAnotherLineLeavesTheActiveOneAlone() + { + var (manager, document, history, nodes) = Chain(2); + using var _ = history; + var first = await history.StartLineAsync(nodes[0]); + var second = await history.StartLineAsync(nodes[1]); + + var deleted = history.DeleteLine(first); + var again = history.DeleteLine(first); + await UndoAll(manager); + + Assert.True(deleted); + Assert.False(again); + Assert.Same(second, Assert.Single(history.Lines)); + Assert.Same(second, history.ActiveLine); + Assert.Same(nodes[1], history.Floor); + Assert.Equal(2, document.X); + } + + [Fact] + public async Task AClearOfTheHostForgetsEveryLine() + { + var (manager, _, history, nodes) = Chain(2); + using var _ = history; + await history.StartLineAsync(nodes[0]); + await history.StartLineAsync(nodes[1]); + + manager.Clear(); + + Assert.Empty(history.Lines); + Assert.Null(history.ActiveLine); + Assert.Same(history.Root, history.Floor); + Assert.Equal(string.Format(Texts.LineDefaultName, 1), (await history.StartLineAsync(history.Root)).Name); + } + + [Fact] + public async Task DroppingSideBranchesRemovesTheLinesWhoseStartIsGoneAndPullsBackTheirHeads() + { + var (manager, document, history, nodes) = Chain(3); + using var _ = history; + var kept = await history.StartLineAsync(nodes[1]); + await history.JumpAsync(nodes[2]); + await history.SwitchToAsync(null); + await history.JumpAsync(nodes[1]); + Histories.Edit(manager, () => document.X = 8); + var newer = history.Cursor; + await history.JumpAsync(nodes[1]); + var doomed = await history.StartLineAsync(nodes[2]); + await history.SwitchToAsync(null); + await history.JumpAsync(newer); + await history.JumpAsync(nodes[1]); + + history.DropSideBranches(); + + Assert.Contains(kept, history.Lines); + Assert.DoesNotContain(doomed, history.Lines); + Assert.Same(nodes[1], kept.Head); + Assert.DoesNotContain(nodes[2], history.Nodes); + } + + [Fact] + public async Task PruningOldBranchesKeepsTheHeadOfALine() + { + var (manager, document, history, nodes) = Chain(1, capacity: 5); + using var _ = history; + var line = await history.StartLineAsync(nodes[0]); + Histories.Edit(manager, () => document.X = 2); + var head = history.Cursor; + await history.SwitchToAsync(null); + + for (var value = 3; value <= 6; value++) + Histories.Edit(manager, () => document.X = value); + + Assert.Contains(head, history.Nodes); + Assert.Same(head, line.Head); + } + + [Fact] + public async Task TheReturnPointOfTheWholeHistoryIsPulledBackWhenItsNodeIsDropped() + { + var (manager, document, history, nodes) = Chain(3); + using var _ = history; + await history.StartLineAsync(nodes[1]); + Histories.Edit(manager, () => document.X = 8); + var newer = history.Cursor; + await history.JumpAsync(nodes[1]); + await history.JumpAsync(newer); + + history.DropSideBranches(); + await history.SwitchToAsync(null); + + Assert.DoesNotContain(nodes[2], history.Nodes); + Assert.Same(nodes[1], history.Cursor); + Assert.Equal(2, document.X); + } + + [Fact] + public async Task PruningOldBranchesKeepsTheReturnPointOfTheWholeHistory() + { + var (manager, document, history, nodes) = Chain(2, capacity: 5); + using var _ = history; + await history.StartLineAsync(nodes[0]); + + for (var value = 3; value <= 6; value++) + Histories.Edit(manager, () => document.X = value); + + Assert.Contains(nodes[1], history.Nodes); + } + + [Fact] + public async Task WithoutRewritableListsALineCannotBeStarted() + { + var (manager, document) = Histories.NewDocument(); + using var history = Track(manager, document, withReader: false); + Histories.Edit(manager, () => document.X = 1); + + await Assert.ThrowsAsync(() => history.StartLineAsync(history.Cursor)); + + Assert.Empty(history.Lines); + Assert.Null(history.ActiveLine); + } + + [Fact] + public async Task WhenTheHostTrimsTheListTheActiveLineStartsLater() + { + var (manager, document, history, nodes) = Chain(4); + using var _ = history; + var line = await history.StartLineAsync(nodes[3]); + manager.Capacity = 3; + + for (var value = 5; value <= 8; value++) + Histories.Edit(manager, () => document.X = value); + + Assert.Same(line, history.ActiveLine); + Assert.Same(history.Floor, line.Base); + Assert.NotSame(nodes[3], line.Base); + Assert.Equal(9, history.Count); + Assert.True(history.RootIsOpenState); + } + + [Fact] + public async Task TheNodeWhereALineStartsIsMarkedWithItsName() + { + var (_, _, history, nodes) = Chain(2); + using var _ = history; + + var first = await history.StartLineAsync(nodes[1]); + var second = await history.StartLineAsync(nodes[1]); + history.RenameLine(first, "Colors"); + + Assert.Equal($"[{string.Format(Texts.LineMark, "Colors")}][{string.Format(Texts.LineMark, second.Name)}]", nodes[1].LineMarks); + Assert.StartsWith(nodes[1].LineMarks, nodes[1].DisplayText); + Assert.Equal(string.Empty, nodes[0].LineMarks); + } + + [Fact] + public async Task TheMarkGoesAwayWithTheLine() + { + var (_, _, history, nodes) = Chain(1); + using var _ = history; + var line = await history.StartLineAsync(nodes[0]); + + history.DeleteLine(line); + + Assert.Equal(string.Empty, nodes[0].LineMarks); + } + + [Fact] + public async Task TheTreeTheListsAndTheLinesStayInStepWhateverHappens() + { + var (manager, document) = Histories.NewDocument("p1"); + using var history = Track(manager, document); + var reader = UndoRedoManagerReader.Create(manager)!; + var states = new Dictionary { [history.Root.Id] = 0 }; + history.Changed += (_, _) => Assert.Same(history.ActiveLine?.Base ?? history.Root, history.Floor); + var random = new Random(20261103); + var counter = 0; + var count = 1; + for (var step = 0; step < 500; step++) + { + switch (random.Next(10)) + { + case 0 or 1 or 2: + Histories.Edit(manager, () => document.X = ++counter); + states[history.Cursor.Id] = counter; + break; + case 3 when manager.IsUndoable: + await manager.UndoAsync(); + break; + case 4 when manager.IsRedoable: + await manager.RedoAsync(); + break; + case 5: + var nodes = history.Nodes.ToArray(); + await history.JumpAsync(nodes[random.Next(nodes.Length)]); + break; + case 6: + var from = history.Nodes.ToArray(); + await history.StartLineAsync(from[random.Next(from.Length)]); + break; + case 7 when history.Lines.Count > 0: + await history.SwitchToAsync(history.Lines[random.Next(history.Lines.Count)]); + break; + case 8: + await history.SwitchToAsync(null); + break; + default: + if (history.Lines.Count > 0) + history.DeleteLine(history.Lines[random.Next(history.Lines.Count)]); + + break; + } + + var cursor = history.Cursor; + Assert.Equal(states[cursor.Id], document.X); + Assert.Contains(history.Floor, cursor.PathFromRoot()); + Assert.Equal(cursor.StepsBelow(history.Floor).Select(node => node.Handle), reader.Undo); + Assert.Equal(!ReferenceEquals(cursor, history.Floor), manager.IsUndoable); + Assert.Same(history.ActiveLine?.Base ?? history.Root, history.Floor); + Assert.True(history.Count >= count); + count = history.Count; + foreach (var line in history.Lines) + { + Assert.Contains(line.Base, history.Nodes); + Assert.Contains(line.Head, history.Nodes); + Assert.Contains(line.Base, line.Head.PathFromRoot()); + } + } + } +} diff --git a/UndoTree.Tests/UndoTreeTextTests.cs b/UndoTree.Tests/UndoTreeTextTests.cs index be8cd25..84e3f36 100644 --- a/UndoTree.Tests/UndoTreeTextTests.cs +++ b/UndoTree.Tests/UndoTreeTextTests.cs @@ -40,11 +40,11 @@ public sealed class UndoTreeTextTests } [Fact] - public void TheMarksComeInTheOrderBaseSavedTag() + public void TheMarksComeInTheOrderBaseSavedTagLines() { - Assert.Equal($"[{Texts.BaseMark}][{Texts.SavedMark}][tag]", UndoTreeText.Marks(true, true, "tag")); - Assert.Equal($"[{Texts.SavedMark}]", UndoTreeText.Marks(false, true, string.Empty)); - Assert.Equal(string.Empty, UndoTreeText.Marks(false, false, string.Empty)); + Assert.Equal($"[{Texts.BaseMark}][{Texts.SavedMark}][tag][line]", UndoTreeText.Marks(true, true, "tag", "[line]")); + Assert.Equal($"[{Texts.SavedMark}]", UndoTreeText.Marks(false, true, string.Empty, string.Empty)); + Assert.Equal(string.Empty, UndoTreeText.Marks(false, false, string.Empty, string.Empty)); } [Fact] diff --git a/UndoTree/Texts.csv b/UndoTree/Texts.csv index 4603ff5..c264612 100644 --- a/UndoTree/Texts.csv +++ b/UndoTree/Texts.csv @@ -558,3 +558,5 @@ RecoveryDismiss,,閉じる,Close,关闭,關閉,닫기,Cerrar,إغلاق,Tutup DiffHeaderLast,,前回の最後の状態からの変更点,Changes from the last state of the previous session,相对于上次最后状态的更改,相對於上次最後狀態的變更,이전 세션의 마지막 상태로부터의 변경점,Cambios desde el último estado de la sesión anterior,التغييرات منذ الحالة الأخيرة من الجلسة السابقة,Perubahan dari kondisi terakhir sesi sebelumnya DiffEmptyLast,,前回の最後の状態との差はありません,There is no difference from the last state of the previous session,与上次最后状态没有差异,與上次最後狀態沒有差異,이전 세션의 마지막 상태와 차이가 없습니다,No hay diferencias con el último estado de la sesión anterior,لا يوجد فرق عن الحالة الأخيرة من الجلسة السابقة,Tidak ada perbedaan dari kondisi terakhir sesi sebelumnya RecordNotReplayable,,再現できない操作を含むため、適用できません,Cannot apply because it includes an operation that cannot be reproduced.,包含无法重现的操作,因此无法应用。,包含無法重現的操作,因此無法套用。,재현할 수 없는 작업이 포함되어 있어 적용할 수 없습니다.,No se puede aplicar porque incluye una operación que no se puede reproducir.,لا يمكن التطبيق لأنه يتضمن عملية لا يمكن إعادة إنتاجها.,Tidak dapat diterapkan karena mencakup operasi yang tidak dapat direproduksi. +LineMark,,サブ履歴: {0},Sub-history: {0},子历史记录:{0},子歷史記錄:{0},하위 기록: {0},Subhistorial: {0},سجل فرعي: {0},Sub-riwayat: {0} +LineDefaultName,,サブ履歴 {0},Sub-history {0},子历史记录 {0},子歷史記錄 {0},하위 기록 {0},Subhistorial {0},سجل فرعي {0},Sub-riwayat {0} diff --git a/UndoTree/UndoTreeExport.cs b/UndoTree/UndoTreeExport.cs index 34574af..2748aa0 100644 --- a/UndoTree/UndoTreeExport.cs +++ b/UndoTree/UndoTreeExport.cs @@ -43,7 +43,7 @@ internal static class UndoTreeExport static void AppendNode(StringBuilder text, UndoTreeRecordNode node, int level) { - var marks = UndoTreeText.Marks(false, node.Saved, node.Tag); + var marks = UndoTreeText.Marks(false, node.Saved, node.Tag, string.Empty); var label = UndoTreeText.SingleLine(node.Parent < 0 && node.Label.Length == 0 ? Texts.InitialState : node.Label); var time = node.Time == DateTime.MinValue ? string.Empty : $" ({node.Time:T})"; AppendLine(text, level, (marks.Length > 0 ? marks + " " : string.Empty) + label + time); diff --git a/UndoTree/UndoTreeHistory.cs b/UndoTree/UndoTreeHistory.cs index e89f84e..6cc0a05 100644 --- a/UndoTree/UndoTreeHistory.cs +++ b/UndoTree/UndoTreeHistory.cs @@ -32,6 +32,9 @@ internal class UndoTreeHistory : IDisposable bool observing; bool ownersCurrent; int addedInMerge; + readonly List lines = []; + UndoTreeNodeViewModel? mainHead; + int lineNumber; internal UndoTreeHistory(UndoRedoManager manager, AsyncAwaitStatus asyncAwaitStatus, IReadOnlyList roots, int capacity, UndoRedoManagerReader? reader, Action? report = null) { @@ -58,6 +61,10 @@ internal class UndoTreeHistory : IDisposable public bool CanSetFloor => source is { CanRewriteUndo: true }; + public UndoTreeLine? ActiveLine { get; private set; } + + public IReadOnlyList Lines => lines; + public int Capacity { get; set; } public bool PreferReplay { get; set; } @@ -142,6 +149,7 @@ internal class UndoTreeHistory : IDisposable if (source is not null) changed |= Merge(source.Undo, source.Redo); + changed |= Normalize(); UpdateFlags(); if (!changed) return; @@ -169,23 +177,39 @@ internal class UndoTreeHistory : IDisposable } public bool TrySetFloor(UndoTreeNodeViewModel node) + { + Reconcile(); + RememberPosition(); + return TryEnter(node, null); + } + + bool TryEnter(UndoTreeNodeViewModel node, UndoTreeLine? line) { Reconcile(); if (source is not { CanRewriteUndo: true } || isNavigating || !Cursor.PathFromRoot().Contains(node)) return false; - if (ReferenceEquals(node, Floor)) + if (ReferenceEquals(node, Floor) && ReferenceEquals(line, ActiveLine)) return true; if (!source.TrySetUndo(Cursor.StepsBelow(node).Select(step => step.Handle!).ToArray())) return false; Floor = node; + ActiveLine = line; Version++; Changed?.Invoke(this, EventArgs.Empty); return true; } + void RememberPosition() + { + if (ActiveLine is { } line) + line.Head = Cursor; + else + mainHead = Cursor; + } + void ReleaseFloorFor(UndoTreeNodeViewModel target) { if (UndoTreeNodeViewModel.CommonAncestor(Cursor, target).Depth >= Floor.Depth) @@ -194,11 +218,94 @@ internal class UndoTreeHistory : IDisposable if (!source!.TrySetUndo(Cursor.StepsBelow(Root).Select(step => step.Handle!).ToArray())) throw new UndoTreeOperationException(Texts.BranchUnavailable); + RememberPosition(); Floor = Root; + ActiveLine = null; Version++; Changed?.Invoke(this, EventArgs.Empty); } + public async Task StartLineAsync(UndoTreeNodeViewModel from) + { + var line = new UndoTreeLine(string.Format(Texts.LineDefaultName, ++lineNumber), from); + lines.Add(line); + try + { + await SwitchToAsync(line); + } + catch + { + lines.Remove(line); + throw; + } + + return line; + } + + public async Task SwitchToAsync(UndoTreeLine? line) + { + Reconcile(); + if (source is not { CanRewriteUndo: true }) + throw new UndoTreeOperationException(Texts.Unsupported); + + RememberPosition(); + await JumpAsync(line is null ? mainHead ?? Cursor : line.Head); + if (!TryEnter(line?.Base ?? Root, line)) + throw new UndoTreeOperationException(Texts.BranchUnavailable); + } + + public bool RenameLine(UndoTreeLine line, string name) + { + var next = name.Trim(); + if (next.Length == 0 || string.Equals(line.Name, next, StringComparison.Ordinal) || !lines.Contains(line)) + return false; + + line.Name = next; + UpdateFlags(); + Version++; + Changed?.Invoke(this, EventArgs.Empty); + return true; + } + + public bool DeleteLine(UndoTreeLine line) + { + if (!lines.Contains(line)) + return false; + + if (ReferenceEquals(line, ActiveLine) && !TryEnter(Root, null)) + return false; + + lines.Remove(line); + UpdateFlags(); + Version++; + Changed?.Invoke(this, EventArgs.Empty); + return true; + } + + bool Normalize() + { + if (lines.Count == 0 && mainHead is null) + return false; + + var live = new HashSet(Nodes, ReferenceEqualityComparer.Instance); + var removed = lines.RemoveAll(line => !live.Contains(line.Base)) > 0; + foreach (var line in lines) + line.Head = LiveAncestor(line.Head, live); + + if (mainHead is not null) + mainHead = LiveAncestor(mainHead, live); + + return removed; + } + + static UndoTreeNodeViewModel LiveAncestor(UndoTreeNodeViewModel node, HashSet live) + { + while (!live.Contains(node)) + node = node.Parent!; + + return node; + } + public async Task JumpAsync(UndoTreeNodeViewModel target) { Reconcile(); @@ -414,6 +521,7 @@ internal class UndoTreeHistory : IDisposable if (!removed) return; + Normalize(); UpdateFlags(); Version++; Changed?.Invoke(this, EventArgs.Empty); @@ -615,6 +723,10 @@ internal class UndoTreeHistory : IDisposable Root = CreateRoot(); Cursor = Root; Floor = Root; + lines.Clear(); + ActiveLine = null; + mainHead = null; + lineNumber = 0; owners = null; rootHash = null; rootTrimmed = false; @@ -640,7 +752,12 @@ internal class UndoTreeHistory : IDisposable return visible; if (visible.Count > 0 && byHandle.TryGetValue(visible[0], out var first)) + { + if (ActiveLine is { } active && ReferenceEquals(active.Base, Floor)) + active.Base = first.Parent!; + Floor = first.Parent!; + } return Floor.PathFromRoot().Skip(1).Select(node => node.Handle!).Concat(visible).ToArray(); } @@ -845,6 +962,10 @@ internal class UndoTreeHistory : IDisposable protectedNodes.Add(node); protectedNodes.Add(Cursor); + protectedNodes.UnionWith(lines.Select(line => line.Head)); + if (mainHead is not null) + protectedNodes.Add(mainHead); + var removed = false; while (Count > Capacity) { @@ -895,12 +1016,17 @@ internal class UndoTreeHistory : IDisposable for (var node = Cursor.Parent; node is not null; node = node.Parent) onPath.Add(node); + var lineMarks = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (var line in lines) + lineMarks[line.Base] = lineMarks.GetValueOrDefault(line.Base, string.Empty) + $"[{string.Format(Texts.LineMark, line.Name)}]"; + foreach (var node in Nodes) { node.IsCurrent = ReferenceEquals(node, Cursor); node.IsOnPath = onPath.Contains(node); node.IsRedoable = redoNodes.Contains(node); node.HasSideBranches = node.Children.Count > 1; + node.LineMarks = lineMarks.GetValueOrDefault(node, string.Empty); } } diff --git a/UndoTree/UndoTreeLine.cs b/UndoTree/UndoTreeLine.cs new file mode 100644 index 0000000..b493bdf --- /dev/null +++ b/UndoTree/UndoTreeLine.cs @@ -0,0 +1,17 @@ +namespace UndoTree; + +internal sealed class UndoTreeLine +{ + internal UndoTreeLine(string name, UndoTreeNodeViewModel start) + { + Name = name; + Base = start; + Head = start; + } + + public string Name { get; internal set; } + + public UndoTreeNodeViewModel Base { get; internal set; } + + public UndoTreeNodeViewModel Head { get; internal set; } +} diff --git a/UndoTree/UndoTreeNodeViewModel.cs b/UndoTree/UndoTreeNodeViewModel.cs index f47469c..4ee5825 100644 --- a/UndoTree/UndoTreeNodeViewModel.cs +++ b/UndoTree/UndoTreeNodeViewModel.cs @@ -127,13 +127,15 @@ internal class UndoTreeNodeViewModel : Bindable get { var text = IsRunHidden ? string.Format(Texts.FoldedRun, Text, FoldedCount + 1) : Text; - var marks = UndoTreeText.Marks(IsCompareBase, IsSaved, Tag); + var marks = UndoTreeText.Marks(IsCompareBase, IsSaved, Tag, LineMarks); return marks.Length > 0 ? $"{marks} {text}" : text; } } public string Tag { get; set => Set(ref field, value ?? string.Empty, nameof(Tag), nameof(DisplayText)); } = string.Empty; + public string LineMarks { get; set => Set(ref field, value ?? string.Empty, nameof(LineMarks), nameof(DisplayText)); } = string.Empty; + public bool IsCompareBase { get; set => Set(ref field, value, nameof(IsCompareBase), nameof(DisplayText)); } public bool IsSaved { get; set => Set(ref field, value, nameof(IsSaved), nameof(DisplayText)); } diff --git a/UndoTree/UndoTreeText.cs b/UndoTree/UndoTreeText.cs index 29a6c68..0d88e8b 100644 --- a/UndoTree/UndoTreeText.cs +++ b/UndoTree/UndoTreeText.cs @@ -24,6 +24,6 @@ internal static class UndoTreeText public static string WithNote(string text, string note) => note.Length > 0 ? $"{text} — {note}" : text; - public static string Marks(bool isCompareBase, bool isSaved, string tag) - => (isCompareBase ? $"[{Texts.BaseMark}]" : string.Empty) + (isSaved ? $"[{Texts.SavedMark}]" : string.Empty) + (tag.Length > 0 ? $"[{tag}]" : string.Empty); + public static string Marks(bool isCompareBase, bool isSaved, string tag, string lines) + => (isCompareBase ? $"[{Texts.BaseMark}]" : string.Empty) + (isSaved ? $"[{Texts.SavedMark}]" : string.Empty) + (tag.Length > 0 ? $"[{tag}]" : string.Empty) + lines; }