From 8ddbabbfdee77a63341b5339d3742176806dd28c Mon Sep 17 00:00:00 2001 From: Pavel Penev Date: Fri, 28 Aug 2015 03:16:07 +0300 Subject: [PATCH] Add Dictionary<,> support to FieldSaver --- OpenRA.Game/FieldLoader.cs | 12 ++++++++++++ OpenRA.Game/FieldSaver.cs | 32 +++++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/OpenRA.Game/FieldLoader.cs b/OpenRA.Game/FieldLoader.cs index 77b13c683e..07d2387672 100644 --- a/OpenRA.Game/FieldLoader.cs +++ b/OpenRA.Game/FieldLoader.cs @@ -648,6 +648,7 @@ namespace OpenRA public string YamlName; public string Loader; public bool FromYamlKey; + public bool DictionaryFromYamlKey; public bool Required; public SerializeAttribute(bool serialize = true, bool required = false) @@ -710,6 +711,17 @@ namespace OpenRA } } + // Special-cases FieldFromYamlKeyAttribute for use with Dictionary. + [AttributeUsage(AttributeTargets.Field)] + public sealed class DictionaryFromYamlKeyAttribute : FieldLoader.SerializeAttribute + { + public DictionaryFromYamlKeyAttribute() + { + FromYamlKey = true; + DictionaryFromYamlKey = true; + } + } + // mirrors DescriptionAttribute from System.ComponentModel but we dont want to have to use that everywhere. [AttributeUsage(AttributeTargets.All)] public sealed class DescAttribute : Attribute diff --git a/OpenRA.Game/FieldSaver.cs b/OpenRA.Game/FieldSaver.cs index 70b17ca936..e082074d46 100644 --- a/OpenRA.Game/FieldSaver.cs +++ b/OpenRA.Game/FieldSaver.cs @@ -28,7 +28,18 @@ namespace OpenRA foreach (var info in FieldLoader.GetTypeLoadInfo(o.GetType(), includePrivateByDefault)) { - if (info.Attribute.FromYamlKey) + if (info.Attribute.DictionaryFromYamlKey) + { + var dict = (System.Collections.IDictionary)info.Field.GetValue(o); + foreach (var kvp in dict) + { + var key = ((System.Collections.DictionaryEntry)kvp).Key; + var value = ((System.Collections.DictionaryEntry)kvp).Value; + + nodes.Add(new MiniYamlNode(FormatValue(key, key.GetType()), FormatValue(value, value.GetType()))); + } + } + else if (info.Attribute.FromYamlKey) root = FormatValue(o, info.Field); else nodes.Add(new MiniYamlNode(info.YamlName, FormatValue(o, info.Field))); @@ -99,6 +110,25 @@ namespace OpenRA return ((System.Collections.IEnumerable)v).Cast().JoinWith(", "); } + // This is only for documentation generation + if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>)) + { + var result = ""; + var dict = (System.Collections.IDictionary)v; + foreach (var kvp in dict) + { + var key = ((System.Collections.DictionaryEntry)kvp).Key; + var value = ((System.Collections.DictionaryEntry)kvp).Value; + + var formattedKey = FormatValue(key, key.GetType()); + var formattedValue = FormatValue(value, value.GetType()); + + result += "{0}: {1}{2}".F(formattedKey, formattedValue, Environment.NewLine); + } + + return result; + } + if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(OpenRA.Primitives.Cache<,>)) return ""; // TODO