refactor a little bit

This commit is contained in:
rootdarkarchon
2024-02-29 01:16:01 +01:00
committed by Loporrit
parent 6ab9812f9a
commit dd878e6e36
21 changed files with 1122 additions and 923 deletions

View File

@@ -0,0 +1,7 @@
namespace MareSynchronos.Interop.Ipc;
public interface IIpcCaller : IDisposable
{
bool APIAvailable { get; }
void CheckAPI();
}

View File

@@ -0,0 +1,139 @@
using Dalamud.Game.ClientState.Objects.Types;
using Dalamud.Plugin;
using Dalamud.Plugin.Ipc;
using Dalamud.Utility;
using MareSynchronos.Services;
using MareSynchronos.Services.Mediator;
using Microsoft.Extensions.Logging;
using System.Text;
namespace MareSynchronos.Interop.Ipc;
public sealed class IpcCallerCustomize : IIpcCaller
{
private readonly ICallGateSubscriber<(int, int)> _customizePlusApiVersion;
private readonly ICallGateSubscriber<ushort, (int, Guid?)> _customizePlusGetActiveProfile;
private readonly ICallGateSubscriber<Guid, (int, string?)> _customizePlusGetProfileById;
private readonly ICallGateSubscriber<ushort, Guid, object> _customizePlusOnScaleUpdate;
private readonly ICallGateSubscriber<ushort, int> _customizePlusRevertCharacter;
private readonly ICallGateSubscriber<ushort, string, (int, Guid?)> _customizePlusSetBodyScaleToCharacter;
private readonly ICallGateSubscriber<Guid, int> _customizePlusDeleteByUniqueId;
private readonly ILogger<IpcCallerCustomize> _logger;
private readonly DalamudUtilService _dalamudUtil;
private readonly MareMediator _mareMediator;
public IpcCallerCustomize(ILogger<IpcCallerCustomize> logger, IDalamudPluginInterface dalamudPluginInterface,
DalamudUtilService dalamudUtil, MareMediator mareMediator)
{
_customizePlusApiVersion = dalamudPluginInterface.GetIpcSubscriber<(int, int)>("CustomizePlus.General.GetApiVersion");
_customizePlusGetActiveProfile = dalamudPluginInterface.GetIpcSubscriber<ushort, (int, Guid?)>("CustomizePlus.Profile.GetActiveProfileIdOnCharacter");
_customizePlusGetProfileById = dalamudPluginInterface.GetIpcSubscriber<Guid, (int, string?)>("CustomizePlus.Profile.GetByUniqueId");
_customizePlusRevertCharacter = dalamudPluginInterface.GetIpcSubscriber<ushort, int>("CustomizePlus.Profile.DeleteTemporaryProfileOnCharacter");
_customizePlusSetBodyScaleToCharacter = dalamudPluginInterface.GetIpcSubscriber<ushort, string, (int, Guid?)>("CustomizePlus.Profile.SetTemporaryProfileOnCharacter");
_customizePlusOnScaleUpdate = dalamudPluginInterface.GetIpcSubscriber<ushort, Guid, object>("CustomizePlus.Profile.OnUpdate");
_customizePlusDeleteByUniqueId = dalamudPluginInterface.GetIpcSubscriber<Guid, int>("CustomizePlus.Profile.DeleteTemporaryProfileByUniqueId");
_customizePlusOnScaleUpdate.Subscribe(OnCustomizePlusScaleChange);
_logger = logger;
_dalamudUtil = dalamudUtil;
_mareMediator = mareMediator;
CheckAPI();
}
public bool APIAvailable { get; private set; } = false;
public async Task RevertAsync(nint character)
{
if (!APIAvailable) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
var gameObj = _dalamudUtil.CreateGameObject(character);
if (gameObj is ICharacter c)
{
_logger.LogTrace("CustomizePlus reverting for {chara}", c.Address.ToString("X"));
_customizePlusRevertCharacter!.InvokeFunc(c.ObjectIndex);
}
}).ConfigureAwait(false);
}
public async Task<Guid?> SetBodyScaleAsync(nint character, string scale)
{
if (!APIAvailable) return null;
return await _dalamudUtil.RunOnFrameworkThread(() =>
{
var gameObj = _dalamudUtil.CreateGameObject(character);
if (gameObj is ICharacter c)
{
string decodedScale = Encoding.UTF8.GetString(Convert.FromBase64String(scale));
_logger.LogTrace("CustomizePlus applying for {chara}", c.Address.ToString("X"));
if (scale.IsNullOrEmpty())
{
_customizePlusRevertCharacter!.InvokeFunc(c.ObjectIndex);
return null;
}
else
{
var result = _customizePlusSetBodyScaleToCharacter!.InvokeFunc(c.ObjectIndex, decodedScale);
return result.Item2;
}
}
return null;
}).ConfigureAwait(false);
}
public async Task RevertByIdAsync(Guid? profileId)
{
if (!APIAvailable || profileId == null) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
_ = _customizePlusDeleteByUniqueId.InvokeFunc(profileId.Value);
}).ConfigureAwait(false);
}
public async Task<string?> GetScaleAsync(nint character)
{
if (!APIAvailable) return null;
var scale = await _dalamudUtil.RunOnFrameworkThread(() =>
{
var gameObj = _dalamudUtil.CreateGameObject(character);
if (gameObj is ICharacter c)
{
var res = _customizePlusGetActiveProfile.InvokeFunc(c.ObjectIndex);
_logger.LogTrace("CustomizePlus GetActiveProfile returned {err}", res.Item1);
if (res.Item1 != 0 || res.Item2 == null) return string.Empty;
return _customizePlusGetProfileById.InvokeFunc(res.Item2.Value).Item2;
}
return string.Empty;
}).ConfigureAwait(false);
if (string.IsNullOrEmpty(scale)) return string.Empty;
return Convert.ToBase64String(Encoding.UTF8.GetBytes(scale));
}
public void CheckAPI()
{
try
{
var version = _customizePlusApiVersion.InvokeFunc();
APIAvailable = (version.Item1 == 6 && version.Item2 >= 0);
}
catch
{
APIAvailable = false;
}
}
private void OnCustomizePlusScaleChange(ushort c, Guid g)
{
var obj = _dalamudUtil.GetCharacterFromObjectTableByIndex(c);
_mareMediator.Publish(new CustomizePlusMessage(obj?.Name.ToString() ?? string.Empty));
}
public void Dispose()
{
_customizePlusOnScaleUpdate.Unsubscribe(OnCustomizePlusScaleChange);
}
}

View File

@@ -0,0 +1,211 @@
using Dalamud.Game.ClientState.Objects.Types;
using Dalamud.Interface.ImGuiNotification;
using Dalamud.Plugin;
using Glamourer.Api.Helpers;
using Glamourer.Api.IpcSubscribers;
using MareSynchronos.PlayerData.Handlers;
using MareSynchronos.Services;
using MareSynchronos.Services.Mediator;
using Microsoft.Extensions.Logging;
namespace MareSynchronos.Interop.Ipc;
public sealed class IpcCallerGlamourer : IIpcCaller
{
private readonly ILogger<IpcCallerGlamourer> _logger;
private readonly IDalamudPluginInterface _pi;
private readonly DalamudUtilService _dalamudUtil;
private readonly MareMediator _mareMediator;
private readonly RedrawManager _redrawManager;
private readonly ApiVersion _glamourerApiVersions;
private readonly ApplyState? _glamourerApplyAll;
private readonly GetStateBase64? _glamourerGetAllCustomization;
private readonly RevertState _glamourerRevert;
private readonly RevertStateName _glamourerRevertByName;
private readonly UnlockState _glamourerUnlock;
private readonly UnlockStateName _glamourerUnlockByName;
private readonly EventSubscriber<nint>? _glamourerStateChanged;
private bool _shownGlamourerUnavailable = false;
private readonly uint LockCode = 0x626E7579;
public IpcCallerGlamourer(ILogger<IpcCallerGlamourer> logger, IDalamudPluginInterface pi, DalamudUtilService dalamudUtil, MareMediator mareMediator,
RedrawManager redrawManager)
{
_glamourerApiVersions = new(pi);
_glamourerGetAllCustomization = new(pi);
_glamourerApplyAll = new(pi);
_glamourerRevert = new(pi);
_glamourerRevertByName = new(pi);
_glamourerUnlock = new(pi);
_glamourerUnlockByName = new(pi);
_logger = logger;
_pi = pi;
_dalamudUtil = dalamudUtil;
_mareMediator = mareMediator;
_redrawManager = redrawManager;
CheckAPI();
_glamourerStateChanged = StateChanged.Subscriber(pi, GlamourerChanged);
_glamourerStateChanged.Enable();
}
public bool APIAvailable { get; private set; }
public void CheckAPI()
{
bool apiAvailable = false;
try
{
bool versionValid = (_pi.InstalledPlugins
.FirstOrDefault(p => string.Equals(p.InternalName, "Glamourer", StringComparison.OrdinalIgnoreCase))
?.Version ?? new Version(0, 0, 0, 0)) >= new Version(1, 0, 6, 1);
try
{
var version = _glamourerApiVersions.Invoke();
if (version is { Major: 1, Minor: >= 1 } && versionValid)
{
apiAvailable = true;
}
}
catch
{
// ignore
}
_shownGlamourerUnavailable = _shownGlamourerUnavailable && !apiAvailable;
APIAvailable = apiAvailable;
}
catch
{
APIAvailable = apiAvailable;
}
finally
{
if (!apiAvailable && !_shownGlamourerUnavailable)
{
_shownGlamourerUnavailable = true;
_mareMediator.Publish(new NotificationMessage("Glamourer inactive", "Your Glamourer installation is not active or out of date. Update Glamourer to continue to use Loporrit. If you just updated Glamourer, ignore this message.",
NotificationType.Error));
}
}
}
public void Dispose()
{
_glamourerStateChanged?.Dispose();
}
public async Task ApplyAllAsync(ILogger logger, GameObjectHandler handler, string? customization, Guid applicationId, CancellationToken token, bool fireAndForget = false)
{
if (!APIAvailable || string.IsNullOrEmpty(customization) || _dalamudUtil.IsZoning) return;
await _redrawManager.RedrawSemaphore.WaitAsync(token).ConfigureAwait(false);
try
{
await _redrawManager.PenumbraRedrawInternalAsync(logger, handler, applicationId, (chara) =>
{
try
{
logger.LogDebug("[{appid}] Calling on IPC: GlamourerApplyAll", applicationId);
_glamourerApplyAll!.Invoke(customization, chara.ObjectIndex, LockCode);
}
catch (Exception ex)
{
logger.LogWarning(ex, "[{appid}] Failed to apply Glamourer data", applicationId);
}
}).ConfigureAwait(false);
}
finally
{
_redrawManager.RedrawSemaphore.Release();
}
}
public async Task<string> GetCharacterCustomizationAsync(IntPtr character)
{
if (!APIAvailable) return string.Empty;
try
{
return await _dalamudUtil.RunOnFrameworkThread(() =>
{
var gameObj = _dalamudUtil.CreateGameObject(character);
if (gameObj is ICharacter c)
{
return _glamourerGetAllCustomization!.Invoke(c.ObjectIndex).Item2 ?? string.Empty;
}
return string.Empty;
}).ConfigureAwait(false);
}
catch
{
return string.Empty;
}
}
public async Task RevertAsync(ILogger logger, GameObjectHandler handler, Guid applicationId, CancellationToken token)
{
if ((!APIAvailable) || _dalamudUtil.IsZoning) return;
try
{
await _redrawManager.RedrawSemaphore.WaitAsync(token).ConfigureAwait(false);
await _redrawManager.PenumbraRedrawInternalAsync(logger, handler, applicationId, (chara) =>
{
try
{
logger.LogDebug("[{appid}] Calling On IPC: GlamourerUnlock", applicationId);
_glamourerUnlock.Invoke(chara.ObjectIndex, LockCode);
logger.LogDebug("[{appid}] Calling On IPC: GlamourerRevert", applicationId);
_glamourerRevert.Invoke(chara.ObjectIndex, LockCode);
logger.LogDebug("[{appid}] Calling On IPC: PenumbraRedraw", applicationId);
_mareMediator.Publish(new PenumbraRedrawCharacterMessage(chara));
}
catch (Exception ex)
{
logger.LogWarning(ex, "[{appid}] Error during GlamourerRevert", applicationId);
}
}).ConfigureAwait(false);
}
finally
{
_redrawManager.RedrawSemaphore.Release();
}
}
public async Task RevertByNameAsync(ILogger logger, string name, Guid applicationId)
{
if ((!APIAvailable) || _dalamudUtil.IsZoning) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
RevertByName(logger, name, applicationId);
}).ConfigureAwait(false);
}
public void RevertByName(ILogger logger, string name, Guid applicationId)
{
if ((!APIAvailable) || _dalamudUtil.IsZoning) return;
try
{
logger.LogDebug("[{appid}] Calling On IPC: GlamourerRevertByName", applicationId);
_glamourerRevertByName.Invoke(name, LockCode);
logger.LogDebug("[{appid}] Calling On IPC: GlamourerUnlockName", applicationId);
_glamourerUnlockByName.Invoke(name, LockCode);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error during Glamourer RevertByName");
}
}
private void GlamourerChanged(nint address)
{
_mareMediator.Publish(new GlamourerChangedMessage(address));
}
}

View File

@@ -0,0 +1,94 @@
using Dalamud.Game.ClientState.Objects.Types;
using Dalamud.Plugin;
using Dalamud.Plugin.Ipc;
using MareSynchronos.Services;
using MareSynchronos.Services.Mediator;
using Microsoft.Extensions.Logging;
namespace MareSynchronos.Interop.Ipc;
public sealed class IpcCallerHeels : IIpcCaller
{
private readonly ILogger<IpcCallerHeels> _logger;
private readonly MareMediator _mareMediator;
private readonly DalamudUtilService _dalamudUtil;
private readonly ICallGateSubscriber<(int, int)> _heelsGetApiVersion;
private readonly ICallGateSubscriber<string> _heelsGetOffset;
private readonly ICallGateSubscriber<string, object?> _heelsOffsetUpdate;
private readonly ICallGateSubscriber<int, string, object?> _heelsRegisterPlayer;
private readonly ICallGateSubscriber<int, object?> _heelsUnregisterPlayer;
public IpcCallerHeels(ILogger<IpcCallerHeels> logger, IDalamudPluginInterface pi, DalamudUtilService dalamudUtil, MareMediator mareMediator)
{
_logger = logger;
_mareMediator = mareMediator;
_dalamudUtil = dalamudUtil;
_heelsGetApiVersion = pi.GetIpcSubscriber<(int, int)>("SimpleHeels.ApiVersion");
_heelsGetOffset = pi.GetIpcSubscriber<string>("SimpleHeels.GetLocalPlayer");
_heelsRegisterPlayer = pi.GetIpcSubscriber<int, string, object?>("SimpleHeels.RegisterPlayer");
_heelsUnregisterPlayer = pi.GetIpcSubscriber<int, object?>("SimpleHeels.UnregisterPlayer");
_heelsOffsetUpdate = pi.GetIpcSubscriber<string, object?>("SimpleHeels.LocalChanged");
_heelsOffsetUpdate.Subscribe(HeelsOffsetChange);
CheckAPI();
}
public bool APIAvailable { get; private set; } = false;
private void HeelsOffsetChange(string offset)
{
_mareMediator.Publish(new HeelsOffsetMessage());
}
public async Task<string> GetOffsetAsync()
{
if (!APIAvailable) return string.Empty;
return await _dalamudUtil.RunOnFrameworkThread(_heelsGetOffset.InvokeFunc).ConfigureAwait(false);
}
public async Task RestoreOffsetForPlayerAsync(IntPtr character)
{
if (!APIAvailable) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
var gameObj = _dalamudUtil.CreateGameObject(character);
if (gameObj != null)
{
_logger.LogTrace("Restoring Heels data to {chara}", character.ToString("X"));
_heelsUnregisterPlayer.InvokeAction(gameObj.ObjectIndex);
}
}).ConfigureAwait(false);
}
public async Task SetOffsetForPlayerAsync(IntPtr character, string data)
{
if (!APIAvailable) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
var gameObj = _dalamudUtil.CreateGameObject(character);
if (gameObj != null)
{
_logger.LogTrace("Applying Heels data to {chara}", character.ToString("X"));
_heelsRegisterPlayer.InvokeAction(gameObj.ObjectIndex, data);
}
}).ConfigureAwait(false);
}
public void CheckAPI()
{
try
{
APIAvailable = _heelsGetApiVersion.InvokeFunc() is { Item1: 2, Item2: >= 0 };
}
catch
{
APIAvailable = false;
}
}
public void Dispose()
{
_heelsOffsetUpdate.Unsubscribe(HeelsOffsetChange);
}
}

View File

@@ -0,0 +1,132 @@
using Dalamud.Game.ClientState.Objects.SubKinds;
using Dalamud.Plugin;
using Dalamud.Plugin.Ipc;
using MareSynchronos.Services;
using MareSynchronos.Services.Mediator;
using Microsoft.Extensions.Logging;
using System.Text;
namespace MareSynchronos.Interop.Ipc;
public sealed class IpcCallerHonorific : IIpcCaller
{
private readonly ICallGateSubscriber<(uint major, uint minor)> _honorificApiVersion;
private readonly ICallGateSubscriber<int, object> _honorificClearCharacterTitle;
private readonly ICallGateSubscriber<object> _honorificDisposing;
private readonly ICallGateSubscriber<string> _honorificGetLocalCharacterTitle;
private readonly ICallGateSubscriber<string, object> _honorificLocalCharacterTitleChanged;
private readonly ICallGateSubscriber<object> _honorificReady;
private readonly ICallGateSubscriber<int, string, object> _honorificSetCharacterTitle;
private readonly ILogger<IpcCallerHonorific> _logger;
private readonly MareMediator _mareMediator;
private readonly DalamudUtilService _dalamudUtil;
public IpcCallerHonorific(ILogger<IpcCallerHonorific> logger, IDalamudPluginInterface pi, DalamudUtilService dalamudUtil,
MareMediator mareMediator)
{
_logger = logger;
_mareMediator = mareMediator;
_dalamudUtil = dalamudUtil;
_honorificApiVersion = pi.GetIpcSubscriber<(uint, uint)>("Honorific.ApiVersion");
_honorificGetLocalCharacterTitle = pi.GetIpcSubscriber<string>("Honorific.GetLocalCharacterTitle");
_honorificClearCharacterTitle = pi.GetIpcSubscriber<int, object>("Honorific.ClearCharacterTitle");
_honorificSetCharacterTitle = pi.GetIpcSubscriber<int, string, object>("Honorific.SetCharacterTitle");
_honorificLocalCharacterTitleChanged = pi.GetIpcSubscriber<string, object>("Honorific.LocalCharacterTitleChanged");
_honorificDisposing = pi.GetIpcSubscriber<object>("Honorific.Disposing");
_honorificReady = pi.GetIpcSubscriber<object>("Honorific.Ready");
_honorificLocalCharacterTitleChanged.Subscribe(OnHonorificLocalCharacterTitleChanged);
_honorificDisposing.Subscribe(OnHonorificDisposing);
_honorificReady.Subscribe(OnHonorificReady);
CheckAPI();
}
public bool APIAvailable { get; private set; } = false;
public void CheckAPI()
{
try
{
APIAvailable = _honorificApiVersion.InvokeFunc() is { Item1: 3, Item2: >= 0 };
}
catch
{
APIAvailable = false;
}
}
public void Dispose()
{
_honorificLocalCharacterTitleChanged.Unsubscribe(OnHonorificLocalCharacterTitleChanged);
_honorificDisposing.Unsubscribe(OnHonorificDisposing);
_honorificReady.Unsubscribe(OnHonorificReady);
}
public async Task ClearTitleAsync(nint character)
{
if (!APIAvailable) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
var gameObj = _dalamudUtil.CreateGameObject(character);
if (gameObj is IPlayerCharacter c)
{
_logger.LogTrace("Honorific removing for {addr}", c.Address.ToString("X"));
_honorificClearCharacterTitle!.InvokeAction(c.ObjectIndex);
}
}).ConfigureAwait(false);
}
public string GetTitle()
{
if (!APIAvailable) return string.Empty;
string title = _honorificGetLocalCharacterTitle.InvokeFunc();
return string.IsNullOrEmpty(title) ? string.Empty : Convert.ToBase64String(Encoding.UTF8.GetBytes(title));
}
public async Task SetTitleAsync(IntPtr character, string honorificDataB64)
{
if (!APIAvailable) return;
_logger.LogTrace("Applying Honorific data to {chara}", character.ToString("X"));
try
{
await _dalamudUtil.RunOnFrameworkThread(() =>
{
var gameObj = _dalamudUtil.CreateGameObject(character);
if (gameObj is IPlayerCharacter pc)
{
string honorificData = string.IsNullOrEmpty(honorificDataB64) ? string.Empty : Encoding.UTF8.GetString(Convert.FromBase64String(honorificDataB64));
if (string.IsNullOrEmpty(honorificData))
{
_honorificClearCharacterTitle!.InvokeAction(pc.ObjectIndex);
}
else
{
_honorificSetCharacterTitle!.InvokeAction(pc.ObjectIndex, honorificData);
}
}
}).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogWarning(e, "Could not apply Honorific data");
}
}
private void OnHonorificDisposing()
{
_mareMediator.Publish(new HonorificMessage(string.Empty));
}
private void OnHonorificLocalCharacterTitleChanged(string titleJson)
{
string titleData = string.IsNullOrEmpty(titleJson) ? string.Empty : Convert.ToBase64String(Encoding.UTF8.GetBytes(titleJson));
_mareMediator.Publish(new HonorificMessage(titleData));
}
private void OnHonorificReady()
{
CheckAPI();
_mareMediator.Publish(new HonorificReadyMessage());
}
}

View File

@@ -0,0 +1,334 @@
using Dalamud.Interface.ImGuiNotification;
using Dalamud.Plugin;
using MareSynchronos.MareConfiguration.Models;
using MareSynchronos.PlayerData.Handlers;
using MareSynchronos.Services;
using MareSynchronos.Services.Mediator;
using Microsoft.Extensions.Logging;
using Penumbra.Api.Enums;
using Penumbra.Api.Helpers;
using Penumbra.Api.IpcSubscribers;
using System.Collections.Concurrent;
namespace MareSynchronos.Interop.Ipc;
public sealed class IpcCallerPenumbra : DisposableMediatorSubscriberBase, IIpcCaller
{
private readonly IDalamudPluginInterface _pi;
private readonly DalamudUtilService _dalamudUtil;
private readonly MareMediator _mareMediator;
private readonly RedrawManager _redrawManager;
private bool _shownPenumbraUnavailable = false;
private string? _penumbraModDirectory;
public string? PenumbraModDirectory
{
get => _penumbraModDirectory;
private set
{
if (!string.Equals(_penumbraModDirectory, value, StringComparison.Ordinal))
{
_penumbraModDirectory = value;
_mareMediator.Publish(new PenumbraDirectoryChangedMessage(_penumbraModDirectory));
}
}
}
private readonly ConcurrentDictionary<IntPtr, bool> _penumbraRedrawRequests = new();
private readonly EventSubscriber _penumbraDispose;
private readonly EventSubscriber<nint, string, string> _penumbraGameObjectResourcePathResolved;
private readonly EventSubscriber _penumbraInit;
private readonly EventSubscriber<ModSettingChange, Guid, string, bool> _penumbraModSettingChanged;
private readonly EventSubscriber<nint, int> _penumbraObjectIsRedrawn;
private readonly AddTemporaryMod _penumbraAddTemporaryMod;
private readonly AssignTemporaryCollection _penumbraAssignTemporaryCollection;
private readonly ConvertTextureFile _penumbraConvertTextureFile;
private readonly CreateTemporaryCollection _penumbraCreateNamedTemporaryCollection;
private readonly GetEnabledState _penumbraEnabled;
private readonly GetPlayerMetaManipulations _penumbraGetMetaManipulations;
private readonly RedrawObject _penumbraRedraw;
private readonly DeleteTemporaryCollection _penumbraRemoveTemporaryCollection;
private readonly RemoveTemporaryMod _penumbraRemoveTemporaryMod;
private readonly GetModDirectory _penumbraResolveModDir;
private readonly ResolvePlayerPathsAsync _penumbraResolvePaths;
private readonly GetGameObjectResourcePaths _penumbraResourcePaths;
public IpcCallerPenumbra(ILogger<IpcCallerPenumbra> logger, IDalamudPluginInterface pi, DalamudUtilService dalamudUtil,
MareMediator mareMediator, RedrawManager redrawManager) : base(logger, mareMediator)
{
_pi = pi;
_dalamudUtil = dalamudUtil;
_mareMediator = mareMediator;
_redrawManager = redrawManager;
_penumbraInit = Initialized.Subscriber(pi, PenumbraInit);
_penumbraDispose = Disposed.Subscriber(pi, PenumbraDispose);
_penumbraResolveModDir = new GetModDirectory(pi);
_penumbraRedraw = new RedrawObject(pi);
_penumbraObjectIsRedrawn = GameObjectRedrawn.Subscriber(pi, RedrawEvent);
_penumbraGetMetaManipulations = new GetPlayerMetaManipulations(pi);
_penumbraRemoveTemporaryMod = new RemoveTemporaryMod(pi);
_penumbraAddTemporaryMod = new AddTemporaryMod(pi);
_penumbraCreateNamedTemporaryCollection = new CreateTemporaryCollection(pi);
_penumbraRemoveTemporaryCollection = new DeleteTemporaryCollection(pi);
_penumbraAssignTemporaryCollection = new AssignTemporaryCollection(pi);
_penumbraResolvePaths = new ResolvePlayerPathsAsync(pi);
_penumbraEnabled = new GetEnabledState(pi);
_penumbraModSettingChanged = ModSettingChanged.Subscriber(pi, (change, arg1, arg, b) =>
{
if (change == ModSettingChange.EnableState)
_mareMediator.Publish(new PenumbraModSettingChangedMessage());
});
_penumbraConvertTextureFile = new ConvertTextureFile(pi);
_penumbraResourcePaths = new GetGameObjectResourcePaths(pi);
_penumbraGameObjectResourcePathResolved = GameObjectResourcePathResolved.Subscriber(pi, ResourceLoaded);
CheckAPI();
CheckModDirectory();
Mediator.Subscribe<PenumbraRedrawCharacterMessage>(this, (msg) =>
{
_penumbraRedraw.Invoke(msg.Character.ObjectIndex, RedrawType.AfterGPose);
});
}
public bool APIAvailable { get; private set; } = false;
public void CheckAPI()
{
bool penumbraAvailable = false;
try
{
var penumbraVersion = (_pi.InstalledPlugins
.FirstOrDefault(p => string.Equals(p.InternalName, "Penumbra", StringComparison.OrdinalIgnoreCase))
?.Version ?? new Version(0, 0, 0, 0));
penumbraAvailable = penumbraVersion >= new Version(1, 0, 1, 0);
penumbraAvailable &= _penumbraEnabled.Invoke();
_shownPenumbraUnavailable = _shownPenumbraUnavailable && !penumbraAvailable;
APIAvailable = penumbraAvailable;
}
catch
{
APIAvailable = penumbraAvailable;
}
finally
{
if (!penumbraAvailable && !_shownPenumbraUnavailable)
{
_shownPenumbraUnavailable = true;
_mareMediator.Publish(new NotificationMessage("Penumbra inactive",
"Your Penumbra installation is not active or out of date. Update Penumbra and/or the Enable Mods setting in Penumbra to continue to use Loporrit. If you just updated Penumbra, ignore this message.",
NotificationType.Error));
}
}
}
public void CheckModDirectory()
{
if (!APIAvailable)
{
PenumbraModDirectory = string.Empty;
}
else
{
PenumbraModDirectory = _penumbraResolveModDir!.Invoke().ToLowerInvariant();
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_redrawManager.Cancel();
_penumbraModSettingChanged.Dispose();
_penumbraGameObjectResourcePathResolved.Dispose();
_penumbraDispose.Dispose();
_penumbraInit.Dispose();
_penumbraObjectIsRedrawn.Dispose();
}
public async Task AssignTemporaryCollectionAsync(ILogger logger, Guid collName, int idx)
{
if (!APIAvailable) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
var retAssign = _penumbraAssignTemporaryCollection.Invoke(collName, idx, forceAssignment: true);
logger.LogTrace("Assigning Temp Collection {collName} to index {idx}, Success: {ret}", collName, idx, retAssign);
return collName;
}).ConfigureAwait(false);
}
public async Task ConvertTextureFiles(ILogger logger, Dictionary<string, string[]> textures, IProgress<(string, int)> progress, CancellationToken token)
{
if (!APIAvailable) return;
_mareMediator.Publish(new HaltScanMessage(nameof(ConvertTextureFiles)));
int currentTexture = 0;
foreach (var texture in textures)
{
if (token.IsCancellationRequested) break;
progress.Report((texture.Key, ++currentTexture));
logger.LogInformation("Converting Texture {path} to {type}", texture.Key, TextureType.Bc7Tex);
var convertTask = _penumbraConvertTextureFile.Invoke(texture.Key, texture.Key, TextureType.Bc7Tex, mipMaps: true);
await convertTask.ConfigureAwait(false);
if (convertTask.IsCompletedSuccessfully && texture.Value.Any())
{
foreach (var duplicatedTexture in texture.Value)
{
logger.LogInformation("Migrating duplicate {dup}", duplicatedTexture);
try
{
File.Copy(texture.Key, duplicatedTexture, overwrite: true);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to copy duplicate {dup}", duplicatedTexture);
}
}
}
}
_mareMediator.Publish(new ResumeScanMessage(nameof(ConvertTextureFiles)));
await _dalamudUtil.RunOnFrameworkThread(async () =>
{
var gameObject = await _dalamudUtil.CreateGameObjectAsync(await _dalamudUtil.GetPlayerPointerAsync().ConfigureAwait(false)).ConfigureAwait(false);
_penumbraRedraw.Invoke(gameObject!.ObjectIndex, RedrawType.Redraw);
}).ConfigureAwait(false);
}
public async Task<Guid> CreateTemporaryCollectionAsync(ILogger logger, string uid)
{
if (!APIAvailable) return Guid.Empty;
return await _dalamudUtil.RunOnFrameworkThread(() =>
{
var collName = "Loporrit_" + uid;
var collId = _penumbraCreateNamedTemporaryCollection.Invoke(collName);
logger.LogTrace("Creating Temp Collection {collName}, GUID: {collId}", collName, collId);
return collId;
}).ConfigureAwait(false);
}
public async Task<Dictionary<string, HashSet<string>>?> GetCharacterData(ILogger logger, GameObjectHandler handler)
{
if (!APIAvailable) return null;
return await _dalamudUtil.RunOnFrameworkThread(() =>
{
logger.LogTrace("Calling On IPC: Penumbra.GetGameObjectResourcePaths");
var idx = handler.GetGameObject()?.ObjectIndex;
if (idx == null) return null;
return _penumbraResourcePaths.Invoke(idx.Value)[0];
}).ConfigureAwait(false);
}
public string GetMetaManipulations()
{
if (!APIAvailable) return string.Empty;
return _penumbraGetMetaManipulations.Invoke();
}
public async Task RedrawAsync(ILogger logger, GameObjectHandler handler, Guid applicationId, CancellationToken token)
{
if (!APIAvailable || _dalamudUtil.IsZoning) return;
try
{
await _redrawManager.RedrawSemaphore.WaitAsync(token).ConfigureAwait(false);
await _redrawManager.PenumbraRedrawInternalAsync(logger, handler, applicationId, (chara) =>
{
logger.LogDebug("[{appid}] Calling on IPC: PenumbraRedraw", applicationId);
_penumbraRedraw!.Invoke(chara.ObjectIndex, setting: RedrawType.Redraw);
}).ConfigureAwait(false);
}
finally
{
_redrawManager.RedrawSemaphore.Release();
}
}
public async Task RemoveTemporaryCollectionAsync(ILogger logger, Guid applicationId, Guid collId)
{
if (!APIAvailable) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
logger.LogTrace("[{applicationId}] Removing temp collection for {collId}", applicationId, collId);
var ret2 = _penumbraRemoveTemporaryCollection.Invoke(collId);
logger.LogTrace("[{applicationId}] RemoveTemporaryCollection: {ret2}", applicationId, ret2);
}).ConfigureAwait(false);
}
public async Task<(string[] forward, string[][] reverse)> ResolvePathsAsync(string[] forward, string[] reverse)
{
return await _penumbraResolvePaths.Invoke(forward, reverse).ConfigureAwait(false);
}
public async Task SetManipulationDataAsync(ILogger logger, Guid applicationId, Guid collId, string manipulationData)
{
if (!APIAvailable) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
logger.LogTrace("[{applicationId}] Manip: {data}", applicationId, manipulationData);
var retAdd = _penumbraAddTemporaryMod.Invoke("MareChara_Meta", collId, [], manipulationData, 0);
logger.LogTrace("[{applicationId}] Setting temp meta mod for {collId}, Success: {ret}", applicationId, collId, retAdd);
}).ConfigureAwait(false);
}
public async Task SetTemporaryModsAsync(ILogger logger, Guid applicationId, Guid collId, Dictionary<string, string> modPaths)
{
if (!APIAvailable) return;
await _dalamudUtil.RunOnFrameworkThread(() =>
{
foreach (var mod in modPaths)
{
logger.LogTrace("[{applicationId}] Change: {from} => {to}", applicationId, mod.Key, mod.Value);
}
var retRemove = _penumbraRemoveTemporaryMod.Invoke("MareChara_Files", collId, 0);
logger.LogTrace("[{applicationId}] Removing temp files mod for {collId}, Success: {ret}", applicationId, collId, retRemove);
var retAdd = _penumbraAddTemporaryMod.Invoke("MareChara_Files", collId, modPaths, string.Empty, 0);
logger.LogTrace("[{applicationId}] Setting temp files mod for {collId}, Success: {ret}", applicationId, collId, retAdd);
}).ConfigureAwait(false);
}
private void RedrawEvent(IntPtr objectAddress, int objectTableIndex)
{
bool wasRequested = false;
if (_penumbraRedrawRequests.TryGetValue(objectAddress, out var redrawRequest) && redrawRequest)
{
_penumbraRedrawRequests[objectAddress] = false;
}
else
{
_mareMediator.Publish(new PenumbraRedrawMessage(objectAddress, objectTableIndex, wasRequested));
}
}
private void ResourceLoaded(IntPtr ptr, string arg1, string arg2)
{
if (ptr != IntPtr.Zero && string.Compare(arg1, arg2, ignoreCase: true, System.Globalization.CultureInfo.InvariantCulture) != 0)
{
_mareMediator.Publish(new PenumbraResourceLoadMessage(ptr, arg1, arg2));
}
}
private void PenumbraDispose()
{
_redrawManager.Cancel();
_mareMediator.Publish(new PenumbraDisposedMessage());
}
private void PenumbraInit()
{
APIAvailable = true;
PenumbraModDirectory = _penumbraResolveModDir.Invoke();
_mareMediator.Publish(new PenumbraInitializedMessage());
_penumbraRedraw!.Invoke(0, setting: RedrawType.Redraw);
}
}

View File

@@ -0,0 +1,52 @@
using MareSynchronos.Services.Mediator;
using Microsoft.Extensions.Logging;
namespace MareSynchronos.Interop.Ipc;
public sealed partial class IpcManager : DisposableMediatorSubscriberBase
{
public IpcManager(ILogger<IpcManager> logger, MareMediator mediator,
IpcCallerPenumbra penumbraIpc, IpcCallerGlamourer glamourerIpc, IpcCallerCustomize customizeIpc, IpcCallerHeels heelsIpc,
IpcCallerHonorific honorificIpc) : base(logger, mediator)
{
CustomizePlus = customizeIpc;
Heels = heelsIpc;
Glamourer = glamourerIpc;
Penumbra = penumbraIpc;
Honorific = honorificIpc;
if (Initialized)
{
Mediator.Publish(new PenumbraInitializedMessage());
}
Mediator.Subscribe<DelayedFrameworkUpdateMessage>(this, (_) => PeriodicApiStateCheck());
try
{
PeriodicApiStateCheck();
}
catch (Exception ex)
{
logger.LogWarning(ex, "Failed to check for some IPC, plugin not installed?");
}
}
public bool Initialized => Penumbra.APIAvailable && Glamourer.APIAvailable;
public IpcCallerCustomize CustomizePlus { get; init; }
public IpcCallerHonorific Honorific { get; init; }
public IpcCallerHeels Heels { get; init; }
public IpcCallerGlamourer Glamourer { get; }
public IpcCallerPenumbra Penumbra { get; }
private void PeriodicApiStateCheck()
{
Penumbra.CheckAPI();
Penumbra.CheckModDirectory();
Glamourer.CheckAPI();
Heels.CheckAPI();
CustomizePlus.CheckAPI();
Honorific.CheckAPI();
}
}

View File

@@ -0,0 +1,51 @@
using Dalamud.Game.ClientState.Objects.Types;
using MareSynchronos.PlayerData.Handlers;
using MareSynchronos.Services;
using MareSynchronos.Services.Mediator;
using MareSynchronos.Utils;
using Microsoft.Extensions.Logging;
namespace MareSynchronos.Interop.Ipc;
public class RedrawManager
{
private readonly MareMediator _mareMediator;
private readonly DalamudUtilService _dalamudUtil;
private readonly Dictionary<nint, bool> _penumbraRedrawRequests = [];
private CancellationTokenSource _disposalCts = new();
public SemaphoreSlim RedrawSemaphore { get; init; } = new(2, 2);
public RedrawManager(MareMediator mareMediator, DalamudUtilService dalamudUtil)
{
_mareMediator = mareMediator;
_dalamudUtil = dalamudUtil;
}
public async Task PenumbraRedrawInternalAsync(ILogger logger, GameObjectHandler handler, Guid applicationId, Action<ICharacter> action)
{
_mareMediator.Publish(new PenumbraStartRedrawMessage(handler.Address));
_penumbraRedrawRequests[handler.Address] = true;
try
{
CancellationTokenSource cancelToken = new CancellationTokenSource();
cancelToken.CancelAfter(TimeSpan.FromSeconds(15));
await handler.ActOnFrameworkAfterEnsureNoDrawAsync(action, cancelToken.Token).ConfigureAwait(false);
if (!_disposalCts.Token.IsCancellationRequested)
await _dalamudUtil.WaitWhileCharacterIsDrawing(logger, handler, applicationId, 30000, _disposalCts.Token).ConfigureAwait(false);
}
finally
{
_penumbraRedrawRequests[handler.Address] = false;
_mareMediator.Publish(new PenumbraEndRedrawMessage(handler.Address));
}
}
internal void Cancel()
{
_disposalCts = _disposalCts.CancelRecreate();
}
}