2 * Copyright(c) 2022 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 element)
164 element.IsCreateByXaml = true;
165 element.LineNumber = node.LineNumber;
166 element.LinePosition = node.LinePosition;
170 catch (TargetInvocationException e)
172 if (e.InnerException is XamlParseException || e.InnerException is XmlException)
173 throw e.InnerException;
178 Values[node] = value;
180 var markup = value as IMarkupExtension;
181 if (markup != null && (value is TypeExtension || value is StaticExtension || value is ArrayExtension))
183 var serviceProvider = new XamlServiceProvider(node, Context);
185 var visitor = new ApplyPropertiesVisitor(Context);
186 foreach (var cnode in node.Properties.Values.ToList())
187 cnode.Accept(visitor, node);
188 foreach (var cnode in node.CollectionItems)
189 cnode.Accept(visitor, node);
191 value = markup.ProvideValue(serviceProvider);
194 if (!node.Properties.TryGetValue(XmlName.xKey, out xKey))
197 node.Properties.Clear();
198 node.CollectionItems.Clear();
201 node.Properties.Add(XmlName.xKey, xKey);
203 Values[node] = value;
206 if (value is BindableObject)
207 NameScope.SetNameScope(value as BindableObject, node.Namescope);
210 public void Visit(RootNode node, INode parentNode)
212 var rnode = (XamlLoader.RuntimeRootNode)node;
213 Values[node] = rnode.Root;
214 Context.Types[node] = rnode.Root.GetType();
215 var bindableRoot = rnode.Root as BindableObject;
216 if (bindableRoot != null)
217 NameScope.SetNameScope(bindableRoot, node.Namescope);
220 public void Visit(ListNode node, INode parentNode)
222 //this is a gross hack to keep ListNode alive. ListNode must go in favor of Properties
224 if (ApplyPropertiesVisitor.TryGetPropertyName(node, parentNode, out name))
228 bool ValidateCtorArguments(Type nodeType, IElementNode node, out string missingArgName)
230 missingArgName = null;
232 nodeType.GetTypeInfo()
233 .DeclaredConstructors.FirstOrDefault(
235 ci.GetParameters().Length != 0 && ci.IsPublic &&
236 ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute))));
237 if (ctorInfo == null)
239 foreach (var parameter in ctorInfo.GetParameters())
241 // Modify the namespace
243 parameter.CustomAttributes.First(ca => ca.AttributeType.FullName == "Tizen.NUI.Binding.ParameterAttribute")?
244 .ConstructorArguments.First()
246 if (!node.Properties.ContainsKey(new XmlName("", propname)))
248 missingArgName = propname;
256 public object CreateFromParameterizedConstructor(Type nodeType, IElementNode node)
259 nodeType.GetTypeInfo()
260 .DeclaredConstructors.FirstOrDefault(
262 ci.GetParameters().Length != 0 && ci.IsPublic &&
263 ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute))));
264 object[] arguments = CreateArgumentsArray(node, ctorInfo);
266 if (arguments != null)
268 return ctorInfo?.Invoke(arguments);
276 public object CreateFromFactory(Type nodeType, IElementNode node)
278 object[] arguments = CreateArgumentsArray(node);
280 if (!node.Properties.ContainsKey(XmlName.xFactoryMethod))
283 object ret = Activator.CreateInstance(nodeType, BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance | BindingFlags.OptionalParamBinding, null, arguments, CultureInfo.CurrentCulture);
284 if (ret is Element element)
286 element.IsCreateByXaml = true;
287 element.LineNumber = (node as ElementNode)?.LineNumber ?? -1;
288 element.LinePosition = (node as ElementNode)?.LinePosition ?? -1;
293 var factoryMethod = ((string)((ValueNode)node.Properties[XmlName.xFactoryMethod]).Value);
294 Type[] types = arguments == null ? System.Array.Empty<Type>() : arguments.Select(a => a.GetType()).ToArray();
295 Func<MethodInfo, bool> isMatch = m =>
297 if (m.Name != factoryMethod)
299 var p = m.GetParameters();
300 if (p.Length != types.Length)
304 for (var i = 0; i < p.Length; i++)
306 if ((p[i].ParameterType.IsAssignableFrom(types[i])))
308 var op_impl = p[i].ParameterType.GetImplicitConversionOperator(fromType: types[i], toType: p[i].ParameterType)
309 ?? types[i].GetImplicitConversionOperator(fromType: types[i], toType: p[i].ParameterType);
313 arguments[i] = op_impl.Invoke(null, new[] { arguments[i] });
317 var mi = nodeType.GetRuntimeMethods().FirstOrDefault(isMatch);
320 if (node is ElementNode elementNode)
322 var nodeTypeExtension = XamlParser.GetElementTypeExtension(node.XmlType, elementNode, Context.RootElement?.GetType().GetTypeInfo().Assembly);
323 mi = nodeTypeExtension?.GetRuntimeMethods().FirstOrDefault(isMatch);
329 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 element)
423 element.IsCreateByXaml = true;
424 element.LineNumber = (node as ElementNode)?.LineNumber ?? -1;
425 element.LinePosition = (node as ElementNode)?.LinePosition ?? -1;
429 if (node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode &&
430 ((ValueNode)node.CollectionItems[0]).Value is string)
432 var valuestring = ((ValueNode)node.CollectionItems[0]).Value as string;
434 if (nodeType == typeof(SByte))
437 if (sbyte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
440 if (nodeType == typeof(Int16))
442 return Convert.ToInt16(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring));
444 if (nodeType == typeof(Int32))
446 return Convert.ToInt32(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring));
448 if (nodeType == typeof(Int64))
450 return Convert.ToInt64(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring));
452 if (nodeType == typeof(Byte))
455 if (byte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
458 if (nodeType == typeof(UInt16))
460 return Convert.ToUInt16(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring));
462 if (nodeType == typeof(UInt32))
464 return Convert.ToUInt32(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring));
466 if (nodeType == typeof(UInt64))
468 return Convert.ToUInt64(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring));
470 if (nodeType == typeof(Single))
472 return GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring);
474 if (nodeType == typeof(Double))
476 return Convert.ToDouble(GraphicsTypeManager.Instance.ConvertScriptToPixel(valuestring));
478 if (nodeType == typeof(Boolean))
481 if (bool.TryParse(valuestring, out outbool))
484 if (nodeType == typeof(TimeSpan))
487 if (TimeSpan.TryParse(valuestring, CultureInfo.InvariantCulture, out retval))
490 if (nodeType == typeof(char))
493 if (char.TryParse(valuestring, out retval))
496 if (nodeType == typeof(string))
498 if (nodeType == typeof(decimal))
501 if (decimal.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval))
505 else if (nodeType == typeof(Uri))
508 if (Uri.TryCreate(valuestring, UriKind.RelativeOrAbsolute, out retval))