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

82 行
2.9 KiB
C#

using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Resources;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Plugin;
namespace UndoTree;
internal static class UndoTreeNames
{
const string TypePrefix = "Type_";
const string MemberPrefix = "Member_";
const string HostNamespace = "YukkuriMovieMaker";
static readonly ConcurrentDictionary<Type, IPlugin?> Plugins = new();
public static string OfType(Type type, CultureInfo? culture = null) => (IsHost(type) ? Find(TypePrefix + type.Name, culture) : null) ?? type.Name;
public static string OfMember(Type? owner, string member, CultureInfo? culture = null) => (owner is not null && IsHost(owner) ? Find(MemberPrefix + member, culture) : null) ?? member;
public static string OfPlugin(Type type)
=> Plugins.GetOrAdd(type, CreatePlugin)?.Name is { Length: > 0 } name ? name : OfType(type);
public static string OfEnum(Enum value)
{
if (value is AnimationType animation && AnimationName(animation) is { } name)
return name;
var type = value.GetType();
return string.Join(", ", value.ToString().Split(", ").Select(field => DisplayName(type, field)));
}
static bool IsHost(Type type) => type.Namespace is { } name && (name == HostNamespace || name.StartsWith(HostNamespace + ".", StringComparison.Ordinal));
static string? Find(string key, CultureInfo? culture)
=> Texts.ResourceManager.GetString(key, culture ?? Texts.Culture) is { Length: > 0 } text ? text : null;
static IPlugin? CreatePlugin(Type type)
{
if (!typeof(IPlugin).IsAssignableFrom(type) || type.IsAbstract || type.GetConstructor(Type.EmptyTypes) is null)
return null;
try
{
return Activator.CreateInstance(type) as IPlugin;
}
catch (Exception exception) when (exception is TargetInvocationException or MemberAccessException or InvalidOperationException)
{
return null;
}
}
static string? AnimationName(AnimationType animation)
{
try
{
return AnimationTypeToToolTipConverter.ConvertText(animation, false);
}
catch (Exception exception) when (exception is NotImplementedException or ArgumentException or InvalidOperationException)
{
return null;
}
}
static string DisplayName(Type type, string field)
{
try
{
if (type.GetField(field)?.GetCustomAttribute<DisplayAttribute>()?.GetName() is { Length: > 0 } name)
return name;
}
catch (Exception exception) when (exception is InvalidOperationException or MissingManifestResourceException or AmbiguousMatchException)
{
}
return field;
}
}