-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathAttributeHelper.cs
More file actions
317 lines (282 loc) · 13.3 KB
/
Copy pathAttributeHelper.cs
File metadata and controls
317 lines (282 loc) · 13.3 KB
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
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Scripting;
using System;
using System.Collections;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnityEditor
{
[RequiredByNativeCode]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
internal sealed partial class RequiredSignatureAttribute : Attribute {}
internal class AttributeHelper
{
[StructLayout(LayoutKind.Sequential)]
struct MonoGizmoMethod
{
public MethodInfo drawGizmo;
public Type drawnType;
public int options;
}
[RequiredByNativeCode]
static MonoGizmoMethod[] ExtractGizmos(Assembly assembly)
{
var commands = new List<MonoGizmoMethod>();
foreach (var mi in EditorAssemblies.GetAllMethodsWithAttribute<DrawGizmo>(BindingFlags.Static).Where(m => m.DeclaringType.Assembly == assembly))
{
var attrs = mi.GetCustomAttributes(typeof(DrawGizmo), false).Cast<DrawGizmo>();
foreach (var gizmoAttr in attrs)
{
var parameters = mi.GetParameters();
if (parameters.Length != 2)
{
Debug.LogWarningFormat(
"Method {0}.{1} is marked with the DrawGizmo attribute but does not take parameters (ComponentType, GizmoType) so will be ignored.",
mi.DeclaringType?.FullName, mi.Name
);
continue;
}
if (mi.DeclaringType != null && mi.DeclaringType.IsGenericTypeDefinition)
{
Debug.LogWarningFormat(
"Method {0}.{1} is marked with the DrawGizmo attribute but is defined on a generic type definition, so will be ignored.",
mi.DeclaringType.FullName, mi.Name
);
continue;
}
Type targetType;
if (gizmoAttr.drawnType == null)
targetType = parameters[0].ParameterType;
else if (parameters[0].ParameterType.IsAssignableFrom(gizmoAttr.drawnType))
targetType = gizmoAttr.drawnType;
else
{
Debug.LogWarningFormat(
"Method {0}.{1} is marked with the DrawGizmo attribute but the component type it applies to could not be determined.",
mi.DeclaringType?.FullName, mi.Name
);
continue;
}
if (parameters[1].ParameterType != typeof(GizmoType) &&
parameters[1].ParameterType != typeof(int))
{
Debug.LogWarningFormat(
"Method {0}.{1} is marked with the DrawGizmo attribute but does not take a second parameter of type GizmoType so will be ignored.",
mi.DeclaringType?.FullName, mi.Name
);
continue;
}
if (targetType.IsInterface)
{
var types = TypeCache.GetTypesDerivedFrom(targetType);
foreach (var type in types)
{
//Limit the types to the classes that have the interface and not it's children
if (type.BaseType != null && type.BaseType.IsAssignableFrom(targetType))
continue;
commands.Add(new MonoGizmoMethod
{
drawnType = type,
drawGizmo = mi,
options = (int)gizmoAttr.drawOptions,
});
}
}
else
{
commands.Add(new MonoGizmoMethod
{
drawnType = targetType,
drawGizmo = mi,
options = (int)gizmoAttr.drawOptions,
});
}
}
}
return commands.ToArray();
}
[RequiredByNativeCode]
static object GetComponentMenuName(Type type)
{
var attrs = type.GetCustomAttributes(typeof(AddComponentMenu), false);
if (attrs.Length > 0)
{
var menu = (AddComponentMenu)attrs[0];
return menu.componentMenu;
}
return null;
}
[RequiredByNativeCode]
static int GetComponentMenuOrdering(Type type)
{
var attrs = type.GetCustomAttributes(typeof(AddComponentMenu), false);
if (attrs.Length > 0)
{
var menu = (AddComponentMenu)attrs[0];
return menu.componentOrder;
}
return 0;
}
[StructLayout(LayoutKind.Sequential)]
struct MonoCreateAssetItem
{
public string menuItem;
public string fileName;
public int order;
public Type type;
}
[RequiredByNativeCode]
static MonoCreateAssetItem[] ExtractCreateAssetMenuItems()
{
var result = new List<MonoCreateAssetItem>();
foreach (var type in TypeCache.GetTypesWithAttribute<CreateAssetMenuAttribute>())
{
var attr = type.GetCustomAttributes(typeof(CreateAssetMenuAttribute), false).FirstOrDefault() as CreateAssetMenuAttribute;
if (attr == null)
continue;
if (!type.IsSubclassOf(typeof(ScriptableObject)))
{
Debug.LogWarningFormat("CreateAssetMenu attribute on {0} will be ignored as {0} is not derived from ScriptableObject.", type.FullName);
continue;
}
string menuItemName = (string.IsNullOrEmpty(attr.menuName)) ? ObjectNames.NicifyVariableName(type.Name) : attr.menuName;
string fileName = (string.IsNullOrEmpty(attr.fileName)) ? ("New " + ObjectNames.NicifyVariableName(type.Name) + ".asset") : attr.fileName;
if (!System.IO.Path.HasExtension(fileName))
fileName = fileName + ".asset";
// trim the trailing space from the menu name:
// 1. visually it is hard to differentialte menu names with or without spaces.
// 2. when asset menu is searched, it will search the trimmed menu name, so it will create a edge case where a menu name with space could not be found after creation.
menuItemName = menuItemName.TrimEnd();
var item = new MonoCreateAssetItem
{
menuItem = menuItemName,
fileName = fileName,
order = attr.order,
type = type
};
result.Add(item);
}
return result.ToArray();
}
internal static bool GameObjectContainsAttribute<T>(GameObject go) where T : Attribute
{
var behaviours = go.GetComponents(typeof(Component));
for (var index = 0; index < behaviours.Length; index++)
{
var behaviour = behaviours[index];
if (behaviour == null)
continue;
var behaviourType = behaviour.GetType();
if (behaviourType.GetCustomAttributes(typeof(T), true).Length > 0)
return true;
}
return false;
}
internal static IEnumerable<TReturnValue> CallMethodsWithAttribute<TReturnValue, TAttr>(params object[] arguments)
where TAttr : Attribute
{
foreach (var method in EditorAssemblies.GetAllMethodsWithAttribute<TAttr>(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
yield return (TReturnValue)method.Invoke(null, arguments);
}
private static bool AreSignaturesMatching(MethodInfo left, MethodInfo right)
{
if (left.IsStatic != right.IsStatic)
return false;
if (left.ReturnType != right.ReturnType)
return false;
ParameterInfo[] leftParams = left.GetParameters();
ParameterInfo[] rightParams = right.GetParameters();
if (leftParams.Length != rightParams.Length)
return false;
for (int i = 0; i < leftParams.Length; i++)
{
if (leftParams[i].ParameterType != rightParams[i].ParameterType)
return false;
}
return true;
}
internal static string MethodToString(MethodInfo method)
{
return string.Format("{0}{1}", method.IsStatic ? "static " : "", method);
}
internal static bool MethodMatchesAnyRequiredSignatureOfAttribute(MethodInfo method, Type attributeType)
{
List<MethodInfo> validSignatures = new List<MethodInfo>();
foreach (var signature in attributeType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
var requiredSignatureAttributes = signature.GetCustomAttributes(typeof(RequiredSignatureAttribute), false);
if (requiredSignatureAttributes.Length > 0)
{
if (AreSignaturesMatching(method, signature))
{
return true;
}
validSignatures.Add(signature);
}
}
if (validSignatures.Count == 0)
Debug.LogError(MethodToString(method) + " has an invalid attribute : " + attributeType + ". " + attributeType + " must have at least one required signature declaration");
else if (validSignatures.Count == 1)
Debug.LogError(MethodToString(method) + " does not match " + attributeType + " expected signature.\n Use " + MethodToString(validSignatures[0]));
else
Debug.LogError(MethodToString(method) + " does not match any of " + attributeType + " expected signatures.\n Valid signatures are: " + string.Join(" , ", validSignatures.Select((a) => MethodToString(a)).ToArray()));
return false;
}
internal struct MethodWithAttribute
{
public MethodInfo info;
public Attribute attribute;
}
internal class MethodInfoSorter
{
internal MethodInfoSorter(List<MethodWithAttribute> methodsWithAttributes)
{
this.methodsWithAttributes = methodsWithAttributes;
}
public IEnumerable<MethodInfo> FilterAndSortOnAttribute<T>(Func<T, bool> filter, Func<T, IComparable> sorter) where T : Attribute
{
return methodsWithAttributes.Where(a => filter((T)a.attribute)).OrderBy(c => sorter((T)c.attribute)).Select(o => o.info);
}
public IEnumerable<MethodWithAttribute> methodsWithAttributes { get; }
}
static Dictionary<Type, MethodInfoSorter> s_DecoratedMethodsByAttrTypeCache = new Dictionary<Type, MethodInfoSorter>();
private const BindingFlags kAllStatic = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
internal static MethodInfoSorter GetMethodsWithAttribute<T>(BindingFlags bindingFlags = kAllStatic) where T : Attribute
{
MethodInfoSorter result;
if (!s_DecoratedMethodsByAttrTypeCache.TryGetValue(typeof(T), out result))
{
var tmp = new List<MethodWithAttribute>();
foreach (var method in EditorAssemblies.GetAllMethodsWithAttribute<T>(bindingFlags))
{
if (method.IsGenericMethod)
{
Debug.LogErrorFormat(
"{0} is a generic method. {1} cannot be applied to it.", MethodToString(method), typeof(T)
);
}
else
{
foreach (var attr in method.GetCustomAttributes(typeof(T), false))
{
if (MethodMatchesAnyRequiredSignatureOfAttribute(method, typeof(T)))
{
var methodWithAttribute = new MethodWithAttribute { info = method, attribute = (T)attr };
tmp.Add(methodWithAttribute);
}
}
}
}
result = new MethodInfoSorter(tmp);
s_DecoratedMethodsByAttrTypeCache[typeof(T)] = result;
}
return result;
}
}
}