対象の持ち主を木からたどる
このコミットが含まれているのは:
1ファイル変更
+94
@@ -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<Type, PropertyInfo[]> Properties = new();
|
||||
|
||||
readonly Dictionary<object, object> parents = new(ReferenceEqualityComparer.Instance);
|
||||
|
||||
public UndoTreeOwners(IEnumerable<object> roots)
|
||||
{
|
||||
var watch = Stopwatch.StartNew();
|
||||
var seen = new HashSet<object>(ReferenceEqualityComparer.Instance);
|
||||
var pending = new Queue<object>();
|
||||
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<object> OwnersOf(object target)
|
||||
{
|
||||
var owners = new List<object>();
|
||||
for (var current = target; parents.TryGetValue(current, out var parent); current = parent)
|
||||
owners.Add(parent);
|
||||
|
||||
owners.Reverse();
|
||||
return owners;
|
||||
}
|
||||
|
||||
static IEnumerable<object> 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<IgnoreUndoRedoAttribute>() is null
|
||||
&& (property.CanWrite || typeof(INotifyCollectionChanged).IsAssignableFrom(property.PropertyType)))
|
||||
.ToArray());
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする