Skip to content

Commit

Permalink
Update Generichelpers
Browse files Browse the repository at this point in the history
  • Loading branch information
Limiana committed Mar 20, 2024
2 parents 32d781e + 5b84a97 commit d238d41
Show file tree
Hide file tree
Showing 28 changed files with 1,377 additions and 131 deletions.
12 changes: 12 additions & 0 deletions ECommons/Automation/Chat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,18 @@ public void SendMessage(string message)
SendMessageUnsafe(bytes);
#pragma warning restore CS0618 // Type or member is obsolete
}

/// <summary>
/// Executes command as if it was typed in chat box.
/// </summary>
/// <param name="message">Full text of the command.</param>
/// <exception cref="InvalidOperationException">If you didn't prefixed it with a slash.</exception>
public void ExecuteCommand(string message)
{
if (!message.StartsWith("/")) throw new InvalidOperationException($"Attempted to execute command but was not prefixed with a slash: {message}");
this.SendMessage(message);
}

/// <summary>
/// <para>
/// Sanitises a string by removing any invalid input.
Expand Down
66 changes: 52 additions & 14 deletions ECommons/Configuration/EzConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
using System.Linq;
using System.Text;
using System.CodeDom;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Threading.Tasks;
using ImGuiNET;

namespace ECommons.Configuration;

Expand All @@ -31,6 +35,8 @@ public static class EzConfig

private static bool WasCalled = false;

public static event Action? OnSave;

/// <summary>
/// Default serialization factory. Create a class that extends SerializationFactory, implement your own serializer and deserializer and assign DefaultSerializationFactory to it before loading any configurations to change serializer to your own liking.
/// </summary>
Expand Down Expand Up @@ -93,6 +99,10 @@ public static void Save()
if (Config != null)
{
SaveConfiguration(Config, DefaultSerializationFactory.DefaultConfigFileName, true);
if(OnSave != null)
{
GenericHelpers.Safe(OnSave.Invoke);
}
}
}

Expand All @@ -104,25 +114,48 @@ public static void Save()
/// <param name="prettyPrint">Inform serializer that you want pretty-print your configuration</param>
/// <param name="appendConfigDirectory">If true, plugin configuration directory will be added to path</param>
/// <param name="serializationFactory">If null, then default factory will be used.</param>
public static void SaveConfiguration(this IEzConfig Configuration, string path, bool prettyPrint = false, bool appendConfigDirectory = true, ISerializationFactory? serializationFactory = null)
/// <param name="writeFileAsync">Whether to perform writing operation in a separate thread. Serialization is performed in current thread.</param>
public static void SaveConfiguration(this IEzConfig Configuration, string path, bool prettyPrint = false, bool appendConfigDirectory = true, ISerializationFactory? serializationFactory = null, bool writeFileAsync = false)
{
WasCalled = true;
serializationFactory ??= DefaultSerializationFactory;
if (appendConfigDirectory) path = Path.Combine(Svc.PluginInterface.GetPluginConfigDirectory(), path);
var antiCorruptionPath = $"{path}.new";
if (File.Exists(antiCorruptionPath))
var serialized = serializationFactory.Serialize(Configuration, prettyPrint);
void Write()
{
try
{
lock (Configuration)
{
if (appendConfigDirectory) path = Path.Combine(Svc.PluginInterface.GetPluginConfigDirectory(), path);
var antiCorruptionPath = $"{path}.new";
if (File.Exists(antiCorruptionPath))
{
var saveTo = $"{antiCorruptionPath}.{DateTimeOffset.Now.ToUnixTimeMilliseconds()}";
PluginLog.Warning($"Detected unsuccessfully saved file {antiCorruptionPath}: moving to {saveTo}");
Notify.Warning("Detected unsuccessfully saved configuration file.");
File.Move(antiCorruptionPath, saveTo);
PluginLog.Warning($"Success. Please manually check {saveTo} file contents.");
}
PluginLog.Verbose($"From caller {GenericHelpers.GetCallStackID(999)} engaging anti-corruption mechanism, writing file to {antiCorruptionPath}");
File.WriteAllText(antiCorruptionPath, serialized, Encoding.UTF8);
PluginLog.Verbose($"Now moving {antiCorruptionPath} to {path}");
File.Move(antiCorruptionPath, path, true);
PluginLog.Verbose($"Configuration successfully saved.");
}
}
catch(Exception e)
{
e.Log();
}
}
if (writeFileAsync)
{
Task.Run(Write);
}
else
{
var saveTo = $"{antiCorruptionPath}.{DateTimeOffset.Now.ToUnixTimeMilliseconds()}";
PluginLog.Warning($"Detected unsuccessfully saved file {antiCorruptionPath}: moving to {saveTo}");
Notify.Warning("Detected unsuccessfully saved configuration file.");
File.Move(antiCorruptionPath, saveTo);
PluginLog.Warning($"Success. Please manually check {saveTo} file contents.");
Write();
}
PluginLog.Verbose($"From caller {GenericHelpers.GetCallStackID(999)} engaging anti-corruption mechanism, writing file to {antiCorruptionPath}");
File.WriteAllText(antiCorruptionPath, serializationFactory.Serialize(Configuration, prettyPrint), Encoding.UTF8);
PluginLog.Verbose($"Now moving {antiCorruptionPath} to {path}");
File.Move(antiCorruptionPath, path, true);
PluginLog.Verbose($"Configuration successfully saved.");
}

/// <summary>
Expand All @@ -144,4 +177,9 @@ public static T LoadConfiguration<T>(string path, bool appendConfigDirectory = t
}
return serializationFactory.Deserialize<T>(File.ReadAllText(path, Encoding.UTF8)) ?? new T();
}

internal static void Dispose()
{
OnSave = null;
}
}
4 changes: 2 additions & 2 deletions ECommons/ECommons.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
</PropertyGroup>

<PropertyGroup>
<TargetFramework>net7.0-windows</TargetFramework>
<TargetFramework>net8.0-windows</TargetFramework>
<Platforms>x64</Platforms>
<LangVersion>preview</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ProduceReferenceAssembly>false</ProduceReferenceAssembly>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<OutputPath>bin\$(Configuration)\</OutputPath>
<NoWarn>CS1591;CA1401</NoWarn>
<NoWarn>CS1591;CA1401;CS0649;CS8632;CS0414;CS0169</NoWarn>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<Optimize>True</Optimize>
<UseWindowsForms>true</UseWindowsForms>
Expand Down
5 changes: 5 additions & 0 deletions ECommons/ECommonsMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
using ECommons.EzEventManager;
using ECommons.EzHookManager;
using ECommons.EzSharedDataManager;
using Serilog.Events;
using ECommons.EzIpcManager;
#nullable disable

namespace ECommons;
Expand All @@ -32,6 +34,7 @@ public static void Init(DalamudPluginInterface pluginInterface, IDalamudPlugin i
Instance = instance;
GenericHelpers.Safe(() => Svc.Init(pluginInterface));
PluginLog.Information($"This is ECommons v{typeof(ECommonsMain).Assembly.GetName().Version} and {Svc.PluginInterface.InternalName} v{instance.GetType().Assembly.GetName().Version}. Hello!");
Svc.Log.MinimumLogLevel = LogEventLevel.Verbose;
GenericHelpers.Safe(CmdManager.Init);
if (modules.ContainsAny(Module.All, Module.ObjectFunctions))
{
Expand Down Expand Up @@ -64,6 +67,7 @@ public static void Dispose()
{
GenericHelpers.Safe(EzConfig.Save);
}
GenericHelpers.Safe(EzConfig.Dispose);
GenericHelpers.Safe(ThreadLoadImageHandler.Dispose);
GenericHelpers.Safe(ObjectLife.Dispose);
GenericHelpers.Safe(DalamudReflector.Dispose);
Expand Down Expand Up @@ -103,6 +107,7 @@ public static void Dispose()
GenericHelpers.Safe(EzEvent.DisposeAll);
GenericHelpers.Safe(EzHookCommon.DisposeAll);
GenericHelpers.Safe(EzSharedData.Dispose);
GenericHelpers.Safe(EzIPC.Dispose);
Chat.instance = null;
Instance = null;
}
Expand Down
11 changes: 11 additions & 0 deletions ECommons/ExcelServices/ExcelJobHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Lumina.Excel.GeneratedSheets;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;

namespace ECommons.ExcelServices;
#nullable disable
Expand All @@ -27,6 +28,16 @@ public static Job GetUpgradedJob(this Job j)
return j;
}

public static Job GetDowngradedJob(this Job j)
{
var dj = Upgrades.FindKeysByValue(j);
if(dj.TryGetFirst(out var ret))
{
return ret;
}
return j;
}

public static bool IsUpgradeable(this Job j) => Upgrades.ContainsKey(j);

public static int GetIcon(this Job j)
Expand Down
33 changes: 30 additions & 3 deletions ECommons/ExcelServices/ExcelWorldHelper.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using ECommons.DalamudServices;
using ECommons.DalamudServices;
using FFXIVClientStructs.FFXIV.Client.UI.Agent;
using Lumina.Excel.GeneratedSheets;
using System;
using System.Collections;
using System.Linq;
using System.Windows.Forms;

namespace ECommons.ExcelServices;
#nullable disable
Expand All @@ -12,6 +15,7 @@ public static class ExcelWorldHelper
public static World GetWorldByName(string name) => Get(name);
public static World Get(string name, bool onlyPublic = false)
{
if (name == null) return null;
if(Svc.Data.GetExcelSheet<World>().TryGetFirst(x => x.Name.ToString().EqualsIgnoreCase(name) && (!onlyPublic || x.Region.EqualsAny(Enum.GetValues<Region>().Select(z => (byte)z).ToArray())), out var result))
{
return result;
Expand Down Expand Up @@ -44,9 +48,24 @@ public static bool TryGet(uint id, out World result)
return result != null;
}

public static World[] GetPublicWorlds(Region? region)
public static World[] GetPublicWorlds(Region? region = null)
{
return Svc.Data.GetExcelSheet<World>().Where(x => ((region == null && x.Region.EqualsAny(Enum.GetValues<Region>().Select(z => (byte)z).ToArray())) || (region.HasValue && x.Region == (byte)region.Value)) && x.IsPublic).ToArray();
return Svc.Data.GetExcelSheet<World>().Where(x => x.IsPublic && (region == null || x.GetRegion() == region.Value)).ToArray();
}

public static World[] GetPublicWorlds(uint dataCenter)
{
return Svc.Data.GetExcelSheet<World>().Where(x => x.IsPublic && x.DataCenter.Row == dataCenter).ToArray();
}

public static WorldDCGroupType[] GetDataCenters(Region? region = null)
{
return Svc.Data.GetExcelSheet<WorldDCGroupType>().Where(x => region == null || (Region)x.Region == region.Value).ToArray();
}

public static WorldDCGroupType[] GetDataCenters(System.Collections.Generic.IEnumerable<Region> regions)
{
return Svc.Data.GetExcelSheet<WorldDCGroupType>().Where(x => regions.Contains((Region)x.Region)).ToArray();
}

[Obsolete("Please use Get")]
Expand Down Expand Up @@ -76,4 +95,12 @@ public enum Region
EU = 3,
OC = 4,
}

public static Region GetRegion(this World world)
{
var dc = world.DataCenter;
var dcg = Svc.Data.GetExcelSheet<WorldDCGroupType>().GetRow(dc.Row);
if (dcg == null) return 0;
return (Region)dcg.Region;
}
}
4 changes: 3 additions & 1 deletion ECommons/ExcelServices/Region.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System.Reflection;
using System;
using System.Reflection;

namespace ECommons.ExcelServices;

[Obfuscation(Exclude = true, ApplyToMembers = true)]
[Obsolete($"Use {nameof(ExcelWorldHelper.Region)}")]
public enum Region
{
JP = 1, NA = 2, EU = 3, OC = 4
Expand Down

0 comments on commit d238d41

Please sign in to comment.