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.
21 // Stephane Delcroix <stephane@mi8.be>
23 // Copyright (c) 2013 Mobile Inception
24 // Copyright (c) 2013-2014 Xamarin, Inc
26 // Permission is hereby granted, free of charge, to any person obtaining a copy
27 // of this software and associated documentation files (the "Software"), to deal
28 // in the Software without restriction, including without limitation the rights
29 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30 // copies of the Software, and to permit persons to whom the Software is
31 // furnished to do so, subject to the following conditions:
33 // The above copyright notice and this permission notice shall be included in
34 // all copies or substantial portions of the Software.
36 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45 using System.Collections.Generic;
46 using System.Diagnostics;
48 using System.Reflection;
50 using Tizen.NUI.Binding;
51 using Tizen.NUI.BaseComponents;
52 using Tizen.NUI.Binding.Internals;
54 namespace Tizen.NUI.Xaml
56 internal static class XamlParser
58 public const string XFUri = "http://tizen.org/Tizen.NUI/2018/XAML";
59 public const string NUI2018Uri = "http://tizen.org/Tizen.NUI/2018/XAML";
60 public const string X2006Uri = "http://schemas.microsoft.com/winfx/2006/xaml";
61 public const string X2009Uri = "http://schemas.microsoft.com/winfx/2009/xaml";
62 public const string McUri = "http://schemas.openxmlformats.org/markup-compatibility/2006";
64 public static void ParseXaml(RootNode rootNode, XmlReader reader)
66 IList<KeyValuePair<string, string>> xmlns;
67 var attributes = ParseXamlAttributes(reader, out xmlns);
68 var prefixes = PrefixesToIgnore(xmlns);
69 (rootNode.IgnorablePrefixes ?? (rootNode.IgnorablePrefixes = new List<string>())).AddRange(prefixes);
70 rootNode.Properties.AddRange(attributes);
71 ParseXamlElementFor(rootNode, reader);
74 static void ParseXamlElementFor(IElementNode node, XmlReader reader)
76 Debug.Assert(reader.NodeType == XmlNodeType.Element);
78 var elementName = reader.Name;
79 var isEmpty = reader.IsEmptyElement;
86 switch (reader.NodeType)
88 case XmlNodeType.EndElement:
89 Debug.Assert(reader.Name == elementName); //make sure we close the right element
91 case XmlNodeType.Element:
92 // 1. Property Element.
93 if (reader.Name.Contains("."))
96 if (reader.Name.StartsWith(elementName + ".", StringComparison.Ordinal))
97 name = new XmlName(reader.NamespaceURI, reader.Name.Substring(elementName.Length + 1));
99 name = new XmlName(reader.NamespaceURI, reader.LocalName);
101 var prop = ReadNode(reader);
103 node.Properties.Add(name, prop);
105 // 2. Xaml2009 primitives, x:Arguments, ...
106 else if (reader.NamespaceURI == X2009Uri && reader.LocalName == "Arguments")
108 var prop = ReadNode(reader);
110 node.Properties.Add(XmlName.xArguments, prop);
112 // 3. DataTemplate (should be handled by 4.)
113 else if ((node.XmlType.NamespaceUri == XFUri || node.XmlType.NamespaceUri == NUI2018Uri) &&
114 (node.XmlType.Name == "DataTemplate" || node.XmlType.Name == "ControlTemplate"))
116 var prop = ReadNode(reader, true);
118 node.Properties.Add(XmlName._CreateContent, prop);
120 // 4. Implicit content, implicit collection, or collection syntax. Add to CollectionItems, resolve case later.
123 var item = ReadNode(reader, true);
125 node.CollectionItems.Add(item);
128 case XmlNodeType.Whitespace:
130 case XmlNodeType.Text:
131 case XmlNodeType.CDATA:
132 if (node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode)
133 ((ValueNode)node.CollectionItems[0]).Value += reader.Value.Trim();
135 node.CollectionItems.Add(new ValueNode(reader.Value.Trim(), (IXmlNamespaceResolver)reader));
138 Debug.WriteLine("Unhandled node {0} {1} {2}", reader.NodeType, reader.Name, reader.Value);
144 static INode ReadNode(XmlReader reader, bool nested = false)
146 var skipFirstRead = nested;
147 Debug.Assert(reader.NodeType == XmlNodeType.Element);
148 var name = reader.Name;
149 List<INode> nodes = new List<INode>();
152 while (skipFirstRead || reader.Read())
154 skipFirstRead = false;
156 switch (reader.NodeType)
158 case XmlNodeType.EndElement:
159 Debug.Assert(reader.Name == name);
160 if (nodes.Count == 0) //Empty element
162 if (nodes.Count == 1)
164 return new ListNode(nodes, (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber,
165 ((IXmlLineInfo)reader).LinePosition);
166 case XmlNodeType.Element:
167 var isEmpty = reader.IsEmptyElement && reader.Name == name;
168 var elementName = reader.Name;
169 var elementNsUri = reader.NamespaceURI;
170 var elementXmlInfo = (IXmlLineInfo)reader;
171 IList<KeyValuePair<string, string>> xmlns;
173 var attributes = ParseXamlAttributes(reader, out xmlns);
174 var prefixes = PrefixesToIgnore(xmlns);
176 IList<XmlType> typeArguments = null;
177 if (attributes.Any(kvp => kvp.Key == XmlName.xTypeArguments))
180 ((ValueNode)attributes.First(kvp => kvp.Key == XmlName.xTypeArguments).Value).Value as IList<XmlType>;
183 node = new ElementNode(new XmlType(elementNsUri, elementName, typeArguments), elementNsUri,
184 reader as IXmlNamespaceResolver, elementXmlInfo.LineNumber, elementXmlInfo.LinePosition);
185 ((IElementNode)node).Properties.AddRange(attributes);
186 (node.IgnorablePrefixes ?? (node.IgnorablePrefixes = new List<string>()))?.AddRange(prefixes);
188 ParseXamlElementFor((IElementNode)node, reader);
190 if (isEmpty || nested)
193 case XmlNodeType.Text:
194 node = new ValueNode(reader.Value.Trim(), (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber,
195 ((IXmlLineInfo)reader).LinePosition);
198 case XmlNodeType.Whitespace:
201 Debug.WriteLine("Unhandled node {0} {1} {2}", reader.NodeType, reader.Name, reader.Value);
205 throw new XamlParseException("Closing PropertyElement expected", (IXmlLineInfo)reader);
208 static IList<KeyValuePair<XmlName, INode>> ParseXamlAttributes(XmlReader reader, out IList<KeyValuePair<string, string>> xmlns)
210 Debug.Assert(reader.NodeType == XmlNodeType.Element);
211 var attributes = new List<KeyValuePair<XmlName, INode>>();
212 xmlns = new List<KeyValuePair<string, string>>();
213 for (var i = 0; i < reader.AttributeCount; i++)
215 reader.MoveToAttribute(i);
218 if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
220 xmlns.Add(new KeyValuePair<string, string>(reader.LocalName, reader.Value));
224 var namespaceUri = reader.NamespaceURI;
225 if (reader.LocalName.Contains(".") && string.IsNullOrEmpty(namespaceUri))
226 namespaceUri = ((IXmlNamespaceResolver)reader).LookupNamespace("");
227 var propertyName = new XmlName(namespaceUri, reader.LocalName);
229 object value = reader.Value;
231 if (reader.NamespaceURI == X2006Uri)
236 propertyName = XmlName.xKey;
239 propertyName = XmlName.xName;
242 case "x:FieldModifier":
245 Debug.WriteLine("Unhandled attribute {0}", reader.Name);
250 if (reader.NamespaceURI == X2009Uri)
255 propertyName = XmlName.xKey;
258 propertyName = XmlName.xName;
260 case "x:TypeArguments":
261 propertyName = XmlName.xTypeArguments;
262 value = TypeArgumentsParser.ParseExpression((string)value, (IXmlNamespaceResolver)reader, (IXmlLineInfo)reader);
265 propertyName = XmlName.xDataType;
268 case "x:FieldModifier":
270 case "x:FactoryMethod":
271 propertyName = XmlName.xFactoryMethod;
274 propertyName = XmlName.xArguments;
277 Debug.WriteLine("Unhandled attribute {0}", reader.Name);
282 var propertyNode = GetValueNode(value, reader);
283 attributes.Add(new KeyValuePair<XmlName, INode>(propertyName, propertyNode));
285 reader.MoveToElement();
289 static IList<string> PrefixesToIgnore(IList<KeyValuePair<string, string>> xmlns)
291 var prefixes = new List<string>();
292 foreach (var kvp in xmlns)
294 var prefix = kvp.Key;
296 string typeName = null, ns = null, asm = null;
297 XmlnsHelper.ParseXmlns(kvp.Value, out typeName, out ns, out asm);
302 static IValueNode GetValueNode(object value, XmlReader reader)
304 var valueString = value as string;
305 if (valueString != null && valueString.Trim().StartsWith("{}", StringComparison.Ordinal))
307 return new ValueNode(valueString.Substring(2), (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber,
308 ((IXmlLineInfo)reader).LinePosition);
310 if (valueString != null && valueString.Trim().StartsWith("{", StringComparison.Ordinal))
312 return new MarkupNode(valueString.Trim(), reader as IXmlNamespaceResolver, ((IXmlLineInfo)reader).LineNumber,
313 ((IXmlLineInfo)reader).LinePosition);
315 return new ValueNode(value, (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber,
316 ((IXmlLineInfo)reader).LinePosition);
319 static IList<XmlnsDefinitionAttribute> s_xmlnsDefinitions;
320 public static IList<Assembly> s_assemblies = new List<Assembly>();// = new Assembly[]{};
322 static void GatherXmlnsDefinitionAttributes(Assembly currentAssembly)
324 //this could be extended to look for [XmlnsDefinition] in all assemblies
325 // var assemblies = new [] {
326 // typeof(View).GetTypeInfo().Assembly,
327 // //typeof(XamlLoader).GetTypeInfo().Assembly,
329 // s_assemblies = new Assembly[]{typeof(View).GetTypeInfo().Assembly};
330 if (null == currentAssembly)
332 s_assemblies.Add(typeof(View).GetTypeInfo().Assembly);
336 s_assemblies.Add(currentAssembly);
338 var assemblies = currentAssembly?.GetReferencedAssemblies();
340 if (null != assemblies)
342 foreach (var assembly in assemblies)
346 s_assemblies.Add(Assembly.Load(assembly));
350 Tizen.Log.Fatal("NUI", "Load referenced assemblies e.Message: " + e.Message);
351 Console.WriteLine("\n[FATAL] Load referenced assemblies e.Message: {0}\n", e.Message);
352 throw new XamlParseException(e.Message);
358 s_xmlnsDefinitions = new List<XmlnsDefinitionAttribute>();
360 foreach (var assembly in s_assemblies)
361 foreach (XmlnsDefinitionAttribute attribute in assembly.GetCustomAttributes(typeof(XmlnsDefinitionAttribute)))
363 s_xmlnsDefinitions.Add(attribute);
364 attribute.AssemblyName = attribute.AssemblyName ?? assembly.FullName;
368 public static Type GetElementType(XmlType xmlType, IXmlLineInfo xmlInfo, Assembly currentAssembly,
369 out XamlParseException exception)
371 if (s_xmlnsDefinitions == null)
372 GatherXmlnsDefinitionAttributes(currentAssembly);
374 var namespaceURI = xmlType.NamespaceUri;
375 var elementName = xmlType.Name;
376 var typeArguments = xmlType.TypeArguments;
379 if (elementName.Contains("-"))
381 elementName = elementName.Replace('-', '+');
384 var lookupAssemblies = new List<XmlnsDefinitionAttribute>();
385 var lookupNames = new List<string>();
387 foreach (var xmlnsDef in s_xmlnsDefinitions)
389 if (xmlnsDef.XmlNamespace != namespaceURI)
391 lookupAssemblies.Add(xmlnsDef);
394 if (lookupAssemblies.Count == 0)
396 string ns, asmstring, _;
397 XmlnsHelper.ParseXmlns(namespaceURI, out _, out ns, out asmstring);
398 lookupAssemblies.Add(new XmlnsDefinitionAttribute(namespaceURI, ns)
400 AssemblyName = asmstring ?? currentAssembly.FullName
404 lookupNames.Add(elementName);
405 lookupNames.Add(elementName + "Extension");
407 for (var i = 0; i < lookupNames.Count; i++)
409 var name = lookupNames[i];
410 if (name.Contains(":"))
411 name = name.Substring(name.LastIndexOf(':') + 1);
412 if (typeArguments != null)
413 name += "`" + typeArguments.Count; //this will return an open generic Type
414 lookupNames[i] = name;
418 foreach (var asm in lookupAssemblies)
420 foreach (var name in lookupNames)
422 if ((type = Type.GetType($"{asm.ClrNamespace}.{name}, {asm.AssemblyName}")) != null)
425 if ('?' == name.Last())
427 string nameOfNotNull = name.Substring(0, name.Length - 1);
428 Type typeofNotNull = Type.GetType($"{asm.ClrNamespace}.{nameOfNotNull}, {asm.AssemblyName}");
430 if (null != typeofNotNull)
432 type = typeof(Nullable<>).MakeGenericType(new Type[] { typeofNotNull });
442 if (type != null && typeArguments != null)
444 XamlParseException innerexception = null;
445 var args = typeArguments.Select(delegate (XmlType xmltype)
447 XamlParseException xpe;
448 var t = GetElementType(xmltype, xmlInfo, currentAssembly, out xpe);
451 innerexception = xpe;
456 if (innerexception != null)
458 exception = innerexception;
461 type = type.MakeGenericType(args);
466 var message = $"Type {elementName} not found in xmlns {namespaceURI}\n";
467 message += "\n - Make sure the all used assemblies (e.g. Tizen.NUI.Components) are included in the application project.";
468 message += "\n - Make sure the type and namespace are correct.\n";
469 exception = new XamlParseException($"message", xmlInfo);