ファイル
YMM4-UndoTree/UndoTree/UndoTreeReplayer.cs
T

142 行
5.5 KiB
C#

using System.Collections;
using System.Collections.Immutable;
using System.Reflection;
using YukkuriMovieMaker.UndoRedo;
namespace UndoTree;
internal static class UndoTreeReplayer
{
const BindingFlags Instance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
static readonly MethodInfo CreateRange = typeof(ImmutableList).GetMethods().Single(method => method.Name == nameof(ImmutableList.CreateRange) && method.GetParameters().Length == 1);
public static async Task<string?> ApplyAsync(IReadOnlyList<IUndoRedoable> roots, IReadOnlyList<UndoTreeStep> steps, bool inverse)
{
var ordered = inverse ? steps.Reverse().ToArray() : steps.ToArray();
foreach (var pass in new[] { false, true })
{
foreach (var step in ordered.Where(step => step.Kind == nameof(StepKind.Call) == pass))
{
if (await ApplyOneAsync(roots, step, inverse) is { } failure)
return failure;
}
}
return null;
}
public static string Describe(UndoTreeStep step)
=> string.Join(" / ", step.Target.Skip(1).Select(hop => hop.Index >= 0 ? $"{hop.Property}[{hop.Index}]" : hop.Property).Append(step.Member).Where(part => part.Length > 0));
static async Task<string?> ApplyOneAsync(IReadOnlyList<IUndoRedoable> roots, UndoTreeStep step, bool inverse)
{
if (UndoTreeAddress.Resolve(roots, step.Target) is not { } target)
return Describe(step);
try
{
var applied = step.Kind switch
{
nameof(StepKind.Set) => ApplySet(target, step, inverse),
nameof(StepKind.Replace) => ApplyReplace(target, step, inverse),
nameof(StepKind.Collection) => ApplyCollection(target, step, inverse),
nameof(StepKind.Call) => await ApplyCallAsync(target, step),
_ => false,
};
return applied ? null : Describe(step);
}
catch (Exception exception) when (exception is TargetInvocationException or ArgumentException or InvalidCastException or NotSupportedException or InvalidOperationException)
{
return Describe(step);
}
}
static bool ApplySet(object target, UndoTreeStep step, bool inverse)
{
if (UndoTreeMembers.PropertyOf(target, step.Member) is not { CanWrite: true } property)
return false;
var declared = property.PropertyType;
var current = UndoTreeMembers.ValueOf(target, property);
if (!UndoTreeCodec.TryDecode(inverse ? step.After : step.Before, declared, out var expected) || !UndoTreeCodec.TryDecode(inverse ? step.Before : step.After, declared, out var next))
return false;
if (UndoTreeCodec.IsPlain(declared) ? !Equals(current, expected) : (current is null) != (expected is null))
return false;
property.SetValue(target, next);
return true;
}
static bool ApplyReplace(object target, UndoTreeStep step, bool inverse)
{
if (step.List is not { } change || UndoTreeMembers.PropertyOf(target, step.Member) is not { CanWrite: true } property || UndoTreeMembers.ElementOf(property.PropertyType) is not { } element)
return false;
if (UndoTreeMembers.ValueOf(target, property) is not IEnumerable current || !change.TryApply(current.Cast<object?>().ToArray(), inverse, element, out var result))
return false;
var items = Array.CreateInstance(element, result.Count);
for (var index = 0; index < result.Count; index++)
items.SetValue(result[index], index);
property.SetValue(target, CreateRange.MakeGenericMethod(element).Invoke(null, [items]));
return true;
}
static bool ApplyCollection(object target, UndoTreeStep step, bool inverse)
{
if (step.List is not { } change || target is not IList collection || UndoTreeMembers.ElementOf(collection.GetType()) is not { } element)
return false;
if (!change.TryApply(collection.Cast<object?>().ToArray(), inverse, element, out var result))
return false;
Reshape(collection, result);
return true;
}
static async Task<bool> ApplyCallAsync(object target, UndoTreeStep step)
{
if (target.GetType().GetMethod(step.Member, Instance, null, Type.EmptyTypes, null) is not { } method || method.Invoke(target, null) is not Task task)
return false;
await task;
return true;
}
static void Reshape(IList collection, IReadOnlyList<object?> wanted)
{
var keep = new HashSet<object?>(wanted, ReferenceEqualityComparer.Instance);
for (var index = collection.Count - 1; index >= 0; index--)
{
if (!keep.Contains(collection[index]))
collection.RemoveAt(index);
}
for (var index = 0; index < wanted.Count; index++)
{
if (index < collection.Count && ReferenceEquals(collection[index], wanted[index]))
continue;
var found = IndexOfFrom(collection, wanted[index], index + 1);
if (found >= 0)
collection.RemoveAt(found);
collection.Insert(index, wanted[index]);
}
}
static int IndexOfFrom(IList collection, object? item, int start)
{
for (var index = start; index < collection.Count; index++)
{
if (ReferenceEquals(collection[index], item))
return index;
}
return -1;
}
}