-
Notifications
You must be signed in to change notification settings - Fork 1
/
NoesisCsBindingsGenerator.cs
314 lines (269 loc) · 11.5 KB
/
NoesisCsBindingsGenerator.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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.Xml;
public class NoesisCsBindingsGenerator {
public class NoesisGeneratedAttribute :Attribute { }
public static void GenerateCsFile(string filename) {
var generator = new NoesisCsBindingsGenerator {
XamlAsset = AssetDatabase.LoadAssetAtPath<NoesisXaml>(filename.Replace(".xaml", ".asset")),
XamlText = File.ReadAllText(filename)
};
generator.SaveFile();
}
public NoesisXaml XamlAsset { get; set; }
public string XamlText { get; set; }
private static readonly Regex NameRegex = new Regex("x:Name=\"([\\w\\d_]+)\""); // x:Name="MyElementNameHere"
private static readonly Regex XmlnsRegex = new Regex("xmlns:([\\w\\d_]+)=\"clr-namespace:([^;\"]+)(?:;.*)?\""); // xmlns:designerui="clr-namespace:Assets.UI.Views.DesignerUI"
private static readonly Regex XamlCodeBehindRegex = new Regex("x:Class=\"(.+)\""); // x:Class="Assets.UI.Views.DesignerUI.CircleButton"
private const string DummyAttribute = "[UnityEngine.HideInInspector]";
private void SaveFile() {
if (HasExistingUserImplemention())
return;
var file = GetCsFileName();
var csText = GetCsText();
if (csText == null) {
if (File.Exists(file))
File.Delete(file);
return;
}
if (AssetDatabase.LoadAssetAtPath<TextAsset>(file) != null) {
var oldFile = File.ReadAllText(file);
if (oldFile == csText)
return;
}
File.WriteAllText(file, csText);
AssetDatabase.ImportAsset(file);
}
private string GetCsText() {
var namespaceString = GetNamespaceString();
var className = GetClassNameString();
var hasCodeBehind = className != null && namespaceString != null;
if (hasCodeBehind == false)
return null;
var inheritsClassName = GetBaseClassName();
var includedNamespaces = GetXamlIncludedNamespaces().ToArray();
var events = GetEvents().ToArray();
var elements = GetNamedElements()
.Select(p=>new XamlElement {
Name = p.Name,
Type = ReplaceXamlNamespace(p.Type, includedNamespaces)
})
.ToArray();
var hasNamedElements = elements.Any();
var hasEvents = events.Any();
var stringBuilder = new System.Text.StringBuilder();
stringBuilder.AppendLine("/* This file has been generated automatically. All user changes will be overwritten if the XAML is changed. */");
stringBuilder.AppendLine("using Noesis;");
stringBuilder.AppendLine();
stringBuilder.Append("namespace ").Append(namespaceString).AppendLine(" {");
stringBuilder.AppendLine("\t" + DummyAttribute);
stringBuilder.Append("\tpublic partial class ").Append(className).Append(" : ").Append(inheritsClassName).AppendLine(" {");
{
if (hasNamedElements)
stringBuilder.AppendLine();
foreach (var item in elements)
stringBuilder
.Append("\t\tinternal ")
.Append(item.Type)
.Append(" ")
.Append(item.Name)
.AppendLine(";");
stringBuilder.AppendLine();
stringBuilder.AppendLine("\t\tprivate void InitializeComponent() {");
stringBuilder.Append("\t\t\tGUI.LoadComponent(this, \"").Append(XamlAsset.source).AppendLine("\");");
if(hasNamedElements)
stringBuilder.AppendLine();
foreach (var item in elements) {
stringBuilder
.Append("\t\t\tthis.")
.Append(item.Name)
.Append(" = (")
.Append(item.Type)
.Append(")FindName(\"")
.Append(item.Name)
.AppendLine("\");");
}
stringBuilder.AppendLine("\t\t}");
}
if (hasEvents) {
stringBuilder.AppendLine();
stringBuilder.AppendLine("\t\tprotected override bool ConnectEvent(object s, string e, string h) {");
foreach (var evt in GetEvents()) {
stringBuilder
.Append("\t\t\tif(s is ")
.Append(evt.Type)
.Append(" && e==\"")
.Append(evt.EventName)
.Append("\" && h==\"")
.Append(evt.HandlerName)
.AppendLine("\") {");
stringBuilder
.Append("\t\t\t\t((")
.Append(evt.Type)
.Append(")s).")
.Append(evt.EventName)
.Append("+=")
.Append(evt.HandlerName)
.AppendLine(";");
stringBuilder.AppendLine("\t\t\t\treturn true;");
stringBuilder.AppendLine("\t\t\t}");
}
stringBuilder.AppendLine("\t\t\treturn false;");
stringBuilder.AppendLine("\t\t}");
}
stringBuilder.AppendLine("\t}");
stringBuilder.AppendLine("}");
return stringBuilder.ToString();
}
// check if the class already exists and implements the InitializeComponent() and is not a generated class
private bool HasExistingUserImplemention() {
var type = GetType(GetNamespaceString() + "." + GetClassNameString());
if(type == null)
return false;
var initializeComponentMethod = type.GetMethod("InitializeComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var dummyAttributes = type.GetCustomAttributes(typeof(HideInInspector), true);
return initializeComponentMethod != null && dummyAttributes.Any() == false;
}
// gets string for the namespace without the class name
private string GetNamespaceString() {
var codeBehindClassMatch = XamlCodeBehindRegex.Match(XamlText);
if (codeBehindClassMatch.Success == false)
return null;
var namespaceString = codeBehindClassMatch.Groups[1].Value;
var lastIndex = namespaceString.LastIndexOf('.');
namespaceString = namespaceString.Substring(0, lastIndex);
return namespaceString;
}
// get string for class name without the namespace
private string GetClassNameString() {
var codeBehindClassMatch = XamlCodeBehindRegex.Match(XamlText);
if (codeBehindClassMatch.Success == false)
return null;
var namespaceString = codeBehindClassMatch.Groups[1].Value;
var lastIndex = namespaceString.LastIndexOf('.');
var className = namespaceString.Substring(lastIndex + 1);
namespaceString = namespaceString.Substring(0, lastIndex);
return className;
}
private string GetBaseClassName() {
var inheritsClassName = "";
var startIndex = 0;
while (XamlText[startIndex] != '<')
startIndex++;
startIndex += 1;
for (var i = startIndex; XamlText[i] != ' ' && XamlText[i] != '\r' && XamlText[i] != '\n'; i++)
inheritsClassName += XamlText[i];
return inheritsClassName;
}
private struct XamlElement {
public string Type { get; set; }
public string Name { get; set; }
}
// enumerate x:Name="" definitions
private IEnumerable<XamlElement> GetNamedElements() {
var elements = new List<XamlElement>();
var matches = NameRegex.Matches(XamlText);
foreach (Match match in matches) {
// backwards search for owner element start
var elementStartIndex = -1;
for (var i = match.Index; XamlText[i] != '<'; i--)
elementStartIndex = i;
// forward search for owner element start
var xamlTypeName = "";
for (var i = elementStartIndex; XamlText[i] != ' ' && XamlText[i] != '\r' && XamlText[i] != '\n'; i++)
xamlTypeName += XamlText[i];
var name = match.Groups[1].Value;
yield return new XamlElement {
Type = xamlTypeName,
Name = name
};
}
}
private struct XamlNamespaceInclusion {
public string XamlName { get; set; }
public string ClrNamespace { get; set; }
}
// enumerate xmlns:local="" definitions
private IEnumerable<XamlNamespaceInclusion> GetXamlIncludedNamespaces() {
var matches = XmlnsRegex.Matches(XamlText);
foreach (Match match in matches)
yield return new XamlNamespaceInclusion {
XamlName = match.Groups[1].Value,
ClrNamespace = match.Groups[2].Value
};
}
// replace strings "local:MyCircle" with "MyApp.CustomControls.MyCircle"
private string ReplaceXamlNamespace(string xamlElementType, IEnumerable<XamlNamespaceInclusion> includedNamespaces) {
foreach (var ns in includedNamespaces) {
var before = xamlElementType;
xamlElementType = xamlElementType.Replace(ns.XamlName + ":", ns.ClrNamespace + ".");
if (xamlElementType != before)
break;
}
return xamlElementType;
}
private string GetCsFileName() {
return XamlAsset.source.Replace(".xaml", ".g.cs");
}
private struct EventConnection {
public string EventName { get; set; }
public string HandlerName { get; set; }
public string Type { get; set; }
}
private IEnumerable<EventConnection> GetEvents() {
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(XamlText);
var includedNamespaces = GetXamlIncludedNamespaces().ToArray();
foreach (var node in XmlRecursion(xmlDoc).Skip(1)) { // first element is always #document, skip it
// prevent handling of nested property tags <Grid><Grid.Resources /></Grid>
if (node.Name.StartsWith(node.ParentNode.Name) && node.Name != node.ParentNode.Name)
continue;
if (node.Name.StartsWith("x:"))
continue;
var typename = ReplaceXamlNamespace(node.Name, includedNamespaces);
Type type;
if(typename == node.Name)
type = GetType("Noesis."+typename);
else
type = GetType(typename);
if (node.Attributes == null)
continue;
foreach (XmlAttribute attribute in node.Attributes) {
var evt = type.GetEvent(attribute.Name);
if (evt == null)
continue;
yield return new EventConnection {
EventName = attribute.Name,
HandlerName = attribute.Value,
Type = typename
};
}
}
yield break;
}
private IEnumerable<XmlNode> XmlRecursion(XmlNode node) {
yield return node;
var children = node.ChildNodes;
foreach (XmlNode child in node.ChildNodes) {
foreach (var child2 in XmlRecursion(child)){
yield return child2;
}
}
}
// https://stackoverflow.com/a/11811046
public static Type GetType(string typeName) {
var type = Type.GetType(typeName);
if (type != null) return type;
foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
type = a.GetType(typeName);
if (type != null)
return type;
}
return null;
}
}