diff --git a/UndoTree/UndoTreeOwners.cs b/UndoTree/UndoTreeOwners.cs new file mode 100644 index 0000000..e160407 --- /dev/null +++ b/UndoTree/UndoTreeOwners.cs @@ -0,0 +1,94 @@ +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Specialized; +using System.Diagnostics; +using System.Reflection; +using YukkuriMovieMaker.UndoRedo; + +namespace UndoTree; + +internal class UndoTreeOwners +{ + const int MaxObjects = 200000; + + static readonly TimeSpan MaxTime = TimeSpan.FromMilliseconds(150); + static readonly ConcurrentDictionary Properties = new(); + + readonly Dictionary parents = new(ReferenceEqualityComparer.Instance); + + public UndoTreeOwners(IEnumerable roots) + { + var watch = Stopwatch.StartNew(); + var seen = new HashSet(ReferenceEqualityComparer.Instance); + var pending = new Queue(); + foreach (var root in roots) + { + if (seen.Add(root)) + pending.Enqueue(root); + } + + while (pending.Count > 0 && seen.Count < MaxObjects && watch.Elapsed < MaxTime) + { + var owner = pending.Dequeue(); + foreach (var child in ChildrenOf(owner)) + { + if (!seen.Add(child)) + continue; + + parents[child] = owner; + pending.Enqueue(child); + } + } + } + + public IReadOnlyList OwnersOf(object target) + { + var owners = new List(); + for (var current = target; parents.TryGetValue(current, out var parent); current = parent) + owners.Add(parent); + + owners.Reverse(); + return owners; + } + + static IEnumerable ChildrenOf(object owner) + { + foreach (var property in PropertiesOf(owner.GetType())) + { + object? value; + try + { + value = property.GetValue(owner); + } + catch (TargetInvocationException) + { + continue; + } + + if (value is IUndoRedoable child) + { + yield return child; + continue; + } + + if (value is not IEnumerable items || value is string) + continue; + + foreach (var item in items) + { + if (item is IUndoRedoable member) + yield return member; + } + } + } + + static PropertyInfo[] PropertiesOf(Type type) + => Properties.GetOrAdd(type, key => key.GetProperties(BindingFlags.Instance | BindingFlags.Public) + .Where(property => property.CanRead + && property.GetIndexParameters().Length == 0 + && !property.PropertyType.IsValueType + && property.PropertyType != typeof(string) + && property.GetCustomAttribute() is null + && (property.CanWrite || typeof(INotifyCollectionChanged).IsAssignableFrom(property.PropertyType))) + .ToArray()); +}