quantum-space-buddies/QSB/Patches/QSBPatchManager.cs

86 lines
2.3 KiB
C#
Raw Normal View History

2021-12-01 09:10:38 +00:00
using HarmonyLib;
using OWML.Common;
2020-11-03 21:11:10 +00:00
using QSB.Utility;
2021-12-24 01:07:29 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
2020-11-03 21:11:10 +00:00
namespace QSB.Patches
2020-11-03 21:11:10 +00:00
{
public static class QSBPatchManager
{
public static event Action<QSBPatchTypes> OnPatchType;
public static event Action<QSBPatchTypes> OnUnpatchType;
2020-11-04 20:01:28 +00:00
private static readonly List<QSBPatch> _patchList = new();
private static readonly List<QSBPatchTypes> _patchedTypes = new();
2020-12-14 20:41:56 +00:00
public static Dictionary<QSBPatchTypes, Harmony> TypeToInstance = new();
public static void Init()
2020-12-02 21:29:53 +00:00
{
foreach (var type in typeof(QSBPatch).GetDerivedTypes())
2020-12-02 21:29:53 +00:00
{
_patchList.Add((QSBPatch)Activator.CreateInstance(type));
}
2020-11-03 21:11:10 +00:00
TypeToInstance = new Dictionary<QSBPatchTypes, Harmony>
{
{
QSBPatchTypes.OnClientConnect, new Harmony("QSB.Client")
},
{
QSBPatchTypes.OnServerClientConnect, new Harmony("QSB.Server")
},
{
QSBPatchTypes.OnNonServerClientConnect, new Harmony("QSB.NonServer")
},
{
QSBPatchTypes.RespawnTime, new Harmony("QSB.Death")
}
};
DebugLog.DebugWrite("Patch Manager ready.", MessageType.Success);
2020-12-02 21:29:53 +00:00
}
2020-11-03 21:11:10 +00:00
public static void DoPatchType(QSBPatchTypes type)
2020-12-02 21:29:53 +00:00
{
if (_patchedTypes.Contains(type))
{
DebugLog.ToConsole($"Warning - Tried to patch type {type}, when it has already been patched!", MessageType.Warning);
return;
}
OnPatchType?.SafeInvoke(type);
//DebugLog.DebugWrite($"Patch block {Enum.GetName(typeof(QSBPatchTypes), type)}", MessageType.Info);
foreach (var patch in _patchList.Where(x => x.Type == type))
2020-12-02 21:29:53 +00:00
{
//DebugLog.DebugWrite($" - Patching in {patch.GetType().Name}", MessageType.Info);
try
{
patch.DoPatches(TypeToInstance[type]);
}
catch (Exception ex)
{
DebugLog.ToConsole($"Error while patching {patch.GetType().Name} :\r\n{ex}", MessageType.Error);
}
2020-12-02 21:29:53 +00:00
}
2021-02-09 17:18:01 +00:00
_patchedTypes.Add(type);
}
public static void DoUnpatchType(QSBPatchTypes type)
{
if (!_patchedTypes.Contains(type))
{
DebugLog.ToConsole($"Warning - Tried to unpatch type {type}, when it is either unpatched or was never patched.", MessageType.Warning);
return;
}
OnUnpatchType?.SafeInvoke(type);
//DebugLog.DebugWrite($"Unpatch block {Enum.GetName(typeof(QSBPatchTypes), type)}", MessageType.Info);
TypeToInstance[type].UnpatchSelf();
_patchedTypes.Remove(type);
}
2020-12-02 21:29:53 +00:00
}
}