ファイル

186 行
6.0 KiB
C#

using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Specialized;
using System.Reflection;
using YukkuriMovieMaker.UndoRedo;
namespace UndoTree;
internal readonly record struct UndoTreeOwnerLink(object Owner, PropertyInfo Property, bool IsElement);
internal class UndoTreeOwners
{
const int MaxDepth = 32;
static readonly ConcurrentDictionary<Type, PropertyInfo[]> Properties = new();
readonly Dictionary<object, UndoTreeOwnerLink> parents = new(ReferenceEqualityComparer.Instance);
readonly Dictionary<object, List<object>> children = new(ReferenceEqualityComparer.Instance);
readonly HashSet<object> shared = new(ReferenceEqualityComparer.Instance);
readonly HashSet<object> roots = new(ReferenceEqualityComparer.Instance);
public UndoTreeOwners(IEnumerable<object> roots)
{
var pending = new Queue<(object Owner, int Depth)>();
foreach (var root in roots)
{
if (this.roots.Add(root))
pending.Enqueue((root, 0));
}
Expand(pending);
}
internal IEnumerable<KeyValuePair<object, UndoTreeOwnerLink>> Links => parents;
public UndoTreeOwnerLink? LinkOf(object target) => parents.TryGetValue(target, out var link) ? link : null;
public IReadOnlyList<object> OwnersOf(object target)
{
var owners = new List<object>();
for (var current = target; parents.TryGetValue(current, out var link); current = link.Owner)
owners.Add(link.Owner);
owners.Reverse();
return owners;
}
public bool Detach(object value, object owner, PropertyInfo property)
{
if (!parents.TryGetValue(value, out var link))
return true;
if (!ReferenceEquals(link.Owner, owner) || link.Property.Name != property.Name)
return false;
var doomed = new List<object>();
var pending = new Stack<object>([value]);
while (pending.Count > 0)
{
var current = pending.Pop();
if (shared.Contains(current))
return false;
doomed.Add(current);
foreach (var child in children.TryGetValue(current, out var list) ? list : [])
pending.Push(child);
}
children[owner].RemoveAll(child => ReferenceEquals(child, value));
foreach (var node in doomed)
{
parents.Remove(node);
children.Remove(node);
}
return true;
}
public bool Attach(object owner, PropertyInfo property, bool isElement, object value)
{
if (!roots.Contains(owner) && !parents.ContainsKey(owner))
return false;
var pending = new Queue<(object Owner, int Depth)>();
Link(value, new UndoTreeOwnerLink(owner, property, isElement), OwnersOf(owner).Count + 1, pending);
Expand(pending);
return true;
}
void Expand(Queue<(object Owner, int Depth)> pending)
{
while (pending.Count > 0)
{
var (owner, depth) = pending.Dequeue();
if (depth < MaxDepth)
Visit(owner, depth + 1, pending);
}
}
void Visit(object owner, int childDepth, Queue<(object Owner, int Depth)> pending)
{
foreach (var property in PropertiesOf(owner.GetType()))
{
object? value;
try
{
value = property.GetValue(owner);
}
catch (TargetInvocationException)
{
continue;
}
if (value is IUndoRedoable child)
{
Link(child, new UndoTreeOwnerLink(owner, property, false), childDepth, pending);
continue;
}
if (value is not IEnumerable items || value is string)
continue;
if (value is INotifyCollectionChanged)
Link(value, new UndoTreeOwnerLink(owner, property, false), childDepth, null);
foreach (var item in items)
{
if (item is IUndoRedoable member)
Link(member, new UndoTreeOwnerLink(owner, property, true), childDepth, pending);
}
}
}
void Link(object child, UndoTreeOwnerLink link, int childDepth, Queue<(object Owner, int Depth)>? pending)
{
if (roots.Contains(child))
return;
if (!parents.TryAdd(child, link))
{
shared.Add(child);
return;
}
if (!children.TryGetValue(link.Owner, out var siblings))
children[link.Owner] = siblings = [];
siblings.Add(child);
pending?.Enqueue((child, childDepth));
}
static PropertyInfo[] PropertiesOf(Type type)
=> Properties.GetOrAdd(type, key => key.IsValueType
? []
: key.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(IsLink)
.ToArray());
static bool IsLink(PropertyInfo property)
{
var type = property.PropertyType;
return property.CanRead
&& property.GetIndexParameters().Length == 0
&& !type.IsValueType
&& type != typeof(string)
&& property.GetCustomAttribute<IgnoreUndoRedoAttribute>() is null
&& (property.CanWrite || typeof(INotifyCollectionChanged).IsAssignableFrom(type) || typeof(IUndoRedoable).IsAssignableFrom(type))
&& CanHoldChildren(type);
}
static bool CanHoldChildren(Type type)
{
if (typeof(IUndoRedoable).IsAssignableFrom(type))
return true;
if (!typeof(IEnumerable).IsAssignableFrom(type))
return !type.IsSealed;
var elements = type.GetInterfaces().Append(type)
.Where(candidate => candidate.IsGenericType && candidate.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.Select(candidate => candidate.GetGenericArguments()[0])
.ToArray();
return elements.Length == 0 || elements.Any(element => typeof(IUndoRedoable).IsAssignableFrom(element) || !(element.IsValueType || element.IsSealed));
}
}