2 // Copyright (C) 2010 Novell Inc. http://novell.com
4 // Permission is hereby granted, free of charge, to any person obtaining
5 // a copy of this software and associated documentation files (the
6 // "Software"), to deal in the Software without restriction, including
7 // without limitation the rights to use, copy, modify, merge, publish,
8 // distribute, sublicense, and/or sell copies of the Software, and to
9 // permit persons to whom the Software is furnished to do so, subject to
10 // the following conditions:
12 // The above copyright notice and this permission notice shall be
13 // included in all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 using System.Collections.Generic;
25 using System.ComponentModel;
27 using System.Reflection;
28 using System.Windows.Markup;
29 using System.Xaml.Schema;
31 using Pair = System.Collections.Generic.KeyValuePair<string,string>;
35 // This type caches assembly attribute search results. To do this,
36 // it registers AssemblyLoaded event on CurrentDomain when it should
37 // reflect dynamic in-scope asemblies.
38 // It should be released at finalizer.
39 public class XamlSchemaContext
41 public XamlSchemaContext ()
46 public XamlSchemaContext (IEnumerable<Assembly> referenceAssemblies)
47 : this (referenceAssemblies, null)
51 public XamlSchemaContext (XamlSchemaContextSettings settings)
52 : this (null, settings)
56 public XamlSchemaContext (IEnumerable<Assembly> referenceAssemblies, XamlSchemaContextSettings settings)
58 if (referenceAssemblies != null)
59 reference_assemblies = new List<Assembly> (referenceAssemblies);
61 AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoaded;
66 FullyQualifyAssemblyNamesInClrNamespaces = settings.FullyQualifyAssemblyNamesInClrNamespaces;
67 SupportMarkupExtensionsWithDuplicateArity = settings.SupportMarkupExtensionsWithDuplicateArity;
72 if (reference_assemblies == null)
73 AppDomain.CurrentDomain.AssemblyLoad -= OnAssemblyLoaded;
76 IList<Assembly> reference_assemblies;
78 // assembly attribute caches
79 List<string> xaml_nss;
80 Dictionary<string,string> prefixes;
81 Dictionary<string,string> compat_nss;
82 Dictionary<string,List<XamlType>> all_xaml_types;
83 XamlType [] empty_xaml_types = new XamlType [0];
84 List<XamlType> run_time_types = new List<XamlType> ();
86 public bool FullyQualifyAssemblyNamesInClrNamespaces { get; private set; }
88 public IList<Assembly> ReferenceAssemblies {
89 get { return reference_assemblies; }
92 IEnumerable<Assembly> AssembliesInScope {
93 get { return reference_assemblies ?? AppDomain.CurrentDomain.GetAssemblies (); }
96 public bool SupportMarkupExtensionsWithDuplicateArity { get; private set; }
98 public virtual IEnumerable<string> GetAllXamlNamespaces ()
100 if (xaml_nss == null) {
101 xaml_nss = new List<string> ();
102 foreach (var ass in AssembliesInScope)
103 FillXamlNamespaces (ass);
108 public virtual ICollection<XamlType> GetAllXamlTypes (string xamlNamespace)
110 if (xamlNamespace == null)
111 throw new ArgumentNullException ("xamlNamespace");
112 if (all_xaml_types == null) {
113 all_xaml_types = new Dictionary<string,List<XamlType>> ();
114 foreach (var ass in AssembliesInScope)
115 FillAllXamlTypes (ass);
119 if (all_xaml_types.TryGetValue (xamlNamespace, out l))
122 return empty_xaml_types;
125 public virtual string GetPreferredPrefix (string xmlns)
128 throw new ArgumentNullException ("xmlns");
129 if (xmlns == XamlLanguage.Xaml2006Namespace)
131 if (prefixes == null) {
132 prefixes = new Dictionary<string,string> ();
133 foreach (var ass in AssembliesInScope)
137 return prefixes.TryGetValue (xmlns, out ret) ? ret : "p"; // default
140 protected internal XamlValueConverter<TConverterBase> GetValueConverter<TConverterBase> (Type converterType, XamlType targetType)
141 where TConverterBase : class
143 return new XamlValueConverter<TConverterBase> (converterType, targetType);
146 Dictionary<Pair,XamlDirective> xaml_directives = new Dictionary<Pair,XamlDirective> ();
148 public virtual XamlDirective GetXamlDirective (string xamlNamespace, string name)
151 var p = new Pair (xamlNamespace, name);
152 if (!xaml_directives.TryGetValue (p, out t)) {
153 t = new XamlDirective (xamlNamespace, name);
154 xaml_directives.Add (p, t);
159 public virtual XamlType GetXamlType (Type type)
161 XamlType xt = run_time_types.FirstOrDefault (t => t.UnderlyingType == type);
163 foreach (var ns in GetAllXamlNamespaces ())
164 if ((xt = GetAllXamlTypes (ns).FirstOrDefault (t => t.UnderlyingType == type)) != null)
167 xt = new XamlType (type, this);
168 run_time_types.Add (xt);
173 public XamlType GetXamlType (XamlTypeName xamlTypeName)
175 if (xamlTypeName == null)
176 throw new ArgumentNullException ("xamlTypeName");
178 var n = xamlTypeName;
179 if (n.TypeArguments.Count == 0) // non-generic
180 return GetXamlType (n.Namespace, n.Name);
183 XamlType [] typeArgs = new XamlType [n.TypeArguments.Count];
184 for (int i = 0; i < typeArgs.Length; i++)
185 typeArgs [i] = GetXamlType (n.TypeArguments [i]);
186 return GetXamlType (n.Namespace, n.Name, typeArgs);
189 protected internal virtual XamlType GetXamlType (string xamlNamespace, string name, params XamlType [] typeArguments)
192 if (TryGetCompatibleXamlNamespace (xamlNamespace, out dummy))
193 xamlNamespace = dummy;
196 if (xamlNamespace == XamlLanguage.Xaml2006Namespace) {
197 ret = XamlLanguage.SpecialNames.Find (name, xamlNamespace);
199 ret = XamlLanguage.AllTypes.FirstOrDefault (t => TypeMatches (t, xamlNamespace, name, typeArguments));
203 ret = run_time_types.FirstOrDefault (t => TypeMatches (t, xamlNamespace, name, typeArguments));
205 ret = GetAllXamlTypes (xamlNamespace).FirstOrDefault (t => TypeMatches (t, xamlNamespace, name, typeArguments));
207 if (reference_assemblies == null) {
208 var type = ResolveXamlTypeName (xamlNamespace, name, typeArguments);
210 ret = GetXamlType (type);
213 // If the type was not found, it just returns null.
217 bool TypeMatches (XamlType t, string ns, string name, XamlType [] typeArgs)
219 if (t.PreferredXamlNamespace == ns && t.Name == name && t.TypeArguments.ListEquals (typeArgs))
221 if (t.IsMarkupExtension)
222 return t.PreferredXamlNamespace == ns && t.Name.Substring (0, t.Name.Length - 9) == name && t.TypeArguments.ListEquals (typeArgs);
227 protected internal virtual Assembly OnAssemblyResolve (string assemblyName)
229 return Assembly.LoadWithPartialName (assemblyName);
232 public virtual bool TryGetCompatibleXamlNamespace (string xamlNamespace, out string compatibleNamespace)
234 if (xamlNamespace == null)
235 throw new ArgumentNullException ("xamlNamespace");
236 if (compat_nss == null) {
237 compat_nss = new Dictionary<string,string> ();
238 foreach (var ass in AssembliesInScope)
239 FillCompatibilities (ass);
241 return compat_nss.TryGetValue (xamlNamespace, out compatibleNamespace);
244 void OnAssemblyLoaded (object o, AssemblyLoadEventArgs e)
246 if (reference_assemblies != null)
247 return; // do nothing
249 if (xaml_nss != null)
250 FillXamlNamespaces (e.LoadedAssembly);
251 if (prefixes != null)
252 FillPrefixes (e.LoadedAssembly);
253 if (compat_nss != null)
254 FillCompatibilities (e.LoadedAssembly);
255 if (all_xaml_types != null)
256 FillAllXamlTypes (e.LoadedAssembly);
259 // cache updater methods
260 void FillXamlNamespaces (Assembly ass)
262 foreach (XmlnsDefinitionAttribute xda in ass.GetCustomAttributes (typeof (XmlnsDefinitionAttribute), false))
263 xaml_nss.Add (xda.XmlNamespace);
266 void FillPrefixes (Assembly ass)
268 foreach (XmlnsPrefixAttribute xpa in ass.GetCustomAttributes (typeof (XmlnsPrefixAttribute), false))
269 prefixes.Add (xpa.XmlNamespace, xpa.Prefix);
272 void FillCompatibilities (Assembly ass)
274 foreach (XmlnsCompatibleWithAttribute xca in ass.GetCustomAttributes (typeof (XmlnsCompatibleWithAttribute), false))
275 compat_nss.Add (xca.OldNamespace, xca.NewNamespace);
278 void FillAllXamlTypes (Assembly ass)
280 foreach (XmlnsDefinitionAttribute xda in ass.GetCustomAttributes (typeof (XmlnsDefinitionAttribute), false)) {
281 var l = new List<XamlType> ();
282 all_xaml_types.Add (xda.XmlNamespace, l);
283 foreach (var t in ass.GetTypes ())
284 if (t.Namespace == xda.ClrNamespace)
285 l.Add (GetXamlType (t));
289 // XamlTypeName -> Type resolution
291 static readonly int clr_ns_len = "clr-namespace:".Length;
292 static readonly int clr_ass_len = "assembly=".Length;
294 Type ResolveXamlTypeName (string xmlNamespace, string xmlLocalName, IList<XamlType> typeArguments)
296 string ns = xmlNamespace;
297 string name = xmlLocalName;
299 if (ns == XamlLanguage.Xaml2006Namespace) {
300 var xt = XamlLanguage.SpecialNames.Find (name, ns);
302 xt = XamlLanguage.AllTypes.FirstOrDefault (t => t.Name == xmlLocalName);
304 throw new FormatException (string.Format ("There is no type '{0}' in XAML namespace", name));
305 return xt.UnderlyingType;
307 else if (!ns.StartsWith ("clr-namespace:", StringComparison.Ordinal))
310 Type [] genArgs = null;
311 if (typeArguments != null && typeArguments.Count > 0) {
312 var xtns = typeArguments;
313 genArgs = (from t in typeArguments select t.UnderlyingType).ToArray ();
314 if (genArgs.Any (t => t == null))
318 // convert xml namespace to clr namespace and assembly
319 string [] split = ns.Split (';');
320 if (split.Length != 2 || split [0].Length < clr_ns_len || split [1].Length <= clr_ass_len)
321 throw new XamlParseException (string.Format ("Cannot resolve runtime namespace from XML namespace '{0}'", ns));
322 string tns = split [0].Substring (clr_ns_len);
323 string aname = split [1].Substring (clr_ass_len);
325 string taqn = GetTypeName (tns, name, genArgs);
326 var ass = OnAssemblyResolve (aname);
327 // MarkupExtension type could omit "Extension" part in XML name.
328 Type ret = ass == null ? null : ass.GetType (taqn) ?? ass.GetType (GetTypeName (tns, name + "Extension", genArgs));
330 throw new XamlParseException (string.Format ("Cannot resolve runtime type from XML namespace '{0}', local name '{1}' with {2} type arguments ({3})", ns, name, typeArguments !=null ? typeArguments.Count : 0, taqn));
331 return genArgs == null ? ret : ret.MakeGenericType (genArgs);
334 static string GetTypeName (string tns, string name, Type [] genArgs)
336 string tfn = tns.Length > 0 ? tns + '.' + name : name;
338 tfn += "`" + genArgs.Length;