/// <summary> /// Load data for ParserTarget field or property from a configuration node /// </summary> /// <param name="member">Member to load data for</param> /// <param name="o">Instance of the object which owns member</param> /// <param name="node">Configuration node from which to load data</param> /// <param name="configName">The name of the mod that corresponds to the entry in ParserOptions</param> /// <param name="getChildren">Whether getters on the object should get called</param> private static void LoadObjectMemberFromConfigurationNode(MemberInfo member, Object o, ConfigNode node, String configName = "Default", Boolean getChildren = true) { // Get the parser targets ParserTarget[] targets = (ParserTarget[])member.GetCustomAttributes(typeof(ParserTarget), true); // Process the targets foreach (ParserTarget target in targets) { // Figure out if this field exists and if we care Boolean isNode = node.GetNodes() .Any(n => n.name.StartsWith(target.FieldName + ":") || n.name == target.FieldName); Boolean isValue = node.HasValue(target.FieldName); // Obtain the type the member is (can only be field or property) Type targetType; Object targetValue = null; if (member.MemberType == MemberTypes.Field) { targetType = ((FieldInfo)member).FieldType; targetValue = getChildren ? ((FieldInfo)member).GetValue(o) : null; } else { targetType = ((PropertyInfo)member).PropertyType; try { if (((PropertyInfo)member).CanRead && getChildren) { targetValue = ((PropertyInfo)member).GetValue(o, null); } } catch (Exception) { // ignored } } // Get settings data ParserOptions.Data data = ParserOptions.Options[configName]; // Log data.LogCallback("Parsing Target " + target.FieldName + " in (" + o.GetType() + ") as (" + targetType + ")"); // If there was no data found for this node if (!isNode && !isValue) { if (!target.Optional && !(target.AllowMerge && targetValue != null)) { // Error - non optional field is missing throw new ParserTargetMissingException( "Missing non-optional field: " + o.GetType() + "." + target.FieldName); } // Nothing to do, so DONT return! continue; } // Does this node have a required config source type (and if so, check if valid) RequireConfigType[] attributes = (RequireConfigType[])targetType.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0) { if (attributes[0].Type == ConfigType.Node && !isNode || attributes[0].Type == ConfigType.Value && !isValue) { throw new ParserTargetTypeMismatchException( target.FieldName + " requires config value of " + attributes[0].Type); } } // If this object is a value (attempt no merge here) if (isValue) { // Process the value Object val = ProcessValue(targetType, node.GetValue(target.FieldName)); // Throw exception or print error if (val == null) { data.LogCallback("[Kopernicus]: Configuration.Parser: ParserTarget \"" + target.FieldName + "\" is a non parsable type: " + targetType); continue; } targetValue = val; } // If this object is a node (potentially merge) else { // If the target type is a ConfigNode, this works natively if (targetType == typeof(ConfigNode)) { targetValue = node.GetNode(target.FieldName); } // We need to get an instance of the object we are trying to populate // If we are not allowed to merge, or the object does not exist, make a new instance // Otherwise we can merge this value else if (targetValue == null || !target.AllowMerge) { if (!targetType.IsAbstract) { targetValue = Activator.CreateInstance(targetType); } } // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: // Just processes the contents of the node LoadObjectFromConfigurationNode(targetValue, node.GetNode(target.FieldName), configName, target.GetChild); break; case NameSignificance.Type: // Generate the type from the name ConfigNode subnode = node.GetNodes().First(n => n.name.StartsWith(target.FieldName + ":")); String[] split = subnode.name.Split(':'); Type elementType = ModTypes.FirstOrDefault(t => t.Name == split[1] && !Equals(t.Assembly, typeof(HighLogic).Assembly) && targetType.IsAssignableFrom(t)); // If no object was found, check if the type implements custom constructors targetValue = Activator.CreateInstance(elementType); if (typeof(ICreatable).IsAssignableFrom(elementType)) { ICreatable creatable = (ICreatable)targetValue; creatable.Create(); } // Parse the config node into the object LoadObjectFromConfigurationNode(targetValue, subnode, configName, target.GetChild); break; case NameSignificance.Key: throw new Exception("NameSignificance.Key is not supported on ParserTargets"); default: throw new ArgumentOutOfRangeException(); } } // If the member type is a field, set the value if (member.MemberType == MemberTypes.Field) { ((FieldInfo)member).SetValue(o, targetValue); } // If the member wasn't a field, it must be a property. If the property is writable, set it. else if (((PropertyInfo)member).CanWrite) { ((PropertyInfo)member).SetValue(o, targetValue, null); } } }
/// <summary> /// Load collection for ParserTargetCollection /// </summary> /// <param name="member">Member to load data for</param> /// <param name="o">Instance of the object which owns member</param> /// <param name="node">Configuration node from which to load data</param> /// <param name="modName">The name of the mod that corresponds to the entry in ParserOptions</param> /// <param name="getChilds">Whether getters on the object should get called</param> public static void LoadCollectionMemberFromConfigurationNode(MemberInfo member, Object o, ConfigNode node, String modName = "Default", Boolean getChilds = true) { // Get the target attribute ParserTargetCollection target = ((ParserTargetCollection[])member.GetCustomAttributes(typeof(ParserTargetCollection), true))[0]; // Figure out if this field exists and if we care Boolean isNode = node.HasNode(target.fieldName); Boolean isValue = node.HasValue(target.fieldName); // Obtain the type the member is (can only be field or property) Type targetType; Object targetValue = null; if (member.MemberType == MemberTypes.Field) { targetType = ((FieldInfo)member).FieldType; targetValue = getChilds ? ((FieldInfo)member).GetValue(o) : null; } else { targetType = ((PropertyInfo)member).PropertyType; try { if (((PropertyInfo)member).CanRead && getChilds) { targetValue = ((PropertyInfo)member).GetValue(o, null); } } catch (Exception) { // ignored } } // If there was no data found for this node if (!isNode && !isValue) { if (!target.optional && !(target.allowMerge && targetValue != null)) { // Error - non optional field is missing throw new ParserTargetMissingException("Missing non-optional field: " + o.GetType() + "." + target.fieldName); } // Nothing to do, so return return; } // If we are dealing with a generic collection if (targetType.IsGenericType) { // If the target is a generic dictionary if (typeof(IDictionary).IsAssignableFrom(targetType)) { throw new Exception("Generic dictionaries are unsupported at this time"); } // If the target is a generic collection else if (typeof(IList).IsAssignableFrom(targetType)) { // We need a node for this decoding if (!isNode) { throw new Exception("Loading a generic list requires sources to be nodes"); } // Get the target value as a collection IList collection = targetValue as IList; // Get the internal type of this collection Type genericType = targetType.GetGenericArguments()[0]; // Create a new collection if merge is disallowed or if the collection is null if (collection == null || !target.allowMerge) { collection = Activator.CreateInstance(targetType) as IList; targetValue = collection; } // Iterate over all of the nodes in this node foreach (ConfigNode subnode in node.GetNode(target.fieldName).nodes) { // Check for the name significance if (target.nameSignificance == NameSignificance.None) { // Just processes the contents of the node collection?.Add(CreateObjectFromConfigNode(genericType, subnode, modName, target.getChild)); } // Otherwise throw an exception because we don't support named ones yet else if (target.nameSignificance == NameSignificance.Type) { // Generate the type from the name Type elementType = ModTypes.FirstOrDefault(t => t.Name == subnode.name); // Add the object to the collection collection?.Add(CreateObjectFromConfigNode(elementType, subnode, modName, target.getChild)); } } } } // If we are dealing with a non generic collection else { // Check for invalid scenarios if (target.nameSignificance == NameSignificance.None) { throw new Exception("Can not infer type from non generic target; can not infer type from zero name significance"); } } // If the member type is a field, set the value if (member.MemberType == MemberTypes.Field) { ((FieldInfo)member).SetValue(o, targetValue); } // If the member wasn't a field, it must be a property. If the property is writable, set it. else if (((PropertyInfo)member).CanWrite) { ((PropertyInfo)member).SetValue(o, targetValue, null); } }
/// <summary> /// Load collection for ParserTargetCollection /// </summary> /// <param name="member">Member to load data for</param> /// <param name="o">Instance of the object which owns member</param> /// <param name="node">Configuration node from which to load data</param> /// <param name="configName">The name of the mod that corresponds to the entry in ParserOptions</param> /// <param name="getChildren">Whether getters on the object should get called</param> private static void LoadCollectionMemberFromConfigurationNode(MemberInfo member, Object o, ConfigNode node, String configName = "Default", Boolean getChildren = true) { // Get the target attributes ParserTargetCollection[] targets = (ParserTargetCollection[])member.GetCustomAttributes(typeof(ParserTargetCollection), true); // Process the target attributes foreach (ParserTargetCollection target in targets) { // Figure out if this field exists and if we care Boolean isNode = node.HasNode(target.FieldName) || target.FieldName == "self"; Boolean isValue = node.HasValue(target.FieldName); // Obtain the type the member is (can only be field or property) Type targetType; Object targetValue = null; if (member.MemberType == MemberTypes.Field) { targetType = ((FieldInfo)member).FieldType; targetValue = getChildren ? ((FieldInfo)member).GetValue(o) : null; } else { targetType = ((PropertyInfo)member).PropertyType; try { if (((PropertyInfo)member).CanRead && getChildren) { targetValue = ((PropertyInfo)member).GetValue(o, null); } } catch (Exception) { // ignored } } // Get settings data ParserOptions.Data data = ParserOptions.Options[configName]; // Log data.LogCallback("Parsing Target " + target.FieldName + " in (" + o.GetType() + ") as (" + targetType + ")"); // If there was no data found for this node if (!isNode && !isValue) { if (!target.Optional && !(target.AllowMerge && targetValue != null)) { // Error - non optional field is missing throw new ParserTargetMissingException( "Missing non-optional field: " + o.GetType() + "." + target.FieldName); } // Nothing to do, so return continue; } // If we are dealing with a generic collection if (targetType.IsGenericType) { // If the target is a generic dictionary if (typeof(IDictionary).IsAssignableFrom(targetType)) { // We need a node for this decoding if (!isNode) { throw new Exception("Loading a generic dictionary requires sources to be nodes"); } // Get the target value as a dictionary IDictionary collection = targetValue as IDictionary; // Get the internal type of this collection Type genericTypeA = targetType.GetGenericArguments()[0]; Type genericTypeB = targetType.GetGenericArguments()[1]; // Create a new collection if merge is disallowed or if the collection is null if (collection == null || !target.AllowMerge) { collection = Activator.CreateInstance(targetType) as IDictionary; targetValue = collection; } // Process the node ConfigNode targetNode = target.FieldName == "self" ? node : node.GetNode(target.FieldName); // Check the config type RequireConfigType[] attributes = (RequireConfigType[])genericTypeA.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0) { if (attributes[0].Type == ConfigType.Node) { throw new ParserTargetTypeMismatchException( "The key value of a generic dictionary must be a Value"); } } attributes = (RequireConfigType[])genericTypeB.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0 || genericTypeB == typeof(String)) { ConfigType type = genericTypeB == typeof(String) ? ConfigType.Value : attributes[0].Type; if (type == ConfigType.Node) { // Iterate over all of the nodes in this node foreach (ConfigNode subnode in targetNode.nodes) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: // Just processes the contents of the node collection.Add(ProcessValue(genericTypeA, subnode.name), CreateObjectFromConfigNode(genericTypeB, subnode, configName, target.GetChild)); break; case NameSignificance.Type: throw new Exception( "NameSignificance.Type isn't supported on generic dictionaries."); case NameSignificance.Key: throw new Exception( "NameSignificance.Key isn't supported on generic dictionaries"); default: throw new ArgumentOutOfRangeException(); } } } else { // Iterate over all of the values in this node foreach (ConfigNode.Value value in targetNode.values) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: collection.Add(ProcessValue(genericTypeA, value.name), ProcessValue(genericTypeB, value.value)); break; case NameSignificance.Type: throw new Exception( "NameSignificance.Type isn't supported on generic dictionaries."); case NameSignificance.Key: throw new Exception( "NameSignificance.Key isn't supported on generic dictionaries"); default: throw new ArgumentOutOfRangeException(); } } } } } // If the target is a generic collection else if (typeof(IList).IsAssignableFrom(targetType)) { // We need a node for this decoding if (!isNode) { throw new Exception("Loading a generic list requires sources to be nodes"); } // Get the target value as a collection IList collection = targetValue as IList; // Get the internal type of this collection Type genericType = targetType.GetGenericArguments()[0]; // Create a new collection if merge is disallowed or if the collection is null if (collection == null || !target.AllowMerge) { collection = Activator.CreateInstance(targetType) as IList; targetValue = collection; } // Store the objects that were already patched List <Object> patched = new List <Object>(); // Process the node ConfigNode targetNode = target.FieldName == "self" ? node : node.GetNode(target.FieldName); // Check the config type RequireConfigType[] attributes = (RequireConfigType[])genericType.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0 || genericType == typeof(String)) { ConfigType type = genericType == typeof(String) ? ConfigType.Value : attributes[0].Type; if (type == ConfigType.Node) { // Iterate over all of the nodes in this node foreach (ConfigNode subnode in targetNode.nodes) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: case NameSignificance.Key when subnode.name == target.Key: // Check if the type represents patchable data Object current = null; if (typeof(IPatchable).IsAssignableFrom(genericType) && collection.Count > 0) { for (Int32 i = 0; i < collection.Count; i++) { if (collection[i].GetType() != genericType) { continue; } if (patched.Contains(collection[i])) { continue; } IPatchable patchable = (IPatchable)collection[i]; PatchData patchData = CreateObjectFromConfigNode <PatchData>(subnode, "Internal"); if (patchData.name == patchable.name) { // Name matches, check for an index if (patchData.index == collection.IndexOf(collection[i])) { // Both values match current = collection[i]; break; } if (patchData.index > -1) { // Index doesn't match, continue continue; } // Name matches, and no index exists current = collection[i]; break; } if (patchData.name != null) { // The name doesn't match, continue the search continue; } // We found the first object that wasn't patched yet current = collection[i]; break; } } // If no object was found, check if the type implements custom constructors if (current == null) { current = Activator.CreateInstance(genericType); collection?.Add(current); } // Parse the config node into the object LoadObjectFromConfigurationNode(current, subnode, configName, target.GetChild); patched.Add(current); if (collection != null) { collection[collection.IndexOf(current)] = current; } break; case NameSignificance.Type: // Generate the type from the name Type elementType = ModTypes.FirstOrDefault(t => t.Name == subnode.name && !Equals(t.Assembly, typeof(HighLogic).Assembly) && genericType.IsAssignableFrom(t)); // Check if the type represents patchable data current = null; if (typeof(IPatchable).IsAssignableFrom(elementType) && collection.Count > 0) { for (Int32 i = 0; i < collection.Count; i++) { if (collection[i].GetType() != elementType) { continue; } if (patched.Contains(collection[i])) { continue; } IPatchable patchable = (IPatchable)collection[i]; PatchData patchData = CreateObjectFromConfigNode <PatchData>(subnode, "Internal"); if (patchData.name == patchable.name) { // Name matches, check for an index if (patchData.index == i) { // Both values match current = collection[i]; break; } if (patchData.index > -1) { // Index doesn't match, continue continue; } // Name matches, and no index exists current = collection[i]; break; } if (patchData.name != null) { // The name doesn't match, continue the search continue; } // We found the first object that wasn't patched yet current = collection[i]; break; } } // If no object was found, check if the type implements custom constructors if (current == null) { current = Activator.CreateInstance(elementType); collection?.Add(current); if (typeof(ICreatable).IsAssignableFrom(elementType)) { ICreatable creatable = (ICreatable)current; creatable.Create(); } } // Parse the config node into the object LoadObjectFromConfigurationNode(current, subnode, configName, target.GetChild); patched.Add(current); if (collection != null) { collection[collection.IndexOf(current)] = current; } break; default: continue; } } } else { // Iterate over all of the nodes in this node foreach (ConfigNode.Value value in targetNode.values) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: // Just processes the contents of the node collection?.Add(ProcessValue(genericType, value.value)); break; case NameSignificance.Type: // Generate the type from the name Type elementType = ModTypes.FirstOrDefault(t => t.Name == value.name && !Equals(t.Assembly, typeof(HighLogic).Assembly) && genericType.IsAssignableFrom(t)); // Add the object to the collection collection?.Add(ProcessValue(elementType, value.value)); break; case NameSignificance.Key when value.name == target.Key: // Just processes the contents of the node collection?.Add(ProcessValue(genericType, value.value)); break; default: continue; } } } } } } // If we are dealing with a non generic collection else { // Check for invalid scenarios if (target.NameSignificance == NameSignificance.None) { throw new Exception( "Can not infer type from non generic target; can not infer type from zero name significance"); } } // If the member type is a field, set the value if (member.MemberType == MemberTypes.Field) { ((FieldInfo)member).SetValue(o, targetValue); } // If the member wasn't a field, it must be a property. If the property is writable, set it. else if (((PropertyInfo)member).CanWrite) { ((PropertyInfo)member).SetValue(o, targetValue, null); } } }