From ff1d7f28298a302080380e57188cd01fa38f7d29 Mon Sep 17 00:00:00 2001 From: Raymond Date: Fri, 20 Aug 2021 11:59:35 -0400 Subject: [PATCH] Implement service locator --- Dalamud.CorePlugin/PluginImpl.cs | 42 +-- Dalamud.CorePlugin/PluginWindow.cs | 9 +- .../SeStringHandling/SeStringManagerTests.cs | 2 +- Dalamud/Dalamud.cs | 274 +++++------------- Dalamud/Data/DataManager.cs | 15 +- Dalamud/EntryPoint.cs | 3 - Dalamud/Game/BaseAddressResolver.cs | 9 + Dalamud/Game/ChatHandlers.cs | 82 ++++-- Dalamud/Game/ClientState/Buddy/BuddyList.cs | 15 +- Dalamud/Game/ClientState/Buddy/BuddyMember.cs | 15 +- Dalamud/Game/ClientState/ClientState.cs | 102 ++----- Dalamud/Game/ClientState/Fates/Fate.cs | 15 +- Dalamud/Game/ClientState/Fates/FateTable.cs | 15 +- Dalamud/Game/ClientState/Keys/KeyState.cs | 9 +- .../Game/ClientState/Objects/ObjectTable.cs | 23 +- .../ClientState/Objects/SubKinds/BattleNpc.cs | 5 +- .../ClientState/Objects/SubKinds/EventObj.cs | 5 +- .../Game/ClientState/Objects/SubKinds/Npc.cs | 5 +- .../Objects/SubKinds/PlayerCharacter.cs | 9 +- .../Objects/{Targets.cs => TargetManager.cs} | 23 +- .../ClientState/Objects/Types/BattleChara.cs | 7 +- .../ClientState/Objects/Types/Character.cs | 8 +- .../ClientState/Objects/Types/GameObject.cs | 10 +- Dalamud/Game/ClientState/Party/PartyList.cs | 21 +- Dalamud/Game/ClientState/Party/PartyMember.cs | 17 +- .../ClientState/Resolvers/ExcelResolver{T}.cs | 9 +- Dalamud/Game/ClientState/Statuses/Status.cs | 11 +- .../Game/ClientState/Statuses/StatusList.cs | 17 +- Dalamud/Game/Command/CommandManager.cs | 16 +- Dalamud/Game/Framework.cs | 92 +++--- Dalamud/Game/Gui/ChatGui.cs | 37 +-- Dalamud/Game/Gui/FlyText/FlyTextGui.cs | 18 +- Dalamud/Game/Gui/GameGui.cs | 62 ++-- Dalamud/Game/Gui/Internal/DalamudIME.cs | 13 +- .../Game/Gui/PartyFinder/PartyFinderGui.cs | 15 +- .../PartyFinder/Types/PartyFinderListing.cs | 11 +- Dalamud/Game/Gui/Toast/ToastGui.cs | 21 +- Dalamud/Game/Internal/AntiDebug.cs | 5 +- Dalamud/Game/Internal/DalamudSystemMenu.cs | 27 +- Dalamud/Game/Libc/LibcFunction.cs | 10 +- Dalamud/Game/Network/GameNetwork.cs | 13 +- .../UniversalisMarketBoardUploader.cs | 23 +- .../Game/Network/Internal/NetworkHandlers.cs | 46 +-- Dalamud/Game/SigScanner.cs | 4 + Dalamud/Game/Text/SeStringHandling/Payload.cs | 9 +- .../Payloads/AutoTranslatePayload.cs | 5 +- .../SeStringHandling/Payloads/ItemPayload.cs | 5 +- .../Payloads/MapLinkPayload.cs | 9 +- .../Payloads/PlayerPayload.cs | 5 +- .../SeStringHandling/Payloads/QuestPayload.cs | 5 +- .../Payloads/StatusPayload.cs | 5 +- .../Payloads/UIForegroundPayload.cs | 7 +- .../Payloads/UIGlowPayload.cs | 7 +- .../Game/Text/SeStringHandling/SeString.cs | 9 +- .../Text/SeStringHandling/SeStringManager.cs | 38 +-- Dalamud/Hooking/Internal/HookManager.cs | 4 +- Dalamud/Interface/Internal/DalamudCommands.cs | 172 ++++++----- .../Interface/Internal/DalamudInterface.cs | 109 ++++--- .../Interface/Internal/InterfaceManager.cs | 91 +++--- Dalamud/Interface/Internal/Notifications.cs | 6 +- .../Scratchpad/ScratchExecutionManager.cs | 7 +- .../Scratchpad/ScratchMacroProcessor.cs | 10 +- Dalamud/Interface/Internal/UiDebug.cs | 15 +- .../Internal/Windows/ChangelogWindow.cs | 8 +- .../Internal/Windows/ConsoleWindow.cs | 36 +-- .../Internal/Windows/CreditsWindow.cs | 19 +- .../Interface/Internal/Windows/DataWindow.cs | 251 +++++++++------- .../Interface/Internal/Windows/IMEWindow.cs | 18 +- .../Internal/Windows/PluginInstallerWindow.cs | 167 +++++++---- .../Internal/Windows/PluginStatWindow.cs | 11 +- .../Internal/Windows/ScratchpadWindow.cs | 9 +- .../AgingSteps/ActorTableAgingStep.cs | 11 +- .../SelfTest/AgingSteps/ChatAgingStep.cs | 19 +- .../SelfTest/AgingSteps/ConditionAgingStep.cs | 12 +- .../AgingSteps/EnterTerritoryAgingStep.cs | 17 +- .../SelfTest/AgingSteps/FateTableAgingStep.cs | 13 +- .../AgingSteps/GamepadStateAgingStep.cs | 14 +- .../AgingSteps/HandledExceptionAgingStep.cs | 6 +- .../SelfTest/AgingSteps/HoverAgingStep.cs | 16 +- .../Windows/SelfTest/AgingSteps/IAgingStep.cs | 8 +- .../SelfTest/AgingSteps/KeyStateAgingStep.cs | 18 +- .../AgingSteps/LoginEventAgingStep.cs | 17 +- .../AgingSteps/LogoutEventAgingStep.cs | 17 +- .../SelfTest/AgingSteps/LuminaAgingStep.cs | 11 +- .../AgingSteps/PartyFinderAgingStep.cs | 17 +- .../SelfTest/AgingSteps/TargetAgingStep.cs | 17 +- .../SelfTest/AgingSteps/ToastAgingStep.cs | 14 +- .../AgingSteps/WaitFramesAgingStep.cs | 6 +- .../Windows/SelfTest/SelfTestWindow.cs | 13 +- .../Internal/Windows/SettingsWindow.cs | 111 +++---- Dalamud/Interface/UiBuilder.cs | 65 +++-- .../IoC/Internal/InterfaceVersionAttribute.cs | 25 ++ Dalamud/IoC/PluginInterfaceAttribute.cs | 12 + Dalamud/IoC/RequiredVersionAttribute.cs | 25 ++ Dalamud/Memory/MemoryHelper.cs | 17 +- Dalamud/Plugin/DalamudPluginInterface.cs | 74 +++-- Dalamud/Plugin/Internal/LocalDevPlugin.cs | 13 +- Dalamud/Plugin/Internal/LocalPlugin.cs | 18 +- Dalamud/Plugin/Internal/PluginManager.cs | 73 +++-- Dalamud/Service{T}.cs | 122 ++++++++ Dalamud/Troubleshooting.cs | 22 +- 101 files changed, 1614 insertions(+), 1436 deletions(-) rename Dalamud/Game/ClientState/Objects/{Targets.cs => TargetManager.cs} (86%) create mode 100644 Dalamud/IoC/Internal/InterfaceVersionAttribute.cs create mode 100644 Dalamud/IoC/PluginInterfaceAttribute.cs create mode 100644 Dalamud/IoC/RequiredVersionAttribute.cs create mode 100644 Dalamud/Service{T}.cs diff --git a/Dalamud.CorePlugin/PluginImpl.cs b/Dalamud.CorePlugin/PluginImpl.cs index d00539559..d6e472277 100644 --- a/Dalamud.CorePlugin/PluginImpl.cs +++ b/Dalamud.CorePlugin/PluginImpl.cs @@ -1,6 +1,6 @@ using System; -using System.IO; +using Dalamud.Game.Command; using Dalamud.Interface.Windowing; using Dalamud.Logging; using Dalamud.Plugin; @@ -14,7 +14,8 @@ namespace Dalamud.CorePlugin public sealed class PluginImpl : IDalamudPlugin { private readonly WindowSystem windowSystem = new("Dalamud.CorePlugin"); - private Localization localizationManager; + + // private Localization localizationManager; /// public string Name => "Dalamud.CorePlugin"; @@ -29,16 +30,16 @@ namespace Dalamud.CorePlugin { try { - this.InitLoc(); - + // this.InitLoc(); this.Interface = pluginInterface; - this.windowSystem.AddWindow(new PluginWindow(Dalamud.Instance)); + this.windowSystem.AddWindow(new PluginWindow()); this.Interface.UiBuilder.Draw += this.OnDraw; this.Interface.UiBuilder.OpenConfigUi += this.OnOpenConfigUi; - this.Interface.CommandManager.AddHandler("/di", new(this.OnCommand) { HelpMessage = $"Access the {this.Name} plugin." }); + var commandManager = Service.Get(); + commandManager.AddHandler("/di", new(this.OnCommand) { HelpMessage = $"Access the {this.Name} plugin." }); } catch (Exception ex) { @@ -58,20 +59,23 @@ namespace Dalamud.CorePlugin this.Interface.Dispose(); } - private void InitLoc() - { - // CheapLoc needs to be reinitialized here because it tracks the setup by assembly name. New assembly, new setup. - this.localizationManager = new Localization(Path.Combine(Dalamud.Instance.AssetDirectory.FullName, "UIRes", "loc", "dalamud"), "dalamud_"); - if (!string.IsNullOrEmpty(Dalamud.Instance.Configuration.LanguageOverride)) - { - this.localizationManager.SetupWithLangCode(Dalamud.Instance.Configuration.LanguageOverride); - } - else - { - this.localizationManager.SetupWithUiCulture(); - } - } + // private void InitLoc() + // { + // // CheapLoc needs to be reinitialized here because it tracks the setup by assembly name. New assembly, new setup. + // this.localizationManager = new Localization(Path.Combine(Dalamud.Instance.AssetDirectory.FullName, "UIRes", "loc", "dalamud"), "dalamud_"); + // if (!string.IsNullOrEmpty(Dalamud.Instance.Configuration.LanguageOverride)) + // { + // this.localizationManager.SetupWithLangCode(Dalamud.Instance.Configuration.LanguageOverride); + // } + // else + // { + // this.localizationManager.SetupWithUiCulture(); + // } + // } + /// + /// Draw the window system. + /// private void OnDraw() { try diff --git a/Dalamud.CorePlugin/PluginWindow.cs b/Dalamud.CorePlugin/PluginWindow.cs index 71c5fb9d2..b42b9069b 100644 --- a/Dalamud.CorePlugin/PluginWindow.cs +++ b/Dalamud.CorePlugin/PluginWindow.cs @@ -8,21 +8,16 @@ using ImGuiNET; namespace Dalamud.CorePlugin { /// - /// Class responsible for drawing the plugin installer. + /// Class responsible for drawing the main plugin window. /// internal class PluginWindow : Window, IDisposable { - [SuppressMessage("CodeQuality", "IDE0052:Remove unread private members", Justification = "This is a placeholder.")] - private readonly Dalamud dalamud; - /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public PluginWindow(Dalamud dalamud) + public PluginWindow() : base("CorePlugin") { - this.dalamud = dalamud; this.IsOpen = true; this.Size = new Vector2(810, 520); diff --git a/Dalamud.Test/Game/Text/SeStringHandling/SeStringManagerTests.cs b/Dalamud.Test/Game/Text/SeStringHandling/SeStringManagerTests.cs index 95c1ec4d3..f9f7b05b8 100644 --- a/Dalamud.Test/Game/Text/SeStringHandling/SeStringManagerTests.cs +++ b/Dalamud.Test/Game/Text/SeStringHandling/SeStringManagerTests.cs @@ -9,7 +9,7 @@ namespace Dalamud.Test.Game.Text.SeStringHandling [Fact] public void TestNewLinePayload() { - var manager = new SeStringManager(null); + var manager = new SeStringManager(); var newLinePayloadBytes = new byte[] {0x02, 0x10, 0x01, 0x03}; var seString = manager.Parse(newLinePayloadBytes); diff --git a/Dalamud/Dalamud.cs b/Dalamud/Dalamud.cs index 6fc23b449..01e1a151d 100644 --- a/Dalamud/Dalamud.cs +++ b/Dalamud/Dalamud.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Threading; @@ -9,22 +8,25 @@ using Dalamud.Data; using Dalamud.Game; using Dalamud.Game.ClientState; using Dalamud.Game.Command; +using Dalamud.Game.Gui; using Dalamud.Game.Gui.Internal; using Dalamud.Game.Internal; +using Dalamud.Game.Network; using Dalamud.Game.Network.Internal; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Hooking.Internal; using Dalamud.Interface.Internal; -using Dalamud.Memory; +using Dalamud.IoC.Internal; using Dalamud.Plugin.Internal; using Serilog; using Serilog.Core; #if DEBUG -// This allows for rapid prototyping of Dalamud modules with access to internal objects. [assembly: InternalsVisibleTo("Dalamud.CorePlugin")] #endif +[assembly: InternalsVisibleTo("Dalamud.Test")] + namespace Dalamud { /// @@ -49,14 +51,11 @@ namespace Dalamud /// The Dalamud configuration. public Dalamud(DalamudStartInfo info, LoggingLevelSwitch loggingLevelSwitch, ManualResetEvent finishSignal, DalamudConfiguration configuration) { -#if DEBUG - Instance = this; -#endif - this.StartInfo = info; - this.LogLevelSwitch = loggingLevelSwitch; - this.Configuration = configuration; + Service.Set(this); + Service.Set(info); + Service.Set(configuration); - // this.baseDirectory = info.WorkingDirectory; + this.LogLevelSwitch = loggingLevelSwitch; this.unloadSignal = new ManualResetEvent(false); this.unloadSignal.Reset(); @@ -65,139 +64,11 @@ namespace Dalamud this.finishUnloadSignal.Reset(); } -#if DEBUG - /// - /// Gets the Dalamud singleton instance. - /// - internal static Dalamud Instance { get; private set; } -#endif - - #region Native Game Subsystems - - /// - /// Gets game framework subsystem. - /// - internal Framework Framework { get; private set; } - - /// - /// Gets Anti-Debug detection prevention subsystem. - /// - internal AntiDebug AntiDebug { get; private set; } - - /// - /// Gets WinSock optimization subsystem. - /// - internal WinSockHandlers WinSock2 { get; private set; } - - /// - /// Gets Hook management subsystem. - /// - internal HookManager HookManager { get; private set; } - - /// - /// Gets ImGui Interface subsystem. - /// - internal InterfaceManager InterfaceManager { get; private set; } - - /// - /// Gets the Input Method subsystem. - /// - internal DalamudIME IME { get; private set; } - - /// - /// Gets ClientState subsystem. - /// - internal ClientState ClientState { get; private set; } - - #endregion - - #region Dalamud Subsystems - - /// - /// Gets Plugin Manager subsystem. - /// - internal PluginManager PluginManager { get; private set; } - - /// - /// Gets Data provider subsystem. - /// - internal DataManager Data { get; private set; } - - /// - /// Gets Command Manager subsystem. - /// - internal CommandManager CommandManager { get; private set; } - - /// - /// Gets Localization subsystem facilitating localization for Dalamud and plugins. - /// - internal Localization LocalizationManager { get; private set; } - - #endregion - - #region Helpers - - /// - /// Gets SeStringManager subsystem facilitating string parsing. - /// - internal SeStringManager SeStringManager { get; private set; } - - /// - /// Gets copy-enabled SigScanner for target module. - /// - internal SigScanner SigScanner { get; private set; } - /// /// Gets LoggingLevelSwitch for Dalamud and Plugin logs. /// internal LoggingLevelSwitch LogLevelSwitch { get; private set; } - /// - /// Gets StartInfo object passed from injector. - /// - internal DalamudStartInfo StartInfo { get; private set; } - - /// - /// Gets Configuration object facilitating save and load of Dalamud configuration. - /// - internal DalamudConfiguration Configuration { get; private set; } - - #endregion - - #region Dalamud Core functionality - - /// - /// Gets Dalamud base UI. - /// - internal DalamudInterface DalamudUi { get; private set; } - - /// - /// Gets Dalamud chat commands. - /// - internal DalamudCommands DalamudCommands { get; private set; } - - /// - /// Gets Dalamud chat-based features. - /// - internal ChatHandlers ChatHandlers { get; private set; } - - /// - /// Gets Dalamud network-based features. - /// - internal NetworkHandlers NetworkHandlers { get; private set; } - - /// - /// Gets subsystem responsible for adding the Dalamud menu items to the game's system menu. - /// - internal DalamudSystemMenu SystemMenu { get; private set; } - - #endregion - - /// - /// Gets Injected process module. - /// - internal ProcessModule TargetModule { get; private set; } - /// /// Gets a value indicating whether Dalamud was successfully loaded. /// @@ -206,12 +77,12 @@ namespace Dalamud /// /// Gets a value indicating whether the plugin system is loaded. /// - internal bool IsLoadedPluginSystem => this.PluginManager != null; + internal bool IsLoadedPluginSystem => Service.GetNullable() != null; /// /// Gets location of stored assets. /// - internal DirectoryInfo AssetDirectory => new(this.StartInfo.AssetDirectory); + internal DirectoryInfo AssetDirectory => new(Service.Get().AssetDirectory); /// /// Runs tier 1 of the Dalamud initialization process. @@ -221,20 +92,23 @@ namespace Dalamud try { // Initialize the process information. - this.TargetModule = Process.GetCurrentProcess().MainModule; - this.SigScanner = new SigScanner(this.TargetModule, true); - this.HookManager = new HookManager(this); + Service.Set(new SigScanner(true)); + Service.Set(); + Service.Set(); // Initialize FFXIVClientStructs function resolver FFXIVClientStructs.Resolver.Initialize(); Log.Information("[T1] FFXIVClientStructs initialized!"); // Initialize game subsystem - this.Framework = new Framework(this.SigScanner, this); - + var framework = Service.Set(); Log.Information("[T1] Framework OK!"); - this.Framework.Enable(); + Service.Set(); + Service.Set(); + + framework.Enable(); + Log.Information("[T1] Framework ENABLE!"); } catch (Exception ex) @@ -251,33 +125,35 @@ namespace Dalamud { try { - this.AntiDebug = new AntiDebug(this.SigScanner); - if (this.Configuration.IsAntiAntiDebugEnabled) - this.AntiDebug.Enable(); -#if DEBUG - if (!this.AntiDebug.IsEnabled) - this.AntiDebug.Enable(); -#endif + var configuration = Service.Get(); + var antiDebug = Service.Set(); + if (configuration.IsAntiAntiDebugEnabled) + antiDebug.Enable(); +#if DEBUG + if (!antiDebug.IsEnabled) + antiDebug.Enable(); +#endif Log.Information("[T2] AntiDebug OK!"); - this.WinSock2 = new WinSockHandlers(); - + Service.Set(); Log.Information("[T2] WinSock OK!"); - this.NetworkHandlers = new NetworkHandlers(this, this.StartInfo.OptOutMbCollection); - + Service.Set(); Log.Information("[T2] NH OK!"); - this.ClientState = new ClientState(this, this.StartInfo, this.SigScanner); - + Service.Set(); Log.Information("[T2] CS OK!"); - this.LocalizationManager = new Localization(Path.Combine(this.AssetDirectory.FullName, "UIRes", "loc", "dalamud"), "dalamud_"); - if (!string.IsNullOrEmpty(this.Configuration.LanguageOverride)) - this.LocalizationManager.SetupWithLangCode(this.Configuration.LanguageOverride); + var localization = Service.Set(new Localization(Path.Combine(this.AssetDirectory.FullName, "UIRes", "loc", "dalamud"), "dalamud_")); + if (!string.IsNullOrEmpty(configuration.LanguageOverride)) + { + localization.SetupWithLangCode(configuration.LanguageOverride); + } else - this.LocalizationManager.SetupWithUiCulture(); + { + localization.SetupWithUiCulture(); + } Log.Information("[T2] LOC OK!"); @@ -285,9 +161,7 @@ namespace Dalamud { try { - this.InterfaceManager = new InterfaceManager(this, this.SigScanner); - - this.InterfaceManager.Enable(); + Service.Set().Enable(); Log.Information("[T2] IM OK!"); } @@ -299,7 +173,7 @@ namespace Dalamud try { - this.IME = new DalamudIME(this); + Service.Set(); Log.Information("[T2] IME OK!"); } catch (Exception e) @@ -307,10 +181,9 @@ namespace Dalamud Log.Information(e, "Could not init IME."); } - this.Data = new DataManager(this.StartInfo.Language, this.InterfaceManager); try { - this.Data.Initialize(this.AssetDirectory.FullName); + Service.Set().Initialize(this.AssetDirectory.FullName); } catch (Exception e) { @@ -321,27 +194,25 @@ namespace Dalamud Log.Information("[T2] Data OK!"); - this.SeStringManager = new SeStringManager(this.Data); - MemoryHelper.Initialize(this); // For SeString handling + Service.Set(); Log.Information("[T2] SeString OK!"); // Initialize managers. Basically handlers for the logic - this.CommandManager = new CommandManager(this, this.StartInfo.Language); - this.DalamudCommands = new DalamudCommands(this); - this.DalamudCommands.SetupCommands(); + Service.Set(); + + Service.Set().SetupCommands(); Log.Information("[T2] CM OK!"); - this.ChatHandlers = new ChatHandlers(this); + Service.Set(); Log.Information("[T2] CH OK!"); - this.ClientState.Enable(); + Service.Set().Enable(); Log.Information("[T2] CS ENABLE!"); - this.SystemMenu = new DalamudSystemMenu(this); - this.SystemMenu.Enable(); + Service.Set().Enable(); this.IsReady = true; } @@ -365,16 +236,16 @@ namespace Dalamud { try { - this.PluginManager = new PluginManager(this); - this.PluginManager.OnInstalledPluginsChanged += () => - Troubleshooting.LogTroubleshooting(this, this.InterfaceManager.IsReady); + var pluginManager = Service.Set(); + pluginManager.OnInstalledPluginsChanged += () => + Troubleshooting.LogTroubleshooting(); Log.Information("[T3] PM OK!"); - this.PluginManager.CleanupPlugins(); + pluginManager.CleanupPlugins(); Log.Information("[T3] PMC OK!"); - this.PluginManager.LoadAllPlugins(); + pluginManager.LoadAllPlugins(); Log.Information("[T3] PML OK!"); } catch (Exception ex) @@ -383,10 +254,10 @@ namespace Dalamud } } - this.DalamudUi = new DalamudInterface(this); + Service.Set(); Log.Information("[T3] DUI OK!"); - Troubleshooting.LogTroubleshooting(this, this.InterfaceManager.IsReady); + Troubleshooting.LogTroubleshooting(); Log.Information("Dalamud is ready."); } @@ -432,17 +303,17 @@ namespace Dalamud // this must be done before unloading interface manager, in order to do rebuild // the correct cascaded WndProc (IME -> RawDX11Scene -> Game). Otherwise the game // will not receive any windows messages - this.IME?.Dispose(); + Service.GetNullable()?.Dispose(); // this must be done before unloading plugins, or it can cause a race condition // due to rendering happening on another thread, where a plugin might receive // a render call after it has been disposed, which can crash if it attempts to // use any resources that it freed in its own Dispose method - this.InterfaceManager?.Dispose(); + Service.GetNullable()?.Dispose(); - this.DalamudUi?.Dispose(); + Service.GetNullable()?.Dispose(); - this.PluginManager?.Dispose(); + Service.GetNullable()?.Dispose(); } /// @@ -458,23 +329,17 @@ namespace Dalamud Thread.Sleep(100); } - this.Framework?.Dispose(); - - this.ClientState?.Dispose(); + Service.GetNullable()?.Dispose(); + Service.GetNullable()?.Dispose(); this.unloadSignal?.Dispose(); - this.WinSock2?.Dispose(); - - this.Data?.Dispose(); - - this.AntiDebug?.Dispose(); - - this.SystemMenu?.Dispose(); - - this.HookManager?.Dispose(); - - this.SigScanner?.Dispose(); + Service.GetNullable()?.Dispose(); + Service.GetNullable()?.Dispose(); + Service.GetNullable()?.Dispose(); + Service.GetNullable()?.Dispose(); + Service.GetNullable()?.Dispose(); + Service.GetNullable()?.Dispose(); Log.Debug("Dalamud::Dispose() OK!"); } @@ -489,7 +354,8 @@ namespace Dalamud /// internal void ReplaceExceptionHandler() { - var releaseFilter = this.SigScanner.ScanText("40 55 53 56 48 8D AC 24 ?? ?? ?? ?? B8 ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 2B E0 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 85 ?? ?? ?? ?? 48 83 3D ?? ?? ?? ?? ??"); + var releaseSig = "40 55 53 56 48 8D AC 24 ?? ?? ?? ?? B8 ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 2B E0 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 85 ?? ?? ?? ?? 48 83 3D ?? ?? ?? ?? ??"; + var releaseFilter = Service.Get().ScanText(releaseSig); Log.Debug($"SE debug filter at {releaseFilter.ToInt64():X}"); var oldFilter = NativeFunctions.SetUnhandledExceptionFilter(releaseFilter); diff --git a/Dalamud/Data/DataManager.cs b/Dalamud/Data/DataManager.cs index 093c8bb1a..e24fc6bdb 100644 --- a/Dalamud/Data/DataManager.cs +++ b/Dalamud/Data/DataManager.cs @@ -6,6 +6,8 @@ using System.IO; using System.Threading; using Dalamud.Interface.Internal; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Dalamud.Utility; using ImGuiScene; using JetBrains.Annotations; @@ -21,10 +23,11 @@ namespace Dalamud.Data /// /// This class provides data for Dalamud-internal features, but can also be used by plugins if needed. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class DataManager : IDisposable { private const string IconFileFormat = "ui/icon/{0:D3}000/{1}{2:D6}.tex"; - private readonly InterfaceManager interfaceManager; /// /// A object which gives access to any excel/game data. @@ -37,16 +40,12 @@ namespace Dalamud.Data /// /// Initializes a new instance of the class. /// - /// The language to load data with by default. - /// An instance to parse the data with. - internal DataManager(ClientLanguage language, InterfaceManager interfaceManager) + internal DataManager() { - this.interfaceManager = interfaceManager; + this.Language = Service.Get().Language; // Set up default values so plugins do not null-reference when data is being loaded. this.ClientOpCodes = this.ServerOpCodes = new ReadOnlyDictionary(new Dictionary()); - - this.Language = language; } /// @@ -212,7 +211,7 @@ namespace Dalamud.Data /// The Lumina . /// A that can be used to draw the texture. public TextureWrap GetImGuiTexture(TexFile tex) - => this.interfaceManager.LoadImageRaw(tex.GetRgbaImageData(), tex.Header.Width, tex.Header.Height, 4); + => Service.Get().LoadImageRaw(tex.GetRgbaImageData(), tex.Header.Width, tex.Header.Height, 4); /// /// Get the passed texture path as a drawable ImGui TextureWrap. diff --git a/Dalamud/EntryPoint.cs b/Dalamud/EntryPoint.cs index befc59c9b..78258c580 100644 --- a/Dalamud/EntryPoint.cs +++ b/Dalamud/EntryPoint.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics; using System.IO; -using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Threading; @@ -9,8 +8,6 @@ using System.Threading.Tasks; using Dalamud.Configuration.Internal; using Dalamud.Logging.Internal; -using Dalamud.Utility; -using HarmonyLib; using Newtonsoft.Json; using PInvoke; using Serilog; diff --git a/Dalamud/Game/BaseAddressResolver.cs b/Dalamud/Game/BaseAddressResolver.cs index b1873b0d7..4528b138e 100644 --- a/Dalamud/Game/BaseAddressResolver.cs +++ b/Dalamud/Game/BaseAddressResolver.cs @@ -20,6 +20,15 @@ namespace Dalamud.Game /// protected bool IsResolved { get; set; } + /// + /// Setup the resolver, calling the appopriate method based on the process architecture. + /// + public void Setup() + { + var scanner = Service.Get(); + this.Setup(scanner); + } + /// /// Setup the resolver, calling the appopriate method based on the process architecture. /// diff --git a/Dalamud/Game/ChatHandlers.cs b/Dalamud/Game/ChatHandlers.cs index 165633627..577652739 100644 --- a/Dalamud/Game/ChatHandlers.cs +++ b/Dalamud/Game/ChatHandlers.cs @@ -6,10 +6,16 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using CheapLoc; +using Dalamud.Configuration.Internal; +using Dalamud.Data; +using Dalamud.Game.Gui; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Interface.Internal; +using Dalamud.IoC; +using Dalamud.IoC.Internal; +using Dalamud.Plugin.Internal; using Serilog; namespace Dalamud.Game @@ -17,6 +23,8 @@ namespace Dalamud.Game /// /// Chat events and public helper functions. /// + [PluginInterface] + [InterfaceVersion("1.0")] public class ChatHandlers { // private static readonly Dictionary UnicodeToDiscordEmojiDict = new() @@ -93,31 +101,30 @@ namespace Dalamud.Game private readonly Regex urlRegex = new(@"(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?", RegexOptions.Compiled); - private readonly Dalamud dalamud; private readonly DalamudLinkPayload openInstallerWindowLink; + private bool hasSeenLoadingMsg; /// /// Initializes a new instance of the class. /// - /// Dalamud instance. - internal ChatHandlers(Dalamud dalamud) + internal ChatHandlers() { - this.dalamud = dalamud; + var chatGui = Service.Get(); - dalamud.Framework.Gui.Chat.CheckMessageHandled += this.OnCheckMessageHandled; - dalamud.Framework.Gui.Chat.ChatMessage += this.OnChatMessage; + chatGui.CheckMessageHandled += this.OnCheckMessageHandled; + chatGui.ChatMessage += this.OnChatMessage; - this.openInstallerWindowLink = this.dalamud.Framework.Gui.Chat.AddChatLinkHandler("Dalamud", 1001, (i, m) => + this.openInstallerWindowLink = chatGui.AddChatLinkHandler("Dalamud", 1001, (i, m) => { - this.dalamud.DalamudUi.OpenPluginInstaller(); + Service.Get().OpenPluginInstaller(); }); } /// /// Gets the last URL seen in chat. /// - public string LastLink { get; private set; } + public string? LastLink { get; private set; } /// /// Convert a TextPayload to SeString and wrap in italics payloads. @@ -137,6 +144,8 @@ namespace Dalamud.Game private void OnCheckMessageHandled(XivChatType type, uint senderid, ref SeString sender, ref SeString message, ref bool isHandled) { + var configuration = Service.Get(); + var textVal = message.TextValue; var matched = this.rmtRegex.IsMatch(textVal); @@ -148,8 +157,8 @@ namespace Dalamud.Game return; } - if (this.dalamud.Configuration.BadWords != null && - this.dalamud.Configuration.BadWords.Any(x => !string.IsNullOrEmpty(x) && textVal.Contains(x))) + if (configuration.BadWords != null && + configuration.BadWords.Any(x => !string.IsNullOrEmpty(x) && textVal.Contains(x))) { // This seems to be in the user block list - let's not show it Log.Debug("Blocklist triggered"); @@ -160,11 +169,14 @@ namespace Dalamud.Game private void OnChatMessage(XivChatType type, uint senderId, ref SeString sender, ref SeString message, ref bool isHandled) { + var startInfo = Service.Get(); + var clientState = Service.Get(); + if (type == XivChatType.Notice && !this.hasSeenLoadingMsg) this.PrintWelcomeMessage(); // For injections while logged in - if (this.dalamud.ClientState.LocalPlayer != null && this.dalamud.ClientState.TerritoryType == 0 && !this.hasSeenLoadingMsg) + if (clientState.LocalPlayer != null && clientState.TerritoryType == 0 && !this.hasSeenLoadingMsg) this.PrintWelcomeMessage(); #if !DEBUG && false @@ -174,7 +186,7 @@ namespace Dalamud.Game if (type == XivChatType.RetainerSale) { - foreach (var regex in this.retainerSaleRegexes[this.dalamud.StartInfo.Language]) + foreach (var regex in this.retainerSaleRegexes[startInfo.Language]) { var matchInfo = regex.Match(message.TextValue); @@ -235,35 +247,41 @@ namespace Dalamud.Game private void PrintWelcomeMessage() { + var chatGui = Service.Get(); + var configuration = Service.Get(); + var pluginManager = Service.Get(); + var dalamudInterface = Service.Get(); + var notifications = Service.Get(); + var assemblyVersion = Assembly.GetAssembly(typeof(ChatHandlers)).GetName().Version.ToString(); - this.dalamud.Framework.Gui.Chat.Print(string.Format(Loc.Localize("DalamudWelcome", "Dalamud vD{0} loaded."), assemblyVersion) - + string.Format(Loc.Localize("PluginsWelcome", " {0} plugin(s) loaded."), this.dalamud.PluginManager.InstalledPlugins.Count)); + chatGui.Print(string.Format(Loc.Localize("DalamudWelcome", "Dalamud vD{0} loaded."), assemblyVersion) + + string.Format(Loc.Localize("PluginsWelcome", " {0} plugin(s) loaded."), pluginManager.InstalledPlugins.Count)); - if (this.dalamud.Configuration.PrintPluginsWelcomeMsg) + if (configuration.PrintPluginsWelcomeMsg) { - foreach (var plugin in this.dalamud.PluginManager.InstalledPlugins.OrderBy(plugin => plugin.Name)) + foreach (var plugin in pluginManager.InstalledPlugins.OrderBy(plugin => plugin.Name)) { - this.dalamud.Framework.Gui.Chat.Print(string.Format(Loc.Localize("DalamudPluginLoaded", " 》 {0} v{1} loaded."), plugin.Name, plugin.Manifest.AssemblyVersion)); + chatGui.Print(string.Format(Loc.Localize("DalamudPluginLoaded", " 》 {0} v{1} loaded."), plugin.Name, plugin.Manifest.AssemblyVersion)); } } - if (string.IsNullOrEmpty(this.dalamud.Configuration.LastVersion) || !assemblyVersion.StartsWith(this.dalamud.Configuration.LastVersion)) + if (string.IsNullOrEmpty(configuration.LastVersion) || !assemblyVersion.StartsWith(configuration.LastVersion)) { - this.dalamud.Framework.Gui.Chat.PrintChat(new XivChatEntry + chatGui.PrintChat(new XivChatEntry { Message = Loc.Localize("DalamudUpdated", "The In-Game addon has been updated or was reinstalled successfully! Please check the discord for a full changelog."), Type = XivChatType.Notice, }); - if (this.dalamud.DalamudUi.WarrantsChangelog) - this.dalamud.DalamudUi.OpenChangelogWindow(); + if (dalamudInterface.WarrantsChangelog) + dalamudInterface.OpenChangelogWindow(); - this.dalamud.Configuration.LastVersion = assemblyVersion; - this.dalamud.Configuration.Save(); + configuration.LastVersion = assemblyVersion; + configuration.Save(); } - Task.Run(() => this.dalamud.PluginManager.UpdatePluginsAsync(!this.dalamud.Configuration.AutoUpdatePlugins)) + Task.Run(() => pluginManager.UpdatePluginsAsync(!configuration.AutoUpdatePlugins)) .ContinueWith(t => { if (t.IsFaulted) @@ -276,24 +294,26 @@ namespace Dalamud.Game if (updatedPlugins != null && updatedPlugins.Any()) { - if (this.dalamud.Configuration.AutoUpdatePlugins) + if (configuration.AutoUpdatePlugins) { - this.dalamud.PluginManager.PrintUpdatedPlugins(updatedPlugins, Loc.Localize("DalamudPluginAutoUpdate", "Auto-update:")); - this.dalamud.InterfaceManager.Notifications.AddNotification(Loc.Localize("NotificationUpdatedPlugins", "{0} of your plugins were updated."), Loc.Localize("NotificationAutoUpdate", "Auto-Update"), Notifications.Notification.Type.Info); + pluginManager.PrintUpdatedPlugins(updatedPlugins, Loc.Localize("DalamudPluginAutoUpdate", "Auto-update:")); + notifications.AddNotification(Loc.Localize("NotificationUpdatedPlugins", "{0} of your plugins were updated."), Loc.Localize("NotificationAutoUpdate", "Auto-Update"), Notifications.Notification.Type.Info); } else { - this.dalamud.Framework.Gui.Chat.PrintChat(new XivChatEntry + var data = Service.Get(); + + chatGui.PrintChat(new XivChatEntry { Message = new SeString(new List() { new TextPayload(Loc.Localize("DalamudPluginUpdateRequired", "One or more of your plugins needs to be updated. Please use the /xlplugins command in-game to update them!")), new TextPayload(" ["), - new UIForegroundPayload(this.dalamud.Data, 500), + new UIForegroundPayload(500), this.openInstallerWindowLink, new TextPayload(Loc.Localize("DalamudInstallerHelp", "Open the plugin installer")), RawPayload.LinkTerminator, - new UIForegroundPayload(this.dalamud.Data, 0), + new UIForegroundPayload(0), new TextPayload("]"), }), Type = XivChatType.Urgent, diff --git a/Dalamud/Game/ClientState/Buddy/BuddyList.cs b/Dalamud/Game/ClientState/Buddy/BuddyList.cs index 3080283a5..eda592d6b 100644 --- a/Dalamud/Game/ClientState/Buddy/BuddyList.cs +++ b/Dalamud/Game/ClientState/Buddy/BuddyList.cs @@ -3,6 +3,8 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using JetBrains.Annotations; using Serilog; @@ -12,21 +14,20 @@ namespace Dalamud.Game.ClientState.Buddy /// This collection represents the buddies present in your squadron or trust party. /// It does not include the local player. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed partial class BuddyList { private const uint InvalidObjectID = 0xE0000000; - private readonly Dalamud dalamud; private readonly ClientStateAddressResolver address; /// /// Initializes a new instance of the class. /// - /// The instance. /// Client state address resolver. - internal BuddyList(Dalamud dalamud, ClientStateAddressResolver addressResolver) + internal BuddyList(ClientStateAddressResolver addressResolver) { - this.dalamud = dalamud; this.address = addressResolver; Log.Verbose($"Buddy list address 0x{this.address.BuddyList.ToInt64():X}"); @@ -151,13 +152,15 @@ namespace Dalamud.Game.ClientState.Buddy [CanBeNull] public BuddyMember CreateBuddyMemberReference(IntPtr address) { - if (this.dalamud.ClientState.LocalContentId == 0) + var clientState = Service.Get(); + + if (clientState.LocalContentId == 0) return null; if (address == IntPtr.Zero) return null; - var buddy = new BuddyMember(address, this.dalamud); + var buddy = new BuddyMember(address); if (buddy.ObjectId == InvalidObjectID) return null; diff --git a/Dalamud/Game/ClientState/Buddy/BuddyMember.cs b/Dalamud/Game/ClientState/Buddy/BuddyMember.cs index 1cb40f39f..4c4fbc013 100644 --- a/Dalamud/Game/ClientState/Buddy/BuddyMember.cs +++ b/Dalamud/Game/ClientState/Buddy/BuddyMember.cs @@ -1,5 +1,6 @@ using System; +using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Game.ClientState.Resolvers; using JetBrains.Annotations; @@ -11,16 +12,12 @@ namespace Dalamud.Game.ClientState.Buddy /// public unsafe class BuddyMember { - private Dalamud dalamud; - /// /// Initializes a new instance of the class. /// /// Buddy address. - /// Dalamud instance. - internal BuddyMember(IntPtr address, Dalamud dalamud) + internal BuddyMember(IntPtr address) { - this.dalamud = dalamud; this.Address = address; } @@ -41,7 +38,7 @@ namespace Dalamud.Game.ClientState.Buddy /// This iterates the actor table, it should be used with care. /// [CanBeNull] - public GameObject Actor => this.dalamud.ClientState.Objects.SearchByID(this.ObjectId); + public GameObject GameObject => Service.Get().SearchByID(this.ObjectId); /// /// Gets the current health of this buddy. @@ -61,17 +58,17 @@ namespace Dalamud.Game.ClientState.Buddy /// /// Gets the Mount data related to this buddy. It should only be used with companion buddies. /// - public ExcelResolver MountData => new(this.DataID, this.dalamud); + public ExcelResolver MountData => new(this.DataID); /// /// Gets the Pet data related to this buddy. It should only be used with pet buddies. /// - public ExcelResolver PetData => new(this.DataID, this.dalamud); + public ExcelResolver PetData => new(this.DataID); /// /// Gets the Trust data related to this buddy. It should only be used with battle buddies. /// - public ExcelResolver TrustData => new(this.DataID, this.dalamud); + public ExcelResolver TrustData => new(this.DataID); private FFXIVClientStructs.FFXIV.Client.Game.UI.Buddy.BuddyMember* Struct => (FFXIVClientStructs.FFXIV.Client.Game.UI.Buddy.BuddyMember*)this.Address; } diff --git a/Dalamud/Game/ClientState/ClientState.cs b/Dalamud/Game/ClientState/ClientState.cs index 43bff6a92..5ed9443ab 100644 --- a/Dalamud/Game/ClientState/ClientState.cs +++ b/Dalamud/Game/ClientState/ClientState.cs @@ -10,7 +10,10 @@ using Dalamud.Game.ClientState.Keys; using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.SubKinds; using Dalamud.Game.ClientState.Party; +using Dalamud.Game.Network.Internal; using Dalamud.Hooking; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using JetBrains.Annotations; using Serilog; @@ -19,9 +22,10 @@ namespace Dalamud.Game.ClientState /// /// This class represents the state of the game client at the time of access. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class ClientState : IDisposable { - private readonly Dalamud dalamud; private readonly ClientStateAddressResolver address; private readonly Hook setupTerritoryTypeHook; @@ -31,43 +35,42 @@ namespace Dalamud.Game.ClientState /// Initializes a new instance of the class. /// Set up client state access. /// - /// Dalamud instance. - /// StartInfo of the current Dalamud launch. - /// Sig scanner. - internal ClientState(Dalamud dalamud, DalamudStartInfo startInfo, SigScanner scanner) + internal ClientState() { - this.dalamud = dalamud; this.address = new ClientStateAddressResolver(); - this.address.Setup(scanner); + this.address.Setup(); Log.Verbose("===== C L I E N T S T A T E ====="); - this.ClientLanguage = startInfo.Language; + this.ClientLanguage = Service.Get().Language; - this.Objects = new ObjectTable(dalamud, this.address); + Service.Set(this.address); - this.Fates = new FateTable(dalamud, this.address); + Service.Set(this.address); - this.PartyList = new PartyList(dalamud, this.address); + Service.Set(this.address); - this.BuddyList = new BuddyList(dalamud, this.address); + Service.Set(this.address); - this.JobGauges = new JobGauges(this.address); + Service.Set(this.address); - this.KeyState = new KeyState(this.address, scanner.Module.BaseAddress); + Service.Set(this.address); - this.GamepadState = new GamepadState(this.address); + Service.Set(this.address); - this.Condition = new Condition(this.address); + Service.Set(this.address); - this.Targets = new Targets(dalamud, this.address); + Service.Set(this.address); Log.Verbose($"SetupTerritoryType address 0x{this.address.SetupTerritoryType.ToInt64():X}"); this.setupTerritoryTypeHook = new Hook(this.address.SetupTerritoryType, this.SetupTerritoryTypeDetour); - dalamud.Framework.OnUpdateEvent += this.FrameworkOnOnUpdateEvent; - dalamud.NetworkHandlers.CfPop += this.NetworkHandlersOnCfPop; + var framework = Service.Get(); + framework.OnUpdateEvent += this.FrameworkOnOnUpdateEvent; + + var networkHandlers = Service.Get(); + networkHandlers.CfPop += this.NetworkHandlersOnCfPop; } [UnmanagedFunctionPointer(CallingConvention.ThisCall)] @@ -93,56 +96,11 @@ namespace Dalamud.Game.ClientState /// public event EventHandler CfPop; - /// - /// Gets the table of all present actors. - /// - public ObjectTable Objects { get; } - - /// - /// Gets the table of all present fates. - /// - public FateTable Fates { get; } - /// /// Gets the language of the client. /// public ClientLanguage ClientLanguage { get; } - /// - /// Gets the class facilitating Job Gauge data access. - /// - public JobGauges JobGauges { get; } - - /// - /// Gets the class facilitating party list data access. - /// - public PartyList PartyList { get; } - - /// - /// Gets the class facilitating buddy list data access. - /// - public BuddyList BuddyList { get; } - - /// - /// Gets access to the keypress state of keyboard keys in game. - /// - public KeyState KeyState { get; } - - /// - /// Gets access to the button state of gamepad buttons in game. - /// - public GamepadState GamepadState { get; } - - /// - /// Gets access to client conditions/player state. Allows you to check if a player is in a duty, mounted, etc. - /// - public Condition Condition { get; } - - /// - /// Gets the class facilitating target data access. - /// - public Targets Targets { get; } - /// /// Gets the current Territory the player resides in. /// @@ -152,7 +110,7 @@ namespace Dalamud.Game.ClientState /// Gets the local player character, if one is present. /// [CanBeNull] - public PlayerCharacter LocalPlayer => this.Objects[0] as PlayerCharacter; + public PlayerCharacter LocalPlayer => Service.Get()[0] as PlayerCharacter; /// /// Gets the content ID of the local character. @@ -169,7 +127,7 @@ namespace Dalamud.Game.ClientState /// public void Enable() { - this.GamepadState.Enable(); + Service.Get().Enable(); this.setupTerritoryTypeHook.Enable(); } @@ -179,10 +137,9 @@ namespace Dalamud.Game.ClientState public void Dispose() { this.setupTerritoryTypeHook.Dispose(); - this.GamepadState.Dispose(); - - this.dalamud.Framework.OnUpdateEvent -= this.FrameworkOnOnUpdateEvent; - this.dalamud.NetworkHandlers.CfPop += this.NetworkHandlersOnCfPop; + Service.Get().Dispose(); + Service.Get().OnUpdateEvent -= this.FrameworkOnOnUpdateEvent; + Service.Get().CfPop -= this.NetworkHandlersOnCfPop; } private IntPtr SetupTerritoryTypeDetour(IntPtr manager, ushort terriType) @@ -202,7 +159,8 @@ namespace Dalamud.Game.ClientState private void FrameworkOnOnUpdateEvent(Framework framework) { - if (this.Condition.Any() && this.lastConditionNone == true) + var condition = Service.Get(); + if (condition.Any() && this.lastConditionNone == true) { Log.Debug("Is login"); this.lastConditionNone = false; @@ -210,7 +168,7 @@ namespace Dalamud.Game.ClientState this.Login?.Invoke(this, null); } - if (!this.Condition.Any() && this.lastConditionNone == false) + if (!condition.Any() && this.lastConditionNone == false) { Log.Debug("Is logout"); this.lastConditionNone = true; diff --git a/Dalamud/Game/ClientState/Fates/Fate.cs b/Dalamud/Game/ClientState/Fates/Fate.cs index 2b284b6a5..3d18bef38 100644 --- a/Dalamud/Game/ClientState/Fates/Fate.cs +++ b/Dalamud/Game/ClientState/Fates/Fate.cs @@ -1,6 +1,7 @@ using System; using System.Numerics; +using Dalamud.Data; using Dalamud.Game.ClientState.Resolvers; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Memory; @@ -12,17 +13,13 @@ namespace Dalamud.Game.ClientState.Fates /// public unsafe partial class Fate : IEquatable { - private Dalamud dalamud; - /// /// Initializes a new instance of the class. /// /// The address of this fate in memory. - /// Dalamud instance. - internal Fate(IntPtr address, Dalamud dalamud) + internal Fate(IntPtr address) { this.Address = address; - this.dalamud = dalamud; } /// @@ -49,10 +46,12 @@ namespace Dalamud.Game.ClientState.Fates /// True or false. public static bool IsValid(Fate fate) { + var clientState = Service.Get(); + if (fate == null) return false; - if (fate.dalamud.ClientState.LocalContentId == 0) + if (clientState.LocalContentId == 0) return false; return true; @@ -87,7 +86,7 @@ namespace Dalamud.Game.ClientState.Fates /// /// Gets game data linked to this Fate. /// - public Lumina.Excel.GeneratedSheets.Fate GameData => this.dalamud.Data.GetExcelSheet().GetRow(this.FateId); + public Lumina.Excel.GeneratedSheets.Fate GameData => Service.Get().GetExcelSheet().GetRow(this.FateId); /// /// Gets the time this started. @@ -132,6 +131,6 @@ namespace Dalamud.Game.ClientState.Fates /// /// Gets the territory this is located in. /// - public ExcelResolver TerritoryType => new(this.Struct->TerritoryID, this.dalamud); + public ExcelResolver TerritoryType => new(this.Struct->TerritoryID); } } diff --git a/Dalamud/Game/ClientState/Fates/FateTable.cs b/Dalamud/Game/ClientState/Fates/FateTable.cs index cd6e58ada..d57d3f4bd 100644 --- a/Dalamud/Game/ClientState/Fates/FateTable.cs +++ b/Dalamud/Game/ClientState/Fates/FateTable.cs @@ -2,6 +2,8 @@ using System; using System.Collections; using System.Collections.Generic; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using JetBrains.Annotations; using Serilog; @@ -10,20 +12,19 @@ namespace Dalamud.Game.ClientState.Fates /// /// This collection represents the currently available Fate events. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed partial class FateTable { - private readonly Dalamud dalamud; private readonly ClientStateAddressResolver address; /// /// Initializes a new instance of the class. /// - /// The instance. /// Client state address resolver. - internal FateTable(Dalamud dalamud, ClientStateAddressResolver addressResolver) + internal FateTable(ClientStateAddressResolver addressResolver) { this.address = addressResolver; - this.dalamud = dalamud; Log.Verbose($"Fate table address 0x{this.address.FateTablePtr.ToInt64():X}"); } @@ -110,13 +111,15 @@ namespace Dalamud.Game.ClientState.Fates [CanBeNull] internal unsafe Fate CreateFateReference(IntPtr offset) { - if (this.dalamud.ClientState.LocalContentId == 0) + var clientState = Service.Get(); + + if (clientState.LocalContentId == 0) return null; if (offset == IntPtr.Zero) return null; - return new Fate(offset, this.dalamud); + return new Fate(offset); } } diff --git a/Dalamud/Game/ClientState/Keys/KeyState.cs b/Dalamud/Game/ClientState/Keys/KeyState.cs index b9d21ef2e..974f4b01f 100644 --- a/Dalamud/Game/ClientState/Keys/KeyState.cs +++ b/Dalamud/Game/ClientState/Keys/KeyState.cs @@ -1,6 +1,8 @@ using System; using System.Runtime.InteropServices; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Serilog; namespace Dalamud.Game.ClientState.Keys @@ -8,6 +10,8 @@ namespace Dalamud.Game.ClientState.Keys /// /// Wrapper around the game keystate buffer, which contains the pressed state for all keyboard keys, indexed by virtual vkCode. /// + [PluginInterface] + [InterfaceVersion("1.0")] public class KeyState { // The array is accessed in a way that this limit doesn't appear to exist @@ -20,9 +24,10 @@ namespace Dalamud.Game.ClientState.Keys /// Initializes a new instance of the class. /// /// The ClientStateAddressResolver instance. - /// The base address of the main process module. - public KeyState(ClientStateAddressResolver addressResolver, IntPtr moduleBaseAddress) + public KeyState(ClientStateAddressResolver addressResolver) { + var moduleBaseAddress = Service.Get().Module.BaseAddress; + this.bufferBase = moduleBaseAddress + Marshal.ReadInt32(addressResolver.KeyboardState); Log.Verbose($"Keyboard state buffer address 0x{this.bufferBase.ToInt64():X}"); diff --git a/Dalamud/Game/ClientState/Objects/ObjectTable.cs b/Dalamud/Game/ClientState/Objects/ObjectTable.cs index 7e11d8e6f..d2c0e6eaa 100644 --- a/Dalamud/Game/ClientState/Objects/ObjectTable.cs +++ b/Dalamud/Game/ClientState/Objects/ObjectTable.cs @@ -5,6 +5,8 @@ using System.Collections.Generic; using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Game.ClientState.Objects.SubKinds; using Dalamud.Game.ClientState.Objects.Types; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using JetBrains.Annotations; using Serilog; @@ -13,21 +15,20 @@ namespace Dalamud.Game.ClientState.Objects /// /// This collection represents the currently spawned FFXIV game objects. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed partial class ObjectTable { private const int ObjectTableLength = 424; - private readonly Dalamud dalamud; private readonly ClientStateAddressResolver address; /// /// Initializes a new instance of the class. /// - /// The instance. /// Client state address resolver. - internal ObjectTable(Dalamud dalamud, ClientStateAddressResolver addressResolver) + internal ObjectTable(ClientStateAddressResolver addressResolver) { - this.dalamud = dalamud; this.address = addressResolver; Log.Verbose($"Object table address 0x{this.address.ObjectTable.ToInt64():X}"); @@ -99,7 +100,9 @@ namespace Dalamud.Game.ClientState.Objects [CanBeNull] public unsafe GameObject CreateObjectReference(IntPtr address) { - if (this.dalamud.ClientState.LocalContentId == 0) + var clientState = Service.Get(); + + if (clientState.LocalContentId == 0) return null; if (address == IntPtr.Zero) @@ -109,11 +112,11 @@ namespace Dalamud.Game.ClientState.Objects var objKind = (ObjectKind)obj->ObjectKind; return objKind switch { - ObjectKind.Player => new PlayerCharacter(address, this.dalamud), - ObjectKind.BattleNpc => new BattleNpc(address, this.dalamud), - ObjectKind.EventObj => new EventObj(address, this.dalamud), - ObjectKind.Companion => new Npc(address, this.dalamud), - _ => new GameObject(address, this.dalamud), + ObjectKind.Player => new PlayerCharacter(address), + ObjectKind.BattleNpc => new BattleNpc(address), + ObjectKind.EventObj => new EventObj(address), + ObjectKind.Companion => new Npc(address), + _ => new GameObject(address), }; } } diff --git a/Dalamud/Game/ClientState/Objects/SubKinds/BattleNpc.cs b/Dalamud/Game/ClientState/Objects/SubKinds/BattleNpc.cs index ea5fc64fa..4e445beff 100644 --- a/Dalamud/Game/ClientState/Objects/SubKinds/BattleNpc.cs +++ b/Dalamud/Game/ClientState/Objects/SubKinds/BattleNpc.cs @@ -14,9 +14,8 @@ namespace Dalamud.Game.ClientState.Objects.Types /// Set up a new BattleNpc with the provided memory representation. /// /// The address of this actor in memory. - /// A dalamud reference needed to access game data in Resolvers. - internal BattleNpc(IntPtr address, Dalamud dalamud) - : base(address, dalamud) + internal BattleNpc(IntPtr address) + : base(address) { } diff --git a/Dalamud/Game/ClientState/Objects/SubKinds/EventObj.cs b/Dalamud/Game/ClientState/Objects/SubKinds/EventObj.cs index 55e0b3f97..61710f32b 100644 --- a/Dalamud/Game/ClientState/Objects/SubKinds/EventObj.cs +++ b/Dalamud/Game/ClientState/Objects/SubKinds/EventObj.cs @@ -14,9 +14,8 @@ namespace Dalamud.Game.ClientState.Objects.SubKinds /// Set up a new EventObj with the provided memory representation. /// /// The address of this event object in memory. - /// A dalamud reference. - internal EventObj(IntPtr address, Dalamud dalamud) - : base(address, dalamud) + internal EventObj(IntPtr address) + : base(address) { } } diff --git a/Dalamud/Game/ClientState/Objects/SubKinds/Npc.cs b/Dalamud/Game/ClientState/Objects/SubKinds/Npc.cs index cf582a11f..2ff6ab173 100644 --- a/Dalamud/Game/ClientState/Objects/SubKinds/Npc.cs +++ b/Dalamud/Game/ClientState/Objects/SubKinds/Npc.cs @@ -14,9 +14,8 @@ namespace Dalamud.Game.ClientState.Objects.SubKinds /// Set up a new NPC with the provided memory representation. /// /// The address of this actor in memory. - /// A dalamud reference needed to access game data in Resolvers. - internal Npc(IntPtr address, Dalamud dalamud) - : base(address, dalamud) + internal Npc(IntPtr address) + : base(address) { } diff --git a/Dalamud/Game/ClientState/Objects/SubKinds/PlayerCharacter.cs b/Dalamud/Game/ClientState/Objects/SubKinds/PlayerCharacter.cs index 9b33e6ce5..a7dd836d6 100644 --- a/Dalamud/Game/ClientState/Objects/SubKinds/PlayerCharacter.cs +++ b/Dalamud/Game/ClientState/Objects/SubKinds/PlayerCharacter.cs @@ -15,21 +15,20 @@ namespace Dalamud.Game.ClientState.Objects.SubKinds /// This represents a player character. /// /// The address of this actor in memory. - /// A dalamud reference needed to access game data in Resolvers. - internal PlayerCharacter(IntPtr address, Dalamud dalamud) - : base(address, dalamud) + internal PlayerCharacter(IntPtr address) + : base(address) { } /// /// Gets the current world of the character. /// - public ExcelResolver CurrentWorld => new(this.Struct->Character.CurrentWorld, this.Dalamud); + public ExcelResolver CurrentWorld => new(this.Struct->Character.CurrentWorld); /// /// Gets the home world of the character. /// - public ExcelResolver HomeWorld => new(this.Struct->Character.HomeWorld, this.Dalamud); + public ExcelResolver HomeWorld => new(this.Struct->Character.HomeWorld); /// /// Gets the target actor ID of the PlayerCharacter. diff --git a/Dalamud/Game/ClientState/Objects/Targets.cs b/Dalamud/Game/ClientState/Objects/TargetManager.cs similarity index 86% rename from Dalamud/Game/ClientState/Objects/Targets.cs rename to Dalamud/Game/ClientState/Objects/TargetManager.cs index 1c9527221..7d7f08121 100644 --- a/Dalamud/Game/ClientState/Objects/Targets.cs +++ b/Dalamud/Game/ClientState/Objects/TargetManager.cs @@ -1,6 +1,8 @@ using System; using Dalamud.Game.ClientState.Objects.Types; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using JetBrains.Annotations; namespace Dalamud.Game.ClientState.Objects @@ -8,19 +10,18 @@ namespace Dalamud.Game.ClientState.Objects /// /// Get and set various kinds of targets for the player. /// - public sealed unsafe class Targets + [PluginInterface] + [InterfaceVersion("1.0")] + public sealed unsafe class TargetManager { - private readonly Dalamud dalamud; private readonly ClientStateAddressResolver address; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - /// The Dalamud instance. /// The ClientStateAddressResolver instance. - internal Targets(Dalamud dalamud, ClientStateAddressResolver addressResolver) + internal TargetManager(ClientStateAddressResolver addressResolver) { - this.dalamud = dalamud; this.address = addressResolver; } @@ -35,7 +36,7 @@ namespace Dalamud.Game.ClientState.Objects [CanBeNull] public GameObject Target { - get => this.dalamud.ClientState.Objects.CreateObjectReference((IntPtr)Struct->Target); + get => Service.Get().CreateObjectReference((IntPtr)Struct->Target); set => this.SetTarget(value); } @@ -45,7 +46,7 @@ namespace Dalamud.Game.ClientState.Objects [CanBeNull] public GameObject MouseOverTarget { - get => this.dalamud.ClientState.Objects.CreateObjectReference((IntPtr)Struct->MouseOverTarget); + get => Service.Get().CreateObjectReference((IntPtr)Struct->MouseOverTarget); set => this.SetMouseOverTarget(value); } @@ -55,7 +56,7 @@ namespace Dalamud.Game.ClientState.Objects [CanBeNull] public GameObject FocusTarget { - get => this.dalamud.ClientState.Objects.CreateObjectReference((IntPtr)Struct->FocusTarget); + get => Service.Get().CreateObjectReference((IntPtr)Struct->FocusTarget); set => this.SetFocusTarget(value); } @@ -65,7 +66,7 @@ namespace Dalamud.Game.ClientState.Objects [CanBeNull] public GameObject PreviousTarget { - get => this.dalamud.ClientState.Objects.CreateObjectReference((IntPtr)Struct->PreviousTarget); + get => Service.Get().CreateObjectReference((IntPtr)Struct->PreviousTarget); set => this.SetPreviousTarget(value); } @@ -75,7 +76,7 @@ namespace Dalamud.Game.ClientState.Objects [CanBeNull] public GameObject SoftTarget { - get => this.dalamud.ClientState.Objects.CreateObjectReference((IntPtr)Struct->SoftTarget); + get => Service.Get().CreateObjectReference((IntPtr)Struct->SoftTarget); set => this.SetSoftTarget(value); } diff --git a/Dalamud/Game/ClientState/Objects/Types/BattleChara.cs b/Dalamud/Game/ClientState/Objects/Types/BattleChara.cs index 5a553b215..633b5eb38 100644 --- a/Dalamud/Game/ClientState/Objects/Types/BattleChara.cs +++ b/Dalamud/Game/ClientState/Objects/Types/BattleChara.cs @@ -14,16 +14,15 @@ namespace Dalamud.Game.ClientState.Objects.Types /// This represents a battle character. /// /// The address of this character in memory. - /// Dalamud itself. - internal BattleChara(IntPtr address, Dalamud dalamud) - : base(address, dalamud) + internal BattleChara(IntPtr address) + : base(address) { } /// /// Gets the current status effects. /// - public StatusList StatusList => new(&this.Struct->StatusManager, this.Dalamud); + public StatusList StatusList => new(&this.Struct->StatusManager); /// /// Gets a value indicating whether the chara is currently casting. diff --git a/Dalamud/Game/ClientState/Objects/Types/Character.cs b/Dalamud/Game/ClientState/Objects/Types/Character.cs index 2ebcbd1c5..97a0a53d5 100644 --- a/Dalamud/Game/ClientState/Objects/Types/Character.cs +++ b/Dalamud/Game/ClientState/Objects/Types/Character.cs @@ -4,7 +4,6 @@ using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Game.ClientState.Resolvers; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Memory; -using JetBrains.Annotations; namespace Dalamud.Game.ClientState.Objects.Types { @@ -18,9 +17,8 @@ namespace Dalamud.Game.ClientState.Objects.Types /// This represents a non-static entity. /// /// The address of this character in memory. - /// Dalamud itself. - internal Character(IntPtr address, Dalamud dalamud) - : base(address, dalamud) + internal Character(IntPtr address) + : base(address) { } @@ -67,7 +65,7 @@ namespace Dalamud.Game.ClientState.Objects.Types /// /// Gets the ClassJob of this Chara. /// - public ExcelResolver ClassJob => new(this.Struct->ClassJob, this.Dalamud); + public ExcelResolver ClassJob => new(this.Struct->ClassJob); /// /// Gets the level of this Chara. diff --git a/Dalamud/Game/ClientState/Objects/Types/GameObject.cs b/Dalamud/Game/ClientState/Objects/Types/GameObject.cs index 68e41ef3f..138dc43e2 100644 --- a/Dalamud/Game/ClientState/Objects/Types/GameObject.cs +++ b/Dalamud/Game/ClientState/Objects/Types/GameObject.cs @@ -17,11 +17,9 @@ namespace Dalamud.Game.ClientState.Objects.Types /// Initializes a new instance of the class. /// /// The address of this game object in memory. - /// Dalamud itself. - internal GameObject(IntPtr address, Dalamud dalamud) + internal GameObject(IntPtr address) { this.Address = address; - this.Dalamud = dalamud; } /// @@ -59,10 +57,12 @@ namespace Dalamud.Game.ClientState.Objects.Types /// True or false. public static bool IsValid(GameObject? actor) { + var clientState = Service.Get(); + if (actor is null) return false; - if (actor.Dalamud.ClientState.LocalContentId == 0) + if (clientState.LocalContentId == 0) return false; return true; @@ -158,7 +158,7 @@ namespace Dalamud.Game.ClientState.Objects.Types /// This iterates the actor table, it should be used with care. /// [CanBeNull] - public virtual GameObject TargetObject => this.Dalamud.ClientState.Objects.SearchByID(this.TargetObjectId); + public virtual GameObject TargetObject => Service.Get().SearchByID(this.TargetObjectId); /// /// Gets the underlying structure. diff --git a/Dalamud/Game/ClientState/Party/PartyList.cs b/Dalamud/Game/ClientState/Party/PartyList.cs index 8de1ad1ea..60432c710 100644 --- a/Dalamud/Game/ClientState/Party/PartyList.cs +++ b/Dalamud/Game/ClientState/Party/PartyList.cs @@ -3,6 +3,8 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using JetBrains.Annotations; using Serilog; @@ -11,22 +13,21 @@ namespace Dalamud.Game.ClientState.Party /// /// This collection represents the actors present in your party or alliance. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed unsafe partial class PartyList { private const int GroupLength = 8; private const int AllianceLength = 20; - private readonly Dalamud dalamud; private readonly ClientStateAddressResolver address; /// /// Initializes a new instance of the class. /// - /// The instance. /// Client state address resolver. - internal PartyList(Dalamud dalamud, ClientStateAddressResolver addressResolver) + internal PartyList(ClientStateAddressResolver addressResolver) { - this.dalamud = dalamud; this.address = addressResolver; Log.Verbose($"Group manager address 0x{this.address.GroupManager.ToInt64():X}"); @@ -114,13 +115,15 @@ namespace Dalamud.Game.ClientState.Party [CanBeNull] public PartyMember CreatePartyMemberReference(IntPtr address) { - if (this.dalamud.ClientState.LocalContentId == 0) + var clientState = Service.Get(); + + if (clientState.LocalContentId == 0) return null; if (address == IntPtr.Zero) return null; - return new PartyMember(address, this.dalamud); + return new PartyMember(address); } /// @@ -144,13 +147,15 @@ namespace Dalamud.Game.ClientState.Party [CanBeNull] public PartyMember CreateAllianceMemberReference(IntPtr address) { - if (this.dalamud.ClientState.LocalContentId == 0) + var clientState = Service.Get(); + + if (clientState.LocalContentId == 0) return null; if (address == IntPtr.Zero) return null; - return new PartyMember(address, this.dalamud); + return new PartyMember(address); } } diff --git a/Dalamud/Game/ClientState/Party/PartyMember.cs b/Dalamud/Game/ClientState/Party/PartyMember.cs index 8cbd2dd84..8a74977cf 100644 --- a/Dalamud/Game/ClientState/Party/PartyMember.cs +++ b/Dalamud/Game/ClientState/Party/PartyMember.cs @@ -1,6 +1,7 @@ using System; using System.Numerics; +using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Game.ClientState.Resolvers; using Dalamud.Game.ClientState.Statuses; @@ -15,17 +16,13 @@ namespace Dalamud.Game.ClientState.Party /// public unsafe class PartyMember { - private Dalamud dalamud; - /// /// Initializes a new instance of the class. /// /// Address of the party member. - /// Dalamud itself. - internal PartyMember(IntPtr address, Dalamud dalamud) + internal PartyMember(IntPtr address) { this.Address = address; - this.dalamud = dalamud; } /// @@ -36,7 +33,7 @@ namespace Dalamud.Game.ClientState.Party /// /// Gets a list of buffs or debuffs applied to this party member. /// - public StatusList Statuses => new(&this.Struct->StatusManager, this.dalamud); + public StatusList Statuses => new(&this.Struct->StatusManager); /// /// Gets the position of the party member. @@ -60,7 +57,7 @@ namespace Dalamud.Game.ClientState.Party /// This iterates the actor table, it should be used with care. /// [CanBeNull] - public GameObject GameObject => this.dalamud.ClientState.Objects.SearchByID(this.ObjectId); + public GameObject GameObject => Service.Get().SearchByID(this.ObjectId); /// /// Gets the current HP of this party member. @@ -85,12 +82,12 @@ namespace Dalamud.Game.ClientState.Party /// /// Gets the territory this party member is located in. /// - public ExcelResolver Territory => new(this.Struct->TerritoryType, this.dalamud); + public ExcelResolver Territory => new(this.Struct->TerritoryType); /// /// Gets the World this party member resides in. /// - public ExcelResolver World => new(this.Struct->HomeWorld, this.dalamud); + public ExcelResolver World => new(this.Struct->HomeWorld); /// /// Gets the displayname of this party member. @@ -105,7 +102,7 @@ namespace Dalamud.Game.ClientState.Party /// /// Gets the classjob of this party member. /// - public ExcelResolver ClassJob => new(this.Struct->ClassJob, this.dalamud); + public ExcelResolver ClassJob => new(this.Struct->ClassJob); /// /// Gets the level of this party member. diff --git a/Dalamud/Game/ClientState/Resolvers/ExcelResolver{T}.cs b/Dalamud/Game/ClientState/Resolvers/ExcelResolver{T}.cs index 920f7b69e..5a5af1080 100644 --- a/Dalamud/Game/ClientState/Resolvers/ExcelResolver{T}.cs +++ b/Dalamud/Game/ClientState/Resolvers/ExcelResolver{T}.cs @@ -1,3 +1,4 @@ +using Dalamud.Data; using Lumina.Excel; namespace Dalamud.Game.ClientState.Resolvers @@ -8,16 +9,12 @@ namespace Dalamud.Game.ClientState.Resolvers /// The type of Lumina sheet to resolve. public class ExcelResolver where T : ExcelRow { - private readonly Dalamud dalamud; - /// /// Initializes a new instance of the class. /// /// The ID of the classJob. - /// The Dalamud instance. - internal ExcelResolver(uint id, Dalamud dalamud) + internal ExcelResolver(uint id) { - this.dalamud = dalamud; this.Id = id; } @@ -29,6 +26,6 @@ namespace Dalamud.Game.ClientState.Resolvers /// /// Gets GameData linked to this excel row. /// - public T GameData => this.dalamud.Data.GetExcelSheet().GetRow(this.Id); + public T GameData => Service.Get().GetExcelSheet().GetRow(this.Id); } } diff --git a/Dalamud/Game/ClientState/Statuses/Status.cs b/Dalamud/Game/ClientState/Statuses/Status.cs index 9570c79a9..9d159e25c 100644 --- a/Dalamud/Game/ClientState/Statuses/Status.cs +++ b/Dalamud/Game/ClientState/Statuses/Status.cs @@ -1,5 +1,6 @@ using System; +using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Game.ClientState.Resolvers; using JetBrains.Annotations; @@ -11,16 +12,12 @@ namespace Dalamud.Game.ClientState.Statuses /// public unsafe class Status { - private Dalamud dalamud; - /// /// Initializes a new instance of the class. /// /// Status address. - /// Dalamud instance. - internal Status(IntPtr address, Dalamud dalamud) + internal Status(IntPtr address) { - this.dalamud = dalamud; this.Address = address; } @@ -37,7 +34,7 @@ namespace Dalamud.Game.ClientState.Statuses /// /// Gets the GameData associated with this status. /// - public Lumina.Excel.GeneratedSheets.Status GameData => new ExcelResolver(this.Struct->StatusID, this.dalamud).GameData; + public Lumina.Excel.GeneratedSheets.Status GameData => new ExcelResolver(this.Struct->StatusID).GameData; /// /// Gets the parameter value of the status. @@ -66,7 +63,7 @@ namespace Dalamud.Game.ClientState.Statuses /// This iterates the actor table, it should be used with care. /// [CanBeNull] - public GameObject SourceActor => this.dalamud.ClientState.Objects.SearchByID(this.SourceID); + public GameObject SourceObject => Service.Get().SearchByID(this.SourceID); private FFXIVClientStructs.FFXIV.Client.Game.Status* Struct => (FFXIVClientStructs.FFXIV.Client.Game.Status*)this.Address; } diff --git a/Dalamud/Game/ClientState/Statuses/StatusList.cs b/Dalamud/Game/ClientState/Statuses/StatusList.cs index a617d900d..800d6077b 100644 --- a/Dalamud/Game/ClientState/Statuses/StatusList.cs +++ b/Dalamud/Game/ClientState/Statuses/StatusList.cs @@ -14,26 +14,21 @@ namespace Dalamud.Game.ClientState.Statuses { private const int StatusListLength = 30; - private readonly Dalamud dalamud; - /// /// Initializes a new instance of the class. /// /// Address of the status list. - /// The instance. - internal StatusList(IntPtr address, Dalamud dalamud) + internal StatusList(IntPtr address) { this.Address = address; - this.dalamud = dalamud; } /// /// Initializes a new instance of the class. /// /// Pointer to the status list. - /// The instance. - internal unsafe StatusList(void* pointer, Dalamud dalamud) - : this((IntPtr)pointer, dalamud) + internal unsafe StatusList(void* pointer) + : this((IntPtr)pointer) { } @@ -104,13 +99,15 @@ namespace Dalamud.Game.ClientState.Statuses [CanBeNull] public Status CreateStatusReference(IntPtr address) { - if (this.dalamud.ClientState.LocalContentId == 0) + var clientState = Service.Get(); + + if (clientState.LocalContentId == 0) return null; if (address == IntPtr.Zero) return null; - return new Status(address, this.dalamud); + return new Status(address); } } diff --git a/Dalamud/Game/Command/CommandManager.cs b/Dalamud/Game/Command/CommandManager.cs index e1f2298f5..ee4ce33db 100644 --- a/Dalamud/Game/Command/CommandManager.cs +++ b/Dalamud/Game/Command/CommandManager.cs @@ -3,8 +3,11 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text.RegularExpressions; +using Dalamud.Game.Gui; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Serilog; namespace Dalamud.Game.Command @@ -12,9 +15,10 @@ namespace Dalamud.Game.Command /// /// This class manages registered in-game slash commands. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class CommandManager { - private readonly Dalamud dalamud; private readonly Dictionary commandMap = new(); private readonly Regex commandRegexEn = new(@"^The command (?.+) does not exist\.$", RegexOptions.Compiled); private readonly Regex commandRegexJp = new(@"^そのコマンドはありません。: (?.+)$", RegexOptions.Compiled); @@ -25,13 +29,11 @@ namespace Dalamud.Game.Command /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - /// The client language requested. - internal CommandManager(Dalamud dalamud, ClientLanguage language) + internal CommandManager() { - this.dalamud = dalamud; + var startInfo = Service.Get(); - this.currentLangCommandRegex = language switch + this.currentLangCommandRegex = startInfo.Language switch { ClientLanguage.Japanese => this.commandRegexJp, ClientLanguage.English => this.commandRegexEn, @@ -40,7 +42,7 @@ namespace Dalamud.Game.Command _ => this.currentLangCommandRegex, }; - dalamud.Framework.Gui.Chat.CheckMessageHandled += this.OnCheckMessageHandled; + Service.Get().CheckMessageHandled += this.OnCheckMessageHandled; } /// diff --git a/Dalamud/Game/Framework.cs b/Dalamud/Game/Framework.cs index cd16fb829..e4bc8967a 100644 --- a/Dalamud/Game/Framework.cs +++ b/Dalamud/Game/Framework.cs @@ -6,9 +6,12 @@ using System.Runtime.InteropServices; using System.Threading; using Dalamud.Game.Gui; -using Dalamud.Game.Libc; +using Dalamud.Game.Gui.Toast; using Dalamud.Game.Network; using Dalamud.Hooking; +using Dalamud.Interface.Internal; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Serilog; namespace Dalamud.Game @@ -16,11 +19,12 @@ namespace Dalamud.Game /// /// This class represents the Framework of the native game client and grants access to various subsystems. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class Framework : IDisposable { private static Stopwatch statsStopwatch = new(); - private readonly Dalamud dalamud; private Hook updateHook; private Hook destroyHook; private Hook realDestroyHook; @@ -28,13 +32,10 @@ namespace Dalamud.Game /// /// Initializes a new instance of the class. /// - /// The SigScanner instance. - /// The Dalamud instance. - internal Framework(SigScanner scanner, Dalamud dalamud) + internal Framework() { - this.dalamud = dalamud; this.Address = new FrameworkAddressResolver(); - this.Address.Setup(scanner); + this.Address.Setup(); Log.Verbose($"Framework address 0x{this.Address.BaseAddress.ToInt64():X}"); if (this.Address.BaseAddress == IntPtr.Zero) @@ -44,13 +45,6 @@ namespace Dalamud.Game // Hook virtual functions this.HookVTable(); - - // Initialize subsystems - this.Libc = new LibcFunction(scanner); - - this.Gui = new GameGui(this.Address.GuiManager, scanner, dalamud); - - this.Network = new GameNetwork(scanner); } /// @@ -92,27 +86,6 @@ namespace Dalamud.Game /// public static Dictionary> StatsHistory { get; } = new(); - #region Subsystems - - /// - /// Gets the GUI subsystem, used to access e.g. chat. - /// - public GameGui Gui { get; private set; } - - /// - /// Gets the Network subsystem, used to access network data. - /// - public GameNetwork Network { get; private set; } - - // public ResourceManager Resource { get; private set; } - - /// - /// Gets the Libc subsystem, used to facilitate interop with std::strings. - /// - public LibcFunction Libc { get; private set; } - - #endregion - /// /// Gets a raw pointer to the instance of Client::Framework. /// @@ -128,8 +101,8 @@ namespace Dalamud.Game /// public void Enable() { - this.Gui.Enable(); - this.Network.Enable(); + Service.Get().Enable(); + Service.Get().Enable(); this.updateHook.Enable(); this.destroyHook.Enable(); @@ -141,17 +114,17 @@ namespace Dalamud.Game /// public void Dispose() { - this.Gui.Dispose(); - this.Network.Dispose(); + Service.GetNullable()?.Dispose(); + Service.GetNullable()?.Dispose(); - this.updateHook.Disable(); - this.destroyHook.Disable(); - this.realDestroyHook.Disable(); + this.updateHook?.Disable(); + this.destroyHook?.Disable(); + this.realDestroyHook?.Disable(); Thread.Sleep(500); - this.updateHook.Dispose(); - this.destroyHook.Dispose(); - this.realDestroyHook.Dispose(); + this.updateHook?.Dispose(); + this.destroyHook?.Dispose(); + this.realDestroyHook?.Dispose(); } private void HookVTable() @@ -176,18 +149,20 @@ namespace Dalamud.Game private bool HandleFrameworkUpdate(IntPtr framework) { - // If this is the first time we are running this loop, we need to init Dalamud subsystems synchronously - if (!this.dalamud.IsReady) - this.dalamud.LoadTier2(); + var dalamud = Service.Get(); - if (!this.dalamud.IsLoadedPluginSystem && this.dalamud.InterfaceManager.IsReady) - this.dalamud.LoadTier3(); + // If this is the first time we are running this loop, we need to init Dalamud subsystems synchronously + if (!dalamud.IsReady) + dalamud.LoadTier2(); + + if (!dalamud.IsLoadedPluginSystem && Service.GetNullable()?.IsReady == true) + dalamud.LoadTier3(); try { - this.Gui.Chat.UpdateQueue(this); - this.Gui.Toast.UpdateQueue(); - this.Network.UpdateQueue(this); + Service.Get().UpdateQueue(); + Service.Get().UpdateQueue(); + Service.Get().UpdateQueue(); } catch (Exception ex) { @@ -251,7 +226,10 @@ namespace Dalamud.Game if (this.DispatchUpdateEvents) { Log.Information("Framework::Destroy!"); - this.dalamud.DisposePlugins(); + + var dalamud = Service.Get(); + dalamud.DisposePlugins(); + Log.Information("Framework::Destroy OK!"); } @@ -267,9 +245,9 @@ namespace Dalamud.Game // Store the pointer to the original trampoline location var originalPtr = Marshal.GetFunctionPointerForDelegate(this.destroyHook.Original); - this.dalamud.Unload(); - - this.dalamud.WaitForUnloadFinish(); + var dalamud = Service.Get(); + dalamud.Unload(); + dalamud.WaitForUnloadFinish(); Log.Information("Framework::Free OK!"); diff --git a/Dalamud/Game/Gui/ChatGui.cs b/Dalamud/Game/Gui/ChatGui.cs index 5895404ab..0d0fc5ebc 100644 --- a/Dalamud/Game/Gui/ChatGui.cs +++ b/Dalamud/Game/Gui/ChatGui.cs @@ -3,11 +3,14 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; +using Dalamud.Configuration.Internal; using Dalamud.Game.Libc; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Hooking; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Serilog; namespace Dalamud.Game.Gui @@ -15,9 +18,10 @@ namespace Dalamud.Game.Gui /// /// This class handles interacting with the native chat UI. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class ChatGui : IDisposable { - private readonly Dalamud dalamud; private readonly ChatGuiAddressResolver address; private readonly Queue chatQueue = new(); @@ -33,14 +37,10 @@ namespace Dalamud.Game.Gui /// Initializes a new instance of the class. /// /// The base address of the ChatManager. - /// The SigScanner instance. - /// The Dalamud instance. - internal ChatGui(IntPtr baseAddress, SigScanner scanner, Dalamud dalamud) + internal ChatGui(IntPtr baseAddress) { - this.dalamud = dalamud; - this.address = new ChatGuiAddressResolver(baseAddress); - this.address.Setup(scanner); + this.address.Setup(); Log.Verbose($"Chat manager address 0x{this.address.BaseAddress.ToInt64():X}"); @@ -163,11 +163,13 @@ namespace Dalamud.Game.Gui /// A message to send. public void Print(string message) { + var configuration = Service.Get(); + Log.Verbose("[CHATGUI PRINT REGULAR]{0}", message); this.PrintChat(new XivChatEntry { Message = message, - Type = this.dalamud.Configuration.GeneralChatType, + Type = configuration.GeneralChatType, }); } @@ -178,11 +180,13 @@ namespace Dalamud.Game.Gui /// A message to send. public void Print(SeString message) { + var configuration = Service.Get(); + Log.Verbose("[CHATGUI PRINT SESTRING]{0}", message.TextValue); this.PrintChat(new XivChatEntry { Message = message, - Type = this.dalamud.Configuration.GeneralChatType, + Type = configuration.GeneralChatType, }); } @@ -219,8 +223,7 @@ namespace Dalamud.Game.Gui /// /// Process a chat queue. /// - /// The Framework instance. - public void UpdateQueue(Framework framework) + public void UpdateQueue() { while (this.chatQueue.Count > 0) { @@ -232,10 +235,10 @@ namespace Dalamud.Game.Gui } var senderRaw = (chat.Name ?? string.Empty).Encode(); - using var senderOwned = framework.Libc.NewString(senderRaw); + using var senderOwned = Service.Get().NewString(senderRaw); var messageRaw = (chat.Message ?? string.Empty).Encode(); - using var messageOwned = framework.Libc.NewString(messageRaw); + using var messageOwned = Service.Get().NewString(messageRaw); this.HandlePrintMessageDetour(this.baseAddress, chat.Type, senderOwned.Address, messageOwned.Address, chat.SenderId, chat.Parameters); } @@ -353,8 +356,8 @@ namespace Dalamud.Game.Gui var sender = StdString.ReadFromPointer(pSenderName); var message = StdString.ReadFromPointer(pMessage); - var parsedSender = this.dalamud.SeStringManager.Parse(sender.RawData); - var parsedMessage = this.dalamud.SeStringManager.Parse(message.RawData); + var parsedSender = Service.Get().Parse(sender.RawData); + var parsedMessage = Service.Get().Parse(message.RawData); Log.Verbose("[CHATGUI][{0}][{1}]", parsedSender.TextValue, parsedMessage.TextValue); @@ -386,7 +389,7 @@ namespace Dalamud.Game.Gui if (!FastByteArrayCompare(originalMessageData, message.RawData)) { - allocatedString = this.dalamud.Framework.Libc.NewString(message.RawData); + allocatedString = Service.Get().NewString(message.RawData); Log.Debug( $"HandlePrintMessageDetour String modified: {originalMessageData}({messagePtr}) -> {message}({allocatedString.Address})"); messagePtr = allocatedString.Address; @@ -436,7 +439,7 @@ namespace Dalamud.Game.Gui while (Marshal.ReadByte(payloadPtr, messageSize) != 0) messageSize++; var payloadBytes = new byte[messageSize]; Marshal.Copy(payloadPtr, payloadBytes, 0, messageSize); - var seStr = this.dalamud.SeStringManager.Parse(payloadBytes); + var seStr = Service.Get().Parse(payloadBytes); var terminatorIndex = seStr.Payloads.IndexOf(RawPayload.LinkTerminator); var payloads = terminatorIndex >= 0 ? seStr.Payloads.Take(terminatorIndex + 1).ToList() : seStr.Payloads; if (payloads.Count == 0) return; diff --git a/Dalamud/Game/Gui/FlyText/FlyTextGui.cs b/Dalamud/Game/Gui/FlyText/FlyTextGui.cs index 64b3a2ea4..2255e9171 100644 --- a/Dalamud/Game/Gui/FlyText/FlyTextGui.cs +++ b/Dalamud/Game/Gui/FlyText/FlyTextGui.cs @@ -4,8 +4,9 @@ using System.Threading.Tasks; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Hooking; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Dalamud.Memory; -using FFXIVClientStructs.FFXIV.Client.UI; using Serilog; namespace Dalamud.Game.Gui.FlyText @@ -13,6 +14,8 @@ namespace Dalamud.Game.Gui.FlyText /// /// This class facilitates interacting with and creating native in-game "fly text". /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class FlyTextGui : IDisposable { /// @@ -28,14 +31,10 @@ namespace Dalamud.Game.Gui.FlyText /// /// Initializes a new instance of the class. /// - /// The SigScanner instance. - /// The Dalamud instance. - internal FlyTextGui(SigScanner scanner, Dalamud dalamud) + internal FlyTextGui() { - this.Dalamud = dalamud; - this.Address = new FlyTextGuiAddressResolver(); - this.Address.Setup(scanner); + this.Address.Setup(); this.addFlyTextNative = Marshal.GetDelegateForFunctionPointer(this.Address.AddFlyText); this.createFlyTextHook = new Hook(this.Address.CreateFlyText, this.CreateFlyTextDetour); @@ -132,8 +131,9 @@ namespace Dalamud.Game.Gui.FlyText var strOffset = 28u; // Get the UI module and flytext addon pointers - var ui = (UIModule*)this.Dalamud.Framework.Gui.GetUIModule(); - var flytext = this.Dalamud.Framework.Gui.GetAddonByName("_FlyText", 1); + var gameGui = Service.Get(); + var ui = (FFXIVClientStructs.FFXIV.Client.UI.UIModule*)gameGui.GetUIModule(); + var flytext = gameGui.GetAddonByName("_FlyText", 1); if (ui == null || flytext == IntPtr.Zero) return; diff --git a/Dalamud/Game/Gui/GameGui.cs b/Dalamud/Game/Gui/GameGui.cs index 11366e969..6c65abf4b 100644 --- a/Dalamud/Game/Gui/GameGui.cs +++ b/Dalamud/Game/Gui/GameGui.cs @@ -8,6 +8,8 @@ using Dalamud.Game.Gui.Toast; using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Hooking; using Dalamud.Interface; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Dalamud.Utility; using ImGuiNET; using Serilog; @@ -17,9 +19,10 @@ namespace Dalamud.Game.Gui /// /// A class handling many aspects of the in-game UI. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class GameGui : IDisposable { - private readonly Dalamud dalamud; private readonly GameGuiAddressResolver address; private readonly GetMatrixSingletonDelegate getMatrixSingleton; @@ -41,15 +44,10 @@ namespace Dalamud.Game.Gui /// Initializes a new instance of the class. /// This class is responsible for many aspects of interacting with the native game UI. /// - /// The base address of the native GuiManager class. - /// The SigScanner instance. - /// The Dalamud instance. - internal GameGui(IntPtr baseAddress, SigScanner scanner, Dalamud dalamud) + internal GameGui() { - this.dalamud = dalamud; - - this.address = new GameGuiAddressResolver(baseAddress); - this.address.Setup(scanner); + this.address = new GameGuiAddressResolver(this.address.BaseAddress); + this.address.Setup(); Log.Verbose("===== G A M E G U I ====="); @@ -60,10 +58,10 @@ namespace Dalamud.Game.Gui Log.Verbose($"HandleImm address 0x{this.address.HandleImm.ToInt64():X}"); Log.Verbose($"GetAgentModule address 0x{this.address.GetAgentModule.ToInt64():X}"); - this.Chat = new ChatGui(this.address.ChatManager, scanner, dalamud); - this.PartyFinder = new PartyFinderGui(scanner, dalamud); - this.Toast = new ToastGui(scanner, dalamud); - this.FlyText = new FlyTextGui(scanner, dalamud); + Service.Set(new ChatGui(this.address.ChatManager)); + Service.Set(); + Service.Set(); + Service.Set(); this.setGlobalBgmHook = new Hook(this.address.SetGlobalBgm, this.HandleSetGlobalBgmDetour); @@ -128,26 +126,6 @@ namespace Dalamud.Game.Gui /// public event EventHandler OnUiHideToggled; - /// - /// Gets the instance. - /// - public ChatGui Chat { get; private set; } - - /// - /// Gets the instance. - /// - public PartyFinderGui PartyFinder { get; private set; } - - /// - /// Gets the instance. - /// - public ToastGui Toast { get; private set; } - - /// - /// Gets the instance. - /// - public FlyTextGui FlyText { get; private set; } - /// /// Gets a value indicating whether the game UI is hidden. /// @@ -440,7 +418,7 @@ namespace Dalamud.Game.Gui if (addon == IntPtr.Zero) return IntPtr.Zero; - var uiModule = this.dalamud.Framework.Gui.GetUIModule(); + var uiModule = Service.Get().GetUIModule(); if (uiModule == IntPtr.Zero) { return IntPtr.Zero; @@ -483,10 +461,10 @@ namespace Dalamud.Game.Gui /// public void Enable() { - this.Chat.Enable(); - this.Toast.Enable(); - this.FlyText.Enable(); - this.PartyFinder.Enable(); + Service.Get().Enable(); + Service.Get().Enable(); + Service.Get().Enable(); + Service.Get().Enable(); this.setGlobalBgmHook.Enable(); this.handleItemHoverHook.Enable(); this.handleItemOutHook.Enable(); @@ -501,10 +479,10 @@ namespace Dalamud.Game.Gui /// public void Dispose() { - this.Chat.Dispose(); - this.Toast.Dispose(); - this.FlyText.Dispose(); - this.PartyFinder.Dispose(); + Service.Get().Dispose(); + Service.Get().Dispose(); + Service.Get().Dispose(); + Service.Get().Dispose(); this.setGlobalBgmHook.Dispose(); this.handleItemHoverHook.Dispose(); this.handleItemOutHook.Dispose(); diff --git a/Dalamud/Game/Gui/Internal/DalamudIME.cs b/Dalamud/Game/Gui/Internal/DalamudIME.cs index de1c4a6a5..6e9616b8c 100644 --- a/Dalamud/Game/Gui/Internal/DalamudIME.cs +++ b/Dalamud/Game/Gui/Internal/DalamudIME.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; +using Dalamud.Interface.Internal; using Dalamud.Logging.Internal; using ImGuiNET; @@ -17,8 +18,6 @@ namespace Dalamud.Game.Gui.Internal { private static readonly ModuleLog Log = new("IME"); - private readonly Dalamud dalamud; - private IntPtr interfaceHandle; private IntPtr wndProcPtr; private IntPtr oldWndProcPtr; @@ -27,10 +26,8 @@ namespace Dalamud.Game.Gui.Internal /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - internal DalamudIME(Dalamud dalamud) + internal DalamudIME() { - this.dalamud = dalamud; } private delegate long WndProcDelegate(IntPtr hWnd, uint msg, ulong wParam, long lParam); @@ -68,7 +65,7 @@ namespace Dalamud.Game.Gui.Internal try { this.wndProcDelegate = this.WndProcDetour; - this.interfaceHandle = this.dalamud.InterfaceManager.WindowHandlePtr; + this.interfaceHandle = Service.Get().WindowHandlePtr; this.wndProcPtr = Marshal.GetFunctionPointerForDelegate(this.wndProcDelegate); this.oldWndProcPtr = SetWindowLongPtrW(this.interfaceHandle, WindowLongType.WndProc, this.wndProcPtr); this.IsEnabled = true; @@ -83,9 +80,9 @@ namespace Dalamud.Game.Gui.Internal private void ToggleWindow(bool visible) { if (visible) - this.dalamud.DalamudUi.OpenIMEWindow(); + Service.Get().OpenIMEWindow(); else - this.dalamud.DalamudUi.CloseIMEWindow(); + Service.Get().CloseIMEWindow(); } private long WndProcDetour(IntPtr hWnd, uint msg, ulong wParam, long lParam) diff --git a/Dalamud/Game/Gui/PartyFinder/PartyFinderGui.cs b/Dalamud/Game/Gui/PartyFinder/PartyFinderGui.cs index dcfd03c46..e61cbaf84 100644 --- a/Dalamud/Game/Gui/PartyFinder/PartyFinderGui.cs +++ b/Dalamud/Game/Gui/PartyFinder/PartyFinderGui.cs @@ -4,6 +4,8 @@ using System.Runtime.InteropServices; using Dalamud.Game.Gui.PartyFinder.Internal; using Dalamud.Game.Gui.PartyFinder.Types; using Dalamud.Hooking; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Serilog; namespace Dalamud.Game.Gui.PartyFinder @@ -11,9 +13,10 @@ namespace Dalamud.Game.Gui.PartyFinder /// /// This class handles interacting with the native PartyFinder window. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class PartyFinderGui : IDisposable { - private readonly Dalamud dalamud; private readonly PartyFinderAddressResolver address; private readonly IntPtr memory; @@ -22,14 +25,10 @@ namespace Dalamud.Game.Gui.PartyFinder /// /// Initializes a new instance of the class. /// - /// The SigScanner instance. - /// The Dalamud instance. - internal PartyFinderGui(SigScanner scanner, Dalamud dalamud) + internal PartyFinderGui() { - this.dalamud = dalamud; - this.address = new PartyFinderAddressResolver(); - this.address.Setup(scanner); + this.address.Setup(); this.memory = Marshal.AllocHGlobal(PartyFinderPacket.PacketSize); @@ -101,7 +100,7 @@ namespace Dalamud.Game.Gui.PartyFinder continue; } - var listing = new PartyFinderListing(packet.Listings[i], this.dalamud.Data, this.dalamud.SeStringManager); + var listing = new PartyFinderListing(packet.Listings[i]); var args = new PartyFinderListingEventArgs(packet.BatchNumber); this.ReceiveListing?.Invoke(listing, args); diff --git a/Dalamud/Game/Gui/PartyFinder/Types/PartyFinderListing.cs b/Dalamud/Game/Gui/PartyFinder/Types/PartyFinderListing.cs index c75748942..4ee89bb80 100644 --- a/Dalamud/Game/Gui/PartyFinder/Types/PartyFinderListing.cs +++ b/Dalamud/Game/Gui/PartyFinder/Types/PartyFinderListing.cs @@ -14,8 +14,6 @@ namespace Dalamud.Game.Gui.PartyFinder.Types /// public class PartyFinderListing { - #region Backing fields - private readonly byte objective; private readonly byte conditions; private readonly byte dutyFinderSettings; @@ -24,16 +22,15 @@ namespace Dalamud.Game.Gui.PartyFinder.Types private readonly PartyFinderSlot[] slots; private readonly byte[] jobsPresent; - #endregion - /// /// Initializes a new instance of the class. /// /// The interop listing data. - /// The DataManager instance. - /// The SeStringManager instance. - internal PartyFinderListing(PartyFinderPacketListing listing, DataManager dataManager, SeStringManager seStringManager) + internal PartyFinderListing(PartyFinderPacketListing listing) { + var dataManager = Service.Get(); + var seStringManager = Service.Get(); + this.objective = listing.Objective; this.conditions = listing.Conditions; this.dutyFinderSettings = listing.DutyFinderSettings; diff --git a/Dalamud/Game/Gui/Toast/ToastGui.cs b/Dalamud/Game/Gui/Toast/ToastGui.cs index 84485cc1e..ce578ba0b 100644 --- a/Dalamud/Game/Gui/Toast/ToastGui.cs +++ b/Dalamud/Game/Gui/Toast/ToastGui.cs @@ -4,17 +4,20 @@ using System.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Hooking; +using Dalamud.IoC; +using Dalamud.IoC.Internal; namespace Dalamud.Game.Gui.Toast { /// /// This class facilitates interacting with and creating native toast windows. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed partial class ToastGui : IDisposable { private const uint QuestToastCheckmarkMagic = 60081; - private readonly Dalamud dalamud; private readonly ToastGuiAddressResolver address; private readonly Queue<(byte[] Message, ToastOptions Options)> normalQueue = new(); @@ -28,14 +31,10 @@ namespace Dalamud.Game.Gui.Toast /// /// Initializes a new instance of the class. /// - /// The SigScanner instance. - /// The Dalamud instance. - internal ToastGui(SigScanner scanner, Dalamud dalamud) + internal ToastGui() { - this.dalamud = dalamud; - this.address = new ToastGuiAddressResolver(); - this.address.Setup(scanner); + this.address.Setup(); this.showNormalToastHook = new Hook(this.address.ShowNormalToast, new ShowNormalToastDelegate(this.HandleNormalToastDetour)); this.showQuestToastHook = new Hook(this.address.ShowQuestToast, new ShowQuestToastDelegate(this.HandleQuestToastDetour)); @@ -165,7 +164,7 @@ namespace Dalamud.Game.Gui.Toast } // call events - return this.dalamud.SeStringManager.Parse(bytes.ToArray()); + return Service.Get().Parse(bytes.ToArray()); } } @@ -200,7 +199,7 @@ namespace Dalamud.Game.Gui.Toast { options ??= new ToastOptions(); - var manager = this.dalamud.Framework.Gui.GetUIModule(); + var manager = Service.Get().GetUIModule(); // terminate the string var terminated = Terminate(bytes); @@ -281,7 +280,7 @@ namespace Dalamud.Game.Gui.Toast { options ??= new QuestToastOptions(); - var manager = this.dalamud.Framework.Gui.GetUIModule(); + var manager = Service.Get().GetUIModule(); // terminate the string var terminated = Terminate(bytes); @@ -383,7 +382,7 @@ namespace Dalamud.Game.Gui.Toast private void ShowError(byte[] bytes) { - var manager = this.dalamud.Framework.Gui.GetUIModule(); + var manager = Service.Get().GetUIModule(); // terminate the string var terminated = Terminate(bytes); diff --git a/Dalamud/Game/Internal/AntiDebug.cs b/Dalamud/Game/Internal/AntiDebug.cs index 59e2a1df4..7cac7b7dc 100644 --- a/Dalamud/Game/Internal/AntiDebug.cs +++ b/Dalamud/Game/Internal/AntiDebug.cs @@ -17,9 +17,10 @@ namespace Dalamud.Game.Internal /// /// Initializes a new instance of the class. /// - /// The SigScanner instance. - public AntiDebug(SigScanner scanner) + public AntiDebug() { + var scanner = Service.Get(); + try { this.debugCheckAddress = scanner.ScanText("FF 15 ?? ?? ?? ?? 85 C0 74 11 41"); diff --git a/Dalamud/Game/Internal/DalamudSystemMenu.cs b/Dalamud/Game/Internal/DalamudSystemMenu.cs index 673bcb55b..8e7bc475c 100644 --- a/Dalamud/Game/Internal/DalamudSystemMenu.cs +++ b/Dalamud/Game/Internal/DalamudSystemMenu.cs @@ -3,7 +3,9 @@ using System.Runtime.InteropServices; using System.Text; using CheapLoc; +using Dalamud.Configuration.Internal; using Dalamud.Hooking; +using Dalamud.Interface.Internal; using FFXIVClientStructs.FFXIV.Component.GUI; using ValueType = FFXIVClientStructs.FFXIV.Component.GUI.ValueType; @@ -15,32 +17,31 @@ namespace Dalamud.Game.Internal /// internal sealed unsafe partial class DalamudSystemMenu { - private readonly Dalamud dalamud; private readonly AtkValueChangeType atkValueChangeType; private readonly AtkValueSetString atkValueSetString; private readonly Hook hookAgentHudOpenSystemMenu; + // TODO: Make this into events in Framework.Gui private readonly Hook hookUiModuleRequestMainCommand; /// /// Initializes a new instance of the class. /// - /// The dalamud instance to act on. - public DalamudSystemMenu(Dalamud dalamud) + public DalamudSystemMenu() { - this.dalamud = dalamud; + var sigScanner = Service.Get(); - var openSystemMenuAddress = this.dalamud.SigScanner.ScanText("E8 ?? ?? ?? ?? 32 C0 4C 8B AC 24 ?? ?? ?? ?? 48 8B 8D ?? ?? ?? ??"); + var openSystemMenuAddress = sigScanner.ScanText("E8 ?? ?? ?? ?? 32 C0 4C 8B AC 24 ?? ?? ?? ?? 48 8B 8D ?? ?? ?? ??"); this.hookAgentHudOpenSystemMenu = new Hook(openSystemMenuAddress, this.AgentHudOpenSystemMenuDetour); - var atkValueChangeTypeAddress = this.dalamud.SigScanner.ScanText("E8 ?? ?? ?? ?? 45 84 F6 48 8D 4C 24 ??"); + var atkValueChangeTypeAddress = sigScanner.ScanText("E8 ?? ?? ?? ?? 45 84 F6 48 8D 4C 24 ??"); this.atkValueChangeType = Marshal.GetDelegateForFunctionPointer(atkValueChangeTypeAddress); - var atkValueSetStringAddress = this.dalamud.SigScanner.ScanText("E8 ?? ?? ?? ?? 41 03 ED"); + var atkValueSetStringAddress = sigScanner.ScanText("E8 ?? ?? ?? ?? 41 03 ED"); this.atkValueSetString = Marshal.GetDelegateForFunctionPointer(atkValueSetStringAddress); - var uiModuleRequestMainCommandAddress = this.dalamud.SigScanner.ScanText("40 53 56 48 81 EC ?? ?? ?? ?? 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 84 24 ?? ?? ?? ?? 48 8B 01 8B DA 48 8B F1 FF 90 ?? ?? ?? ??"); + var uiModuleRequestMainCommandAddress = sigScanner.ScanText("40 53 56 48 81 EC ?? ?? ?? ?? 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 84 24 ?? ?? ?? ?? 48 8B 01 8B DA 48 8B F1 FF 90 ?? ?? ?? ??"); this.hookUiModuleRequestMainCommand = new Hook(uiModuleRequestMainCommandAddress, this.UiModuleRequestMainCommandDetour); } @@ -63,7 +64,9 @@ namespace Dalamud.Game.Internal private void AgentHudOpenSystemMenuDetour(void* thisPtr, AtkValue* atkValueArgs, uint menuSize) { - if (!this.dalamud.Configuration.DoButtonsSystemMenu) + var configuration = Service.Get(); + + if (!configuration.DoButtonsSystemMenu) { this.hookAgentHudOpenSystemMenu.Original(thisPtr, atkValueArgs, menuSize); return; @@ -134,13 +137,15 @@ namespace Dalamud.Game.Internal private void UiModuleRequestMainCommandDetour(void* thisPtr, int commandId) { + var dalamudInterface = Service.Get(); + switch (commandId) { case 69420: - this.dalamud.DalamudUi.TogglePluginInstallerWindow(); + dalamudInterface.TogglePluginInstallerWindow(); break; case 69421: - this.dalamud.DalamudUi.ToggleSettingsWindow(); + dalamudInterface.ToggleSettingsWindow(); break; default: this.hookUiModuleRequestMainCommand.Original(thisPtr, commandId); diff --git a/Dalamud/Game/Libc/LibcFunction.cs b/Dalamud/Game/Libc/LibcFunction.cs index cfab061c3..3c2361277 100644 --- a/Dalamud/Game/Libc/LibcFunction.cs +++ b/Dalamud/Game/Libc/LibcFunction.cs @@ -2,11 +2,16 @@ using System; using System.Runtime.InteropServices; using System.Text; +using Dalamud.IoC; +using Dalamud.IoC.Internal; + namespace Dalamud.Game.Libc { /// /// This class handles creating cstrings utilizing native game methods. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class LibcFunction { private readonly LibcFunctionAddressResolver address; @@ -16,11 +21,10 @@ namespace Dalamud.Game.Libc /// /// Initializes a new instance of the class. /// - /// The SigScanner instance. - public LibcFunction(SigScanner scanner) + public LibcFunction() { this.address = new LibcFunctionAddressResolver(); - this.address.Setup(scanner); + this.address.Setup(); this.stdStringCtorCString = Marshal.GetDelegateForFunctionPointer(this.address.StdStringFromCstring); this.stdStringDeallocate = Marshal.GetDelegateForFunctionPointer(this.address.StdStringDeallocate); diff --git a/Dalamud/Game/Network/GameNetwork.cs b/Dalamud/Game/Network/GameNetwork.cs index 90d585654..d75865d50 100644 --- a/Dalamud/Game/Network/GameNetwork.cs +++ b/Dalamud/Game/Network/GameNetwork.cs @@ -2,8 +2,9 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; -using Dalamud.Game.Network; using Dalamud.Hooking; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Serilog; namespace Dalamud.Game.Network @@ -11,6 +12,8 @@ namespace Dalamud.Game.Network /// /// This class handles interacting with game network events. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class GameNetwork : IDisposable { private readonly GameNetworkAddressResolver address; @@ -23,11 +26,10 @@ namespace Dalamud.Game.Network /// /// Initializes a new instance of the class. /// - /// The SigScanner instance. - public GameNetwork(SigScanner scanner) + internal GameNetwork() { this.address = new GameNetworkAddressResolver(); - this.address.Setup(scanner); + this.address.Setup(); Log.Verbose("===== G A M E N E T W O R K ====="); Log.Verbose($"ProcessZonePacketDown address 0x{this.address.ProcessZonePacketDown.ToInt64():X}"); @@ -79,8 +81,7 @@ namespace Dalamud.Game.Network /// /// Process a chat queue. /// - /// The Framework instance. - public void UpdateQueue(Framework framework) + internal void UpdateQueue() { while (this.zoneInjectQueue.Count > 0) { diff --git a/Dalamud/Game/Network/Internal/MarketBoardUploaders/Universalis/UniversalisMarketBoardUploader.cs b/Dalamud/Game/Network/Internal/MarketBoardUploaders/Universalis/UniversalisMarketBoardUploader.cs index 5e4ac76e1..104faef36 100644 --- a/Dalamud/Game/Network/Internal/MarketBoardUploaders/Universalis/UniversalisMarketBoardUploader.cs +++ b/Dalamud/Game/Network/Internal/MarketBoardUploaders/Universalis/UniversalisMarketBoardUploader.cs @@ -21,30 +21,27 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis private const string ApiKey = "GGD6RdSfGyRiHM5WDnAo0Nj9Nv7aC5NDhMj3BebT"; - private readonly Dalamud dalamud; - /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public UniversalisMarketBoardUploader(Dalamud dalamud) + public UniversalisMarketBoardUploader() { - this.dalamud = dalamud; } /// public void Upload(MarketBoardItemRequest request) { + var clientState = Service.Get(); using var client = new HttpClient(); Log.Verbose("Starting Universalis upload."); - var uploader = this.dalamud.ClientState.LocalContentId; + var uploader = clientState.LocalContentId; // ==================================================================================== var listingsUploadObject = new UniversalisItemListingsUploadRequest { - WorldId = this.dalamud.ClientState.LocalPlayer?.CurrentWorld.Id ?? 0, + WorldId = clientState.LocalPlayer?.CurrentWorld.Id ?? 0, UploaderId = uploader.ToString(), ItemId = request.CatalogId, Listings = new List(), @@ -89,7 +86,7 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis var historyUploadObject = new UniversalisHistoryUploadRequest { - WorldId = this.dalamud.ClientState.LocalPlayer?.CurrentWorld.Id ?? 0, + WorldId = clientState.LocalPlayer?.CurrentWorld.Id ?? 0, UploaderId = uploader.ToString(), ItemId = request.CatalogId, Entries = new List(), @@ -121,14 +118,15 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis /// public void UploadTax(MarketTaxRates taxRates) { + var clientState = Service.Get(); using var client = new HttpClient(); // ==================================================================================== var taxUploadObject = new UniversalisTaxUploadRequest { - WorldId = this.dalamud.ClientState.LocalPlayer?.CurrentWorld.Id ?? 0, - UploaderId = this.dalamud.ClientState.LocalContentId.ToString(), + WorldId = clientState.LocalPlayer?.CurrentWorld.Id ?? 0, + UploaderId = clientState.LocalContentId.ToString(), TaxData = new UniversalisTaxData { LimsaLominsa = taxRates.LimsaLominsaTax, @@ -159,12 +157,13 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis /// public void UploadPurchase(MarketBoardPurchaseHandler purchaseHandler) { + var clientState = Service.Get(); using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(ApiKey); var itemId = purchaseHandler.CatalogId; - var worldId = this.dalamud.ClientState.LocalPlayer?.CurrentWorld.Id ?? 0; + var worldId = clientState.LocalPlayer?.CurrentWorld.Id ?? 0; // ==================================================================================== @@ -174,7 +173,7 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis Quantity = purchaseHandler.ItemQuantity, ListingId = purchaseHandler.ListingId.ToString(), RetainerId = purchaseHandler.RetainerId.ToString(), - UploaderId = this.dalamud.ClientState.LocalContentId.ToString(), + UploaderId = clientState.LocalContentId.ToString(), }; var deletePath = $"/api/{worldId}/{itemId}/delete"; diff --git a/Dalamud/Game/Network/Internal/NetworkHandlers.cs b/Dalamud/Game/Network/Internal/NetworkHandlers.cs index bf20122b0..c27fd2a97 100644 --- a/Dalamud/Game/Network/Internal/NetworkHandlers.cs +++ b/Dalamud/Game/Network/Internal/NetworkHandlers.cs @@ -5,6 +5,9 @@ using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; +using Dalamud.Configuration.Internal; +using Dalamud.Data; +using Dalamud.Game.Gui; using Dalamud.Game.Network.Internal.MarketBoardUploaders; using Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis; using Dalamud.Game.Network.Structures; @@ -18,8 +21,6 @@ namespace Dalamud.Game.Network.Internal /// internal class NetworkHandlers { - private readonly Dalamud dalamud; - private readonly List marketBoardRequests = new(); private readonly bool optOutMbUploads; @@ -30,16 +31,13 @@ namespace Dalamud.Game.Network.Internal /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - /// Whether the client should opt out of market board uploads. - public NetworkHandlers(Dalamud dalamud, bool optOutMbUploads) + public NetworkHandlers() { - this.dalamud = dalamud; - this.optOutMbUploads = optOutMbUploads; + this.optOutMbUploads = Service.Get().OptOutMbCollection; - this.uploader = new UniversalisMarketBoardUploader(dalamud); + this.uploader = new UniversalisMarketBoardUploader(); - dalamud.Framework.Network.OnNetworkMessage += this.OnNetworkMessage; + Service.Get().OnNetworkMessage += this.OnNetworkMessage; } /// @@ -49,14 +47,18 @@ namespace Dalamud.Game.Network.Internal private void OnNetworkMessage(IntPtr dataPtr, ushort opCode, uint sourceActorId, uint targetActorId, NetworkMessageDirection direction) { - if (!this.dalamud.Data.IsDataReady) + var dataManager = Service.GetNullable(); + + if (dataManager?.IsDataReady == false) return; + var configuration = Service.Get(); + if (direction == NetworkMessageDirection.ZoneUp) { if (!this.optOutMbUploads) { - if (opCode == this.dalamud.Data.ClientOpCodes["MarketBoardPurchaseHandler"]) + if (opCode == Service.Get().ClientOpCodes["MarketBoardPurchaseHandler"]) { this.marketBoardPurchaseHandler = MarketBoardPurchaseHandler.Read(dataPtr); } @@ -65,7 +67,7 @@ namespace Dalamud.Game.Network.Internal return; } - if (opCode == this.dalamud.Data.ServerOpCodes["CfNotifyPop"]) + if (opCode == dataManager.ServerOpCodes["CfNotifyPop"]) { var data = new byte[64]; Marshal.Copy(dataPtr, data, 0, 64); @@ -76,7 +78,7 @@ namespace Dalamud.Game.Network.Internal if (notifyType != 3) return; - var contentFinderCondition = this.dalamud.Data.GetExcelSheet().GetRow(contentFinderConditionId); + var contentFinderCondition = dataManager.GetExcelSheet().GetRow(contentFinderConditionId); if (contentFinderCondition == null) { @@ -91,7 +93,7 @@ namespace Dalamud.Game.Network.Internal contentFinderCondition.Image = 112324; } - if (this.dalamud.Configuration.DutyFinderTaskbarFlash && !NativeFunctions.ApplicationIsActivated()) + if (configuration.DutyFinderTaskbarFlash && !NativeFunctions.ApplicationIsActivated()) { var flashInfo = new NativeFunctions.FlashWindowInfo { @@ -106,8 +108,10 @@ namespace Dalamud.Game.Network.Internal Task.Run(() => { - if (this.dalamud.Configuration.DutyFinderChatMessage) - this.dalamud.Framework.Gui.Chat.Print("Duty pop: " + cfcName); + if (configuration.DutyFinderChatMessage) + { + Service.Get().Print("Duty pop: " + cfcName); + } this.CfPop?.Invoke(this, contentFinderCondition); }); @@ -117,7 +121,7 @@ namespace Dalamud.Game.Network.Internal if (!this.optOutMbUploads) { - if (opCode == this.dalamud.Data.ServerOpCodes["MarketBoardItemRequestStart"]) + if (opCode == dataManager.ServerOpCodes["MarketBoardItemRequestStart"]) { var catalogId = (uint)Marshal.ReadInt32(dataPtr); var amount = Marshal.ReadByte(dataPtr + 0xB); @@ -134,7 +138,7 @@ namespace Dalamud.Game.Network.Internal return; } - if (opCode == this.dalamud.Data.ServerOpCodes["MarketBoardOfferings"]) + if (opCode == dataManager.ServerOpCodes["MarketBoardOfferings"]) { var listing = MarketBoardCurrentOfferings.Read(dataPtr); @@ -200,7 +204,7 @@ namespace Dalamud.Game.Network.Internal return; } - if (opCode == this.dalamud.Data.ServerOpCodes["MarketBoardHistory"]) + if (opCode == dataManager.ServerOpCodes["MarketBoardHistory"]) { var listing = MarketBoardHistory.Read(dataPtr); @@ -237,7 +241,7 @@ namespace Dalamud.Game.Network.Internal } } - if (opCode == this.dalamud.Data.ServerOpCodes["MarketTaxRates"]) + if (opCode == dataManager.ServerOpCodes["MarketTaxRates"]) { var category = (uint)Marshal.ReadInt32(dataPtr); @@ -267,7 +271,7 @@ namespace Dalamud.Game.Network.Internal } } - if (opCode == this.dalamud.Data.ServerOpCodes["MarketBoardPurchase"]) + if (opCode == dataManager.ServerOpCodes["MarketBoardPurchase"]) { if (this.marketBoardPurchaseHandler == null) return; diff --git a/Dalamud/Game/SigScanner.cs b/Dalamud/Game/SigScanner.cs index 285f845fe..28bb0137b 100644 --- a/Dalamud/Game/SigScanner.cs +++ b/Dalamud/Game/SigScanner.cs @@ -5,6 +5,8 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Serilog; namespace Dalamud.Game @@ -12,6 +14,8 @@ namespace Dalamud.Game /// /// A SigScanner facilitates searching for memory signatures in a given ProcessModule. /// + [PluginInterface] + [InterfaceVersion("1.0")] public sealed class SigScanner : IDisposable { private IntPtr moduleCopyPtr; diff --git a/Dalamud/Game/Text/SeStringHandling/Payload.cs b/Dalamud/Game/Text/SeStringHandling/Payload.cs index 3ace4ebf1..8a1e03cb1 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payload.cs @@ -27,9 +27,9 @@ namespace Dalamud.Game.Text.SeStringHandling private byte[] encodedData; /// - /// Gets or sets the Lumina instance to use for any necessary data lookups. + /// Gets the Lumina instance to use for any necessary data lookups. /// - public DataManager DataResolver { get; set; } + public DataManager DataResolver => Service.Get(); /// /// Gets the type of this payload. @@ -45,9 +45,8 @@ namespace Dalamud.Game.Text.SeStringHandling /// Decodes a binary representation of a payload into its corresponding nice object payload. /// /// A reader positioned at the start of the payload, and containing at least one entire payload. - /// The DataManager instance. /// The constructed Payload-derived object that was decoded from the binary data. - public static Payload Decode(BinaryReader reader, DataManager data) + public static Payload Decode(BinaryReader reader) { var payloadStartPos = reader.BaseStream.Position; @@ -64,8 +63,6 @@ namespace Dalamud.Game.Text.SeStringHandling payload = DecodeChunk(reader); } - payload.DataResolver = data; - // for now, cache off the actual binary data for this payload, so we don't have to // regenerate it if the payload isn't modified // TODO: probably better ways to handle this diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/AutoTranslatePayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/AutoTranslatePayload.cs index 24e2a139f..8e9eb5b65 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/AutoTranslatePayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/AutoTranslatePayload.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using Dalamud.Data; using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; using Serilog; @@ -27,17 +26,15 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Initializes a new instance of the class. /// Creates a new auto-translate payload. /// - /// DataManager instance needed to resolve game data. /// The group id for this message. /// The key/row id for this message. Which table this is in depends on the group id and details the Completion table. /// /// This table is somewhat complicated in structure, and so using this constructor may not be very nice. /// There is probably little use to create one of these, however. /// - public AutoTranslatePayload(DataManager data, uint group, uint key) + public AutoTranslatePayload(uint group, uint key) { // TODO: friendlier ctor? not sure how to handle that given how weird the tables are - this.DataResolver = data; this.group = group; this.key = key; } diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/ItemPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/ItemPayload.cs index 9236dffe8..9714852e9 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/ItemPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/ItemPayload.cs @@ -3,7 +3,6 @@ using System.IO; using System.Linq; using System.Text; -using Dalamud.Data; using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; @@ -29,15 +28,13 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Initializes a new instance of the class. /// Creates a payload representing an interactable item link for the specified item. /// - /// DataManager instance needed to resolve game data. /// The id of the item. /// Whether or not the link should be for the high-quality variant of the item. /// An optional name to include in the item link. Typically this should /// be left as null, or set to the normal item name. Actual overrides are better done with the subsequent /// TextPayload that is a part of a full item link in chat. - public ItemPayload(DataManager data, uint itemId, bool isHQ, string displayNameOverride = null) + public ItemPayload(uint itemId, bool isHQ, string displayNameOverride = null) { - this.DataResolver = data; this.itemId = itemId; this.IsHQ = isHQ; this.displayName = displayNameOverride; diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/MapLinkPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/MapLinkPayload.cs index a6e6c2e49..8f7418b48 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/MapLinkPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/MapLinkPayload.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.IO; -using Dalamud.Data; using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; @@ -28,15 +27,13 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Initializes a new instance of the class. /// Creates an interactable MapLinkPayload from a human-readable position. /// - /// DataManager instance needed to resolve game data. /// The id of the TerritoryType entry for this link. /// The id of the Map entry for this link. /// The human-readable x-coordinate for this link. /// The human-readable y-coordinate for this link. /// An optional offset to account for rounding and truncation errors; it is best to leave this untouched in most cases. - public MapLinkPayload(DataManager data, uint territoryTypeId, uint mapId, float niceXCoord, float niceYCoord, float fudgeFactor = 0.05f) + public MapLinkPayload(uint territoryTypeId, uint mapId, float niceXCoord, float niceYCoord, float fudgeFactor = 0.05f) { - this.DataResolver = data; this.territoryTypeId = territoryTypeId; this.mapId = mapId; // this fudge is necessary basically to ensure we don't shift down a full tenth @@ -50,14 +47,12 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Initializes a new instance of the class. /// Creates an interactable MapLinkPayload from a raw position. /// - /// DataManager instance needed to resolve game data. /// The id of the TerritoryType entry for this link. /// The id of the Map entry for this link. /// The internal raw x-coordinate for this link. /// The internal raw y-coordinate for this link. - public MapLinkPayload(DataManager data, uint territoryTypeId, uint mapId, int rawX, int rawY) + public MapLinkPayload(uint territoryTypeId, uint mapId, int rawX, int rawY) { - this.DataResolver = data; this.territoryTypeId = territoryTypeId; this.mapId = mapId; this.RawX = rawX; diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/PlayerPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/PlayerPayload.cs index 484290c9e..01d8331e1 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/PlayerPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/PlayerPayload.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using Dalamud.Data; using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; @@ -25,12 +24,10 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Initializes a new instance of the class. /// Create a PlayerPayload link for the specified player. /// - /// DataManager instance needed to resolve game data. /// The player's displayed name. /// The player's home server id. - public PlayerPayload(DataManager data, string playerName, uint serverId) + public PlayerPayload(string playerName, uint serverId) { - this.DataResolver = data; this.playerName = playerName; this.serverId = serverId; } diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/QuestPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/QuestPayload.cs index a250d3b58..d9dca651b 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/QuestPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/QuestPayload.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.IO; -using Dalamud.Data; using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; @@ -21,11 +20,9 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Initializes a new instance of the class. /// Creates a payload representing an interactable quest link for the specified quest. /// - /// DataManager instance needed to resolve game data. /// The id of the quest. - public QuestPayload(DataManager data, uint questId) + public QuestPayload(uint questId) { - this.DataResolver = data; this.questId = questId; } diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/StatusPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/StatusPayload.cs index 6adf988dd..e7df98ae8 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/StatusPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/StatusPayload.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.IO; -using Dalamud.Data; using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; @@ -21,11 +20,9 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Initializes a new instance of the class. /// Creates a new StatusPayload for the given status id. /// - /// DataManager instance needed to resolve game data. /// The id of the Status for this link. - public StatusPayload(DataManager data, uint statusId) + public StatusPayload(uint statusId) { - this.DataResolver = data; this.statusId = statusId; } diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/UIForegroundPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/UIForegroundPayload.cs index 61a0599c9..4934004bf 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/UIForegroundPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/UIForegroundPayload.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.IO; -using Dalamud.Data; using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; @@ -21,11 +20,9 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Initializes a new instance of the class. /// Creates a new UIForegroundPayload for the given UIColor key. /// - /// DataManager instance needed to resolve game data. /// A UIColor key. - public UIForegroundPayload(DataManager data, ushort colorKey) + public UIForegroundPayload(ushort colorKey) { - this.DataResolver = data; this.colorKey = colorKey; } @@ -41,7 +38,7 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Gets a payload representing disabling foreground color on following text. /// // TODO Make this work with DI - public static UIForegroundPayload UIForegroundOff => new(null, 0); + public static UIForegroundPayload UIForegroundOff => new(0); /// public override PayloadType Type => PayloadType.UIForeground; diff --git a/Dalamud/Game/Text/SeStringHandling/Payloads/UIGlowPayload.cs b/Dalamud/Game/Text/SeStringHandling/Payloads/UIGlowPayload.cs index 4a716c99d..480aae24a 100644 --- a/Dalamud/Game/Text/SeStringHandling/Payloads/UIGlowPayload.cs +++ b/Dalamud/Game/Text/SeStringHandling/Payloads/UIGlowPayload.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.IO; -using Dalamud.Data; using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; @@ -21,11 +20,9 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Initializes a new instance of the class. /// Creates a new UIForegroundPayload for the given UIColor key. /// - /// DataManager instance needed to resolve game data. /// A UIColor key. - public UIGlowPayload(DataManager data, ushort colorKey) + public UIGlowPayload(ushort colorKey) { - this.DataResolver = data; this.colorKey = colorKey; } @@ -41,7 +38,7 @@ namespace Dalamud.Game.Text.SeStringHandling.Payloads /// Gets a payload representing disabling glow color on following text. /// // TODO Make this work with DI - public static UIGlowPayload UIGlowOff => new(null, 0); + public static UIGlowPayload UIGlowOff => new(0); /// public override PayloadType Type => PayloadType.UIGlow; diff --git a/Dalamud/Game/Text/SeStringHandling/SeString.cs b/Dalamud/Game/Text/SeStringHandling/SeString.cs index 0e8fe1ff3..6b571b8e9 100644 --- a/Dalamud/Game/Text/SeStringHandling/SeString.cs +++ b/Dalamud/Game/Text/SeStringHandling/SeString.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using Dalamud.Data; using Dalamud.Game.Text.SeStringHandling.Payloads; using Newtonsoft.Json; @@ -76,9 +75,8 @@ namespace Dalamud.Game.Text.SeStringHandling /// Creates a SeString from a json. (For testing - not recommended for production use.) /// /// A serialized SeString produced by ToJson() . - /// An initialized instance of DataManager for Lumina queries. /// A SeString initialized with values from the json. - public static SeString FromJson(string json, DataManager dataManager) + public static SeString FromJson(string json) { var s = JsonConvert.DeserializeObject(json, new JsonSerializerSettings { @@ -87,11 +85,6 @@ namespace Dalamud.Game.Text.SeStringHandling ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, }); - foreach (var payload in s.Payloads) - { - payload.DataResolver = dataManager; - } - return s; } diff --git a/Dalamud/Game/Text/SeStringHandling/SeStringManager.cs b/Dalamud/Game/Text/SeStringHandling/SeStringManager.cs index ad805f528..f5219e361 100644 --- a/Dalamud/Game/Text/SeStringHandling/SeStringManager.cs +++ b/Dalamud/Game/Text/SeStringHandling/SeStringManager.cs @@ -4,6 +4,8 @@ using System.Linq; using Dalamud.Data; using Dalamud.Game.Text.SeStringHandling.Payloads; +using Dalamud.IoC; +using Dalamud.IoC.Internal; using Lumina.Excel.GeneratedSheets; namespace Dalamud.Game.Text.SeStringHandling @@ -11,17 +13,15 @@ namespace Dalamud.Game.Text.SeStringHandling /// /// This class facilitates creating new SeStrings and breaking down existing ones into their individual payload components. /// - public class SeStringManager + [PluginInterface] + [InterfaceVersion("1.0")] + public sealed class SeStringManager { - private readonly DataManager data; - /// /// Initializes a new instance of the class. /// - /// The DataManager instance. - public SeStringManager(DataManager data) + internal SeStringManager() { - this.data = data; } /// @@ -38,7 +38,7 @@ namespace Dalamud.Game.Text.SeStringHandling { while (stream.Position < bytes.Length) { - var payload = Payload.Decode(reader, this.data); + var payload = Payload.Decode(reader); if (payload != null) payloads.Add(payload); } @@ -56,7 +56,9 @@ namespace Dalamud.Game.Text.SeStringHandling /// An SeString containing all the payloads necessary to display an item link in the chat log. public SeString CreateItemLink(uint itemId, bool isHQ, string displayNameOverride = null) { - var displayName = displayNameOverride ?? this.data.GetExcelSheet().GetRow(itemId).Name; + var data = Service.Get(); + + var displayName = displayNameOverride ?? data.GetExcelSheet().GetRow(itemId).Name; if (isHQ) { displayName += $" {(char)SeIconChar.HighQuality}"; @@ -65,9 +67,9 @@ namespace Dalamud.Game.Text.SeStringHandling // TODO: probably a cleaner way to build these than doing the bulk+insert var payloads = new List(new Payload[] { - new UIForegroundPayload(this.data, 0x0225), - new UIGlowPayload(this.data, 0x0226), - new ItemPayload(this.data, itemId, isHQ), + new UIForegroundPayload(0x0225), + new UIGlowPayload(0x0226), + new ItemPayload(itemId, isHQ), // arrow goes here new TextPayload(displayName), RawPayload.LinkTerminator, @@ -101,7 +103,7 @@ namespace Dalamud.Game.Text.SeStringHandling /// An SeString containing all of the payloads necessary to display a map link in the chat log. public SeString CreateMapLink(uint territoryId, uint mapId, int rawX, int rawY) { - var mapPayload = new MapLinkPayload(this.data, territoryId, mapId, rawX, rawY); + var mapPayload = new MapLinkPayload(territoryId, mapId, rawX, rawY); var nameString = $"{mapPayload.PlaceName} {mapPayload.CoordinateString}"; var payloads = new List(new Payload[] @@ -127,7 +129,7 @@ namespace Dalamud.Game.Text.SeStringHandling /// An SeString containing all of the payloads necessary to display a map link in the chat log. public SeString CreateMapLink(uint territoryId, uint mapId, float xCoord, float yCoord, float fudgeFactor = 0.05f) { - var mapPayload = new MapLinkPayload(this.data, territoryId, mapId, xCoord, yCoord, fudgeFactor); + var mapPayload = new MapLinkPayload(territoryId, mapId, xCoord, yCoord, fudgeFactor); var nameString = $"{mapPayload.PlaceName} {mapPayload.CoordinateString}"; var payloads = new List(new Payload[] @@ -152,9 +154,11 @@ namespace Dalamud.Game.Text.SeStringHandling /// An SeString containing all of the payloads necessary to display a map link in the chat log. public SeString CreateMapLink(string placeName, float xCoord, float yCoord, float fudgeFactor = 0.05f) { - var mapSheet = this.data.GetExcelSheet(); + var data = Service.Get(); - var matches = this.data.GetExcelSheet() + var mapSheet = data.GetExcelSheet(); + + var matches = data.GetExcelSheet() .Where(row => row.Name.ToString().ToLowerInvariant() == placeName.ToLowerInvariant()) .ToArray(); @@ -180,8 +184,8 @@ namespace Dalamud.Game.Text.SeStringHandling { return new List(new Payload[] { - new UIForegroundPayload(this.data, 0x01F4), - new UIGlowPayload(this.data, 0x01F5), + new UIForegroundPayload(0x01F4), + new UIGlowPayload(0x01F5), new TextPayload($"{(char)SeIconChar.LinkMarker}"), UIGlowPayload.UIGlowOff, UIForegroundPayload.UIForegroundOff, diff --git a/Dalamud/Hooking/Internal/HookManager.cs b/Dalamud/Hooking/Internal/HookManager.cs index ecf03f1af..60ea3ef3a 100644 --- a/Dalamud/Hooking/Internal/HookManager.cs +++ b/Dalamud/Hooking/Internal/HookManager.cs @@ -19,10 +19,8 @@ namespace Dalamud.Hooking.Internal /// /// Initializes a new instance of the class. /// - /// Dalamud instance. - internal HookManager(Dalamud dalamud) + public HookManager() { - _ = dalamud; } /// diff --git a/Dalamud/Interface/Internal/DalamudCommands.cs b/Dalamud/Interface/Internal/DalamudCommands.cs index f3a895ff3..0300885bb 100644 --- a/Dalamud/Interface/Internal/DalamudCommands.cs +++ b/Dalamud/Interface/Internal/DalamudCommands.cs @@ -4,7 +4,11 @@ using System.Diagnostics; using System.Linq; using CheapLoc; +using Dalamud.Configuration.Internal; +using Dalamud.Game; using Dalamud.Game.Command; +using Dalamud.Game.Gui; +using Dalamud.Plugin.Internal; using Serilog; namespace Dalamud.Interface.Internal @@ -14,15 +18,11 @@ namespace Dalamud.Interface.Internal /// internal class DalamudCommands { - private readonly Dalamud dalamud; - /// /// Initializes a new instance of the class. /// - /// The Dalamud instance to register to. - public DalamudCommands(Dalamud dalamud) + public DalamudCommands() { - this.dalamud = dalamud; } /// @@ -30,83 +30,85 @@ namespace Dalamud.Interface.Internal /// public void SetupCommands() { - this.dalamud.CommandManager.AddHandler("/xldclose", new CommandInfo(this.OnUnloadCommand) + var commandManager = Service.Get(); + + commandManager.AddHandler("/xldclose", new CommandInfo(this.OnUnloadCommand) { HelpMessage = Loc.Localize("DalamudUnloadHelp", "Unloads XIVLauncher in-game addon."), ShowInHelp = false, }); - this.dalamud.CommandManager.AddHandler("/xldreloadplugins", new CommandInfo(this.OnPluginReloadCommand) + commandManager.AddHandler("/xldreloadplugins", new CommandInfo(this.OnPluginReloadCommand) { HelpMessage = Loc.Localize("DalamudPluginReloadHelp", "Reloads all plugins."), ShowInHelp = false, }); - this.dalamud.CommandManager.AddHandler("/xlhelp", new CommandInfo(this.OnHelpCommand) + commandManager.AddHandler("/xlhelp", new CommandInfo(this.OnHelpCommand) { HelpMessage = Loc.Localize("DalamudCmdInfoHelp", "Shows list of commands available."), }); - this.dalamud.CommandManager.AddHandler("/xlmute", new CommandInfo(this.OnBadWordsAddCommand) + commandManager.AddHandler("/xlmute", new CommandInfo(this.OnBadWordsAddCommand) { HelpMessage = Loc.Localize("DalamudMuteHelp", "Mute a word or sentence from appearing in chat. Usage: /xlmute "), }); - this.dalamud.CommandManager.AddHandler("/xlmutelist", new CommandInfo(this.OnBadWordsListCommand) + commandManager.AddHandler("/xlmutelist", new CommandInfo(this.OnBadWordsListCommand) { HelpMessage = Loc.Localize("DalamudMuteListHelp", "List muted words or sentences."), }); - this.dalamud.CommandManager.AddHandler("/xlunmute", new CommandInfo(this.OnBadWordsRemoveCommand) + commandManager.AddHandler("/xlunmute", new CommandInfo(this.OnBadWordsRemoveCommand) { HelpMessage = Loc.Localize("DalamudUnmuteHelp", "Unmute a word or sentence. Usage: /xlunmute "), }); - this.dalamud.CommandManager.AddHandler("/ll", new CommandInfo(this.OnLastLinkCommand) + commandManager.AddHandler("/ll", new CommandInfo(this.OnLastLinkCommand) { HelpMessage = Loc.Localize("DalamudLastLinkHelp", "Open the last posted link in your default browser."), }); - this.dalamud.CommandManager.AddHandler("/xlbgmset", new CommandInfo(this.OnBgmSetCommand) + commandManager.AddHandler("/xlbgmset", new CommandInfo(this.OnBgmSetCommand) { HelpMessage = Loc.Localize("DalamudBgmSetHelp", "Set the Game background music. Usage: /xlbgmset "), }); - this.dalamud.CommandManager.AddHandler("/xldev", new CommandInfo(this.OnDebugDrawDevMenu) + commandManager.AddHandler("/xldev", new CommandInfo(this.OnDebugDrawDevMenu) { HelpMessage = Loc.Localize("DalamudDevMenuHelp", "Draw dev menu DEBUG"), ShowInHelp = false, }); - this.dalamud.CommandManager.AddHandler("/xldata", new CommandInfo(this.OnDebugDrawDataMenu) + commandManager.AddHandler("/xldata", new CommandInfo(this.OnDebugDrawDataMenu) { HelpMessage = Loc.Localize("DalamudDevDataMenuHelp", "Draw dev data menu DEBUG. Usage: /xldata [Data Dropdown Type]"), ShowInHelp = false, }); - this.dalamud.CommandManager.AddHandler("/xlime", new CommandInfo(this.OnDebugDrawIMEPanel) + commandManager.AddHandler("/xlime", new CommandInfo(this.OnDebugDrawIMEPanel) { HelpMessage = Loc.Localize("DalamudIMEPanelHelp", "Draw IME panel"), ShowInHelp = false, }); - this.dalamud.CommandManager.AddHandler("/xllog", new CommandInfo(this.OnOpenLog) + commandManager.AddHandler("/xllog", new CommandInfo(this.OnOpenLog) { HelpMessage = Loc.Localize("DalamudDevLogHelp", "Open dev log DEBUG"), ShowInHelp = false, }); - this.dalamud.CommandManager.AddHandler("/xlplugins", new CommandInfo(this.OnOpenInstallerCommand) + commandManager.AddHandler("/xlplugins", new CommandInfo(this.OnOpenInstallerCommand) { HelpMessage = Loc.Localize("DalamudInstallerHelp", "Open the plugin installer"), }); - this.dalamud.CommandManager.AddHandler("/xlcredits", new CommandInfo(this.OnOpenCreditsCommand) + commandManager.AddHandler("/xlcredits", new CommandInfo(this.OnOpenCreditsCommand) { HelpMessage = Loc.Localize("DalamudCreditsHelp", "Opens the credits for dalamud."), }); - this.dalamud.CommandManager.AddHandler("/xllanguage", new CommandInfo(this.OnSetLanguageCommand) + commandManager.AddHandler("/xllanguage", new CommandInfo(this.OnSetLanguageCommand) { HelpMessage = Loc.Localize( @@ -115,14 +117,14 @@ namespace Dalamud.Interface.Internal Localization.ApplicableLangCodes.Aggregate("en", (current, code) => current + ", " + code), }); - this.dalamud.CommandManager.AddHandler("/xlsettings", new CommandInfo(this.OnOpenSettingsCommand) + commandManager.AddHandler("/xlsettings", new CommandInfo(this.OnOpenSettingsCommand) { HelpMessage = Loc.Localize( "DalamudSettingsHelp", "Change various In-Game-Addon settings like chat channels and the discord bot setup."), }); - this.dalamud.CommandManager.AddHandler("/imdebug", new CommandInfo(this.OnDebugImInfoCommand) + commandManager.AddHandler("/imdebug", new CommandInfo(this.OnDebugImInfoCommand) { HelpMessage = "ImGui DEBUG", ShowInHelp = false, @@ -131,139 +133,159 @@ namespace Dalamud.Interface.Internal private void OnUnloadCommand(string command, string arguments) { - this.dalamud.Framework.Gui.Chat.Print("Unloading..."); - this.dalamud.Unload(); + Service.Get().Print("Unloading..."); + Service.Get().Unload(); } private void OnHelpCommand(string command, string arguments) { + var chatGui = Service.Get(); + var commandManager = Service.Get(); + var showDebug = arguments.Contains("debug"); - this.dalamud.Framework.Gui.Chat.Print(Loc.Localize("DalamudCmdHelpAvailable", "Available commands:")); - foreach (var cmd in this.dalamud.CommandManager.Commands) + chatGui.Print(Loc.Localize("DalamudCmdHelpAvailable", "Available commands:")); + foreach (var cmd in commandManager.Commands) { if (!cmd.Value.ShowInHelp && !showDebug) continue; - this.dalamud.Framework.Gui.Chat.Print($"{cmd.Key}: {cmd.Value.HelpMessage}"); + chatGui.Print($"{cmd.Key}: {cmd.Value.HelpMessage}"); } } private void OnPluginReloadCommand(string command, string arguments) { - this.dalamud.Framework.Gui.Chat.Print("Reloading..."); + var chatGui = Service.Get(); + + chatGui.Print("Reloading..."); try { - this.dalamud.PluginManager.ReloadAllPlugins(); - - this.dalamud.Framework.Gui.Chat.Print("OK"); + Service.Get().ReloadAllPlugins(); + chatGui.Print("OK"); } catch (Exception ex) { - this.dalamud.Framework.Gui.Chat.PrintError("Reload failed."); Log.Error(ex, "Plugin reload failed."); + chatGui.PrintError("Reload failed."); } } private void OnBadWordsAddCommand(string command, string arguments) { - this.dalamud.Configuration.BadWords ??= new List(); + var chatGui = Service.Get(); + var configuration = Service.Get(); + + configuration.BadWords ??= new List(); if (string.IsNullOrEmpty(arguments)) { - this.dalamud.Framework.Gui.Chat.Print( - Loc.Localize("DalamudMuteNoArgs", "Please provide a word to mute.")); + chatGui.Print(Loc.Localize("DalamudMuteNoArgs", "Please provide a word to mute.")); return; } - this.dalamud.Configuration.BadWords.Add(arguments); + configuration.BadWords.Add(arguments); - this.dalamud.Configuration.Save(); + configuration.Save(); - this.dalamud.Framework.Gui.Chat.Print( - string.Format(Loc.Localize("DalamudMuted", "Muted \"{0}\"."), arguments)); + chatGui.Print(string.Format(Loc.Localize("DalamudMuted", "Muted \"{0}\"."), arguments)); } private void OnBadWordsListCommand(string command, string arguments) { - this.dalamud.Configuration.BadWords ??= new List(); + var chatGui = Service.Get(); + var configuration = Service.Get(); - if (this.dalamud.Configuration.BadWords.Count == 0) + configuration.BadWords ??= new List(); + + if (configuration.BadWords.Count == 0) { - this.dalamud.Framework.Gui.Chat.Print(Loc.Localize("DalamudNoneMuted", "No muted words or sentences.")); + chatGui.Print(Loc.Localize("DalamudNoneMuted", "No muted words or sentences.")); return; } - this.dalamud.Configuration.Save(); + configuration.Save(); - foreach (var word in this.dalamud.Configuration.BadWords) - this.dalamud.Framework.Gui.Chat.Print($"\"{word}\""); + foreach (var word in configuration.BadWords) + chatGui.Print($"\"{word}\""); } private void OnBadWordsRemoveCommand(string command, string arguments) { - this.dalamud.Configuration.BadWords ??= new List(); + var chatGui = Service.Get(); + var configuration = Service.Get(); - this.dalamud.Configuration.BadWords.RemoveAll(x => x == arguments); + configuration.BadWords ??= new List(); - this.dalamud.Configuration.Save(); + configuration.BadWords.RemoveAll(x => x == arguments); - this.dalamud.Framework.Gui.Chat.Print( - string.Format(Loc.Localize("DalamudUnmuted", "Unmuted \"{0}\"."), arguments)); + configuration.Save(); + + chatGui.Print(string.Format(Loc.Localize("DalamudUnmuted", "Unmuted \"{0}\"."), arguments)); } private void OnLastLinkCommand(string command, string arguments) { - if (string.IsNullOrEmpty(this.dalamud.ChatHandlers.LastLink)) + var chatHandlers = Service.Get(); + var chatGui = Service.Get(); + + if (string.IsNullOrEmpty(chatHandlers.LastLink)) { - this.dalamud.Framework.Gui.Chat.Print(Loc.Localize("DalamudNoLastLink", "No last link...")); + chatGui.Print(Loc.Localize("DalamudNoLastLink", "No last link...")); return; } - this.dalamud.Framework.Gui.Chat.Print(string.Format(Loc.Localize("DalamudOpeningLink", "Opening {0}"), this.dalamud.ChatHandlers.LastLink)); - Process.Start(this.dalamud.ChatHandlers.LastLink); + chatGui.Print(string.Format(Loc.Localize("DalamudOpeningLink", "Opening {0}"), chatHandlers.LastLink)); + Process.Start(new ProcessStartInfo(chatHandlers.LastLink) + { + UseShellExecute = true, + }); } private void OnBgmSetCommand(string command, string arguments) { + var gameGui = Service.Get(); + if (ushort.TryParse(arguments, out var value)) { - this.dalamud.Framework.Gui.SetBgm(value); + gameGui.SetBgm(value); } else { // Revert to the original BGM by specifying an invalid one - this.dalamud.Framework.Gui.SetBgm(9999); + gameGui.SetBgm(9999); } } private void OnDebugDrawDevMenu(string command, string arguments) { - this.dalamud.DalamudUi.ToggleDevMenu(); + Service.Get().ToggleDevMenu(); } private void OnDebugDrawDataMenu(string command, string arguments) { + var dalamudInterface = Service.Get(); + if (string.IsNullOrEmpty(arguments)) - this.dalamud.DalamudUi.ToggleDataWindow(); + dalamudInterface.ToggleDataWindow(); else - this.dalamud.DalamudUi.OpenDataWindow(arguments); + dalamudInterface.ToggleDataWindow(arguments); } private void OnDebugDrawIMEPanel(string command, string arguments) { - this.dalamud.DalamudUi.OpenIMEWindow(); + Service.Get().OpenIMEWindow(); } private void OnOpenLog(string command, string arguments) { - this.dalamud.DalamudUi.ToggleLogWindow(); + Service.Get().ToggleLogWindow(); } private void OnDebugImInfoCommand(string command, string arguments) { - var io = this.dalamud.InterfaceManager.LastImGuiIoPtr; + var io = Service.Get().LastImGuiIoPtr; var info = $"WantCaptureKeyboard: {io.WantCaptureKeyboard}\n"; info += $"WantCaptureMouse: {io.WantCaptureMouse}\n"; info += $"WantSetMousePos: {io.WantSetMousePos}\n"; @@ -286,39 +308,41 @@ namespace Dalamud.Interface.Internal private void OnOpenInstallerCommand(string command, string arguments) { - this.dalamud.DalamudUi.TogglePluginInstallerWindow(); + Service.Get().TogglePluginInstallerWindow(); } private void OnOpenCreditsCommand(string command, string arguments) { - this.dalamud.DalamudUi.ToggleCreditsWindow(); + Service.Get().ToggleCreditsWindow(); } private void OnSetLanguageCommand(string command, string arguments) { + var chatGui = Service.Get(); + var configuration = Service.Get(); + var localization = Service.Get(); + if (Localization.ApplicableLangCodes.Contains(arguments.ToLower()) || arguments.ToLower() == "en") { - this.dalamud.LocalizationManager.SetupWithLangCode(arguments.ToLower()); - this.dalamud.Configuration.LanguageOverride = arguments.ToLower(); + localization.SetupWithLangCode(arguments.ToLower()); + configuration.LanguageOverride = arguments.ToLower(); - this.dalamud.Framework.Gui.Chat.Print( - string.Format(Loc.Localize("DalamudLanguageSetTo", "Language set to {0}"), arguments)); + chatGui.Print(string.Format(Loc.Localize("DalamudLanguageSetTo", "Language set to {0}"), arguments)); } else { - this.dalamud.LocalizationManager.SetupWithUiCulture(); - this.dalamud.Configuration.LanguageOverride = null; + localization.SetupWithUiCulture(); + configuration.LanguageOverride = null; - this.dalamud.Framework.Gui.Chat.Print( - string.Format(Loc.Localize("DalamudLanguageSetTo", "Language set to {0}"), "default")); + chatGui.Print(string.Format(Loc.Localize("DalamudLanguageSetTo", "Language set to {0}"), "default")); } - this.dalamud.Configuration.Save(); + configuration.Save(); } private void OnOpenSettingsCommand(string command, string arguments) { - this.dalamud.DalamudUi.ToggleSettingsWindow(); + Service.Get().ToggleSettingsWindow(); } } } diff --git a/Dalamud/Interface/Internal/DalamudInterface.cs b/Dalamud/Interface/Internal/DalamudInterface.cs index c782fe44e..9dfa550a0 100644 --- a/Dalamud/Interface/Internal/DalamudInterface.cs +++ b/Dalamud/Interface/Internal/DalamudInterface.cs @@ -4,6 +4,10 @@ using System.Linq; using System.Numerics; using System.Runtime.InteropServices; +using Dalamud.Configuration.Internal; +using Dalamud.Game.ClientState.Conditions; +using Dalamud.Game.Gui; +using Dalamud.Game.Internal; using Dalamud.Interface.Internal.Windows; using Dalamud.Interface.Internal.Windows.SelfTest; using Dalamud.Interface.Windowing; @@ -24,7 +28,6 @@ namespace Dalamud.Interface.Internal { private static readonly ModuleLog Log = new("DUI"); - private readonly Dalamud dalamud; private readonly WindowSystem windowSystem; private readonly ChangelogWindow changelogWindow; @@ -54,25 +57,25 @@ namespace Dalamud.Interface.Internal /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public DalamudInterface(Dalamud dalamud) + public DalamudInterface() { - this.dalamud = dalamud; + var configuration = Service.Get(); + this.windowSystem = new WindowSystem("DalamudCore"); - this.changelogWindow = new ChangelogWindow(dalamud) { IsOpen = false }; + this.changelogWindow = new ChangelogWindow() { IsOpen = false }; this.colorDemoWindow = new ColorDemoWindow() { IsOpen = false }; this.componentDemoWindow = new ComponentDemoWindow() { IsOpen = false }; - this.creditsWindow = new CreditsWindow(dalamud) { IsOpen = false }; - this.dataWindow = new DataWindow(dalamud) { IsOpen = false }; - this.gamepadModeNotifierWindow = new GamepadModeNotifierWindow(); - this.imeWindow = new IMEWindow(dalamud); - this.consoleWindow = new ConsoleWindow(dalamud) { IsOpen = this.dalamud.Configuration.LogOpenAtStartup }; - this.pluginStatWindow = new PluginStatWindow(dalamud) { IsOpen = false }; - this.pluginWindow = new PluginInstallerWindow(dalamud) { IsOpen = false }; - this.scratchpadWindow = new ScratchpadWindow(dalamud) { IsOpen = false }; - this.settingsWindow = new SettingsWindow(dalamud) { IsOpen = false }; - this.selfTestWindow = new SelfTestWindow(dalamud) { IsOpen = false }; + this.creditsWindow = new CreditsWindow() { IsOpen = false }; + this.dataWindow = new DataWindow() { IsOpen = false }; + this.gamepadModeNotifierWindow = new GamepadModeNotifierWindow() { IsOpen = false }; + this.imeWindow = new IMEWindow() { IsOpen = false }; + this.consoleWindow = new ConsoleWindow() { IsOpen = configuration.LogOpenAtStartup }; + this.pluginStatWindow = new PluginStatWindow() { IsOpen = false }; + this.pluginWindow = new PluginInstallerWindow() { IsOpen = false }; + this.scratchpadWindow = new ScratchpadWindow() { IsOpen = false }; + this.settingsWindow = new SettingsWindow() { IsOpen = false }; + this.selfTestWindow = new SelfTestWindow() { IsOpen = false }; this.windowSystem.AddWindow(this.changelogWindow); this.windowSystem.AddWindow(this.colorDemoWindow); @@ -90,7 +93,7 @@ namespace Dalamud.Interface.Internal ImGuiManagedAsserts.EnableAsserts = true; - this.dalamud.InterfaceManager.Draw += this.OnDraw; + Service.Get().Draw += this.OnDraw; Log.Information("Windows added"); } @@ -112,7 +115,7 @@ namespace Dalamud.Interface.Internal /// public void Dispose() { - this.dalamud.InterfaceManager.Draw -= this.OnDraw; + Service.Get().Draw -= this.OnDraw; this.windowSystem.RemoveAllWindows(); @@ -303,7 +306,7 @@ namespace Dalamud.Interface.Internal this.DrawHiddenDevMenuOpener(); this.DrawDevMenu(); - if (this.dalamud.Framework.Gui.GameUiHidden) + if (Service.Get().GameUiHidden) return; this.windowSystem.Draw(); @@ -319,7 +322,9 @@ namespace Dalamud.Interface.Internal private void DrawHiddenDevMenuOpener() { - if (!this.isImGuiDrawDevMenu && !this.dalamud.ClientState.Condition.Any()) + var condition = Service.Get(); + + if (!this.isImGuiDrawDevMenu && !condition.Any()) { ImGui.PushStyleColor(ImGuiCol.Button, Vector4.Zero); ImGui.PushStyleColor(ImGuiCol.ButtonActive, Vector4.Zero); @@ -352,6 +357,10 @@ namespace Dalamud.Interface.Internal { if (ImGui.BeginMainMenuBar()) { + var dalamud = Service.Get(); + var configuration = Service.Get(); + var pluginManager = Service.Get(); + if (ImGui.BeginMenu("Dalamud")) { ImGui.MenuItem("Draw Dalamud dev menu", string.Empty, ref this.isImGuiDrawDevMenu); @@ -367,27 +376,28 @@ namespace Dalamud.Interface.Internal { foreach (var logLevel in Enum.GetValues(typeof(LogEventLevel)).Cast()) { - if (ImGui.MenuItem(logLevel + "##logLevelSwitch", string.Empty, this.dalamud.LogLevelSwitch.MinimumLevel == logLevel)) + if (ImGui.MenuItem(logLevel + "##logLevelSwitch", string.Empty, dalamud.LogLevelSwitch.MinimumLevel == logLevel)) { - this.dalamud.LogLevelSwitch.MinimumLevel = logLevel; - this.dalamud.Configuration.LogLevel = logLevel; - this.dalamud.Configuration.Save(); + dalamud.LogLevelSwitch.MinimumLevel = logLevel; + configuration.LogLevel = logLevel; + configuration.Save(); } } ImGui.EndMenu(); } - if (ImGui.MenuItem("Enable AntiDebug", null, this.dalamud.AntiDebug.IsEnabled)) + var antiDebug = Service.Get(); + if (ImGui.MenuItem("Enable AntiDebug", null, antiDebug.IsEnabled)) { - var newEnabled = !this.dalamud.AntiDebug.IsEnabled; + var newEnabled = !antiDebug.IsEnabled; if (newEnabled) - this.dalamud.AntiDebug.Enable(); + antiDebug.Enable(); else - this.dalamud.AntiDebug.Disable(); + antiDebug.Disable(); - this.dalamud.Configuration.IsAntiAntiDebugEnabled = newEnabled; - this.dalamud.Configuration.Save(); + configuration.IsAntiAntiDebugEnabled = newEnabled; + configuration.Save(); } ImGui.Separator(); @@ -431,7 +441,7 @@ namespace Dalamud.Interface.Internal if (ImGui.MenuItem("Unload Dalamud")) { - this.dalamud.Unload(); + Service.Get().Unload(); } if (ImGui.MenuItem("Kill game")) @@ -445,14 +455,15 @@ namespace Dalamud.Interface.Internal } ImGui.Separator(); - if (ImGui.MenuItem("Enable Dalamud testing", string.Empty, this.dalamud.Configuration.DoDalamudTest)) + if (ImGui.MenuItem("Enable Dalamud testing", string.Empty, configuration.DoDalamudTest)) { - this.dalamud.Configuration.DoDalamudTest ^= true; - this.dalamud.Configuration.Save(); + configuration.DoDalamudTest ^= true; + configuration.Save(); } + var startInfo = Service.Get(); ImGui.MenuItem(Util.AssemblyVersion, false); - ImGui.MenuItem(this.dalamud.StartInfo.GameVersion.ToString(), false); + ImGui.MenuItem(startInfo.GameVersion.ToString(), false); ImGui.EndMenu(); } @@ -472,7 +483,7 @@ namespace Dalamud.Interface.Internal { if (ImGui.MenuItem("Replace ExceptionHandler")) { - this.dalamud.ReplaceExceptionHandler(); + dalamud.ReplaceExceptionHandler(); } ImGui.EndMenu(); @@ -494,7 +505,7 @@ namespace Dalamud.Interface.Internal if (ImGui.MenuItem("Print plugin info")) { - foreach (var plugin in this.dalamud.PluginManager.InstalledPlugins) + foreach (var plugin in pluginManager.InstalledPlugins) { // TODO: some more here, state maybe? PluginLog.Information($"{plugin.Name}"); @@ -505,31 +516,31 @@ namespace Dalamud.Interface.Internal { try { - this.dalamud.PluginManager.ReloadAllPlugins(); + pluginManager.ReloadAllPlugins(); } catch (Exception ex) { - this.dalamud.Framework.Gui.Chat.PrintError("Reload failed."); + Service.Get().PrintError("Reload failed."); PluginLog.Error(ex, "Plugin reload failed."); } } if (ImGui.MenuItem("Scan dev plugins")) { - this.dalamud.PluginManager.ScanDevPlugins(); + pluginManager.ScanDevPlugins(); } ImGui.Separator(); - if (ImGui.MenuItem("Load all API levels", null, this.dalamud.Configuration.LoadAllApiLevels)) + if (ImGui.MenuItem("Load all API levels", null, configuration.LoadAllApiLevels)) { - this.dalamud.Configuration.LoadAllApiLevels = !this.dalamud.Configuration.LoadAllApiLevels; - this.dalamud.Configuration.Save(); + configuration.LoadAllApiLevels = !configuration.LoadAllApiLevels; + configuration.Save(); } ImGui.Separator(); ImGui.MenuItem("API Level:" + PluginManager.DalamudApiLevel, false); - ImGui.MenuItem("Loaded plugins:" + this.dalamud.PluginManager?.InstalledPlugins.Count, false); + ImGui.MenuItem("Loaded plugins:" + pluginManager.InstalledPlugins.Count, false); ImGui.EndMenu(); } @@ -550,28 +561,30 @@ namespace Dalamud.Interface.Internal if (ImGui.BeginMenu("Localization")) { + var localization = Service.Get(); + if (ImGui.MenuItem("Export localizable")) { - this.dalamud.LocalizationManager.ExportLocalizable(); + localization.ExportLocalizable(); } if (ImGui.BeginMenu("Load language...")) { if (ImGui.MenuItem("From Fallbacks")) { - this.dalamud.LocalizationManager.SetupWithFallbacks(); + localization.SetupWithFallbacks(); } if (ImGui.MenuItem("From UICulture")) { - this.dalamud.LocalizationManager.SetupWithUiCulture(); + localization.SetupWithUiCulture(); } foreach (var applicableLangCode in Localization.ApplicableLangCodes) { if (ImGui.MenuItem($"Applicable: {applicableLangCode}")) { - this.dalamud.LocalizationManager.SetupWithLangCode(applicableLangCode); + localization.SetupWithLangCode(applicableLangCode); } } @@ -581,7 +594,7 @@ namespace Dalamud.Interface.Internal ImGui.EndMenu(); } - if (this.dalamud.Framework.Gui.GameUiHidden) + if (Service.Get().GameUiHidden) ImGui.BeginMenu("UI is hidden...", false); ImGui.BeginMenu(Util.GetGitHash(), false); diff --git a/Dalamud/Interface/Internal/InterfaceManager.cs b/Dalamud/Interface/Internal/InterfaceManager.cs index 3c8f63f25..146a89a50 100644 --- a/Dalamud/Interface/Internal/InterfaceManager.cs +++ b/Dalamud/Interface/Internal/InterfaceManager.cs @@ -7,8 +7,11 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Dalamud.Configuration.Internal; using Dalamud.Game; using Dalamud.Game.ClientState.GamePad; +using Dalamud.Game.ClientState.Keys; +using Dalamud.Game.Gui.Internal; using Dalamud.Game.Internal.DXGI; using Dalamud.Hooking; using Dalamud.Hooking.Internal; @@ -36,7 +39,6 @@ namespace Dalamud.Interface.Internal /// internal class InterfaceManager : IDisposable { - private readonly Dalamud dalamud; private readonly string rtssPath; private readonly Hook presentHook; @@ -54,11 +56,11 @@ namespace Dalamud.Interface.Internal /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - /// The SigScanner instance. - public InterfaceManager(Dalamud dalamud, SigScanner scanner) + public InterfaceManager() { - this.dalamud = dalamud; + Service.Set(); + + var scanner = Service.Get(); this.fontBuildSignal = new ManualResetEvent(false); @@ -341,7 +343,10 @@ namespace Dalamud.Interface.Internal { this.scene = new RawDX11Scene(swapChain); - this.scene.ImGuiIniPath = Path.Combine(Path.GetDirectoryName(this.dalamud.StartInfo.ConfigurationPath), "dalamudUI.ini"); + var startInfo = Service.Get(); + var configuration = Service.Get(); + + this.scene.ImGuiIniPath = Path.Combine(Path.GetDirectoryName(startInfo.ConfigurationPath), "dalamudUI.ini"); this.scene.OnBuildUI += this.Display; this.scene.OnNewInputFrame += this.OnNewInputFrame; @@ -376,9 +381,9 @@ namespace Dalamud.Interface.Internal ImGui.GetStyle().Colors[(int)ImGuiCol.TabActive] = new Vector4(0.36f, 0.36f, 0.36f, 1.00f); ImGui.GetStyle().Colors[(int)ImGuiCol.ScrollbarBg] = Vector4.Zero; - ImGui.GetIO().FontGlobalScale = this.dalamud.Configuration.GlobalUiScale; + ImGui.GetIO().FontGlobalScale = configuration.GlobalUiScale; - if (!this.dalamud.Configuration.IsDocking) + if (!configuration.IsDocking) { ImGui.GetIO().ConfigFlags &= ~ImGuiConfigFlags.DockingEnable; } @@ -388,7 +393,7 @@ namespace Dalamud.Interface.Internal } // NOTE (Chiv) Toggle gamepad navigation via setting - if (!this.dalamud.Configuration.IsGamepadNavigationEnabled) + if (!configuration.IsGamepadNavigationEnabled) { ImGui.GetIO().BackendFlags &= ~ImGuiBackendFlags.HasGamepad; ImGui.GetIO().ConfigFlags &= ~ImGuiConfigFlags.NavEnableSetMousePos; @@ -406,7 +411,7 @@ namespace Dalamud.Interface.Internal Log.Information("[IM] Scene & ImGui setup OK!"); - this.dalamud.IME.Enable(); + Service.Get().Enable(); } // Process information needed by ImGuiHelpers each frame. @@ -422,7 +427,9 @@ namespace Dalamud.Interface.Internal private void CheckViewportState() { - if (this.dalamud.Configuration.IsDisableViewport || this.scene.SwapChain.IsFullScreen || ImGui.GetPlatformIO().Monitors.Size == 1) + var configuration = Service.Get(); + + if (configuration.IsDisableViewport || this.scene.SwapChain.IsFullScreen || ImGui.GetPlatformIO().Monitors.Size == 1) { ImGui.GetIO().ConfigFlags &= ~ImGuiConfigFlags.ViewportsEnable; return; @@ -433,6 +440,8 @@ namespace Dalamud.Interface.Internal private unsafe void SetupFonts() { + var dalamud = Service.Get(); + this.fontBuildSignal.Reset(); ImGui.GetIO().Fonts.Clear(); @@ -441,7 +450,7 @@ namespace Dalamud.Interface.Internal fontConfig.MergeMode = true; fontConfig.PixelSnapH = true; - var fontPathJp = Path.Combine(this.dalamud.AssetDirectory.FullName, "UIRes", "NotoSansCJKjp-Medium.otf"); + var fontPathJp = Path.Combine(dalamud.AssetDirectory.FullName, "UIRes", "NotoSansCJKjp-Medium.otf"); if (!File.Exists(fontPathJp)) ShowFontError(fontPathJp); @@ -450,7 +459,7 @@ namespace Dalamud.Interface.Internal DefaultFont = ImGui.GetIO().Fonts.AddFontFromFileTTF(fontPathJp, 17.0f, null, japaneseRangeHandle.AddrOfPinnedObject()); - var fontPathGame = Path.Combine(this.dalamud.AssetDirectory.FullName, "UIRes", "gamesym.ttf"); + var fontPathGame = Path.Combine(dalamud.AssetDirectory.FullName, "UIRes", "gamesym.ttf"); if (!File.Exists(fontPathGame)) ShowFontError(fontPathGame); @@ -466,7 +475,7 @@ namespace Dalamud.Interface.Internal ImGui.GetIO().Fonts.AddFontFromFileTTF(fontPathGame, 17.0f, fontConfig, gameRangeHandle.AddrOfPinnedObject()); - var fontPathIcon = Path.Combine(this.dalamud.AssetDirectory.FullName, "UIRes", "FontAwesome5FreeSolid.otf"); + var fontPathIcon = Path.Combine(dalamud.AssetDirectory.FullName, "UIRes", "FontAwesome5FreeSolid.otf"); if (!File.Exists(fontPathIcon)) ShowFontError(fontPathIcon); @@ -481,7 +490,7 @@ namespace Dalamud.Interface.Internal GCHandleType.Pinned); IconFont = ImGui.GetIO().Fonts.AddFontFromFileTTF(fontPathIcon, 17.0f, null, iconRangeHandle.AddrOfPinnedObject()); - var fontPathMono = Path.Combine(this.dalamud.AssetDirectory.FullName, "UIRes", "Inconsolata-Regular.ttf"); + var fontPathMono = Path.Combine(dalamud.AssetDirectory.FullName, "UIRes", "Inconsolata-Regular.ttf"); if (!File.Exists(fontPathMono)) ShowFontError(fontPathMono); @@ -567,13 +576,17 @@ namespace Dalamud.Interface.Internal private void OnNewInputFrame() { + var dalamudInterface = Service.GetNullable(); + var gamepadState = Service.GetNullable(); + var keyState = Service.GetNullable(); + // fix for keys in game getting stuck, if you were holding a game key (like run) // and then clicked on an imgui textbox - imgui would swallow the keyup event, // so the game would think the key remained pressed continuously until you left // imgui and pressed and released the key again if (ImGui.GetIO().WantTextInput) { - this.dalamud.ClientState.KeyState.ClearAll(); + keyState.ClearAll(); } // TODO: mouse state? @@ -583,36 +596,36 @@ namespace Dalamud.Interface.Internal // NOTE (Chiv) Activate ImGui navigation via L1+L3 press // (mimicking how mouse navigation is activated via L1+R3 press in game). if (gamepadEnabled - && this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.L1) > 0 - && this.dalamud.ClientState.GamepadState.Pressed(GamepadButtons.L3) > 0) + && gamepadState.Raw(GamepadButtons.L1) > 0 + && gamepadState.Pressed(GamepadButtons.L3) > 0) { ImGui.GetIO().ConfigFlags ^= ImGuiConfigFlags.NavEnableGamepad; - this.dalamud.ClientState.GamepadState.NavEnableGamepad ^= true; - this.dalamud.DalamudUi.ToggleGamepadModeNotifierWindow(); + gamepadState.NavEnableGamepad ^= true; + dalamudInterface.ToggleGamepadModeNotifierWindow(); } if (gamepadEnabled && (ImGui.GetIO().ConfigFlags & ImGuiConfigFlags.NavEnableGamepad) > 0) { - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.Activate] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.South); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.Cancel] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.East); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.Input] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.North); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.Menu] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.West); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.DpadLeft] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.DpadLeft); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.DpadRight] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.DpadRight); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.DpadUp] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.DpadUp); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.DpadDown] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.DpadDown); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.LStickLeft] = this.dalamud.ClientState.GamepadState.LeftStickLeft; - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.LStickRight] = this.dalamud.ClientState.GamepadState.LeftStickRight; - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.LStickUp] = this.dalamud.ClientState.GamepadState.LeftStickUp; - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.LStickDown] = this.dalamud.ClientState.GamepadState.LeftStickDown; - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.FocusPrev] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.L1); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.FocusNext] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.R1); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.TweakSlow] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.L2); - ImGui.GetIO().NavInputs[(int)ImGuiNavInput.TweakFast] = this.dalamud.ClientState.GamepadState.Raw(GamepadButtons.R2); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.Activate] = gamepadState.Raw(GamepadButtons.South); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.Cancel] = gamepadState.Raw(GamepadButtons.East); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.Input] = gamepadState.Raw(GamepadButtons.North); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.Menu] = gamepadState.Raw(GamepadButtons.West); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.DpadLeft] = gamepadState.Raw(GamepadButtons.DpadLeft); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.DpadRight] = gamepadState.Raw(GamepadButtons.DpadRight); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.DpadUp] = gamepadState.Raw(GamepadButtons.DpadUp); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.DpadDown] = gamepadState.Raw(GamepadButtons.DpadDown); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.LStickLeft] = gamepadState.LeftStickLeft; + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.LStickRight] = gamepadState.LeftStickRight; + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.LStickUp] = gamepadState.LeftStickUp; + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.LStickDown] = gamepadState.LeftStickDown; + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.FocusPrev] = gamepadState.Raw(GamepadButtons.L1); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.FocusNext] = gamepadState.Raw(GamepadButtons.R1); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.TweakSlow] = gamepadState.Raw(GamepadButtons.L2); + ImGui.GetIO().NavInputs[(int)ImGuiNavInput.TweakFast] = gamepadState.Raw(GamepadButtons.R2); - if (this.dalamud.ClientState.GamepadState.Pressed(GamepadButtons.R3) > 0) + if (gamepadState.Pressed(GamepadButtons.R3) > 0) { - this.dalamud.DalamudUi.TogglePluginInstallerWindow(); + dalamudInterface.TogglePluginInstallerWindow(); } } } @@ -631,7 +644,7 @@ namespace Dalamud.Interface.Internal this.lastWantCapture = this.LastImGuiIoPtr.WantCaptureMouse; this.Draw?.Invoke(); - this.Notifications.Draw(); + Service.Get().Draw(); } } } diff --git a/Dalamud/Interface/Internal/Notifications.cs b/Dalamud/Interface/Internal/Notifications.cs index 4e64a366b..f685e1ab9 100644 --- a/Dalamud/Interface/Internal/Notifications.cs +++ b/Dalamud/Interface/Internal/Notifications.cs @@ -1,10 +1,9 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Dalamud.Interface.Colors; -using Dalamud.Interface.Internal; using Dalamud.Utility; using ImGuiNET; @@ -62,8 +61,7 @@ namespace Dalamud.Interface.Internal /// The title of the notification. /// The type of the notification. /// The time the notification should be displayed for. - public void AddNotification( - string content, string title = null, Notification.Type type = Notification.Type.None, int msDelay = NotifyDefaultDismiss) + public void AddNotification(string content, string title = null, Notification.Type type = Notification.Type.None, int msDelay = NotifyDefaultDismiss) { this.notifications.Add(new Notification { diff --git a/Dalamud/Interface/Internal/Scratchpad/ScratchExecutionManager.cs b/Dalamud/Interface/Internal/Scratchpad/ScratchExecutionManager.cs index 676a34381..eba0b3d2a 100644 --- a/Dalamud/Interface/Internal/Scratchpad/ScratchExecutionManager.cs +++ b/Dalamud/Interface/Internal/Scratchpad/ScratchExecutionManager.cs @@ -15,16 +15,13 @@ namespace Dalamud.Interface.Internal.Scratchpad /// internal class ScratchExecutionManager { - private readonly Dalamud dalamud; private Dictionary loadedScratches = new(); /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public ScratchExecutionManager(Dalamud dalamud) + public ScratchExecutionManager() { - this.dalamud = dalamud; } /// @@ -82,7 +79,7 @@ namespace Dalamud.Interface.Internal.Scratchpad { var script = CSharpScript.Create(code, options); - var pi = new DalamudPluginInterface(this.dalamud, "Scratch-" + doc.Id, PluginLoadReason.Unknown); + var pi = new DalamudPluginInterface("Scratch-" + doc.Id, PluginLoadReason.Unknown); var plugin = script.ContinueWith("return new ScratchPlugin() as IDalamudPlugin;") .RunAsync().GetAwaiter().GetResult().ReturnValue; diff --git a/Dalamud/Interface/Internal/Scratchpad/ScratchMacroProcessor.cs b/Dalamud/Interface/Internal/Scratchpad/ScratchMacroProcessor.cs index e39741072..0a2e4e8fb 100644 --- a/Dalamud/Interface/Internal/Scratchpad/ScratchMacroProcessor.cs +++ b/Dalamud/Interface/Internal/Scratchpad/ScratchMacroProcessor.cs @@ -25,7 +25,7 @@ public class ScratchPlugin : IDalamudPlugin { { this.pi = pluginInterface; - this.pi.UiBuilder.OnBuildUi += DrawUI; + this.pi.UiBuilder.Draw += DrawUI; {INITBODY} } @@ -39,7 +39,7 @@ public class ScratchPlugin : IDalamudPlugin { public void Dispose() { - this.pi.UiBuilder.OnBuildUi -= DrawUI; + this.pi.UiBuilder.Draw -= DrawUI; {DISPOSEBODY} } } @@ -168,10 +168,8 @@ public class ScratchPlugin : IDalamudPlugin { { var hook = hooks[i]; - hookSetup += - $"private delegate {hook.RetType} Hook{i}Delegate({hook.Arguments});\n"; - hookSetup += - $"private Hook hook{i}Inst;\n"; + hookSetup += $"private delegate {hook.RetType} Hook{i}Delegate({hook.Arguments});\n"; + hookSetup += $"private Hook hook{i}Inst;\n"; hookInit += $"var addrH{i} = pi.TargetModuleScanner.ScanText(\"{hook.Sig}\");\n"; hookInit += $"this.hook{i}Inst = new Hook(addrH{i}, new Hook{i}Delegate(Hook{i}Detour), this);\n"; diff --git a/Dalamud/Interface/Internal/UiDebug.cs b/Dalamud/Interface/Internal/UiDebug.cs index 3a2847b99..e64ec6bc2 100644 --- a/Dalamud/Interface/Internal/UiDebug.cs +++ b/Dalamud/Interface/Internal/UiDebug.cs @@ -6,12 +6,11 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using Dalamud.Game; +using Dalamud.Game.Gui; using FFXIVClientStructs.FFXIV.Component.GUI; -using FFXIVClientStructs.FFXIV.Component.GUI.ULD; using ImGuiNET; -using AlignmentType = FFXIVClientStructs.FFXIV.Component.GUI.AlignmentType; - // Customised version of https://github.com/aers/FFXIVUIDebug namespace Dalamud.Interface.Internal @@ -23,7 +22,6 @@ namespace Dalamud.Interface.Internal { private const int UnitListCount = 18; - private readonly Dalamud dalamud; private readonly GetAtkStageSingleton getAtkStageSingleton; private readonly bool[] selectedInList = new bool[UnitListCount]; private readonly string[] listNames = new string[UnitListCount] @@ -57,11 +55,10 @@ namespace Dalamud.Interface.Internal /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public UIDebug(Dalamud dalamud) + public UIDebug() { - this.dalamud = dalamud; - var getSingletonAddr = dalamud.SigScanner.ScanText("E8 ?? ?? ?? ?? 41 B8 01 00 00 00 48 8D 15 ?? ?? ?? ?? 48 8B 48 20 E8 ?? ?? ?? ?? 48 8B CF"); + var sigScanner = Service.Get(); + var getSingletonAddr = sigScanner.ScanText("E8 ?? ?? ?? ?? 41 B8 01 00 00 00 48 8D 15 ?? ?? ?? ?? 48 8B 48 20 E8 ?? ?? ?? ?? 48 8B CF"); this.getAtkStageSingleton = Marshal.GetDelegateForFunctionPointer(getSingletonAddr); } @@ -108,7 +105,7 @@ namespace Dalamud.Interface.Internal { var isVisible = (atkUnitBase->Flags & 0x20) == 0x20; var addonName = Marshal.PtrToStringAnsi(new IntPtr(atkUnitBase->Name)); - var agent = this.dalamud.Framework.Gui.FindAgentInterface((IntPtr)atkUnitBase); + var agent = Service.Get().FindAgentInterface(atkUnitBase); ImGui.Text($"{addonName}"); ImGui.SameLine(); diff --git a/Dalamud/Interface/Internal/Windows/ChangelogWindow.cs b/Dalamud/Interface/Internal/Windows/ChangelogWindow.cs index 0420fe591..fa1f39b0a 100644 --- a/Dalamud/Interface/Internal/Windows/ChangelogWindow.cs +++ b/Dalamud/Interface/Internal/Windows/ChangelogWindow.cs @@ -22,18 +22,14 @@ namespace Dalamud.Interface.Internal.Windows If you note any issues or need help, please make sure to ask on our discord server."; - private readonly Dalamud dalamud; private readonly string assemblyVersion = Util.AssemblyVersion; /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public ChangelogWindow(Dalamud dalamud) + public ChangelogWindow() : base("What's new in XIVLauncher?", ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoResize) { - this.dalamud = dalamud; - this.Namespace = "DalamudChangelogWindow"; this.IsOpen = WarrantsChangelog; @@ -59,7 +55,7 @@ If you note any issues or need help, please make sure to ask on our discord serv if (ImGui.Button(FontAwesomeIcon.Download.ToIconString())) { - this.dalamud.DalamudUi.OpenPluginInstaller(); + Service.Get().OpenPluginInstaller(); } if (ImGui.IsItemHovered()) diff --git a/Dalamud/Interface/Internal/Windows/ConsoleWindow.cs b/Dalamud/Interface/Internal/Windows/ConsoleWindow.cs index e82200e2d..62caca3af 100644 --- a/Dalamud/Interface/Internal/Windows/ConsoleWindow.cs +++ b/Dalamud/Interface/Internal/Windows/ConsoleWindow.cs @@ -6,6 +6,8 @@ using System.Numerics; using System.Runtime.InteropServices; using System.Text; +using Dalamud.Configuration.Internal; +using Dalamud.Game.Command; using Dalamud.Interface.Colors; using Dalamud.Interface.Components; using Dalamud.Interface.Windowing; @@ -21,8 +23,6 @@ namespace Dalamud.Interface.Internal.Windows /// internal class ConsoleWindow : Window, IDisposable { - private readonly Dalamud dalamud; - private readonly List logText = new(); private readonly object renderLock = new(); @@ -46,14 +46,13 @@ namespace Dalamud.Interface.Internal.Windows /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public ConsoleWindow(Dalamud dalamud) + public ConsoleWindow() : base("Dalamud Console") { - this.dalamud = dalamud; + var configuration = Service.Get(); - this.autoScroll = this.dalamud.Configuration.LogAutoScroll; - this.openAtStartup = this.dalamud.Configuration.LogOpenAtStartup; + this.autoScroll = configuration.LogAutoScroll; + this.openAtStartup = configuration.LogOpenAtStartup; SerilogEventSink.Instance.OnLogLine += this.OnLogLine; this.Size = new Vector2(500, 400); @@ -113,24 +112,27 @@ namespace Dalamud.Interface.Internal.Windows // Options menu if (ImGui.BeginPopup("Options")) { + var dalamud = Service.Get(); + var configuration = Service.Get(); + if (ImGui.Checkbox("Auto-scroll", ref this.autoScroll)) { - this.dalamud.Configuration.LogAutoScroll = this.autoScroll; - this.dalamud.Configuration.Save(); + configuration.LogAutoScroll = this.autoScroll; + configuration.Save(); } if (ImGui.Checkbox("Open at startup", ref this.openAtStartup)) { - this.dalamud.Configuration.LogOpenAtStartup = this.openAtStartup; - this.dalamud.Configuration.Save(); + configuration.LogOpenAtStartup = this.openAtStartup; + configuration.Save(); } - var prevLevel = (int)this.dalamud.LogLevelSwitch.MinimumLevel; + var prevLevel = (int)dalamud.LogLevelSwitch.MinimumLevel; if (ImGui.Combo("Log Level", ref prevLevel, Enum.GetValues(typeof(LogEventLevel)).Cast().Select(x => x.ToString()).ToArray(), 6)) { - this.dalamud.LogLevelSwitch.MinimumLevel = (LogEventLevel)prevLevel; - this.dalamud.Configuration.LogLevel = (LogEventLevel)prevLevel; - this.dalamud.Configuration.Save(); + dalamud.LogLevelSwitch.MinimumLevel = (LogEventLevel)prevLevel; + configuration.LogLevel = (LogEventLevel)prevLevel; + configuration.Save(); } ImGui.EndPopup(); @@ -336,7 +338,7 @@ namespace Dalamud.Interface.Internal.Windows return; } - this.lastCmdSuccess = this.dalamud.CommandManager.ProcessCommand("/" + this.commandText); + this.lastCmdSuccess = Service.Get().ProcessCommand("/" + this.commandText); this.commandText = string.Empty; // TODO: Force scroll to bottom @@ -367,7 +369,7 @@ namespace Dalamud.Interface.Internal.Windows // TODO: Improve this, add partial completion // https://github.com/ocornut/imgui/blob/master/imgui_demo.cpp#L6443-L6484 - var candidates = this.dalamud.CommandManager.Commands.Where(x => x.Key.Contains("/" + words[0])).ToList(); + var candidates = Service.Get().Commands.Where(x => x.Key.Contains("/" + words[0])).ToList(); if (candidates.Count > 0) { ptr.DeleteChars(0, ptr.BufTextLen); diff --git a/Dalamud/Interface/Internal/Windows/CreditsWindow.cs b/Dalamud/Interface/Internal/Windows/CreditsWindow.cs index a307d0161..4eb0e979b 100644 --- a/Dalamud/Interface/Internal/Windows/CreditsWindow.cs +++ b/Dalamud/Interface/Internal/Windows/CreditsWindow.cs @@ -4,7 +4,10 @@ using System.IO; using System.Linq; using System.Numerics; +using Dalamud.Game; +using Dalamud.Game.Gui; using Dalamud.Interface.Windowing; +using Dalamud.Plugin.Internal; using ImGuiNET; using ImGuiScene; @@ -115,7 +118,6 @@ Contribute at: https://github.com/goatsoft/Dalamud Thank you for using XIVLauncher and Dalamud! "; - private readonly Dalamud dalamud; private readonly TextureWrap logoTexture; private readonly Stopwatch creditsThrottler; @@ -124,12 +126,13 @@ Thank you for using XIVLauncher and Dalamud! /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public CreditsWindow(Dalamud dalamud) + public CreditsWindow() : base("Dalamud Credits", ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoResize, true) { - this.dalamud = dalamud; - this.logoTexture = this.dalamud.InterfaceManager.LoadImage(Path.Combine(this.dalamud.AssetDirectory.FullName, "UIRes", "logo.png")); + var dalamud = Service.Get(); + var interfaceManager = Service.Get(); + + this.logoTexture = interfaceManager.LoadImage(Path.Combine(dalamud.AssetDirectory.FullName, "UIRes", "logo.png")); this.creditsThrottler = new(); this.Size = new Vector2(500, 400); @@ -143,14 +146,14 @@ Thank you for using XIVLauncher and Dalamud! /// public override void OnOpen() { - var pluginCredits = this.dalamud.PluginManager.InstalledPlugins + var pluginCredits = Service.Get().InstalledPlugins .Where(plugin => plugin.Manifest != null) .Select(plugin => $"{plugin.Manifest.Name} by {plugin.Manifest.Author}\n") .Aggregate(string.Empty, (current, next) => $"{current}{next}"); this.creditsText = string.Format(CreditsTextTempl, typeof(Dalamud).Assembly.GetName().Version, pluginCredits); - this.dalamud.Framework.Gui.SetBgm(132); + Service.Get().SetBgm(132); this.creditsThrottler.Restart(); } @@ -158,7 +161,7 @@ Thank you for using XIVLauncher and Dalamud! public override void OnClose() { this.creditsThrottler.Reset(); - this.dalamud.Framework.Gui.SetBgm(9999); + Service.Get().SetBgm(9999); } /// diff --git a/Dalamud/Interface/Internal/Windows/DataWindow.cs b/Dalamud/Interface/Internal/Windows/DataWindow.cs index 4105e9894..d49ee8524 100644 --- a/Dalamud/Interface/Internal/Windows/DataWindow.cs +++ b/Dalamud/Interface/Internal/Windows/DataWindow.cs @@ -4,19 +4,29 @@ using System.Dynamic; using System.Linq; using System.Numerics; +using Dalamud.Data; using Dalamud.Game; +using Dalamud.Game.ClientState; +using Dalamud.Game.ClientState.Buddy; using Dalamud.Game.ClientState.Conditions; +using Dalamud.Game.ClientState.Fates; using Dalamud.Game.ClientState.GamePad; +using Dalamud.Game.ClientState.JobGauge; using Dalamud.Game.ClientState.JobGauge.Enums; using Dalamud.Game.ClientState.JobGauge.Types; +using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.SubKinds; using Dalamud.Game.ClientState.Objects.Types; +using Dalamud.Game.ClientState.Party; +using Dalamud.Game.Command; +using Dalamud.Game.Gui; using Dalamud.Game.Gui.FlyText; using Dalamud.Game.Gui.Toast; using Dalamud.Game.Text; using Dalamud.Interface.Windowing; using Dalamud.Memory; using Dalamud.Plugin; +using Dalamud.Plugin.Internal; using Dalamud.Utility; using ImGuiNET; using ImGuiScene; @@ -30,7 +40,6 @@ namespace Dalamud.Interface.Internal.Windows /// internal class DataWindow : Window { - private readonly Dalamud dalamud; private readonly string[] dataKindNames = Enum.GetNames(typeof(DataKind)).Select(k => k.Replace("_", " ")).ToArray(); private bool wasReady; @@ -85,12 +94,9 @@ namespace Dalamud.Interface.Internal.Windows /// /// Initializes a new instance of the class. /// - /// The Dalamud instance to access data of. - public DataWindow(Dalamud dalamud) + public DataWindow() : base("Dalamud Data") { - this.dalamud = dalamud; - this.Size = new Vector2(500, 500); this.SizeCondition = ImGuiCond.FirstUseEver; @@ -160,7 +166,7 @@ namespace Dalamud.Interface.Internal.Windows } else { - this.dalamud.Framework.Gui.Chat.PrintError("/xldata: Invalid Data Type"); + Service.Get().PrintError("/xldata: Invalid Data Type"); } } @@ -307,7 +313,8 @@ namespace Dalamud.Interface.Internal.Windows { try { - this.sigResult = this.dalamud.SigScanner.ScanText(this.inputSig); + var sigScanner = Service.Get(); + this.sigResult = sigScanner.ScanText(this.inputSig); } catch (KeyNotFoundException) { @@ -337,38 +344,44 @@ namespace Dalamud.Interface.Internal.Windows private void DrawObjectTable() { + var chatGui = Service.Get(); + var clientState = Service.Get(); + var framework = Service.Get(); + var gameGui = Service.Get(); + var objectTable = Service.Get(); + var stateString = string.Empty; - if (this.dalamud.ClientState.LocalPlayer == null) + if (clientState.LocalPlayer == null) { ImGui.TextUnformatted("LocalPlayer null."); } else { - stateString += $"FrameworkBase: {this.dalamud.Framework.Address.BaseAddress.ToInt64():X}\n"; - stateString += $"ObjectTableLen: {this.dalamud.ClientState.Objects.Length}\n"; - stateString += $"LocalPlayerName: {this.dalamud.ClientState.LocalPlayer.Name}\n"; - stateString += $"CurrentWorldName: {(this.resolveGameData ? this.dalamud.ClientState.LocalPlayer.CurrentWorld.GameData.Name : this.dalamud.ClientState.LocalPlayer.CurrentWorld.Id.ToString())}\n"; - stateString += $"HomeWorldName: {(this.resolveGameData ? this.dalamud.ClientState.LocalPlayer.HomeWorld.GameData.Name : this.dalamud.ClientState.LocalPlayer.HomeWorld.Id.ToString())}\n"; - stateString += $"LocalCID: {this.dalamud.ClientState.LocalContentId:X}\n"; - stateString += $"LastLinkedItem: {this.dalamud.Framework.Gui.Chat.LastLinkedItemId}\n"; - stateString += $"TerritoryType: {this.dalamud.ClientState.TerritoryType}\n\n"; + stateString += $"FrameworkBase: {framework.Address.BaseAddress.ToInt64():X}\n"; + stateString += $"ObjectTableLen: {objectTable.Length}\n"; + stateString += $"LocalPlayerName: {clientState.LocalPlayer.Name}\n"; + stateString += $"CurrentWorldName: {(this.resolveGameData ? clientState.LocalPlayer.CurrentWorld.GameData.Name : clientState.LocalPlayer.CurrentWorld.Id.ToString())}\n"; + stateString += $"HomeWorldName: {(this.resolveGameData ? clientState.LocalPlayer.HomeWorld.GameData.Name : clientState.LocalPlayer.HomeWorld.Id.ToString())}\n"; + stateString += $"LocalCID: {clientState.LocalContentId:X}\n"; + stateString += $"LastLinkedItem: {chatGui.LastLinkedItemId}\n"; + stateString += $"TerritoryType: {clientState.TerritoryType}\n\n"; ImGui.TextUnformatted(stateString); ImGui.Checkbox("Draw characters on screen", ref this.drawCharas); ImGui.SliderFloat("Draw Distance", ref this.maxCharaDrawDistance, 2f, 40f); - for (var i = 0; i < this.dalamud.ClientState.Objects.Length; i++) + for (var i = 0; i < objectTable.Length; i++) { - var obj = this.dalamud.ClientState.Objects[i]; + var obj = objectTable[i]; if (obj == null) continue; this.PrintGameObject(obj, i.ToString()); - if (this.drawCharas && this.dalamud.Framework.Gui.WorldToScreen(obj.Position, out var screenCoords)) + if (this.drawCharas && gameGui.WorldToScreen(obj.Position, out var screenCoords)) { // So, while WorldToScreen will return false if the point is off of game client screen, to // to avoid performance issues, we have to manually determine if creating a window would @@ -413,21 +426,24 @@ namespace Dalamud.Interface.Internal.Windows private void DrawFateTable() { + var fateTable = Service.Get(); + var framework = Service.Get(); + var stateString = string.Empty; - if (this.dalamud.ClientState.Fates.Length == 0) + if (fateTable.Length == 0) { ImGui.TextUnformatted("No fates or data not ready."); } else { - stateString += $"FrameworkBase: {this.dalamud.Framework.Address.BaseAddress.ToInt64():X}\n"; - stateString += $"FateTableLen: {this.dalamud.ClientState.Fates.Length}\n"; + stateString += $"FrameworkBase: {framework.Address.BaseAddress.ToInt64():X}\n"; + stateString += $"FateTableLen: {fateTable.Length}\n"; ImGui.TextUnformatted(stateString); - for (var i = 0; i < this.dalamud.ClientState.Fates.Length; i++) + for (var i = 0; i < fateTable.Length; i++) { - var fate = this.dalamud.ClientState.Fates[i]; + var fate = fateTable[i]; if (fate == null) continue; @@ -473,17 +489,19 @@ namespace Dalamud.Interface.Internal.Windows private void DrawPartyList() { + var partyList = Service.Get(); + ImGui.Checkbox("Resolve Actors", ref this.resolveObjects); - ImGui.Text($"GroupManager: {this.dalamud.ClientState.PartyList.GroupManagerAddress.ToInt64():X}"); - ImGui.Text($"GroupList: {this.dalamud.ClientState.PartyList.GroupListAddress.ToInt64():X}"); - ImGui.Text($"AllianceList: {this.dalamud.ClientState.PartyList.AllianceListAddress.ToInt64():X}"); + ImGui.Text($"GroupManager: {partyList.GroupManagerAddress.ToInt64():X}"); + ImGui.Text($"GroupList: {partyList.GroupListAddress.ToInt64():X}"); + ImGui.Text($"AllianceList: {partyList.AllianceListAddress.ToInt64():X}"); - ImGui.Text($"{this.dalamud.ClientState.PartyList.Length} Members"); + ImGui.Text($"{partyList.Length} Members"); - for (var i = 0; i < this.dalamud.ClientState.PartyList.Length; i++) + for (var i = 0; i < partyList.Length; i++) { - var member = this.dalamud.ClientState.PartyList[i]; + var member = partyList[i]; if (member == null) { ImGui.Text($"[{i}] was null"); @@ -508,11 +526,13 @@ namespace Dalamud.Interface.Internal.Windows private void DrawBuddyList() { + var buddyList = Service.Get(); + ImGui.Checkbox("Resolve Actors", ref this.resolveObjects); - ImGui.Text($"BuddyList: {this.dalamud.ClientState.BuddyList.BuddyListAddress.ToInt64():X}"); + ImGui.Text($"BuddyList: {buddyList.BuddyListAddress.ToInt64():X}"); { - var member = this.dalamud.ClientState.BuddyList.CompanionBuddy; + var member = buddyList.CompanionBuddy; if (member == null) { ImGui.Text("[Companion] null"); @@ -522,21 +542,21 @@ namespace Dalamud.Interface.Internal.Windows ImGui.Text($"[Companion] {member.Address.ToInt64():X} - {member.ObjectId} - {member.DataID}"); if (this.resolveObjects) { - var actor = member.Actor; - if (actor == null) + var gameObject = member.GameObject; + if (gameObject == null) { - ImGui.Text("Actor was null"); + ImGui.Text("GameObject was null"); } else { - this.PrintGameObject(actor, "-"); + this.PrintGameObject(gameObject, "-"); } } } } { - var member = this.dalamud.ClientState.BuddyList.PetBuddy; + var member = buddyList.PetBuddy; if (member == null) { ImGui.Text("[Pet] null"); @@ -546,21 +566,21 @@ namespace Dalamud.Interface.Internal.Windows ImGui.Text($"[Pet] {member.Address.ToInt64():X} - {member.ObjectId} - {member.DataID}"); if (this.resolveObjects) { - var actor = member.Actor; - if (actor == null) + var gameObject = member.GameObject; + if (gameObject == null) { - ImGui.Text("Actor was null"); + ImGui.Text("GameObject was null"); } else { - this.PrintGameObject(actor, "-"); + this.PrintGameObject(gameObject, "-"); } } } } { - var count = this.dalamud.ClientState.BuddyList.Length; + var count = buddyList.Length; if (count == 0) { ImGui.Text("[BattleBuddy] None present"); @@ -569,18 +589,18 @@ namespace Dalamud.Interface.Internal.Windows { for (var i = 0; i < count; i++) { - var member = this.dalamud.ClientState.BuddyList[i]; + var member = buddyList[i]; ImGui.Text($"[BattleBuddy] [{i}] {member.Address.ToInt64():X} - {member.ObjectId} - {member.DataID}"); if (this.resolveObjects) { - var actor = member.Actor; - if (actor == null) + var gameObject = member.GameObject; + if (gameObject == null) { - ImGui.Text("Actor was null"); + ImGui.Text("GameObject was null"); } else { - this.PrintGameObject(actor, "-"); + this.PrintGameObject(gameObject, "-"); } } } @@ -591,8 +611,8 @@ namespace Dalamud.Interface.Internal.Windows private void DrawPluginIPC() { #pragma warning disable CS0618 // Type or member is obsolete - var i1 = new DalamudPluginInterface(this.dalamud, "DalamudTestSub", PluginLoadReason.Unknown); - var i2 = new DalamudPluginInterface(this.dalamud, "DalamudTestPub", PluginLoadReason.Unknown); + var i1 = new DalamudPluginInterface("DalamudTestSub", PluginLoadReason.Unknown); + var i2 = new DalamudPluginInterface("DalamudTestPub", PluginLoadReason.Unknown); if (ImGui.Button("Add test sub")) { @@ -633,15 +653,18 @@ namespace Dalamud.Interface.Internal.Windows i2.SendMessage("DalamudTestSub", testMsg); } - foreach (var ipc in this.dalamud.PluginManager.IpcSubscriptions) + var pluginManager = Service.Get(); + foreach (var ipc in pluginManager.IpcSubscriptions) ImGui.Text($"Source:{ipc.SourcePluginName} Sub:{ipc.SubPluginName}"); #pragma warning restore CS0618 // Type or member is obsolete } private void DrawCondition() { + var condition = Service.Get(); + #if DEBUG - ImGui.Text($"ptr: 0x{this.dalamud.ClientState.Condition.ConditionArrayBase.ToInt64():X}"); + ImGui.Text($"ptr: 0x{condition.ConditionArrayBase.ToInt64():X}"); #endif ImGui.Text("Current Conditions:"); @@ -652,7 +675,7 @@ namespace Dalamud.Interface.Internal.Windows for (var i = 0; i < Condition.MaxConditionEntries; i++) { var typedCondition = (ConditionFlag)i; - var cond = this.dalamud.ClientState.Condition[typedCondition]; + var cond = condition[typedCondition]; if (!cond) continue; @@ -667,7 +690,10 @@ namespace Dalamud.Interface.Internal.Windows private void DrawGauge() { - var player = this.dalamud.ClientState.LocalPlayer; + var clientState = Service.Get(); + var jobGauges = Service.Get(); + + var player = clientState.LocalPlayer; if (player == null) { ImGui.Text("Player is not present"); @@ -677,25 +703,25 @@ namespace Dalamud.Interface.Internal.Windows var jobID = player.ClassJob.Id; if (jobID == 19) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.OathGauge)}: {gauge.OathGauge}"); } else if (jobID == 20) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.Chakra)}: {gauge.Chakra}"); } else if (jobID == 21) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.BeastGauge)}: {gauge.BeastGauge}"); } else if (jobID == 22) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.BOTDTimer)}: {gauge.BOTDTimer}"); ImGui.Text($"{nameof(gauge.BOTDState)}: {gauge.BOTDState}"); @@ -703,7 +729,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 23) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.SongTimer)}: {gauge.SongTimer}"); ImGui.Text($"{nameof(gauge.Repertoire)}: {gauge.Repertoire}"); @@ -712,7 +738,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 24) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.LilyTimer)}: {gauge.LilyTimer}"); ImGui.Text($"{nameof(gauge.Lily)}: {gauge.Lily}"); @@ -720,7 +746,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 25) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.EnochianTimer)}: {gauge.EnochianTimer}"); ImGui.Text($"{nameof(gauge.ElementTimeRemaining)}: {gauge.ElementTimeRemaining}"); @@ -734,7 +760,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 27) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.TimerRemaining)}: {gauge.TimerRemaining}"); ImGui.Text($"{nameof(gauge.ReturnSummon)}: {gauge.ReturnSummon}"); @@ -746,7 +772,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 28) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.Aetherflow)}: {gauge.Aetherflow}"); ImGui.Text($"{nameof(gauge.FairyGauge)}: {gauge.FairyGauge}"); @@ -755,7 +781,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 30) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.HutonTimer)}: {gauge.HutonTimer}"); ImGui.Text($"{nameof(gauge.Ninki)}: {gauge.Ninki}"); @@ -763,7 +789,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 31) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.OverheatTimeRemaining)}: {gauge.OverheatTimeRemaining}"); ImGui.Text($"{nameof(gauge.SummonTimeRemaining)}: {gauge.SummonTimeRemaining}"); @@ -775,7 +801,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 32) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.Blood)}: {gauge.Blood}"); ImGui.Text($"{nameof(gauge.DarksideTimeRemaining)}: {gauge.DarksideTimeRemaining}"); @@ -784,7 +810,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 33) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.DrawnCard)}: {gauge.DrawnCard}"); foreach (var seal in Enum.GetValues(typeof(SealType)).Cast()) @@ -795,7 +821,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 34) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.Kenki)}: {gauge.Kenki}"); ImGui.Text($"{nameof(gauge.MeditationStacks)}: {gauge.MeditationStacks}"); @@ -806,14 +832,14 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 35) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.WhiteMana)}: {gauge.WhiteMana}"); ImGui.Text($"{nameof(gauge.BlackMana)}: {gauge.BlackMana}"); } else if (jobID == 37) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.Ammo)}: {gauge.Ammo}"); ImGui.Text($"{nameof(gauge.MaxTimerDuration)}: {gauge.MaxTimerDuration}"); @@ -821,7 +847,7 @@ namespace Dalamud.Interface.Internal.Windows } else if (jobID == 38) { - var gauge = this.dalamud.ClientState.JobGauges.Get(); + var gauge = jobGauges.Get(); ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}"); ImGui.Text($"{nameof(gauge.Feathers)}: {gauge.Feathers}"); ImGui.Text($"{nameof(gauge.Esprit)}: {gauge.Esprit}"); @@ -837,13 +863,17 @@ namespace Dalamud.Interface.Internal.Windows private void DrawCommand() { - foreach (var command in this.dalamud.CommandManager.Commands) + var commandManager = Service.Get(); + + foreach (var command in commandManager.Commands) + { ImGui.Text($"{command.Key}\n -> {command.Value.HelpMessage}\n -> In help: {command.Value.ShowInHelp}\n\n"); + } } private unsafe void DrawAddon() { - var gameGui = this.dalamud.Framework.Gui; + var gameGui = Service.Get(); ImGui.InputText("Addon name", ref this.inputAddonName, 256); ImGui.InputInt("Addon Index", ref this.inputAddonIndex); @@ -880,18 +910,21 @@ namespace Dalamud.Interface.Internal.Windows private void DrawAddonInspector() { - this.addonInspector ??= new UIDebug(this.dalamud); + this.addonInspector ??= new UIDebug(); this.addonInspector.Draw(); } private void DrawStartInfo() { - ImGui.Text(JsonConvert.SerializeObject(this.dalamud.StartInfo, Formatting.Indented)); + var startInfo = Service.Get(); + + ImGui.Text(JsonConvert.SerializeObject(startInfo, Formatting.Indented)); } private void DrawTarget() { - var targetMgr = this.dalamud.ClientState.Targets; + var clientState = Service.Get(); + var targetMgr = Service.Get(); if (targetMgr.Target != null) { @@ -917,7 +950,7 @@ namespace Dalamud.Interface.Internal.Windows if (ImGui.Button("Clear FT")) targetMgr.ClearFocusTarget(); - var localPlayer = this.dalamud.ClientState.LocalPlayer; + var localPlayer = clientState.LocalPlayer; if (localPlayer != null) { @@ -935,6 +968,8 @@ namespace Dalamud.Interface.Internal.Windows private void DrawToast() { + var toastGui = Service.Get(); + ImGui.InputText("Toast text", ref this.inputTextToast, 200); ImGui.Combo("Toast Position", ref this.toastPosition, new[] { "Bottom", "Top", }, 2); @@ -948,7 +983,7 @@ namespace Dalamud.Interface.Internal.Windows if (ImGui.Button("Show toast")) { - this.dalamud.Framework.Gui.Toast.ShowNormal(this.inputTextToast, new ToastOptions + toastGui.ShowNormal(this.inputTextToast, new ToastOptions { Position = (ToastPosition)this.toastPosition, Speed = (ToastSpeed)this.toastSpeed, @@ -957,7 +992,7 @@ namespace Dalamud.Interface.Internal.Windows if (ImGui.Button("Show Quest toast")) { - this.dalamud.Framework.Gui.Toast.ShowQuest(this.inputTextToast, new QuestToastOptions + toastGui.ShowQuest(this.inputTextToast, new QuestToastOptions { Position = (QuestToastPosition)this.questToastPosition, DisplayCheckmark = this.questToastCheckmark, @@ -968,7 +1003,7 @@ namespace Dalamud.Interface.Internal.Windows if (ImGui.Button("Show Error toast")) { - this.dalamud.Framework.Gui.Toast.ShowError(this.inputTextToast); + toastGui.ShowError(this.inputTextToast); } } @@ -999,7 +1034,7 @@ namespace Dalamud.Interface.Internal.Windows if (ImGui.Button("Send")) { - this.dalamud.Framework.Gui.FlyText.AddFlyText( + Service.Get().AddFlyText( this.flyKind, unchecked((uint)this.flyActor), unchecked((uint)this.flyVal1), @@ -1013,11 +1048,13 @@ namespace Dalamud.Interface.Internal.Windows private void DrawImGui() { + var interfaceManager = Service.Get(); + ImGui.Text("Monitor count: " + ImGui.GetPlatformIO().Monitors.Size); - ImGui.Text("OverrideGameCursor: " + this.dalamud.InterfaceManager.OverrideGameCursor); + ImGui.Text("OverrideGameCursor: " + interfaceManager.OverrideGameCursor); ImGui.Button("THIS IS A BUTTON###hoverTestButton"); - this.dalamud.InterfaceManager.OverrideGameCursor = !ImGui.IsItemHovered(); + interfaceManager.OverrideGameCursor = !ImGui.IsItemHovered(); ImGui.Separator(); @@ -1048,12 +1085,14 @@ namespace Dalamud.Interface.Internal.Windows var text = "Bla bla bla bla bla bla bla bla bla bla bla.\nBla bla bla bla bla bla bla bla bla bla bla bla bla bla."; - this.dalamud.InterfaceManager.Notifications.AddNotification(text, title, type); + interfaceManager.Notifications.AddNotification(text, title, type); } } private void DrawTex() { + var dataManager = Service.Get(); + ImGui.InputText("Tex Path", ref this.inputTexPath, 255); ImGui.InputFloat2("UV0", ref this.inputTexUv0); ImGui.InputFloat2("UV1", ref this.inputTexUv1); @@ -1064,7 +1103,7 @@ namespace Dalamud.Interface.Internal.Windows { try { - this.debugTex = this.dalamud.Data.GetImGuiTexture(this.inputTexPath); + this.debugTex = dataManager.GetImGuiTexture(this.inputTexPath); this.inputTexScale = new Vector2(this.debugTex.Width, this.debugTex.Height); } catch (Exception ex) @@ -1085,6 +1124,8 @@ namespace Dalamud.Interface.Internal.Windows private void DrawGamepad() { + var gamepadState = Service.Get(); + static void DrawHelper(string text, uint mask, Func resolve) { ImGui.Text($"{text} {mask:X4}"); @@ -1106,47 +1147,49 @@ namespace Dalamud.Interface.Internal.Windows $"R3 {resolve(GamepadButtons.R3)} "); } - ImGui.Text($"GamepadInput 0x{this.dalamud.ClientState.GamepadState.GamepadInputAddress.ToInt64():X}"); + ImGui.Text($"GamepadInput 0x{gamepadState.GamepadInputAddress.ToInt64():X}"); #if DEBUG if (ImGui.IsItemHovered()) ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); if (ImGui.IsItemClicked()) - ImGui.SetClipboardText($"0x{this.dalamud.ClientState.GamepadState.GamepadInputAddress.ToInt64():X}"); + ImGui.SetClipboardText($"0x{gamepadState.GamepadInputAddress.ToInt64():X}"); #endif DrawHelper( "Buttons Raw", - this.dalamud.ClientState.GamepadState.ButtonsRaw, - this.dalamud.ClientState.GamepadState.Raw); + gamepadState.ButtonsRaw, + gamepadState.Raw); DrawHelper( "Buttons Pressed", - this.dalamud.ClientState.GamepadState.ButtonsPressed, - this.dalamud.ClientState.GamepadState.Pressed); + gamepadState.ButtonsPressed, + gamepadState.Pressed); DrawHelper( "Buttons Repeat", - this.dalamud.ClientState.GamepadState.ButtonsRepeat, - this.dalamud.ClientState.GamepadState.Repeat); + gamepadState.ButtonsRepeat, + gamepadState.Repeat); DrawHelper( "Buttons Released", - this.dalamud.ClientState.GamepadState.ButtonsReleased, - this.dalamud.ClientState.GamepadState.Released); - ImGui.Text($"LeftStickLeft {this.dalamud.ClientState.GamepadState.LeftStickLeft:0.00} " + - $"LeftStickUp {this.dalamud.ClientState.GamepadState.LeftStickUp:0.00} " + - $"LeftStickRight {this.dalamud.ClientState.GamepadState.LeftStickRight:0.00} " + - $"LeftStickDown {this.dalamud.ClientState.GamepadState.LeftStickDown:0.00} "); - ImGui.Text($"RightStickLeft {this.dalamud.ClientState.GamepadState.RightStickLeft:0.00} " + - $"RightStickUp {this.dalamud.ClientState.GamepadState.RightStickUp:0.00} " + - $"RightStickRight {this.dalamud.ClientState.GamepadState.RightStickRight:0.00} " + - $"RightStickDown {this.dalamud.ClientState.GamepadState.RightStickDown:0.00} "); + gamepadState.ButtonsReleased, + gamepadState.Released); + ImGui.Text($"LeftStickLeft {gamepadState.LeftStickLeft:0.00} " + + $"LeftStickUp {gamepadState.LeftStickUp:0.00} " + + $"LeftStickRight {gamepadState.LeftStickRight:0.00} " + + $"LeftStickDown {gamepadState.LeftStickDown:0.00} "); + ImGui.Text($"RightStickLeft {gamepadState.RightStickLeft:0.00} " + + $"RightStickUp {gamepadState.RightStickUp:0.00} " + + $"RightStickRight {gamepadState.RightStickRight:0.00} " + + $"RightStickDown {gamepadState.RightStickDown:0.00} "); } private void Load() { - if (this.dalamud.Data.IsDataReady) + var dataManager = Service.Get(); + + if (dataManager.IsDataReady) { - this.serverOpString = JsonConvert.SerializeObject(this.dalamud.Data.ServerOpCodes, Formatting.Indented); + this.serverOpString = JsonConvert.SerializeObject(dataManager.ServerOpCodes, Formatting.Indented); this.wasReady = true; } } diff --git a/Dalamud/Interface/Internal/Windows/IMEWindow.cs b/Dalamud/Interface/Internal/Windows/IMEWindow.cs index addaeaec6..fcfbfd00d 100644 --- a/Dalamud/Interface/Internal/Windows/IMEWindow.cs +++ b/Dalamud/Interface/Internal/Windows/IMEWindow.cs @@ -11,16 +11,12 @@ namespace Dalamud.Interface.Internal.Windows /// internal class IMEWindow : Window { - private readonly DalamudIME dalamudIME; - /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public IMEWindow(Dalamud dalamud) + public IMEWindow() : base("Dalamud IME", ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoFocusOnAppearing) { - this.dalamudIME = dalamud.IME; this.Size = new Vector2(100, 200); this.SizeCondition = ImGuiCond.FirstUseEver; } @@ -28,18 +24,20 @@ namespace Dalamud.Interface.Internal.Windows /// public override void Draw() { - if (this.dalamudIME == null || !this.dalamudIME.IsEnabled) + var ime = Service.GetNullable(); + + if (ime == null || ime.IsEnabled) { - ImGui.Text("IME unavailable."); + ImGui.Text("IME is unavailable."); return; } - ImGui.Text(this.dalamudIME.ImmComp); + ImGui.Text(ime.ImmComp); ImGui.Separator(); - for (var i = 0; i < this.dalamudIME.ImmCand.Count; i++) + for (var i = 0; i < ime.ImmCand.Count; i++) { - ImGui.Text($"{i + 1}. {this.dalamudIME.ImmCand[i]}"); + ImGui.Text($"{i + 1}. {ime.ImmCand[i]}"); } } } diff --git a/Dalamud/Interface/Internal/Windows/PluginInstallerWindow.cs b/Dalamud/Interface/Internal/Windows/PluginInstallerWindow.cs index b0e0da8b0..634b5e676 100644 --- a/Dalamud/Interface/Internal/Windows/PluginInstallerWindow.cs +++ b/Dalamud/Interface/Internal/Windows/PluginInstallerWindow.cs @@ -10,6 +10,8 @@ using System.Numerics; using System.Threading.Tasks; using CheapLoc; +using Dalamud.Configuration.Internal; +using Dalamud.Game.Command; using Dalamud.Interface.Colors; using Dalamud.Interface.Components; using Dalamud.Interface.Windowing; @@ -37,8 +39,6 @@ namespace Dalamud.Interface.Internal.Windows private static readonly ModuleLog Log = new("PLUGINW"); - private readonly Dalamud dalamud; - private readonly TextureWrap defaultIcon; private readonly TextureWrap troubleIcon; private readonly TextureWrap updateIcon; @@ -72,13 +72,11 @@ namespace Dalamud.Interface.Internal.Windows /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public PluginInstallerWindow(Dalamud dalamud) + public PluginInstallerWindow() : base( - Locs.WindowTitle + (dalamud.Configuration.DoPluginTest ? Locs.WindowTitleMod_Testing : string.Empty) + "###XlPluginInstaller", + Locs.WindowTitle + (Service.Get().DoPluginTest ? Locs.WindowTitleMod_Testing : string.Empty) + "###XlPluginInstaller", ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoScrollbar) { - this.dalamud = dalamud; this.IsOpen = true; this.Size = new Vector2(830, 570); @@ -90,24 +88,22 @@ namespace Dalamud.Interface.Internal.Windows MaximumSize = new Vector2(5000, 5000), }; + var dalamud = Service.Get(); + var interfaceManager = Service.Get(); + var pluginManager = Service.Get(); + // For debugging - if (this.dalamud.PluginManager.PluginsReady) + if (pluginManager.PluginsReady) this.OnInstalledPluginsChanged(); - this.dalamud.PluginManager.OnAvailablePluginsChanged += this.OnAvailablePluginsChanged; - this.dalamud.PluginManager.OnInstalledPluginsChanged += this.OnInstalledPluginsChanged; + pluginManager.OnAvailablePluginsChanged += this.OnAvailablePluginsChanged; + pluginManager.OnInstalledPluginsChanged += this.OnInstalledPluginsChanged; - this.defaultIcon = - this.dalamud.InterfaceManager.LoadImage( - Path.Combine(this.dalamud.AssetDirectory.FullName, "UIRes", "defaultIcon.png")); + this.defaultIcon = interfaceManager.LoadImage(Path.Combine(dalamud.AssetDirectory.FullName, "UIRes", "defaultIcon.png")); - this.troubleIcon = - this.dalamud.InterfaceManager.LoadImage( - Path.Combine(this.dalamud.AssetDirectory.FullName, "UIRes", "troubleIcon.png")); + this.troubleIcon = interfaceManager.LoadImage(Path.Combine(dalamud.AssetDirectory.FullName, "UIRes", "troubleIcon.png")); - this.updateIcon = - this.dalamud.InterfaceManager.LoadImage( - Path.Combine(this.dalamud.AssetDirectory.FullName, "UIRes", "updateIcon.png")); + this.updateIcon = interfaceManager.LoadImage(Path.Combine(dalamud.AssetDirectory.FullName, "UIRes", "updateIcon.png")); } private enum OperationStatus @@ -128,8 +124,10 @@ namespace Dalamud.Interface.Internal.Windows /// public void Dispose() { - this.dalamud.PluginManager.OnAvailablePluginsChanged -= this.OnAvailablePluginsChanged; - this.dalamud.PluginManager.OnInstalledPluginsChanged -= this.OnInstalledPluginsChanged; + var pluginManager = Service.Get(); + + pluginManager.OnAvailablePluginsChanged -= this.OnAvailablePluginsChanged; + pluginManager.OnInstalledPluginsChanged -= this.OnInstalledPluginsChanged; this.defaultIcon.Dispose(); this.troubleIcon.Dispose(); @@ -139,7 +137,9 @@ namespace Dalamud.Interface.Internal.Windows /// public override void OnOpen() { - Task.Run(this.dalamud.PluginManager.ReloadPluginMasters); + var pluginManager = Service.Get(); + + Task.Run(pluginManager.ReloadPluginMasters); this.updatePluginCount = 0; this.updatedPlugins = null; @@ -152,7 +152,7 @@ namespace Dalamud.Interface.Internal.Windows /// public override void OnClose() { - this.dalamud.Configuration.Save(); + Service.Get().Save(); } /// @@ -223,6 +223,9 @@ namespace Dalamud.Interface.Internal.Windows private void DrawFooter() { + var configuration = Service.Get(); + var pluginManager = Service.Get(); + var windowSize = ImGui.GetWindowContentRegionMax(); var placeholderButtonSize = GetButtonSize("placeholder"); @@ -235,7 +238,7 @@ namespace Dalamud.Interface.Internal.Windows ImGui.SameLine(); if (ImGui.Button(Locs.FooterButton_Settings)) { - this.dalamud.DalamudUi.OpenSettings(); + Service.Get().OpenSettings(); } // If any dev plugins are installed, allow a shortcut for the /xldev menu item @@ -244,7 +247,7 @@ namespace Dalamud.Interface.Internal.Windows ImGui.SameLine(); if (ImGui.Button(Locs.FooterButton_ScanDevPlugins)) { - this.dalamud.PluginManager.ScanDevPlugins(); + pluginManager.ScanDevPlugins(); } } @@ -255,13 +258,17 @@ namespace Dalamud.Interface.Internal.Windows if (ImGui.Button(closeText)) { this.IsOpen = false; - this.dalamud.Configuration.Save(); + configuration.Save(); } } private void DrawUpdatePluginsButton() { - var ready = this.dalamud.PluginManager.PluginsReady && this.dalamud.PluginManager.ReposReady; + var interfaceManager = Service.Get(); + var pluginManager = Service.Get(); + var notifications = Service.Get(); + + var ready = pluginManager.PluginsReady && pluginManager.ReposReady; if (!ready || this.updateStatus == OperationStatus.InProgress || this.installStatus == OperationStatus.InProgress) { @@ -279,7 +286,7 @@ namespace Dalamud.Interface.Internal.Windows { this.updateStatus = OperationStatus.InProgress; - Task.Run(() => this.dalamud.PluginManager.UpdatePluginsAsync()) + Task.Run(() => pluginManager.UpdatePluginsAsync()) .ContinueWith(task => { this.updateStatus = OperationStatus.Complete; @@ -314,12 +321,12 @@ namespace Dalamud.Interface.Internal.Windows if (this.updatePluginCount > 0) { - this.dalamud.PluginManager.PrintUpdatedPlugins(this.updatedPlugins, Locs.PluginUpdateHeader_Chatbox); - this.dalamud.InterfaceManager.Notifications.AddNotification(Locs.Notifications_UpdatesInstalled(this.updatePluginCount), Locs.Notifications_UpdatesInstalledTitle, Notifications.Notification.Type.Success); + pluginManager.PrintUpdatedPlugins(this.updatedPlugins, Locs.PluginUpdateHeader_Chatbox); + notifications.AddNotification(Locs.Notifications_UpdatesInstalled(this.updatePluginCount), Locs.Notifications_UpdatesInstalledTitle, Notifications.Notification.Type.Success); } else if (this.updatePluginCount == 0) { - this.dalamud.InterfaceManager.Notifications.AddNotification(Locs.Notifications_NoUpdatesFound, Locs.Notifications_NoUpdatesFoundTitle, Notifications.Notification.Type.Info); + notifications.AddNotification(Locs.Notifications_NoUpdatesFound, Locs.Notifications_NoUpdatesFoundTitle, Notifications.Notification.Type.Info); } } }); @@ -493,14 +500,16 @@ namespace Dalamud.Interface.Internal.Windows private bool DrawPluginListLoading() { - var ready = this.dalamud.PluginManager.PluginsReady && this.dalamud.PluginManager.ReposReady; + var pluginManager = Service.Get(); + + var ready = pluginManager.PluginsReady && pluginManager.ReposReady; if (!ready) { ImGui.TextColored(ImGuiColors.DalamudGrey, Locs.TabBody_LoadingPlugins); } - var failedRepos = this.dalamud.PluginManager.Repos + var failedRepos = pluginManager.Repos .Where(repo => repo.State == PluginRepositoryState.Fail) .ToArray(); @@ -617,7 +626,12 @@ namespace Dalamud.Interface.Internal.Windows private void DrawAvailablePlugin(RemotePluginManifest manifest, int index) { - var useTesting = this.dalamud.PluginManager.UseTesting(manifest); + var configuration = Service.Get(); + var interfaceManager = Service.Get(); + var notifications = Service.Get(); + var pluginManager = Service.Get(); + + var useTesting = pluginManager.UseTesting(manifest); var wasSeen = this.WasPluginSeen(manifest.InternalName); // Check for valid versions @@ -641,7 +655,7 @@ namespace Dalamud.Interface.Internal.Windows if (this.DrawPluginCollapsingHeader(label, manifest, false, false, !wasSeen, () => this.DrawAvailablePluginContextMenu(manifest), index)) { if (!wasSeen) - this.dalamud.Configuration.SeenPluginInternalName.Add(manifest.InternalName); + configuration.SeenPluginInternalName.Add(manifest.InternalName); ImGuiHelpers.ScaledDummy(5); @@ -682,7 +696,7 @@ namespace Dalamud.Interface.Internal.Windows { this.installStatus = OperationStatus.InProgress; - Task.Run(() => this.dalamud.PluginManager.InstallPluginAsync(manifest, useTesting, PluginLoadReason.Installer)) + Task.Run(() => pluginManager.InstallPluginAsync(manifest, useTesting, PluginLoadReason.Installer)) .ContinueWith(task => { // There is no need to set as Complete for an individual plugin installation @@ -691,11 +705,11 @@ namespace Dalamud.Interface.Internal.Windows { if (task.Result.State == PluginState.Loaded) { - this.dalamud.InterfaceManager.Notifications.AddNotification(Locs.Notifications_PluginInstalled(manifest.Name), Locs.Notifications_PluginInstalledTitle, Notifications.Notification.Type.Success); + notifications.AddNotification(Locs.Notifications_PluginInstalled(manifest.Name), Locs.Notifications_PluginInstalledTitle, Notifications.Notification.Type.Success); } else { - this.dalamud.InterfaceManager.Notifications.AddNotification(Locs.Notifications_PluginNotInstalled(manifest.Name), Locs.Notifications_PluginNotInstalledTitle, Notifications.Notification.Type.Error); + notifications.AddNotification(Locs.Notifications_PluginNotInstalled(manifest.Name), Locs.Notifications_PluginNotInstalledTitle, Notifications.Notification.Type.Error); this.ShowErrorModal(Locs.ErrorModal_InstallFail(manifest.Name)); } } @@ -718,21 +732,25 @@ namespace Dalamud.Interface.Internal.Windows private void DrawAvailablePluginContextMenu(PluginManifest manifest) { + var configuration = Service.Get(); + var pluginManager = Service.Get(); + var startInfo = Service.Get(); + if (ImGui.BeginPopupContextItem("ItemContextMenu")) { if (ImGui.Selectable(Locs.PluginContext_MarkAllSeen)) { - this.dalamud.Configuration.SeenPluginInternalName.AddRange(this.pluginListAvailable.Select(x => x.InternalName)); - this.dalamud.Configuration.Save(); - this.dalamud.PluginManager.RefilterPluginMasters(); + configuration.SeenPluginInternalName.AddRange(this.pluginListAvailable.Select(x => x.InternalName)); + configuration.Save(); + pluginManager.RefilterPluginMasters(); } if (ImGui.Selectable(Locs.PluginContext_HidePlugin)) { Log.Debug($"Adding {manifest.InternalName} to hidden plugins"); - this.dalamud.Configuration.HiddenPluginInternalName.Add(manifest.InternalName); - this.dalamud.Configuration.Save(); - this.dalamud.PluginManager.RefilterPluginMasters(); + configuration.HiddenPluginInternalName.Add(manifest.InternalName); + configuration.Save(); + pluginManager.RefilterPluginMasters(); } if (ImGui.Selectable(Locs.PluginContext_DeletePluginConfig)) @@ -743,9 +761,9 @@ namespace Dalamud.Interface.Internal.Windows Task.Run(() => { - this.dalamud.PluginManager.PluginConfigs.Delete(manifest.InternalName); + pluginManager.PluginConfigs.Delete(manifest.InternalName); - var path = Path.Combine(this.dalamud.StartInfo.PluginDirectory, manifest.InternalName); + var path = Path.Combine(startInfo.PluginDirectory, manifest.InternalName); if (Directory.Exists(path)) Directory.Delete(path, true); }) @@ -763,6 +781,11 @@ namespace Dalamud.Interface.Internal.Windows private void DrawInstalledPlugin(LocalPlugin plugin, int index, bool showInstalled = false) { + var configuration = Service.Get(); + var commandManager = Service.Get(); + var pluginManager = Service.Get(); + var startInfo = Service.Get(); + var trouble = false; // Name @@ -837,7 +860,7 @@ namespace Dalamud.Interface.Internal.Windows if (this.DrawPluginCollapsingHeader(label, plugin.Manifest, trouble, availablePluginUpdate != default, false, () => this.DrawInstalledPluginContextMenu(plugin), index)) { if (!this.WasPluginSeen(plugin.Manifest.InternalName)) - this.dalamud.Configuration.SeenPluginInternalName.Add(plugin.Manifest.InternalName); + configuration.SeenPluginInternalName.Add(plugin.Manifest.InternalName); var manifest = plugin.Manifest; @@ -884,7 +907,7 @@ namespace Dalamud.Interface.Internal.Windows // Available commands (if loaded) if (plugin.IsLoaded) { - var commands = this.dalamud.CommandManager.Commands.Where(cInfo => cInfo.Value.ShowInHelp && cInfo.Value.LoaderAssemblyName == plugin.Manifest.InternalName); + var commands = commandManager.Commands.Where(cInfo => cInfo.Value.ShowInHelp && cInfo.Value.LoaderAssemblyName == plugin.Manifest.InternalName); if (commands.Any()) { ImGui.Dummy(ImGuiHelpers.ScaledVector2(10f, 10f)); @@ -926,6 +949,8 @@ namespace Dalamud.Interface.Internal.Windows private void DrawInstalledPluginContextMenu(LocalPlugin plugin) { + var pluginManager = Service.Get(); + if (ImGui.BeginPopupContextItem("InstalledItemContextMenu")) { if (ImGui.Selectable(Locs.PluginContext_DeletePluginConfigReload)) @@ -934,7 +959,7 @@ namespace Dalamud.Interface.Internal.Windows this.installStatus = OperationStatus.InProgress; - Task.Run(() => this.dalamud.PluginManager.DeleteConfiguration(plugin)) + Task.Run(() => pluginManager.DeleteConfiguration(plugin)) .ContinueWith(task => { this.installStatus = OperationStatus.Idle; @@ -949,11 +974,16 @@ namespace Dalamud.Interface.Internal.Windows private void DrawPluginControlButton(LocalPlugin plugin) { + var configuration = Service.Get(); + var notifications = Service.Get(); + var pluginManager = Service.Get(); + var startInfo = Service.Get(); + // Disable everything if the updater is running or another plugin is operating var disabled = this.updateStatus == OperationStatus.InProgress || this.installStatus == OperationStatus.InProgress; // Disable everything if the plugin is outdated - disabled = disabled || (plugin.Manifest.DalamudApiLevel < PluginManager.DalamudApiLevel && !this.dalamud.Configuration.LoadAllApiLevels); + disabled = disabled || (plugin.Manifest.DalamudApiLevel < PluginManager.DalamudApiLevel && !configuration.LoadAllApiLevels); if (plugin.State == PluginState.InProgress) { @@ -987,10 +1017,10 @@ namespace Dalamud.Interface.Internal.Windows if (!plugin.IsDev) { - this.dalamud.PluginManager.RemovePlugin(plugin); + pluginManager.RemovePlugin(plugin); } - this.dalamud.InterfaceManager.Notifications.AddNotification(Locs.Notifications_PluginDisabled(plugin.Manifest.Name), Locs.Notifications_PluginDisabledTitle, Notifications.Notification.Type.Success); + notifications.AddNotification(Locs.Notifications_PluginDisabled(plugin.Manifest.Name), Locs.Notifications_PluginDisabledTitle, Notifications.Notification.Type.Success); }); } } @@ -1041,13 +1071,15 @@ namespace Dalamud.Interface.Internal.Windows private void DrawUpdateSinglePluginButton(AvailablePluginUpdate update) { + var pluginManager = Service.Get(); + ImGui.SameLine(); if (ImGuiComponents.IconButton(FontAwesomeIcon.Download)) { this.installStatus = OperationStatus.InProgress; - Task.Run(() => this.dalamud.PluginManager.UpdateSinglePluginAsync(update, true, false)) + Task.Run(() => pluginManager.UpdateSinglePluginAsync(update, true, false)) .ContinueWith(task => { // There is no need to set as Complete for an individual plugin installation @@ -1093,6 +1125,9 @@ namespace Dalamud.Interface.Internal.Windows private void DrawDevPluginButtons(LocalPlugin localPlugin) { + var configuration = Service.Get(); + var pluginManager = Service.Get(); + if (localPlugin is LocalDevPlugin plugin) { // https://colorswall.com/palette/2868/ @@ -1107,7 +1142,7 @@ namespace Dalamud.Interface.Internal.Windows if (ImGuiComponents.IconButton(FontAwesomeIcon.PowerOff)) { plugin.StartOnBoot ^= true; - this.dalamud.Configuration.Save(); + configuration.Save(); } ImGui.PopStyleColor(2); @@ -1125,7 +1160,7 @@ namespace Dalamud.Interface.Internal.Windows if (ImGuiComponents.IconButton(FontAwesomeIcon.SyncAlt)) { plugin.AutomaticReload ^= true; - this.dalamud.Configuration.Save(); + configuration.Save(); } ImGui.PopStyleColor(2); @@ -1144,7 +1179,7 @@ namespace Dalamud.Interface.Internal.Windows try { plugin.DllFile.Delete(); - this.dalamud.PluginManager.RemovePlugin(plugin); + pluginManager.RemovePlugin(plugin); } catch (Exception ex) { @@ -1281,12 +1316,14 @@ namespace Dalamud.Interface.Internal.Windows private void OnAvailablePluginsChanged() { + var pluginManager = Service.Get(); + // By removing installed plugins only when the available plugin list changes (basically when the window is // opened), plugins that have been newly installed remain in the available plugin list as installed. - this.pluginListAvailable = this.dalamud.PluginManager.AvailablePlugins + this.pluginListAvailable = pluginManager.AvailablePlugins .Where(manifest => !this.IsManifestInstalled(manifest).IsInstalled) .ToList(); - this.pluginListUpdatable = this.dalamud.PluginManager.UpdatablePlugins.ToList(); + this.pluginListUpdatable = pluginManager.UpdatablePlugins.ToList(); this.ResortPlugins(); this.DownloadPluginIcons(); @@ -1294,8 +1331,10 @@ namespace Dalamud.Interface.Internal.Windows private void OnInstalledPluginsChanged() { - this.pluginListInstalled = this.dalamud.PluginManager.InstalledPlugins.ToList(); - this.pluginListUpdatable = this.dalamud.PluginManager.UpdatablePlugins.ToList(); + var pluginManager = Service.Get(); + + this.pluginListInstalled = pluginManager.InstalledPlugins.ToList(); + this.pluginListUpdatable = pluginManager.UpdatablePlugins.ToList(); this.hasDevPlugins = this.pluginListInstalled.Any(plugin => plugin.IsDev); this.ResortPlugins(); @@ -1330,7 +1369,7 @@ namespace Dalamud.Interface.Internal.Windows } private bool WasPluginSeen(string internalName) => - this.dalamud.Configuration.SeenPluginInternalName.Contains(internalName); + Service.Get().SeenPluginInternalName.Contains(internalName); /// /// A continuation task that displays any errors received into the error modal. @@ -1410,6 +1449,8 @@ namespace Dalamud.Interface.Internal.Windows private async Task DownloadPluginIconAsync(PluginManifest manifest) { + var interfaceManager = Service.Get(); + Log.Verbose($"Downloading icon for {manifest.InternalName}"); this.pluginIconMap.Add(manifest.InternalName, (false, null)); @@ -1419,7 +1460,7 @@ namespace Dalamud.Interface.Internal.Windows { var data = await client.GetAsync(manifest.IconUrl); data.EnsureSuccessStatusCode(); - var icon = this.dalamud.InterfaceManager.LoadImage(await data.Content.ReadAsByteArrayAsync()); + var icon = interfaceManager.LoadImage(await data.Content.ReadAsByteArrayAsync()); if (icon != null) { @@ -1436,6 +1477,8 @@ namespace Dalamud.Interface.Internal.Windows private async Task DownloadPluginImagesAsync(PluginManifest manifest) { + var interfaceManager = Service.Get(); + Log.Verbose($"Downloading images for {manifest.InternalName}"); this.pluginImagesMap.Add(manifest.InternalName, (false, null)); @@ -1455,7 +1498,7 @@ namespace Dalamud.Interface.Internal.Windows { var data = await client.GetAsync(manifest.ImageUrls[i]); data.EnsureSuccessStatusCode(); - var image = this.dalamud.InterfaceManager.LoadImage(await data.Content.ReadAsByteArrayAsync()); + var image = interfaceManager.LoadImage(await data.Content.ReadAsByteArrayAsync()); if (image == null) { diff --git a/Dalamud/Interface/Internal/Windows/PluginStatWindow.cs b/Dalamud/Interface/Internal/Windows/PluginStatWindow.cs index 733baa454..fbc07eb47 100644 --- a/Dalamud/Interface/Internal/Windows/PluginStatWindow.cs +++ b/Dalamud/Interface/Internal/Windows/PluginStatWindow.cs @@ -17,22 +17,21 @@ namespace Dalamud.Interface.Internal.Windows /// internal class PluginStatWindow : Window { - private readonly PluginManager pluginManager; private bool showDalamudHooks; /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public PluginStatWindow(Dalamud dalamud) + public PluginStatWindow() : base("Plugin Statistics###DalamudPluginStatWindow") { - this.pluginManager = dalamud.PluginManager; } /// public override void Draw() { + var pluginManager = Service.Get(); + ImGui.BeginTabBar("Stat Tabs"); if (ImGui.BeginTabItem("Draw times")) @@ -49,7 +48,7 @@ namespace Dalamud.Interface.Internal.Windows ImGui.SameLine(); if (ImGui.Button("Reset")) { - foreach (var plugin in this.pluginManager.InstalledPlugins) + foreach (var plugin in pluginManager.InstalledPlugins) { plugin.DalamudInterface.UiBuilder.LastDrawTime = -1; plugin.DalamudInterface.UiBuilder.MaxDrawTime = -1; @@ -77,7 +76,7 @@ namespace Dalamud.Interface.Internal.Windows ImGui.Separator(); - foreach (var plugin in this.pluginManager.InstalledPlugins.Where(plugin => plugin.State == PluginState.Loaded)) + foreach (var plugin in pluginManager.InstalledPlugins.Where(plugin => plugin.State == PluginState.Loaded)) { ImGui.Text(plugin.Manifest.Name); ImGui.NextColumn(); diff --git a/Dalamud/Interface/Internal/Windows/ScratchpadWindow.cs b/Dalamud/Interface/Internal/Windows/ScratchpadWindow.cs index 1f420f1e8..fb4aca9bf 100644 --- a/Dalamud/Interface/Internal/Windows/ScratchpadWindow.cs +++ b/Dalamud/Interface/Internal/Windows/ScratchpadWindow.cs @@ -16,7 +16,6 @@ namespace Dalamud.Interface.Internal.Windows /// internal class ScratchpadWindow : Window, IDisposable { - private readonly Dalamud dalamud; private readonly List documents = new(); private readonly ScratchFileWatcher watcher = new(); private string pathInput = string.Empty; @@ -24,11 +23,9 @@ namespace Dalamud.Interface.Internal.Windows /// /// Initializes a new instance of the class. /// - /// The Dalamud instance. - public ScratchpadWindow(Dalamud dalamud) + public ScratchpadWindow() : base("Plugin Scratchpad", ImGuiWindowFlags.MenuBar) { - this.dalamud = dalamud; this.documents.Add(new ScratchpadDocument()); this.SizeConstraints = new WindowSizeConstraints @@ -37,7 +34,7 @@ namespace Dalamud.Interface.Internal.Windows MaximumSize = new Vector2(1000, 1000), }; - this.Execution = new ScratchExecutionManager(dalamud); + this.Execution = new ScratchExecutionManager(); } /// @@ -143,7 +140,7 @@ namespace Dalamud.Interface.Internal.Windows if (ImGui.Button("Toggle Log")) { - this.dalamud.DalamudUi.ToggleLogWindow(); + Service.Get().ToggleLogWindow(); } ImGui.SameLine(); diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ActorTableAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ActorTableAgingStep.cs index ee956de44..a8cb3e4a1 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ActorTableAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ActorTableAgingStep.cs @@ -1,3 +1,4 @@ +using Dalamud.Game.ClientState.Objects; using Dalamud.Utility; using ImGuiNET; @@ -14,16 +15,18 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test ActorTable"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var objectTable = Service.Get(); + ImGui.Text("Checking actor table..."); - if (this.index == dalamud.ClientState.Objects.Length - 1) + if (this.index == objectTable.Length - 1) { return SelfTestStepResult.Pass; } - var actor = dalamud.ClientState.Objects[this.index]; + var actor = objectTable[this.index]; this.index++; if (actor == null) @@ -37,7 +40,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ChatAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ChatAgingStep.cs index d6d2197e8..02613dee2 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ChatAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ChatAgingStep.cs @@ -1,4 +1,5 @@ -using Dalamud.Game.Text; +using Dalamud.Game.Gui; +using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using ImGuiNET; @@ -17,12 +18,14 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test Chat"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var chatGui = Service.Get(); + switch (this.step) { case 0: - dalamud.Framework.Gui.Chat.Print("Testing!"); + chatGui.Print("Testing!"); this.step++; break; @@ -33,12 +36,12 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps if (!this.subscribed) { this.subscribed = true; - dalamud.Framework.Gui.Chat.ChatMessage += this.ChatOnOnChatMessage; + chatGui.ChatMessage += this.ChatOnOnChatMessage; } if (this.hasPassed) { - dalamud.Framework.Gui.Chat.ChatMessage -= this.ChatOnOnChatMessage; + chatGui.ChatMessage -= this.ChatOnOnChatMessage; this.subscribed = false; return SelfTestStepResult.Pass; } @@ -50,9 +53,11 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { - dalamud.Framework.Gui.Chat.ChatMessage -= this.ChatOnOnChatMessage; + var chatGui = Service.Get(); + + chatGui.ChatMessage -= this.ChatOnOnChatMessage; this.subscribed = false; } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ConditionAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ConditionAgingStep.cs index 2907d39a3..501920343 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ConditionAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ConditionAgingStep.cs @@ -1,4 +1,4 @@ -using Dalamud.Game.ClientState.Conditions; +using Dalamud.Game.ClientState.Conditions; using ImGuiNET; using Serilog; @@ -13,9 +13,11 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test Condition"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { - if (!dalamud.ClientState.Condition.Any()) + var condition = Service.Get(); + + if (!condition.Any()) { Log.Error("No condition flags present."); return SelfTestStepResult.Fail; @@ -23,11 +25,11 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps ImGui.Text("Please jump..."); - return dalamud.ClientState.Condition[ConditionFlag.Jumping] ? SelfTestStepResult.Pass : SelfTestStepResult.Waiting; + return condition[ConditionFlag.Jumping] ? SelfTestStepResult.Pass : SelfTestStepResult.Waiting; } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/EnterTerritoryAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/EnterTerritoryAgingStep.cs index 9db72c197..487a6e572 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/EnterTerritoryAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/EnterTerritoryAgingStep.cs @@ -1,4 +1,5 @@ -using ImGuiNET; +using Dalamud.Game.ClientState; +using ImGuiNET; namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps { @@ -27,19 +28,21 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => $"Enter Terri: {this.terriName}"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var clientState = Service.Get(); + ImGui.TextUnformatted(this.Name); if (!this.subscribed) { - dalamud.ClientState.TerritoryChanged += this.ClientStateOnTerritoryChanged; + clientState.TerritoryChanged += this.ClientStateOnTerritoryChanged; this.subscribed = true; } if (this.hasPassed) { - dalamud.ClientState.TerritoryChanged -= this.ClientStateOnTerritoryChanged; + clientState.TerritoryChanged -= this.ClientStateOnTerritoryChanged; this.subscribed = false; return SelfTestStepResult.Pass; } @@ -48,9 +51,11 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { - dalamud.ClientState.TerritoryChanged -= this.ClientStateOnTerritoryChanged; + var clientState = Service.Get(); + + clientState.TerritoryChanged -= this.ClientStateOnTerritoryChanged; this.subscribed = false; } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/FateTableAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/FateTableAgingStep.cs index 1a34b5a58..b037d06ca 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/FateTableAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/FateTableAgingStep.cs @@ -1,4 +1,5 @@ -using Dalamud.Utility; +using Dalamud.Game.ClientState.Fates; +using Dalamud.Utility; using ImGuiNET; namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps @@ -14,16 +15,18 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test FateTable"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var fateTable = Service.Get(); + ImGui.Text("Checking fate table..."); - if (this.index == dalamud.ClientState.Fates.Length - 1) + if (this.index == fateTable.Length - 1) { return SelfTestStepResult.Pass; } - var actor = dalamud.ClientState.Fates[this.index]; + var actor = fateTable[this.index]; this.index++; if (actor == null) @@ -37,7 +40,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/GamepadStateAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/GamepadStateAgingStep.cs index 443d65843..320e0d55c 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/GamepadStateAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/GamepadStateAgingStep.cs @@ -1,4 +1,4 @@ -using Dalamud.Game.ClientState.GamePad; +using Dalamud.Game.ClientState.GamePad; using ImGuiNET; namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps @@ -12,13 +12,15 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test GamePadState"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var gamepadState = Service.Get(); + ImGui.Text("Hold down North, East, L1"); - if (dalamud.ClientState.GamepadState.Pressed(GamepadButtons.North) == 1 - && dalamud.ClientState.GamepadState.Pressed(GamepadButtons.East) == 1 - && dalamud.ClientState.GamepadState.Pressed(GamepadButtons.L1) == 1) + if (gamepadState.Pressed(GamepadButtons.North) == 1 + && gamepadState.Pressed(GamepadButtons.East) == 1 + && gamepadState.Pressed(GamepadButtons.L1) == 1) { return SelfTestStepResult.Pass; } @@ -27,7 +29,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/HandledExceptionAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/HandledExceptionAgingStep.cs index cf64b03c3..7a63d6ba7 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/HandledExceptionAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/HandledExceptionAgingStep.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.InteropServices; namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps @@ -12,7 +12,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test Handled Exception"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { try { @@ -27,7 +27,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/HoverAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/HoverAgingStep.cs index 845a5d40d..713d0ebc4 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/HoverAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/HoverAgingStep.cs @@ -1,4 +1,4 @@ -using Dalamud.Game.Gui; +using Dalamud.Game.Gui; using ImGuiNET; namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps @@ -15,16 +15,15 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test Hover"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { - var hoverItem = dalamud.Framework.Gui.HoveredItem; - var hoverAction = dalamud.Framework.Gui.HoveredAction; + var gameGui = Service.Get(); if (!this.clearedItem) { ImGui.Text("Hover WHM soul crystal..."); - if (hoverItem == 4547) + if (gameGui.HoveredItem == 4547) { this.clearedItem = true; } @@ -34,8 +33,9 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps { ImGui.Text("Hover \"Open Linkshells\" action..."); - if (hoverAction != null && hoverAction.ActionKind == HoverActionKind.MainCommand && - hoverAction.ActionID == 28) + if (gameGui.HoveredAction != null && + gameGui.HoveredAction.ActionKind == HoverActionKind.MainCommand && + gameGui.HoveredAction.ActionID == 28) { this.clearedAction = true; } @@ -50,7 +50,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/IAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/IAgingStep.cs index fb1683b40..6315f9d05 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/IAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/IAgingStep.cs @@ -1,4 +1,4 @@ -namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps +namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps { /// /// Interface for test implementations. @@ -13,14 +13,12 @@ /// /// Run the test step, once per frame it is active. /// - /// Dalamud instance to act on. /// The result of this frame, test is discarded once a result other than is returned. - public SelfTestStepResult RunStep(Dalamud dalamud); + public SelfTestStepResult RunStep(); /// /// Clean up this test. /// - /// Dalamud instance to act on. - public void CleanUp(Dalamud dalamud); + public void CleanUp(); } } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/KeyStateAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/KeyStateAgingStep.cs index b93ae3165..20b645b15 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/KeyStateAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/KeyStateAgingStep.cs @@ -1,4 +1,4 @@ -using Dalamud.Game.ClientState.Keys; +using Dalamud.Game.ClientState.Keys; using ImGuiNET; namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps @@ -12,15 +12,17 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test KeyState"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var keyState = Service.Get(); + ImGui.Text("Hold down D,A,L,M,U"); - if (dalamud.ClientState.KeyState[VirtualKey.D] - && dalamud.ClientState.KeyState[VirtualKey.A] - && dalamud.ClientState.KeyState[VirtualKey.L] - && dalamud.ClientState.KeyState[VirtualKey.M] - && dalamud.ClientState.KeyState[VirtualKey.U]) + if (keyState[VirtualKey.D] + && keyState[VirtualKey.A] + && keyState[VirtualKey.L] + && keyState[VirtualKey.M] + && keyState[VirtualKey.U]) { return SelfTestStepResult.Pass; } @@ -29,7 +31,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LoginEventAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LoginEventAgingStep.cs index 648b42e63..47a7f9bc9 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LoginEventAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LoginEventAgingStep.cs @@ -1,5 +1,6 @@ -using System; +using System; +using Dalamud.Game.ClientState; using ImGuiNET; namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps @@ -16,19 +17,21 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test Log-In"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var clientState = Service.Get(); + ImGui.Text("Log in now..."); if (!this.subscribed) { - dalamud.ClientState.Login += this.ClientStateOnOnLogin; + clientState.Login += this.ClientStateOnOnLogin; this.subscribed = true; } if (this.hasPassed) { - dalamud.ClientState.Login -= this.ClientStateOnOnLogin; + clientState.Login -= this.ClientStateOnOnLogin; this.subscribed = false; return SelfTestStepResult.Pass; } @@ -37,11 +40,13 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { + var clientState = Service.Get(); + if (this.subscribed) { - dalamud.ClientState.Login -= this.ClientStateOnOnLogin; + clientState.Login -= this.ClientStateOnOnLogin; this.subscribed = false; } } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LogoutEventAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LogoutEventAgingStep.cs index 6b6ce78fe..8c216eb19 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LogoutEventAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LogoutEventAgingStep.cs @@ -1,5 +1,6 @@ -using System; +using System; +using Dalamud.Game.ClientState; using ImGuiNET; namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps @@ -16,19 +17,21 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test Log-In"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var clientState = Service.Get(); + ImGui.Text("Log out now..."); if (!this.subscribed) { - dalamud.ClientState.Logout += this.ClientStateOnOnLogout; + clientState.Logout += this.ClientStateOnOnLogout; this.subscribed = true; } if (this.hasPassed) { - dalamud.ClientState.Logout -= this.ClientStateOnOnLogout; + clientState.Logout -= this.ClientStateOnOnLogout; this.subscribed = false; return SelfTestStepResult.Pass; } @@ -37,11 +40,13 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { + var clientState = Service.Get(); + if (this.subscribed) { - dalamud.ClientState.Logout -= this.ClientStateOnOnLogout; + clientState.Logout -= this.ClientStateOnOnLogout; this.subscribed = false; } } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LuminaAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LuminaAgingStep.cs index 7a8ae0fd6..e1ab91978 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LuminaAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/LuminaAgingStep.cs @@ -1,6 +1,7 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Dalamud.Data; using Dalamud.Utility; using Lumina.Excel; @@ -20,9 +21,11 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test Lumina"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { - this.rows ??= dalamud.Data.GetExcelSheet().ToList(); + var dataManager = Service.Get(); + + this.rows ??= dataManager.GetExcelSheet().ToList(); Util.ShowObject(this.rows[this.step]); @@ -31,7 +34,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/PartyFinderAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/PartyFinderAgingStep.cs index c2172b9dc..6e8edbe29 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/PartyFinderAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/PartyFinderAgingStep.cs @@ -1,4 +1,5 @@ -using Dalamud.Game.Gui.PartyFinder.Types; +using Dalamud.Game.Gui.PartyFinder; +using Dalamud.Game.Gui.PartyFinder.Types; using ImGuiNET; namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps @@ -15,17 +16,19 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test Party Finder"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var partyFinderGui = Service.Get(); + if (!this.subscribed) { - dalamud.Framework.Gui.PartyFinder.ReceiveListing += this.PartyFinderOnReceiveListing; + partyFinderGui.ReceiveListing += this.PartyFinderOnReceiveListing; this.subscribed = true; } if (this.hasPassed) { - dalamud.Framework.Gui.PartyFinder.ReceiveListing -= this.PartyFinderOnReceiveListing; + partyFinderGui.ReceiveListing -= this.PartyFinderOnReceiveListing; this.subscribed = false; return SelfTestStepResult.Pass; } @@ -36,11 +39,13 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { + var partyFinderGui = Service.Get(); + if (this.subscribed) { - dalamud.Framework.Gui.PartyFinder.ReceiveListing -= this.PartyFinderOnReceiveListing; + partyFinderGui.ReceiveListing -= this.PartyFinderOnReceiveListing; this.subscribed = false; } } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/TargetAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/TargetAgingStep.cs index d6f0e6365..6866cdd52 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/TargetAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/TargetAgingStep.cs @@ -1,3 +1,4 @@ +using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.SubKinds; using Dalamud.Game.ClientState.Objects.Types; using ImGuiNET; @@ -15,13 +16,15 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps public string Name => "Test Target"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { + var targetManager = Service.Get(); + switch (this.step) { case 0: - dalamud.ClientState.Targets.ClearTarget(); - dalamud.ClientState.Targets.ClearFocusTarget(); + targetManager.ClearTarget(); + targetManager.ClearFocusTarget(); this.step++; @@ -30,7 +33,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps case 1: ImGui.Text("Target a player..."); - var cTarget = dalamud.ClientState.Targets.Target; + var cTarget = targetManager.Target; if (cTarget is PlayerCharacter) { this.step++; @@ -41,7 +44,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps case 2: ImGui.Text("Focus-Target a Battle NPC..."); - var fTarget = dalamud.ClientState.Targets.FocusTarget; + var fTarget = targetManager.FocusTarget; if (fTarget is BattleNpc) { this.step++; @@ -52,7 +55,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps case 3: ImGui.Text("Soft-Target an EventObj..."); - var sTarget = dalamud.ClientState.Targets.FocusTarget; + var sTarget = targetManager.FocusTarget; if (sTarget is EventObj) { return SelfTestStepResult.Pass; @@ -65,7 +68,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ToastAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ToastAgingStep.cs index 548fe698a..239f8650e 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ToastAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/ToastAgingStep.cs @@ -1,4 +1,6 @@ -namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps +using Dalamud.Game.Gui.Toast; + +namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps { /// /// Test setup for toasts. @@ -9,16 +11,18 @@ public string Name => "Test Toasts"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { - dalamud.Framework.Gui.Toast.ShowNormal("Normal Toast"); - dalamud.Framework.Gui.Toast.ShowError("Error Toast"); + var toastGui = Service.Get(); + + toastGui.ShowNormal("Normal Toast"); + toastGui.ShowError("Error Toast"); return SelfTestStepResult.Pass; } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { // ignored } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/WaitFramesAgingStep.cs b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/WaitFramesAgingStep.cs index bac881324..57e7e99ac 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/WaitFramesAgingStep.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/AgingSteps/WaitFramesAgingStep.cs @@ -1,4 +1,4 @@ -namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps +namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps { /// /// Test that waits N frames. @@ -22,7 +22,7 @@ public string Name => $"Wait {this.cFrames} frames"; /// - public SelfTestStepResult RunStep(Dalamud dalamud) + public SelfTestStepResult RunStep() { this.cFrames--; @@ -30,7 +30,7 @@ } /// - public void CleanUp(Dalamud dalamud) + public void CleanUp() { this.cFrames = this.frames; } diff --git a/Dalamud/Interface/Internal/Windows/SelfTest/SelfTestWindow.cs b/Dalamud/Interface/Internal/Windows/SelfTest/SelfTestWindow.cs index 9f95c4d27..ba37a9401 100644 --- a/Dalamud/Interface/Internal/Windows/SelfTest/SelfTestWindow.cs +++ b/Dalamud/Interface/Internal/Windows/SelfTest/SelfTestWindow.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Numerics; @@ -20,8 +20,6 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest { private static readonly ModuleLog Log = new("AGING"); - private readonly Dalamud dalamud; - private readonly List steps = new() { @@ -53,12 +51,9 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest /// /// Initializes a new instance of the class. /// - /// The dalamud instance to act on. - public SelfTestWindow(Dalamud dalamud) + public SelfTestWindow() : base("Dalamud Self-Test", ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse) { - this.dalamud = dalamud; - this.Size = new Vector2(800, 800); this.SizeCondition = ImGuiCond.FirstUseEver; } @@ -142,7 +137,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest SelfTestStepResult result; try { - result = step.RunStep(this.dalamud); + result = step.RunStep(); } catch (Exception ex) { @@ -248,7 +243,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest { try { - agingStep.CleanUp(this.dalamud); + agingStep.CleanUp(); } catch (Exception ex) { diff --git a/Dalamud/Interface/Internal/Windows/SettingsWindow.cs b/Dalamud/Interface/Internal/Windows/SettingsWindow.cs index fde2ad0c7..f979be5ca 100644 --- a/Dalamud/Interface/Internal/Windows/SettingsWindow.cs +++ b/Dalamud/Interface/Internal/Windows/SettingsWindow.cs @@ -7,10 +7,12 @@ using System.Threading.Tasks; using CheapLoc; using Dalamud.Configuration; +using Dalamud.Configuration.Internal; using Dalamud.Game.Text; using Dalamud.Interface.Colors; using Dalamud.Interface.Components; using Dalamud.Interface.Windowing; +using Dalamud.Plugin.Internal; using ImGuiNET; namespace Dalamud.Interface.Internal.Windows @@ -23,8 +25,6 @@ namespace Dalamud.Interface.Internal.Windows private const float MinScale = 0.3f; private const float MaxScale = 2.0f; - private readonly Dalamud dalamud; - private readonly string[] languages; private readonly string[] locLanguages; private int langIndex; @@ -68,41 +68,40 @@ namespace Dalamud.Interface.Internal.Windows /// /// Initializes a new instance of the class. /// - /// The Dalamud Instance. - public SettingsWindow(Dalamud dalamud) + public SettingsWindow() : base(Loc.Localize("DalamudSettingsHeader", "Dalamud Settings") + "###XlSettings2", ImGuiWindowFlags.NoCollapse) { - this.dalamud = dalamud; + var configuration = Service.Get(); this.Size = new Vector2(740, 550); this.SizeCondition = ImGuiCond.FirstUseEver; - this.dalamudMessagesChatType = this.dalamud.Configuration.GeneralChatType; + this.dalamudMessagesChatType = configuration.GeneralChatType; - this.doCfTaskBarFlash = this.dalamud.Configuration.DutyFinderTaskbarFlash; - this.doCfChatMessage = this.dalamud.Configuration.DutyFinderChatMessage; + this.doCfTaskBarFlash = configuration.DutyFinderTaskbarFlash; + this.doCfChatMessage = configuration.DutyFinderChatMessage; - this.globalUiScale = this.dalamud.Configuration.GlobalUiScale; - this.doToggleUiHide = this.dalamud.Configuration.ToggleUiHide; - this.doToggleUiHideDuringCutscenes = this.dalamud.Configuration.ToggleUiHideDuringCutscenes; - this.doToggleUiHideDuringGpose = this.dalamud.Configuration.ToggleUiHideDuringGpose; + this.globalUiScale = configuration.GlobalUiScale; + this.doToggleUiHide = configuration.ToggleUiHide; + this.doToggleUiHideDuringCutscenes = configuration.ToggleUiHideDuringCutscenes; + this.doToggleUiHideDuringGpose = configuration.ToggleUiHideDuringGpose; - this.doDocking = this.dalamud.Configuration.IsDocking; - this.doViewport = !this.dalamud.Configuration.IsDisableViewport; - this.doGamepad = this.dalamud.Configuration.IsGamepadNavigationEnabled; + this.doDocking = configuration.IsDocking; + this.doViewport = !configuration.IsDisableViewport; + this.doGamepad = configuration.IsGamepadNavigationEnabled; - this.doPluginTest = this.dalamud.Configuration.DoPluginTest; - this.thirdRepoList = this.dalamud.Configuration.ThirdRepoList.Select(x => x.Clone()).ToList(); - this.devPluginLocations = this.dalamud.Configuration.DevPluginLoadLocations.Select(x => x.Clone()).ToList(); + this.doPluginTest = configuration.DoPluginTest; + this.thirdRepoList = configuration.ThirdRepoList.Select(x => x.Clone()).ToList(); + this.devPluginLocations = configuration.DevPluginLoadLocations.Select(x => x.Clone()).ToList(); - this.printPluginsWelcomeMsg = this.dalamud.Configuration.PrintPluginsWelcomeMsg; - this.autoUpdatePlugins = this.dalamud.Configuration.AutoUpdatePlugins; - this.doButtonsSystemMenu = this.dalamud.Configuration.DoButtonsSystemMenu; + this.printPluginsWelcomeMsg = configuration.PrintPluginsWelcomeMsg; + this.autoUpdatePlugins = configuration.AutoUpdatePlugins; + this.doButtonsSystemMenu = configuration.DoButtonsSystemMenu; this.languages = Localization.ApplicableLangCodes.Prepend("en").ToArray(); try { - if (string.IsNullOrEmpty(this.dalamud.Configuration.LanguageOverride)) + if (string.IsNullOrEmpty(configuration.LanguageOverride)) { var currentUiLang = CultureInfo.CurrentUICulture; @@ -113,7 +112,7 @@ namespace Dalamud.Interface.Internal.Windows } else { - this.langIndex = Array.IndexOf(this.languages, this.dalamud.Configuration.LanguageOverride); + this.langIndex = Array.IndexOf(this.languages, configuration.LanguageOverride); } } catch (Exception) @@ -156,14 +155,19 @@ namespace Dalamud.Interface.Internal.Windows /// public override void OnClose() { - ImGui.GetIO().FontGlobalScale = this.dalamud.Configuration.GlobalUiScale; - this.thirdRepoList = this.dalamud.Configuration.ThirdRepoList.Select(x => x.Clone()).ToList(); - this.devPluginLocations = this.dalamud.Configuration.DevPluginLoadLocations.Select(x => x.Clone()).ToList(); + var configuration = Service.Get(); + + ImGui.GetIO().FontGlobalScale = configuration.GlobalUiScale; + this.thirdRepoList = configuration.ThirdRepoList.Select(x => x.Clone()).ToList(); + this.devPluginLocations = configuration.DevPluginLoadLocations.Select(x => x.Clone()).ToList(); } /// public override void Draw() { + var configuration = Service.Get(); + var pluginManager = Service.Get(); + var windowSize = ImGui.GetWindowSize(); ImGui.BeginChild("scrolling", new Vector2(windowSize.X - 5 - (5 * ImGuiHelpers.GlobalScale), windowSize.Y - 35 - (35 * ImGuiHelpers.GlobalScale)), false, ImGuiWindowFlags.HorizontalScrollbar); @@ -273,8 +277,8 @@ namespace Dalamud.Interface.Internal.Windows if (ImGui.Button(Loc.Localize("DalamudSettingsClearHidden", "Clear hidden plugins"))) { - this.dalamud.Configuration.HiddenPluginInternalName.Clear(); - this.dalamud.PluginManager.RefilterPluginMasters(); + configuration.HiddenPluginInternalName.Clear(); + pluginManager.RefilterPluginMasters(); } ImGui.TextColored(this.hintTextColor, Loc.Localize("DalamudSettingsClearHiddenHint", "Restore plugins you have previously hidden from the plugin installer.")); @@ -525,13 +529,13 @@ namespace Dalamud.Interface.Internal.Windows if (this.thirdRepoListChanged) { - this.dalamud.PluginManager.SetPluginReposFromConfig(true); + pluginManager.SetPluginReposFromConfig(true); this.thirdRepoListChanged = false; } if (this.devPluginLocationsChanged) { - this.dalamud.PluginManager.ScanDevPlugins(); + pluginManager.ScanDevPlugins(); this.devPluginLocationsChanged = false; } } @@ -544,27 +548,30 @@ namespace Dalamud.Interface.Internal.Windows private void Save() { - this.dalamud.LocalizationManager.SetupWithLangCode(this.languages[this.langIndex]); - this.dalamud.Configuration.LanguageOverride = this.languages[this.langIndex]; + var configuration = Service.Get(); + var localization = Service.Get(); - this.dalamud.Configuration.GeneralChatType = this.dalamudMessagesChatType; + localization.SetupWithLangCode(this.languages[this.langIndex]); + configuration.LanguageOverride = this.languages[this.langIndex]; - this.dalamud.Configuration.DutyFinderTaskbarFlash = this.doCfTaskBarFlash; - this.dalamud.Configuration.DutyFinderChatMessage = this.doCfChatMessage; + configuration.GeneralChatType = this.dalamudMessagesChatType; - this.dalamud.Configuration.GlobalUiScale = this.globalUiScale; - this.dalamud.Configuration.ToggleUiHide = this.doToggleUiHide; - this.dalamud.Configuration.ToggleUiHideDuringCutscenes = this.doToggleUiHideDuringCutscenes; - this.dalamud.Configuration.ToggleUiHideDuringGpose = this.doToggleUiHideDuringGpose; + configuration.DutyFinderTaskbarFlash = this.doCfTaskBarFlash; + configuration.DutyFinderChatMessage = this.doCfChatMessage; - this.dalamud.Configuration.IsDocking = this.doDocking; - this.dalamud.Configuration.IsGamepadNavigationEnabled = this.doGamepad; + configuration.GlobalUiScale = this.globalUiScale; + configuration.ToggleUiHide = this.doToggleUiHide; + configuration.ToggleUiHideDuringCutscenes = this.doToggleUiHideDuringCutscenes; + configuration.ToggleUiHideDuringGpose = this.doToggleUiHideDuringGpose; + + configuration.IsDocking = this.doDocking; + configuration.IsGamepadNavigationEnabled = this.doGamepad; // This is applied every frame in InterfaceManager::CheckViewportState() - this.dalamud.Configuration.IsDisableViewport = !this.doViewport; + configuration.IsDisableViewport = !this.doViewport; // Apply docking flag - if (!this.dalamud.Configuration.IsDocking) + if (!configuration.IsDocking) { ImGui.GetIO().ConfigFlags &= ~ImGuiConfigFlags.DockingEnable; } @@ -574,7 +581,7 @@ namespace Dalamud.Interface.Internal.Windows } // NOTE (Chiv) Toggle gamepad navigation via setting - if (!this.dalamud.Configuration.IsGamepadNavigationEnabled) + if (!configuration.IsGamepadNavigationEnabled) { ImGui.GetIO().BackendFlags &= ~ImGuiBackendFlags.HasGamepad; ImGui.GetIO().ConfigFlags &= ~ImGuiConfigFlags.NavEnableSetMousePos; @@ -585,17 +592,17 @@ namespace Dalamud.Interface.Internal.Windows ImGui.GetIO().ConfigFlags |= ImGuiConfigFlags.NavEnableSetMousePos; } - this.dalamud.Configuration.DoPluginTest = this.doPluginTest; - this.dalamud.Configuration.ThirdRepoList = this.thirdRepoList.Select(x => x.Clone()).ToList(); - this.dalamud.Configuration.DevPluginLoadLocations = this.devPluginLocations.Select(x => x.Clone()).ToList(); + configuration.DoPluginTest = this.doPluginTest; + configuration.ThirdRepoList = this.thirdRepoList.Select(x => x.Clone()).ToList(); + configuration.DevPluginLoadLocations = this.devPluginLocations.Select(x => x.Clone()).ToList(); - this.dalamud.Configuration.PrintPluginsWelcomeMsg = this.printPluginsWelcomeMsg; - this.dalamud.Configuration.AutoUpdatePlugins = this.autoUpdatePlugins; - this.dalamud.Configuration.DoButtonsSystemMenu = this.doButtonsSystemMenu; + configuration.PrintPluginsWelcomeMsg = this.printPluginsWelcomeMsg; + configuration.AutoUpdatePlugins = this.autoUpdatePlugins; + configuration.DoButtonsSystemMenu = this.doButtonsSystemMenu; - this.dalamud.Configuration.Save(); + configuration.Save(); - this.dalamud.PluginManager.ReloadPluginMasters(); + Service.Get().ReloadPluginMasters(); } } } diff --git a/Dalamud/Interface/UiBuilder.cs b/Dalamud/Interface/UiBuilder.cs index f6590009e..f888442c2 100644 --- a/Dalamud/Interface/UiBuilder.cs +++ b/Dalamud/Interface/UiBuilder.cs @@ -2,7 +2,9 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using Dalamud.Configuration.Internal; using Dalamud.Game.ClientState.Conditions; +using Dalamud.Game.Gui; using Dalamud.Interface.Internal; using ImGuiNET; using ImGuiScene; @@ -17,7 +19,6 @@ namespace Dalamud.Interface /// public sealed class UiBuilder : IDisposable { - private readonly Dalamud dalamud; private readonly Stopwatch stopwatch; private readonly string namespaceName; @@ -27,15 +28,13 @@ namespace Dalamud.Interface /// Initializes a new instance of the class and registers it. /// You do not have to call this manually. /// - /// The dalamud to register on. /// The plugin namespace. - internal UiBuilder(Dalamud dalamud, string namespaceName) + internal UiBuilder(string namespaceName) { - this.dalamud = dalamud; this.stopwatch = new Stopwatch(); this.namespaceName = namespaceName; - this.dalamud.InterfaceManager.Draw += this.OnDraw; + Service.Get().Draw += this.OnDraw; } /// @@ -67,12 +66,12 @@ namespace Dalamud.Interface /// /// Gets the game's active Direct3D device. /// - public Device Device => this.dalamud.InterfaceManager.Device; + public Device Device => Service.Get().Device; /// /// Gets the game's main window handle. /// - public IntPtr WindowHandlePtr => this.dalamud.InterfaceManager.WindowHandlePtr; + public IntPtr WindowHandlePtr => Service.Get().WindowHandlePtr; /// /// Gets or sets a value indicating whether this plugin should hide its UI automatically when the game's UI is hidden. @@ -99,8 +98,8 @@ namespace Dalamud.Interface /// public bool OverrideGameCursor { - get => this.dalamud.InterfaceManager.OverrideGameCursor; - set => this.dalamud.InterfaceManager.OverrideGameCursor = value; + get => Service.Get().OverrideGameCursor; + set => Service.Get().OverrideGameCursor = value; } /// @@ -112,8 +111,8 @@ namespace Dalamud.Interface /// public Action OnBuildFonts { - get => this.dalamud.InterfaceManager.OnBuildFonts; - set => this.dalamud.InterfaceManager.OnBuildFonts = value; + get => Service.Get().OnBuildFonts; + set => Service.Get().OnBuildFonts = value; } /// @@ -145,12 +144,24 @@ namespace Dalamud.Interface /// internal List DrawTimeHistory { get; set; } = new List(); - private bool CutsceneActive => this.dalamud.ClientState != null && - (this.dalamud.ClientState.Condition[ConditionFlag.OccupiedInCutSceneEvent] || - this.dalamud.ClientState.Condition[ConditionFlag.WatchingCutscene78]); + private bool CutsceneActive + { + get + { + var condition = Service.Get(); + return condition[ConditionFlag.OccupiedInCutSceneEvent] + || condition[ConditionFlag.WatchingCutscene78]; + } + } - private bool GposeActive => this.dalamud.ClientState != null && - this.dalamud.ClientState.Condition[ConditionFlag.WatchingCutscene]; + private bool GposeActive + { + get + { + var condition = Service.Get(); + return condition[ConditionFlag.WatchingCutscene]; + } + } /// /// Loads an image from the specified file. @@ -158,7 +169,7 @@ namespace Dalamud.Interface /// The full filepath to the image. /// A object wrapping the created image. Use inside ImGui.Image(). public TextureWrap LoadImage(string filePath) => - this.dalamud.InterfaceManager.LoadImage(filePath); + Service.Get().LoadImage(filePath); /// /// Loads an image from a byte stream, such as a png downloaded into memory. @@ -166,7 +177,7 @@ namespace Dalamud.Interface /// A byte array containing the raw image data. /// A object wrapping the created image. Use inside ImGui.Image(). public TextureWrap LoadImage(byte[] imageData) => - this.dalamud.InterfaceManager.LoadImage(imageData); + Service.Get().LoadImage(imageData); /// /// Loads an image from raw unformatted pixel data, with no type or header information. To load formatted data, use . @@ -177,7 +188,7 @@ namespace Dalamud.Interface /// The number of channels (bytes per pixel) of the image contained in . This should usually be 4. /// A object wrapping the created image. Use inside ImGui.Image(). public TextureWrap LoadImageRaw(byte[] imageData, int width, int height, int numChannels) => - this.dalamud.InterfaceManager.LoadImageRaw(imageData, width, height, numChannels); + Service.Get().LoadImageRaw(imageData, width, height, numChannels); /// /// Call this to queue a rebuild of the font atlas.
@@ -187,7 +198,7 @@ namespace Dalamud.Interface public void RebuildFonts() { Log.Verbose("[FONT] {0} plugin is initiating FONT REBUILD", this.namespaceName); - this.dalamud.InterfaceManager.RebuildFonts(); + Service.Get().RebuildFonts(); } /// @@ -195,7 +206,7 @@ namespace Dalamud.Interface /// public void Dispose() { - this.dalamud.InterfaceManager.Draw -= this.OnDraw; + Service.Get().Draw -= this.OnDraw; } /// @@ -208,12 +219,16 @@ namespace Dalamud.Interface private void OnDraw() { - if ((this.dalamud.Framework.Gui.GameUiHidden && this.dalamud.Configuration.ToggleUiHide && !(this.DisableUserUiHide || this.DisableAutomaticUiHide)) || - (this.CutsceneActive && this.dalamud.Configuration.ToggleUiHideDuringCutscenes && !(this.DisableCutsceneUiHide || this.DisableAutomaticUiHide)) || - (this.GposeActive && this.dalamud.Configuration.ToggleUiHideDuringGpose && !(this.DisableGposeUiHide || this.DisableAutomaticUiHide))) + var configuration = Service.Get(); + var gameGui = Service.Get(); + var interfaceManager = Service.Get(); + + if ((gameGui.GameUiHidden && configuration.ToggleUiHide && !(this.DisableUserUiHide || this.DisableAutomaticUiHide)) || + (this.CutsceneActive && configuration.ToggleUiHideDuringCutscenes && !(this.DisableCutsceneUiHide || this.DisableAutomaticUiHide)) || + (this.GposeActive && configuration.ToggleUiHideDuringGpose && !(this.DisableGposeUiHide || this.DisableAutomaticUiHide))) return; - if (!this.dalamud.InterfaceManager.FontsReady) + if (!interfaceManager.FontsReady) return; ImGui.PushID(this.namespaceName); diff --git a/Dalamud/IoC/Internal/InterfaceVersionAttribute.cs b/Dalamud/IoC/Internal/InterfaceVersionAttribute.cs new file mode 100644 index 000000000..f6e6c1001 --- /dev/null +++ b/Dalamud/IoC/Internal/InterfaceVersionAttribute.cs @@ -0,0 +1,25 @@ +using System; + +namespace Dalamud.IoC.Internal +{ + /// + /// This attribute represents the current version of a module that is loaded in the Service Locator. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] + internal class InterfaceVersionAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The current version. + public InterfaceVersionAttribute(string version) + { + this.Version = new(version); + } + + /// + /// Gets the service version. + /// + public Version Version { get; } + } +} diff --git a/Dalamud/IoC/PluginInterfaceAttribute.cs b/Dalamud/IoC/PluginInterfaceAttribute.cs new file mode 100644 index 000000000..98d330117 --- /dev/null +++ b/Dalamud/IoC/PluginInterfaceAttribute.cs @@ -0,0 +1,12 @@ +using System; + +namespace Dalamud.IoC +{ + /// + /// This attribute indicates whether the decorated class should be exposed to plugins via IoC. + /// + [AttributeUsage(AttributeTargets.Class)] + public class PluginInterfaceAttribute : Attribute + { + } +} diff --git a/Dalamud/IoC/RequiredVersionAttribute.cs b/Dalamud/IoC/RequiredVersionAttribute.cs new file mode 100644 index 000000000..537d6e7a6 --- /dev/null +++ b/Dalamud/IoC/RequiredVersionAttribute.cs @@ -0,0 +1,25 @@ +using System; + +namespace Dalamud.IoC +{ + /// + /// This attribute indicates the version of a service module that is required for the plugin to load. + /// + [AttributeUsage(AttributeTargets.Parameter)] + public class RequiredVersionAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The required version. + public RequiredVersionAttribute(string version) + { + this.Version = new(version); + } + + /// + /// Gets the required version. + /// + public Version Version { get; } + } +} diff --git a/Dalamud/Memory/MemoryHelper.cs b/Dalamud/Memory/MemoryHelper.cs index 08c624bfc..e76bfae25 100644 --- a/Dalamud/Memory/MemoryHelper.cs +++ b/Dalamud/Memory/MemoryHelper.cs @@ -18,8 +18,6 @@ namespace Dalamud.Memory /// public static unsafe class MemoryHelper { - private static SeStringManager seStringManager; - #region Read /// @@ -232,7 +230,7 @@ namespace Dalamud.Memory public static SeString ReadSeStringNullTerminated(IntPtr memoryAddress) { var buffer = ReadRawNullTerminated(memoryAddress); - return seStringManager.Parse(buffer); + return Service.Get().Parse(buffer); } /// @@ -248,13 +246,13 @@ namespace Dalamud.Memory var eos = Array.IndexOf(buffer, (byte)0); if (eos < 0) { - return seStringManager.Parse(buffer); + return Service.Get().Parse(buffer); } else { var newBuffer = new byte[eos]; Buffer.BlockCopy(buffer, 0, newBuffer, 0, eos); - return seStringManager.Parse(newBuffer); + return Service.Get().Parse(newBuffer); } } @@ -655,14 +653,5 @@ namespace Dalamud.Memory => SizeOf(marshal) * elementCount; #endregion - - /// - /// Initialize with static access to Dalamud. - /// - /// The Dalamud instance. - internal static void Initialize(Dalamud dalamud) - { - seStringManager = dalamud.SeStringManager; - } } } diff --git a/Dalamud/Plugin/DalamudPluginInterface.cs b/Dalamud/Plugin/DalamudPluginInterface.cs index 0cd7007a4..e5494ea91 100644 --- a/Dalamud/Plugin/DalamudPluginInterface.cs +++ b/Dalamud/Plugin/DalamudPluginInterface.cs @@ -11,12 +11,14 @@ using Dalamud.Data; using Dalamud.Game; using Dalamud.Game.ClientState; using Dalamud.Game.Command; -using Dalamud.Game.Internal; +using Dalamud.Game.Gui; using Dalamud.Game.Text; using Dalamud.Game.Text.Sanitizer; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Interface; +using Dalamud.Interface.Internal; +using Dalamud.Plugin.Internal; namespace Dalamud.Plugin { @@ -25,7 +27,6 @@ namespace Dalamud.Plugin /// public sealed class DalamudPluginInterface : IDisposable { - private readonly Dalamud dalamud; private readonly string pluginName; private readonly PluginConfigurations configs; @@ -33,29 +34,30 @@ namespace Dalamud.Plugin /// Initializes a new instance of the class. /// Set up the interface and populate all fields needed. /// - /// The dalamud instance to expose. /// The internal name of the plugin. /// The reason the plugin was loaded. - internal DalamudPluginInterface(Dalamud dalamud, string pluginName, PluginLoadReason reason) + internal DalamudPluginInterface(string pluginName, PluginLoadReason reason) { - this.CommandManager = dalamud.CommandManager; - this.Framework = dalamud.Framework; - this.ClientState = dalamud.ClientState; - this.UiBuilder = new UiBuilder(dalamud, pluginName); - this.TargetModuleScanner = dalamud.SigScanner; - this.Data = dalamud.Data; - this.SeStringManager = dalamud.SeStringManager; + var configuration = Service.Get(); + var localization = Service.Get(); + + this.CommandManager = Service.Get(); + this.Framework = Service.Get(); + this.ClientState = Service.Get(); + this.UiBuilder = new UiBuilder(pluginName); + this.TargetModuleScanner = Service.Get(); + this.Data = Service.Get(); + this.SeStringManager = Service.Get(); - this.dalamud = dalamud; this.pluginName = pluginName; - this.configs = dalamud.PluginManager.PluginConfigs; + this.configs = Service.Get().PluginConfigs; this.Reason = reason; - this.GeneralChatType = this.dalamud.Configuration.GeneralChatType; + this.GeneralChatType = configuration.GeneralChatType; this.Sanitizer = new Sanitizer(this.Data.Language); - if (this.dalamud.Configuration.LanguageOverride != null) + if (configuration.LanguageOverride != null) { - this.UiLanguage = this.dalamud.Configuration.LanguageOverride; + this.UiLanguage = configuration.LanguageOverride; } else { @@ -66,8 +68,8 @@ namespace Dalamud.Plugin this.UiLanguage = "en"; } - dalamud.LocalizationManager.OnLocalizationChanged += this.OnLocalizationChanged; - dalamud.Configuration.OnDalamudConfigurationSaved += this.OnDalamudConfigurationSaved; + localization.OnLocalizationChanged += this.OnLocalizationChanged; + configuration.OnDalamudConfigurationSaved += this.OnDalamudConfigurationSaved; } /// @@ -89,7 +91,7 @@ namespace Dalamud.Plugin /// /// Gets the directory Dalamud assets are stored in. /// - public DirectoryInfo DalamudAssetDirectory => this.dalamud.AssetDirectory; + public DirectoryInfo DalamudAssetDirectory => Service.Get().AssetDirectory; /// /// Gets the directory your plugin configurations are stored in. @@ -142,7 +144,7 @@ namespace Dalamud.Plugin #if DEBUG public bool IsDebugging => true; #else - public bool IsDebugging => this.dalamud.DalamudUi.IsDevMenuOpen; + public bool IsDebugging => Service.Get().IsDevMenuOpen; #endif /// @@ -230,7 +232,7 @@ namespace Dalamud.Plugin /// Returns an SeString payload for the link. public DalamudLinkPayload AddChatLinkHandler(uint commandId, Action commandAction) { - return this.Framework.Gui.Chat.AddChatLinkHandler(this.pluginName, commandId, commandAction); + return Service.Get().AddChatLinkHandler(this.pluginName, commandId, commandAction); } /// @@ -239,7 +241,7 @@ namespace Dalamud.Plugin /// The ID of the command. public void RemoveChatLinkHandler(uint commandId) { - this.Framework.Gui.Chat.RemoveChatLinkHandler(this.pluginName, commandId); + Service.Get().RemoveChatLinkHandler(this.pluginName, commandId); } /// @@ -247,7 +249,7 @@ namespace Dalamud.Plugin /// public void RemoveChatLinkHandler() { - this.Framework.Gui.Chat.RemoveChatLinkHandler(this.pluginName); + Service.Get().RemoveChatLinkHandler(this.pluginName); } #endregion @@ -274,10 +276,12 @@ namespace Dalamud.Plugin [Obsolete("The current IPC mechanism is obsolete and scheduled to be replaced after API level 3.")] public void Subscribe(string pluginName, Action action) { - if (this.dalamud.PluginManager.IpcSubscriptions.Any(x => x.SourcePluginName == this.pluginName && x.SubPluginName == pluginName)) + var pluginManager = Service.Get(); + + if (pluginManager.IpcSubscriptions.Any(x => x.SourcePluginName == this.pluginName && x.SubPluginName == pluginName)) throw new InvalidOperationException("Can't add multiple subscriptions for the same plugin."); - this.dalamud.PluginManager.IpcSubscriptions.Add(new(this.pluginName, pluginName, action)); + pluginManager.IpcSubscriptions.Add(new(this.pluginName, pluginName, action)); } /// @@ -299,11 +303,13 @@ namespace Dalamud.Plugin [Obsolete("The current IPC mechanism is obsolete and scheduled to be replaced after API level 3.")] public void Unsubscribe(string pluginName) { - var sub = this.dalamud.PluginManager.IpcSubscriptions.FirstOrDefault(x => x.SourcePluginName == this.pluginName && x.SubPluginName == pluginName); + var pluginManager = Service.Get(); + + var sub = pluginManager.IpcSubscriptions.FirstOrDefault(x => x.SourcePluginName == this.pluginName && x.SubPluginName == pluginName); if (sub.SubAction == null) throw new InvalidOperationException("Wasn't subscribed to this plugin."); - this.dalamud.PluginManager.IpcSubscriptions.Remove(sub); + pluginManager.IpcSubscriptions.Remove(sub); } /// @@ -313,7 +319,9 @@ namespace Dalamud.Plugin [Obsolete("The current IPC mechanism is obsolete and scheduled to be replaced after API level 3.")] public void SendMessage(ExpandoObject message) { - var subs = this.dalamud.PluginManager.IpcSubscriptions.Where(x => x.SubPluginName == this.pluginName); + var pluginManager = Service.Get(); + + var subs = pluginManager.IpcSubscriptions.Where(x => x.SubPluginName == this.pluginName); foreach (var sub in subs.Select(x => x.SubAction)) { sub.Invoke(message); @@ -329,7 +337,9 @@ namespace Dalamud.Plugin [Obsolete("The current IPC mechanism is obsolete and scheduled to be replaced after API level 3.")] public bool SendMessage(string pluginName, ExpandoObject message) { - var plugin = this.dalamud.PluginManager.InstalledPlugins.FirstOrDefault(x => x.Manifest.InternalName == pluginName); + var pluginManager = Service.Get(); + + var plugin = pluginManager.InstalledPlugins.FirstOrDefault(x => x.Manifest.InternalName == pluginName); if (plugin == default) return false; @@ -350,9 +360,9 @@ namespace Dalamud.Plugin public void Dispose() { this.UiBuilder.Dispose(); - this.Framework.Gui.Chat.RemoveChatLinkHandler(this.pluginName); - this.dalamud.LocalizationManager.OnLocalizationChanged -= this.OnLocalizationChanged; - this.dalamud.Configuration.OnDalamudConfigurationSaved -= this.OnDalamudConfigurationSaved; + Service.Get().RemoveChatLinkHandler(this.pluginName); + Service.Get().OnLocalizationChanged -= this.OnLocalizationChanged; + Service.Get().OnDalamudConfigurationSaved -= this.OnDalamudConfigurationSaved; } private void OnLocalizationChanged(string langCode) diff --git a/Dalamud/Plugin/Internal/LocalDevPlugin.cs b/Dalamud/Plugin/Internal/LocalDevPlugin.cs index f874267a8..ac6152495 100644 --- a/Dalamud/Plugin/Internal/LocalDevPlugin.cs +++ b/Dalamud/Plugin/Internal/LocalDevPlugin.cs @@ -27,16 +27,17 @@ namespace Dalamud.Plugin.Internal /// /// Initializes a new instance of the class. /// - /// Dalamud instance. /// Path to the DLL file. /// The plugin manifest. - public LocalDevPlugin(Dalamud dalamud, FileInfo dllFile, LocalPluginManifest manifest) - : base(dalamud, dllFile, manifest) + public LocalDevPlugin(FileInfo dllFile, LocalPluginManifest? manifest) + : base(dllFile, manifest) { - if (!dalamud.Configuration.DevPluginSettings.TryGetValue(dllFile.FullName, out this.devSettings)) + var configuration = Service.Get(); + + if (!configuration.DevPluginSettings.TryGetValue(dllFile.FullName, out this.devSettings)) { - dalamud.Configuration.DevPluginSettings[dllFile.FullName] = this.devSettings = new DevPluginSettings(); - dalamud.Configuration.Save(); + configuration.DevPluginSettings[dllFile.FullName] = this.devSettings = new DevPluginSettings(); + configuration.Save(); } if (this.AutomaticReload) diff --git a/Dalamud/Plugin/Internal/LocalPlugin.cs b/Dalamud/Plugin/Internal/LocalPlugin.cs index 3a57b25be..80983ab2c 100644 --- a/Dalamud/Plugin/Internal/LocalPlugin.cs +++ b/Dalamud/Plugin/Internal/LocalPlugin.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Reflection; +using Dalamud.Configuration.Internal; using Dalamud.Game; using Dalamud.Logging.Internal; using Dalamud.Plugin.Internal.Exceptions; @@ -19,7 +20,6 @@ namespace Dalamud.Plugin.Internal { private static readonly ModuleLog Log = new("LOCALPLUGIN"); - private readonly Dalamud dalamud; private readonly FileInfo manifestFile; private readonly FileInfo disabledFile; private readonly FileInfo testingFile; @@ -32,12 +32,10 @@ namespace Dalamud.Plugin.Internal /// /// Initializes a new instance of the class. /// - /// Dalamud instance. /// Path to the DLL file. /// The plugin manifest. - public LocalPlugin(Dalamud dalamud, FileInfo dllFile, LocalPluginManifest manifest) + public LocalPlugin(FileInfo dllFile, LocalPluginManifest?manifest) { - this.dalamud = dalamud; this.DllFile = dllFile; this.State = PluginState.Unloaded; @@ -192,6 +190,10 @@ namespace Dalamud.Plugin.Internal /// Load while reloading. public void Load(PluginLoadReason reason, bool reloading = false) { + var startInfo = Service.Get(); + var configuration = Service.Get(); + var pluginManager = Service.Get(); + // Allowed: Unloaded switch (this.State) { @@ -205,10 +207,10 @@ namespace Dalamud.Plugin.Internal throw new InvalidPluginOperationException($"Unable to load {this.Name}, unload previously faulted, restart Dalamud"); } - if (this.Manifest.ApplicableVersion < this.dalamud.StartInfo.GameVersion) + if (this.Manifest.ApplicableVersion < startInfo.GameVersion) throw new InvalidPluginOperationException($"Unable to load {this.Name}, no applicable version"); - if (this.Manifest.DalamudApiLevel < PluginManager.DalamudApiLevel && !this.dalamud.Configuration.LoadAllApiLevels) + if (this.Manifest.DalamudApiLevel < PluginManager.DalamudApiLevel && !configuration.LoadAllApiLevels) throw new InvalidPluginOperationException($"Unable to load {this.Name}, incompatible API level"); if (this.Manifest.Disabled) @@ -243,7 +245,7 @@ namespace Dalamud.Plugin.Internal // Check for any loaded plugins with the same assembly name var assemblyName = this.pluginAssembly.GetName().Name; - foreach (var otherPlugin in this.dalamud.PluginManager.InstalledPlugins) + foreach (var otherPlugin in pluginManager.InstalledPlugins) { // During hot-reloading, this plugin will be in the plugin list, and the instance will have been disposed if (otherPlugin == this || otherPlugin.instance == null) @@ -272,7 +274,7 @@ namespace Dalamud.Plugin.Internal this.Manifest.Save(this.manifestFile); } - this.DalamudInterface = new DalamudPluginInterface(this.dalamud, this.pluginAssembly.GetName().Name, reason); + this.DalamudInterface = new DalamudPluginInterface(this.pluginAssembly.GetName().Name, reason); if (this.IsDev) { diff --git a/Dalamud/Plugin/Internal/PluginManager.cs b/Dalamud/Plugin/Internal/PluginManager.cs index 77a2118b4..204f025fb 100644 --- a/Dalamud/Plugin/Internal/PluginManager.cs +++ b/Dalamud/Plugin/Internal/PluginManager.cs @@ -13,6 +13,8 @@ using System.Threading.Tasks; using CheapLoc; using Dalamud.Configuration; +using Dalamud.Configuration.Internal; +using Dalamud.Game.Gui; using Dalamud.Game.Text; using Dalamud.Logging.Internal; using Dalamud.Plugin.Internal.Exceptions; @@ -36,7 +38,6 @@ namespace Dalamud.Plugin.Internal private static readonly ModuleLog Log = new("PLUGINM"); - private readonly Dalamud dalamud; private readonly DirectoryInfo pluginDirectory; private readonly DirectoryInfo devPluginDirectory; private readonly BannedPlugin[] bannedPlugins; @@ -48,12 +49,12 @@ namespace Dalamud.Plugin.Internal /// /// Initializes a new instance of the class. /// - /// The instance to load plugins with. - public PluginManager(Dalamud dalamud) + public PluginManager() { - this.dalamud = dalamud; - this.pluginDirectory = new DirectoryInfo(dalamud.StartInfo.PluginDirectory); - this.devPluginDirectory = new DirectoryInfo(dalamud.StartInfo.DefaultPluginDirectory); + var startInfo = Service.Get(); + + this.pluginDirectory = new DirectoryInfo(startInfo.PluginDirectory); + this.devPluginDirectory = new DirectoryInfo(startInfo.DefaultPluginDirectory); if (!this.pluginDirectory.Exists) this.pluginDirectory.Create(); @@ -61,9 +62,9 @@ namespace Dalamud.Plugin.Internal if (!this.devPluginDirectory.Exists) this.devPluginDirectory.Create(); - this.PluginConfigs = new PluginConfigurations(Path.Combine(Path.GetDirectoryName(dalamud.StartInfo.ConfigurationPath), "pluginConfigs")); + this.PluginConfigs = new PluginConfigurations(Path.Combine(Path.GetDirectoryName(startInfo.ConfigurationPath) ?? string.Empty, "pluginConfigs")); - var bannedPluginsJson = File.ReadAllText(Path.Combine(this.dalamud.StartInfo.AssetDirectory, "UIRes", "bannedplugin.json")); + var bannedPluginsJson = File.ReadAllText(Path.Combine(startInfo.AssetDirectory, "UIRes", "bannedplugin.json")); this.bannedPlugins = JsonConvert.DeserializeObject(bannedPluginsJson); this.SetPluginReposFromConfig(false); @@ -143,8 +144,10 @@ namespace Dalamud.Plugin.Internal /// Whether the available plugins changed should be evented after. public void SetPluginReposFromConfig(bool notify) { + var configuration = Service.Get(); + var repos = new List() { PluginRepository.MainRepo }; - repos.AddRange(this.dalamud.Configuration.ThirdRepoList + repos.AddRange(configuration.ThirdRepoList .Select(repo => new PluginRepository(repo.Url, repo.IsEnabled))); this.Repos = repos; @@ -159,12 +162,14 @@ namespace Dalamud.Plugin.Internal /// public void LoadAllPlugins() { - if (this.dalamud.Configuration.PluginSafeMode) + var configuration = Service.Get(); + + if (configuration.PluginSafeMode) { Log.Information("PluginSafeMode was enabled, not loading any plugins."); - this.dalamud.Configuration.PluginSafeMode = false; - this.dalamud.Configuration.Save(); + configuration.PluginSafeMode = false; + configuration.Save(); return; } @@ -198,7 +203,7 @@ namespace Dalamud.Plugin.Internal // devPlugins are more freeform. Look for any dll and hope to get lucky. var devDllFiles = this.devPluginDirectory.GetFiles("*.dll", SearchOption.AllDirectories).ToList(); - foreach (var setting in this.dalamud.Configuration.DevPluginLoadLocations) + foreach (var setting in configuration.DevPluginLoadLocations) { if (!setting.IsEnabled) continue; @@ -304,7 +309,7 @@ namespace Dalamud.Plugin.Internal /// public void RefilterPluginMasters() { - this.availablePlugins = this.dalamud.PluginManager.Repos + this.availablePlugins = this.Repos .SelectMany(repo => repo.PluginMaster) .Where(this.IsManifestEligible) .Where(this.IsManifestVisible) @@ -320,13 +325,15 @@ namespace Dalamud.Plugin.Internal /// public void ScanDevPlugins() { + var configuration = Service.Get(); + if (!this.devPluginDirectory.Exists) this.devPluginDirectory.Create(); // devPlugins are more freeform. Look for any dll and hope to get lucky. var devDllFiles = this.devPluginDirectory.GetFiles("*.dll", SearchOption.AllDirectories).ToList(); - foreach (var setting in this.dalamud.Configuration.DevPluginLoadLocations) + foreach (var setting in configuration.DevPluginLoadLocations) { if (!setting.IsEnabled) continue; @@ -483,7 +490,7 @@ namespace Dalamud.Plugin.Internal if (isDev) { Log.Information($"Loading dev plugin {name}"); - var devPlugin = new LocalDevPlugin(this.dalamud, dllFile, manifest); + var devPlugin = new LocalDevPlugin(dllFile, manifest); loadPlugin &= !isBoot || devPlugin.StartOnBoot; // If we're not loading it, make sure it's disabled @@ -495,7 +502,7 @@ namespace Dalamud.Plugin.Internal else { Log.Information($"Loading plugin {name}"); - plugin = new LocalPlugin(this.dalamud, dllFile, manifest); + plugin = new LocalPlugin(dllFile, manifest); } if (loadPlugin) @@ -559,6 +566,9 @@ namespace Dalamud.Plugin.Internal /// public void CleanupPlugins() { + var configuration = Service.Get(); + var startInfo = Service.Get(); + foreach (var pluginDir in this.pluginDirectory.GetDirectories()) { try @@ -617,14 +627,14 @@ namespace Dalamud.Plugin.Internal continue; } - if (manifest.DalamudApiLevel < DalamudApiLevel - 1 && !this.dalamud.Configuration.LoadAllApiLevels) + if (manifest.DalamudApiLevel < DalamudApiLevel - 1 && !configuration.LoadAllApiLevels) { Log.Information($"Lower API: cleaning up {versionDir.FullName}"); versionDir.Delete(true); continue; } - if (manifest.ApplicableVersion < this.dalamud.StartInfo.GameVersion - TimeSpan.FromDays(90)) + if (manifest.ApplicableVersion < startInfo.GameVersion) { Log.Information($"Inapplicable version: cleaning up {versionDir.FullName}"); versionDir.Delete(true); @@ -778,19 +788,21 @@ namespace Dalamud.Plugin.Internal /// The header text to send to chat prior to any update info. public void PrintUpdatedPlugins(List updateMetadata, string header) { + var chatGui = Service.Get(); + if (updateMetadata != null && updateMetadata.Count > 0) { - this.dalamud.Framework.Gui.Chat.Print(header); + chatGui.Print(header); foreach (var metadata in updateMetadata) { if (metadata.WasUpdated) { - this.dalamud.Framework.Gui.Chat.Print(Locs.DalamudPluginUpdateSuccessful(metadata.Name, metadata.Version)); + chatGui.Print(Locs.DalamudPluginUpdateSuccessful(metadata.Name, metadata.Version)); } else { - this.dalamud.Framework.Gui.Chat.PrintChat(new XivChatEntry + chatGui.PrintChat(new XivChatEntry { Message = Locs.DalamudPluginUpdateFailed(metadata.Name, metadata.Version), Type = XivChatType.Urgent, @@ -808,7 +820,9 @@ namespace Dalamud.Plugin.Internal /// A value indicating whether testing should be used. public bool UseTesting(PluginManifest manifest) { - if (!this.dalamud.Configuration.DoPluginTest) + var configuration = Service.Get(); + + if (!configuration.DoPluginTest) return false; if (manifest.IsTestingExclusive) @@ -836,8 +850,10 @@ namespace Dalamud.Plugin.Internal /// If the manifest is visible. public bool IsManifestVisible(RemotePluginManifest manifest) { + var configuration = Service.Get(); + // Hidden by user - if (this.dalamud.Configuration.HiddenPluginInternalName.Contains(manifest.InternalName)) + if (configuration.HiddenPluginInternalName.Contains(manifest.InternalName)) return false; // Hidden by manifest @@ -855,16 +871,19 @@ namespace Dalamud.Plugin.Internal /// If the manifest is eligible. public bool IsManifestEligible(PluginManifest manifest) { + var configuration = Service.Get(); + var startInfo = Service.Get(); + // Testing exclusive - if (manifest.IsTestingExclusive && !this.dalamud.Configuration.DoPluginTest) + if (manifest.IsTestingExclusive && !configuration.DoPluginTest) return false; // Applicable version - if (manifest.ApplicableVersion < this.dalamud.StartInfo.GameVersion) + if (manifest.ApplicableVersion < startInfo.GameVersion) return false; // API level - if (manifest.DalamudApiLevel < DalamudApiLevel && !this.dalamud.Configuration.LoadAllApiLevels) + if (manifest.DalamudApiLevel < DalamudApiLevel && !configuration.LoadAllApiLevels) return false; // Banned diff --git a/Dalamud/Service{T}.cs b/Dalamud/Service{T}.cs new file mode 100644 index 000000000..daf291494 --- /dev/null +++ b/Dalamud/Service{T}.cs @@ -0,0 +1,122 @@ +using System; +using System.Reflection; + +using Dalamud.IoC; +using Dalamud.IoC.Internal; +using Dalamud.Logging.Internal; + +namespace Dalamud +{ + /// + /// Basic service locator. + /// + /// + /// Only used internally within Dalamud, if plugins need access to things it should be _only_ via DI. + /// + /// The class you want to store in the service locator. + internal static class Service where T : class + { + private static readonly ModuleLog Log = new("SVC"); + + private static T? instance; + + static Service() + { + } + + /// + /// Sets the type in the service locator to the given object. + /// + /// Object to set. + /// The set object. + public static T Set(T obj) + { + SetInstanceObject(obj); + + return instance!; + } + + /// + /// Sets the type in the service locator via the default parameterless constructor. + /// + /// The set object. + public static T Set() + { + var obj = (T?)Activator.CreateInstance(typeof(T), true); + + SetInstanceObject(obj); + + return instance!; + } + + /// + /// Sets a type in the service locator via a constructor with the given parameter types. + /// + /// Constructor arguments. + /// The set object. + public static T Set(params object[] args) + { + if (args == null) + { + throw new ArgumentNullException(nameof(args), $"Service locator was passed a null for type {typeof(T).FullName} parameterized constructor "); + } + + var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.OptionalParamBinding; + var obj = (T?)Activator.CreateInstance(typeof(T), flags, null, args, null, null); + + SetInstanceObject(obj); + + return obj; + } + + /// + /// Attempt to pull the instance out of the service locator. + /// + /// The object if registered. + /// Thrown when the object instance is not present in the service locator. + public static T Get() + { + return instance ?? throw new InvalidOperationException($"{typeof(T).FullName} has not been registered in the service locator!"); + } + + /// + /// Attempt to pull the instance out of the service locator. + /// + /// The object if registered, null otherwise. + public static T? GetNullable() + { + return instance; + } + + private static void SetInstanceObject(T instance) + { + Service.instance = instance ?? throw new ArgumentNullException(nameof(instance), $"Service locator received a null for type {typeof(T).FullName}"); + + var availableToPlugins = RegisterInIoCContainer(instance); + + if (availableToPlugins) + Log.Information($"Registered {typeof(T).FullName} into service locator and exposed to plugins"); + else + Log.Information($"Registered {typeof(T).FullName} into service locator privately"); + } + + private static bool RegisterInIoCContainer(T instance) + { + var attr = typeof(T).GetCustomAttribute(); + if (attr == null) + { + return false; + } + + var ioc = Service.GetNullable(); + if (ioc == null) + { + return false; + } + + ioc.RegisterSingleton(instance); + + return true; + } + } +} diff --git a/Dalamud/Troubleshooting.cs b/Dalamud/Troubleshooting.cs index c2cfa2e7e..bec723e3c 100644 --- a/Dalamud/Troubleshooting.cs +++ b/Dalamud/Troubleshooting.cs @@ -4,6 +4,9 @@ using System.Linq; using System.Text; using Dalamud.Configuration; +using Dalamud.Configuration.Internal; +using Dalamud.Interface.Internal; +using Dalamud.Plugin.Internal; using Dalamud.Plugin.Internal.Types; using Dalamud.Utility; using Newtonsoft.Json; @@ -48,19 +51,24 @@ namespace Dalamud /// Whether or not the interface was loaded. internal static void LogTroubleshooting(Dalamud dalamud, bool isInterfaceLoaded) { + var interfaceManager = Service.Get(); + var startInfo = Service.Get(); + var pluginManager = Service.Get(); + var configuration = Service.Get(); + try { var payload = new TroubleshootingPayload { - LoadedPlugins = dalamud.PluginManager.InstalledPlugins.Select(x => x.Manifest).ToArray(), + LoadedPlugins = pluginManager.InstalledPlugins.Select(x => x.Manifest).ToArray(), DalamudVersion = Util.AssemblyVersion, DalamudGitHash = Util.GetGitHash(), - GameVersion = dalamud.StartInfo.GameVersion.ToString(), - Language = dalamud.StartInfo.Language.ToString(), - DoDalamudTest = dalamud.Configuration.DoDalamudTest, - DoPluginTest = dalamud.Configuration.DoPluginTest, - InterfaceLoaded = isInterfaceLoaded, - ThirdRepo = dalamud.Configuration.ThirdRepoList, + GameVersion = startInfo.GameVersion.ToString(), + Language = startInfo.Language.ToString(), + DoDalamudTest = configuration.DoDalamudTest, + DoPluginTest = configuration.DoPluginTest, + InterfaceLoaded = interfaceManager.IsReady, + ThirdRepo = configuration.ThirdRepoList, }; var encodedPayload = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload)));