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;
25 using System.Collections.Generic;
26 using System.ComponentModel;
28 using System.Reflection;
29 using System.Windows.Markup;
30 using System.Xaml.Schema;
34 public class XamlType : IEquatable<XamlType>
36 public XamlType (Type underlyingType, XamlSchemaContext schemaContext)
37 : this (underlyingType, schemaContext, null)
41 static readonly Type [] predefined_types = {
42 typeof (XData), typeof (Uri), typeof (TimeSpan), typeof (PropertyDefinition), typeof (MemberDefinition), typeof (Reference)
45 public XamlType (Type underlyingType, XamlSchemaContext schemaContext, XamlTypeInvoker invoker)
46 : this (schemaContext, invoker)
48 if (underlyingType == null)
49 throw new ArgumentNullException ("underlyingType");
50 type = underlyingType;
51 underlying_type = type;
54 if (XamlLanguage.InitializingTypes) {
55 Name = type.GetXamlName ();
56 PreferredXamlNamespace = XamlLanguage.Xaml2006Namespace;
57 } else if ((xt = XamlLanguage.AllTypes.FirstOrDefault (t => t.UnderlyingType == type)) != null) {
59 PreferredXamlNamespace = XamlLanguage.Xaml2006Namespace;
61 Name = type.GetXamlName ();
62 PreferredXamlNamespace = String.Format ("clr-namespace:{0};assembly={1}", type.Namespace, type.Assembly.GetName ().Name);
66 public XamlType (string unknownTypeNamespace, string unknownTypeName, IList<XamlType> typeArguments, XamlSchemaContext schemaContext)
67 : this (schemaContext, null)
69 if (unknownTypeNamespace == null)
70 throw new ArgumentNullException ("unknownTypeNamespace");
71 if (unknownTypeName == null)
72 throw new ArgumentNullException ("unknownTypeName");
73 if (schemaContext == null)
74 throw new ArgumentNullException ("schemaContext");
76 type = typeof (object);
77 Name = unknownTypeName;
78 PreferredXamlNamespace = unknownTypeNamespace;
79 TypeArguments = typeArguments != null && typeArguments.Count == 0 ? null : typeArguments;
80 explicit_ns = unknownTypeNamespace;
83 protected XamlType (string typeName, IList<XamlType> typeArguments, XamlSchemaContext schemaContext)
84 : this (String.Empty, typeName, typeArguments, schemaContext)
88 XamlType (XamlSchemaContext schemaContext, XamlTypeInvoker invoker)
90 if (schemaContext == null)
91 throw new ArgumentNullException ("schemaContext");
92 SchemaContext = schemaContext;
93 this.invoker = invoker ?? new XamlTypeInvoker (this);
96 Type type, underlying_type;
100 // populated properties
102 XamlTypeInvoker invoker;
104 internal EventHandler<XamlSetMarkupExtensionEventArgs> SetMarkupExtensionHandler {
105 get { return LookupSetMarkupExtensionHandler (); }
108 internal EventHandler<XamlSetTypeConverterEventArgs> SetTypeConverterHandler {
109 get { return LookupSetTypeConverterHandler (); }
112 public IList<XamlType> AllowedContentTypes {
113 get { return LookupAllowedContentTypes (); }
116 public XamlType BaseType {
117 get { return LookupBaseType (); }
120 public bool ConstructionRequiresArguments {
121 get { return LookupConstructionRequiresArguments (); }
124 public XamlMember ContentProperty {
125 get { return LookupContentProperty (); }
128 public IList<XamlType> ContentWrappers {
129 get { return LookupContentWrappers (); }
132 public XamlValueConverter<XamlDeferringLoader> DeferringLoader {
133 get { return LookupDeferringLoader (); }
136 public XamlTypeInvoker Invoker {
137 get { return LookupInvoker (); }
140 public bool IsAmbient {
141 get { return LookupIsAmbient (); }
144 public bool IsArray {
145 get { return LookupCollectionKind () == XamlCollectionKind.Array; }
148 // it somehow treats array as not a collection...
149 public bool IsCollection {
150 get { return LookupCollectionKind () == XamlCollectionKind.Collection; }
153 public bool IsConstructible {
154 get { return LookupIsConstructible (); }
157 public bool IsDictionary {
158 get { return LookupCollectionKind () == XamlCollectionKind.Dictionary; }
161 public bool IsGeneric {
162 get { return type.IsGenericType; }
165 public bool IsMarkupExtension {
166 get { return LookupIsMarkupExtension (); }
168 public bool IsNameScope {
169 get { return LookupIsNameScope (); }
171 public bool IsNameValid {
172 get { return XamlLanguage.IsValidXamlName (Name); }
175 public bool IsNullable {
176 get { return LookupIsNullable (); }
179 public bool IsPublic {
180 get { return LookupIsPublic (); }
183 public bool IsUnknown {
184 get { return LookupIsUnknown (); }
187 public bool IsUsableDuringInitialization {
188 get { return LookupUsableDuringInitialization (); }
191 public bool IsWhitespaceSignificantCollection {
192 get { return LookupIsWhitespaceSignificantCollection (); }
195 public bool IsXData {
196 get { return LookupIsXData (); }
199 public XamlType ItemType {
200 get { return LookupItemType (); }
203 public XamlType KeyType {
204 get { return LookupKeyType (); }
207 public XamlType MarkupExtensionReturnType {
208 get { return LookupMarkupExtensionReturnType (); }
211 public string Name { get; private set; }
213 public string PreferredXamlNamespace { get; private set; }
215 public XamlSchemaContext SchemaContext { get; private set; }
217 public bool TrimSurroundingWhitespace {
218 get { return LookupTrimSurroundingWhitespace (); }
221 public IList<XamlType> TypeArguments { get; private set; }
223 public XamlValueConverter<TypeConverter> TypeConverter {
224 get { return LookupTypeConverter (); }
227 public Type UnderlyingType {
228 get { return LookupUnderlyingType (); }
231 public XamlValueConverter<ValueSerializer> ValueSerializer {
232 get { return LookupValueSerializer (); }
235 public static bool operator == (XamlType left, XamlType right)
237 return IsNull (left) ? IsNull (right) : left.Equals (right);
240 static bool IsNull (XamlType a)
242 return Object.ReferenceEquals (a, null);
245 public static bool operator != (XamlType left, XamlType right)
247 return !(left == right);
250 public bool Equals (XamlType other)
252 return !IsNull (other) &&
253 UnderlyingType == other.UnderlyingType &&
254 Name == other.Name &&
255 PreferredXamlNamespace == other.PreferredXamlNamespace && TypeArguments.ListEquals (other.TypeArguments);
258 public override bool Equals (object obj)
260 var a = obj as XamlType;
264 public override int GetHashCode ()
266 if (UnderlyingType != null)
267 return UnderlyingType.GetHashCode ();
268 int x = Name.GetHashCode () << 7 + PreferredXamlNamespace.GetHashCode ();
269 if (TypeArguments != null)
270 foreach (var t in TypeArguments)
271 x = t.GetHashCode () + x << 5;
275 public override string ToString ()
277 return String.IsNullOrEmpty (PreferredXamlNamespace) ? Name : String.Concat ("{", PreferredXamlNamespace, "}", Name);
280 public virtual bool CanAssignTo (XamlType xamlType)
282 throw new NotImplementedException ();
285 public XamlMember GetAliasedProperty (XamlDirective directive)
287 return LookupAliasedProperty (directive);
290 public ICollection<XamlMember> GetAllAttachableMembers ()
292 return new List<XamlMember> (LookupAllAttachableMembers ());
295 public ICollection<XamlMember> GetAllMembers ()
297 return new List<XamlMember> (LookupAllMembers ());
300 public XamlMember GetAttachableMember (string name)
302 return LookupAttachableMember (name);
305 public XamlMember GetMember (string name)
307 return LookupMember (name, false);
310 public IList<XamlType> GetPositionalParameters (int parameterCount)
312 return LookupPositionalParameters (parameterCount);
315 public virtual IList<string> GetXamlNamespaces ()
317 throw new NotImplementedException ();
318 /* this does not work like documented!
319 if (explicit_ns != null)
320 return new string [] {explicit_ns};
321 var l = SchemaContext.GetAllXamlNamespaces ();
323 return new List<string> (l);
324 return new string [] {String.Empty};
330 protected virtual XamlMember LookupAliasedProperty (XamlDirective directive)
332 if (directive == XamlLanguage.Key) {
333 var a = this.GetCustomAttribute<DictionaryKeyPropertyAttribute> ();
334 return a != null ? GetMember (a.Name) : null;
336 if (directive == XamlLanguage.Name) {
337 var a = this.GetCustomAttribute<RuntimeNamePropertyAttribute> ();
338 return a != null ? GetMember (a.Name) : null;
340 if (directive == XamlLanguage.Uid) {
341 var a = this.GetCustomAttribute<UidPropertyAttribute> ();
342 return a != null ? GetMember (a.Name) : null;
344 if (directive == XamlLanguage.Lang) {
345 var a = this.GetCustomAttribute<XmlLangPropertyAttribute> ();
346 return a != null ? GetMember (a.Name) : null;
351 protected virtual IEnumerable<XamlMember> LookupAllAttachableMembers ()
353 if (UnderlyingType == null)
354 return BaseType != null ? BaseType.GetAllMembers () : null;
355 return DoLookupAllAttachableMembers ();
358 IEnumerable<XamlMember> DoLookupAllAttachableMembers ()
360 yield break; // FIXME: what to return here?
363 protected virtual IEnumerable<XamlMember> LookupAllMembers ()
365 if (UnderlyingType == null)
366 return BaseType != null ? BaseType.GetAllMembers () : null;
367 if (all_members_cache == null)
368 all_members_cache = new List<XamlMember> (DoLookupAllMembers ());
369 return all_members_cache;
372 List<XamlMember> all_members_cache;
374 IEnumerable<XamlMember> DoLookupAllMembers ()
376 foreach (var pi in UnderlyingType.GetProperties ())
377 if (pi.CanRead && pi.CanWrite)
378 yield return new XamlMember (pi, SchemaContext);
381 protected virtual IList<XamlType> LookupAllowedContentTypes ()
383 // the actual implementation is very different from what is documented :(
387 var l = new List<XamlType> ();
388 if (ContentWrappers != null)
389 l.AddRange (ContentWrappers);
390 if (ContentProperty != null)
391 l.Add (ContentProperty.Type);
392 if (ItemType != null)
394 return l.Count > 0 ? l : null;
398 protected virtual XamlMember LookupAttachableMember (string name)
400 throw new NotImplementedException ();
404 protected virtual XamlType LookupBaseType ()
406 if (base_type == null) {
407 if (UnderlyingType == null)
408 // FIXME: probably something advanced is needed here.
409 base_type = new XamlType (typeof (object), SchemaContext, Invoker);
411 base_type = type.BaseType == null || type.BaseType == typeof (object) ? null : new XamlType (type.BaseType, SchemaContext, Invoker);
416 // This implementation is not verified. (No place to use.)
417 protected virtual XamlCollectionKind LookupCollectionKind ()
419 if (UnderlyingType == null)
420 return BaseType != null ? BaseType.LookupCollectionKind () : XamlCollectionKind.None;
422 return XamlCollectionKind.Array;
424 if (type.ImplementsAnyInterfacesOf (typeof (IDictionary), typeof (IDictionary<,>)))
425 return XamlCollectionKind.Dictionary;
427 if (type.ImplementsAnyInterfacesOf (typeof (ICollection), typeof (ICollection<>)))
428 return XamlCollectionKind.Collection;
430 return XamlCollectionKind.None;
433 protected virtual bool LookupConstructionRequiresArguments ()
435 if (UnderlyingType == null)
438 // not sure if it is required, but MemberDefinition return true while they are abstract and it makes no sense.
439 if (UnderlyingType.IsAbstract)
442 // FIXME: probably some primitive types are treated as special.
443 switch (Type.GetTypeCode (UnderlyingType)) {
444 case TypeCode.String:
446 case TypeCode.Object:
447 if (UnderlyingType == typeof (TimeSpan))
454 return UnderlyingType.GetConstructor (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null) == null;
457 protected virtual XamlMember LookupContentProperty ()
459 var a = this.GetCustomAttribute<ContentPropertyAttribute> ();
460 return a != null && a.Name != null ? GetMember (a.Name) : null;
463 protected virtual IList<XamlType> LookupContentWrappers ()
465 if (CustomAttributeProvider == null)
468 var arr = CustomAttributeProvider.GetCustomAttributes (typeof (ContentWrapperAttribute), false);
469 if (arr == null || arr.Length == 0)
471 var l = new XamlType [arr.Length];
472 for (int i = 0; i < l.Length; i++)
473 l [i] = SchemaContext.GetXamlType (((ContentWrapperAttribute) arr [i]).ContentWrapper);
477 internal ICustomAttributeProvider CustomAttributeProvider {
478 get { return LookupCustomAttributeProvider (); }
481 protected virtual ICustomAttributeProvider LookupCustomAttributeProvider ()
483 return UnderlyingType;
485 protected virtual XamlValueConverter<XamlDeferringLoader> LookupDeferringLoader ()
487 throw new NotImplementedException ();
490 protected virtual XamlTypeInvoker LookupInvoker ()
495 protected virtual bool LookupIsAmbient ()
497 return this.GetCustomAttribute<AmbientAttribute> () != null;
500 // It is documented as if it were to reflect spec. section 5.2,
501 // but the actual behavior shows it is *totally* wrong.
502 // Here I have implemented this based on the nunit test results. sigh.
503 protected virtual bool LookupIsConstructible ()
505 if (UnderlyingType == null)
507 if (IsMarkupExtension)
509 if (UnderlyingType.IsAbstract)
516 protected virtual bool LookupIsMarkupExtension ()
518 return typeof (MarkupExtension).IsAssignableFrom (UnderlyingType);
521 protected virtual bool LookupIsNameScope ()
523 return typeof (INameScope).IsAssignableFrom (UnderlyingType);
526 protected virtual bool LookupIsNullable ()
528 return !type.IsValueType || type.ImplementsInterface (typeof (Nullable<>));
531 protected virtual bool LookupIsPublic ()
533 return underlying_type == null || underlying_type.IsPublic || underlying_type.IsNestedPublic;
536 protected virtual bool LookupIsUnknown ()
538 return UnderlyingType == null;
541 protected virtual bool LookupIsWhitespaceSignificantCollection ()
543 // probably for unknown types, it should preserve whitespaces.
544 return IsUnknown || this.GetCustomAttribute<WhitespaceSignificantCollectionAttribute> () != null;
547 protected virtual bool LookupIsXData ()
549 // huh? XamlLanguage.XData.IsXData returns false(!)
550 // return typeof (XData).IsAssignableFrom (UnderlyingType);
554 protected virtual XamlType LookupItemType ()
557 return new XamlType (type.GetElementType (), SchemaContext);
561 return new XamlType (typeof (object), SchemaContext);
562 return new XamlType (type.GetGenericArguments () [0], SchemaContext);
565 protected virtual XamlType LookupKeyType ()
570 return new XamlType (typeof (object), SchemaContext);
571 return new XamlType (type.GetGenericArguments () [0], SchemaContext);
574 protected virtual XamlType LookupMarkupExtensionReturnType ()
576 var a = this.GetCustomAttribute<MarkupExtensionReturnTypeAttribute> ();
577 return a != null ? new XamlType (a.ReturnType, SchemaContext) : null;
580 protected virtual XamlMember LookupMember (string name, bool skipReadOnlyCheck)
582 var pi = UnderlyingType.GetProperty (name);
583 if (pi != null && (skipReadOnlyCheck || pi.CanWrite))
584 return new XamlMember (pi, SchemaContext);
585 var ei = UnderlyingType.GetEvent (name);
587 return new XamlMember (ei, SchemaContext);
591 protected virtual IList<XamlType> LookupPositionalParameters (int parameterCount)
593 throw new NotImplementedException ();
596 BindingFlags flags_get_static = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
598 protected virtual EventHandler<XamlSetMarkupExtensionEventArgs> LookupSetMarkupExtensionHandler ()
600 var a = this.GetCustomAttribute<XamlSetMarkupExtensionAttribute> ();
603 var mi = type.GetMethod (a.XamlSetMarkupExtensionHandler, flags_get_static);
605 throw new ArgumentException ("Binding to XamlSetMarkupExtensionHandler failed");
606 return (EventHandler<XamlSetMarkupExtensionEventArgs>) Delegate.CreateDelegate (typeof (EventHandler<XamlSetMarkupExtensionEventArgs>), mi);
609 protected virtual EventHandler<XamlSetTypeConverterEventArgs> LookupSetTypeConverterHandler ()
611 var a = this.GetCustomAttribute<XamlSetTypeConverterAttribute> ();
614 var mi = type.GetMethod (a.XamlSetTypeConverterHandler, flags_get_static);
616 throw new ArgumentException ("Binding to XamlSetTypeConverterHandler failed");
617 return (EventHandler<XamlSetTypeConverterEventArgs>) Delegate.CreateDelegate (typeof (EventHandler<XamlSetTypeConverterEventArgs>), mi);
620 protected virtual bool LookupTrimSurroundingWhitespace ()
622 return this.GetCustomAttribute<TrimSurroundingWhitespaceAttribute> () != null;
625 protected virtual XamlValueConverter<TypeConverter> LookupTypeConverter ()
627 var t = UnderlyingType;
631 var a = CustomAttributeProvider.GetCustomAttribute<TypeConverterAttribute> (false);
633 return SchemaContext.GetValueConverter<TypeConverter> (Type.GetType (a.ConverterTypeName), this);
635 if (t == typeof (object))
636 return SchemaContext.GetValueConverter<TypeConverter> (typeof (TypeConverter), this);
637 // equivalent to TypeExtension.
638 // FIXME: not sure if it should be specially handled here.
639 if (t == typeof (Type))
640 return SchemaContext.GetValueConverter<TypeConverter> (typeof (TypeExtensionConverter), this);
642 // It's still not decent to check CollectionConverter.
643 var tct = TypeDescriptor.GetConverter (t).GetType ();
644 if (tct != typeof (TypeConverter) && tct != typeof (CollectionConverter))
645 return SchemaContext.GetValueConverter<TypeConverter> (tct, this);
649 protected virtual Type LookupUnderlyingType ()
651 return underlying_type;
654 protected virtual bool LookupUsableDuringInitialization ()
656 var a = this.GetCustomAttribute<UsableDuringInitializationAttribute> ();
657 return a != null && a.Usable;
660 static XamlValueConverter<ValueSerializer> string_value_serializer;
662 protected virtual XamlValueConverter<ValueSerializer> LookupValueSerializer ()
664 return LookupValueSerializer (this, CustomAttributeProvider);
667 internal static XamlValueConverter<ValueSerializer> LookupValueSerializer (XamlType targetType, ICustomAttributeProvider provider)
669 if (provider == null)
672 var a = provider.GetCustomAttribute<ValueSerializerAttribute> (true);
674 return new XamlValueConverter<ValueSerializer> (a.ValueSerializerType ?? Type.GetType (a.ValueSerializerTypeName), targetType);
676 if (targetType.BaseType != null) {
677 var ret = targetType.BaseType.LookupValueSerializer ();
682 if (targetType.UnderlyingType == typeof (string)) {
683 if (string_value_serializer == null)
684 string_value_serializer = new XamlValueConverter<ValueSerializer> (typeof (StringValueSerializer), targetType);
685 return string_value_serializer;