summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Xaml/TypeConversionExtensions.cs
blob: 15a66f5d820e722af78a431666d4442c0784864d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
//
// TypeConversionExtensions.cs
//
// Author:
//       Stephane Delcroix <stephane@mi8.be>
//
// Copyright (c) 2013 Mobile Inception
// Copyright (c) 2014 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace Xamarin.Forms.Xaml
{
	internal static class TypeConversionExtensions
	{
		internal static object ConvertTo(this object value, Type toType, Func<ParameterInfo> pinfoRetriever,
			IServiceProvider serviceProvider)
		{
			Func<TypeConverter> getConverter = () =>
			{
				ParameterInfo pInfo;
				if (pinfoRetriever == null || (pInfo = pinfoRetriever()) == null)
					return null;

				var converterTypeName = pInfo.CustomAttributes.GetTypeConverterTypeName();
				if (converterTypeName == null)
					return null;
				var convertertype = Type.GetType(converterTypeName);
				return (TypeConverter)Activator.CreateInstance(convertertype);
			};

			return ConvertTo(value, toType, getConverter, serviceProvider);
		}

		internal static object ConvertTo(this object value, Type toType, Func<MemberInfo> minfoRetriever,
			IServiceProvider serviceProvider)
		{
			Func<object> getConverter = () =>
			{
				MemberInfo memberInfo;

				var converterTypeName = toType.GetTypeInfo().CustomAttributes.GetTypeConverterTypeName();
				if (minfoRetriever != null && (memberInfo = minfoRetriever()) != null)
					converterTypeName = memberInfo.CustomAttributes.GetTypeConverterTypeName() ?? converterTypeName;
				if (converterTypeName == null)
					return null;

				var convertertype = Type.GetType(converterTypeName);
				return Activator.CreateInstance(convertertype);
			};

			return ConvertTo(value, toType, getConverter, serviceProvider);
		}

		static string GetTypeConverterTypeName(this IEnumerable<CustomAttributeData> attributes)
		{
			var converterAttribute =
				attributes.FirstOrDefault(cad => TypeConverterAttribute.TypeConvertersType.Contains(cad.AttributeType.FullName));
			if (converterAttribute == null)
				return null;
			if (converterAttribute.ConstructorArguments[0].ArgumentType == typeof (string))
				return (string)converterAttribute.ConstructorArguments[0].Value;
			if (converterAttribute.ConstructorArguments[0].ArgumentType == typeof (Type))
				return ((Type)converterAttribute.ConstructorArguments[0].Value).AssemblyQualifiedName;
			return null;
		}

		//Don't change the name or the signature of this, it's used by XamlC
		public static object ConvertTo(this object value, Type toType, Type convertertype, IServiceProvider serviceProvider)
		{
			if (convertertype == null)
				return value.ConvertTo(toType, (Func<object>)null, serviceProvider);
			Func<object> getConverter = () => Activator.CreateInstance(convertertype);
			;
			return value.ConvertTo(toType, getConverter, serviceProvider);
		}

		internal static object ConvertTo(this object value, Type toType, Func<object> getConverter,
			IServiceProvider serviceProvider)
		{
			if (value == null)
				return null;

			var str = value as string;
			if (str != null)
			{
				//If there's a [TypeConverter], use it
				object converter = getConverter?.Invoke();
				var xfTypeConverter = converter as TypeConverter;
				var xfExtendedTypeConverter = xfTypeConverter as IExtendedTypeConverter;
				if (xfExtendedTypeConverter != null)
					return value = xfExtendedTypeConverter.ConvertFromInvariantString(str, serviceProvider);
				if (xfTypeConverter != null)
					return value = xfTypeConverter.ConvertFromInvariantString(str);
				var converterType = converter?.GetType();
				if (converterType != null)
				{
					var convertFromStringInvariant = converterType.GetRuntimeMethod("ConvertFromInvariantString",
						new[] { typeof (string) });
					if (convertFromStringInvariant != null)
						return value = convertFromStringInvariant.Invoke(converter, new object[] { str });
				}

				//If the type is nullable, as the value is not null, it's safe to assume we want the built-in conversion
				if (toType.GetTypeInfo().IsGenericType && toType.GetGenericTypeDefinition() == typeof (Nullable<>))
					toType = Nullable.GetUnderlyingType(toType);

				//Obvious Built-in conversions
				if (toType.GetTypeInfo().IsEnum)
					return Enum.Parse(toType, str);
				if (toType == typeof(SByte))
					return SByte.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof(Int16))
					return Int16.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof(Int32))
					return Int32.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof(Int64))
					return Int64.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof(Byte))
					return Byte.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof(UInt16))
					return UInt16.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof(UInt32))
					return UInt32.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof(UInt64))
					return UInt64.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof (Single))
					return Single.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof (Double))
					return Double.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof (Boolean))
					return Boolean.Parse(str);
				if (toType == typeof (TimeSpan))
					return TimeSpan.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof (DateTime))
					return DateTime.Parse(str, CultureInfo.InvariantCulture);
				if (toType == typeof(Char)) {
					char c = '\0';
					Char.TryParse(str, out c);
					return c;
				}
				if (toType == typeof (String) && str.StartsWith("{}", StringComparison.Ordinal))
					return str.Substring(2);
				if (toType == typeof (String))
					return value;
				if (toType == typeof(Decimal))
					return Decimal.Parse(str, CultureInfo.InvariantCulture);
			}

			//if there's an implicit conversion, convert
			if (value != null) {
				MethodInfo opImplicit = null;
				foreach (var mi in value.GetType().GetRuntimeMethods()) {
					if (!mi.IsSpecialName) continue;
					if (mi.Name != "op_Implicit") continue;
					if (!mi.IsPublic) continue;
					if (mi.ReturnType != toType) continue;
					var parameters = mi.GetParameters();
					if (parameters.Length != 1) continue;
					if (parameters[0].ParameterType != value.GetType()) continue;
					opImplicit = mi;
					break;
				}
				if (opImplicit == null) {
					foreach (var mi in toType.GetRuntimeMethods()) {
						if (!mi.IsSpecialName) continue;
						if (mi.Name != "op_Implicit") continue;
						if (!mi.IsPublic) continue;
						if (mi.ReturnType != toType) continue;
						var parameters = mi.GetParameters();
						if (parameters.Length != 1) continue;
						if (parameters[0].ParameterType != value.GetType()) continue;
						opImplicit = mi;
						break;
					}
				}
				if (opImplicit != null) {
					value = opImplicit.Invoke(null, new[] { value });
					return value;
				}
			}

			var nativeValueConverterService = DependencyService.Get<INativeValueConverterService>();

			object nativeValue = null;
			if (nativeValueConverterService != null && nativeValueConverterService.ConvertTo(value, toType, out nativeValue))
				return nativeValue;

			return value;
		}
	}
}