ファイル

88 行
2.6 KiB
C#

using System.Collections;
using System.Reflection;
using YukkuriMovieMaker.UndoRedo;
namespace UndoTree;
internal static class UndoTreeAddress
{
const BindingFlags PublicInstance = BindingFlags.Instance | BindingFlags.Public;
public static IReadOnlyList<UndoTreeHop>? Of(object target, IReadOnlyList<IUndoRedoable> roots, UndoTreeOwners owners)
{
var hops = new List<UndoTreeHop>();
for (var current = target; ;)
{
var rootIndex = IndexOf(roots, current);
if (rootIndex >= 0)
{
hops.Add(UndoTreeHop.Root(rootIndex));
break;
}
if (owners.LinkOf(current) is not { } link)
return null;
var index = link.IsElement ? IndexOf(UndoTreeMembers.ValueOf(link.Owner, link.Property) as IEnumerable, current) : -1;
if (link.IsElement && index < 0)
return null;
hops.Add(new UndoTreeHop(link.Property.Name, index));
current = link.Owner;
}
hops.Reverse();
return hops;
}
public static string Text(IReadOnlyList<UndoTreeHop> hops)
=> string.Concat(hops.Select(hop => hop.IsRoot ? $"#{hop.Index}" : hop.Index >= 0 ? $"/{hop.Property}[{hop.Index}]" : $"/{hop.Property}"));
public static object? Resolve(IReadOnlyList<IUndoRedoable> roots, IReadOnlyList<UndoTreeHop> hops)
{
if (hops is not [{ IsRoot: true } first, ..] || first.Index < 0 || first.Index >= roots.Count)
return null;
object? current = roots[first.Index];
foreach (var hop in hops.Skip(1))
{
current = Step(current, hop);
if (current is null)
return null;
}
return current;
}
static object? Step(object owner, UndoTreeHop hop)
{
try
{
var property = owner.GetType().GetProperty(hop.Property, PublicInstance);
if (property is null || property.GetIndexParameters().Length != 0)
return null;
var value = property.GetValue(owner);
return hop.Index < 0 ? value : (value as IEnumerable)?.Cast<object?>().Skip(hop.Index).FirstOrDefault();
}
catch (Exception exception) when (exception is TargetInvocationException or AmbiguousMatchException)
{
return null;
}
}
static int IndexOf(IEnumerable? items, object target)
{
var index = 0;
foreach (var item in items ?? Array.Empty<object>())
{
if (ReferenceEquals(item, target))
return index;
index++;
}
return -1;
}
}