Decompiled source of Localyssation v2.2.1
Localyssation.dll
Decompiled 7 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Localyssation.Exporter; using Localyssation.LangAdjutable; using Localyssation.LanguageModule; using Localyssation.Patches; using Localyssation.Patches.ReplaceFont; using Localyssation.Patches.ReplaceText; using Localyssation.Util; using Mirror; using MonoMod.Utils; using Nessie.ATLYSS.EasySettings; using Nessie.ATLYSS.EasySettings.UIElements; using Newtonsoft.Json; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.SceneManagement; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Serialization; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("UnityEngine.CoreModule")] [assembly: IgnoresAccessChecksTo("UnityEngine")] [assembly: IgnoresAccessChecksTo("UnityEngine.UI")] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyCompany("Localyssation")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1+dae59f7d2b6ed3b6a95f5b7e2fe36be7e2f80923")] [assembly: AssemblyProduct("Localyssation")] [assembly: AssemblyTitle("Localyssation")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.2.1.0")] [module: UnverifiableCode] [module: UnverifiableCode] namespace Localyssation { internal static class I18nKeys { internal static class CharacterCreation { public static readonly string HEADER = Create("CHARACTER_CREATION_HEADER", "Character Creation"); public static readonly string HEADER_RACE_NAME = Create("CHARACTER_CREATION_HEADER_RACE_NAME", "Race Select"); public static readonly string RACE_DESCRIPTOR_HEADER_INITIAL_SKILL = Create("CHARACTER_CREATION_RACE_DESCRIPTOR_HEADER_INITIAL_SKILL", "Initial Skill"); public static readonly string BUTTON_SET_TO_DEFAULTS = Create("CHARACTER_CREATION_BUTTON_SET_TO_DEFAULTS", "Defaults"); public static readonly string CHARACTER_NAME_PLACEHOLDER_TEXT = Create("CHARACTER_CREATION_CHARACTER_NAME_PLACEHOLDER_TEXT", "Enter Name..."); public static readonly string BUTTON_CREATE_CHARACTER = Create("CHARACTER_CREATION_BUTTON_CREATE_CHARACTER", "Create Character"); public static readonly string BUTTON_RETURN = Create("CHARACTER_CREATION_BUTTON_RETURN", "Return"); public static readonly string CUSTOMIZER_HEADER_COLOR = Create("CHARACTER_CREATION_CUSTOMIZER_HEADER_COLOR", "Color"); public static readonly string CUSTOMIZER_COLOR_BODY_HEADER = Create("CHARACTER_CREATION_CUSTOMIZER_COLOR_BODY_HEADER", "Body"); public static readonly string CUSTOMIZER_COLOR_BODY_TEXTURE = Create("CHARACTER_CREATION_CUSTOMIZER_COLOR_BODY_TEXTURE", "Texture"); public static readonly string CUSTOMIZER_COLOR_HAIR_HEADER = Create("CHARACTER_CREATION_CUSTOMIZER_COLOR_HAIR_HEADER", "Hair"); public static readonly string CUSTOMIZER_COLOR_HAIR_LOCK_COLOR = Create("CHARACTER_CREATION_CUSTOMIZER_COLOR_HAIR_LOCK_COLOR", "Lock Color"); public static readonly string CUSTOMIZER_HEADER_HEAD = Create("CHARACTER_CREATION_CUSTOMIZER_HEADER_HEAD", "Head"); public static readonly string CUSTOMIZER_HEAD_HEAD_WIDTH = Create("CHARACTER_CREATION_CUSTOMIZER_HEAD_HEAD_WIDTH", "Head Width"); public static readonly string CUSTOMIZER_HEAD_HEAD_MOD = Create("CHARACTER_CREATION_CUSTOMIZER_HEAD_HEAD_MOD", "Modify"); public static readonly string CUSTOMIZER_HEAD_VOICE_PITCH = Create("CHARACTER_CREATION_CUSTOMIZER_HEAD_VOICE_PITCH", "Voice Pitch"); public static readonly string CUSTOMIZER_HEAD_HAIR_STYLE = Create("CHARACTER_CREATION_CUSTOMIZER_HEAD_HAIR_STYLE", "Hair"); public static readonly string CUSTOMIZER_HEAD_EARS = Create("CHARACTER_CREATION_CUSTOMIZER_HEAD_EARS", "Ears"); public static readonly string CUSTOMIZER_HEAD_EYES = Create("CHARACTER_CREATION_CUSTOMIZER_HEAD_EYES", "Eyes"); public static readonly string CUSTOMIZER_HEAD_MOUTH = Create("CHARACTER_CREATION_CUSTOMIZER_HEAD_MOUTH", "Mouth"); public static readonly string CUSTOMIZER_HEADER_BODY = Create("CHARACTER_CREATION_CUSTOMIZER_HEADER_BODY", "Body"); public static readonly string CUSTOMIZER_BODY_HEIGHT = Create("CHARACTER_CREATION_CUSTOMIZER_BODY_HEIGHT", "Height"); public static readonly string CUSTOMIZER_BODY_WIDTH = Create("CHARACTER_CREATION_CUSTOMIZER_BODY_WIDTH", "Width"); public static readonly string CUSTOMIZER_BODY_CHEST = Create("CHARACTER_CREATION_CUSTOMIZER_BODY_CHEST", "Chest"); public static readonly string CUSTOMIZER_BODY_ARMS = Create("CHARACTER_CREATION_CUSTOMIZER_BODY_ARMS", "Arms"); public static readonly string CUSTOMIZER_BODY_BELLY = Create("CHARACTER_CREATION_CUSTOMIZER_BODY_BELLY", "Belly"); public static readonly string CUSTOMIZER_BODY_BOTTOM = Create("CHARACTER_CREATION_CUSTOMIZER_BODY_BOTTOM", "Bottom"); public static readonly string CUSTOMIZER_BODY_TAIL = Create("CHARACTER_CREATION_CUSTOMIZER_BODY_TAIL", "Tail"); public static readonly string CUSTOMIZER_BODY_TOGGLE_LEFT_HANDED = Create("CHARACTER_CREATION_CUSTOMIZER_BODY_TOGGLE_LEFT_HANDED", "Mirror Body"); public static readonly string CUSTOMIZER_HEADER_TRAIT = Create("CHARACTER_CREATION_CUSTOMIZER_HEADER_TRAIT", "Trait"); public static readonly string CUSTOMIZER_TRAIT_EQUIPMENT = Create("CHARACTER_CREATION_CUSTOMIZER_TRAIT_EQUIPMENT", "Equipment"); public static readonly string CUSTOMIZER_TRAIT_WEAPON_LOADOUT = Create("CHARACTER_CREATION_CUSTOMIZER_TRAIT_WEAPON_LOADOUT", "Weapon"); public static readonly string CUSTOMIZER_TRAIT_GEAR_DYE = Create("CHARACTER_CREATION_CUSTOMIZER_TRAIT_GEAR_DYE", "Dye"); public static readonly string CUSTOMIZER_TRAIT_ATTRIBUTES = Create("CHARACTER_CREATION_CUSTOMIZER_TRAIT_ATTRIBUTES", "Attributes"); public static readonly string CUSTOMIZER_TRAIT_RESET_ATTRIBUTE_POINTS = Create("CHARACTER_CREATION_CUSTOMIZER_TRAIT_RESET_ATTRIBUTE_POINTS", "Reset Points"); internal static void Init() { } } internal static class CharacterSelect { public static readonly string HEADER = Create("CHARACTER_SELECT_HEADER", "Character Select"); public static readonly string HEADER_GAME_MODE_SINGLEPLAYER = Create("CHARACTER_SELECT_HEADER_GAME_MODE_SINGLEPLAYER", "Singleplayer"); public static readonly string HEADER_GAME_MODE_HOST_MULTIPLAYER_PUBLIC = Create("CHARACTER_SELECT_HEADER_GAME_MODE_HOST_MULTIPLAYER_PUBLIC", "Host Game (Public)"); public static readonly string HEADER_GAME_MODE_HOST_MULTIPLAYER_FRIENDS = Create("CHARACTER_SELECT_HEADER_GAME_MODE_HOST_MULTIPLAYER_FRIENDS", "Host Game (Friends)"); public static readonly string HEADER_GAME_MODE_HOST_MULTIPLAYER_PRIVATE = Create("CHARACTER_SELECT_HEADER_GAME_MODE_HOST_MULTIPLAYER_PRIVATE", "Host Game (Private)"); public static readonly string HEADER_GAME_MODE_JOIN_MULTIPLAYER = Create("CHARACTER_SELECT_HEADER_GAME_MODE_JOIN_MULTIPLAYER", "Join Game"); public static readonly string HEADER_GAME_MODE_LOBBY_QUERY = Create("CHARACTER_SELECT_HEADER_GAME_MODE_LOBBY_QUERY", "Lobby Query"); public static readonly string BUTTON_CREATE_CHARACTER = Create("CHARACTER_SELECT_BUTTON_CREATE_CHARACTER", "Create Character"); public static readonly string BUTTON_DELETE_CHARACTER = Create("CHARACTER_SELECT_BUTTON_DELETE_CHARACTER", "Delete Character"); public static readonly string BUTTON_SELECT_CHARACTER = Create("CHARACTER_SELECT_BUTTON_SELECT_CHARACTER", "Select Character"); public static readonly string BUTTON_RETURN = Create("CHARACTER_SELECT_BUTTON_RETURN", "Return"); public static readonly string DATA_ENTRY_EMPTY_SLOT = Create("CHARACTER_SELECT_DATA_ENTRY_EMPTY_SLOT", "Empty Slot"); public static readonly string FORMAT_DATA_ENTRY_INFO = Create("FORMAT_CHARACTER_SELECT_DATA_ENTRY_INFO", "Lv-{0} {1} {2}"); public static readonly string CHARACTER_DELETE_PROMPT_TEXT = Create("CHARACTER_SELECT_CHARACTER_DELETE_PROMPT_TEXT", "Type in the character's name to confirm."); public static readonly string CHARACTER_DELETE_PROMPT_PLACEHOLDER_TEXT = Create("CHARACTER_SELECT_CHARACTER_DELETE_PROMPT_PLACEHOLDER_TEXT", "Enter Nickname..."); public static readonly string CHARACTER_DELETE_BUTTON_CONFIRM = Create("CHARACTER_SELECT_CHARACTER_DELETE_BUTTON_CONFIRM", "Delete Character"); public static readonly string CHARACTER_DELETE_BUTTON_RETURN = Create("CHARACTER_SELECT_CHARACTER_DELETE_BUTTON_RETURN", "Return"); internal static void Init() { } } public static class ChatBehaviour { public static readonly TranslationKey DISABLE_GLOBAL_CHANNEL_MESSAGE = Create("DISABLE_GLOBAL_CHANNEL_MESSAGE", "<color=yellow>Disabled #Global Chat Channel.</color>"); public static readonly TranslationKey ENABLE_GLOBAL_CHANNEL_MESSAGE = Create("ENABLE_GLOBAL_CHANNEL_MESSAGE", "<color=yellow>Enabled #Global Chat Channel.</color>"); public static readonly TranslationKey DISABLE_PARTY_CHANNEL_MESSAGE = Create("DISABLE_PARTY_CHANNEL_MESSAGE", "<color=yellow>Disabled #Party Chat Channel.</color>"); public static readonly TranslationKey ENABLE_PARTY_CHANNEL_MESSAGE = Create("ENABLE_PARTY_CHANNEL_MESSAGE", "<color=yellow>Enabled #Party Chat Channel.</color>"); public static readonly TranslationKey DISABLE_ROOM_CHANNEL_MESSAGE = Create("DISABLE_ROOM_CHANNEL_MESSAGE", "<color=yellow>Disabled #Room Chat Channel.</color>"); public static readonly TranslationKey ENABLE_ROOM_CHANNEL_MESSAGE = Create("ENABLE_ROOM_CHANNEL_MESSAGE", "<color=yellow>Enabled #Room Chat Channel.</color>"); public static readonly TranslationKey CHANNEL_SWTICH_MESSAGE_FORMAT = Create("CHANNEL_SWTICH_MESSAGE_FORMAT", "{0} Entered #{1}."); public static readonly TranslationKey GLOBAL_CHANNEL_DISABLED = Create("GLOBAL_CHANNEL_DISABLED", "#Global chat is disabled."); public static readonly TranslationKey PARTY_CHANNEL_DISABLED = Create("PARTY_CHANNEL_DISABLED", "#Party chat is disabled."); public static readonly TranslationKey ROOM_CHANNEL_DISABLED = Create("ROOM_CHANNEL_DISABLED", "#Room chat is disabled."); public static readonly TranslationKey ENTER_A_ROOM_HINT = Create("ENTER_A_ROOM_HINT", "Enter a room to send messages to a room channel."); private static TranslationKey Create(string key, string english) { return I18nKeys.Create("CHAT_BEHAVIOUR_" + key, english); } public static void Init() { } } internal static class ChatMessage { public static readonly TranslationKey RECIEVE_DUNGEON_KEY = Create("RECIEVE_DUNGEON_KEY", "You received a dungeon key."); public static readonly TranslationKey DUNGEON_KEY_DISSIPATES = Create("DUNGEON_KEY_DISSIPATES", "A dungeon key dissipates..."); public static readonly TranslationKey UNMUTE_PLAYER_FORMAT = Create("UNMUTE_PLAYER_FORMAT", "Unmuted {0}."); public static readonly TranslationKey MUTE_PLAYER_FORMAT = Create("MUTE_PLAYER_FORMAT", "Muted {0}."); internal static void Init() { } private static TranslationKey Create(string key, string defaultValue) { return I18nKeys.Create("CHAT_MESSAGE_" + key, defaultValue); } } internal static class Enchanter { public static readonly TranslationKey HEADER = create("HEADER", "- Item Enchant -"); public static readonly TranslationKey BUTTON_CLEAR_SELECTION = create("BUTTON_CLEAR_SELECTION", "Clear Selection"); public static readonly string[] BUTTON_TRANSMUTE = ((IEnumerable<DamageType>)(object)new DamageType[3] { (DamageType)1, default(DamageType), (DamageType)2 }).SelectMany((DamageType type) => new bool[2] { true, false }.Select((bool free) => generateTransmuteButton(type, free))).ToArray(); public static readonly TranslationKey BUTTON_ENCHANT_REROLL = create("BUTTON_ENCHANT_REROLL", "Re-roll Enchant"); public static readonly TranslationKey BUTTON_ENCHANT_ENCHANT = create("BUTTON_ENCHANT_ENCHANT", "Enchant Item"); public static readonly TranslationKey BUTTON_ENCHANT_UNABLE = create("BUTTON_ENCHANT_UNABLE", "Cannot enchant"); public static readonly TranslationKey STATUS_NO_ENCHANT = create("STATUS_NO_ENCHANT", "No enchantment applied on this item"); public static readonly TranslationKey STATUS_UNABLE_TO_ENCHANT = create("STATUS_UNABLE_TO_ENCHANT", "Item cannot be enchanted"); public static readonly TranslationKey BUTTON_ENCHANT_INSERT_ITEM = create("BUTTON_ENCHANT_INSERT_ITEM", "Insert item to enchant"); public static readonly TranslationKey STATUS_CURRENT_ENCHANTMENT = create("STATUS_CURRENT_ENCHANTMENT", "Current enchantment: "); public static readonly TranslationKey GET_NEW_ENCHANTMENT_FORMAT = create("GET_NEW_ENCHANTMENT_FORMAT", "You got the {0} enchantment!"); public static readonly TranslationKey TRANSMUTE_TO_STRENGTH_FORMAT = create("TRANSMUTE_TO_STRENGTH_FORMAT", "Your {0} now scales off Strength!"); public static readonly TranslationKey TRANSMUTE_TO_DEXTERITY_FORMAT = create("TRANSMUTE_TO_DEXTERITY_FORMAT", "Your {0} now scales off Dexterity!"); public static readonly TranslationKey TRANSMUTE_TO_MIND_FORMAT = create("TRANSMUTE_TO_MIND_FORMAT", "Your {0} now scales off Mind!"); public static readonly TranslationKey NOT_ENOUGH_TRANSMUTE_STONES_STRENGTH = create("NOT_ENOUGH_TRANSMUTE_STONES_STRENGTH", "Not enough Might Stones"); public static readonly TranslationKey NOT_ENOUGH_TRANSMUTE_STONES_DEXTERITY = create("NOT_ENOUGH_TRANSMUTE_STONES_DEXTERITY", "Not enough Agility Stones"); public static readonly TranslationKey NOT_ENOUGH_TRANSMUTE_STONES_MIND = create("NOT_ENOUGH_TRANSMUTE_STONES_MIND", "Not enough Flux Stones"); public static readonly TranslationKey CANNOT_TRANSMUTE_WEAPON = create("CANNOT_TRANSMUTE_WEAPON", "Cannot Transmute Weapon"); internal static void Init() { } private static TranslationKey create(string key, string value = "") { return Create("ENCHANTER_GUI_" + key.ToUpper(), value); } public static string TransmuteButtonKey(DamageType type, bool free) { return "BUTTON_TRANSMUTE_" + ((object)(DamageType)(ref type)).ToString().ToUpper() + "_" + (free ? "FREE" : "FORMAT"); } private static string generateTransmuteButton(DamageType type, bool free) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 return create(TransmuteButtonKey(type, free), ((int)type == 2 && free) ? "Apply Flux Stone (Free)" : ("Transmute " + ((object)(DamageType)(ref type)).ToString() + " " + (free ? "(Free)" : "(x{0})"))); } } internal static class Enums { public static readonly IDictionary<TranslationKey, string> ITEM_RARITY = CreateEnumKeys<ItemRarity>((Func<ItemRarity, TranslationKey>)null, (Func<ItemRarity, string>)null, (IDictionary<ItemRarity, string>)null); public static readonly IDictionary<TranslationKey, string> DAMAGE_TYPE = CreateEnumKeys<DamageType>((Func<DamageType, TranslationKey>)null, (Func<DamageType, string>)null, (IDictionary<DamageType, string>)null); public static readonly IDictionary<TranslationKey, string> SKILL_CONTROL_TYPE = CreateEnumKeys<SkillControlType>((Func<SkillControlType, TranslationKey>)null, (Func<SkillControlType, string>)null, (IDictionary<SkillControlType, string>)null); public static readonly IDictionary<TranslationKey, string> COMBAT_COLLIDER_TYPE = CreateEnumKeys<CombatColliderType>((Func<CombatColliderType, TranslationKey>)null, (Func<CombatColliderType, string>)null, (IDictionary<CombatColliderType, string>)null); public static readonly IDictionary<TranslationKey, string> ITEM_TYPE = CreateEnumKeys<ItemType>((Func<ItemType, TranslationKey>)null, (Func<ItemType, string>)null, (IDictionary<ItemType, string>)null); public static readonly IDictionary<TranslationKey, string> ZONE_TYPE = CreateEnumKeys<ZoneType>((Func<ZoneType, TranslationKey>)null, (Func<ZoneType, string>)null, (IDictionary<ZoneType, string>)null); public static readonly IDictionary<TranslationKey, string> SKILL_TOOLTIP_REQUIREMENT = CreateEnumKeys<SkillToolTipRequirement>((Func<SkillToolTipRequirement, TranslationKey>)null, (Func<SkillToolTipRequirement, string>)((SkillToolTipRequirement skillToolTipRequirement) => ((object)(SkillToolTipRequirement)(ref skillToolTipRequirement)).ToString().ToLower()), (IDictionary<SkillToolTipRequirement, string>)null); public static readonly IDictionary<TranslationKey, string> QUEST_SUB_TYPE = CreateEnumKeys<QuestSubType>((Func<QuestSubType, TranslationKey>)null, (Func<QuestSubType, string>)((QuestSubType questSubType) => ""), (IDictionary<QuestSubType, string>)new Dictionary<QuestSubType, string> { { (QuestSubType)2, "Class Tome" }, { (QuestSubType)3, "Skill Scroll" } }); private static readonly IDictionary<ShopTab, string> __SHOP_TABS = new Dictionary<ShopTab, string> { { (ShopTab)0, "Equipment" }, { (ShopTab)1, "Consumables" }, { (ShopTab)2, "Trade Items" }, { (ShopTab)3, "Sold Items" } }; public static readonly IDictionary<TranslationKey, string> SHOP_TAB = __SHOP_TABS.ToDictionary((KeyValuePair<ShopTab, string> kv) => Create(KeyUtil.GetForAsset(kv.Key).ToString(), kv.Value), (KeyValuePair<ShopTab, string> kv) => kv.Value); internal static void Init() { } private static IDictionary<TranslationKey, string> CreateEnumKeys<TEnum>(Func<TEnum, TranslationKey> keyOverride = null, Func<TEnum, string> valueOverride = null, IDictionary<TEnum, string> valueOverrideDict = null) where TEnum : Enum { if (keyOverride == null) { keyOverride = defaultGetString; } if (valueOverride == null) { valueOverride = (TEnum item) => item.ToString(); } Func<TEnum, string> _valueOverride = valueOverride; if (valueOverrideDict != null) { _valueOverride = (TEnum item) => (!valueOverrideDict.TryGetValue(item, out var value)) ? valueOverride(item) : value; } return Enum.GetValues(typeof(TEnum)).OfType<TEnum>().ToDictionary((TEnum item) => Create(keyOverride(item).ToString(), _valueOverride(item)), _valueOverride); static TranslationKey defaultGetString(TEnum item) { return (TranslationKey)(from m in typeof(KeyUtil).GetMethods() where m.Name == "GetForAsset" select m).FirstOrDefault(delegate(MethodInfo m) { ParameterInfo[] parameters = m.GetParameters(); return parameters.Length == 1 && parameters[0].ParameterType == typeof(TEnum); }).Invoke(null, new object[1] { item }); } } } internal static class Equipment { public static readonly string TOOLTIP_GAMBLE_ITEM_NAME = Create("EQUIP_TOOLTIP_GAMBLE_ITEM_NAME", "Mystery Gear"); public static readonly string TOOLTIP_GAMBLE_ITEM_RARITY = Create("EQUIP_TOOLTIP_GAMBLE_ITEM_RARITY", "[Unknown]"); public static readonly string TOOLTIP_GAMBLE_ITEM_TYPE = Create("EQUIP_TOOLTIP_GAMBLE_ITEM_TYPE", "???"); public static readonly string TOOLTIP_GAMBLE_ITEM_DESCRIPTION = Create("EQUIP_TOOLTIP_GAMBLE_ITEM_DESCRIPTION", "You can't really see what this is until you buy it."); public static readonly string FORMAT_LEVEL_REQUIREMENT = Create("FORMAT_EQUIP_LEVEL_REQUIREMENT", "Lv-{0}"); public static readonly string FORMAT_CLASS_REQUIREMENT = Create("FORMAT_EQUIP_CLASS_REQUIREMENT", "Class: {0}"); public static readonly string FORMAT_WEAPON_CONDITION = Create("FORMAT_EQUIP_WEAPON_CONDITION", "\n<color=lime>- <color=yellow>{0}%</color> chance to apply {1}.</color>"); public static readonly string TOOLTIP_TYPE_HELM = Create("EQUIP_TOOLTIP_TYPE_HELM", "Helm (Armor)"); public static readonly string TOOLTIP_TYPE_CHESTPIECE = Create("EQUIP_TOOLTIP_TYPE_CHESTPIECE", "Chestpiece (Armor)"); public static readonly string TOOLTIP_TYPE_LEGGINGS = Create("EQUIP_TOOLTIP_TYPE_LEGGINGS", "Leggings (Armor)"); public static readonly string TOOLTIP_TYPE_CAPE = Create("EQUIP_TOOLTIP_TYPE_CAPE", "Cape (Armor)"); public static readonly string TOOLTIP_TYPE_RING = Create("EQUIP_TOOLTIP_TYPE_RING", "Ring (Armor)"); public static readonly string FORMAT_TOOLTIP_TYPE_WEAPON = Create("FORMAT_EQUIP_TOOLTIP_TYPE_WEAPON", "{0} (Weapon)"); public static readonly string TOOLTIP_TYPE_SHIELD = Create("EQUIP_TOOLTIP_TYPE_SHIELD", "Shield (Off Hand)"); public static readonly string STATS_DAMAGE = Create("EQUIP_TOOLTIP_STATS_DAMAGE", "Damage"); public static readonly string STATS_BASE_DAMAGE = Create("EQUIP_TOOLTIP_STATS_BASE_DAMAGE", "Base Damage"); public static readonly string FORMAT_STATS_BLOCK_THRESHOLD = Create("FORMAT_EQUIP_STATS_BLOCK_THRESHOLD", "Block threshold: {0} damage"); public static readonly string FORMAT_WEAPON_DAMAGE_TYPE = Create("FORMAT_EQUIP_STATS_WEAPON_DAMAGE_TYPE", "{0} Weapon"); public static readonly string FORMAT_WEAPON_TRANSMUTE_TYPE = Create("FORMAT_EQUIP_STATS_WEAPON_TRASMUTE_TYPE", "Damage Transmute: {0}"); public static readonly string COMPARE = Create("EQUIP_TOOLTIP_COMPARE", "Compare"); public static readonly string STAT_DISPLAY_DEFENSE = Create(statDisplayKey("defense"), "Defense"); public static readonly string STAT_DISPLAY_MAGIC_DEFENSE = Create(statDisplayKey("magicDefense"), "Mgk. Defense"); public static readonly string STAT_DISPLAY_MAX_HEALTH = Create(statDisplayKey("maxHealth"), "Max Health"); public static readonly string STAT_DISPLAY_MAX_MANA = Create(statDisplayKey("maxMana"), "Max Mana"); public static readonly string STAT_DISPLAY_MAX_STAMINA = Create(statDisplayKey("maxStamina"), "Max Stamina"); public static readonly string STAT_DISPLAY_ATTACK_POWER = Create(statDisplayKey("attackPower"), "Attack Power"); public static readonly string STAT_DISPLAY_MAGIC_POWER = Create(statDisplayKey("magicPower"), "Mgk. Power"); public static readonly string STAT_DISPLAY_DEX_POWER = Create(statDisplayKey("dexPower"), "Dex Power"); public static readonly string STAT_DISPLAY_CRITICAL = Create(statDisplayKey("critical"), "Phys. Critical"); public static readonly string STAT_DISPLAY_MAGIC_CRITICAL = Create(statDisplayKey("magicCritical"), "Mgk. Critical"); public static readonly string STAT_DISPLAY_EVASION = Create(statDisplayKey("evasion"), "Evasion"); public static readonly string STAT_DISPLAY_RESIST_FIRE = Create(statDisplayKey("resistFire"), "Fire Resist"); public static readonly string STAT_DISPLAY_RESIST_WATER = Create(statDisplayKey("resistWater"), "Water Resist"); public static readonly string STAT_DISPLAY_RESIST_NATURE = Create(statDisplayKey("resistNature"), "Nature Resist"); public static readonly string STAT_DISPLAY_RESIST_EARTH = Create(statDisplayKey("resistEarth"), "Earth Resist"); public static readonly string STAT_DISPLAY_RESIST_HOLY = Create(statDisplayKey("resistHoly"), "Holy Resist"); public static readonly string STAT_DISPLAY_RESIST_SHADOW = Create(statDisplayKey("resistShadow"), "Shadow Resist"); internal static void Init() { } public static string statDisplayKey(string stat) { return "ITEM_STAT_DISPLAY_" + KeyUtil.Normalize(Regex.Replace(stat, "[A-Z]", (Match x) => $"_{x}")); } } internal static class ErrorMessages { public static readonly TranslationKey QUEST_LOG_FULL = Create("QUEST_LOG_FULL", "Quest Log Full"); public static readonly TranslationKey QUEST_ALREADY_IN_LOG = Create("ALREADY_ON_THIS_QUEST", "Already on this Quest"); internal static void Init() { } private static TranslationKey Create(string key, string english) { return I18nKeys.Create("ERROR_MESSAGE_" + key, english); } } internal static class Feedback { public static readonly string DROP_ITEM_FORMAT = Create("DROP_ITEM_FORMAT", "Dropped {0}. (-{1})"); internal static void Init() { } private static string Create(string key, string defaultString) { if (!key.StartsWith("FEEDBACK_")) { key = "FEEDBACK_" + key; } I18nKeys.Create(key, defaultString); return key; } } internal static class Item { public static readonly string FORMAT_ITEM_RARITY = Create("FORMAT_ITEM_RARITY", "[{0}]"); public static readonly string FORMAT_ITEM_TOOLTIP_VENDOR_VALUE_COUNTER = Create("FORMAT_ITEM_TOOLTIP_VENDOR_VALUE_COUNTER", "{0}"); public static readonly string FORMAT_ITEM_TOOLTIP_VENDOR_VALUE_COUNTER_MULTIPLE = Create("FORMAT_ITEM_TOOLTIP_VENDOR_VALUE_COUNTER_MULTIPLE", "<color=grey>(x{0} each)</color> {1}"); public static readonly string TOOLTIP_GAMBLE_ITEM_NAME = Create("ITEM_TOOLTIP_GAMBLE_ITEM_NAME", "Mystery Item"); public static readonly string TOOLTIP_GAMBLE_ITEM_RARITY = Create("ITEM_TOOLTIP_GAMBLE_ITEM_RARITY", "[Unknown]"); public static readonly string TOOLTIP_GAMBLE_ITEM_DESC = Create("ITEM_TOOLTIP_GAMBLE_ITEM_DESCRIPTION", "You can't really see what this is until you buy it."); public static readonly string TOOLTIP_CONSUMABLE_DESCRIPTION_HEALTH_APPLY = Create("ITEM_TOOLTIP_CONSUMABLE_DESCRIPTION_HEALTH_APPLY", "Recovers {0} Health."); public static readonly string TOOLTIP_CONSUMABLE_DESCRIPTION_MANA_APPLY = Create("ITEM_TOOLTIP_CONSUMABLE_DESCRIPTION_MANA_APPLY", "Recovers {0} Mana."); public static readonly string TOOLTIP_CONSUMABLE_DESCRIPTION_STAMINA_APPLY = Create("ITEM_TOOLTIP_CONSUMABLE_DESCRIPTION_STAMINA_APPLY", "Recovers {0} Stamina."); public static readonly string TOOLTIP_CONSUMABLE_DESCRIPTION_EXP_GAIN = Create("ITEM_TOOLTIP_CONSUMABLE_DESCRIPTION_EXP_GAIN", "Gain {0} Experience on use."); internal static void Init() { } } internal static class Lore { public static readonly string CROWN = Create("CROWN", "crown"); public static readonly string CROWN_PLURAL = Create("CROWN_PLURAL", "crowns"); public static readonly string GAME_LOADING = Create("GAME_LOADING", "Loading..."); public static readonly string EXP_COUNTER_MAX = Create("EXP_COUNTER_MAX", "MAX"); public static readonly string COMBAT_ELEMENT_NORMAL_NAME = Create("COMBAT_ELEMENT_NORMAL_NAME", "Normal"); public static readonly string FORMAT_MAP_ZONE = Create("MAP_ZONE_FORMAT", "- {0} Zone -"); public static readonly string INTERACT_TELEPORT = Create("INTERACT_TELEPORT", "TELEPORT"); public static readonly string INTERACT_REEL = Create("INTERACT_REEL", "REEL"); public static readonly string INTERACT_REVIVE = Create("INTERACT_REVIVE", "REVIVE"); public static readonly string INTERACT_INTERACT = Create("INTERACT_INTERACT", "INTERACT"); public static readonly string INTERACT_HOLD = Create("INTERACT_HOLD", "HOLD"); public static readonly string INTERACT_OPEN = Create("INTERACT_OPEN", "OPEN"); public static readonly string INTERACT_PICK_UP = Create("INTERACT_PICK_UP", "PICK UP"); public static readonly string WORLDPORTAL_SELECT_WAYPOINT = Create("WORLDPORTAL_SELECT_WAYPOINT", "- Select Waypoint -"); public static readonly string WORLDPORTAL_TITLE = Create("WORLDPORTAL_TITLE", "World Portal"); public static readonly string WORLDPORTAL_TELEPORT = Create("WORLDPORTAL_TELEPORT", "Teleport"); public static readonly string GAMBLING_SHOP_BUTTON_REROLL = Create("GAMBLING_SHOP_BUTTON_REROLL", "Re-roll Stock"); public static readonly string DUNGEON_PORTAL_ENTER_PARTY = Create("DUNGEON_PORTAL_ENTER_PARTY", "Join Party"); public static readonly string DUNGEON_PORTAL_ENTER_LEVELED_FORMAT = Create("DUNGEON_PORTAL_ENTER_LEVELED_FORMAT", "Enter Dungeon (LV {0}-{1})"); internal static void Init() { } } internal static class MainMenu { public static readonly string BUTTON_SINGLEPLAY = Create("MAIN_MENU_BUTTON_SINGLEPLAY", "Singleplayer"); public static readonly string BUTTON_SINGLEPLAY_TOOLTIP = Create("MAIN_MENU_BUTTON_SINGLEPLAY_TOOLTIP", "Start a Singleplayer Game."); public static readonly string BUTTON_MULTIPLAY = Create("MAIN_MENU_BUTTON_MULTIPLAY", "Multiplayer"); public static readonly string BUTTON_MULTIPLAY_TOOLTIP = Create("MAIN_MENU_BUTTON_MULTIPLAY_TOOLTIP", "Start a Netplay Game."); public static readonly string BUTTON_MULTIPLAY_DISABLED_TOOLTIP = Create("MAIN_MENU_BUTTON_MULTIPLAY_DISABLED_TOOLTIP", "Multiplayer is disabled on this demo."); public static readonly string BUTTON_SETTINGS = Create("MAIN_MENU_BUTTON_SETTINGS", "Settings"); public static readonly string BUTTON_SETTINGS_TOOLTIP = Create("MAIN_MENU_BUTTON_SETTINGS_TOOLTIP", "Configure Game Settings."); public static readonly string BUTTON_QUIT = Create("MAIN_MENU_BUTTON_QUIT", "Quit"); public static readonly string BUTTON_QUIT_TOOLTIP = Create("MAIN_MENU_BUTTON_QUIT_TOOLTIP", "End The Application."); public static readonly string PAGER = Create("MAIN_MENU_PAGER", "Page ( {0} / 15 )"); public static readonly string BUTTON_JOIN_SERVER = Create("MAIN_MENU_BUTTON_JOIN_SERVER", "Join"); public static readonly string BUTTON_HOST_SERVER = Create("MAIN_MENU_BUTTON_HOST_SERVER", "Host"); public static readonly string BUTTON_RETURN = Create("MAIN_MENU_BUTTON_RETURN", "Return"); internal static void Init() { } } internal static class Quest { public static readonly string FORMAT_REQUIRED_LEVEL = Create("FORMAT_QUEST_REQUIRED_LEVEL", "(lv-{0})"); public static readonly string MENU_SUMMARY_NO_QUESTS = Create("QUEST_MENU_SUMMARY_NO_QUESTS", "No Quests in Quest Log."); public static readonly string MENU_HEADER_UNSELECTED = Create("QUEST_MENU_HEADER_UNSELECTED", "Select a Quest."); public static readonly string FORMAT_MENU_CELL_LOG_COUNTER = Create("FORMAT_QUEST_MENU_CELL_QUEST_LOG_COUNTER", "Quest Log: ({0} / {1})"); public static readonly string FORMAT_MENU_CELL_FINISHED_COUNTER = Create("FORMAT_QUEST_MENU_CELL_FINISHED_QUEST_COUNTER", "Completed Quests: {0}"); public static readonly string FORMAT_MENU_CELL_REWARD_EXP = Create("FORMAT_QUEST_MENU_CELL_REWARD_EXP", "{0} exp"); public static readonly string FORMAT_MENU_CELL_REWARD_CURRENCY = Create("FORMAT_QUEST_MENU_CELL_REWARD_CURRENCY", "{0} Crowns"); public static readonly string MENU_CELL_SLOT_EMPTY = Create("QUEST_MENU_CELL_SLOT_EMPTY", "Empty Slot"); public static readonly string SELECTION_MANAGER_ACCEPT_BUTTON_ACCEPT = Create("QUEST_SELECTION_MANAGER_QUEST_ACCEPT_BUTTON_ACCEPT", "Accept Quest"); public static readonly string SELECTION_MANAGER_ACCEPT_BUTTON_LOCKED = Create("QUEST_SELECTION_MANAGER_QUEST_ACCEPT_BUTTON_LOCKED", "Quest Locked"); public static readonly string SELECTION_MANAGER_ACCEPT_BUTTON_INCOMPLETE = Create("QUEST_SELECTION_MANAGER_QUEST_ACCEPT_BUTTON_INCOMPLETE", "Quest Incomplete"); public static readonly string SELECTION_MANAGER_ACCEPT_BUTTON_TURN_IN = Create("QUEST_SELECTION_MANAGER_QUEST_ACCEPT_BUTTON_TURN_IN", "Complete Quest"); public static readonly string SELECTION_MANAGER_ACCEPT_BUTTON_UNSELECTED = Create("QUEST_SELECTION_MANAGER_QUEST_ACCEPT_BUTTON_UNSELECTED", "Select a Quest"); public static readonly string FORMAT_PROGRESS = Create("FORMAT_QUEST_PROGRESS", "{0}: ({1} / {2})"); public static readonly string FORMAT_PROGRESS_CREEPS_KILLED = Create("FORMAT_QUEST_PROGRESS_CREEPS_KILLED", "{0} slain"); public static readonly TranslationKey RETRIEVED_QUEST_OBJECTIVE_ITEM_FORMAT = Create("QUEST_RETRIEVED_QUEST_OBJECTIVE_ITEM_FORMAT", "Retrieved Quest Objective Item: {0}."); public static readonly TranslationKey GAME_LOGIC_ACCEPT_QUEST_FORMAT = Create("QUEST_GAME_LOGIC_ACCEPT_QUEST_FORMAT", "Accepted Quest: {0}."); internal static void Init() { } } internal static class ScriptableStatusCondition { public static readonly string DURATION_FORMAT = Create("SCRIPTABLE_STATUS_CONDITION_DURATION_FORMAT", "<color=yellow>Lasts for {0} sec</color>."); public static readonly string RATE_FORMAT = Create("SCRIPTABLE_STATUS_CONDITION_RATE_FORMAT", "<color=yellow>every {0} sec</color>."); internal static void Init() { } } internal static class Settings { internal static class Audio { public static readonly string HEADER_AUDIO_SETTINGS = Create("SETTINGS_AUDIO_HEADER_AUDIO_SETTINGS", "Audio Settings"); public static readonly string CELL_MASTER_VOLUME = Create("SETTINGS_AUDIO_CELL_MASTER_VOLUME", "Master Volume"); public static readonly string CELL_MUTE_APPLICATION = Create("SETTINGS_AUDIO_CELL_MUTE_APPLICATION", "Mute Application"); public static readonly string CELL_MUTE_MUSIC = Create("SETTINGS_AUDIO_CELL_MUTE_MUSIC", "Mute Music"); public static readonly string HEADER_AUDIO_CHANNEL_SETTINGS = Create("SETTINGS_AUDIO_HEADER_AUDIO_CHANNEL_SETTINGS", "Audio Channels"); public static readonly string CELL_GAME_VOLUME = Create("SETTINGS_AUDIO_CELL_GAME_VOLUME", "Game Volume"); public static readonly string CELL_GUI_VOLUME = Create("SETTINGS_AUDIO_CELL_GUI_VOLUME", "GUI Volume"); public static readonly string CELL_AMBIENCE_VOLUME = Create("SETTINGS_AUDIO_CELL_AMBIENCE_VOLUME", "Ambience Volume"); public static readonly string CELL_MUSIC_VOLUME = Create("SETTINGS_AUDIO_CELL_MUSIC_VOLUME", "Music Volume"); public static readonly string CELL_VOICE_VOLUME = Create("SETTINGS_AUDIO_CELL_VOICE_VOLUME", "Voice Volume"); internal static void Init() { } } internal static class Input { public static readonly string HEADER_INPUT_SETTINGS = Create("SETTINGS_INPUT_HEADER_INPUT_SETTINGS", "Input Settings"); public static readonly string CELL_AXIS_TYPE = Create("SETTINGS_INPUT_CELL_AXIS_TYPE", "Analog Stick Axis Type"); public static readonly string CELL_AXIS_TYPE_OPTION_1 = Create("SETTINGS_INPUT_CELL_AXIS_TYPE_OPTION_1", "WASD (8 Directional)"); public static readonly string CELL_AXIS_TYPE_OPTION_2 = Create("SETTINGS_INPUT_CELL_AXIS_TYPE_OPTION_2", "Xbox"); public static readonly string CELL_AXIS_TYPE_OPTION_3 = Create("SETTINGS_INPUT_CELL_AXIS_TYPE_OPTION_3", "Playstation 4"); public static readonly string GAME_PAD_WIP = Create("SETTINGS_INPUT_GAME_PAD_WIP", "*Gamepad Input is a work in progress.\r\nVarious menu elements are incomplete."); public static readonly string HEADER_CAMERA_CONTROL = Create("SETTINGS_INPUT_HEADER_CAMERA_CONTROL", "Camera Control"); public static readonly string CELL_CAMERA_SENSITIVITY = Create("SETTINGS_INPUT_CELL_CAMERA_SENSITIVITY", "Axis Sensitivity"); public static readonly string CELL_INVERT_X_CAMERA_AXIS = Create("SETTINGS_INPUT_CELL_INVERT_X_CAMERA_AXIS", "Invert X Axis"); public static readonly string CELL_INVERT_Y_CAMERA_AXIS = Create("SETTINGS_INPUT_CELL_INVERT_Y_CAMERA_AXIS", "Invert Y Axis"); public static readonly string CELL_KEYBINDING_RESET_CAMERA = Create("SETTINGS_INPUT_CELL_KEYBINDING_RESET_CAMERA", "Reset Camera"); public static readonly string HEADER_MOVEMENT = Create("SETTINGS_INPUT_HEADER_MOVEMENT", "Movement"); public static readonly string CELL_KEYBINDING_UP = Create("SETTINGS_INPUT_CELL_KEYBINDING_UP", "Up"); public static readonly string CELL_KEYBINDING_DOWN = Create("SETTINGS_INPUT_CELL_KEYBINDING_DOWN", "Down"); public static readonly string CELL_KEYBINDING_LEFT = Create("SETTINGS_INPUT_CELL_KEYBINDING_LEFT", "Left"); public static readonly string CELL_KEYBINDING_RIGHT = Create("SETTINGS_INPUT_CELL_KEYBINDING_RIGHT", "Right"); public static readonly string CELL_KEYBINDING_JUMP = Create("SETTINGS_INPUT_CELL_KEYBINDING_JUMP", "Jump"); public static readonly string CELL_KEYBINDING_DASH = Create("SETTINGS_INPUT_CELL_KEYBINDING_DASH", "Dash"); public static readonly string HEADER_STRAFING = Create("SETTINGS_INPUT_HEADER_STRAFING", "Strafing"); public static readonly string CELL_KEYBINDING_LOCK_DIRECTION = Create("SETTINGS_INPUT_CELL_KEYBINDING_LOCK_DIRECTION", "Strafe"); public static readonly string CELL_KEYBINDING_STRAFE_MODE = Create("SETTINGS_INPUT_CELL_KEYBINDING_STRAFE_MODE", "Strafe / Aim Mode"); public static readonly string CELL_KEYBINDING_STRAFE_MODE_OPTION_1 = Create("SETTINGS_INPUT_CELL_KEYBINDING_STRAFE_MODE_OPTION_1", "Hold Strafe Key"); public static readonly string CELL_KEYBINDING_STRAFE_MODE_OPTION_2 = Create("SETTINGS_INPUT_CELL_KEYBINDING_STRAFE_MODE_OPTION_2", "Toggle Strafe Key"); public static readonly string CELL_KEYBINDING_STRAFE_WEAPON = Create("SETTINGS_INPUT_CELL_KEYBINDING_STRAFE_WEAPON", "Strafe While Holding Weapon"); public static readonly string CELL_KEYBINDING_STRAFE_CASTING = Create("SETTINGS_INPUT_CELL_KEYBINDING_STRAFE_CASTING", "Strafe While Casting Offensive Skills"); public static readonly string HEADER_ACTION = Create("SETTINGS_INPUT_HEADER_ACTION", "Action"); public static readonly string CELL_KEYBINDING_ATTACK = Create("SETTINGS_INPUT_CELL_KEYBINDING_ATTACK", "Attack"); public static readonly string CELL_KEYBINDING_CHARGE_ATTACK = Create("SETTINGS_INPUT_CELL_KEYBINDING_CHARGE_ATTACK", "Charge Attack"); public static readonly string CELL_KEYBINDING_BLOCK = Create("SETTINGS_INPUT_CELL_KEYBINDING_BLOCK", "Block"); public static readonly string CELL_KEYBINDING_TARGET = Create("SETTINGS_INPUT_CELL_KEYBINDING_TARGET", "Lock On"); public static readonly string CELL_KEYBINDING_INTERACT = Create("SETTINGS_INPUT_CELL_KEYBINDING_INTERACT", "Interact"); public static readonly string CELL_KEYBINDING_PVP_FLAG = Create("SETTINGS_INPUT_CELL_KEYBINDING_PVP_FLAG", "PvP Flag Toggle"); public static readonly string CELL_KEYBINDING_SKILL_SLOT_01 = Create("SETTINGS_INPUT_CELL_KEYBINDING_SKILL_SLOT_01", "Skill Slot 1"); public static readonly string CELL_KEYBINDING_SKILL_SLOT_02 = Create("SETTINGS_INPUT_CELL_KEYBINDING_SKILL_SLOT_02", "Skill Slot 2"); public static readonly string CELL_KEYBINDING_SKILL_SLOT_03 = Create("SETTINGS_INPUT_CELL_KEYBINDING_SKILL_SLOT_03", "Skill Slot 3"); public static readonly string CELL_KEYBINDING_SKILL_SLOT_04 = Create("SETTINGS_INPUT_CELL_KEYBINDING_SKILL_SLOT_04", "Skill Slot 4"); public static readonly string CELL_KEYBINDING_SKILL_SLOT_05 = Create("SETTINGS_INPUT_CELL_KEYBINDING_SKILL_SLOT_05", "Skill Slot 5"); public static readonly string CELL_KEYBINDING_SKILL_SLOT_06 = Create("SETTINGS_INPUT_CELL_KEYBINDING_SKILL_SLOT_06", "Skill Slot 6"); public static readonly string CELL_KEYBINDING_RECALL = Create("SETTINGS_INPUT_CELL_KEYBINDING_RECALL", "Recall"); public static readonly string CELL_KEYBINDING_QUICKSWAP_WEAPON = Create("SETTINGS_INPUT_CELL_KEYBINDING_QUICKSWAP_WEAPON", "Quickswap Weapon"); public static readonly string CELL_KEYBINDING_SHEATHE_WEAPON = Create("SETTINGS_INPUT_CELL_KEYBINDING_SHEATHE_WEAPON", "Sheathe / Unsheathe Weapon"); public static readonly string CELL_KEYBINDING_SIT = Create("SETTINGS_INPUT_CELL_KEYBINDING_SIT", "Sit"); public static readonly string HEADER_CONSUMABLE_SLOTS = Create("SETTINGS_INPUT_HEADER_CONSUMABLE_SLOTS", "Consumable Quick Slots"); public static readonly string CELL_KEYBINDING_QUICK_SLOT_01 = Create("SETTINGS_INPUT_CELL_KEYBINDING_QUICK_SLOT_01", "Quick Slot 1"); public static readonly string CELL_KEYBINDING_QUICK_SLOT_02 = Create("SETTINGS_INPUT_CELL_KEYBINDING_QUICK_SLOT_02", "Quick Slot 2"); public static readonly string CELL_KEYBINDING_QUICK_SLOT_03 = Create("SETTINGS_INPUT_CELL_KEYBINDING_QUICK_SLOT_03", "Quick Slot 3"); public static readonly string CELL_KEYBINDING_QUICK_SLOT_04 = Create("SETTINGS_INPUT_CELL_KEYBINDING_QUICK_SLOT_04", "Quick Slot 4"); public static readonly string CELL_KEYBINDING_QUICK_SLOT_05 = Create("SETTINGS_INPUT_CELL_KEYBINDING_QUICK_SLOT_05", "Quick Slot 5"); public static readonly string HEADER_INTERFACE = Create("SETTINGS_INPUT_HEADER_INTERFACE", "Interface"); public static readonly string CELL_KEYBINDING_HOST_CONSOLE = Create("SETTINGS_INPUT_CELL_KEYBINDING_HOST_CONSOLE", "Host Console"); public static readonly string CELL_KEYBINDING_LEXICON = Create("SETTINGS_INPUT_CELL_KEYBINDING_LEXICON", "Open Lexicon"); public static readonly string CELL_KEYBINDING_TAB_MENU = Create("SETTINGS_INPUT_CELL_KEYBINDING_TAB_MENU", "Open Tab Menu"); public static readonly string CELL_KEYBINDING_STATS_TAB = Create("SETTINGS_INPUT_CELL_KEYBINDING_STATS_TAB", "Stats Tab"); public static readonly string CELL_KEYBINDING_SKILLS_TAB = Create("SETTINGS_INPUT_CELL_KEYBINDING_SKILLS_TAB", "Skills Tab"); public static readonly string CELL_KEYBINDING_ITEM_TAB = Create("SETTINGS_INPUT_CELL_KEYBINDING_ITEM_TAB", "Item Tab"); public static readonly string CELL_KEYBINDING_QUEST_TAB = Create("SETTINGS_INPUT_CELL_KEYBINDING_QUEST_TAB", "Quest Tab"); public static readonly string CELL_KEYBINDING_WHO_TAB = Create("SETTINGS_INPUT_CELL_KEYBINDING_WHO_TAB", "Who Tab"); public static readonly string CELL_KEYBINDING_HIDE_UI = Create("SETTINGS_INPUT_CELL_KEYBINDING_HIDE_UI", "Hide Game UI"); public static readonly string CELL_RESET_BINDINGS = Create("SETTINGS_INPUT_CELL_RESET_BINDINGS", "Reset Bindings"); internal static void init() { } } public static class Mod { public static readonly TranslationKey LANGUAGE = Create(ConfigDefinitions.Language); public static readonly TranslationKey TRANSLATOR_MODE = Create(ConfigDefinitions.TraslatorMode); public static readonly TranslationKey CREATE_DEFAULT_LANGUAGE_FILES = Create(ConfigDefinitions.CreateDefaultLanguageFiles); public static readonly TranslationKey SHOW_TRANSLATION_KEY = Create(ConfigDefinitions.ShowTranslationKey); public static readonly TranslationKey EXPORT_EXTRA = Create(ConfigDefinitions.ExportExtra); public static readonly TranslationKey RELOAD_LANGUAGE_KEYBIND = Create(ConfigDefinitions.ReloadLanguageKeybind); public static readonly TranslationKey LOG_VANILLA_FONTS = Create(ConfigDefinitions.LogVanillaFonts); public static readonly TranslationKey RELOAD_FONT_BUNDLES_KEYBIND = Create(ConfigDefinitions.ReloadFontBundlesKeybind); public static readonly TranslationKey SWITCH_TRANSLATION_KEYBIND = Create(ConfigDefinitions.SwitchTranslationKeybind); public static readonly TranslationKey ADD_MISSING_KEYS_TO_CURRENT_LANGUAGE = Create("ADD_MISSING_KEYS_TO_CURRENT_LANGUAGE", "Add Missing Keys to Current Language"); public static readonly TranslationKey LOG_UNTRANSLATED_STRINGS = Create("LOG_UNTRANSLATED_STRINGS", "Log Untranslated Strings"); internal static void Init() { } private static TranslationKey Create(string key, string defaultValue = "") { return I18nKeys.Create("SETTINGS_MOD_CELL_LOCALYSSATION_" + key, defaultValue); } private static TranslationKey Create(ConfigDefinition configEntry) { return Create(KeyUtil.Normalize(configEntry.Key), configEntry.Key); } } internal static class Network { public static readonly string HEADER_GAME_SETTINGS = Create("SETTINGS_NETWORK_HEADER_GAME_SETTINGS", "Game Settings"); public static readonly string CELL_ENABLE_PVP_ON_MAP_ENTER = Create("SETTINGS_NETWORK_CELL_ENABLE_PVP_ON_MAP_ENTER", "Flag for PvP when available"); public static readonly string HEADER_NAMETAG_SETTINGS = Create("SETTINGS_NETWORK_HEADER_NAMETAG_SETTINGS", "Nametag Settings"); public static readonly string CELL_DISPLAY_GLOBAL_NICKNAME_TAGS = Create("SETTINGS_NETWORK_CELL_DISPLAY_GLOBAL_NICKNAME_TAGS", "Display Global Nametags <color=cyan>(@XX)</color>"); public static readonly string CELL_DISPLAY_LOCAL_NAMETAG = Create("SETTINGS_NETWORK_CELL_DISPLAY_LOCAL_NAMETAG", "Display Local Character Name Tag"); public static readonly string CELL_DISPLAY_HOST_TAG = Create("SETTINGS_NETWORK_CELL_DISPLAY_HOST_TAG", "Display [HOST] Tag on Host Character"); public static readonly string HEADER_UI_SETTINGS = Create("SETTINGS_NETWORK_HEADER_UI_SETTINGS", "UI Settings"); public static readonly string CELL_HIDE_FPS_COUNTER = Create("SETTINGS_NETWORK_CELL_HIDE_FPS_COUNTER", "Hide FPS Counter"); public static readonly string CELL_HIDE_PING_COUNTER = Create("SETTINGS_NETWORK_CELL_HIDE_PING_COUNTER", "Hide Ping Counter"); public static readonly string CELL_HIDE_STAT_POINT_COUNTER = Create("SETTINGS_NETWORK_CELL_HIDE_STAT_POINT_COUNTER", "Hide Stat Point Notice Panel"); public static readonly string CELL_HIDE_SKILL_POINT_COUNTER = Create("SETTINGS_NETWORK_CELL_HIDE_SKILL_POINT_COUNTER", "Hide Skill Point Notice Panel"); public static readonly string CELL_HIDE_QUEST_TRACKER = Create("SETTINGS_NETWORK_CELL_HIDE_QUEST_TRACKER", "Hide Quest Tracker"); public static readonly string CELL_HIDE_MINIMAP = Create("SETTINGS_NETWORK_CELL_HIDE_MINIMAP", "Hide Minimap"); public static readonly string CELL_HIDE_DAMAGE_VALUE_NUMBER_ICONS = Create("SETTINGS_NETWORK_CELL_HIDE_VALUE_NUMBER_ICONS", "Hide Value Number Icons"); public static readonly string HEADER_CHATBOX_SETTINGS = Create("SETTINGS_NETWORK_HEADER_CHATBOX_SETTINGS", "Chatbox Settings"); public static readonly string CELL_DEFAULT_CHANNEL = Create("SETTINGS_NETWORK_CELL_DEFAULT_CHANNEL", "Default #Room Channel"); public static readonly string CELL_FADE_CHAT_TEXT = Create("SETTINGS_NETWORK_CELL_FADE_CHAT_TEXT", "Fade Chat Text"); public static readonly string CELL_FADE_GAME_FEED_TEXT = Create("SETTINGS_NETWORK_CELL_FADE_GAME_FEED_TEXT", "Fade Game Feed Text"); internal static void Init() { } } internal static class Video { public static readonly string HEADER_GAME_EFFECT_SETTINGS = Create("SETTINGS_VIDEO_HEADER_GAME_EFFECT_SETTINGS", "Display Sensitive Settings"); public static readonly string CELL_PROPORTIONS_TOGGLE = Create("SETTINGS_VIDEO_CELL_PROPORTIONS_TOGGLE", "Limit Player Character Proportions"); public static readonly string CELL_JIGGLE_BONES_TOGGLE = Create("SETTINGS_VIDEO_CELL_JIGGLE_BONES_TOGGLE", "Disable Suggestive Jiggle Bones"); public static readonly string CELL_CLEAR_UNDERCLOTHES_TOGGLE = Create("SETTINGS_VIDEO_CELL_CLEAR_UNDERCLOTHES_TOGGLE", "Enable Clear Clothing"); public static readonly string HEADER_VIDEO_SETTINGS = Create("SETTINGS_VIDEO_HEADER_VIDEO_SETTINGS", "Video Settings"); public static readonly string CELL_SCREEN_MODE = CreateCell("SCREEN_MODE", "Screen Mode"); public static readonly TranslationKey[] CELL_SCREEN_MODE_OPTIONS = CreateOptions(CELL_SCREEN_MODE, new string[3] { "Windowed", "Fullscreen", "Fullscreen (Borderless)" }); public static readonly string CELL_FULLSCREEN_TOGGLE = Create("SETTINGS_VIDEO_CELL_FULLSCREEN_TOGGLE", "Fullscreen Mode"); public static readonly string CELL_VERTICAL_SYNC = Create("SETTINGS_VIDEO_CELL_VERTICAL_SYNC", "Vertical Sync / Lock 60 FPS"); public static readonly string CELL_ANISOTROPIC_FILTERING = Create("SETTINGS_VIDEO_CELL_ANISOTROPIC_FILTERING", "Anisotropic Filtering"); public static readonly string CELL_SCREEN_RESOLUTION = Create("SETTINGS_VIDEO_CELL_SCREEN_RESOLUTION", "Screen Resolution"); public static readonly string CELL_ANTI_ALIASING = Create("SETTINGS_VIDEO_CELL_ANTI_ALIASING", "Anti Aliasing"); public static readonly TranslationKey[] CELL_ANTI_ALIASING_OPTIONS = CreateOptions(CELL_ANTI_ALIASING, new string[4] { "Disabled", "2x Multi Sampling", "4x Multi Sampling", "8x Multi Sampling" }); public static readonly string CELL_TEXTURE_FILTERING = Create("SETTINGS_VIDEO_CELL_TEXTURE_FILTERING", "Texture Filtering"); public static readonly TranslationKey[] CELL_TEXTURE_FILTERING_OPTIONS = CreateOptions(CELL_TEXTURE_FILTERING, new string[2] { "Bilnear (Smooth)", "Nearest (Crunchy)" }); public static readonly string CELL_TEXTURE_QUALITY = Create("SETTINGS_VIDEO_CELL_TEXTURE_QUALITY", "Texture Quality"); public static readonly TranslationKey[] CELL_TEXTURE_QUALITY_OPTIONS = CreateOptions(CELL_TEXTURE_QUALITY, new string[4] { "High", "Medium", "Low", "Very Low" }); public static readonly string HEADER_CAMERA_SETTINGS = Create("SETTINGS_VIDEO_HEADER_CAMERA_SETTINGS", "Camera Display Settings"); public static readonly string CELL_FIELD_OF_VIEW = Create("SETTINGS_VIDEO_CELL_FIELD_OF_VIEW", "Field Of View"); public static readonly string CELL_CAMERA_SMOOTHING = Create("SETTINGS_VIDEO_CELL_CAMERA_SMOOTHING", "Camera Smoothing"); public static readonly string CELL_CAMERA_HORIZ = Create("SETTINGS_VIDEO_CELL_CAMERA_HORIZ", "Camera X Position"); public static readonly string CELL_CAMERA_VERT = Create("SETTINGS_VIDEO_CELL_CAMERA_VERT", "Camera Y Position"); public static readonly string CELL_CAMERA_RENDER_DISTANCE = Create("SETTINGS_VIDEO_CELL_CAMERA_RENDER_DISTANCE", "Render Distance"); public static readonly TranslationKey[] CELL_CAMERA_RENDER_DISTANCE_OPTIONS = CreateOptions(CELL_CAMERA_RENDER_DISTANCE, new string[4] { "Very Near", "Near", "Far", "Very Far" }); public static readonly string HEADER_CURSOR_SETTINGS = Create("SETTINGS_VIDEO_HEADER_CURSOR_SETTINGS", "Cursor Settings"); public static readonly string CELL_CURSOR_GRAPHIC = Create("SETTINGS_VIDEO_CELL_CURSOR_GRAPHIC", "Cursor Graphic"); public static readonly string CELL_HARDWARE_CURSOR = Create("SETTINGS_VIDEO_CELL_HARDWARE_CURSOR", "Hardware Cursor"); public static readonly string HEADER_POST_PROCESSING = Create("SETTINGS_VIDEO_HEADER_POST_PROCESSING", "Post Processing"); public static readonly string CELL_CAMERA_BITCRUSH_SHADER = Create("SETTINGS_VIDEO_CELL_CAMERA_BITCRUSH_SHADER", "Enable Bitcrush Shader"); public static readonly string CELL_CAMERA_WATER_EFFECT = Create("SETTINGS_VIDEO_CELL_CAMERA_WATER_EFFECT", "Enable Underwater Distortion Shader"); public static readonly string CELL_CAMERA_SHAKE = Create("SETTINGS_VIDEO_CELL_CAMERA_SHAKE", "Enable Screen Shake"); public static readonly string CELL_WEAPON_GLOW = Create("SETTINGS_VIDEO_CELL_WEAPON_GLOW", "Disable Weapon Glow Effect"); public static readonly string CELL_DISABLE_GIB_EFFECT = Create("SETTINGS_VIDEO_CELL_DISABLE_GIB_EFFECT", "Disable Gib Effect"); private static string CreateCell(string key, string defaultString) { return Create("SETTINGS_VIDEO_CELL_" + key, defaultString); } private static TranslationKey[] CreateOptions(string parentKey, string[] defaultStrings) { return defaultStrings.Select((string value, int index) => Create($"{parentKey}_OPTION_{index + 1}", value)).ToArray(); } internal static void Init() { } } public static readonly TranslationKey BUTTON_VIDEO = Create("SETTINGS_TAB_BUTTON_VIDEO", "Display"); public static readonly TranslationKey BUTTON_AUDIO = Create("SETTINGS_TAB_BUTTON_AUDIO", "Audio"); public static readonly TranslationKey BUTTON_INPUT = Create("SETTINGS_TAB_BUTTON_INPUT", "Input"); public static readonly TranslationKey BUTTON_NETWORK = Create("SETTINGS_TAB_BUTTON_NETWORK", "Interface"); public static readonly TranslationKey BUTTON_MODS = Create("SETTINGS_TAB_BUTTON_MODS", "Mods"); public static readonly TranslationKey BUTTON_RESET_TO_DEFAULTS = Create("SETTINGS_BUTTON_RESET_TO_DEFAULTS", "Reset to Defaults"); public static readonly TranslationKey BUTTON_RESET = Create("SETTINGS_BUTTON_RESET", "Reset"); public static readonly TranslationKey BUTTON_CANCEL = Create("SETTINGS_BUTTON_CANCEL", "Cancel"); public static readonly TranslationKey BUTTON_APPLY = Create("SETTINGS_BUTTON_APPLY", "Apply"); internal static void Init() { Video.Init(); Audio.Init(); Input.init(); Network.Init(); Mod.Init(); } } internal static class SkillMenu { public static readonly TranslationKey RANK_SOULBOUND = Create("SKILL_RANK_SOULBOUND", "Soulbound Skill"); public static readonly TranslationKey RANK = Create("FORMAT_SKILL_RANK", "[Rank {0} / {1}]"); public static readonly TranslationKey SKILL_POINT_COST_FORMAT = Create("SKILL_POINT_COST_FORMAT", "Point Cost: {0}"); public static readonly TranslationKey TOOLTIP_DAMAGE_TYPE = Create("FORMAT_SKILL_TOOLTIP_DAMAGE_TYPE", "{0} Skill"); public static readonly TranslationKey TOOLTIP_ITEM_COST = Create("FORMAT_SKILL_TOOLTIP_ITEM_COST", "{0} {1}"); public static readonly TranslationKey TOOLTIP_MANA_COST = Create("FORMAT_SKILL_TOOLTIP_MANA_COST", "{0} Mana"); public static readonly TranslationKey TOOLTIP_HEALTH_COST = Create("FORMAT_SKILL_TOOLTIP_HEALTH_COST", "{0} Health"); public static readonly TranslationKey TOOLTIP_STAMINA_COST = Create("FORMAT_SKILL_TOOLTIP_STAMINA_COST", "{0} Stamina"); public static readonly TranslationKey TOOLTIP_CAST_TIME_INSTANT = Create("SKILL_TOOLTIP_CAST_TIME_INSTANT", "Instant Cast"); public static readonly TranslationKey TOOLTIP_CAST_TIME = Create("FORMAT_SKILL_TOOLTIP_CAST_TIME", "{0} sec Cast"); public static readonly TranslationKey TOOLTIP_COOLDOWN = Create("FORMAT_SKILL_TOOLTIP_COOLDOWN", "{0} sec Cooldown"); public static readonly TranslationKey TOOLTIP_PASSIVE = Create("SKILL_TOOLTIP_PASSIVE", "Passive Skill"); public static readonly TranslationKey TOOLTIP_DESCRIPTOR_MANACOST = Create("FORMAT_SKILL_TOOLTIP_DESCRIPTOR_MANACOST", "<color=yellow>Costs {0} Mana.</color>"); public static readonly TranslationKey TOOLTIP_DESCRIPTOR_HEALTHCOST = Create("FORMAT_SKILL_TOOLTIP_DESCRIPTOR_HEALTHCOST", "<color=yellow>Costs {0} Health.</color>"); public static readonly TranslationKey TOOLTIP_DESCRIPTOR_STAMINACOST = Create("FORMAT_SKILL_TOOLTIP_DESCRIPTOR_STAMINACOST", "<color=yellow>Costs {0} Stamina.</color>"); public static readonly TranslationKey TOOLTIP_DESCRIPTOR_COOLDOWN = Create("FORMAT_SKILL_TOOLTIP_DESCRIPTOR_COOLDOWN", "<color=yellow>{0} sec cooldown.</color>"); public static readonly TranslationKey TOOLTIP_DESCRIPTOR_CAST_TIME = Create("FORMAT_SKILL_TOOLTIP_DESCRIPTOR_CAST_TIME", "<color=yellow>{0} sec cast time.</color>"); public static readonly TranslationKey TOOLTIP_DESCRIPTOR_CAST_TIME_INSTANT = Create("SKILL_TOOLTIP_DESCRIPTOR_CAST_TIME_INSTANT", "<color=yellow>instant cast time.</color>"); public static readonly TranslationKey TOOLTIP_REQUIEMENT_FORMAT = Create("FORMAT_SKILL_TOOLTIP_REQUIREMENT", " <color=yellow>Requirement a {0} weapon.</color>"); public static readonly TranslationKey TOOLTIP_REQUIRE_SHIELD = Create("SKILL_TOOLTIP_REQUIREMENT_SHIELD", " <color=yellow>Requires a shield.</color>"); public static readonly TranslationKey TOOLTIP_DESCRIPTOR_CONDITION_CANCEL_ON_HIT = Create("SKILL_TOOLTIP_DESCRIPTOR_CONDITION_CANCEL_ON_HIT", " <color=yellow>Cancels if hit.</color>"); public static readonly TranslationKey TOOLTIP_DESCRIPTOR_CONDITION_IS_STACKABLE = Create("SKILL_TOOLTIO_DESCRIPTOR_CONDITION_IS_STACKABLE", " <color=yellow>Stackable.</color>"); public static readonly TranslationKey TOOLTIP_DESCRIPTOR_CONDITION_CHANCE = Create("SKILL_TOOLTIP_DESCRIPTOR_CONDITION_CHANCE", "\n\n<color=cyan>{0} - ({1}) ({2}% Chance)</color>"); internal static void Init() { } } public static class SteamLobby { public static readonly TranslationKey LOBBY_HOST_HEADER = Create("LOBBY_HOST_HEADER", "Host Lobby"); public static readonly TranslationKey LOBBY_HOST_HEADER_STEAM_UNAVAILABLE = Create("LOBBY_HOST_HEADER_STEAM_UNAVAILABLE", "Steam is not Initialized."); public static readonly TranslationKey TAG_LOBBY_NAME = Create("TAG_LOBBY_NAME", "Lobby Name"); public static readonly TranslationKey TAG_LOBBY_PASSWORD = Create("TAG_LOBBY_PASSWORD", "Lobby Password"); public static readonly TranslationKey TAG_MOTD = Create("TAG_MOTD", "Message Of The Day"); public static readonly TranslationKey TAG_LOBBY_TYPE = Create("TAG_LOBBY_TYPE", "Lobby Type"); public static readonly TranslationKey TAG_MAX_PLAYERS = Create("TAG_MAX_PLAYERS", "Max Players"); public static readonly TranslationKey TAG_STREAM_MODE = Create("TAG_STREAM_MODE", "Stream Mode (Disable Chat)"); public static readonly TranslationKey TAG_LOBBY_REALM = Create("TAG_LOBBY_REALM", "Lobby Realm"); public static readonly TranslationKey BUTTON_RETURN = Create("BUTTON_RETURN", "Return"); public static readonly TranslationKey BUTTON_HOST_LOBBY = Create("BUTTON_HOST_LOBBY", "Host Lobby"); public static readonly TranslationKey PLACEHOLDER_LOBBY_NAME = Create("PLACEHOLDER_LOBBY_NAME", "Enter text..."); public static readonly TranslationKey PLACEHOLDER_LOBBY_PASSWORD = Create("PLACEHOLDER_LOBBY_PASSWORD", "Enter Password..."); public static readonly TranslationKey PLACEHOLDER_MOTD = Create("PLACEHOLDER_MOTD", "Enter Message..."); public static readonly TranslationKey LOBBY_TYPE_DESCRIPTION_PUBLIC = Create("LOBBY_TYPE_DESCRIPTION_PUBLIC", "Public lobbies will be advertised for anyone to join."); public static readonly TranslationKey LOBBY_TYPE_DESCRIPTION_FRIENDS = Create("LOBBY_TYPE_DESCRIPTION_FRIENDS", "Friend lobbies are joinable by invite or from the Steam friends list."); public static readonly TranslationKey LOBBY_TYPE_DESCRIPTION_PRIVATE = Create("LOBBY_TYPE_DESCRIPTION_PRIVATE", "Private lobbies are by invitation from Host only."); public static readonly TranslationKey CLEARED_HIDDEN_LOBBY_CACHE = Create("CLEARED_HIDDEN_LOBBY_CACHE", "Cleared hidden lobby cache..."); public static readonly TranslationKey HIDDEN_LOBBY_COUNT_FORMAT = Create("HIDDEN_LOBBY_COUNT_FORMAT", "Hidden Lobbies: {0}"); public static readonly TranslationKey STEAM_NOT_INITIALIZED = Create("STEAM_NOT_INITIALIZED", "Steam is not initialized."); public static readonly TranslationKey SEARCHING_FOR_LOBBIES = Create("SEARCHING_FOR_LOBBIES", "Searching..."); public static readonly TranslationKey NO_LOBBIES_FOUND = Create("NO_LOBBIES_FOUND", "No lobbies found."); public static readonly TranslationKey LOBBY_FOUNDED_COUNT_FORMAT_1 = Create("LOBBY_FOUNDED_COUNT_FORMAT_1", "{0} lobby found."); public static readonly TranslationKey LOBBY_FOUNDED_COUNT_FORMAT_PLURAL = Create("LOBBY_FOUNDED_COUNT_FORMAT_PLURAL", "{0} lobbies found."); public static readonly TranslationKey LOBBY_FULL = Create("LOBBY_FULL", "Lobby Full"); public static readonly TranslationKey LOBBY_PASSWORD_LOBBY = Create("LOBBY_PASSWORD_LOBBY", "Password Lobby"); public static readonly TranslationKey LOBBY_DIFFERENT_VERSION = Create("LOBBY_DIFFERENT_VERSION", "Different Version"); public static readonly TranslationKey LOBBY_INVALID = Create("LOBBY_INVALID", "Invalid Lobby"); public static readonly TranslationKey LOBBY_JOIN_FRIEND = Create("LOBBY_JOIN_FRIEND", "Join Lobby (Friend)"); public static readonly TranslationKey LOBBY_PLAYER_COUNT = Create("LOBBY_PLAYER_COUNT", "Players: "); public static readonly TranslationKey UNTITLED_LOBBY = Create("UNTITLED_LOBBY", "Untitled Lobby"); public static readonly TranslationKey LOBBY_PING_FORMAT = Create("LOBBY_PING_FORMAT", "Ping: {0}ms"); public static readonly TranslationKey MODDED_LOBBY = Create("MODDED_LOBBY", "Modded Lobby"); public static readonly TranslationKey JOIN_LOBBY = Create("JOIN_LOBBY", "Join Lobby"); public static readonly TranslationKey CLEAR_HIDDEN_LOBBY_BUTTON = Create("CLEAR_HIDDEN_LOBBY_BUTTON", "Clear Hidden Lobby Cache"); public static readonly TranslationKey LOBBY_LIST_FILTER_BASE = Create("LOBBY_LIST_FILTER", "Lobby List Filter"); public static readonly TranslationKey[] LOBBY_LIST_FILTER = CreateOptions(LOBBY_LIST_FILTER_BASE, new string[3] { "Nearby", "Far", "Worldwide" }); public static readonly TranslationKey LOBBY_TYPE_BASE = Create("LOBBY_TYPE", "Lobby Type"); public static readonly TranslationKey[] LOBBY_TYPES = CreateOptions(LOBBY_TYPE_BASE, new string[3] { "Public", "Friends", "Private" }); public static readonly TranslationKey PLACEHOLDER_LOBBY_NAME_SEARCH = Create("PLACEHOLDER_LOBBY_NAME_SEARCH", "Search Lobby Name..."); internal static void Init() { } private static TranslationKey Create(string key, string defaultValue = "") { return I18nKeys.Create("STEAM_LOBBY_" + key, defaultValue); } } internal static class TabMenu { public static readonly string PAGER_FORMAT = Create("PAGER_FORMAT", "Page ( {0} / {1} )"); public static readonly string PAGER_1_PAGE = Create("PAGER_1_PAGE", "Page ( 1 / 1 )"); public static readonly TranslationKey POINTS_AVAILABLE = Create("TAB_MENU_POINTS_AVAILABLE", "Points Available"); public static readonly string CELL_STATS_HEADER = Create("TAB_MENU_CELL_STATS_HEADER", "Stats"); public static readonly string CELL_STATS_ATTRIBUTE_POINT_COUNTER = Create("TAB_MENU_CELL_STATS_ATTRIBUTE_POINT_COUNTER", "Points"); public static readonly string CELL_STATS_BUTTON_APPLY_ATTRIBUTE_POINTS = Create("TAB_MENU_CELL_STATS_BUTTON_APPLY_ATTRIBUTE_POINTS", "Apply"); public static readonly string CELL_STATS_INFO_CELL_NICK_NAME = Create("TAB_MENU_CELL_STATS_INFO_CELL_NICK_NAME", "Nickname"); public static readonly string CELL_STATS_INFO_CELL_RACE_NAME = Create("TAB_MENU_CELL_STATS_INFO_CELL_RACE_NAME", "Race"); public static readonly string CELL_STATS_INFO_CELL_CLASS_NAME = Create("TAB_MENU_CELL_STATS_INFO_CELL_CLASS_NAME", "Class"); public static readonly string CELL_STATS_INFO_CELL_LEVEL_COUNTER = Create("TAB_MENU_CELL_STATS_INFO_CELL_LEVEL_COUNTER", "Level"); public static readonly string CELL_STATS_INFO_CELL_EXPERIENCE = Create("TAB_MENU_CELL_STATS_INFO_CELL_EXPERIENCE", "Experience"); public static readonly string CELL_STATS_INFO_CELL_MAX_HEALTH = Create("TAB_MENU_CELL_STATS_INFO_CELL_MAX_HEALTH", "Health"); public static readonly string CELL_STATS_INFO_CELL_MAX_MANA = Create("TAB_MENU_CELL_STATS_INFO_CELL_MAX_MANA", "Mana"); public static readonly string CELL_STATS_INFO_CELL_MAX_STAMINA = Create("TAB_MENU_CELL_STATS_INFO_CELL_MAX_STAMINA", "Stamina"); public static readonly string CELL_STATS_INFO_CELL_ATTACK = Create("TAB_MENU_CELL_STATS_INFO_CELL_ATTACK", "Attack Power"); public static readonly string CELL_STATS_INFO_CELL_RANGED_POWER = Create("TAB_MENU_CELL_STATS_INFO_CELL_RANGED_POWER", "Dex Power"); public static readonly string CELL_STATS_INFO_CELL_PHYS_CRITICAL = Create("TAB_MENU_CELL_STATS_INFO_CELL_PHYS_CRITICAL", "Phys. Crit %"); public static readonly string CELL_STATS_INFO_CELL_MAGIC_POW = Create("TAB_MENU_CELL_STATS_INFO_CELL_MAGIC_POW", "Mgk. Power"); public static readonly string CELL_STATS_INFO_CELL_MAGIC_CRIT = Create("TAB_MENU_CELL_STATS_INFO_CELL_MAGIC_CRIT", "Mgk. Crit %"); public static readonly string CELL_STATS_INFO_CELL_DEFENSE = Create("TAB_MENU_CELL_STATS_INFO_CELL_DEFENSE", "Defense"); public static readonly string CELL_STATS_INFO_CELL_MAGIC_DEF = Create("TAB_MENU_CELL_STATS_INFO_CELL_MAGIC_DEF", "Mgk. Defense"); public static readonly string CELL_STATS_INFO_CELL_EVASION = Create("TAB_MENU_CELL_STATS_INFO_CELL_EVASION", "Evasion %"); public static readonly string CELL_STATS_INFO_CELL_MOVE_SPD = Create("TAB_MENU_CELL_STATS_INFO_CELL_MOVE_SPD", "Mov Spd %"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_BEGIN = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_BEGIN", "<b>Base Stat:</b> <i>"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_END_CRIT = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_END_CRIT", "%</i> (Critical %)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_END_EVASION = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_END_EVASION", "%</i> (Evasion %)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_ATTACK_POW = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_ATTACK_POW", "{0}</i> (Attack Power)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAX_MP = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAX_MP", "{0}</i> (Max Mana)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAX_HP = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAX_HP", "{0}</i> (Max Health)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_RANGE_POW = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_RANGE_POW", "{0}</i> (Dex Power)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_END_MAGIC_CRIT = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_END_MAGIC_CRIT", "%</i> (Magic Critical %)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAGIC_DEF = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAGIC_DEF", "{0}</i> (Magic Defense)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_DEFENSE = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_DEFENSE", "{0}</i> (Defense)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAGIC_POW = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAGIC_POW", "{0}</i> (Magic Power)"); public static readonly string CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAX_STAM = Create("TAB_MENU_CELL_STATS_TOOLTIP_BASE_STAT_FORMAT_MAX_STAM", "{0}</i> (Max Stamina)"); public static readonly string CELL_SKILLS_HEADER = Create("TAB_MENU_CELL_SKILLS_HEADER", "Skills"); public static readonly string CELL_SKILLS_SKILL_POINT_COUNTER = Create("TAB_MENU_CELL_SKILLS_SKILL_POINT_COUNTER", "Skill Points"); public static readonly string CELL_SKILLS_CLASS_TAB_TOOLTIP_NOVICE = Create("TAB_MENU_CELL_SKILLS_CLASS_TAB_TOOLTIP_NOVICE", "General Skills"); public static readonly string CELL_SKILLS_CLASS_TAB_TOOLTIP = Create("TAB_MENU_CELL_SKILLS_CLASS_TAB_TOOLTIP", "{0} Skills"); public static readonly string CELL_SKILLS_CLASS_HEADER_NOVICE = Create("TAB_MENU_CELL_SKILLS_CLASS_HEADER_NOVICE", "General Skillbook"); public static readonly string CELL_SKILLS_CLASS_HEADER = Create("TAB_MENU_CELL_SKILLS_CLASS_HEADER", "{0} Skillbook"); public static readonly string CELL_OPTIONS_HEADER = Create("TAB_MENU_CELL_OPTIONS_HEADER", "Options"); public static readonly string CELL_OPTIONS_BUTTON_SETTINGS = Create("TAB_MENU_CELL_OPTIONS_BUTTON_SETTINS", "Settings"); public static readonly string CELL_OPTIONS_BUTTON_SAVE_FILE = Create("TAB_MENU_CELL_OPTIONS_BUTTON_SAVE_FILE", "Save File"); public static readonly string CELL_OPTIONS_BUTTON_INVITE_TO_LOBBY = Create("TAB_MENU_CELL_OPTIONS_BUTTON_INVITE_TO_LOBBY", "Invite to Lobby"); public static readonly string CELL_OPTIONS_BUTTON_HOST_CONSOLE = Create("TAB_MENU_CELL_OPTIONS_BUTTON_HOST_CONSOLE", "Host Console"); public static readonly string CELL_OPTIONS_BUTTON_SAVE_AND_QUIT = Create("TAB_MENU_CELL_OPTIONS_BUTTON_SAVE_AND_QUIT", "Save & Quit"); public static readonly string CELL_OPTIONS_CONFIRM_QUIT_HEADER = Create("TAB_MENU_CELL_OPTIONS_CONFIRM_QUIT_HEADER", "Save and Quit Game?"); public static readonly string CELL_OPTIONS_CONFIRM_QUIT_CONFIRM = Create("TAB_MENU_CELL_OPTIONS_CONFIRM_QUIT_CONFIRM", "Confirm"); public static readonly string CELL_OPTIONS_CONFIRM_QUIT_CANCEL = Create("TAB_MENU_CELL_OPTIONS_CONFIRM_QUIT_CANCEL", "Cancel"); public static readonly string CELL_ITEMS_HEADER = Create("TAB_MENU_CELL_ITEMS_HEADER", "Items"); public static readonly string CELL_ITEMS_EQUIP_TAB_HEADER_EQUIPMENT = Create("TAB_MENU_CELL_ITEMS_EQUIP_TAB_HEADER_EQUIPMENT", "Equipment"); public static readonly string CELL_ITEMS_EQUIP_TAB_HEADER_VANITY = Create("TAB_MENU_CELL_ITEMS_EQUIP_TAB_HEADER_VANITY", "Vanity"); public static readonly string CELL_ITEMS_EQUIP_TAB_HEADER_STAT = Create("TAB_MENU_CELL_ITEMS_EQUIP_TAB_HEADER_STAT", "Stats"); public static readonly string CELL_ITEMS_INVENTORY_TYPE_EQUIPMENT = CreateCellItems("INVENTORY_TYPE_EQUIPMENT", "Equipment"); public static readonly string CELL_ITEMS_INVENTORY_TYPE_CONSUMABLE = CreateCellItems("INVENTORY_TYPE_CONSUMABLE", "Consumables"); public static readonly string CELL_ITEMS_INVENTORY_TYPE_TRADE_ITEM = CreateCellItems("INVENTORY_TYPE_TRADE_TYPE", "Trade Items"); public static readonly string CELL_ITEMS_INVENTORY_SORT_ITEMS = CreateCellItems("INVENTORY_SORT_ITEMS", "Sort Items"); public static readonly TranslationKey DROP_ITEM_ABANDON_QUEST_FORMAT = Create("TAB_MENU_DROP_ITEM_ABANDON_QUEST_FORMAT", "Abandoned Quest: {0}"); public static readonly IDictionary<string, string> CELL_ITEMS_PROMPT_BUTTONS = new string[7] { "equip", "transmogrify", "remove", "use", "split", "drop", "cancel" }.ToDictionary((string x) => x, (string x) => CreateCellItems("PROMPT_BUTTON_" + x.ToUpper(), char.ToUpper(x[0]) + x.Substring(1))); public static readonly string CELL_QUESTS_HEADER = Create("TAB_MENU_CELL_QUESTS_HEADER", "Quests"); public static readonly string CELL_QUESTS_BUTTON_ABANDON = Create("TAB_MENU_CELL_QUESTS_BUTTON_ABANDON", "Abandon Quest"); public static readonly string CELL_WHO_HEADER = Create("TAB_MENU_CELL_WHO_HEADER", "Who"); public static readonly string CELL_WHO_BUTTON_INVITE_TO_PARTY = Create("TAB_MENU_CELL_WHO_BUTTON_INVITE_TO_PARTY", "Invite to Party"); public static readonly string CELL_WHO_BUTTON_LEAVE_PARTY = Create("TAB_MENU_CELL_WHO_BUTTON_LEAVE_PARTY", "Leave Party"); public static readonly string CELL_WHO_BUTTON_MUTE_PEER = Create("TAB_MENU_CELL_WHO_BUTTON_MUTE_PEER", "Mute / Unmute"); public static readonly string CELL_WHO_BUTTON_REFRESH_LIST = Create("TAB_MENU_CELL_WHO_BUTTON_REFRESH_LIST", "Refresh"); internal static void Init() { } private static string CreateCellItems(string key, string value = "") { return Create("TAB_MENU_CELL_ITEMS_" + key, value); } } internal static readonly Dictionary<string, string> TR_KEYS = new Dictionary<string, string>(); public static void Init() { CharacterCreation.Init(); CharacterSelect.Init(); ChatBehaviour.Init(); ChatMessage.Init(); Enchanter.Init(); Enums.Init(); Equipment.Init(); ErrorMessages.Init(); Feedback.Init(); Item.Init(); Lore.Init(); MainMenu.Init(); Quest.Init(); ScriptableStatusCondition.Init(); Settings.Init(); SkillMenu.Init(); SteamLobby.Init(); TabMenu.Init(); } private static TranslationKey Create(string key, string defaultString = "") { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key is empty"); } if (string.IsNullOrEmpty(defaultString)) { defaultString = key; } if (TR_KEYS.ContainsKey(key)) { throw new ArgumentException("key `" + key + "` Already Exists!"); } TR_KEYS[key] = defaultString; return new TranslationKey(key); } private static TranslationKey[] CreateOptions(string key, string[] defaultStrings) { return (from i in Enumerable.Range(0, defaultStrings.Length) select Create(new TranslationKey(key).Option[i], defaultStrings[i])).ToArray(); } public static string GetDefaulted(string key) { if (TR_KEYS.TryGetValue(key, out var value)) { return value; } return key; } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("org.sallys-workshop.localyssation", "Localyssation", "2.2.1")] public class Localyssation : BaseUnityPlugin { private delegate string TextEditTagFunc(string str, string arg, int fontSize); public static Localyssation instance; internal static Assembly assembly; internal static string dllPath; internal static ManualLogSource logger; internal static bool settingsTabReady = false; internal static bool languagesLoaded = false; internal static bool settingsTabSetup = false; public const string GET_STRING_DEFAULT_VALUE_ARG_UNSPECIFIED = "SAME_AS_KEY"; private static readonly Dictionary<string, TextEditTagFunc> textEditTags = new Dictionary<string, TextEditTagFunc> { { "firstupper", delegate(string str, string arg, int fontSize) { if (str.Length > 0) { string text2 = str[0].ToString(); str = str.Remove(0, 1); str = str.Insert(0, text2.ToUpper()); } return str; } }, { "firstlower", delegate(string str, string arg, int fontSize) { if (str.Length > 0) { string text = str[0].ToString(); str = str.Remove(0, 1); str = str.Insert(0, text.ToLower()); } return str; } }, { "scale", delegate(string str, string arg, int fontSize) { if (fontSize > 0) { try { float num2 = float.Parse(arg, CultureInfo.InvariantCulture); str = $"<size={Math.Round((float)fontSize * num2)}>{str}</size>"; } catch { } } else { str = "<scalefallback=" + arg + ">" + str + "</scalefallback>"; } return str; } }, { "scalefallback", delegate(string str, string arg, int fontSize) { if (fontSize > 0) { try { float num = float.Parse(arg, CultureInfo.InvariantCulture); str = $"<size={Math.Round((float)fontSize * num)}>{str}</size>"; } catch { } } return str; } } }; private static readonly List<string> defaultAppliedTextEditTags = new List<string> { "firstupper", "firstlower", "scale" }; public static bool ShowTranslation { get; private set; } = true; public event Action<Language> OnLanguageChanged; internal void CallOnLanguageChanged(Language newLanguage) { this.OnLanguageChanged?.Invoke(newLanguage); } private void Awake() { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_008c: Expected O, but got Unknown instance = this; logger = ((BaseUnityPlugin)this).Logger; assembly = Assembly.GetExecutingAssembly(); dllPath = new Uri(assembly.CodeBase).LocalPath; LanguageManager.Init(); FontManager.LoadFontBundlesFromFileSystem(); LocalyssationConfig.Init(((BaseUnityPlugin)this).Config); if (LocalyssationConfig.TranslatorMode && LocalyssationConfig.LogVanillaFonts) { FontHelper.DetectVanillaFonts(); } SettingsGUI.Init(); Harmony val = new Harmony("org.sallys-workshop.localyssation"); val.PatchAll(); val.PatchAll(typeof(GameLoadPatches)); FRUtil.PatchAll(val); RTUtil.PatchAll(val); SettingsGUI.Init(); OnSceneLoaded.Init(); LangAdjustables.Init(); } private void Update() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if (LocalyssationConfig.TranslatorMode) { if (Input.GetKeyDown(LocalyssationConfig.ReloadLanguageKeybind)) { LanguageManager.CurrentLanguage.LoadFromFileSystem(forceOverwrite: true); CallOnLanguageChanged(LanguageManager.CurrentLanguage); } if (Input.GetKeyDown(LocalyssationConfig.ReloadFontBundlesKeybind)) { FontManager.LoadFontBundlesFromFileSystem(); CallOnLanguageChanged(LanguageManager.CurrentLanguage); } if (Input.GetKeyDown(LocalyssationConfig.SwitchTranslationKeybind)) { ShowTranslation = !ShowTranslation; CallOnLanguageChanged(LanguageManager.CurrentLanguage); } } } public static string GetStringRaw(string key, string defaultValue = "SAME_AS_KEY") { if (ShowTranslation && LanguageManager.CurrentLanguage.TryGetString(key, out var value)) { return value; } if (LanguageManager.DefaultLanguage.TryGetString(key, out value)) { return value; } if (!(defaultValue == "SAME_AS_KEY")) { return defaultValue; } return key; } public static string ApplyTextEditTags(string str, int fontSize = -1, List<string> appliedTextEditTags = null) { if (appliedTextEditTags == null) { appliedTextEditTags = defaultAppliedTextEditTags; } string text = str; foreach (KeyValuePair<string, TextEditTagFunc> textEditTag in textEditTags) { if (!appliedTextEditTags.Contains(textEditTag.Key)) { continue; } while (true) { string text2 = "<" + textEditTag.Key; int num = text.IndexOf(text2); if (num == -1) { break; } int num2 = text.IndexOf(">", num + text2.Length); if (num2 == -1) { break; } string text3 = "</" + textEditTag.Key + ">"; int num3 = text.IndexOf(text3, num2 + 1); if (num3 == -1) { break; } string text4 = text.Substring(num + 1, num2 - 1); string arg = ""; if (text4.Contains("=")) { string[] array = text4.Split(new char[1] { '=' }); if (array.Length == 2) { arg = array[1]; } } string text5 = ""; if (num2 + 1 <= num3 - 1) { text5 = text.Substring(num2 + 1, num3 - num2 - 1); } string value = textEditTag.Value(text5, arg, fontSize); text = text.Remove(num3, text3.Length).Remove(num, num2 - num + 1); text = text.Remove(num, text5.Length).Insert(num, value); } } return text; } public static string GetString(string key, string defaultValue = "SAME_AS_KEY", int fontSize = -1) { if (LocalyssationConfig.ShowTranslationKey) { return key; } return ApplyTextEditTags(GetStringRaw(key, defaultValue), fontSize); } public static string GetString(TranslationKey translationKey, string defaultValue = "SAME_AS_KEY", int fontSize = -1) { if (LocalyssationConfig.ShowTranslationKey) { return translationKey.ToString(); } return ApplyTextEditTags(GetStringRaw(translationKey.ToString(), defaultValue), fontSize); } public static string Format(TranslationKey formatKey, params object[] args) { return string.Format(GetString(formatKey), args.Select((object x) => (x is TranslationKey translationKey) ? translationKey.Localize() : x).ToArray()); } public static string GetDefaultString(string key) { if (!LanguageManager.DefaultLanguage.TryGetString(key, out var value)) { return ""; } return value; } } public static class MyPluginInfo { public const string PLUGIN_GUID = "org.sallys-workshop.localyssation"; public const string PLUGIN_NAME = "Localyssation"; public const string PLUGIN_VERSION = "2.2.1"; } public static class TSVUtil { public static string makeTsv(List<List<string>> rows, string delimeter = "\t") { List<string> list = new List<string>(); List<string> list2 = null; for (int i = 0; i < rows.Count; i++) { List<string> list3 = rows[i]; for (int j = 0; j < list3.Count; j++) { list3[j] = list3[j].Replace("\n", "\\n").Replace("\t", "\\t"); } string text = string.Join(delimeter, list3); if (list2 == null) { list2 = list3; } else if (list2.Count != list3.Count) { Localyssation.logger.LogError((object)$"Row {i} has {list3.Count} columns, which does not match header column count (${list2.Count})"); Localyssation.logger.LogError((object)("Row content: " + text)); return string.Join(delimeter, list2); } list.Add(text); } return string.Join("\n", list); } public static List<List<string>> parseTsv(string tsv, string delimeter = "\t") { List<List<string>> list = new List<List<string>>(); List<string> list2 = null; string[] array = tsv.Split(new string[1] { "\n" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { string text = array[i]; if (text.EndsWith("\r")) { text = text.Substring(0, text.Length - 2); } List<string> list3 = new List<string>(Split(text, delimeter)); for (int j = 0; j < list3.Count; j++) { list3[j] = list3[j].Replace("\\n", "\n").Replace("\\t", "\t"); } if (list2 == null) { list2 = list3; } else if (list2.Count != list3.Count) { Localyssation.logger.LogError((object)$"Row {i} has {list3.Count} columns, which does not match header column count (${list2.Count})"); Localyssation.logger.LogError((object)("Row content: " + text)); return new List<List<string>> { list2 }; } list.Add(list3); } return list; } public static List<Dictionary<string, string>> parseTsvWithHeaders(string tsv, string delimeter = "\t") { List<List<string>> list = parseTsv(tsv, delimeter); List<Dictionary<string, string>> list2 = new List<Dictionary<string, string>>(); if (list.Count <= 0) { return list2; } List<string> headerRow = list[0]; for (int i = 1; i < list.Count; i++) { Dictionary<string, string> item = list[i].Select((string x, int y) => new KeyValuePair<string, string>(headerRow[y], x)).ToDictionary((KeyValuePair<string, string> x) => x.Key, (KeyValuePair<string, string> x) => x.Value); list2.Add(item); } return list2; } public static List<string> Split(string str, string delimeter) { List<string> list = new List<string>(); bool flag = delimeter.StartsWith("\\"); int num = 0; int num2 = 0; while (true) { int num3 = str.IndexOf(delimeter, num2); if (num3 == -1) { list.Add(str.Substring(num, str.Length - num)); break; } num2 = num3 + delimeter.Length; if (!flag || (num3 > 0 && str[num3 - 1] != '\\')) { list.Add(str.Substring(num, num3 - num)); num = num2; } if (num2 >= str.Length) { list.Add(str.Substring(num, str.Length - num)); break; } } return list; } } } namespace Localyssation.Util { public static class ConfigDefinitions { public static readonly ConfigDefinition Language = new ConfigDefinition("General", "Language"); public static readonly ConfigDefinition TraslatorMode = new ConfigDefinition("Translators", "Translator Mode"); public static readonly ConfigDefinition CreateDefaultLanguageFiles = new ConfigDefinition("Translators", "Create Default Language Files On Load"); public static readonly ConfigDefinition ShowTranslationKey = new ConfigDefinition("Translators", "Show Translation Key"); public static readonly ConfigDefinition ExportExtra = new ConfigDefinition("Translators", "Export Extra Info"); public static readonly ConfigDefinition ReloadLanguageKeybind = new ConfigDefinition("Translators", "Reload Language Keybind"); public static readonly ConfigDefinition ReloadFontBundlesKeybind = new ConfigDefinition("Translators", "Reload Font Bundles Keybind"); public static readonly ConfigDefinition SwitchTranslationKeybind = new ConfigDefinition("Translators", "Switch Translation Keybind"); public static readonly ConfigDefinition LogVanillaFonts = new ConfigDefinition("Translators", "Log Vanilla Fonts"); } public static class LocalyssationConfig { private static ConfigFile config; internal static ConfigEntry<string> configLanguage { get; private set; } public static string Language => configLanguage.Value; internal static ConfigEntry<bool> configTranslatorMode { get; private set; } public static bool TranslatorMode => configTranslatorMode.Value; internal static ConfigEntry<bool> configCreateDefaultLanguageFiles { get; private set; } public static bool CreateDefaultLanguageFiles => configCreateDefaultLanguageFiles.Value; internal static ConfigEntry<bool> configShowTranslationKey { get; private set; } public static bool ShowTranslationKey => configShowTranslationKey.Value; internal static ConfigEntry<bool> configExportExtra { get; private set; } public static bool ExportExtra => configExportExtra.Value; internal static ConfigEntry<KeyCode> configReloadLanguageKeybind { get; private set; } public static KeyCode ReloadLanguageKeybind => configReloadLanguageKeybind.Value; internal static ConfigEntry<KeyCode> configReloadFontBundlesKeybind { get; private set; } public static KeyCode ReloadFontBundlesKeybind => configReloadFontBundlesKeybind.Value; internal static ConfigEntry<KeyCode> configSwitchTranslationKeybind { get; private set; } public static KeyCode SwitchTranslationKeybind => configSwitchTranslationKeybind.Value; internal static ConfigEntry<bool> configLogVanillaFonts { get; private set; } public static bool LogVanillaFonts => configLogVanillaFonts.Value; public static void Init(ConfigFile _config) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Expected O, but got Unknown //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Expected O, but got Unknown //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Expected O, but got Unknown //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Expected O, but got Unknown config = _config; configLanguage = config.Bind<string>(ConfigDefinitions.Language, LanguageManager.DefaultLanguage.info.code, new ConfigDescription("Currently selected language's code", (AcceptableValueBase)null, Array.Empty<object>())); if (LanguageManager.GetLanguage(Language, out var language)) { LanguageManager.ChangeLanguage(language); } configTranslatorMode = config.Bind<bool>(ConfigDefinitions.TraslatorMode, false, new ConfigDescription("Enables the features of this section", (AcceptableValueBase)null, Array.Empty<object>())); configCreateDefaultLanguageFiles = config.Bind<bool>(ConfigDefinitions.CreateDefaultLanguageFiles, true, new ConfigDescription("If enabled, files for the default game language will be created in the mod's directory on game load", (AcceptableValueBase)null, Array.Empty<object>())); configReloadLanguageKeybind = config.Bind<KeyCode>(ConfigDefinitions.ReloadLanguageKeybind, (KeyCode)291, new ConfigDescription("When you press this button, your current language's files will be reloaded mid-game", (AcceptableValueBase)null, Array.Empty<object>())); configShowTranslationKey = config.Bind<bool>(ConfigDefinitions.ShowTranslationKey, false, new ConfigDescription("Show translation keys instead of translated string for debugging.", (AcceptableValueBase)null, Array.Empty<object>())); configExportExtra = config.Bind<bool>(ConfigDefinitions.ExportExtra, false, new ConfigDescription("Export quest and item data and image to markdown for translation referencing.", (AcceptableValueBase)null, Array.Empty<object>())); configReloadFontBundlesKeybind = config.Bind<KeyCode>(ConfigDefinitions.ReloadFontBundlesKeybind, (KeyCode)290, new ConfigDescription("When you press this button, the font bundles will be reloaded mid-game", (AcceptableValueBase)null, Array.Empty<object>())); configSwitchTranslationKeybind = config.Bind<KeyCode>(ConfigDefinitions.SwitchTranslationKeybind, (KeyCode)292, new ConfigDescription("When you press this button, the translation mode will be switched mid-game", (AcceptableValueBase)null, Array.Empty<object>())); configLogVanillaFonts = config.Bind<bool>(ConfigDefinitions.LogVanillaFonts, false, new ConfigDescription("Log vanilla fonts to console", (AcceptableValueBase)null, Array.Empty<object>())); } } internal class SettingsGUI { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static UnityAction <>9__15_0; public static UnityAction<bool> <>9__16_4; public static Func<KeyValuePair<string, Language>, string> <>9__17_0; public static Func<string, string> <>9__17_1; internal void <.ctor>b__15_0() { } internal void <SetupTranslatorModeElements>b__16_4(bool v) { LanguageManager.ChangeLanguage(LanguageManager.CurrentLanguage, forced: true); } internal string <SetupSettingsTab>b__17_0(KeyValuePair<string, Language> kv) { return kv.Key; } internal string <SetupSettingsTab>b__17_1(string key) { return LanguageManager.languages[key].info.name; } } private AtlyssDropdown languageDropdown; private List<string> languageKeys; private AtlyssToggle translatorModeToggle; private AtlyssToggle showTranslationKeyToggle; private AtlyssToggle createDefaultLanguageFilesToggle; private AtlyssToggle exportExtraToggle; private AtlyssToggle logVanillaFontsToggle; private AtlyssKeyButton reloadLanguageKeybind; private AtlyssKeyButton reloadFontBundlesKeybind; private AtlyssKeyButton switchTranslationKeybind; private AtlyssButton createMissingForCurrentLangButton; private AtlyssButton logUntranslatedStringsButton; private readonly List<BaseAtlyssElement> translatorModeElements = new List<BaseAtlyssElement>(); private static SettingsGUI instance; public static void Init() { if (instance == null) { instance = new SettingsGUI(); } } private SettingsGUI() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown Settings.OnInitialized.AddListener(new UnityAction(SetupSettingsTab)); UnityEvent onApplySettings = Settings.OnApplySettings; object obj = <>c.<>9__15_0; if (obj == null) { UnityAction val = delegate { }; <>c.<>9__15_0 = val; obj = (object)val; } onApplySettings.AddListener((UnityAction)obj); } private void SetupTranslatorModeElements() { SettingsTab tab = Settings.ModTab; SetupToggles(); SetupKeybind(); SetupButton(); void RegisterTranslatorModeElement<T>(T element, TranslationKey key) where T : BaseAtlyssElement { translatorModeElements.Add((BaseAtlyssElement)(object)element); object obj = element; BaseAtlyssLabelElement val = (BaseAtlyssLabelElement)((obj is BaseAtlyssLabelElement) ? obj : null); if (val != null) { LangAdjustables.RegisterText(val.Label, key); } object obj2 = element; AtlyssButton val2 = (AtlyssButton)((obj2 is AtlyssButton) ? obj2 : null); if (val2 != null) { LangAdjustables.RegisterText(val2.ButtonLabel, key); } } void SetupButton() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown createMissingForCurrentLangButton = tab.AddButton(Localyssation.GetString(I18nKeys.Settings.Mod.ADD_MISSING_KEYS_TO_CURRENT_LANGUAGE), new UnityAction(OnAddMissingKeyButtonPressed)); translatorModeElements.Add((BaseAtlyssElement)(object)createMissingForCurrentLangButton); logUntranslatedStringsButton = tab.AddButton(Localyssation.GetString(I18nKeys.Settings.Mod.LOG_UNTRANSLATED_STRINGS), new UnityAction(OnLogUntranslated)); translatorModeElements.Add((BaseAtlyssElement)(object)logUntranslatedStringsButton); } void SetupKeybind() { reloadLanguageKeybind = tab.AddKeyButton(LocalyssationConfig.configReloadLanguageKeybind); RegisterTranslatorModeElement<AtlyssKeyButton>(reloadLanguageKeybind, I18nKeys.Settings.Mod.RELOAD_LANGUAGE_KEYBIND); reloadFontBundlesKeybind = tab.AddKeyButton(LocalyssationConfig.configReloadFontBundlesKeybind); RegisterTranslatorModeElement<AtlyssKeyButton>(reloadFontBundlesKeybind, I18nKeys.Settings.Mod.RELOAD_FONT_BUNDLES_KEYBIND); switchTranslationKeybind = tab.AddKeyButton(LocalyssationConfig.configSwitchTranslationKeybind); RegisterTranslatorModeElement<AtlyssKeyButton>(switchTranslationKeybind, I18nKeys.Settings.Mod.SWITCH_TRANSLATION_KEYBIND); } void SetupToggles() { showTranslationKeyToggle = tab.AddToggle(LocalyssationConfig.configShowTranslationKey); showTranslationKeyToggle.OnValueChanged.AddListener((UnityAction<bool>)delegate { LanguageManager.ChangeLanguage(LanguageManager.CurrentLanguage, forced: true); }); RegisterTranslatorModeElement<AtlyssToggle>(showTranslationKeyToggle, I18nKeys.Settings.Mod.SHOW_TRANSLATION_KEY); createDefaultLanguageFilesToggle = tab.AddToggle(LocalyssationConfig.configCreateDefaultLanguageFiles); RegisterTranslatorModeElement<AtlyssToggle>(createDefaultLanguageFilesToggle, I18nKeys.Settings.Mod.CREATE_DEFAULT_LANGUAGE_FILES); exportExtraToggle = tab.AddToggle(LocalyssationConfig.configExportExtra); RegisterTranslatorModeElement<AtlyssToggle>(exportExtraToggle, I18nKeys.Settings.Mod.EXPORT_EXTRA); logVanillaFontsToggle = tab.AddToggle(LocalyssationConfig.configLogVanillaFonts); RegisterTranslatorModeElement<AtlyssToggle>(logVanillaFontsToggle, I18nKeys.Settings.Mod.LOG_VANILLA_FONTS); } } private void SetupSettingsTab() { SettingsTab modTab = Settings.ModTab; LangAdjustables.RegisterText(modTab.TabButton.Label, I18nKeys.Settings.BUTTON_MODS); modTab.AddHeader("Localyssation"); languageKeys = LanguageManager.languages.Select((KeyValuePair<string, Language> kv) => kv.Key).ToList(); int num = languageKeys.IndexOf(LanguageManager.CurrentLanguage.info.code); languageDropdown = modTab.AddDropdown("Language", languageKeys.Select((string key) => LanguageManager.languages[key].info.name).ToList(), num); languageDropdown.OnValueChanged.AddListener((UnityAction<int>)OnLanguageDropdownChanged); LangAdjustables.RegisterText(((BaseAtlyssLabelElement)languageDropdown).Label, I18nKeys.Settings.Mod.LANGUAGE); translatorModeToggle = modTab.AddToggle(LocalyssationConfig.configTranslatorMode); translatorModeToggle.OnValueChanged.AddListener((UnityAction<bool>)OnTranslatorModeChanged); LangAdjustables.RegisterText(((BaseAtlyssLabelElement)translatorModeToggle).Label, I18nKeys.Settings.Mod.TRANSLATOR_MODE); SetupTranslatorModeElements(); OnTranslatorModeChanged(LocalyssationConfig.TranslatorMode); Localyssation.instance.OnLanguageChanged += OnLanguageChanged; OnLanguageChange(); } private static void ChangeAtlyssSettingsElementsEnabled<T>(T uiElement, bool enabled) where T : BaseAtlyssElement { ((Component)((BaseAtlyssElement)uiElement).Root).gameObject.SetActive(enabled); } private void OnTranslatorModeChanged(bool value) { translatorModeElements.ForEach(delegate(BaseAtlyssElement v) { ChangeAtlyssSettingsElementsEnabled<BaseAtlyssElement>(v, value); }); } private void OnLanguageDropdownChanged(int valueIndex) { string text = languageKeys[valueIndex]; LanguageManager.ChangeLanguage(text); LocalyssationConfig.configLanguage.Value = text; } private void OnAddMissingKeyButtonPressed() { foreach (KeyValuePair<string, string> @string in LanguageManager.DefaultLanguage.GetStrings()) { if (!LanguageManager.CurrentLanguage.ContainsKey(@string.Key)) { LanguageManager.CurrentLanguage.RegisterKey(@string.Key, @string.Value); } } LanguageManager.CurrentLanguage.WriteToFileSystem("missing"); } private void OnLogUntranslated() { int num = 0; int num2 = 0; Localyssation.logger.LogMessage((object)("Logging strings that are the same in " + LanguageManager.DefaultLanguage.info.name + " and " + LanguageManager.CurrentLanguage.info.name + ":")); foreach (KeyValuePair<string, string> @string in LanguageManager.CurrentLanguage.GetStrings()) { if (LanguageManager.DefaultLanguage.GetStrings().TryGetValue(@string.Key, out var value)) { num2++; if (@string.Value == value) { Localyssation.logger.LogMessage((object)@string.Key); } else { num++; } } } Localyssation.logger.LogMessage((object)$"Done! {num}/{num2} ({(float)num / (float)num2 * 100f:0.00}%) strings are different between the languages."); } private void OnLanguageChange() { createMissingForCurrentLangButton.ButtonLabel.text = Localyssation.GetString(I18nKeys.Settings.Mod.ADD_MISSING_KEYS_TO_CURRENT_LANGUAGE); logUntranslatedStringsButton.ButtonLabel.text = Localyssation.GetString(I18nKeys.Settings.Mod.LOG_UNTRANSLATED_STRINGS); } public void OnLanguageChanged(Language newLanguage) { OnLanguageChange(); } ~SettingsGUI() { Localyssation.instance.OnLanguageChanged -= OnLanguageChanged; } } public class FontBundle { public string fileSystemPath; public readonly Dictionary<string, Font> fonts = new Dictionary<string, Font>(); public readonly Dictionary<string, TMP_FontAsset> TMPfonts = new Dictionary<string, TMP_FontAsset>(); public bool LoadFromFileSystem() { if (string.IsNullOrEmpty(fileSystemPath)) { return false; } AssetBundle obj = AssetBundle.LoadFromFile(fileSystemPath); Localyssation.logger.LogInfo((object)("Loading font bundle `" + fileSystemPath + "`")); Localyssation.logger.LogInfo((object)"Found Fonts:"); CollectionExtensions.Do<Font>(obj.LoadAllAssets(typeof(Font)).Cast<Font>(), (Action<Font>)delegate(Font font) { Localyssation.logger.LogInfo((object)("\t- " + ((Object)font).name)); fonts.Add(((Object)font).name, font); }); Localyssation.logger.LogInfo((object)"Found TMP_FontAsset:"); CollectionExtensions.Do<TMP_FontAsset>(obj.LoadAllAssets(typeof(TMP_FontAsset)).Cast<TMP_FontAsset>(), (Action<TMP_FontAsset>)delegate(TMP_FontAsset font) { Localyssation.logger.LogInfo((object)("\t- " + ((Object)font).name)); TMPfonts.Add(((Object)font).name, font); }); obj.Unload(false); return true; } } public static class FontManager { private static readonly Dictionary<string, Font> availableFonts = new Dictionary<string, Font>(); private static readonly Dictionary<string, TMP_FontAsset> availableTMP_FontAssets = new Dictionary<string, TMP_FontAsset>(); public static TMP_FontAsset UNIFONT_SDF { get; private set; } public static bool UnifontLoaded { get; private set; } = false; public static IDictionary<string, Font> Fonts => availableFonts; public static IDictionary<string, TMP_FontAsset> TMPfonts => availableTMP_FontAssets; public static void LoadFontBundlesFromFileSystem() { availableFonts.Clear(); availableTMP_FontAssets.Clear(); Resources.UnloadUnusedAssets(); string[] files = Directory.GetFiles(Paths.PluginPath, "*.fontbundle", SearchOption.AllDirectories); Localyssation.logger.LogInfo((object)$"Found {files.Length} fontBundles"); string[] array = files; foreach (string text in array) { FontBundle fontBundle = new FontBundle { fileSystemPath = text }; if (fontBundle.LoadFromFileSystem()) { RegisterFontBundle(fontBundle); } else { Localyssation.logger.LogError((object)("Error occured when loading font bundle `" + text + "`")); } } UNIFONT_SDF = TMPfonts["unifont SDF"]; UnifontLoaded = true; CollectionExtensions.DoIf<TMP_FontAsset>(TMPfonts.Values.SkipWhile((TMP_FontAsset font) => (Object)(object)font == (Object)(object)UNIFONT_SDF), (Func<TMP_FontAsset, bool>)((TMP_FontAsset font) => !font.fallbackFontAssetTable.Contains(UNIFONT_SDF)), (Action<TMP_FontAsset>)delegate(TMP_FontAsset font) { font.fallbackFontAssetTable.Add(UNIFONT_SDF); }); } private static void RegisterFontBundle(FontBundle fontBundle) { Extensions.AddRange<string, Font>(availableFonts, fontBundle.fonts); Extensions.AddRange<string, TMP_FontAsset>(availableTMP_FontAssets, fontBundle.TMPfonts); } } public static class FontHelper { public static void DetectVanillaFonts() { Localyssation.logger.LogInfo((object)"Fonts used by Vanilla:"); CollectionExtensions.Do<Font>(Resources.LoadAll<Font>("").Cast<Font>(), (Action<Font>)delegate(Font font) { Localyssation.logger.LogInfo((object)("\t - " + ((Object)font).name)); }); Localyssation.logger.LogInfo((object)"TMP_FontAsset used by Vanilla:"); CollectionExtensions.Do<TMP_FontAsset>(Resources.LoadAll<TMP_FontAsset>("").Cast<TMP_FontAsset>(), (Action<TMP_FontAsset>)delegate(TMP_FontAsset font) { Localyssation.logger.LogInfo((object)("\t - " + ((Object)font).name)); }); Resources.UnloadUnusedAssets(); } } public class TranslationKey { public class TranslationKeyOptionGenerator { public readonly TranslationKey baseKey; public TranslationKey this[int index] => new TranslationKey(baseKey.key + $"_OPTION_{index}"); public TranslationKeyOptionGenerator(TranslationKey _baseKey) { baseKey = _baseKey; } } public static TranslationKey EMPTY = new TranslationKey(""); public readonly string key; public TranslationKey Name => new TranslationKey(key + "_NAME"); public TranslationKey NamePlural => new TranslationKey(key + "_NAME_PLURAL"); public TranslationKey Description => new TranslationKey(key + "_DESCRIP
libs/YamlDotNet.dll
Decompiled 7 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.CodeAnalysis; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.ObjectPool; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Callbacks; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("16.3.0.0")] [assembly: AssemblyInformationalVersion("16.3.0")] [assembly: AssemblyTitle("YamlDotNet")] [assembly: AssemblyDescription("The YamlDotNet library.")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("YamlDotNet")] [assembly: AssemblyCopyright("Copyright (c) Antoine Aubry and contributors 2008 - 2019")] [assembly: AssemblyTrademark("")] [assembly: CLSCompliant(true)] [assembly: InternalsVisibleTo("YamlDotNet.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010065e52a453dde5c5b4be5bbe2205755727fce80244b79b894faf8793d80f7db9a96d360b51c220782db32aacee4cb5b8a91bee33aeec700e1f21895c4baadef501eeeac609220d1651603b378173811ee5bb6a002df973d38821bd2fef820c00c174a69faec326a1983b570f07ec66147026b9c8753465de3a8d0c44b613b02af")] [assembly: TargetFramework(".NETFramework,Version=v4.7", FrameworkDisplayName = ".NET Framework 4.7")] [assembly: AssemblyVersion("16.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace YamlDotNet { internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.Name) { this.provider = provider; } public override object? GetFormat(Type formatType) { return provider.GetFormat(formatType); } } internal static class Polyfills { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool Contains(this string source, char c) { return source.IndexOf(c) != -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool EndsWith(this string source, char c) { if (source.Length > 0) { return source[source.Length - 1] == c; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool StartsWith(this string source, char c) { if (source.Length > 0) { return source[0] == c; } return false; } } internal static class PropertyInfoExtensions { public static object? ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } internal static class ReflectionExtensions { private static readonly Func<PropertyInfo, bool> IsInstance = (PropertyInfo property) => !(property.GetMethod ?? property.SetMethod).IsStatic; private static readonly Func<PropertyInfo, bool> IsInstancePublic = (PropertyInfo property) => IsInstance(property) && (property.GetMethod ?? property.SetMethod).IsPublic; public static Type? BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.GetTypeInfo().IsGenericTypeDefinition; } public static Type? GetImplementationOfOpenGenericInterface(this Type type, Type openGenericType) { if (!openGenericType.IsGenericType || !openGenericType.IsInterface) { throw new ArgumentException("The type must be a generic type definition and an interface", "openGenericType"); } if (IsGenericDefinitionOfType(type, openGenericType)) { return type; } return type.FindInterfaces((Type t, object context) => IsGenericDefinitionOfType(t, context), openGenericType).FirstOrDefault(); static bool IsGenericDefinitionOfType(Type t, object? context) { if (t.IsGenericType) { return t.GetGenericTypeDefinition() == (Type)context; } return false; } } public static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsRequired(this MemberInfo member) { return member.GetCustomAttributes(inherit: true).Any((object x) => x.GetType().FullName == "System.Runtime.CompilerServices.RequiredMemberAttribute"); } public static bool HasDefaultConstructor(this Type type, bool allowPrivateConstructors) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (allowPrivateConstructors) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsValueType) { return type.GetConstructor(bindingFlags, null, Type.EmptyTypes, null) != null; } return true; } public static bool IsAssignableFrom(this Type type, Type source) { return type.IsAssignableFrom(source.GetTypeInfo()); } public static bool IsAssignableFrom(this Type type, TypeInfo source) { return type.GetTypeInfo().IsAssignableFrom(source); } public static TypeCode GetTypeCode(this Type type) { if (type.IsEnum()) { type = Enum.GetUnderlyingType(type); } if (type == typeof(bool)) { return TypeCode.Boolean; } if (type == typeof(char)) { return TypeCode.Char; } if (type == typeof(sbyte)) { return TypeCode.SByte; } if (type == typeof(byte)) { return TypeCode.Byte; } if (type == typeof(short)) { return TypeCode.Int16; } if (type == typeof(ushort)) { return TypeCode.UInt16; } if (type == typeof(int)) { return TypeCode.Int32; } if (type == typeof(uint)) { return TypeCode.UInt32; } if (type == typeof(long)) { return TypeCode.Int64; } if (type == typeof(ulong)) { return TypeCode.UInt64; } if (type == typeof(float)) { return TypeCode.Single; } if (type == typeof(double)) { return TypeCode.Double; } if (type == typeof(decimal)) { return TypeCode.Decimal; } if (type == typeof(DateTime)) { return TypeCode.DateTime; } if (type == typeof(string)) { return TypeCode.String; } return TypeCode.Object; } public static bool IsDbNull(this object value) { return value?.GetType()?.FullName == "System.DBNull"; } public static Type[] GetGenericArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } public static PropertyInfo? GetPublicProperty(this Type type, string name) { string name2 = name; return type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).FirstOrDefault((PropertyInfo p) => p.Name == name2); } public static FieldInfo? GetPublicStaticField(this Type type, string name) { return type.GetRuntimeField(name); } public static IEnumerable<PropertyInfo> GetProperties(this Type type, bool includeNonPublic) { Func<PropertyInfo, bool> predicate = (includeNonPublic ? IsInstance : IsInstancePublic); if (!type.IsInterface()) { return type.GetRuntimeProperties().Where(predicate); } return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetRuntimeProperties().Where(predicate)); } public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type) { return type.GetProperties(includeNonPublic: false); } public static IEnumerable<FieldInfo> GetPublicFields(this Type type) { return from f in type.GetRuntimeFields() where !f.IsStatic && f.IsPublic select f; } public static IEnumerable<MethodInfo> GetPublicStaticMethods(this Type type) { return from m in type.GetRuntimeMethods() where m.IsPublic && m.IsStatic select m; } public static MethodInfo GetPrivateStaticMethod(this Type type, string name) { string name2 = name; return type.GetRuntimeMethods().FirstOrDefault((MethodInfo m) => !m.IsPublic && m.IsStatic && m.Name.Equals(name2)) ?? throw new MissingMethodException("Expected to find a method named '" + name2 + "' in '" + type.FullName + "'."); } public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { string name2 = name; Type[] parameterTypes2 = parameterTypes; return type.GetRuntimeMethods().FirstOrDefault(delegate(MethodInfo m) { if (m.IsPublic && m.IsStatic && m.Name.Equals(name2)) { ParameterInfo[] parameters = m.GetParameters(); if (parameters.Length == parameterTypes2.Length) { return parameters.Zip(parameterTypes2, (ParameterInfo pi, Type pt) => pi.ParameterType == pt).All((bool r) => r); } return false; } return false; }); } public static MethodInfo? GetPublicInstanceMethod(this Type type, string name) { string name2 = name; return type.GetRuntimeMethods().FirstOrDefault((MethodInfo m) => m.IsPublic && !m.IsStatic && m.Name.Equals(name2)); } public static MethodInfo? GetGetMethod(this PropertyInfo property, bool nonPublic) { MethodInfo methodInfo = property.GetMethod; if (!nonPublic && !methodInfo.IsPublic) { methodInfo = null; } return methodInfo; } public static MethodInfo? GetSetMethod(this PropertyInfo property) { return property.SetMethod; } public static IEnumerable<Type> GetInterfaces(this Type type) { return type.GetTypeInfo().ImplementedInterfaces; } public static bool IsInstanceOf(this Type type, object o) { if (!(o.GetType() == type)) { return o.GetType().GetTypeInfo().IsSubclassOf(type); } return true; } public static Attribute[] GetAllCustomAttributes<TAttribute>(this PropertyInfo member) { return Attribute.GetCustomAttributes(member, typeof(TAttribute), inherit: true); } public static bool AcceptsNull(this MemberInfo member) { object[] customAttributes = member.DeclaringType.GetCustomAttributes(inherit: true); object obj = customAttributes.FirstOrDefault((object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableContextAttribute"); int num = 0; if (obj != null) { Type type = obj.GetType(); PropertyInfo property = type.GetProperty("Flag"); num = (byte)property.GetValue(obj); } object[] customAttributes2 = member.GetCustomAttributes(inherit: true); object obj2 = customAttributes2.FirstOrDefault((object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableAttribute"); PropertyInfo propertyInfo = (obj2?.GetType())?.GetProperty("NullableFlags"); byte[] source = (byte[])propertyInfo.GetValue(obj2); return source.Any((byte x) => x == 2) || num == 2; } } internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } } namespace YamlDotNet.Serialization { public abstract class BuilderSkeleton<TBuilder> where TBuilder : BuilderSkeleton<TBuilder> { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal INamingConvention enumNamingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly YamlAttributeOverrides overrides; internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories; internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories; internal bool ignoreFields; internal bool includeNonPublicProperties; internal Settings settings; internal YamlFormatter yamlFormatter = YamlFormatter.Default; protected abstract TBuilder Self { get; } internal BuilderSkeleton(ITypeResolver typeResolver) { overrides = new YamlAttributeOverrides(); typeConverterFactories = new LazyComponentRegistrationList<Nothing, IYamlTypeConverter> { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) }, { typeof(SystemTypeConverter), (Nothing _) => new SystemTypeConverter() } }; typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder IgnoreFields() { ignoreFields = true; return Self; } public TBuilder IncludeNonPublicProperties() { includeNonPublicProperties = true; return Self; } public TBuilder EnablePrivateConstructors() { settings.AllowPrivateConstructors = true; return Self; } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithEnumNamingConvention(INamingConvention enumNamingConvention) { this.enumNamingConvention = enumNamingConvention; return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithAttributeOverride<TClass>(Expression<Func<TClass, object>> propertyAccessor, Attribute attribute) { overrides.Add(propertyAccessor, attribute); return Self; } public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute) { overrides.Add(type, member, attribute); return Self; } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) { IYamlTypeConverter typeConverter2 = typeConverter; if (typeConverter2 == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2)); return Self; } public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter { WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory2 = typeConverterFactory; if (typeConverterFactory2 == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped))); return Self; } public TBuilder WithoutTypeConverter<TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w) { w.OnTop(); }); } public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector { Func<ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner))); return Self; } public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector { WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector<TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } public TBuilder WithYamlFormatter(YamlFormatter formatter) { yamlFormatter = formatter ?? throw new ArgumentNullException("formatter"); return Self; } protected IEnumerable<IYamlTypeConverter> BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } public delegate TComponent WrapperFactory<TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase; public delegate TComponent WrapperFactory<TArgument, TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] public enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } public sealed class Deserializer : IDeserializer { private readonly IValueDeserializer valueDeserializer; public Deserializer() : this(new DeserializerBuilder().BuildValueDeserializer()) { } private Deserializer(IValueDeserializer valueDeserializer) { this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer"); } public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer) { return new Deserializer(valueDeserializer); } public T Deserialize<T>(string input) { using StringReader input2 = new StringReader(input); return Deserialize<T>(input2); } public T Deserialize<T>(TextReader input) { return Deserialize<T>(new Parser(input)); } public T Deserialize<T>(IParser parser) { return (T)Deserialize(parser, typeof(T)); } public object? Deserialize(string input) { return Deserialize<object>(input); } public object? Deserialize(TextReader input) { return Deserialize<object>(input); } public object? Deserialize(IParser parser) { return Deserialize<object>(parser); } public object? Deserialize(string input, Type type) { using StringReader input2 = new StringReader(input); return Deserialize(input2, type); } public object? Deserialize(TextReader input, Type type) { return Deserialize(new Parser(input), type); } public object? Deserialize(IParser parser, Type type) { if (parser == null) { throw new ArgumentNullException("parser"); } if (type == null) { throw new ArgumentNullException("type"); } YamlDotNet.Core.Events.StreamStart @event; bool flag = parser.TryConsume<YamlDotNet.Core.Events.StreamStart>(out @event); YamlDotNet.Core.Events.DocumentStart event2; bool flag2 = parser.TryConsume<YamlDotNet.Core.Events.DocumentStart>(out event2); object result = null; if (!parser.Accept<YamlDotNet.Core.Events.DocumentEnd>(out var _) && !parser.Accept<YamlDotNet.Core.Events.StreamEnd>(out var _)) { using SerializerState serializerState = new SerializerState(); result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer); serializerState.OnDeserialization(); } if (flag2) { parser.Consume<YamlDotNet.Core.Events.DocumentEnd>(); } if (flag) { parser.Consume<YamlDotNet.Core.Events.StreamEnd>(); } return result; } } public sealed class DeserializerBuilder : BuilderSkeleton<DeserializerBuilder> { private Lazy<IObjectFactory> objectFactory; private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories; private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories; private readonly Dictionary<TagName, Type> tagMappings; private readonly Dictionary<Type, Type> typeMappings; private readonly ITypeConverter typeConverter; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; private bool enforceNullability; private bool caseInsensitivePropertyMatching; private bool enforceRequiredProperties; protected override DeserializerBuilder Self => this; public DeserializerBuilder() : base((ITypeResolver)new StaticTypeResolver()) { typeMappings = new Dictionary<Type, Type>(); objectFactory = new Lazy<IObjectFactory>(() => new DefaultObjectFactory(typeMappings, settings), isThreadSafe: true); tagMappings = new Dictionary<TagName, Type> { { FailsafeSchema.Tags.Map, typeof(Dictionary<object, object>) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), (ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList<Nothing, INodeDeserializer> { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter, BuildTypeInspector(), yamlFormatter, enumNamingConvention) }, { typeof(ArrayNodeDeserializer), (Nothing _) => new ArrayNodeDeserializer(enumNamingConvention, BuildTypeInspector()) }, { typeof(DictionaryNodeDeserializer), (Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking) }, { typeof(CollectionNodeDeserializer), (Nothing _) => new CollectionNodeDeserializer(objectFactory.Value, enumNamingConvention, BuildTypeInspector()) }, { typeof(EnumerableNodeDeserializer), (Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter, enumNamingConvention, enforceNullability, caseInsensitivePropertyMatching, enforceRequiredProperties, BuildTypeConverters()) }, { typeof(FsharpListNodeDeserializer), (Nothing _) => new FsharpListNodeDeserializer(BuildTypeInspector(), enumNamingConvention) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList<Nothing, INodeTypeResolver> { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new ReflectionTypeConverter(); } public ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new WritablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } public DeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory) { IObjectFactory objectFactory2 = objectFactory; if (objectFactory2 == null) { throw new ArgumentNullException("objectFactory"); } this.objectFactory = new Lazy<IObjectFactory>(() => objectFactory2, isThreadSafe: true); return this; } public DeserializerBuilder WithObjectFactory(Func<Type, object> objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } return WithObjectFactory(new LambdaObjectFactory(objectFactory)); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> w) { w.OnTop(); }); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where) { INodeDeserializer nodeDeserializer2 = nodeDeserializer; if (nodeDeserializer2 == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2)); return this; } public DeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer { WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory2 = nodeDeserializerFactory; if (nodeDeserializerFactory2 == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped))); return this; } public DeserializerBuilder WithoutNodeDeserializer<TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public DeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action<ITypeDiscriminatingNodeDeserializerOptions> configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> s) { s.Before<DictionaryNodeDeserializer>(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w) { w.OnTop(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) { INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver; if (nodeTypeResolver2 == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2)); return this; } public DeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver { WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory2 = nodeTypeResolverFactory; if (nodeTypeResolverFactory2 == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped))); return this; } public DeserializerBuilder WithCaseInsensitivePropertyMatching() { caseInsensitivePropertyMatching = true; return this; } public DeserializerBuilder WithEnforceNullability() { enforceNullability = true; return this; } public DeserializerBuilder WithEnforceRequiredMembers() { enforceRequiredProperties = true; return this; } public DeserializerBuilder WithoutNodeTypeResolver<TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override DeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out Type value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public DeserializerBuilder WithTypeMapping<TInterface, TConcrete>() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (!DictionaryExtensions.TryAdd(typeMappings, typeFromHandle, typeFromHandle2)) { typeMappings[typeFromHandle] = typeFromHandle2; } return this; } public DeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public DeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public DeserializerBuilder WithDuplicateKeyChecking() { duplicateKeyChecking = true; return this; } public IDeserializer Build() { if (FsharpHelper.Instance == null) { FsharpHelper.Instance = new DefaultFsharpHelper(); } return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter, enumNamingConvention, BuildTypeInspector())); } } public sealed class EmissionPhaseObjectGraphVisitorArgs { private readonly IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors; public IObjectGraphVisitor<IEmitter> InnerVisitor { get; private set; } public IEventEmitter EventEmitter { get; private set; } public ObjectSerializer NestedObjectSerializer { get; private set; } public IEnumerable<IYamlTypeConverter> TypeConverters { get; private set; } public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor<IEmitter> innerVisitor, IEventEmitter eventEmitter, IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors, IEnumerable<IYamlTypeConverter> typeConverters, ObjectSerializer nestedObjectSerializer) { InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor"); EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter"); this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors"); TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters"); NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer"); } public T GetPreProcessingPhaseObjectGraphVisitor<T>() where T : IObjectGraphVisitor<Nothing> { return preProcessingPhaseVisitors.OfType<T>().Single(); } } public abstract class EventInfo { public IObjectDescriptor Source { get; } protected EventInfo(IObjectDescriptor source) { Source = source ?? throw new ArgumentNullException("source"); } } public class AliasEventInfo : EventInfo { public AnchorName Alias { get; } public bool NeedsExpansion { get; set; } public AliasEventInfo(IObjectDescriptor source, AnchorName alias) : base(source) { if (alias.IsEmpty) { throw new ArgumentNullException("alias"); } Alias = alias; } } public class ObjectEventInfo : EventInfo { public AnchorName Anchor { get; set; } public TagName Tag { get; set; } protected ObjectEventInfo(IObjectDescriptor source) : base(source) { } } public sealed class ScalarEventInfo : ObjectEventInfo { public string RenderedValue { get; set; } public ScalarStyle Style { get; set; } public bool IsPlainImplicit { get; set; } public bool IsQuotedImplicit { get; set; } public ScalarEventInfo(IObjectDescriptor source) : base(source) { Style = source.ScalarStyle; RenderedValue = string.Empty; } } public sealed class MappingStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public MappingStyle Style { get; set; } public MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } public sealed class MappingEndEventInfo : EventInfo { public MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } public sealed class SequenceStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public SequenceStyle Style { get; set; } public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } public sealed class SequenceEndEventInfo : EventInfo { public SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } public interface IAliasProvider { AnchorName GetAlias(object target); } public interface IDeserializer { T Deserialize<T>(string input); T Deserialize<T>(TextReader input); T Deserialize<T>(IParser parser); object? Deserialize(string input); object? Deserialize(TextReader input); object? Deserialize(IParser parser); object? Deserialize(string input, Type type); object? Deserialize(TextReader input, Type type); object? Deserialize(IParser parser, Type type); } public interface IEventEmitter { void Emit(AliasEventInfo eventInfo, IEmitter emitter); void Emit(ScalarEventInfo eventInfo, IEmitter emitter); void Emit(MappingStartEventInfo eventInfo, IEmitter emitter); void Emit(MappingEndEventInfo eventInfo, IEmitter emitter); void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter); void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter); } public interface INamingConvention { string Apply(string value); string Reverse(string value); } public interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer); } public interface INodeTypeResolver { bool Resolve(NodeEvent? nodeEvent, ref Type currentType); } public interface IObjectAccessor { void Set(string name, object target, object value); object? Read(string name, object target); } public interface IObjectDescriptor { object? Value { get; } Type Type { get; } Type StaticType { get; } ScalarStyle ScalarStyle { get; } } public static class ObjectDescriptorExtensions { public static object NonNullValue(this IObjectDescriptor objectDescriptor) { return objectDescriptor.Value ?? throw new InvalidOperationException("Attempted to use a IObjectDescriptor of type '" + objectDescriptor.Type.FullName + "' whose Value is null at a point whete it is invalid to do so. This may indicate a bug in YamlDotNet."); } } public interface IObjectFactory { object Create(Type type); object? CreatePrimitive(Type type); bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments); Type GetValueType(Type type); void ExecuteOnDeserializing(object value); void ExecuteOnDeserialized(object value); void ExecuteOnSerializing(object value); void ExecuteOnSerialized(object value); } public interface IObjectGraphTraversalStrategy { void Traverse<TContext>(IObjectDescriptor graph, IObjectGraphVisitor<TContext> visitor, TContext context, ObjectSerializer serializer); } public interface IObjectGraphVisitor<TContext> { bool Enter(IPropertyDescriptor? propertyDescriptor, IObjectDescriptor value, TContext context, ObjectSerializer serializer); bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context, ObjectSerializer serializer); bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context, ObjectSerializer serializer); void VisitScalar(IObjectDescriptor scalar, TContext context, ObjectSerializer serializer); void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context, ObjectSerializer serializer); void VisitMappingEnd(IObjectDescriptor mapping, TContext context, ObjectSerializer serializer); void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context, ObjectSerializer serializer); void VisitSequenceEnd(IObjectDescriptor sequence, TContext context, ObjectSerializer serializer); } public interface IPropertyDescriptor { string Name { get; } bool AllowNulls { get; } bool CanWrite { get; } Type Type { get; } Type? TypeOverride { get; set; } int Order { get; set; } ScalarStyle ScalarStyle { get; set; } bool Required { get; } Type? ConverterType { get; } T? GetCustomAttribute<T>() where T : Attribute; IObjectDescriptor Read(object target); void Write(object target, object? value); } public interface IRegistrationLocationSelectionSyntax<TBaseRegistrationType> { void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType; void Before<TRegistrationType>() where TRegistrationType : TBaseRegistrationType; void After<TRegistrationType>() where TRegistrationType : TBaseRegistrationType; void OnTop(); void OnBottom(); } public interface ITrackingRegistrationLocationSelectionSyntax<TBaseRegistrationType> { void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType; } public interface ISerializer { string Serialize(object? graph); string Serialize(object? graph, Type type); void Serialize(TextWriter writer, object? graph); void Serialize(TextWriter writer, object? graph, Type type); void Serialize(IEmitter emitter, object? graph); void Serialize(IEmitter emitter, object? graph, Type type); } public interface ITypeInspector { IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container); IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched, bool caseInsensitivePropertyMatching); string GetEnumName(Type enumType, string name); string GetEnumValue(object enumValue); } public interface ITypeResolver { Type Resolve(Type staticType, object? actualValue); } public interface IValueDeserializer { object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer); } public interface IValuePromise { event Action<object?> ValueAvailable; } public interface IValueSerializer { void SerializeValue(IEmitter emitter, object? value, Type? type); } public interface IYamlConvertible { void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); } public delegate object? ObjectDeserializer(Type type); public delegate void ObjectSerializer(object? value, Type? type = null); [Obsolete("Please use IYamlConvertible instead")] public interface IYamlSerializable { void ReadYaml(IParser parser); void WriteYaml(IEmitter emitter); } public interface IYamlTypeConverter { bool Accepts(Type type); object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer); void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer); } internal sealed class LazyComponentRegistrationList<TArgument, TComponent> : IEnumerable<Func<TArgument, TComponent>>, IEnumerable { public sealed class LazyComponentRegistration { public readonly Type ComponentType; public readonly Func<TArgument, TComponent> Factory; public LazyComponentRegistration(Type componentType, Func<TArgument, TComponent> factory) { ComponentType = componentType; Factory = factory; } } public sealed class TrackingLazyComponentRegistration { public readonly Type ComponentType; public readonly Func<TComponent, TArgument, TComponent> Factory; public TrackingLazyComponentRegistration(Type componentType, Func<TComponent, TArgument, TComponent> factory) { ComponentType = componentType; Factory = factory; } } private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax<TComponent> { private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations; private readonly LazyComponentRegistration newRegistration; public RegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, LazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void IRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists<TRegistrationType>(); registrations.entries[index] = newRegistration; } void IRegistrationLocationSelectionSyntax<TComponent>.After<TRegistrationType>() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int num = registrations.EnsureRegistrationExists<TRegistrationType>(); registrations.entries.Insert(num + 1, newRegistration); } void IRegistrationLocationSelectionSyntax<TComponent>.Before<TRegistrationType>() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int index = registrations.EnsureRegistrationExists<TRegistrationType>(); registrations.entries.Insert(index, newRegistration); } void IRegistrationLocationSelectionSyntax<TComponent>.OnBottom() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Add(newRegistration); } void IRegistrationLocationSelectionSyntax<TComponent>.OnTop() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Insert(0, newRegistration); } } private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax<TComponent> { private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations; private readonly TrackingLazyComponentRegistration newRegistration; public TrackingRegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, TrackingLazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void ITrackingRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists<TRegistrationType>(); Func<TArgument, TComponent> innerComponentFactory = registrations.entries[index].Factory; registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg)); } } private readonly List<LazyComponentRegistration> entries = new List<LazyComponentRegistration>(); public int Count => entries.Count; public IEnumerable<Func<TArgument, TComponent>> InReverseOrder { get { int i = entries.Count - 1; while (i >= 0) { yield return entries[i].Factory; int num = i - 1; i = num; } } } public LazyComponentRegistrationList<TArgument, TComponent> Clone() { LazyComponentRegistrationList<TArgument, TComponent> lazyComponentRegistrationList = new LazyComponentRegistrationList<TArgument, TComponent>(); foreach (LazyComponentRegistration entry in entries) { lazyComponentRegistrationList.entries.Add(entry); } return lazyComponentRegistrationList; } public void Clear() { entries.Clear(); } public void Add(Type componentType, Func<TArgument, TComponent> factory) { entries.Add(new LazyComponentRegistration(componentType, factory)); } public void Remove(Type componentType) { for (int i = 0; i < entries.Count; i++) { if (entries[i].ComponentType == componentType) { entries.RemoveAt(i); return; } } throw new KeyNotFoundException("A component registration of type '" + componentType.FullName + "' was not found."); } public IRegistrationLocationSelectionSyntax<TComponent> CreateRegistrationLocationSelector(Type componentType, Func<TArgument, TComponent> factory) { return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory)); } public ITrackingRegistrationLocationSelectionSyntax<TComponent> CreateTrackingRegistrationLocationSelector(Type componentType, Func<TComponent, TArgument, TComponent> factory) { return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory)); } public IEnumerator<Func<TArgument, TComponent>> GetEnumerator() { return entries.Select((LazyComponentRegistration e) => e.Factory).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private int IndexOfRegistration(Type registrationType) { for (int i = 0; i < entries.Count; i++) { if (registrationType == entries[i].ComponentType) { return i; } } return -1; } private void EnsureNoDuplicateRegistrationType(Type componentType) { if (IndexOfRegistration(componentType) != -1) { throw new InvalidOperationException("A component of type '" + componentType.FullName + "' has already been registered."); } } private int EnsureRegistrationExists<TRegistrationType>() { int num = IndexOfRegistration(typeof(TRegistrationType)); if (num == -1) { throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered."); } return num; } } internal static class LazyComponentRegistrationListExtensions { public static TComponent BuildComponentChain<TComponent>(this LazyComponentRegistrationList<TComponent, TComponent> registrations, TComponent innerComponent) { return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TComponent, TComponent> factory) => factory(inner)); } public static TComponent BuildComponentChain<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TComponent innerComponent, Func<TComponent, TArgument> argumentBuilder) { Func<TComponent, TArgument> argumentBuilder2 = argumentBuilder; return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TArgument, TComponent> factory) => factory(argumentBuilder2(inner))); } public static List<TComponent> BuildComponentList<TComponent>(this LazyComponentRegistrationList<Nothing, TComponent> registrations) { return registrations.Select((Func<Nothing, TComponent> factory) => factory(default(Nothing))).ToList(); } public static List<TComponent> BuildComponentList<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TArgument argument) { TArgument argument2 = argument; return registrations.Select((Func<TArgument, TComponent> factory) => factory(argument2)).ToList(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct Nothing { } public sealed class ObjectDescriptor : IObjectDescriptor { public object? Value { get; private set; } public Type Type { get; private set; } public Type StaticType { get; private set; } public ScalarStyle ScalarStyle { get; private set; } public ObjectDescriptor(object? value, Type type, Type staticType) : this(value, type, staticType, ScalarStyle.Any) { } public ObjectDescriptor(object? value, Type type, Type staticType, ScalarStyle scalarStyle) { Value = value; Type = type ?? throw new ArgumentNullException("type"); StaticType = staticType ?? throw new ArgumentNullException("staticType"); ScalarStyle = scalarStyle; } } public delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion); public sealed class PropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; public bool AllowNulls => baseDescriptor.AllowNulls; public string Name { get; set; } public bool Required => baseDescriptor.Required; public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public Type? ConverterType => baseDescriptor.ConverterType; public int Order { get; set; } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public bool CanWrite => baseDescriptor.CanWrite; public PropertyDescriptor(IPropertyDescriptor baseDescriptor) { this.baseDescriptor = baseDescriptor; Name = baseDescriptor.Name; } public void Write(object target, object? value) { baseDescriptor.Write(target, value); } public T? GetCustomAttribute<T>() where T : Attribute { return baseDescriptor.GetCustomAttribute<T>(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } public sealed class Serializer : ISerializer { private readonly IValueSerializer valueSerializer; private readonly EmitterSettings emitterSettings; public Serializer() : this(new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default) { } private Serializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer"); this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings"); } public static Serializer FromValueSerializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { return new Serializer(valueSerializer, emitterSettings); } public string Serialize(object? graph) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph); return stringWriter.ToString(); } public string Serialize(object? graph, Type type) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph, type); return stringWriter.ToString(); } public void Serialize(TextWriter writer, object? graph) { Serialize(new Emitter(writer, emitterSettings), graph); } public void Serialize(TextWriter writer, object? graph, Type type) { Serialize(new Emitter(writer, emitterSettings), graph, type); } public void Serialize(IEmitter emitter, object? graph) { if (emitter == null) { throw new ArgumentNullException("emitter"); } EmitDocument(emitter, graph, null); } public void Serialize(IEmitter emitter, object? graph, Type type) { if (emitter == null) { throw new ArgumentNullException("emitter"); } if (type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, graph, type); } private void EmitDocument(IEmitter emitter, object? graph, Type? type) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); valueSerializer.SerializeValue(emitter, graph, type); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: true)); emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } } public sealed class SerializerBuilder : BuilderSkeleton<SerializerBuilder> { private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable<IYamlTypeConverter> typeConverters; private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<IYamlTypeConverter> typeConverters, LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } public void SerializeValue(IEmitter emitter, object? value, Type? type) { IEmitter emitter2 = emitter; Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List<IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); IObjectGraphVisitor<IEmitter> visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor<IEmitter> inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); foreach (IObjectGraphVisitor<Nothing> item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing), NestedObjectSerializer); } traversalStrategy.Traverse(graph, visitor, emitter2, NestedObjectSerializer); void NestedObjectSerializer(object? v, Type? t) { SerializeValue(emitter2, v, t); } } } private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList<IEventEmitter, IEventEmitter> eventEmitterFactories; private readonly Dictionary<Type, TagName> tagMappings = new Dictionary<Type, TagName>(); private readonly IObjectFactory objectFactory; private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private ScalarStyle defaultScalarStyle; private bool quoteNecessaryStrings; private bool quoteYaml1_1Strings; protected override SerializerBuilder Self => this; public SerializerBuilder() : base((ITypeResolver)new DynamicTypeResolver()) { typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> { { typeof(AnchorAssigner), (IEnumerable<IYamlTypeConverter> typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor<AnchorAssigner>()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, new DefaultObjectFactory()) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList<IEventEmitter, IEventEmitter> { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()) } }; objectFactory = new DefaultObjectFactory(); objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, objectFactory); } public SerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false) { quoteNecessaryStrings = true; this.quoteYaml1_1Strings = quoteYaml1_1Strings; return this; } public SerializerBuilder WithDefaultScalarStyle(ScalarStyle style) { defaultScalarStyle = style; return this; } public SerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory, Action<IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter { Func<IEventEmitter, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory; return WithEventEmitter((IEventEmitter e, ITypeInspector _) => eventEmitterFactory2(e), where); } public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory, Action<IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter { Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory2(inner, BuildTypeInspector()))); return Self; } public SerializerBuilder WithEventEmitter<TEventEmitter>(WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter { WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory2(wrapped, inner))); return Self; } public SerializerBuilder WithoutEventEmitter<TEventEmitter>() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public SerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override SerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public SerializerBuilder WithoutTagMapping(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public SerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, objectFactory); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc) { loc.InsteadOf<TypeAssigningEventEmitter>(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> loc) { loc.OnBottom(); }); } public SerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public SerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public SerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName().WithUtf16SurrogatePairs(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w) { w.InsteadOf<YamlDotNet.Serialization.Converters.GuidConverter>(); }).WithTypeConverter(new DateTime8601Converter(ScalarStyle.DoubleQuoted)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc) { loc.InsteadOf<TypeAssigningEventEmitter>(); }); } public SerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<IEnumerable<IYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { TObjectGraphVisitor objectGraphVisitor2 = objectGraphVisitor; if (objectGraphVisitor2 == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<IYamlTypeConverter> _) => objectGraphVisitor2)); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<IEnumerable<IYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { Func<IEnumerable<IYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<IYamlTypeConverter> typeConverters) => objectGraphVisitorFactory2(typeConverters))); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<Nothing> wrapped, IEnumerable<IYamlTypeConverter> _) => objectGraphVisitorFactory2(wrapped))); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { WrapperFactory<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<Nothing> wrapped, IEnumerable<IYamlTypeConverter> typeConverters) => objectGraphVisitorFactory2(wrapped, typeConverters))); return this; } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>> w) { w.OnTop(); }); } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(args))); return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<IEmitter> wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(wrapped, args))); return this; } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { if (FsharpHelper.Instance == null) { FsharpHelper.Instance = new DefaultFsharpHelper(); } return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable<IYamlTypeConverter> typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } public ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } } public class Settings { public bool AllowPrivateConstructors { get; set; } } public abstract class StaticBuilderSkeleton<TBuilder> where TBuilder : StaticBuilderSkeleton<TBuilder> { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal INamingConvention enumNamingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories; internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories; internal bool includeNonPublicProperties; internal Settings settings; internal YamlFormatter yamlFormatter = YamlFormatter.Default; protected abstract TBuilder Self { get; } internal StaticBuilderSkeleton(ITypeResolver typeResolver) { typeConverterFactories = new LazyComponentRegistrationList<Nothing, IYamlTypeConverter> { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) } }; typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithEnumNamingConvention(INamingConvention enumNamingConvention) { this.enumNamingConvention = enumNamingConvention ?? throw new ArgumentNullException("enumNamingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) { IYamlTypeConverter typeConverter2 = typeConverter; if (typeConverter2 == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2)); return Self; } public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter { WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory2 = typeConverterFactory; if (typeConverterFactory2 == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped))); return Self; } public TBuilder WithoutTypeConverter<TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w) { w.OnTop(); }); } public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector { Func<ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner))); return Self; } public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector { WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector<TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } public TBuilder WithYamlFormatter(YamlFormatter formatter) { yamlFormatter = formatter ?? throw new ArgumentNullException("formatter"); return Self; } protected IEnumerable<IYamlTypeConverter> BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } public abstract class StaticContext { public virtual bool IsKnownType(Type type) { throw new NotImplementedException(); } public virtual ITypeResolver GetTypeResolver() { throw new NotImplementedException(); } public virtual StaticObjectFactory GetFactory() { throw new NotImplementedException(); } public virtual ITypeInspector GetTypeInspector() { throw new NotImplementedException(); } } public sealed class StaticDeserializerBuilder : StaticBuilderSkeleton<StaticDeserializerBuilder> { private readonly StaticContext context; private readonly StaticObjectFactory factory; private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories; private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories; private readonly Dictionary<TagName, Type> tagMappings; private readonly ITypeConverter typeConverter; private readonly Dictionary<Type, Type> typeMappings; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; private bool enforceNullability; private bool caseInsensitivePropertyMatching; protected override StaticDeserializerBuilder Self => this; public StaticDeserializerBuilder(StaticContext context) : base(context.GetTypeResolver()) { this.context = context; factory = context.GetFactory(); typeMappings = new Dictionary<Type, Type>(); tagMappings = new Dictionary<TagName, Type> { { FailsafeSchema.Tags.Map, typeof(Dictionary<object, object>) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList<Nothing, INodeDeserializer> { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(factory) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(factory) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter, BuildTypeInspector(), yamlFormatter, enumNamingConvention) }, { typeof(StaticArrayNodeDeserializer), (Nothing _) => new StaticArrayNodeDeserializer(factory) }, { typeof(StaticDictionaryNodeDeserializer), (Nothing _) => new StaticDictionaryNodeDeserializer(factory, duplicateKeyChecking) }, { typeof(StaticCollectionNodeDeserializer), (Nothing _) => new StaticCollectionNodeDeserializer(factory) }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(factory, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter, enumNamingConvention, enforceNullability, caseInsensitivePropertyMatching, enforceRequiredProperties: false, BuildTypeConverters()) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList<Nothing, INodeTypeResolver> { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new NullTypeConverter(); } public ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } public StaticDeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where) { INodeDeserializer nodeDeserializer2 = nodeDeserializer; if (nodeDeserializer2 == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2)); return this; } public StaticDeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer { WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory2 = nodeDeserializerFactory; if (nodeDeserializerFactory2 == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped))); return this; } public StaticDeserializerBuilder WithCaseInsensitivePropertyMatching() { caseInsensitivePropertyMatching = true; return this; } public StaticDeserializerBuilder WithEnforceNullability() { enforceNullability = true; return this; } public StaticDeserializerBuilder WithoutNodeDeserializer<TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public StaticDeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public StaticDeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action<ITypeDiscriminatingNodeDeserializerOptions> configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> s) { s.Before<DictionaryNodeDeserializer>(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) { INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver; if (nodeTypeResolver2 == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2)); return this; } public StaticDeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver { WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory2 = nodeTypeResolverFactory; if (nodeTypeResolverFactory2 == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeTypeResolver<TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public StaticDeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override StaticDeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out Type value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public StaticDeserializerBuilder WithTypeMapping<TInterface, TConcrete>() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } typeMappings[typeFromHandle] = typeFromHandle2; return this; } public StaticDeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public StaticDeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public StaticDeserializerBuilder WithDuplicateKeyChecking() { duplicateKeyChecking = true; return this; } public IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter, enumNamingConvention, BuildTypeInspector())); } } public sealed class StaticSerializerBuilder : StaticBuilderSkeleton<StaticSerializerBuilder> { private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable<IYamlTypeConverter> typeConverters; private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<IYamlTypeConverter> typeConverters, LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } public void SerializeValue(IEmitter emitter, object? value, Type? type) { IEmitter emitter2 =