summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Xaml/CreateValuesVisitor.cs
blob: 817b62c80b89299816435e3cfd53acdbb4a0a05c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Xml;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Xaml.Internals;

namespace Xamarin.Forms.Xaml
{
	internal class CreateValuesVisitor : IXamlNodeVisitor
	{
		public CreateValuesVisitor(HydratationContext context)
		{
			Context = context;
		}

		Dictionary<INode, object> Values
		{
			get { return Context.Values; }
		}

		HydratationContext Context { get; }

		public bool VisitChildrenFirst
		{
			get { return true; }
		}

		public bool StopOnDataTemplate
		{
			get { return true; }
		}

		public bool StopOnResourceDictionary
		{
			get { return false; }
		}

		public void Visit(ValueNode node, INode parentNode)
		{
			Values[node] = node.Value;
		}

		public void Visit(MarkupNode node, INode parentNode)
		{
		}

		public void Visit(ElementNode node, INode parentNode)
		{
			object value = null;

			XamlParseException xpe;
			var type = XamlParser.GetElementType(node.XmlType, node, Context.RootElement?.GetType().GetTypeInfo().Assembly,
				out xpe);
			if (xpe != null)
				throw xpe;

			Context.Types[node] = type;
			string ctorargname;
			if (IsXaml2009LanguagePrimitive(node))
				value = CreateLanguagePrimitive(type, node);
			else if (node.Properties.ContainsKey(XmlName.xArguments) || node.Properties.ContainsKey(XmlName.xFactoryMethod))
				value = CreateFromFactory(type, node);
			else if (
				type.GetTypeInfo()
					.DeclaredConstructors.Any(
						ci =>
							ci.IsPublic && ci.GetParameters().Length != 0 &&
							ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof (ParameterAttribute)))) &&
				ValidateCtorArguments(type, node, out ctorargname))
				value = CreateFromParameterizedConstructor(type, node);
			else if (!type.GetTypeInfo().DeclaredConstructors.Any(ci => ci.IsPublic && ci.GetParameters().Length == 0) &&
			         !ValidateCtorArguments(type, node, out ctorargname))
			{
				throw new XamlParseException($"The Property {ctorargname} is required to create a {type.FullName} object.", node);
			}
			else
			{
				//this is a trick as the DataTemplate parameterless ctor is internal, and we can't CreateInstance(..., false) on WP7
				try
				{
					if (type == typeof (DataTemplate))
						value = new DataTemplate();
					if (type == typeof (ControlTemplate))
						value = new ControlTemplate();
					if (value == null && node.CollectionItems.Any() && node.CollectionItems.First() is ValueNode)
					{
						var serviceProvider = new XamlServiceProvider(node, Context);
						var converted = ((ValueNode)node.CollectionItems.First()).Value.ConvertTo(type, () => type.GetTypeInfo(),
							serviceProvider);
						if (converted != null && converted.GetType() == type)
							value = converted;
					}
					if (value == null)
						value = Activator.CreateInstance(type);
				}
				catch (TargetInvocationException e)
				{
					if (e.InnerException is XamlParseException || e.InnerException is XmlException)
						throw e.InnerException;
					throw;
				}
			}

			Values[node] = value;

			var markup = value as IMarkupExtension;
			if (markup != null && (value is TypeExtension || value is StaticExtension || value is ArrayExtension))
			{
				var serviceProvider = new XamlServiceProvider(node, Context);

				var visitor = new ApplyPropertiesVisitor(Context);
				foreach (var cnode in node.Properties.Values.ToList())
					cnode.Accept(visitor, node);
				foreach (var cnode in node.CollectionItems)
					cnode.Accept(visitor, node);

				value = markup.ProvideValue(serviceProvider);

				INode xKey;
				if (!node.Properties.TryGetValue(XmlName.xKey, out xKey))
					xKey = null;
				
				node.Properties.Clear();
				node.CollectionItems.Clear();

				if (xKey != null)
					node.Properties.Add(XmlName.xKey, xKey);

				Values[node] = value;
			}

			if (value is BindableObject)
				NameScope.SetNameScope(value as BindableObject, node.Namescope);
		}

		public void Visit(RootNode node, INode parentNode)
		{
			var rnode = (XamlLoader.RuntimeRootNode)node;
			Values[node] = rnode.Root;
			Context.Types[node] = rnode.Root.GetType();
			var bindableRoot = rnode.Root as BindableObject;
			if (bindableRoot != null)
				NameScope.SetNameScope(bindableRoot, node.Namescope);
		}

		public void Visit(ListNode node, INode parentNode)
		{
			//this is a gross hack to keep ListNode alive. ListNode must go in favor of Properties
			XmlName name;
			if (ApplyPropertiesVisitor.TryGetPropertyName(node, parentNode, out name))
				node.XmlName = name;
		}

		bool ValidateCtorArguments(Type nodeType, IElementNode node, out string missingArgName)
		{
			missingArgName = null;
			var ctorInfo =
				nodeType.GetTypeInfo()
					.DeclaredConstructors.FirstOrDefault(
						ci =>
							ci.GetParameters().Length != 0 && ci.IsPublic &&
							ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof (ParameterAttribute))));
			if (ctorInfo == null)
				return true;
			foreach (var parameter in ctorInfo.GetParameters())
			{
				var propname =
					parameter.CustomAttributes.First(ca => ca.AttributeType.FullName == "Xamarin.Forms.ParameterAttribute")
						.ConstructorArguments.First()
						.Value as string;
				if (!node.Properties.ContainsKey(new XmlName("", propname)))
				{
					missingArgName = propname;
					return false;
				}
			}

			return true;
		}

		public object CreateFromParameterizedConstructor(Type nodeType, IElementNode node)
		{
			var ctorInfo =
				nodeType.GetTypeInfo()
					.DeclaredConstructors.FirstOrDefault(
						ci =>
							ci.GetParameters().Length != 0 && ci.IsPublic &&
							ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof (ParameterAttribute))));
			object[] arguments = CreateArgumentsArray(node, ctorInfo);
			return ctorInfo.Invoke(arguments);
		}

		public object CreateFromFactory(Type nodeType, IElementNode node)
		{
			object[] arguments = CreateArgumentsArray(node);

			if (!node.Properties.ContainsKey(XmlName.xFactoryMethod))
			{
				//non-default ctor
				return Activator.CreateInstance(nodeType, arguments);
			}

			var factoryMethod = ((string)((ValueNode)node.Properties[XmlName.xFactoryMethod]).Value);
			Type[] types = arguments == null ? new Type[0] : arguments.Select(a => a.GetType()).ToArray();
			Func<MethodInfo, bool> isMatch = m => {
				if (m.Name != factoryMethod)
					return false;
				var p = m.GetParameters();
				if (p.Length != types.Length)
					return false;
				if (!m.IsStatic)
					return false;
				for (var i = 0; i < p.Length; i++) {
					if ((p [i].ParameterType.IsAssignableFrom(types [i])))
						continue;
					var op_impl = p [i].ParameterType.GetRuntimeMethod("op_Implicit", new [] { types [i]});
					if (op_impl == null)
						return false;
					arguments [i] = op_impl.Invoke(null, new [] { arguments [i]});
				}
				return true;
			};
			var mi = nodeType.GetRuntimeMethods().FirstOrDefault(isMatch);
			if (mi == null)
				throw new MissingMemberException($"No static method found for {nodeType.FullName}::{factoryMethod} ({string.Join(", ", types.Select(t => t.FullName))})");
			return mi.Invoke(null, arguments);
		}

		public object[] CreateArgumentsArray(IElementNode enode)
		{
			if (!enode.Properties.ContainsKey(XmlName.xArguments))
				return null;
			var node = enode.Properties[XmlName.xArguments];
			var elementNode = node as ElementNode;
			if (elementNode != null)
			{
				var array = new object[1];
				array[0] = Values[elementNode];
				return array;
			}

			var listnode = node as ListNode;
			if (listnode != null)
			{
				var array = new object[listnode.CollectionItems.Count];
				for (var i = 0; i < listnode.CollectionItems.Count; i++)
					array[i] = Values[(ElementNode)listnode.CollectionItems[i]];
				return array;
			}
			return null;
		}

		public object[] CreateArgumentsArray(IElementNode enode, ConstructorInfo ctorInfo)
		{
			var n = ctorInfo.GetParameters().Length;
			var array = new object[n];
			for (var i = 0; i < n; i++)
			{
				var parameter = ctorInfo.GetParameters()[i];
				var propname =
					parameter.CustomAttributes.First(attr => attr.AttributeType == typeof (ParameterAttribute))
						.ConstructorArguments.First()
						.Value as string;
				var name = new XmlName("", propname);
				INode node;
				if (!enode.Properties.TryGetValue(name, out node))
				{
					throw new XamlParseException(
						String.Format("The Property {0} is required to create a {1} object.", propname, ctorInfo.DeclaringType.FullName),
						enode as IXmlLineInfo);
				}
				if (!enode.SkipProperties.Contains(name))
					enode.SkipProperties.Add(name);
				var value = Context.Values[node];
				var serviceProvider = new XamlServiceProvider(enode, Context);
				var convertedValue = value.ConvertTo(parameter.ParameterType, () => parameter, serviceProvider);
				array[i] = convertedValue;
			}

			return array;
		}

		static bool IsXaml2009LanguagePrimitive(IElementNode node)
		{
			return node.NamespaceURI == "http://schemas.microsoft.com/winfx/2009/xaml";
		}

		static object CreateLanguagePrimitive(Type nodeType, IElementNode node)
		{
			object value = null;
			if (nodeType == typeof (string))
				value = String.Empty;
			else if (nodeType == typeof (Uri))
				value = null;
			else
				value = Activator.CreateInstance(nodeType);

			if (node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode &&
			    ((ValueNode)node.CollectionItems[0]).Value is string)
			{
				var valuestring = ((ValueNode)node.CollectionItems[0]).Value as string;

				if (nodeType == typeof(SByte)) {
					sbyte retval;
					if (sbyte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof(Int16)) {
					short retval;
					if (short.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof(Int32)) {
					int retval;
					if (int.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof(Int64)) {
					long retval;
					if (long.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof(Byte)) {
					byte retval;
					if (byte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof(UInt16)) {
					ushort retval;
					if (ushort.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof(UInt32)) {
					uint retval;
					if (uint.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof(UInt64)) {
					ulong retval;
					if (ulong.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof(Single)) {
					float retval;
					if (float.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof(Double)) {
					double retval;
					if (double.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof (Boolean))
				{
					bool outbool;
					if (bool.TryParse(valuestring, out outbool))
						return outbool;
				}
				if (nodeType == typeof(TimeSpan)) {
					TimeSpan retval;
					if (TimeSpan.TryParse(valuestring, CultureInfo.InvariantCulture, out retval))
						return retval;
				}
				if (nodeType == typeof (char))
				{
					char retval;
					if (char.TryParse(valuestring, out retval))
						return retval;
				}
				if (nodeType == typeof (string))
					return valuestring;
				if (nodeType == typeof (decimal))
				{
					decimal retval;
					if (decimal.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
						return retval;
				}

				else if (nodeType == typeof (Uri))
				{
					Uri retval;
					if (Uri.TryCreate(valuestring, UriKind.RelativeOrAbsolute, out retval))
						return retval;
				}
			}
			return value;
		}
	}
}