Implement service locator

This commit is contained in:
Raymond 2021-08-20 11:59:35 -04:00
parent 06b1163a52
commit ff1d7f2829
101 changed files with 1614 additions and 1436 deletions

View file

@ -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
{
/// <summary>
@ -49,14 +51,11 @@ namespace Dalamud
/// <param name="configuration">The Dalamud configuration.</param>
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<Dalamud>.Set(this);
Service<DalamudStartInfo>.Set(info);
Service<DalamudConfiguration>.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
/// <summary>
/// Gets the Dalamud singleton instance.
/// </summary>
internal static Dalamud Instance { get; private set; }
#endif
#region Native Game Subsystems
/// <summary>
/// Gets game framework subsystem.
/// </summary>
internal Framework Framework { get; private set; }
/// <summary>
/// Gets Anti-Debug detection prevention subsystem.
/// </summary>
internal AntiDebug AntiDebug { get; private set; }
/// <summary>
/// Gets WinSock optimization subsystem.
/// </summary>
internal WinSockHandlers WinSock2 { get; private set; }
/// <summary>
/// Gets Hook management subsystem.
/// </summary>
internal HookManager HookManager { get; private set; }
/// <summary>
/// Gets ImGui Interface subsystem.
/// </summary>
internal InterfaceManager InterfaceManager { get; private set; }
/// <summary>
/// Gets the Input Method subsystem.
/// </summary>
internal DalamudIME IME { get; private set; }
/// <summary>
/// Gets ClientState subsystem.
/// </summary>
internal ClientState ClientState { get; private set; }
#endregion
#region Dalamud Subsystems
/// <summary>
/// Gets Plugin Manager subsystem.
/// </summary>
internal PluginManager PluginManager { get; private set; }
/// <summary>
/// Gets Data provider subsystem.
/// </summary>
internal DataManager Data { get; private set; }
/// <summary>
/// Gets Command Manager subsystem.
/// </summary>
internal CommandManager CommandManager { get; private set; }
/// <summary>
/// Gets Localization subsystem facilitating localization for Dalamud and plugins.
/// </summary>
internal Localization LocalizationManager { get; private set; }
#endregion
#region Helpers
/// <summary>
/// Gets SeStringManager subsystem facilitating string parsing.
/// </summary>
internal SeStringManager SeStringManager { get; private set; }
/// <summary>
/// Gets copy-enabled SigScanner for target module.
/// </summary>
internal SigScanner SigScanner { get; private set; }
/// <summary>
/// Gets LoggingLevelSwitch for Dalamud and Plugin logs.
/// </summary>
internal LoggingLevelSwitch LogLevelSwitch { get; private set; }
/// <summary>
/// Gets StartInfo object passed from injector.
/// </summary>
internal DalamudStartInfo StartInfo { get; private set; }
/// <summary>
/// Gets Configuration object facilitating save and load of Dalamud configuration.
/// </summary>
internal DalamudConfiguration Configuration { get; private set; }
#endregion
#region Dalamud Core functionality
/// <summary>
/// Gets Dalamud base UI.
/// </summary>
internal DalamudInterface DalamudUi { get; private set; }
/// <summary>
/// Gets Dalamud chat commands.
/// </summary>
internal DalamudCommands DalamudCommands { get; private set; }
/// <summary>
/// Gets Dalamud chat-based features.
/// </summary>
internal ChatHandlers ChatHandlers { get; private set; }
/// <summary>
/// Gets Dalamud network-based features.
/// </summary>
internal NetworkHandlers NetworkHandlers { get; private set; }
/// <summary>
/// Gets subsystem responsible for adding the Dalamud menu items to the game's system menu.
/// </summary>
internal DalamudSystemMenu SystemMenu { get; private set; }
#endregion
/// <summary>
/// Gets Injected process module.
/// </summary>
internal ProcessModule TargetModule { get; private set; }
/// <summary>
/// Gets a value indicating whether Dalamud was successfully loaded.
/// </summary>
@ -206,12 +77,12 @@ namespace Dalamud
/// <summary>
/// Gets a value indicating whether the plugin system is loaded.
/// </summary>
internal bool IsLoadedPluginSystem => this.PluginManager != null;
internal bool IsLoadedPluginSystem => Service<PluginManager>.GetNullable() != null;
/// <summary>
/// Gets location of stored assets.
/// </summary>
internal DirectoryInfo AssetDirectory => new(this.StartInfo.AssetDirectory);
internal DirectoryInfo AssetDirectory => new(Service<DalamudStartInfo>.Get().AssetDirectory);
/// <summary>
/// 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<SigScanner>.Set(new SigScanner(true));
Service<HookManager>.Set();
Service<ServiceContainer>.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<Framework>.Set();
Log.Information("[T1] Framework OK!");
this.Framework.Enable();
Service<GameNetwork>.Set();
Service<GameGui>.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<DalamudConfiguration>.Get();
var antiDebug = Service<AntiDebug>.Set();
if (configuration.IsAntiAntiDebugEnabled)
antiDebug.Enable();
#if DEBUG
if (!antiDebug.IsEnabled)
antiDebug.Enable();
#endif
Log.Information("[T2] AntiDebug OK!");
this.WinSock2 = new WinSockHandlers();
Service<WinSockHandlers>.Set();
Log.Information("[T2] WinSock OK!");
this.NetworkHandlers = new NetworkHandlers(this, this.StartInfo.OptOutMbCollection);
Service<NetworkHandlers>.Set();
Log.Information("[T2] NH OK!");
this.ClientState = new ClientState(this, this.StartInfo, this.SigScanner);
Service<ClientState>.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<Localization>.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<InterfaceManager>.Set().Enable();
Log.Information("[T2] IM OK!");
}
@ -299,7 +173,7 @@ namespace Dalamud
try
{
this.IME = new DalamudIME(this);
Service<DalamudIME>.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<DataManager>.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<SeStringManager>.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<CommandManager>.Set();
Service<DalamudCommands>.Set().SetupCommands();
Log.Information("[T2] CM OK!");
this.ChatHandlers = new ChatHandlers(this);
Service<ChatHandlers>.Set();
Log.Information("[T2] CH OK!");
this.ClientState.Enable();
Service<ClientState>.Set().Enable();
Log.Information("[T2] CS ENABLE!");
this.SystemMenu = new DalamudSystemMenu(this);
this.SystemMenu.Enable();
Service<DalamudSystemMenu>.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<PluginManager>.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<DalamudInterface>.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<DalamudIME>.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<InterfaceManager>.GetNullable()?.Dispose();
this.DalamudUi?.Dispose();
Service<DalamudInterface>.GetNullable()?.Dispose();
this.PluginManager?.Dispose();
Service<PluginManager>.GetNullable()?.Dispose();
}
/// <summary>
@ -458,23 +329,17 @@ namespace Dalamud
Thread.Sleep(100);
}
this.Framework?.Dispose();
this.ClientState?.Dispose();
Service<Framework>.GetNullable()?.Dispose();
Service<ClientState>.GetNullable()?.Dispose();
this.unloadSignal?.Dispose();
this.WinSock2?.Dispose();
this.Data?.Dispose();
this.AntiDebug?.Dispose();
this.SystemMenu?.Dispose();
this.HookManager?.Dispose();
this.SigScanner?.Dispose();
Service<WinSockHandlers>.GetNullable()?.Dispose();
Service<DataManager>.GetNullable()?.Dispose();
Service<AntiDebug>.GetNullable()?.Dispose();
Service<DalamudSystemMenu>.GetNullable()?.Dispose();
Service<HookManager>.GetNullable()?.Dispose();
Service<SigScanner>.GetNullable()?.Dispose();
Log.Debug("Dalamud::Dispose() OK!");
}
@ -489,7 +354,8 @@ namespace Dalamud
/// </summary>
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<SigScanner>.Get().ScanText(releaseSig);
Log.Debug($"SE debug filter at {releaseFilter.ToInt64():X}");
var oldFilter = NativeFunctions.SetUnhandledExceptionFilter(releaseFilter);

View file

@ -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
/// <summary>
/// This class provides data for Dalamud-internal features, but can also be used by plugins if needed.
/// </summary>
[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;
/// <summary>
/// A <see cref="Lumina"/> object which gives access to any excel/game data.
@ -37,16 +40,12 @@ namespace Dalamud.Data
/// <summary>
/// Initializes a new instance of the <see cref="DataManager"/> class.
/// </summary>
/// <param name="language">The language to load data with by default.</param>
/// <param name="interfaceManager">An <see cref="InterfaceManager"/> instance to parse the data with.</param>
internal DataManager(ClientLanguage language, InterfaceManager interfaceManager)
internal DataManager()
{
this.interfaceManager = interfaceManager;
this.Language = Service<DalamudStartInfo>.Get().Language;
// Set up default values so plugins do not null-reference when data is being loaded.
this.ClientOpCodes = this.ServerOpCodes = new ReadOnlyDictionary<string, ushort>(new Dictionary<string, ushort>());
this.Language = language;
}
/// <summary>
@ -212,7 +211,7 @@ namespace Dalamud.Data
/// <param name="tex">The Lumina <see cref="TexFile"/>.</param>
/// <returns>A <see cref="TextureWrap"/> that can be used to draw the texture.</returns>
public TextureWrap GetImGuiTexture(TexFile tex)
=> this.interfaceManager.LoadImageRaw(tex.GetRgbaImageData(), tex.Header.Width, tex.Header.Height, 4);
=> Service<InterfaceManager>.Get().LoadImageRaw(tex.GetRgbaImageData(), tex.Header.Width, tex.Header.Height, 4);
/// <summary>
/// Get the passed texture path as a drawable ImGui TextureWrap.

View file

@ -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;

View file

@ -20,6 +20,15 @@ namespace Dalamud.Game
/// </summary>
protected bool IsResolved { get; set; }
/// <summary>
/// Setup the resolver, calling the appopriate method based on the process architecture.
/// </summary>
public void Setup()
{
var scanner = Service<SigScanner>.Get();
this.Setup(scanner);
}
/// <summary>
/// Setup the resolver, calling the appopriate method based on the process architecture.
/// </summary>

View file

@ -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
/// <summary>
/// Chat events and public helper functions.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public class ChatHandlers
{
// private static readonly Dictionary<string, string> 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;
/// <summary>
/// Initializes a new instance of the <see cref="ChatHandlers"/> class.
/// </summary>
/// <param name="dalamud">Dalamud instance.</param>
internal ChatHandlers(Dalamud dalamud)
internal ChatHandlers()
{
this.dalamud = dalamud;
var chatGui = Service<ChatGui>.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<DalamudInterface>.Get().OpenPluginInstaller();
});
}
/// <summary>
/// Gets the last URL seen in chat.
/// </summary>
public string LastLink { get; private set; }
public string? LastLink { get; private set; }
/// <summary>
/// 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<DalamudConfiguration>.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<DalamudStartInfo>.Get();
var clientState = Service<ClientState.ClientState>.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<ChatGui>.Get();
var configuration = Service<DalamudConfiguration>.Get();
var pluginManager = Service<PluginManager>.Get();
var dalamudInterface = Service<DalamudInterface>.Get();
var notifications = Service<Notifications>.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<DataManager>.Get();
chatGui.PrintChat(new XivChatEntry
{
Message = new SeString(new List<Payload>()
{
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,

View file

@ -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.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed partial class BuddyList
{
private const uint InvalidObjectID = 0xE0000000;
private readonly Dalamud dalamud;
private readonly ClientStateAddressResolver address;
/// <summary>
/// Initializes a new instance of the <see cref="BuddyList"/> class.
/// </summary>
/// <param name="dalamud">The <see cref="dalamud"/> instance.</param>
/// <param name="addressResolver">Client state address resolver.</param>
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<ClientState>.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;

View file

@ -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
/// </summary>
public unsafe class BuddyMember
{
private Dalamud dalamud;
/// <summary>
/// Initializes a new instance of the <see cref="BuddyMember"/> class.
/// </summary>
/// <param name="address">Buddy address.</param>
/// <param name="dalamud">Dalamud instance.</param>
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.
/// </remarks>
[CanBeNull]
public GameObject Actor => this.dalamud.ClientState.Objects.SearchByID(this.ObjectId);
public GameObject GameObject => Service<ObjectTable>.Get().SearchByID(this.ObjectId);
/// <summary>
/// Gets the current health of this buddy.
@ -61,17 +58,17 @@ namespace Dalamud.Game.ClientState.Buddy
/// <summary>
/// Gets the Mount data related to this buddy. It should only be used with companion buddies.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.Mount> MountData => new(this.DataID, this.dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.Mount> MountData => new(this.DataID);
/// <summary>
/// Gets the Pet data related to this buddy. It should only be used with pet buddies.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.Pet> PetData => new(this.DataID, this.dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.Pet> PetData => new(this.DataID);
/// <summary>
/// Gets the Trust data related to this buddy. It should only be used with battle buddies.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.DawnGrowMember> TrustData => new(this.DataID, this.dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.DawnGrowMember> TrustData => new(this.DataID);
private FFXIVClientStructs.FFXIV.Client.Game.UI.Buddy.BuddyMember* Struct => (FFXIVClientStructs.FFXIV.Client.Game.UI.Buddy.BuddyMember*)this.Address;
}

View file

@ -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
/// <summary>
/// This class represents the state of the game client at the time of access.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed class ClientState : IDisposable
{
private readonly Dalamud dalamud;
private readonly ClientStateAddressResolver address;
private readonly Hook<SetupTerritoryTypeDelegate> setupTerritoryTypeHook;
@ -31,43 +35,42 @@ namespace Dalamud.Game.ClientState
/// Initializes a new instance of the <see cref="ClientState"/> class.
/// Set up client state access.
/// </summary>
/// <param name="dalamud">Dalamud instance.</param>
/// <param name="startInfo">StartInfo of the current Dalamud launch.</param>
/// <param name="scanner">Sig scanner.</param>
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<DalamudStartInfo>.Get().Language;
this.Objects = new ObjectTable(dalamud, this.address);
Service<ObjectTable>.Set(this.address);
this.Fates = new FateTable(dalamud, this.address);
Service<FateTable>.Set(this.address);
this.PartyList = new PartyList(dalamud, this.address);
Service<PartyList>.Set(this.address);
this.BuddyList = new BuddyList(dalamud, this.address);
Service<BuddyList>.Set(this.address);
this.JobGauges = new JobGauges(this.address);
Service<JobGauges>.Set(this.address);
this.KeyState = new KeyState(this.address, scanner.Module.BaseAddress);
Service<KeyState>.Set(this.address);
this.GamepadState = new GamepadState(this.address);
Service<GamepadState>.Set(this.address);
this.Condition = new Condition(this.address);
Service<Condition>.Set(this.address);
this.Targets = new Targets(dalamud, this.address);
Service<TargetManager>.Set(this.address);
Log.Verbose($"SetupTerritoryType address 0x{this.address.SetupTerritoryType.ToInt64():X}");
this.setupTerritoryTypeHook = new Hook<SetupTerritoryTypeDelegate>(this.address.SetupTerritoryType, this.SetupTerritoryTypeDetour);
dalamud.Framework.OnUpdateEvent += this.FrameworkOnOnUpdateEvent;
dalamud.NetworkHandlers.CfPop += this.NetworkHandlersOnCfPop;
var framework = Service<Framework>.Get();
framework.OnUpdateEvent += this.FrameworkOnOnUpdateEvent;
var networkHandlers = Service<NetworkHandlers>.Get();
networkHandlers.CfPop += this.NetworkHandlersOnCfPop;
}
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
@ -93,56 +96,11 @@ namespace Dalamud.Game.ClientState
/// </summary>
public event EventHandler<Lumina.Excel.GeneratedSheets.ContentFinderCondition> CfPop;
/// <summary>
/// Gets the table of all present actors.
/// </summary>
public ObjectTable Objects { get; }
/// <summary>
/// Gets the table of all present fates.
/// </summary>
public FateTable Fates { get; }
/// <summary>
/// Gets the language of the client.
/// </summary>
public ClientLanguage ClientLanguage { get; }
/// <summary>
/// Gets the class facilitating Job Gauge data access.
/// </summary>
public JobGauges JobGauges { get; }
/// <summary>
/// Gets the class facilitating party list data access.
/// </summary>
public PartyList PartyList { get; }
/// <summary>
/// Gets the class facilitating buddy list data access.
/// </summary>
public BuddyList BuddyList { get; }
/// <summary>
/// Gets access to the keypress state of keyboard keys in game.
/// </summary>
public KeyState KeyState { get; }
/// <summary>
/// Gets access to the button state of gamepad buttons in game.
/// </summary>
public GamepadState GamepadState { get; }
/// <summary>
/// Gets access to client conditions/player state. Allows you to check if a player is in a duty, mounted, etc.
/// </summary>
public Condition Condition { get; }
/// <summary>
/// Gets the class facilitating target data access.
/// </summary>
public Targets Targets { get; }
/// <summary>
/// Gets the current Territory the player resides in.
/// </summary>
@ -152,7 +110,7 @@ namespace Dalamud.Game.ClientState
/// Gets the local player character, if one is present.
/// </summary>
[CanBeNull]
public PlayerCharacter LocalPlayer => this.Objects[0] as PlayerCharacter;
public PlayerCharacter LocalPlayer => Service<ObjectTable>.Get()[0] as PlayerCharacter;
/// <summary>
/// Gets the content ID of the local character.
@ -169,7 +127,7 @@ namespace Dalamud.Game.ClientState
/// </summary>
public void Enable()
{
this.GamepadState.Enable();
Service<GamepadState>.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<GamepadState>.Get().Dispose();
Service<Framework>.Get().OnUpdateEvent -= this.FrameworkOnOnUpdateEvent;
Service<NetworkHandlers>.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<Condition>.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;

View file

@ -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
/// </summary>
public unsafe partial class Fate : IEquatable<Fate>
{
private Dalamud dalamud;
/// <summary>
/// Initializes a new instance of the <see cref="Fate"/> class.
/// </summary>
/// <param name="address">The address of this fate in memory.</param>
/// <param name="dalamud">Dalamud instance.</param>
internal Fate(IntPtr address, Dalamud dalamud)
internal Fate(IntPtr address)
{
this.Address = address;
this.dalamud = dalamud;
}
/// <summary>
@ -49,10 +46,12 @@ namespace Dalamud.Game.ClientState.Fates
/// <returns>True or false.</returns>
public static bool IsValid(Fate fate)
{
var clientState = Service<ClientState>.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
/// <summary>
/// Gets game data linked to this Fate.
/// </summary>
public Lumina.Excel.GeneratedSheets.Fate GameData => this.dalamud.Data.GetExcelSheet<Lumina.Excel.GeneratedSheets.Fate>().GetRow(this.FateId);
public Lumina.Excel.GeneratedSheets.Fate GameData => Service<DataManager>.Get().GetExcelSheet<Lumina.Excel.GeneratedSheets.Fate>().GetRow(this.FateId);
/// <summary>
/// Gets the time this <see cref="Fate"/> started.
@ -132,6 +131,6 @@ namespace Dalamud.Game.ClientState.Fates
/// <summary>
/// Gets the territory this <see cref="Fate"/> is located in.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.TerritoryType> TerritoryType => new(this.Struct->TerritoryID, this.dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.TerritoryType> TerritoryType => new(this.Struct->TerritoryID);
}
}

View file

@ -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
/// <summary>
/// This collection represents the currently available Fate events.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed partial class FateTable
{
private readonly Dalamud dalamud;
private readonly ClientStateAddressResolver address;
/// <summary>
/// Initializes a new instance of the <see cref="FateTable"/> class.
/// </summary>
/// <param name="dalamud">The <see cref="dalamud"/> instance.</param>
/// <param name="addressResolver">Client state address resolver.</param>
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<ClientState>.Get();
if (clientState.LocalContentId == 0)
return null;
if (offset == IntPtr.Zero)
return null;
return new Fate(offset, this.dalamud);
return new Fate(offset);
}
}

View file

@ -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
/// <summary>
/// Wrapper around the game keystate buffer, which contains the pressed state for all keyboard keys, indexed by virtual vkCode.
/// </summary>
[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 <see cref="KeyState"/> class.
/// </summary>
/// <param name="addressResolver">The ClientStateAddressResolver instance.</param>
/// <param name="moduleBaseAddress">The base address of the main process module.</param>
public KeyState(ClientStateAddressResolver addressResolver, IntPtr moduleBaseAddress)
public KeyState(ClientStateAddressResolver addressResolver)
{
var moduleBaseAddress = Service<SigScanner>.Get().Module.BaseAddress;
this.bufferBase = moduleBaseAddress + Marshal.ReadInt32(addressResolver.KeyboardState);
Log.Verbose($"Keyboard state buffer address 0x{this.bufferBase.ToInt64():X}");

View file

@ -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
/// <summary>
/// This collection represents the currently spawned FFXIV game objects.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed partial class ObjectTable
{
private const int ObjectTableLength = 424;
private readonly Dalamud dalamud;
private readonly ClientStateAddressResolver address;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectTable"/> class.
/// </summary>
/// <param name="dalamud">The <see cref="dalamud"/> instance.</param>
/// <param name="addressResolver">Client state address resolver.</param>
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<ClientState>.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),
};
}
}

View file

@ -14,9 +14,8 @@ namespace Dalamud.Game.ClientState.Objects.Types
/// Set up a new BattleNpc with the provided memory representation.
/// </summary>
/// <param name="address">The address of this actor in memory.</param>
/// <param name="dalamud">A dalamud reference needed to access game data in Resolvers.</param>
internal BattleNpc(IntPtr address, Dalamud dalamud)
: base(address, dalamud)
internal BattleNpc(IntPtr address)
: base(address)
{
}

View file

@ -14,9 +14,8 @@ namespace Dalamud.Game.ClientState.Objects.SubKinds
/// Set up a new EventObj with the provided memory representation.
/// </summary>
/// <param name="address">The address of this event object in memory.</param>
/// <param name="dalamud">A dalamud reference.</param>
internal EventObj(IntPtr address, Dalamud dalamud)
: base(address, dalamud)
internal EventObj(IntPtr address)
: base(address)
{
}
}

View file

@ -14,9 +14,8 @@ namespace Dalamud.Game.ClientState.Objects.SubKinds
/// Set up a new NPC with the provided memory representation.
/// </summary>
/// <param name="address">The address of this actor in memory.</param>
/// <param name="dalamud">A dalamud reference needed to access game data in Resolvers.</param>
internal Npc(IntPtr address, Dalamud dalamud)
: base(address, dalamud)
internal Npc(IntPtr address)
: base(address)
{
}

View file

@ -15,21 +15,20 @@ namespace Dalamud.Game.ClientState.Objects.SubKinds
/// This represents a player character.
/// </summary>
/// <param name="address">The address of this actor in memory.</param>
/// <param name="dalamud">A dalamud reference needed to access game data in Resolvers.</param>
internal PlayerCharacter(IntPtr address, Dalamud dalamud)
: base(address, dalamud)
internal PlayerCharacter(IntPtr address)
: base(address)
{
}
/// <summary>
/// Gets the current <see cref="ExcelResolver{T}">world</see> of the character.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.World> CurrentWorld => new(this.Struct->Character.CurrentWorld, this.Dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.World> CurrentWorld => new(this.Struct->Character.CurrentWorld);
/// <summary>
/// Gets the home <see cref="ExcelResolver{T}">world</see> of the character.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.World> HomeWorld => new(this.Struct->Character.HomeWorld, this.Dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.World> HomeWorld => new(this.Struct->Character.HomeWorld);
/// <summary>
/// Gets the target actor ID of the PlayerCharacter.

View file

@ -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
/// <summary>
/// Get and set various kinds of targets for the player.
/// </summary>
public sealed unsafe class Targets
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed unsafe class TargetManager
{
private readonly Dalamud dalamud;
private readonly ClientStateAddressResolver address;
/// <summary>
/// Initializes a new instance of the <see cref="Targets"/> class.
/// Initializes a new instance of the <see cref="TargetManager"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
/// <param name="addressResolver">The ClientStateAddressResolver instance.</param>
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<ObjectTable>.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<ObjectTable>.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<ObjectTable>.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<ObjectTable>.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<ObjectTable>.Get().CreateObjectReference((IntPtr)Struct->SoftTarget);
set => this.SetSoftTarget(value);
}

View file

@ -14,16 +14,15 @@ namespace Dalamud.Game.ClientState.Objects.Types
/// This represents a battle character.
/// </summary>
/// <param name="address">The address of this character in memory.</param>
/// <param name="dalamud">Dalamud itself.</param>
internal BattleChara(IntPtr address, Dalamud dalamud)
: base(address, dalamud)
internal BattleChara(IntPtr address)
: base(address)
{
}
/// <summary>
/// Gets the current status effects.
/// </summary>
public StatusList StatusList => new(&this.Struct->StatusManager, this.Dalamud);
public StatusList StatusList => new(&this.Struct->StatusManager);
/// <summary>
/// Gets a value indicating whether the chara is currently casting.

View file

@ -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.
/// </summary>
/// <param name="address">The address of this character in memory.</param>
/// <param name="dalamud">Dalamud itself.</param>
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
/// <summary>
/// Gets the ClassJob of this Chara.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.ClassJob> ClassJob => new(this.Struct->ClassJob, this.Dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.ClassJob> ClassJob => new(this.Struct->ClassJob);
/// <summary>
/// Gets the level of this Chara.

View file

@ -17,11 +17,9 @@ namespace Dalamud.Game.ClientState.Objects.Types
/// Initializes a new instance of the <see cref="GameObject"/> class.
/// </summary>
/// <param name="address">The address of this game object in memory.</param>
/// <param name="dalamud">Dalamud itself.</param>
internal GameObject(IntPtr address, Dalamud dalamud)
internal GameObject(IntPtr address)
{
this.Address = address;
this.Dalamud = dalamud;
}
/// <summary>
@ -59,10 +57,12 @@ namespace Dalamud.Game.ClientState.Objects.Types
/// <returns>True or false.</returns>
public static bool IsValid(GameObject? actor)
{
var clientState = Service<ClientState>.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.
/// </remarks>
[CanBeNull]
public virtual GameObject TargetObject => this.Dalamud.ClientState.Objects.SearchByID(this.TargetObjectId);
public virtual GameObject TargetObject => Service<ObjectTable>.Get().SearchByID(this.TargetObjectId);
/// <summary>
/// Gets the underlying structure.

View file

@ -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
/// <summary>
/// This collection represents the actors present in your party or alliance.
/// </summary>
[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;
/// <summary>
/// Initializes a new instance of the <see cref="PartyList"/> class.
/// </summary>
/// <param name="dalamud">The <see cref="dalamud"/> instance.</param>
/// <param name="addressResolver">Client state address resolver.</param>
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<ClientState>.Get();
if (clientState.LocalContentId == 0)
return null;
if (address == IntPtr.Zero)
return null;
return new PartyMember(address, this.dalamud);
return new PartyMember(address);
}
/// <summary>
@ -144,13 +147,15 @@ namespace Dalamud.Game.ClientState.Party
[CanBeNull]
public PartyMember CreateAllianceMemberReference(IntPtr address)
{
if (this.dalamud.ClientState.LocalContentId == 0)
var clientState = Service<ClientState>.Get();
if (clientState.LocalContentId == 0)
return null;
if (address == IntPtr.Zero)
return null;
return new PartyMember(address, this.dalamud);
return new PartyMember(address);
}
}

View file

@ -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
/// </summary>
public unsafe class PartyMember
{
private Dalamud dalamud;
/// <summary>
/// Initializes a new instance of the <see cref="PartyMember"/> class.
/// </summary>
/// <param name="address">Address of the party member.</param>
/// <param name="dalamud">Dalamud itself.</param>
internal PartyMember(IntPtr address, Dalamud dalamud)
internal PartyMember(IntPtr address)
{
this.Address = address;
this.dalamud = dalamud;
}
/// <summary>
@ -36,7 +33,7 @@ namespace Dalamud.Game.ClientState.Party
/// <summary>
/// Gets a list of buffs or debuffs applied to this party member.
/// </summary>
public StatusList Statuses => new(&this.Struct->StatusManager, this.dalamud);
public StatusList Statuses => new(&this.Struct->StatusManager);
/// <summary>
/// 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.
/// </remarks>
[CanBeNull]
public GameObject GameObject => this.dalamud.ClientState.Objects.SearchByID(this.ObjectId);
public GameObject GameObject => Service<ObjectTable>.Get().SearchByID(this.ObjectId);
/// <summary>
/// Gets the current HP of this party member.
@ -85,12 +82,12 @@ namespace Dalamud.Game.ClientState.Party
/// <summary>
/// Gets the territory this party member is located in.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.TerritoryType> Territory => new(this.Struct->TerritoryType, this.dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.TerritoryType> Territory => new(this.Struct->TerritoryType);
/// <summary>
/// Gets the World this party member resides in.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.World> World => new(this.Struct->HomeWorld, this.dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.World> World => new(this.Struct->HomeWorld);
/// <summary>
/// Gets the displayname of this party member.
@ -105,7 +102,7 @@ namespace Dalamud.Game.ClientState.Party
/// <summary>
/// Gets the classjob of this party member.
/// </summary>
public ExcelResolver<Lumina.Excel.GeneratedSheets.ClassJob> ClassJob => new(this.Struct->ClassJob, this.dalamud);
public ExcelResolver<Lumina.Excel.GeneratedSheets.ClassJob> ClassJob => new(this.Struct->ClassJob);
/// <summary>
/// Gets the level of this party member.

View file

@ -1,3 +1,4 @@
using Dalamud.Data;
using Lumina.Excel;
namespace Dalamud.Game.ClientState.Resolvers
@ -8,16 +9,12 @@ namespace Dalamud.Game.ClientState.Resolvers
/// <typeparam name="T">The type of Lumina sheet to resolve.</typeparam>
public class ExcelResolver<T> where T : ExcelRow
{
private readonly Dalamud dalamud;
/// <summary>
/// Initializes a new instance of the <see cref="ExcelResolver{T}"/> class.
/// </summary>
/// <param name="id">The ID of the classJob.</param>
/// <param name="dalamud">The Dalamud instance.</param>
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
/// <summary>
/// Gets GameData linked to this excel row.
/// </summary>
public T GameData => this.dalamud.Data.GetExcelSheet<T>().GetRow(this.Id);
public T GameData => Service<DataManager>.Get().GetExcelSheet<T>().GetRow(this.Id);
}
}

View file

@ -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
/// </summary>
public unsafe class Status
{
private Dalamud dalamud;
/// <summary>
/// Initializes a new instance of the <see cref="Status"/> class.
/// </summary>
/// <param name="address">Status address.</param>
/// <param name="dalamud">Dalamud instance.</param>
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
/// <summary>
/// Gets the GameData associated with this status.
/// </summary>
public Lumina.Excel.GeneratedSheets.Status GameData => new ExcelResolver<Lumina.Excel.GeneratedSheets.Status>(this.Struct->StatusID, this.dalamud).GameData;
public Lumina.Excel.GeneratedSheets.Status GameData => new ExcelResolver<Lumina.Excel.GeneratedSheets.Status>(this.Struct->StatusID).GameData;
/// <summary>
/// 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.
/// </remarks>
[CanBeNull]
public GameObject SourceActor => this.dalamud.ClientState.Objects.SearchByID(this.SourceID);
public GameObject SourceObject => Service<ObjectTable>.Get().SearchByID(this.SourceID);
private FFXIVClientStructs.FFXIV.Client.Game.Status* Struct => (FFXIVClientStructs.FFXIV.Client.Game.Status*)this.Address;
}

View file

@ -14,26 +14,21 @@ namespace Dalamud.Game.ClientState.Statuses
{
private const int StatusListLength = 30;
private readonly Dalamud dalamud;
/// <summary>
/// Initializes a new instance of the <see cref="StatusList"/> class.
/// </summary>
/// <param name="address">Address of the status list.</param>
/// <param name="dalamud">The <see cref="dalamud"/> instance.</param>
internal StatusList(IntPtr address, Dalamud dalamud)
internal StatusList(IntPtr address)
{
this.Address = address;
this.dalamud = dalamud;
}
/// <summary>
/// Initializes a new instance of the <see cref="StatusList"/> class.
/// </summary>
/// <param name="pointer">Pointer to the status list.</param>
/// <param name="dalamud">The <see cref="dalamud"/> instance.</param>
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<ClientState>.Get();
if (clientState.LocalContentId == 0)
return null;
if (address == IntPtr.Zero)
return null;
return new Status(address, this.dalamud);
return new Status(address);
}
}

View file

@ -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
/// <summary>
/// This class manages registered in-game slash commands.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed class CommandManager
{
private readonly Dalamud dalamud;
private readonly Dictionary<string, CommandInfo> commandMap = new();
private readonly Regex commandRegexEn = new(@"^The command (?<command>.+) does not exist\.$", RegexOptions.Compiled);
private readonly Regex commandRegexJp = new(@"^そのコマンドはありません。: (?<command>.+)$", RegexOptions.Compiled);
@ -25,13 +29,11 @@ namespace Dalamud.Game.Command
/// <summary>
/// Initializes a new instance of the <see cref="CommandManager"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
/// <param name="language">The client language requested.</param>
internal CommandManager(Dalamud dalamud, ClientLanguage language)
internal CommandManager()
{
this.dalamud = dalamud;
var startInfo = Service<DalamudStartInfo>.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<ChatGui>.Get().CheckMessageHandled += this.OnCheckMessageHandled;
}
/// <summary>

View file

@ -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
/// <summary>
/// This class represents the Framework of the native game client and grants access to various subsystems.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed class Framework : IDisposable
{
private static Stopwatch statsStopwatch = new();
private readonly Dalamud dalamud;
private Hook<OnUpdateDetour> updateHook;
private Hook<OnDestroyDetour> destroyHook;
private Hook<OnRealDestroyDelegate> realDestroyHook;
@ -28,13 +32,10 @@ namespace Dalamud.Game
/// <summary>
/// Initializes a new instance of the <see cref="Framework"/> class.
/// </summary>
/// <param name="scanner">The SigScanner instance.</param>
/// <param name="dalamud">The Dalamud instance.</param>
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);
}
/// <summary>
@ -92,27 +86,6 @@ namespace Dalamud.Game
/// </summary>
public static Dictionary<string, List<double>> StatsHistory { get; } = new();
#region Subsystems
/// <summary>
/// Gets the GUI subsystem, used to access e.g. chat.
/// </summary>
public GameGui Gui { get; private set; }
/// <summary>
/// Gets the Network subsystem, used to access network data.
/// </summary>
public GameNetwork Network { get; private set; }
// public ResourceManager Resource { get; private set; }
/// <summary>
/// Gets the Libc subsystem, used to facilitate interop with std::strings.
/// </summary>
public LibcFunction Libc { get; private set; }
#endregion
/// <summary>
/// Gets a raw pointer to the instance of Client::Framework.
/// </summary>
@ -128,8 +101,8 @@ namespace Dalamud.Game
/// </summary>
public void Enable()
{
this.Gui.Enable();
this.Network.Enable();
Service<GameGui>.Get().Enable();
Service<GameNetwork>.Get().Enable();
this.updateHook.Enable();
this.destroyHook.Enable();
@ -141,17 +114,17 @@ namespace Dalamud.Game
/// </summary>
public void Dispose()
{
this.Gui.Dispose();
this.Network.Dispose();
Service<GameGui>.GetNullable()?.Dispose();
Service<GameNetwork>.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<Dalamud>.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<InterfaceManager>.GetNullable()?.IsReady == true)
dalamud.LoadTier3();
try
{
this.Gui.Chat.UpdateQueue(this);
this.Gui.Toast.UpdateQueue();
this.Network.UpdateQueue(this);
Service<ChatGui>.Get().UpdateQueue();
Service<ToastGui>.Get().UpdateQueue();
Service<GameNetwork>.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<Dalamud>.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<Dalamud>.Get();
dalamud.Unload();
dalamud.WaitForUnloadFinish();
Log.Information("Framework::Free OK!");

View file

@ -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
/// <summary>
/// This class handles interacting with the native chat UI.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed class ChatGui : IDisposable
{
private readonly Dalamud dalamud;
private readonly ChatGuiAddressResolver address;
private readonly Queue<XivChatEntry> chatQueue = new();
@ -33,14 +37,10 @@ namespace Dalamud.Game.Gui
/// Initializes a new instance of the <see cref="ChatGui"/> class.
/// </summary>
/// <param name="baseAddress">The base address of the ChatManager.</param>
/// <param name="scanner">The SigScanner instance.</param>
/// <param name="dalamud">The Dalamud instance.</param>
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
/// <param name="message">A message to send.</param>
public void Print(string message)
{
var configuration = Service<DalamudConfiguration>.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
/// <param name="message">A message to send.</param>
public void Print(SeString message)
{
var configuration = Service<DalamudConfiguration>.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
/// <summary>
/// Process a chat queue.
/// </summary>
/// <param name="framework">The Framework instance.</param>
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<LibcFunction>.Get().NewString(senderRaw);
var messageRaw = (chat.Message ?? string.Empty).Encode();
using var messageOwned = framework.Libc.NewString(messageRaw);
using var messageOwned = Service<LibcFunction>.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<SeStringManager>.Get().Parse(sender.RawData);
var parsedMessage = Service<SeStringManager>.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<LibcFunction>.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<SeStringManager>.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;

View file

@ -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
/// <summary>
/// This class facilitates interacting with and creating native in-game "fly text".
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed class FlyTextGui : IDisposable
{
/// <summary>
@ -28,14 +31,10 @@ namespace Dalamud.Game.Gui.FlyText
/// <summary>
/// Initializes a new instance of the <see cref="FlyTextGui"/> class.
/// </summary>
/// <param name="scanner">The SigScanner instance.</param>
/// <param name="dalamud">The Dalamud instance.</param>
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<AddFlyTextDelegate>(this.Address.AddFlyText);
this.createFlyTextHook = new Hook<CreateFlyTextDelegate>(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<GameGui>.Get();
var ui = (FFXIVClientStructs.FFXIV.Client.UI.UIModule*)gameGui.GetUIModule();
var flytext = gameGui.GetAddonByName("_FlyText", 1);
if (ui == null || flytext == IntPtr.Zero)
return;

View file

@ -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
/// <summary>
/// A class handling many aspects of the in-game UI.
/// </summary>
[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 <see cref="GameGui"/> class.
/// This class is responsible for many aspects of interacting with the native game UI.
/// </summary>
/// <param name="baseAddress">The base address of the native GuiManager class.</param>
/// <param name="scanner">The SigScanner instance.</param>
/// <param name="dalamud">The Dalamud instance.</param>
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<ChatGui>.Set(new ChatGui(this.address.ChatManager));
Service<PartyFinderGui>.Set();
Service<ToastGui>.Set();
Service<FlyTextGui>.Set();
this.setGlobalBgmHook = new Hook<SetGlobalBgmDelegate>(this.address.SetGlobalBgm, this.HandleSetGlobalBgmDetour);
@ -128,26 +126,6 @@ namespace Dalamud.Game.Gui
/// </summary>
public event EventHandler<bool> OnUiHideToggled;
/// <summary>
/// Gets the <see cref="Chat"/> instance.
/// </summary>
public ChatGui Chat { get; private set; }
/// <summary>
/// Gets the <see cref="PartyFinder"/> instance.
/// </summary>
public PartyFinderGui PartyFinder { get; private set; }
/// <summary>
/// Gets the <see cref="Toast"/> instance.
/// </summary>
public ToastGui Toast { get; private set; }
/// <summary>
/// Gets the <see cref="FlyText"/> instance.
/// </summary>
public FlyTextGui FlyText { get; private set; }
/// <summary>
/// Gets a value indicating whether the game UI is hidden.
/// </summary>
@ -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<GameGui>.Get().GetUIModule();
if (uiModule == IntPtr.Zero)
{
return IntPtr.Zero;
@ -483,10 +461,10 @@ namespace Dalamud.Game.Gui
/// </summary>
public void Enable()
{
this.Chat.Enable();
this.Toast.Enable();
this.FlyText.Enable();
this.PartyFinder.Enable();
Service<ChatGui>.Get().Enable();
Service<ToastGui>.Get().Enable();
Service<FlyTextGui>.Get().Enable();
Service<PartyFinderGui>.Get().Enable();
this.setGlobalBgmHook.Enable();
this.handleItemHoverHook.Enable();
this.handleItemOutHook.Enable();
@ -501,10 +479,10 @@ namespace Dalamud.Game.Gui
/// </summary>
public void Dispose()
{
this.Chat.Dispose();
this.Toast.Dispose();
this.FlyText.Dispose();
this.PartyFinder.Dispose();
Service<ChatGui>.Get().Dispose();
Service<ToastGui>.Get().Dispose();
Service<FlyTextGui>.Get().Dispose();
Service<PartyFinderGui>.Get().Dispose();
this.setGlobalBgmHook.Dispose();
this.handleItemHoverHook.Dispose();
this.handleItemOutHook.Dispose();

View file

@ -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
/// <summary>
/// Initializes a new instance of the <see cref="DalamudIME"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
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<InterfaceManager>.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<DalamudInterface>.Get().OpenIMEWindow();
else
this.dalamud.DalamudUi.CloseIMEWindow();
Service<DalamudInterface>.Get().CloseIMEWindow();
}
private long WndProcDetour(IntPtr hWnd, uint msg, ulong wParam, long lParam)

View file

@ -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
/// <summary>
/// This class handles interacting with the native PartyFinder window.
/// </summary>
[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
/// <summary>
/// Initializes a new instance of the <see cref="PartyFinderGui"/> class.
/// </summary>
/// <param name="scanner">The SigScanner instance.</param>
/// <param name="dalamud">The Dalamud instance.</param>
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);

View file

@ -14,8 +14,6 @@ namespace Dalamud.Game.Gui.PartyFinder.Types
/// </summary>
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
/// <summary>
/// Initializes a new instance of the <see cref="PartyFinderListing"/> class.
/// </summary>
/// <param name="listing">The interop listing data.</param>
/// <param name="dataManager">The DataManager instance.</param>
/// <param name="seStringManager">The SeStringManager instance.</param>
internal PartyFinderListing(PartyFinderPacketListing listing, DataManager dataManager, SeStringManager seStringManager)
internal PartyFinderListing(PartyFinderPacketListing listing)
{
var dataManager = Service<DataManager>.Get();
var seStringManager = Service<SeStringManager>.Get();
this.objective = listing.Objective;
this.conditions = listing.Conditions;
this.dutyFinderSettings = listing.DutyFinderSettings;

View file

@ -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
{
/// <summary>
/// This class facilitates interacting with and creating native toast windows.
/// </summary>
[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
/// <summary>
/// Initializes a new instance of the <see cref="ToastGui"/> class.
/// </summary>
/// <param name="scanner">The SigScanner instance.</param>
/// <param name="dalamud">The Dalamud instance.</param>
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<ShowNormalToastDelegate>(this.address.ShowNormalToast, new ShowNormalToastDelegate(this.HandleNormalToastDetour));
this.showQuestToastHook = new Hook<ShowQuestToastDelegate>(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<SeStringManager>.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<GameGui>.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<GameGui>.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<GameGui>.Get().GetUIModule();
// terminate the string
var terminated = Terminate(bytes);

View file

@ -17,9 +17,10 @@ namespace Dalamud.Game.Internal
/// <summary>
/// Initializes a new instance of the <see cref="AntiDebug"/> class.
/// </summary>
/// <param name="scanner">The SigScanner instance.</param>
public AntiDebug(SigScanner scanner)
public AntiDebug()
{
var scanner = Service<SigScanner>.Get();
try
{
this.debugCheckAddress = scanner.ScanText("FF 15 ?? ?? ?? ?? 85 C0 74 11 41");

View file

@ -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
/// </summary>
internal sealed unsafe partial class DalamudSystemMenu
{
private readonly Dalamud dalamud;
private readonly AtkValueChangeType atkValueChangeType;
private readonly AtkValueSetString atkValueSetString;
private readonly Hook<AgentHudOpenSystemMenuPrototype> hookAgentHudOpenSystemMenu;
// TODO: Make this into events in Framework.Gui
private readonly Hook<UiModuleRequestMainCommand> hookUiModuleRequestMainCommand;
/// <summary>
/// Initializes a new instance of the <see cref="DalamudSystemMenu"/> class.
/// </summary>
/// <param name="dalamud">The dalamud instance to act on.</param>
public DalamudSystemMenu(Dalamud dalamud)
public DalamudSystemMenu()
{
this.dalamud = dalamud;
var sigScanner = Service<SigScanner>.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<AgentHudOpenSystemMenuPrototype>(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<AtkValueChangeType>(atkValueChangeTypeAddress);
var atkValueSetStringAddress = this.dalamud.SigScanner.ScanText("E8 ?? ?? ?? ?? 41 03 ED");
var atkValueSetStringAddress = sigScanner.ScanText("E8 ?? ?? ?? ?? 41 03 ED");
this.atkValueSetString = Marshal.GetDelegateForFunctionPointer<AtkValueSetString>(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<UiModuleRequestMainCommand>(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<DalamudConfiguration>.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<DalamudInterface>.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);

View file

@ -2,11 +2,16 @@ using System;
using System.Runtime.InteropServices;
using System.Text;
using Dalamud.IoC;
using Dalamud.IoC.Internal;
namespace Dalamud.Game.Libc
{
/// <summary>
/// This class handles creating cstrings utilizing native game methods.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed class LibcFunction
{
private readonly LibcFunctionAddressResolver address;
@ -16,11 +21,10 @@ namespace Dalamud.Game.Libc
/// <summary>
/// Initializes a new instance of the <see cref="LibcFunction"/> class.
/// </summary>
/// <param name="scanner">The SigScanner instance.</param>
public LibcFunction(SigScanner scanner)
public LibcFunction()
{
this.address = new LibcFunctionAddressResolver();
this.address.Setup(scanner);
this.address.Setup();
this.stdStringCtorCString = Marshal.GetDelegateForFunctionPointer<StdStringFromCStringDelegate>(this.address.StdStringFromCstring);
this.stdStringDeallocate = Marshal.GetDelegateForFunctionPointer<StdStringDeallocateDelegate>(this.address.StdStringDeallocate);

View file

@ -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
/// <summary>
/// This class handles interacting with game network events.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed class GameNetwork : IDisposable
{
private readonly GameNetworkAddressResolver address;
@ -23,11 +26,10 @@ namespace Dalamud.Game.Network
/// <summary>
/// Initializes a new instance of the <see cref="GameNetwork"/> class.
/// </summary>
/// <param name="scanner">The SigScanner instance.</param>
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
/// <summary>
/// Process a chat queue.
/// </summary>
/// <param name="framework">The Framework instance.</param>
public void UpdateQueue(Framework framework)
internal void UpdateQueue()
{
while (this.zoneInjectQueue.Count > 0)
{

View file

@ -21,30 +21,27 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis
private const string ApiKey = "GGD6RdSfGyRiHM5WDnAo0Nj9Nv7aC5NDhMj3BebT";
private readonly Dalamud dalamud;
/// <summary>
/// Initializes a new instance of the <see cref="UniversalisMarketBoardUploader"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
public UniversalisMarketBoardUploader(Dalamud dalamud)
public UniversalisMarketBoardUploader()
{
this.dalamud = dalamud;
}
/// <inheritdoc/>
public void Upload(MarketBoardItemRequest request)
{
var clientState = Service<ClientState.ClientState>.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<UniversalisItemListingsEntry>(),
@ -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<UniversalisHistoryEntry>(),
@ -121,14 +118,15 @@ namespace Dalamud.Game.Network.Internal.MarketBoardUploaders.Universalis
/// <inheritdoc/>
public void UploadTax(MarketTaxRates taxRates)
{
var clientState = Service<ClientState.ClientState>.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
/// </remarks>
public void UploadPurchase(MarketBoardPurchaseHandler purchaseHandler)
{
var clientState = Service<ClientState.ClientState>.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";

View file

@ -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
/// </summary>
internal class NetworkHandlers
{
private readonly Dalamud dalamud;
private readonly List<MarketBoardItemRequest> marketBoardRequests = new();
private readonly bool optOutMbUploads;
@ -30,16 +31,13 @@ namespace Dalamud.Game.Network.Internal
/// <summary>
/// Initializes a new instance of the <see cref="NetworkHandlers"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
/// <param name="optOutMbUploads">Whether the client should opt out of market board uploads.</param>
public NetworkHandlers(Dalamud dalamud, bool optOutMbUploads)
public NetworkHandlers()
{
this.dalamud = dalamud;
this.optOutMbUploads = optOutMbUploads;
this.optOutMbUploads = Service<DalamudStartInfo>.Get().OptOutMbCollection;
this.uploader = new UniversalisMarketBoardUploader(dalamud);
this.uploader = new UniversalisMarketBoardUploader();
dalamud.Framework.Network.OnNetworkMessage += this.OnNetworkMessage;
Service<GameNetwork>.Get().OnNetworkMessage += this.OnNetworkMessage;
}
/// <summary>
@ -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<DataManager>.GetNullable();
if (dataManager?.IsDataReady == false)
return;
var configuration = Service<DalamudConfiguration>.Get();
if (direction == NetworkMessageDirection.ZoneUp)
{
if (!this.optOutMbUploads)
{
if (opCode == this.dalamud.Data.ClientOpCodes["MarketBoardPurchaseHandler"])
if (opCode == Service<DataManager>.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<ContentFinderCondition>().GetRow(contentFinderConditionId);
var contentFinderCondition = dataManager.GetExcelSheet<ContentFinderCondition>().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<ChatGui>.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;

View file

@ -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
/// <summary>
/// A SigScanner facilitates searching for memory signatures in a given ProcessModule.
/// </summary>
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed class SigScanner : IDisposable
{
private IntPtr moduleCopyPtr;

View file

@ -27,9 +27,9 @@ namespace Dalamud.Game.Text.SeStringHandling
private byte[] encodedData;
/// <summary>
/// Gets or sets the Lumina instance to use for any necessary data lookups.
/// Gets the Lumina instance to use for any necessary data lookups.
/// </summary>
public DataManager DataResolver { get; set; }
public DataManager DataResolver => Service<DataManager>.Get();
/// <summary>
/// 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.
/// </summary>
/// <param name="reader">A reader positioned at the start of the payload, and containing at least one entire payload.</param>
/// <param name="data">The DataManager instance.</param>
/// <returns>The constructed Payload-derived object that was decoded from the binary data.</returns>
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

View file

@ -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 <see cref="AutoTranslatePayload"/> class.
/// Creates a new auto-translate payload.
/// </summary>
/// <param name="data">DataManager instance needed to resolve game data.</param>
/// <param name="group">The group id for this message.</param>
/// <param name="key">The key/row id for this message. Which table this is in depends on the group id and details the Completion table.</param>
/// <remarks>
/// 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.
/// </remarks>
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;
}

View file

@ -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 <see cref="ItemPayload"/> class.
/// Creates a payload representing an interactable item link for the specified item.
/// </summary>
/// <param name="data">DataManager instance needed to resolve game data.</param>
/// <param name="itemId">The id of the item.</param>
/// <param name="isHQ">Whether or not the link should be for the high-quality variant of the item.</param>
/// <param name="displayNameOverride">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.</param>
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;

View file

@ -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 <see cref="MapLinkPayload"/> class.
/// Creates an interactable MapLinkPayload from a human-readable position.
/// </summary>
/// <param name="data">DataManager instance needed to resolve game data.</param>
/// <param name="territoryTypeId">The id of the TerritoryType entry for this link.</param>
/// <param name="mapId">The id of the Map entry for this link.</param>
/// <param name="niceXCoord">The human-readable x-coordinate for this link.</param>
/// <param name="niceYCoord">The human-readable y-coordinate for this link.</param>
/// <param name="fudgeFactor">An optional offset to account for rounding and truncation errors; it is best to leave this untouched in most cases.</param>
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 <see cref="MapLinkPayload"/> class.
/// Creates an interactable MapLinkPayload from a raw position.
/// </summary>
/// <param name="data">DataManager instance needed to resolve game data.</param>
/// <param name="territoryTypeId">The id of the TerritoryType entry for this link.</param>
/// <param name="mapId">The id of the Map entry for this link.</param>
/// <param name="rawX">The internal raw x-coordinate for this link.</param>
/// <param name="rawY">The internal raw y-coordinate for this link.</param>
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;

View file

@ -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 <see cref="PlayerPayload"/> class.
/// Create a PlayerPayload link for the specified player.
/// </summary>
/// <param name="data">DataManager instance needed to resolve game data.</param>
/// <param name="playerName">The player's displayed name.</param>
/// <param name="serverId">The player's home server id.</param>
public PlayerPayload(DataManager data, string playerName, uint serverId)
public PlayerPayload(string playerName, uint serverId)
{
this.DataResolver = data;
this.playerName = playerName;
this.serverId = serverId;
}

View file

@ -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 <see cref="QuestPayload"/> class.
/// Creates a payload representing an interactable quest link for the specified quest.
/// </summary>
/// <param name="data">DataManager instance needed to resolve game data.</param>
/// <param name="questId">The id of the quest.</param>
public QuestPayload(DataManager data, uint questId)
public QuestPayload(uint questId)
{
this.DataResolver = data;
this.questId = questId;
}

View file

@ -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 <see cref="StatusPayload"/> class.
/// Creates a new StatusPayload for the given status id.
/// </summary>
/// <param name="data">DataManager instance needed to resolve game data.</param>
/// <param name="statusId">The id of the Status for this link.</param>
public StatusPayload(DataManager data, uint statusId)
public StatusPayload(uint statusId)
{
this.DataResolver = data;
this.statusId = statusId;
}

View file

@ -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 <see cref="UIForegroundPayload"/> class.
/// Creates a new UIForegroundPayload for the given UIColor key.
/// </summary>
/// <param name="data">DataManager instance needed to resolve game data.</param>
/// <param name="colorKey">A UIColor key.</param>
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.
/// </summary>
// TODO Make this work with DI
public static UIForegroundPayload UIForegroundOff => new(null, 0);
public static UIForegroundPayload UIForegroundOff => new(0);
/// <inheritdoc/>
public override PayloadType Type => PayloadType.UIForeground;

View file

@ -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 <see cref="UIGlowPayload"/> class.
/// Creates a new UIForegroundPayload for the given UIColor key.
/// </summary>
/// <param name="data">DataManager instance needed to resolve game data.</param>
/// <param name="colorKey">A UIColor key.</param>
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.
/// </summary>
// TODO Make this work with DI
public static UIGlowPayload UIGlowOff => new(null, 0);
public static UIGlowPayload UIGlowOff => new(0);
/// <inheritdoc/>
public override PayloadType Type => PayloadType.UIGlow;

View file

@ -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.)
/// </summary>
/// <param name="json">A serialized SeString produced by ToJson() <see cref="ToJson"/>.</param>
/// <param name="dataManager">An initialized instance of DataManager for Lumina queries.</param>
/// <returns>A SeString initialized with values from the json.</returns>
public static SeString FromJson(string json, DataManager dataManager)
public static SeString FromJson(string json)
{
var s = JsonConvert.DeserializeObject<SeString>(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;
}

View file

@ -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
/// <summary>
/// This class facilitates creating new SeStrings and breaking down existing ones into their individual payload components.
/// </summary>
public class SeStringManager
[PluginInterface]
[InterfaceVersion("1.0")]
public sealed class SeStringManager
{
private readonly DataManager data;
/// <summary>
/// Initializes a new instance of the <see cref="SeStringManager"/> class.
/// </summary>
/// <param name="data">The DataManager instance.</param>
public SeStringManager(DataManager data)
internal SeStringManager()
{
this.data = data;
}
/// <summary>
@ -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
/// <returns>An SeString containing all the payloads necessary to display an item link in the chat log.</returns>
public SeString CreateItemLink(uint itemId, bool isHQ, string displayNameOverride = null)
{
var displayName = displayNameOverride ?? this.data.GetExcelSheet<Item>().GetRow(itemId).Name;
var data = Service<DataManager>.Get();
var displayName = displayNameOverride ?? data.GetExcelSheet<Item>().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<Payload>(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
/// <returns>An SeString containing all of the payloads necessary to display a map link in the chat log.</returns>
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<Payload>(new Payload[]
@ -127,7 +129,7 @@ namespace Dalamud.Game.Text.SeStringHandling
/// <returns>An SeString containing all of the payloads necessary to display a map link in the chat log.</returns>
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<Payload>(new Payload[]
@ -152,9 +154,11 @@ namespace Dalamud.Game.Text.SeStringHandling
/// <returns>An SeString containing all of the payloads necessary to display a map link in the chat log.</returns>
public SeString CreateMapLink(string placeName, float xCoord, float yCoord, float fudgeFactor = 0.05f)
{
var mapSheet = this.data.GetExcelSheet<Map>();
var data = Service<DataManager>.Get();
var matches = this.data.GetExcelSheet<PlaceName>()
var mapSheet = data.GetExcelSheet<Map>();
var matches = data.GetExcelSheet<PlaceName>()
.Where(row => row.Name.ToString().ToLowerInvariant() == placeName.ToLowerInvariant())
.ToArray();
@ -180,8 +184,8 @@ namespace Dalamud.Game.Text.SeStringHandling
{
return new List<Payload>(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,

View file

@ -19,10 +19,8 @@ namespace Dalamud.Hooking.Internal
/// <summary>
/// Initializes a new instance of the <see cref="HookManager"/> class.
/// </summary>
/// <param name="dalamud">Dalamud instance.</param>
internal HookManager(Dalamud dalamud)
public HookManager()
{
_ = dalamud;
}
/// <summary>

View file

@ -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
/// </summary>
internal class DalamudCommands
{
private readonly Dalamud dalamud;
/// <summary>
/// Initializes a new instance of the <see cref="DalamudCommands"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance to register to.</param>
public DalamudCommands(Dalamud dalamud)
public DalamudCommands()
{
this.dalamud = dalamud;
}
/// <summary>
@ -30,83 +30,85 @@ namespace Dalamud.Interface.Internal
/// </summary>
public void SetupCommands()
{
this.dalamud.CommandManager.AddHandler("/xldclose", new CommandInfo(this.OnUnloadCommand)
var commandManager = Service<CommandManager>.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 <word or sentence>"),
});
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 <word or sentence>"),
});
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 <BGM ID>"),
});
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<ChatGui>.Get().Print("Unloading...");
Service<Dalamud>.Get().Unload();
}
private void OnHelpCommand(string command, string arguments)
{
var chatGui = Service<ChatGui>.Get();
var commandManager = Service<CommandManager>.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<ChatGui>.Get();
chatGui.Print("Reloading...");
try
{
this.dalamud.PluginManager.ReloadAllPlugins();
this.dalamud.Framework.Gui.Chat.Print("OK");
Service<PluginManager>.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<string>();
var chatGui = Service<ChatGui>.Get();
var configuration = Service<DalamudConfiguration>.Get();
configuration.BadWords ??= new List<string>();
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<string>();
var chatGui = Service<ChatGui>.Get();
var configuration = Service<DalamudConfiguration>.Get();
if (this.dalamud.Configuration.BadWords.Count == 0)
configuration.BadWords ??= new List<string>();
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<string>();
var chatGui = Service<ChatGui>.Get();
var configuration = Service<DalamudConfiguration>.Get();
this.dalamud.Configuration.BadWords.RemoveAll(x => x == arguments);
configuration.BadWords ??= new List<string>();
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<ChatHandlers>.Get();
var chatGui = Service<ChatGui>.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<GameGui>.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<DalamudInterface>.Get().ToggleDevMenu();
}
private void OnDebugDrawDataMenu(string command, string arguments)
{
var dalamudInterface = Service<DalamudInterface>.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<DalamudInterface>.Get().OpenIMEWindow();
}
private void OnOpenLog(string command, string arguments)
{
this.dalamud.DalamudUi.ToggleLogWindow();
Service<DalamudInterface>.Get().ToggleLogWindow();
}
private void OnDebugImInfoCommand(string command, string arguments)
{
var io = this.dalamud.InterfaceManager.LastImGuiIoPtr;
var io = Service<InterfaceManager>.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<DalamudInterface>.Get().TogglePluginInstallerWindow();
}
private void OnOpenCreditsCommand(string command, string arguments)
{
this.dalamud.DalamudUi.ToggleCreditsWindow();
Service<DalamudInterface>.Get().ToggleCreditsWindow();
}
private void OnSetLanguageCommand(string command, string arguments)
{
var chatGui = Service<ChatGui>.Get();
var configuration = Service<DalamudConfiguration>.Get();
var localization = Service<Localization>.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<DalamudInterface>.Get().ToggleSettingsWindow();
}
}
}

View file

@ -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
/// <summary>
/// Initializes a new instance of the <see cref="DalamudInterface"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
public DalamudInterface(Dalamud dalamud)
public DalamudInterface()
{
this.dalamud = dalamud;
var configuration = Service<DalamudConfiguration>.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<InterfaceManager>.Get().Draw += this.OnDraw;
Log.Information("Windows added");
}
@ -112,7 +115,7 @@ namespace Dalamud.Interface.Internal
/// <inheritdoc/>
public void Dispose()
{
this.dalamud.InterfaceManager.Draw -= this.OnDraw;
Service<InterfaceManager>.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<GameGui>.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<Condition>.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<Dalamud>.Get();
var configuration = Service<DalamudConfiguration>.Get();
var pluginManager = Service<PluginManager>.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<LogEventLevel>())
{
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<AntiDebug>.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<Dalamud>.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<DalamudStartInfo>.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<ChatGui>.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<Localization>.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<GameGui>.Get().GameUiHidden)
ImGui.BeginMenu("UI is hidden...", false);
ImGui.BeginMenu(Util.GetGitHash(), false);

View file

@ -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
/// </summary>
internal class InterfaceManager : IDisposable
{
private readonly Dalamud dalamud;
private readonly string rtssPath;
private readonly Hook<PresentDelegate> presentHook;
@ -54,11 +56,11 @@ namespace Dalamud.Interface.Internal
/// <summary>
/// Initializes a new instance of the <see cref="InterfaceManager"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
/// <param name="scanner">The SigScanner instance.</param>
public InterfaceManager(Dalamud dalamud, SigScanner scanner)
public InterfaceManager()
{
this.dalamud = dalamud;
Service<Notifications>.Set();
var scanner = Service<SigScanner>.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<DalamudStartInfo>.Get();
var configuration = Service<DalamudConfiguration>.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<DalamudIME>.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<DalamudConfiguration>.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<Dalamud>.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<DalamudInterface>.GetNullable();
var gamepadState = Service<GamepadState>.GetNullable();
var keyState = Service<KeyState>.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<Notifications>.Get().Draw();
}
}
}

View file

@ -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
/// <param name="title">The title of the notification.</param>
/// <param name="type">The type of the notification.</param>
/// <param name="msDelay">The time the notification should be displayed for.</param>
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
{

View file

@ -15,16 +15,13 @@ namespace Dalamud.Interface.Internal.Scratchpad
/// </summary>
internal class ScratchExecutionManager
{
private readonly Dalamud dalamud;
private Dictionary<Guid, IDalamudPlugin> loadedScratches = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScratchExecutionManager"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
public ScratchExecutionManager(Dalamud dalamud)
public ScratchExecutionManager()
{
this.dalamud = dalamud;
}
/// <summary>
@ -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<IDalamudPlugin>("return new ScratchPlugin() as IDalamudPlugin;")
.RunAsync().GetAwaiter().GetResult().ReturnValue;

View file

@ -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}Delegate> hook{i}Inst;\n";
hookSetup += $"private delegate {hook.RetType} Hook{i}Delegate({hook.Arguments});\n";
hookSetup += $"private Hook<Hook{i}Delegate> hook{i}Inst;\n";
hookInit += $"var addrH{i} = pi.TargetModuleScanner.ScanText(\"{hook.Sig}\");\n";
hookInit += $"this.hook{i}Inst = new Hook<Hook{i}Delegate>(addrH{i}, new Hook{i}Delegate(Hook{i}Detour), this);\n";

View file

@ -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
/// <summary>
/// Initializes a new instance of the <see cref="UIDebug"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
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<SigScanner>.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<GetAtkStageSingleton>(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<GameGui>.Get().FindAgentInterface(atkUnitBase);
ImGui.Text($"{addonName}");
ImGui.SameLine();

View file

@ -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;
/// <summary>
/// Initializes a new instance of the <see cref="ChangelogWindow"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
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<DalamudInterface>.Get().OpenPluginInstaller();
}
if (ImGui.IsItemHovered())

View file

@ -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
/// </summary>
internal class ConsoleWindow : Window, IDisposable
{
private readonly Dalamud dalamud;
private readonly List<LogEntry> logText = new();
private readonly object renderLock = new();
@ -46,14 +46,13 @@ namespace Dalamud.Interface.Internal.Windows
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleWindow"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
public ConsoleWindow(Dalamud dalamud)
public ConsoleWindow()
: base("Dalamud Console")
{
this.dalamud = dalamud;
var configuration = Service<DalamudConfiguration>.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<Dalamud>.Get();
var configuration = Service<DalamudConfiguration>.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<LogEventLevel>().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<CommandManager>.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<CommandManager>.Get().Commands.Where(x => x.Key.Contains("/" + words[0])).ToList();
if (candidates.Count > 0)
{
ptr.DeleteChars(0, ptr.BufTextLen);

View file

@ -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!
/// <summary>
/// Initializes a new instance of the <see cref="CreditsWindow"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
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<Dalamud>.Get();
var interfaceManager = Service<InterfaceManager>.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!
/// <inheritdoc/>
public override void OnOpen()
{
var pluginCredits = this.dalamud.PluginManager.InstalledPlugins
var pluginCredits = Service<PluginManager>.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<GameGui>.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<GameGui>.Get().SetBgm(9999);
}
/// <inheritdoc/>

View file

@ -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
/// </summary>
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
/// <summary>
/// Initializes a new instance of the <see cref="DataWindow"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance to access data of.</param>
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<ChatGui>.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<SigScanner>.Get();
this.sigResult = sigScanner.ScanText(this.inputSig);
}
catch (KeyNotFoundException)
{
@ -337,38 +344,44 @@ namespace Dalamud.Interface.Internal.Windows
private void DrawObjectTable()
{
var chatGui = Service<ChatGui>.Get();
var clientState = Service<ClientState>.Get();
var framework = Service<Framework>.Get();
var gameGui = Service<GameGui>.Get();
var objectTable = Service<ObjectTable>.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<FateTable>.Get();
var framework = Service<Framework>.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<PartyList>.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<BuddyList>.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<PluginManager>.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<Condition>.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<ClientState>.Get();
var jobGauges = Service<JobGauges>.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<PLDGauge>();
var gauge = jobGauges.Get<PLDGauge>();
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<MNKGauge>();
var gauge = jobGauges.Get<MNKGauge>();
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<WARGauge>();
var gauge = jobGauges.Get<WARGauge>();
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<DRGGauge>();
var gauge = jobGauges.Get<DRGGauge>();
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<BRDGauge>();
var gauge = jobGauges.Get<BRDGauge>();
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<WHMGauge>();
var gauge = jobGauges.Get<WHMGauge>();
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<BLMGauge>();
var gauge = jobGauges.Get<BLMGauge>();
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<SMNGauge>();
var gauge = jobGauges.Get<SMNGauge>();
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<SCHGauge>();
var gauge = jobGauges.Get<SCHGauge>();
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<NINGauge>();
var gauge = jobGauges.Get<NINGauge>();
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<MCHGauge>();
var gauge = jobGauges.Get<MCHGauge>();
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<DRKGauge>();
var gauge = jobGauges.Get<DRKGauge>();
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<ASTGauge>();
var gauge = jobGauges.Get<ASTGauge>();
ImGui.Text($"Address: 0x{gauge.Address.ToInt64():X}");
ImGui.Text($"{nameof(gauge.DrawnCard)}: {gauge.DrawnCard}");
foreach (var seal in Enum.GetValues(typeof(SealType)).Cast<SealType>())
@ -795,7 +821,7 @@ namespace Dalamud.Interface.Internal.Windows
}
else if (jobID == 34)
{
var gauge = this.dalamud.ClientState.JobGauges.Get<SAMGauge>();
var gauge = jobGauges.Get<SAMGauge>();
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<RDMGauge>();
var gauge = jobGauges.Get<RDMGauge>();
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<GNBGauge>();
var gauge = jobGauges.Get<GNBGauge>();
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<DNCGauge>();
var gauge = jobGauges.Get<DNCGauge>();
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<CommandManager>.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<GameGui>.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<DalamudStartInfo>.Get();
ImGui.Text(JsonConvert.SerializeObject(startInfo, Formatting.Indented));
}
private void DrawTarget()
{
var targetMgr = this.dalamud.ClientState.Targets;
var clientState = Service<ClientState>.Get();
var targetMgr = Service<TargetManager>.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<ToastGui>.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<FlyTextGui>.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<InterfaceManager>.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<DataManager>.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<GamepadState>.Get();
static void DrawHelper(string text, uint mask, Func<GamepadButtons, float> 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<DataManager>.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;
}
}

View file

@ -11,16 +11,12 @@ namespace Dalamud.Interface.Internal.Windows
/// </summary>
internal class IMEWindow : Window
{
private readonly DalamudIME dalamudIME;
/// <summary>
/// Initializes a new instance of the <see cref="IMEWindow"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
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
/// <inheritdoc/>
public override void Draw()
{
if (this.dalamudIME == null || !this.dalamudIME.IsEnabled)
var ime = Service<DalamudIME>.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]}");
}
}
}

View file

@ -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
/// <summary>
/// Initializes a new instance of the <see cref="PluginInstallerWindow"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
public PluginInstallerWindow(Dalamud dalamud)
public PluginInstallerWindow()
: base(
Locs.WindowTitle + (dalamud.Configuration.DoPluginTest ? Locs.WindowTitleMod_Testing : string.Empty) + "###XlPluginInstaller",
Locs.WindowTitle + (Service<DalamudConfiguration>.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<Dalamud>.Get();
var interfaceManager = Service<InterfaceManager>.Get();
var pluginManager = Service<PluginManager>.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
/// <inheritdoc/>
public void Dispose()
{
this.dalamud.PluginManager.OnAvailablePluginsChanged -= this.OnAvailablePluginsChanged;
this.dalamud.PluginManager.OnInstalledPluginsChanged -= this.OnInstalledPluginsChanged;
var pluginManager = Service<PluginManager>.Get();
pluginManager.OnAvailablePluginsChanged -= this.OnAvailablePluginsChanged;
pluginManager.OnInstalledPluginsChanged -= this.OnInstalledPluginsChanged;
this.defaultIcon.Dispose();
this.troubleIcon.Dispose();
@ -139,7 +137,9 @@ namespace Dalamud.Interface.Internal.Windows
/// <inheritdoc/>
public override void OnOpen()
{
Task.Run(this.dalamud.PluginManager.ReloadPluginMasters);
var pluginManager = Service<PluginManager>.Get();
Task.Run(pluginManager.ReloadPluginMasters);
this.updatePluginCount = 0;
this.updatedPlugins = null;
@ -152,7 +152,7 @@ namespace Dalamud.Interface.Internal.Windows
/// <inheritdoc/>
public override void OnClose()
{
this.dalamud.Configuration.Save();
Service<DalamudConfiguration>.Get().Save();
}
/// <inheritdoc/>
@ -223,6 +223,9 @@ namespace Dalamud.Interface.Internal.Windows
private void DrawFooter()
{
var configuration = Service<DalamudConfiguration>.Get();
var pluginManager = Service<PluginManager>.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<DalamudInterface>.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<InterfaceManager>.Get();
var pluginManager = Service<PluginManager>.Get();
var notifications = Service<Notifications>.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<PluginManager>.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<DalamudConfiguration>.Get();
var interfaceManager = Service<InterfaceManager>.Get();
var notifications = Service<Notifications>.Get();
var pluginManager = Service<PluginManager>.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<DalamudConfiguration>.Get();
var pluginManager = Service<PluginManager>.Get();
var startInfo = Service<DalamudStartInfo>.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<DalamudConfiguration>.Get();
var commandManager = Service<CommandManager>.Get();
var pluginManager = Service<PluginManager>.Get();
var startInfo = Service<DalamudStartInfo>.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<PluginManager>.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<DalamudConfiguration>.Get();
var notifications = Service<Notifications>.Get();
var pluginManager = Service<PluginManager>.Get();
var startInfo = Service<DalamudStartInfo>.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<PluginManager>.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<DalamudConfiguration>.Get();
var pluginManager = Service<PluginManager>.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<PluginManager>.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<PluginManager>.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<DalamudConfiguration>.Get().SeenPluginInternalName.Contains(internalName);
/// <summary>
/// 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<InterfaceManager>.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<InterfaceManager>.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)
{

View file

@ -17,22 +17,21 @@ namespace Dalamud.Interface.Internal.Windows
/// </summary>
internal class PluginStatWindow : Window
{
private readonly PluginManager pluginManager;
private bool showDalamudHooks;
/// <summary>
/// Initializes a new instance of the <see cref="PluginStatWindow"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
public PluginStatWindow(Dalamud dalamud)
public PluginStatWindow()
: base("Plugin Statistics###DalamudPluginStatWindow")
{
this.pluginManager = dalamud.PluginManager;
}
/// <inheritdoc/>
public override void Draw()
{
var pluginManager = Service<PluginManager>.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();

View file

@ -16,7 +16,6 @@ namespace Dalamud.Interface.Internal.Windows
/// </summary>
internal class ScratchpadWindow : Window, IDisposable
{
private readonly Dalamud dalamud;
private readonly List<ScratchpadDocument> documents = new();
private readonly ScratchFileWatcher watcher = new();
private string pathInput = string.Empty;
@ -24,11 +23,9 @@ namespace Dalamud.Interface.Internal.Windows
/// <summary>
/// Initializes a new instance of the <see cref="ScratchpadWindow"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
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();
}
/// <summary>
@ -143,7 +140,7 @@ namespace Dalamud.Interface.Internal.Windows
if (ImGui.Button("Toggle Log"))
{
this.dalamud.DalamudUi.ToggleLogWindow();
Service<DalamudInterface>.Get().ToggleLogWindow();
}
ImGui.SameLine();

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var objectTable = Service<ObjectTable>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var chatGui = Service<ChatGui>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
dalamud.Framework.Gui.Chat.ChatMessage -= this.ChatOnOnChatMessage;
var chatGui = Service<ChatGui>.Get();
chatGui.ChatMessage -= this.ChatOnOnChatMessage;
this.subscribed = false;
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
if (!dalamud.ClientState.Condition.Any())
var condition = Service<Condition>.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;
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -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}";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var clientState = Service<ClientState>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
dalamud.ClientState.TerritoryChanged -= this.ClientStateOnTerritoryChanged;
var clientState = Service<ClientState>.Get();
clientState.TerritoryChanged -= this.ClientStateOnTerritoryChanged;
this.subscribed = false;
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var fateTable = Service<FateTable>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var gamepadState = Service<GamepadState>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
try
{
@ -27,7 +27,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var hoverItem = dalamud.Framework.Gui.HoveredItem;
var hoverAction = dalamud.Framework.Gui.HoveredAction;
var gameGui = Service<GameGui>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -1,4 +1,4 @@
namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps
namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps
{
/// <summary>
/// Interface for test implementations.
@ -13,14 +13,12 @@
/// <summary>
/// Run the test step, once per frame it is active.
/// </summary>
/// <param name="dalamud">Dalamud instance to act on.</param>
/// <returns>The result of this frame, test is discarded once a result other than <see cref="SelfTestStepResult.Waiting"/> is returned.</returns>
public SelfTestStepResult RunStep(Dalamud dalamud);
public SelfTestStepResult RunStep();
/// <summary>
/// Clean up this test.
/// </summary>
/// <param name="dalamud">Dalamud instance to act on.</param>
public void CleanUp(Dalamud dalamud);
public void CleanUp();
}
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var keyState = Service<KeyState>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var clientState = Service<ClientState>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
var clientState = Service<ClientState>.Get();
if (this.subscribed)
{
dalamud.ClientState.Login -= this.ClientStateOnOnLogin;
clientState.Login -= this.ClientStateOnOnLogin;
this.subscribed = false;
}
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var clientState = Service<ClientState>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
var clientState = Service<ClientState>.Get();
if (this.subscribed)
{
dalamud.ClientState.Logout -= this.ClientStateOnOnLogout;
clientState.Logout -= this.ClientStateOnOnLogout;
this.subscribed = false;
}
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
this.rows ??= dalamud.Data.GetExcelSheet<T>().ToList();
var dataManager = Service<DataManager>.Get();
this.rows ??= dataManager.GetExcelSheet<T>().ToList();
Util.ShowObject(this.rows[this.step]);
@ -31,7 +34,7 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var partyFinderGui = Service<PartyFinderGui>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
var partyFinderGui = Service<PartyFinderGui>.Get();
if (this.subscribed)
{
dalamud.Framework.Gui.PartyFinder.ReceiveListing -= this.PartyFinderOnReceiveListing;
partyFinderGui.ReceiveListing -= this.PartyFinderOnReceiveListing;
this.subscribed = false;
}
}

View file

@ -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";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
var targetManager = Service<TargetManager>.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
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -1,4 +1,6 @@
namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps
using Dalamud.Game.Gui.Toast;
namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps
{
/// <summary>
/// Test setup for toasts.
@ -9,16 +11,18 @@
public string Name => "Test Toasts";
/// <inheritdoc/>
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<ToastGui>.Get();
toastGui.ShowNormal("Normal Toast");
toastGui.ShowError("Error Toast");
return SelfTestStepResult.Pass;
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
// ignored
}

View file

@ -1,4 +1,4 @@
namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps
namespace Dalamud.Interface.Internal.Windows.SelfTest.AgingSteps
{
/// <summary>
/// Test that waits N frames.
@ -22,7 +22,7 @@
public string Name => $"Wait {this.cFrames} frames";
/// <inheritdoc/>
public SelfTestStepResult RunStep(Dalamud dalamud)
public SelfTestStepResult RunStep()
{
this.cFrames--;
@ -30,7 +30,7 @@
}
/// <inheritdoc/>
public void CleanUp(Dalamud dalamud)
public void CleanUp()
{
this.cFrames = this.frames;
}

View file

@ -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<IAgingStep> steps =
new()
{
@ -53,12 +51,9 @@ namespace Dalamud.Interface.Internal.Windows.SelfTest
/// <summary>
/// Initializes a new instance of the <see cref="SelfTestWindow"/> class.
/// </summary>
/// <param name="dalamud">The dalamud instance to act on.</param>
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)
{

View file

@ -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
/// <summary>
/// Initializes a new instance of the <see cref="SettingsWindow"/> class.
/// </summary>
/// <param name="dalamud">The Dalamud Instance.</param>
public SettingsWindow(Dalamud dalamud)
public SettingsWindow()
: base(Loc.Localize("DalamudSettingsHeader", "Dalamud Settings") + "###XlSettings2", ImGuiWindowFlags.NoCollapse)
{
this.dalamud = dalamud;
var configuration = Service<DalamudConfiguration>.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
/// <inheritdoc/>
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<DalamudConfiguration>.Get();
ImGui.GetIO().FontGlobalScale = configuration.GlobalUiScale;
this.thirdRepoList = configuration.ThirdRepoList.Select(x => x.Clone()).ToList();
this.devPluginLocations = configuration.DevPluginLoadLocations.Select(x => x.Clone()).ToList();
}
/// <inheritdoc/>
public override void Draw()
{
var configuration = Service<DalamudConfiguration>.Get();
var pluginManager = Service<PluginManager>.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<DalamudConfiguration>.Get();
var localization = Service<Localization>.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<PluginManager>.Get().ReloadPluginMasters();
}
}
}

View file

@ -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
/// </summary>
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 <see cref="UiBuilder"/> class and registers it.
/// You do not have to call this manually.
/// </summary>
/// <param name="dalamud">The dalamud to register on.</param>
/// <param name="namespaceName">The plugin namespace.</param>
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<InterfaceManager>.Get().Draw += this.OnDraw;
}
/// <summary>
@ -67,12 +66,12 @@ namespace Dalamud.Interface
/// <summary>
/// Gets the game's active Direct3D device.
/// </summary>
public Device Device => this.dalamud.InterfaceManager.Device;
public Device Device => Service<InterfaceManager>.Get().Device;
/// <summary>
/// Gets the game's main window handle.
/// </summary>
public IntPtr WindowHandlePtr => this.dalamud.InterfaceManager.WindowHandlePtr;
public IntPtr WindowHandlePtr => Service<InterfaceManager>.Get().WindowHandlePtr;
/// <summary>
/// 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
/// </summary>
public bool OverrideGameCursor
{
get => this.dalamud.InterfaceManager.OverrideGameCursor;
set => this.dalamud.InterfaceManager.OverrideGameCursor = value;
get => Service<InterfaceManager>.Get().OverrideGameCursor;
set => Service<InterfaceManager>.Get().OverrideGameCursor = value;
}
/// <summary>
@ -112,8 +111,8 @@ namespace Dalamud.Interface
/// </summary>
public Action OnBuildFonts
{
get => this.dalamud.InterfaceManager.OnBuildFonts;
set => this.dalamud.InterfaceManager.OnBuildFonts = value;
get => Service<InterfaceManager>.Get().OnBuildFonts;
set => Service<InterfaceManager>.Get().OnBuildFonts = value;
}
/// <summary>
@ -145,12 +144,24 @@ namespace Dalamud.Interface
/// </summary>
internal List<long> DrawTimeHistory { get; set; } = new List<long>();
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<Condition>.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<Condition>.Get();
return condition[ConditionFlag.WatchingCutscene];
}
}
/// <summary>
/// Loads an image from the specified file.
@ -158,7 +169,7 @@ namespace Dalamud.Interface
/// <param name="filePath">The full filepath to the image.</param>
/// <returns>A <see cref="TextureWrap"/> object wrapping the created image. Use <see cref="TextureWrap.ImGuiHandle"/> inside ImGui.Image().</returns>
public TextureWrap LoadImage(string filePath) =>
this.dalamud.InterfaceManager.LoadImage(filePath);
Service<InterfaceManager>.Get().LoadImage(filePath);
/// <summary>
/// Loads an image from a byte stream, such as a png downloaded into memory.
@ -166,7 +177,7 @@ namespace Dalamud.Interface
/// <param name="imageData">A byte array containing the raw image data.</param>
/// <returns>A <see cref="TextureWrap"/> object wrapping the created image. Use <see cref="TextureWrap.ImGuiHandle"/> inside ImGui.Image().</returns>
public TextureWrap LoadImage(byte[] imageData) =>
this.dalamud.InterfaceManager.LoadImage(imageData);
Service<InterfaceManager>.Get().LoadImage(imageData);
/// <summary>
/// Loads an image from raw unformatted pixel data, with no type or header information. To load formatted data, use <see cref="LoadImage(byte[])"/>.
@ -177,7 +188,7 @@ namespace Dalamud.Interface
/// <param name="numChannels">The number of channels (bytes per pixel) of the image contained in <paramref name="imageData"/>. This should usually be 4.</param>
/// <returns>A <see cref="TextureWrap"/> object wrapping the created image. Use <see cref="TextureWrap.ImGuiHandle"/> inside ImGui.Image().</returns>
public TextureWrap LoadImageRaw(byte[] imageData, int width, int height, int numChannels) =>
this.dalamud.InterfaceManager.LoadImageRaw(imageData, width, height, numChannels);
Service<InterfaceManager>.Get().LoadImageRaw(imageData, width, height, numChannels);
/// <summary>
/// Call this to queue a rebuild of the font atlas.<br/>
@ -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<InterfaceManager>.Get().RebuildFonts();
}
/// <summary>
@ -195,7 +206,7 @@ namespace Dalamud.Interface
/// </summary>
public void Dispose()
{
this.dalamud.InterfaceManager.Draw -= this.OnDraw;
Service<InterfaceManager>.Get().Draw -= this.OnDraw;
}
/// <summary>
@ -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<DalamudConfiguration>.Get();
var gameGui = Service<GameGui>.Get();
var interfaceManager = Service<InterfaceManager>.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);

View file

@ -0,0 +1,25 @@
using System;
namespace Dalamud.IoC.Internal
{
/// <summary>
/// This attribute represents the current version of a module that is loaded in the Service Locator.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
internal class InterfaceVersionAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="InterfaceVersionAttribute"/> class.
/// </summary>
/// <param name="version">The current version.</param>
public InterfaceVersionAttribute(string version)
{
this.Version = new(version);
}
/// <summary>
/// Gets the service version.
/// </summary>
public Version Version { get; }
}
}

View file

@ -0,0 +1,12 @@
using System;
namespace Dalamud.IoC
{
/// <summary>
/// This attribute indicates whether the decorated class should be exposed to plugins via IoC.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class PluginInterfaceAttribute : Attribute
{
}
}

View file

@ -0,0 +1,25 @@
using System;
namespace Dalamud.IoC
{
/// <summary>
/// This attribute indicates the version of a service module that is required for the plugin to load.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class RequiredVersionAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequiredVersionAttribute"/> class.
/// </summary>
/// <param name="version">The required version.</param>
public RequiredVersionAttribute(string version)
{
this.Version = new(version);
}
/// <summary>
/// Gets the required version.
/// </summary>
public Version Version { get; }
}
}

View file

@ -18,8 +18,6 @@ namespace Dalamud.Memory
/// </summary>
public static unsafe class MemoryHelper
{
private static SeStringManager seStringManager;
#region Read
/// <summary>
@ -232,7 +230,7 @@ namespace Dalamud.Memory
public static SeString ReadSeStringNullTerminated(IntPtr memoryAddress)
{
var buffer = ReadRawNullTerminated(memoryAddress);
return seStringManager.Parse(buffer);
return Service<SeStringManager>.Get().Parse(buffer);
}
/// <summary>
@ -248,13 +246,13 @@ namespace Dalamud.Memory
var eos = Array.IndexOf(buffer, (byte)0);
if (eos < 0)
{
return seStringManager.Parse(buffer);
return Service<SeStringManager>.Get().Parse(buffer);
}
else
{
var newBuffer = new byte[eos];
Buffer.BlockCopy(buffer, 0, newBuffer, 0, eos);
return seStringManager.Parse(newBuffer);
return Service<SeStringManager>.Get().Parse(newBuffer);
}
}
@ -655,14 +653,5 @@ namespace Dalamud.Memory
=> SizeOf<T>(marshal) * elementCount;
#endregion
/// <summary>
/// Initialize with static access to Dalamud.
/// </summary>
/// <param name="dalamud">The Dalamud instance.</param>
internal static void Initialize(Dalamud dalamud)
{
seStringManager = dalamud.SeStringManager;
}
}
}

View file

@ -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
/// </summary>
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 <see cref="DalamudPluginInterface"/> class.
/// Set up the interface and populate all fields needed.
/// </summary>
/// <param name="dalamud">The dalamud instance to expose.</param>
/// <param name="pluginName">The internal name of the plugin.</param>
/// <param name="reason">The reason the plugin was loaded.</param>
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<DalamudConfiguration>.Get();
var localization = Service<Localization>.Get();
this.CommandManager = Service<CommandManager>.Get();
this.Framework = Service<Framework>.Get();
this.ClientState = Service<ClientState>.Get();
this.UiBuilder = new UiBuilder(pluginName);
this.TargetModuleScanner = Service<SigScanner>.Get();
this.Data = Service<DataManager>.Get();
this.SeStringManager = Service<SeStringManager>.Get();
this.dalamud = dalamud;
this.pluginName = pluginName;
this.configs = dalamud.PluginManager.PluginConfigs;
this.configs = Service<PluginManager>.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;
}
/// <summary>
@ -89,7 +91,7 @@ namespace Dalamud.Plugin
/// <summary>
/// Gets the directory Dalamud assets are stored in.
/// </summary>
public DirectoryInfo DalamudAssetDirectory => this.dalamud.AssetDirectory;
public DirectoryInfo DalamudAssetDirectory => Service<Dalamud>.Get().AssetDirectory;
/// <summary>
/// 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<DalamudInterface>.Get().IsDevMenuOpen;
#endif
/// <summary>
@ -230,7 +232,7 @@ namespace Dalamud.Plugin
/// <returns>Returns an SeString payload for the link.</returns>
public DalamudLinkPayload AddChatLinkHandler(uint commandId, Action<uint, SeString> commandAction)
{
return this.Framework.Gui.Chat.AddChatLinkHandler(this.pluginName, commandId, commandAction);
return Service<ChatGui>.Get().AddChatLinkHandler(this.pluginName, commandId, commandAction);
}
/// <summary>
@ -239,7 +241,7 @@ namespace Dalamud.Plugin
/// <param name="commandId">The ID of the command.</param>
public void RemoveChatLinkHandler(uint commandId)
{
this.Framework.Gui.Chat.RemoveChatLinkHandler(this.pluginName, commandId);
Service<ChatGui>.Get().RemoveChatLinkHandler(this.pluginName, commandId);
}
/// <summary>
@ -247,7 +249,7 @@ namespace Dalamud.Plugin
/// </summary>
public void RemoveChatLinkHandler()
{
this.Framework.Gui.Chat.RemoveChatLinkHandler(this.pluginName);
Service<ChatGui>.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<ExpandoObject> action)
{
if (this.dalamud.PluginManager.IpcSubscriptions.Any(x => x.SourcePluginName == this.pluginName && x.SubPluginName == pluginName))
var pluginManager = Service<PluginManager>.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));
}
/// <summary>
@ -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<PluginManager>.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);
}
/// <summary>
@ -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<PluginManager>.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<PluginManager>.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<ChatGui>.Get().RemoveChatLinkHandler(this.pluginName);
Service<Localization>.Get().OnLocalizationChanged -= this.OnLocalizationChanged;
Service<DalamudConfiguration>.Get().OnDalamudConfigurationSaved -= this.OnDalamudConfigurationSaved;
}
private void OnLocalizationChanged(string langCode)

View file

@ -27,16 +27,17 @@ namespace Dalamud.Plugin.Internal
/// <summary>
/// Initializes a new instance of the <see cref="LocalDevPlugin"/> class.
/// </summary>
/// <param name="dalamud">Dalamud instance.</param>
/// <param name="dllFile">Path to the DLL file.</param>
/// <param name="manifest">The plugin manifest.</param>
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<DalamudConfiguration>.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)

View file

@ -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
/// <summary>
/// Initializes a new instance of the <see cref="LocalPlugin"/> class.
/// </summary>
/// <param name="dalamud">Dalamud instance.</param>
/// <param name="dllFile">Path to the DLL file.</param>
/// <param name="manifest">The plugin manifest.</param>
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
/// <param name="reloading">Load while reloading.</param>
public void Load(PluginLoadReason reason, bool reloading = false)
{
var startInfo = Service<DalamudStartInfo>.Get();
var configuration = Service<DalamudConfiguration>.Get();
var pluginManager = Service<PluginManager>.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)
{

View file

@ -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
/// <summary>
/// Initializes a new instance of the <see cref="PluginManager"/> class.
/// </summary>
/// <param name="dalamud">The <see cref="Dalamud"/> instance to load plugins with.</param>
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<DalamudStartInfo>.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<BannedPlugin[]>(bannedPluginsJson);
this.SetPluginReposFromConfig(false);
@ -143,8 +144,10 @@ namespace Dalamud.Plugin.Internal
/// <param name="notify">Whether the available plugins changed should be evented after.</param>
public void SetPluginReposFromConfig(bool notify)
{
var configuration = Service<DalamudConfiguration>.Get();
var repos = new List<PluginRepository>() { 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
/// </summary>
public void LoadAllPlugins()
{
if (this.dalamud.Configuration.PluginSafeMode)
var configuration = Service<DalamudConfiguration>.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
/// </summary>
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
/// </summary>
public void ScanDevPlugins()
{
var configuration = Service<DalamudConfiguration>.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
/// </summary>
public void CleanupPlugins()
{
var configuration = Service<DalamudConfiguration>.Get();
var startInfo = Service<DalamudStartInfo>.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
/// <param name="header">The header text to send to chat prior to any update info.</param>
public void PrintUpdatedPlugins(List<PluginUpdateStatus> updateMetadata, string header)
{
var chatGui = Service<ChatGui>.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
/// <returns>A value indicating whether testing should be used.</returns>
public bool UseTesting(PluginManifest manifest)
{
if (!this.dalamud.Configuration.DoPluginTest)
var configuration = Service<DalamudConfiguration>.Get();
if (!configuration.DoPluginTest)
return false;
if (manifest.IsTestingExclusive)
@ -836,8 +850,10 @@ namespace Dalamud.Plugin.Internal
/// <returns>If the manifest is visible.</returns>
public bool IsManifestVisible(RemotePluginManifest manifest)
{
var configuration = Service<DalamudConfiguration>.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
/// <returns>If the manifest is eligible.</returns>
public bool IsManifestEligible(PluginManifest manifest)
{
var configuration = Service<DalamudConfiguration>.Get();
var startInfo = Service<DalamudStartInfo>.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

122
Dalamud/Service{T}.cs Normal file
View file

@ -0,0 +1,122 @@
using System;
using System.Reflection;
using Dalamud.IoC;
using Dalamud.IoC.Internal;
using Dalamud.Logging.Internal;
namespace Dalamud
{
/// <summary>
/// Basic service locator.
/// </summary>
/// <remarks>
/// Only used internally within Dalamud, if plugins need access to things it should be _only_ via DI.
/// </remarks>
/// <typeparam name="T">The class you want to store in the service locator.</typeparam>
internal static class Service<T> where T : class
{
private static readonly ModuleLog Log = new("SVC");
private static T? instance;
static Service()
{
}
/// <summary>
/// Sets the type in the service locator to the given object.
/// </summary>
/// <param name="obj">Object to set.</param>
/// <returns>The set object.</returns>
public static T Set(T obj)
{
SetInstanceObject(obj);
return instance!;
}
/// <summary>
/// Sets the type in the service locator via the default parameterless constructor.
/// </summary>
/// <returns>The set object.</returns>
public static T Set()
{
var obj = (T?)Activator.CreateInstance(typeof(T), true);
SetInstanceObject(obj);
return instance!;
}
/// <summary>
/// Sets a type in the service locator via a constructor with the given parameter types.
/// </summary>
/// <param name="args">Constructor arguments.</param>
/// <returns>The set object.</returns>
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;
}
/// <summary>
/// Attempt to pull the instance out of the service locator.
/// </summary>
/// <returns>The object if registered.</returns>
/// <exception cref="InvalidOperationException">Thrown when the object instance is not present in the service locator.</exception>
public static T Get()
{
return instance ?? throw new InvalidOperationException($"{typeof(T).FullName} has not been registered in the service locator!");
}
/// <summary>
/// Attempt to pull the instance out of the service locator.
/// </summary>
/// <returns>The object if registered, null otherwise.</returns>
public static T? GetNullable()
{
return instance;
}
private static void SetInstanceObject(T instance)
{
Service<T>.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<PluginInterfaceAttribute>();
if (attr == null)
{
return false;
}
var ioc = Service<ServiceContainer>.GetNullable();
if (ioc == null)
{
return false;
}
ioc.RegisterSingleton(instance);
return true;
}
}
}

View file

@ -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
/// <param name="isInterfaceLoaded">Whether or not the interface was loaded.</param>
internal static void LogTroubleshooting(Dalamud dalamud, bool isInterfaceLoaded)
{
var interfaceManager = Service<InterfaceManager>.Get();
var startInfo = Service<DalamudStartInfo>.Get();
var pluginManager = Service<PluginManager>.Get();
var configuration = Service<DalamudConfiguration>.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)));