2 * Copyright(c) 2021 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 using System.Collections.Generic;
20 using System.Globalization;
22 using System.Reflection;
24 using Tizen.NUI.Binding.Internals;
25 using Tizen.NUI.Binding;
28 namespace Tizen.NUI.Xaml
30 internal class CreateValuesVisitor : IXamlNodeVisitor
32 public CreateValuesVisitor(HydrationContext context)
37 Dictionary<INode, object> Values
39 get { return Context.Values; }
42 HydrationContext Context { get; }
44 public TreeVisitingMode VisitingMode => TreeVisitingMode.BottomUp;
45 public bool StopOnDataTemplate => true;
46 public bool StopOnResourceDictionary => false;
47 public bool VisitNodeOnDataTemplate => false;
48 public bool SkipChildren(INode node, INode parentNode) => false;
49 public bool IsResourceDictionary(ElementNode node) => typeof(ResourceDictionary).IsAssignableFrom(Context.Types[node]);
51 public void Visit(ValueNode node, INode parentNode)
53 Values[node] = node.Value;
56 public void Visit(MarkupNode node, INode parentNode)
60 public void Visit(ElementNode node, INode parentNode)
64 XamlParseException xpe;
65 var type = XamlParser.GetElementType(node.XmlType, node, Context.RootElement?.GetType().GetTypeInfo().Assembly,
68 throw new ArgumentNullException(null, "type should not be null");
72 Context.Types[node] = type;
74 if (IsXaml2009LanguagePrimitive(node))
75 value = CreateLanguagePrimitive(type, node);
76 else if (node.Properties.ContainsKey(XmlName.xArguments) || node.Properties.ContainsKey(XmlName.xFactoryMethod))
77 value = CreateFromFactory(type, node);
80 .DeclaredConstructors.Any(
82 ci.IsPublic && ci.GetParameters().Length != 0 &&
83 ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute)))) &&
84 ValidateCtorArguments(type, node, out ctorargname))
85 value = CreateFromParameterizedConstructor(type, node);
86 else if (!type.GetTypeInfo().DeclaredConstructors.Any(ci => ci.IsPublic && ci.GetParameters().Length == 0) &&
87 !ValidateCtorArguments(type, node, out ctorargname))
89 throw new XamlParseException($"The Property {ctorargname} is required to create a {type?.FullName} object.", node);
93 //this is a trick as the DataTemplate parameterless ctor is internal, and we can't CreateInstance(..., false) on WP7
96 if (type == typeof(DataTemplate))
97 value = new DataTemplate();
98 if (type == typeof(ControlTemplate))
99 value = new ControlTemplate();
100 if (value == null && node.CollectionItems.Any() && node.CollectionItems.First() is ValueNode)
102 var serviceProvider = new XamlServiceProvider(node, Context);
103 var converted = ((ValueNode)node.CollectionItems.First()).Value.ConvertTo(type, () => type.GetTypeInfo(),
105 if (converted != null && converted.GetType() == type)
110 if (type.GetTypeInfo().DeclaredConstructors.Any(ci => ci.IsPublic && ci.GetParameters().Length == 0))
112 //default constructor
113 value = Activator.CreateInstance(type);
117 ConstructorInfo constructorInfo = null;
119 //constructor with all default parameters
120 foreach (var constructor in type.GetConstructors())
122 if (!constructor.IsStatic)
124 bool areAllParamsDefault = true;
126 foreach (var param in constructor.GetParameters())
128 if (!param.HasDefaultValue)
130 areAllParamsDefault = false;
135 if (areAllParamsDefault)
137 if (null == constructorInfo)
139 constructorInfo = constructor;
143 throw new XamlParseException($"{type.FullName} has more than one constructor which params are all default.", node);
149 if (null == constructorInfo)
151 throw new XamlParseException($"{type.FullName} has no constructor which params are all default.", node);
154 List<object> defaultParams = new List<object>();
155 foreach (var param in constructorInfo.GetParameters())
157 defaultParams.Add(param.DefaultValue);
160 value = Activator.CreateInstance(type, defaultParams.ToArray());
162 if (value is Element)
164 if (null != Application.Current)
166 Application.AddResourceChangedCallback(value, (value as Element).OnResourcesChanged);
169 if (value is BindableObject)
171 ((BindableObject)value).IsCreateByXaml = true;
176 catch (TargetInvocationException e)
178 if (e.InnerException is XamlParseException || e.InnerException is XmlException)
179 throw e.InnerException;
184 Values[node] = value;
186 var markup = value as IMarkupExtension;
187 if (markup != null && (value is TypeExtension || value is StaticExtension || value is ArrayExtension))
189 var serviceProvider = new XamlServiceProvider(node, Context);
191 var visitor = new ApplyPropertiesVisitor(Context);
192 foreach (var cnode in node.Properties.Values.ToList())
193 cnode.Accept(visitor, node);
194 foreach (var cnode in node.CollectionItems)
195 cnode.Accept(visitor, node);
197 value = markup.ProvideValue(serviceProvider);
200 if (!node.Properties.TryGetValue(XmlName.xKey, out xKey))
203 node.Properties.Clear();
204 node.CollectionItems.Clear();
207 node.Properties.Add(XmlName.xKey, xKey);
209 Values[node] = value;
212 if (value is BindableObject)
213 NameScope.SetNameScope(value as BindableObject, node.Namescope);
216 public void Visit(RootNode node, INode parentNode)
218 var rnode = (XamlLoader.RuntimeRootNode)node;
219 Values[node] = rnode.Root;
220 Context.Types[node] = rnode.Root.GetType();
221 var bindableRoot = rnode.Root as BindableObject;
222 if (bindableRoot != null)
223 NameScope.SetNameScope(bindableRoot, node.Namescope);
226 public void Visit(ListNode node, INode parentNode)
228 //this is a gross hack to keep ListNode alive. ListNode must go in favor of Properties
230 if (ApplyPropertiesVisitor.TryGetPropertyName(node, parentNode, out name))
234 bool ValidateCtorArguments(Type nodeType, IElementNode node, out string missingArgName)
236 missingArgName = null;
238 nodeType.GetTypeInfo()
239 .DeclaredConstructors.FirstOrDefault(
241 ci.GetParameters().Length != 0 && ci.IsPublic &&
242 ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute))));
243 if (ctorInfo == null)
245 foreach (var parameter in ctorInfo.GetParameters())
247 // Modify the namespace
249 parameter.CustomAttributes.First(ca => ca.AttributeType.FullName == "Tizen.NUI.Binding.ParameterAttribute")?
250 .ConstructorArguments.First()
252 if (!node.Properties.ContainsKey(new XmlName("", propname)))
254 missingArgName = propname;
262 public object CreateFromParameterizedConstructor(Type nodeType, IElementNode node)
265 nodeType.GetTypeInfo()
266 .DeclaredConstructors.FirstOrDefault(
268 ci.GetParameters().Length != 0 && ci.IsPublic &&
269 ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute))));
270 object[] arguments = CreateArgumentsArray(node, ctorInfo);
272 if (arguments != null)
274 return ctorInfo?.Invoke(arguments);
282 public object CreateFromFactory(Type nodeType, IElementNode node)
284 object[] arguments = CreateArgumentsArray(node);
286 if (!node.Properties.ContainsKey(XmlName.xFactoryMethod))
289 object ret = Activator.CreateInstance(nodeType, BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance | BindingFlags.OptionalParamBinding, null, arguments, CultureInfo.CurrentCulture);
292 if (null != Application.Current)
294 Application.AddResourceChangedCallback(ret, (ret as Element).OnResourcesChanged);
297 if (ret is BindableObject)
299 ((BindableObject)ret).IsCreateByXaml = true;
305 var factoryMethod = ((string)((ValueNode)node.Properties[XmlName.xFactoryMethod]).Value);
306 Type[] types = arguments == null ? System.Array.Empty<Type>() : arguments.Select(a => a.GetType()).ToArray();
307 Func<MethodInfo, bool> isMatch = m =>
309 if (m.Name != factoryMethod)
311 var p = m.GetParameters();
312 if (p.Length != types.Length)
316 for (var i = 0; i < p.Length; i++)
318 if ((p[i].ParameterType.IsAssignableFrom(types[i])))
320 var op_impl = p[i].ParameterType.GetImplicitConversionOperator(fromType: types[i], toType: p[i].ParameterType)
321 ?? types[i].GetImplicitConversionOperator(fromType: types[i], toType: p[i].ParameterType);
325 arguments[i] = op_impl.Invoke(null, new[] { arguments[i] });
329 var mi = nodeType.GetRuntimeMethods().FirstOrDefault(isMatch);
331 throw new MissingMemberException($"No static method found for {nodeType.FullName}::{factoryMethod} ({string.Join(", ", types.Select(t => t.FullName))})");
332 return mi.Invoke(null, arguments);
335 public object[] CreateArgumentsArray(IElementNode enode)
337 if (!enode.Properties.ContainsKey(XmlName.xArguments))
339 var node = enode.Properties[XmlName.xArguments];
340 var elementNode = node as ElementNode;
341 if (elementNode != null)
343 var array = new object[1];
344 array[0] = Values[elementNode];
346 if (array[0].GetType().IsClass)
348 elementNode.Accept(new ApplyPropertiesVisitor(Context, true), null);
354 var listnode = node as ListNode;
355 if (listnode != null)
357 var array = new object[listnode.CollectionItems.Count];
358 for (var i = 0; i < listnode.CollectionItems.Count; i++)
359 array[i] = Values[(ElementNode)listnode.CollectionItems[i]];
365 public object[] CreateArgumentsArray(IElementNode enode, ConstructorInfo ctorInfo)
367 if (ctorInfo != null)
369 var n = ctorInfo.GetParameters().Length;
370 var array = new object[n];
371 for (var i = 0; i < n; i++)
373 var parameter = ctorInfo.GetParameters()[i];
375 parameter?.CustomAttributes?.First(attr => attr.AttributeType == typeof(ParameterAttribute))?
376 .ConstructorArguments.First()
378 var name = new XmlName("", propname);
380 if (!enode.Properties.TryGetValue(name, out node))
383 if (propname != null)
385 msg = String.Format("The Property {0} is required to create a {1} object.", propname, ctorInfo.DeclaringType.FullName);
389 msg = "propname is null.";
391 throw new XamlParseException(msg, enode as IXmlLineInfo);
393 if (!enode.SkipProperties.Contains(name))
394 enode.SkipProperties.Add(name);
395 var value = Context.Values[node];
396 var serviceProvider = new XamlServiceProvider(enode, Context);
397 var convertedValue = value?.ConvertTo(parameter?.ParameterType, () => parameter, serviceProvider);
398 array[i] = convertedValue;
406 static bool IsXaml2009LanguagePrimitive(IElementNode node)
408 return node.NamespaceURI == XamlParser.X2009Uri;
411 static object CreateLanguagePrimitive(Type nodeType, IElementNode node)
414 if (nodeType == typeof(string))
415 value = String.Empty;
416 else if (nodeType == typeof(Uri))
420 value = Activator.CreateInstance(nodeType);
421 if (value is Element)
423 if (null != Application.Current)
425 Application.AddResourceChangedCallback(value, (value as Element).OnResourcesChanged);
428 if (value is BindableObject)
430 ((BindableObject)value).IsCreateByXaml = true;
435 if (node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode &&
436 ((ValueNode)node.CollectionItems[0]).Value is string)
438 var valuestring = ((ValueNode)node.CollectionItems[0]).Value as string;
440 if (nodeType == typeof(SByte))
443 if (sbyte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
446 if (nodeType == typeof(Int16))
449 if (short.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
452 if (nodeType == typeof(Int32))
455 if (int.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
458 if (nodeType == typeof(Int64))
461 if (long.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
464 if (nodeType == typeof(Byte))
467 if (byte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
470 if (nodeType == typeof(UInt16))
473 if (ushort.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
476 if (nodeType == typeof(UInt32))
479 if (uint.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
482 if (nodeType == typeof(UInt64))
485 if (ulong.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
488 if (nodeType == typeof(Single))
491 if (float.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
494 if (nodeType == typeof(Double))
497 if (double.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
500 if (nodeType == typeof(Boolean))
503 if (bool.TryParse(valuestring, out outbool))
506 if (nodeType == typeof(TimeSpan))
509 if (TimeSpan.TryParse(valuestring, CultureInfo.InvariantCulture, out retval))
512 if (nodeType == typeof(char))
515 if (char.TryParse(valuestring, out retval))
518 if (nodeType == typeof(string))
520 if (nodeType == typeof(decimal))
523 if (decimal.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
527 else if (nodeType == typeof(Uri))
530 if (Uri.TryCreate(valuestring, UriKind.RelativeOrAbsolute, out retval))