forked from PassivePicasso/ThunderKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImportConfiguration.cs
More file actions
367 lines (331 loc) · 13.1 KB
/
Copy pathImportConfiguration.cs
File metadata and controls
367 lines (331 loc) · 13.1 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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#if UNITY_2019_1_OR_NEWER
using UnityEditor.UIElements;
using UnityEngine.UIElements;
#else
using UnityEditor.Experimental.UIElements;
using UnityEngine.Experimental.UIElements;
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ThunderKit.Common;
using ThunderKit.Core.UIElements;
using UnityEditor;
using UnityEngine;
using ThunderKit.Core.Config;
using UnityEngine.Serialization;
using System.Reflection;
namespace ThunderKit.Core.Data
{
using static AssetDatabase;
public class ImportConfiguration : ThunderKitSetting
{
public OptionalExecutor[] ConfigurationExecutors = Array.Empty<OptionalExecutor>();
[SerializeField]
[FormerlySerializedAs("ConfigurationIndex")]
private int configurationIndex = -1;
public int ConfigurationIndex
{
get => configurationIndex;
set
{
if (value == configurationIndex)
{
return;
}
configurationIndex = value;
EditorUtility.SetDirty(this);
}
}
[SerializeField, HideInInspector] private int totalImportExtensionCount = -1;
static bool executorsRelinked;
[InitializeOnLoadMethod]
static void Init()
{
EditorApplication.update += StepImporters;
}
private static void StepImporters()
{
if (EditorApplication.isCompiling || EditorApplication.isUpdating)
{
return;
}
var configInstance = GetOrCreateSettings<ImportConfiguration>();
if (configInstance.CheckForNewImportConfigs(out _))
{
configInstance = RecreateSelf(configInstance);
SaveAssets();
}
else if (!executorsRelinked)
{
configInstance.RelinkExecutors();
}
executorsRelinked = true;
configInstance.ImportGame();
}
static ImportConfiguration RecreateSelf(ImportConfiguration configInstance)
{
var clone = CreateInstance<ImportConfiguration>();
var configInstancePath = GetAssetPath(configInstance);
var clonePath = configInstancePath.Replace(".asset", "CLONE.asset");
CreateAsset(clone, clonePath);
ImportAsset(clonePath);
clone.Initialize();
ImportAsset(clonePath);
foreach (var executor in configInstance.ConfigurationExecutors)
{
if (!executor) continue;
var friend = clone.ConfigurationExecutors.FirstOrDefault(oe => oe.GetType() == executor.GetType());
if (friend)
EditorUtility.CopySerialized(executor, friend);
}
DeleteAsset(configInstancePath);
Refresh();
clone.name = nameof(ImportConfiguration);
var message = RenameAsset(clonePath, nameof(ImportConfiguration));
if(!string.IsNullOrEmpty(message))
Debug.LogError(message);
Refresh();
return clone;
}
public override void CreateSettingsUI(VisualElement rootElement)
{
string templatePath = Path.Combine(Constants.SettingsTemplatesPath, $"{nameof(ImportConfiguration)}.uxml");
var settingsElement = TemplateHelpers.LoadTemplateInstance(templatePath);
settingsElement.AddEnvironmentAwareSheets(templatePath);
rootElement.Add(settingsElement);
var executorView = settingsElement.Q<VisualElement>("executor-element");
foreach (var executor in ConfigurationExecutors)
{
if (!executor) continue;
VisualElement element = null;
try
{
var child = executor.CreateUI();
if (child != null)
{
if (element == null)
element = new VisualElement { name = "extension-listview-item" };
element.Add(child);
}
}
catch (Exception e)
{
Debug.LogError(e);
element = new VisualElement { name = "extension-item" };
var header = new VisualElement { name = "extension-item-header" };
header.AddToClassList("thunderkit-field");
var label = new Label { name = "extension-label", text = executor.Name };
header.Add(label);
var errorLabel = new Label { name = "extension-error-label", text = "Error", tooltip = e.Message };
header.Add(errorLabel);
element.Add(header);
}
if (element != null)
{
executorView.Add(element);
element.Bind(new SerializedObject(executor));
}
}
}
public override void Initialize()
{
if (CheckForNewImportConfigs(out var executorTypes))
{
LoadImportExtensions(executorTypes);
SaveAssets();
}
}
private bool CheckForNewImportConfigs(out List<Type> executorTypes)
{
executorTypes = GetOptionalExecutors();
if (executorTypes.Count == totalImportExtensionCount)
{
executorTypes = null;
return false;
}
totalImportExtensionCount = executorTypes.Count;
return true;
}
private List<Type> GetOptionalExecutors()
{
#if UNITY_2019_2_OR_NEWER
return TypeCache.GetTypesDerivedFrom<OptionalExecutor>()
.Where(t => t.Assembly.GetCustomAttribute<ImportExtensionsAttribute>() != null)
#else
return FilterForConfigurationAssemblies()
.SelectMany(asm =>
{
try
{
return asm.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types;
}
})
.Where(t => typeof(OptionalExecutor).IsAssignableFrom(t))
#endif
.Where(t => t != null)
.Where(t => !t.IsAbstract && !t.IsInterface)
.ToList();
}
#if UNITY_2019_2_OR_NEWER
#else
private List<Assembly> FilterForConfigurationAssemblies()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
for (int i = assemblies.Count - 1; i >= 0; i--)
{
try
{
var asm = assemblies[i];
try
{
if (asm?.GetCustomAttribute<ImportExtensionsAttribute>() == null)
assemblies.RemoveAt(i);
}
catch
{
Debug.LogError($"Failed to analyze {asm.Location} for ImportExtensions");
assemblies.RemoveAt(i);
}
}
catch (Exception ex) { Debug.LogError(ex.Message); }
}
return assemblies;
}
#endif
private void LoadImportExtensions(List<Type> executorTypes, Dictionary<Type, bool> previousStates = null)
{
var settingsPath = GetAssetPath(this);
var builder = new StringBuilder("Loaded Import Extensions");
builder.AppendLine();
var existingAssetTypes = new HashSet<Type>(ConfigurationExecutors.Where(obj => obj).Select(obj => obj.GetType()));
foreach (var t in executorTypes)
{
if (existingAssetTypes.Contains(t))
continue;
var executor = CreateInstance(t) as OptionalExecutor;
if (executor)
{
AddObjectToAsset(executor, this);
executor.name = executor.Name;
if (previousStates != null && previousStates.TryGetValue(t, out var enabled))
{
executor.enabled = enabled;
}
builder.AppendLine(executor.GetType().FullName);
}
}
EditorUtility.SetDirty(this);
SaveAssets();
ImportAsset(settingsPath);
RelinkExecutors();
}
// Rebuilt from the asset because sub-assets outlive the references to them.
// The type name tiebreak keeps equal-priority executors ordered identically
// across editor versions, so the write below happens only on a real change.
private void RelinkExecutors()
{
var executors = LoadAllAssetRepresentationsAtPath(GetAssetPath(this))
.OfType<OptionalExecutor>()
.OrderByDescending(executor => executor.Priority)
.ThenBy(executor => executor.GetType().FullName, StringComparer.Ordinal)
.ToArray();
if (ConfigurationExecutors != null && ConfigurationExecutors.SequenceEqual(executors))
return;
ConfigurationExecutors = executors;
EditorUtility.SetDirty(this);
SaveAssets();
}
public void ImportGame()
{
if (EditorApplication.isCompiling || EditorApplication.isUpdating) return;
if (ConfigurationExecutors == null) return;
var thunderKitSettings = GetOrCreateSettings<ThunderKitSettings>();
if (ConfigurationIndex >= (ConfigurationExecutors?.Length ?? 0) || ConfigurationIndex < 0) return;
if (string.IsNullOrEmpty(thunderKitSettings.GamePath) || string.IsNullOrEmpty(thunderKitSettings.GameExecutable))
{
if (!LocateGame(thunderKitSettings))
{
ConfigurationIndex = -1;
}
return;
}
var executor = ConfigurationExecutors[ConfigurationIndex];
try
{
if (executor && executor.enabled)
{
if (executor.Execute())
{
Debug.Log($"Executed: {executor.name}");
ConfigurationIndex++;
Refresh();
}
}
else
ConfigurationIndex++;
}
catch (Exception e)
{
ConfigurationIndex = -1;
throw new Exception("Import Failed", e);
//Debug.LogError(e);
//return;
}
if (ConfigurationIndex >= ConfigurationExecutors.Length)
{
foreach (var ce in ConfigurationExecutors)
{
try
{
if (ce.enabled)
{
ce.Cleanup();
}
}
catch (Exception e)
{
Debug.LogError($"Error during Cleanup: {e}");
}
}
AssetDatabase.SaveAssets();
}
}
public static bool LocateGame(ThunderKitSettings tkSettings)
{
var foundExecutable = false;
while (!foundExecutable)
{
var path = string.IsNullOrEmpty(tkSettings.GamePath) ? Directory.GetCurrentDirectory() : tkSettings.GamePath;
switch (Application.platform)
{
case RuntimePlatform.WindowsEditor:
path = EditorUtility.OpenFilePanel("Open Game Executable", path, "exe");
break;
case RuntimePlatform.LinuxEditor:
path = EditorUtility.OpenFilePanel("Open Game Executable", path, "");
break;
//case RuntimePlatform.OSXEditor:
// path = EditorUtility.OpenFilePanel("Open Game Executable", currentDir, "app");
// break;
default:
EditorUtility.DisplayDialog("Unsupported", "Your operating system is partially or completely unsupported. Contributions to improve this are welcome", "Ok");
return false;
}
if (string.IsNullOrEmpty(path)) return false;
//For Linux, we will have to check the selected file to see if the GameExecutable_Data folder exists, we can use this to verify the executable was selected
tkSettings.GameExecutable = Path.GetFileName(path);
tkSettings.GamePath = Path.GetDirectoryName(path);
foundExecutable = Directory.GetFiles(tkSettings.GamePath, tkSettings.GameExecutable).Any();
}
EditorUtility.SetDirty(tkSettings);
return true;
}
}
}