diff --git a/Dalamud.sln b/Dalamud.sln index de91e7ceb..fa26a5d67 100644 --- a/Dalamud.sln +++ b/Dalamud.sln @@ -75,6 +75,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Excel.Generator", "l EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Excel", "lib\Lumina.Excel\src\Lumina.Excel\Lumina.Excel.csproj", "{88FB719B-EB41-73C5-8D25-C03E0C69904F}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Source Generators", "Source Generators", "{50BEC23B-FFFD-427B-A95D-27E1D1958FFF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dalamud.EnumGenerator", "generators\Dalamud.EnumGenerator\Dalamud.EnumGenerator\Dalamud.EnumGenerator.csproj", "{27AA9F87-D2AA-41D9-A559-0F1EBA38C5F8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dalamud.EnumGenerator.Sample", "generators\Dalamud.EnumGenerator\Dalamud.EnumGenerator.Sample\Dalamud.EnumGenerator.Sample.csproj", "{8CDAEB2D-5022-450A-A97F-181C6270185F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dalamud.EnumGenerator.Tests", "generators\Dalamud.EnumGenerator\Dalamud.EnumGenerator.Tests\Dalamud.EnumGenerator.Tests.csproj", "{F5D92D2D-D36F-4471-B657-8B9AA6C98AD6}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -173,6 +181,18 @@ Global {88FB719B-EB41-73C5-8D25-C03E0C69904F}.Debug|Any CPU.Build.0 = Debug|Any CPU {88FB719B-EB41-73C5-8D25-C03E0C69904F}.Release|Any CPU.ActiveCfg = Release|Any CPU {88FB719B-EB41-73C5-8D25-C03E0C69904F}.Release|Any CPU.Build.0 = Release|Any CPU + {27AA9F87-D2AA-41D9-A559-0F1EBA38C5F8}.Debug|Any CPU.ActiveCfg = Debug|x64 + {27AA9F87-D2AA-41D9-A559-0F1EBA38C5F8}.Debug|Any CPU.Build.0 = Debug|x64 + {27AA9F87-D2AA-41D9-A559-0F1EBA38C5F8}.Release|Any CPU.ActiveCfg = Release|x64 + {27AA9F87-D2AA-41D9-A559-0F1EBA38C5F8}.Release|Any CPU.Build.0 = Release|x64 + {8CDAEB2D-5022-450A-A97F-181C6270185F}.Debug|Any CPU.ActiveCfg = Debug|x64 + {8CDAEB2D-5022-450A-A97F-181C6270185F}.Debug|Any CPU.Build.0 = Debug|x64 + {8CDAEB2D-5022-450A-A97F-181C6270185F}.Release|Any CPU.ActiveCfg = Release|x64 + {8CDAEB2D-5022-450A-A97F-181C6270185F}.Release|Any CPU.Build.0 = Release|x64 + {F5D92D2D-D36F-4471-B657-8B9AA6C98AD6}.Debug|Any CPU.ActiveCfg = Debug|x64 + {F5D92D2D-D36F-4471-B657-8B9AA6C98AD6}.Debug|Any CPU.Build.0 = Debug|x64 + {F5D92D2D-D36F-4471-B657-8B9AA6C98AD6}.Release|Any CPU.ActiveCfg = Release|x64 + {F5D92D2D-D36F-4471-B657-8B9AA6C98AD6}.Release|Any CPU.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -197,6 +217,9 @@ Global {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} = {E15BDA6D-E881-4482-94BA-BE5527E917FF} {5A44DF0C-C9DA-940F-4D6B-4A11D13AEA3D} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {88FB719B-EB41-73C5-8D25-C03E0C69904F} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {27AA9F87-D2AA-41D9-A559-0F1EBA38C5F8} = {50BEC23B-FFFD-427B-A95D-27E1D1958FFF} + {8CDAEB2D-5022-450A-A97F-181C6270185F} = {50BEC23B-FFFD-427B-A95D-27E1D1958FFF} + {F5D92D2D-D36F-4471-B657-8B9AA6C98AD6} = {50BEC23B-FFFD-427B-A95D-27E1D1958FFF} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {79B65AC9-C940-410E-AB61-7EA7E12C7599} diff --git a/Dalamud/Configuration/Internal/DalamudConfiguration.cs b/Dalamud/Configuration/Internal/DalamudConfiguration.cs index ddcb26914..7e93d2863 100644 --- a/Dalamud/Configuration/Internal/DalamudConfiguration.cs +++ b/Dalamud/Configuration/Internal/DalamudConfiguration.cs @@ -10,7 +10,6 @@ using System.Threading.Tasks; using Dalamud.Game.Text; using Dalamud.Interface; using Dalamud.Interface.FontIdentifier; -using Dalamud.Interface.ImGuiNotification.Internal; using Dalamud.Interface.Internal; using Dalamud.Interface.Internal.ReShadeHandling; using Dalamud.Interface.Style; @@ -20,9 +19,12 @@ using Dalamud.Plugin.Internal.AutoUpdate; using Dalamud.Plugin.Internal.Profiles; using Dalamud.Storage; using Dalamud.Utility; + using Newtonsoft.Json; + using Serilog; using Serilog.Events; + using Windows.Win32.UI.WindowsAndMessaging; namespace Dalamud.Configuration.Internal; @@ -91,7 +93,7 @@ internal sealed class DalamudConfiguration : IInternalDisposableService /// /// Gets or sets a dictionary of seen FTUE levels. /// - public Dictionary SeenFtueLevels { get; set; } = new(); + public Dictionary SeenFtueLevels { get; set; } = []; /// /// Gets or sets the last loaded Dalamud version. @@ -111,7 +113,7 @@ internal sealed class DalamudConfiguration : IInternalDisposableService /// /// Gets or sets a list of custom repos. /// - public List ThirdRepoList { get; set; } = new(); + public List ThirdRepoList { get; set; } = []; /// /// Gets or sets a value indicating whether a disclaimer regarding third-party repos has been dismissed. @@ -121,12 +123,12 @@ internal sealed class DalamudConfiguration : IInternalDisposableService /// /// Gets or sets a list of hidden plugins. /// - public List HiddenPluginInternalName { get; set; } = new(); + public List HiddenPluginInternalName { get; set; } = []; /// /// Gets or sets a list of seen plugins. /// - public List SeenPluginInternalName { get; set; } = new(); + public List SeenPluginInternalName { get; set; } = []; /// /// Gets or sets a list of additional settings for devPlugins. The key is the absolute path @@ -134,14 +136,14 @@ internal sealed class DalamudConfiguration : IInternalDisposableService /// However by specifiying this value manually, you can add arbitrary files outside the normal /// file paths. /// - public Dictionary DevPluginSettings { get; set; } = new(); + public Dictionary DevPluginSettings { get; set; } = []; /// /// Gets or sets a list of additional locations that dev plugins should be loaded from. This can /// be either a DLL or folder, but should be the absolute path, or a path relative to the currently /// injected Dalamud instance. /// - public List DevPluginLoadLocations { get; set; } = new(); + public List DevPluginLoadLocations { get; set; } = []; /// /// Gets or sets the global UI scale. @@ -223,7 +225,7 @@ internal sealed class DalamudConfiguration : IInternalDisposableService /// /// Gets or sets a list representing the command history for the Dalamud Console. /// - public List LogCommandHistory { get; set; } = new(); + public List LogCommandHistory { get; set; } = []; /// /// Gets or sets a value indicating whether the dev bar should open at startup. @@ -599,7 +601,7 @@ internal sealed class DalamudConfiguration : IInternalDisposableService { // https://source.chromium.org/chromium/chromium/src/+/main:ui/gfx/animation/animation_win.cc;l=29?q=ReducedMotion&ss=chromium var winAnimEnabled = 0; - var success = false; + bool success; unsafe { success = Windows.Win32.PInvoke.SystemParametersInfo( diff --git a/Dalamud/Configuration/Internal/DevPluginSettings.cs b/Dalamud/Configuration/Internal/DevPluginSettings.cs index 64327e658..400834cf8 100644 --- a/Dalamud/Configuration/Internal/DevPluginSettings.cs +++ b/Dalamud/Configuration/Internal/DevPluginSettings.cs @@ -31,5 +31,5 @@ internal sealed class DevPluginSettings /// /// Gets or sets a list of validation problems that have been dismissed by the user. /// - public List DismissedValidationProblems { get; set; } = new(); + public List DismissedValidationProblems { get; set; } = []; } diff --git a/Dalamud/Console/ConsoleManager.cs b/Dalamud/Console/ConsoleManager.cs index 377bac208..ba1c38b16 100644 --- a/Dalamud/Console/ConsoleManager.cs +++ b/Dalamud/Console/ConsoleManager.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; @@ -17,9 +17,9 @@ namespace Dalamud.Console; [ServiceManager.BlockingEarlyLoadedService("Console is needed by other blocking early loaded services.")] internal partial class ConsoleManager : IServiceType { - private static readonly ModuleLog Log = new("CON"); + private static readonly ModuleLog Log = ModuleLog.Create(); - private Dictionary entries = new(); + private Dictionary entries = []; /// /// Initializes a new instance of the class. @@ -99,10 +99,7 @@ internal partial class ConsoleManager : IServiceType ArgumentNullException.ThrowIfNull(name); ArgumentNullException.ThrowIfNull(alias); - var target = this.FindEntry(name); - if (target == null) - throw new EntryNotFoundException(name); - + var target = this.FindEntry(name) ?? throw new EntryNotFoundException(name); if (this.FindEntry(alias) != null) throw new InvalidOperationException($"Entry '{alias}' already exists."); @@ -346,7 +343,7 @@ internal partial class ConsoleManager : IServiceType private static class Traits { - public static void ThrowIfTIsNullableAndNull(T? argument, [CallerArgumentExpression("argument")] string? paramName = null) + public static void ThrowIfTIsNullableAndNull(T? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) { if (argument == null && !typeof(T).IsValueType) throw new ArgumentNullException(paramName); diff --git a/Dalamud/Console/ConsoleManagerPluginScoped.cs b/Dalamud/Console/ConsoleManagerPluginScoped.cs index 41949c7d7..8e7516429 100644 --- a/Dalamud/Console/ConsoleManagerPluginScoped.cs +++ b/Dalamud/Console/ConsoleManagerPluginScoped.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; @@ -65,7 +65,7 @@ internal class ConsoleManagerPluginScoped : IConsole, IInternalDisposableService [ServiceManager.ServiceDependency] private readonly ConsoleManager console = Service.Get(); - private readonly List trackedEntries = new(); + private readonly List trackedEntries = []; /// /// Initializes a new instance of the class. diff --git a/Dalamud/Dalamud.cs b/Dalamud/Dalamud.cs index 2d32b8e8a..f80252ef9 100644 --- a/Dalamud/Dalamud.cs +++ b/Dalamud/Dalamud.cs @@ -14,7 +14,9 @@ using Dalamud.Plugin.Internal; using Dalamud.Storage; using Dalamud.Utility; using Dalamud.Utility.Timing; + using Serilog; + using Windows.Win32.Foundation; using Windows.Win32.Security; diff --git a/Dalamud/Dalamud.csproj b/Dalamud/Dalamud.csproj index f5e75af63..bb8f5af7c 100644 --- a/Dalamud/Dalamud.csproj +++ b/Dalamud/Dalamud.csproj @@ -88,6 +88,15 @@ + + + + + + + + + imgui-frag.hlsl.bytes diff --git a/Dalamud/Data/DataManager.cs b/Dalamud/Data/DataManager.cs index f53195a2d..11cb3a979 100644 --- a/Dalamud/Data/DataManager.cs +++ b/Dalamud/Data/DataManager.cs @@ -8,11 +8,13 @@ using Dalamud.IoC.Internal; using Dalamud.Plugin.Services; using Dalamud.Utility; using Dalamud.Utility.Timing; + using Lumina; using Lumina.Data; using Lumina.Excel; using Newtonsoft.Json; + using Serilog; namespace Dalamud.Data; diff --git a/Dalamud/Data/RsvResolver.cs b/Dalamud/Data/RsvResolver.cs index 3f507ff1d..6fd84356c 100644 --- a/Dalamud/Data/RsvResolver.cs +++ b/Dalamud/Data/RsvResolver.cs @@ -3,7 +3,9 @@ using System.Collections.Generic; using Dalamud.Hooking; using Dalamud.Logging.Internal; using Dalamud.Memory; + using FFXIVClientStructs.FFXIV.Client.LayoutEngine; + using Lumina.Text.ReadOnly; namespace Dalamud.Data; @@ -13,7 +15,7 @@ namespace Dalamud.Data; /// internal sealed unsafe class RsvResolver : IDisposable { - private static readonly ModuleLog Log = new("RsvProvider"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly Hook addRsvStringHook; diff --git a/Dalamud/EntryPoint.cs b/Dalamud/EntryPoint.cs index d9f6ef172..7abebee3b 100644 --- a/Dalamud/EntryPoint.cs +++ b/Dalamud/EntryPoint.cs @@ -1,8 +1,6 @@ using System.ComponentModel; using System.Diagnostics; using System.IO; -using System.Net; -using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; @@ -16,10 +14,13 @@ using Dalamud.Plugin.Internal; using Dalamud.Storage; using Dalamud.Support; using Dalamud.Utility; + using Newtonsoft.Json; + using Serilog; using Serilog.Core; using Serilog.Events; + using Windows.Win32.Foundation; using Windows.Win32.UI.WindowsAndMessaging; diff --git a/Dalamud/EnumCloneMap.txt b/Dalamud/EnumCloneMap.txt new file mode 100644 index 000000000..bbc3c1eda --- /dev/null +++ b/Dalamud/EnumCloneMap.txt @@ -0,0 +1,3 @@ +# Format: Target.Full.TypeName = Source.Full.EnumTypeName +# Example: Generate a local enum MyGeneratedEnum in namespace Sample.Gen mapped to SourceEnums.SampleSourceEnum +Dalamud.Game.Agent.AgentId = FFXIVClientStructs.FFXIV.Client.UI.Agent.AgentId diff --git a/Dalamud/Game/Addon/Events/AddonEventEntry.cs b/Dalamud/Game/Addon/Events/AddonEventEntry.cs index 30d0465dc..eca1903f2 100644 --- a/Dalamud/Game/Addon/Events/AddonEventEntry.cs +++ b/Dalamud/Game/Addon/Events/AddonEventEntry.cs @@ -1,5 +1,4 @@ using Dalamud.Plugin.Services; -using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Component.GUI; diff --git a/Dalamud/Game/Addon/Events/AddonEventManager.cs b/Dalamud/Game/Addon/Events/AddonEventManager.cs index 980404940..17b70fcc2 100644 --- a/Dalamud/Game/Addon/Events/AddonEventManager.cs +++ b/Dalamud/Game/Addon/Events/AddonEventManager.cs @@ -24,7 +24,7 @@ internal unsafe class AddonEventManager : IInternalDisposableService /// public static readonly Guid DalamudInternalKey = Guid.NewGuid(); - private static readonly ModuleLog Log = new("AddonEventManager"); + private static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceDependency] private readonly AddonLifecycle addonLifecycle = Service.Get(); diff --git a/Dalamud/Game/Addon/Events/AddonEventType.cs b/Dalamud/Game/Addon/Events/AddonEventType.cs index 25beb13fc..9e062a9d0 100644 --- a/Dalamud/Game/Addon/Events/AddonEventType.cs +++ b/Dalamud/Game/Addon/Events/AddonEventType.cs @@ -61,6 +61,11 @@ public enum AddonEventType : byte /// InputBaseInputReceived = 15, + /// + /// Fired at the very beginning of AtkInputManager.HandleInput on AtkStage.ViewportEventManager. Used in LovmMiniMap. + /// + RawInputData = 16, + /// /// Focus Start. /// @@ -107,7 +112,12 @@ public enum AddonEventType : byte SliderReleased = 30, /// - /// AtkComponentList RollOver. + /// AtkComponentList Button Press. + /// + ListButtonPress = 31, + + /// + /// AtkComponentList Roll Over. /// ListItemRollOver = 33, @@ -126,11 +136,31 @@ public enum AddonEventType : byte /// ListItemDoubleClick = 36, + /// + /// AtkComponentList Highlight. + /// + ListItemHighlight = 37, + /// /// AtkComponentList Select. /// ListItemSelect = 38, + /// + /// AtkComponentList Pad Drag Drop Begin. + /// + ListItemPadDragDropBegin = 40, + + /// + /// AtkComponentList Pad Drag Drop End. + /// + ListItemPadDragDropEnd = 41, + + /// + /// AtkComponentList Pad Drag Drop Insert. + /// + ListItemPadDragDropInsert = 42, + /// /// AtkComponentDragDrop Begin. /// Sent on MouseDown over a draggable icon (will NOT send for a locked icon). @@ -142,12 +172,22 @@ public enum AddonEventType : byte /// DragDropEnd = 51, + /// + /// AtkComponentDragDrop Insert Attempt. + /// + DragDropInsertAttempt = 52, + /// /// AtkComponentDragDrop Insert. /// Sent when dropping an icon into a hotbar/inventory slot or similar. /// DragDropInsert = 53, + /// + /// AtkComponentDragDrop Can Accept Check. + /// + DragDropCanAcceptCheck = 54, + /// /// AtkComponentDragDrop Roll Over. /// @@ -165,23 +205,18 @@ public enum AddonEventType : byte DragDropDiscard = 57, /// - /// Drag Drop Unknown. + /// AtkComponentDragDrop Click. + /// Sent on MouseUp if the cursor has not moved since DragDropBegin, OR on MouseDown over a locked icon. /// - [Obsolete("Use DragDropDiscard", true)] - DragDropUnk54 = 54, + DragDropClick = 58, /// /// AtkComponentDragDrop Cancel. /// Sent on MouseUp if the cursor has not moved since DragDropBegin, OR on MouseDown over a locked icon. /// + [Obsolete("Renamed to DragDropClick")] DragDropCancel = 58, - /// - /// Drag Drop Unknown. - /// - [Obsolete("Use DragDropCancel", true)] - DragDropUnk55 = 55, - /// /// AtkComponentIconText Roll Over. /// @@ -217,6 +252,11 @@ public enum AddonEventType : byte /// TimerEnd = 65, + /// + /// AtkTimer Start. + /// + TimerStart = 66, + /// /// AtkSimpleTween Progress. /// @@ -247,6 +287,11 @@ public enum AddonEventType : byte /// WindowChangeScale = 72, + /// + /// AtkTimeline Active Label Changed. + /// + TimelineActiveLabelChanged = 75, + /// /// AtkTextNode Link Mouse Click. /// diff --git a/Dalamud/Game/Addon/Events/PluginEventController.cs b/Dalamud/Game/Addon/Events/PluginEventController.cs index afaee9966..076c39cbb 100644 --- a/Dalamud/Game/Addon/Events/PluginEventController.cs +++ b/Dalamud/Game/Addon/Events/PluginEventController.cs @@ -5,7 +5,6 @@ using Dalamud.Game.Addon.Events.EventDataTypes; using Dalamud.Game.Gui; using Dalamud.Logging.Internal; using Dalamud.Plugin.Services; -using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Component.GUI; @@ -16,7 +15,7 @@ namespace Dalamud.Game.Addon.Events; /// internal unsafe class PluginEventController : IDisposable { - private static readonly ModuleLog Log = new("AddonEventManager"); + private static readonly ModuleLog Log = ModuleLog.Create(); /// /// Initializes a new instance of the class. @@ -28,7 +27,7 @@ internal unsafe class PluginEventController : IDisposable private AddonEventListener EventListener { get; init; } - private List Events { get; } = new(); + private List Events { get; } = []; /// /// Adds a tracked event. diff --git a/Dalamud/Game/Addon/Lifecycle/AddonLifecycle.cs b/Dalamud/Game/Addon/Lifecycle/AddonLifecycle.cs index 78cea1a0f..c70c0c10f 100644 --- a/Dalamud/Game/Addon/Lifecycle/AddonLifecycle.cs +++ b/Dalamud/Game/Addon/Lifecycle/AddonLifecycle.cs @@ -25,9 +25,13 @@ internal unsafe class AddonLifecycle : IInternalDisposableService /// public static readonly List AllocatedTables = []; - private static readonly ModuleLog Log = new("AddonLifecycle"); + private static readonly ModuleLog Log = ModuleLog.Create(); + + [ServiceManager.ServiceDependency] + private readonly Framework framework = Service.Get(); private Hook? onInitializeAddonHook; + private bool isInvokingListeners = false; [ServiceManager.ServiceConstructor] private AddonLifecycle() @@ -58,20 +62,23 @@ internal unsafe class AddonLifecycle : IInternalDisposableService /// The listener to register. internal void RegisterListener(AddonLifecycleEventListener listener) { - if (!this.EventListeners.ContainsKey(listener.EventType)) + this.framework.RunOnTick(() => { - if (!this.EventListeners.TryAdd(listener.EventType, [])) - return; - } + if (!this.EventListeners.ContainsKey(listener.EventType)) + { + if (!this.EventListeners.TryAdd(listener.EventType, [])) + return; + } - // Note: string.Empty is a valid addon name, as that will trigger on any addon for this event type - if (!this.EventListeners[listener.EventType].ContainsKey(listener.AddonName)) - { - if (!this.EventListeners[listener.EventType].TryAdd(listener.AddonName, [])) - return; - } + // Note: string.Empty is a valid addon name, as that will trigger on any addon for this event type + if (!this.EventListeners[listener.EventType].ContainsKey(listener.AddonName)) + { + if (!this.EventListeners[listener.EventType].TryAdd(listener.AddonName, [])) + return; + } - this.EventListeners[listener.EventType][listener.AddonName].Add(listener); + this.EventListeners[listener.EventType][listener.AddonName].Add(listener); + }, delayTicks: this.isInvokingListeners ? 1 : 0); } /// @@ -80,13 +87,16 @@ internal unsafe class AddonLifecycle : IInternalDisposableService /// The listener to unregister. internal void UnregisterListener(AddonLifecycleEventListener listener) { - if (this.EventListeners.TryGetValue(listener.EventType, out var addonListeners)) + this.framework.RunOnTick(() => { - if (addonListeners.TryGetValue(listener.AddonName, out var addonListener)) + if (this.EventListeners.TryGetValue(listener.EventType, out var addonListeners)) { - addonListener.Remove(listener); + if (addonListeners.TryGetValue(listener.AddonName, out var addonListener)) + { + addonListener.Remove(listener); + } } - } + }, delayTicks: this.isInvokingListeners ? 1 : 0); } /// @@ -97,6 +107,8 @@ internal unsafe class AddonLifecycle : IInternalDisposableService /// What to blame on errors. internal void InvokeListenersSafely(AddonEvent eventType, AddonArgs args, [CallerMemberName] string blame = "") { + this.isInvokingListeners = true; + // Early return if we don't have any listeners of this type if (!this.EventListeners.TryGetValue(eventType, out var addonListeners)) return; @@ -131,6 +143,8 @@ internal unsafe class AddonLifecycle : IInternalDisposableService } } } + + this.isInvokingListeners = false; } /// diff --git a/Dalamud/Game/BaseAddressResolver.cs b/Dalamud/Game/BaseAddressResolver.cs index d41b1d9d8..1f20e3aeb 100644 --- a/Dalamud/Game/BaseAddressResolver.cs +++ b/Dalamud/Game/BaseAddressResolver.cs @@ -14,7 +14,7 @@ public abstract class BaseAddressResolver /// /// Gets a list of memory addresses that were found, to list in /xldata. /// - public static Dictionary> DebugScannedValues { get; } = new(); + public static Dictionary> DebugScannedValues { get; } = []; /// /// Gets or sets a value indicating whether the resolver has successfully run or . diff --git a/Dalamud/Game/Chat/LogMessage.cs b/Dalamud/Game/Chat/LogMessage.cs new file mode 100644 index 000000000..c772783a1 --- /dev/null +++ b/Dalamud/Game/Chat/LogMessage.cs @@ -0,0 +1,221 @@ +using System.Diagnostics.CodeAnalysis; + +using Dalamud.Data; +using Dalamud.Utility; + +using FFXIVClientStructs.FFXIV.Client.System.String; +using FFXIVClientStructs.FFXIV.Client.UI.Agent; +using FFXIVClientStructs.FFXIV.Client.UI.Misc; +using FFXIVClientStructs.FFXIV.Component.Text; +using FFXIVClientStructs.Interop; + +using Lumina.Excel; +using Lumina.Text.ReadOnly; + +namespace Dalamud.Game.Chat; + +/// +/// Interface representing a log message. +/// +public interface ILogMessage : IEquatable +{ + /// + /// Gets the address of the log message in memory. + /// + nint Address { get; } + + /// + /// Gets the ID of this log message. + /// + uint LogMessageId { get; } + + /// + /// Gets the GameData associated with this log message. + /// + RowRef GameData { get; } + + /// + /// Gets the entity that is the source of this log message, if any. + /// + ILogMessageEntity? SourceEntity { get; } + + /// + /// Gets the entity that is the target of this log message, if any. + /// + ILogMessageEntity? TargetEntity { get; } + + /// + /// Gets the number of parameters. + /// + int ParameterCount { get; } + + /// + /// Retrieves the value of a parameter for the log message if it is an int. + /// + /// The index of the parameter to retrieve. + /// The value of the parameter. + /// if the parameter was retrieved successfully. + bool TryGetIntParameter(int index, out int value); + + /// + /// Retrieves the value of a parameter for the log message if it is a string. + /// + /// The index of the parameter to retrieve. + /// The value of the parameter. + /// if the parameter was retrieved successfully. + bool TryGetStringParameter(int index, out ReadOnlySeString value); + + /// + /// Formats this log message into an approximation of the string that will eventually be shown in the log. + /// + /// This can cause side effects such as playing sound effects and thus should only be used for debugging. + /// The formatted string. + ReadOnlySeString FormatLogMessageForDebugging(); +} + +/// +/// This struct represents log message in the queue to be added to the chat. +/// +/// A pointer to the log message. +internal unsafe readonly struct LogMessage(LogMessageQueueItem* ptr) : ILogMessage +{ + /// + public nint Address => (nint)ptr; + + /// + public uint LogMessageId => ptr->LogMessageId; + + /// + public RowRef GameData => LuminaUtils.CreateRef(ptr->LogMessageId); + + /// + ILogMessageEntity? ILogMessage.SourceEntity => ptr->SourceKind == EntityRelationKind.None ? null : this.SourceEntity; + + /// + ILogMessageEntity? ILogMessage.TargetEntity => ptr->TargetKind == EntityRelationKind.None ? null : this.TargetEntity; + + /// + public int ParameterCount => ptr->Parameters.Count; + + private LogMessageEntity SourceEntity => new(ptr, true); + + private LogMessageEntity TargetEntity => new(ptr, false); + + public static bool operator ==(LogMessage x, LogMessage y) => x.Equals(y); + + public static bool operator !=(LogMessage x, LogMessage y) => !(x == y); + + /// + public bool Equals(ILogMessage? other) + { + return other is LogMessage logMessage && this.Equals(logMessage); + } + + /// + public override bool Equals([NotNullWhen(true)] object? obj) + { + return obj is LogMessage logMessage && this.Equals(logMessage); + } + + /// + public override int GetHashCode() + { + return HashCode.Combine(this.LogMessageId, this.SourceEntity, this.TargetEntity); + } + + /// + public bool TryGetIntParameter(int index, out int value) + { + value = 0; + if (!this.TryGetParameter(index, out var parameter)) return false; + if (parameter.Type != TextParameterType.Integer) return false; + value = parameter.IntValue; + return true; + } + + /// + public bool TryGetStringParameter(int index, out ReadOnlySeString value) + { + value = default; + if (!this.TryGetParameter(index, out var parameter)) return false; + if (parameter.Type == TextParameterType.String) + { + value = new(parameter.StringValue.AsSpan()); + return true; + } + + if (parameter.Type == TextParameterType.ReferencedUtf8String) + { + value = new(parameter.ReferencedUtf8StringValue->Utf8String.AsSpan()); + return true; + } + + return false; + } + + /// + public ReadOnlySeString FormatLogMessageForDebugging() + { + var logModule = RaptureLogModule.Instance(); + + // the formatting logic is taken from RaptureLogModule_Update + + using var utf8 = new Utf8String(); + SetName(logModule, this.SourceEntity); + SetName(logModule, this.TargetEntity); + + using var rssb = new RentedSeStringBuilder(); + logModule->RaptureTextModule->FormatString(rssb.Builder.Append(this.GameData.Value.Text).GetViewAsSpan(), &ptr->Parameters, &utf8); + + return new ReadOnlySeString(utf8.AsSpan()); + + static void SetName(RaptureLogModule* self, LogMessageEntity item) + { + var name = item.NameSpan.GetPointer(0); + + if (item.IsPlayer) + { + var str = self->TempParseMessage.GetPointer(item.IsSourceEntity ? 8 : 9); + self->FormatPlayerLink(name, str, null, 0, item.Kind != 1 /* LocalPlayer */, item.HomeWorldId, false, null, false); + + if (item.HomeWorldId != 0 && item.HomeWorldId != AgentLobby.Instance()->LobbyData.HomeWorldId) + { + var crossWorldSymbol = self->RaptureTextModule->UnkStrings0.GetPointer(3); + if (!crossWorldSymbol->StringPtr.HasValue) + self->RaptureTextModule->ProcessMacroCode(crossWorldSymbol, "\0"u8); + str->Append(crossWorldSymbol); + if (self->UIModule->GetWorldHelper()->AllWorlds.TryGetValuePointer(item.HomeWorldId, out var world)) + str->ConcatCStr(world->Name); + } + + name = str->StringPtr; + } + + if (item.IsSourceEntity) + { + self->RaptureTextModule->SetGlobalTempEntity1(name, item.Sex, item.ObjStrId); + } + else + { + self->RaptureTextModule->SetGlobalTempEntity2(name, item.Sex, item.ObjStrId); + } + } + } + + private bool TryGetParameter(int index, out TextParameter value) + { + if (index < 0 || index >= ptr->Parameters.Count) + { + value = default; + return false; + } + + value = ptr->Parameters[index]; + return true; + } + + private bool Equals(LogMessage other) + { + return this.LogMessageId == other.LogMessageId && this.SourceEntity == other.SourceEntity && this.TargetEntity == other.TargetEntity; + } +} diff --git a/Dalamud/Game/Chat/LogMessageEntity.cs b/Dalamud/Game/Chat/LogMessageEntity.cs new file mode 100644 index 000000000..91e905928 --- /dev/null +++ b/Dalamud/Game/Chat/LogMessageEntity.cs @@ -0,0 +1,113 @@ +using System.Diagnostics.CodeAnalysis; + +using Dalamud.Data; +using Dalamud.Plugin.Services; + +using FFXIVClientStructs.FFXIV.Client.UI.Misc; + +using Lumina.Excel; +using Lumina.Excel.Sheets; +using Lumina.Text.ReadOnly; + +namespace Dalamud.Game.Chat; + +/// +/// Interface representing an entity related to a log message. +/// +public interface ILogMessageEntity : IEquatable +{ + /// + /// Gets the name of this entity. + /// + ReadOnlySeString Name { get; } + + /// + /// Gets the ID of the homeworld of this entity, if it is a player. + /// + ushort HomeWorldId { get; } + + /// + /// Gets the homeworld of this entity, if it is a player. + /// + RowRef HomeWorld { get; } + + /// + /// Gets the ObjStr ID of this entity, if not a player. See . + /// + uint ObjStrId { get; } + + /// + /// Gets a value indicating whether this entity is a player. + /// + bool IsPlayer { get; } +} + +/// +/// This struct represents an entity related to a log message. +/// +/// A pointer to the log message item. +/// If represents the source entity of the log message, otherwise represents the target entity. +internal unsafe readonly struct LogMessageEntity(LogMessageQueueItem* ptr, bool source) : ILogMessageEntity +{ + /// + public ReadOnlySeString Name => new(this.NameSpan[..this.NameSpan.IndexOf((byte)0)]); + + /// + public ushort HomeWorldId => source ? ptr->SourceHomeWorld : ptr->TargetHomeWorld; + + /// + public RowRef HomeWorld => LuminaUtils.CreateRef(this.HomeWorldId); + + /// + public uint ObjStrId => source ? ptr->SourceObjStrId : ptr->TargetObjStrId; + + /// + public bool IsPlayer => source ? ptr->SourceIsPlayer : ptr->TargetIsPlayer; + + /// + /// Gets the Span containing the raw name of this entity. + /// + internal Span NameSpan => source ? ptr->SourceName : ptr->TargetName; + + /// + /// Gets the kind of the entity. + /// + internal byte Kind => source ? (byte)ptr->SourceKind : (byte)ptr->TargetKind; + + /// + /// Gets the Sex of this entity. + /// + internal byte Sex => source ? ptr->SourceSex : ptr->TargetSex; + + /// + /// Gets a value indicating whether this entity is the source entity of a log message. + /// + internal bool IsSourceEntity => source; + + public static bool operator ==(LogMessageEntity x, LogMessageEntity y) => x.Equals(y); + + public static bool operator !=(LogMessageEntity x, LogMessageEntity y) => !(x == y); + + /// + public bool Equals(ILogMessageEntity other) + { + return other is LogMessageEntity entity && this.Equals(entity); + } + + /// + public override bool Equals([NotNullWhen(true)] object? obj) + { + return obj is LogMessageEntity entity && this.Equals(entity); + } + + /// + public override int GetHashCode() + { + return HashCode.Combine(this.Name, this.HomeWorldId, this.ObjStrId, this.Sex, this.IsPlayer); + } + + private bool Equals(LogMessageEntity other) + { + return this.Name == other.Name && this.HomeWorldId == other.HomeWorldId && this.ObjStrId == other.ObjStrId && this.Kind == other.Kind && this.Sex == other.Sex && this.IsPlayer == other.IsPlayer; + } +} diff --git a/Dalamud/Game/ChatHandlers.cs b/Dalamud/Game/ChatHandlers.cs index 279bf46e5..2d7d3c83a 100644 --- a/Dalamud/Game/ChatHandlers.cs +++ b/Dalamud/Game/ChatHandlers.cs @@ -1,5 +1,4 @@ using System.Linq; -using System.Reflection; using System.Text.RegularExpressions; using CheapLoc; @@ -23,7 +22,7 @@ namespace Dalamud.Game; [ServiceManager.EarlyLoadedService] internal partial class ChatHandlers : IServiceType { - private static readonly ModuleLog Log = new("ChatHandlers"); + private static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceDependency] private readonly DalamudConfiguration configuration = Service.Get(); diff --git a/Dalamud/Game/ClientState/Aetherytes/AetheryteList.cs b/Dalamud/Game/ClientState/Aetherytes/AetheryteList.cs index 12a629958..2df64b73b 100644 --- a/Dalamud/Game/ClientState/Aetherytes/AetheryteList.cs +++ b/Dalamud/Game/ClientState/Aetherytes/AetheryteList.cs @@ -8,6 +8,7 @@ using Dalamud.Plugin.Services; using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.Game.UI; + using Serilog; namespace Dalamud.Game.ClientState.Aetherytes; diff --git a/Dalamud/Game/ClientState/ClientState.cs b/Dalamud/Game/ClientState/ClientState.cs index f7c0b75ed..304dde82c 100644 --- a/Dalamud/Game/ClientState/ClientState.cs +++ b/Dalamud/Game/ClientState/ClientState.cs @@ -33,7 +33,7 @@ namespace Dalamud.Game.ClientState; [ServiceManager.EarlyLoadedService] internal sealed class ClientState : IInternalDisposableService, IClientState { - private static readonly ModuleLog Log = new("ClientState"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly GameLifecycle lifecycle; private readonly ClientStateAddressResolver address; diff --git a/Dalamud/Game/ClientState/GamePad/GamepadState.cs b/Dalamud/Game/ClientState/GamePad/GamepadState.cs index ab4f8a03f..3a8642cfa 100644 --- a/Dalamud/Game/ClientState/GamePad/GamepadState.cs +++ b/Dalamud/Game/ClientState/GamePad/GamepadState.cs @@ -5,7 +5,9 @@ using Dalamud.Hooking; using Dalamud.IoC; using Dalamud.IoC.Internal; using Dalamud.Plugin.Services; + using FFXIVClientStructs.FFXIV.Client.System.Input; + using Serilog; namespace Dalamud.Game.ClientState.GamePad; diff --git a/Dalamud/Game/ClientState/JobGauge/JobGauges.cs b/Dalamud/Game/ClientState/JobGauge/JobGauges.cs index 67429956b..5d6ba4554 100644 --- a/Dalamud/Game/ClientState/JobGauge/JobGauges.cs +++ b/Dalamud/Game/ClientState/JobGauge/JobGauges.cs @@ -37,7 +37,7 @@ internal class JobGauges : IServiceType, IJobGauges // Since the gauge itself reads from live memory, there isn't much downside to doing this. if (!this.cache.TryGetValue(typeof(T), out var gauge)) { - gauge = this.cache[typeof(T)] = (T)Activator.CreateInstance(typeof(T), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { this.Address }, null); + gauge = this.cache[typeof(T)] = (T)Activator.CreateInstance(typeof(T), BindingFlags.NonPublic | BindingFlags.Instance, null, [this.Address], null); } return (T)gauge; diff --git a/Dalamud/Game/ClientState/JobGauge/Types/BRDGauge.cs b/Dalamud/Game/ClientState/JobGauge/Types/BRDGauge.cs index 8880c3555..de73d540e 100644 --- a/Dalamud/Game/ClientState/JobGauge/Types/BRDGauge.cs +++ b/Dalamud/Game/ClientState/JobGauge/Types/BRDGauge.cs @@ -1,4 +1,5 @@ using Dalamud.Game.ClientState.JobGauge.Enums; + using FFXIVClientStructs.FFXIV.Client.Game.Gauge; namespace Dalamud.Game.ClientState.JobGauge.Types; @@ -82,12 +83,12 @@ public unsafe class BRDGauge : JobGaugeBaseSongFlags.HasFlag(SongFlags.MagesBalladCoda) ? Song.Mage : Song.None, this.Struct->SongFlags.HasFlag(SongFlags.ArmysPaeonCoda) ? Song.Army : Song.None, this.Struct->SongFlags.HasFlag(SongFlags.WanderersMinuetCoda) ? Song.Wanderer : Song.None, - }; + ]; } } } diff --git a/Dalamud/Game/ClientState/JobGauge/Types/DRKGauge.cs b/Dalamud/Game/ClientState/JobGauge/Types/DRKGauge.cs index c56d03db0..06d923cc4 100644 --- a/Dalamud/Game/ClientState/JobGauge/Types/DRKGauge.cs +++ b/Dalamud/Game/ClientState/JobGauge/Types/DRKGauge.cs @@ -1,4 +1,5 @@ using Dalamud.Game.ClientState.JobGauge.Enums; + using FFXIVClientStructs.FFXIV.Client.Game.Gauge; namespace Dalamud.Game.ClientState.JobGauge.Types; diff --git a/Dalamud/Game/ClientState/JobGauge/Types/PCTGauge.cs b/Dalamud/Game/ClientState/JobGauge/Types/PCTGauge.cs index d31a22702..9745bff7c 100644 --- a/Dalamud/Game/ClientState/JobGauge/Types/PCTGauge.cs +++ b/Dalamud/Game/ClientState/JobGauge/Types/PCTGauge.cs @@ -1,4 +1,4 @@ -using FFXIVClientStructs.FFXIV.Client.Game.Gauge; +using FFXIVClientStructs.FFXIV.Client.Game.Gauge; using CanvasFlags = Dalamud.Game.ClientState.JobGauge.Enums.CanvasFlags; using CreatureFlags = Dalamud.Game.ClientState.JobGauge.Enums.CreatureFlags; @@ -22,45 +22,45 @@ public unsafe class PCTGauge : JobGaugeBase /// /// Gets the use of subjective pallete. /// - public byte PalleteGauge => Struct->PalleteGauge; + public byte PalleteGauge => this.Struct->PalleteGauge; /// /// Gets the amount of paint the player has. /// - public byte Paint => Struct->Paint; + public byte Paint => this.Struct->Paint; /// /// Gets a value indicating whether a creature motif is drawn. /// - public bool CreatureMotifDrawn => Struct->CreatureMotifDrawn; + public bool CreatureMotifDrawn => this.Struct->CreatureMotifDrawn; /// /// Gets a value indicating whether a weapon motif is drawn. /// - public bool WeaponMotifDrawn => Struct->WeaponMotifDrawn; + public bool WeaponMotifDrawn => this.Struct->WeaponMotifDrawn; /// /// Gets a value indicating whether a landscape motif is drawn. /// - public bool LandscapeMotifDrawn => Struct->LandscapeMotifDrawn; + public bool LandscapeMotifDrawn => this.Struct->LandscapeMotifDrawn; /// /// Gets a value indicating whether a moogle portrait is ready. /// - public bool MooglePortraitReady => Struct->MooglePortraitReady; + public bool MooglePortraitReady => this.Struct->MooglePortraitReady; /// /// Gets a value indicating whether a madeen portrait is ready. /// - public bool MadeenPortraitReady => Struct->MadeenPortraitReady; + public bool MadeenPortraitReady => this.Struct->MadeenPortraitReady; /// /// Gets which creature flags are present. /// - public CreatureFlags CreatureFlags => (CreatureFlags)Struct->CreatureFlags; + public CreatureFlags CreatureFlags => (CreatureFlags)this.Struct->CreatureFlags; /// /// Gets which canvas flags are present. /// - public CanvasFlags CanvasFlags => (CanvasFlags)Struct->CanvasFlags; + public CanvasFlags CanvasFlags => (CanvasFlags)this.Struct->CanvasFlags; } diff --git a/Dalamud/Game/ClientState/JobGauge/Types/SMNGauge.cs b/Dalamud/Game/ClientState/JobGauge/Types/SMNGauge.cs index 899ea78eb..5f2d6e932 100644 --- a/Dalamud/Game/ClientState/JobGauge/Types/SMNGauge.cs +++ b/Dalamud/Game/ClientState/JobGauge/Types/SMNGauge.cs @@ -1,4 +1,5 @@ using Dalamud.Game.ClientState.JobGauge.Enums; + using FFXIVClientStructs.FFXIV.Client.Game.Gauge; namespace Dalamud.Game.ClientState.JobGauge.Types; diff --git a/Dalamud/Game/ClientState/JobGauge/Types/VPRGauge.cs b/Dalamud/Game/ClientState/JobGauge/Types/VPRGauge.cs index 3c822c7d7..625ecde24 100644 --- a/Dalamud/Game/ClientState/JobGauge/Types/VPRGauge.cs +++ b/Dalamud/Game/ClientState/JobGauge/Types/VPRGauge.cs @@ -1,7 +1,5 @@ using FFXIVClientStructs.FFXIV.Client.Game.Gauge; -using Reloaded.Memory; - using DreadCombo = Dalamud.Game.ClientState.JobGauge.Enums.DreadCombo; using SerpentCombo = Dalamud.Game.ClientState.JobGauge.Enums.SerpentCombo; @@ -24,25 +22,25 @@ public unsafe class VPRGauge : JobGaugeBase /// /// Gets how many uses of uncoiled fury the player has. /// - public byte RattlingCoilStacks => Struct->RattlingCoilStacks; + public byte RattlingCoilStacks => this.Struct->RattlingCoilStacks; /// /// Gets Serpent Offering stacks and gauge. /// - public byte SerpentOffering => Struct->SerpentOffering; + public byte SerpentOffering => this.Struct->SerpentOffering; /// /// Gets value indicating the use of 1st, 2nd, 3rd, 4th generation and Ouroboros. /// - public byte AnguineTribute => Struct->AnguineTribute; + public byte AnguineTribute => this.Struct->AnguineTribute; /// /// Gets the last Weaponskill used in DreadWinder/Pit of Dread combo. /// - public DreadCombo DreadCombo => (DreadCombo)Struct->DreadCombo; + public DreadCombo DreadCombo => (DreadCombo)this.Struct->DreadCombo; /// /// Gets current ability for Serpent's Tail. /// - public SerpentCombo SerpentCombo => (SerpentCombo)Struct->SerpentCombo; + public SerpentCombo SerpentCombo => (SerpentCombo)this.Struct->SerpentCombo; } diff --git a/Dalamud/Game/ClientState/Objects/TargetManager.cs b/Dalamud/Game/ClientState/Objects/TargetManager.cs index a6432e242..5f317d077 100644 --- a/Dalamud/Game/ClientState/Objects/TargetManager.cs +++ b/Dalamud/Game/ClientState/Objects/TargetManager.cs @@ -30,50 +30,50 @@ internal sealed unsafe class TargetManager : IServiceType, ITargetManager /// public IGameObject? Target { - get => this.objectTable.CreateObjectReference((IntPtr)Struct->GetHardTarget()); - set => Struct->SetHardTarget((FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address); + get => this.objectTable.CreateObjectReference((IntPtr)this.Struct->GetHardTarget()); + set => this.Struct->SetHardTarget((FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address); } /// public IGameObject? MouseOverTarget { - get => this.objectTable.CreateObjectReference((IntPtr)Struct->MouseOverTarget); - set => Struct->MouseOverTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; + get => this.objectTable.CreateObjectReference((IntPtr)this.Struct->MouseOverTarget); + set => this.Struct->MouseOverTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; } /// public IGameObject? FocusTarget { - get => this.objectTable.CreateObjectReference((IntPtr)Struct->FocusTarget); - set => Struct->FocusTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; + get => this.objectTable.CreateObjectReference((IntPtr)this.Struct->FocusTarget); + set => this.Struct->FocusTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; } /// public IGameObject? PreviousTarget { - get => this.objectTable.CreateObjectReference((IntPtr)Struct->PreviousTarget); - set => Struct->PreviousTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; + get => this.objectTable.CreateObjectReference((IntPtr)this.Struct->PreviousTarget); + set => this.Struct->PreviousTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; } /// public IGameObject? SoftTarget { - get => this.objectTable.CreateObjectReference((IntPtr)Struct->GetSoftTarget()); - set => Struct->SetSoftTarget((FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address); + get => this.objectTable.CreateObjectReference((IntPtr)this.Struct->GetSoftTarget()); + set => this.Struct->SetSoftTarget((FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address); } /// public IGameObject? GPoseTarget { - get => this.objectTable.CreateObjectReference((IntPtr)Struct->GPoseTarget); - set => Struct->GPoseTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; + get => this.objectTable.CreateObjectReference((IntPtr)this.Struct->GPoseTarget); + set => this.Struct->GPoseTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; } /// public IGameObject? MouseOverNameplateTarget { - get => this.objectTable.CreateObjectReference((IntPtr)Struct->MouseOverNameplateTarget); - set => Struct->MouseOverNameplateTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; + get => this.objectTable.CreateObjectReference((IntPtr)this.Struct->MouseOverNameplateTarget); + set => this.Struct->MouseOverNameplateTarget = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)value?.Address; } private TargetSystem* Struct => TargetSystem.Instance(); diff --git a/Dalamud/Game/ClientState/Objects/Types/BattleChara.cs b/Dalamud/Game/ClientState/Objects/Types/BattleChara.cs index 238c81a72..37f1f5504 100644 --- a/Dalamud/Game/ClientState/Objects/Types/BattleChara.cs +++ b/Dalamud/Game/ClientState/Objects/Types/BattleChara.cs @@ -1,5 +1,4 @@ using Dalamud.Game.ClientState.Statuses; -using Dalamud.Utility; namespace Dalamud.Game.ClientState.Objects.Types; diff --git a/Dalamud/Game/ClientState/Objects/Types/Character.cs b/Dalamud/Game/ClientState/Objects/Types/Character.cs index a91ecc230..2002a16b8 100644 --- a/Dalamud/Game/ClientState/Objects/Types/Character.cs +++ b/Dalamud/Game/ClientState/Objects/Types/Character.cs @@ -1,9 +1,6 @@ -using System.Runtime.CompilerServices; - using Dalamud.Data; using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Game.Text.SeStringHandling; -using Dalamud.Memory; using Lumina.Excel; using Lumina.Excel.Sheets; diff --git a/Dalamud/Game/ClientState/Party/PartyList.cs b/Dalamud/Game/ClientState/Party/PartyList.cs index 90959f926..0326350d2 100644 --- a/Dalamud/Game/ClientState/Party/PartyList.cs +++ b/Dalamud/Game/ClientState/Party/PartyList.cs @@ -47,7 +47,7 @@ internal sealed unsafe partial class PartyList : IServiceType, IPartyList public unsafe nint GroupManagerAddress => (nint)CSGroupManager.Instance(); /// - public nint GroupListAddress => (nint)Unsafe.AsPointer(ref GroupManagerStruct->MainGroup.PartyMembers[0]); + public nint GroupListAddress => (nint)Unsafe.AsPointer(ref this.GroupManagerStruct->MainGroup.PartyMembers[0]); /// public nint AllianceListAddress => (nint)Unsafe.AsPointer(ref this.GroupManagerStruct->MainGroup.AllianceMembers[0]); diff --git a/Dalamud/Game/ClientState/Party/PartyMember.cs b/Dalamud/Game/ClientState/Party/PartyMember.cs index 84e3f21c8..843824318 100644 --- a/Dalamud/Game/ClientState/Party/PartyMember.cs +++ b/Dalamud/Game/ClientState/Party/PartyMember.cs @@ -6,6 +6,7 @@ using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Game.ClientState.Statuses; using Dalamud.Game.Text.SeStringHandling; + using Dalamud.Utility; using Lumina.Excel; diff --git a/Dalamud/Game/ClientState/Statuses/StatusList.cs b/Dalamud/Game/ClientState/Statuses/StatusList.cs index 43650a48c..2e8024ab8 100644 --- a/Dalamud/Game/ClientState/Statuses/StatusList.cs +++ b/Dalamud/Game/ClientState/Statuses/StatusList.cs @@ -38,7 +38,7 @@ public sealed unsafe partial class StatusList /// /// Gets the amount of status effect slots the actor has. /// - public int Length => Struct->NumValidStatuses; + public int Length => this.Struct->NumValidStatuses; private static int StatusSize { get; } = Marshal.SizeOf(); diff --git a/Dalamud/Game/Command/CommandManager.cs b/Dalamud/Game/Command/CommandManager.cs index 01442c409..e9abb7336 100644 --- a/Dalamud/Game/Command/CommandManager.cs +++ b/Dalamud/Game/Command/CommandManager.cs @@ -24,7 +24,7 @@ namespace Dalamud.Game.Command; [ServiceManager.EarlyLoadedService] internal sealed unsafe class CommandManager : IInternalDisposableService, ICommandManager { - private static readonly ModuleLog Log = new("Command"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly ConcurrentDictionary commandMap = new(); private readonly ConcurrentDictionary<(string, IReadOnlyCommandInfo), string> commandAssemblyNameMap = new(); @@ -71,7 +71,7 @@ internal sealed unsafe class CommandManager : IInternalDisposableService, IComma if (separatorPosition + 1 >= content.Length) { // Remove the trailing space - command = content.Substring(0, separatorPosition); + command = content[..separatorPosition]; } else { @@ -262,12 +262,12 @@ internal sealed unsafe class CommandManager : IInternalDisposableService, IComma #pragma warning restore SA1015 internal class CommandManagerPluginScoped : IInternalDisposableService, ICommandManager { - private static readonly ModuleLog Log = new("Command"); + private static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceDependency] private readonly CommandManager commandManagerService = Service.Get(); - private readonly List pluginRegisteredCommands = new(); + private readonly List pluginRegisteredCommands = []; private readonly LocalPlugin pluginInfo; /// diff --git a/Dalamud/Game/Config/GameConfig.cs b/Dalamud/Game/Config/GameConfig.cs index 9579d84bc..a55056351 100644 --- a/Dalamud/Game/Config/GameConfig.cs +++ b/Dalamud/Game/Config/GameConfig.cs @@ -1,11 +1,13 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using Dalamud.Hooking; using Dalamud.IoC; using Dalamud.IoC.Internal; using Dalamud.Plugin.Services; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Common.Configuration; + using Serilog; namespace Dalamud.Game.Config; diff --git a/Dalamud/Game/Config/GameConfigSection.cs b/Dalamud/Game/Config/GameConfigSection.cs index 8ebab8a60..eb2f1107e 100644 --- a/Dalamud/Game/Config/GameConfigSection.cs +++ b/Dalamud/Game/Config/GameConfigSection.cs @@ -1,10 +1,12 @@ -using System.Collections.Concurrent; +using System.Collections.Concurrent; using System.Diagnostics; using System.Text; using Dalamud.Memory; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Common.Configuration; + using Serilog; namespace Dalamud.Game.Config; diff --git a/Dalamud/Game/Framework.cs b/Dalamud/Game/Framework.cs index 808bbce50..035745684 100644 --- a/Dalamud/Game/Framework.cs +++ b/Dalamud/Game/Framework.cs @@ -26,7 +26,7 @@ namespace Dalamud.Game; [ServiceManager.EarlyLoadedService] internal sealed class Framework : IInternalDisposableService, IFramework { - private static readonly ModuleLog Log = new("Framework"); + private static readonly ModuleLog Log = ModuleLog.Create(); private static readonly Stopwatch StatsStopwatch = new(); @@ -86,7 +86,7 @@ internal sealed class Framework : IInternalDisposableService, IFramework /// /// Gets the stats history mapping. /// - public static Dictionary> StatsHistory { get; } = new(); + public static Dictionary> StatsHistory { get; } = []; /// public DateTime LastUpdate { get; private set; } = DateTime.MinValue; @@ -106,7 +106,7 @@ internal sealed class Framework : IInternalDisposableService, IFramework /// /// Gets the list of update sub-delegates that didn't get updated this frame. /// - internal List NonUpdatedSubDelegates { get; private set; } = new(); + internal List NonUpdatedSubDelegates { get; private set; } = []; /// /// Gets or sets a value indicating whether to dispatch update events. @@ -212,11 +212,10 @@ internal sealed class Framework : IInternalDisposableService, IFramework if (cancellationToken == default) cancellationToken = this.FrameworkThreadTaskFactory.CancellationToken; return this.FrameworkThreadTaskFactory.ContinueWhenAll( - new[] - { + [ Task.Delay(delay, cancellationToken), this.DelayTicks(delayTicks, cancellationToken), - }, + ], _ => func(), cancellationToken, TaskContinuationOptions.HideScheduler, @@ -239,11 +238,10 @@ internal sealed class Framework : IInternalDisposableService, IFramework if (cancellationToken == default) cancellationToken = this.FrameworkThreadTaskFactory.CancellationToken; return this.FrameworkThreadTaskFactory.ContinueWhenAll( - new[] - { + [ Task.Delay(delay, cancellationToken), this.DelayTicks(delayTicks, cancellationToken), - }, + ], _ => action(), cancellationToken, TaskContinuationOptions.HideScheduler, @@ -266,11 +264,10 @@ internal sealed class Framework : IInternalDisposableService, IFramework if (cancellationToken == default) cancellationToken = this.FrameworkThreadTaskFactory.CancellationToken; return this.FrameworkThreadTaskFactory.ContinueWhenAll( - new[] - { + [ Task.Delay(delay, cancellationToken), this.DelayTicks(delayTicks, cancellationToken), - }, + ], _ => func(), cancellationToken, TaskContinuationOptions.HideScheduler, @@ -293,11 +290,10 @@ internal sealed class Framework : IInternalDisposableService, IFramework if (cancellationToken == default) cancellationToken = this.FrameworkThreadTaskFactory.CancellationToken; return this.FrameworkThreadTaskFactory.ContinueWhenAll( - new[] - { + [ Task.Delay(delay, cancellationToken), this.DelayTicks(delayTicks, cancellationToken), - }, + ], _ => func(), cancellationToken, TaskContinuationOptions.HideScheduler, @@ -333,7 +329,7 @@ internal sealed class Framework : IInternalDisposableService, IFramework internal static void AddToStats(string key, double ms) { if (!StatsHistory.ContainsKey(key)) - StatsHistory.Add(key, new List()); + StatsHistory.Add(key, []); StatsHistory[key].Add(ms); diff --git a/Dalamud/Game/Gui/ChatGui.cs b/Dalamud/Game/Gui/ChatGui.cs index 30e2b676c..c514752da 100644 --- a/Dalamud/Game/Gui/ChatGui.cs +++ b/Dalamud/Game/Gui/ChatGui.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Dalamud.Configuration.Internal; @@ -37,14 +38,16 @@ namespace Dalamud.Game.Gui; [ServiceManager.EarlyLoadedService] internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui { - private static readonly ModuleLog Log = new("ChatGui"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly Queue chatQueue = new(); - private readonly Dictionary<(string PluginName, uint CommandId), Action> dalamudLinkHandlers = new(); + private readonly Dictionary<(string PluginName, uint CommandId), Action> dalamudLinkHandlers = []; + private readonly List seenLogMessageObjects = []; private readonly Hook printMessageHook; private readonly Hook inventoryItemCopyHook; private readonly Hook handleLinkClickHook; + private readonly Hook handleLogModuleUpdate; [ServiceManager.ServiceDependency] private readonly DalamudConfiguration configuration = Service.Get(); @@ -58,10 +61,12 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui this.printMessageHook = Hook.FromAddress(RaptureLogModule.Addresses.PrintMessage.Value, this.HandlePrintMessageDetour); this.inventoryItemCopyHook = Hook.FromAddress((nint)InventoryItem.StaticVirtualTablePointer->Copy, this.InventoryItemCopyDetour); this.handleLinkClickHook = Hook.FromAddress(LogViewer.Addresses.HandleLinkClick.Value, this.HandleLinkClickDetour); + this.handleLogModuleUpdate = Hook.FromAddress(RaptureLogModule.Addresses.Update.Value, this.UpdateDetour); this.printMessageHook.Enable(); this.inventoryItemCopyHook.Enable(); this.handleLinkClickHook.Enable(); + this.handleLogModuleUpdate.Enable(); } [UnmanagedFunctionPointer(CallingConvention.ThisCall)] @@ -79,6 +84,9 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui /// public event IChatGui.OnMessageUnhandledDelegate? ChatMessageUnhandled; + /// + public event IChatGui.OnLogMessageDelegate? LogMessage; + /// public uint LastLinkedItemId { get; private set; } @@ -110,6 +118,7 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui this.printMessageHook.Dispose(); this.inventoryItemCopyHook.Dispose(); this.handleLinkClickHook.Dispose(); + this.handleLogModuleUpdate.Dispose(); } #region DalamudSeString @@ -493,6 +502,46 @@ internal sealed unsafe class ChatGui : IInternalDisposableService, IChatGui Log.Error(ex, "Exception in HandleLinkClickDetour"); } } + + private void UpdateDetour(RaptureLogModule* thisPtr) + { + try + { + foreach (ref var item in thisPtr->LogMessageQueue) + { + var logMessage = new Chat.LogMessage((LogMessageQueueItem*)Unsafe.AsPointer(ref item)); + + // skip any entries that survived the previous Update call as the event was already called for them + if (this.seenLogMessageObjects.Contains(logMessage.Address)) + continue; + + foreach (var action in Delegate.EnumerateInvocationList(this.LogMessage)) + { + try + { + action(logMessage); + } + catch (Exception e) + { + Log.Error(e, "Could not invoke registered OnLogMessageDelegate for {Name}", action.Method); + } + } + } + + this.handleLogModuleUpdate.Original(thisPtr); + + // record the log messages for that we already called the event, but are still in the queue + this.seenLogMessageObjects.Clear(); + foreach (ref var item in thisPtr->LogMessageQueue) + { + this.seenLogMessageObjects.Add((nint)Unsafe.AsPointer(ref item)); + } + } + catch (Exception ex) + { + Log.Error(ex, "Exception in UpdateDetour"); + } + } } /// @@ -521,6 +570,7 @@ internal class ChatGuiPluginScoped : IInternalDisposableService, IChatGui this.chatGuiService.CheckMessageHandled += this.OnCheckMessageForward; this.chatGuiService.ChatMessageHandled += this.OnMessageHandledForward; this.chatGuiService.ChatMessageUnhandled += this.OnMessageUnhandledForward; + this.chatGuiService.LogMessage += this.OnLogMessageForward; } /// @@ -535,6 +585,9 @@ internal class ChatGuiPluginScoped : IInternalDisposableService, IChatGui /// public event IChatGui.OnMessageUnhandledDelegate? ChatMessageUnhandled; + /// + public event IChatGui.OnLogMessageDelegate? LogMessage; + /// public uint LastLinkedItemId => this.chatGuiService.LastLinkedItemId; @@ -551,11 +604,13 @@ internal class ChatGuiPluginScoped : IInternalDisposableService, IChatGui this.chatGuiService.CheckMessageHandled -= this.OnCheckMessageForward; this.chatGuiService.ChatMessageHandled -= this.OnMessageHandledForward; this.chatGuiService.ChatMessageUnhandled -= this.OnMessageUnhandledForward; + this.chatGuiService.LogMessage -= this.OnLogMessageForward; this.ChatMessage = null; this.CheckMessageHandled = null; this.ChatMessageHandled = null; this.ChatMessageUnhandled = null; + this.LogMessage = null; } /// @@ -609,4 +664,7 @@ internal class ChatGuiPluginScoped : IInternalDisposableService, IChatGui private void OnMessageUnhandledForward(XivChatType type, int timestamp, SeString sender, SeString message) => this.ChatMessageUnhandled?.Invoke(type, timestamp, sender, message); + + private void OnLogMessageForward(Chat.ILogMessage message) + => this.LogMessage?.Invoke(message); } diff --git a/Dalamud/Game/Gui/ContextMenu/ContextMenu.cs b/Dalamud/Game/Gui/ContextMenu/ContextMenu.cs index aada374ec..0b306f093 100644 --- a/Dalamud/Game/Gui/ContextMenu/ContextMenu.cs +++ b/Dalamud/Game/Gui/ContextMenu/ContextMenu.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Threading; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; @@ -28,7 +29,7 @@ namespace Dalamud.Game.Gui.ContextMenu; [ServiceManager.EarlyLoadedService] internal sealed unsafe class ContextMenu : IInternalDisposableService, IContextMenu { - private static readonly ModuleLog Log = new("ContextMenu"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly Hook atkModuleVf22OpenAddonByAgentHook; private readonly Hook addonContextMenuOnMenuSelectedHook; @@ -53,7 +54,7 @@ internal sealed unsafe class ContextMenu : IInternalDisposableService, IContextM private Dictionary> MenuItems { get; } = []; - private object MenuItemsLock { get; } = new(); + private Lock MenuItemsLock { get; } = new(); private AgentInterface* SelectedAgent { get; set; } diff --git a/Dalamud/Game/Gui/ContextMenu/MenuArgs.cs b/Dalamud/Game/Gui/ContextMenu/MenuArgs.cs index 39fd1c52c..900935ed5 100644 --- a/Dalamud/Game/Gui/ContextMenu/MenuArgs.cs +++ b/Dalamud/Game/Gui/ContextMenu/MenuArgs.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using Dalamud.Memory; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.UI.Agent; diff --git a/Dalamud/Game/Gui/Dtr/DtrBar.cs b/Dalamud/Game/Gui/Dtr/DtrBar.cs index 2235c5ade..5663d0748 100644 --- a/Dalamud/Game/Gui/Dtr/DtrBar.cs +++ b/Dalamud/Game/Gui/Dtr/DtrBar.cs @@ -30,7 +30,7 @@ internal sealed unsafe class DtrBar : IInternalDisposableService, IDtrBar { private const uint BaseNodeId = 1000; - private static readonly ModuleLog Log = new("DtrBar"); + private static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceDependency] private readonly Framework framework = Service.Get(); @@ -54,7 +54,7 @@ internal sealed unsafe class DtrBar : IInternalDisposableService, IDtrBar private readonly ReaderWriterLockSlim entriesLock = new(); private readonly List entries = []; - private readonly Dictionary> eventHandles = new(); + private readonly Dictionary> eventHandles = []; private ImmutableList? entriesReadOnlyCopy; @@ -516,7 +516,7 @@ internal sealed unsafe class DtrBar : IInternalDisposableService, IDtrBar var node = data.TextNode = this.MakeNode(++this.runningNodeIds); - this.eventHandles.TryAdd(node->NodeId, new List()); + this.eventHandles.TryAdd(node->NodeId, []); this.eventHandles[node->NodeId].AddRange(new List { this.uiEventManager.AddEvent(AddonEventManager.DalamudInternalKey, (nint)dtr, (nint)node, AddonEventType.MouseOver, this.DtrEventHandler), diff --git a/Dalamud/Game/Gui/Dtr/DtrBarEntry.cs b/Dalamud/Game/Gui/Dtr/DtrBarEntry.cs index 138484580..e0bd8fd49 100644 --- a/Dalamud/Game/Gui/Dtr/DtrBarEntry.cs +++ b/Dalamud/Game/Gui/Dtr/DtrBarEntry.cs @@ -1,7 +1,6 @@ -using System.Numerics; +using System.Numerics; using Dalamud.Configuration.Internal; -using Dalamud.Game.Addon.Events.EventDataTypes; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Plugin.Internal.Types; using Dalamud.Utility; diff --git a/Dalamud/Game/Gui/GameGui.cs b/Dalamud/Game/Gui/GameGui.cs index 3d17aad86..3b0f6eb66 100644 --- a/Dalamud/Game/Gui/GameGui.cs +++ b/Dalamud/Game/Gui/GameGui.cs @@ -32,7 +32,7 @@ namespace Dalamud.Game.Gui; [ServiceManager.EarlyLoadedService] internal sealed unsafe class GameGui : IInternalDisposableService, IGameGui { - private static readonly ModuleLog Log = new("GameGui"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly GameGuiAddressResolver address; diff --git a/Dalamud/Game/Gui/NamePlate/NamePlateUpdateHandler.cs b/Dalamud/Game/Gui/NamePlate/NamePlateUpdateHandler.cs index a8c6ff3c1..e197e2360 100644 --- a/Dalamud/Game/Gui/NamePlate/NamePlateUpdateHandler.cs +++ b/Dalamud/Game/Gui/NamePlate/NamePlateUpdateHandler.cs @@ -427,8 +427,8 @@ internal unsafe class NamePlateUpdateHandler : INamePlateUpdateHandler /// public int VisibilityFlags { - get => ObjectData->VisibilityFlags; - set => ObjectData->VisibilityFlags = value; + get => this.ObjectData->VisibilityFlags; + set => this.ObjectData->VisibilityFlags = value; } /// diff --git a/Dalamud/Game/Gui/PartyFinder/Types/JobFlagsExtensions.cs b/Dalamud/Game/Gui/PartyFinder/Types/JobFlagsExtensions.cs index 1c78c871b..d7ab3080b 100644 --- a/Dalamud/Game/Gui/PartyFinder/Types/JobFlagsExtensions.cs +++ b/Dalamud/Game/Gui/PartyFinder/Types/JobFlagsExtensions.cs @@ -1,4 +1,5 @@ using Dalamud.Plugin.Services; + using Lumina.Excel.Sheets; namespace Dalamud.Game.Gui.PartyFinder.Types; diff --git a/Dalamud/Game/Gui/PartyFinder/Types/PartyFinderSlot.cs b/Dalamud/Game/Gui/PartyFinder/Types/PartyFinderSlot.cs index 3d1e496fc..953e575d4 100644 --- a/Dalamud/Game/Gui/PartyFinder/Types/PartyFinderSlot.cs +++ b/Dalamud/Game/Gui/PartyFinder/Types/PartyFinderSlot.cs @@ -23,23 +23,7 @@ public class PartyFinderSlot /// /// Gets a list of jobs that this slot is accepting. /// - public IReadOnlyCollection Accepting - { - get - { - if (this.listAccepting != null) - { - return this.listAccepting; - } - - this.listAccepting = Enum.GetValues(typeof(JobFlags)) - .Cast() - .Where(flag => this[flag]) - .ToArray(); - - return this.listAccepting; - } - } + public IReadOnlyCollection Accepting => this.listAccepting ??= Enum.GetValues().Where(flag => this[flag]).ToArray(); /// /// Tests if this slot is accepting a job. diff --git a/Dalamud/Game/Internal/DalamudAtkTweaks.cs b/Dalamud/Game/Internal/DalamudAtkTweaks.cs index 466401ef3..24fa88023 100644 --- a/Dalamud/Game/Internal/DalamudAtkTweaks.cs +++ b/Dalamud/Game/Internal/DalamudAtkTweaks.cs @@ -22,7 +22,7 @@ namespace Dalamud.Game.Internal; [ServiceManager.EarlyLoadedService] internal sealed unsafe class DalamudAtkTweaks : IInternalDisposableService { - private static readonly ModuleLog Log = new("DalamudAtkTweaks"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly Hook hookAgentHudOpenSystemMenu; diff --git a/Dalamud/Game/Inventory/GameInventory.cs b/Dalamud/Game/Inventory/GameInventory.cs index 5390c2707..2cfacfad0 100644 --- a/Dalamud/Game/Inventory/GameInventory.cs +++ b/Dalamud/Game/Inventory/GameInventory.cs @@ -18,15 +18,15 @@ namespace Dalamud.Game.Inventory; [ServiceManager.EarlyLoadedService] internal class GameInventory : IInternalDisposableService { - private readonly List subscribersPendingChange = new(); - private readonly List subscribers = new(); + private readonly List subscribersPendingChange = []; + private readonly List subscribers = []; - private readonly List addedEvents = new(); - private readonly List removedEvents = new(); - private readonly List changedEvents = new(); - private readonly List movedEvents = new(); - private readonly List splitEvents = new(); - private readonly List mergedEvents = new(); + private readonly List addedEvents = []; + private readonly List removedEvents = []; + private readonly List changedEvents = []; + private readonly List movedEvents = []; + private readonly List splitEvents = []; + private readonly List mergedEvents = []; [ServiceManager.ServiceDependency] private readonly Framework framework = Service.Get(); @@ -151,7 +151,7 @@ internal class GameInventory : IInternalDisposableService bool isNew; lock (this.subscribersPendingChange) { - isNew = this.subscribersPendingChange.Any() && !this.subscribers.Any(); + isNew = this.subscribersPendingChange.Count != 0 && this.subscribers.Count == 0; this.subscribers.Clear(); this.subscribers.AddRange(this.subscribersPendingChange); this.subscribersChanged = false; @@ -348,7 +348,7 @@ internal class GameInventory : IInternalDisposableService #pragma warning restore SA1015 internal class GameInventoryPluginScoped : IInternalDisposableService, IGameInventory { - private static readonly ModuleLog Log = new(nameof(GameInventoryPluginScoped)); + private static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceDependency] private readonly GameInventory gameInventoryService = Service.Get(); diff --git a/Dalamud/Game/Marketboard/MarketBoard.cs b/Dalamud/Game/Marketboard/MarketBoard.cs index 962e0010e..563a5bc4a 100644 --- a/Dalamud/Game/Marketboard/MarketBoard.cs +++ b/Dalamud/Game/Marketboard/MarketBoard.cs @@ -1,5 +1,3 @@ -using System.Linq; - using Dalamud.Game.Network.Internal; using Dalamud.Game.Network.Structures; using Dalamud.IoC; @@ -95,7 +93,7 @@ internal class MarketBoard : IInternalDisposableService, IMarketBoard #pragma warning restore SA1015 internal class MarketBoardPluginScoped : IInternalDisposableService, IMarketBoard { - private static readonly ModuleLog Log = new(nameof(MarketBoardPluginScoped)); + private static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceDependency] private readonly MarketBoard marketBoardService = Service.Get(); diff --git a/Dalamud/Game/NativeWrapper/AtkValuePtr.cs b/Dalamud/Game/NativeWrapper/AtkValuePtr.cs index a47483a66..b274d388b 100644 --- a/Dalamud/Game/NativeWrapper/AtkValuePtr.cs +++ b/Dalamud/Game/NativeWrapper/AtkValuePtr.cs @@ -89,7 +89,7 @@ public readonly unsafe struct AtkValuePtr(nint address) : IEquatable public unsafe bool TryGet([NotNullWhen(true)] out T? result) where T : struct { - object? value = this.GetValue(); + var value = this.GetValue(); if (value is T typed) { result = typed; diff --git a/Dalamud/Game/Network/GameNetwork.cs b/Dalamud/Game/Network/GameNetwork.cs index be464ef34..b8c91b235 100644 --- a/Dalamud/Game/Network/GameNetwork.cs +++ b/Dalamud/Game/Network/GameNetwork.cs @@ -2,9 +2,6 @@ using System.Runtime.InteropServices; using Dalamud.Configuration.Internal; using Dalamud.Hooking; -using Dalamud.IoC; -using Dalamud.IoC.Internal; -using Dalamud.Plugin.Services; using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.Network; diff --git a/Dalamud/Game/Network/Internal/MarketBoardUploaders/Universalis/UniversalisMarketBoardUploader.cs b/Dalamud/Game/Network/Internal/MarketBoardUploaders/Universalis/UniversalisMarketBoardUploader.cs index 7ecb9c397..67769e4ca 100644 --- a/Dalamud/Game/Network/Internal/MarketBoardUploaders/Universalis/UniversalisMarketBoardUploader.cs +++ b/Dalamud/Game/Network/Internal/MarketBoardUploaders/Universalis/UniversalisMarketBoardUploader.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; @@ -8,6 +7,7 @@ using Dalamud.Game.Network.Structures; using Dalamud.Networking.Http; using Newtonsoft.Json; + using Serilog; namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis; @@ -64,7 +64,7 @@ internal class UniversalisMarketBoardUploader : IMarketBoardUploader PricePerUnit = marketBoardItemListing.PricePerUnit, Quantity = marketBoardItemListing.ItemQuantity, RetainerCity = marketBoardItemListing.RetainerCityId, - Materia = new List(), + Materia = [], }; #pragma warning restore CS0618 // Type or member is obsolete diff --git a/Dalamud/Game/Network/Internal/NetworkHandlers.cs b/Dalamud/Game/Network/Internal/NetworkHandlers.cs index 6a6d73b33..5ca7da54a 100644 --- a/Dalamud/Game/Network/Internal/NetworkHandlers.cs +++ b/Dalamud/Game/Network/Internal/NetworkHandlers.cs @@ -33,7 +33,7 @@ namespace Dalamud.Game.Network.Internal; [ServiceManager.EarlyLoadedService] internal unsafe class NetworkHandlers : IInternalDisposableService { - private readonly IMarketBoardUploader uploader; + private readonly UniversalisMarketBoardUploader uploader; private readonly IDisposable handleMarketBoardItemRequest; private readonly IDisposable handleMarketTaxRates; @@ -419,7 +419,7 @@ internal unsafe class NetworkHandlers : IInternalDisposableService private IDisposable HandleMarketBoardItemRequest() { - void LogStartObserved(MarketBoardItemRequest request) + static void LogStartObserved(MarketBoardItemRequest request) { Log.Verbose("Observed start of request for item with {NumListings} expected listings", request.AmountToArrive); } @@ -448,7 +448,7 @@ internal unsafe class NetworkHandlers : IInternalDisposableService private void UploadMarketBoardData( MarketBoardItemRequest request, (uint CatalogId, ICollection Sales) sales, - ICollection listings, + List listings, ulong uploaderId, uint worldId) { diff --git a/Dalamud/Game/SigScanner.cs b/Dalamud/Game/SigScanner.cs index 262e98fa5..81fb8a3a3 100644 --- a/Dalamud/Game/SigScanner.cs +++ b/Dalamud/Game/SigScanner.cs @@ -11,7 +11,9 @@ using System.Threading; using Dalamud.Plugin.Services; using Iced.Intel; + using Newtonsoft.Json; + using Serilog; namespace Dalamud.Game; diff --git a/Dalamud/Game/Text/Evaluator/SeStringEvaluator.cs b/Dalamud/Game/Text/Evaluator/SeStringEvaluator.cs index f05c15263..58b9011e6 100644 --- a/Dalamud/Game/Text/Evaluator/SeStringEvaluator.cs +++ b/Dalamud/Game/Text/Evaluator/SeStringEvaluator.cs @@ -48,7 +48,7 @@ namespace Dalamud.Game.Text.Evaluator; [ResolveVia] internal class SeStringEvaluator : IServiceType, ISeStringEvaluator { - private static readonly ModuleLog Log = new("SeStringEvaluator"); + private static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceDependency] private readonly ClientState.ClientState clientState = Service.Get(); @@ -244,154 +244,67 @@ internal class SeStringEvaluator : IServiceType, ISeStringEvaluator // if (context.HandlePayload(payload, in context)) // return true; - switch (payload.MacroCode) + return payload.MacroCode switch { - case MacroCode.SetResetTime: - return this.TryResolveSetResetTime(in context, payload); - - case MacroCode.SetTime: - return this.TryResolveSetTime(in context, payload); - - case MacroCode.If: - return this.TryResolveIf(in context, payload); - - case MacroCode.Switch: - return this.TryResolveSwitch(in context, payload); - - case MacroCode.SwitchPlatform: - return this.TryResolveSwitchPlatform(in context, payload); - - case MacroCode.PcName: - return this.TryResolvePcName(in context, payload); - - case MacroCode.IfPcGender: - return this.TryResolveIfPcGender(in context, payload); - - case MacroCode.IfPcName: - return this.TryResolveIfPcName(in context, payload); - - // case MacroCode.Josa: - // case MacroCode.Josaro: - - case MacroCode.IfSelf: - return this.TryResolveIfSelf(in context, payload); - - // case MacroCode.NewLine: // pass through - // case MacroCode.Wait: // pass through - // case MacroCode.Icon: // pass through - - case MacroCode.Color: - return this.TryResolveColor(in context, payload); - - case MacroCode.EdgeColor: - return this.TryResolveEdgeColor(in context, payload); - - case MacroCode.ShadowColor: - return this.TryResolveShadowColor(in context, payload); - - // case MacroCode.SoftHyphen: // pass through - // case MacroCode.Key: - // case MacroCode.Scale: - - case MacroCode.Bold: - return this.TryResolveBold(in context, payload); - - case MacroCode.Italic: - return this.TryResolveItalic(in context, payload); - - // case MacroCode.Edge: - // case MacroCode.Shadow: - // case MacroCode.NonBreakingSpace: // pass through - // case MacroCode.Icon2: // pass through - // case MacroCode.Hyphen: // pass through - - case MacroCode.Num: - return this.TryResolveNum(in context, payload); - - case MacroCode.Hex: - return this.TryResolveHex(in context, payload); - - case MacroCode.Kilo: - return this.TryResolveKilo(in context, payload); - - // case MacroCode.Byte: - - case MacroCode.Sec: - return this.TryResolveSec(in context, payload); - - // case MacroCode.Time: - - case MacroCode.Float: - return this.TryResolveFloat(in context, payload); - - // case MacroCode.Link: // pass through - - case MacroCode.Sheet: - return this.TryResolveSheet(in context, payload); - - case MacroCode.SheetSub: - return this.TryResolveSheetSub(in context, payload); - - case MacroCode.String: - return this.TryResolveString(in context, payload); - - case MacroCode.Caps: - return this.TryResolveCaps(in context, payload); - - case MacroCode.Head: - return this.TryResolveHead(in context, payload); - - case MacroCode.Split: - return this.TryResolveSplit(in context, payload); - - case MacroCode.HeadAll: - return this.TryResolveHeadAll(in context, payload); - - case MacroCode.Fixed: - return this.TryResolveFixed(in context, payload); - - case MacroCode.Lower: - return this.TryResolveLower(in context, payload); - - case MacroCode.JaNoun: - return this.TryResolveNoun(ClientLanguage.Japanese, in context, payload); - - case MacroCode.EnNoun: - return this.TryResolveNoun(ClientLanguage.English, in context, payload); - - case MacroCode.DeNoun: - return this.TryResolveNoun(ClientLanguage.German, in context, payload); - - case MacroCode.FrNoun: - return this.TryResolveNoun(ClientLanguage.French, in context, payload); - - // case MacroCode.ChNoun: - - case MacroCode.LowerHead: - return this.TryResolveLowerHead(in context, payload); - - case MacroCode.ColorType: - return this.TryResolveColorType(in context, payload); - - case MacroCode.EdgeColorType: - return this.TryResolveEdgeColorType(in context, payload); - - // case MacroCode.Ruby: - - case MacroCode.Digit: - return this.TryResolveDigit(in context, payload); - - case MacroCode.Ordinal: - return this.TryResolveOrdinal(in context, payload); - - // case MacroCode.Sound: // pass through - - case MacroCode.LevelPos: - return this.TryResolveLevelPos(in context, payload); - - default: - return false; - } + MacroCode.SetResetTime => this.TryResolveSetResetTime(in context, payload), + MacroCode.SetTime => this.TryResolveSetTime(in context, payload), + MacroCode.If => this.TryResolveIf(in context, payload), + MacroCode.Switch => this.TryResolveSwitch(in context, payload), + MacroCode.SwitchPlatform => this.TryResolveSwitchPlatform(in context, payload), + MacroCode.PcName => this.TryResolvePcName(in context, payload), + MacroCode.IfPcGender => this.TryResolveIfPcGender(in context, payload), + MacroCode.IfPcName => this.TryResolveIfPcName(in context, payload), + // MacroCode.Josa + // MacroCode.Josaro + MacroCode.IfSelf => this.TryResolveIfSelf(in context, payload), + // MacroCode.NewLine (pass through) + // MacroCode.Wait (pass through) + // MacroCode.Icon (pass through) + MacroCode.Color => this.TryResolveColor(in context, payload), + MacroCode.EdgeColor => this.TryResolveEdgeColor(in context, payload), + MacroCode.ShadowColor => this.TryResolveShadowColor(in context, payload), + // MacroCode.SoftHyphen (pass through) + // MacroCode.Key + // MacroCode.Scale + MacroCode.Bold => this.TryResolveBold(in context, payload), + MacroCode.Italic => this.TryResolveItalic(in context, payload), + // MacroCode.Edge + // MacroCode.Shadow + // MacroCode.NonBreakingSpace (pass through) + // MacroCode.Icon2 (pass through) + // MacroCode.Hyphen (pass through) + MacroCode.Num => this.TryResolveNum(in context, payload), + MacroCode.Hex => this.TryResolveHex(in context, payload), + MacroCode.Kilo => this.TryResolveKilo(in context, payload), + // MacroCode.Byte + MacroCode.Sec => this.TryResolveSec(in context, payload), + // MacroCode.Time + MacroCode.Float => this.TryResolveFloat(in context, payload), + // MacroCode.Link (pass through) + MacroCode.Sheet => this.TryResolveSheet(in context, payload), + MacroCode.SheetSub => this.TryResolveSheetSub(in context, payload), + MacroCode.String => this.TryResolveString(in context, payload), + MacroCode.Caps => this.TryResolveCaps(in context, payload), + MacroCode.Head => this.TryResolveHead(in context, payload), + MacroCode.Split => this.TryResolveSplit(in context, payload), + MacroCode.HeadAll => this.TryResolveHeadAll(in context, payload), + MacroCode.Fixed => this.TryResolveFixed(in context, payload), + MacroCode.Lower => this.TryResolveLower(in context, payload), + MacroCode.JaNoun => this.TryResolveNoun(ClientLanguage.Japanese, in context, payload), + MacroCode.EnNoun => this.TryResolveNoun(ClientLanguage.English, in context, payload), + MacroCode.DeNoun => this.TryResolveNoun(ClientLanguage.German, in context, payload), + MacroCode.FrNoun => this.TryResolveNoun(ClientLanguage.French, in context, payload), + // MacroCode.ChNoun + MacroCode.LowerHead => this.TryResolveLowerHead(in context, payload), + MacroCode.ColorType => this.TryResolveColorType(in context, payload), + MacroCode.EdgeColorType => this.TryResolveEdgeColorType(in context, payload), + // MacroCode.Ruby + MacroCode.Digit => this.TryResolveDigit(in context, payload), + MacroCode.Ordinal => this.TryResolveOrdinal(in context, payload), + // MacroCode.Sound (pass through) + MacroCode.LevelPos => this.TryResolveLevelPos(in context, payload), + _ => false, + }; } private unsafe bool TryResolveSetResetTime(in SeStringContext context, in ReadOnlySePayloadSpan payload) @@ -932,7 +845,7 @@ internal class SeStringEvaluator : IServiceType, ISeStringEvaluator using var rssb = new RentedSeStringBuilder(); var sb = rssb.Builder; - sb.Append(this.EvaluateFromAddon(6, [rarity], context.Language)); + sb.Append(this.EvaluateFromAddon(6, [rarity], context.Language)); // appends colortype and edgecolortype if (!skipLink) sb.PushLink(LinkMacroPayloadType.Item, itemId, rarity, 0u); // arg3 = some LogMessage flag based on LogKind RowId? => "89 5C 24 20 E8 ?? ?? ?? ?? 48 8B 1F" @@ -955,6 +868,9 @@ internal class SeStringEvaluator : IServiceType, ISeStringEvaluator if (!skipLink) sb.PopLink(); + sb.PopEdgeColorType(); + sb.PopColorType(); + text = sb.ToReadOnlySeString(); } diff --git a/Dalamud/Game/Text/Noun/NounProcessor.cs b/Dalamud/Game/Text/Noun/NounProcessor.cs index 993d341df..c218bb26c 100644 --- a/Dalamud/Game/Text/Noun/NounProcessor.cs +++ b/Dalamud/Game/Text/Noun/NounProcessor.cs @@ -85,7 +85,7 @@ internal class NounProcessor : IServiceType private const int PronounColumnIdx = 6; private const int ArticleColumnIdx = 7; - private static readonly ModuleLog Log = new("NounProcessor"); + private static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceDependency] private readonly DataManager dataManager = Service.Get(); diff --git a/Dalamud/Game/Text/SeStringHandling/Payload.cs b/Dalamud/Game/Text/SeStringHandling/Payload.cs index c797c4a91..685ff517a 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payload.cs @@ -213,11 +213,10 @@ public abstract partial class Payload return payload; } - private static Payload DecodeText(BinaryReader reader) + private static TextPayload DecodeText(BinaryReader reader) { var payload = new TextPayload(); payload.DecodeImpl(reader, reader.BaseStream.Length); - return payload; } } @@ -382,7 +381,7 @@ public abstract partial class Payload { if (value < 0xCF) { - return new byte[] { (byte)(value + 1) }; + return [(byte)(value + 1)]; } var bytes = BitConverter.GetBytes(value); diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/IconPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/IconPayload.cs index 7963d422f..ad25de01d 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/IconPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/IconPayload.cs @@ -45,10 +45,10 @@ public class IconPayload : Payload { var indexBytes = MakeInteger((uint)this.Icon); var chunkLen = indexBytes.Length + 1; - var bytes = new List(new byte[] - { + var bytes = new List( + [ START_BYTE, (byte)SeStringChunkType.Icon, (byte)chunkLen, - }); + ]); bytes.AddRange(indexBytes); bytes.Add(END_BYTE); return bytes.ToArray(); diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/ItemPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/ItemPayload.cs index 0c1f75a1d..20f05958f 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/ItemPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/ItemPayload.cs @@ -8,6 +8,7 @@ using Dalamud.Utility; using Lumina.Excel; using Lumina.Excel.Sheets; + using Newtonsoft.Json; namespace Dalamud.Game.Text.SeStringHandling.Payloads; @@ -172,7 +173,7 @@ public class ItemPayload : Payload }; bytes.AddRange(idBytes); // unk - bytes.AddRange(new byte[] { 0x02, 0x01 }); + bytes.AddRange([0x02, 0x01]); // Links don't have to include the name, but if they do, it requires additional work if (hasName) @@ -183,17 +184,17 @@ public class ItemPayload : Payload nameLen += 4; // space plus 3 bytes for HQ symbol } - bytes.AddRange(new byte[] - { + bytes.AddRange( + [ 0xFF, // unk (byte)nameLen, - }); + ]); bytes.AddRange(Encoding.UTF8.GetBytes(this.displayName)); if (this.IsHQ) { // space and HQ symbol - bytes.AddRange(new byte[] { 0x20, 0xEE, 0x80, 0xBC }); + bytes.AddRange([0x20, 0xEE, 0x80, 0xBC]); } } diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/MapLinkPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/MapLinkPayload.cs index 7b672d07a..31cab41a1 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/MapLinkPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/MapLinkPayload.cs @@ -5,6 +5,7 @@ using Dalamud.Data; using Lumina.Excel; using Lumina.Excel.Sheets; + using Newtonsoft.Json; namespace Dalamud.Game.Text.SeStringHandling.Payloads; @@ -174,7 +175,7 @@ public class MapLinkPayload : Payload bytes.AddRange(yBytes); // unk - bytes.AddRange(new byte[] { 0xFF, 0x01, END_BYTE }); + bytes.AddRange([0xFF, 0x01, END_BYTE]); return bytes.ToArray(); } diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/NewLinePayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/NewLinePayload.cs index 0b090b3d6..8072c87f5 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/NewLinePayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/NewLinePayload.cs @@ -7,7 +7,7 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads; /// public class NewLinePayload : Payload, ITextProvider { - private readonly byte[] bytes = { START_BYTE, (byte)SeStringChunkType.NewLine, 0x01, END_BYTE }; + private readonly byte[] bytes = [START_BYTE, (byte)SeStringChunkType.NewLine, 0x01, END_BYTE]; /// /// Gets an instance of NewLinePayload. diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/PartyFinderPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/PartyFinderPayload.cs index 0931ab03f..77ed7b8bc 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/PartyFinderPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/PartyFinderPayload.cs @@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using Lumina.Extensions; + using Newtonsoft.Json; namespace Dalamud.Game.Text.SeStringHandling.Payloads @@ -97,7 +98,7 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads reader.ReadByte(); // if the next byte is 0xF3 then this listing is limited to home world - byte nextByte = reader.ReadByte(); + var nextByte = reader.ReadByte(); switch (nextByte) { case (byte)PartyFinderLinkType.LimitedToHomeWorld: @@ -121,11 +122,11 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads // if the link type is notification, just use premade payload data since it's always the same. // i have no idea why it is formatted like this, but it is how it is. // note it is identical to the link terminator payload except the embedded info type is 0x08 - if (this.LinkType == PartyFinderLinkType.PartyFinderNotification) return new byte[] { 0x02, 0x27, 0x07, 0x08, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x03, }; + if (this.LinkType == PartyFinderLinkType.PartyFinderNotification) return [0x02, 0x27, 0x07, 0x08, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x03,]; // back to our regularly scheduled programming... var listingIDBytes = MakeInteger(this.ListingId); - bool isFlagSpecified = this.LinkType != PartyFinderLinkType.NotSpecified; + var isFlagSpecified = this.LinkType != PartyFinderLinkType.NotSpecified; var chunkLen = listingIDBytes.Length + 4; // 1 more byte for the type flag if it is specified diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/QuestPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/QuestPayload.cs index 19d494d8a..47947ccde 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/QuestPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/QuestPayload.cs @@ -5,6 +5,7 @@ using Dalamud.Data; using Lumina.Excel; using Lumina.Excel.Sheets; + using Newtonsoft.Json; namespace Dalamud.Game.Text.SeStringHandling.Payloads; @@ -62,7 +63,7 @@ public class QuestPayload : Payload }; bytes.AddRange(idBytes); - bytes.AddRange(new byte[] { 0x01, 0x01, END_BYTE }); + bytes.AddRange([0x01, 0x01, END_BYTE]); return bytes.ToArray(); } diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/RawPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/RawPayload.cs index 02a7c113e..50464077b 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/RawPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/RawPayload.cs @@ -45,7 +45,7 @@ public class RawPayload : Payload /// /// Gets a fixed Payload representing a common link-termination sequence, found in many payload chains. /// - public static RawPayload LinkTerminator => new(new byte[] { 0x02, 0x27, 0x07, 0xCF, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x03 }); + public static RawPayload LinkTerminator => new([0x02, 0x27, 0x07, 0xCF, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x03]); /// public override PayloadType Type => PayloadType.Unknown; diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/SeHyphenPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/SeHyphenPayload.cs index 1739b9cda..48c55a5a8 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/SeHyphenPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/SeHyphenPayload.cs @@ -7,7 +7,7 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads; /// public class SeHyphenPayload : Payload, ITextProvider { - private readonly byte[] bytes = { START_BYTE, (byte)SeStringChunkType.SeHyphen, 0x01, END_BYTE }; + private readonly byte[] bytes = [START_BYTE, (byte)SeStringChunkType.SeHyphen, 0x01, END_BYTE]; /// /// Gets an instance of SeHyphenPayload. diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/StatusPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/StatusPayload.cs index d102dfab6..c17213f60 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/StatusPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/StatusPayload.cs @@ -5,6 +5,7 @@ using Dalamud.Data; using Lumina.Excel; using Lumina.Excel.Sheets; + using Newtonsoft.Json; namespace Dalamud.Game.Text.SeStringHandling.Payloads; @@ -63,7 +64,7 @@ public class StatusPayload : Payload bytes.AddRange(idBytes); // unk - bytes.AddRange(new byte[] { 0x01, 0x01, 0xFF, 0x02, 0x20, END_BYTE }); + bytes.AddRange([0x01, 0x01, 0xFF, 0x02, 0x20, END_BYTE]); return bytes.ToArray(); } diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/UIForegroundPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/UIForegroundPayload.cs index bf360ce34..f161cff9d 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/UIForegroundPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/UIForegroundPayload.cs @@ -5,6 +5,7 @@ using Dalamud.Data; using Lumina.Excel; using Lumina.Excel.Sheets; + using Newtonsoft.Json; namespace Dalamud.Game.Text.SeStringHandling.Payloads; @@ -95,10 +96,10 @@ public class UIForegroundPayload : Payload var colorBytes = MakeInteger(this.colorKey); var chunkLen = colorBytes.Length + 1; - var bytes = new List(new byte[] - { + var bytes = new List( + [ START_BYTE, (byte)SeStringChunkType.UIForeground, (byte)chunkLen, - }); + ]); bytes.AddRange(colorBytes); bytes.Add(END_BYTE); diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/UIGlowPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/UIGlowPayload.cs index e54427073..01c0d05d2 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/UIGlowPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/UIGlowPayload.cs @@ -5,6 +5,7 @@ using Dalamud.Data; using Lumina.Excel; using Lumina.Excel.Sheets; + using Newtonsoft.Json; namespace Dalamud.Game.Text.SeStringHandling.Payloads; @@ -98,10 +99,10 @@ public class UIGlowPayload : Payload var colorBytes = MakeInteger(this.colorKey); var chunkLen = colorBytes.Length + 1; - var bytes = new List(new byte[] - { + var bytes = new List( + [ START_BYTE, (byte)SeStringChunkType.UIGlow, (byte)chunkLen, - }); + ]); bytes.AddRange(colorBytes); bytes.Add(END_BYTE); diff --git a/Dalamud/Game/Text/SeStringHandling/SeString.cs b/Dalamud/Game/Text/SeStringHandling/SeString.cs index b94b05cac..b64a8bb67 100644 --- a/Dalamud/Game/Text/SeStringHandling/SeString.cs +++ b/Dalamud/Game/Text/SeStringHandling/SeString.cs @@ -28,7 +28,7 @@ public class SeString /// public SeString() { - this.Payloads = new List(); + this.Payloads = []; } /// diff --git a/Dalamud/Hooking/AsmHook.cs b/Dalamud/Hooking/AsmHook.cs index 09ae336dc..e6c9f61d8 100644 --- a/Dalamud/Hooking/AsmHook.cs +++ b/Dalamud/Hooking/AsmHook.cs @@ -169,9 +169,6 @@ public sealed class AsmHook : IDisposable, IDalamudHook /// private void CheckDisposed() { - if (this.IsDisposed) - { - throw new ObjectDisposedException(message: "Hook is already disposed", null); - } + ObjectDisposedException.ThrowIf(this.IsDisposed, this); } } diff --git a/Dalamud/Hooking/Hook.cs b/Dalamud/Hooking/Hook.cs index b8fd78b4f..c54a8f399 100644 --- a/Dalamud/Hooking/Hook.cs +++ b/Dalamud/Hooking/Hook.cs @@ -160,7 +160,7 @@ public abstract class Hook : IDalamudHook where T : Delegate (int)Math.Min(pDataDirectory->Size + pDataDirectory->VirtualAddress - importDescriptor.Name, moduleNameLowerWithNullTerminator.Length)); // Is this entry about the DLL that we're looking for? (Case insensitive) - if (currentDllNameWithNullTerminator.ToLowerInvariant() != moduleNameLowerWithNullTerminator) + if (!currentDllNameWithNullTerminator.Equals(moduleNameLowerWithNullTerminator, StringComparison.InvariantCultureIgnoreCase)) continue; if (isPe64) @@ -245,10 +245,7 @@ public abstract class Hook : IDalamudHook where T : Delegate /// protected void CheckDisposed() { - if (this.IsDisposed) - { - throw new ObjectDisposedException(message: "Hook is already disposed", null); - } + ObjectDisposedException.ThrowIf(this.IsDisposed, this); } private static unsafe IntPtr FromImportHelper32(IntPtr baseAddress, ref PeHeader.IMAGE_IMPORT_DESCRIPTOR desc, ref PeHeader.IMAGE_DATA_DIRECTORY dir, string functionName, uint hintOrOrdinal) diff --git a/Dalamud/Hooking/Internal/FunctionPointerVariableHook.cs b/Dalamud/Hooking/Internal/FunctionPointerVariableHook.cs index 8a53e664a..3d1073d2f 100644 --- a/Dalamud/Hooking/Internal/FunctionPointerVariableHook.cs +++ b/Dalamud/Hooking/Internal/FunctionPointerVariableHook.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using JetBrains.Annotations; + using Windows.Win32.System.Memory; using Win32Exception = System.ComponentModel.Win32Exception; @@ -45,7 +45,7 @@ internal unsafe class FunctionPointerVariableHook : Hook if (!HookManager.MultiHookTracker.TryGetValue(this.Address, out var indexList)) { - indexList = HookManager.MultiHookTracker[this.Address] = new List(); + indexList = HookManager.MultiHookTracker[this.Address] = []; } this.detourDelegate = detour; diff --git a/Dalamud/Hooking/Internal/GameInteropProviderPluginScoped.cs b/Dalamud/Hooking/Internal/GameInteropProviderPluginScoped.cs index 52d266335..583060d53 100644 --- a/Dalamud/Hooking/Internal/GameInteropProviderPluginScoped.cs +++ b/Dalamud/Hooking/Internal/GameInteropProviderPluginScoped.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using System.Linq; using Dalamud.Game; @@ -8,6 +8,7 @@ using Dalamud.Plugin.Internal.Types; using Dalamud.Plugin.Services; using Dalamud.Utility; using Dalamud.Utility.Signatures; + using Serilog; namespace Dalamud.Hooking.Internal; @@ -25,7 +26,7 @@ internal class GameInteropProviderPluginScoped : IGameInteropProvider, IInternal private readonly LocalPlugin plugin; private readonly SigScanner scanner; - private readonly WeakConcurrentCollection trackedHooks = new(); + private readonly WeakConcurrentCollection trackedHooks = []; /// /// Initializes a new instance of the class. diff --git a/Dalamud/Hooking/Internal/HookManager.cs b/Dalamud/Hooking/Internal/HookManager.cs index 8f5dba583..83af01bf4 100644 --- a/Dalamud/Hooking/Internal/HookManager.cs +++ b/Dalamud/Hooking/Internal/HookManager.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; +using System.Threading; using Dalamud.Logging.Internal; using Dalamud.Memory; @@ -20,7 +21,7 @@ internal class HookManager : IInternalDisposableService /// /// Logger shared with . /// - internal static readonly ModuleLog Log = new("HM"); + internal static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceConstructor] private HookManager() @@ -30,7 +31,7 @@ internal class HookManager : IInternalDisposableService /// /// Gets sync root object for hook enabling/disabling. /// - internal static object HookEnableSyncRoot { get; } = new(); + internal static Lock HookEnableSyncRoot { get; } = new(); /// /// Gets a static list of tracked and registered hooks. diff --git a/Dalamud/Hooking/Internal/MinHookHook.cs b/Dalamud/Hooking/Internal/MinHookHook.cs index d4889ba11..9c7ec0f88 100644 --- a/Dalamud/Hooking/Internal/MinHookHook.cs +++ b/Dalamud/Hooking/Internal/MinHookHook.cs @@ -24,7 +24,7 @@ internal class MinHookHook : Hook where T : Delegate var unhooker = HookManager.RegisterUnhooker(this.Address); if (!HookManager.MultiHookTracker.TryGetValue(this.Address, out var indexList)) - indexList = HookManager.MultiHookTracker[this.Address] = new(); + indexList = HookManager.MultiHookTracker[this.Address] = []; var index = (ulong)indexList.Count; diff --git a/Dalamud/Hooking/WndProcHook/WndProcHookManager.cs b/Dalamud/Hooking/WndProcHook/WndProcHookManager.cs index 7c70a9f0b..82620eed8 100644 --- a/Dalamud/Hooking/WndProcHook/WndProcHookManager.cs +++ b/Dalamud/Hooking/WndProcHook/WndProcHookManager.cs @@ -17,10 +17,10 @@ namespace Dalamud.Hooking.WndProcHook; [ServiceManager.EarlyLoadedService] internal sealed class WndProcHookManager : IInternalDisposableService { - private static readonly ModuleLog Log = new(nameof(WndProcHookManager)); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly Hook dispatchMessageWHook; - private readonly Dictionary wndProcOverrides = new(); + private readonly Dictionary wndProcOverrides = []; private HWND mainWindowHwnd; diff --git a/Dalamud/Interface/ColorHelpers.cs b/Dalamud/Interface/ColorHelpers.cs index a3ae6799e..dd56f3d14 100644 --- a/Dalamud/Interface/ColorHelpers.cs +++ b/Dalamud/Interface/ColorHelpers.cs @@ -56,11 +56,10 @@ public static class ColorHelpers var min = Math.Min(r, Math.Min(g, b)); var h = max; - var s = max; var v = max; var d = max - min; - s = max == 0 ? 0 : d / max; + var s = max == 0 ? 0 : d / max; if (max == min) { diff --git a/Dalamud/Interface/Components/ImGuiComponents.HelpMarker.cs b/Dalamud/Interface/Components/ImGuiComponents.HelpMarker.cs index 57a4bd150..0d919cf6e 100644 --- a/Dalamud/Interface/Components/ImGuiComponents.HelpMarker.cs +++ b/Dalamud/Interface/Components/ImGuiComponents.HelpMarker.cs @@ -1,5 +1,6 @@ using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Common.Math; namespace Dalamud.Interface.Components; diff --git a/Dalamud/Interface/DragDrop/DragDropManager.cs b/Dalamud/Interface/DragDrop/DragDropManager.cs index 4375ddea9..504bdc716 100644 --- a/Dalamud/Interface/DragDrop/DragDropManager.cs +++ b/Dalamud/Interface/DragDrop/DragDropManager.cs @@ -5,6 +5,7 @@ using Dalamud.Bindings.ImGui; using Dalamud.Interface.Internal; using Dalamud.IoC; using Dalamud.IoC.Internal; + using Serilog; namespace Dalamud.Interface.DragDrop; diff --git a/Dalamud/Interface/DragDrop/DragDropTarget.cs b/Dalamud/Interface/DragDrop/DragDropTarget.cs index c6b66e7e8..8ac347c72 100644 --- a/Dalamud/Interface/DragDrop/DragDropTarget.cs +++ b/Dalamud/Interface/DragDrop/DragDropTarget.cs @@ -6,6 +6,7 @@ using System.Text; using Dalamud.Bindings.ImGui; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.DragDrop; diff --git a/Dalamud/Interface/FontAwesome/FontAwesomeExtensions.cs b/Dalamud/Interface/FontAwesome/FontAwesomeExtensions.cs index 2b8cb8c52..0bab4538a 100644 --- a/Dalamud/Interface/FontAwesome/FontAwesomeExtensions.cs +++ b/Dalamud/Interface/FontAwesome/FontAwesomeExtensions.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Dalamud.Utility; @@ -37,7 +37,7 @@ public static class FontAwesomeExtensions public static IEnumerable GetSearchTerms(this FontAwesomeIcon icon) { var searchTermsAttribute = icon.GetAttribute(); - return searchTermsAttribute == null ? new string[] { } : searchTermsAttribute.SearchTerms; + return searchTermsAttribute == null ? [] : searchTermsAttribute.SearchTerms; } /// @@ -48,6 +48,6 @@ public static class FontAwesomeExtensions public static IEnumerable GetCategories(this FontAwesomeIcon icon) { var categoriesAttribute = icon.GetAttribute(); - return categoriesAttribute == null ? new string[] { } : categoriesAttribute.Categories; + return categoriesAttribute == null ? [] : categoriesAttribute.Categories; } } diff --git a/Dalamud/Interface/FontAwesome/FontAwesomeHelpers.cs b/Dalamud/Interface/FontAwesome/FontAwesomeHelpers.cs index cf34d736e..51c896ad2 100644 --- a/Dalamud/Interface/FontAwesome/FontAwesomeHelpers.cs +++ b/Dalamud/Interface/FontAwesome/FontAwesomeHelpers.cs @@ -16,14 +16,7 @@ public static class FontAwesomeHelpers /// list of font awesome icons. public static List GetIcons() { - var icons = new List(); - foreach (var icon in Enum.GetValues(typeof(FontAwesomeIcon)).Cast().ToList()) - { - if (icon.IsObsolete()) continue; - icons.Add(icon); - } - - return icons; + return [.. Enum.GetValues().Where(icon => !icon.IsObsolete())]; } /// @@ -75,7 +68,7 @@ public static class FontAwesomeHelpers { var name = Enum.GetName(icon)?.ToLowerInvariant(); var searchTerms = icon.GetSearchTerms(); - if (name!.Contains(search.ToLowerInvariant()) || searchTerms.Contains(search.ToLowerInvariant())) + if (name!.Contains(search, StringComparison.InvariantCultureIgnoreCase) || searchTerms.Contains(search.ToLowerInvariant())) { result.Add(icon); } @@ -105,7 +98,7 @@ public static class FontAwesomeHelpers var name = Enum.GetName(icon)?.ToLowerInvariant(); var searchTerms = icon.GetSearchTerms(); var categories = icon.GetCategories(); - if ((name!.Contains(search.ToLowerInvariant()) || searchTerms.Contains(search.ToLowerInvariant())) && categories.Contains(category)) + if ((name!.Contains(search, StringComparison.InvariantCultureIgnoreCase) || searchTerms.Contains(search.ToLowerInvariant())) && categories.Contains(category)) { result.Add(icon); } diff --git a/Dalamud/Interface/FontIdentifier/DalamudAssetFontAndFamilyId.cs b/Dalamud/Interface/FontIdentifier/DalamudAssetFontAndFamilyId.cs index c531dced5..3778ea0de 100644 --- a/Dalamud/Interface/FontIdentifier/DalamudAssetFontAndFamilyId.cs +++ b/Dalamud/Interface/FontIdentifier/DalamudAssetFontAndFamilyId.cs @@ -3,7 +3,9 @@ using System.Collections.Generic; using Dalamud.Bindings.ImGui; using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Storage.Assets; + using Newtonsoft.Json; + using TerraFX.Interop.DirectX; namespace Dalamud.Interface.FontIdentifier; diff --git a/Dalamud/Interface/FontIdentifier/DalamudDefaultFontAndFamilyId.cs b/Dalamud/Interface/FontIdentifier/DalamudDefaultFontAndFamilyId.cs index c45cf256b..4666de54a 100644 --- a/Dalamud/Interface/FontIdentifier/DalamudDefaultFontAndFamilyId.cs +++ b/Dalamud/Interface/FontIdentifier/DalamudDefaultFontAndFamilyId.cs @@ -2,7 +2,9 @@ using System.Collections.Generic; using Dalamud.Bindings.ImGui; using Dalamud.Interface.ManagedFontAtlas; + using Newtonsoft.Json; + using TerraFX.Interop.DirectX; namespace Dalamud.Interface.FontIdentifier; diff --git a/Dalamud/Interface/FontIdentifier/GameFontAndFamilyId.cs b/Dalamud/Interface/FontIdentifier/GameFontAndFamilyId.cs index e294c8813..f19a2ec6a 100644 --- a/Dalamud/Interface/FontIdentifier/GameFontAndFamilyId.cs +++ b/Dalamud/Interface/FontIdentifier/GameFontAndFamilyId.cs @@ -3,7 +3,9 @@ using System.Collections.Generic; using Dalamud.Bindings.ImGui; using Dalamud.Interface.GameFonts; using Dalamud.Interface.ManagedFontAtlas; + using Newtonsoft.Json; + using TerraFX.Interop.DirectX; namespace Dalamud.Interface.FontIdentifier; diff --git a/Dalamud/Interface/FontIdentifier/IFontFamilyId.cs b/Dalamud/Interface/FontIdentifier/IFontFamilyId.cs index 991716f74..40780422a 100644 --- a/Dalamud/Interface/FontIdentifier/IFontFamilyId.cs +++ b/Dalamud/Interface/FontIdentifier/IFontFamilyId.cs @@ -36,26 +36,25 @@ public interface IFontFamilyId : IObjectWithLocalizableName /// /// The list of fonts. public static List ListDalamudFonts() => - new() - { + [ new DalamudAssetFontAndFamilyId(DalamudAsset.NotoSansJpMedium), new DalamudAssetFontAndFamilyId(DalamudAsset.InconsolataRegular), new DalamudAssetFontAndFamilyId(DalamudAsset.FontAwesomeFreeSolid), - }; + ]; /// /// Gets the list of Game-provided fonts. /// /// The list of fonts. - public static List ListGameFonts() => new() - { + public static List ListGameFonts() => + [ new GameFontAndFamilyId(GameFontFamily.Axis), new GameFontAndFamilyId(GameFontFamily.Jupiter), new GameFontAndFamilyId(GameFontFamily.JupiterNumeric), new GameFontAndFamilyId(GameFontFamily.Meidinger), new GameFontAndFamilyId(GameFontFamily.MiedingerMid), new GameFontAndFamilyId(GameFontFamily.TrumpGothic), - }; + ]; /// /// Gets the list of System-provided fonts. diff --git a/Dalamud/Interface/FontIdentifier/SingleFontSpec.cs b/Dalamud/Interface/FontIdentifier/SingleFontSpec.cs index 070b1c1e1..b1c03f9dd 100644 --- a/Dalamud/Interface/FontIdentifier/SingleFontSpec.cs +++ b/Dalamud/Interface/FontIdentifier/SingleFontSpec.cs @@ -6,6 +6,7 @@ using System.Text; using Dalamud.Bindings.ImGui; using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.Utility; + using Newtonsoft.Json; namespace Dalamud.Interface.FontIdentifier; diff --git a/Dalamud/Interface/FontIdentifier/SystemFontFamilyId.cs b/Dalamud/Interface/FontIdentifier/SystemFontFamilyId.cs index 83a5e810d..60e20fb6f 100644 --- a/Dalamud/Interface/FontIdentifier/SystemFontFamilyId.cs +++ b/Dalamud/Interface/FontIdentifier/SystemFontFamilyId.cs @@ -83,7 +83,7 @@ public sealed class SystemFontFamilyId : IFontFamilyId else if (candidates.Any(x => x.Style == (int)DWRITE_FONT_STYLE.DWRITE_FONT_STYLE_NORMAL)) candidates.RemoveAll(x => x.Style != (int)DWRITE_FONT_STYLE.DWRITE_FONT_STYLE_NORMAL); - if (!candidates.Any()) + if (candidates.Count == 0) return 0; for (var i = 0; i < this.Fonts.Count; i++) @@ -117,7 +117,7 @@ public sealed class SystemFontFamilyId : IFontFamilyId return new(IObjectWithLocalizableName.GetLocaleNames(fn)); } - private unsafe IReadOnlyList GetFonts() + private unsafe List GetFonts() { using var dwf = default(ComPtr); fixed (Guid* piid = &IID.IID_IDWriteFactory) diff --git a/Dalamud/Interface/FontIdentifier/SystemFontId.cs b/Dalamud/Interface/FontIdentifier/SystemFontId.cs index 8401f4c79..45885a9a8 100644 --- a/Dalamud/Interface/FontIdentifier/SystemFontId.cs +++ b/Dalamud/Interface/FontIdentifier/SystemFontId.cs @@ -5,7 +5,9 @@ using System.Linq; using Dalamud.Bindings.ImGui; using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Utility; + using Newtonsoft.Json; + using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; diff --git a/Dalamud/Interface/GameFonts/FdtReader.cs b/Dalamud/Interface/GameFonts/FdtReader.cs index 0e8f3fb59..6f6aaea25 100644 --- a/Dalamud/Interface/GameFonts/FdtReader.cs +++ b/Dalamud/Interface/GameFonts/FdtReader.cs @@ -43,12 +43,12 @@ public class FdtReader /// /// Gets all the glyphs defined in this file. /// - public List Glyphs { get; init; } = new(); + public List Glyphs { get; init; } = []; /// /// Gets all the kerning entries defined in this file. /// - public List Distances { get; init; } = new(); + public List Distances { get; init; } = []; /// /// Finds the glyph index for the corresponding codepoint. @@ -269,7 +269,7 @@ public class FdtReader /// /// Mapping of texture channel index to byte index. /// - public static readonly int[] TextureChannelOrder = { 2, 1, 0, 3 }; + public static readonly int[] TextureChannelOrder = [2, 1, 0, 3]; /// /// Integer representation of a Unicode character in UTF-8 in reverse order, read in little endian. diff --git a/Dalamud/Interface/GameFonts/GameFontLayoutPlan.cs b/Dalamud/Interface/GameFonts/GameFontLayoutPlan.cs index 5b0fe100b..126e7601f 100644 --- a/Dalamud/Interface/GameFonts/GameFontLayoutPlan.cs +++ b/Dalamud/Interface/GameFonts/GameFontLayoutPlan.cs @@ -200,30 +200,25 @@ public class GameFontLayoutPlan return false; // TODO: Whatever - switch (char.GetUnicodeCategory((char)this.Codepoint)) - { - case System.Globalization.UnicodeCategory.SpaceSeparator: - case System.Globalization.UnicodeCategory.LineSeparator: - case System.Globalization.UnicodeCategory.ParagraphSeparator: - case System.Globalization.UnicodeCategory.Control: - case System.Globalization.UnicodeCategory.Format: - case System.Globalization.UnicodeCategory.Surrogate: - case System.Globalization.UnicodeCategory.PrivateUse: - case System.Globalization.UnicodeCategory.ConnectorPunctuation: - case System.Globalization.UnicodeCategory.DashPunctuation: - case System.Globalization.UnicodeCategory.OpenPunctuation: - case System.Globalization.UnicodeCategory.ClosePunctuation: - case System.Globalization.UnicodeCategory.InitialQuotePunctuation: - case System.Globalization.UnicodeCategory.FinalQuotePunctuation: - case System.Globalization.UnicodeCategory.OtherPunctuation: - case System.Globalization.UnicodeCategory.MathSymbol: - case System.Globalization.UnicodeCategory.ModifierSymbol: - case System.Globalization.UnicodeCategory.OtherSymbol: - case System.Globalization.UnicodeCategory.OtherNotAssigned: - return true; - } - - return false; + return char.GetUnicodeCategory((char)this.Codepoint) + is System.Globalization.UnicodeCategory.SpaceSeparator + or System.Globalization.UnicodeCategory.LineSeparator + or System.Globalization.UnicodeCategory.ParagraphSeparator + or System.Globalization.UnicodeCategory.Control + or System.Globalization.UnicodeCategory.Format + or System.Globalization.UnicodeCategory.Surrogate + or System.Globalization.UnicodeCategory.PrivateUse + or System.Globalization.UnicodeCategory.ConnectorPunctuation + or System.Globalization.UnicodeCategory.DashPunctuation + or System.Globalization.UnicodeCategory.OpenPunctuation + or System.Globalization.UnicodeCategory.ClosePunctuation + or System.Globalization.UnicodeCategory.InitialQuotePunctuation + or System.Globalization.UnicodeCategory.FinalQuotePunctuation + or System.Globalization.UnicodeCategory.OtherPunctuation + or System.Globalization.UnicodeCategory.MathSymbol + or System.Globalization.UnicodeCategory.ModifierSymbol + or System.Globalization.UnicodeCategory.OtherSymbol + or System.Globalization.UnicodeCategory.OtherNotAssigned; } } } @@ -300,7 +295,7 @@ public class GameFontLayoutPlan elements.Add(new() { Codepoint = c, Glyph = this.fdt.GetGlyph(c), }); var lastBreakIndex = 0; - List lineBreakIndices = new() { 0 }; + List lineBreakIndices = [0]; for (var i = 1; i < elements.Count; i++) { var prev = elements[i - 1]; diff --git a/Dalamud/Interface/GlyphRangesJapanese.cs b/Dalamud/Interface/GlyphRangesJapanese.cs index 2773b9db5..2acf7f40e 100644 --- a/Dalamud/Interface/GlyphRangesJapanese.cs +++ b/Dalamud/Interface/GlyphRangesJapanese.cs @@ -8,8 +8,8 @@ public static class GlyphRangesJapanese /// /// Gets the unicode glyph ranges for the Japanese language. /// - public static ushort[] GlyphRanges => new ushort[] - { + public static ushort[] GlyphRanges => + [ 0x0020, 0x00FF, 0x0391, 0x03A1, 0x03A3, 0x03A9, 0x03B1, 0x03C1, 0x03C3, 0x03C9, 0x0401, 0x0401, 0x0410, 0x044F, 0x0451, 0x0451, 0x2000, 0x206F, 0x2103, 0x2103, 0x212B, 0x212B, 0x2190, 0x2193, 0x21D2, 0x21D2, 0x21D4, 0x21D4, 0x2200, 0x2200, 0x2202, 0x2203, 0x2207, 0x2208, 0x220B, 0x220B, 0x2212, 0x2212, 0x221A, 0x221A, 0x221D, 0x221E, 0x2220, 0x2220, 0x2227, 0x222C, 0x2234, 0x2235, @@ -524,5 +524,5 @@ public static class GlyphRangesJapanese 0x9F4E, 0x9F4F, 0x9F52, 0x9F52, 0x9F54, 0x9F54, 0x9F5F, 0x9F63, 0x9F66, 0x9F67, 0x9F6A, 0x9F6A, 0x9F6C, 0x9F6C, 0x9F72, 0x9F72, 0x9F76, 0x9F77, 0x9F8D, 0x9F8D, 0x9F95, 0x9F95, 0x9F9C, 0x9F9D, 0x9FA0, 0x9FA0, 0xFF01, 0xFF01, 0xFF03, 0xFF06, 0xFF08, 0xFF0C, 0xFF0E, 0xFF3B, 0xFF3D, 0xFF5D, 0xFF61, 0xFF9F, 0xFFE3, 0xFFE3, 0xFFE5, 0xFFE5, 0xFFFF, 0xFFFF, 0, - }; + ]; } diff --git a/Dalamud/Interface/ImGuiBackend/Dx11Win32Backend.cs b/Dalamud/Interface/ImGuiBackend/Dx11Win32Backend.cs index ea609828d..e3b98ec37 100644 --- a/Dalamud/Interface/ImGuiBackend/Dx11Win32Backend.cs +++ b/Dalamud/Interface/ImGuiBackend/Dx11Win32Backend.cs @@ -1,9 +1,4 @@ -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using Dalamud.Bindings.ImGui; using Dalamud.Bindings.ImGuizmo; @@ -14,8 +9,6 @@ using Dalamud.Interface.ImGuiBackend.InputHandler; using Dalamud.Interface.ImGuiBackend.Renderers; using Dalamud.Utility; -using Serilog; - using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; diff --git a/Dalamud/Interface/ImGuiBackend/Renderers/Dx11Renderer.ViewportHandler.cs b/Dalamud/Interface/ImGuiBackend/Renderers/Dx11Renderer.ViewportHandler.cs index fe83d58a9..c8d82648e 100644 --- a/Dalamud/Interface/ImGuiBackend/Renderers/Dx11Renderer.ViewportHandler.cs +++ b/Dalamud/Interface/ImGuiBackend/Renderers/Dx11Renderer.ViewportHandler.cs @@ -5,6 +5,7 @@ using System.Runtime.InteropServices; using Dalamud.Bindings.ImGui; using Dalamud.Interface.ImGuiBackend.Helpers; using Dalamud.Utility; + using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; diff --git a/Dalamud/Interface/ImGuiBackend/Renderers/Dx11Renderer.cs b/Dalamud/Interface/ImGuiBackend/Renderers/Dx11Renderer.cs index 2eb4e4970..a6abbb862 100644 --- a/Dalamud/Interface/ImGuiBackend/Renderers/Dx11Renderer.cs +++ b/Dalamud/Interface/ImGuiBackend/Renderers/Dx11Renderer.cs @@ -15,6 +15,7 @@ using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Interface.Textures.TextureWraps.Internal; using Dalamud.Interface.Utility; using Dalamud.Utility; + using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -30,7 +31,7 @@ namespace Dalamud.Interface.ImGuiBackend.Renderers; Justification = "Multiple fixed/using scopes")] internal unsafe partial class Dx11Renderer : IImGuiRenderer { - private readonly List fontTextures = new(); + private readonly List fontTextures = []; private readonly D3D_FEATURE_LEVEL featureLevel; private readonly ViewportHandler viewportHandler; private readonly nint renderNamePtr; @@ -398,10 +399,9 @@ internal unsafe partial class Dx11Renderer : IImGuiRenderer /// private void CreateFontsTexture() { - if (this.device.IsEmpty()) - throw new ObjectDisposedException(nameof(Dx11Renderer)); + ObjectDisposedException.ThrowIf(this.device.IsEmpty(), this); - if (this.fontTextures.Any()) + if (this.fontTextures.Count != 0) return; var io = ImGui.GetIO(); @@ -479,8 +479,7 @@ internal unsafe partial class Dx11Renderer : IImGuiRenderer /// private void EnsureDeviceObjects() { - if (this.device.IsEmpty()) - throw new ObjectDisposedException(nameof(Dx11Renderer)); + ObjectDisposedException.ThrowIf(this.device.IsEmpty(), this); var assembly = Assembly.GetExecutingAssembly(); diff --git a/Dalamud/Interface/ImGuiFileDialog/FileDialog.Files.cs b/Dalamud/Interface/ImGuiFileDialog/FileDialog.Files.cs index e5b7fc15e..1bad08f08 100644 --- a/Dalamud/Interface/ImGuiFileDialog/FileDialog.Files.cs +++ b/Dalamud/Interface/ImGuiFileDialog/FileDialog.Files.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; using Dalamud.Utility; @@ -11,7 +12,7 @@ namespace Dalamud.Interface.ImGuiFileDialog; /// public partial class FileDialog { - private readonly object filesLock = new(); + private readonly Lock filesLock = new(); private readonly DriveListLoader driveListLoader = new(); diff --git a/Dalamud/Interface/ImGuiFileDialog/FileDialog.Filters.cs b/Dalamud/Interface/ImGuiFileDialog/FileDialog.Filters.cs index 85b380bee..46f264354 100644 --- a/Dalamud/Interface/ImGuiFileDialog/FileDialog.Filters.cs +++ b/Dalamud/Interface/ImGuiFileDialog/FileDialog.Filters.cs @@ -8,11 +8,12 @@ namespace Dalamud.Interface.ImGuiFileDialog; /// public partial class FileDialog { - private static Regex filterRegex = new(@"[^,{}]+(\{([^{}]*?)\})?", RegexOptions.Compiled); - - private List filters = new(); + private List filters = []; private FilterStruct selectedFilter; + [GeneratedRegex(@"[^,{}]+(\{([^{}]*?)\})?", RegexOptions.Compiled)] + private static partial Regex FilterRegex(); + private void ParseFilters(string filters) { // ".*,.cpp,.h,.hpp" @@ -22,13 +23,13 @@ public partial class FileDialog if (filters.Length == 0) return; var currentFilterFound = false; - var matches = filterRegex.Matches(filters); + var matches = FilterRegex().Matches(filters); foreach (Match m in matches) { var match = m.Value; var filter = default(FilterStruct); - if (match.Contains("{")) + if (match.Contains('{')) { var exts = m.Groups[2].Value; filter = new FilterStruct @@ -42,7 +43,7 @@ public partial class FileDialog filter = new FilterStruct { Filter = match, - CollectionFilters = new(), + CollectionFilters = [], }; } @@ -89,7 +90,7 @@ public partial class FileDialog foreach (var file in this.files) { var show = true; - if (!string.IsNullOrEmpty(this.searchBuffer) && !file.FileName.ToLowerInvariant().Contains(this.searchBuffer.ToLowerInvariant())) + if (!string.IsNullOrEmpty(this.searchBuffer) && !file.FileName.Contains(this.searchBuffer, StringComparison.InvariantCultureIgnoreCase)) { show = false; } diff --git a/Dalamud/Interface/ImGuiFileDialog/FileDialog.Helpers.cs b/Dalamud/Interface/ImGuiFileDialog/FileDialog.Helpers.cs index 57844c48b..7e5363673 100644 --- a/Dalamud/Interface/ImGuiFileDialog/FileDialog.Helpers.cs +++ b/Dalamud/Interface/ImGuiFileDialog/FileDialog.Helpers.cs @@ -12,7 +12,7 @@ public partial class FileDialog private static string BytesToString(long byteCount) { - string[] suf = { " B", " KB", " MB", " GB", " TB" }; + string[] suf = [" B", " KB", " MB", " GB", " TB"]; if (byteCount == 0) return "0" + suf[0]; var bytes = Math.Abs(byteCount); diff --git a/Dalamud/Interface/ImGuiFileDialog/FileDialog.UI.cs b/Dalamud/Interface/ImGuiFileDialog/FileDialog.UI.cs index 3c02f9559..ef886e957 100644 --- a/Dalamud/Interface/ImGuiFileDialog/FileDialog.UI.cs +++ b/Dalamud/Interface/ImGuiFileDialog/FileDialog.UI.cs @@ -54,7 +54,7 @@ public partial class FileDialog windowVisible = ImGui.Begin(name, ref this.visible, this.WindowFlags); } - bool wasClosed = false; + var wasClosed = false; if (windowVisible) { if (!this.visible) @@ -122,15 +122,15 @@ public partial class FileDialog { if (iconMap == null) { - iconMap = new(); - AddToIconMap(new[] { "mp4", "gif", "mov", "avi" }, FontAwesomeIcon.FileVideo, miscTextColor); - AddToIconMap(new[] { "pdf" }, FontAwesomeIcon.FilePdf, miscTextColor); - AddToIconMap(new[] { "png", "jpg", "jpeg", "tiff" }, FontAwesomeIcon.FileImage, imageTextColor); - AddToIconMap(new[] { "cs", "json", "cpp", "h", "py", "xml", "yaml", "js", "html", "css", "ts", "java" }, FontAwesomeIcon.FileCode, codeTextColor); - AddToIconMap(new[] { "txt", "md" }, FontAwesomeIcon.FileAlt, standardTextColor); - AddToIconMap(new[] { "zip", "7z", "gz", "tar" }, FontAwesomeIcon.FileArchive, miscTextColor); - AddToIconMap(new[] { "mp3", "m4a", "ogg", "wav" }, FontAwesomeIcon.FileAudio, miscTextColor); - AddToIconMap(new[] { "csv" }, FontAwesomeIcon.FileCsv, miscTextColor); + iconMap = []; + AddToIconMap(["mp4", "gif", "mov", "avi"], FontAwesomeIcon.FileVideo, miscTextColor); + AddToIconMap(["pdf"], FontAwesomeIcon.FilePdf, miscTextColor); + AddToIconMap(["png", "jpg", "jpeg", "tiff"], FontAwesomeIcon.FileImage, imageTextColor); + AddToIconMap(["cs", "json", "cpp", "h", "py", "xml", "yaml", "js", "html", "css", "ts", "java"], FontAwesomeIcon.FileCode, codeTextColor); + AddToIconMap(["txt", "md"], FontAwesomeIcon.FileAlt, standardTextColor); + AddToIconMap(["zip", "7z", "gz", "tar"], FontAwesomeIcon.FileArchive, miscTextColor); + AddToIconMap(["mp3", "m4a", "ogg", "wav"], FontAwesomeIcon.FileAudio, miscTextColor); + AddToIconMap(["csv"], FontAwesomeIcon.FileCsv, miscTextColor); } return iconMap.TryGetValue(ext.ToLowerInvariant(), out var icon) ? icon : new IconColorItem diff --git a/Dalamud/Interface/ImGuiFileDialog/FileDialog.cs b/Dalamud/Interface/ImGuiFileDialog/FileDialog.cs index 3d8246ffd..e33fc2fc4 100644 --- a/Dalamud/Interface/ImGuiFileDialog/FileDialog.cs +++ b/Dalamud/Interface/ImGuiFileDialog/FileDialog.cs @@ -30,7 +30,7 @@ public partial class FileDialog private string currentPath; private string fileNameBuffer = string.Empty; - private List pathDecomposition = new(); + private List pathDecomposition = []; private bool pathClicked = true; private bool pathInputActivated = false; private string pathInputBuffer = string.Empty; @@ -46,12 +46,12 @@ public partial class FileDialog private string searchBuffer = string.Empty; private string lastSelectedFileName = string.Empty; - private List selectedFileNames = new(); + private List selectedFileNames = []; private float footerHeight = 0; private string selectedSideBar = string.Empty; - private List quickAccess = new(); + private List quickAccess = []; /// /// Initializes a new instance of the class. @@ -130,12 +130,12 @@ public partial class FileDialog { if (!this.flags.HasFlag(ImGuiFileDialogFlags.SelectOnly)) { - return new List { this.GetFilePathName() }; + return [this.GetFilePathName()]; } if (this.IsDirectoryMode() && this.selectedFileNames.Count == 0) { - return new List { this.GetFilePathName() }; // current directory + return [this.GetFilePathName()]; // current directory } var fullPaths = this.selectedFileNames.Where(x => !string.IsNullOrEmpty(x)).Select(x => Path.Combine(this.currentPath, x)); diff --git a/Dalamud/Interface/ImGuiFontChooserDialog/SingleFontChooserDialog.cs b/Dalamud/Interface/ImGuiFontChooserDialog/SingleFontChooserDialog.cs index 6a381f5b2..2abdd3403 100644 --- a/Dalamud/Interface/ImGuiFontChooserDialog/SingleFontChooserDialog.cs +++ b/Dalamud/Interface/ImGuiFontChooserDialog/SingleFontChooserDialog.cs @@ -13,6 +13,7 @@ using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.ManagedFontAtlas.Internals; using Dalamud.Interface.Utility; using Dalamud.Utility; + using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -31,10 +32,10 @@ public sealed class SingleFontChooserDialog : IDisposable private const float MaxFontSizePt = 127; - private static readonly List EmptyIFontList = new(); + private static readonly List EmptyIFontList = []; private static readonly (string Name, float Value)[] FontSizeList = - { + [ ("9.6", 9.6f), ("10", 10f), ("12", 12f), @@ -51,7 +52,7 @@ public sealed class SingleFontChooserDialog : IDisposable ("46", 46), ("68", 68), ("90", 90), - }; + ]; private static int counterStatic; @@ -1235,7 +1236,7 @@ public sealed class SingleFontChooserDialog : IDisposable } private void UpdateSelectedFamilyAndFontIndices( - IReadOnlyList fonts, + List fonts, string familyName, string fontName) { diff --git a/Dalamud/Interface/ImGuiNotification/Internal/NotificationManager.cs b/Dalamud/Interface/ImGuiNotification/Internal/NotificationManager.cs index 340763a55..1b6e7e59b 100644 --- a/Dalamud/Interface/ImGuiNotification/Internal/NotificationManager.cs +++ b/Dalamud/Interface/ImGuiNotification/Internal/NotificationManager.cs @@ -26,8 +26,8 @@ internal class NotificationManager : INotificationManager, IInternalDisposableSe [ServiceManager.ServiceDependency] private readonly DalamudConfiguration configuration = Service.Get(); - private readonly List notifications = new(); - private readonly ConcurrentBag pendingNotifications = new(); + private readonly List notifications = []; + private readonly ConcurrentBag pendingNotifications = []; private NotificationPositionChooser? positionChooser; diff --git a/Dalamud/Interface/ImGuiNotification/Notification.cs b/Dalamud/Interface/ImGuiNotification/Notification.cs index 4dcb10c17..ef6bb3da8 100644 --- a/Dalamud/Interface/ImGuiNotification/Notification.cs +++ b/Dalamud/Interface/ImGuiNotification/Notification.cs @@ -1,9 +1,5 @@ -using System.Threading.Tasks; - using Dalamud.Interface.ImGuiNotification.Internal; using Dalamud.Interface.Textures; -using Dalamud.Interface.Textures.TextureWraps; -using Serilog; namespace Dalamud.Interface.ImGuiNotification; /// Represents a blueprint for a notification. diff --git a/Dalamud/Interface/ImGuiNotification/NotificationUtilities.cs b/Dalamud/Interface/ImGuiNotification/NotificationUtilities.cs index 4f0830fa1..5ef3cf4ac 100644 --- a/Dalamud/Interface/ImGuiNotification/NotificationUtilities.cs +++ b/Dalamud/Interface/ImGuiNotification/NotificationUtilities.cs @@ -1,11 +1,9 @@ using System.IO; using System.Numerics; using System.Runtime.CompilerServices; -using System.Threading.Tasks; using Dalamud.Bindings.ImGui; using Dalamud.Game.Text; -using Dalamud.Interface.Internal; using Dalamud.Interface.Internal.Windows; using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.Textures; diff --git a/Dalamud/Interface/ImGuiSeStringRenderer/Internal/SeStringRenderer.cs b/Dalamud/Interface/ImGuiSeStringRenderer/Internal/SeStringRenderer.cs index f161c1868..5a19f9a50 100644 --- a/Dalamud/Interface/ImGuiSeStringRenderer/Internal/SeStringRenderer.cs +++ b/Dalamud/Interface/ImGuiSeStringRenderer/Internal/SeStringRenderer.cs @@ -5,6 +5,7 @@ using System.Runtime.InteropServices; using System.Text; using BitFaster.Caching.Lru; + using Dalamud.Bindings.ImGui; using Dalamud.Data; using Dalamud.Game; @@ -12,8 +13,10 @@ using Dalamud.Game.Text.SeStringHandling; using Dalamud.Interface.ImGuiSeStringRenderer.Internal.TextProcessing; using Dalamud.Interface.Utility; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Client.System.String; using FFXIVClientStructs.FFXIV.Client.UI; + using Lumina.Excel.Sheets; using Lumina.Text; using Lumina.Text.Parse; diff --git a/Dalamud/Interface/ImGuiSeStringRenderer/SeStringDrawState.cs b/Dalamud/Interface/ImGuiSeStringRenderer/SeStringDrawState.cs index dcbe123e7..ee03643ad 100644 --- a/Dalamud/Interface/ImGuiSeStringRenderer/SeStringDrawState.cs +++ b/Dalamud/Interface/ImGuiSeStringRenderer/SeStringDrawState.cs @@ -7,6 +7,7 @@ using System.Text; using Dalamud.Bindings.ImGui; using Dalamud.Interface.ImGuiSeStringRenderer.Internal; using Dalamud.Interface.Utility; + using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Component.GUI; diff --git a/Dalamud/Interface/Internal/Asserts/AssertHandler.cs b/Dalamud/Interface/Internal/Asserts/AssertHandler.cs index 276dddb57..fadf80406 100644 --- a/Dalamud/Interface/Internal/Asserts/AssertHandler.cs +++ b/Dalamud/Interface/Internal/Asserts/AssertHandler.cs @@ -21,7 +21,7 @@ internal class AssertHandler : IDisposable private const int HidePrintEvery = 500; private readonly HashSet ignoredAsserts = []; - private readonly Dictionary assertCounts = new(); + private readonly Dictionary assertCounts = []; // Store callback to avoid it from being GC'd private readonly AssertCallbackDelegate callback; diff --git a/Dalamud/Interface/Internal/DalamudCommands.cs b/Dalamud/Interface/Internal/DalamudCommands.cs index 3e4a5cec6..9812a4e6a 100644 --- a/Dalamud/Interface/Internal/DalamudCommands.cs +++ b/Dalamud/Interface/Internal/DalamudCommands.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using CheapLoc; + using Dalamud.Configuration.Internal; using Dalamud.Game; using Dalamud.Game.Command; @@ -11,7 +11,6 @@ using Dalamud.Game.Gui; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Plugin.Internal; using Dalamud.Utility; -using Serilog; namespace Dalamud.Interface.Internal; @@ -208,7 +207,7 @@ internal class DalamudCommands : IServiceType var chatGui = Service.Get(); var configuration = Service.Get(); - configuration.BadWords ??= new List(); + configuration.BadWords ??= []; if (configuration.BadWords.Count == 0) { @@ -227,7 +226,7 @@ internal class DalamudCommands : IServiceType var chatGui = Service.Get(); var configuration = Service.Get(); - configuration.BadWords ??= new List(); + configuration.BadWords ??= []; configuration.BadWords.RemoveAll(x => x == arguments); @@ -326,7 +325,7 @@ internal class DalamudCommands : IServiceType var configuration = Service.Get(); var localization = Service.Get(); - if (Localization.ApplicableLangCodes.Contains(arguments.ToLowerInvariant()) || arguments.ToLowerInvariant() == "en") + if (Localization.ApplicableLangCodes.Contains(arguments.ToLowerInvariant()) || arguments.Equals("en", StringComparison.InvariantCultureIgnoreCase)) { localization.SetupWithLangCode(arguments.ToLowerInvariant()); configuration.LanguageOverride = arguments.ToLowerInvariant(); diff --git a/Dalamud/Interface/Internal/DalamudIme.cs b/Dalamud/Interface/Internal/DalamudIme.cs index cdb976333..e5ff83ff8 100644 --- a/Dalamud/Interface/Internal/DalamudIme.cs +++ b/Dalamud/Interface/Internal/DalamudIme.cs @@ -74,7 +74,7 @@ internal sealed unsafe class DalamudIme : IInternalDisposableService private readonly ImGuiSetPlatformImeDataDelegate setPlatformImeDataDelegate; /// The candidates. - private readonly List<(string String, bool Supported)> candidateStrings = new(); + private readonly List<(string String, bool Supported)> candidateStrings = []; /// The selected imm component. private string compositionString = string.Empty; diff --git a/Dalamud/Interface/Internal/DalamudInterface.cs b/Dalamud/Interface/Internal/DalamudInterface.cs index 13e7ff3f7..43f6d6ce7 100644 --- a/Dalamud/Interface/Internal/DalamudInterface.cs +++ b/Dalamud/Interface/Internal/DalamudInterface.cs @@ -7,6 +7,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Bindings.ImPlot; using Dalamud.Configuration.Internal; @@ -39,9 +40,11 @@ using Dalamud.Plugin.Internal; using Dalamud.Plugin.SelfTest.Internal; using Dalamud.Storage.Assets; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Client.System.Framework; using FFXIVClientStructs.FFXIV.Client.UI; using FFXIVClientStructs.FFXIV.Component.GUI; + using Serilog.Events; namespace Dalamud.Interface.Internal; @@ -54,7 +57,7 @@ internal class DalamudInterface : IInternalDisposableService { private const float CreditsDarkeningMaxAlpha = 0.8f; - private static readonly ModuleLog Log = new("DUI"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly Dalamud dalamud; private readonly DalamudConfiguration configuration; @@ -779,7 +782,7 @@ internal class DalamudInterface : IInternalDisposableService if (ImGui.BeginMenu("Set log level..."u8)) { - foreach (var logLevel in Enum.GetValues(typeof(LogEventLevel)).Cast()) + foreach (var logLevel in Enum.GetValues()) { if (ImGui.MenuItem(logLevel + "##logLevelSwitch", (byte*)null, EntryPoint.LogLevelSwitch.MinimumLevel == logLevel)) { @@ -912,7 +915,7 @@ internal class DalamudInterface : IInternalDisposableService if (ImGui.MenuItem("Cause CLR fastfail"u8)) { - unsafe void CauseFastFail() + static unsafe void CauseFastFail() { // ReSharper disable once NotAccessedVariable var texture = Unsafe.AsRef((void*)0x12345678); diff --git a/Dalamud/Interface/Internal/DesignSystem/DalamudComponents.PluginPicker.cs b/Dalamud/Interface/Internal/DesignSystem/DalamudComponents.PluginPicker.cs index 33bcffd38..3a69d55ea 100644 --- a/Dalamud/Interface/Internal/DesignSystem/DalamudComponents.PluginPicker.cs +++ b/Dalamud/Interface/Internal/DesignSystem/DalamudComponents.PluginPicker.cs @@ -1,7 +1,8 @@ -using System.Linq; +using System.Linq; using System.Numerics; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; diff --git a/Dalamud/Interface/Internal/ImGuiClipboardFunctionProvider.cs b/Dalamud/Interface/Internal/ImGuiClipboardFunctionProvider.cs index b7bfd21f1..13623545c 100644 --- a/Dalamud/Interface/Internal/ImGuiClipboardFunctionProvider.cs +++ b/Dalamud/Interface/Internal/ImGuiClipboardFunctionProvider.cs @@ -3,10 +3,12 @@ using System.Runtime.InteropServices; using System.Text; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Game.Gui.Toast; using Dalamud.Interface.Utility; using Dalamud.Logging.Internal; + using TerraFX.Interop.Windows; using static TerraFX.Interop.Windows.Windows; @@ -34,7 +36,7 @@ namespace Dalamud.Interface.Internal; [ServiceManager.EarlyLoadedService] internal sealed unsafe class ImGuiClipboardFunctionProvider : IInternalDisposableService { - private static readonly ModuleLog Log = new(nameof(ImGuiClipboardFunctionProvider)); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly void* clipboardUserDataOriginal; private readonly void* setTextOriginal; private readonly void* getTextOriginal; diff --git a/Dalamud/Interface/Internal/ImGuiInputTextStatePtrExtensions.cs b/Dalamud/Interface/Internal/ImGuiInputTextStatePtrExtensions.cs index ab5fdaac8..e27c20d06 100644 --- a/Dalamud/Interface/Internal/ImGuiInputTextStatePtrExtensions.cs +++ b/Dalamud/Interface/Internal/ImGuiInputTextStatePtrExtensions.cs @@ -110,7 +110,7 @@ internal static unsafe class ImGuiInputTextStatePtrExtensions var text = new Span(self.TextW.Data, self.TextW.Size); if (pos != textLen) - text.Slice(pos, textLen - pos).CopyTo(text[(pos + newText.Length)..]); + text[pos..textLen].CopyTo(text[(pos + newText.Length)..]); newText.CopyTo(text[pos..]); self.Edited = true; diff --git a/Dalamud/Interface/Internal/InterfaceManager.cs b/Dalamud/Interface/Internal/InterfaceManager.cs index 96fcb7dfd..a1954524a 100644 --- a/Dalamud/Interface/Internal/InterfaceManager.cs +++ b/Dalamud/Interface/Internal/InterfaceManager.cs @@ -1,5 +1,4 @@ using System.Collections.Concurrent; -using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; @@ -9,6 +8,7 @@ using System.Threading; using System.Threading.Tasks; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Game; @@ -32,10 +32,13 @@ using Dalamud.Interface.Windowing; using Dalamud.Interface.Windowing.Persistence; using Dalamud.IoC.Internal; using Dalamud.Logging.Internal; +using Dalamud.Memory; using Dalamud.Plugin.Services; using Dalamud.Utility; using Dalamud.Utility.Timing; + using JetBrains.Annotations; + using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -76,10 +79,10 @@ internal partial class InterfaceManager : IInternalDisposableService /// public const float DefaultFontSizePx = (DefaultFontSizePt * 4.0f) / 3.0f; - private static readonly ModuleLog Log = new("INTERFACE"); + private static readonly ModuleLog Log = ModuleLog.Create(); - private readonly ConcurrentBag deferredDisposeTextures = new(); - private readonly ConcurrentBag deferredDisposeDisposables = new(); + private readonly ConcurrentBag deferredDisposeTextures = []; + private readonly ConcurrentBag deferredDisposeDisposables = []; [ServiceManager.ServiceDependency] private readonly DalamudConfiguration dalamudConfiguration = Service.Get(); @@ -500,6 +503,34 @@ internal partial class InterfaceManager : IInternalDisposableService ImGuiHelpers.ClearStacksOnContext(); } + /// + /// Applies immersive dark mode to the game window based on the current system theme setting. + /// + internal void SetImmersiveModeFromSystemTheme() + { + bool useDark = this.IsSystemInDarkMode(); + this.SetImmersiveMode(useDark); + } + + /// + /// Checks whether the system use dark mode. + /// + /// Returns true if dark mode is preferred. + internal bool IsSystemInDarkMode() + { + try + { + using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey( + @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"); + var value = key?.GetValue("AppsUseLightTheme") as int?; + return value != 1; + } + catch + { + return false; + } + } + /// /// Toggle Windows 11 immersive mode on the game window. /// @@ -678,8 +709,7 @@ internal partial class InterfaceManager : IInternalDisposableService if (configuration.SavedStyles == null || configuration.SavedStyles.All(x => x.Name != StyleModelV1.DalamudStandard.Name)) { - configuration.SavedStyles = new List - { StyleModelV1.DalamudStandard, StyleModelV1.DalamudClassic }; + configuration.SavedStyles = [StyleModelV1.DalamudStandard, StyleModelV1.DalamudClassic]; configuration.ChosenStyle = StyleModelV1.DalamudStandard.Name; } else if (configuration.SavedStyles.Count == 1) @@ -744,6 +774,18 @@ internal partial class InterfaceManager : IInternalDisposableService private void WndProcHookManagerOnPreWndProc(WndProcEventArgs args) { + if (args.Message == WM.WM_SETTINGCHANGE) + { + if (this.dalamudConfiguration.WindowIsImmersive) + { + if (MemoryHelper.EqualsZeroTerminatedWideString("ImmersiveColorSet", args.LParam) || + MemoryHelper.EqualsZeroTerminatedWideString("VisualStyleChanged", args.LParam)) + { + this.SetImmersiveModeFromSystemTheme(); + } + } + } + var r = this.backend?.ProcessWndProcW(args.Hwnd, args.Message, args.WParam, args.LParam); if (r is not null) args.SuppressWithValue(r.Value); @@ -858,7 +900,7 @@ internal partial class InterfaceManager : IInternalDisposableService { // Requires that game window to be there, which will be the case once game swap chain is initialized. if (Service.Get().WindowIsImmersive) - this.SetImmersiveMode(true); + this.SetImmersiveModeFromSystemTheme(); } catch (Exception ex) { diff --git a/Dalamud/Interface/Internal/PluginCategoryManager.cs b/Dalamud/Interface/Internal/PluginCategoryManager.cs index d3aea7f57..2b7f0f354 100644 --- a/Dalamud/Interface/Internal/PluginCategoryManager.cs +++ b/Dalamud/Interface/Internal/PluginCategoryManager.cs @@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using CheapLoc; + using Dalamud.Plugin.Internal; using Dalamud.Plugin.Internal.Types; @@ -58,8 +59,8 @@ internal class PluginCategoryManager private CategoryKind currentCategoryKind = CategoryKind.All; private bool isContentDirty; - private Dictionary mapPluginCategories = new(); - private List highlightedCategoryKinds = new(); + private Dictionary mapPluginCategories = []; + private List highlightedCategoryKinds = []; /// /// Type of category group. @@ -513,8 +514,7 @@ internal class PluginCategoryManager this.GroupKind = groupKind; this.nameFunc = nameFunc; - this.Categories = new(); - this.Categories.AddRange(categories); + this.Categories = [.. categories]; } /// diff --git a/Dalamud/Interface/Internal/UiDebug.cs b/Dalamud/Interface/Internal/UiDebug.cs index 82554995b..a79cc1880 100644 --- a/Dalamud/Interface/Internal/UiDebug.cs +++ b/Dalamud/Interface/Internal/UiDebug.cs @@ -11,7 +11,6 @@ using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.System.String; using FFXIVClientStructs.FFXIV.Client.UI.Misc; using FFXIVClientStructs.FFXIV.Component.GUI; -using Lumina.Text.ReadOnly; // Customised version of https://github.com/aers/FFXIVUIDebug @@ -25,8 +24,8 @@ internal unsafe class UiDebug private const int UnitListCount = 18; private readonly bool[] selectedInList = new bool[UnitListCount]; - private readonly string[] listNames = new string[UnitListCount] - { + private readonly string[] listNames = + [ "Depth Layer 1", "Depth Layer 2", "Depth Layer 3", @@ -45,7 +44,7 @@ internal unsafe class UiDebug "Units 16", "Units 17", "Units 18", - }; + ]; private bool doingSearch; private string searchInput = string.Empty; @@ -557,7 +556,7 @@ internal unsafe class UiDebug var name = unitBase->NameString; if (searching) { - if (name == null || !name.ToLowerInvariant().Contains(searchStr.ToLowerInvariant())) continue; + if (name == null || !name.Contains(searchStr, StringComparison.InvariantCultureIgnoreCase)) continue; } noResults = false; diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.AtkValues.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.AtkValues.cs index b31f74264..ed9ed2150 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.AtkValues.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.AtkValues.cs @@ -2,10 +2,9 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Internal.UiDebug2.Utility; -using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; -using Dalamud.Memory; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Component.GUI; using ValueType = FFXIVClientStructs.FFXIV.Component.GUI.ValueType; @@ -28,7 +27,6 @@ public unsafe partial class AddonTree if (tree.Success) { using var tbl = ImRaii.Table("atkUnitBase_atkValueTable"u8, 3, ImGuiTableFlags.Borders | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); - if (tbl.Success) { ImGui.TableSetupColumn("Index"u8); diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.FieldNames.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.FieldNames.cs index 0b1dcb66c..6ff58d657 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.FieldNames.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.FieldNames.cs @@ -41,7 +41,7 @@ public unsafe partial class AddonTree { foreach (var t in from t in ClientStructsAssembly.GetTypes() where t.IsPublic - let xivAddonAttr = (AddonAttribute?)t.GetCustomAttribute(typeof(AddonAttribute), false) + let xivAddonAttr = t.GetCustomAttribute(false) where xivAddonAttr != null where xivAddonAttr.AddonIdentifiers.Contains(this.AddonName) select t) @@ -83,7 +83,7 @@ public unsafe partial class AddonTree foreach (var field in baseType.GetFields(Static | Public | NonPublic | Instance)) { - if (field.GetCustomAttribute(typeof(FieldOffsetAttribute)) is FieldOffsetAttribute offset) + if (field.GetCustomAttribute() is FieldOffsetAttribute offset) { try { diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.cs index 7cb2cc704..2e0874206 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/AddonTree.cs @@ -4,7 +4,6 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Components; -using Dalamud.Interface.Utility; using FFXIVClientStructs.FFXIV.Component.GUI; diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/Events.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/Events.cs index 98c7d9efe..ed1926ce9 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/Events.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/Events.cs @@ -3,6 +3,7 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Component.GUI; using static Dalamud.Bindings.ImGui.ImGuiTableColumnFlags; @@ -28,11 +29,9 @@ public static class Events } using var tree = ImRaii.TreeNode($"Events##{(nint)node:X}eventTree"); - if (tree.Success) { using var tbl = ImRaii.Table($"##{(nint)node:X}eventTable", 7, Resizable | SizingFixedFit | Borders | RowBg); - if (tbl.Success) { ImGui.TableSetupColumn("#"u8, WidthFixed); @@ -50,18 +49,25 @@ public static class Events { ImGui.TableNextColumn(); ImGui.Text($"{i++}"); + ImGui.TableNextColumn(); ImGui.Text($"{evt->State.EventType}"); + ImGui.TableNextColumn(); ImGui.Text($"{evt->Param}"); + ImGui.TableNextColumn(); ImGui.Text($"{evt->State.StateFlags}"); + ImGui.TableNextColumn(); ImGui.Text($"{evt->State.ReturnFlags}"); + ImGui.TableNextColumn(); ImGuiHelpers.ClickToCopyText($"{(nint)evt->Target:X}", default, new Vector4(0.6f, 0.6f, 0.6f, 1)); + ImGui.TableNextColumn(); ImGuiHelpers.ClickToCopyText($"{(nint)evt->Listener:X}", default, new Vector4(0.6f, 0.6f, 0.6f, 1)); + evt = evt->NextEvent; } } diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Component.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Component.cs index 922d226b6..13d559c11 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Component.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Component.cs @@ -1,8 +1,11 @@ using System.Runtime.InteropServices; using Dalamud.Bindings.ImGui; + using FFXIVClientStructs.FFXIV.Component.GUI; +using Lumina.Text.ReadOnly; + using static Dalamud.Interface.Internal.UiDebug2.Utility.Gui; using static Dalamud.Utility.Util; using static FFXIVClientStructs.FFXIV.Component.GUI.ComponentType; @@ -89,14 +92,14 @@ internal unsafe class ComponentNodeTree : ResNodeTree { case TextInput: var textInputComponent = (AtkComponentTextInput*)this.Component; - ImGui.Text($"InputBase Text1: {Marshal.PtrToStringAnsi(new(textInputComponent->AtkComponentInputBase.EvaluatedString.StringPtr))}"); - ImGui.Text($"InputBase Text2: {Marshal.PtrToStringAnsi(new(textInputComponent->AtkComponentInputBase.RawString.StringPtr))}"); + ImGui.Text($"InputBase Text1 (Lumina): {new ReadOnlySeStringSpan(textInputComponent->AtkComponentInputBase.EvaluatedString.AsSpan()).ToMacroString()}"); + ImGui.Text($"InputBase Text2 (Lumina): {new ReadOnlySeStringSpan(textInputComponent->AtkComponentInputBase.RawString.AsSpan()).ToMacroString()}"); // TODO: Reenable when unknowns have been unprivated / named - // ImGui.Text($"Text1: {Marshal.PtrToStringAnsi(new(textInputComponent->UnkText01.StringPtr))}"); - // ImGui.Text($"Text2: {Marshal.PtrToStringAnsi(new(textInputComponent->UnkText02.StringPtr))}"); - ImGui.Text($"AvailableLines: {Marshal.PtrToStringAnsi(new(textInputComponent->AvailableLines.StringPtr))}"); - ImGui.Text($"HighlightedAutoTranslateOptionColorPrefix: {Marshal.PtrToStringAnsi(new(textInputComponent->HighlightedAutoTranslateOptionColorPrefix.StringPtr))}"); - ImGui.Text($"HighlightedAutoTranslateOptionColorSuffix: {Marshal.PtrToStringAnsi(new(textInputComponent->HighlightedAutoTranslateOptionColorSuffix.StringPtr))}"); + // ImGui.Text($"Text1: {new ReadOnlySeStringSpan(textInputComponent->UnkText01.AsSpan()).ToMacroString()}"); + // ImGui.Text($"Text2: {new ReadOnlySeStringSpan(textInputComponent->UnkText02.AsSpan()).ToMacroString()}"); + ImGui.Text($"AvailableLines: {new ReadOnlySeStringSpan(textInputComponent->AvailableLines.AsSpan()).ToMacroString()}"); + ImGui.Text($"HighlightedAutoTranslateOptionColorPrefix: {new ReadOnlySeStringSpan(textInputComponent->HighlightedAutoTranslateOptionColorPrefix.AsSpan()).ToMacroString()}"); + ImGui.Text($"HighlightedAutoTranslateOptionColorSuffix: {new ReadOnlySeStringSpan(textInputComponent->HighlightedAutoTranslateOptionColorSuffix.AsSpan()).ToMacroString()}"); break; case List: case TreeList: diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Counter.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Counter.cs index ff40db37a..2b2adbcee 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Counter.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Counter.cs @@ -1,5 +1,7 @@ using FFXIVClientStructs.FFXIV.Component.GUI; +using Lumina.Text.ReadOnly; + using static Dalamud.Interface.Internal.UiDebug2.Utility.Gui; using static Dalamud.Utility.Util; @@ -30,7 +32,7 @@ internal unsafe partial class CounterNodeTree : ResNodeTree { if (!isEditorOpen) { - PrintFieldValuePairs(("Text", ((AtkCounterNode*)this.Node)->NodeText.ToString())); + PrintFieldValuePairs(("Text", new ReadOnlySeStringSpan(((AtkCounterNode*)this.Node)->NodeText.AsSpan()).ToMacroString())); } } } diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Editor.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Editor.cs index ae6f5fffa..d4e8e61ab 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Editor.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Editor.cs @@ -5,8 +5,11 @@ using Dalamud.Bindings.ImGui; using Dalamud.Interface.Components; using Dalamud.Interface.Internal.UiDebug2.Utility; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Component.GUI; +using Lumina.Text.ReadOnly; + using static Dalamud.Bindings.ImGui.ImGuiColorEditFlags; using static Dalamud.Bindings.ImGui.ImGuiInputTextFlags; using static Dalamud.Bindings.ImGui.ImGuiTableColumnFlags; @@ -27,10 +30,10 @@ internal unsafe partial class ResNodeTree private protected void DrawNodeEditorTable() { using var tbl = ImRaii.Table($"###Editor{(nint)this.Node}", 2, SizingStretchProp | NoHostExtendX); - if (tbl.Success) - { - this.DrawEditorRows(); - } + if (!tbl.Success) + return; + + this.DrawEditorRows(); } /// @@ -59,7 +62,7 @@ internal unsafe partial class ResNodeTree ImGui.TableNextColumn(); ImGui.SetNextItemWidth(150); - if (ImGui.DragFloat2($"##{(nint)this.Node:X}position", ref pos, 1, default, default, "%.0f")) + if (ImGui.DragFloat2($"##{(nint)this.Node:X}position", ref pos, 1, 0, 0, "%.0f")) { this.Node->X = pos.X; this.Node->Y = pos.Y; @@ -73,7 +76,7 @@ internal unsafe partial class ResNodeTree ImGui.Text("Size:"u8); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(150); - if (ImGui.DragFloat2($"##{(nint)this.Node:X}size", ref size, 1, 0, default, "%.0f")) + if (ImGui.DragFloat2($"##{(nint)this.Node:X}size", ref size, 1, 0, 0, "%.0f")) { this.Node->Width = (ushort)Math.Max(size.X, 0); this.Node->Height = (ushort)Math.Max(size.Y, 0); @@ -101,7 +104,7 @@ internal unsafe partial class ResNodeTree ImGui.Text("Origin:"u8); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(150); - if (ImGui.DragFloat2($"##{(nint)this.Node:X}origin", ref origin, 1, default, default, "%.0f")) + if (ImGui.DragFloat2($"##{(nint)this.Node:X}origin", ref origin, 1, 0, 0, "%.0f")) { this.Node->OriginX = origin.X; this.Node->OriginY = origin.Y; @@ -120,7 +123,7 @@ internal unsafe partial class ResNodeTree angle -= 360; } - if (ImGui.DragFloat($"##{(nint)this.Node:X}rotation", ref angle, 0.05f, default, default, "%.2f°")) + if (ImGui.DragFloat($"##{(nint)this.Node:X}rotation", ref angle, 0.05f, 0, 0, "%.2f°")) { this.Node->Rotation = (float)(angle / (180 / Math.PI)); this.Node->DrawFlags |= 0xD; @@ -168,7 +171,6 @@ internal unsafe partial class ResNodeTree ImGui.Text("Add:"u8); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(124); - if (ImGui.DragFloat3($"##{(nint)this.Node:X}addRGB", ref add, 1, -255, 255, "%.0f")) { this.Node->AddRed = (short)add.X; @@ -199,7 +201,7 @@ internal unsafe partial class CounterNodeTree { base.DrawEditorRows(); - var str = this.CntNode->NodeText.ToString(); + var str = new ReadOnlySeStringSpan(this.CntNode->NodeText.AsSpan()).ToMacroString(); ImGui.TableNextRow(); ImGui.TableNextColumn(); @@ -299,7 +301,7 @@ internal unsafe partial class TextNodeTree { base.DrawEditorRows(); - var text = this.TxtNode->NodeText.ToString(); + var text = new ReadOnlySeStringSpan(this.TxtNode->NodeText.AsSpan()).ToMacroString(); var fontIndex = FontList.IndexOf(this.TxtNode->FontType); int fontSize = this.TxtNode->FontSize; var alignment = this.TxtNode->AlignmentType; diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Image.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Image.cs index 260ea4942..45dd63b53 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Image.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Image.cs @@ -2,8 +2,8 @@ using System.Numerics; using System.Runtime.InteropServices; using Dalamud.Bindings.ImGui; -using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Component.GUI; @@ -64,7 +64,6 @@ internal unsafe partial class ImageNodeTree : ResNodeTree } using var tree = ImRaii.TreeNode($"Texture##texture{(nint)this.TexData.Texture->D3D11ShaderResourceView:X}", SpanFullWidth); - if (tree.Success) { PrintFieldValuePairs( diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.NineGrid.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.NineGrid.cs index 489135ed0..1c06dfb40 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.NineGrid.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.NineGrid.cs @@ -1,6 +1,5 @@ using Dalamud.Bindings.ImGui; using Dalamud.Interface.Internal.UiDebug2.Utility; -using Dalamud.Interface.Utility; using FFXIVClientStructs.FFXIV.Component.GUI; @@ -61,10 +60,10 @@ internal unsafe partial class NineGridNodeTree : ImageNodeTree var ngCol = RgbaVector4ToUint(col with { W = 0.75f * col.W }); - ImGui.GetWindowDrawList() - .AddRect(partBegin, partEnd, RgbaVector4ToUint(col)); - ImGui.GetWindowDrawList().AddRect(ngBegin1, ngEnd1, ngCol); - ImGui.GetWindowDrawList().AddRect(ngBegin2, ngEnd2, ngCol); + var windowDrawList = ImGui.GetWindowDrawList(); + windowDrawList.AddRect(partBegin, partEnd, RgbaVector4ToUint(col)); + windowDrawList.AddRect(ngBegin1, ngEnd1, ngCol); + windowDrawList.AddRect(ngBegin2, ngEnd2, ngCol); ImGui.SetCursorPos(cursorLocalPos + uv + new Vector2(0, -20)); ImGui.TextColored(col, $"[#{partId}]\t{part.U}, {part.V}\t{part.Width}x{part.Height}"); diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Res.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Res.cs index 418156811..086a41efc 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Res.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Res.cs @@ -5,8 +5,8 @@ using System.Runtime.InteropServices; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Components; using Dalamud.Interface.Internal.UiDebug2.Utility; -using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Component.GUI; using static Dalamud.Bindings.ImGui.ImGuiCol; @@ -138,7 +138,6 @@ internal unsafe partial class ResNodeTree : IDisposable PrintNodeList(nodeList, count, addonTree); var lineEnd = lineStart with { Y = ImGui.GetCursorScreenPos().Y - 7 }; - if (lineStart.Y < lineEnd.Y) { ImGui.GetWindowDrawList().AddLine(lineStart, lineEnd, RgbaVector4ToUint(color), 1); diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Text.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Text.cs index 1435335db..7ae0d8fca 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Text.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/NodeTree.Text.cs @@ -2,15 +2,15 @@ using System.Numerics; using System.Runtime.InteropServices; using Dalamud.Bindings.ImGui; -using Dalamud.Game.Text.SeStringHandling; -using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Interface.ImGuiSeStringRenderer; -using Dalamud.Interface.Internal.UiDebug2.Utility; using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Client.System.String; using FFXIVClientStructs.FFXIV.Component.GUI; +using Lumina.Text.ReadOnly; + using static Dalamud.Interface.ColorHelpers; using static Dalamud.Interface.Internal.UiDebug2.Utility.Gui; using static Dalamud.Utility.Util; @@ -64,7 +64,7 @@ internal unsafe partial class TextNodeTree : ResNodeTree } catch { - ImGui.Text(Marshal.PtrToStringAnsi(new(this.NodeText.StringPtr)) ?? string.Empty); + ImGui.Text(new ReadOnlySeStringSpan(this.NodeText.AsSpan()).ToMacroString()); } PrintFieldValuePairs( @@ -82,36 +82,24 @@ internal unsafe partial class TextNodeTree : ResNodeTree private void PrintPayloads() { using var tree = ImRaii.TreeNode($"Text Payloads##{(nint)this.Node:X}"); - if (tree.Success) { - var utf8String = this.NodeText; - var seStringBytes = new byte[utf8String.BufUsed]; - for (var i = 0L; i < utf8String.BufUsed; i++) + var idx = 0; + foreach (var payload in new ReadOnlySeString(this.NodeText.AsSpan())) { - seStringBytes[i] = utf8String.StringPtr.Value[i]; - } - - var seString = SeString.Parse(seStringBytes); - for (var i = 0; i < seString.Payloads.Count; i++) - { - var payload = seString.Payloads[i]; - ImGui.Text($"[{i}]"); + ImGui.Text($"[{idx}]"); ImGui.SameLine(); switch (payload.Type) { - case PayloadType.RawText when payload is TextPayload tp: - { - Gui.PrintFieldValuePair("Raw Text", tp.Text ?? string.Empty); + case ReadOnlySePayloadType.Text: + PrintFieldValuePair("Raw Text", payload.ToString()); break; - } - default: - { ImGui.Text(payload.ToString()); break; - } } + + idx++; } } } diff --git a/Dalamud/Interface/Internal/UiDebug2/Browsing/TimelineTree.cs b/Dalamud/Interface/Internal/UiDebug2/Browsing/TimelineTree.cs index 21f4fb54a..10d3d9362 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Browsing/TimelineTree.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Browsing/TimelineTree.cs @@ -5,6 +5,7 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Client.Graphics; using FFXIVClientStructs.FFXIV.Component.GUI; @@ -57,7 +58,6 @@ public readonly unsafe partial struct TimelineTree if (animationCount > 0) { using var tree = ImRaii.TreeNode($"Timeline##{(nint)this.node:X}timeline", SpanFullWidth); - if (tree.Success) { PrintFieldValuePair("Timeline", $"{(nint)this.NodeTimeline:X}"); @@ -89,7 +89,6 @@ public readonly unsafe partial struct TimelineTree if (labelSetCount > 0 && this.Resource->LabelSets is not null) { using var tree = ImRaii.TreeNode($"Timeline Label Sets##{(nint)this.node:X}LabelSets", SpanFullWidth); - if (tree.Success) { this.DrawLabelSets(); @@ -324,7 +323,6 @@ public readonly unsafe partial struct TimelineTree using (ImRaii.PushColor(ImGuiCol.Text, new Vector4(1, 0.65F, 0.4F, 1), isActive)) { using var tree = ImRaii.TreeNode($"[#{a}] [Frames {animation.StartFrameIdx}-{animation.EndFrameIdx}] {(isActive ? " (Active)" : string.Empty)}###{(nint)this.node}animTree{a}"); - if (tree.Success) { PrintFieldValuePair("Animation", $"{address:X}"); @@ -334,7 +332,6 @@ public readonly unsafe partial struct TimelineTree if (columns.Count > 0) { using var tbl = ImRaii.Table($"##{(nint)this.node}animTable{a}", columns.Count, Borders | SizingFixedFit | RowBg | NoHostExtendX); - if (tbl.Success) { foreach (var c in columns) diff --git a/Dalamud/Interface/Internal/UiDebug2/ElementSelector.cs b/Dalamud/Interface/Internal/UiDebug2/ElementSelector.cs index 2ea8fd5d2..46e0c1f8f 100644 --- a/Dalamud/Interface/Internal/UiDebug2/ElementSelector.cs +++ b/Dalamud/Interface/Internal/UiDebug2/ElementSelector.cs @@ -8,6 +8,7 @@ using Dalamud.Interface.Components; using Dalamud.Interface.Internal.UiDebug2.Browsing; using Dalamud.Interface.Internal.UiDebug2.Utility; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Component.GUI; using static System.Globalization.NumberFormatInfo; @@ -159,65 +160,61 @@ internal unsafe class ElementSelector : IDisposable if (ch.Success) { using var gr = ImRaii.Group(); - if (gr.Success) + Gui.PrintFieldValuePair("Mouse Position", $"{mousePos.X}, {mousePos.Y}"); + ImGui.Spacing(); + ImGui.Text("RESULTS:\n"u8); + + var i = 0; + foreach (var a in addonResults) { - Gui.PrintFieldValuePair("Mouse Position", $"{mousePos.X}, {mousePos.Y}"); - ImGui.Spacing(); - ImGui.Text("RESULTS:\n"u8); + var name = a.Addon->NameString; + ImGui.Text($"[Addon] {name}"); - var i = 0; - foreach (var a in addonResults) + using var indent = ImRaii.PushIndent(15.0f); + foreach (var n in a.Nodes) { - var name = a.Addon->NameString; - ImGui.Text($"[Addon] {name}"); - ImGui.Indent(15); - foreach (var n in a.Nodes) + var nSelected = i++ == this.index; + + PrintNodeHeaderOnly(n.Node, nSelected, a.Addon); + + if (nSelected && ImGui.IsMouseClicked(ImGuiMouseButton.Left)) { - var nSelected = i++ == this.index; + this.Active = false; - PrintNodeHeaderOnly(n.Node, nSelected, a.Addon); + this.uiDebug2.SelectedAddonName = a.Addon->NameString; - if (nSelected && ImGui.IsMouseClicked(ImGuiMouseButton.Left)) + var ptrList = new List { (nint)n.Node }; + + var nextNode = n.Node->ParentNode; + while (nextNode != null) { - this.Active = false; - - this.uiDebug2.SelectedAddonName = a.Addon->NameString; - - var ptrList = new List { (nint)n.Node }; - - var nextNode = n.Node->ParentNode; - while (nextNode != null) - { - ptrList.Add((nint)nextNode); - nextNode = nextNode->ParentNode; - } - - SearchResults = [.. ptrList]; - Countdown = 100; - Scrolled = false; + ptrList.Add((nint)nextNode); + nextNode = nextNode->ParentNode; } - if (nSelected) - { - n.NodeBounds.DrawFilled(new(1, 1, 0.2f, 1)); - } + SearchResults = [.. ptrList]; + Countdown = 100; + Scrolled = false; } - ImGui.Indent(-15); + if (nSelected) + { + n.NodeBounds.DrawFilled(new(1, 1, 0.2f, 1)); + } + } + } + + if (i != 0) + { + this.index -= (int)ImGui.GetIO().MouseWheel; + while (this.index < 0) + { + this.index += i; } - if (i != 0) + while (this.index >= i) { - this.index -= (int)ImGui.GetIO().MouseWheel; - while (this.index < 0) - { - this.index += i; - } - - while (this.index >= i) - { - this.index -= i; - } + this.index -= i; } } } diff --git a/Dalamud/Interface/Internal/UiDebug2/Popout.Addon.cs b/Dalamud/Interface/Internal/UiDebug2/Popout.Addon.cs index 4684caa60..69fbc17fb 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Popout.Addon.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Popout.Addon.cs @@ -39,7 +39,7 @@ internal class AddonPopoutWindow : Window, IDisposable /// public override void Draw() { - using var ch = ImRaii.Child($"{this.WindowName}child", new(-1, -1), true); + using var ch = ImRaii.Child($"{this.WindowName}child", Vector2.Zero, true); if (ch.Success) { this.addonTree.Draw(); diff --git a/Dalamud/Interface/Internal/UiDebug2/Popout.Node.cs b/Dalamud/Interface/Internal/UiDebug2/Popout.Node.cs index da4b95256..de476983f 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Popout.Node.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Popout.Node.cs @@ -4,6 +4,7 @@ using Dalamud.Bindings.ImGui; using Dalamud.Interface.Internal.UiDebug2.Browsing; using Dalamud.Interface.Utility.Raii; using Dalamud.Interface.Windowing; + using FFXIVClientStructs.FFXIV.Component.GUI; using static Dalamud.Interface.Internal.UiDebug2.UiDebug2; @@ -38,7 +39,7 @@ internal unsafe class NodePopoutWindow : Window, IDisposable this.PositionCondition = ImGuiCond.Once; this.SizeCondition = ImGuiCond.Once; this.Size = new(700, 200); - this.SizeConstraints = new() { MinimumSize = new(100, 100) }; + this.SizeConstraints = new() { MinimumSize = new Vector2(100, 100) }; } private AddonTree AddonTree => this.resNodeTree.AddonTree; @@ -50,7 +51,7 @@ internal unsafe class NodePopoutWindow : Window, IDisposable { if (this.Node != null && this.AddonTree.ContainsNode(this.Node)) { - using var ch = ImRaii.Child($"{(nint)this.Node:X}popoutChild", new(-1, -1), true); + using var ch = ImRaii.Child($"{(nint)this.Node:X}popoutChild", Vector2.Zero, true); if (ch.Success) { ResNodeTree.GetOrCreate(this.Node, this.AddonTree).Print(null, this.firstDraw); diff --git a/Dalamud/Interface/Internal/UiDebug2/UiDebug2.Sidebar.cs b/Dalamud/Interface/Internal/UiDebug2/UiDebug2.Sidebar.cs index 210da896f..14da58d94 100644 --- a/Dalamud/Interface/Internal/UiDebug2/UiDebug2.Sidebar.cs +++ b/Dalamud/Interface/Internal/UiDebug2/UiDebug2.Sidebar.cs @@ -4,6 +4,7 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Components; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Client.UI; using FFXIVClientStructs.FFXIV.Component.GUI; diff --git a/Dalamud/Interface/Internal/UiDebug2/UiDebug2.cs b/Dalamud/Interface/Internal/UiDebug2/UiDebug2.cs index ce4c6dfeb..2aaef9256 100644 --- a/Dalamud/Interface/Internal/UiDebug2/UiDebug2.cs +++ b/Dalamud/Interface/Internal/UiDebug2/UiDebug2.cs @@ -7,6 +7,7 @@ using Dalamud.Interface.Utility.Raii; using Dalamud.Interface.Windowing; using Dalamud.Logging.Internal; using Dalamud.Plugin.Services; + using FFXIVClientStructs.FFXIV.Component.GUI; using static Dalamud.Bindings.ImGui.ImGuiWindowFlags; @@ -21,6 +22,9 @@ namespace Dalamud.Interface.Internal.UiDebug2; /// internal partial class UiDebug2 : IDisposable { + /// + internal static readonly ModuleLog Log = ModuleLog.Create(); + private readonly ElementSelector elementSelector; /// @@ -31,9 +35,6 @@ internal partial class UiDebug2 : IDisposable this.elementSelector = new(this); } - /// - internal static ModuleLog Log { get; set; } = new("UiDebug2"); - /// internal static IGameGui GameGui { get; set; } = Service.Get(); diff --git a/Dalamud/Interface/Internal/UiDebug2/Utility/Gui.cs b/Dalamud/Interface/Internal/UiDebug2/Utility/Gui.cs index da5f30e68..adfbfa81c 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Utility/Gui.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Utility/Gui.cs @@ -3,6 +3,7 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Client.Graphics; using static Dalamud.Bindings.ImGui.ImGuiCol; @@ -104,12 +105,8 @@ internal static class Gui var index = (int)Math.Floor(prog * tooltips.Length); - using var tt = ImRaii.Tooltip(); - - if (tt.Success) - { - ImGui.Text(tooltips[index]); - } + using var tooltip = ImRaii.Tooltip(); + ImGui.Text(tooltips[index]); return true; } @@ -123,13 +120,14 @@ internal static class Gui { if ((mask & 0b10) > 0) { - ImGui.Dummy(new(padding * ImGui.GetIO().FontGlobalScale)); + ImGuiHelpers.ScaledDummy(padding); } ImGui.Separator(); + if ((mask & 0b01) > 0) { - ImGui.Dummy(new(padding * ImGui.GetIO().FontGlobalScale)); + ImGuiHelpers.ScaledDummy(padding); } } } diff --git a/Dalamud/Interface/Internal/UiDebug2/Utility/NodeBounds.cs b/Dalamud/Interface/Internal/UiDebug2/Utility/NodeBounds.cs index 832c7f357..20feb903f 100644 --- a/Dalamud/Interface/Internal/UiDebug2/Utility/NodeBounds.cs +++ b/Dalamud/Interface/Internal/UiDebug2/Utility/NodeBounds.cs @@ -4,6 +4,7 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; + using FFXIVClientStructs.FFXIV.Component.GUI; using static System.MathF; @@ -61,10 +62,11 @@ public unsafe struct NodeBounds return; } + var backgroundDrawList = ImGui.GetBackgroundDrawList(); if (this.Points.Count == 1) { - ImGui.GetBackgroundDrawList().AddCircle(this.Points[0], 10, RgbaVector4ToUint(col with { W = col.W / 2 }), 12, thickness); - ImGui.GetBackgroundDrawList().AddCircle(this.Points[0], thickness, RgbaVector4ToUint(col), 12, thickness + 1); + backgroundDrawList.AddCircle(this.Points[0], 10, RgbaVector4ToUint(col with { W = col.W / 2 }), 12, thickness); + backgroundDrawList.AddCircle(this.Points[0], thickness, RgbaVector4ToUint(col), 12, thickness + 1); } else { @@ -74,8 +76,7 @@ public unsafe struct NodeBounds path.Add(p); } - ImGui.GetBackgroundDrawList() - .AddPolyline(ref path[0], path.Length, RgbaVector4ToUint(col), ImDrawFlags.Closed, thickness); + backgroundDrawList.AddPolyline(ref path[0], path.Length, RgbaVector4ToUint(col), ImDrawFlags.Closed, thickness); path.Dispose(); } @@ -93,11 +94,11 @@ public unsafe struct NodeBounds return; } + var backgroundDrawList = ImGui.GetBackgroundDrawList(); if (this.Points.Count == 1) { - ImGui.GetBackgroundDrawList() - .AddCircleFilled(this.Points[0], 10, RgbaVector4ToUint(col with { W = col.W / 2 }), 12); - ImGui.GetBackgroundDrawList().AddCircle(this.Points[0], 10, RgbaVector4ToUint(col), 12, thickness); + backgroundDrawList.AddCircleFilled(this.Points[0], 10, RgbaVector4ToUint(col with { W = col.W / 2 }), 12); + backgroundDrawList.AddCircle(this.Points[0], 10, RgbaVector4ToUint(col), 12, thickness); } else { @@ -107,10 +108,8 @@ public unsafe struct NodeBounds path.Add(p); } - ImGui.GetBackgroundDrawList() - .AddConvexPolyFilled(ref path[0], path.Length, RgbaVector4ToUint(col with { W = col.W / 2 })); - ImGui.GetBackgroundDrawList() - .AddPolyline(ref path[0], path.Length, RgbaVector4ToUint(col), ImDrawFlags.Closed, thickness); + backgroundDrawList.AddConvexPolyFilled(ref path[0], path.Length, RgbaVector4ToUint(col with { W = col.W / 2 })); + backgroundDrawList.AddPolyline(ref path[0], path.Length, RgbaVector4ToUint(col), ImDrawFlags.Closed, thickness); path.Dispose(); } diff --git a/Dalamud/Interface/Internal/Windows/ChangelogWindow.cs b/Dalamud/Interface/Internal/Windows/ChangelogWindow.cs index 44626ba31..c67eebfec 100644 --- a/Dalamud/Interface/Internal/Windows/ChangelogWindow.cs +++ b/Dalamud/Interface/Internal/Windows/ChangelogWindow.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Numerics; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Game; @@ -22,6 +23,7 @@ using Dalamud.Plugin.Internal.AutoUpdate; using Dalamud.Plugin.Services; using Dalamud.Storage.Assets; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Client.UI; namespace Dalamud.Interface.Internal.Windows; @@ -85,7 +87,7 @@ internal sealed class ChangelogWindow : Window, IDisposable private AutoUpdateBehavior? chosenAutoUpdateBehavior; - private Dictionary currentFtueLevels = new(); + private Dictionary currentFtueLevels = []; private DateTime? isEligibleSince; private bool openedThroughEligibility; diff --git a/Dalamud/Interface/Internal/Windows/ColorDemoWindow.cs b/Dalamud/Interface/Internal/Windows/ColorDemoWindow.cs index 1bff1d5c1..564e8ca5e 100644 --- a/Dalamud/Interface/Internal/Windows/ColorDemoWindow.cs +++ b/Dalamud/Interface/Internal/Windows/ColorDemoWindow.cs @@ -5,7 +5,6 @@ using System.Reflection; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Colors; -using Dalamud.Interface.Utility; using Dalamud.Interface.Windowing; namespace Dalamud.Interface.Internal.Windows; diff --git a/Dalamud/Interface/Internal/Windows/ComponentDemoWindow.cs b/Dalamud/Interface/Internal/Windows/ComponentDemoWindow.cs index 9096d78de..61435f723 100644 --- a/Dalamud/Interface/Internal/Windows/ComponentDemoWindow.cs +++ b/Dalamud/Interface/Internal/Windows/ComponentDemoWindow.cs @@ -19,14 +19,14 @@ internal sealed class ComponentDemoWindow : Window private static readonly TimeSpan DefaultEasingTime = new(0, 0, 0, 1700); private readonly List<(string Name, Action Demo)> componentDemos; - private readonly IReadOnlyList easings = new Easing[] - { + private readonly IReadOnlyList easings = + [ new InSine(DefaultEasingTime), new OutSine(DefaultEasingTime), new InOutSine(DefaultEasingTime), new InCubic(DefaultEasingTime), new OutCubic(DefaultEasingTime), new InOutCubic(DefaultEasingTime), new InQuint(DefaultEasingTime), new OutQuint(DefaultEasingTime), new InOutQuint(DefaultEasingTime), new InCirc(DefaultEasingTime), new OutCirc(DefaultEasingTime), new InOutCirc(DefaultEasingTime), new InElastic(DefaultEasingTime), new OutElastic(DefaultEasingTime), new InOutElastic(DefaultEasingTime), - }; + ]; private int animationTimeMs = (int)DefaultEasingTime.TotalMilliseconds; private Vector4 defaultColor = ImGuiColors.DalamudOrange; @@ -42,14 +42,14 @@ internal sealed class ComponentDemoWindow : Window this.RespectCloseHotkey = false; - this.componentDemos = new() - { + this.componentDemos = + [ ("Test", ImGuiComponents.Test), ("HelpMarker", HelpMarkerDemo), ("IconButton", IconButtonDemo), ("TextWithLabel", TextWithLabelDemo), ("ColorPickerWithPalette", this.ColorPickerWithPaletteDemo), - }; + ]; } /// diff --git a/Dalamud/Interface/Internal/Windows/ConsoleWindow.cs b/Dalamud/Interface/Internal/Windows/ConsoleWindow.cs index 74df500db..36b0883bb 100644 --- a/Dalamud/Interface/Internal/Windows/ConsoleWindow.cs +++ b/Dalamud/Interface/Internal/Windows/ConsoleWindow.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Numerics; -using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; @@ -22,6 +21,7 @@ using Dalamud.Interface.Windowing; using Dalamud.Plugin.Internal; using Dalamud.Plugin.Services; using Dalamud.Utility; + using Serilog; using Serilog.Events; @@ -40,7 +40,7 @@ internal class ConsoleWindow : Window, IDisposable private readonly RollingList logText; private readonly RollingList filteredLogEntries; - private readonly List pluginFilters = new(); + private readonly List pluginFilters = []; private readonly DalamudConfiguration configuration; diff --git a/Dalamud/Interface/Internal/Windows/Data/DataWindow.cs b/Dalamud/Interface/Internal/Windows/Data/DataWindow.cs index eb0589d59..444b923ab 100644 --- a/Dalamud/Interface/Internal/Windows/Data/DataWindow.cs +++ b/Dalamud/Interface/Internal/Windows/Data/DataWindow.cs @@ -8,6 +8,7 @@ using Dalamud.Interface.Internal.Windows.Data.Widgets; using Dalamud.Interface.Utility; using Dalamud.Interface.Windowing; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.Internal.Windows.Data; @@ -18,7 +19,7 @@ namespace Dalamud.Interface.Internal.Windows.Data; internal class DataWindow : Window, IDisposable { private readonly IDataWindowWidget[] modules = - { + [ new AddonInspectorWidget(), new AddonInspectorWidget2(), new AddonLifecycleWidget(), @@ -44,6 +45,7 @@ internal class DataWindow : Window, IDisposable new ImGuiWidget(), new InventoryWidget(), new KeyStateWidget(), + new LogMessageMonitorWidget(), new MarketBoardWidget(), new NetworkMonitorWidget(), new NounProcessorWidget(), @@ -62,7 +64,7 @@ internal class DataWindow : Window, IDisposable new UiColorWidget(), new UldWidget(), new VfsWidget(), - }; + ]; private readonly IOrderedEnumerable orderedModules; diff --git a/Dalamud/Interface/Internal/Windows/Data/DataWindowWidgetExtensions.cs b/Dalamud/Interface/Internal/Windows/Data/DataWindowWidgetExtensions.cs index a81d3edf3..d286c4428 100644 --- a/Dalamud/Interface/Internal/Windows/Data/DataWindowWidgetExtensions.cs +++ b/Dalamud/Interface/Internal/Windows/Data/DataWindowWidgetExtensions.cs @@ -3,7 +3,6 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.ImGuiNotification.Internal; -using Dalamud.Interface.Utility; namespace Dalamud.Interface.Internal.Windows.Data; diff --git a/Dalamud/Interface/Internal/Windows/Data/GameInventoryTestWidget.cs b/Dalamud/Interface/Internal/Windows/Data/GameInventoryTestWidget.cs index 55f619e9f..2031c66c2 100644 --- a/Dalamud/Interface/Internal/Windows/Data/GameInventoryTestWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/GameInventoryTestWidget.cs @@ -5,9 +5,9 @@ using Dalamud.Configuration.Internal; using Dalamud.Game.Inventory; using Dalamud.Game.Inventory.InventoryEventArgTypes; using Dalamud.Interface.Colors; -using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; using Dalamud.Logging.Internal; + using Serilog.Events; namespace Dalamud.Interface.Internal.Windows.Data; @@ -17,14 +17,14 @@ namespace Dalamud.Interface.Internal.Windows.Data; /// internal class GameInventoryTestWidget : IDataWindowWidget { - private static readonly ModuleLog Log = new(nameof(GameInventoryTestWidget)); + private static readonly ModuleLog Log = ModuleLog.Create(); private GameInventoryPluginScoped? scoped; private bool standardEnabled; private bool rawEnabled; /// - public string[]? CommandShortcuts { get; init; } = { "gameinventorytest" }; + public string[]? CommandShortcuts { get; init; } = ["gameinventorytest"]; /// public string DisplayName { get; init; } = "GameInventory Test"; diff --git a/Dalamud/Interface/Internal/Windows/Data/WidgetUtil.cs b/Dalamud/Interface/Internal/Windows/Data/WidgetUtil.cs index bb8bd8ea1..58cc672e8 100644 --- a/Dalamud/Interface/Internal/Windows/Data/WidgetUtil.cs +++ b/Dalamud/Interface/Internal/Windows/Data/WidgetUtil.cs @@ -1,5 +1,4 @@ using Dalamud.Bindings.ImGui; -using Dalamud.Interface.Utility; namespace Dalamud.Interface.Internal.Windows.Data; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/AddonInspectorWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/AddonInspectorWidget.cs index e11404dec..c8a747239 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/AddonInspectorWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/AddonInspectorWidget.cs @@ -8,7 +8,7 @@ internal class AddonInspectorWidget : IDataWindowWidget private UiDebug? addonInspector; /// - public string[]? CommandShortcuts { get; init; } = { "ai", "addoninspector" }; + public string[]? CommandShortcuts { get; init; } = ["ai", "addoninspector"]; /// public string DisplayName { get; init; } = "Addon Inspector"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/AddonLifecycleWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/AddonLifecycleWidget.cs index 4fb13b81a..0316cc84e 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/AddonLifecycleWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/AddonLifecycleWidget.cs @@ -19,7 +19,7 @@ public class AddonLifecycleWidget : IDataWindowWidget public string DisplayName { get; init; } = "Addon Lifecycle"; /// - [MemberNotNullWhen(true, "AddonLifecycle")] + [MemberNotNullWhen(true, nameof(AddonLifecycle))] public bool Ready { get; set; } private AddonLifecycle? AddonLifecycle { get; set; } diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/AddressesWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/AddressesWidget.cs index 6f41fa46f..06c7ea393 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/AddressesWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/AddressesWidget.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Dalamud.Bindings.ImGui; using Dalamud.Game; @@ -15,7 +15,7 @@ internal class AddressesWidget : IDataWindowWidget private nint sigResult = nint.Zero; /// - public string[]? CommandShortcuts { get; init; } = { "address" }; + public string[]? CommandShortcuts { get; init; } = ["address"]; /// public string DisplayName { get; init; } = "Addresses"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/AetherytesWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/AetherytesWidget.cs index cc5492228..f414a9423 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/AetherytesWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/AetherytesWidget.cs @@ -12,7 +12,7 @@ internal class AetherytesWidget : IDataWindowWidget public bool Ready { get; set; } /// - public string[]? CommandShortcuts { get; init; } = { "aetherytes" }; + public string[]? CommandShortcuts { get; init; } = ["aetherytes"]; /// public string DisplayName { get; init; } = "Aetherytes"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/AtkArrayDataBrowserWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/AtkArrayDataBrowserWidget.cs index c3074e807..03f5ab32e 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/AtkArrayDataBrowserWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/AtkArrayDataBrowserWidget.cs @@ -3,8 +3,10 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; + using FFXIVClientStructs.FFXIV.Client.UI; using FFXIVClientStructs.FFXIV.Component.GUI; + using Lumina.Text.ReadOnly; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; @@ -32,7 +34,7 @@ internal unsafe class AtkArrayDataBrowserWidget : IDataWindowWidget public bool Ready { get; set; } /// - public string[]? CommandShortcuts { get; init; } = { "atkarray" }; + public string[]? CommandShortcuts { get; init; } = ["atkarray"]; /// public string DisplayName { get; init; } = "Atk Array Data"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/BuddyListWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/BuddyListWidget.cs index 06dc1b11e..10efdbae1 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/BuddyListWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/BuddyListWidget.cs @@ -15,7 +15,7 @@ internal class BuddyListWidget : IDataWindowWidget public bool Ready { get; set; } /// - public string[]? CommandShortcuts { get; init; } = { "buddy", "buddylist" }; + public string[]? CommandShortcuts { get; init; } = ["buddy", "buddylist"]; /// public string DisplayName { get; init; } = "Buddy List"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/CommandWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/CommandWidget.cs index f5a521672..1082bf6ca 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/CommandWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/CommandWidget.cs @@ -2,7 +2,6 @@ using System.Linq; using Dalamud.Bindings.ImGui; using Dalamud.Game.Command; -using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; @@ -13,7 +12,7 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; internal class CommandWidget : IDataWindowWidget { /// - public string[]? CommandShortcuts { get; init; } = { "command" }; + public string[]? CommandShortcuts { get; init; } = ["command"]; /// public string DisplayName { get; init; } = "Command"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/ConditionWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/ConditionWidget.cs index 6ecee48ed..e3a737a25 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/ConditionWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/ConditionWidget.cs @@ -1,4 +1,4 @@ -using Dalamud.Bindings.ImGui; +using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.Conditions; using Dalamud.Utility; @@ -13,7 +13,7 @@ internal class ConditionWidget : IDataWindowWidget public bool Ready { get; set; } /// - public string[]? CommandShortcuts { get; init; } = { "condition" }; + public string[]? CommandShortcuts { get; init; } = ["condition"]; /// public string DisplayName { get; init; } = "Condition"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/ConfigurationWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/ConfigurationWidget.cs index f66b50fca..c6a3477ae 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/ConfigurationWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/ConfigurationWidget.cs @@ -1,4 +1,4 @@ -using Dalamud.Configuration.Internal; +using Dalamud.Configuration.Internal; using Dalamud.Utility; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; @@ -9,7 +9,7 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; internal class ConfigurationWidget : IDataWindowWidget { /// - public string[]? CommandShortcuts { get; init; } = { "config", "configuration" }; + public string[]? CommandShortcuts { get; init; } = ["config", "configuration"]; /// public string DisplayName { get; init; } = "Configuration"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/DataShareWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/DataShareWidget.cs index 83db4ac6e..8c9774840 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/DataShareWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/DataShareWidget.cs @@ -11,6 +11,7 @@ using Dalamud.Interface.ImGuiNotification.Internal; using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; using Dalamud.Plugin.Ipc.Internal; + using Newtonsoft.Json; using Formatting = Newtonsoft.Json.Formatting; @@ -28,13 +29,13 @@ internal class DataShareWidget : IDataWindowWidget { private const ImGuiTabItemFlags NoCloseButton = (ImGuiTabItemFlags)(1 << 20); - private readonly List<(string Name, byte[]? Data)> dataView = new(); + private readonly List<(string Name, byte[]? Data)> dataView = []; private int nextTab = -1; private IReadOnlyDictionary? gates; private List? gatesSorted; /// - public string[]? CommandShortcuts { get; init; } = { "datashare" }; + public string[]? CommandShortcuts { get; init; } = ["datashare"]; /// public string DisplayName { get; init; } = "Data Share & Call Gate"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/DtrBarWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/DtrBarWidget.cs index 0a40c9be7..838f11632 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/DtrBarWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/DtrBarWidget.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using System.Threading; using Dalamud.Bindings.ImGui; @@ -21,7 +21,7 @@ internal class DtrBarWidget : IDataWindowWidget, IDisposable private CancellationTokenSource? loadTestThreadCt; /// - public string[]? CommandShortcuts { get; init; } = { "dtr", "dtrbar" }; + public string[]? CommandShortcuts { get; init; } = ["dtr", "dtrbar"]; /// public string DisplayName { get; init; } = "DTR Bar"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/FateTableWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/FateTableWidget.cs index 50ed79b3d..e241f157d 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/FateTableWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/FateTableWidget.cs @@ -1,7 +1,6 @@ using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.Fates; using Dalamud.Interface.Textures.Internal; -using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; @@ -12,7 +11,7 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; internal class FateTableWidget : IDataWindowWidget { /// - public string[]? CommandShortcuts { get; init; } = { "fate", "fatetable" }; + public string[]? CommandShortcuts { get; init; } = ["fate", "fatetable"]; /// public string DisplayName { get; init; } = "Fate Table"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/FlyTextWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/FlyTextWidget.cs index d20aa5cb1..7910daaec 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/FlyTextWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/FlyTextWidget.cs @@ -22,7 +22,7 @@ internal class FlyTextWidget : IDataWindowWidget private Vector4 flyColor = new(1, 0, 0, 1); /// - public string[]? CommandShortcuts { get; init; } = { "flytext" }; + public string[]? CommandShortcuts { get; init; } = ["flytext"]; /// public string DisplayName { get; init; } = "Fly Text"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/FontAwesomeTestWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/FontAwesomeTestWidget.cs index ea4b80247..8beb437ac 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/FontAwesomeTestWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/FontAwesomeTestWidget.cs @@ -27,7 +27,7 @@ internal class FontAwesomeTestWidget : IDataWindowWidget private bool useFixedWidth = false; /// - public string[]? CommandShortcuts { get; init; } = { "fa", "fatest", "fontawesome" }; + public string[]? CommandShortcuts { get; init; } = ["fa", "fatest", "fontawesome"]; /// public string DisplayName { get; init; } = "Font Awesome Test"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/GamePrebakedFontsTestWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/GamePrebakedFontsTestWidget.cs index c653e9185..32ad076db 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/GamePrebakedFontsTestWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/GamePrebakedFontsTestWidget.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Numerics; -using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; @@ -15,6 +14,7 @@ using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.ManagedFontAtlas.Internals; using Dalamud.Interface.Utility; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; @@ -25,11 +25,11 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; internal class GamePrebakedFontsTestWidget : IDataWindowWidget, IDisposable { private static readonly string[] FontScaleModes = - { + [ nameof(FontScaleMode.Default), nameof(FontScaleMode.SkipHandling), nameof(FontScaleMode.UndoGlobalScale), - }; + ]; private ImVectorWrapper testStringBuffer; private IFontAtlas? privateAtlas; @@ -338,7 +338,7 @@ internal class GamePrebakedFontsTestWidget : IDataWindowWidget, IDisposable return; - void TestSingle(ImFontPtr fontPtr, IFontHandle handle) + static void TestSingle(ImFontPtr fontPtr, IFontHandle handle) { var dim = ImGui.CalcTextSizeA(fontPtr, fontPtr.FontSize, float.MaxValue, 0f, "Test string"u8, out _); Log.Information($"{nameof(GamePrebakedFontsTestWidget)}: {handle} => {dim}"); diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/GamepadWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/GamepadWidget.cs index 65e6cd3d6..ed1a4da5b 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/GamepadWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/GamepadWidget.cs @@ -1,4 +1,4 @@ -using Dalamud.Bindings.ImGui; +using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.GamePad; using Dalamud.Utility; @@ -10,7 +10,7 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; internal class GamepadWidget : IDataWindowWidget { /// - public string[]? CommandShortcuts { get; init; } = { "gamepad", "controller" }; + public string[]? CommandShortcuts { get; init; } = ["gamepad", "controller"]; /// public string DisplayName { get; init; } = "Gamepad"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/GaugeWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/GaugeWidget.cs index 7a5a9c89b..09bd29851 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/GaugeWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/GaugeWidget.cs @@ -12,7 +12,7 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; internal class GaugeWidget : IDataWindowWidget { /// - public string[]? CommandShortcuts { get; init; } = { "gauge", "jobgauge", "job" }; + public string[]? CommandShortcuts { get; init; } = ["gauge", "jobgauge", "job"]; /// public string DisplayName { get; init; } = "Job Gauge"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/HookWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/HookWidget.cs index f3e25caf8..ad06e12fd 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/HookWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/HookWidget.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; @@ -6,8 +6,11 @@ using System.Threading.Tasks; using Dalamud.Bindings.ImGui; using Dalamud.Game; using Dalamud.Hooking; + using FFXIVClientStructs.FFXIV.Component.GUI; + using Serilog; + using Windows.Win32.Foundation; using Windows.Win32.UI.WindowsAndMessaging; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/IconBrowserWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/IconBrowserWidget.cs index 0395f4c96..77ca7ec2b 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/IconBrowserWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/IconBrowserWidget.cs @@ -33,7 +33,7 @@ public class IconBrowserWidget : IDataWindowWidget private Vector2 lastWindowSize = Vector2.Zero; /// - public string[]? CommandShortcuts { get; init; } = { "icon", "icons" }; + public string[]? CommandShortcuts { get; init; } = ["icon", "icons"]; /// public string DisplayName { get; init; } = "Icon Browser"; @@ -269,7 +269,7 @@ public class IconBrowserWidget : IDataWindowWidget if (this.valueRange is not null) return; - this.valueRange = new(); + this.valueRange = []; foreach (var (id, _) in this.iconIdsTask!.Result) { if (this.startRange <= id && id < this.stopRange) diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/ImGuiWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/ImGuiWidget.cs index d4afce48d..4327fa12f 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/ImGuiWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/ImGuiWidget.cs @@ -19,11 +19,11 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; /// internal class ImGuiWidget : IDataWindowWidget { - private readonly HashSet notifications = new(); + private readonly HashSet notifications = []; private NotificationTemplate notificationTemplate; /// - public string[]? CommandShortcuts { get; init; } = { "imgui" }; + public string[]? CommandShortcuts { get; init; } = ["imgui"]; /// public string DisplayName { get; init; } = "ImGui"; @@ -334,7 +334,7 @@ internal class ImGuiWidget : IDataWindowWidget private struct NotificationTemplate { public static readonly string[] IconTitles = - { + [ "None (use Type)", "SeIconChar", "FontAwesomeIcon", @@ -344,7 +344,7 @@ internal class ImGuiWidget : IDataWindowWidget "TextureWrap from DalamudAssets(Async)", "TextureWrap from GamePath", "TextureWrap from FilePath", - }; + ]; public static readonly string[] AssetSources = Enum.GetValues() @@ -353,46 +353,46 @@ internal class ImGuiWidget : IDataWindowWidget .ToArray(); public static readonly string[] ProgressModeTitles = - { + [ "Default", "Random", "Increasing", "Increasing & Auto Dismiss", "Indeterminate", - }; + ]; public static readonly string[] TypeTitles = - { + [ nameof(NotificationType.None), nameof(NotificationType.Success), nameof(NotificationType.Warning), nameof(NotificationType.Error), nameof(NotificationType.Info), - }; + ]; public static readonly string[] InitialDurationTitles = - { + [ "Infinite", "1 seconds", "3 seconds (default)", "10 seconds", - }; + ]; public static readonly string[] HoverExtendDurationTitles = - { + [ "Disable", "1 seconds", "3 seconds (default)", "10 seconds", - }; + ]; public static readonly TimeSpan[] Durations = - { + [ TimeSpan.Zero, TimeSpan.FromSeconds(1), NotificationConstants.DefaultDuration, TimeSpan.FromSeconds(10), - }; + ]; public bool ManualContent; public string Content; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/InventoryWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/InventoryWidget.cs index c0ec3d490..f5b26c04c 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/InventoryWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/InventoryWidget.cs @@ -10,7 +10,9 @@ using Dalamud.Interface.Textures.Internal; using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Client.Game; + using Lumina.Excel.Sheets; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/KeyStateWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/KeyStateWidget.cs index fa615ed47..1b45b58fe 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/KeyStateWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/KeyStateWidget.cs @@ -1,4 +1,4 @@ -using Dalamud.Bindings.ImGui; +using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.Keys; using Dalamud.Interface.Colors; @@ -10,7 +10,7 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; internal class KeyStateWidget : IDataWindowWidget { /// - public string[]? CommandShortcuts { get; init; } = { "keystate" }; + public string[]? CommandShortcuts { get; init; } = ["keystate"]; /// public string DisplayName { get; init; } = "KeyState"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/LogMessageMonitorWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/LogMessageMonitorWidget.cs new file mode 100644 index 000000000..fde46f0c7 --- /dev/null +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/LogMessageMonitorWidget.cs @@ -0,0 +1,156 @@ +using System.Buffers; +using System.Collections.Concurrent; +using System.Linq; +using System.Text.Json; +using System.Text.RegularExpressions; + +using Dalamud.Bindings.ImGui; +using Dalamud.Game.Chat; +using Dalamud.Game.Gui; +using Dalamud.Interface.Utility; +using Dalamud.Interface.Utility.Raii; + +using Lumina.Text.ReadOnly; + +using ImGuiTable = Dalamud.Interface.Utility.ImGuiTable; + +namespace Dalamud.Interface.Internal.Windows.Data.Widgets; + +/// +/// Widget to display the LogMessages. +/// +internal class LogMessageMonitorWidget : IDataWindowWidget +{ + private readonly ConcurrentQueue messages = new(); + + private bool trackMessages; + private int trackedMessages; + private Regex? filterRegex; + private string filterString = string.Empty; + + /// + public string[]? CommandShortcuts { get; init; } = ["logmessage"]; + + /// + public string DisplayName { get; init; } = "LogMessage Monitor"; + + /// + public bool Ready { get; set; } + + /// + public void Load() + { + this.trackMessages = false; + this.trackedMessages = 20; + this.filterRegex = null; + this.filterString = string.Empty; + this.messages.Clear(); + this.Ready = true; + } + + /// + public void Draw() + { + var network = Service.Get(); + if (ImGui.Checkbox("Track LogMessages"u8, ref this.trackMessages)) + { + if (this.trackMessages) + { + network.LogMessage += this.OnLogMessage; + } + else + { + network.LogMessage -= this.OnLogMessage; + } + } + + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X / 2); + if (ImGui.DragInt("Stored Number of Messages"u8, ref this.trackedMessages, 0.1f, 1, 512)) + { + this.trackedMessages = Math.Clamp(this.trackedMessages, 1, 512); + } + + if (ImGui.Button("Clear Stored Messages"u8)) + { + this.messages.Clear(); + } + + this.DrawFilterInput(); + + ImGuiTable.DrawTable(string.Empty, this.messages.Where(m => this.filterRegex == null || this.filterRegex.IsMatch(m.Formatted.ExtractText())), this.DrawNetworkPacket, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp, "LogMessageId", "Source", "Target", "Parameters", "Formatted"); + } + + private void DrawNetworkPacket(LogMessageData data) + { + ImGui.TableNextColumn(); + ImGui.Text(data.LogMessageId.ToString()); + + ImGui.TableNextColumn(); + ImGuiHelpers.SeStringWrapped(data.Source); + + ImGui.TableNextColumn(); + ImGuiHelpers.SeStringWrapped(data.Target); + + ImGui.TableNextColumn(); + ImGui.Text(data.Parameters); + + ImGui.TableNextColumn(); + ImGuiHelpers.SeStringWrapped(data.Formatted); + } + + private void DrawFilterInput() + { + var invalidRegEx = this.filterString.Length > 0 && this.filterRegex == null; + using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, 2 * ImGuiHelpers.GlobalScale, invalidRegEx); + using var color = ImRaii.PushColor(ImGuiCol.Border, 0xFF0000FF, invalidRegEx); + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X); + if (!ImGui.InputTextWithHint("##Filter"u8, "Regex Filter..."u8, ref this.filterString, 1024)) + { + return; + } + + if (this.filterString.Length == 0) + { + this.filterRegex = null; + } + else + { + try + { + this.filterRegex = new Regex(this.filterString, RegexOptions.Compiled | RegexOptions.ExplicitCapture); + } + catch + { + this.filterRegex = null; + } + } + } + + private void OnLogMessage(ILogMessage message) + { + var buffer = new ArrayBufferWriter(); + var writer = new Utf8JsonWriter(buffer); + + writer.WriteStartArray(); + for (var i = 0; i < message.ParameterCount; i++) + { + if (message.TryGetStringParameter(i, out var str)) + writer.WriteStringValue(str.ExtractText()); + else if (message.TryGetIntParameter(i, out var num)) + writer.WriteNumberValue(num); + else + writer.WriteNullValue(); + } + + writer.WriteEndArray(); + writer.Flush(); + + this.messages.Enqueue(new LogMessageData(message.LogMessageId, message.SourceEntity?.Name ?? default, message.TargetEntity?.Name ?? default, buffer.WrittenMemory, message.FormatLogMessageForDebugging())); + while (this.messages.Count > this.trackedMessages) + { + this.messages.TryDequeue(out _); + } + } + + private readonly record struct LogMessageData(uint LogMessageId, ReadOnlySeString Source, ReadOnlySeString Target, ReadOnlyMemory Parameters, ReadOnlySeString Formatted); +} diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/MarketBoardWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/MarketBoardWidget.cs index 56de19de7..382c42f91 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/MarketBoardWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/MarketBoardWidget.cs @@ -1,10 +1,9 @@ -using System.Collections.Concurrent; +using System.Collections.Concurrent; using System.Globalization; using Dalamud.Bindings.ImGui; using Dalamud.Game.MarketBoard; using Dalamud.Game.Network.Structures; -using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; using ImGuiTable = Dalamud.Interface.Utility.ImGuiTable; @@ -44,7 +43,7 @@ internal class MarketBoardWidget : IDataWindowWidget } /// - public string[]? CommandShortcuts { get; init; } = { "marketboard" }; + public string[]? CommandShortcuts { get; init; } = ["marketboard"]; /// public string DisplayName { get; init; } = "Market Board"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/NetworkMonitorWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/NetworkMonitorWidget.cs index 4a32a16df..7761a18b4 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/NetworkMonitorWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/NetworkMonitorWidget.cs @@ -42,7 +42,7 @@ internal class NetworkMonitorWidget : IDataWindowWidget } /// - public string[]? CommandShortcuts { get; init; } = { "network", "netmon", "networkmonitor" }; + public string[]? CommandShortcuts { get; init; } = ["network", "netmon", "networkmonitor"]; /// public string DisplayName { get; init; } = "Network Monitor"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/NounProcessorWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/NounProcessorWidget.cs index cbf5c3355..eac8b5a52 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/NounProcessorWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/NounProcessorWidget.cs @@ -8,6 +8,7 @@ using Dalamud.Game.ClientState; using Dalamud.Game.Text.Noun; using Dalamud.Game.Text.Noun.Enums; using Dalamud.Interface.Utility.Raii; + using Lumina.Data; using Lumina.Excel; using Lumina.Excel.Sheets; @@ -60,7 +61,7 @@ internal class NounProcessorWidget : IDataWindowWidget private int amount = 1; /// - public string[]? CommandShortcuts { get; init; } = { "noun" }; + public string[]? CommandShortcuts { get; init; } = ["noun"]; /// public string DisplayName { get; init; } = "Noun Processor"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/ObjectTableWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/ObjectTableWidget.cs index 71fb18352..dd5dc7472 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/ObjectTableWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/ObjectTableWidget.cs @@ -19,7 +19,7 @@ internal class ObjectTableWidget : IDataWindowWidget private float maxCharaDrawDistance = 20.0f; /// - public string[]? CommandShortcuts { get; init; } = { "ot", "objecttable" }; + public string[]? CommandShortcuts { get; init; } = ["ot", "objecttable"]; /// public string DisplayName { get; init; } = "Object Table"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/PartyListWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/PartyListWidget.cs index e43b231be..4033e4f41 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/PartyListWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/PartyListWidget.cs @@ -1,4 +1,4 @@ -using Dalamud.Bindings.ImGui; +using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.Party; using Dalamud.Utility; @@ -12,7 +12,7 @@ internal class PartyListWidget : IDataWindowWidget private bool resolveGameData; /// - public string[]? CommandShortcuts { get; init; } = { "partylist", "party" }; + public string[]? CommandShortcuts { get; init; } = ["partylist", "party"]; /// public string DisplayName { get; init; } = "Party List"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/PluginIpcWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/PluginIpcWidget.cs index 1f1f82cdd..72a02b219 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/PluginIpcWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/PluginIpcWidget.cs @@ -25,7 +25,7 @@ internal class PluginIpcWidget : IDataWindowWidget private string callGateResponse = string.Empty; /// - public string[]? CommandShortcuts { get; init; } = { "ipc" }; + public string[]? CommandShortcuts { get; init; } = ["ipc"]; /// public string DisplayName { get; init; } = "Plugin IPC"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/SeFontTestWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/SeFontTestWidget.cs index 17b7959f6..87c0afe58 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/SeFontTestWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/SeFontTestWidget.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using Dalamud.Bindings.ImGui; using Dalamud.Game.Text; @@ -11,7 +11,7 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; internal class SeFontTestWidget : IDataWindowWidget { /// - public string[]? CommandShortcuts { get; init; } = { "sefont", "sefonttest" }; + public string[]? CommandShortcuts { get; init; } = ["sefont", "sefonttest"]; /// public string DisplayName { get; init; } = "SeFont Test"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/SeStringRendererTestWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/SeStringRendererTestWidget.cs index 6a07152e5..8f5fe7b8a 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/SeStringRendererTestWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/SeStringRendererTestWidget.cs @@ -13,7 +13,9 @@ using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Internal; using Dalamud.Storage.Assets; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Component.GUI; + using Lumina.Excel.Sheets; using Lumina.Text; using Lumina.Text.Parse; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/ServicesWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/ServicesWidget.cs index 78ea6d233..3ddc2a888 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/ServicesWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/ServicesWidget.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Reflection; @@ -16,15 +16,15 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; /// internal class ServicesWidget : IDataWindowWidget { - private readonly Dictionary nodeRects = new(); - private readonly HashSet selectedNodes = new(); - private readonly HashSet tempRelatedNodes = new(); + private readonly Dictionary nodeRects = []; + private readonly HashSet selectedNodes = []; + private readonly HashSet tempRelatedNodes = []; private bool includeUnloadDependencies; private List>? dependencyNodes; /// - public string[]? CommandShortcuts { get; init; } = { "services" }; + public string[]? CommandShortcuts { get; init; } = ["services"]; /// public string DisplayName { get; init; } = "Service Container"; @@ -280,9 +280,9 @@ internal class ServicesWidget : IDataWindowWidget private class ServiceDependencyNode { - private readonly List parents = new(); - private readonly List children = new(); - private readonly List invalidParents = new(); + private readonly List parents = []; + private readonly List children = []; + private readonly List invalidParents = []; private ServiceDependencyNode(Type t) { @@ -370,7 +370,7 @@ internal class ServicesWidget : IDataWindowWidget foreach (var n in CreateTree(includeUnloadDependencies)) { while (res.Count <= n.Level) - res.Add(new()); + res.Add([]); res[n.Level].Add(n); } diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/StartInfoWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/StartInfoWidget.cs index 7fb2cc2bf..c0c38da24 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/StartInfoWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/StartInfoWidget.cs @@ -1,4 +1,5 @@ -using Dalamud.Bindings.ImGui; +using Dalamud.Bindings.ImGui; + using Newtonsoft.Json; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; @@ -9,7 +10,7 @@ namespace Dalamud.Interface.Internal.Windows.Data.Widgets; internal class StartInfoWidget : IDataWindowWidget { /// - public string[]? CommandShortcuts { get; init; } = { "startinfo" }; + public string[]? CommandShortcuts { get; init; } = ["startinfo"]; /// public string DisplayName { get; init; } = "Start Info"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/TargetWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/TargetWidget.cs index 6caf3286d..2e52d7586 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/TargetWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/TargetWidget.cs @@ -14,7 +14,7 @@ internal class TargetWidget : IDataWindowWidget private bool resolveGameData; /// - public string[]? CommandShortcuts { get; init; } = { "target" }; + public string[]? CommandShortcuts { get; init; } = ["target"]; /// public string DisplayName { get; init; } = "Target"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/TaskSchedulerWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/TaskSchedulerWidget.cs index cd72d751e..d9cf0fea2 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/TaskSchedulerWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/TaskSchedulerWidget.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; -using System.Text; using System.Threading; using System.Threading.Tasks; @@ -17,6 +16,7 @@ using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; using Dalamud.Logging.Internal; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; @@ -35,7 +35,7 @@ internal class TaskSchedulerWidget : IDataWindowWidget private CancellationTokenSource taskSchedulerCancelSource = new(); /// - public string[]? CommandShortcuts { get; init; } = { "tasksched", "taskscheduler" }; + public string[]? CommandShortcuts { get; init; } = ["tasksched", "taskscheduler"]; /// public string DisplayName { get; init; } = "Task Scheduler"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/TexWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/TexWidget.cs index 3416a2506..e6a092b6e 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/TexWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/TexWidget.cs @@ -17,6 +17,7 @@ using Dalamud.Interface.Utility.Internal; using Dalamud.Plugin.Services; using Dalamud.Storage.Assets; using Dalamud.Utility; + using TerraFX.Interop.DirectX; using TextureManager = Dalamud.Interface.Textures.Internal.TextureManager; @@ -43,7 +44,7 @@ internal class TexWidget : IDataWindowWidget [DrawBlameTableColumnUserId.NativeAddress] = static x => x.ResourceAddress, }; - private readonly List addedTextures = new(); + private readonly List addedTextures = []; private string allLoadedTexturesTableName = "##table"; private string iconId = "18"; @@ -83,7 +84,7 @@ internal class TexWidget : IDataWindowWidget } /// - public string[]? CommandShortcuts { get; init; } = { "tex", "texture" }; + public string[]? CommandShortcuts { get; init; } = ["tex", "texture"]; /// public string DisplayName { get; init; } = "Tex"; @@ -137,9 +138,9 @@ internal class TexWidget : IDataWindowWidget conf.QueueSave(); } - var allBlames = this.textureManager.BlameTracker; - lock (allBlames) + lock (this.textureManager.BlameTracker) { + var allBlames = this.textureManager.BlameTracker; ImGui.PushID("blames"u8); var sizeSum = allBlames.Sum(static x => Math.Max(0, x.RawSpecs.EstimatedBytes)); if (ImGui.CollapsingHeader( @@ -609,7 +610,7 @@ internal class TexWidget : IDataWindowWidget ImGui.SameLine(); if (ImGuiComponents.IconButton(FontAwesomeIcon.Sync)) - this.textureManager.InvalidatePaths(new[] { texture.SourcePathForDebug }); + this.textureManager.InvalidatePaths([texture.SourcePathForDebug]); if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Call {nameof(ITextureSubstitutionProvider.InvalidatePaths)}."); diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/ToastWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/ToastWidget.cs index 5e5a077c3..6be0a3a85 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/ToastWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/ToastWidget.cs @@ -20,7 +20,7 @@ internal class ToastWidget : IDataWindowWidget private bool questToastCheckmark; /// - public string[]? CommandShortcuts { get; init; } = { "toast" }; + public string[]? CommandShortcuts { get; init; } = ["toast"]; /// public string DisplayName { get; init; } = "Toast"; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/UIColorWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/UIColorWidget.cs index fd3f1d11c..029dc0b75 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/UIColorWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/UIColorWidget.cs @@ -7,6 +7,7 @@ using Dalamud.Data; using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.ImGuiNotification.Internal; using Dalamud.Interface.ImGuiSeStringRenderer.Internal; + using Lumina.Excel.Sheets; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/UldWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/UldWidget.cs index 7c8110301..cc291af1a 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/UldWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/UldWidget.cs @@ -13,6 +13,7 @@ using Dalamud.Interface.Components; using Dalamud.Interface.Textures.Internal; using Dalamud.Interface.Utility; using Dalamud.Memory; + using Lumina.Data.Files; using Lumina.Data.Parsing.Uld; diff --git a/Dalamud/Interface/Internal/Windows/Data/Widgets/VfsWidget.cs b/Dalamud/Interface/Internal/Windows/Data/Widgets/VfsWidget.cs index f044b2989..d01bd7d78 100644 --- a/Dalamud/Interface/Internal/Windows/Data/Widgets/VfsWidget.cs +++ b/Dalamud/Interface/Internal/Windows/Data/Widgets/VfsWidget.cs @@ -4,6 +4,7 @@ using System.IO; using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Storage; + using Serilog; namespace Dalamud.Interface.Internal.Windows.Data.Widgets; @@ -17,7 +18,7 @@ internal class VfsWidget : IDataWindowWidget private int reps = 1; /// - public string[]? CommandShortcuts { get; init; } = { "vfs" }; + public string[]? CommandShortcuts { get; init; } = ["vfs"]; /// public string DisplayName { get; init; } = "VFS Performance"; diff --git a/Dalamud/Interface/Internal/Windows/GamepadModeNotifierWindow.cs b/Dalamud/Interface/Internal/Windows/GamepadModeNotifierWindow.cs index 91f7f02d9..edad04951 100644 --- a/Dalamud/Interface/Internal/Windows/GamepadModeNotifierWindow.cs +++ b/Dalamud/Interface/Internal/Windows/GamepadModeNotifierWindow.cs @@ -1,6 +1,7 @@ using System.Numerics; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; using Dalamud.Interface.Windowing; diff --git a/Dalamud/Interface/Internal/Windows/PluginImageCache.cs b/Dalamud/Interface/Internal/Windows/PluginImageCache.cs index e95d2e1b8..fb77cf1cf 100644 --- a/Dalamud/Interface/Internal/Windows/PluginImageCache.cs +++ b/Dalamud/Interface/Internal/Windows/PluginImageCache.cs @@ -6,7 +6,6 @@ using System.Net; using System.Threading; using System.Threading.Tasks; -using Dalamud.Game; using Dalamud.Interface.Textures.Internal; using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Networking.Http; @@ -15,6 +14,7 @@ using Dalamud.Plugin.Internal.Types; using Dalamud.Plugin.Internal.Types.Manifest; using Dalamud.Storage.Assets; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.Internal.Windows; @@ -51,8 +51,8 @@ internal class PluginImageCache : IInternalDisposableService [ServiceManager.ServiceDependency] private readonly HappyHttpClient happyHttpClient = Service.Get(); - private readonly BlockingCollection>> downloadQueue = new(); - private readonly BlockingCollection> loadQueue = new(); + private readonly BlockingCollection>> downloadQueue = []; + private readonly BlockingCollection> loadQueue = []; private readonly CancellationTokenSource cancelToken = new(); private readonly Task downloadTask; private readonly Task loadTask; @@ -144,7 +144,7 @@ internal class PluginImageCache : IInternalDisposableService this.downloadQueue.CompleteAdding(); this.loadQueue.CompleteAdding(); - if (!Task.WaitAll(new[] { this.loadTask, this.downloadTask }, 4000)) + if (!Task.WaitAll([this.loadTask, this.downloadTask], 4000)) { Log.Error("Plugin Image download/load thread has not cancelled in time"); } @@ -357,7 +357,7 @@ internal class PluginImageCache : IInternalDisposableService try { token.ThrowIfCancellationRequested(); - if (!pendingFuncs.Any()) + if (pendingFuncs.Count == 0) { if (!this.downloadQueue.TryTake(out var taskTuple, -1, token)) return; @@ -373,7 +373,7 @@ internal class PluginImageCache : IInternalDisposableService pendingFuncs = pendingFuncs.OrderBy(x => x.Item1).ToList(); var item1 = pendingFuncs.Last().Item1; - while (pendingFuncs.Any() && pendingFuncs.Last().Item1 == item1) + while (pendingFuncs.Count != 0 && pendingFuncs.Last().Item1 == item1) { token.ThrowIfCancellationRequested(); while (runningTasks.Count >= concurrency) diff --git a/Dalamud/Interface/Internal/Windows/PluginInstaller/DalamudChangelogManager.cs b/Dalamud/Interface/Internal/Windows/PluginInstaller/DalamudChangelogManager.cs index f6171e192..bbc92efb5 100644 --- a/Dalamud/Interface/Internal/Windows/PluginInstaller/DalamudChangelogManager.cs +++ b/Dalamud/Interface/Internal/Windows/PluginInstaller/DalamudChangelogManager.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Net.Http.Json; using System.Threading.Tasks; @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Dalamud.Networking.Http; using Dalamud.Plugin.Internal; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.Internal.Windows.PluginInstaller; diff --git a/Dalamud/Interface/Internal/Windows/PluginInstaller/PluginChangelogEntry.cs b/Dalamud/Interface/Internal/Windows/PluginInstaller/PluginChangelogEntry.cs index 879034fd4..3f964b4b8 100644 --- a/Dalamud/Interface/Internal/Windows/PluginInstaller/PluginChangelogEntry.cs +++ b/Dalamud/Interface/Internal/Windows/PluginInstaller/PluginChangelogEntry.cs @@ -1,5 +1,7 @@ -using CheapLoc; +using CheapLoc; + using Dalamud.Plugin.Internal.Types; + using Serilog; namespace Dalamud.Interface.Internal.Windows.PluginInstaller; diff --git a/Dalamud/Interface/Internal/Windows/PluginInstaller/PluginInstallerWindow.cs b/Dalamud/Interface/Internal/Windows/PluginInstaller/PluginInstallerWindow.cs index 3241015fc..e32d31181 100644 --- a/Dalamud/Interface/Internal/Windows/PluginInstaller/PluginInstallerWindow.cs +++ b/Dalamud/Interface/Internal/Windows/PluginInstaller/PluginInstallerWindow.cs @@ -10,6 +10,7 @@ using System.Threading; using System.Threading.Tasks; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Console; @@ -41,7 +42,7 @@ namespace Dalamud.Interface.Internal.Windows.PluginInstaller; /// internal class PluginInstallerWindow : Window, IDisposable { - private static readonly ModuleLog Log = new("PLUGINW"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly Vector4 changelogBgColor = new(0.114f, 0.584f, 0.192f, 0.678f); private readonly Vector4 changelogTextColor = new(0.812f, 1.000f, 0.816f, 1.000f); @@ -49,7 +50,7 @@ internal class PluginInstallerWindow : Window, IDisposable private readonly PluginImageCache imageCache; private readonly PluginCategoryManager categoryManager = new(); - private readonly List openPluginCollapsibles = new(); + private readonly List openPluginCollapsibles = []; private readonly DateTime timeLoaded; @@ -113,9 +114,9 @@ internal class PluginInstallerWindow : Window, IDisposable private List? updatedPlugins; [SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1201:Elements should appear in the correct order", Justification = "Makes sense like this")] - private List pluginListAvailable = new(); - private List pluginListInstalled = new(); - private List pluginListUpdatable = new(); + private List pluginListAvailable = []; + private List pluginListInstalled = []; + private List pluginListUpdatable = []; private bool hasDevPlugins = false; private bool hasHiddenPlugins = false; @@ -2360,7 +2361,7 @@ internal class PluginInstallerWindow : Window, IDisposable else if (!string.IsNullOrWhiteSpace(manifest.Description)) { const int punchlineLen = 200; - var firstLine = manifest.Description.Split(new[] { '\r', '\n' })[0]; + var firstLine = manifest.Description.Split(['\r', '\n'])[0]; ImGui.TextWrapped(firstLine.Length < punchlineLen ? firstLine diff --git a/Dalamud/Interface/Internal/Windows/PluginInstaller/ProfileManagerWidget.cs b/Dalamud/Interface/Internal/Windows/PluginInstaller/ProfileManagerWidget.cs index fb2719868..c01d7f390 100644 --- a/Dalamud/Interface/Internal/Windows/PluginInstaller/ProfileManagerWidget.cs +++ b/Dalamud/Interface/Internal/Windows/PluginInstaller/ProfileManagerWidget.cs @@ -3,6 +3,7 @@ using System.Numerics; using System.Threading.Tasks; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Interface.Colors; @@ -15,6 +16,7 @@ using Dalamud.Interface.Utility.Raii; using Dalamud.Plugin.Internal; using Dalamud.Plugin.Internal.Profiles; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.Internal.Windows.PluginInstaller; @@ -403,7 +405,7 @@ internal class ProfileManagerWidget ImGui.Text(Locs.StartupBehavior); if (ImGui.BeginCombo("##startupBehaviorPicker"u8, Locs.PolicyToLocalisedName(profile.StartupPolicy))) { - foreach (var policy in Enum.GetValues(typeof(ProfileModelV1.ProfileStartupPolicy)).Cast()) + foreach (var policy in Enum.GetValues()) { var name = Locs.PolicyToLocalisedName(policy); if (ImGui.Selectable(name, profile.StartupPolicy == policy)) diff --git a/Dalamud/Interface/Internal/Windows/PluginStatWindow.cs b/Dalamud/Interface/Internal/Windows/PluginStatWindow.cs index b8e10020e..8b702123c 100644 --- a/Dalamud/Interface/Internal/Windows/PluginStatWindow.cs +++ b/Dalamud/Interface/Internal/Windows/PluginStatWindow.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Reflection; @@ -14,6 +13,7 @@ using Dalamud.Interface.Windowing; using Dalamud.Plugin.Internal; using Dalamud.Plugin.Internal.Types; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.Internal.Windows; @@ -186,7 +186,7 @@ internal class PluginStatWindow : Window ImGui.SameLine(); ImGuiComponents.TextWithLabel("Total Average", $"{totalAverage:F4}ms", "All average update times added together"); ImGui.SameLine(); - ImGuiComponents.TextWithLabel("Collective Average", $"{(statsHistory.Any() ? totalAverage / statsHistory.Length : 0):F4}ms", "Average of all average update times"); + ImGuiComponents.TextWithLabel("Collective Average", $"{(statsHistory.Length != 0 ? totalAverage / statsHistory.Length : 0):F4}ms", "Average of all average update times"); ImGui.InputTextWithHint( "###PluginStatWindow_FrameworkSearch"u8, @@ -230,7 +230,7 @@ internal class PluginStatWindow : Window foreach (var handlerHistory in statsHistory) { - if (!handlerHistory.Value.Any()) + if (handlerHistory.Value.Count == 0) { continue; } diff --git a/Dalamud/Interface/Internal/Windows/ProfilerWindow.cs b/Dalamud/Interface/Internal/Windows/ProfilerWindow.cs index abe8d1584..8ff407cd7 100644 --- a/Dalamud/Interface/Internal/Windows/ProfilerWindow.cs +++ b/Dalamud/Interface/Internal/Windows/ProfilerWindow.cs @@ -19,7 +19,7 @@ public class ProfilerWindow : Window { private double min; private double max; - private List>> occupied = new(); + private List>> occupied = []; /// /// Initializes a new instance of the class. @@ -109,7 +109,7 @@ public class ProfilerWindow : Window } if (depth == this.occupied.Count) - this.occupied.Add(new()); + this.occupied.Add([]); this.occupied[depth].Add(Tuple.Create(timingHandle.StartTime, timingHandle.EndTime)); parentDepthDict[timingHandle.Id] = depth; @@ -188,7 +188,7 @@ public class ProfilerWindow : Window } } - uint eventTextDepth = maxRectDept + 2; + var eventTextDepth = maxRectDept + 2; var eventsXPos = new List(); const float eventsXPosFudge = 5f; diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/SelfTestWindow.cs b/Dalamud/Interface/Internal/Windows/SelfTest/SelfTestWindow.cs index ea8cd0070..0335cafc5 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/SelfTestWindow.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/SelfTestWindow.cs @@ -10,6 +10,7 @@ using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; using Dalamud.Interface.Windowing; using Dalamud.Logging.Internal; + using Dalamud.Plugin.SelfTest; using Dalamud.Plugin.SelfTest.Internal; using Dalamud.Utility; @@ -21,11 +22,11 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest; /// internal class SelfTestWindow : Window { - private static readonly ModuleLog Log = new("AGING"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly SelfTestRegistry selfTestRegistry; - private List visibleSteps = new(); + private List visibleSteps = []; private bool selfTestRunning = false; private SelfTestGroup? currentTestGroup = null; @@ -138,7 +139,7 @@ internal class SelfTestWindow : Window ImGui.SameLine(); var stepNumber = this.currentStep != null ? this.visibleSteps.IndexOf(this.currentStep) : 0; - ImGui.Text($"Step: {stepNumber} / {this.visibleSteps.Count}"); + ImGui.Text($"Step: {stepNumber} / {this.visibleSteps.Count}"); ImGui.Spacing(); diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/AddonLifecycleSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/AddonLifecycleSelfTestStep.cs index d9c9facc7..e2c1a40df 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/AddonLifecycleSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/AddonLifecycleSelfTestStep.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Dalamud.Bindings.ImGui; using Dalamud.Game.Addon.Lifecycle; @@ -23,15 +23,15 @@ internal class AddonLifecycleSelfTestStep : ISelfTestStep /// public AddonLifecycleSelfTestStep() { - this.listeners = new List - { + this.listeners = + [ new(AddonEvent.PostSetup, "Character", this.PostSetup), new(AddonEvent.PostUpdate, "Character", this.PostUpdate), new(AddonEvent.PostDraw, "Character", this.PostDraw), new(AddonEvent.PostRefresh, "Character", this.PostRefresh), new(AddonEvent.PostRequestedUpdate, "Character", this.PostRequestedUpdate), new(AddonEvent.PreFinalize, "Character", this.PreFinalize), - }; + ]; } private enum TestStep diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ChatSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ChatSelfTestStep.cs index 7a2631fbf..851957b4b 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ChatSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ChatSelfTestStep.cs @@ -1,4 +1,5 @@ using Dalamud.Bindings.ImGui; +using Dalamud.Game.Chat; using Dalamud.Game.Gui; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; @@ -12,8 +13,12 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.Steps; internal class ChatSelfTestStep : ISelfTestStep { private int step = 0; - private bool subscribed = false; - private bool hasPassed = false; + private bool subscribedChatMessage = false; + private bool subscribedLogMessage = false; + private bool hasSeenEchoMessage = false; + private bool hasSeenActionMessage = false; + private string actionName = string.Empty; + private string actionUser = string.Empty; /// public string Name => "Test Chat"; @@ -34,20 +39,55 @@ internal class ChatSelfTestStep : ISelfTestStep case 1: ImGui.Text("Type \"/e DALAMUD\" in chat..."); - if (!this.subscribed) + if (!this.subscribedChatMessage) { - this.subscribed = true; + this.subscribedChatMessage = true; chatGui.ChatMessage += this.ChatOnOnChatMessage; } - if (this.hasPassed) + if (this.hasSeenEchoMessage) { chatGui.ChatMessage -= this.ChatOnOnChatMessage; - this.subscribed = false; - return SelfTestStepResult.Pass; + this.subscribedChatMessage = false; + this.step++; } break; + + case 2: + ImGui.Text("Use any action (for example Sprint) or be near a player using an action."); + + if (!this.subscribedLogMessage) + { + this.subscribedLogMessage = true; + chatGui.LogMessage += this.ChatOnLogMessage; + } + + if (this.hasSeenActionMessage) + { + ImGui.Text($"{this.actionUser} used {this.actionName}."); + ImGui.Text("Is this correct?"); + + if (ImGui.Button("Yes")) + { + chatGui.LogMessage -= this.ChatOnLogMessage; + this.subscribedLogMessage = false; + this.step++; + } + + ImGui.SameLine(); + if (ImGui.Button("No")) + { + chatGui.LogMessage -= this.ChatOnLogMessage; + this.subscribedLogMessage = false; + return SelfTestStepResult.Fail; + } + } + + break; + + default: + return SelfTestStepResult.Pass; } return SelfTestStepResult.Waiting; @@ -59,7 +99,9 @@ internal class ChatSelfTestStep : ISelfTestStep var chatGui = Service.Get(); chatGui.ChatMessage -= this.ChatOnOnChatMessage; - this.subscribed = false; + chatGui.LogMessage -= this.ChatOnLogMessage; + this.subscribedChatMessage = false; + this.subscribedLogMessage = false; } private void ChatOnOnChatMessage( @@ -67,7 +109,17 @@ internal class ChatSelfTestStep : ISelfTestStep { if (type == XivChatType.Echo && message.TextValue == "DALAMUD") { - this.hasPassed = true; + this.hasSeenEchoMessage = true; + } + } + + private void ChatOnLogMessage(ILogMessage message) + { + if (message.LogMessageId == 533 && message.TryGetStringParameter(0, out var value)) + { + this.hasSeenActionMessage = true; + this.actionUser = message.SourceEntity?.Name.ExtractText() ?? ""; + this.actionName = value.ExtractText(); } } } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/CompletionSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/CompletionSelfTestStep.cs index a34b058bd..1f33e5dd2 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/CompletionSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/CompletionSelfTestStep.cs @@ -1,6 +1,5 @@ using Dalamud.Bindings.ImGui; using Dalamud.Game.Command; -using Dalamud.Interface.Utility; using Dalamud.Plugin.SelfTest; namespace Dalamud.Interface.Internal.Windows.SelfTest.Steps; diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ConditionSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ConditionSelfTestStep.cs index 89083da48..1c9b589d0 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ConditionSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ConditionSelfTestStep.cs @@ -1,6 +1,7 @@ using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.Conditions; using Dalamud.Plugin.SelfTest; + using Serilog; namespace Dalamud.Interface.Internal.Windows.SelfTest.Steps; diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ContextMenuSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ContextMenuSelfTestStep.cs index 0fe5b4443..b61c62589 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ContextMenuSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/ContextMenuSelfTestStep.cs @@ -9,8 +9,10 @@ using Dalamud.Game.Gui.ContextMenu; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Plugin.SelfTest; + using Lumina.Excel; using Lumina.Excel.Sheets; + using Serilog; namespace Dalamud.Interface.Internal.Windows.SelfTest.Steps; diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/FrameworkTaskSchedulerSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/FrameworkTaskSchedulerSelfTestStep.cs index eb6909fa7..c5f3ab76b 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/FrameworkTaskSchedulerSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/FrameworkTaskSchedulerSelfTestStep.cs @@ -4,8 +4,6 @@ using Dalamud.Game; using Dalamud.Plugin.SelfTest; using Dalamud.Utility; -using Microsoft.VisualBasic.Logging; - using Log = Serilog.Log; namespace Dalamud.Interface.Internal.Windows.SelfTest.Steps; diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/LuminaSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/LuminaSelfTestStep.cs index 741dd71b1..dd8a16689 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/LuminaSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/LuminaSelfTestStep.cs @@ -1,6 +1,7 @@ using Dalamud.Data; using Dalamud.Plugin.SelfTest; using Dalamud.Utility; + using Lumina.Excel; namespace Dalamud.Interface.Internal.Windows.SelfTest.Steps; diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/MarketBoardSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/MarketBoardSelfTestStep.cs index 6a45f343a..ff6b64383 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/MarketBoardSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/MarketBoardSelfTestStep.cs @@ -4,7 +4,6 @@ using System.Linq; using Dalamud.Bindings.ImGui; using Dalamud.Game.MarketBoard; using Dalamud.Game.Network.Structures; -using Dalamud.Interface.Utility; using Dalamud.Plugin.SelfTest; namespace Dalamud.Interface.Internal.Windows.SelfTest.Steps; diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/NamePlateSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/NamePlateSelfTestStep.cs index 9cc6045a6..7136c8801 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/NamePlateSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/NamePlateSelfTestStep.cs @@ -36,7 +36,7 @@ internal class NamePlateSelfTestStep : ISelfTestStep namePlateGui.OnNamePlateUpdate += this.OnNamePlateUpdate; namePlateGui.OnDataUpdate += this.OnDataUpdate; namePlateGui.RequestRedraw(); - this.updateCount = new Dictionary(); + this.updateCount = []; this.currentSubStep++; break; diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/SheetRedirectResolverSelfTestStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/SheetRedirectResolverSelfTestStep.cs index c285fda46..c99ec91de 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/Steps/SheetRedirectResolverSelfTestStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/Steps/SheetRedirectResolverSelfTestStep.cs @@ -4,6 +4,7 @@ using Dalamud.Bindings.ImGui; using Dalamud.Game; using Dalamud.Game.Text.Evaluator.Internal; using Dalamud.Plugin.SelfTest; + using FFXIVClientStructs.FFXIV.Client.System.String; using FFXIVClientStructs.FFXIV.Client.UI.Misc; diff --git a/Dalamud/Interface/Internal/Windows/Settings/SettingsWindow.cs b/Dalamud/Interface/Internal/Windows/Settings/SettingsWindow.cs index 62c931b20..aa8d1dc3a 100644 --- a/Dalamud/Interface/Internal/Windows/Settings/SettingsWindow.cs +++ b/Dalamud/Interface/Internal/Windows/Settings/SettingsWindow.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Numerics; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Interface.Colors; diff --git a/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabAbout.cs b/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabAbout.cs index 4785ceb3c..1d5eebb85 100644 --- a/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabAbout.cs +++ b/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabAbout.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Numerics; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Game.Gui; using Dalamud.Interface.GameFonts; @@ -15,6 +16,7 @@ using Dalamud.Interface.Utility.Raii; using Dalamud.Plugin.Internal; using Dalamud.Storage.Assets; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Client.Game.UI; namespace Dalamud.Interface.Internal.Windows.Settings.Tabs; diff --git a/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabAutoUpdate.cs b/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabAutoUpdate.cs index 6b99c5c24..b03a0f51c 100644 --- a/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabAutoUpdate.cs +++ b/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabAutoUpdate.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Numerics; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Interface.Colors; diff --git a/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabDtr.cs b/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabDtr.cs index 4b055b35b..18382b1f8 100644 --- a/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabDtr.cs +++ b/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabDtr.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Numerics; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Game.Gui.Dtr; diff --git a/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabLook.cs b/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabLook.cs index 9b2c418b6..d8bf31bfd 100644 --- a/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabLook.cs +++ b/Dalamud/Interface/Internal/Windows/Settings/Tabs/SettingsTabLook.cs @@ -4,6 +4,7 @@ using System.Numerics; using System.Text; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Game; @@ -65,7 +66,14 @@ internal sealed class SettingsTabLook : SettingsTab { try { - Service.GetNullable()?.SetImmersiveMode(b); + if (b) + { + Service.GetNullable()?.SetImmersiveModeFromSystemTheme(); + } + else + { + Service.GetNullable()?.SetImmersiveMode(false); + } } catch (Exception ex) { diff --git a/Dalamud/Interface/Internal/Windows/Settings/Widgets/EnumSettingsEntry{T}.cs b/Dalamud/Interface/Internal/Windows/Settings/Widgets/EnumSettingsEntry{T}.cs index 8fb91940e..096e408b8 100644 --- a/Dalamud/Interface/Internal/Windows/Settings/Widgets/EnumSettingsEntry{T}.cs +++ b/Dalamud/Interface/Internal/Windows/Settings/Widgets/EnumSettingsEntry{T}.cs @@ -2,8 +2,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; -using CheapLoc; - using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Interface.Colors; diff --git a/Dalamud/Interface/Internal/Windows/Settings/Widgets/ThirdRepoSettingsEntry.cs b/Dalamud/Interface/Internal/Windows/Settings/Widgets/ThirdRepoSettingsEntry.cs index 5737b44db..daa91420f 100644 --- a/Dalamud/Interface/Internal/Windows/Settings/Widgets/ThirdRepoSettingsEntry.cs +++ b/Dalamud/Interface/Internal/Windows/Settings/Widgets/ThirdRepoSettingsEntry.cs @@ -5,6 +5,7 @@ using System.Numerics; using System.Threading.Tasks; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration; using Dalamud.Configuration.Internal; diff --git a/Dalamud/Interface/Internal/Windows/StyleEditor/StyleEditorWindow.cs b/Dalamud/Interface/Internal/Windows/StyleEditor/StyleEditorWindow.cs index f9e8022a1..4add874ba 100644 --- a/Dalamud/Interface/Internal/Windows/StyleEditor/StyleEditorWindow.cs +++ b/Dalamud/Interface/Internal/Windows/StyleEditor/StyleEditorWindow.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Reflection; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Interface.Colors; @@ -12,6 +12,7 @@ using Dalamud.Interface.Style; using Dalamud.Interface.Utility; using Dalamud.Interface.Windowing; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.Internal.Windows.StyleEditor; @@ -50,7 +51,7 @@ public class StyleEditorWindow : Window this.didSave = false; var config = Service.Get(); - config.SavedStyles ??= new List(); + config.SavedStyles ??= []; this.currentSel = config.SavedStyles.FindIndex(x => x.Name == config.ChosenStyle); this.initialStyle = config.ChosenStyle; diff --git a/Dalamud/Interface/Internal/Windows/TitleScreenMenuWindow.cs b/Dalamud/Interface/Internal/Windows/TitleScreenMenuWindow.cs index ec9440e0e..9d4f7ab04 100644 --- a/Dalamud/Interface/Internal/Windows/TitleScreenMenuWindow.cs +++ b/Dalamud/Interface/Internal/Windows/TitleScreenMenuWindow.cs @@ -22,8 +22,11 @@ using Dalamud.Plugin.Internal; using Dalamud.Plugin.Services; using Dalamud.Storage.Assets; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Component.GUI; + using Lumina.Text.ReadOnly; + using Serilog; namespace Dalamud.Interface.Internal.Windows; @@ -47,9 +50,9 @@ internal class TitleScreenMenuWindow : Window, IDisposable private readonly Lazy shadeTexture; private readonly AddonLifecycleEventListener versionStringListener; - private readonly Dictionary shadeEasings = new(); - private readonly Dictionary moveEasings = new(); - private readonly Dictionary logoEasings = new(); + private readonly Dictionary shadeEasings = []; + private readonly Dictionary moveEasings = []; + private readonly Dictionary logoEasings = []; private readonly IConsoleVariable showTsm; diff --git a/Dalamud/Interface/ManagedFontAtlas/FontAtlasBuildToolkitUtilities.cs b/Dalamud/Interface/ManagedFontAtlas/FontAtlasBuildToolkitUtilities.cs index 2e497b6cd..b2b2c2ab1 100644 --- a/Dalamud/Interface/ManagedFontAtlas/FontAtlasBuildToolkitUtilities.cs +++ b/Dalamud/Interface/ManagedFontAtlas/FontAtlasBuildToolkitUtilities.cs @@ -3,7 +3,6 @@ using System.Runtime.CompilerServices; using System.Text.Unicode; using Dalamud.Bindings.ImGui; -using Dalamud.Interface.Utility; namespace Dalamud.Interface.ManagedFontAtlas; diff --git a/Dalamud/Interface/ManagedFontAtlas/Internals/DelegateFontHandle.cs b/Dalamud/Interface/ManagedFontAtlas/Internals/DelegateFontHandle.cs index f2c91d264..0e2f503b4 100644 --- a/Dalamud/Interface/ManagedFontAtlas/Internals/DelegateFontHandle.cs +++ b/Dalamud/Interface/ManagedFontAtlas/Internals/DelegateFontHandle.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using System.Threading; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; @@ -34,8 +35,8 @@ internal sealed class DelegateFontHandle : FontHandle /// internal sealed class HandleManager : IFontHandleManager { - private readonly HashSet handles = new(); - private readonly object syncRoot = new(); + private readonly HashSet handles = []; + private readonly Lock syncRoot = new(); /// /// Initializes a new instance of the class. @@ -95,8 +96,8 @@ internal sealed class DelegateFontHandle : FontHandle private static readonly ModuleLog Log = new($"{nameof(DelegateFontHandle)}.{nameof(HandleSubstance)}"); // Owned by this class, but ImFontPtr values still do not belong to this. - private readonly Dictionary fonts = new(); - private readonly Dictionary buildExceptions = new(); + private readonly Dictionary fonts = []; + private readonly Dictionary buildExceptions = []; /// /// Initializes a new instance of the class. diff --git a/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.BuildToolkit.cs b/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.BuildToolkit.cs index 41c87fd39..97dc29804 100644 --- a/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.BuildToolkit.cs +++ b/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.BuildToolkit.cs @@ -15,6 +15,7 @@ using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Interface.Utility; using Dalamud.Storage.Assets; using Dalamud.Utility; + using TerraFX.Interop.DirectX; namespace Dalamud.Interface.ManagedFontAtlas.Internals; @@ -24,8 +25,7 @@ namespace Dalamud.Interface.ManagedFontAtlas.Internals; /// internal sealed partial class FontAtlasFactory { - private static readonly Dictionary> PairAdjustmentsCache = - new(); + private static readonly Dictionary> PairAdjustmentsCache = []; /// /// Implementations for and @@ -43,7 +43,7 @@ internal sealed partial class FontAtlasFactory private readonly GamePrebakedFontHandle.HandleSubstance gameFontHandleSubstance; private readonly FontAtlasFactory factory; private readonly FontAtlasBuiltData data; - private readonly List registeredPostBuildActions = new(); + private readonly List registeredPostBuildActions = []; /// /// Initializes a new instance of the class. @@ -85,7 +85,7 @@ internal sealed partial class FontAtlasFactory /// /// Gets the font scale modes. /// - private Dictionary FontScaleModes { get; } = new(); + private Dictionary FontScaleModes { get; } = []; /// public void Dispose() => this.disposeAfterBuild.Dispose(); @@ -170,7 +170,7 @@ internal sealed partial class FontAtlasFactory }; if (fontConfig.GlyphRanges is not { Length: > 0 } ranges) - ranges = new ushort[] { 1, 0xFFFE, 0 }; + ranges = [1, 0xFFFE, 0]; raw.GlyphRanges = (ushort*)this.DisposeAfterBuild( GCHandle.Alloc(ranges, GCHandleType.Pinned)).AddrOfPinnedObject(); @@ -188,7 +188,7 @@ internal sealed partial class FontAtlasFactory { if (!PairAdjustmentsCache.TryGetValue(hashIdent, out pairAdjustments)) { - PairAdjustmentsCache.Add(hashIdent, pairAdjustments = new()); + PairAdjustmentsCache.Add(hashIdent, pairAdjustments = []); try { pairAdjustments.AddRange(TrueTypeUtils.ExtractHorizontalPairAdjustments(raw).ToArray()); @@ -382,7 +382,7 @@ internal sealed partial class FontAtlasFactory DalamudAsset.FontAwesomeFreeSolid, fontConfig with { - GlyphRanges = new ushort[] { FontAwesomeIconMin, FontAwesomeIconMax, 0 }, + GlyphRanges = [FontAwesomeIconMin, FontAwesomeIconMax, 0], }); /// @@ -391,12 +391,12 @@ internal sealed partial class FontAtlasFactory DalamudAsset.LodestoneGameSymbol, fontConfig with { - GlyphRanges = new ushort[] - { + GlyphRanges = + [ GamePrebakedFontHandle.SeIconCharMin, GamePrebakedFontHandle.SeIconCharMax, 0, - }, + ], }); /// @@ -629,7 +629,7 @@ internal sealed partial class FontAtlasFactory { this.AddDalamudAssetFont( DalamudAsset.NotoSansJpMedium, - new() { GlyphRanges = new ushort[] { ' ', ' ', '\0' }, SizePx = 1 }); + new() { GlyphRanges = [' ', ' ', '\0'], SizePx = 1 }); } if (!this.NewImAtlas.Build()) diff --git a/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.Implementation.cs b/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.Implementation.cs index 430f26127..323d4173d 100644 --- a/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.Implementation.cs +++ b/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.Implementation.cs @@ -1,4 +1,4 @@ -// #define VeryVerboseLog +// #define VeryVerboseLog using System.Collections.Generic; using System.Diagnostics; @@ -41,9 +41,9 @@ internal sealed partial class FontAtlasFactory /// /// If set, disables concurrent font build operation. /// - private static readonly object? NoConcurrentBuildOperationLock = null; // new(); + private static readonly Lock? NoConcurrentBuildOperationLock = null; // new(); - private static readonly ModuleLog Log = new(nameof(FontAtlasFactory)); + private static readonly ModuleLog Log = ModuleLog.Create(); private static readonly Task EmptyTask = Task.FromResult(default(FontAtlasBuiltData)); @@ -66,10 +66,10 @@ internal sealed partial class FontAtlasFactory try { - var substancesList = this.substances = new(); + var substancesList = this.substances = []; this.Garbage.Add(() => substancesList.Clear()); - var wrapsCopy = this.wraps = new(); + var wrapsCopy = this.wraps = []; this.Garbage.Add(() => wrapsCopy.Clear()); var atlasPtr = ImGui.ImFontAtlas(); @@ -115,16 +115,14 @@ internal sealed partial class FontAtlasFactory public void AddExistingTexture(IDalamudTextureWrap wrap) { - if (this.wraps is null) - throw new ObjectDisposedException(nameof(FontAtlasBuiltData)); + ObjectDisposedException.ThrowIf(this.wraps == null, this); this.wraps.Add(this.Garbage.Add(wrap)); } public int AddNewTexture(IDalamudTextureWrap wrap, bool disposeOnError) { - if (this.wraps is null) - throw new ObjectDisposedException(nameof(FontAtlasBuiltData)); + ObjectDisposedException.ThrowIf(this.wraps == null, this); var handle = wrap.Handle; var index = this.ImTextures.IndexOf(x => x.TexID == handle); @@ -254,7 +252,7 @@ internal sealed partial class FontAtlasFactory private readonly GamePrebakedFontHandle.HandleManager gameFontHandleManager; private readonly IFontHandleManager[] fontHandleManagers; - private readonly object syncRoot = new(); + private readonly Lock syncRoot = new(); private Task buildTask = EmptyTask; private FontAtlasBuiltData? builtData; @@ -292,13 +290,13 @@ internal sealed partial class FontAtlasFactory this.factory.InterfaceManager.AfterBuildFonts += this.OnRebuildRecommend; this.disposables.Add(() => this.factory.InterfaceManager.AfterBuildFonts -= this.OnRebuildRecommend); - this.fontHandleManagers = new IFontHandleManager[] - { + this.fontHandleManagers = + [ this.delegateFontHandleManager = this.disposables.Add( new DelegateFontHandle.HandleManager(atlasName)), this.gameFontHandleManager = this.disposables.Add( new GamePrebakedFontHandle.HandleManager(atlasName, factory)), - }; + ]; foreach (var fhm in this.fontHandleManagers) fhm.RebuildRecommend += this.OnRebuildRecommend; } diff --git a/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.cs b/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.cs index 6ae810dec..55c2acdbc 100644 --- a/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.cs +++ b/Dalamud/Interface/ManagedFontAtlas/Internals/FontAtlasFactory.cs @@ -18,7 +18,9 @@ using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Plugin.Internal.Types; using Dalamud.Storage.Assets; using Dalamud.Utility; + using Lumina.Data.Files; + using TerraFX.Interop.DirectX; namespace Dalamud.Interface.ManagedFontAtlas.Internals; diff --git a/Dalamud/Interface/ManagedFontAtlas/Internals/FontHandle.cs b/Dalamud/Interface/ManagedFontAtlas/Internals/FontHandle.cs index 98a823deb..ce67b0eec 100644 --- a/Dalamud/Interface/ManagedFontAtlas/Internals/FontHandle.cs +++ b/Dalamud/Interface/ManagedFontAtlas/Internals/FontHandle.cs @@ -10,6 +10,7 @@ using Dalamud.Interface.Utility; using Dalamud.Plugin.Internal; using Dalamud.Plugin.Internal.Types; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface.ManagedFontAtlas.Internals; @@ -20,7 +21,7 @@ namespace Dalamud.Interface.ManagedFontAtlas.Internals; internal abstract class FontHandle : IFontHandle { private const int NonMainThreadFontAccessWarningCheckInterval = 10000; - private static readonly ConditionalWeakTable NonMainThreadFontAccessWarning = new(); + private static readonly ConditionalWeakTable NonMainThreadFontAccessWarning = []; private static long nextNonMainThreadFontAccessWarningCheck; private readonly List pushedFonts = new(8); diff --git a/Dalamud/Interface/ManagedFontAtlas/Internals/GamePrebakedFontHandle.cs b/Dalamud/Interface/ManagedFontAtlas/Internals/GamePrebakedFontHandle.cs index f6904db7c..81c7d4d89 100644 --- a/Dalamud/Interface/ManagedFontAtlas/Internals/GamePrebakedFontHandle.cs +++ b/Dalamud/Interface/ManagedFontAtlas/Internals/GamePrebakedFontHandle.cs @@ -4,14 +4,15 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reactive.Disposables; +using System.Threading; using Dalamud.Bindings.ImGui; using Dalamud.Game.Text; using Dalamud.Interface.GameFonts; -using Dalamud.Interface.Internal; using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Interface.Utility; using Dalamud.Utility; + using Lumina.Data.Files; using Vector4 = System.Numerics.Vector4; @@ -101,9 +102,9 @@ internal class GamePrebakedFontHandle : FontHandle /// internal sealed class HandleManager : IFontHandleManager { - private readonly Dictionary gameFontsRc = new(); - private readonly HashSet handles = new(); - private readonly object syncRoot = new(); + private readonly Dictionary gameFontsRc = []; + private readonly HashSet handles = []; + private readonly Lock syncRoot = new(); /// /// Initializes a new instance of the class. @@ -188,11 +189,11 @@ internal class GamePrebakedFontHandle : FontHandle private readonly HashSet gameFontStyles; // Owned by this class, but ImFontPtr values still do not belong to this. - private readonly Dictionary fonts = new(); - private readonly Dictionary buildExceptions = new(); - private readonly List<(ImFontPtr Font, GameFontStyle Style, ushort[]? Ranges)> attachments = new(); + private readonly Dictionary fonts = []; + private readonly Dictionary buildExceptions = []; + private readonly List<(ImFontPtr Font, GameFontStyle Style, ushort[]? Ranges)> attachments = []; - private readonly HashSet templatedFonts = new(); + private readonly HashSet templatedFonts = []; /// /// Initializes a new instance of the class. @@ -415,7 +416,7 @@ internal class GamePrebakedFontHandle : FontHandle DalamudAsset.NotoSansJpMedium, new() { - GlyphRanges = new ushort[] { ' ', ' ', '\0' }, + GlyphRanges = [' ', ' ', '\0'], SizePx = sizePx, }); this.templatedFonts.Add(font); @@ -449,8 +450,8 @@ internal class GamePrebakedFontHandle : FontHandle public readonly GameFontStyle BaseStyle; public readonly GameFontFamilyAndSizeAttribute BaseAttr; public readonly int TexCount; - public readonly Dictionary Ranges = new(); - public readonly List<(int RectId, int FdtGlyphIndex)> Rects = new(); + public readonly Dictionary Ranges = []; + public readonly List<(int RectId, int FdtGlyphIndex)> Rects = []; public readonly ushort[] RectLookup = new ushort[0x10000]; public readonly FdtFileView Fdt; public readonly ImFontPtr FullRangeFont; diff --git a/Dalamud/Interface/ManagedFontAtlas/Internals/LockedImFont.cs b/Dalamud/Interface/ManagedFontAtlas/Internals/LockedImFont.cs index b7f5ad12b..9eb90fe16 100644 --- a/Dalamud/Interface/ManagedFontAtlas/Internals/LockedImFont.cs +++ b/Dalamud/Interface/ManagedFontAtlas/Internals/LockedImFont.cs @@ -34,8 +34,7 @@ internal class LockedImFont : ILockedImFont /// public ILockedImFont NewRef() { - if (this.owner is null) - throw new ObjectDisposedException(nameof(LockedImFont)); + ObjectDisposedException.ThrowIf(this.owner == null, this); var newRef = new LockedImFont(this.ImFont, this.owner); this.owner.AddRef(); diff --git a/Dalamud/Interface/ManagedFontAtlas/Internals/SimplePushedFont.cs b/Dalamud/Interface/ManagedFontAtlas/Internals/SimplePushedFont.cs index 0d6ad5c7c..ed40ce28b 100644 --- a/Dalamud/Interface/ManagedFontAtlas/Internals/SimplePushedFont.cs +++ b/Dalamud/Interface/ManagedFontAtlas/Internals/SimplePushedFont.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Diagnostics; using Dalamud.Bindings.ImGui; -using Dalamud.Interface.Utility; using Microsoft.Extensions.ObjectPool; diff --git a/Dalamud/Interface/Style/DalamudColors.cs b/Dalamud/Interface/Style/DalamudColors.cs index aa3339c19..e4a8c5b9b 100644 --- a/Dalamud/Interface/Style/DalamudColors.cs +++ b/Dalamud/Interface/Style/DalamudColors.cs @@ -1,6 +1,7 @@ -using System.Numerics; +using System.Numerics; using Dalamud.Interface.Colors; + using Newtonsoft.Json; namespace Dalamud.Interface.Style; diff --git a/Dalamud/Interface/Style/StyleModel.cs b/Dalamud/Interface/Style/StyleModel.cs index bfce480f2..4c64e3a21 100644 --- a/Dalamud/Interface/Style/StyleModel.cs +++ b/Dalamud/Interface/Style/StyleModel.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Numerics; @@ -6,7 +6,9 @@ using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Interface.Colors; using Dalamud.Utility; + using Newtonsoft.Json; + using Serilog; namespace Dalamud.Interface.Style; @@ -68,7 +70,7 @@ public abstract class StyleModel /// Thrown in case the version of the model is not known. public static StyleModel? Deserialize(string model) { - var json = Util.DecompressString(Convert.FromBase64String(model.Substring(3))); + var json = Util.DecompressString(Convert.FromBase64String(model[3..])); if (model.StartsWith(StyleModelV1.SerializedPrefix)) return JsonConvert.DeserializeObject(json); @@ -86,8 +88,7 @@ public abstract class StyleModel if (configuration.SavedStylesOld == null) return; - configuration.SavedStyles = new List(); - configuration.SavedStyles.AddRange(configuration.SavedStylesOld); + configuration.SavedStyles = [.. configuration.SavedStylesOld]; Log.Information("Transferred {NumStyles} styles", configuration.SavedStyles.Count); @@ -102,16 +103,11 @@ public abstract class StyleModel /// Thrown when the version of the style model is unknown. public string Serialize() { - string prefix; - switch (this) + var prefix = this switch { - case StyleModelV1: - prefix = StyleModelV1.SerializedPrefix; - break; - default: - throw new ArgumentOutOfRangeException(); - } - + StyleModelV1 => StyleModelV1.SerializedPrefix, + _ => throw new ArgumentOutOfRangeException(), + }; return prefix + Convert.ToBase64String(Util.CompressString(JsonConvert.SerializeObject(this))); } diff --git a/Dalamud/Interface/Style/StyleModelV1.cs b/Dalamud/Interface/Style/StyleModelV1.cs index 8c1de86f3..4af2512fd 100644 --- a/Dalamud/Interface/Style/StyleModelV1.cs +++ b/Dalamud/Interface/Style/StyleModelV1.cs @@ -3,6 +3,7 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Interface.Colors; + using Newtonsoft.Json; namespace Dalamud.Interface.Style; @@ -17,7 +18,7 @@ public class StyleModelV1 : StyleModel /// private StyleModelV1() { - this.Colors = new Dictionary(); + this.Colors = []; this.Name = "Unknown"; } @@ -396,7 +397,7 @@ public class StyleModelV1 : StyleModel model.SelectableTextAlign = style.SelectableTextAlign; model.DisplaySafeAreaPadding = style.DisplaySafeAreaPadding; - model.Colors = new Dictionary(); + model.Colors = []; foreach (var imGuiCol in Enum.GetValues()) { diff --git a/Dalamud/Interface/Textures/ForwardingSharedImmediateTexture.cs b/Dalamud/Interface/Textures/ForwardingSharedImmediateTexture.cs index 12e312b3e..45dc69bbd 100644 --- a/Dalamud/Interface/Textures/ForwardingSharedImmediateTexture.cs +++ b/Dalamud/Interface/Textures/ForwardingSharedImmediateTexture.cs @@ -1,8 +1,7 @@ -using System.Threading; +using System.Threading; using System.Threading.Tasks; using Dalamud.Interface.Textures.TextureWraps; -using Dalamud.Storage.Assets; namespace Dalamud.Interface.Textures; diff --git a/Dalamud/Interface/Textures/ISharedImmediateTexture.cs b/Dalamud/Interface/Textures/ISharedImmediateTexture.cs index b6aa4da83..7f3b54c97 100644 --- a/Dalamud/Interface/Textures/ISharedImmediateTexture.cs +++ b/Dalamud/Interface/Textures/ISharedImmediateTexture.cs @@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; -using Dalamud.Interface.Internal; using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Utility; diff --git a/Dalamud/Interface/Textures/ImGuiViewportTextureArgs.cs b/Dalamud/Interface/Textures/ImGuiViewportTextureArgs.cs index d04688fe4..248fbbc67 100644 --- a/Dalamud/Interface/Textures/ImGuiViewportTextureArgs.cs +++ b/Dalamud/Interface/Textures/ImGuiViewportTextureArgs.cs @@ -2,9 +2,7 @@ using System.Numerics; using System.Text; using Dalamud.Bindings.ImGui; -using Dalamud.Interface.Internal; using Dalamud.Interface.Textures.TextureWraps; -using TerraFX.Interop.DirectX; namespace Dalamud.Interface.Textures; diff --git a/Dalamud/Interface/Textures/Internal/SharedImmediateTextures/ManifestResourceSharedImmediateTexture.cs b/Dalamud/Interface/Textures/Internal/SharedImmediateTextures/ManifestResourceSharedImmediateTexture.cs index c95a9b0ad..511f6e110 100644 --- a/Dalamud/Interface/Textures/Internal/SharedImmediateTextures/ManifestResourceSharedImmediateTexture.cs +++ b/Dalamud/Interface/Textures/Internal/SharedImmediateTextures/ManifestResourceSharedImmediateTexture.cs @@ -3,7 +3,6 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; -using Dalamud.Interface.Internal; using Dalamud.Interface.Textures.TextureWraps; namespace Dalamud.Interface.Textures.Internal.SharedImmediateTextures; @@ -36,10 +35,7 @@ internal sealed class ManifestResourceSharedImmediateTexture : SharedImmediateTe /// protected override async Task CreateTextureAsync(CancellationToken cancellationToken) { - await using var stream = this.assembly.GetManifestResourceStream(this.name); - if (stream is null) - throw new FileNotFoundException("The resource file could not be found."); - + await using var stream = this.assembly.GetManifestResourceStream(this.name) ?? throw new FileNotFoundException("The resource file could not be found."); var tm = await Service.GetAsync(); var ms = new MemoryStream(stream.CanSeek ? checked((int)stream.Length) : 0); await stream.CopyToAsync(ms, cancellationToken); diff --git a/Dalamud/Interface/Textures/Internal/SharedImmediateTextures/SharedImmediateTexture.cs b/Dalamud/Interface/Textures/Internal/SharedImmediateTextures/SharedImmediateTexture.cs index 5f9925ed3..931a1a73b 100644 --- a/Dalamud/Interface/Textures/Internal/SharedImmediateTextures/SharedImmediateTexture.cs +++ b/Dalamud/Interface/Textures/Internal/SharedImmediateTextures/SharedImmediateTexture.cs @@ -23,8 +23,8 @@ internal abstract class SharedImmediateTexture private static long instanceCounter; - private readonly object reviveLock = new(); - private readonly List ownerPlugins = new(); + private readonly Lock reviveLock = new(); + private readonly List ownerPlugins = []; private bool resourceReleased; private int refCount; @@ -476,8 +476,8 @@ internal abstract class SharedImmediateTexture { var ownerCopy = this.owner; var wrapCopy = this.innerWrap; - if (ownerCopy is null || wrapCopy is null) - throw new ObjectDisposedException(nameof(RefCountableWrappingTextureWrap)); + + ObjectDisposedException.ThrowIf(ownerCopy is null || wrapCopy is null, this); ownerCopy.AddRef(); return new RefCountableWrappingTextureWrap(wrapCopy, ownerCopy); diff --git a/Dalamud/Interface/Textures/Internal/TextureManager.BlameTracker.cs b/Dalamud/Interface/Textures/Internal/TextureManager.BlameTracker.cs index fde40d462..ed1824e5c 100644 --- a/Dalamud/Interface/Textures/Internal/TextureManager.BlameTracker.cs +++ b/Dalamud/Interface/Textures/Internal/TextureManager.BlameTracker.cs @@ -3,7 +3,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Dalamud.Bindings.ImGui; -using Dalamud.Interface.Internal; using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Plugin.Internal.Types; using Dalamud.Plugin.Services; @@ -44,7 +43,7 @@ internal sealed partial class TextureManager /// Gets the list containing all the loaded textures from plugins. /// Returned value must be used inside a lock. - public List BlameTracker { get; } = new(); + public List BlameTracker { get; } = []; /// Gets the blame for a texture wrap. /// The texture wrap. @@ -234,7 +233,7 @@ internal sealed partial class TextureManager public static Guid* NativeGuid => (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in MyGuid)); /// - public List OwnerPlugins { get; } = new(); + public List OwnerPlugins { get; } = []; /// public nint ResourceAddress => (nint)this.tex2D; diff --git a/Dalamud/Interface/Textures/Internal/TextureManager.Drawer.cs b/Dalamud/Interface/Textures/Internal/TextureManager.Drawer.cs index b4573f04f..e803a1d13 100644 --- a/Dalamud/Interface/Textures/Internal/TextureManager.Drawer.cs +++ b/Dalamud/Interface/Textures/Internal/TextureManager.Drawer.cs @@ -5,6 +5,7 @@ using System.Numerics; using Dalamud.Bindings.ImGui; using Dalamud.Storage.Assets; using Dalamud.Utility; + using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; diff --git a/Dalamud/Interface/Textures/Internal/TextureManager.GamePath.cs b/Dalamud/Interface/Textures/Internal/TextureManager.GamePath.cs index 0796ad6cc..fe0f390eb 100644 --- a/Dalamud/Interface/Textures/Internal/TextureManager.GamePath.cs +++ b/Dalamud/Interface/Textures/Internal/TextureManager.GamePath.cs @@ -113,8 +113,8 @@ internal sealed partial class TextureManager var format = highResolution ? HighResolutionIconFileFormat : IconFileFormat; type ??= string.Empty; - if (type.Length > 0 && !type.EndsWith("/")) - type += "/"; + if (type.Length > 0 && !type.EndsWith('/')) + type += '/'; return string.Format(format, iconId / 1000, type, iconId); } diff --git a/Dalamud/Interface/Textures/Internal/TextureManager.SharedTextures.cs b/Dalamud/Interface/Textures/Internal/TextureManager.SharedTextures.cs index d7e185b68..85cf3a1ca 100644 --- a/Dalamud/Interface/Textures/Internal/TextureManager.SharedTextures.cs +++ b/Dalamud/Interface/Textures/Internal/TextureManager.SharedTextures.cs @@ -5,7 +5,6 @@ using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; -using System.Threading.Tasks; using BitFaster.Caching.Lru; @@ -65,7 +64,7 @@ internal sealed partial class TextureManager private readonly ConcurrentDictionary gameDict = new(); private readonly ConcurrentDictionary fileDict = new(); private readonly ConcurrentDictionary<(Assembly, string), SharedImmediateTexture> manifestResourceDict = new(); - private readonly HashSet invalidatedTextures = new(); + private readonly HashSet invalidatedTextures = []; private readonly Thread sharedTextureReleaseThread; diff --git a/Dalamud/Interface/Textures/Internal/TextureManager.cs b/Dalamud/Interface/Textures/Internal/TextureManager.cs index d0f0d8c07..982b5c58d 100644 --- a/Dalamud/Interface/Textures/Internal/TextureManager.cs +++ b/Dalamud/Interface/Textures/Internal/TextureManager.cs @@ -34,7 +34,7 @@ internal sealed partial class TextureManager ITextureSubstitutionProvider, ITextureReadbackProvider { - private static readonly ModuleLog Log = new(nameof(TextureManager)); + private static readonly ModuleLog Log = ModuleLog.Create(); [ServiceManager.ServiceDependency] private readonly Dalamud dalamud = Service.Get(); @@ -382,10 +382,10 @@ internal sealed partial class TextureManager var tf = new TexFile(); typeof(TexFile).GetProperty(nameof(tf.Data))!.GetSetMethod(true)!.Invoke( tf, - new object?[] { bytesArray }); + [bytesArray]); typeof(TexFile).GetProperty(nameof(tf.Reader))!.GetSetMethod(true)!.Invoke( tf, - new object?[] { new LuminaBinaryReader(bytesArray) }); + [new LuminaBinaryReader(bytesArray)]); // Note: FileInfo and FilePath are not used from TexFile; skip it. var wrap = this.NoThrottleCreateFromTexFile(tf); diff --git a/Dalamud/Interface/Textures/TextureWraps/ForwardingTextureWrap.cs b/Dalamud/Interface/Textures/TextureWraps/ForwardingTextureWrap.cs index 342397c5e..2cb1deac5 100644 --- a/Dalamud/Interface/Textures/TextureWraps/ForwardingTextureWrap.cs +++ b/Dalamud/Interface/Textures/TextureWraps/ForwardingTextureWrap.cs @@ -3,7 +3,6 @@ using System.Numerics; using System.Runtime.CompilerServices; using Dalamud.Bindings.ImGui; -using Dalamud.Interface.Internal; using Dalamud.Interface.Textures.TextureWraps.Internal; using TerraFX.Interop.Windows; diff --git a/Dalamud/Interface/Textures/TextureWraps/Internal/ViewportTextureWrap.cs b/Dalamud/Interface/Textures/TextureWraps/Internal/ViewportTextureWrap.cs index 3e0f31eca..d4407d76a 100644 --- a/Dalamud/Interface/Textures/TextureWraps/Internal/ViewportTextureWrap.cs +++ b/Dalamud/Interface/Textures/TextureWraps/Internal/ViewportTextureWrap.cs @@ -9,6 +9,7 @@ using Dalamud.Interface.Textures.Internal; using Dalamud.Plugin.Internal.Types; using Dalamud.Storage.Assets; using Dalamud.Utility; + using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; diff --git a/Dalamud/Interface/TitleScreenMenu/TitleScreenMenu.cs b/Dalamud/Interface/TitleScreenMenu/TitleScreenMenu.cs index 586d65559..cf849a1ef 100644 --- a/Dalamud/Interface/TitleScreenMenu/TitleScreenMenu.cs +++ b/Dalamud/Interface/TitleScreenMenu/TitleScreenMenu.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -22,7 +22,7 @@ internal class TitleScreenMenu : IServiceType, ITitleScreenMenu /// internal const uint TextureSize = 64; - private readonly List entries = new(); + private readonly List entries = []; private TitleScreenMenuEntry[]? entriesView; [ServiceManager.ServiceConstructor] @@ -42,7 +42,7 @@ internal class TitleScreenMenu : IServiceType, ITitleScreenMenu { lock (this.entries) { - if (!this.entries.Any()) + if (this.entries.Count == 0) return Array.Empty(); return this.entriesView ??= this.entries.OrderByDescending(x => x.IsInternal).ToArray(); @@ -59,7 +59,7 @@ internal class TitleScreenMenu : IServiceType, ITitleScreenMenu { lock (this.entries) { - if (!this.entries.Any()) + if (this.entries.Count == 0) return Array.Empty(); return this.entriesView ??= this.entries.OrderByDescending(x => x.IsInternal).ToArray(); @@ -81,7 +81,7 @@ internal class TitleScreenMenu : IServiceType, ITitleScreenMenu lock (this.entries) { var entriesOfAssembly = this.entries.Where(x => x.CallingAssembly == Assembly.GetCallingAssembly()).ToList(); - var priority = entriesOfAssembly.Any() + var priority = entriesOfAssembly.Count != 0 ? unchecked(entriesOfAssembly.Select(x => x.Priority).Max() + 1) : 0; entry = new(Assembly.GetCallingAssembly(), priority, text, texture, onTriggered); @@ -191,7 +191,7 @@ internal class TitleScreenMenu : IServiceType, ITitleScreenMenu lock (this.entries) { var entriesOfAssembly = this.entries.Where(x => x.CallingAssembly == null).ToList(); - var priority = entriesOfAssembly.Any() + var priority = entriesOfAssembly.Count != 0 ? unchecked(entriesOfAssembly.Select(x => x.Priority).Max() + 1) : 0; entry = new(null, priority, text, texture, onTriggered, showConditionKeys) @@ -220,7 +220,7 @@ internal class TitleScreenMenuPluginScoped : IInternalDisposableService, ITitleS [ServiceManager.ServiceDependency] private readonly TitleScreenMenu titleScreenMenuService = Service.Get(); - private readonly List pluginEntries = new(); + private readonly List pluginEntries = []; /// public IReadOnlyList? Entries => this.titleScreenMenuService.Entries; diff --git a/Dalamud/Interface/UiBuilder.cs b/Dalamud/Interface/UiBuilder.cs index ea0e21e97..d2b4b655e 100644 --- a/Dalamud/Interface/UiBuilder.cs +++ b/Dalamud/Interface/UiBuilder.cs @@ -15,6 +15,7 @@ using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.ManagedFontAtlas.Internals; using Dalamud.Plugin.Internal.Types; using Dalamud.Utility; + using Serilog; namespace Dalamud.Interface; @@ -601,7 +602,7 @@ public sealed class UiBuilder : IDisposable, IUiBuilder /// /// Gets or sets a history of the last draw times, used to calculate an average. /// - internal List DrawTimeHistory { get; set; } = new List(); + internal List DrawTimeHistory { get; set; } = []; private InterfaceManager? InterfaceManagerWithScene => Service.GetNullable()?.Manager; diff --git a/Dalamud/Interface/UldWrapper.cs b/Dalamud/Interface/UldWrapper.cs index 85a2d8344..48c6a114d 100644 --- a/Dalamud/Interface/UldWrapper.cs +++ b/Dalamud/Interface/UldWrapper.cs @@ -7,6 +7,7 @@ using Dalamud.Interface.Textures; using Dalamud.Interface.Textures.Internal; using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Utility; + using Lumina.Data.Files; using Lumina.Data.Parsing.Uld; @@ -17,7 +18,7 @@ public class UldWrapper : IDisposable { private readonly DataManager data; private readonly TextureManager textureManager; - private readonly Dictionary textures = new(); + private readonly Dictionary textures = []; /// Initializes a new instance of the class, wrapping an ULD file. /// The UiBuilder used to load textures. diff --git a/Dalamud/Interface/Utility/Internal/DevTextureSaveMenu.cs b/Dalamud/Interface/Utility/Internal/DevTextureSaveMenu.cs index 4a0137c88..7fcf795aa 100644 --- a/Dalamud/Interface/Utility/Internal/DevTextureSaveMenu.cs +++ b/Dalamud/Interface/Utility/Internal/DevTextureSaveMenu.cs @@ -14,7 +14,9 @@ using Dalamud.Interface.Internal; using Dalamud.Interface.Internal.Windows.Data.Widgets; using Dalamud.Interface.Textures.Internal; using Dalamud.Interface.Textures.TextureWraps; + using Serilog; + using TerraFX.Interop.Windows; namespace Dalamud.Interface.Utility.Internal; diff --git a/Dalamud/Interface/Utility/Raii/Color.cs b/Dalamud/Interface/Utility/Raii/Color.cs index 7bf2efc38..9682b929e 100644 --- a/Dalamud/Interface/Utility/Raii/Color.cs +++ b/Dalamud/Interface/Utility/Raii/Color.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Numerics; using Dalamud.Bindings.ImGui; -using Dalamud.Utility; namespace Dalamud.Interface.Utility.Raii; @@ -29,7 +28,7 @@ public static partial class ImRaii public sealed class Color : IDisposable { - internal static readonly List<(ImGuiCol, uint)> Stack = new(); + internal static readonly List<(ImGuiCol, uint)> Stack = []; private int count; public Color Push(ImGuiCol idx, uint color, bool condition = true) diff --git a/Dalamud/Interface/Utility/Raii/EndObjects.cs b/Dalamud/Interface/Utility/Raii/EndObjects.cs index 80122360c..80ae495e2 100644 --- a/Dalamud/Interface/Utility/Raii/EndObjects.cs +++ b/Dalamud/Interface/Utility/Raii/EndObjects.cs @@ -193,8 +193,8 @@ public static partial class ImRaii return new EndUnconditionally(Restore, true); } - private static IEndObject DisabledEnd() - => new EndUnconditionally(() => + private static EndUnconditionally DisabledEnd() + => new(() => { --disabledCount; ImGui.EndDisabled(); diff --git a/Dalamud/Interface/Utility/Raii/Font.cs b/Dalamud/Interface/Utility/Raii/Font.cs index da35c693a..1b5e8cc58 100644 --- a/Dalamud/Interface/Utility/Raii/Font.cs +++ b/Dalamud/Interface/Utility/Raii/Font.cs @@ -1,5 +1,4 @@ using Dalamud.Bindings.ImGui; -using Dalamud.Utility; namespace Dalamud.Interface.Utility.Raii; diff --git a/Dalamud/Interface/Utility/Raii/Plot.cs b/Dalamud/Interface/Utility/Raii/Plot.cs index d2ff38299..e88919e48 100644 --- a/Dalamud/Interface/Utility/Raii/Plot.cs +++ b/Dalamud/Interface/Utility/Raii/Plot.cs @@ -96,7 +96,7 @@ public static partial class ImRaii public sealed class PlotStyle : IDisposable { - internal static readonly List<(ImPlotStyleVar, Vector2)> Stack = new(); + internal static readonly List<(ImPlotStyleVar, Vector2)> Stack = []; private int count; @@ -249,7 +249,7 @@ public static partial class ImRaii public sealed class PlotColor : IDisposable { - internal static readonly List<(ImPlotCol, uint)> Stack = new(); + internal static readonly List<(ImPlotCol, uint)> Stack = []; private int count; // Reimplementation of https://github.com/ocornut/imgui/blob/868facff9ded2d61425c67deeba354eb24275bd1/imgui.cpp#L3035 diff --git a/Dalamud/Interface/Utility/Raii/Style.cs b/Dalamud/Interface/Utility/Raii/Style.cs index bfd04ea3c..e178b68d3 100644 --- a/Dalamud/Interface/Utility/Raii/Style.cs +++ b/Dalamud/Interface/Utility/Raii/Style.cs @@ -35,7 +35,7 @@ public static partial class ImRaii public sealed class Style : IDisposable { - internal static readonly List<(ImGuiStyleVar, Vector2)> Stack = new(); + internal static readonly List<(ImGuiStyleVar, Vector2)> Stack = []; private int count; diff --git a/Dalamud/Interface/Windowing/Persistence/PresetModel.cs b/Dalamud/Interface/Windowing/Persistence/PresetModel.cs index 4ddf55e51..1c6a93c16 100644 --- a/Dalamud/Interface/Windowing/Persistence/PresetModel.cs +++ b/Dalamud/Interface/Windowing/Persistence/PresetModel.cs @@ -25,7 +25,7 @@ internal class PresetModel /// Gets or sets a dictionary containing the windows in the preset, mapping their ID to the preset. /// [JsonProperty("w")] - public Dictionary Windows { get; set; } = new(); + public Dictionary Windows { get; set; } = []; /// /// Class representing a window in a preset. diff --git a/Dalamud/Interface/Windowing/Window.cs b/Dalamud/Interface/Windowing/Window.cs index 5a79a017a..3cbd1a521 100644 --- a/Dalamud/Interface/Windowing/Window.cs +++ b/Dalamud/Interface/Windowing/Window.cs @@ -1,9 +1,11 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Numerics; using System.Threading.Tasks; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.Keys; using Dalamud.Interface.Colors; @@ -33,7 +35,7 @@ public abstract class Window private const float FadeInOutTime = 0.072f; private const string AdditionsPopupName = "WindowSystemContextActions"; - private static readonly ModuleLog Log = new("WindowSystem"); + private static readonly ModuleLog Log = ModuleLog.Create(); private static bool wasEscPressedLastFrame = false; @@ -261,7 +263,7 @@ public abstract class Window /// disabled globally by the user, an internal title bar button to manage these is added when drawing, but it will /// not appear in this collection. If you wish to remove this button, set both of these values to false. /// - public List TitleBarButtons { get; set; } = new(); + public List TitleBarButtons { get; set; } = []; /// /// Gets or sets a value indicating whether this window will stay open. diff --git a/Dalamud/Interface/Windowing/WindowSystem.cs b/Dalamud/Interface/Windowing/WindowSystem.cs index d6e9649bb..319640336 100644 --- a/Dalamud/Interface/Windowing/WindowSystem.cs +++ b/Dalamud/Interface/Windowing/WindowSystem.cs @@ -4,6 +4,7 @@ using System.Linq; using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Interface.Windowing.Persistence; + using Serilog; namespace Dalamud.Interface.Windowing; @@ -15,7 +16,7 @@ public class WindowSystem { private static DateTimeOffset lastAnyFocus; - private readonly List windows = new(); + private readonly List windows = []; private string lastFocusedWindowName = string.Empty; diff --git a/Dalamud/IoC/Internal/ObjectInstance.cs b/Dalamud/IoC/Internal/ObjectInstance.cs index 3a963f6bd..af97b7124 100644 --- a/Dalamud/IoC/Internal/ObjectInstance.cs +++ b/Dalamud/IoC/Internal/ObjectInstance.cs @@ -1,4 +1,3 @@ -using System.Reflection; using System.Threading.Tasks; namespace Dalamud.IoC.Internal; diff --git a/Dalamud/IoC/Internal/ServiceContainer.cs b/Dalamud/IoC/Internal/ServiceContainer.cs index 6383b6b11..0dacacc54 100644 --- a/Dalamud/IoC/Internal/ServiceContainer.cs +++ b/Dalamud/IoC/Internal/ServiceContainer.cs @@ -20,10 +20,10 @@ namespace Dalamud.IoC.Internal; [ServiceManager.ProvidedService] internal class ServiceContainer : IServiceType { - private static readonly ModuleLog Log = new("SERVICECONTAINER"); + private static readonly ModuleLog Log = ModuleLog.Create(); - private readonly Dictionary instances = new(); - private readonly Dictionary interfaceToTypeMap = new(); + private readonly Dictionary instances = []; + private readonly Dictionary interfaceToTypeMap = []; /// /// Initializes a new instance of the class. diff --git a/Dalamud/Localization.cs b/Dalamud/Localization.cs index 0a7086e73..8c7368c3f 100644 --- a/Dalamud/Localization.cs +++ b/Dalamud/Localization.cs @@ -18,7 +18,7 @@ public class Localization : IServiceType /// /// Array of language codes which have a valid translation in Dalamud. /// - public static readonly string[] ApplicableLangCodes = { "de", "ja", "fr", "it", "es", "ko", "no", "ru", "zh", "tw" }; + public static readonly string[] ApplicableLangCodes = ["de", "ja", "fr", "it", "es", "ko", "no", "ru", "zh", "tw"]; private const string FallbackLangCode = "en"; diff --git a/Dalamud/Logging/Internal/TaskTracker.cs b/Dalamud/Logging/Internal/TaskTracker.cs index cb9a0db6d..c6bd895a0 100644 --- a/Dalamud/Logging/Internal/TaskTracker.cs +++ b/Dalamud/Logging/Internal/TaskTracker.cs @@ -15,8 +15,8 @@ namespace Dalamud.Logging.Internal; [ServiceManager.EarlyLoadedService] internal class TaskTracker : IInternalDisposableService { - private static readonly ModuleLog Log = new("TT"); - private static readonly List TrackedTasksInternal = new(); + private static readonly ModuleLog Log = ModuleLog.Create(); + private static readonly List TrackedTasksInternal = []; private static readonly ConcurrentQueue NewlyCreatedTasks = new(); private static bool clearRequested = false; diff --git a/Dalamud/Memory/MemoryHelper.cs b/Dalamud/Memory/MemoryHelper.cs index 2eae1be6d..5f7f69f2f 100644 --- a/Dalamud/Memory/MemoryHelper.cs +++ b/Dalamud/Memory/MemoryHelper.cs @@ -6,11 +6,15 @@ using System.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Memory.Exceptions; using Dalamud.Utility; + using FFXIVClientStructs.FFXIV.Client.System.Memory; using FFXIVClientStructs.FFXIV.Client.System.String; + using Lumina.Text.Payloads; using Lumina.Text.ReadOnly; + using Microsoft.Extensions.ObjectPool; + using Windows.Win32.Foundation; using Windows.Win32.System.Memory; @@ -264,6 +268,31 @@ public static unsafe class MemoryHelper } } + /// + /// Compares a UTF-16 character span with a null-terminated UTF-16 string at . + /// + /// UTF-16 character span (e.g., from a string literal). + /// Address of null-terminated UTF-16 (wide) string, as used by Windows APIs. + /// if equal; otherwise, . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe bool EqualsZeroTerminatedWideString( + scoped ReadOnlySpan charSpan, + nint memoryAddress) + { + if (memoryAddress == 0) + return charSpan.Length == 0; + + char* p = (char*)memoryAddress; + + foreach (char c in charSpan) + { + if (*p++ != c) + return false; + } + + return *p == '\0'; + } + /// /// Read a UTF-8 encoded string from a specified memory address. /// diff --git a/Dalamud/Networking/Http/HappyEyeballsCallback.cs b/Dalamud/Networking/Http/HappyEyeballsCallback.cs index 4e3ee61f6..59bdff630 100644 --- a/Dalamud/Networking/Http/HappyEyeballsCallback.cs +++ b/Dalamud/Networking/Http/HappyEyeballsCallback.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; @@ -20,7 +20,7 @@ namespace Dalamud.Networking.Http; /// public class HappyEyeballsCallback : IDisposable { - private static readonly ModuleLog Log = new("HTTP"); + private static readonly ModuleLog Log = ModuleLog.Create(); /* * ToDo: Eventually add in some kind of state management to cache DNS and IP Family. diff --git a/Dalamud/Plugin/DalamudPluginInterface.cs b/Dalamud/Plugin/DalamudPluginInterface.cs index e42bbe608..df1d0f6e9 100644 --- a/Dalamud/Plugin/DalamudPluginInterface.cs +++ b/Dalamud/Plugin/DalamudPluginInterface.cs @@ -342,7 +342,7 @@ internal sealed class DalamudPluginInterface : IDalamudPluginInterface, IDisposa { var mi = this.configs.GetType().GetMethod("LoadForType"); var fn = mi.MakeGenericMethod(type); - return (IPluginConfiguration)fn.Invoke(this.configs, new object[] { this.plugin.InternalName }); + return (IPluginConfiguration)fn.Invoke(this.configs, [this.plugin.InternalName]); } } diff --git a/Dalamud/Plugin/Internal/AutoUpdate/AutoUpdateManager.cs b/Dalamud/Plugin/Internal/AutoUpdate/AutoUpdateManager.cs index 3fc011a68..734bc5ef9 100644 --- a/Dalamud/Plugin/Internal/AutoUpdate/AutoUpdateManager.cs +++ b/Dalamud/Plugin/Internal/AutoUpdate/AutoUpdateManager.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using CheapLoc; + using Dalamud.Bindings.ImGui; using Dalamud.Configuration.Internal; using Dalamud.Console; @@ -32,7 +33,7 @@ namespace Dalamud.Plugin.Internal.AutoUpdate; [ServiceManager.EarlyLoadedService] internal class AutoUpdateManager : IServiceType { - private static readonly ModuleLog Log = new("AUTOUPDATE"); + private static readonly ModuleLog Log = ModuleLog.Create(); /// /// Time we should wait after login to update. @@ -376,7 +377,7 @@ internal class AutoUpdateManager : IServiceType } } - private void NotifyUpdatesAreAvailable(ICollection updatablePlugins) + private void NotifyUpdatesAreAvailable(List updatablePlugins) { if (updatablePlugins.Count == 0) return; diff --git a/Dalamud/Plugin/Internal/Loader/AssemblyLoadContextBuilder.cs b/Dalamud/Plugin/Internal/Loader/AssemblyLoadContextBuilder.cs index 1c6e6feed..aa304cd05 100644 --- a/Dalamud/Plugin/Internal/Loader/AssemblyLoadContextBuilder.cs +++ b/Dalamud/Plugin/Internal/Loader/AssemblyLoadContextBuilder.cs @@ -15,9 +15,9 @@ namespace Dalamud.Plugin.Internal.Loader; /// internal class AssemblyLoadContextBuilder { - private readonly List additionalProbingPaths = new(); - private readonly List resourceProbingPaths = new(); - private readonly List resourceProbingSubpaths = new(); + private readonly List additionalProbingPaths = []; + private readonly List resourceProbingPaths = []; + private readonly List resourceProbingSubpaths = []; private readonly Dictionary managedLibraries = new(StringComparer.Ordinal); private readonly Dictionary nativeLibraries = new(StringComparer.Ordinal); private readonly HashSet privateAssemblies = new(StringComparer.Ordinal); @@ -140,7 +140,7 @@ internal class AssemblyLoadContextBuilder return this; } - var names = new Queue(new[] { assemblyName }); + var names = new Queue([assemblyName]); while (names.TryDequeue(out var name)) { diff --git a/Dalamud/Plugin/Internal/Loader/LoaderConfig.cs b/Dalamud/Plugin/Internal/Loader/LoaderConfig.cs index b863b8ee1..e26338820 100644 --- a/Dalamud/Plugin/Internal/Loader/LoaderConfig.cs +++ b/Dalamud/Plugin/Internal/Loader/LoaderConfig.cs @@ -39,13 +39,13 @@ internal class LoaderConfig /// /// Gets a list of assemblies which should be treated as private. /// - public ICollection PrivateAssemblies { get; } = new List(); + public ICollection PrivateAssemblies { get; } = []; /// /// Gets a list of assemblies which should be unified between the host and the plugin. /// /// what-are-shared-types - public ICollection<(AssemblyName Name, bool Recursive)> SharedAssemblies { get; } = new List<(AssemblyName Name, bool Recursive)>(); + public ICollection<(AssemblyName Name, bool Recursive)> SharedAssemblies { get; } = []; /// /// Gets or sets a value indicating whether attempt to unify all types from a plugin with the host. diff --git a/Dalamud/Plugin/Internal/Loader/ManagedLoadContext.cs b/Dalamud/Plugin/Internal/Loader/ManagedLoadContext.cs index 4ea4eb5c4..a85d20e40 100644 --- a/Dalamud/Plugin/Internal/Loader/ManagedLoadContext.cs +++ b/Dalamud/Plugin/Internal/Loader/ManagedLoadContext.cs @@ -24,7 +24,7 @@ internal class ManagedLoadContext : AssemblyLoadContext private readonly IReadOnlyDictionary managedAssemblies; private readonly IReadOnlyDictionary nativeLibraries; private readonly IReadOnlyCollection privateAssemblies; - private readonly ICollection defaultAssemblies; + private readonly List defaultAssemblies; private readonly IReadOnlyCollection additionalProbingPaths; private readonly bool preferDefaultLoadContext; private readonly string[] resourceRoots; @@ -64,8 +64,7 @@ internal class ManagedLoadContext : AssemblyLoadContext bool shadowCopyNativeLibraries) : base(Path.GetFileNameWithoutExtension(mainAssemblyPath), isCollectible) { - if (resourceProbingPaths == null) - throw new ArgumentNullException(nameof(resourceProbingPaths)); + ArgumentNullException.ThrowIfNull(resourceProbingPaths); this.mainAssemblyPath = mainAssemblyPath ?? throw new ArgumentNullException(nameof(mainAssemblyPath)); this.dependencyResolver = new AssemblyDependencyResolver(mainAssemblyPath); @@ -243,7 +242,7 @@ internal class ManagedLoadContext : AssemblyLoadContext } // check to see if there is a library entry for the library without the file extension - var trimmedName = unmanagedDllName.Substring(0, unmanagedDllName.Length - suffix.Length); + var trimmedName = unmanagedDllName[..^suffix.Length]; if (this.nativeLibraries.TryGetValue(prefix + trimmedName, out library)) { diff --git a/Dalamud/Plugin/Internal/Loader/PlatformInformation.cs b/Dalamud/Plugin/Internal/Loader/PlatformInformation.cs index ec1d557be..151d184db 100644 --- a/Dalamud/Plugin/Internal/Loader/PlatformInformation.cs +++ b/Dalamud/Plugin/Internal/Loader/PlatformInformation.cs @@ -11,21 +11,21 @@ internal class PlatformInformation /// /// Gets a list of native OS specific library extensions. /// - public static string[] NativeLibraryExtensions => new[] { ".dll" }; + public static string[] NativeLibraryExtensions => [".dll"]; /// /// Gets a list of native OS specific library prefixes. /// - public static string[] NativeLibraryPrefixes => new[] { string.Empty }; + public static string[] NativeLibraryPrefixes => [string.Empty]; /// /// Gets a list of native OS specific managed assembly extensions. /// - public static string[] ManagedAssemblyExtensions => new[] - { + public static string[] ManagedAssemblyExtensions => + [ ".dll", ".ni.dll", ".exe", ".ni.exe", - }; + ]; } diff --git a/Dalamud/Plugin/Internal/Loader/PluginLoader.cs b/Dalamud/Plugin/Internal/Loader/PluginLoader.cs index 54b9cad4b..a77bfe088 100644 --- a/Dalamud/Plugin/Internal/Loader/PluginLoader.cs +++ b/Dalamud/Plugin/Internal/Loader/PluginLoader.cs @@ -53,8 +53,7 @@ internal class PluginLoader : IDisposable /// A loader. public static PluginLoader CreateFromAssemblyFile(string assemblyFile, Action configure) { - if (configure == null) - throw new ArgumentNullException(nameof(configure)); + ArgumentNullException.ThrowIfNull(configure); var config = new LoaderConfig(assemblyFile); configure(config); @@ -159,7 +158,6 @@ internal class PluginLoader : IDisposable private void EnsureNotDisposed() { - if (this.disposed) - throw new ObjectDisposedException(nameof(PluginLoader)); + ObjectDisposedException.ThrowIf(this.disposed, this); } } diff --git a/Dalamud/Plugin/Internal/PluginErrorHandler.cs b/Dalamud/Plugin/Internal/PluginErrorHandler.cs index 0094c3751..6733cc3ca 100644 --- a/Dalamud/Plugin/Internal/PluginErrorHandler.cs +++ b/Dalamud/Plugin/Internal/PluginErrorHandler.cs @@ -22,7 +22,7 @@ internal class PluginErrorHandler : IServiceType private readonly NotificationManager notificationManager; private readonly DalamudInterface di; - private readonly Dictionary invokerCache = new(); + private readonly Dictionary invokerCache = []; private DateTime lastErrorTime = DateTime.MinValue; private IActiveNotification? activeNotification; @@ -141,10 +141,7 @@ internal class PluginErrorHandler : IServiceType private static Action CreateInvoker() where TDelegate : Delegate { var delegateType = typeof(TDelegate); - var method = delegateType.GetMethod("Invoke"); - if (method == null) - throw new InvalidOperationException($"Delegate {delegateType} does not have an Invoke method."); - + var method = delegateType.GetMethod("Invoke") ?? throw new InvalidOperationException($"Delegate {delegateType} does not have an Invoke method."); var parameters = method.GetParameters(); // Create parameters for the lambda @@ -153,7 +150,7 @@ internal class PluginErrorHandler : IServiceType // Create expressions to convert array elements to parameter types var callArgs = new Expression[parameters.Length]; - for (int i = 0; i < parameters.Length; i++) + for (var i = 0; i < parameters.Length; i++) { var paramType = parameters[i].ParameterType; var arrayAccess = Expression.ArrayIndex(argsParam, Expression.Constant(i)); diff --git a/Dalamud/Plugin/Internal/PluginManager.cs b/Dalamud/Plugin/Internal/PluginManager.cs index 193a2d45f..0c9894380 100644 --- a/Dalamud/Plugin/Internal/PluginManager.cs +++ b/Dalamud/Plugin/Internal/PluginManager.cs @@ -11,6 +11,7 @@ using System.Threading; using System.Threading.Tasks; using CheapLoc; + using Dalamud.Configuration; using Dalamud.Configuration.Internal; using Dalamud.Game; @@ -31,6 +32,7 @@ using Dalamud.Plugin.Ipc.Internal; using Dalamud.Support; using Dalamud.Utility; using Dalamud.Utility.Timing; + using Newtonsoft.Json; namespace Dalamud.Plugin.Internal; @@ -56,9 +58,9 @@ internal class PluginManager : IInternalDisposableService private readonly DirectoryInfo pluginDirectory; private readonly BannedPlugin[]? bannedPlugins; - private readonly List installedPluginsList = new(); - private readonly List availablePluginsList = new(); - private readonly List updatablePluginsList = new(); + private readonly List installedPluginsList = []; + private readonly List availablePluginsList = []; + private readonly List updatablePluginsList = []; private readonly Task openInstallerWindowPluginChangelogsLink; @@ -131,7 +133,7 @@ internal class PluginManager : IInternalDisposableService PluginInstallerOpenKind.Changelogs); })); - this.configuration.PluginTestingOptIns ??= new(); + this.configuration.PluginTestingOptIns ??= []; this.MainRepo = PluginRepository.CreateMainRepo(this.happyHttpClient); registerStartupBlocker( @@ -230,7 +232,7 @@ internal class PluginManager : IInternalDisposableService /// /// Gets a list of all plugin repositories. The main repo should always be first. /// - public List Repos { get; private set; } = new(); + public List Repos { get; private set; } = []; /// /// Gets a value indicating whether plugins are not still loading from boot. @@ -1514,11 +1516,7 @@ internal class PluginManager : IInternalDisposableService JsonConvert.SerializeObject(repoManifest, Formatting.Indented)); // Reload as a local manifest, add some attributes, and save again. - var tempManifest = LocalPluginManifest.Load(tempManifestFile); - - if (tempManifest == null) - throw new Exception("Plugin had no valid manifest"); - + var tempManifest = LocalPluginManifest.Load(tempManifestFile) ?? throw new Exception("Plugin had no valid manifest"); if (tempManifest.InternalName != repoManifest.InternalName) { throw new Exception( @@ -1897,9 +1895,9 @@ internal class PluginManager : IInternalDisposableService /// public class StartupLoadTracker { - private readonly Dictionary internalToPublic = new(); - private readonly ConcurrentBag allInternalNames = new(); - private readonly ConcurrentBag finishedInternalNames = new(); + private readonly Dictionary internalToPublic = []; + private readonly ConcurrentBag allInternalNames = []; + private readonly ConcurrentBag finishedInternalNames = []; /// /// Gets a value indicating the total load progress. diff --git a/Dalamud/Plugin/Internal/PluginValidator.cs b/Dalamud/Plugin/Internal/PluginValidator.cs index b2cbe5520..4c6bb9fef 100644 --- a/Dalamud/Plugin/Internal/PluginValidator.cs +++ b/Dalamud/Plugin/Internal/PluginValidator.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Dalamud.Game.Command; @@ -11,7 +11,7 @@ namespace Dalamud.Plugin.Internal; /// internal static class PluginValidator { - private static readonly char[] LineSeparator = new[] { ' ', '\n', '\r' }; + private static readonly char[] LineSeparator = [' ', '\n', '\r']; /// /// Represents the severity of a validation problem. diff --git a/Dalamud/Plugin/Internal/Profiles/PluginManagementCommandHandler.cs b/Dalamud/Plugin/Internal/Profiles/PluginManagementCommandHandler.cs index 09cceebcb..6608f2669 100644 --- a/Dalamud/Plugin/Internal/Profiles/PluginManagementCommandHandler.cs +++ b/Dalamud/Plugin/Internal/Profiles/PluginManagementCommandHandler.cs @@ -3,12 +3,14 @@ using System.Linq; using System.Threading.Tasks; using CheapLoc; + using Dalamud.Game; using Dalamud.Game.Command; using Dalamud.Game.Gui; using Dalamud.Plugin.Internal.Types; using Dalamud.Plugin.Services; using Dalamud.Utility; + using Serilog; namespace Dalamud.Plugin.Internal.Profiles; @@ -39,7 +41,7 @@ internal class PluginManagementCommandHandler : IInternalDisposableService private readonly ChatGui chat; private readonly Framework framework; - private List<(Target Target, PluginCommandOperation Operation)> commandQueue = new(); + private List<(Target Target, PluginCommandOperation Operation)> commandQueue = []; /// /// Initializes a new instance of the class. diff --git a/Dalamud/Plugin/Internal/Profiles/Profile.cs b/Dalamud/Plugin/Internal/Profiles/Profile.cs index d899b0cca..9d931d9ed 100644 --- a/Dalamud/Plugin/Internal/Profiles/Profile.cs +++ b/Dalamud/Plugin/Internal/Profiles/Profile.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; @@ -14,7 +14,7 @@ namespace Dalamud.Plugin.Internal.Profiles; /// internal class Profile { - private static readonly ModuleLog Log = new("PROFILE"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly ProfileManager manager; private readonly ProfileModelV1 modelV1; diff --git a/Dalamud/Plugin/Internal/Profiles/ProfileManager.cs b/Dalamud/Plugin/Internal/Profiles/ProfileManager.cs index 775ff7a72..bbe678162 100644 --- a/Dalamud/Plugin/Internal/Profiles/ProfileManager.cs +++ b/Dalamud/Plugin/Internal/Profiles/ProfileManager.cs @@ -1,10 +1,11 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using CheapLoc; + using Dalamud.Configuration.Internal; using Dalamud.Logging.Internal; using Dalamud.Utility; @@ -15,12 +16,12 @@ namespace Dalamud.Plugin.Internal.Profiles; /// Class responsible for managing plugin profiles. /// [ServiceManager.BlockingEarlyLoadedService($"Data provider for {nameof(PluginManager)}.")] -internal class ProfileManager : IServiceType +internal partial class ProfileManager : IServiceType { - private static readonly ModuleLog Log = new("PROFMAN"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly DalamudConfiguration config; - private readonly List profiles = new(); + private readonly List profiles = []; private volatile bool isBusy = false; @@ -151,11 +152,7 @@ internal class ProfileManager : IServiceType /// The newly cloned profile. public Profile CloneProfile(Profile toClone) { - var newProfile = this.ImportProfile(toClone.Model.SerializeForShare()); - if (newProfile == null) - throw new Exception("New profile was null while cloning"); - - return newProfile; + return this.ImportProfile(toClone.Model.SerializeForShare()) ?? throw new Exception("New profile was null while cloning"); } /// @@ -338,12 +335,15 @@ internal class ProfileManager : IServiceType } } + [GeneratedRegex(@" \(.* Mix\)")] + private static partial Regex MixRegex(); + private string GenerateUniqueProfileName(string startingWith) { if (this.profiles.All(x => x.Name != startingWith)) return startingWith; - startingWith = Regex.Replace(startingWith, @" \(.* Mix\)", string.Empty); + startingWith = MixRegex().Replace(startingWith, string.Empty); while (true) { @@ -359,7 +359,7 @@ internal class ProfileManager : IServiceType this.config.DefaultProfile ??= new ProfileModelV1(); this.profiles.Add(new Profile(this, this.config.DefaultProfile, true, true)); - this.config.SavedProfiles ??= new List(); + this.config.SavedProfiles ??= []; foreach (var profileModel in this.config.SavedProfiles) { this.profiles.Add(new Profile(this, profileModel, false, true)); diff --git a/Dalamud/Plugin/Internal/Profiles/ProfileModel.cs b/Dalamud/Plugin/Internal/Profiles/ProfileModel.cs index e3d9e2955..37487e321 100644 --- a/Dalamud/Plugin/Internal/Profiles/ProfileModel.cs +++ b/Dalamud/Plugin/Internal/Profiles/ProfileModel.cs @@ -1,7 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Reflection; using Dalamud.Utility; + using Newtonsoft.Json; using Newtonsoft.Json.Serialization; @@ -32,7 +33,7 @@ public abstract class ProfileModel /// Thrown when the parsed string is not a valid profile. public static ProfileModel? Deserialize(string model) { - var json = Util.DecompressString(Convert.FromBase64String(model.Substring(3))); + var json = Util.DecompressString(Convert.FromBase64String(model[3..])); if (model.StartsWith(ProfileModelV1.SerializedPrefix)) return JsonConvert.DeserializeObject(json); @@ -47,19 +48,15 @@ public abstract class ProfileModel /// Thrown when an unsupported model is serialized. public string SerializeForShare() { - string prefix; - switch (this) + var prefix = this switch { - case ProfileModelV1: - prefix = ProfileModelV1.SerializedPrefix; - break; - default: - throw new ArgumentOutOfRangeException(); - } + ProfileModelV1 => ProfileModelV1.SerializedPrefix, + _ => throw new ArgumentOutOfRangeException(), + }; // HACK: Just filter the ID for now, we should split the sharing + saving model var serialized = JsonConvert.SerializeObject(this, new JsonSerializerSettings() - { ContractResolver = new IgnorePropertiesResolver(new[] { "WorkingPluginId" }) }); + { ContractResolver = new IgnorePropertiesResolver(["WorkingPluginId"]) }); return prefix + Convert.ToBase64String(Util.CompressString(serialized)); } diff --git a/Dalamud/Plugin/Internal/Profiles/ProfileModelV1.cs b/Dalamud/Plugin/Internal/Profiles/ProfileModelV1.cs index a1a327c1d..deee9c04f 100644 --- a/Dalamud/Plugin/Internal/Profiles/ProfileModelV1.cs +++ b/Dalamud/Plugin/Internal/Profiles/ProfileModelV1.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Newtonsoft.Json; @@ -63,7 +63,7 @@ public class ProfileModelV1 : ProfileModel /// /// Gets or sets the list of plugins in this profile. /// - public List Plugins { get; set; } = new(); + public List Plugins { get; set; } = []; /// /// Class representing a single plugin in a profile. diff --git a/Dalamud/Plugin/Internal/Types/LocalDevPlugin.cs b/Dalamud/Plugin/Internal/Types/LocalDevPlugin.cs index 34b54163a..2e20d2aef 100644 --- a/Dalamud/Plugin/Internal/Types/LocalDevPlugin.cs +++ b/Dalamud/Plugin/Internal/Types/LocalDevPlugin.cs @@ -17,7 +17,7 @@ namespace Dalamud.Plugin.Internal.Types; /// internal sealed class LocalDevPlugin : LocalPlugin { - private static readonly ModuleLog Log = new("PLUGIN"); + private static readonly ModuleLog Log = ModuleLog.Create(); // Ref to Dalamud.Configuration.DevPluginSettings private readonly DevPluginSettings devSettings; diff --git a/Dalamud/Plugin/Internal/Types/LocalPlugin.cs b/Dalamud/Plugin/Internal/Types/LocalPlugin.cs index 1fe18b95b..29867b355 100644 --- a/Dalamud/Plugin/Internal/Types/LocalPlugin.cs +++ b/Dalamud/Plugin/Internal/Types/LocalPlugin.cs @@ -33,7 +33,7 @@ internal class LocalPlugin : IAsyncDisposable protected LocalPluginManifest manifest; #pragma warning restore SA1401 - private static readonly ModuleLog Log = new("LOCALPLUGIN"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly FileInfo manifestFile; private readonly FileInfo disabledFile; diff --git a/Dalamud/Plugin/Internal/Types/Manifest/LocalPluginManifest.cs b/Dalamud/Plugin/Internal/Types/Manifest/LocalPluginManifest.cs index 3aededa18..73d23d19f 100644 --- a/Dalamud/Plugin/Internal/Types/Manifest/LocalPluginManifest.cs +++ b/Dalamud/Plugin/Internal/Types/Manifest/LocalPluginManifest.cs @@ -1,7 +1,9 @@ using System.IO; using Dalamud.Utility; + using Newtonsoft.Json; + using Serilog; namespace Dalamud.Plugin.Internal.Types.Manifest; diff --git a/Dalamud/Plugin/Internal/Types/Manifest/RemotePluginManifest.cs b/Dalamud/Plugin/Internal/Types/Manifest/RemotePluginManifest.cs index 47e92cd84..b83ba91a8 100644 --- a/Dalamud/Plugin/Internal/Types/Manifest/RemotePluginManifest.cs +++ b/Dalamud/Plugin/Internal/Types/Manifest/RemotePluginManifest.cs @@ -1,4 +1,5 @@ using JetBrains.Annotations; + using Newtonsoft.Json; namespace Dalamud.Plugin.Internal.Types.Manifest; diff --git a/Dalamud/Plugin/Internal/Types/PluginDef.cs b/Dalamud/Plugin/Internal/Types/PluginDef.cs index 25cd82423..f9f49225a 100644 --- a/Dalamud/Plugin/Internal/Types/PluginDef.cs +++ b/Dalamud/Plugin/Internal/Types/PluginDef.cs @@ -7,7 +7,7 @@ namespace Dalamud.Plugin.Internal.Types; /// /// Plugin Definition. /// -internal struct PluginDef +internal readonly struct PluginDef { /// /// Initializes a new instance of the struct. diff --git a/Dalamud/Plugin/Internal/Types/PluginManifest.cs b/Dalamud/Plugin/Internal/Types/PluginManifest.cs index cbf69bb5e..fc9f4e372 100644 --- a/Dalamud/Plugin/Internal/Types/PluginManifest.cs +++ b/Dalamud/Plugin/Internal/Types/PluginManifest.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Dalamud.Common.Game; using Dalamud.Plugin.Internal.Types.Manifest; + using Newtonsoft.Json; namespace Dalamud.Plugin.Internal.Types; diff --git a/Dalamud/Plugin/Internal/Types/PluginRepository.cs b/Dalamud/Plugin/Internal/Types/PluginRepository.cs index d5c1131af..d47a3727d 100644 --- a/Dalamud/Plugin/Internal/Types/PluginRepository.cs +++ b/Dalamud/Plugin/Internal/Types/PluginRepository.cs @@ -29,7 +29,7 @@ internal class PluginRepository private const int HttpRequestTimeoutSeconds = 20; - private static readonly ModuleLog Log = new("PLUGINR"); + private static readonly ModuleLog Log = ModuleLog.Create(); private readonly HttpClient httpClient; /// @@ -119,13 +119,7 @@ internal class PluginRepository response.EnsureSuccessStatusCode(); var data = await response.Content.ReadAsStringAsync(); - var pluginMaster = JsonConvert.DeserializeObject>(data); - - if (pluginMaster == null) - { - throw new Exception("Deserialized PluginMaster was null."); - } - + var pluginMaster = JsonConvert.DeserializeObject>(data) ?? throw new Exception("Deserialized PluginMaster was null."); pluginMaster.Sort((pm1, pm2) => string.Compare(pm1.Name, pm2.Name, StringComparison.Ordinal)); // Set the source for each remote manifest. Allows for checking if is 3rd party. diff --git a/Dalamud/Plugin/Ipc/ICallGateProvider.cs b/Dalamud/Plugin/Ipc/ICallGateProvider.cs index 387f0adf9..5fde2ef01 100644 --- a/Dalamud/Plugin/Ipc/ICallGateProvider.cs +++ b/Dalamud/Plugin/Ipc/ICallGateProvider.cs @@ -1,5 +1,4 @@ using Dalamud.Plugin.Ipc.Internal; -using Dalamud.Utility; #pragma warning disable SA1402 // File may only contain a single type diff --git a/Dalamud/Plugin/Ipc/Internal/CallGate.cs b/Dalamud/Plugin/Ipc/Internal/CallGate.cs index fef4b97d0..3f299da9d 100644 --- a/Dalamud/Plugin/Ipc/Internal/CallGate.cs +++ b/Dalamud/Plugin/Ipc/Internal/CallGate.cs @@ -9,7 +9,7 @@ namespace Dalamud.Plugin.Ipc.Internal; [ServiceManager.EarlyLoadedService] internal class CallGate : IServiceType { - private readonly Dictionary gates = new(); + private readonly Dictionary gates = []; private ImmutableDictionary? gatesCopy; diff --git a/Dalamud/Plugin/Ipc/Internal/CallGateChannel.cs b/Dalamud/Plugin/Ipc/Internal/CallGateChannel.cs index 8bd631b0e..78c7f841b 100644 --- a/Dalamud/Plugin/Ipc/Internal/CallGateChannel.cs +++ b/Dalamud/Plugin/Ipc/Internal/CallGateChannel.cs @@ -9,6 +9,7 @@ using Dalamud.Plugin.Ipc.Exceptions; using Dalamud.Plugin.Ipc.Internal.Converters; using Newtonsoft.Json; + using Serilog; namespace Dalamud.Plugin.Ipc.Internal; @@ -23,7 +24,7 @@ internal class CallGateChannel /// /// The actual storage. /// - private readonly HashSet subscriptions = new(); + private readonly HashSet subscriptions = []; /// /// A copy of the actual storage, that will be cleared and populated depending on changes made to diff --git a/Dalamud/Plugin/Ipc/Internal/DataCache.cs b/Dalamud/Plugin/Ipc/Internal/DataCache.cs index 38cea4866..d565c8b35 100644 --- a/Dalamud/Plugin/Ipc/Internal/DataCache.cs +++ b/Dalamud/Plugin/Ipc/Internal/DataCache.cs @@ -40,7 +40,7 @@ internal readonly struct DataCache { this.Tag = tag; this.CreatorAssemblyName = creatorAssemblyName; - this.UserAssemblyNames = new(); + this.UserAssemblyNames = []; this.Data = data; this.Type = type; } diff --git a/Dalamud/Plugin/Ipc/Internal/DataShare.cs b/Dalamud/Plugin/Ipc/Internal/DataShare.cs index 8ce5ddb95..becbe1211 100644 --- a/Dalamud/Plugin/Ipc/Internal/DataShare.cs +++ b/Dalamud/Plugin/Ipc/Internal/DataShare.cs @@ -19,7 +19,7 @@ internal class DataShare : IServiceType /// Dictionary of cached values. Note that is being used, as it does its own locking, /// effectively preventing calling the data generator multiple times concurrently. /// - private readonly Dictionary> caches = new(); + private readonly Dictionary> caches = []; [ServiceManager.ServiceConstructor] private DataShare() diff --git a/Dalamud/Plugin/Services/IChatGui.cs b/Dalamud/Plugin/Services/IChatGui.cs index 572ac6c95..2bb7b6913 100644 --- a/Dalamud/Plugin/Services/IChatGui.cs +++ b/Dalamud/Plugin/Services/IChatGui.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; +using Dalamud.Game.Chat; using Dalamud.Game.Gui; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; @@ -50,6 +51,12 @@ public interface IChatGui : IDalamudService /// The message sent. public delegate void OnMessageUnhandledDelegate(XivChatType type, int timestamp, SeString sender, SeString message); + /// + /// A delegate type used with the event. + /// + /// The message sent. + public delegate void OnLogMessageDelegate(ILogMessage message); + /// /// Event that will be fired when a chat message is sent to chat by the game. /// @@ -70,6 +77,11 @@ public interface IChatGui : IDalamudService /// public event OnMessageUnhandledDelegate ChatMessageUnhandled; + /// + /// Event that will be fired when a log message, that is a chat message based on entries in the LogMessage sheet, is sent. + /// + public event OnLogMessageDelegate LogMessage; + /// /// Gets the ID of the last linked item. /// diff --git a/Dalamud/SafeMemory.cs b/Dalamud/SafeMemory.cs index ca0c8ff92..16d16056d 100644 --- a/Dalamud/SafeMemory.cs +++ b/Dalamud/SafeMemory.cs @@ -193,7 +193,7 @@ public static class SafeMemory return null; var data = encoding.GetString(buffer); var eosPos = data.IndexOf('\0'); - return eosPos == -1 ? data : data.Substring(0, eosPos); + return eosPos == -1 ? data : data[..eosPos]; } /// @@ -303,7 +303,7 @@ public static class SafeMemory return bytes; } - public T Read(int offset = 0) => (T)Marshal.PtrToStructure(this.hGlobal + offset, typeof(T)); + public T Read(int offset = 0) => Marshal.PtrToStructure(this.hGlobal + offset); public object? Read(Type type, int offset = 0) => Marshal.PtrToStructure(this.hGlobal + offset, type); diff --git a/Dalamud/Service/ServiceManager.cs b/Dalamud/Service/ServiceManager.cs index 88c6366fd..824f816ff 100644 --- a/Dalamud/Service/ServiceManager.cs +++ b/Dalamud/Service/ServiceManager.cs @@ -35,7 +35,7 @@ internal static class ServiceManager /// /// Static log facility for Service{T}, to avoid duplicate instances for different types. /// - public static readonly ModuleLog Log = new("SVC"); + public static readonly ModuleLog Log = new(nameof(ServiceManager)); #if DEBUG /// @@ -44,7 +44,7 @@ internal static class ServiceManager internal static readonly ThreadLocal CurrentConstructorServiceType = new(); [SuppressMessage("ReSharper", "CollectionNeverQueried.Local", Justification = "Debugging purposes")] - private static readonly List LoadedServices = new(); + private static readonly List LoadedServices = []; #endif private static readonly TaskCompletionSource BlockingServicesLoadedTaskCompletionSource = @@ -291,7 +291,7 @@ internal static class ServiceManager await loadingDialog.HideAndJoin(); return; - async Task WaitWithTimeoutConsent(IEnumerable tasksEnumerable, LoadingDialog.State state) + static async Task WaitWithTimeoutConsent(IEnumerable tasksEnumerable, LoadingDialog.State state) { loadingDialog.CurrentState = state; var tasks = tasksEnumerable.AsReadOnlyCollection(); @@ -317,7 +317,7 @@ internal static class ServiceManager servicesToLoad.UnionWith(earlyLoadingServices); servicesToLoad.UnionWith(blockingEarlyLoadingServices); - while (servicesToLoad.Any()) + while (servicesToLoad.Count != 0) { foreach (var serviceType in servicesToLoad) { @@ -367,7 +367,7 @@ internal static class ServiceManager BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, null, null, - new object[] { startLoaderArgs })); + [startLoaderArgs])); servicesToLoad.Remove(serviceType); #if DEBUG @@ -383,23 +383,23 @@ internal static class ServiceManager #endif } - if (!tasks.Any()) + if (tasks.Count == 0) { // No more services we can start loading for now. // Either we're waiting for provided services, or there's a dependency cycle. providedServices.RemoveWhere(x => getAsyncTaskMap[x].IsCompleted); - if (providedServices.Any()) + if (providedServices.Count != 0) await Task.WhenAny(providedServices.Select(x => getAsyncTaskMap[x])); else throw new InvalidOperationException("Unresolvable dependency cycle detected"); continue; } - if (servicesToLoad.Any()) + if (servicesToLoad.Count != 0) { await Task.WhenAny(tasks); var faultedTasks = tasks.Where(x => x.IsFaulted).Select(x => (Exception)x.Exception!).ToArray(); - if (faultedTasks.Any()) + if (faultedTasks.Length != 0) throw new AggregateException(faultedTasks); } else @@ -426,7 +426,7 @@ internal static class ServiceManager await loadingDialog.HideAndJoin(); - while (tasks.Any()) + while (tasks.Count != 0) { await Task.WhenAny(tasks); tasks.RemoveAll(x => x.IsCompleted); diff --git a/Dalamud/Service/Service{T}.cs b/Dalamud/Service/Service{T}.cs index 1f5558893..c965eeb3d 100644 --- a/Dalamud/Service/Service{T}.cs +++ b/Dalamud/Service/Service{T}.cs @@ -206,7 +206,7 @@ internal static class Service where T : IServiceType is not ServiceManager.ServiceKind.BlockingEarlyLoadedService and not ServiceManager.ServiceKind.ProvidedService) .ToArray(); - if (offenders.Any()) + if (offenders.Length != 0) { const string bels = nameof(ServiceManager.BlockingEarlyLoadedServiceAttribute); const string ps = nameof(ServiceManager.ProvidedServiceAttribute); @@ -286,13 +286,13 @@ internal static class Service where T : IServiceType { if (method.Invoke(instance, args) is Task task) { - tasks ??= new(); + tasks ??= []; tasks.Add(task); } } catch (Exception e) { - tasks ??= new(); + tasks ??= []; tasks.Add(Task.FromException(e)); } } @@ -351,15 +351,12 @@ internal static class Service where T : IServiceType BindingFlags.CreateInstance | BindingFlags.OptionalParamBinding; return typeof(T) .GetConstructors(ctorBindingFlags) - .SingleOrDefault(x => x.GetCustomAttributes(typeof(ServiceManager.ServiceConstructor), true).Any()); + .SingleOrDefault(x => x.GetCustomAttributes(typeof(ServiceManager.ServiceConstructor), true).Length != 0); } private static async Task ConstructObject(IReadOnlyCollection additionalProvidedTypedObjects) { - var ctor = GetServiceConstructor(); - if (ctor == null) - throw new Exception($"Service \"{typeof(T).FullName}\" had no applicable constructor"); - + var ctor = GetServiceConstructor() ?? throw new Exception($"Service \"{typeof(T).FullName}\" had no applicable constructor"); var args = await ResolveInjectedParameters(ctor.GetParameters(), additionalProvidedTypedObjects) .ConfigureAwait(false); using (Timings.Start($"{typeof(T).Name} Construct")) @@ -460,7 +457,7 @@ internal static class ServiceHelpers BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, - new object?[] { includeUnloadDependencies }) ?? new List(); + [includeUnloadDependencies]) ?? new List(); } /// diff --git a/Dalamud/Storage/Assets/IDalamudAssetManager.cs b/Dalamud/Storage/Assets/IDalamudAssetManager.cs index b4dc41bfd..8b74e4347 100644 --- a/Dalamud/Storage/Assets/IDalamudAssetManager.cs +++ b/Dalamud/Storage/Assets/IDalamudAssetManager.cs @@ -1,9 +1,8 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.IO; using System.Threading.Tasks; -using Dalamud.Interface.Internal; using Dalamud.Interface.Textures.TextureWraps; namespace Dalamud.Storage.Assets; diff --git a/Dalamud/Storage/ReliableFileStorage.cs b/Dalamud/Storage/ReliableFileStorage.cs index d9f8526c3..72cc598ae 100644 --- a/Dalamud/Storage/ReliableFileStorage.cs +++ b/Dalamud/Storage/ReliableFileStorage.cs @@ -1,9 +1,11 @@ -using System.IO; +using System.IO; using System.Text; +using System.Threading; using System.Threading.Tasks; using Dalamud.Logging.Internal; using Dalamud.Utility; + using SQLite; namespace Dalamud.Storage; @@ -25,9 +27,9 @@ namespace Dalamud.Storage; [ServiceManager.ProvidedService] internal class ReliableFileStorage : IInternalDisposableService { - private static readonly ModuleLog Log = new("VFS"); + private static readonly ModuleLog Log = ModuleLog.Create(); - private readonly object syncRoot = new(); + private readonly Lock syncRoot = new(); private SQLiteConnection? db; @@ -272,8 +274,9 @@ internal class ReliableFileStorage : IInternalDisposableService throw new FileNotFoundException("Backup database was not available"); var normalizedPath = NormalizePath(path); - var file = this.db.Table().FirstOrDefault(f => f.Path == normalizedPath && f.ContainerId == containerId); - return file == null ? throw new FileNotFoundException() : file.Data; + var file = this.db.Table().FirstOrDefault(f => f.Path == normalizedPath && f.ContainerId == containerId) + ?? throw new FileNotFoundException(); + return file.Data; } // If the file doesn't exist, immediately check the backup db diff --git a/Dalamud/Support/BugBait.cs b/Dalamud/Support/BugBait.cs index f0a98ca98..c37c4d2f8 100644 --- a/Dalamud/Support/BugBait.cs +++ b/Dalamud/Support/BugBait.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Dalamud.Networking.Http; using Dalamud.Plugin.Internal.Types.Manifest; using Dalamud.Utility; + using Newtonsoft.Json; namespace Dalamud.Support; diff --git a/Dalamud/Support/Troubleshooting.cs b/Dalamud/Support/Troubleshooting.cs index de529a29b..2dd0fb623 100644 --- a/Dalamud/Support/Troubleshooting.cs +++ b/Dalamud/Support/Troubleshooting.cs @@ -8,7 +8,9 @@ using Dalamud.Interface.Internal; using Dalamud.Plugin.Internal; using Dalamud.Plugin.Internal.Types.Manifest; using Dalamud.Utility; + using Newtonsoft.Json; + using Serilog; namespace Dalamud.Support; @@ -32,7 +34,7 @@ public static class Troubleshooting { LastException = exception; - var fixedContext = context?.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(); + var fixedContext = context?.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(); try { @@ -127,7 +129,7 @@ public static class Troubleshooting public bool ForcedMinHook { get; set; } - public List ThirdRepo => new(); + public List ThirdRepo => []; public bool HasThirdRepo { get; set; } } diff --git a/Dalamud/Utility/ArrayExtensions.cs b/Dalamud/Utility/ArrayExtensions.cs index 5b6ce2332..5444468c6 100644 --- a/Dalamud/Utility/ArrayExtensions.cs +++ b/Dalamud/Utility/ArrayExtensions.cs @@ -115,8 +115,7 @@ internal static class ArrayExtensions if (count < 0 || startIndex > list.Count - count) throw new ArgumentOutOfRangeException(nameof(count), count, null); - if (match == null) - throw new ArgumentNullException(nameof(match)); + ArgumentNullException.ThrowIfNull(match); var endIndex = startIndex + count; for (var i = startIndex; i < endIndex; i++) @@ -138,8 +137,7 @@ internal static class ArrayExtensions /// public static int FindLastIndex(this IReadOnlyList list, int startIndex, int count, Predicate match) { - if (match == null) - throw new ArgumentNullException(nameof(match)); + ArgumentNullException.ThrowIfNull(match); if (list.Count == 0) { diff --git a/Dalamud/Utility/CultureFixes.cs b/Dalamud/Utility/CultureFixes.cs index 133e79c71..f37844206 100644 --- a/Dalamud/Utility/CultureFixes.cs +++ b/Dalamud/Utility/CultureFixes.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; namespace Dalamud.Utility; @@ -22,7 +22,7 @@ internal static class CultureFixes // This glyph is not present in any game fonts and not in the range for our Noto // so it will be rendered as a geta (=) instead. That's a hack, but it works and // doesn't look as weird. - CultureInfo PatchCulture(CultureInfo info) + static CultureInfo PatchCulture(CultureInfo info) { var newCulture = (CultureInfo)info.Clone(); diff --git a/Dalamud/Utility/DateTimeSpanExtensions.cs b/Dalamud/Utility/DateTimeSpanExtensions.cs index 3cf8975af..d60b17924 100644 --- a/Dalamud/Utility/DateTimeSpanExtensions.cs +++ b/Dalamud/Utility/DateTimeSpanExtensions.cs @@ -100,7 +100,7 @@ public static class DateTimeSpanExtensions private sealed class ParsedRelativeFormatStrings { - private readonly List<(float MinSeconds, string FormatString)> formatStrings = new(); + private readonly List<(float MinSeconds, string FormatString)> formatStrings = []; public ParsedRelativeFormatStrings(string value) { diff --git a/Dalamud/Utility/DiagnosticUtil.cs b/Dalamud/Utility/DiagnosticUtil.cs index 155d5cda7..d853a2668 100644 --- a/Dalamud/Utility/DiagnosticUtil.cs +++ b/Dalamud/Utility/DiagnosticUtil.cs @@ -1,8 +1,6 @@ -using System.Diagnostics; +using System.Diagnostics; using System.Linq; -using Dalamud.Bindings.ImGui; - namespace Dalamud.Utility; /// diff --git a/Dalamud/Utility/DisposeSafety.cs b/Dalamud/Utility/DisposeSafety.cs index 64d31048f..ac7ed07d7 100644 --- a/Dalamud/Utility/DisposeSafety.cs +++ b/Dalamud/Utility/DisposeSafety.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reactive.Disposables; @@ -92,7 +92,7 @@ public static class DisposeSafety new AggregateException( new[] { e }.Concat( (IEnumerable)r.Exception?.InnerExceptions - ?? new[] { new OperationCanceledException() }))); + ?? [new OperationCanceledException()]))); } } @@ -125,7 +125,7 @@ public static class DisposeSafety } catch (Exception de) { - exceptions ??= new(); + exceptions ??= []; exceptions.Add(de); } } @@ -140,7 +140,7 @@ public static class DisposeSafety /// public class ScopedFinalizer : IDisposeCallback, IAsyncDisposable { - private readonly List objects = new(); + private readonly List objects = []; /// public event Action? BeforeDispose; @@ -338,7 +338,7 @@ public static class DisposeSafety } catch (Exception ex) { - exceptions ??= new(); + exceptions ??= []; exceptions.Add(ex); } } @@ -402,7 +402,7 @@ public static class DisposeSafety } catch (Exception ex) { - exceptions ??= new(); + exceptions ??= []; exceptions.Add(ex); } } diff --git a/Dalamud/Utility/DynamicPriorityQueueLoader.cs b/Dalamud/Utility/DynamicPriorityQueueLoader.cs index 83fd366bb..c32858bb4 100644 --- a/Dalamud/Utility/DynamicPriorityQueueLoader.cs +++ b/Dalamud/Utility/DynamicPriorityQueueLoader.cs @@ -15,7 +15,7 @@ internal class DynamicPriorityQueueLoader : IDisposable private readonly Channel newItemChannel; private readonly Channel workTokenChannel; - private readonly List workItemPending = new(); + private readonly List workItemPending = []; private bool disposing; diff --git a/Dalamud/Utility/EventHandlerExtensions.cs b/Dalamud/Utility/EventHandlerExtensions.cs index 285e18fa2..415937dbf 100644 --- a/Dalamud/Utility/EventHandlerExtensions.cs +++ b/Dalamud/Utility/EventHandlerExtensions.cs @@ -4,6 +4,7 @@ using Dalamud.Game; using Dalamud.Game.Gui.ContextMenu; using Dalamud.Game.Gui.NamePlate; using Dalamud.Plugin.Services; + using Serilog; namespace Dalamud.Utility; diff --git a/Dalamud/Utility/FuzzyMatcher.cs b/Dalamud/Utility/FuzzyMatcher.cs index 03723da89..d8b881300 100644 --- a/Dalamud/Utility/FuzzyMatcher.cs +++ b/Dalamud/Utility/FuzzyMatcher.cs @@ -1,4 +1,4 @@ -#define BORDER_MATCHING +#define BORDER_MATCHING using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -32,18 +32,12 @@ internal readonly ref struct FuzzyMatcher this.needleFinalPosition = this.needleSpan.Length - 1; this.mode = matchMode; - switch (matchMode) + this.needleSegments = matchMode switch { - case MatchMode.FuzzyParts: - this.needleSegments = FindNeedleSegments(this.needleSpan); - break; - case MatchMode.Fuzzy: - case MatchMode.Simple: - this.needleSegments = EmptySegArray; - break; - default: - throw new ArgumentOutOfRangeException(nameof(matchMode), matchMode, null); - } + MatchMode.FuzzyParts => FindNeedleSegments(this.needleSpan), + MatchMode.Fuzzy or MatchMode.Simple => EmptySegArray, + _ => throw new ArgumentOutOfRangeException(nameof(matchMode), matchMode, null), + }; } private static (int Start, int End)[] FindNeedleSegments(ReadOnlySpan span) diff --git a/Dalamud/Utility/Hash.cs b/Dalamud/Utility/Hash.cs index 08fc78901..952c2305f 100644 --- a/Dalamud/Utility/Hash.cs +++ b/Dalamud/Utility/Hash.cs @@ -1,4 +1,4 @@ -using System.Security.Cryptography; +using System.Security.Cryptography; namespace Dalamud.Utility; @@ -24,10 +24,9 @@ public static class Hash /// The computed hash. internal static string GetSha256Hash(byte[] buffer) { - using var sha = SHA256.Create(); - var hash = sha.ComputeHash(buffer); + var hash = SHA256.HashData(buffer); return ByteArrayToString(hash); } - private static string ByteArrayToString(byte[] ba) => BitConverter.ToString(ba).Replace("-", string.Empty); + private static string ByteArrayToString(byte[] ba) => Convert.ToHexString(ba); } diff --git a/Dalamud/Utility/RollingList.cs b/Dalamud/Utility/RollingList.cs index 0f1553bf9..896b74fbf 100644 --- a/Dalamud/Utility/RollingList.cs +++ b/Dalamud/Utility/RollingList.cs @@ -40,7 +40,7 @@ namespace Dalamud.Utility { ThrowHelper.ThrowArgumentOutOfRangeExceptionIfLessThan(nameof(size), size, 0); this.size = size; - this.items = new(); + this.items = []; } /// Initializes a new instance of the class. diff --git a/Dalamud/Utility/Signatures/SignatureHelper.cs b/Dalamud/Utility/Signatures/SignatureHelper.cs index cdf601852..e1a4dafc2 100755 --- a/Dalamud/Utility/Signatures/SignatureHelper.cs +++ b/Dalamud/Utility/Signatures/SignatureHelper.cs @@ -5,8 +5,8 @@ using System.Runtime.InteropServices; using Dalamud.Game; using Dalamud.Hooking; -using Dalamud.Logging; using Dalamud.Utility.Signatures.Wrappers; + using Serilog; namespace Dalamud.Utility.Signatures; @@ -72,9 +72,8 @@ internal static class SignatureHelper } } - IntPtr ptr; var success = sig.ScanType == ScanType.Text - ? scanner.TryScanText(sig.Signature, out ptr) + ? scanner.TryScanText(sig.Signature, out var ptr) : scanner.TryGetStaticAddressFromSig(sig.Signature, out ptr); if (!success) { @@ -159,7 +158,7 @@ internal static class SignatureHelper continue; } - var hook = creator.Invoke(null, new object?[] { ptr, detour, false }) as IDalamudHook; + var hook = creator.Invoke(null, [ptr, detour, false]) as IDalamudHook; info.SetValue(self, hook); createdHooks.Add(hook); diff --git a/Dalamud/Utility/StringExtensions.cs b/Dalamud/Utility/StringExtensions.cs index c28aebab2..7f9975f82 100644 --- a/Dalamud/Utility/StringExtensions.cs +++ b/Dalamud/Utility/StringExtensions.cs @@ -57,7 +57,7 @@ public static class StringExtensions /// The input string. /// /// A new string with the first character converted to uppercase. - [return: NotNullIfNotNull("input")] + [return: NotNullIfNotNull(nameof(input))] public static string? FirstCharToUpper(this string? input, CultureInfo? culture = null) => string.IsNullOrWhiteSpace(input) ? input @@ -69,7 +69,7 @@ public static class StringExtensions /// The input string. /// /// A new string with the first character converted to lowercase. - [return: NotNullIfNotNull("input")] + [return: NotNullIfNotNull(nameof(input))] public static string? FirstCharToLower(this string? input, CultureInfo? culture = null) => string.IsNullOrWhiteSpace(input) ? input diff --git a/Dalamud/Utility/TerraFxCom/TerraFxComInterfaceExtensions.cs b/Dalamud/Utility/TerraFxCom/TerraFxComInterfaceExtensions.cs index ec108403e..f952cba7e 100644 --- a/Dalamud/Utility/TerraFxCom/TerraFxComInterfaceExtensions.cs +++ b/Dalamud/Utility/TerraFxCom/TerraFxComInterfaceExtensions.cs @@ -51,38 +51,22 @@ internal static unsafe partial class TerraFxComInterfaceExtensions throw new ArgumentOutOfRangeException(nameof(mode), mode, null); } - switch (access) + grfMode |= access switch { - case FileAccess.Read: - grfMode |= STGM.STGM_READ; - break; - case FileAccess.Write: - grfMode |= STGM.STGM_WRITE; - break; - case FileAccess.ReadWrite: - grfMode |= STGM.STGM_READWRITE; - break; - default: - throw new ArgumentOutOfRangeException(nameof(access), access, null); - } + FileAccess.Read => STGM.STGM_READ, + FileAccess.Write => STGM.STGM_WRITE, + FileAccess.ReadWrite => (uint)STGM.STGM_READWRITE, + _ => throw new ArgumentOutOfRangeException(nameof(access), access, null), + }; - switch (share) + grfMode |= share switch { - case FileShare.None: - grfMode |= STGM.STGM_SHARE_EXCLUSIVE; - break; - case FileShare.Read: - grfMode |= STGM.STGM_SHARE_DENY_WRITE; - break; - case FileShare.Write: - grfMode |= STGM.STGM_SHARE_DENY_READ; - break; - case FileShare.ReadWrite: - grfMode |= STGM.STGM_SHARE_DENY_NONE; - break; - default: - throw new NotSupportedException($"Only ${FileShare.Read} and ${FileShare.Write} are supported."); - } + FileShare.None => STGM.STGM_SHARE_EXCLUSIVE, + FileShare.Read => STGM.STGM_SHARE_DENY_WRITE, + FileShare.Write => STGM.STGM_SHARE_DENY_READ, + FileShare.ReadWrite => (uint)STGM.STGM_SHARE_DENY_NONE, + _ => throw new NotSupportedException($"Only ${FileShare.Read} and ${FileShare.Write} are supported."), + }; using var stream = default(ComPtr); fixed (char* pPath = path) diff --git a/Dalamud/Utility/Timing/Timings.cs b/Dalamud/Utility/Timing/Timings.cs index e2c00461c..563221fb9 100644 --- a/Dalamud/Utility/Timing/Timings.cs +++ b/Dalamud/Utility/Timing/Timings.cs @@ -19,12 +19,12 @@ public static class Timings /// /// All concluded timings. /// - internal static readonly SortedList AllTimings = new(); + internal static readonly SortedList AllTimings = []; /// /// List of all timing events. /// - internal static readonly List Events = new(); + internal static readonly List Events = []; private static readonly AsyncLocal>> TaskTimingHandleStorage = new(); @@ -36,7 +36,7 @@ public static class Timings get { if (TaskTimingHandleStorage.Value == null || TaskTimingHandleStorage.Value.Item1 != Task.CurrentId) - TaskTimingHandleStorage.Value = Tuple.Create>(Task.CurrentId, new()); + TaskTimingHandleStorage.Value = Tuple.Create>(Task.CurrentId, []); return TaskTimingHandleStorage.Value!.Item2!; } set => TaskTimingHandleStorage.Value = Tuple.Create(Task.CurrentId, value); @@ -53,7 +53,7 @@ public static class Timings var outerTimingHandle = TaskTimingHandles; return () => { - T res = default(T); + var res = default(T); var prev = TaskTimingHandles; TaskTimingHandles = outerTimingHandle; try diff --git a/Dalamud/Utility/Util.cs b/Dalamud/Utility/Util.cs index 0ea5bbcbf..72db5cfc6 100644 --- a/Dalamud/Utility/Util.cs +++ b/Dalamud/Utility/Util.cs @@ -367,7 +367,7 @@ public static partial class Util /// Human readable version. public static string FormatBytes(long bytes) { - string[] suffix = { "B", "KB", "MB", "GB", "TB" }; + string[] suffix = ["B", "KB", "MB", "GB", "TB"]; int i; double dblSByte = bytes; for (i = 0; i < suffix.Length && bytes >= 1024; i++, bytes /= 1024) @@ -823,7 +823,7 @@ public static partial class Util MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, null, - new[] { typeof(object), typeof(IList), typeof(ulong) }, + [typeof(object), typeof(IList), typeof(ulong)], obj.GetType(), true); @@ -850,7 +850,7 @@ public static partial class Util ilg.Emit(OpCodes.Call, mm); ilg.Emit(OpCodes.Ret); - dm.Invoke(null, new[] { obj, path, addr }); + dm.Invoke(null, [obj, path, addr]); } #pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type @@ -1029,8 +1029,8 @@ public static partial class Util foreach (var f in obj.GetType() .GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance)) { - var fixedBuffer = (FixedBufferAttribute)f.GetCustomAttribute(typeof(FixedBufferAttribute)); - var offset = (FieldOffsetAttribute)f.GetCustomAttribute(typeof(FieldOffsetAttribute)); + var fixedBuffer = f.GetCustomAttribute(); + var offset = f.GetCustomAttribute(); if (fixedBuffer != null) { diff --git a/Dalamud/Utility/WeakConcurrentCollection.cs b/Dalamud/Utility/WeakConcurrentCollection.cs index a3bc04651..c23ebac9a 100644 --- a/Dalamud/Utility/WeakConcurrentCollection.cs +++ b/Dalamud/Utility/WeakConcurrentCollection.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; @@ -11,7 +11,7 @@ namespace Dalamud.Utility; /// The type of object that we're tracking. public class WeakConcurrentCollection : ICollection where T : class { - private readonly ConditionalWeakTable cwt = new(); + private readonly ConditionalWeakTable cwt = []; /// public int Count => this.cwt.Count(); diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Sample/Dalamud.EnumGenerator.Sample.csproj b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Sample/Dalamud.EnumGenerator.Sample.csproj new file mode 100644 index 000000000..225ea5f94 --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Sample/Dalamud.EnumGenerator.Sample.csproj @@ -0,0 +1,20 @@ + + + + net9.0 + enable + Dalamud.EnumGenerator.Sample + + false + + + + + + + + + + + + diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Sample/EnumCloneMap.txt b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Sample/EnumCloneMap.txt new file mode 100644 index 000000000..a7db08bf3 --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Sample/EnumCloneMap.txt @@ -0,0 +1,4 @@ +# Format: Target.Full.TypeName = Source.Full.EnumTypeName +# Example: Generate a local enum MyGeneratedEnum in namespace Sample.Gen mapped to SourceEnums.SampleSourceEnum +Dalamud.EnumGenerator.Sample.Gen.MyGeneratedEnum = Dalamud.EnumGenerator.Sample.SourceEnums.SampleSourceEnum + diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Sample/SourceEnums.cs b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Sample/SourceEnums.cs new file mode 100644 index 000000000..407b4c151 --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Sample/SourceEnums.cs @@ -0,0 +1,9 @@ +namespace Dalamud.EnumGenerator.Sample.SourceEnums +{ + public enum SampleSourceEnum : long + { + First = 1, + Second = 2, + Third = 10000000000L + } +} diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Tests/Dalamud.EnumGenerator.Tests.csproj b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Tests/Dalamud.EnumGenerator.Tests.csproj new file mode 100644 index 000000000..50de4a7c8 --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Tests/Dalamud.EnumGenerator.Tests.csproj @@ -0,0 +1,29 @@ + + + + net9.0 + enable + + false + + Dalamud.EnumGenerator.Tests + + false + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Tests/EnumCloneMapTests.cs b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Tests/EnumCloneMapTests.cs new file mode 100644 index 000000000..f14279c53 --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Tests/EnumCloneMapTests.cs @@ -0,0 +1,47 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace Dalamud.EnumGenerator.Tests; + +public class EnumCloneMapTests +{ + [Fact] + public void ParseMappings_SimpleLines_ParsesCorrectly() + { + var text = @"# Comment line +My.Namespace.Target = Other.Namespace.Source + +Another.Target = Some.Source"; + + var results = Dalamud.EnumGenerator.EnumCloneGenerator.ParseMappings(text); + + Assert.Equal(2, results.Length); + Assert.Equal("My.Namespace.Target", results[0].TargetFullName); + Assert.Equal("Other.Namespace.Source", results[0].SourceFullName); + Assert.Equal("Another.Target", results[1].TargetFullName); + } + + [Fact] + public void Generator_ProducesFile_WhenSourceResolved() + { + // We'll create a compilation that contains a source enum type and add an AdditionalText mapping + var sourceEnum = @"namespace Foo.Bar { public enum SourceEnum { A = 1, B = 2 } }"; + + var mapText = "GeneratedNs.TargetEnum = Foo.Bar.SourceEnum"; + + var generator = new EnumCloneGenerator(); + var driver = CSharpGeneratorDriver.Create(generator) + .AddAdditionalTexts(ImmutableArray.Create(new Utils.TestAdditionalFile("EnumCloneMap.txt", mapText))); + + var compilation = CSharpCompilation.Create("TestGen", [CSharpSyntaxTree.ParseText(sourceEnum)], + [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)]); + + driver.RunGeneratorsAndUpdateCompilation(compilation, out var newCompilation, out var diagnostics); + + var generated = newCompilation.SyntaxTrees.Select(t => t.FilePath).Where(p => p.EndsWith("TargetEnum.CloneEnum.g.cs")).ToArray(); + Assert.Single(generated); + } +} diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Tests/Utils/TestAdditionalFile.cs b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Tests/Utils/TestAdditionalFile.cs new file mode 100644 index 000000000..e5c0df848 --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator.Tests/Utils/TestAdditionalFile.cs @@ -0,0 +1,21 @@ +using System.Threading; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Dalamud.EnumGenerator.Tests.Utils; + +public class TestAdditionalFile : AdditionalText +{ + private readonly SourceText text; + + public TestAdditionalFile(string path, string text) + { + Path = path; + this.text = SourceText.From(text); + } + + public override SourceText GetText(CancellationToken cancellationToken = new()) => this.text; + + public override string Path { get; } +} diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/AnalyzerReleases.Shipped.md b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/AnalyzerReleases.Shipped.md new file mode 100644 index 000000000..60b59dd99 --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/AnalyzerReleases.Shipped.md @@ -0,0 +1,3 @@ +; Shipped analyzer releases +; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md + diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/AnalyzerReleases.Unshipped.md b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/AnalyzerReleases.Unshipped.md new file mode 100644 index 000000000..e90084796 --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/AnalyzerReleases.Unshipped.md @@ -0,0 +1,9 @@ +; Unshipped analyzer release +; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +ENUMGEN001 | EnumGenerator | Warning | SourceGeneratorWithAttributes +ENUMGEN002 | EnumGenerator | Warning | SourceGeneratorWithAttributes \ No newline at end of file diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/Dalamud.EnumGenerator.csproj b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/Dalamud.EnumGenerator.csproj new file mode 100644 index 000000000..106b036a8 --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/Dalamud.EnumGenerator.csproj @@ -0,0 +1,33 @@ + + + + netstandard2.0 + false + enable + latest + + true + true + + Dalamud.EnumGenerator + Dalamud.EnumGenerator + + false + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/EnumCloneGenerator.cs b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/EnumCloneGenerator.cs new file mode 100644 index 000000000..10cf0723c --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/EnumCloneGenerator.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Text; +using System.Globalization; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Dalamud.EnumGenerator; + +[Generator] +public class EnumCloneGenerator : IIncrementalGenerator +{ + private const string NewLine = "\r\n"; + + private const string MappingFileName = "EnumCloneMap.txt"; + + private static readonly DiagnosticDescriptor MissingSourceDescriptor = new( + id: "ENUMGEN001", + title: "Source enum not found", + messageFormat: "Source enum '{0}' could not be resolved by the compilation", + category: "EnumGenerator", + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + private static readonly DiagnosticDescriptor DuplicateTargetDescriptor = new( + id: "ENUMGEN002", + title: "Duplicate target mapping", + messageFormat: "Target enum '{0}' is mapped multiple times; generation skipped for this target", + category: "EnumGenerator", + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + public void Initialize(IncrementalGeneratorInitializationContext context) + { + // Read mappings from additional files named EnumCloneMap.txt + var mappingEntries = context.AdditionalTextsProvider + .Where(at => Path.GetFileName(at.Path).Equals(MappingFileName, StringComparison.OrdinalIgnoreCase)) + .SelectMany((at, _) => ParseMappings(at.GetText()?.ToString() ?? string.Empty)); + + // Combine with compilation so we can resolve types + var compilationAndMaps = context.CompilationProvider.Combine(mappingEntries.Collect()); + + context.RegisterSourceOutput(compilationAndMaps, (spc, pair) => + { + var compilation = pair.Left; + var maps = pair.Right; + + // Detect duplicate targets first and report diagnostics + var duplicateTargets = maps.GroupBy(m => m.TargetFullName, StringComparer.OrdinalIgnoreCase) + .Where(g => g.Count() > 1) + .Select(g => g.Key) + .ToImmutableArray(); + foreach (var dup in duplicateTargets) + { + var diag = Diagnostic.Create(DuplicateTargetDescriptor, Location.None, dup); + spc.ReportDiagnostic(diag); + } + + foreach (var (targetFullName, sourceFullName) in maps) + { + if (string.IsNullOrWhiteSpace(targetFullName) || string.IsNullOrWhiteSpace(sourceFullName)) + continue; + + if (duplicateTargets.Contains(targetFullName, StringComparer.OrdinalIgnoreCase)) + continue; + + // Resolve the source enum type by metadata name (namespace.type) + var sourceSymbol = compilation.GetTypeByMetadataName(sourceFullName); + if (sourceSymbol is null) + { + // Report diagnostic for missing source type + var diag = Diagnostic.Create(MissingSourceDescriptor, Location.None, sourceFullName); + spc.ReportDiagnostic(diag); + continue; + } + + if (sourceSymbol.TypeKind != TypeKind.Enum) + continue; + + var sourceNamed = sourceSymbol; // GetTypeByMetadataName already returns INamedTypeSymbol + + // Split target into namespace and type name + string? targetNamespace = null; + var targetName = targetFullName; + var lastDot = targetFullName.LastIndexOf('.'); + if (lastDot >= 0) + { + targetNamespace = targetFullName.Substring(0, lastDot); + targetName = targetFullName.Substring(lastDot + 1); + } + + var underlyingType = sourceNamed.EnumUnderlyingType; + var underlyingDisplay = underlyingType?.ToDisplayString() ?? "int"; + + var fields = sourceNamed.GetMembers() + .OfType() + .Where(f => f.IsStatic && f.HasConstantValue) + .ToArray(); + + var memberLines = fields.Select(f => + { + var name = f.Name; + var constValue = f.ConstantValue; + string literal; + + var st = underlyingType?.SpecialType ?? SpecialType.System_Int32; + + if (constValue is null) + { + literal = "0"; + } + else if (st == SpecialType.System_UInt64) + { + literal = Convert.ToString(constValue, CultureInfo.InvariantCulture) + "UL"; + } + else if (st == SpecialType.System_UInt32) + { + literal = Convert.ToString(constValue, CultureInfo.InvariantCulture) + "U"; + } + else if (st == SpecialType.System_Int64) + { + literal = Convert.ToString(constValue, CultureInfo.InvariantCulture) + "L"; + } + else + { + literal = Convert.ToString(constValue, CultureInfo.InvariantCulture) ?? throw new InvalidOperationException("Unable to convert enum constant value to string."); + } + + return $" {name} = {literal},"; + }); + + var membersText = string.Join(NewLine, memberLines); + + var nsPrefix = targetNamespace is null ? string.Empty : $"namespace {targetNamespace};" + NewLine + NewLine; + + var sourceFullyQualified = sourceNamed.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + + var code = "// " + NewLine + NewLine + + nsPrefix + + $"public enum {targetName} : {underlyingDisplay}" + NewLine + + "{" + NewLine + + membersText + NewLine + + "}" + NewLine + NewLine; + + var extClassName = targetName + "Conversions"; + var extMethodName = "ToDalamud" + targetName; + + var extClass = $"public static class {extClassName}" + NewLine + + "{" + NewLine + + $" public static {targetName} {extMethodName}(this {sourceFullyQualified} value) => ({targetName})(({underlyingDisplay})value);" + NewLine + + "}" + NewLine; + + code += extClass; + + var hintName = $"{targetName}.CloneEnum.g.cs"; + spc.AddSource(hintName, SourceText.From(code, Encoding.UTF8)); + } + }); + } + + internal static ImmutableArray<(string TargetFullName, string SourceFullName)> ParseMappings(string text) + { + var builder = ImmutableArray.CreateBuilder<(string, string)>(); + using var reader = new StringReader(text); + string? line; + while ((line = reader.ReadLine()) != null) + { + // Remove comments starting with # + var commentIndex = line.IndexOf('#'); + var content = commentIndex >= 0 ? line.Substring(0, commentIndex) : line; + content = content.Trim(); + if (string.IsNullOrEmpty(content)) + continue; + + // Expected format: Target.Full.Name = Source.Full.Name + var idx = content.IndexOf('='); + if (idx <= 0) + continue; + + var left = content.Substring(0, idx).Trim(); + var right = content.Substring(idx + 1).Trim(); + if (string.IsNullOrEmpty(left) || string.IsNullOrEmpty(right)) + continue; + + builder.Add((left, right)); + } + + return builder.ToImmutable(); + } +} diff --git a/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/Properties/AssemblyInfo.cs b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..6eac4d12e --- /dev/null +++ b/generators/Dalamud.EnumGenerator/Dalamud.EnumGenerator/Properties/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Dalamud.EnumGenerator.Tests")] + diff --git a/lib/FFXIVClientStructs b/lib/FFXIVClientStructs index b6f886afc..d83e0c13d 160000 --- a/lib/FFXIVClientStructs +++ b/lib/FFXIVClientStructs @@ -1 +1 @@ -Subproject commit b6f886afc2b1a54d8fd76c37a260a05f214a559e +Subproject commit d83e0c13d3c802d4a483f373edcd129bc4802073 diff --git a/lib/Lumina.Excel b/lib/Lumina.Excel index 52cb5e0a9..31e50c3f2 160000 --- a/lib/Lumina.Excel +++ b/lib/Lumina.Excel @@ -1 +1 @@ -Subproject commit 52cb5e0a9a7a1138d8c2406c277307a6c9ad8898 +Subproject commit 31e50c3f267dd845891b328140106a0cc3b1f35e