Skip to content

Commit

Permalink
Using collection expression
Browse files Browse the repository at this point in the history
  • Loading branch information
Aragas committed Oct 4, 2024
1 parent bf71e36 commit 98b2786
Show file tree
Hide file tree
Showing 18 changed files with 69 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ public void Disable()
IsEnabled = false;
}

public IReadOnlyCollection<SubSystemSettingsDeclaration<DistanceMatrixSubSystem>> Declarations { get; } = new SubSystemSettingsDeclaration<DistanceMatrixSubSystem>[]
{
public IReadOnlyCollection<SubSystemSettingsDeclaration<DistanceMatrixSubSystem>> Declarations { get; } =
[
new SubSystemSettingsPropertyBool<DistanceMatrixSubSystem>(
"{=MSJe8ih4yp}Consider Villages",
"{=kvR54SiOFn}Allow villages to be used for built-in distance matrix calculations. May negatively affect performance.",
x => x.ConsiderVillages),
};
x => x.ConsiderVillages)
];
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ internal sealed class HotKeyCategoryContainer : GameKeyContext
public HotKeyCategoryContainer(string categoryId, string categoryName, IEnumerable<HotKeyBase> keys) : base(categoryId, ListCapacity)
{
var keyCategoryName = Module.CurrentModule.GlobalTextManager.AddGameText("str_key_category_name");
keyCategoryName.AddVariationWithId(categoryId, new TextObject(categoryName), new List<GameTextManager.ChoiceTag>());
keyCategoryName.AddVariationWithId(categoryId, new TextObject(categoryName), []);

var keyName = Module.CurrentModule.GlobalTextManager.AddGameText("str_key_name");
var keyDesc = Module.CurrentModule.GlobalTextManager.AddGameText("str_key_description");
foreach (var key in keys)
{
var variationId = $"{categoryId}_{(GameKeyDefinition) key.Id}";
keyName.AddVariationWithId(variationId, new TextObject(key.DisplayName), new List<GameTextManager.ChoiceTag>());
keyDesc.AddVariationWithId(variationId, new TextObject(key.Description), new List<GameTextManager.ChoiceTag>());
keyName.AddVariationWithId(variationId, new TextObject(key.DisplayName), []);
keyDesc.AddVariationWithId(variationId, new TextObject(key.Description), []);
RegisterGameKey(new GameKey(key.Id, key.Uid, categoryId, key.DefaultKey, key.Category));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ namespace Bannerlord.ButterLib.Implementation.HotKeys;

internal sealed class HotKeyManagerImplementation : HotKeyManager
{
internal static readonly List<HotKeyCategoryContainer> GlobalContainerStorage = new();
internal static readonly List<HotKeyBase> GlobalHotKeyStorage = new();
internal static readonly List<HotKeyCategoryContainer> GlobalContainerStorage = [];
internal static readonly List<HotKeyBase> GlobalHotKeyStorage = [];

private int _currentId = 0; // To prevent collision with the game
private readonly string _modName;
private readonly string _categoryName;
private readonly List<HotKeyBase> _instanceHotKeys = new();
private readonly List<HotKeyBase> _instanceHotKeys = [];

internal HotKeyManagerImplementation(string modName, string categoryName = "")
{
Expand Down Expand Up @@ -54,7 +54,7 @@ public override IReadOnlyList<HotKeyBase> Build()
#if v100 || v101 || v102 || v103 || v110 || v111 || v112 || v113 || v114 || v115 || v116
TWHotKeyManager.RegisterInitialContexts(new[] { hotKeyCategoryContainer }, true);
#elif v120 || v121 || v122 || v123 || v124 || v125 || v126 || v127 || v128 || v129 || v1210 || v1211
TWHotKeyManager.RegisterInitialContexts(TWHotKeyManager.GetAllCategories().ToList().Concat(new[] { hotKeyCategoryContainer }), true);
TWHotKeyManager.RegisterInitialContexts(TWHotKeyManager.GetAllCategories().ToList().Concat([hotKeyCategoryContainer]), true);
#else
#error DEFINE
#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,20 @@ public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstructio
{
case "OnGameStart":
miToSearchFor = miMBSubModuleBaseOnGameStartEvent!;
ciToAdd = new CodeInstruction[] { new(opcode: OpCodes.Ldarg_1),
new(opcode: OpCodes.Ldarg_2),
new(opcode: OpCodes.Call, operand: miDelayedOnGameStartEventCaller) };
ciToAdd =
[
new(opcode: OpCodes.Ldarg_1),
new(opcode: OpCodes.Ldarg_2),
new(opcode: OpCodes.Call, operand: miDelayedOnGameStartEventCaller)
];
break;
case "OnGameEnd":
miToSearchFor = miMBSubModuleBaseOnGameEndEvent!;
ciToAdd = new CodeInstruction[] { new(opcode: OpCodes.Ldarg_1),
new(opcode: OpCodes.Call, operand: miDelayedOnGameEndEventCaller) };
ciToAdd =
[
new(opcode: OpCodes.Ldarg_1),
new(opcode: OpCodes.Call, operand: miDelayedOnGameEndEventCaller)
];
break;
default:
_log.LogError("Error while applying Harmony transpiler for {Method} - unexpected target method!", originalMethodName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,11 @@ public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstructio
}
else
{
codes.InsertRange(finallyIndex + 1, new CodeInstruction[] {
codes.InsertRange(finallyIndex + 1,
[
new CodeInstruction(opcode: OpCodes.Ldarg_0),
new CodeInstruction(opcode: OpCodes.Call, operand: miDelayedScreenAsRootEventCaller)
});
]);
codes[finallyIndex + 1].MoveLabelsFrom(codes[finallyIndex + 3]);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@ internal static bool Disable(Harmony harmony)
private delegate bool IsContainerDelegate(Type type);

private static readonly IsContainerDelegate? IsContainer =
AccessTools2.GetDelegate<IsContainerDelegate>("TaleWorlds.SaveSystem.TypeExtensions:IsContainer", new[] { typeof(Type) });
AccessTools2.GetDelegate<IsContainerDelegate>("TaleWorlds.SaveSystem.TypeExtensions:IsContainer", [typeof(Type)]);

private static MethodInfo? TargetTypeMethod(string name) => AccessTools2.Method($"TaleWorlds.SaveSystem.Definition.DefinitionContext:{name}");

private static readonly Patch[] Patches = new Patch[]
{
private static readonly Patch[] Patches =
[
new PrefixPatch(nameof(AddBasicTypeDefinitionPrefix), TargetTypeMethod("AddBasicTypeDefinition")),
new PrefixPatch(nameof(AddClassDefinitionPrefix), TargetTypeMethod("AddClassDefinition")),
new PrefixPatch(nameof(AddContainerDefinitionPrefix), TargetTypeMethod("AddContainerDefinition")),
Expand All @@ -70,8 +70,8 @@ internal static bool Disable(Harmony harmony)
new PrefixPatch(nameof(AddInterfaceDefinitionPrefix), TargetTypeMethod("AddInterfaceDefinition")),
new PrefixPatch(nameof(AddRootClassDefinitionPrefix), TargetTypeMethod("AddRootClassDefinition")),
new PrefixPatch(nameof(AddStructDefinitionPrefix), TargetTypeMethod("AddStructDefinition")),
new ConstructContainerDefinitionPrefixPatch(),
};
new ConstructContainerDefinitionPrefixPatch()
];

// PATCH METHODS

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ internal static bool Disable(Harmony harmony)
}

private static readonly Type? TargetType = AccessTools2.TypeByName("TaleWorlds.SaveSystem.TypeExtensions");
private static readonly Type[] TargetMethodParams = { typeof(Type), typeof(ContainerType).MakeByRefType() };
private static readonly Type[] TargetMethodParams = [typeof(Type), typeof(ContainerType).MakeByRefType()];
private static readonly MethodInfo? TargetMethod = AccessTools2.Method(TargetType!, "IsContainer", TargetMethodParams);
private static readonly MethodInfo? PatchMethod = SymbolExtensions2.GetMethodInfo((Type x, ContainerType y, bool z) => IsContainerPrefix(x, out y, ref z));

Expand Down
2 changes: 1 addition & 1 deletion src/Bannerlord.ButterLib/ButterLibSubModule.Services.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Bannerlord.ButterLib;
public sealed partial class ButterLibSubModule
{
public static bool CanBeConfigured { get; private set; } = true;

Check warning on line 12 in src/Bannerlord.ButterLib/ButterLibSubModule.Services.cs

View workflow job for this annotation

GitHub Actions / DocFX Documentation

Missing XML comment for publicly visible type or member 'ButterLibSubModule.CanBeConfigured'

Check warning on line 12 in src/Bannerlord.ButterLib/ButterLibSubModule.Services.cs

View workflow job for this annotation

GitHub Actions / Test

Missing XML comment for publicly visible type or member 'ButterLibSubModule.CanBeConfigured'
private static List<Action<IServiceCollection>> BeforeInitialization { get; } = new();
private static List<Action<IServiceCollection>> BeforeInitialization { get; } = [];

/// <summary>
/// The only way to inject your stuff before ButterLib will start it's initialization
Expand Down
18 changes: 9 additions & 9 deletions src/Bannerlord.ButterLib/DynamicAPI/DynamicAPIProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@ private record MethodInfoWithAttribute(MethodInfo MethodInfo, CustomAttributeDat

private delegate object DynamicAPIObjectActivator();

private static readonly HashSet<string> PossibleClassNames = new()
{
private static readonly HashSet<string> PossibleClassNames =
[
"Bannerlord.ButterLib.DynamicAPI.DynamicAPIClassAttribute",
"Bannerlord.DynamicAPI.DynamicAPIClassAttribute",
};
private static readonly HashSet<string> PossibleMethodNames = new()
{
"Bannerlord.DynamicAPI.DynamicAPIClassAttribute"
];
private static readonly HashSet<string> PossibleMethodNames =
[
"Bannerlord.ButterLib.DynamicAPI.DynamicAPIMethodAttribute",
"Bannerlord.DynamicAPI.DynamicAPIMethodAttribute",
};
"Bannerlord.DynamicAPI.DynamicAPIMethodAttribute"
];

private static readonly ConcurrentDictionary<string, DynamicAPIObjectActivator?> CachedActivators = new();
internal static Dictionary<string, Type>? APIClasses;
Expand Down Expand Up @@ -104,7 +104,7 @@ internal static void Initialize()
}
catch (Exception)
{
return Enumerable.Empty<TypeWithAttribute?>();
return [];
}
})
.OfType<TypeWithAttribute>()
Expand Down
4 changes: 2 additions & 2 deletions src/Bannerlord.ButterLib/ExceptionHandler/BEWPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ internal record ExceptionIdentifier(Type Type, string? StackTrace, string Messag
public static ExceptionIdentifier FromException(Exception e) => new(e.GetType(), e.StackTrace, e.Message);
}

internal static readonly HashSet<ExceptionIdentifier> SuppressedExceptions = new();
internal static readonly HashSet<ExceptionIdentifier> SuppressedExceptions = [];

private static readonly string[] BEW = { "org.calradia.admiralnelson.betterexceptionwindow" };
private static readonly string[] BEW = ["org.calradia.admiralnelson.betterexceptionwindow"];


private static readonly MethodInfo? ManagedApplicationTickMethod = AccessTools2.Method("TaleWorlds.DotNet.Managed:ApplicationTick");
Expand Down
34 changes: 17 additions & 17 deletions src/Bannerlord.ButterLib/ExceptionHandler/ExceptionReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,35 +53,35 @@ public static void Show(Exception exception)
var harmonyProvider = new HarmonyProvider();
var crashReportRendererUtilities = new CrashReportRendererUtilities();

var crashReport = CrashReportInfo.Create(exception, metadata, filter, helper, helper, helper, harmonyProvider);
var crashReportModel = CrashReportInfo.ToModel(crashReport, helper, helper, helper, helper, helper, helper);
var logSources = GetLogSources().ToArray();
try
{
CrashReportImGui.ShowAndWait(crashReportModel, logSources, crashReportRendererUtilities);
}
catch (Exception ex)
{
var crashReport = CrashReportInfo.Create(exception, metadata, filter, helper, helper, helper, harmonyProvider);
var crashReportModel = CrashReportInfo.ToModel(crashReport, helper, helper, helper, helper, helper, helper);
var logSources = GetLogSources().ToArray();
try
{
CrashReportImGui.ShowAndWait(crashReportModel, logSources, crashReportRendererUtilities);
}
catch (Exception ex)
{
try
{
#if NET472 || (NET6_0 && WINDOWS)

var forms = new CrashReportWinForms(crashReportModel, logSources, crashReportRendererUtilities);
forms.ShowDialog();
var forms = new CrashReportWinForms(crashReportModel, logSources, crashReportRendererUtilities);
forms.ShowDialog();
#endif
}
catch (Exception ex2)
{
throw new AggregateException(ex, ex2);
}
catch (Exception ex2)
{
throw new AggregateException(ex, ex2);
}
}
}
}

private static IEnumerable<LogSource> GetLogSources()
{
var now = DateTimeOffset.Now;

foreach (var logSource in ButterLibSubModule.ServiceProvider?.GetService<IEnumerable<ILogSource>>() ?? Enumerable.Empty<ILogSource>())
foreach (var logSource in ButterLibSubModule.ServiceProvider?.GetService<IEnumerable<ILogSource>>() ?? [])
{
switch (logSource)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Bannerlord.ButterLib/ImplementationLoaderSubModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ private static IEnumerable<MBSubModuleBase> LoadAllImplementations(ILogger? logg
catch (Exception e) when (e is ReflectionTypeLoadException)
{
logger?.LogError(e, "Implementation {Name} is not compatible with the current game!", Path.GetFileName(a.Location));
return Enumerable.Empty<Type>();
return [];
}

}).ToList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ public static class LoggerExtensions
private class LogValuesFormatter
{
private const string NullValue = "(null)";
private static readonly object[] EmptyArray = Array.Empty<object>();
private static readonly object[] EmptyArray = [];
private readonly string _format;
private readonly List<string> _valueNames = new();
private readonly List<string> _valueNames = [];

public LogValuesFormatter(string format)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Bannerlord.ButterLib/Logger/ReverseTextReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public ReverseTextReader(Stream stream, Encoding encoding)
throw new InvalidOperationException("The specified stream needs to support reading to be read backwards.");
// Set the current position to the end of the file
_stream.Position = _stream.Length;
_leftoverBuffer = Array.Empty<byte>();
_leftoverBuffer = [];
}

#endregion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class TaleWorldsContractResolverBase : DefaultContractResolver
{
protected delegate bool IsContainerDelegate(Type type);
protected static readonly IsContainerDelegate? _isContainerDelegate =
AccessTools2.GetDelegate<IsContainerDelegate>("TaleWorlds.SaveSystem.TypeExtensions:IsContainer", new[] { typeof(Type) });
AccessTools2.GetDelegate<IsContainerDelegate>("TaleWorlds.SaveSystem.TypeExtensions:IsContainer", [typeof(Type)]);

protected static bool IsContainerFallback(Type type)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace Bannerlord.ButterLib.SubModuleWrappers2;
/// </summary>
public class MBSubModuleBaseListWrapper : MBSubModuleBase
{
protected readonly List<MBSubModuleBaseWrapper> _subModules = new();
protected readonly List<MBSubModuleBaseWrapper> _subModules = [];
public IReadOnlyList<MBSubModuleBaseWrapper> SubModules => _subModules.AsReadOnly();

public new virtual void OnSubModuleLoad()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ private static bool MockedGetConfigName(ref string __result)
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool MockedGetModuleNames(ref string[] __result)
{
__result = Array.Empty<string>();
__result = [];
return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ IEnumerable<Type> Filter(IEnumerable<Type> types)
}
catch (Exception)
{
return Enumerable.Empty<Type>();
return [];
}
})
.ToList();
Expand Down Expand Up @@ -158,7 +158,7 @@ IEnumerable<Type> Filter(Type[] types)
}
catch (Exception)
{
return Enumerable.Empty<Type>();
return [];
}
})
.ToList();
Expand Down

0 comments on commit 98b2786

Please sign in to comment.