Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
PropertyKeyYamlSerializer.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Reflection;
5 using System.Text;
6 using SharpYaml;
7 using SharpYaml.Events;
8 using SharpYaml.Serialization;
9 using SiliconStudio.Core;
10 using SiliconStudio.Core.Yaml;
11 
12 namespace SiliconStudio.Assets.Serializers
13 {
14  [YamlSerializerFactory]
15  internal class PropertyKeyYamlSerializer : AssetScalarSerializerBase
16  {
17  public override bool CanVisit(Type type)
18  {
19  // Because a PropertyKey<> inherits directly from PropertyKey, we can directly check the base only
20  // ParameterKey<> inherits from ParameterKey, so it won't conflict with the custom ParameterKeyYamlSerializer
21  // defined in the SiliconStudio.Paradox.Assets assembly
22 
23  if (type == typeof(PropertyKey))
24  {
25  return true;
26  }
27 
28  for (Type t = type; t != null; t = t.BaseType)
29  if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(PropertyKey<>))
30  return true;
31 
32  return false;
33  }
34 
35  public override object ConvertFrom(ref ObjectContext objectContext, Scalar fromScalar)
36  {
37  var lastDot = fromScalar.Value.LastIndexOf('.');
38  if (lastDot == -1)
39  return null;
40 
41  var className = fromScalar.Value.Substring(0, lastDot);
42 
43  var containingClass = objectContext.SerializerContext.TypeFromTag("!" + className); // Readd initial '!'
44  if (containingClass == null)
45  {
46  throw new YamlException(fromScalar.Start, fromScalar.End, "Unable to find class from tag [{0}]".ToFormat(className));
47  }
48 
49  var propertyName = fromScalar.Value.Substring(lastDot + 1);
50  var propertyField = containingClass.GetField(propertyName, BindingFlags.Public | BindingFlags.Static);
51  if (propertyField == null)
52  {
53  throw new YamlException(fromScalar.Start, fromScalar.End, "Unable to find property [{0}] in class [{1}]".ToFormat(propertyName, containingClass.Name));
54  }
55 
56  return propertyField.GetValue(null);
57  }
58 
59  protected override void WriteScalar(ref ObjectContext objectContext, ScalarEventInfo scalar)
60  {
61  // TODO: if ParameterKey is written to an object, It will not serialized a tag
62  scalar.Tag = null;
63  scalar.IsPlainImplicit = true;
64  base.WriteScalar(ref objectContext, scalar);
65  }
66 
67  public override string ConvertTo(ref ObjectContext objectContext)
68  {
69  var propertyKey = (PropertyKey)objectContext.Instance;
70 
71  return AssetPropertyKeyNameResolver.ComputePropertyKeyName(objectContext.SerializerContext, propertyKey);
72  }
73 
74 
75  }
76 }
A class that represents a tag propety.
Definition: PropertyKey.cs:17