using System.Reflection; using System.Runtime.CompilerServices; using YukkuriMovieMaker.Plugin; using YukkuriMovieMaker.Project; using YukkuriMovieMaker.UndoRedo; namespace UndoTree; internal class UndoTreeHistory : IDisposable { static readonly ConditionalWeakTable Instances = []; readonly UndoRedoManager manager; readonly UndoRedoMirror mirror; readonly UndoRedoManagerReader? reader; readonly Action? report; readonly Dictionary byHandle = new(ReferenceEqualityComparer.Instance); readonly HashSet redoNodes = new(ReferenceEqualityComparer.Instance); AsyncAwaitStatus asyncAwaitStatus; IUndoRedoHistory? source; int nextId; long clock; bool isNavigating; bool readerLostReported; UndoTreeRecorder? recorder; UndoTreeSaveWatcher? saveWatcher; UndoTreeOwners? owners; internal UndoTreeHistory(UndoRedoManager manager, AsyncAwaitStatus asyncAwaitStatus, IReadOnlyList roots, int capacity, UndoRedoManagerReader? reader, Action? report = null) { this.manager = manager; this.asyncAwaitStatus = asyncAwaitStatus; this.report = report; this.reader = reader; Roots = roots; Capacity = capacity; mirror = new UndoRedoMirror(manager, roots); Root = CreateRoot(); Cursor = Root; manager.HistoryChanged += Manager_HistoryChanged; Reconcile(); } public UndoTreeNodeViewModel Root { get; private set; } public UndoTreeNodeViewModel Cursor { get; private set; } public int Capacity { get; set; } public bool PreferReplay { get; set; } public int Count => byHandle.Count + 1; public long Version { get; private set; } public bool IsSupported => source is not null; public bool CanReplay => source?.CanReplay ?? false; public UndoRedoHistorySource? Source => source?.Source; public IReadOnlyList Roots { get; } public IEnumerable Nodes => byHandle.Values.Prepend(Root); internal UndoTreeHostModel? Host { get; set; } public UndoTreeOwners Owners { get { owners ??= new UndoTreeOwners(Roots); return owners; } } public event EventHandler? Changed; public static UndoTreeHistory For(TimelineToolInfo info) { var history = Instances.GetValue(info.UndoRedoManager, manager => { var created = new UndoTreeHistory(manager, info.AsyncAwaitStatus, RootsOf(info.Scenes), UndoTreeSettings.Default.MaxNodes, UndoRedoManagerReader.Create(manager), UndoTreeTelemetry.Report); created.recorder = new UndoTreeRecorder(created, UndoTreeRecordStore.Default, created.HostProjectPath); UndoTreeDispatch.Defer(() => { created.Host = UndoTreeHostModel.Find(manager); if (created.Host is null) UndoTreeTelemetry.Report(new InvalidOperationException("The main model of the host was not found.")); else created.saveWatcher = new UndoTreeSaveWatcher(created, created.Host); }); return created; }); history.asyncAwaitStatus = info.AsyncAwaitStatus; history.Capacity = UndoTreeSettings.Default.MaxNodes; history.PreferReplay = UndoTreeSettings.Default.PreferReplay; return history; } public void Dispose() { saveWatcher?.Dispose(); recorder?.Dispose(); manager.HistoryChanged -= Manager_HistoryChanged; mirror.Dispose(); } public void Reconcile() { var selected = Select(); var changed = false; if (!ReferenceEquals(selected, source)) { if (source is not null && selected is not null && !readerLostReported && ReferenceEquals(source, reader)) { readerLostReported = true; report?.Invoke(new InvalidOperationException("The internal lists of UndoRedoManager no longer match its state.")); } source = selected; ResetTree(); changed = true; } if (source is not null) changed |= Merge(source.Undo, source.Redo); UpdateFlags(); if (!changed) return; Version++; Changed?.Invoke(this, EventArgs.Empty); } public async Task UndoAsync() { if (!manager.IsUndoable) return; using (asyncAwaitStatus.Lock()) await manager.UndoAsync(); } public async Task RedoAsync() { if (!manager.IsRedoable) return; using (asyncAwaitStatus.Lock()) await manager.RedoAsync(); } public async Task JumpAsync(UndoTreeNodeViewModel target) { Reconcile(); if (source is null) throw new UndoTreeOperationException(Texts.Unsupported); isNavigating = true; try { using (asyncAwaitStatus.Lock()) { var ancestor = UndoTreeNodeViewModel.CommonAncestor(Cursor, target); var undone = Cursor.StepsBelow(ancestor).Reverse().ToArray(); var descent = target.StepsBelow(ancestor); if (descent.Count > 0 && !IsDescendable(source, descent, undone)) throw new UndoTreeOperationException(Texts.BranchUnavailable); foreach (var _ in undone) await manager.UndoAsync(); if (descent.Count > 0) await DescendAsync(source, descent, target); } } finally { isNavigating = false; Reconcile(); } } public async Task ApplyAsync(IReadOnlyList sources, ConflictPolicy policy, bool inverse = false) { Reconcile(); if (source is null) throw new UndoTreeOperationException(Texts.Unsupported); 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 applied = 0; var conflicts = new List(); if (sources.Count == 0) return new UndoTreeApplyResult(0, conflicts); var touched = TouchedOnTheWayTo(sources[0]); isNavigating = true; try { using (asyncAwaitStatus.Lock()) { foreach (var node in sources) { var result = await ReplayAsync(source, node.Handle!, true, policy, touched, inverse); applied += result.Applied; conflicts.AddRange(result.Conflicts); Merge(source.Undo, source.Redo); } } } finally { isNavigating = false; Reconcile(); } return new UndoTreeApplyResult(applied, conflicts); } public IReadOnlyList PredictConflicts(IReadOnlyList sources, ConflictPolicy policy, bool inverse = false) { var conflicts = new List(); if (source is not { CanReplay: true } || sources.Count == 0) return conflicts; var touched = TouchedOnTheWayTo(sources[0]); var apply = policy == ConflictPolicy.Apply; 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); 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)); } } return conflicts; } public int CountSideBranches() { var keep = NodesToKeep(); return byHandle.Values.Count(node => !keep.Contains(node)); } public void DropSideBranches() { var keep = NodesToKeep(); var removed = false; foreach (var node in byHandle.Values.ToArray()) { if (keep.Contains(node)) continue; Detach(node); removed = true; } if (!removed) return; UpdateFlags(); Version++; Changed?.Invoke(this, EventArgs.Empty); } HashSet NodesToKeep() { var keep = new HashSet(ReferenceEqualityComparer.Instance); for (var node = Cursor; node is not null; node = node.Parent) keep.Add(node); foreach (var node in Cursor.PrimaryChain()) keep.Add(node); return keep; } HashSet TouchedOnTheWayTo(UndoTreeNodeViewModel first) { var touched = new HashSet(); var ancestor = UndoTreeNodeViewModel.CommonAncestor(Cursor, first); foreach (var node in Cursor.StepsBelow(ancestor)) touched.UnionWith(node.Keys); return touched; } public IReadOnlyList NetChangeOf(IReadOnlyList steps) => source is null ? [] : UndoTreeDiff.Between(source, [], steps); public string? ProjectPath => recorder?.CurrentPath(); string? HostProjectPath() => Host is { } host ? host.ProjectPath : UndoTreeProject.PathOfOnlyWindow(); public void MarkSaved() { if (Count <= 1 || Cursor.IsSaved) return; Cursor.IsSaved = true; Version++; Changed?.Invoke(this, EventArgs.Empty); } public void SetTag(UndoTreeNodeViewModel node, string tag) { var next = tag.Trim(); if (string.Equals(node.Tag, next, StringComparison.Ordinal)) return; node.Tag = next; Version++; Changed?.Invoke(this, EventArgs.Empty); } public bool HasPreviousRecord => recorder?.HasPrevious() ?? false; public UndoTreeRecord? PreviousRecord() => recorder?.Previous(); public UndoTreeRecord ToRecord() { var nodes = Nodes.OrderBy(node => node.Id).Select(node => new UndoTreeRecordNode( node.Id, node.Parent?.Id ?? -1, node.Label, node.Time, node.Commands.Select(command => new UndoTreeRecordCommand(command.Kind.ToString(), command.TargetLabel, command.Member, command.Detail)).ToArray(), node.Tag, node.IsSaved)); return new UndoTreeRecord(DateTime.Now, nodes.ToArray()); } public IReadOnlyList DiffFromCurrent(UndoTreeNodeViewModel node) => Diff(Cursor, node); public IReadOnlyList Diff(UndoTreeNodeViewModel from, UndoTreeNodeViewModel to) { if (source is null) return []; var ancestor = UndoTreeNodeViewModel.CommonAncestor(from, to); return UndoTreeDiff.Between(source, from.StepsBelow(ancestor), to.StepsBelow(ancestor)); } static IReadOnlyList RootsOf(Scenes scenes) { var roots = new List { scenes }; if (CharacterSettingsRoot() is { } characters) roots.Add(characters); return roots; } static IUndoRedoable? CharacterSettingsRoot() { try { var type = typeof(Scenes).Assembly.GetType("YukkuriMovieMaker.Settings.CharacterSettings"); var settings = type is null ? null : typeof(SettingsBase<>).MakeGenericType(type); return settings?.GetProperty("Default", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as IUndoRedoable; } catch (Exception exception) when (exception is TargetInvocationException or ArgumentException or TypeLoadException) { return null; } } UndoTreeCommandInfo InContext(UndoTreeCommandInfo info) { if (info.Target is not { } target) return info; var name = UndoTreeTargetNames.Of(target, Owners); return info.Kind switch { CommandKind.Property or CommandKind.Indexer => info with { TargetLabel = name.Full }, CommandKind.ListItems when name.Owner is not null => info with { TargetLabel = name.Full }, _ => info, }; } static string LabelOf(IReadOnlyList commands) { if (commands.Count == 0) return Texts.Operation; return commands.Count == 1 ? commands[0].Text : string.Format(Texts.OperationAndMore, commands[0].Text, commands.Count - 1); } static async Task ExecuteAsync(IUndoRedoCommandBase command, bool inverse) { if (command is IUndoRedoCommand synchronous) { if (inverse) synchronous.Undo(); else synchronous.Redo(); } else if (command is IUndoRedoAsyncCommand asynchronous) { if (inverse) await asynchronous.UndoAsync(); else await asynchronous.RedoAsync(); } } void Manager_HistoryChanged(object? sender, EventArgs e) { if (!isNavigating) Reconcile(); } IUndoRedoHistory? Select() { if (reader is { IsConsistent: true }) return reader; return mirror.IsConsistent ? mirror : null; } UndoTreeNodeViewModel CreateRoot() => new(nextId++, null, null, string.Empty, [], DateTime.MinValue, clock); void ResetTree() { byHandle.Clear(); redoNodes.Clear(); Root = CreateRoot(); Cursor = Root; owners = null; } void MoveCursor(UndoTreeNodeViewModel next) { if (owners is not null && ChangesOwnershipBetween(Cursor, next)) owners = null; Cursor = next; } bool ChangesOwnershipBetween(UndoTreeNodeViewModel from, UndoTreeNodeViewModel to) { var ancestor = UndoTreeNodeViewModel.CommonAncestor(from, to); return from.StepsBelow(ancestor).Concat(to.StepsBelow(ancestor)).Any(node => node.ChangesOwnership); } bool Merge(IReadOnlyList undo, IReadOnlyList redo) { if (undo.Count == 0 && redo.Count == 0) { if (Root.Children.Count == 0 && ReferenceEquals(Cursor, Root) && redoNodes.Count == 0) return false; ResetTree(); return true; } var changed = false; var node = Root; for (var index = 0; index < undo.Count; index++) { var handle = undo[index]; var child = ChildOf(node, handle); if (child is null) { if (index == 0 && byHandle.TryGetValue(handle, out var existing)) { Promote(existing); child = existing; } else { child = Add(node, handle); } changed = true; } node.LastVisited = child; child.Visit = ++clock; node = child; } if (!ReferenceEquals(Cursor, node)) { MoveCursor(node); changed = true; } var redoSet = new HashSet(ReferenceEqualityComparer.Instance); var tail = node; for (var index = redo.Count - 1; index >= 0; index--) { var handle = redo[index]; var child = ChildOf(tail, handle); if (child is null) { child = Add(tail, handle); changed = true; } tail.LastVisited = child; child.Visit = ++clock; redoSet.Add(child); tail = child; } if (!redoNodes.SetEquals(redoSet)) { redoNodes.Clear(); redoNodes.UnionWith(redoSet); changed = true; } return Prune(tail) || changed; } static UndoTreeNodeViewModel? ChildOf(UndoTreeNodeViewModel parent, object handle) { foreach (var child in parent.Children) { if (ReferenceEquals(child.Handle, handle)) return child; } return null; } UndoTreeNodeViewModel Add(UndoTreeNodeViewModel parent, object handle) { IReadOnlyList commands; string label; try { commands = source!.CommandsOf(handle).Select(command => InContext(UndoRedoCommandView.Read(command).Describe())).ToArray(); label = LabelOf(commands); } catch (Exception exception) when (exception is not OperationCanceledException) { report?.Invoke(exception); commands = []; label = Texts.Operation; } var node = new UndoTreeNodeViewModel(nextId++, handle, parent, label, commands, DateTime.Now, ++clock); parent.Children.Add(node); byHandle[handle] = node; return node; } void Promote(UndoTreeNodeViewModel node) { var keep = new HashSet(ReferenceEqualityComparer.Instance); var pending = new Stack(); pending.Push(node); while (pending.Count > 0) { var current = pending.Pop(); keep.Add(current); foreach (var child in current.Children) pending.Push(child); } foreach (var pair in byHandle.ToArray()) { if (!keep.Contains(pair.Value)) byHandle.Remove(pair.Key); } node.Parent!.Children.Remove(node); node.Parent = Root; Root.Children.Clear(); Root.Children.Add(node); Root.LastVisited = node; } bool Prune(UndoTreeNodeViewModel tail) { if (Count <= Capacity) return false; var protectedNodes = new HashSet(ReferenceEqualityComparer.Instance); for (var node = tail; node is not null; node = node.Parent) protectedNodes.Add(node); protectedNodes.Add(Cursor); var removed = false; while (Count > Capacity) { UndoTreeNodeViewModel? candidate = null; foreach (var node in byHandle.Values) { if (node.Children.Count != 0 || protectedNodes.Contains(node)) continue; if (candidate is null || node.Visit < candidate.Visit) candidate = node; } if (candidate is null) break; Detach(candidate); removed = true; } return removed; } void Detach(UndoTreeNodeViewModel node) { var stack = new Stack(); stack.Push(node); while (stack.Count > 0) { var current = stack.Pop(); if (current.Handle is { } handle) byHandle.Remove(handle); redoNodes.Remove(current); foreach (var child in current.Children) stack.Push(child); } var parent = node.Parent!; parent.Children.Remove(node); if (ReferenceEquals(parent.LastVisited, node)) parent.LastVisited = null; } void UpdateFlags() { var onPath = new HashSet(ReferenceEqualityComparer.Instance); for (var node = Cursor.Parent; node is not null; node = node.Parent) onPath.Add(node); 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; } } static bool IsRedoLine(IReadOnlyList redo, IReadOnlyList descent) => descent.Count <= redo.Count && descent.Select((node, index) => ReferenceEquals(redo[redo.Count - 1 - index], node.Handle)).All(matches => matches); static bool IsDescendable(IUndoRedoHistory history, IReadOnlyList descent, IReadOnlyList undone) => history.CanReplay || history.CanRewriteRedo || IsRedoLine(history.Redo.Concat(undone.Select(node => node.Handle!)).ToArray(), descent); async Task DescendAsync(IUndoRedoHistory history, IReadOnlyList descent, UndoTreeNodeViewModel target) { if (IsRedoLine(history.Redo, descent)) { for (var step = 0; step < descent.Count; step++) await manager.RedoAsync(); return; } var chain = descent.Concat(target.PrimaryChain()).Select(node => node.Handle!).ToArray(); if (!PreferReplay && history.CanRewriteRedo && history.TrySetRedo(chain)) { for (var step = 0; step < descent.Count; step++) await manager.RedoAsync(); return; } if (!history.CanReplay) throw new UndoTreeOperationException(Texts.BranchUnavailable); foreach (var node in descent) { var result = await ReplayAsync(history, node.Handle!, false, ConflictPolicy.Skip, [], false); if (result.Handle is null) throw new UndoTreeOperationException(Texts.NothingToApply); byHandle.Remove(node.Handle!); node.Handle = result.Handle; byHandle[result.Handle] = node; } } async Task ReplayAsync(IUndoRedoHistory history, object handle, bool check, ConflictPolicy policy, HashSet touched, bool inverse) { var commands = inverse ? history.CommandsOf(handle).Reverse().ToArray() : history.CommandsOf(handle); var before = history.Undo; var applied = 0; var conflicts = new List(); try { foreach (var pass in new[] { false, true }) { foreach (var command in commands.Where(command => command.IsAction == pass)) { if (await ReplayCommandAsync(command, check, policy, touched, conflicts, inverse)) applied++; } } } finally { manager.Record(); } var after = history.Undo; var recorded = after.Count > 0 && (after.Count != before.Count || !ReferenceEquals(after[^1], before.Count > 0 ? before[^1] : null)); return new ReplayResult(recorded ? after[^1] : null, applied, conflicts); } async Task ReplayCommandAsync(IUndoRedoCommandBase command, bool check, ConflictPolicy policy, HashSet touched, List conflicts, bool inverse) { if (command.IsAction) { await ExecuteAsync(command, inverse); manager.AddCommand(command); return true; } if (!check) { await ExecuteAsync(command, inverse); return true; } var view = UndoRedoCommandView.Read(command); var info = InContext(view.Describe()); var verdict = Judge(view, touched, inverse); var apply = policy == ConflictPolicy.Apply; switch (verdict) { 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; } } static Verdict Judge(UndoRedoCommandView view, HashSet touched, bool inverse) { 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); 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); } enum Verdict { Run, DeadTarget, Unreadable, Merged, SameProperty, } sealed record ReplayResult(object? Handle, int Applied, IReadOnlyList Conflicts); }