1
0
mirror of https://github.com/soarqin/DSP_Mods.git synced 2025-12-08 21:33:28 +08:00
Files
DSP_Mods/UXAssist/Common/PatchImpl.cs
2024-09-24 00:33:41 +08:00

58 lines
2.1 KiB
C#

using System;
using System.Linq;
using System.Reflection;
using HarmonyLib;
namespace UXAssist.Common;
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class PatchGuidAttribute(string guid) : Attribute
{
public string Guid { get; } = guid;
}
public enum PatchCallbackFlag
{
// OnEnable() is called After patch is applied by default, set this flag to call it before patch is applied
CallOnEnableBeforePatch,
// OnDisable() is called Before patch is removed by default, set this flag to call it after patch is removed
CallOnDisableAfterUnpatch,
}
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public class PatchSetCallbackFlagAttribute(PatchCallbackFlag flag) : Attribute
{
public PatchCallbackFlag Flag { get; } = flag;
}
public class PatchImpl<T> where T : PatchImpl<T>, new()
{
private static T Instance { get; } = new();
private Harmony _patch;
public static void Enable(bool enable)
{
var thisInstance = Instance;
if (enable)
{
var guid = typeof(T).GetCustomAttribute<PatchGuidAttribute>()?.Guid ?? $"PatchImpl.{typeof(T).FullName ?? typeof(T).ToString()}";
var callOnEnableBefore = typeof(T).GetCustomAttributes<PatchSetCallbackFlagAttribute>().Any(n => n.Flag == PatchCallbackFlag.CallOnEnableBeforePatch);
if (callOnEnableBefore) thisInstance.OnEnable();
thisInstance._patch ??= Harmony.CreateAndPatchAll(typeof(T), guid);
if (!callOnEnableBefore) thisInstance.OnEnable();
return;
}
var callOnDisableAfter = typeof(T).GetCustomAttributes<PatchSetCallbackFlagAttribute>().Any(n => n.Flag == PatchCallbackFlag.CallOnDisableAfterUnpatch);
if (!callOnDisableAfter) thisInstance.OnDisable();
thisInstance._patch?.UnpatchSelf();
thisInstance._patch = null;
if (callOnDisableAfter) thisInstance.OnDisable();
}
public static Harmony GetHarmony() => Instance._patch;
protected virtual void OnEnable() { }
protected virtual void OnDisable() { }
}