Merge remote branch 'upstream/master'
[mono.git] / mcs / class / System.Xaml / System.Xaml / TypeExtensionMethods.cs
1 //
2 // Copyright (C) 2010 Novell Inc. http://novell.com
3 //
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:
11 // 
12 // The above copyright notice and this permission notice shall be
13 // included in all copies or substantial portions of the Software.
14 // 
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.
22 //
23 using System;
24 using System.Collections;
25 using System.Collections.Generic;
26 using System.ComponentModel;
27 using System.Globalization;
28 using System.Linq;
29 using System.Reflection;
30 using System.Windows.Markup;
31 using System.Xaml.Schema;
32
33 namespace System.Xaml
34 {
35         static class TypeExtensionMethods
36         {
37                 #region inheritance search and custom attribute provision
38
39                 public static T GetCustomAttribute<T> (this ICustomAttributeProvider type, bool inherit) where T : Attribute
40                 {
41                         foreach (var a in type.GetCustomAttributes (typeof (T), inherit))
42                                 return (T) (object) a;
43                         return null;
44                 }
45
46                 public static T GetCustomAttribute<T> (this XamlType type) where T : Attribute
47                 {
48                         if (type.UnderlyingType == null)
49                                 return null;
50
51                         T ret = type.GetCustomAttributeProvider ().GetCustomAttribute<T> (true);
52                         if (ret != null)
53                                 return ret;
54                         if (type.BaseType != null)
55                                 return type.BaseType.GetCustomAttribute<T> ();
56                         return null;
57                 }
58
59                 public static bool ImplementsAnyInterfacesOf (this Type type, params Type [] definitions)
60                 {
61                         return definitions.Any (t => ImplementsInterface (type, t));
62                 }
63
64                 public static bool ImplementsInterface (this Type type, Type definition)
65                 {
66                         if (type == null)
67                                 throw new ArgumentNullException ("type");
68                         if (definition == null)
69                                 throw new ArgumentNullException ("definition");
70                         if (type == definition)
71                                 return true;
72
73                         foreach (var iface in type.GetInterfaces ())
74                                 if (iface == definition || (iface.IsGenericType && iface.GetGenericTypeDefinition () == definition))
75                                         return true;
76                         return false;
77                 }
78                 
79                 #endregion
80                 
81                 #region type conversion and member value retrieval
82                 
83                 static readonly NullExtension null_value = new NullExtension ();
84
85                 public static object GetExtensionWrapped (object o)
86                 {
87                         // FIXME: should this manually checked, or is there any way to automate it?
88                         // Also XamlSchemaContext might be involved but this method signature does not take it consideration.
89                         if (o == null)
90                                 return null_value;
91                         if (o is Array)
92                                 return new ArrayExtension ((Array) o);
93                         if (o is Type)
94                                 return new TypeExtension ((Type) o);
95                         return o;
96                 }
97                 
98                 public static string GetStringValue (XamlType xt, XamlMember xm, object obj, IValueSerializerContext vsctx)
99                 {
100                         if (obj == null)
101                                 return String.Empty;
102                         if (obj is Type)
103                                 return new XamlTypeName (xt.SchemaContext.GetXamlType ((Type) obj)).ToString (vsctx != null ? vsctx.GetService (typeof (INamespacePrefixLookup)) as INamespacePrefixLookup : null);
104
105                         var vs = (xm != null ? xm.ValueSerializer : null) ?? xt.ValueSerializer;
106                         if (vs != null)
107                                 return vs.ConverterInstance.ConvertToString (obj, vsctx);
108
109                         // FIXME: does this make sense?
110                         var vc = (xm != null ? xm.TypeConverter : null) ?? xt.TypeConverter;
111                         var tc = vc != null ? vc.ConverterInstance : null;
112                         if (tc != null && typeof (string) != null && tc.CanConvertTo (vsctx, typeof (string)))
113                                 return (string) tc.ConvertTo (vsctx, CultureInfo.InvariantCulture, obj, typeof (string));
114                         if (obj is string || obj == null)
115                                 return (string) obj;
116                         throw new InvalidCastException (String.Format ("Cannot cast object '{0}' to string", obj.GetType ()));
117                 }
118                 
119                 public static TypeConverter GetTypeConverter (this Type type)
120                 {
121 #if MOONLIGHT
122                         if (typeof (IConvertible).IsAssignableFrom (type))
123                                 return (TypeConverter) Activator.CreateInstance (typeof (ConvertibleTypeConverter<>).MakeGenericType (new Type [] {type}));
124                         var name = type.GetCustomAttribute<TypeConverterAttribute> (true).ConverterTypeName;
125                         return (TypeConverter) Activator.CreateInstance (type.Assembly.GetType (name) ?? Type.GetType (name));
126 #else
127                         return TypeDescriptor.GetConverter (type);
128 #endif
129                 }
130                 
131                 // FIXME: I want this to cover all the existing types and make it valid in both NET_2_1 and !NET_2_1.
132                 class ConvertibleTypeConverter<T> : TypeConverter
133                 {
134                         Type type;
135                         public ConvertibleTypeConverter ()
136                         {
137                                 this.type = typeof (T);
138                         }
139                         public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
140                         {
141                                 return sourceType == typeof (string);
142                         }
143                         public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
144                         {
145                                 return destinationType == typeof (string);
146                         }
147                         public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
148                         {
149                                 if (type == typeof (DateTime))
150                                         return System.Xml.XmlConvert.ToDateTime ((string) value, System.Xml.XmlDateTimeSerializationMode.Unspecified);
151                                 return ((IConvertible) value).ToType (type, CultureInfo.InvariantCulture);
152                         }
153                         public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
154                         {
155                                 if (value is DateTime)
156                                         return System.Xml.XmlConvert.ToString ((DateTime) value);
157                                 return ((IConvertible) value).ToType (destinationType, CultureInfo.InvariantCulture);
158                         }
159                 }
160
161                 #endregion
162
163                 public static bool IsContentValue (this XamlMember member, IValueSerializerContext vsctx)
164                 {
165                         if (member == XamlLanguage.Initialization)
166                                 return true;
167                         if (member == XamlLanguage.PositionalParameters || member == XamlLanguage.Arguments)
168                                 return false; // it's up to the argument (no need to check them though, as IList<object> is not of value)
169                         if (member.TypeConverter != null && member.TypeConverter.ConverterInstance != null && member.TypeConverter.ConverterInstance.CanConvertTo (vsctx, typeof (string)))
170                                 return true;
171                         return IsContentValue (member.Type,vsctx);
172                 }
173
174                 public static bool IsContentValue (this XamlType type, IValueSerializerContext vsctx)
175                 {
176                         if (type.TypeConverter != null && type.TypeConverter.ConverterInstance != null && type.TypeConverter.ConverterInstance.CanConvertTo (vsctx, typeof (string)))
177                                 return true;
178                         return false;
179                 }
180
181                 public static bool ListEquals (this IList<XamlType> a1, IList<XamlType> a2)
182                 {
183                         if (a1 == null || a1.Count == 0)
184                                 return a2 == null || a2.Count == 0;
185                         if (a2 == null || a2.Count == 0)
186                                 return false;
187                         if (a1.Count != a2.Count)
188                                 return false;
189                         for (int i = 0; i < a1.Count; i++)
190                                 if (a1 [i] != a2 [i])
191                                         return false;
192                         return true;
193                 }
194
195                 public static bool HasPositionalParameters (this XamlType type, IValueSerializerContext vsctx)
196                 {
197                         // FIXME: find out why only TypeExtension and StaticExtension yield this directive. Seealso XamlObjectReaderTest.Read_CustomMarkupExtension*()
198                         return  type == XamlLanguage.Type ||
199                                 type == XamlLanguage.Static ||
200                                 ExaminePositionalParametersApplicable (type, vsctx) && type.ConstructionRequiresArguments;
201                 }
202                 
203                 static bool ExaminePositionalParametersApplicable (this XamlType type, IValueSerializerContext vsctx)
204                 {
205                         if (!type.IsMarkupExtension || type.UnderlyingType == null)
206                                 return false;
207
208                         var args = type.GetSortedConstructorArguments ();
209                         if (args == null)
210                                 return false;
211
212                         foreach (var arg in args)
213                                 if (arg.Type != null && !arg.Type.IsContentValue (vsctx))
214                                         return false;
215
216                         Type [] argTypes = (from arg in args select arg.Type.UnderlyingType).ToArray ();
217                         if (argTypes.Any (at => at == null))
218                                 return false;
219                         var ci = type.UnderlyingType.GetConstructor (argTypes);
220                         return ci != null;
221                 }
222                 
223                 public static IEnumerable<XamlMember> GetConstructorArguments (this XamlType type)
224                 {
225                         return type.GetAllMembers ().Where (m => m.UnderlyingMember != null && m.GetCustomAttributeProvider ().GetCustomAttribute<ConstructorArgumentAttribute> (false) != null);
226                 }
227
228                 public static IEnumerable<XamlMember> GetSortedConstructorArguments (this XamlType type)
229                 {
230                         var args = type.GetConstructorArguments ().ToArray ();
231                         foreach (var ci in type.UnderlyingType.GetConstructors ().Where (c => c.GetParameters ().Length == args.Length)) {
232                                 var pis = ci.GetParameters ();
233                                 if (args.Length != pis.Length)
234                                         continue;
235                                 bool mismatch = false;
236                                 foreach (var pi in pis)
237                                 for (int i = 0; i < args.Length; i++)
238                                         if (!args.Any (a => a.ConstructorArgumentName () == pi.Name))
239                                                 mismatch = true;
240                                 if (mismatch)
241                                         continue;
242                                 return args.OrderBy (c => pis.FindParameterWithName (c.ConstructorArgumentName ()).Position);
243                         }
244                         return null;
245                 }
246
247                 static ParameterInfo FindParameterWithName (this IEnumerable<ParameterInfo> pis, string name)
248                 {
249                         return pis.FirstOrDefault (pi => pi.Name == name);
250                 }
251
252                 public static string ConstructorArgumentName (this XamlMember xm)
253                 {
254                         var caa = xm.GetCustomAttributeProvider ().GetCustomAttribute<ConstructorArgumentAttribute> (false);
255                         return caa.ArgumentName;
256                 }
257                 
258
259                 internal static int CompareMembers (XamlMember m1, XamlMember m2)
260                 {
261                         // ConstructorArguments and PositionalParameters go first.
262                         if (m1 == XamlLanguage.PositionalParameters)
263                                 return -1;
264                         if (m2 == XamlLanguage.PositionalParameters)
265                                 return 1;
266                         if (m1.IsConstructorArgument ()) {
267                                 if (!m2.IsConstructorArgument ())
268                                         return -1;
269                         }
270                         else if (m2.IsConstructorArgument ())
271                                 return 1;
272
273                         // ContentProperty is returned at last.
274                         if (m1.DeclaringType != null && m1.DeclaringType.ContentProperty == m1)
275                                 return 1;
276                         if (m2.DeclaringType != null && m2.DeclaringType.ContentProperty == m2)
277                                 return -1;
278
279                         // then, compare names.
280                         return String.CompareOrdinal (m1.Name, m2.Name);
281                 }
282
283                 internal static bool IsConstructorArgument (this XamlMember xm)
284                 {
285                         var ap = xm.GetCustomAttributeProvider ();
286                         return ap != null && ap.GetCustomAttributes (typeof (ConstructorArgumentAttribute), false).Length > 0;
287                 }
288
289                 internal static string GetInternalXmlName (this XamlMember xm)
290                 {
291                         return xm.IsAttachable ? String.Concat (xm.DeclaringType.GetInternalXmlName (), ".", xm.Name) : xm.Name;
292                 }
293
294 #if DOTNET
295                 internal static ICustomAttributeProvider GetCustomAttributeProvider (this XamlType type)
296                 {
297                         return type.UnderlyingType;
298                 }
299                 
300                 internal static ICustomAttributeProvider GetCustomAttributeProvider (this XamlMember member)
301                 {
302                         return member.UnderlyingMember;
303                 }
304 #endif
305         }
306 }