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> /// <returns>Whether the command was successfully processed.</returns>
public bool ProcessCommand(string command) 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; return true;
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
}
var matches = GetCommandParsingRegex().Matches(command); var matches = GetCommandParsingRegex().Matches(command);
if (matches.Count == 0) if (matches.Count == 0)

View file

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

View file

@ -157,13 +157,16 @@ internal sealed class Condition : IInternalDisposableService, ICondition
{ {
this.cache[i] = value; this.cache[i] = value;
foreach (var d in Delegate.EnumerateInvocationList(this.ConditionChange))
{
try try
{ {
this.ConditionChange?.Invoke((ConditionFlag)i, value); d((ConditionFlag)i, value);
} }
catch (Exception ex) 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; return false;
} }
this.CommandAdded?.Invoke(this, new CommandEventArgs this.CommandAdded?.InvokeSafely(this, new CommandEventArgs
{ {
Command = command, Command = command,
CommandInfo = info, CommandInfo = info,
@ -160,7 +160,7 @@ internal sealed unsafe class CommandManager : IInternalDisposableService, IComma
return false; return false;
} }
this.CommandAdded?.Invoke(this, new CommandEventArgs this.CommandAdded?.InvokeSafely(this, new CommandEventArgs
{ {
Command = command, Command = command,
CommandInfo = info, CommandInfo = info,
@ -180,7 +180,7 @@ internal sealed unsafe class CommandManager : IInternalDisposableService, IComma
var removed = this.commandMap.Remove(command, out var info); var removed = this.commandMap.Remove(command, out var info);
if (removed) if (removed)
{ {
this.CommandRemoved?.Invoke(this, new CommandEventArgs this.CommandRemoved?.InvokeSafely(this, new CommandEventArgs
{ {
Command = command, Command = command,
CommandInfo = info, 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> /// <param name="frameworkInstance">The Framework Instance to pass to delegate.</param>
internal void ProfileAndInvoke(IFramework.OnUpdateDelegate? eventDelegate, IFramework frameworkInstance) internal void ProfileAndInvoke(IFramework.OnUpdateDelegate? eventDelegate, IFramework frameworkInstance)
{ {
if (eventDelegate is null) return;
var invokeList = eventDelegate.GetInvocationList();
// Individually invoke OnUpdate handlers and time them. // Individually invoke OnUpdate handlers and time them.
foreach (var d in invokeList) foreach (var d in Delegate.EnumerateInvocationList(eventDelegate))
{ {
var stopwatch = Stopwatch.StartNew(); var stopwatch = Stopwatch.StartNew();
try try
{ {
d.Method.Invoke(d.Target, new object[] { frameworkInstance }); d(frameworkInstance);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -370,7 +366,6 @@ internal sealed class Framework : IInternalDisposableService, IFramework
stopwatch.Stop(); stopwatch.Stop();
var key = $"{d.Target}::{d.Method.Name}"; var key = $"{d.Target}::{d.Method.Name}";
if (this.NonUpdatedSubDelegates.Contains(key))
this.NonUpdatedSubDelegates.Remove(key); this.NonUpdatedSubDelegates.Remove(key);
AddToStats(key, stopwatch.Elapsed.TotalMilliseconds); AddToStats(key, stopwatch.Elapsed.TotalMilliseconds);

View file

@ -346,9 +346,7 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui
// Call events // Call events
var isHandled = false; var isHandled = false;
if (this.CheckMessageHandled is { } handledCallback) foreach (var action in Delegate.EnumerateInvocationList(this.CheckMessageHandled))
{
foreach (var action in handledCallback.GetInvocationList().Cast<IChatGui.OnCheckMessageHandledDelegate>())
{ {
try try
{ {
@ -359,11 +357,10 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui
Log.Error(e, "Could not invoke registered OnCheckMessageHandledDelegate for {Name}", action.Method); 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 try
{ {
@ -394,12 +391,14 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui
// Print the original chat if it's handled. // Print the original chat if it's handled.
if (isHandled) if (isHandled)
{ {
this.ChatMessageHandled?.Invoke(chatType, timestamp, parsedSender, parsedMessage); foreach (var d in Delegate.EnumerateInvocationList(this.ChatMessageHandled))
d(chatType, timestamp, parsedSender, parsedMessage);
} }
else else
{ {
messageId = this.printMessageHook.Original(manager, chatType, sender, message, timestamp, silent); 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) 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}\") " + $"text1({(nint)text1:X}, \"{tmpText1}\") text2({(nint)text2:X}, \"{tmpText2}\") " +
$"color({color:X}) icon({icon}) yOffset({yOffset})"); $"color({color:X}) icon({icon}) yOffset({yOffset})");
Log.Verbose("[FlyText] Calling flytext events!"); Log.Verbose("[FlyText] Calling flytext events!");
this.FlyTextCreated?.Invoke( foreach (var d in Delegate.EnumerateInvocationList(this.FlyTextCreated))
{
try
{
d(
ref tmpKind, ref tmpKind,
ref tmpVal1, ref tmpVal1,
ref tmpVal2, ref tmpVal2,
@ -127,6 +131,12 @@ internal sealed class FlyTextGui : IInternalDisposableService, IFlyTextGui
ref tmpDamageTypeIcon, ref tmpDamageTypeIcon,
ref tmpYOffset, ref tmpYOffset,
ref handled); ref handled);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", d.Method);
}
}
// If handled, ignore the original call // If handled, ignore the original call
if (handled) if (handled)

View file

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

View file

@ -10,6 +10,8 @@ using Dalamud.Plugin.Services;
using FFXIVClientStructs.FFXIV.Client.UI; using FFXIVClientStructs.FFXIV.Client.UI;
using Serilog;
namespace Dalamud.Game.Gui.Toast; namespace Dalamud.Game.Gui.Toast;
/// <summary> /// <summary>
@ -150,7 +152,17 @@ internal sealed partial class ToastGui
Speed = (ToastSpeed)isFast, 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 // do nothing if handled
if (isHandled) if (isHandled)
@ -223,7 +235,17 @@ internal sealed partial class ToastGui
PlaySound = playSound == 1, 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 // do nothing if handled
if (isHandled) if (isHandled)
@ -286,7 +308,17 @@ internal sealed partial class ToastGui
var isHandled = false; var isHandled = false;
var str = SeString.Parse(text); 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 // do nothing if handled
if (isHandled) if (isHandled)

View file

@ -150,9 +150,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnHistoryReceived(IMarketBoardHistory history) private void OnHistoryReceived(IMarketBoardHistory history)
{ {
if (this.HistoryReceived == null) return; foreach (var action in Delegate.EnumerateInvocationList(this.HistoryReceived))
foreach (var action in this.HistoryReceived.GetInvocationList().Cast<HistoryReceivedDelegate>())
{ {
try try
{ {
@ -167,9 +165,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnItemPurchased(IMarketBoardPurchase purchase) private void OnItemPurchased(IMarketBoardPurchase purchase)
{ {
if (this.ItemPurchased == null) return; foreach (var action in Delegate.EnumerateInvocationList(this.ItemPurchased))
foreach (var action in this.ItemPurchased.GetInvocationList().Cast<ItemPurchasedDelegate>())
{ {
try try
{ {
@ -184,10 +180,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnOfferingsReceived(IMarketBoardCurrentOfferings currentOfferings) private void OnOfferingsReceived(IMarketBoardCurrentOfferings currentOfferings)
{ {
if (this.OfferingsReceived == null) return; foreach (var action in Delegate.EnumerateInvocationList(this.OfferingsReceived))
foreach (var action in this.OfferingsReceived.GetInvocationList()
.Cast<OfferingsReceivedDelegate>())
{ {
try try
{ {
@ -202,9 +195,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnPurchaseRequested(IMarketBoardPurchaseHandler purchaseHandler) private void OnPurchaseRequested(IMarketBoardPurchaseHandler purchaseHandler)
{ {
if (this.PurchaseRequested == null) return; foreach (var action in Delegate.EnumerateInvocationList(this.PurchaseRequested))
foreach (var action in this.PurchaseRequested.GetInvocationList().Cast<PurchaseRequestedDelegate>())
{ {
try try
{ {
@ -219,9 +210,7 @@ internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoar
private void OnTaxRatesReceived(IMarketTaxRates taxRates) private void OnTaxRatesReceived(IMarketTaxRates taxRates)
{ {
if (this.TaxRatesReceived == null) return; foreach (var action in Delegate.EnumerateInvocationList(this.TaxRatesReceived))
foreach (var action in this.TaxRatesReceived.GetInvocationList().Cast<TaxRatesReceivedDelegate>())
{ {
try 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 // Go back 0x10 to get back to the start of the packet header
dataPtr -= 0x10; dataPtr -= 0x10;
foreach (var d in Delegate.EnumerateInvocationList(this.NetworkMessage))
{
try try
{ {
// Call events d.Invoke(
this.NetworkMessage?.Invoke(dataPtr + 0x20, (ushort)Marshal.ReadInt16(dataPtr, 0x12), 0, targetId, NetworkMessageDirection.ZoneDown); dataPtr + 0x20,
(ushort)Marshal.ReadInt16(dataPtr, 0x12),
this.processZonePacketDownHook.Original(dispatcher, targetId, dataPtr + 0x10); 0,
targetId,
NetworkMessageDirection.ZoneDown);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -93,10 +97,10 @@ internal sealed unsafe class GameNetwork : IInternalDisposableService, IGameNetw
} }
Log.Error(ex, "Exception on ProcessZonePacketDown hook. Header: " + header); 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(); this.hitchDetectorDown.Stop();
} }

View file

@ -81,14 +81,17 @@ internal sealed class WndProcHookManager : IInternalDisposableService
/// </summary> /// </summary>
/// <param name="args">The arguments.</param> /// <param name="args">The arguments.</param>
internal void InvokePreWndProc(WndProcEventArgs args) internal void InvokePreWndProc(WndProcEventArgs args)
{
foreach (var d in Delegate.EnumerateInvocationList(this.PreWndProc))
{ {
try try
{ {
this.PreWndProc?.Invoke(args); d(args);
} }
catch (Exception e) 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> /// </summary>
/// <param name="args">The arguments.</param> /// <param name="args">The arguments.</param>
internal void InvokePostWndProc(WndProcEventArgs args) internal void InvokePostWndProc(WndProcEventArgs args)
{
foreach (var d in Delegate.EnumerateInvocationList(this.PostWndProc))
{ {
try try
{ {
this.PostWndProc?.Invoke(args); d(args);
} }
catch (Exception e) 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) if (@delegate is null)
return null; return null;
foreach (var il in @delegate.GetInvocationList()) foreach (var il in Delegate.EnumerateInvocationList(@delegate))
{ {
if (il.Target is { } target && !IsOwnedByDalamud(target.GetType())) if (il.Target is { } target && !IsOwnedByDalamud(target.GetType()))
@delegate = (T)Delegate.Remove(@delegate, il); @delegate = (T)Delegate.Remove(@delegate, il);

View file

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

View file

@ -832,7 +832,7 @@ internal partial class InterfaceManager : IInternalDisposableService
this.defaultFontResourceLock = fontLocked; this.defaultFontResourceLock = fontLocked;
// Broadcast to auto-rebuilding instances. // 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); var key = new DelegateFontHandle(this, buildStepDelegate);
lock (this.syncRoot) lock (this.syncRoot)
this.handles.Add(key); this.handles.Add(key);
this.RebuildRecommend?.Invoke(); this.RebuildRecommend.InvokeSafely();
return key; return key;
} }

View file

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

View file

@ -78,14 +78,17 @@ internal abstract class FontHandle : IFontHandle
/// </summary> /// </summary>
/// <param name="font">The font, locked during the call of <see cref="ImFontChanged"/>.</param> /// <param name="font">The font, locked during the call of <see cref="ImFontChanged"/>.</param>
public void InvokeImFontChanged(ILockedImFont font) public void InvokeImFontChanged(ILockedImFont font)
{
foreach (var d in Delegate.EnumerateInvocationList(this.ImFontChanged))
{ {
try try
{ {
this.ImFontChanged?.Invoke(this, font); d(this, font);
} }
catch (Exception e) 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) if (suggestRebuild)
this.RebuildRecommend?.Invoke(); this.RebuildRecommend.InvokeSafely();
return handle; return handle;
} }

View file

@ -117,7 +117,18 @@ public class Localization : IServiceType
public void SetupWithFallbacks() public void SetupWithFallbacks()
{ {
this.DalamudLanguageCultureInfo = CultureInfo.InvariantCulture; 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); Loc.SetupWithFallbacks(this.assembly);
} }
@ -134,7 +145,17 @@ public class Localization : IServiceType
} }
this.DalamudLanguageCultureInfo = GetCultureInfoFromLangCode(langCode); 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 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> /// <param name="affectedThisPlugin">If this plugin was affected by the change.</param>
internal void NotifyActivePluginsChanged(PluginListInvalidationKind kind, bool affectedThisPlugin) internal void NotifyActivePluginsChanged(PluginListInvalidationKind kind, bool affectedThisPlugin)
{ {
if (this.ActivePluginsChanged is { } callback) foreach (var action in Delegate.EnumerateInvocationList(this.ActivePluginsChanged))
{
foreach (var action in callback.GetInvocationList().Cast<IDalamudPluginInterface.ActivePluginsChangedDelegate>())
{ {
try try
{ {
@ -541,15 +539,12 @@ internal sealed class DalamudPluginInterface : IDalamudPluginInterface, IDisposa
} }
} }
} }
}
private void OnLocalizationChanged(string langCode) private void OnLocalizationChanged(string langCode)
{ {
this.UiLanguage = langCode; this.UiLanguage = langCode;
if (this.LanguageChanged is { } callback) foreach (var action in Delegate.EnumerateInvocationList(this.LanguageChanged))
{
foreach (var action in callback.GetInvocationList().Cast<IDalamudPluginInterface.LanguageChangedDelegate>())
{ {
try try
{ {
@ -561,7 +556,6 @@ internal sealed class DalamudPluginInterface : IDalamudPluginInterface, IDisposa
} }
} }
} }
}
private void OnDalamudConfigurationSaved(DalamudConfiguration dalamudConfiguration) private void OnDalamudConfigurationSaved(DalamudConfiguration dalamudConfiguration)
{ {

View file

@ -1,7 +1,8 @@
using System.Linq; using System.Collections.Generic;
using Dalamud.Game; using Dalamud.Game;
using Dalamud.Game.Gui.ContextMenu; using Dalamud.Game.Gui.ContextMenu;
using Dalamud.Game.Gui.NamePlate;
using Dalamud.Plugin.Services; using Dalamud.Plugin.Services;
using Serilog; using Serilog;
@ -14,25 +15,29 @@ internal static class EventHandlerExtensions
{ {
/// <summary> /// <summary>
/// Replacement for Invoke() on EventHandlers to catch exceptions that stop event propagation in case /// 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> /// </summary>
/// <param name="eh">The EventHandler in question.</param> /// <param name="eh">The EventHandler in question.</param>
/// <param name="sender">Default sender for Invoke equivalent.</param> /// <param name="sender">Default sender for Invoke equivalent.</param>
/// <param name="e">Default EventArgs for Invoke equivalent.</param> /// <param name="e">Default EventArgs for Invoke equivalent.</param>
public static void InvokeSafely(this EventHandler? eh, object sender, EventArgs e) public static void InvokeSafely(this EventHandler? eh, object sender, EventArgs e)
{ {
if (eh == null) foreach (var handler in Delegate.EnumerateInvocationList(eh))
return;
foreach (var handler in eh.GetInvocationList().Cast<EventHandler>())
{ {
HandleInvoke(() => handler(sender, e)); try
{
handler(sender, e);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", handler.Method);
}
} }
} }
/// <summary> /// <summary>
/// Replacement for Invoke() on generic EventHandlers to catch exceptions that stop event propagation in case /// 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> /// </summary>
/// <param name="eh">The EventHandler in question.</param> /// <param name="eh">The EventHandler in question.</param>
/// <param name="sender">Default sender for Invoke equivalent.</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> /// <typeparam name="T">Type of EventArgs.</typeparam>
public static void InvokeSafely<T>(this EventHandler<T>? eh, object sender, T e) public static void InvokeSafely<T>(this EventHandler<T>? eh, object sender, T e)
{ {
if (eh == null) foreach (var handler in Delegate.EnumerateInvocationList(eh))
return;
foreach (var handler in eh.GetInvocationList().Cast<EventHandler<T>>())
{ {
HandleInvoke(() => handler(sender, e)); try
{
handler(sender, e);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", handler.Method);
}
} }
} }
/// <summary> /// <summary>
/// Replacement for Invoke() on event Actions to catch exceptions that stop event propagation in case /// 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> /// </summary>
/// <param name="act">The Action in question.</param> /// <param name="act">The Action in question.</param>
public static void InvokeSafely(this Action? act) public static void InvokeSafely(this Action? act)
{ {
if (act == null) foreach (var action in Delegate.EnumerateInvocationList(act))
return;
foreach (var action in act.GetInvocationList().Cast<Action>())
{ {
HandleInvoke(action); try
{
action();
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
} }
} }
/// <summary> /// <inheritdoc cref="InvokeSafely(Action)"/>
/// 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>
public static void InvokeSafely<T>(this Action<T>? act, T argument) public static void InvokeSafely<T>(this Action<T>? act, T argument)
{ {
if (act == null) foreach (var action in Delegate.EnumerateInvocationList(act))
return;
foreach (var action in act.GetInvocationList().Cast<Action<T>>())
{ {
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> /// <summary>
/// Replacement for Invoke() on OnUpdateDelegate to catch exceptions that stop event propagation in case /// 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> /// </summary>
/// <param name="updateDelegate">The OnUpdateDelegate in question.</param> /// <param name="updateDelegate">The OnUpdateDelegate in question.</param>
/// <param name="framework">Framework to be passed on to OnUpdateDelegate.</param> /// <param name="framework">Framework to be passed on to OnUpdateDelegate.</param>
public static void InvokeSafely(this IFramework.OnUpdateDelegate? updateDelegate, Framework framework) public static void InvokeSafely(this IFramework.OnUpdateDelegate? updateDelegate, Framework framework)
{ {
if (updateDelegate == null) foreach (var action in Delegate.EnumerateInvocationList(updateDelegate))
return;
foreach (var action in updateDelegate.GetInvocationList().Cast<IFramework.OnUpdateDelegate>())
{ {
HandleInvoke(() => action(framework)); try
{
action(framework);
}
catch (Exception ex)
{
Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
} }
} }
/// <summary> /// <summary>
/// Replacement for Invoke() on OnMenuOpenedDelegate to catch exceptions that stop event propagation in case /// 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> /// </summary>
/// <param name="openedDelegate">The OnMenuOpenedDelegate in question.</param> /// <param name="openedDelegate">The OnMenuOpenedDelegate in question.</param>
/// <param name="argument">Templated argument for Action.</param> /// <param name="argument">Templated argument for Action.</param>
public static void InvokeSafely(this IContextMenu.OnMenuOpenedDelegate? openedDelegate, MenuOpenedArgs argument) public static void InvokeSafely(this IContextMenu.OnMenuOpenedDelegate? openedDelegate, MenuOpenedArgs argument)
{ {
if (openedDelegate == null) foreach (var action in Delegate.EnumerateInvocationList(openedDelegate))
return;
foreach (var action in openedDelegate.GetInvocationList().Cast<IContextMenu.OnMenuOpenedDelegate>())
{
HandleInvoke(() => action(argument));
}
}
private static void HandleInvoke(Action act)
{ {
try try
{ {
act(); action(argument);
} }
catch (Exception ex) 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 try
{ {
act(argument); action(context, handlers);
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex, "Exception during raise of {handler}", act.Method); Log.Error(ex, "Exception during raise of {handler}", action.Method);
}
} }
} }
} }