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

79 行
2.6 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_";
static readonly ConcurrentDictionary<Type, IPlugin?> Plugins = new();
public static string OfType(Type type, CultureInfo? culture = null) => Find(TypePrefix + type.Name, culture) ?? type.Name;
public static string OfMember(string member, CultureInfo? culture = null) => Find(MemberPrefix + member, culture) ?? 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 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;
}
}