From ad612cd6751f4a55b795c96cadd5ef9157456bab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BAben=20Garcia?= Date: Wed, 24 Apr 2024 02:31:51 +0100 Subject: [PATCH 1/3] Enforce brackets --- .../Items/ItemDirectoryExtensions.cs | 2 + .../Transforms/QuaternionMathExtensions.cs | 14 +- .../Vehicles/VehicleDirectoryExtensions.cs | 2 + .../Persistence/SerializeIgnoreAttribute.cs | 23 +- .../Helpers/AssemblyExtensions.cs | 8 +- .../Helpers/ReflectionExtensions.cs | 14 +- .../Commands/CommandContextBuilder.cs | 4 + .../Commands/CommandParameters.cs | 37 +- .../YamlConfigurationExtensions.cs | 14 +- .../OpenMod.Core/Cooldowns/CooldownSpan.cs | 5 +- framework/OpenMod.Core/Eventing/Event.cs | 14 +- framework/OpenMod.Core/Eventing/EventBus.cs | 105 +- .../OpenMod.Core/Helpers/ArgumentsParser.cs | 6 + .../Helpers/AssemblyEqualityComparer.cs | 2 +- .../OpenMod.Core/Helpers/ProcessHelper.cs | 5 +- .../OpenMod.Core/Helpers/StringHelper.cs | 11 +- .../Permissions/DefaultPermissionStore.cs | 3 + .../Permissions/UserDataPermissionActor.cs | 5 +- .../OpenMod.Core/Persistence/YamlDataStore.cs | 3 + .../Persistence/YamlDataStoreOptions.cs | 77 +- .../Persistence/YamlVector3TypeConverter.cs | 108 +- .../OpenMod.Core/Plugins/PluginActivator.cs | 9 +- .../Plugins/PluginAssemblyStore.cs | 36 +- .../OpenMod.Core/Users/OfflineUserProvider.cs | 3 +- .../OpenMod.NuGet/NuGetPackageManager.cs | 4 + framework/OpenMod.Runtime/Runtime.cs | 17 +- .../UnturnedBroadcastCommenceShutdownPatch.cs | 6 +- .../System.Drawing/Color.cs | 1883 +++++++++-------- .../System.Drawing/ColorConverter.cs | 507 ++--- .../System.Drawing/ColorTranslator.cs | 335 +-- .../System.Drawing/KnownColors.cs | 861 ++++---- .../Building/UnturnedBuildableOwnership.cs | 19 +- .../ConfigurationConfigurator.cs | 10 +- .../Effects/UnturnedUIEffectKey.cs | 58 +- .../Events/UnturnedEventsActivator.cs | 10 +- .../Items/UnturnedInventoryItem.cs | 21 +- .../OpenMod.Unturned/Items/UnturnedItem.cs | 16 +- .../Items/UnturnedItemSpawner.cs | 18 + .../Level/Events/LevelEventsListener.cs | 18 +- .../Events/UnturnedBattlEyeKickedEvent.cs | 15 +- .../Events/UnturnedBattlEyeListener.cs | 36 +- .../Players/Chat/Events/ChatEventsListener.cs | 5 +- .../Events/PlayerEquipmentEventsListener.cs | 11 +- .../Events/UnturnedPlayerPunchEvent.cs | 5 +- .../UnturnedPlayerGroupIdChangedEvent.cs | 21 +- .../UnturnedPlayerGroupOrRankChangedEvent.cs | 29 +- .../Players/UnturnedPlayer.cs | 79 +- .../RocketCooldownPermissionCheckProvider.cs | 4 + .../RocketMod/Rcon/RocketModRconClient.cs | 12 +- .../Users/UnturnedUserProvider.cs | 26 +- .../Vehicles/UnturnedVehicleSpawner.cs | 10 +- 51 files changed, 2503 insertions(+), 2043 deletions(-) diff --git a/extensions/OpenMod.Extensions.Games.Abstractions/Items/ItemDirectoryExtensions.cs b/extensions/OpenMod.Extensions.Games.Abstractions/Items/ItemDirectoryExtensions.cs index 493ededb1..ccde29353 100644 --- a/extensions/OpenMod.Extensions.Games.Abstractions/Items/ItemDirectoryExtensions.cs +++ b/extensions/OpenMod.Extensions.Games.Abstractions/Items/ItemDirectoryExtensions.cs @@ -30,8 +30,10 @@ public static class ItemDirectoryExtensions public static async Task FindByNameAsync(this IItemDirectory directory, string itemName, bool exact = true) { if (exact) + { return (await directory.GetItemAssetsAsync()).FirstOrDefault(d => d.ItemName.Equals(itemName, StringComparison.OrdinalIgnoreCase)); + } return (await directory.GetItemAssetsAsync()) .Where(x => x.ItemName.IndexOf(itemName, StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/extensions/OpenMod.Extensions.Games.Abstractions/Transforms/QuaternionMathExtensions.cs b/extensions/OpenMod.Extensions.Games.Abstractions/Transforms/QuaternionMathExtensions.cs index 61fb62af9..668ca8085 100644 --- a/extensions/OpenMod.Extensions.Games.Abstractions/Transforms/QuaternionMathExtensions.cs +++ b/extensions/OpenMod.Extensions.Games.Abstractions/Transforms/QuaternionMathExtensions.cs @@ -11,22 +11,34 @@ public static class QuaternionMathExtensions private static void CleanUpAngles(this ref Vector3 vector) { while (vector.X >= 360) + { vector.X -= 360; + } while (vector.X < 0) + { vector.X += 360; + } while (vector.Y >= 360) + { vector.Y -= 360; + } while (vector.Y < 0) + { vector.Y += 360; + } while (vector.Z >= 360) + { vector.Z -= 360; + } while (vector.Z < 0) + { vector.Z += 360; + } } /// @@ -88,7 +100,7 @@ public static Quaternion ToQuaternion(this Vector3 eulerAngles) var cosYOver2 = (float)Math.Cos(yOver2); var sinZOver2 = (float)Math.Sin(zOver2); var cosZOver2 = (float)Math.Cos(zOver2); - + return new Quaternion() { X = cosYOver2 * sinXOver2 * cosZOver2 + sinYOver2 * cosXOver2 * sinZOver2, diff --git a/extensions/OpenMod.Extensions.Games.Abstractions/Vehicles/VehicleDirectoryExtensions.cs b/extensions/OpenMod.Extensions.Games.Abstractions/Vehicles/VehicleDirectoryExtensions.cs index 4431be510..52a42d863 100644 --- a/extensions/OpenMod.Extensions.Games.Abstractions/Vehicles/VehicleDirectoryExtensions.cs +++ b/extensions/OpenMod.Extensions.Games.Abstractions/Vehicles/VehicleDirectoryExtensions.cs @@ -30,8 +30,10 @@ public static class VehicleDirectoryExtensions public static async Task FindByNameAsync(this IVehicleDirectory directory, string vehicleName, bool exact = true) { if (exact) + { return (await directory.GetVehicleAssetsAsync()).FirstOrDefault(d => d.VehicleName.Equals(vehicleName, StringComparison.OrdinalIgnoreCase)); + } return (await directory.GetVehicleAssetsAsync()) .Where(x => x.VehicleName.IndexOf(vehicleName, StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/framework/OpenMod.API/Persistence/SerializeIgnoreAttribute.cs b/framework/OpenMod.API/Persistence/SerializeIgnoreAttribute.cs index 580b12976..f5f598d33 100644 --- a/framework/OpenMod.API/Persistence/SerializeIgnoreAttribute.cs +++ b/framework/OpenMod.API/Persistence/SerializeIgnoreAttribute.cs @@ -1,15 +1,16 @@ using System; -namespace OpenMod.API.Persistence; - -/// -/// Attribute to mark any property or field to be ignored -/// This make API independent of any type such as json/xml/yaml -/// -//todo add this to docs -//todo propagate this to all serializers, note this will be implemented when change to VYaml -[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | - AttributeTargets.ReturnValue)] -public class SerializeIgnoreAttribute : Attribute +namespace OpenMod.API.Persistence { + /// + /// Attribute to mark any property or field to be ignored + /// This make API independent of any type such as json/xml/yaml + /// + //todo add this to docs + //todo propagate this to all serializers, note this will be implemented when change to VYaml + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | + AttributeTargets.ReturnValue)] + public class SerializeIgnoreAttribute : Attribute + { + } } \ No newline at end of file diff --git a/framework/OpenMod.Common/Helpers/AssemblyExtensions.cs b/framework/OpenMod.Common/Helpers/AssemblyExtensions.cs index 8b174bee2..47a42899e 100644 --- a/framework/OpenMod.Common/Helpers/AssemblyExtensions.cs +++ b/framework/OpenMod.Common/Helpers/AssemblyExtensions.cs @@ -67,16 +67,22 @@ public static IEnumerable GetMissingDependencies(this ReflectionTy //TypeLoadException is just matching with MissingFileAssemblyVersionRegex var match = s_MissingFileAssemblyVersionRegex.Match(loaderException.Message); if (!match.Success) + { match = s_TypeLoadAssemblyVersionRegex.Match(loaderException.Message); + } if (!match.Success) + { continue; - + } + var assemblyName = match.Groups["assembly"].Value; var version = Version.Parse(match.Groups["version"].Value); if (missingAssemblies.TryGetValue(assemblyName, out var currentVersion) && currentVersion >= version) + { continue; + } missingAssemblies[assemblyName] = version; } diff --git a/framework/OpenMod.Common/Helpers/ReflectionExtensions.cs b/framework/OpenMod.Common/Helpers/ReflectionExtensions.cs index 2d6dc7bbf..172aa1af5 100644 --- a/framework/OpenMod.Common/Helpers/ReflectionExtensions.cs +++ b/framework/OpenMod.Common/Helpers/ReflectionExtensions.cs @@ -25,7 +25,9 @@ public static class ReflectionExtensions var frame = st.GetFrame(i); var frameMethod = frame.GetMethod(); if (frameMethod == null) + { continue; + } // Hot fix for async Task methods: // If current frame method is called "MoveNext" and parent frame is from "AsyncMethodBuilderCore" type @@ -56,10 +58,14 @@ public static class ReflectionExtensions } if (skipList.Any(c => c == frameMethod?.DeclaringType)) + { continue; + } if (skipMethods?.Any(c => c == frameMethod) ?? false) + { continue; + } frameTarget = frame; break; @@ -77,7 +83,9 @@ public static class ReflectionExtensions { var frame = st.GetFrame(i); if (skipAssemblies.Any(c => Equals(c, frame.GetMethod()?.DeclaringType?.Assembly))) + { continue; + } frameTarget = frame; } @@ -227,7 +235,11 @@ public static bool HasConversionOperator(this Type from, Type to) throw new ArgumentNullException(nameof(to)); } - UnaryExpression BodyFunction(Expression body) => Expression.Convert(body, to); + UnaryExpression BodyFunction(Expression body) + { + return Expression.Convert(body, to); + } + var inp = Expression.Parameter(from, "inp"); try { diff --git a/framework/OpenMod.Core/Commands/CommandContextBuilder.cs b/framework/OpenMod.Core/Commands/CommandContextBuilder.cs index 173c2e14e..b9cf44a2f 100644 --- a/framework/OpenMod.Core/Commands/CommandContextBuilder.cs +++ b/framework/OpenMod.Core/Commands/CommandContextBuilder.cs @@ -105,11 +105,15 @@ public ICommandContext CreateContext(ICommandActor actor, string[] args, string foreach (var registration in baseQuery) { if (registration.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) + { return registration; + } if (registration.Aliases != null && registration.Aliases.Any(e => e.Equals(name, StringComparison.OrdinalIgnoreCase))) + { aliasMatch = registration; + } } return aliasMatch; diff --git a/framework/OpenMod.Core/Commands/CommandParameters.cs b/framework/OpenMod.Core/Commands/CommandParameters.cs index 0b8473709..a86e3fab4 100644 --- a/framework/OpenMod.Core/Commands/CommandParameters.cs +++ b/framework/OpenMod.Core/Commands/CommandParameters.cs @@ -29,13 +29,22 @@ public CommandParameters(ICommandContext commandContext, ICollection arg protected ICollection RawParameters { get; } /// - public string this[int index] => ToArray()[index]; + public string this[int index] + { + get => ToArray()[index]; + } /// - public int Length => ToArray().Length; + public int Length + { + get => ToArray().Length; + } /// - public async Task GetAsync(int index) => (T)await GetAsync(index, typeof(T)); + public async Task GetAsync(int index) + { + return (T)await GetAsync(index, typeof(T)); + } /// public async Task GetAsync(int index, Type type) @@ -156,21 +165,33 @@ public bool TryGet(int index, Type type, out object? value) } /// - public string[] ToArray() => RawParameters.ToArray(); + public string[] ToArray() + { + return RawParameters.ToArray(); + } /// - public List ToList() => ToArray().ToList(); + public List ToList() + { + return ToArray().ToList(); + } /// - public IEnumerator GetEnumerator() => ToList().GetEnumerator(); + public IEnumerator GetEnumerator() + { + return ToList().GetEnumerator(); + } /// - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } /// public int Count { - get { return RawParameters.Count; } + get => RawParameters.Count; } } } \ No newline at end of file diff --git a/framework/OpenMod.Core/Configuration/YamlConfigurationExtensions.cs b/framework/OpenMod.Core/Configuration/YamlConfigurationExtensions.cs index 68dc96d31..92d980c94 100644 --- a/framework/OpenMod.Core/Configuration/YamlConfigurationExtensions.cs +++ b/framework/OpenMod.Core/Configuration/YamlConfigurationExtensions.cs @@ -20,7 +20,7 @@ public static class YamlConfigurationExtensions /// Ex: supports variables. /// /// The to add to. - /// Path relative to the base path stored in + /// Path relative to the base path stored in /// of . /// The . public static IConfigurationBuilder AddYamlFileEx(this IConfigurationBuilder builder, string path) @@ -33,7 +33,7 @@ public static IConfigurationBuilder AddYamlFileEx(this IConfigurationBuilder bui /// Ex: supports variables. /// /// The to add to. - /// Path relative to the base path stored in + /// Path relative to the base path stored in /// of . /// Whether the file is optional. /// The . @@ -47,7 +47,7 @@ public static IConfigurationBuilder AddYamlFileEx(this IConfigurationBuilder bui /// Ex: supports variables. /// /// The to add to. - /// Path relative to the base path stored in + /// Path relative to the base path stored in /// of . /// Whether the file is optional. /// Whether the configuration should be reloaded if the file changes. @@ -62,7 +62,7 @@ public static IConfigurationBuilder AddYamlFileEx(this IConfigurationBuilder bui /// Ex: supports variables. /// /// The to add to. - /// Path relative to the base path stored in + /// Path relative to the base path stored in /// of . /// Variables to replace. /// Whether the file is optional. @@ -79,7 +79,7 @@ public static IConfigurationBuilder AddYamlFileEx(this IConfigurationBuilder bui /// /// The to add to. /// The to use to access the file. - /// Path relative to the base path stored in + /// Path relative to the base path stored in /// of . /// Variables to replace. /// Whether the file is optional. @@ -119,6 +119,8 @@ public static IConfigurationBuilder AddYamlFileEx(this IConfigurationBuilder bui /// Configures the source. /// The . public static IConfigurationBuilder AddYamlFileEx(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); + { + return builder.Add(configureSource); + } } } \ No newline at end of file diff --git a/framework/OpenMod.Core/Cooldowns/CooldownSpan.cs b/framework/OpenMod.Core/Cooldowns/CooldownSpan.cs index 139e51c01..d565c6e06 100644 --- a/framework/OpenMod.Core/Cooldowns/CooldownSpan.cs +++ b/framework/OpenMod.Core/Cooldowns/CooldownSpan.cs @@ -10,6 +10,9 @@ public sealed class CooldownSpan public string? Cooldown { get; set; } - public TimeSpan ToTimeSpan() => TimeSpanHelper.Parse(Cooldown!); + public TimeSpan ToTimeSpan() + { + return TimeSpanHelper.Parse(Cooldown!); + } } } \ No newline at end of file diff --git a/framework/OpenMod.Core/Eventing/Event.cs b/framework/OpenMod.Core/Eventing/Event.cs index e16194b61..33ea8aacf 100644 --- a/framework/OpenMod.Core/Eventing/Event.cs +++ b/framework/OpenMod.Core/Eventing/Event.cs @@ -9,12 +9,16 @@ public abstract class Event : EventBase { get { - Dictionary args = new Dictionary(); - PropertyInfo[] props = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); - foreach (PropertyInfo prop in props) + var args = new Dictionary(); + var props = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); + // ReSharper disable once LoopCanBeConvertedToQuery + foreach (var prop in props) { - MethodInfo getter = prop.GetGetMethod(false); - if (getter == null) continue; + var getter = prop.GetGetMethod(false); + if (getter == null) + { + continue; + } args.Add(prop.Name.ToLower(), this); } diff --git a/framework/OpenMod.Core/Eventing/EventBus.cs b/framework/OpenMod.Core/Eventing/EventBus.cs index b2666257a..1a2e6349e 100644 --- a/framework/OpenMod.Core/Eventing/EventBus.cs +++ b/framework/OpenMod.Core/Eventing/EventBus.cs @@ -69,7 +69,10 @@ private IDisposable SubscribeInternal(EventSubscription subscription) public virtual IDisposable Subscribe(IOpenModComponent component, string eventName, EventCallback callback) { - if (callback == null) throw new ArgumentNullException(nameof(callback)); + if (callback == null) + { + throw new ArgumentNullException(nameof(callback)); + } var attribute = GetEventListenerAttribute(callback.Method); @@ -79,13 +82,25 @@ public virtual IDisposable Subscribe(IOpenModComponent component, string eventNa public virtual IDisposable Subscribe(IOpenModComponent component, string eventName, EventCallback callback, IEventListenerOptions options) { - if (component == null) throw new ArgumentNullException(nameof(component)); + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } - if (callback == null) throw new ArgumentNullException(nameof(callback)); + if (callback == null) + { + throw new ArgumentNullException(nameof(callback)); + } - if (string.IsNullOrEmpty(eventName)) throw new ArgumentException(eventName); + if (string.IsNullOrEmpty(eventName)) + { + throw new ArgumentException(eventName); + } - if (options == null) throw new ArgumentNullException(nameof(options)); + if (options == null) + { + throw new ArgumentNullException(nameof(options)); + } if (!component.IsComponentAlive) { @@ -103,7 +118,10 @@ public virtual IDisposable Subscribe(IOpenModComponent component, string eventNa public virtual IDisposable Subscribe(IOpenModComponent component, EventCallback callback) where TEvent : IEvent { - if (callback == null) throw new ArgumentNullException(nameof(callback)); + if (callback == null) + { + throw new ArgumentNullException(nameof(callback)); + } var attribute = GetEventListenerAttribute(callback.Method); @@ -113,11 +131,20 @@ public virtual IDisposable Subscribe(IOpenModComponent component, EventC public virtual IDisposable Subscribe(IOpenModComponent component, EventCallback callback, IEventListenerOptions options) where TEvent : IEvent { - if (component == null) throw new ArgumentNullException(nameof(component)); + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } - if (callback == null) throw new ArgumentNullException(nameof(callback)); + if (callback == null) + { + throw new ArgumentNullException(nameof(callback)); + } - if (options == null) throw new ArgumentNullException(nameof(options)); + if (options == null) + { + throw new ArgumentNullException(nameof(options)); + } if (!component.IsComponentAlive) { @@ -135,7 +162,10 @@ public virtual IDisposable Subscribe(IOpenModComponent component, EventC public virtual IDisposable Subscribe(IOpenModComponent component, Type eventType, EventCallback callback) { - if (callback == null) throw new ArgumentNullException(nameof(callback)); + if (callback == null) + { + throw new ArgumentNullException(nameof(callback)); + } var attribute = GetEventListenerAttribute(callback.Method); @@ -145,11 +175,20 @@ public virtual IDisposable Subscribe(IOpenModComponent component, Type eventType public virtual IDisposable Subscribe(IOpenModComponent component, Type eventType, EventCallback callback, IEventListenerOptions options) { - if (component == null) throw new ArgumentNullException(nameof(component)); + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } - if (callback == null) throw new ArgumentNullException(nameof(callback)); + if (callback == null) + { + throw new ArgumentNullException(nameof(callback)); + } - if (options == null) throw new ArgumentNullException(nameof(options)); + if (options == null) + { + throw new ArgumentNullException(nameof(options)); + } if (!component.IsComponentAlive) { @@ -166,9 +205,15 @@ public virtual IDisposable Subscribe(IOpenModComponent component, Type eventType public virtual IDisposable Subscribe(IOpenModComponent component, Assembly assembly) { - if (component == null) throw new ArgumentNullException(nameof(component)); + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } - if (assembly == null) throw new ArgumentNullException(nameof(assembly)); + if (assembly == null) + { + throw new ArgumentNullException(nameof(assembly)); + } if (!component.IsComponentAlive) { @@ -240,7 +285,10 @@ public virtual IDisposable Subscribe(IOpenModComponent component, Assembly assem public virtual void Unsubscribe(IOpenModComponent component) { - if (component == null) throw new ArgumentNullException(nameof(component)); + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } lock (m_Lock) { @@ -250,7 +298,10 @@ public virtual void Unsubscribe(IOpenModComponent component) public virtual void Unsubscribe(IOpenModComponent component, string eventName) { - if (component == null) throw new ArgumentNullException(nameof(component)); + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } lock (m_Lock) { @@ -262,7 +313,10 @@ public virtual void Unsubscribe(IOpenModComponent component, string eventName) public virtual void Unsubscribe(IOpenModComponent component) where TEvent : IEvent { - if (component == null) throw new ArgumentNullException(nameof(component)); + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } lock (m_Lock) { @@ -275,7 +329,10 @@ public virtual void Unsubscribe(IOpenModComponent component, string eventName) public virtual void Unsubscribe(IOpenModComponent component, Type eventType) { - if (component == null) throw new ArgumentNullException(nameof(component)); + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } lock (m_Lock) { @@ -289,9 +346,15 @@ public virtual void Unsubscribe(IOpenModComponent component, Type eventType) public virtual async Task EmitAsync(IOpenModComponent component, object? sender, IEvent @event, EventExecutedCallback? callback = null) { - if (component == null) throw new ArgumentNullException(nameof(component)); + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } - if (@event == null) throw new ArgumentNullException(nameof(@event)); + if (@event == null) + { + throw new ArgumentNullException(nameof(@event)); + } if (!component.IsComponentAlive) { diff --git a/framework/OpenMod.Core/Helpers/ArgumentsParser.cs b/framework/OpenMod.Core/Helpers/ArgumentsParser.cs index c0b616653..ebfd1a523 100644 --- a/framework/OpenMod.Core/Helpers/ArgumentsParser.cs +++ b/framework/OpenMod.Core/Helpers/ArgumentsParser.cs @@ -81,10 +81,14 @@ public static string[] ParseArguments(string line) } if (inQuote || inApostrophes) //command: 'command "player ' -> args: 'command', 'player' + { currentArg = TrimEnd(currentArg); + } if (currentArg.Length != 0) + { args.Add(currentArg.ToString()); + } return args.ToArray(); } @@ -97,7 +101,9 @@ private static StringBuilder TrimEnd(StringBuilder currentArg) if (!IsSpace(currentArg[i])) { if (lenght != 0) + { currentArg.Remove(i + 1, lenght); + } break; } diff --git a/framework/OpenMod.Core/Helpers/AssemblyEqualityComparer.cs b/framework/OpenMod.Core/Helpers/AssemblyEqualityComparer.cs index 8d80e58ad..95c089c1c 100644 --- a/framework/OpenMod.Core/Helpers/AssemblyEqualityComparer.cs +++ b/framework/OpenMod.Core/Helpers/AssemblyEqualityComparer.cs @@ -5,7 +5,7 @@ namespace OpenMod.Core.Helpers { public class AssemblyEqualityComparer : IEqualityComparer { - public bool Equals(Assembly x, Assembly y) + public bool Equals(Assembly? x, Assembly? y) { return string.Equals(x?.FullName, y?.FullName); } diff --git a/framework/OpenMod.Core/Helpers/ProcessHelper.cs b/framework/OpenMod.Core/Helpers/ProcessHelper.cs index 3f57c5ba4..bede3c2bd 100644 --- a/framework/OpenMod.Core/Helpers/ProcessHelper.cs +++ b/framework/OpenMod.Core/Helpers/ProcessHelper.cs @@ -9,7 +9,10 @@ public static class ProcessHelper public static Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default) { - if (process.HasExited) return Task.CompletedTask; + if (process.HasExited) + { + return Task.CompletedTask; + } var tcs = new TaskCompletionSource(); process.EnableRaisingEvents = true; diff --git a/framework/OpenMod.Core/Helpers/StringHelper.cs b/framework/OpenMod.Core/Helpers/StringHelper.cs index 0741ec880..170d56073 100644 --- a/framework/OpenMod.Core/Helpers/StringHelper.cs +++ b/framework/OpenMod.Core/Helpers/StringHelper.cs @@ -44,8 +44,15 @@ public static int LevenshteinDistance(string a, string b) var lengthB = b.Length; var distances = new int[lengthA + 1, lengthB + 1]; - for (var i = 0; i <= lengthA; distances[i, 0] = i++) ; - for (var j = 0; j <= lengthB; distances[0, j] = j++) ; + for (var i = 0; i <= lengthA; i++) + { + distances[i, 0] = i; + } + + for (var j = 0; j <= lengthB; j++) + { + distances[0, j] = j; + } for (var i = 1; i <= lengthA; i++) for (var j = 1; j <= lengthB; j++) diff --git a/framework/OpenMod.Core/Permissions/DefaultPermissionStore.cs b/framework/OpenMod.Core/Permissions/DefaultPermissionStore.cs index 131d56ab1..66ec29a4c 100644 --- a/framework/OpenMod.Core/Permissions/DefaultPermissionStore.cs +++ b/framework/OpenMod.Core/Permissions/DefaultPermissionStore.cs @@ -46,7 +46,9 @@ protected virtual async Task> GetGrantDenyPermission var trimmedPermission = permission.TrimStart('!'); if (grantedPerms.Contains(trimmedPermission) || deniedPerms.Contains(trimmedPermission)) //if already added or if is denied by priority + { continue; + } if (isDeny) { @@ -61,6 +63,7 @@ protected virtual async Task> GetGrantDenyPermission return isGrant ? grantedPerms : deniedPerms; } + // ReSharper disable once MemberCanBePrivate.Global protected async Task> GetPermissionsAsync(IPermissionActor actor, bool inherit = true) //order by descending priority { var permissions = new HashSet(StringComparer.InvariantCultureIgnoreCase); diff --git a/framework/OpenMod.Core/Permissions/UserDataPermissionActor.cs b/framework/OpenMod.Core/Permissions/UserDataPermissionActor.cs index a6c908c76..31164cd92 100644 --- a/framework/OpenMod.Core/Permissions/UserDataPermissionActor.cs +++ b/framework/OpenMod.Core/Permissions/UserDataPermissionActor.cs @@ -26,6 +26,9 @@ public UserDataPermissionActor(UserData userData) public string FullActorName { get; } - public static implicit operator UserDataPermissionActor(UserData d) => new(d); + public static implicit operator UserDataPermissionActor(UserData d) + { + return new UserDataPermissionActor(d); + } } } \ No newline at end of file diff --git a/framework/OpenMod.Core/Persistence/YamlDataStore.cs b/framework/OpenMod.Core/Persistence/YamlDataStore.cs index da1a9fbf0..0ebafd921 100644 --- a/framework/OpenMod.Core/Persistence/YamlDataStore.cs +++ b/framework/OpenMod.Core/Persistence/YamlDataStore.cs @@ -383,7 +383,9 @@ private void RegisterKnownKey(string key) m_KnownKeys.Add(key); if (!m_LogOnChange || m_WatchedFiles.Contains(key) || m_Runtime == null) + { return; + } m_WatchedFiles.Add(key); AddChangeWatcher(key, m_Runtime!, () => @@ -467,6 +469,7 @@ public RegisteredChangeListener(IOpenModComponent component, string key, Action //Note we could try use AttributeOverride, but they are processed after YamlIgnoreAttribute //So if we add YamlIgnoreAttribute they will be ignored + // ReSharper disable once MemberCanBePrivate.Global public class SerializableIgnoreInspector : TypeInspectorSkeleton { private readonly ITypeInspector m_InnerTypeDescriptor; diff --git a/framework/OpenMod.Core/Persistence/YamlDataStoreOptions.cs b/framework/OpenMod.Core/Persistence/YamlDataStoreOptions.cs index 6938d1776..0efbaa54f 100644 --- a/framework/OpenMod.Core/Persistence/YamlDataStoreOptions.cs +++ b/framework/OpenMod.Core/Persistence/YamlDataStoreOptions.cs @@ -1,57 +1,58 @@ using System.Collections.Generic; using System.Linq; +using JetBrains.Annotations; using YamlDotNet.Serialization; -namespace OpenMod.Core.Persistence; - -public class YamlDataStoreOptions +namespace OpenMod.Core.Persistence { - public IReadOnlyList Converters + public class YamlDataStoreOptions { - get + // ReSharper disable once ReturnTypeCanBeEnumerable.Global + public IReadOnlyList Converters { - return m_Converters.AsReadOnly(); + get => m_Converters.AsReadOnly(); } - } - private readonly List m_Converters; + private readonly List m_Converters; - public YamlDataStoreOptions() - { - m_Converters = new List(); - } - - /// - /// Adds the specified to the converters list. - /// - /// - /// if the converter is added to converters list; if the converter is already present. - public bool TryAddConverter() where T : class, IYamlTypeConverter, new() - { - if (m_Converters.Any(c => c.GetType() == typeof(T))) + public YamlDataStoreOptions() { - return false; + m_Converters = new List(); } - m_Converters.Add(new T()); - return true; - } + /// + /// Adds the specified to the converters list. + /// + /// + /// if the converter is added to converters list; if the converter is already present. + public bool TryAddConverter() where T : class, IYamlTypeConverter, new() + { + if (m_Converters.Any(c => c.GetType() == typeof(T))) + { + return false; + } - /// - /// Removes the specified from the converters list. - /// - /// - /// if the converter is successfully found and removed; otherwise, . - public bool TryRemoveConverter() where T : class, IYamlTypeConverter, new() - { - var indexOfConverter = m_Converters.FindIndex(c => c.GetType() == typeof(T)); + m_Converters.Add(new T()); + return true; + } - if (indexOfConverter == -1) + /// + /// Removes the specified from the converters list. + /// + /// + /// if the converter is successfully found and removed; otherwise, . + [UsedImplicitly] + public bool TryRemoveConverter() where T : class, IYamlTypeConverter, new() { - return false; - } + var indexOfConverter = m_Converters.FindIndex(c => c.GetType() == typeof(T)); + + if (indexOfConverter == -1) + { + return false; + } - m_Converters.RemoveAt(indexOfConverter); - return true; + m_Converters.RemoveAt(indexOfConverter); + return true; + } } } diff --git a/framework/OpenMod.Core/Persistence/YamlVector3TypeConverter.cs b/framework/OpenMod.Core/Persistence/YamlVector3TypeConverter.cs index 799f97dac..88302aa5d 100644 --- a/framework/OpenMod.Core/Persistence/YamlVector3TypeConverter.cs +++ b/framework/OpenMod.Core/Persistence/YamlVector3TypeConverter.cs @@ -5,80 +5,82 @@ using YamlDotNet.Core.Events; using YamlDotNet.Serialization; -namespace OpenMod.Core.Persistence; - -[OpenModInternal] -public class YamlVector3TypeConverter : IYamlTypeConverter +namespace OpenMod.Core.Persistence { - private const string c_YamlKeyOfX = "x"; - - private const string c_YamlKeyOfY = "y"; + [OpenModInternal] + public class YamlVector3TypeConverter : IYamlTypeConverter + { + private const string c_YamlKeyOfX = "x"; - private const string c_YamlKeyOfZ = "z"; + private const string c_YamlKeyOfY = "y"; - public bool Accepts(Type type) - { - return type == typeof(Vector3); - } + private const string c_YamlKeyOfZ = "z"; - public object? ReadYaml(IParser parser, Type type) - { - static float ParseNumber(Scalar scalar) + public bool Accepts(Type type) { - return float.Parse(scalar.Value, YamlFormatter.Default.NumberFormat); + return type == typeof(Vector3); } - parser.Consume(); - - float x = 0, y = 0, z = 0; - - while (!parser.TryConsume(out _)) + public object ReadYaml(IParser parser, Type type) { - var key = parser.Consume(); - var value = parser.Consume(); + parser.Consume(); + + float x = 0, y = 0, z = 0; - switch (key.Value) + while (!parser.TryConsume(out _)) { - case c_YamlKeyOfX: - x = ParseNumber(value); - break; - case c_YamlKeyOfY: - y = ParseNumber(value); - break; - case c_YamlKeyOfZ: - z = ParseNumber(value); - break; + var key = parser.Consume(); + var value = parser.Consume(); + + switch (key.Value) + { + case c_YamlKeyOfX: + x = ParseNumber(value); + break; + case c_YamlKeyOfY: + y = ParseNumber(value); + break; + case c_YamlKeyOfZ: + z = ParseNumber(value); + break; + } } - } - return new Vector3(x, y, z); - } + return new Vector3(x, y, z); - public void WriteYaml(IEmitter emitter, object? value, Type type) - { - static string FormatNumber(float number) - { - return YamlFormatter.Default.FormatNumber(number); + static float ParseNumber(Scalar scalar) + { + return float.Parse(scalar.Value, YamlFormatter.Default.NumberFormat); + } } - if (value == null) + public void WriteYaml(IEmitter emitter, object? value, Type type) { - throw new NullReferenceException(nameof(value)); - } + if (value == null) + { + throw new NullReferenceException(nameof(value)); + } + + var vector = (Vector3)value; - var vector = (Vector3)value; + emitter.Emit(new MappingStart()); - emitter.Emit(new MappingStart()); + emitter.Emit(new Scalar(c_YamlKeyOfX)); + emitter.Emit(new Scalar(FormatNumber(vector.X))); - emitter.Emit(new Scalar(c_YamlKeyOfX)); - emitter.Emit(new Scalar(FormatNumber(vector.X))); + emitter.Emit(new Scalar(c_YamlKeyOfY)); + emitter.Emit(new Scalar(FormatNumber(vector.Y))); - emitter.Emit(new Scalar(c_YamlKeyOfY)); - emitter.Emit(new Scalar(FormatNumber(vector.Y))); + emitter.Emit(new Scalar(c_YamlKeyOfZ)); + emitter.Emit(new Scalar(FormatNumber(vector.Z))); - emitter.Emit(new Scalar(c_YamlKeyOfZ)); - emitter.Emit(new Scalar(FormatNumber(vector.Z))); + emitter.Emit(new MappingEnd()); + return; - emitter.Emit(new MappingEnd()); + static string FormatNumber(float number) + { + return YamlFormatter.Default.FormatNumber(number); + } + } } } \ No newline at end of file diff --git a/framework/OpenMod.Core/Plugins/PluginActivator.cs b/framework/OpenMod.Core/Plugins/PluginActivator.cs index f86a7bccc..005b16336 100644 --- a/framework/OpenMod.Core/Plugins/PluginActivator.cs +++ b/framework/OpenMod.Core/Plugins/PluginActivator.cs @@ -85,16 +85,23 @@ public IReadOnlyCollection ActivatedPlugins var assemblyComparer = AssemblyNameEqualityComparer.Instance; var dependencies = assembly.GetReferencedAssemblies(); var missingDependencies = new List(); + // ReSharper disable once LoopCanBeConvertedToQuery foreach (var dependency in dependencies) { if (dependency.Name.Equals("System.Drawing")) + { continue; + } if (Hotloader.Enabled && Hotloader.ContainsAssembly(dependency)) + { continue; + } if (AppDomain.CurrentDomain.GetAssemblies().Any(s => assemblyComparer.Equals(s.GetName(), dependency))) + { continue; + } missingDependencies.Add(dependency); } @@ -124,7 +131,7 @@ public IReadOnlyCollection ActivatedPlugins assembly); return null; } - + var pluginTypes = assemblyTypes.FindTypes().ToArray(); switch (pluginTypes.Length) { diff --git a/framework/OpenMod.Core/Plugins/PluginAssemblyStore.cs b/framework/OpenMod.Core/Plugins/PluginAssemblyStore.cs index 3c9cfbee1..1ea4ddbd0 100644 --- a/framework/OpenMod.Core/Plugins/PluginAssemblyStore.cs +++ b/framework/OpenMod.Core/Plugins/PluginAssemblyStore.cs @@ -64,7 +64,9 @@ public IReadOnlyCollection LoadedPluginAssemblies var packagesResourceName = assembly.GetManifestResourceNames() .FirstOrDefault(x => x.EndsWith("packages.yaml")); if (packagesResourceName == null) + { return newPlugins; + } var packagesRosourceInfo = assembly.GetManifestResourceInfo(packagesResourceName); m_Logger.LogDebug("Found packages.yaml with name {PackagesResourceName}.", packagesResourceName); @@ -75,7 +77,10 @@ public IReadOnlyCollection LoadedPluginAssemblies #else using var stream = assembly.GetManifestResourceStream(packagesResourceName); #endif - if (stream == null) return newPlugins; + if (stream == null) + { + return newPlugins; + } using var reader = new StreamReader(stream); var packagesContent = await reader.ReadToEndAsync(); @@ -88,7 +93,10 @@ public IReadOnlyCollection LoadedPluginAssemblies : new NuGetVersion(d.Version))) .ToList(); - if (packages == null || packages.Count == 0) return newPlugins; + if (packages == null || packages.Count == 0) + { + return newPlugins; + } m_Logger.LogInformation( "Found and installing embedded NuGet packages for plugin assembly: {AssemblyName}", @@ -103,13 +111,25 @@ public IReadOnlyCollection LoadedPluginAssemblies // ReSharper disable once LoopCanBeConvertedToQuery foreach (var newAssembly in newAssemblies.Select(x => (Assembly)x.Assembly.Target)) { - if (newAssembly == null) continue; + if (newAssembly == null) + { + continue; + } - if (newAssembly.GetCustomAttribute() == null) continue; + if (newAssembly.GetCustomAttribute() == null) + { + continue; + } - if (ignoredAssemblies.Contains(newAssembly)) continue; + if (ignoredAssemblies.Contains(newAssembly)) + { + continue; + } - if (m_LoadedPluginAssemblies.Select(x => x.Target).Cast().Contains(newAssembly)) continue; + if (m_LoadedPluginAssemblies.Select(x => x.Target).Cast().Contains(newAssembly)) + { + continue; + } newPlugins.Add(newAssembly); } @@ -179,9 +199,11 @@ public async Task> LoadPluginAssembliesAsync(IPluginAssemb m_Logger.LogWarning("Trying to install missing dependencies"); - var success = await TryInstallRequiredDependenciesAsync(providerAssembly, missingAssemblies); + var _ = await TryInstallRequiredDependenciesAsync(providerAssembly, missingAssemblies); if (!Hotloader.Enabled) + { continue; + } //todo check result and try reload lib //todo this implementation we will need a new API Interface with a collection of assemblies names diff --git a/framework/OpenMod.Core/Users/OfflineUserProvider.cs b/framework/OpenMod.Core/Users/OfflineUserProvider.cs index 953c4225c..a198cf047 100644 --- a/framework/OpenMod.Core/Users/OfflineUserProvider.cs +++ b/framework/OpenMod.Core/Users/OfflineUserProvider.cs @@ -3,7 +3,6 @@ using System.Drawing; using System.Linq; using System.Threading.Tasks; -using Microsoft.Extensions.Localization; using OpenMod.API.Localization; using OpenMod.API.Prioritization; using OpenMod.API.Users; @@ -66,7 +65,9 @@ public Task BanAsync(IUser user, string? reason = null, DateTime? endTime public async Task BanAsync(IUser user, IUser? instigator = null, string? reason = null, DateTime? expireDate = null) { if (expireDate.HasValue && expireDate.Value < DateTime.Now) + { return false; + } var data = await m_UserDataStore.GetUserDataAsync(user.Id, user.Type); if (data == null) diff --git a/framework/OpenMod.NuGet/NuGetPackageManager.cs b/framework/OpenMod.NuGet/NuGetPackageManager.cs index 40615b794..2dc5827e0 100644 --- a/framework/OpenMod.NuGet/NuGetPackageManager.cs +++ b/framework/OpenMod.NuGet/NuGetPackageManager.cs @@ -359,10 +359,14 @@ public virtual async Task> QueryPackagesAsyn return matches.Where(a => { if (s_PackageBlacklist.Any(p => p.Equals(a.Identity?.Id, StringComparison.OrdinalIgnoreCase))) + { return false; + } if (s_PublisherBlacklist.Any(p => a.Owners.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0)) + { return false; + } return true; }); diff --git a/framework/OpenMod.Runtime/Runtime.cs b/framework/OpenMod.Runtime/Runtime.cs index aa17de3ac..2a3ea99dc 100644 --- a/framework/OpenMod.Runtime/Runtime.cs +++ b/framework/OpenMod.Runtime/Runtime.cs @@ -48,9 +48,12 @@ public Runtime() public SemVersion Version { get; } - public string OpenModComponentId { get; } = "OpenMod.Core"; + public string OpenModComponentId { get => "OpenMod.Core"; } - public bool IsComponentAlive => Status is not RuntimeStatus.Unloaded and not RuntimeStatus.Crashed; + public bool IsComponentAlive + { + get => Status is not RuntimeStatus.Unloaded and not RuntimeStatus.Crashed; + } public ILifetimeScope LifetimeScope { get; private set; } = null!; @@ -319,7 +322,9 @@ public void Init(List openModAssemblies, RuntimeInitParameters paramet var missingDependencies = GetMissingDependencies(ex); if (openModHostAssembly.GetName().Name.Equals("OpenMod.Unturned") && !missingDependencies.Any()) + { continue; + } if (!missingOpenmodDepedencies) { @@ -358,16 +363,22 @@ private static ICollection GetMissingDependencies(ReflectionTypeLo //TypeLoadException is just matching with MissingFileAssemblyVersionRegex var match = s_MissingFileAssemblyVersionRegex.Match(loaderException.Message); if (!match.Success) + { match = s_TypeLoadAssemblyVersionRegex.Match(loaderException.Message); + } if (!match.Success) + { continue; + } var assemblyName = match.Groups["assembly"].Value; var version = System.Version.Parse(match.Groups["version"].Value); if (assemblyName.Equals("Rocket.API") || missingAssemblies.TryGetValue(assemblyName, out var currentVersion) && currentVersion >= version) + { continue; + } missingAssemblies[assemblyName] = version; } @@ -661,7 +672,7 @@ public async Task ShutdownAsync() m_DateLogger = null; m_LoggerFactory = null; m_Logger = null; - + Log.CloseAndFlush(); } } diff --git a/unturned/OpenMod.Unturned.Module.Shared/Patches/UnturnedBroadcastCommenceShutdownPatch.cs b/unturned/OpenMod.Unturned.Module.Shared/Patches/UnturnedBroadcastCommenceShutdownPatch.cs index 2fa7c1656..3ba47ab2b 100644 --- a/unturned/OpenMod.Unturned.Module.Shared/Patches/UnturnedBroadcastCommenceShutdownPatch.cs +++ b/unturned/OpenMod.Unturned.Module.Shared/Patches/UnturnedBroadcastCommenceShutdownPatch.cs @@ -1,5 +1,6 @@ using System.Reflection; using HarmonyLib; +using JetBrains.Annotations; using SDG.Unturned; namespace OpenMod.Unturned.Module.Shared.Patches @@ -8,7 +9,7 @@ namespace OpenMod.Unturned.Module.Shared.Patches [HarmonyPatch("onApplicationQuitting")] public static class UnturnedBroadcastCommenceShutdownPatch { - private static readonly MethodInfo s_BroadcastCommenceShutdown = typeof(Provider).GetMethod("broadcastCommenceShutdown", BindingFlags.NonPublic | BindingFlags.Static); + private static readonly MethodInfo s_BroadcastCommenceShutdown = AccessTools.Method(typeof(Provider), "broadcastCommenceShutdown"); private static bool s_ShutdownCommenced; static UnturnedBroadcastCommenceShutdownPatch() @@ -22,10 +23,13 @@ private static void OnCommenceShutdown() } [HarmonyPrefix] + [UsedImplicitly] public static void BeforeDisconnect() { if (!Provider.isInitialized || s_ShutdownCommenced) + { return; + } s_BroadcastCommenceShutdown.Invoke(null, null); } diff --git a/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/Color.cs b/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/Color.cs index 8c79f72ff..0ba249fa2 100644 --- a/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/Color.cs +++ b/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/Color.cs @@ -42,936 +42,959 @@ namespace System.Drawing { - [Serializable] - [TypeConverter(typeof(ColorConverter))] - public struct Color - { - int value; - - internal Color(int value) - { - this.value = value; - } - - #region Unimplemented bloated properties - // - // These properties were implemented very poorly on Mono, this - // version will only store the int32 value and any helper properties - // like Name, IsKnownColor, IsSystemColor, IsNamedColor are not - // currently implemented, and would be implemented in the future - // using external tables/hastables/dictionaries, without bloating - // the Color structure - // - public string Name - { - get - { - return KnownColors.NameByArgb.TryGetValue((uint)value, out string name) ? name : String.Empty; - } - } - - public bool IsKnownColor - { - get - { - return KnownColors.NameByArgb.ContainsKey((uint)value); - } - } - - public bool IsSystemColor - { - get - { - return false; - } - } - - public bool IsNamedColor - { - get + [Serializable] + [TypeConverter(typeof(ColorConverter))] + public struct Color + { + int value; + + internal Color(int value) + { + this.value = value; + } + + #region Unimplemented bloated properties + + // + // These properties were implemented very poorly on Mono, this + // version will only store the int32 value and any helper properties + // like Name, IsKnownColor, IsSystemColor, IsNamedColor are not + // currently implemented, and would be implemented in the future + // using external tables/hastables/dictionaries, without bloating + // the Color structure + // + public string Name + { + get { return KnownColors.NameByArgb.TryGetValue((uint)value, out string name) ? name : String.Empty; } + } + + public bool IsKnownColor + { + get { return KnownColors.NameByArgb.ContainsKey((uint)value); } + } + + public bool IsSystemColor + { + get { return false; } + } + + public bool IsNamedColor + { + get { return !string.IsNullOrEmpty(Name); } + } + + #endregion + + public static Color FromArgb(int red, int green, int blue) + { + return FromArgb(255, red, green, blue); + } + + public static Color FromArgb(int alpha, int red, int green, int blue) + { + if ((red > 255) || (red < 0)) { - return !string.IsNullOrEmpty(Name); + throw CreateColorArgumentException(red, "red"); } - } - #endregion - - public static Color FromArgb(int red, int green, int blue) - { - return FromArgb(255, red, green, blue); - } - - public static Color FromArgb(int alpha, int red, int green, int blue) - { - if ((red > 255) || (red < 0)) - throw CreateColorArgumentException(red, "red"); - if ((green > 255) || (green < 0)) - throw CreateColorArgumentException(green, "green"); - if ((blue > 255) || (blue < 0)) - throw CreateColorArgumentException(blue, "blue"); - if ((alpha > 255) || (alpha < 0)) - throw CreateColorArgumentException(alpha, "alpha"); - - Color color = new Color(); - color.value = (int)((uint)alpha << 24) + (red << 16) + (green << 8) + blue; - return color; - } - - public int ToArgb() - { - return (int)value; - } - - public static Color FromArgb(int alpha, Color baseColor) - { - return FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B); - } - - public static Color FromArgb(int argb) - { - return new Color(argb); - } - - public static Color FromKnownColor(KnownColor color) - { - return KnownColors.FromKnownColor(color); - } - - public static Color FromName(string name) - { - if (KnownColors.ArgbByName.TryGetValue(name, out uint argb)) - return new Color((int)argb); - return new Color(); - } - - - public static readonly Color Empty; - - public static bool operator ==(Color left, Color right) - { - return left.value == right.value; - } - - public static bool operator !=(Color left, Color right) - { - return left.value != right.value; - } - - public float GetBrightness() - { - byte minval = Math.Min(R, Math.Min(G, B)); - byte maxval = Math.Max(R, Math.Max(G, B)); - - return (float)(maxval + minval) / 510; - } - - public float GetSaturation() - { - byte minval = (byte)Math.Min(R, Math.Min(G, B)); - byte maxval = (byte)Math.Max(R, Math.Max(G, B)); - - if (maxval == minval) - return 0.0f; - - int sum = maxval + minval; - if (sum > 255) - sum = 510 - sum; - - return (float)(maxval - minval) / sum; - } - - public float GetHue() - { - int r = R; - int g = G; - int b = B; - byte minval = (byte)Math.Min(r, Math.Min(g, b)); - byte maxval = (byte)Math.Max(r, Math.Max(g, b)); - - if (maxval == minval) - return 0.0f; - - float diff = (float)(maxval - minval); - float rnorm = (maxval - r) / diff; - float gnorm = (maxval - g) / diff; - float bnorm = (maxval - b) / diff; - - float hue = 0.0f; - if (r == maxval) - hue = 60.0f * (6.0f + bnorm - gnorm); - if (g == maxval) - hue = 60.0f * (2.0f + rnorm - bnorm); - if (b == maxval) - hue = 60.0f * (4.0f + gnorm - rnorm); - if (hue > 360.0f) - hue = hue - 360.0f; - - return hue; - } - - public KnownColor ToKnownColor() - { - throw new NotImplementedException(); - } - - public bool IsEmpty - { - get - { - return value == 0; - } - } - - public byte A - { - get { return (byte)(value >> 24); } - } - - public byte R - { - get { return (byte)(value >> 16); } - } - - public byte G - { - get { return (byte)(value >> 8); } - } - - public byte B - { - get { return (byte)value; } - } - - public override bool Equals(object obj) - { - if (!(obj is Color)) - return false; - Color c = (Color)obj; - return this == c; - } - - public override int GetHashCode() - { - return value; - } - - public override string ToString() - { - if (IsEmpty) - return "Color [Empty]"; - - return String.Format("Color [A={0}, R={1}, G={2}, B={3}]", A, R, G, B); - } - - static ArgumentException CreateColorArgumentException(int value, string color) - { - return new ArgumentException(string.Format("'{0}' is not a valid" - + " value for '{1}'. '{1}' should be greater or equal to 0 and" - + " less than or equal to 255.", value, color)); - } - - static public Color Transparent - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Transparent]); } - } - - static public Color AliceBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.AliceBlue]); } - } - - static public Color AntiqueWhite - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.AntiqueWhite]); } - } - - static public Color Aqua - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Aqua]); } - } - - static public Color Aquamarine - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Aquamarine]); } - } - - static public Color Azure - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Azure]); } - } - - static public Color Beige - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Beige]); } - } - - static public Color Bisque - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Bisque]); } - } - - static public Color Black - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Black]); } - } - - static public Color BlanchedAlmond - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.BlanchedAlmond]); } - } - - static public Color Blue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Blue]); } - } - - static public Color BlueViolet - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.BlueViolet]); } - } - - static public Color Brown - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Brown]); } - } - - static public Color BurlyWood - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.BurlyWood]); } - } - - static public Color CadetBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.CadetBlue]); } - } - - static public Color Chartreuse - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Chartreuse]); } - } - - static public Color Chocolate - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Chocolate]); } - } - - static public Color Coral - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Coral]); } - } - - static public Color CornflowerBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.CornflowerBlue]); } - } - - static public Color Cornsilk - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Cornsilk]); } - } - - static public Color Crimson - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Crimson]); } - } - - static public Color Cyan - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Cyan]); } - } - - static public Color DarkBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkBlue]); } - } - - static public Color DarkCyan - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkCyan]); } - } - - static public Color DarkGoldenrod - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkGoldenrod]); } - } - - static public Color DarkGray - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkGray]); } - } - - static public Color DarkGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkGreen]); } - } - - static public Color DarkKhaki - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkKhaki]); } - } - - static public Color DarkMagenta - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkMagenta]); } - } - - static public Color DarkOliveGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkOliveGreen]); } - } - - static public Color DarkOrange - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkOrange]); } - } - - static public Color DarkOrchid - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkOrchid]); } - } - - static public Color DarkRed - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkRed]); } - } - - static public Color DarkSalmon - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkSalmon]); } - } - - static public Color DarkSeaGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkSeaGreen]); } - } - - static public Color DarkSlateBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkSlateBlue]); } - } - - static public Color DarkSlateGray - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkSlateGray]); } - } - - static public Color DarkTurquoise - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkTurquoise]); } - } - - static public Color DarkViolet - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkViolet]); } - } - - static public Color DeepPink - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DeepPink]); } - } - - static public Color DeepSkyBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DeepSkyBlue]); } - } - - static public Color DimGray - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DimGray]); } - } - - static public Color DodgerBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DodgerBlue]); } - } - - static public Color Firebrick - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Firebrick]); } - } - - static public Color FloralWhite - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.FloralWhite]); } - } - - static public Color ForestGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.ForestGreen]); } - } - - static public Color Fuchsia - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Fuchsia]); } - } - - static public Color Gainsboro - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Gainsboro]); } - } - - static public Color GhostWhite - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.GhostWhite]); } - } - - static public Color Gold - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Gold]); } - } - - static public Color Goldenrod - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Goldenrod]); } - } - - static public Color Gray - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Gray]); } - } - - static public Color Green - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Green]); } - } - - static public Color GreenYellow - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.GreenYellow]); } - } - - static public Color Honeydew - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Honeydew]); } - } - - static public Color HotPink - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.HotPink]); } - } - - static public Color IndianRed - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.IndianRed]); } - } - - static public Color Indigo - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Indigo]); } - } - - static public Color Ivory - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Ivory]); } - } - - static public Color Khaki - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Khaki]); } - } - - static public Color Lavender - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Lavender]); } - } - - static public Color LavenderBlush - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LavenderBlush]); } - } - - static public Color LawnGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LawnGreen]); } - } - - static public Color LemonChiffon - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LemonChiffon]); } - } - - static public Color LightBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightBlue]); } - } - - static public Color LightCoral - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightCoral]); } - } - - static public Color LightCyan - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightCyan]); } - } - - static public Color LightGoldenrodYellow - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightGoldenrodYellow]); } - } - - static public Color LightGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightGreen]); } - } - - static public Color LightGray - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightGray]); } - } - - static public Color LightPink - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightPink]); } - } - - static public Color LightSalmon - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSalmon]); } - } - - static public Color LightSeaGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSeaGreen]); } - } - - static public Color LightSkyBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSkyBlue]); } - } - - static public Color LightSlateGray - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSlateGray]); } - } - - static public Color LightSteelBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSteelBlue]); } - } - - static public Color LightYellow - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightYellow]); } - } - - static public Color Lime - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Lime]); } - } - - static public Color LimeGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LimeGreen]); } - } - - static public Color Linen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Linen]); } - } - - static public Color Magenta - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Magenta]); } - } - - static public Color Maroon - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Maroon]); } - } - - static public Color MediumAquamarine - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumAquamarine]); } - } - - static public Color MediumBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumBlue]); } - } - - static public Color MediumOrchid - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumOrchid]); } - } - - static public Color MediumPurple - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumPurple]); } - } - - static public Color MediumSeaGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumSeaGreen]); } - } - - static public Color MediumSlateBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumSlateBlue]); } - } - - static public Color MediumSpringGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumSpringGreen]); } - } - - static public Color MediumTurquoise - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumTurquoise]); } - } - - static public Color MediumVioletRed - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumVioletRed]); } - } - - static public Color MidnightBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MidnightBlue]); } - } - - static public Color MintCream - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MintCream]); } - } - - static public Color MistyRose - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MistyRose]); } - } - - static public Color Moccasin - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Moccasin]); } - } - - static public Color NavajoWhite - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.NavajoWhite]); } - } - - static public Color Navy - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Navy]); } - } - - static public Color OldLace - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.OldLace]); } - } - - static public Color Olive - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Olive]); } - } - - static public Color OliveDrab - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.OliveDrab]); } - } - - static public Color Orange - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Orange]); } - } - - static public Color OrangeRed - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.OrangeRed]); } - } - - static public Color Orchid - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Orchid]); } - } - - static public Color PaleGoldenrod - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PaleGoldenrod]); } - } - - static public Color PaleGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PaleGreen]); } - } - - static public Color PaleTurquoise - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PaleTurquoise]); } - } - - static public Color PaleVioletRed - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PaleVioletRed]); } - } - - static public Color PapayaWhip - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PapayaWhip]); } - } - - static public Color PeachPuff - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PeachPuff]); } - } - - static public Color Peru - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Peru]); } - } - - static public Color Pink - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Pink]); } - } - - static public Color Plum - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Plum]); } - } - - static public Color PowderBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PowderBlue]); } - } - - static public Color Purple - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Purple]); } - } - - static public Color Red - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Red]); } - } - - static public Color RosyBrown - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.RosyBrown]); } - } - - static public Color RoyalBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.RoyalBlue]); } - } - - static public Color SaddleBrown - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SaddleBrown]); } - } - - static public Color Salmon - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Salmon]); } - } - - static public Color SandyBrown - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SandyBrown]); } - } - - static public Color SeaGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SeaGreen]); } - } - - static public Color SeaShell - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SeaShell]); } - } - - static public Color Sienna - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Sienna]); } - } - - static public Color Silver - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Silver]); } - } - - static public Color SkyBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SkyBlue]); } - } - - static public Color SlateBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SlateBlue]); } - } - - static public Color SlateGray - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SlateGray]); } - } - - static public Color Snow - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Snow]); } - } - - static public Color SpringGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SpringGreen]); } - } - - static public Color SteelBlue - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SteelBlue]); } - } - - static public Color Tan - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Tan]); } - } - - static public Color Teal - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Teal]); } - } - - static public Color Thistle - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Thistle]); } - } - - static public Color Tomato - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Tomato]); } - } - - static public Color Turquoise - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Turquoise]); } - } - - static public Color Violet - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Violet]); } - } - - static public Color Wheat - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Wheat]); } - } - - static public Color White - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.White]); } - } - - static public Color WhiteSmoke - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.WhiteSmoke]); } - } - - static public Color Yellow - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Yellow]); } - } - - static public Color YellowGreen - { - get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.YellowGreen]); } - } - } + + if ((green > 255) || (green < 0)) + { + throw CreateColorArgumentException(green, "green"); + } + + if ((blue > 255) || (blue < 0)) + { + throw CreateColorArgumentException(blue, "blue"); + } + + if ((alpha > 255) || (alpha < 0)) + { + throw CreateColorArgumentException(alpha, "alpha"); + } + + Color color = new Color(); + color.value = (int)((uint)alpha << 24) + (red << 16) + (green << 8) + blue; + return color; + } + + public int ToArgb() + { + return (int)value; + } + + public static Color FromArgb(int alpha, Color baseColor) + { + return FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B); + } + + public static Color FromArgb(int argb) + { + return new Color(argb); + } + + public static Color FromKnownColor(KnownColor color) + { + return KnownColors.FromKnownColor(color); + } + + public static Color FromName(string name) + { + if (KnownColors.ArgbByName.TryGetValue(name, out uint argb)) + { + return new Color((int)argb); + } + + return new Color(); + } + + + public static readonly Color Empty; + + public static bool operator ==(Color left, Color right) + { + return left.value == right.value; + } + + public static bool operator !=(Color left, Color right) + { + return left.value != right.value; + } + + public float GetBrightness() + { + byte minval = Math.Min(R, Math.Min(G, B)); + byte maxval = Math.Max(R, Math.Max(G, B)); + + return (float)(maxval + minval) / 510; + } + + public float GetSaturation() + { + byte minval = (byte)Math.Min(R, Math.Min(G, B)); + byte maxval = (byte)Math.Max(R, Math.Max(G, B)); + + if (maxval == minval) + { + return 0.0f; + } + + int sum = maxval + minval; + if (sum > 255) + { + sum = 510 - sum; + } + + return (float)(maxval - minval) / sum; + } + + public float GetHue() + { + int r = R; + int g = G; + int b = B; + byte minval = (byte)Math.Min(r, Math.Min(g, b)); + byte maxval = (byte)Math.Max(r, Math.Max(g, b)); + + if (maxval == minval) + { + return 0.0f; + } + + float diff = (float)(maxval - minval); + float rnorm = (maxval - r) / diff; + float gnorm = (maxval - g) / diff; + float bnorm = (maxval - b) / diff; + + float hue = 0.0f; + if (r == maxval) + { + hue = 60.0f * (6.0f + bnorm - gnorm); + } + + if (g == maxval) + { + hue = 60.0f * (2.0f + rnorm - bnorm); + } + + if (b == maxval) + { + hue = 60.0f * (4.0f + gnorm - rnorm); + } + + if (hue > 360.0f) + { + hue = hue - 360.0f; + } + + return hue; + } + + public KnownColor ToKnownColor() + { + throw new NotImplementedException(); + } + + public bool IsEmpty + { + get { return value == 0; } + } + + public byte A + { + get { return (byte)(value >> 24); } + } + + public byte R + { + get { return (byte)(value >> 16); } + } + + public byte G + { + get { return (byte)(value >> 8); } + } + + public byte B + { + get { return (byte)value; } + } + + public override bool Equals(object obj) + { + if (!(obj is Color)) + { + return false; + } + + Color c = (Color)obj; + return this == c; + } + + public override int GetHashCode() + { + return value; + } + + public override string ToString() + { + if (IsEmpty) + { + return "Color [Empty]"; + } + + return String.Format("Color [A={0}, R={1}, G={2}, B={3}]", A, R, G, B); + } + + static ArgumentException CreateColorArgumentException(int value, string color) + { + return new ArgumentException(string.Format("'{0}' is not a valid" + + " value for '{1}'. '{1}' should be greater or equal to 0 and" + + " less than or equal to 255.", value, color)); + } + + static public Color Transparent + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Transparent]); } + } + + static public Color AliceBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.AliceBlue]); } + } + + static public Color AntiqueWhite + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.AntiqueWhite]); } + } + + static public Color Aqua + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Aqua]); } + } + + static public Color Aquamarine + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Aquamarine]); } + } + + static public Color Azure + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Azure]); } + } + + static public Color Beige + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Beige]); } + } + + static public Color Bisque + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Bisque]); } + } + + static public Color Black + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Black]); } + } + + static public Color BlanchedAlmond + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.BlanchedAlmond]); } + } + + static public Color Blue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Blue]); } + } + + static public Color BlueViolet + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.BlueViolet]); } + } + + static public Color Brown + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Brown]); } + } + + static public Color BurlyWood + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.BurlyWood]); } + } + + static public Color CadetBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.CadetBlue]); } + } + + static public Color Chartreuse + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Chartreuse]); } + } + + static public Color Chocolate + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Chocolate]); } + } + + static public Color Coral + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Coral]); } + } + + static public Color CornflowerBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.CornflowerBlue]); } + } + + static public Color Cornsilk + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Cornsilk]); } + } + + static public Color Crimson + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Crimson]); } + } + + static public Color Cyan + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Cyan]); } + } + + static public Color DarkBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkBlue]); } + } + + static public Color DarkCyan + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkCyan]); } + } + + static public Color DarkGoldenrod + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkGoldenrod]); } + } + + static public Color DarkGray + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkGray]); } + } + + static public Color DarkGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkGreen]); } + } + + static public Color DarkKhaki + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkKhaki]); } + } + + static public Color DarkMagenta + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkMagenta]); } + } + + static public Color DarkOliveGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkOliveGreen]); } + } + + static public Color DarkOrange + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkOrange]); } + } + + static public Color DarkOrchid + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkOrchid]); } + } + + static public Color DarkRed + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkRed]); } + } + + static public Color DarkSalmon + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkSalmon]); } + } + + static public Color DarkSeaGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkSeaGreen]); } + } + + static public Color DarkSlateBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkSlateBlue]); } + } + + static public Color DarkSlateGray + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkSlateGray]); } + } + + static public Color DarkTurquoise + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkTurquoise]); } + } + + static public Color DarkViolet + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DarkViolet]); } + } + + static public Color DeepPink + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DeepPink]); } + } + + static public Color DeepSkyBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DeepSkyBlue]); } + } + + static public Color DimGray + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DimGray]); } + } + + static public Color DodgerBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.DodgerBlue]); } + } + + static public Color Firebrick + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Firebrick]); } + } + + static public Color FloralWhite + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.FloralWhite]); } + } + + static public Color ForestGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.ForestGreen]); } + } + + static public Color Fuchsia + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Fuchsia]); } + } + + static public Color Gainsboro + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Gainsboro]); } + } + + static public Color GhostWhite + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.GhostWhite]); } + } + + static public Color Gold + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Gold]); } + } + + static public Color Goldenrod + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Goldenrod]); } + } + + static public Color Gray + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Gray]); } + } + + static public Color Green + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Green]); } + } + + static public Color GreenYellow + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.GreenYellow]); } + } + + static public Color Honeydew + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Honeydew]); } + } + + static public Color HotPink + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.HotPink]); } + } + + static public Color IndianRed + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.IndianRed]); } + } + + static public Color Indigo + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Indigo]); } + } + + static public Color Ivory + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Ivory]); } + } + + static public Color Khaki + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Khaki]); } + } + + static public Color Lavender + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Lavender]); } + } + + static public Color LavenderBlush + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LavenderBlush]); } + } + + static public Color LawnGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LawnGreen]); } + } + + static public Color LemonChiffon + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LemonChiffon]); } + } + + static public Color LightBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightBlue]); } + } + + static public Color LightCoral + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightCoral]); } + } + + static public Color LightCyan + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightCyan]); } + } + + static public Color LightGoldenrodYellow + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightGoldenrodYellow]); } + } + + static public Color LightGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightGreen]); } + } + + static public Color LightGray + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightGray]); } + } + + static public Color LightPink + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightPink]); } + } + + static public Color LightSalmon + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSalmon]); } + } + + static public Color LightSeaGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSeaGreen]); } + } + + static public Color LightSkyBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSkyBlue]); } + } + + static public Color LightSlateGray + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSlateGray]); } + } + + static public Color LightSteelBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightSteelBlue]); } + } + + static public Color LightYellow + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LightYellow]); } + } + + static public Color Lime + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Lime]); } + } + + static public Color LimeGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.LimeGreen]); } + } + + static public Color Linen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Linen]); } + } + + static public Color Magenta + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Magenta]); } + } + + static public Color Maroon + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Maroon]); } + } + + static public Color MediumAquamarine + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumAquamarine]); } + } + + static public Color MediumBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumBlue]); } + } + + static public Color MediumOrchid + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumOrchid]); } + } + + static public Color MediumPurple + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumPurple]); } + } + + static public Color MediumSeaGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumSeaGreen]); } + } + + static public Color MediumSlateBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumSlateBlue]); } + } + + static public Color MediumSpringGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumSpringGreen]); } + } + + static public Color MediumTurquoise + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumTurquoise]); } + } + + static public Color MediumVioletRed + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MediumVioletRed]); } + } + + static public Color MidnightBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MidnightBlue]); } + } + + static public Color MintCream + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MintCream]); } + } + + static public Color MistyRose + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.MistyRose]); } + } + + static public Color Moccasin + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Moccasin]); } + } + + static public Color NavajoWhite + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.NavajoWhite]); } + } + + static public Color Navy + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Navy]); } + } + + static public Color OldLace + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.OldLace]); } + } + + static public Color Olive + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Olive]); } + } + + static public Color OliveDrab + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.OliveDrab]); } + } + + static public Color Orange + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Orange]); } + } + + static public Color OrangeRed + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.OrangeRed]); } + } + + static public Color Orchid + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Orchid]); } + } + + static public Color PaleGoldenrod + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PaleGoldenrod]); } + } + + static public Color PaleGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PaleGreen]); } + } + + static public Color PaleTurquoise + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PaleTurquoise]); } + } + + static public Color PaleVioletRed + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PaleVioletRed]); } + } + + static public Color PapayaWhip + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PapayaWhip]); } + } + + static public Color PeachPuff + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PeachPuff]); } + } + + static public Color Peru + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Peru]); } + } + + static public Color Pink + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Pink]); } + } + + static public Color Plum + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Plum]); } + } + + static public Color PowderBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.PowderBlue]); } + } + + static public Color Purple + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Purple]); } + } + + static public Color Red + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Red]); } + } + + static public Color RosyBrown + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.RosyBrown]); } + } + + static public Color RoyalBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.RoyalBlue]); } + } + + static public Color SaddleBrown + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SaddleBrown]); } + } + + static public Color Salmon + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Salmon]); } + } + + static public Color SandyBrown + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SandyBrown]); } + } + + static public Color SeaGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SeaGreen]); } + } + + static public Color SeaShell + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SeaShell]); } + } + + static public Color Sienna + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Sienna]); } + } + + static public Color Silver + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Silver]); } + } + + static public Color SkyBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SkyBlue]); } + } + + static public Color SlateBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SlateBlue]); } + } + + static public Color SlateGray + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SlateGray]); } + } + + static public Color Snow + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Snow]); } + } + + static public Color SpringGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SpringGreen]); } + } + + static public Color SteelBlue + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.SteelBlue]); } + } + + static public Color Tan + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Tan]); } + } + + static public Color Teal + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Teal]); } + } + + static public Color Thistle + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Thistle]); } + } + + static public Color Tomato + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Tomato]); } + } + + static public Color Turquoise + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Turquoise]); } + } + + static public Color Violet + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Violet]); } + } + + static public Color Wheat + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Wheat]); } + } + + static public Color White + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.White]); } + } + + static public Color WhiteSmoke + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.WhiteSmoke]); } + } + + static public Color Yellow + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.Yellow]); } + } + + static public Color YellowGreen + { + get { return new Color((int)KnownColors.ArgbValues[(int)KnownColor.YellowGreen]); } + } + } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/ColorConverter.cs b/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/ColorConverter.cs index ebee18196..297001fe4 100644 --- a/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/ColorConverter.cs +++ b/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/ColorConverter.cs @@ -40,243 +40,274 @@ namespace System.Drawing { - public class ColorConverter : TypeConverter - { - static StandardValuesCollection? cached; - static object creatingCached = new object(); - - public ColorConverter() { } - - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - if (sourceType == typeof(string)) - return true; - - return base.CanConvertFrom(context, sourceType); - } - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(InstanceDescriptor)) - return true; - - return base.CanConvertTo(context, destinationType); - } - - internal static Color StaticConvertFromString(ITypeDescriptorContext context, string s, CultureInfo culture) - { - if (culture == null) - culture = CultureInfo.InvariantCulture; - - s = s.Trim(); - - if (s.Length == 0) - return Color.Empty; - - // Try to process both NamedColor and SystemColors from the KnownColor enumeration - if (Char.IsLetter(s[0])) - { - KnownColor kc; - try - { - kc = (KnownColor)Enum.Parse(typeof(KnownColor), s, true); - } - catch (Exception e) - { - // whatever happens MS throws an basic Exception + public class ColorConverter : TypeConverter + { + static StandardValuesCollection? cached; + static object creatingCached = new object(); + + public ColorConverter() + { + } + + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(string)) + { + return true; + } + + return base.CanConvertFrom(context, sourceType); + } + + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor)) + { + return true; + } + + return base.CanConvertTo(context, destinationType); + } + + internal static Color StaticConvertFromString(ITypeDescriptorContext context, string s, CultureInfo culture) + { + if (culture == null) + { + culture = CultureInfo.InvariantCulture; + } + + s = s.Trim(); + + if (s.Length == 0) + { + return Color.Empty; + } + + // Try to process both NamedColor and SystemColors from the KnownColor enumeration + if (Char.IsLetter(s[0])) + { + KnownColor kc; + try + { + kc = (KnownColor)Enum.Parse(typeof(KnownColor), s, true); + } + catch (Exception e) + { + // whatever happens MS throws an basic Exception string msg = $"Invalid color name '{s}'."; - throw new Exception(msg, new FormatException(msg, e)); - } - return KnownColors.FromKnownColor(kc); - } - - String numSeparator = culture.TextInfo.ListSeparator; - Color result = Color.Empty; - - if (s.IndexOf(numSeparator) == -1) - { - bool sharp = (s[0] == '#'); - int start = sharp ? 1 : 0; - bool hex = false; - // deal with #hex, 0xhex and #0xhex - if ((s.Length > start + 1) && (s[start] == '0')) - { - hex = ((s[start + 1] == 'x') || (s[start + 1] == 'X')); - if (hex) - start += 2; - } - - if (sharp || hex) - { - s = s.Substring(start); - int argb; - try - { - argb = Int32.Parse(s, NumberStyles.HexNumber); - } - catch (Exception e) - { - // whatever happens MS throws an basic Exception - throw new Exception($"Invalid Int32 value '{s}'.", e); - } - - // note that the default alpha value for a 6 hex digit (i.e. when none are present) is - // 0xFF while shorter string defaults to 0xFF - unless both # an 0x are specified - if ((s.Length < 6) || ((s.Length == 6) && sharp && hex)) - argb &= 0x00FFFFFF; - else if ((argb >> 24) == 0) - argb |= unchecked((int)0xFF000000); - result = Color.FromArgb(argb); - } - } - - if (result.IsEmpty) - { - Int32Converter converter = new Int32Converter(); - String[] components = s.Split(numSeparator.ToCharArray()); - - // MS seems to convert the indivual component to int before - // checking the number of components - int[] numComponents = new int[components.Length]; - for (int i = 0; i < numComponents.Length; i++) - { - numComponents[i] = (int)converter.ConvertFrom(context, - culture, components[i]); - } - - switch (components.Length) - { - case 1: - result = Color.FromArgb(numComponents[0]); - break; - case 3: - result = Color.FromArgb(numComponents[0], numComponents[1], - numComponents[2]); - break; - case 4: - result = Color.FromArgb(numComponents[0], numComponents[1], - numComponents[2], numComponents[3]); - break; - default: - throw new ArgumentException(s + " is not a valid color value."); - } - } - - if (!result.IsEmpty) - { - // Look for a named or system color with those values - Color known = KnownColors.FindColorMatch(result); - if (!known.IsEmpty) - return known; - } - - return result; - } - - - public override object ConvertFrom(ITypeDescriptorContext context, - CultureInfo culture, - object value) - { - string? s = value as string; - if (s == null) - return base.ConvertFrom(context, culture, value); - - return StaticConvertFromString(context, s, culture); - } - - public override object ConvertTo(ITypeDescriptorContext context, - CultureInfo culture, - object value, - Type destinationType) - { - if (value is Color) - { - Color color = (Color)value; - if (destinationType == typeof(string)) - { - if (color == Color.Empty) - return string.Empty; - - if (color.IsKnownColor || color.IsNamedColor) // lgtm [cs/constant-condition] - return color.Name; - - String numSeparator = culture.TextInfo.ListSeparator; - - StringBuilder sb = new StringBuilder(); - if (color.A != 255) - { - sb.Append(color.A); - sb.Append(numSeparator); - sb.Append(" "); - } - sb.Append(color.R); - sb.Append(numSeparator); - sb.Append(" "); - - sb.Append(color.G); - sb.Append(numSeparator); - sb.Append(" "); - - sb.Append(color.B); - return sb.ToString(); - } - else if (destinationType == typeof(InstanceDescriptor)) - { - if (color.IsEmpty) - { - return new InstanceDescriptor(typeof(Color).GetTypeInfo().GetField("Empty"), null); - } - else if (color.IsSystemColor) - { - return new InstanceDescriptor(typeof(SystemColors).GetTypeInfo().GetProperty(color.Name), null); - } - else if (color.IsKnownColor) - { - return new InstanceDescriptor(typeof(Color).GetTypeInfo().GetProperty(color.Name), null); - } - else - { - MethodInfo met = typeof(Color).GetTypeInfo().GetMethod("FromArgb", new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) }); - return new InstanceDescriptor(met, new object[] { color.A, color.R, color.G, color.B }); - } - } - } - - return base.ConvertTo(context, culture, value, destinationType); - } - - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) - { - lock (creatingCached) - { - if (cached != null) - return cached; - Array colors = Array.CreateInstance(typeof(Color), KnownColors.ArgbValues.Length - 1); - for (int i = 1; i < KnownColors.ArgbValues.Length; i++) - { - colors.SetValue(KnownColors.FromKnownColor((KnownColor)i), i - 1); - } - - Array.Sort(colors, 0, colors.Length, new CompareColors()); - cached = new StandardValuesCollection(colors); - } - - return cached; - } - - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) - { - return true; - } - - sealed class CompareColors : IComparer - { - - public int Compare(object x, object y) - { - return String.Compare(((Color)x).Name, ((Color)y).Name); - } - } - } + throw new Exception(msg, new FormatException(msg, e)); + } + + return KnownColors.FromKnownColor(kc); + } + + String numSeparator = culture.TextInfo.ListSeparator; + Color result = Color.Empty; + + if (s.IndexOf(numSeparator) == -1) + { + bool sharp = (s[0] == '#'); + int start = sharp ? 1 : 0; + bool hex = false; + // deal with #hex, 0xhex and #0xhex + if ((s.Length > start + 1) && (s[start] == '0')) + { + hex = ((s[start + 1] == 'x') || (s[start + 1] == 'X')); + if (hex) + { + start += 2; + } + } + + if (sharp || hex) + { + s = s.Substring(start); + int argb; + try + { + argb = Int32.Parse(s, NumberStyles.HexNumber); + } + catch (Exception e) + { + // whatever happens MS throws an basic Exception + throw new Exception($"Invalid Int32 value '{s}'.", e); + } + + // note that the default alpha value for a 6 hex digit (i.e. when none are present) is + // 0xFF while shorter string defaults to 0xFF - unless both # an 0x are specified + if ((s.Length < 6) || ((s.Length == 6) && sharp && hex)) + { + argb &= 0x00FFFFFF; + } + else if ((argb >> 24) == 0) + { + argb |= unchecked((int)0xFF000000); + } + + result = Color.FromArgb(argb); + } + } + + if (result.IsEmpty) + { + Int32Converter converter = new Int32Converter(); + String[] components = s.Split(numSeparator.ToCharArray()); + + // MS seems to convert the indivual component to int before + // checking the number of components + int[] numComponents = new int[components.Length]; + for (int i = 0; i < numComponents.Length; i++) + { + numComponents[i] = (int)converter.ConvertFrom(context, + culture, components[i]); + } + + switch (components.Length) + { + case 1: + result = Color.FromArgb(numComponents[0]); + break; + case 3: + result = Color.FromArgb(numComponents[0], numComponents[1], + numComponents[2]); + break; + case 4: + result = Color.FromArgb(numComponents[0], numComponents[1], + numComponents[2], numComponents[3]); + break; + default: + throw new ArgumentException(s + " is not a valid color value."); + } + } + + if (!result.IsEmpty) + { + // Look for a named or system color with those values + Color known = KnownColors.FindColorMatch(result); + if (!known.IsEmpty) + { + return known; + } + } + + return result; + } + + + public override object ConvertFrom(ITypeDescriptorContext context, + CultureInfo culture, + object value) + { + string? s = value as string; + if (s == null) + { + return base.ConvertFrom(context, culture, value); + } + + return StaticConvertFromString(context, s, culture); + } + + public override object ConvertTo(ITypeDescriptorContext context, + CultureInfo culture, + object value, + Type destinationType) + { + if (value is Color) + { + Color color = (Color)value; + if (destinationType == typeof(string)) + { + if (color == Color.Empty) + { + return string.Empty; + } + + if (color.IsKnownColor || color.IsNamedColor) // lgtm [cs/constant-condition] + { + return color.Name; + } + + String numSeparator = culture.TextInfo.ListSeparator; + + StringBuilder sb = new StringBuilder(); + if (color.A != 255) + { + sb.Append(color.A); + sb.Append(numSeparator); + sb.Append(" "); + } + + sb.Append(color.R); + sb.Append(numSeparator); + sb.Append(" "); + + sb.Append(color.G); + sb.Append(numSeparator); + sb.Append(" "); + + sb.Append(color.B); + return sb.ToString(); + } + else if (destinationType == typeof(InstanceDescriptor)) + { + if (color.IsEmpty) + { + return new InstanceDescriptor(typeof(Color).GetTypeInfo().GetField("Empty"), null); + } + else if (color.IsSystemColor) + { + return new InstanceDescriptor(typeof(SystemColors).GetTypeInfo().GetProperty(color.Name), null); + } + else if (color.IsKnownColor) + { + return new InstanceDescriptor(typeof(Color).GetTypeInfo().GetProperty(color.Name), null); + } + else + { + MethodInfo met = typeof(Color).GetTypeInfo().GetMethod("FromArgb", + new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) }); + return new InstanceDescriptor(met, new object[] { color.A, color.R, color.G, color.B }); + } + } + } + + return base.ConvertTo(context, culture, value, destinationType); + } + + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + lock (creatingCached) + { + if (cached != null) + { + return cached; + } + + Array colors = Array.CreateInstance(typeof(Color), KnownColors.ArgbValues.Length - 1); + for (int i = 1; i < KnownColors.ArgbValues.Length; i++) + { + colors.SetValue(KnownColors.FromKnownColor((KnownColor)i), i - 1); + } + + Array.Sort(colors, 0, colors.Length, new CompareColors()); + cached = new StandardValuesCollection(colors); + } + + return cached; + } + + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { + return true; + } + + sealed class CompareColors : IComparer + { + + public int Compare(object x, object y) + { + return String.Compare(((Color)x).Name, ((Color)y).Name); + } + } + } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/ColorTranslator.cs b/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/ColorTranslator.cs index 534799ce0..a4f29baa2 100644 --- a/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/ColorTranslator.cs +++ b/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/ColorTranslator.cs @@ -37,167 +37,176 @@ namespace System.Drawing { - public sealed class ColorTranslator - { - - private ColorTranslator() - { - } - - public static Color FromHtml(string htmlColor) - { - if (string.IsNullOrEmpty(htmlColor)) return Color.Empty; - - switch (htmlColor.ToLowerInvariant()) - { - case "buttonface": - case "threedface": - return SystemColors.Control; - case "buttonhighlight": - case "threedlightshadow": - return SystemColors.ControlLightLight; - case "buttonshadow": - return SystemColors.ControlDark; - case "captiontext": - return SystemColors.ActiveCaptionText; - case "threeddarkshadow": - return SystemColors.ControlDarkDark; - case "threedhighlight": - return SystemColors.ControlLight; - case "background": - return SystemColors.Desktop; - case "buttontext": - return SystemColors.ControlText; - case "infobackground": - return SystemColors.Info; - // special case for Color.LightGray versus html's LightGrey (#340917) - case "lightgrey": - return Color.LightGray; - } - - if (htmlColor[0] == '#' && htmlColor.Length == 4) - { - char r = htmlColor[1], g = htmlColor[2], b = htmlColor[3]; - htmlColor = new string(new char[] { '#', r, r, g, g, b, b }); - } - - TypeConverter converter = TypeDescriptor.GetConverter(typeof(Color)); - return (Color)converter.ConvertFromString(htmlColor); - } - - internal static Color FromBGR(int bgr) - { - Color result = Color.FromArgb(0xFF, (bgr & 0xFF), ((bgr >> 8) & 0xFF), ((bgr >> 16) & 0xFF)); - Color known = KnownColors.FindColorMatch(result); - return (known.IsEmpty) ? result : known; - } - - public static Color FromOle(int oleColor) - { - // OleColor format is BGR - return FromBGR(oleColor); - } - - public static Color FromWin32(int win32Color) - { - // Win32Color format is BGR - return FromBGR(win32Color); - } - - public static string ToHtml(Color c) - { - if (c.IsEmpty) - return String.Empty; - - if (c.IsSystemColor) - { - KnownColor kc = c.ToKnownColor(); - switch (kc) - { - case KnownColor.ActiveBorder: - case KnownColor.ActiveCaption: - case KnownColor.AppWorkspace: - case KnownColor.GrayText: - case KnownColor.Highlight: - case KnownColor.HighlightText: - case KnownColor.InactiveBorder: - case KnownColor.InactiveCaption: - case KnownColor.InactiveCaptionText: - case KnownColor.InfoText: - case KnownColor.Menu: - case KnownColor.MenuText: - case KnownColor.ScrollBar: - case KnownColor.Window: - case KnownColor.WindowFrame: - case KnownColor.WindowText: - return KnownColors.GetName(kc).ToLowerInvariant(); - - case KnownColor.ActiveCaptionText: - return "captiontext"; - case KnownColor.Control: - return "buttonface"; - case KnownColor.ControlDark: - return "buttonshadow"; - case KnownColor.ControlDarkDark: - return "threeddarkshadow"; - case KnownColor.ControlLight: - return "buttonface"; - case KnownColor.ControlLightLight: - return "buttonhighlight"; - case KnownColor.ControlText: - return "buttontext"; - case KnownColor.Desktop: - return "background"; - case KnownColor.HotTrack: - return "highlight"; - case KnownColor.Info: - return "infobackground"; - - default: - return String.Empty; - } - } - - if (c.IsNamedColor) - { - if (c == Color.LightGray) - return "LightGrey"; - else - return c.Name; - } - - return FormatHtml(c.R, c.G, c.B); - } - - static char GetHexNumber(int b) - { - return (char)(b > 9 ? 55 + b : 48 + b); - } - - static string FormatHtml(int r, int g, int b) - { - char[] htmlColor = new char[7]; - htmlColor[0] = '#'; - htmlColor[1] = GetHexNumber((r >> 4) & 15); - htmlColor[2] = GetHexNumber(r & 15); - htmlColor[3] = GetHexNumber((g >> 4) & 15); - htmlColor[4] = GetHexNumber(g & 15); - htmlColor[5] = GetHexNumber((b >> 4) & 15); - htmlColor[6] = GetHexNumber(b & 15); - - return new string(htmlColor); - } - - public static int ToOle(Color c) - { - // OleColor format is BGR, same as Win32 - return ((c.B << 16) | (c.G << 8) | c.R); - } - - public static int ToWin32(Color c) - { - // Win32Color format is BGR, Same as OleColor - return ((c.B << 16) | (c.G << 8) | c.R); - } - } + public sealed class ColorTranslator + { + + private ColorTranslator() + { + } + + public static Color FromHtml(string htmlColor) + { + if (string.IsNullOrEmpty(htmlColor)) + { + return Color.Empty; + } + + switch (htmlColor.ToLowerInvariant()) + { + case "buttonface": + case "threedface": + return SystemColors.Control; + case "buttonhighlight": + case "threedlightshadow": + return SystemColors.ControlLightLight; + case "buttonshadow": + return SystemColors.ControlDark; + case "captiontext": + return SystemColors.ActiveCaptionText; + case "threeddarkshadow": + return SystemColors.ControlDarkDark; + case "threedhighlight": + return SystemColors.ControlLight; + case "background": + return SystemColors.Desktop; + case "buttontext": + return SystemColors.ControlText; + case "infobackground": + return SystemColors.Info; + // special case for Color.LightGray versus html's LightGrey (#340917) + case "lightgrey": + return Color.LightGray; + } + + if (htmlColor[0] == '#' && htmlColor.Length == 4) + { + char r = htmlColor[1], g = htmlColor[2], b = htmlColor[3]; + htmlColor = new string(new char[] { '#', r, r, g, g, b, b }); + } + + TypeConverter converter = TypeDescriptor.GetConverter(typeof(Color)); + return (Color)converter.ConvertFromString(htmlColor); + } + + internal static Color FromBGR(int bgr) + { + Color result = Color.FromArgb(0xFF, (bgr & 0xFF), ((bgr >> 8) & 0xFF), ((bgr >> 16) & 0xFF)); + Color known = KnownColors.FindColorMatch(result); + return (known.IsEmpty) ? result : known; + } + + public static Color FromOle(int oleColor) + { + // OleColor format is BGR + return FromBGR(oleColor); + } + + public static Color FromWin32(int win32Color) + { + // Win32Color format is BGR + return FromBGR(win32Color); + } + + public static string ToHtml(Color c) + { + if (c.IsEmpty) + { + return String.Empty; + } + + if (c.IsSystemColor) + { + KnownColor kc = c.ToKnownColor(); + switch (kc) + { + case KnownColor.ActiveBorder: + case KnownColor.ActiveCaption: + case KnownColor.AppWorkspace: + case KnownColor.GrayText: + case KnownColor.Highlight: + case KnownColor.HighlightText: + case KnownColor.InactiveBorder: + case KnownColor.InactiveCaption: + case KnownColor.InactiveCaptionText: + case KnownColor.InfoText: + case KnownColor.Menu: + case KnownColor.MenuText: + case KnownColor.ScrollBar: + case KnownColor.Window: + case KnownColor.WindowFrame: + case KnownColor.WindowText: + return KnownColors.GetName(kc).ToLowerInvariant(); + + case KnownColor.ActiveCaptionText: + return "captiontext"; + case KnownColor.Control: + return "buttonface"; + case KnownColor.ControlDark: + return "buttonshadow"; + case KnownColor.ControlDarkDark: + return "threeddarkshadow"; + case KnownColor.ControlLight: + return "buttonface"; + case KnownColor.ControlLightLight: + return "buttonhighlight"; + case KnownColor.ControlText: + return "buttontext"; + case KnownColor.Desktop: + return "background"; + case KnownColor.HotTrack: + return "highlight"; + case KnownColor.Info: + return "infobackground"; + + default: + return String.Empty; + } + } + + if (c.IsNamedColor) + { + if (c == Color.LightGray) + { + return "LightGrey"; + } + else + { + return c.Name; + } + } + + return FormatHtml(c.R, c.G, c.B); + } + + static char GetHexNumber(int b) + { + return (char)(b > 9 ? 55 + b : 48 + b); + } + + static string FormatHtml(int r, int g, int b) + { + char[] htmlColor = new char[7]; + htmlColor[0] = '#'; + htmlColor[1] = GetHexNumber((r >> 4) & 15); + htmlColor[2] = GetHexNumber(r & 15); + htmlColor[3] = GetHexNumber((g >> 4) & 15); + htmlColor[4] = GetHexNumber(g & 15); + htmlColor[5] = GetHexNumber((b >> 4) & 15); + htmlColor[6] = GetHexNumber(b & 15); + + return new string(htmlColor); + } + + public static int ToOle(Color c) + { + // OleColor format is BGR, same as Win32 + return ((c.B << 16) | (c.G << 8) | c.R); + } + + public static int ToWin32(Color c) + { + // Win32Color format is BGR, Same as OleColor + return ((c.B << 16) | (c.G << 8) | c.R); + } + } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/KnownColors.cs b/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/KnownColors.cs index 049bd397d..ebc2d81b9 100644 --- a/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/KnownColors.cs +++ b/unturned/OpenMod.Unturned.Module.Shared/System.Drawing/KnownColors.cs @@ -38,434 +38,453 @@ namespace System.Drawing { - internal static partial class KnownColors - { - static internal uint[] ArgbValues = new uint[] { - 0x00000000, /* 000 - Empty */ - 0xFFD4D0C8, /* 001 - ActiveBorder */ - 0xFF0054E3, /* 002 - ActiveCaption */ - 0xFFFFFFFF, /* 003 - ActiveCaptionText */ - 0xFF808080, /* 004 - AppWorkspace */ - 0xFFECE9D8, /* 005 - Control */ - 0xFFACA899, /* 006 - ControlDark */ - 0xFF716F64, /* 007 - ControlDarkDark */ - 0xFFF1EFE2, /* 008 - ControlLight */ - 0xFFFFFFFF, /* 009 - ControlLightLight */ - 0xFF000000, /* 010 - ControlText */ - 0xFF004E98, /* 011 - Desktop */ - 0xFFACA899, /* 012 - GrayText */ - 0xFF316AC5, /* 013 - Highlight */ - 0xFFFFFFFF, /* 014 - HighlightText */ - 0xFF000080, /* 015 - HotTrack */ - 0xFFD4D0C8, /* 016 - InactiveBorder */ - 0xFF7A96DF, /* 017 - InactiveCaption */ - 0xFFD8E4F8, /* 018 - InactiveCaptionText */ - 0xFFFFFFE1, /* 019 - Info */ - 0xFF000000, /* 020 - InfoText */ - 0xFFFFFFFF, /* 021 - Menu */ - 0xFF000000, /* 022 - MenuText */ - 0xFFD4D0C8, /* 023 - ScrollBar */ - 0xFFFFFFFF, /* 024 - Window */ - 0xFF000000, /* 025 - WindowFrame */ - 0xFF000000, /* 026 - WindowText */ - 0x00FFFFFF, /* 027 - Transparent */ - 0xFFF0F8FF, /* 028 - AliceBlue */ - 0xFFFAEBD7, /* 029 - AntiqueWhite */ - 0xFF00FFFF, /* 030 - Aqua */ - 0xFF7FFFD4, /* 031 - Aquamarine */ - 0xFFF0FFFF, /* 032 - Azure */ - 0xFFF5F5DC, /* 033 - Beige */ - 0xFFFFE4C4, /* 034 - Bisque */ - 0xFF000000, /* 035 - Black */ - 0xFFFFEBCD, /* 036 - BlanchedAlmond */ - 0xFF0000FF, /* 037 - Blue */ - 0xFF8A2BE2, /* 038 - BlueViolet */ - 0xFFA52A2A, /* 039 - Brown */ - 0xFFDEB887, /* 040 - BurlyWood */ - 0xFF5F9EA0, /* 041 - CadetBlue */ - 0xFF7FFF00, /* 042 - Chartreuse */ - 0xFFD2691E, /* 043 - Chocolate */ - 0xFFFF7F50, /* 044 - Coral */ - 0xFF6495ED, /* 045 - CornflowerBlue */ - 0xFFFFF8DC, /* 046 - Cornsilk */ - 0xFFDC143C, /* 047 - Crimson */ - 0xFF00FFFF, /* 048 - Cyan */ - 0xFF00008B, /* 049 - DarkBlue */ - 0xFF008B8B, /* 050 - DarkCyan */ - 0xFFB8860B, /* 051 - DarkGoldenrod */ - 0xFFA9A9A9, /* 052 - DarkGray */ - 0xFF006400, /* 053 - DarkGreen */ - 0xFFBDB76B, /* 054 - DarkKhaki */ - 0xFF8B008B, /* 055 - DarkMagenta */ - 0xFF556B2F, /* 056 - DarkOliveGreen */ - 0xFFFF8C00, /* 057 - DarkOrange */ - 0xFF9932CC, /* 058 - DarkOrchid */ - 0xFF8B0000, /* 059 - DarkRed */ - 0xFFE9967A, /* 060 - DarkSalmon */ - 0xFF8FBC8B, /* 061 - DarkSeaGreen */ - 0xFF483D8B, /* 062 - DarkSlateBlue */ - 0xFF2F4F4F, /* 063 - DarkSlateGray */ - 0xFF00CED1, /* 064 - DarkTurquoise */ - 0xFF9400D3, /* 065 - DarkViolet */ - 0xFFFF1493, /* 066 - DeepPink */ - 0xFF00BFFF, /* 067 - DeepSkyBlue */ - 0xFF696969, /* 068 - DimGray */ - 0xFF1E90FF, /* 069 - DodgerBlue */ - 0xFFB22222, /* 070 - Firebrick */ - 0xFFFFFAF0, /* 071 - FloralWhite */ - 0xFF228B22, /* 072 - ForestGreen */ - 0xFFFF00FF, /* 073 - Fuchsia */ - 0xFFDCDCDC, /* 074 - Gainsboro */ - 0xFFF8F8FF, /* 075 - GhostWhite */ - 0xFFFFD700, /* 076 - Gold */ - 0xFFDAA520, /* 077 - Goldenrod */ - 0xFF808080, /* 078 - Gray */ - 0xFF008000, /* 079 - Green */ - 0xFFADFF2F, /* 080 - GreenYellow */ - 0xFFF0FFF0, /* 081 - Honeydew */ - 0xFFFF69B4, /* 082 - HotPink */ - 0xFFCD5C5C, /* 083 - IndianRed */ - 0xFF4B0082, /* 084 - Indigo */ - 0xFFFFFFF0, /* 085 - Ivory */ - 0xFFF0E68C, /* 086 - Khaki */ - 0xFFE6E6FA, /* 087 - Lavender */ - 0xFFFFF0F5, /* 088 - LavenderBlush */ - 0xFF7CFC00, /* 089 - LawnGreen */ - 0xFFFFFACD, /* 090 - LemonChiffon */ - 0xFFADD8E6, /* 091 - LightBlue */ - 0xFFF08080, /* 092 - LightCoral */ - 0xFFE0FFFF, /* 093 - LightCyan */ - 0xFFFAFAD2, /* 094 - LightGoldenrodYellow */ - 0xFFD3D3D3, /* 095 - LightGray */ - 0xFF90EE90, /* 096 - LightGreen */ - 0xFFFFB6C1, /* 097 - LightPink */ - 0xFFFFA07A, /* 098 - LightSalmon */ - 0xFF20B2AA, /* 099 - LightSeaGreen */ - 0xFF87CEFA, /* 100 - LightSkyBlue */ - 0xFF778899, /* 101 - LightSlateGray */ - 0xFFB0C4DE, /* 102 - LightSteelBlue */ - 0xFFFFFFE0, /* 103 - LightYellow */ - 0xFF00FF00, /* 104 - Lime */ - 0xFF32CD32, /* 105 - LimeGreen */ - 0xFFFAF0E6, /* 106 - Linen */ - 0xFFFF00FF, /* 107 - Magenta */ - 0xFF800000, /* 108 - Maroon */ - 0xFF66CDAA, /* 109 - MediumAquamarine */ - 0xFF0000CD, /* 110 - MediumBlue */ - 0xFFBA55D3, /* 111 - MediumOrchid */ - 0xFF9370DB, /* 112 - MediumPurple */ - 0xFF3CB371, /* 113 - MediumSeaGreen */ - 0xFF7B68EE, /* 114 - MediumSlateBlue */ - 0xFF00FA9A, /* 115 - MediumSpringGreen */ - 0xFF48D1CC, /* 116 - MediumTurquoise */ - 0xFFC71585, /* 117 - MediumVioletRed */ - 0xFF191970, /* 118 - MidnightBlue */ - 0xFFF5FFFA, /* 119 - MintCream */ - 0xFFFFE4E1, /* 120 - MistyRose */ - 0xFFFFE4B5, /* 121 - Moccasin */ - 0xFFFFDEAD, /* 122 - NavajoWhite */ - 0xFF000080, /* 123 - Navy */ - 0xFFFDF5E6, /* 124 - OldLace */ - 0xFF808000, /* 125 - Olive */ - 0xFF6B8E23, /* 126 - OliveDrab */ - 0xFFFFA500, /* 127 - Orange */ - 0xFFFF4500, /* 128 - OrangeRed */ - 0xFFDA70D6, /* 129 - Orchid */ - 0xFFEEE8AA, /* 130 - PaleGoldenrod */ - 0xFF98FB98, /* 131 - PaleGreen */ - 0xFFAFEEEE, /* 132 - PaleTurquoise */ - 0xFFDB7093, /* 133 - PaleVioletRed */ - 0xFFFFEFD5, /* 134 - PapayaWhip */ - 0xFFFFDAB9, /* 135 - PeachPuff */ - 0xFFCD853F, /* 136 - Peru */ - 0xFFFFC0CB, /* 137 - Pink */ - 0xFFDDA0DD, /* 138 - Plum */ - 0xFFB0E0E6, /* 139 - PowderBlue */ - 0xFF800080, /* 140 - Purple */ - 0xFFFF0000, /* 141 - Red */ - 0xFFBC8F8F, /* 142 - RosyBrown */ - 0xFF4169E1, /* 143 - RoyalBlue */ - 0xFF8B4513, /* 144 - SaddleBrown */ - 0xFFFA8072, /* 145 - Salmon */ - 0xFFF4A460, /* 146 - SandyBrown */ - 0xFF2E8B57, /* 147 - SeaGreen */ - 0xFFFFF5EE, /* 148 - SeaShell */ - 0xFFA0522D, /* 149 - Sienna */ - 0xFFC0C0C0, /* 150 - Silver */ - 0xFF87CEEB, /* 151 - SkyBlue */ - 0xFF6A5ACD, /* 152 - SlateBlue */ - 0xFF708090, /* 153 - SlateGray */ - 0xFFFFFAFA, /* 154 - Snow */ - 0xFF00FF7F, /* 155 - SpringGreen */ - 0xFF4682B4, /* 156 - SteelBlue */ - 0xFFD2B48C, /* 157 - Tan */ - 0xFF008080, /* 158 - Teal */ - 0xFFD8BFD8, /* 159 - Thistle */ - 0xFFFF6347, /* 160 - Tomato */ - 0xFF40E0D0, /* 161 - Turquoise */ - 0xFFEE82EE, /* 162 - Violet */ - 0xFFF5DEB3, /* 163 - Wheat */ - 0xFFFFFFFF, /* 164 - White */ - 0xFFF5F5F5, /* 165 - WhiteSmoke */ - 0xFFFFFF00, /* 166 - Yellow */ - 0xFF9ACD32, /* 167 - YellowGreen */ - 0xFFECE9D8, /* 168 - ButtonFace */ - 0xFFFFFFFF, /* 169 - ButtonHighlight */ - 0xFFACA899, /* 170 - ButtonShadow */ - 0xFF3D95FF, /* 171 - GradientActiveCaption */ - 0xFF9DB9EB, /* 172 - GradientInactiveCaption */ - 0xFFECE9D8, /* 173 - MenuBar */ - 0xFF316AC5, /* 174 - MenuHighlight */ - }; + internal static partial class KnownColors + { + static internal uint[] ArgbValues = new uint[] + { + 0x00000000, /* 000 - Empty */ + 0xFFD4D0C8, /* 001 - ActiveBorder */ + 0xFF0054E3, /* 002 - ActiveCaption */ + 0xFFFFFFFF, /* 003 - ActiveCaptionText */ + 0xFF808080, /* 004 - AppWorkspace */ + 0xFFECE9D8, /* 005 - Control */ + 0xFFACA899, /* 006 - ControlDark */ + 0xFF716F64, /* 007 - ControlDarkDark */ + 0xFFF1EFE2, /* 008 - ControlLight */ + 0xFFFFFFFF, /* 009 - ControlLightLight */ + 0xFF000000, /* 010 - ControlText */ + 0xFF004E98, /* 011 - Desktop */ + 0xFFACA899, /* 012 - GrayText */ + 0xFF316AC5, /* 013 - Highlight */ + 0xFFFFFFFF, /* 014 - HighlightText */ + 0xFF000080, /* 015 - HotTrack */ + 0xFFD4D0C8, /* 016 - InactiveBorder */ + 0xFF7A96DF, /* 017 - InactiveCaption */ + 0xFFD8E4F8, /* 018 - InactiveCaptionText */ + 0xFFFFFFE1, /* 019 - Info */ + 0xFF000000, /* 020 - InfoText */ + 0xFFFFFFFF, /* 021 - Menu */ + 0xFF000000, /* 022 - MenuText */ + 0xFFD4D0C8, /* 023 - ScrollBar */ + 0xFFFFFFFF, /* 024 - Window */ + 0xFF000000, /* 025 - WindowFrame */ + 0xFF000000, /* 026 - WindowText */ + 0x00FFFFFF, /* 027 - Transparent */ + 0xFFF0F8FF, /* 028 - AliceBlue */ + 0xFFFAEBD7, /* 029 - AntiqueWhite */ + 0xFF00FFFF, /* 030 - Aqua */ + 0xFF7FFFD4, /* 031 - Aquamarine */ + 0xFFF0FFFF, /* 032 - Azure */ + 0xFFF5F5DC, /* 033 - Beige */ + 0xFFFFE4C4, /* 034 - Bisque */ + 0xFF000000, /* 035 - Black */ + 0xFFFFEBCD, /* 036 - BlanchedAlmond */ + 0xFF0000FF, /* 037 - Blue */ + 0xFF8A2BE2, /* 038 - BlueViolet */ + 0xFFA52A2A, /* 039 - Brown */ + 0xFFDEB887, /* 040 - BurlyWood */ + 0xFF5F9EA0, /* 041 - CadetBlue */ + 0xFF7FFF00, /* 042 - Chartreuse */ + 0xFFD2691E, /* 043 - Chocolate */ + 0xFFFF7F50, /* 044 - Coral */ + 0xFF6495ED, /* 045 - CornflowerBlue */ + 0xFFFFF8DC, /* 046 - Cornsilk */ + 0xFFDC143C, /* 047 - Crimson */ + 0xFF00FFFF, /* 048 - Cyan */ + 0xFF00008B, /* 049 - DarkBlue */ + 0xFF008B8B, /* 050 - DarkCyan */ + 0xFFB8860B, /* 051 - DarkGoldenrod */ + 0xFFA9A9A9, /* 052 - DarkGray */ + 0xFF006400, /* 053 - DarkGreen */ + 0xFFBDB76B, /* 054 - DarkKhaki */ + 0xFF8B008B, /* 055 - DarkMagenta */ + 0xFF556B2F, /* 056 - DarkOliveGreen */ + 0xFFFF8C00, /* 057 - DarkOrange */ + 0xFF9932CC, /* 058 - DarkOrchid */ + 0xFF8B0000, /* 059 - DarkRed */ + 0xFFE9967A, /* 060 - DarkSalmon */ + 0xFF8FBC8B, /* 061 - DarkSeaGreen */ + 0xFF483D8B, /* 062 - DarkSlateBlue */ + 0xFF2F4F4F, /* 063 - DarkSlateGray */ + 0xFF00CED1, /* 064 - DarkTurquoise */ + 0xFF9400D3, /* 065 - DarkViolet */ + 0xFFFF1493, /* 066 - DeepPink */ + 0xFF00BFFF, /* 067 - DeepSkyBlue */ + 0xFF696969, /* 068 - DimGray */ + 0xFF1E90FF, /* 069 - DodgerBlue */ + 0xFFB22222, /* 070 - Firebrick */ + 0xFFFFFAF0, /* 071 - FloralWhite */ + 0xFF228B22, /* 072 - ForestGreen */ + 0xFFFF00FF, /* 073 - Fuchsia */ + 0xFFDCDCDC, /* 074 - Gainsboro */ + 0xFFF8F8FF, /* 075 - GhostWhite */ + 0xFFFFD700, /* 076 - Gold */ + 0xFFDAA520, /* 077 - Goldenrod */ + 0xFF808080, /* 078 - Gray */ + 0xFF008000, /* 079 - Green */ + 0xFFADFF2F, /* 080 - GreenYellow */ + 0xFFF0FFF0, /* 081 - Honeydew */ + 0xFFFF69B4, /* 082 - HotPink */ + 0xFFCD5C5C, /* 083 - IndianRed */ + 0xFF4B0082, /* 084 - Indigo */ + 0xFFFFFFF0, /* 085 - Ivory */ + 0xFFF0E68C, /* 086 - Khaki */ + 0xFFE6E6FA, /* 087 - Lavender */ + 0xFFFFF0F5, /* 088 - LavenderBlush */ + 0xFF7CFC00, /* 089 - LawnGreen */ + 0xFFFFFACD, /* 090 - LemonChiffon */ + 0xFFADD8E6, /* 091 - LightBlue */ + 0xFFF08080, /* 092 - LightCoral */ + 0xFFE0FFFF, /* 093 - LightCyan */ + 0xFFFAFAD2, /* 094 - LightGoldenrodYellow */ + 0xFFD3D3D3, /* 095 - LightGray */ + 0xFF90EE90, /* 096 - LightGreen */ + 0xFFFFB6C1, /* 097 - LightPink */ + 0xFFFFA07A, /* 098 - LightSalmon */ + 0xFF20B2AA, /* 099 - LightSeaGreen */ + 0xFF87CEFA, /* 100 - LightSkyBlue */ + 0xFF778899, /* 101 - LightSlateGray */ + 0xFFB0C4DE, /* 102 - LightSteelBlue */ + 0xFFFFFFE0, /* 103 - LightYellow */ + 0xFF00FF00, /* 104 - Lime */ + 0xFF32CD32, /* 105 - LimeGreen */ + 0xFFFAF0E6, /* 106 - Linen */ + 0xFFFF00FF, /* 107 - Magenta */ + 0xFF800000, /* 108 - Maroon */ + 0xFF66CDAA, /* 109 - MediumAquamarine */ + 0xFF0000CD, /* 110 - MediumBlue */ + 0xFFBA55D3, /* 111 - MediumOrchid */ + 0xFF9370DB, /* 112 - MediumPurple */ + 0xFF3CB371, /* 113 - MediumSeaGreen */ + 0xFF7B68EE, /* 114 - MediumSlateBlue */ + 0xFF00FA9A, /* 115 - MediumSpringGreen */ + 0xFF48D1CC, /* 116 - MediumTurquoise */ + 0xFFC71585, /* 117 - MediumVioletRed */ + 0xFF191970, /* 118 - MidnightBlue */ + 0xFFF5FFFA, /* 119 - MintCream */ + 0xFFFFE4E1, /* 120 - MistyRose */ + 0xFFFFE4B5, /* 121 - Moccasin */ + 0xFFFFDEAD, /* 122 - NavajoWhite */ + 0xFF000080, /* 123 - Navy */ + 0xFFFDF5E6, /* 124 - OldLace */ + 0xFF808000, /* 125 - Olive */ + 0xFF6B8E23, /* 126 - OliveDrab */ + 0xFFFFA500, /* 127 - Orange */ + 0xFFFF4500, /* 128 - OrangeRed */ + 0xFFDA70D6, /* 129 - Orchid */ + 0xFFEEE8AA, /* 130 - PaleGoldenrod */ + 0xFF98FB98, /* 131 - PaleGreen */ + 0xFFAFEEEE, /* 132 - PaleTurquoise */ + 0xFFDB7093, /* 133 - PaleVioletRed */ + 0xFFFFEFD5, /* 134 - PapayaWhip */ + 0xFFFFDAB9, /* 135 - PeachPuff */ + 0xFFCD853F, /* 136 - Peru */ + 0xFFFFC0CB, /* 137 - Pink */ + 0xFFDDA0DD, /* 138 - Plum */ + 0xFFB0E0E6, /* 139 - PowderBlue */ + 0xFF800080, /* 140 - Purple */ + 0xFFFF0000, /* 141 - Red */ + 0xFFBC8F8F, /* 142 - RosyBrown */ + 0xFF4169E1, /* 143 - RoyalBlue */ + 0xFF8B4513, /* 144 - SaddleBrown */ + 0xFFFA8072, /* 145 - Salmon */ + 0xFFF4A460, /* 146 - SandyBrown */ + 0xFF2E8B57, /* 147 - SeaGreen */ + 0xFFFFF5EE, /* 148 - SeaShell */ + 0xFFA0522D, /* 149 - Sienna */ + 0xFFC0C0C0, /* 150 - Silver */ + 0xFF87CEEB, /* 151 - SkyBlue */ + 0xFF6A5ACD, /* 152 - SlateBlue */ + 0xFF708090, /* 153 - SlateGray */ + 0xFFFFFAFA, /* 154 - Snow */ + 0xFF00FF7F, /* 155 - SpringGreen */ + 0xFF4682B4, /* 156 - SteelBlue */ + 0xFFD2B48C, /* 157 - Tan */ + 0xFF008080, /* 158 - Teal */ + 0xFFD8BFD8, /* 159 - Thistle */ + 0xFFFF6347, /* 160 - Tomato */ + 0xFF40E0D0, /* 161 - Turquoise */ + 0xFFEE82EE, /* 162 - Violet */ + 0xFFF5DEB3, /* 163 - Wheat */ + 0xFFFFFFFF, /* 164 - White */ + 0xFFF5F5F5, /* 165 - WhiteSmoke */ + 0xFFFFFF00, /* 166 - Yellow */ + 0xFF9ACD32, /* 167 - YellowGreen */ + 0xFFECE9D8, /* 168 - ButtonFace */ + 0xFFFFFFFF, /* 169 - ButtonHighlight */ + 0xFFACA899, /* 170 - ButtonShadow */ + 0xFF3D95FF, /* 171 - GradientActiveCaption */ + 0xFF9DB9EB, /* 172 - GradientInactiveCaption */ + 0xFFECE9D8, /* 173 - MenuBar */ + 0xFF316AC5, /* 174 - MenuHighlight */ + }; - static internal string[] Names = { - String.Empty, - "ActiveBorder", - "ActiveCaption", - "ActiveCaptionText", - "AppWorkspace", - "Control", - "ControlDark", - "ControlDarkDark", - "ControlLight", - "ControlLightLight", - "ControlText", - "Desktop", - "GrayText", - "Highlight", - "HighlightText", - "HotTrack", - "InactiveBorder", - "InactiveCaption", - "InactiveCaptionText", - "Info", - "InfoText", - "Menu", - "MenuText", - "ScrollBar", - "Window", - "WindowFrame", - "WindowText", - "Transparent", - "AliceBlue", - "AntiqueWhite", - "Aqua", - "Aquamarine", - "Azure", - "Beige", - "Bisque", - "Black", - "BlanchedAlmond", - "Blue", - "BlueViolet", - "Brown", - "BurlyWood", - "CadetBlue", - "Chartreuse", - "Chocolate", - "Coral", - "CornflowerBlue", - "Cornsilk", - "Crimson", - "Cyan", - "DarkBlue", - "DarkCyan", - "DarkGoldenrod", - "DarkGray", - "DarkGreen", - "DarkKhaki", - "DarkMagenta", - "DarkOliveGreen", - "DarkOrange", - "DarkOrchid", - "DarkRed", - "DarkSalmon", - "DarkSeaGreen", - "DarkSlateBlue", - "DarkSlateGray", - "DarkTurquoise", - "DarkViolet", - "DeepPink", - "DeepSkyBlue", - "DimGray", - "DodgerBlue", - "Firebrick", - "FloralWhite", - "ForestGreen", - "Fuchsia", - "Gainsboro", - "GhostWhite", - "Gold", - "Goldenrod", - "Gray", - "Green", - "GreenYellow", - "Honeydew", - "HotPink", - "IndianRed", - "Indigo", - "Ivory", - "Khaki", - "Lavender", - "LavenderBlush", - "LawnGreen", - "LemonChiffon", - "LightBlue", - "LightCoral", - "LightCyan", - "LightGoldenrodYellow", - "LightGray", - "LightGreen", - "LightPink", - "LightSalmon", - "LightSeaGreen", - "LightSkyBlue", - "LightSlateGray", - "LightSteelBlue", - "LightYellow", - "Lime", - "LimeGreen", - "Linen", - "Magenta", - "Maroon", - "MediumAquamarine", - "MediumBlue", - "MediumOrchid", - "MediumPurple", - "MediumSeaGreen", - "MediumSlateBlue", - "MediumSpringGreen", - "MediumTurquoise", - "MediumVioletRed", - "MidnightBlue", - "MintCream", - "MistyRose", - "Moccasin", - "NavajoWhite", - "Navy", - "OldLace", - "Olive", - "OliveDrab", - "Orange", - "OrangeRed", - "Orchid", - "PaleGoldenrod", - "PaleGreen", - "PaleTurquoise", - "PaleVioletRed", - "PapayaWhip", - "PeachPuff", - "Peru", - "Pink", - "Plum", - "PowderBlue", - "Purple", - "Red", - "RosyBrown", - "RoyalBlue", - "SaddleBrown", - "Salmon", - "SandyBrown", - "SeaGreen", - "SeaShell", - "Sienna", - "Silver", - "SkyBlue", - "SlateBlue", - "SlateGray", - "Snow", - "SpringGreen", - "SteelBlue", - "Tan", - "Teal", - "Thistle", - "Tomato", - "Turquoise", - "Violet", - "Wheat", - "White", - "WhiteSmoke", - "Yellow", - "YellowGreen", - "ButtonFace", - "ButtonHighlight", - "ButtonShadow", - "GradientActiveCaption", - "GradientInactiveCaption", - "MenuBar", - "MenuHighlight" - }; + static internal string[] Names = + { + String.Empty, + "ActiveBorder", + "ActiveCaption", + "ActiveCaptionText", + "AppWorkspace", + "Control", + "ControlDark", + "ControlDarkDark", + "ControlLight", + "ControlLightLight", + "ControlText", + "Desktop", + "GrayText", + "Highlight", + "HighlightText", + "HotTrack", + "InactiveBorder", + "InactiveCaption", + "InactiveCaptionText", + "Info", + "InfoText", + "Menu", + "MenuText", + "ScrollBar", + "Window", + "WindowFrame", + "WindowText", + "Transparent", + "AliceBlue", + "AntiqueWhite", + "Aqua", + "Aquamarine", + "Azure", + "Beige", + "Bisque", + "Black", + "BlanchedAlmond", + "Blue", + "BlueViolet", + "Brown", + "BurlyWood", + "CadetBlue", + "Chartreuse", + "Chocolate", + "Coral", + "CornflowerBlue", + "Cornsilk", + "Crimson", + "Cyan", + "DarkBlue", + "DarkCyan", + "DarkGoldenrod", + "DarkGray", + "DarkGreen", + "DarkKhaki", + "DarkMagenta", + "DarkOliveGreen", + "DarkOrange", + "DarkOrchid", + "DarkRed", + "DarkSalmon", + "DarkSeaGreen", + "DarkSlateBlue", + "DarkSlateGray", + "DarkTurquoise", + "DarkViolet", + "DeepPink", + "DeepSkyBlue", + "DimGray", + "DodgerBlue", + "Firebrick", + "FloralWhite", + "ForestGreen", + "Fuchsia", + "Gainsboro", + "GhostWhite", + "Gold", + "Goldenrod", + "Gray", + "Green", + "GreenYellow", + "Honeydew", + "HotPink", + "IndianRed", + "Indigo", + "Ivory", + "Khaki", + "Lavender", + "LavenderBlush", + "LawnGreen", + "LemonChiffon", + "LightBlue", + "LightCoral", + "LightCyan", + "LightGoldenrodYellow", + "LightGray", + "LightGreen", + "LightPink", + "LightSalmon", + "LightSeaGreen", + "LightSkyBlue", + "LightSlateGray", + "LightSteelBlue", + "LightYellow", + "Lime", + "LimeGreen", + "Linen", + "Magenta", + "Maroon", + "MediumAquamarine", + "MediumBlue", + "MediumOrchid", + "MediumPurple", + "MediumSeaGreen", + "MediumSlateBlue", + "MediumSpringGreen", + "MediumTurquoise", + "MediumVioletRed", + "MidnightBlue", + "MintCream", + "MistyRose", + "Moccasin", + "NavajoWhite", + "Navy", + "OldLace", + "Olive", + "OliveDrab", + "Orange", + "OrangeRed", + "Orchid", + "PaleGoldenrod", + "PaleGreen", + "PaleTurquoise", + "PaleVioletRed", + "PapayaWhip", + "PeachPuff", + "Peru", + "Pink", + "Plum", + "PowderBlue", + "Purple", + "Red", + "RosyBrown", + "RoyalBlue", + "SaddleBrown", + "Salmon", + "SandyBrown", + "SeaGreen", + "SeaShell", + "Sienna", + "Silver", + "SkyBlue", + "SlateBlue", + "SlateGray", + "Snow", + "SpringGreen", + "SteelBlue", + "Tan", + "Teal", + "Thistle", + "Tomato", + "Turquoise", + "Violet", + "Wheat", + "White", + "WhiteSmoke", + "Yellow", + "YellowGreen", + "ButtonFace", + "ButtonHighlight", + "ButtonShadow", + "GradientActiveCaption", + "GradientInactiveCaption", + "MenuBar", + "MenuHighlight" + }; - static Dictionary? argbByName = null; - static Dictionary? nameByArgb = null; + static Dictionary? argbByName = null; + static Dictionary? nameByArgb = null; - internal static Dictionary ArgbByName - { - get - { - if (argbByName == null) - { - argbByName = new Dictionary(); - for (int i = 0; i < ArgbValues.Length; ++i) - argbByName[Names[i]] = ArgbValues[i]; - } - return argbByName; - } - } + internal static Dictionary ArgbByName + { + get + { + if (argbByName == null) + { + argbByName = new Dictionary(); + for (int i = 0; i < ArgbValues.Length; ++i) + { + argbByName[Names[i]] = ArgbValues[i]; + } + } - internal static Dictionary NameByArgb - { - get - { - if (nameByArgb == null) - { - nameByArgb = new Dictionary(); - for (int i = 0; i < Names.Length; ++i) - nameByArgb[ArgbValues[i]] = Names[i]; - } - return nameByArgb; - } - } + return argbByName; + } + } - public static Color FromKnownColor(KnownColor kc) - { - Color c; - short n = (short)kc; - if ((n <= 0) || (n >= ArgbValues.Length)) - c = Color.FromArgb(0); - else - c = Color.FromArgb((int)ArgbValues[n]); - return c; - } + internal static Dictionary NameByArgb + { + get + { + if (nameByArgb == null) + { + nameByArgb = new Dictionary(); + for (int i = 0; i < Names.Length; ++i) + { + nameByArgb[ArgbValues[i]] = Names[i]; + } + } - public static string GetName(short kc) - { - if (kc > 0 && kc < Names.Length) - return Names[kc]; - return String.Empty; - } + return nameByArgb; + } + } - public static string GetName(KnownColor kc) - { - return GetName((short)kc); - } + public static Color FromKnownColor(KnownColor kc) + { + Color c; + short n = (short)kc; + if ((n <= 0) || (n >= ArgbValues.Length)) + { + c = Color.FromArgb(0); + } + else + { + c = Color.FromArgb((int)ArgbValues[n]); + } - public static Color FindColorMatch(Color c) - { - uint argb = (uint)c.ToArgb(); - for (int i = 0; i < KnownColors.ArgbValues.Length; i++) - { - if (argb == KnownColors.ArgbValues[i]) - return KnownColors.FromKnownColor((KnownColor)i); - } - return Color.Empty; - } + return c; + } - // When this method is called, we teach any new color(s) to the Color class - // NOTE: This is called (reflection) by System.Windows.Forms.Theme (this isn't dead code) - public static void Update(int knownColor, int color) - { - ArgbValues[knownColor] = (uint)color; - } - } + public static string GetName(short kc) + { + if (kc > 0 && kc < Names.Length) + { + return Names[kc]; + } + + return String.Empty; + } + + public static string GetName(KnownColor kc) + { + return GetName((short)kc); + } + + public static Color FindColorMatch(Color c) + { + uint argb = (uint)c.ToArgb(); + for (int i = 0; i < KnownColors.ArgbValues.Length; i++) + { + if (argb == KnownColors.ArgbValues[i]) + { + return KnownColors.FromKnownColor((KnownColor)i); + } + } + + return Color.Empty; + } + + // When this method is called, we teach any new color(s) to the Color class + // NOTE: This is called (reflection) by System.Windows.Forms.Theme (this isn't dead code) + public static void Update(int knownColor, int color) + { + ArgbValues[knownColor] = (uint)color; + } + } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned/Building/UnturnedBuildableOwnership.cs b/unturned/OpenMod.Unturned/Building/UnturnedBuildableOwnership.cs index be8e447f4..3cbc4bd82 100644 --- a/unturned/OpenMod.Unturned/Building/UnturnedBuildableOwnership.cs +++ b/unturned/OpenMod.Unturned/Building/UnturnedBuildableOwnership.cs @@ -13,22 +13,22 @@ public class UnturnedBuildableOwnership : IOwnership public bool HasOwner { - get { return PlayerId != 0 || GroupId != 0; } + get => PlayerId != 0 || GroupId != 0; } public string OwnerPlayerId { - get { return PlayerId.ToString(); } + get => PlayerId.ToString(); } public string OwnerGroupId { - get { return GroupId.ToString(); } + get => GroupId.ToString(); } private ulong PlayerId { - get { return m_Barricade?.owner ?? m_Structure!.owner; } + get => m_Barricade?.owner ?? m_Structure!.owner; } private ulong GroupId @@ -49,10 +49,14 @@ public UnturnedBuildableOwnership(StructureData structure) public Task HasAccessAsync(IPlayer player) { if (player is not UnturnedPlayer unturnedPlayer) + { return Task.FromResult(false); + } if (!HasOwner) + { return Task.FromResult(true); + } //Unturned Code to check access @@ -61,12 +65,7 @@ public Task HasAccessAsync(IPlayer player) //EnemyGroup => Always quests.Group (there is not group for steam and other for quests) //This -> barricade obj in example case - if (PlayerId == unturnedPlayer.SteamId.m_SteamID) - { - return Task.FromResult(true); - } - - return Task.FromResult(GroupId != 0 && GroupId == unturnedPlayer.Player.quests.groupID.m_SteamID); + return Task.FromResult(PlayerId == unturnedPlayer.SteamId.m_SteamID || GroupId != 0 && GroupId == unturnedPlayer.Player.quests.groupID.m_SteamID); } } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned/ConfigurationConfigurator.cs b/unturned/OpenMod.Unturned/ConfigurationConfigurator.cs index 8b0ae987e..bd9837a26 100644 --- a/unturned/OpenMod.Unturned/ConfigurationConfigurator.cs +++ b/unturned/OpenMod.Unturned/ConfigurationConfigurator.cs @@ -1,11 +1,13 @@ using Microsoft.Extensions.Configuration; using OpenMod.API.Ioc; -namespace OpenMod.Unturned; -internal class ConfigurationConfigurator : IConfigurationConfigurator +namespace OpenMod.Unturned { - public void ConfigureConfiguration(IOpenModServiceConfigurationContext openModStartupContext, IConfigurationBuilder configurationBuilder) + internal class ConfigurationConfigurator : IConfigurationConfigurator { - configurationBuilder.AddYamlFile("openmod.unturned.yaml", optional: false, reloadOnChange: true); + public void ConfigureConfiguration(IOpenModServiceConfigurationContext openModStartupContext, IConfigurationBuilder configurationBuilder) + { + configurationBuilder.AddYamlFile("openmod.unturned.yaml", optional: false, reloadOnChange: true); + } } } diff --git a/unturned/OpenMod.Unturned/Effects/UnturnedUIEffectKey.cs b/unturned/OpenMod.Unturned/Effects/UnturnedUIEffectKey.cs index 5dcc4ba80..99bce9033 100644 --- a/unturned/OpenMod.Unturned/Effects/UnturnedUIEffectKey.cs +++ b/unturned/OpenMod.Unturned/Effects/UnturnedUIEffectKey.cs @@ -1,4 +1,5 @@ using System; +using JetBrains.Annotations; namespace OpenMod.Unturned.Effects { @@ -15,34 +16,69 @@ namespace OpenMod.Unturned.Effects /// /// The value of the effect key /// + // ReSharper disable once MemberCanBePrivate.Global public readonly short Value; /// /// Checks if this effect key is valid /// - public bool IsValid => Value != Invalid.Value; + [UsedImplicitly] + public bool IsValid + { + get => Value != Invalid.Value; + } - public UnturnedUIEffectKey(short value) => Value = value; + public UnturnedUIEffectKey(short value) + { + Value = value; + } #region Equality, Comparable, ToString, conversions - public bool Equals(UnturnedUIEffectKey other) => Value == other.Value; + public bool Equals(UnturnedUIEffectKey other) + { + return Value == other.Value; + } - public override bool Equals(object? obj) => obj is UnturnedUIEffectKey other && Equals(other); + public override bool Equals(object? obj) + { + return obj is UnturnedUIEffectKey other && Equals(other); + } - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() + { + return Value.GetHashCode(); + } - public static bool operator ==(UnturnedUIEffectKey left, UnturnedUIEffectKey right) => left.Equals(right); + public static bool operator ==(UnturnedUIEffectKey left, UnturnedUIEffectKey right) + { + return left.Equals(right); + } - public static bool operator !=(UnturnedUIEffectKey left, UnturnedUIEffectKey right) => !left.Equals(right); + public static bool operator !=(UnturnedUIEffectKey left, UnturnedUIEffectKey right) + { + return !left.Equals(right); + } - public int CompareTo(UnturnedUIEffectKey other) => Value.CompareTo(other.Value); + public int CompareTo(UnturnedUIEffectKey other) + { + return Value.CompareTo(other.Value); + } - public override string ToString() => Value.ToString(); + public override string ToString() + { + return Value.ToString(); + } - public static explicit operator short(UnturnedUIEffectKey key) => key.Value; + public static explicit operator short(UnturnedUIEffectKey key) + { + return key.Value; + } - public static explicit operator UnturnedUIEffectKey(short value) => new(value); + public static explicit operator UnturnedUIEffectKey(short value) + { + return new UnturnedUIEffectKey(value); + } #endregion } diff --git a/unturned/OpenMod.Unturned/Events/UnturnedEventsActivator.cs b/unturned/OpenMod.Unturned/Events/UnturnedEventsActivator.cs index 79379038e..45d55a4df 100644 --- a/unturned/OpenMod.Unturned/Events/UnturnedEventsActivator.cs +++ b/unturned/OpenMod.Unturned/Events/UnturnedEventsActivator.cs @@ -66,7 +66,10 @@ public void Dispose() private void SubscribePlayer(SteamPlayer player) { - if (player.player == null) return; + if (player.player == null) + { + return; + } foreach (var eventsListener in m_UnturnedEventsListeners.OfType()) { @@ -76,7 +79,10 @@ private void SubscribePlayer(SteamPlayer player) private void UnsubscribePlayer(SteamPlayer player) { - if (player.player == null) return; + if (player.player == null) + { + return; + } foreach (var eventsListener in m_UnturnedEventsListeners.OfType()) { diff --git a/unturned/OpenMod.Unturned/Items/UnturnedInventoryItem.cs b/unturned/OpenMod.Unturned/Items/UnturnedInventoryItem.cs index 00a690abb..6de87bec4 100644 --- a/unturned/OpenMod.Unturned/Items/UnturnedInventoryItem.cs +++ b/unturned/OpenMod.Unturned/Items/UnturnedInventoryItem.cs @@ -14,11 +14,16 @@ public UnturnedInventoryItem(UnturnedPlayerInventory inventory, ItemJar itemJar) Item = new UnturnedItem(itemJar.item, DestroyAsync); } + // ReSharper disable once MemberCanBePrivate.Global public UnturnedPlayerInventory Inventory { get; } + // ReSharper disable once MemberCanBePrivate.Global public ItemJar ItemJar { get; } - IItem IItemInstance.Item => Item; + IItem IItemInstance.Item + { + get => Item; + } public UnturnedItem Item { get; } @@ -45,23 +50,33 @@ async UniTask DestroyTask() { var itemJars = Inventory.Inventory.items[p].items; - if (itemJars == null) continue; + if (itemJars == null) + { + continue; + } index = itemJars.IndexOf(ItemJar); - if (index < 0) continue; + if (index < 0) + { + continue; + } page = p; break; } if (page == null) + { return true; + } Inventory.Inventory.removeItem(page.Value, (byte)index); if (page.Value < PlayerInventory.SLOTS) + { Inventory.Player.equipment.sendSlot(page.Value); + } return true; } diff --git a/unturned/OpenMod.Unturned/Items/UnturnedItem.cs b/unturned/OpenMod.Unturned/Items/UnturnedItem.cs index 5bd75d807..698a4e7f9 100644 --- a/unturned/OpenMod.Unturned/Items/UnturnedItem.cs +++ b/unturned/OpenMod.Unturned/Items/UnturnedItem.cs @@ -10,6 +10,7 @@ public class UnturnedItem : IItem private readonly DestroyItem m_DestroyItem; + // ReSharper disable once MemberCanBePrivate.Global public Item Item { get; } public UnturnedItem(Item item, DestroyItem destroyItem) @@ -20,7 +21,10 @@ public UnturnedItem(Item item, DestroyItem destroyItem) State = new UnturnedItemState(item); } - public string ItemInstanceId => Item.GetHashCode().ToString(); + public string ItemInstanceId + { + get => Item.GetHashCode().ToString(); + } public IItemAsset Asset { get; } @@ -40,8 +44,14 @@ public Task SetItemAmountAsync(double amount) return Task.CompletedTask; } - public Task SetItemDurabilityAsync(double durability) => SetItemQualityAsync(durability); + public Task SetItemDurabilityAsync(double durability) + { + return SetItemQualityAsync(durability); + } - public Task DestroyAsync() => m_DestroyItem(); + public Task DestroyAsync() + { + return m_DestroyItem(); + } } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned/Items/UnturnedItemSpawner.cs b/unturned/OpenMod.Unturned/Items/UnturnedItemSpawner.cs index 859ca6bcb..9420befee 100644 --- a/unturned/OpenMod.Unturned/Items/UnturnedItemSpawner.cs +++ b/unturned/OpenMod.Unturned/Items/UnturnedItemSpawner.cs @@ -27,7 +27,9 @@ public class UnturnedItemSpawner : IItemSpawner } if (inventory is not UnturnedPlayerInventory playerInventory) + { throw new NotSupportedException($"Inventory type not supported: {inventory.GetType().FullName}"); + } var item = CreateItem(parsedItemId, state, out var itemAsset); if (item == null || itemAsset == null) @@ -102,49 +104,63 @@ private bool TryAddItem(ItemAsset itemAsset, Item? item, UnturnedPlayerInventory { case EItemType.BACKPACK: if (player.clothing.backpack != 0) + { break; + } player.clothing.askWearBackpack(item.id, item.quality, item.state, playEffect: true); return true; case EItemType.GLASSES: if (player.clothing.glasses != 0) + { break; + } player.clothing.askWearGlasses(item.id, item.quality, item.state, playEffect: true); return true; case EItemType.HAT: if (player.clothing.hat != 0) + { break; + } player.clothing.askWearHat(item.id, item.quality, item.state, playEffect: true); return true; case EItemType.MASK: if (player.clothing.mask != 0) + { break; + } player.clothing.askWearMask(item.id, item.quality, item.state, playEffect: true); return true; case EItemType.PANTS: if (player.clothing.pants != 0) + { break; + } player.clothing.askWearPants(item.id, item.quality, item.state, playEffect: true); return true; case EItemType.SHIRT: if (player.clothing.shirt != 0) + { break; + } player.clothing.askWearShirt(item.id, item.quality, item.state, playEffect: true); return true; case EItemType.VEST: if (player.clothing.vest != 0) + { break; + } player.clothing.askWearVest(item.id, item.quality, item.state, playEffect: true); return true; @@ -253,7 +269,9 @@ private void ValidateState(IItemState? state) var item = new Item(itemAsset.id, EItemOrigin.ADMIN); if (state is null or NullItemState) + { return item; + } item.state = state.StateData ?? itemAsset.getState(EItemOrigin.ADMIN); /* item.state must not be null */ item.amount = (byte)state.ItemAmount; diff --git a/unturned/OpenMod.Unturned/Level/Events/LevelEventsListener.cs b/unturned/OpenMod.Unturned/Level/Events/LevelEventsListener.cs index 62df56801..9dbe4e07d 100644 --- a/unturned/OpenMod.Unturned/Level/Events/LevelEventsListener.cs +++ b/unturned/OpenMod.Unturned/Level/Events/LevelEventsListener.cs @@ -36,21 +36,33 @@ private void OnPostLevelLoaded(int level) private void OnPreLevelLoaded(int level) { - if (level != SDG.Unturned.Level.BUILD_INDEX_GAME) return; + if (level != SDG.Unturned.Level.BUILD_INDEX_GAME) + { + return; + } + var @event = new UnturnedPreLevelLoadedEvent(); Emit(@event); } private void OnPrePreLevelLoaded(int level) { - if (level != SDG.Unturned.Level.BUILD_INDEX_GAME) return; + if (level != SDG.Unturned.Level.BUILD_INDEX_GAME) + { + return; + } + var @event = new UnturnedPrePreLevelLoadedEvent(); Emit(@event); } private void OnLevelLoaded(int level) { - if (level != SDG.Unturned.Level.BUILD_INDEX_GAME) return; + if (level != SDG.Unturned.Level.BUILD_INDEX_GAME) + { + return; + } + var @event = new UnturnedLevelLoadedEvent(); Emit(@event); } diff --git a/unturned/OpenMod.Unturned/Players/BattlEye/Events/UnturnedBattlEyeKickedEvent.cs b/unturned/OpenMod.Unturned/Players/BattlEye/Events/UnturnedBattlEyeKickedEvent.cs index 82a64077f..c710b3e88 100644 --- a/unturned/OpenMod.Unturned/Players/BattlEye/Events/UnturnedBattlEyeKickedEvent.cs +++ b/unturned/OpenMod.Unturned/Players/BattlEye/Events/UnturnedBattlEyeKickedEvent.cs @@ -1,13 +1,14 @@ using OpenMod.Unturned.Events; -namespace OpenMod.Unturned.Players.BattlEye.Events; - -public class UnturnedBattlEyeKickedEvent : UnturnedPlayerEvent +namespace OpenMod.Unturned.Players.BattlEye.Events { - public string Reason { get; } - - public UnturnedBattlEyeKickedEvent(UnturnedPlayer player, string reason) : base(player) + public class UnturnedBattlEyeKickedEvent : UnturnedPlayerEvent { - Reason = reason; + public string Reason { get; } + + public UnturnedBattlEyeKickedEvent(UnturnedPlayer player, string reason) : base(player) + { + Reason = reason; + } } } diff --git a/unturned/OpenMod.Unturned/Players/BattlEye/Events/UnturnedBattlEyeListener.cs b/unturned/OpenMod.Unturned/Players/BattlEye/Events/UnturnedBattlEyeListener.cs index 36366c8f0..a17cb684c 100644 --- a/unturned/OpenMod.Unturned/Players/BattlEye/Events/UnturnedBattlEyeListener.cs +++ b/unturned/OpenMod.Unturned/Players/BattlEye/Events/UnturnedBattlEyeListener.cs @@ -3,28 +3,30 @@ using OpenMod.Unturned.Players.BattlEye.Events; using SDG.Unturned; -namespace OpenMod.Unturned.Players.BattleEye.Events; -internal class UnturnedBattlEyeListener : UnturnedEventsListener +namespace OpenMod.Unturned.Players.BattleEye.Events { - public UnturnedBattlEyeListener(IServiceProvider serviceProvider) : base(serviceProvider) + internal class UnturnedBattlEyeListener : UnturnedEventsListener { - } + public UnturnedBattlEyeListener(IServiceProvider serviceProvider) : base(serviceProvider) + { + } - public override void Subscribe() - { - Provider.onBattlEyeKick += Provider_onBattlEyeKick; - } + public override void Subscribe() + { + Provider.onBattlEyeKick += Provider_onBattlEyeKick; + } - public override void Unsubscribe() - { - Provider.onBattlEyeKick -= Provider_onBattlEyeKick; - } + public override void Unsubscribe() + { + Provider.onBattlEyeKick -= Provider_onBattlEyeKick; + } - private void Provider_onBattlEyeKick(SteamPlayer client, string reason) - { - var player = GetUnturnedPlayer(client)!; - var @event = new UnturnedBattlEyeKickedEvent(player, reason); + private void Provider_onBattlEyeKick(SteamPlayer client, string reason) + { + var player = GetUnturnedPlayer(client)!; + var @event = new UnturnedBattlEyeKickedEvent(player, reason); - Emit(@event); + Emit(@event); + } } } diff --git a/unturned/OpenMod.Unturned/Players/Chat/Events/ChatEventsListener.cs b/unturned/OpenMod.Unturned/Players/Chat/Events/ChatEventsListener.cs index 2addd61e6..f7f4e2637 100644 --- a/unturned/OpenMod.Unturned/Players/Chat/Events/ChatEventsListener.cs +++ b/unturned/OpenMod.Unturned/Players/Chat/Events/ChatEventsListener.cs @@ -45,7 +45,10 @@ public override void Unsubscribe() private void OnServerSendingMessage(ref string text, ref Color color, SteamPlayer? nativeFromPlayer, SteamPlayer? nativeToPlayer, EChatMode mode, ref string iconURL, ref bool useRichTextFormatting) // lgtm [cs/too-many-ref-parameters] { // If nativeToPlayer is null, this event will be called again for each player - if (nativeToPlayer == null) return; + if (nativeToPlayer == null) + { + return; + } var fromPlayer = GetUnturnedPlayer(nativeFromPlayer); var toPlayer = GetUnturnedPlayer(nativeToPlayer); diff --git a/unturned/OpenMod.Unturned/Players/Equipment/Events/PlayerEquipmentEventsListener.cs b/unturned/OpenMod.Unturned/Players/Equipment/Events/PlayerEquipmentEventsListener.cs index 2f051b884..c4d479fc8 100644 --- a/unturned/OpenMod.Unturned/Players/Equipment/Events/PlayerEquipmentEventsListener.cs +++ b/unturned/OpenMod.Unturned/Players/Equipment/Events/PlayerEquipmentEventsListener.cs @@ -14,8 +14,8 @@ internal class PlayerEquipmentEventsListener : UnturnedPlayerEventsListener { public PlayerEquipmentEventsListener(IServiceProvider serviceProvider) : base(serviceProvider) { - SubscribePlayer(static player => ref player.equipment.onEquipRequested, player => OnEquipRequested); - SubscribePlayer(static player => ref player.equipment.onDequipRequested, player => OnDequipRequested); + SubscribePlayer(static player => ref player.equipment.onEquipRequested, _ => OnEquipRequested); + SubscribePlayer(static player => ref player.equipment.onDequipRequested, _ => OnDequipRequested); } public override void Subscribe() @@ -52,7 +52,7 @@ private void Events_OnItemEquipped(Player nativePlayer) } var inventoryItem = - new UnturnedInventoryItem(player!.Inventory, item); + new UnturnedInventoryItem(player.Inventory, item); var @event = new UnturnedPlayerItemEquippedEvent(player, inventoryItem.Item); Emit(@event); @@ -105,7 +105,9 @@ private void OnDequipRequested(PlayerEquipment equipment, ref bool shouldAllow) var jar = inv.getItem(page, index); if (jar?.item == null) + { return; + } var inventoryItem = new UnturnedInventoryItem(player.Inventory, jar); @@ -132,6 +134,7 @@ private void OnDequipRequested(PlayerEquipment equipment, ref bool shouldAllow) private static class Patches { [HarmonyCleanup] + [UsedImplicitly] public static Exception? Cleanup(Exception ex, MethodBase original) { HarmonyExceptionHandler.ReportCleanupException(typeof(Patches), ex, original); @@ -153,7 +156,9 @@ public static void PreTellEquip(PlayerEquipment __instance, out ushort __state) public static void PostTellEquip(PlayerEquipment __instance, ushort __state) { if (__state == 0 && __instance.itemID == 0) + { return; + } if (__state != 0) { diff --git a/unturned/OpenMod.Unturned/Players/Equipment/Events/UnturnedPlayerPunchEvent.cs b/unturned/OpenMod.Unturned/Players/Equipment/Events/UnturnedPlayerPunchEvent.cs index 162b89667..ee5e1ff48 100644 --- a/unturned/OpenMod.Unturned/Players/Equipment/Events/UnturnedPlayerPunchEvent.cs +++ b/unturned/OpenMod.Unturned/Players/Equipment/Events/UnturnedPlayerPunchEvent.cs @@ -10,7 +10,8 @@ public class UnturnedPlayerPunchEvent : UnturnedPlayerEvent public EPlayerPunch Punch { get; } public UnturnedPlayerPunchEvent(UnturnedPlayer player, EPlayerPunch punch) : base(player) - => Punch = punch; - + { + Punch = punch; + } } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned/Players/Quests/Events/UnturnedPlayerGroupIdChangedEvent.cs b/unturned/OpenMod.Unturned/Players/Quests/Events/UnturnedPlayerGroupIdChangedEvent.cs index acb8d5afb..775865640 100644 --- a/unturned/OpenMod.Unturned/Players/Quests/Events/UnturnedPlayerGroupIdChangedEvent.cs +++ b/unturned/OpenMod.Unturned/Players/Quests/Events/UnturnedPlayerGroupIdChangedEvent.cs @@ -1,18 +1,19 @@ using OpenMod.Unturned.Events; using Steamworks; -namespace OpenMod.Unturned.Players.Quests.Events; - -public class UnturnedPlayerGroupIdChangedEvent : UnturnedPlayerEvent +namespace OpenMod.Unturned.Players.Quests.Events { - public CSteamID OldGroupId { get; } + public class UnturnedPlayerGroupIdChangedEvent : UnturnedPlayerEvent + { + public CSteamID OldGroupId { get; } - public CSteamID NewGroupId { get; } + public CSteamID NewGroupId { get; } - public UnturnedPlayerGroupIdChangedEvent(UnturnedPlayer player, CSteamID oldGroupId, - CSteamID newGroupId) : base(player) - { - OldGroupId = oldGroupId; - NewGroupId = newGroupId; + public UnturnedPlayerGroupIdChangedEvent(UnturnedPlayer player, CSteamID oldGroupId, + CSteamID newGroupId) : base(player) + { + OldGroupId = oldGroupId; + NewGroupId = newGroupId; + } } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned/Players/Quests/Events/UnturnedPlayerGroupOrRankChangedEvent.cs b/unturned/OpenMod.Unturned/Players/Quests/Events/UnturnedPlayerGroupOrRankChangedEvent.cs index eb38b0108..004bd2738 100644 --- a/unturned/OpenMod.Unturned/Players/Quests/Events/UnturnedPlayerGroupOrRankChangedEvent.cs +++ b/unturned/OpenMod.Unturned/Players/Quests/Events/UnturnedPlayerGroupOrRankChangedEvent.cs @@ -2,22 +2,23 @@ using SDG.Unturned; using Steamworks; -namespace OpenMod.Unturned.Players.Quests.Events; - -public class UnturnedPlayerGroupOrRankChangedEvent : UnturnedPlayerEvent +namespace OpenMod.Unturned.Players.Quests.Events { - public CSteamID OldGroupId { get; } - public EPlayerGroupRank OldGroupRank { get; } + public class UnturnedPlayerGroupOrRankChangedEvent : UnturnedPlayerEvent + { + public CSteamID OldGroupId { get; } + public EPlayerGroupRank OldGroupRank { get; } - public CSteamID NewGroupId { get; } - public EPlayerGroupRank NewGroupRank { get; } + public CSteamID NewGroupId { get; } + public EPlayerGroupRank NewGroupRank { get; } - public UnturnedPlayerGroupOrRankChangedEvent(UnturnedPlayer player, CSteamID oldGroupId, - EPlayerGroupRank oldGroupRank, CSteamID newGroupId, EPlayerGroupRank newGroupRank) : base(player) - { - OldGroupId = oldGroupId; - OldGroupRank = oldGroupRank; - NewGroupId = newGroupId; - NewGroupRank = newGroupRank; + public UnturnedPlayerGroupOrRankChangedEvent(UnturnedPlayer player, CSteamID oldGroupId, + EPlayerGroupRank oldGroupRank, CSteamID newGroupId, EPlayerGroupRank newGroupRank) : base(player) + { + OldGroupId = oldGroupId; + OldGroupRank = oldGroupRank; + NewGroupId = newGroupId; + NewGroupRank = newGroupRank; + } } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned/Players/UnturnedPlayer.cs b/unturned/OpenMod.Unturned/Players/UnturnedPlayer.cs index 143166276..e980573a9 100644 --- a/unturned/OpenMod.Unturned/Players/UnturnedPlayer.cs +++ b/unturned/OpenMod.Unturned/Players/UnturnedPlayer.cs @@ -19,6 +19,7 @@ using System.Net; using System.Numerics; using System.Threading.Tasks; +using JetBrains.Annotations; using Vector3 = System.Numerics.Vector3; namespace OpenMod.Unturned.Players @@ -54,10 +55,12 @@ public bool Equals(UnturnedPlayer other) return ReferenceEquals(this, other) || other.SteamId.Equals(SteamId); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is UnturnedPlayer other) + { return Equals(other); + } return false; } @@ -75,22 +78,30 @@ public override int GetHashCode() public string EntityInstanceId { get; } - public bool IsAlive => !PlayerLife.isDead; + public bool IsAlive + { + get => !PlayerLife.isDead; + } - public double MaxHealth => 100;//Unturned Max health + public double MaxHealth + { + get => 100; //Unturned Max health + } - public double Health => PlayerLife.health; + public double Health + { + get => PlayerLife.health; + } public IPAddress? Address { - get - { - return SteamPlayer.getAddress(); - } + get => SteamPlayer.getAddress(); } public Task SetFullHealthAsync() { + return SetFullHealthTask().AsTask(); + async UniTask SetFullHealthTask() { await UniTask.SwitchToMainThread(); @@ -101,12 +112,12 @@ async UniTask SetFullHealthTask() PlayerLife.askEat((byte)MaxHunger); PlayerLife.askDrink((byte)MaxThirst); } - - return SetFullHealthTask().AsTask(); } public Task SetHealthAsync(double health)//This is a Set and NOT a incremental { + return SetHealthTask().AsTask(); + async UniTask SetHealthTask() { if (health < 0 || health > MaxHealth) @@ -124,8 +135,6 @@ async UniTask SetHealthTask() PlayerLife.serverModifyHealth(amount); } - - return SetHealthTask().AsTask(); } public Task DamageAsync(double amount) @@ -176,16 +185,25 @@ async UniTask TeleportationTask() return TeleportationTask().AsTask(); } - public string Stance => Player.stance.stance.ToString().ToLower(CultureInfo.InvariantCulture); + public string Stance + { + get => Player.stance.stance.ToString().ToLower(CultureInfo.InvariantCulture); + } - IInventory IHasInventory.Inventory => Inventory; + IInventory IHasInventory.Inventory + { + get => Inventory; + } /// /// Gets the inventory of the player. /// public UnturnedPlayerInventory Inventory { get; } - IVehicle? ICanEnterVehicle.CurrentVehicle => CurrentVehicle; + IVehicle? ICanEnterVehicle.CurrentVehicle + { + get => CurrentVehicle; + } /// /// Gets the current vehicle. Returns null if the player is not a passenger. @@ -201,37 +219,36 @@ async UniTask TeleportationTask() public string DamageSourceName { - get - { - return SteamPlayer.playerID.characterName; - } + get => SteamPlayer.playerID.characterName; } - public double MaxHunger => 100;//Unturned Max hunger + public double MaxHunger + { + get => 100; //Unturned Max hunger + } public double Hunger { - get - { - return PlayerLife.food; - } + get => PlayerLife.food; } - public double MaxThirst => 100;//Unturned Max Thirst + public double MaxThirst + { + get => 100; //Unturned Max Thirst + } public double Thirst { - get - { - return PlayerLife.water; - } + get => PlayerLife.water; } + [UsedImplicitly] public Task PrintMessageAsync(string message) { return PrintMessageAsync(message, Color.White); } + // ReSharper disable once MemberCanBePrivate.Global public Task PrintMessageAsync(string message, Color color) { return PrintMessageAsync(message, color, isRich: true, iconUrl: Provider.configData.Browser.Icon); @@ -244,6 +261,8 @@ public Task PrintMessageAsync(string message, Color color, bool isRich, string i throw new ArgumentNullException(nameof(message)); } + return PrintMessageTask().AsTask(); + async UniTask PrintMessageTask() { var lines = message.Replace(System.Environment.NewLine, "\n").Split('\n').Where(line => line.Trim().Length > 0).ToArray(); @@ -264,8 +283,6 @@ async UniTask PrintMessageTask() useRichTextFormatting: isRich); } } - - return PrintMessageTask().AsTask(); } public Task SetHungerAsync(double hunger)//This is a Set and NOT a incremental diff --git a/unturned/OpenMod.Unturned/RocketMod/Permissions/RocketCooldownPermissionCheckProvider.cs b/unturned/OpenMod.Unturned/RocketMod/Permissions/RocketCooldownPermissionCheckProvider.cs index b34f4cd6f..172a33fd7 100644 --- a/unturned/OpenMod.Unturned/RocketMod/Permissions/RocketCooldownPermissionCheckProvider.cs +++ b/unturned/OpenMod.Unturned/RocketMod/Permissions/RocketCooldownPermissionCheckProvider.cs @@ -61,12 +61,16 @@ public Task CheckPermissionAsync(IPermissionActor actor, } if (permissions.All(pm => !string.Equals(pm.Name?.Trim(), permission, StringComparison.OrdinalIgnoreCase))) + { return Task.FromResult(PermissionGrantResult.Default); + } var rocketPermission = permissions.Find(knownPermission => string.Equals(knownPermission.Name?.Trim(), permission, StringComparison.OrdinalIgnoreCase)); if (rocketPermission == null) + { return Task.FromResult(PermissionGrantResult.Default); + } permissionCooldown[permission] = DateTime.UtcNow.AddSeconds(rocketPermission.Cooldown); m_Cooldowns[actor.Id] = permissionCooldown; diff --git a/unturned/OpenMod.Unturned/RocketMod/Rcon/RocketModRconClient.cs b/unturned/OpenMod.Unturned/RocketMod/Rcon/RocketModRconClient.cs index d3b4b28d9..9c9a71773 100644 --- a/unturned/OpenMod.Unturned/RocketMod/Rcon/RocketModRconClient.cs +++ b/unturned/OpenMod.Unturned/RocketMod/Rcon/RocketModRconClient.cs @@ -127,12 +127,17 @@ protected virtual Task ProcessPacketAsync(RocketModRconPacket packet) { try { - if (string.IsNullOrEmpty(packet.Body)) return Task.CompletedTask; + if (string.IsNullOrEmpty(packet.Body)) + { + return Task.CompletedTask; + } var arguments = packet.Body!.Split(' '); var command = arguments.Length == 1 ? packet.Body : arguments.First(); if (command.Equals("login", StringComparison.InvariantCulture) && !IsAuthenticated) + { return ProcessLoginAsync(packet); + } return OnExecuteCommandAsync(packet.Body!); } @@ -182,7 +187,10 @@ private bool ProcessRocketModLogin(RocketModRconPacket packet) var password = string.Join(" ", packet.Body!.Split(' ').Skip(count: 1)); var rocketPassword = R.Settings.Instance.RCON.Password.Trim(); - if (rocketPassword.Equals("changeme", StringComparison.Ordinal)) return false; + if (rocketPassword.Equals("changeme", StringComparison.Ordinal)) + { + return false; + } return string.Equals(password, rocketPassword, StringComparison.InvariantCulture); } diff --git a/unturned/OpenMod.Unturned/Users/UnturnedUserProvider.cs b/unturned/OpenMod.Unturned/Users/UnturnedUserProvider.cs index c4ad29ca4..d2b0885f3 100644 --- a/unturned/OpenMod.Unturned/Users/UnturnedUserProvider.cs +++ b/unturned/OpenMod.Unturned/Users/UnturnedUserProvider.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using Cysharp.Threading.Tasks; +using JetBrains.Annotations; using OpenMod.API; using OpenMod.API.Eventing; using OpenMod.API.Localization; @@ -19,6 +20,7 @@ namespace OpenMod.Unturned.Users { [Priority(Priority = Priority.Low)] + [UsedImplicitly] public class UnturnedUserProvider : IUserProvider, IDisposable { private readonly HashSet m_Users; @@ -122,11 +124,13 @@ public virtual UnturnedUser GetUser(Player player) return GetUser(player.channel.owner); } + // ReSharper disable once MemberCanBeProtected.Global public virtual UnturnedUser GetUser(SteamPlayer player) { return GetUser(player.playerID.steamID)!; } + // ReSharper disable once MemberCanBeProtected.Global public virtual UnturnedUser? GetUser(CSteamID id) { return m_Users.FirstOrDefault(d => d.SteamId == id); @@ -254,10 +258,15 @@ public bool SupportsUserType(string userType) case UserSearchMode.FindByNameOrId: case UserSearchMode.FindById: if (user.Id.Equals(searchString, StringComparison.OrdinalIgnoreCase)) + { return Task.FromResult((IUser?)user); + } if (searchMode == UserSearchMode.FindByNameOrId) + { goto case UserSearchMode.FindByName; + } + break; case UserSearchMode.FindByName: @@ -284,17 +293,26 @@ private int NameConfidence(string userName, string searchName, int currentConfid { case 2: if (userName.Equals(searchName, StringComparison.OrdinalIgnoreCase)) + { return 3; + } + goto case 1; case 1: if (userName.StartsWith(searchName, StringComparison.OrdinalIgnoreCase)) + { return 2; + } + goto case 0; case 0: if (userName.IndexOf(searchName, StringComparison.OrdinalIgnoreCase) != -1) + { return 1; + } + break; default: @@ -325,8 +343,12 @@ public Task BroadcastAsync(string message, System.Drawing.Color? color) return BroadcastAsync(message, color, isRich: true, iconUrl: Provider.configData.Browser.Icon); } + // ReSharper disable once MemberCanBePrivate.Global + // ReSharper disable once MemberCanBeMadeStatic.Global public Task BroadcastAsync(string message, System.Drawing.Color? color, bool isRich, string iconUrl) { + return BroadcastTask().AsTask(); + async UniTask BroadcastTask() { await UniTask.SwitchToMainThread(); @@ -335,8 +357,6 @@ async UniTask BroadcastTask() ChatManager.serverSendMessage(text: message, color: color.Value.ToUnityColor(), useRichTextFormatting: isRich, iconURL: iconUrl); } - - return BroadcastTask().AsTask(); } public Task BanAsync(IUser user, string? reason = null, DateTime? expireDate = null) @@ -350,7 +370,9 @@ public async Task BanAsync(IUser user, IUser? instigator = null, string? r var duration = (expireDate.Value - DateTime.Now).TotalSeconds; if (duration <= 0) + { return false; + } reason ??= m_StringLocalizer["ban_default"]; var data = await m_UserDataStore.GetUserDataAsync(user.Id, user.Type); diff --git a/unturned/OpenMod.Unturned/Vehicles/UnturnedVehicleSpawner.cs b/unturned/OpenMod.Unturned/Vehicles/UnturnedVehicleSpawner.cs index bc4dde15e..397cad9f8 100644 --- a/unturned/OpenMod.Unturned/Vehicles/UnturnedVehicleSpawner.cs +++ b/unturned/OpenMod.Unturned/Vehicles/UnturnedVehicleSpawner.cs @@ -49,7 +49,9 @@ public class UnturnedVehicleSpawner : IVehicleSpawner false, fuel, health, batteryCharge, owner, group, locked, turrets, tireAliveMask); if (iVehicle == null) + { return vehicle; + } vehicle = new UnturnedVehicle(iVehicle); if (itemBatteryId != Guid.Empty) @@ -58,7 +60,9 @@ public class UnturnedVehicleSpawner : IVehicleSpawner } if (items == null) + { return vehicle; + } foreach (var item in items) { @@ -91,7 +95,7 @@ public class UnturnedVehicleSpawner : IVehicleSpawner var forward = (Vector3.UnitZ * 6).Rotate(rotation); position += forward; - + Physics.Raycast((position + Vector3.UnitY * 16f).ToUnityVector(), UVector3.down, out var raycastHit, 32f, RayMasks.BLOCK_VEHICLE); if (raycastHit.collider != null) { @@ -127,7 +131,7 @@ public class UnturnedVehicleSpawner : IVehicleSpawner fuel = reader.ReadUInt16(); health = reader.ReadUInt16(); batteryCharge = reader.ReadUInt16(); - + if (version >= UnturnedVehicleState.SaveDataVersionBatteryGuid) { var guidBuffer = new byte[16]; @@ -177,7 +181,9 @@ public class UnturnedVehicleSpawner : IVehicleSpawner _ = reader.Read(state, 0, stateLength); if (Assets.find(EAssetType.ITEM, id) is not ItemAsset) + { continue; + } var item = new Item(id, amount, quality, state); items[b] = new ItemJar(x, y, rot, item); From e015365d4dacae97a74f901a77d20e7134d2e29d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BAben=20Garcia?= Date: Wed, 24 Apr 2024 02:32:41 +0100 Subject: [PATCH 2/3] Enforce brackets and refactor some code --- .../Helpers/AssemblyNameEqualityComparer.cs | 33 +- .../Cooldowns/CommandCooldownStore.cs | 63 ++-- .../OpenMod.Core/Helpers/TimeSpanHelper.cs | 15 +- .../Localization/SmartFormatOptions.cs | 283 +++++++++--------- .../Permissions/DefaultPermissionRoleStore.cs | 50 ++-- .../PackageDependencyComparerSlim.cs | 24 +- .../Events/UnturnedPlayerEventsListener.cs | 143 ++++----- .../Mono/Patch_SocketTaskExtensions.cs | 128 ++++---- .../Users/UnturnedPendingUser.cs | 35 ++- .../Vehicles/UnturnedVehicleOwnership.cs | 9 +- 10 files changed, 406 insertions(+), 377 deletions(-) diff --git a/framework/OpenMod.Common/Helpers/AssemblyNameEqualityComparer.cs b/framework/OpenMod.Common/Helpers/AssemblyNameEqualityComparer.cs index ec149153a..9a2e389fc 100644 --- a/framework/OpenMod.Common/Helpers/AssemblyNameEqualityComparer.cs +++ b/framework/OpenMod.Common/Helpers/AssemblyNameEqualityComparer.cs @@ -3,34 +3,25 @@ using System.Reflection; using System.Text; -namespace OpenMod.Common.Helpers; - -/// -/// Comparer of that comparers the name -/// -public sealed class AssemblyNameEqualityComparer : IEqualityComparer +namespace OpenMod.Common.Helpers { - public static AssemblyNameEqualityComparer Instance { get; } = new(); + /// + /// Comparer of that comparers the name + /// + public sealed class AssemblyNameEqualityComparer : IEqualityComparer + { + public static AssemblyNameEqualityComparer Instance { get; } = new(); - private AssemblyNameEqualityComparer() { } + private AssemblyNameEqualityComparer() { } - public bool Equals(AssemblyName x, AssemblyName y) - { - if (x == y) + public bool Equals(AssemblyName? x, AssemblyName? y) { - return true; + return string.Equals(x?.Name, y?.Name, StringComparison.OrdinalIgnoreCase); } - if (x == null || y == null) + public int GetHashCode(AssemblyName obj) { - return false; + return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Name); } - - return x.Name.Equals(y.Name, StringComparison.OrdinalIgnoreCase); - } - - public int GetHashCode(AssemblyName obj) - { - return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Name); } } diff --git a/framework/OpenMod.Core/Cooldowns/CommandCooldownStore.cs b/framework/OpenMod.Core/Cooldowns/CommandCooldownStore.cs index 4d1e641a1..8fd03ade7 100644 --- a/framework/OpenMod.Core/Cooldowns/CommandCooldownStore.cs +++ b/framework/OpenMod.Core/Cooldowns/CommandCooldownStore.cs @@ -111,22 +111,41 @@ private string GetActorFullId(ICommandActor actor) private async Task LoadPersistedRecords(bool force = false) { - if (m_LoadedPersistedRecords && !force) return; + if (m_LoadedPersistedRecords && !force) + { + return; + } + m_LoadedPersistedRecords = true; - if (m_DataStore == null) return; + if (m_DataStore == null) + { + return; + } - if (!m_Configuration.GetValue("cooldowns:reloadPersistence", true)) return; + if (!m_Configuration.GetValue("cooldowns:reloadPersistence", true)) + { + return; + } - if (!await m_DataStore.ExistsAsync("cooldowns")) return; + if (!await m_DataStore.ExistsAsync("cooldowns")) + { + return; + } var persistedRecords = (await m_DataStore.LoadAsync(c_DataStoreKey))?.Records; - if (persistedRecords == null || persistedRecords.Count == 0) return; + if (persistedRecords == null || persistedRecords.Count == 0) + { + return; + } foreach (var pair in persistedRecords) { - if (pair.Value == null || pair.Value.Count == 0) continue; + if (pair.Value == null || pair.Value.Count == 0) + { + continue; + } if (!m_Records.TryGetValue(pair.Key, out var records)) { @@ -135,18 +154,21 @@ private async Task LoadPersistedRecords(bool force = false) m_Records.Add(pair.Key, records); } - foreach (var record in pair.Value) - { - records.Add(record); - } + records.AddRange(pair.Value); } } private async Task SavePersistedRecords() { - if (m_DataStore == null) return; + if (m_DataStore == null) + { + return; + } - if (!m_Configuration.GetValue("cooldowns:reloadPersistence", true)) return; + if (!m_Configuration.GetValue("cooldowns:reloadPersistence", true)) + { + return; + } var persistedRecords = new CooldownRecords(m_Records); @@ -168,22 +190,21 @@ private async Task SavePersistedRecords() await LoadPersistedRecords(); var actorId = GetActorFullId(actor); - if (m_Records.TryGetValue(actorId, out List records)) + if (!m_Records.TryGetValue(actorId, out var records)) { - var record = records.FirstOrDefault(x => x.Command == command); - - if (record != null) - { - return record.Executed; - } + return null; } - return null; + var record = records.FirstOrDefault(x => x.Command == command); + return record?.Executed; } public async Task RecordExecutionAsync(ICommandActor actor, string command, DateTime time) { - if (actor.Type == KnownActorTypes.Console) return; + if (actor.Type == KnownActorTypes.Console) + { + return; + } var actorId = GetActorFullId(actor); if (m_Records.TryGetValue(actorId, out var records)) diff --git a/framework/OpenMod.Core/Helpers/TimeSpanHelper.cs b/framework/OpenMod.Core/Helpers/TimeSpanHelper.cs index d5b9c2ce8..bc245b848 100644 --- a/framework/OpenMod.Core/Helpers/TimeSpanHelper.cs +++ b/framework/OpenMod.Core/Helpers/TimeSpanHelper.cs @@ -28,27 +28,28 @@ public static class TimeSpanHelper public static TimeSpan Parse(string unparsed) { var matches = s_RegexPattern.Matches(unparsed); - - TimeSpan total = new TimeSpan(); - if (matches.Count == 0) { throw new UserFriendlyException("Invalid time span format"); } + var total = new TimeSpan(); foreach (Match match in matches) { - string value = match.Value; + var value = match.Value; int i; for (i = 0; i < value.Length; i++) { - if ((value[i] < '0' || value[i] > '9') && value[i] != '.') break; + if ((value[i] < '0' || value[i] > '9') && value[i] != '.') + { + break; + } } - double num = double.Parse(value.Substring(0, i)); - string suffix = value.Substring(i).Trim(); + var num = double.Parse(value[..i]); + var suffix = value[i..].Trim(); switch (suffix.ToLower()) { diff --git a/framework/OpenMod.Core/Localization/SmartFormatOptions.cs b/framework/OpenMod.Core/Localization/SmartFormatOptions.cs index 3cf17aec0..c870a301a 100644 --- a/framework/OpenMod.Core/Localization/SmartFormatOptions.cs +++ b/framework/OpenMod.Core/Localization/SmartFormatOptions.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using Nito.Disposables.Internals; using OpenMod.Core.Helpers; @@ -9,184 +8,186 @@ using SmartFormat.Core.Settings; using SmartFormat.Utilities; -namespace OpenMod.Core.Localization; -public class SmartFormatOptions +namespace OpenMod.Core.Localization { - private readonly List> m_Formatters; - private readonly List> m_Sources; - private readonly SmartSettings m_SmartSettings; - - // used to check if formatter already initialized, - // if so, it throws an exception when trying to modify options - private bool m_IsInitialized; - - public SmartFormatOptions() + public class SmartFormatOptions { - m_SmartSettings = new SmartSettings(); + private readonly List> m_Formatters; + private readonly List> m_Sources; + private readonly SmartSettings m_SmartSettings; - var defaultFormatter = Smart.Default; + // used to check if formatter already initialized, + // if so, it throws an exception when trying to modify options + private bool m_IsInitialized; - // copy formatters and sources - m_Formatters = new(); - foreach (var formatter in defaultFormatter.GetFormatterExtensions()) + public SmartFormatOptions() { - var formatterType = formatter.GetType(); + m_SmartSettings = new SmartSettings(); - m_Formatters.Add(new(formatterType, factory => + var defaultFormatter = Smart.Default; + + // copy formatters and sources + m_Formatters = new List>(); + foreach (var formatter in defaultFormatter.GetFormatterExtensions()) { - try + var formatterType = formatter.GetType(); + + m_Formatters.Add(new FormatterFactory(formatterType, factory => { - return Activator.CreateInstance(factory.Type) as IFormatter; - } - catch + try + { + return Activator.CreateInstance(factory.Type) as IFormatter; + } + catch + { + return null; + } + })); + } + + m_Sources = new List>(); + foreach (var source in defaultFormatter.GetSourceExtensions()) + { + var sourceType = source.GetType(); + + m_Sources.Add(new FormatterFactory(sourceType, factory => { - return null; - } - })); + try + { + return Activator.CreateInstance(factory.Type) as ISource; + } + catch + { + return null; + } + })); + } + + // Smartformatter will be used in threading, so make sure it is thread safe mode is set + // more info: https://github.com/axuno/SmartFormat/wiki/Async-and-Thread-Safety + SmartSettings.IsThreadSafeMode = true; + + // adds support for custom extensions, but removes the string.Format compatibility + m_SmartSettings.StringFormatCompatibility = false; } - m_Sources = new(); - foreach (var source in defaultFormatter.GetSourceExtensions()) + /// + /// Adds extension to the formatters list + /// + /// + /// , if the extension was added. + public bool TryAddFormatter() where T : class, IFormatter, new() { - var sourceType = source.GetType(); + CheckInitialized(); - m_Sources.Add(new(sourceType, factory => + if (m_Formatters.Any(x => x.Type == typeof(T))) { - try - { - return Activator.CreateInstance(factory.Type) as ISource; - } - catch - { - return null; - } - })); - } + return false; + } - // Smartformatter will be used in threading, so make sure it is thread safe mode is set - // more info: https://github.com/axuno/SmartFormat/wiki/Async-and-Thread-Safety - SmartSettings.IsThreadSafeMode = true; + m_Formatters.Add(new(typeof(T), _ => new T())); + return true; + } - // adds support for custom extensions, but removes the string.Format compatibility - m_SmartSettings.StringFormatCompatibility = false; - } + /// + /// Removes extension from the formatters list + /// + /// + /// , if the extension was removed. + public bool TryRemoveFormatter() where T : class, IFormatter + { + CheckInitialized(); - /// - /// Adds extension to the formatters list - /// - /// - /// , if the extension was added. - public bool TryAddFormatter() where T : class, IFormatter, new() - { - CheckInitialized(); + var index = m_Formatters.FindIndex(f => f.Type == typeof(T)); + if (index == -1) + { + return false; + } - if (m_Formatters.Any(x => x.Type == typeof(T))) - { - return false; + m_Formatters.RemoveAt(index); + return true; } - m_Formatters.Add(new(typeof(T), _ => new T())); - return true; - } + /// + /// Adds extension to the source list + /// + /// + /// , if the extension was added. + public bool TryAddSource() where T : class, ISource, new() + { + CheckInitialized(); - /// - /// Removes extension from the formatters list - /// - /// - /// , if the extension was removed. - public bool TryRemoveFormatter() where T : class, IFormatter - { - CheckInitialized(); + if (m_Sources.Any(x => x.Type == typeof(T))) + { + return false; + } - var index = m_Formatters.FindIndex(f => f.Type == typeof(T)); - if (index == -1) - { - return false; + m_Sources.Add(new(typeof(T), _ => new T())); + return true; } - m_Formatters.RemoveAt(index); - return true; - } + /// + /// Removes extension from the source list + /// + /// + /// , if the extension was removed. + public bool TryRemoveSource() where T : class, ISource + { + CheckInitialized(); - /// - /// Adds extension to the source list - /// - /// - /// , if the extension was added. - public bool TryAddSource() where T : class, ISource, new() - { - CheckInitialized(); + var index = m_Sources.FindIndex(f => f.Type == typeof(T)); + if (index == -1) + { + return false; + } - if (m_Sources.Any(x => x.Type == typeof(T))) - { - return false; + m_Sources.RemoveAt(index); + return true; } - m_Sources.Add(new(typeof(T), _ => new T())); - return true; - } + public void SetLocalizationProvider(ILocalizationProvider? localizationProvider) + { + CheckInitialized(); - /// - /// Removes extension from the source list - /// - /// - /// , if the extension was removed. - public bool TryRemoveSource() where T : class, ISource - { - CheckInitialized(); + m_SmartSettings.Localization.LocalizationProvider = localizationProvider; + } - var index = m_Sources.FindIndex(f => f.Type == typeof(T)); - if (index == -1) + private void CheckInitialized() { - return false; + if (m_IsInitialized) + { + throw new InvalidOperationException("SmartFormatter already initialized"); + } } - m_Sources.RemoveAt(index); - return true; - } - - public void SetLocalizationProvider(ILocalizationProvider? localizationProvider) - { - CheckInitialized(); - - m_SmartSettings.Localization.LocalizationProvider = localizationProvider; - } - - private void CheckInitialized() - { - if (m_IsInitialized) + public SmartFormatter GetSmartFormatter() { - throw new InvalidOperationException("SmartFormatter already initialized"); + return SmartFormatterHelper.ObtainSmartFormatter(this); } - } - - public SmartFormatter GetSmartFormatter() - { - return SmartFormatterHelper.ObtainSmartFormatter(this); - } - - internal SmartFormatter CreateSmartFormatter() - { - m_IsInitialized = true; - - return new SmartFormatter(m_SmartSettings) - .AddExtensions(m_Sources.Select(x => x.Factory(x)) - .WhereNotNull() - .ToArray()) - .AddExtensions(m_Formatters.Select(x => x.Factory(x)) - .WhereNotNull() - .ToArray()); - } - private sealed class FormatterFactory - { - public Func, T?> Factory { get; } - public Type Type { get; } + internal SmartFormatter CreateSmartFormatter() + { + m_IsInitialized = true; + + return new SmartFormatter(m_SmartSettings) + .AddExtensions(m_Sources.Select(x => x.Factory(x)) + .WhereNotNull() + .ToArray()) + .AddExtensions(m_Formatters.Select(x => x.Factory(x)) + .WhereNotNull() + .ToArray()); + } - public FormatterFactory(Type type, Func, T?> factory) + private sealed class FormatterFactory { - Factory = factory; - Type = type; + public Func, T?> Factory { get; } + public Type Type { get; } + + public FormatterFactory(Type type, Func, T?> factory) + { + Factory = factory; + Type = type; + } } } } diff --git a/framework/OpenMod.Core/Permissions/DefaultPermissionRoleStore.cs b/framework/OpenMod.Core/Permissions/DefaultPermissionRoleStore.cs index d3b252cdb..a4020e1eb 100644 --- a/framework/OpenMod.Core/Permissions/DefaultPermissionRoleStore.cs +++ b/framework/OpenMod.Core/Permissions/DefaultPermissionRoleStore.cs @@ -51,19 +51,28 @@ public virtual async Task> GetRolesAsync(IP roleIds.Add(role.Id); if (!inherit) + { return roles; + } // ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator foreach (var parentRoleId in role.Parents) { - if (string.IsNullOrEmpty(parentRoleId)) continue; + if (string.IsNullOrEmpty(parentRoleId)) + { + continue; + } if (roleIds.Contains(parentRoleId)) + { continue; + } var parentRole = await GetRoleAsync(parentRoleId); if (parentRole == null) + { continue; + } roles.Add(parentRole); roleIds.Add(parentRoleId); @@ -81,7 +90,10 @@ public virtual async Task> GetRolesAsync(IP // ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator foreach (var roleId in userData.Roles) { - if (string.IsNullOrEmpty(roleId)) continue; + if (string.IsNullOrEmpty(roleId)) + { + continue; + } if (roleIds.Contains(roleId)) { @@ -90,25 +102,36 @@ public virtual async Task> GetRolesAsync(IP var userRole = await GetRoleAsync(roleId); if (userRole == null) + { continue; + } roles.Add(userRole); roleIds.Add(roleId); if (!inherit) + { continue; + } // ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator foreach (var parentRoleId in userRole.Parents) { - if (string.IsNullOrEmpty(parentRoleId)) continue; + if (string.IsNullOrEmpty(parentRoleId)) + { + continue; + } if (roleIds.Contains(parentRoleId)) + { continue; + } var parentRole = await GetRoleAsync(parentRoleId); if (parentRole == null) + { continue; + } roles.Add(parentRole); roleIds.Add(parentRoleId); @@ -193,15 +216,12 @@ public virtual async Task AddRoleToActorAsync(IPermissionActor actor, stri } userData.Roles ??= new HashSet(); - if (userData.Roles.Contains(roleId)) + if (!userData.Roles.Add(roleId)) { return true; } - userData.Roles.Add(roleId); - await m_UserDataStore.SetUserDataAsync(userData); - await m_EventBus.EmitAsync(m_Runtime, this, new PermissionActorRoleAddedEvent(actor, roleId)); return true; @@ -310,19 +330,8 @@ public async Task SavePersistentDataAsync(string roleId, string key, T? data) throw new Exception($"Role does not exist: {roleId}"); } - if(roleData.Data == null) - { - roleData.Data = new Dictionary(); - } - - if (roleData.Data.ContainsKey(key)) - { - roleData.Data[key] = data; - } - else - { - roleData.Data.Add(key, data); - } + roleData.Data ??= new Dictionary(); + roleData.Data[key] = data; await m_PermissionRolesDataStore.SaveChangesAsync(); } @@ -342,6 +351,7 @@ public async Task SavePersistentDataAsync(string roleId, string key, T? data) return m_PermissionRolesDataStore.GetRoleDataAsync(roleId, key); } + // ReSharper disable once MemberCanBePrivate.Global protected IEnumerable GetAutoAssignRoles() { // cast is necessary, OfType<> or Cast<> does not work with cast operators diff --git a/framework/OpenMod.NuGet/PackageDependencyComparerSlim.cs b/framework/OpenMod.NuGet/PackageDependencyComparerSlim.cs index c02f30673..860996028 100644 --- a/framework/OpenMod.NuGet/PackageDependencyComparerSlim.cs +++ b/framework/OpenMod.NuGet/PackageDependencyComparerSlim.cs @@ -2,23 +2,21 @@ using System.Collections.Generic; using NuGet.Packaging.Core; -namespace OpenMod.NuGet; -internal sealed class PackageDependencyComparerSlim : IEqualityComparer +namespace OpenMod.NuGet { - public static PackageDependencyComparerSlim Default { get; } = new(); - - public bool Equals(PackageDependency x, PackageDependency y) + internal sealed class PackageDependencyComparerSlim : IEqualityComparer { - if (x == y) + public static PackageDependencyComparerSlim Default { get; } = new(); + + /// + public bool Equals(PackageDependency? x, PackageDependency? y) { - return true; + return string.Equals(x?.Id, y?.Id, StringComparison.OrdinalIgnoreCase); } - return x != null && y != null && x.Id.Equals(y.Id, StringComparison.OrdinalIgnoreCase); - } - - public int GetHashCode(PackageDependency obj) - { - return obj?.Id.GetHashCode() ?? 0; + public int GetHashCode(PackageDependency? obj) + { + return obj?.Id.GetHashCode() ?? 0; + } } } diff --git a/unturned/OpenMod.Unturned/Events/UnturnedPlayerEventsListener.cs b/unturned/OpenMod.Unturned/Events/UnturnedPlayerEventsListener.cs index b082fed19..2a75f6422 100644 --- a/unturned/OpenMod.Unturned/Events/UnturnedPlayerEventsListener.cs +++ b/unturned/OpenMod.Unturned/Events/UnturnedPlayerEventsListener.cs @@ -3,94 +3,95 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; -namespace OpenMod.Unturned.Events; - -internal abstract class UnturnedPlayerEventsListener : UnturnedEventsListener, IUnturnedPlayerEventsListener +namespace OpenMod.Unturned.Events { - private record EventRegistration( - Action Subscribe, - Action Unsubscribe, - Func HandlerFactory - ); - - private record EventSubscription( - Player Player, - Delegate Handler, - Action Unsubscribe - ); - - private readonly List m_Registrations = new(); - private readonly List m_Subscriptions = new(); - - protected UnturnedPlayerEventsListener(IServiceProvider serviceProvider) : base(serviceProvider) + internal abstract class UnturnedPlayerEventsListener : UnturnedEventsListener, IUnturnedPlayerEventsListener { - } - - public virtual void SubscribePlayer(Player player) - { - foreach (var registration in m_Registrations) + private record EventRegistration( + Action Subscribe, + Action Unsubscribe, + Func HandlerFactory + ); + + private record EventSubscription( + Player Player, + Delegate Handler, + Action Unsubscribe + ); + + private readonly List m_Registrations = new(); + private readonly List m_Subscriptions = new(); + + protected UnturnedPlayerEventsListener(IServiceProvider serviceProvider) : base(serviceProvider) { - var handler = registration.HandlerFactory(player); - registration.Subscribe(player, handler); - - var subscription = new EventSubscription(player, handler, registration.Unsubscribe); - m_Subscriptions.Add(subscription); } - } - public virtual void UnsubscribePlayer(Player player) - { - for (var i = m_Subscriptions.Count - 1; i >= 0; i--) + public virtual void SubscribePlayer(Player player) { - var (subscribedPlayer, handler, unsubscribe) = m_Subscriptions[i]; - - if (subscribedPlayer != player) + foreach (var registration in m_Registrations) { - continue; - } + var handler = registration.HandlerFactory(player); + registration.Subscribe(player, handler); - m_Subscriptions.RemoveAtFast(i); - unsubscribe(player, handler); + var subscription = new EventSubscription(player, handler, registration.Unsubscribe); + m_Subscriptions.Add(subscription); + } } - } - protected delegate ref T FieldRefAccessor(TInstance obj) where TInstance : class; + public virtual void UnsubscribePlayer(Player player) + { + for (var i = m_Subscriptions.Count - 1; i >= 0; i--) + { + var (subscribedPlayer, handler, unsubscribe) = m_Subscriptions[i]; - // Should be used on delegate fields - protected void SubscribePlayer( - FieldRefAccessor delegateAccessor, - Func handlerFactory) - where TDelegate : Delegate - { - SubscribePlayer(SubscribeToDelegate, UnsubscribeFromDelegate, handlerFactory); - return; + if (subscribedPlayer != player) + { + continue; + } - void SubscribeToDelegate(Player player, TDelegate handler) - { - ref var @delegate = ref delegateAccessor(player); - @delegate = (TDelegate) Delegate.Combine(@delegate, handler); + m_Subscriptions.RemoveAtFast(i); + unsubscribe(player, handler); + } } - void UnsubscribeFromDelegate(Player player, TDelegate handler) + protected delegate ref T FieldRefAccessor(TInstance obj) where TInstance : class; + + // Should be used on delegate fields + protected void SubscribePlayer( + FieldRefAccessor delegateAccessor, + Func handlerFactory) + where TDelegate : Delegate { - ref var @delegate = ref delegateAccessor(player); - @delegate = (TDelegate) (Delegate.Remove(@delegate, handler) ?? @delegate); + SubscribePlayer(SubscribeToDelegate, UnsubscribeFromDelegate, handlerFactory); + return; + + void SubscribeToDelegate(Player player, TDelegate handler) + { + ref var @delegate = ref delegateAccessor(player); + @delegate = (TDelegate) Delegate.Combine(@delegate, handler); + } + + void UnsubscribeFromDelegate(Player player, TDelegate handler) + { + ref var @delegate = ref delegateAccessor(player); + @delegate = (TDelegate) (Delegate.Remove(@delegate, handler) ?? @delegate); + } } - } - // Should be used on event fields - protected void SubscribePlayer( - Action subscribe, - Action unsubscribe, - Func handlerFactory) - where TDelegate : Delegate - { - // Upcast to non-generic types so they can be stored in a list - var subscribeUpcast = Unsafe.As>(subscribe); - var unsubscribeUpcast = Unsafe.As>(unsubscribe); - var handlerFactoryUpcast = Unsafe.As>(handlerFactory); + // Should be used on event fields + protected void SubscribePlayer( + Action subscribe, + Action unsubscribe, + Func handlerFactory) + where TDelegate : Delegate + { + // Upcast to non-generic types so they can be stored in a list + var subscribeUpcast = Unsafe.As>(subscribe); + var unsubscribeUpcast = Unsafe.As>(unsubscribe); + var handlerFactoryUpcast = Unsafe.As>(handlerFactory); - var registration = new EventRegistration(subscribeUpcast, unsubscribeUpcast, handlerFactoryUpcast); - m_Registrations.Add(registration); + var registration = new EventRegistration(subscribeUpcast, unsubscribeUpcast, handlerFactoryUpcast); + m_Registrations.Add(registration); + } } } \ No newline at end of file diff --git a/unturned/OpenMod.Unturned/Mono/Patch_SocketTaskExtensions.cs b/unturned/OpenMod.Unturned/Mono/Patch_SocketTaskExtensions.cs index ab6fd6850..5e261c095 100644 --- a/unturned/OpenMod.Unturned/Mono/Patch_SocketTaskExtensions.cs +++ b/unturned/OpenMod.Unturned/Mono/Patch_SocketTaskExtensions.cs @@ -8,81 +8,83 @@ using HarmonyLib; using OpenMod.Unturned.Patching; -namespace OpenMod.Unturned.Mono; - -/// -/// Fixes , that is always empty due -/// to coping the memory array. -/// https://github.com/Unity-Technologies/mono/blob/unity-main/mcs/class/System/System.Net.Sockets/SocketTaskExtensions.cs -/// -[HarmonyPatch] -internal static class Patch_SocketTaskExtensions +namespace OpenMod.Unturned.Mono { - [HarmonyCleanup] - public static Exception? Cleanup(Exception ex, MethodBase original) - { - HarmonyExceptionHandler.ReportCleanupException(typeof(Patch_SocketTaskExtensions), ex, original); - return null; - } - - [HarmonyPatch(typeof(SocketTaskExtensions), nameof(SocketTaskExtensions.ReceiveAsync), - new[] { typeof(Socket), typeof(Memory), typeof(SocketFlags), typeof(CancellationToken) })] - [HarmonyPrefix] - public static bool SocketTaskExtensionsReceiveAsync(Socket socket, Memory memory, SocketFlags socketFlags, CancellationToken cancellationToken, - out ValueTask __result) + /// + /// Fixes , that is always empty due + /// to coping the memory array. + /// https://github.com/Unity-Technologies/mono/blob/unity-main/mcs/class/System/System.Net.Sockets/SocketTaskExtensions.cs + /// + [HarmonyPatch] + internal static class PatchSocketTaskExtensions { - var tcs = new TaskCompletionSource(socket); - if (MemoryMarshal.TryGetArray((ReadOnlyMemory)memory, out var segment)) + [HarmonyCleanup] + public static Exception? Cleanup(Exception ex, MethodBase original) { - // We were able to extract the underlying byte[] from the Memory. Use it. + HarmonyExceptionHandler.ReportCleanupException(typeof(PatchSocketTaskExtensions), ex, original); + return null; + } - socket.BeginReceive(segment.Array, segment.Offset, segment.Count, socketFlags, static iar => + [HarmonyPatch(typeof(SocketTaskExtensions), nameof(SocketTaskExtensions.ReceiveAsync), + new[] { typeof(Socket), typeof(Memory), typeof(SocketFlags), typeof(CancellationToken) })] + [HarmonyPrefix] + public static bool SocketTaskExtensionsReceiveAsync(Socket socket, Memory memory, SocketFlags socketFlags, CancellationToken cancellationToken, + // ReSharper disable once InconsistentNaming + out ValueTask __result) + { + var tcs = new TaskCompletionSource(socket); + if (MemoryMarshal.TryGetArray((ReadOnlyMemory)memory, out var segment)) { - var state = (Tuple, CancellationToken>)iar.AsyncState; + // We were able to extract the underlying byte[] from the Memory. Use it. - state.Item2.ThrowIfCancellationRequested(); - try + socket.BeginReceive(segment.Array!, segment.Offset, segment.Count, socketFlags, static iar => { - state.Item1.TrySetResult(((Socket)state.Item1.Task.AsyncState).EndReceive(iar)); - } - catch (Exception ex) - { - state.Item1.TrySetException(ex); - } - }, Tuple.Create(tcs, cancellationToken)); + var state = (Tuple, CancellationToken>)iar.AsyncState; - cancellationToken.ThrowIfCancellationRequested(); - } - else - { - // We weren't able to extract an underlying byte[] from the Memory. - // Instead read into an ArrayPool array, then copy from that into the memory. + state.Item2.ThrowIfCancellationRequested(); + try + { + state.Item1.TrySetResult(((Socket)state.Item1.Task.AsyncState).EndReceive(iar)); + } + catch (Exception ex) + { + state.Item1.TrySetException(ex); + } + }, Tuple.Create(tcs, cancellationToken)); - var poolArray = ArrayPool.Shared.Rent(memory.Length); - - socket.BeginReceive(poolArray, 0, memory.Length, socketFlags, static iar => + cancellationToken.ThrowIfCancellationRequested(); + } + else { - var state = (Tuple, Memory, byte[], CancellationToken>)iar.AsyncState; - try - { - var bytesCopied = ((Socket)state.Item1.Task.AsyncState).EndReceive(iar); - new ReadOnlyMemory(state.Item3, 0, bytesCopied).Span.CopyTo(state.Item2.Span); - state.Item1.TrySetResult(bytesCopied); - } - catch (Exception e) - { - state.Item1.TrySetException(e); - } - finally + // We weren't able to extract an underlying byte[] from the Memory. + // Instead read into an ArrayPool array, then copy from that into the memory. + + var poolArray = ArrayPool.Shared.Rent(memory.Length); + + socket.BeginReceive(poolArray, 0, memory.Length, socketFlags, static iar => { - ArrayPool.Shared.Return(state.Item3); - } - }, Tuple.Create(tcs, memory, poolArray, cancellationToken)); + var state = (Tuple, Memory, byte[], CancellationToken>)iar.AsyncState; + try + { + var bytesCopied = ((Socket)state.Item1.Task.AsyncState).EndReceive(iar); + new ReadOnlyMemory(state.Item3, 0, bytesCopied).Span.CopyTo(state.Item2.Span); + state.Item1.TrySetResult(bytesCopied); + } + catch (Exception e) + { + state.Item1.TrySetException(e); + } + finally + { + ArrayPool.Shared.Return(state.Item3); + } + }, Tuple.Create(tcs, memory, poolArray, cancellationToken)); - cancellationToken.ThrowIfCancellationRequested(); - } + cancellationToken.ThrowIfCancellationRequested(); + } - __result = new ValueTask(tcs.Task); - return false; + __result = new ValueTask(tcs.Task); + return false; + } } } diff --git a/unturned/OpenMod.Unturned/Users/UnturnedPendingUser.cs b/unturned/OpenMod.Unturned/Users/UnturnedPendingUser.cs index 69e721524..41d9e48ef 100644 --- a/unturned/OpenMod.Unturned/Users/UnturnedPendingUser.cs +++ b/unturned/OpenMod.Unturned/Users/UnturnedPendingUser.cs @@ -18,7 +18,7 @@ public class UnturnedPendingUser : UserBase, IEquatable, IE /// public override string Id { - get { return SteamId.ToString(); } + get => SteamId.ToString(); } /// @@ -51,34 +51,39 @@ public override Task PrintMessageAsync(string message, System.Drawing.Color colo return Task.CompletedTask; } - public bool Equals(UnturnedPendingUser other) + public bool Equals(UnturnedPendingUser? other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; - return SteamId.Equals(other.SteamId); + if (other is null) + { + return false; + } + + return ReferenceEquals(this, other) || SteamId.Equals(other.SteamId); } - public bool Equals(UnturnedUser other) + public bool Equals(UnturnedUser? other) { return other?.SteamId == SteamId; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - - if (obj is UnturnedUser user) + if (obj is null) { - return Equals(user); + return false; } - if (obj is UnturnedPendingUser pendingUser) + if (ReferenceEquals(this, obj)) { - return Equals(pendingUser); + return true; } - return false; + return obj switch + { + UnturnedUser user => Equals(user), + UnturnedPendingUser pendingUser => Equals(pendingUser), + _ => false + }; } public override int GetHashCode() diff --git a/unturned/OpenMod.Unturned/Vehicles/UnturnedVehicleOwnership.cs b/unturned/OpenMod.Unturned/Vehicles/UnturnedVehicleOwnership.cs index 9191b96ce..e92038853 100644 --- a/unturned/OpenMod.Unturned/Vehicles/UnturnedVehicleOwnership.cs +++ b/unturned/OpenMod.Unturned/Vehicles/UnturnedVehicleOwnership.cs @@ -46,18 +46,17 @@ public UnturnedVehicleOwnership(InteractableVehicle vehicle) public Task HasAccessAsync(IPlayer player) { if (player is not UnturnedPlayer unturnedPlayer) + { return Task.FromResult(false); + } if (!HasOwner) - return Task.FromResult(true); - - //Explanation at UnturnedBuildableOwnership - if (PlayerId == unturnedPlayer.SteamId.m_SteamID) { return Task.FromResult(true); } - return Task.FromResult(GroupId != 0 && GroupId == unturnedPlayer.Player.quests.groupID.m_SteamID); + //Explanation at UnturnedBuildableOwnership + return PlayerId == unturnedPlayer.SteamId.m_SteamID ? Task.FromResult(true) : Task.FromResult(GroupId != 0 && GroupId == unturnedPlayer.Player.quests.groupID.m_SteamID); } } } \ No newline at end of file From 791ee203d09e7809ac0495be004a0b69a6125af8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BAben=20Garcia?= Date: Wed, 24 Apr 2024 17:47:44 +0100 Subject: [PATCH 3/3] Use .Select to shut codeql --- .../Localization/SmartFormatOptions.cs | 58 ++++++++++--------- 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/framework/OpenMod.Core/Localization/SmartFormatOptions.cs b/framework/OpenMod.Core/Localization/SmartFormatOptions.cs index c870a301a..63cbbe98a 100644 --- a/framework/OpenMod.Core/Localization/SmartFormatOptions.cs +++ b/framework/OpenMod.Core/Localization/SmartFormatOptions.cs @@ -28,39 +28,41 @@ public SmartFormatOptions() // copy formatters and sources m_Formatters = new List>(); - foreach (var formatter in defaultFormatter.GetFormatterExtensions()) + foreach (var formatterFactory in defaultFormatter.GetFormatterExtensions().Select(f => + { + return new FormatterFactory(f.GetType(), factory => + { + try + { + return Activator.CreateInstance(factory.Type) as IFormatter; + } + catch + { + return null; + } + }); + })) { - var formatterType = formatter.GetType(); - - m_Formatters.Add(new FormatterFactory(formatterType, factory => - { - try - { - return Activator.CreateInstance(factory.Type) as IFormatter; - } - catch - { - return null; - } - })); + m_Formatters.Add(formatterFactory); } m_Sources = new List>(); - foreach (var source in defaultFormatter.GetSourceExtensions()) + foreach (var sourceFactory in defaultFormatter.GetSourceExtensions().Select(s => + { + return new FormatterFactory(s.GetType(), factory => + { + try + { + return Activator.CreateInstance(factory.Type) as ISource; + } + catch + { + return null; + } + }); + })) { - var sourceType = source.GetType(); - - m_Sources.Add(new FormatterFactory(sourceType, factory => - { - try - { - return Activator.CreateInstance(factory.Type) as ISource; - } - catch - { - return null; - } - })); + m_Sources.Add(sourceFactory); } // Smartformatter will be used in threading, so make sure it is thread safe mode is set