This repository has been archived by the owner on Jun 15, 2023. It is now read-only.
forked from CyberFoxHax/NoesisGUIBindingsGenerator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNoesisCsBindingsGenerator.cs
349 lines (304 loc) · 9.57 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using UnityEditor;
using UnityEngine;
public class NoesisCsBindingsGenerator
{
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; }
static readonly Regex NameRegex = new Regex("x:Name=\"([\\w\\d_]+)\""); // x:Name="MyElementNameHere"
static readonly Regex XmlnsRegex = new Regex("xmlns:([\\w\\d_]+)=\"clr-namespace:([^;\"]+)(?:;.*)?\""); // xmlns:designerui="clr-namespace:Assets.UI.Views.DesignerUI"
static readonly Regex XamlCodeBehindRegex = new Regex("x:Class=\"(.+)\""); // x:Class="Assets.UI.Views.DesignerUI.CircleButton"
const string DummyAttribute = "[UnityEngine.HideInInspector]";
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);
}
string GetCsText()
{
var namespaceString = GetNamespaceString();
var className = GetClassNameString();
var hasCodeBehind = className != null && namespaceString != null;
if (!hasCodeBehind) {
return null;
}
var baseClassName = GetBaseClassName();
var includedNamespaces = GetXamlIncludedNamespaces().ToList();
var elements = GetNamedElements()
.Select(p => new XamlElement {
Name = p.Name,
Type = ReplaceXamlNamespace(p.Type, includedNamespaces)
}).ToList();
var events = GetEvents().ToList();
var hasNamedElements = elements.Any() && baseClassName != "ResourceDictionary";
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 ").AppendLine(namespaceString).AppendLine("{");
stringBuilder.AppendLine("\t" + DummyAttribute);
stringBuilder.Append("\tpublic partial class ").Append(className).Append(" : ").AppendLine(baseClassName).AppendLine("\t{");
{
if (hasNamedElements) {
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()").AppendLine("\t\t{");
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 source, string eventName, string handlerName)").AppendLine("\t\t{");
foreach (var evt in GetEvents()) {
stringBuilder
.Append("\t\t\tif (source is ")
.Append(evt.Type)
.Append(" && eventName == \"")
.Append(evt.EventName)
.Append("\" && handlerName == \"")
.Append(evt.HandlerName)
.AppendLine("\") {");
stringBuilder
.Append("\t\t\t\t((")
.Append(evt.Type)
.Append(")source).")
.Append(evt.EventName)
.Append(" += ")
.Append(evt.HandlerName)
.AppendLine(";");
stringBuilder.AppendLine("\t\t\t\treturn true;");
stringBuilder.AppendLine("\t\t\t}");
}
stringBuilder.AppendLine();
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
bool HasExistingUserImplemention()
{
var type = GetType(GetNamespaceString() + "." + GetClassNameString());
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
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
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);
return className;
}
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;
}
struct XamlElement
{
public string Type { get; set; }
public string Name { get; set; }
}
// enumerate x:Name="" definitions
IEnumerable<XamlElement> GetNamedElements()
{
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
};
}
}
struct XamlNamespaceInclusion
{
public string XamlName { get; set; }
public string ClrNamespace { get; set; }
}
// enumerate xmlns:local="" definitions
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"
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;
}
string GetCsFileName()
{
return XamlAsset.source.Replace(".xaml", ".g.cs");
}
struct EventConnection
{
public string EventName { get; set; }
public string HandlerName { get; set; }
public string Type { get; set; }
}
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.ParentNode != null && 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 (type == null || 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
};
}
}
}
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;
}
}