ファイル

175 行
7.3 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)
{
foreach (var step in Ordered(steps, inverse))
{
if (await ApplyStepAsync(roots, step, inverse, ConflictPolicy.Skip) != StepOutcome.Applied)
return Describe(step);
}
return null;
}
public static async Task<UndoTreeApplyResult> ReplayAsync(IReadOnlyList<IUndoRedoable> roots, IReadOnlyList<UndoTreeStep> steps, bool inverse, ConflictPolicy policy)
{
var applied = 0;
var conflicts = new List<UndoTreeConflict>();
foreach (var step in Ordered(steps, inverse))
{
var outcome = await ApplyStepAsync(roots, step, inverse, policy);
if (outcome is StepOutcome.Applied or StepOutcome.Forced or StepOutcome.Offset)
applied++;
if (outcome != StepOutcome.Applied)
conflicts.Add(new UndoTreeConflict(outcome switch { StepOutcome.Missing => ConflictKind.DeadTarget, StepOutcome.Offset => ConflictKind.OffsetApplied, _ => ConflictKind.SameProperty }, DescribeTarget(step), step.Member, outcome is StepOutcome.Forced or StepOutcome.Offset));
}
return new UndoTreeApplyResult(applied, conflicts);
}
public static string Describe(UndoTreeStep step) => UndoTreeText.Join(DescribeTarget(step), step.Member);
static string DescribeTarget(UndoTreeStep step)
=> string.Join(" / ", step.Target.Skip(1).Select(hop => hop.Index >= 0 ? $"{hop.Property}[{hop.Index}]" : hop.Property));
static IEnumerable<UndoTreeStep> Ordered(IReadOnlyList<UndoTreeStep> steps, bool inverse)
{
var ordered = inverse ? steps.Reverse().ToArray() : steps.ToArray();
return ordered.Where(step => step.Kind != nameof(StepKind.Call)).Concat(ordered.Where(step => step.Kind == nameof(StepKind.Call)));
}
static async Task<StepOutcome> ApplyStepAsync(IReadOnlyList<IUndoRedoable> roots, UndoTreeStep step, bool inverse, ConflictPolicy policy)
{
if (UndoTreeAddress.Resolve(roots, step.Target) is not { } target)
return StepOutcome.Missing;
try
{
return step.Kind switch
{
nameof(StepKind.Set) => ApplySet(target, step, inverse, policy),
nameof(StepKind.Replace) => ApplyReplace(target, step, inverse) ? StepOutcome.Applied : StepOutcome.Mismatch,
nameof(StepKind.Collection) => ApplyCollection(target, step, inverse) ? StepOutcome.Applied : StepOutcome.Mismatch,
nameof(StepKind.Call) => await ApplyCallAsync(target, step) ? StepOutcome.Applied : StepOutcome.Missing,
_ => StepOutcome.Mismatch,
};
}
catch (Exception exception) when (exception is TargetInvocationException or ArgumentException or InvalidCastException or NotSupportedException or InvalidOperationException)
{
return StepOutcome.Mismatch;
}
}
static StepOutcome ApplySet(object target, UndoTreeStep step, bool inverse, ConflictPolicy policy)
{
if (UndoTreeMembers.PropertyOf(target, step.Member) is not { CanWrite: true } property)
return StepOutcome.Missing;
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 StepOutcome.Mismatch;
var matches = UndoTreeCodec.IsPlain(declared) ? Equals(current, expected) : (current is null) == (expected is null);
if (!matches && policy == ConflictPolicy.Offset)
{
if (Equals(current, next))
return StepOutcome.Applied;
if (UndoTreeOffset.TryAdd(declared, current, expected, next, out var sum))
{
property.SetValue(target, sum);
return StepOutcome.Offset;
}
}
if (!matches && policy != ConflictPolicy.Apply)
return StepOutcome.Mismatch;
property.SetValue(target, next);
return matches ? StepOutcome.Applied : StepOutcome.Forced;
}
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;
}
}