-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ColorTypeConverter.cs
78 lines (67 loc) · 2.47 KB
/
ColorTypeConverter.cs
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
using System;
using System.Collections.Generic;
using Microsoft.Maui.Controls.Build.Tasks;
using Microsoft.Maui.Controls.Xaml;
using Microsoft.Maui.Graphics;
using Mono.Cecil.Cil;
namespace Microsoft.Maui.Controls.XamlC
{
class ColorTypeConverter : ICompiledTypeConverter
{
public virtual IEnumerable<Instruction> ConvertFromString(string value, ILContext context, BaseNode node)
{
var module = context.Body.Method.Module;
do
{
if (string.IsNullOrEmpty(value))
break;
value = value.Trim();
if (value.StartsWith("#", StringComparison.Ordinal))
{
var color = Color.FromArgb(value);
yield return Instruction.Create(OpCodes.Ldc_R4, color.Red);
yield return Instruction.Create(OpCodes.Ldc_R4, color.Green);
yield return Instruction.Create(OpCodes.Ldc_R4, color.Blue);
yield return Instruction.Create(OpCodes.Ldc_R4, color.Alpha);
yield return Instruction.Create(OpCodes.Newobj, module.ImportCtorReference(context.Cache, ("Microsoft.Maui.Graphics", "Microsoft.Maui.Graphics", "Color"), parameterTypes: new[] {
("mscorlib", "System", "Single"),
("mscorlib", "System", "Single"),
("mscorlib", "System", "Single"),
("mscorlib", "System", "Single")}));
yield break;
}
var parts = value.Split('.');
if (parts.Length == 1 || (parts.Length == 2 && parts[0] == "Color"))
{
var color = parts[parts.Length - 1];
if (color == "lightgrey")
color = "lightgray";
if (color == "Default")
{
yield return Instruction.Create(OpCodes.Ldnull);
yield break;
}
var fieldReference = module.ImportFieldReference(context.Cache, ("Microsoft.Maui.Graphics", "Microsoft.Maui.Graphics", "Colors"),
color,
isStatic: true,
caseSensitive: false);
if (fieldReference != null)
{
yield return Instruction.Create(OpCodes.Ldsfld, fieldReference);
yield break;
}
var propertyGetterReference = module.ImportPropertyGetterReference(context.Cache, ("Microsoft.Maui.Graphics", "Microsoft.Maui.Graphics", "Colors"),
color,
isStatic: true,
caseSensitive: false);
if (propertyGetterReference != null)
{
yield return Instruction.Create(OpCodes.Call, propertyGetterReference);
yield break;
}
}
} while (false);
throw new BuildException(BuildExceptionCode.Conversion, node, null, value, typeof(Color));
}
}
}