Use EnumerateInvocationList instead of GetInvocationList (#2303)

This commit is contained in:
srkizer 2025-06-24 05:09:48 +09:00 committed by GitHub
parent 13306e24ba
commit 03e728e129
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 402 additions and 294 deletions

View file

@ -650,6 +650,16 @@ internal sealed class DalamudConfiguration : IInternalDisposableService
}
});
this.DalamudConfigurationSaved?.Invoke(this);
foreach (var action in Delegate.EnumerateInvocationList(this.DalamudConfigurationSaved))
{
try
{
action(this);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
}
}

View file

@ -184,8 +184,18 @@ internal partial class ConsoleManager : IServiceType
/// <returns>Whether the command was successfully processed.</returns>
public bool ProcessCommand(string command)
{
if (this.Invoke?.Invoke(command) == true)
foreach (var action in Delegate.EnumerateInvocationList(this.Invoke))
{
try
{
if (action(command))
return true;
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
var matches = GetCommandParsingRegex().Matches(command);
if (matches.Count == 0)

View file

@ -211,17 +211,18 @@ internal sealed class ClientState : IInternalDisposableService, IClientState
this.setupTerritoryTypeHook.Original(eventFramework, territoryType);
}
private unsafe void UIModuleHandlePacketDetour(UIModule* thisPtr, UIModulePacketType type, uint uintParam, void* packet)
private unsafe void UIModuleHandlePacketDetour(
UIModule* thisPtr, UIModulePacketType type, uint uintParam, void* packet)
{
this.uiModuleHandlePacketHook.Original(thisPtr, type, uintParam, packet);
switch (type)
{
case UIModulePacketType.ClassJobChange when this.ClassJobChanged is { } callback:
case UIModulePacketType.ClassJobChange:
{
var classJobId = uintParam;
foreach (var action in callback.GetInvocationList().Cast<IClientState.ClassJobChangeDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.ClassJobChanged))
{
try
{
@ -236,12 +237,12 @@ internal sealed class ClientState : IInternalDisposableService, IClientState
break;
}
case UIModulePacketType.LevelChange when this.LevelChanged is { } callback:
case UIModulePacketType.LevelChange:
{
var classJobId = *(uint*)packet;
var level = *(ushort*)((nint)packet + 4);
foreach (var action in callback.GetInvocationList().Cast<IClientState.LevelChangeDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.LevelChanged))
{
try
{
@ -291,9 +292,7 @@ internal sealed class ClientState : IInternalDisposableService, IClientState
Log.Debug("Logout: Type {type}, Code {code}", type, code);
if (this.Logout is { } callback)
{
foreach (var action in callback.GetInvocationList().Cast<IClientState.LogoutDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.Logout))
{
try
{
@ -304,7 +303,6 @@ internal sealed class ClientState : IInternalDisposableService, IClientState
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
}
gameGui?.ResetUiHideState();
this.lastConditionNone = true; // unblock login flag

View file

@ -157,13 +157,16 @@ internal sealed class Condition : IInternalDisposableService, ICondition
{
this.cache[i] = value;
foreach (var d in Delegate.EnumerateInvocationList(this.ConditionChange))
{
try
{
this.ConditionChange?.Invoke((ConditionFlag)i, value);
d((ConditionFlag)i, value);
}
catch (Exception ex)
{
Log.Error(ex, $"While invoking {nameof(this.ConditionChange)}, an exception was thrown.");
Log.Error(ex, $"While invoking {d.Method.Name}, an exception was thrown.");
}
}
}
}

View file

@ -132,7 +132,7 @@ internal sealed unsafe class CommandManager : IInternalDisposableService, IComma
return false;
}
this.CommandAdded?.Invoke(this, new CommandEventArgs
this.CommandAdded?.InvokeSafely(this, new CommandEventArgs
{
Command = command,
CommandInfo = info,
@ -160,7 +160,7 @@ internal sealed unsafe class CommandManager : IInternalDisposableService, IComma
return false;
}
this.CommandAdded?.Invoke(this, new CommandEventArgs
this.CommandAdded?.InvokeSafely(this, new CommandEventArgs
{
Command = command,
CommandInfo = info,
@ -180,7 +180,7 @@ internal sealed unsafe class CommandManager : IInternalDisposableService, IComma
var removed = this.commandMap.Remove(command, out var info);
if (removed)
{
this.CommandRemoved?.Invoke(this, new CommandEventArgs
this.CommandRemoved?.InvokeSafely(this, new CommandEventArgs
{
Command = command,
CommandInfo = info,

View file

@ -350,17 +350,13 @@ internal sealed class Framework : IInternalDisposableService, IFramework
/// <param name="frameworkInstance">The Framework Instance to pass to delegate.</param>
internal void ProfileAndInvoke(IFramework.OnUpdateDelegate? eventDelegate, IFramework frameworkInstance)
{
if (eventDelegate is null) return;
var invokeList = eventDelegate.GetInvocationList();
// Individually invoke OnUpdate handlers and time them.
foreach (var d in invokeList)
foreach (var d in Delegate.EnumerateInvocationList(eventDelegate))
{
var stopwatch = Stopwatch.StartNew();
try
{
d.Method.Invoke(d.Target, new object[] { frameworkInstance });
d(frameworkInstance);
}
catch (Exception ex)
{
@ -370,7 +366,6 @@ internal sealed class Framework : IInternalDisposableService, IFramework
stopwatch.Stop();
var key = $"{d.Target}::{d.Method.Name}";
if (this.NonUpdatedSubDelegates.Contains(key))
this.NonUpdatedSubDelegates.Remove(key);
AddToStats(key, stopwatch.Elapsed.TotalMilliseconds);

View file

@ -346,9 +346,7 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui
// Call events
var isHandled = false;
if (this.CheckMessageHandled is { } handledCallback)
{
foreach (var action in handledCallback.GetInvocationList().Cast<IChatGui.OnCheckMessageHandledDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.CheckMessageHandled))
{
try
{
@ -359,11 +357,10 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui
Log.Error(e, "Could not invoke registered OnCheckMessageHandledDelegate for {Name}", action.Method);
}
}
}
if (!isHandled && this.ChatMessage is { } callback)
if (!isHandled)
{
foreach (var action in callback.GetInvocationList().Cast<IChatGui.OnMessageDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.ChatMessage))
{
try
{
@ -394,12 +391,14 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui
// Print the original chat if it's handled.
if (isHandled)
{
this.ChatMessageHandled?.Invoke(chatType, timestamp, parsedSender, parsedMessage);
foreach (var d in Delegate.EnumerateInvocationList(this.ChatMessageHandled))
d(chatType, timestamp, parsedSender, parsedMessage);
}
else
{
messageId = this.printMessageHook.Original(manager, chatType, sender, message, timestamp, silent);
this.ChatMessageUnhandled?.Invoke(chatType, timestamp, parsedSender, parsedMessage);
foreach (var d in Delegate.EnumerateInvocationList(this.ChatMessageUnhandled))
d(chatType, timestamp, parsedSender, parsedMessage);
}
}
catch (Exception ex)

View file

@ -116,7 +116,11 @@ internal sealed class FlyTextGui : IInternalDisposableService, IFlyTextGui
$"text1({(nint)text1:X}, \"{tmpText1}\") text2({(nint)text2:X}, \"{tmpText2}\") " +
$"color({color:X}) icon({icon}) yOffset({yOffset})");
Log.Verbose("[FlyText] Calling flytext events!");
this.FlyTextCreated?.Invoke(
foreach (var d in Delegate.EnumerateInvocationList(this.FlyTextCreated))
{
try
{
d(
ref tmpKind,
ref tmpVal1,
ref tmpVal2,
@ -127,6 +131,12 @@ internal sealed class FlyTextGui : IInternalDisposableService, IFlyTextGui
ref tmpDamageTypeIcon,
ref tmpYOffset,
ref handled);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", d.Method);
}
}
// If handled, ignore the original call
if (handled)

View file

@ -6,6 +6,7 @@ using Dalamud.Hooking;
using Dalamud.IoC;
using Dalamud.IoC.Internal;
using Dalamud.Plugin.Services;
using Dalamud.Utility;
using FFXIVClientStructs.FFXIV.Client.UI;
using FFXIVClientStructs.FFXIV.Component.GUI;
@ -169,8 +170,8 @@ internal sealed class NamePlateGui : IInternalDisposableService, INamePlateGui
handler.ResetState();
}
this.OnDataUpdate?.Invoke(this.context, activeHandlers);
this.OnNamePlateUpdate?.Invoke(this.context, activeHandlers);
this.OnDataUpdate?.InvokeSafely(this.context, activeHandlers);
this.OnNamePlateUpdate?.InvokeSafely(this.context, activeHandlers);
if (this.context.HasParts)
this.ApplyBuilders(activeHandlers);
@ -185,8 +186,8 @@ internal sealed class NamePlateGui : IInternalDisposableService, INamePlateGui
Log.Error(e, "Caught exception when calling original AddonNamePlate OnRequestedUpdate.");
}
this.OnPostNamePlateUpdate?.Invoke(this.context, activeHandlers);
this.OnPostDataUpdate?.Invoke(this.context, activeHandlers);
this.OnPostNamePlateUpdate?.InvokeSafely(this.context, activeHandlers);
this.OnPostDataUpdate?.InvokeSafely(this.context, activeHandlers);
}
else
{
@ -200,8 +201,8 @@ internal sealed class NamePlateGui : IInternalDisposableService, INamePlateGui
if (this.OnDataUpdate is not null)
{
this.OnDataUpdate?.Invoke(this.context, activeHandlers);
this.OnNamePlateUpdate?.Invoke(this.context, updatedHandlers);
this.OnDataUpdate?.InvokeSafely(this.context, activeHandlers);
this.OnNamePlateUpdate?.InvokeSafely(this.context, updatedHandlers);
if (this.context.HasParts)
this.ApplyBuilders(activeHandlers);
@ -216,12 +217,12 @@ internal sealed class NamePlateGui : IInternalDisposableService, INamePlateGui
Log.Error(e, "Caught exception when calling original AddonNamePlate OnRequestedUpdate.");
}
this.OnPostNamePlateUpdate?.Invoke(this.context, updatedHandlers);
this.OnPostDataUpdate?.Invoke(this.context, activeHandlers);
this.OnPostNamePlateUpdate?.InvokeSafely(this.context, updatedHandlers);
this.OnPostDataUpdate?.InvokeSafely(this.context, activeHandlers);
}
else if (updatedHandlers.Count != 0)
{
this.OnNamePlateUpdate?.Invoke(this.context, updatedHandlers);
this.OnNamePlateUpdate?.InvokeSafely(this.context, updatedHandlers);
if (this.context.HasParts)
this.ApplyBuilders(updatedHandlers);
@ -236,8 +237,8 @@ internal sealed class NamePlateGui : IInternalDisposableService, INamePlateGui
Log.Error(e, "Caught exception when calling original AddonNamePlate OnRequestedUpdate.");
}
this.OnPostNamePlateUpdate?.Invoke(this.context, updatedHandlers);
this.OnPostDataUpdate?.Invoke(this.context, activeHandlers);
this.OnPostNamePlateUpdate?.InvokeSafely(this.context, updatedHandlers);
this.OnPostDataUpdate?.InvokeSafely(this.context, activeHandlers);
}
}
}

View file

@ -89,7 +89,17 @@ internal sealed unsafe class PartyFinderGui : IInternalDisposableService, IParty
var listing = new PartyFinderListing(packet.Listings[i]);
var args = new PartyFinderListingEventArgs(packet.BatchNumber);
this.ReceiveListing?.Invoke(listing, args);
foreach (var d in Delegate.EnumerateInvocationList(this.ReceiveListing))
{
try
{
d(listing, args);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", d.Method);
}
}
if (args.Visible)
{

View file

@ -10,6 +10,8 @@ using Dalamud.Plugin.Services;
using FFXIVClientStructs.FFXIV.Client.UI;
using Serilog;
namespace Dalamud.Game.Gui.Toast;
/// <summary>
@ -150,7 +152,17 @@ internal sealed partial class ToastGui
Speed = (ToastSpeed)isFast,
};
this.Toast?.Invoke(ref str, ref options, ref isHandled);
foreach (var d in Delegate.EnumerateInvocationList(this.Toast))
{
try
{
d.Invoke(ref str, ref options, ref isHandled);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", d.Method);
}
}
// do nothing if handled
if (isHandled)
@ -223,7 +235,17 @@ internal sealed partial class ToastGui
PlaySound = playSound == 1,
};
this.QuestToast?.Invoke(ref str, ref options, ref isHandled);
foreach (var d in Delegate.EnumerateInvocationList(this.QuestToast))
{
try
{
d.Invoke(ref str, ref options, ref isHandled);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", d.Method);
}
}
// do nothing if handled
if (isHandled)
@ -286,7 +308,17 @@ internal sealed partial class ToastGui
var isHandled = false;
var str = SeString.Parse(text);
this.ErrorToast?.Invoke(ref str, ref isHandled);
foreach (var d in Delegate.EnumerateInvocationList(this.ErrorToast))
{
try
{
d.Invoke(ref str, ref isHandled);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", d.Method);
}
}
// do nothing if handled
if (isHandled)

View file

@ -150,9 +150,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnHistoryReceived(IMarketBoardHistory history)
{
if (this.HistoryReceived == null) return;
foreach (var action in this.HistoryReceived.GetInvocationList().Cast<HistoryReceivedDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.HistoryReceived))
{
try
{
@ -167,9 +165,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnItemPurchased(IMarketBoardPurchase purchase)
{
if (this.ItemPurchased == null) return;
foreach (var action in this.ItemPurchased.GetInvocationList().Cast<ItemPurchasedDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.ItemPurchased))
{
try
{
@ -184,10 +180,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnOfferingsReceived(IMarketBoardCurrentOfferings currentOfferings)
{
if (this.OfferingsReceived == null) return;
foreach (var action in this.OfferingsReceived.GetInvocationList()
.Cast<OfferingsReceivedDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.OfferingsReceived))
{
try
{
@ -202,9 +195,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnPurchaseRequested(IMarketBoardPurchaseHandler purchaseHandler)
{
if (this.PurchaseRequested == null) return;
foreach (var action in this.PurchaseRequested.GetInvocationList().Cast<PurchaseRequestedDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.PurchaseRequested))
{
try
{
@ -219,9 +210,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnTaxRatesReceived(IMarketTaxRates taxRates)
{
if (this.TaxRatesReceived == null) return;
foreach (var action in this.TaxRatesReceived.GetInvocationList().Cast<TaxRatesReceivedDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.TaxRatesReceived))
{
try
{

View file

@ -71,12 +71,16 @@ internal sealed unsafe class GameNetwork : IInternalDisposableService, IGameNetw
// Go back 0x10 to get back to the start of the packet header
dataPtr -= 0x10;
foreach (var d in Delegate.EnumerateInvocationList(this.NetworkMessage))
{
try
{
// Call events
this.NetworkMessage?.Invoke(dataPtr + 0x20, (ushort)Marshal.ReadInt16(dataPtr, 0x12), 0, targetId, NetworkMessageDirection.ZoneDown);
this.processZonePacketDownHook.Original(dispatcher, targetId, dataPtr + 0x10);
d.Invoke(
dataPtr + 0x20,
(ushort)Marshal.ReadInt16(dataPtr, 0x12),
0,
targetId,
NetworkMessageDirection.ZoneDown);
}
catch (Exception ex)
{
@ -93,10 +97,10 @@ internal sealed unsafe class GameNetwork : IInternalDisposableService, IGameNetw
}
Log.Error(ex, "Exception on ProcessZonePacketDown hook. Header: " + header);
this.processZonePacketDownHook.Original(dispatcher, targetId, dataPtr + 0x10);
}
}
this.processZonePacketDownHook.Original(dispatcher, targetId, dataPtr + 0x10);
this.hitchDetectorDown.Stop();
}

View file

@ -81,14 +81,17 @@ internal sealed class WndProcHookManager : IInternalDisposableService
/// </summary>
/// <param name="args">The arguments.</param>
internal void InvokePreWndProc(WndProcEventArgs args)
{
foreach (var d in Delegate.EnumerateInvocationList(this.PreWndProc))
{
try
{
this.PreWndProc?.Invoke(args);
d(args);
}
catch (Exception e)
{
Log.Error(e, $"{nameof(this.PreWndProc)} error");
Log.Error(e, $"{nameof(this.PreWndProc)} error calling {d.Method.Name}");
}
}
}
@ -97,14 +100,17 @@ internal sealed class WndProcHookManager : IInternalDisposableService
/// </summary>
/// <param name="args">The arguments.</param>
internal void InvokePostWndProc(WndProcEventArgs args)
{
foreach (var d in Delegate.EnumerateInvocationList(this.PostWndProc))
{
try
{
this.PostWndProc?.Invoke(args);
d(args);
}
catch (Exception e)
{
Log.Error(e, $"{nameof(this.PostWndProc)} error");
Log.Error(e, $"{nameof(this.PostWndProc)} error calling {d.Method.Name}");
}
}
}

View file

@ -278,7 +278,7 @@ internal sealed partial class ActiveNotification : IActiveNotification
if (@delegate is null)
return null;
foreach (var il in @delegate.GetInvocationList())
foreach (var il in Delegate.EnumerateInvocationList(@delegate))
{
if (il.Target is { } target && !IsOwnedByDalamud(target.GetType()))
@delegate = (T)Delegate.Remove(@delegate, il);

View file

@ -3,6 +3,7 @@
using Dalamud.Configuration.Internal;
using Dalamud.Interface.Utility;
using Dalamud.Interface.Utility.Raii;
using Dalamud.Utility;
using ImGuiNET;
@ -69,14 +70,14 @@ internal class NotificationPositionChooser
if (ImGui.IsMouseClicked(ImGuiMouseButton.Right))
{
this.SelectionMade?.Invoke();
this.SelectionMade.InvokeSafely();
}
else if (ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
this.configuration.NotificationAnchorPosition = this.currentAnchorPosition;
this.configuration.QueueSave();
this.SelectionMade?.Invoke();
this.SelectionMade.InvokeSafely();
}
// In the middle of the screen, draw some instructions

View file

@ -832,7 +832,7 @@ internal partial class InterfaceManager : IInternalDisposableService
this.defaultFontResourceLock = fontLocked;
// Broadcast to auto-rebuilding instances.
this.AfterBuildFonts?.Invoke();
this.AfterBuildFonts.InvokeSafely();
});
};
}

View file

@ -66,7 +66,7 @@ internal sealed class DelegateFontHandle : FontHandle
var key = new DelegateFontHandle(this, buildStepDelegate);
lock (this.syncRoot)
this.handles.Add(key);
this.RebuildRecommend?.Invoke();
this.RebuildRecommend.InvokeSafely();
return key;
}

View file

@ -386,7 +386,7 @@ internal sealed partial class FontAtlasFactory
if (this.disposed)
return;
this.BeforeDispose?.InvokeSafely(this);
this.BeforeDispose.InvokeSafely(this);
try
{
@ -400,25 +400,11 @@ internal sealed partial class FontAtlasFactory
this.disposables.Dispose();
}
try
{
this.AfterDispose?.Invoke(this, null);
}
catch
{
// ignore
}
this.AfterDispose.InvokeSafely(this, null);
}
catch (Exception e)
{
try
{
this.AfterDispose?.Invoke(this, e);
}
catch
{
// ignore
}
this.AfterDispose.InvokeSafely(this, e);
}
GC.SuppressFinalize(this);
@ -828,7 +814,7 @@ internal sealed partial class FontAtlasFactory
this.factory.Framework.RunOnFrameworkThread(
() =>
{
this.RebuildRecommend?.InvokeSafely();
this.RebuildRecommend.InvokeSafely();
switch (this.AutoRebuildMode)
{

View file

@ -78,14 +78,17 @@ internal abstract class FontHandle : IFontHandle
/// </summary>
/// <param name="font">The font, locked during the call of <see cref="ImFontChanged"/>.</param>
public void InvokeImFontChanged(ILockedImFont font)
{
foreach (var d in Delegate.EnumerateInvocationList(this.ImFontChanged))
{
try
{
this.ImFontChanged?.Invoke(this, font);
d(this, font);
}
catch (Exception e)
{
Log.Error(e, $"{nameof(this.InvokeImFontChanged)}: error");
Log.Error(e, $"{nameof(this.InvokeImFontChanged)}: error calling {d.Method.Name}");
}
}
}

View file

@ -151,7 +151,7 @@ internal class GamePrebakedFontHandle : FontHandle
}
if (suggestRebuild)
this.RebuildRecommend?.Invoke();
this.RebuildRecommend.InvokeSafely();
return handle;
}

View file

@ -117,7 +117,18 @@ public class Localization : IServiceType
public void SetupWithFallbacks()
{
this.DalamudLanguageCultureInfo = CultureInfo.InvariantCulture;
this.LocalizationChanged?.Invoke(FallbackLangCode);
foreach (var d in Delegate.EnumerateInvocationList(this.LocalizationChanged))
{
try
{
d(FallbackLangCode);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", d.Method);
}
}
Loc.SetupWithFallbacks(this.assembly);
}
@ -134,7 +145,17 @@ public class Localization : IServiceType
}
this.DalamudLanguageCultureInfo = GetCultureInfoFromLangCode(langCode);
this.LocalizationChanged?.Invoke(langCode);
foreach (var d in Delegate.EnumerateInvocationList(this.LocalizationChanged))
{
try
{
d(langCode);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", d.Method);
}
}
try
{

View file

@ -527,9 +527,7 @@ internal sealed class DalamudPluginInterface : IDalamudPluginInterface, IDisposa
/// <param name="affectedThisPlugin">If this plugin was affected by the change.</param>
internal void NotifyActivePluginsChanged(PluginListInvalidationKind kind, bool affectedThisPlugin)
{
if (this.ActivePluginsChanged is { } callback)
{
foreach (var action in callback.GetInvocationList().Cast<IDalamudPluginInterface.ActivePluginsChangedDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.ActivePluginsChanged))
{
try
{
@ -541,15 +539,12 @@ internal sealed class DalamudPluginInterface : IDalamudPluginInterface, IDisposa
}
}
}
}
private void OnLocalizationChanged(string langCode)
{
this.UiLanguage = langCode;
if (this.LanguageChanged is { } callback)
{
foreach (var action in callback.GetInvocationList().Cast<IDalamudPluginInterface.LanguageChangedDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(this.LanguageChanged))
{
try
{
@ -561,7 +556,6 @@ internal sealed class DalamudPluginInterface : IDalamudPluginInterface, IDisposa
}
}
}
}
private void OnDalamudConfigurationSaved(DalamudConfiguration dalamudConfiguration)
{

View file

@ -1,7 +1,8 @@
using System.Linq;
using System.Collections.Generic;
using Dalamud.Game;
using Dalamud.Game.Gui.ContextMenu;
using Dalamud.Game.Gui.NamePlate;
using Dalamud.Plugin.Services;
using Serilog;
@ -14,25 +15,29 @@ internal static class EventHandlerExtensions
{
/// <summary>
/// Replacement for Invoke() on EventHandlers to catch exceptions that stop event propagation in case
/// of a thrown Exception inside of an invocation.
/// of a thrown Exception inside an invocation.
/// </summary>
/// <param name="eh">The EventHandler in question.</param>
/// <param name="sender">Default sender for Invoke equivalent.</param>
/// <param name="e">Default EventArgs for Invoke equivalent.</param>
public static void InvokeSafely(this EventHandler? eh, object sender, EventArgs e)
{
if (eh == null)
return;
foreach (var handler in eh.GetInvocationList().Cast<EventHandler>())
foreach (var handler in Delegate.EnumerateInvocationList(eh))
{
HandleInvoke(() => handler(sender, e));
try
{
handler(sender, e);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", handler.Method);
}
}
}
/// <summary>
/// Replacement for Invoke() on generic EventHandlers to catch exceptions that stop event propagation in case
/// of a thrown Exception inside of an invocation.
/// of a thrown Exception inside an invocation.
/// </summary>
/// <param name="eh">The EventHandler in question.</param>
/// <param name="sender">Default sender for Invoke equivalent.</param>
@ -40,104 +45,135 @@ internal static class EventHandlerExtensions
/// <typeparam name="T">Type of EventArgs.</typeparam>
public static void InvokeSafely<T>(this EventHandler<T>? eh, object sender, T e)
{
if (eh == null)
return;
foreach (var handler in eh.GetInvocationList().Cast<EventHandler<T>>())
foreach (var handler in Delegate.EnumerateInvocationList(eh))
{
HandleInvoke(() => handler(sender, e));
try
{
handler(sender, e);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", handler.Method);
}
}
}
/// <summary>
/// Replacement for Invoke() on event Actions to catch exceptions that stop event propagation in case
/// of a thrown Exception inside of an invocation.
/// of a thrown Exception inside an invocation.
/// </summary>
/// <param name="act">The Action in question.</param>
public static void InvokeSafely(this Action? act)
{
if (act == null)
return;
foreach (var action in act.GetInvocationList().Cast<Action>())
foreach (var action in Delegate.EnumerateInvocationList(act))
{
HandleInvoke(action);
try
{
action();
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
}
/// <summary>
/// Replacement for Invoke() on event Actions to catch exceptions that stop event propagation in case
/// of a thrown Exception inside of an invocation.
/// </summary>
/// <param name="act">The Action in question.</param>
/// <param name="argument">Templated argument for Action.</param>
/// <typeparam name="T">Type of Action args.</typeparam>
/// <inheritdoc cref="InvokeSafely(Action)"/>
public static void InvokeSafely<T>(this Action<T>? act, T argument)
{
if (act == null)
return;
foreach (var action in act.GetInvocationList().Cast<Action<T>>())
foreach (var action in Delegate.EnumerateInvocationList(act))
{
HandleInvoke(action, argument);
try
{
action(argument);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
}
/// <inheritdoc cref="InvokeSafely(Action)"/>
public static void InvokeSafely<T1, T2>(this Action<T1, T2>? act, T1 arg1, T2 arg2)
{
foreach (var action in Delegate.EnumerateInvocationList(act))
{
try
{
action(arg1, arg2);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
}
/// <summary>
/// Replacement for Invoke() on OnUpdateDelegate to catch exceptions that stop event propagation in case
/// of a thrown Exception inside of an invocation.
/// of a thrown Exception inside an invocation.
/// </summary>
/// <param name="updateDelegate">The OnUpdateDelegate in question.</param>
/// <param name="framework">Framework to be passed on to OnUpdateDelegate.</param>
public static void InvokeSafely(this IFramework.OnUpdateDelegate? updateDelegate, Framework framework)
{
if (updateDelegate == null)
return;
foreach (var action in updateDelegate.GetInvocationList().Cast<IFramework.OnUpdateDelegate>())
foreach (var action in Delegate.EnumerateInvocationList(updateDelegate))
{
HandleInvoke(() => action(framework));
try
{
action(framework);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
}
/// <summary>
/// Replacement for Invoke() on OnMenuOpenedDelegate to catch exceptions that stop event propagation in case
/// of a thrown Exception inside of an invocation.
/// of a thrown Exception inside an invocation.
/// </summary>
/// <param name="openedDelegate">The OnMenuOpenedDelegate in question.</param>
/// <param name="argument">Templated argument for Action.</param>
public static void InvokeSafely(this IContextMenu.OnMenuOpenedDelegate? openedDelegate, MenuOpenedArgs argument)
{
if (openedDelegate == null)
return;
foreach (var action in openedDelegate.GetInvocationList().Cast<IContextMenu.OnMenuOpenedDelegate>())
{
HandleInvoke(() => action(argument));
}
}
private static void HandleInvoke(Action act)
foreach (var action in Delegate.EnumerateInvocationList(openedDelegate))
{
try
{
act();
action(argument);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", act.Method);
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
}
private static void HandleInvoke<T>(Action<T> act, T argument)
/// <summary>
/// Replacement for Invoke() on OnMenuOpenedDelegate to catch exceptions that stop event propagation in case
/// of a thrown Exception inside an invocation.
/// </summary>
/// <param name="updatedDelegate">The OnMenuOpenedDelegate in question.</param>
/// <param name="context">An object containing information about the pending data update.</param>
/// <param name="handlers>">A list of handlers used for updating nameplate data.</param>
public static void InvokeSafely(
this INamePlateGui.OnPlateUpdateDelegate? updatedDelegate,
INamePlateUpdateContext context,
IReadOnlyList<INamePlateUpdateHandler> handlers)
{
foreach (var action in Delegate.EnumerateInvocationList(updatedDelegate))
{
try
{
act(argument);
action(context, handlers);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", act.Method);
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
}
}