-
Notifications
You must be signed in to change notification settings - Fork 286
/
DualityEditorApp.cs
1307 lines (1187 loc) · 46 KB
/
DualityEditorApp.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Windows.Forms;
using System.Drawing;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using Duality;
using Duality.IO;
using Duality.Components;
using Duality.Serialization;
using Duality.Resources;
using Duality.Drawing;
using Duality.Backend;
using Duality.Editor.Backend;
using Duality.Editor.Forms;
using Duality.Editor.UndoRedoActions;
using Duality.Editor.AssetManagement;
using WeifenLuo.WinFormsUI.Docking;
namespace Duality.Editor
{
public static class DualityEditorApp
{
public const string EditorLogfilePath = "logfile_editor.txt";
public const string EditorPrevLogfileName = "logfile_editor_{0}.txt";
public const string EditorPrevLogfileDir = "Temp";
public const string DesignTimeDataFile = "DesignTimeData.dat";
public const string UserDataFile = "EditorUserData.xml";
private const string UserDataDockSeparator = "<!-- DockPanel Data -->";
public const string ActionContextMenu = "ContextMenu";
public const string ActionContextOpenRes = "OpenRes";
public const string ActionContextFirstSession = "FirstSession";
public const string ActionContextSetupObjectForEditing = "SetupObjectForEditing";
private static EditorPluginManager pluginManager = new EditorPluginManager();
private static MainForm mainForm = null;
private static IEditorGraphicsBackend graphicsBack = null;
private static INativeEditorGraphicsContext mainGraphicsContext = null;
private static List<IEditorAction> editorActions = new List<IEditorAction>();
private static ReloadCorePluginDialog corePluginReloader = null;
private static bool needsRecovery = false;
private static GameObjectManager editorObjects = new GameObjectManager();
private static HashSet<GameObject> updateObjects = new HashSet<GameObject>();
private static bool dualityAppSuspended = true;
private static List<Resource> unsavedResources = new List<Resource>();
private static ObjectSelection selectionCurrent = ObjectSelection.Null;
private static ObjectSelection selectionPrevious = ObjectSelection.Null;
private static ObjectSelection.Category selectionActiveCat = ObjectSelection.Category.None;
private static bool selectionChanging = false;
private static Dictionary<Guid,Type> selectionTempScene = null; // GameObjCmp sel inbetween scene switches
private static bool firstEditorSession = false;
private static bool backupsEnabled = true;
private static AutosaveFrequency autosaveFrequency = AutosaveFrequency.ThirtyMinutes;
private static DateTime autosaveLast = DateTime.Now;
private static string launcherApp = null;
private static ContentRef<Scene> lastOpenScene = null;
private static bool startWithLastScene = true;
private static EditorLogOutput memoryLogOutput = null;
public static event EventHandler Terminating = null;
public static event EventHandler EventLoopIdling = null;
public static event EventHandler EditorIdling = null;
public static event EventHandler UpdatingEngine = null;
public static event EventHandler SaveAllTriggered = null;
public static event EventHandler<HighlightObjectEventArgs> HighlightObject = null;
public static event EventHandler<SelectionChangedEventArgs> SelectionChanged = null;
/// <summary>
/// Fired whenever an objects property changes within the editor.
/// Generally used as a means of synchronizing with changes to an
/// objects data from other elements of the GUI. To fire this event
/// from a custom plugin
/// see <seealso cref="NotifyObjPropChanged"/>
/// and <seealso cref="NotifyObjPrefabApplied"/>.
/// </summary>
public static event EventHandler<ObjectPropertyChangedEventArgs> ObjectPropertyChanged = null;
public static EditorPluginManager PluginManager
{
get { return pluginManager; }
}
public static EditorLogOutput GlobalLogData
{
get { return memoryLogOutput; }
}
public static MainForm MainForm
{
get { return mainForm; }
}
public static GameObjectManager EditorObjects
{
get { return editorObjects; }
}
public static ObjectSelection Selection
{
get { return selectionCurrent; }
}
public static ObjectSelection.Category SelectionActiveCategory
{
get { return selectionActiveCat; }
}
public static bool IsSelectionChanging
{
get { return selectionChanging; }
}
public static bool IsReloadingPlugins
{
get
{
return
corePluginReloader.State == ReloadCorePluginDialog.ReloaderState.ReloadPlugins ||
corePluginReloader.State == ReloadCorePluginDialog.ReloaderState.RecoverFromRestart;
}
}
public static IEnumerable<Resource> UnsavedResources
{
get { return unsavedResources.Where(r => !r.Disposed && !r.IsDefaultContent && !r.IsRuntimeResource && (r != Scene.Current || !Sandbox.IsActive)); }
}
public static bool IsFirstEditorSession
{
get { return firstEditorSession; }
}
public static bool BackupsEnabled
{
get { return backupsEnabled; }
set { backupsEnabled = value; }
}
public static AutosaveFrequency Autosaves
{
get { return autosaveFrequency; }
set { autosaveFrequency = value; }
}
public static string LauncherAppPath
{
get
{
string launcherPath = string.IsNullOrWhiteSpace(launcherApp) ? EditorHelper.DualityLauncherExecFile : launcherApp;
if (File.Exists(launcherPath)) return launcherPath;
if (!Path.IsPathRooted(launcherPath))
{
string appDirLauncherApp = Path.Combine(PathHelper.ExecutingAssemblyDir, launcherPath);
if (File.Exists(appDirLauncherApp)) return appDirLauncherApp;
}
return EditorHelper.DualityLauncherExecFile;
}
set
{
if (Path.GetFullPath(value) == Path.GetFullPath(EditorHelper.DualityLauncherExecFile)) value = null;
if (value != launcherApp)
{
launcherApp = value;
}
}
}
private static bool AppStillIdle
{
get
{
NativeMethods.Message msg;
return !NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);
}
}
public static void Init(MainForm mainForm, bool recover)
{
DualityEditorApp.needsRecovery = recover;
DualityEditorApp.mainForm = mainForm;
// Set up an in-memory data log so plugins can access the log history when needed
memoryLogOutput = new EditorLogOutput();
Logs.AddGlobalOutput(memoryLogOutput);
// Create working directories, if not existing yet.
if (!Directory.Exists(DualityApp.DataDirectory))
{
Directory.CreateDirectory(DualityApp.DataDirectory);
using (FileStream s = File.OpenWrite(Path.Combine(DualityApp.DataDirectory, "WorkingFolderIcon.ico")))
{
Properties.GeneralResCache.IconWorkingFolder.Save(s);
}
using (StreamWriter w = new StreamWriter(Path.Combine(DualityApp.DataDirectory, "desktop.ini")))
{
w.WriteLine("[.ShellClassInfo]");
w.WriteLine("ConfirmFileOp=0");
w.WriteLine("NoSharing=0");
w.WriteLine("IconFile=WorkingFolderIcon.ico");
w.WriteLine("IconIndex=0");
w.WriteLine("InfoTip=This is Dualitors working folder");
}
DirectoryInfo dirInfo = new DirectoryInfo(DualityApp.DataDirectory);
dirInfo.Attributes |= FileAttributes.System;
FileInfo fileInfoDesktop = new FileInfo(Path.Combine(DualityApp.DataDirectory, "desktop.ini"));
fileInfoDesktop.Attributes |= FileAttributes.Hidden;
FileInfo fileInfoIcon = new FileInfo(Path.Combine(DualityApp.DataDirectory, "WorkingFolderIcon.ico"));
fileInfoIcon.Attributes |= FileAttributes.Hidden;
}
Directory.CreateDirectory(DualityApp.PluginDirectory);
Directory.CreateDirectory(EditorHelper.ImportDirectory);
// Initialize Duality
EditorHintImageAttribute.ImageResolvers += EditorHintImageResolver;
DualityApp.PluginManager.PluginsReady += DualityApp_PluginsReady;
DualityApp.Init(
DualityApp.ExecutionEnvironment.Editor,
DualityApp.ExecutionContext.Editor,
new DefaultAssemblyLoader(),
null);
// Initialize the plugin manager for the editor. We'll use the same loader as the core.
pluginManager.Init(DualityApp.PluginManager.AssemblyLoader);
// Need to load editor plugins before initializing the graphics context, so the backend is available
pluginManager.LoadPlugins();
// Need to initialize graphics context and default content before instantiating anything that could require any of them
InitMainGraphicsContext();
DualityApp.InitPostWindow();
LoadUserData();
pluginManager.InitPlugins();
// Set up core plugin reloader
corePluginReloader = new ReloadCorePluginDialog(mainForm);
// Register events
mainForm.Activated += mainForm_Activated;
mainForm.Deactivate += mainForm_Deactivate;
Scene.Leaving += Scene_Leaving;
Scene.Entered += Scene_Entered;
Application.Idle += Application_Idle;
Resource.ResourceDisposing += Resource_ResourceDisposing;
Resource.ResourceSaved += Resource_ResourceSaved;
Resource.ResourceSaving += Resource_ResourceSaving;
FileEventManager.PluginsChanged += FileEventManager_PluginsChanged;
editorObjects.GameObjectsAdded += editorObjects_GameObjectsAdded;
editorObjects.GameObjectsRemoved += editorObjects_GameObjectsRemoved;
editorObjects.ComponentAdded += editorObjects_ComponentAdded;
editorObjects.ComponentRemoving += editorObjects_ComponentRemoved;
// Initialize secondary editor components
DesignTimeObjectData.Init();
AssetManager.Init();
ConvertOperation.Init();
PreviewProvider.Init();
Sandbox.Init();
HelpSystem.Init();
FileEventManager.Init();
UndoRedoManager.Init();
// Initialize editor actions
foreach (TypeInfo actionType in GetAvailDualityEditorTypes(typeof(IEditorAction)))
{
if (actionType.IsAbstract) continue;
IEditorAction action = actionType.CreateInstanceOf() as IEditorAction;
if (action != null) editorActions.Add(action);
}
editorActions.StableSort((a, b) => b.Priority.CompareTo(a.Priority));
if (startWithLastScene && lastOpenScene.IsAvailable)
{
Scene.SwitchTo(lastOpenScene, true);
}
else
{
// Enter a new, empty Scene, which will trigger the usual updates
Scene.SwitchTo(null, true);
// If there are no Scenes in the current project, init the first one with some default objects.
if (!Directory.EnumerateFiles(DualityApp.DataDirectory, "*" + Resource.GetFileExtByType<Scene>(), SearchOption.AllDirectories).Any())
{
GameObject mainCam = new GameObject("MainCamera");
mainCam.AddComponent<Transform>().Pos = new Vector3(0, 0, -DrawDevice.DefaultFocusDist);
mainCam.AddComponent<VelocityTracker>();
mainCam.AddComponent<Camera>();
mainCam.AddComponent<SoundListener>();
Scene.Current.AddObject(mainCam);
}
}
// Allow the engine to run
dualityAppSuspended = false;
}
public static bool Terminate(bool byUser)
{
bool cancel = false;
// Display safety message boxes if the close operation is triggered by the user.
if (byUser)
{
var unsavedResTemp = DualityEditorApp.UnsavedResources.ToArray();
if (unsavedResTemp.Any())
{
string unsavedResText = unsavedResTemp.Take(5).ToString(r => r.GetType().GetTypeCSCodeName(true) + ":\t" + r.FullName, "\n");
if (unsavedResTemp.Count() > 5)
unsavedResText += "\n" + string.Format(Properties.GeneralRes.Msg_ConfirmQuitUnsaved_Desc_More, unsavedResTemp.Count() - 5);
DialogResult result = MessageBox.Show(
string.Format(Properties.GeneralRes.Msg_ConfirmQuitUnsaved_Desc, "\n\n" + unsavedResText + "\n\n"),
Properties.GeneralRes.Msg_ConfirmQuitUnsaved_Caption,
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
if (result == DialogResult.Yes)
{
Sandbox.Stop();
DualityEditorApp.SaveAllProjectData();
}
else if (result == DialogResult.Cancel)
cancel = true;
}
}
// Did we cancel it? Return false.
if (cancel)
return false;
// Otherwise, actually start terminating.
// From this point on, there's no return - need to re-init the editor afterwards.
if (Terminating != null)
Terminating(null, EventArgs.Empty);
// Unregister events
EditorHintImageAttribute.ImageResolvers -= EditorHintImageResolver;
DualityApp.PluginManager.PluginsReady -= DualityApp_PluginsReady;
mainForm.Activated -= mainForm_Activated;
mainForm.Deactivate -= mainForm_Deactivate;
Scene.Leaving -= Scene_Leaving;
Scene.Entered -= Scene_Entered;
Application.Idle -= Application_Idle;
Resource.ResourceSaved -= Resource_ResourceSaved;
Resource.ResourceSaving -= Resource_ResourceSaving;
Resource.ResourceDisposing -= Resource_ResourceDisposing;
FileEventManager.PluginsChanged -= FileEventManager_PluginsChanged;
editorObjects.GameObjectsAdded -= editorObjects_GameObjectsAdded;
editorObjects.GameObjectsRemoved -= editorObjects_GameObjectsRemoved;
editorObjects.ComponentAdded -= editorObjects_ComponentAdded;
editorObjects.ComponentRemoving -= editorObjects_ComponentRemoved;
// Terminate editor actions
editorActions.Clear();
// Terminate secondary editor components
UndoRedoManager.Terminate();
FileEventManager.Terminate();
HelpSystem.Terminate();
Sandbox.Terminate();
PreviewProvider.Terminate();
ConvertOperation.Terminate();
AssetManager.Terminate();
DesignTimeObjectData.Terminate();
// Shut down the editor backend
DualityApp.ShutdownBackend(ref graphicsBack);
// Shut down the plugin manager
pluginManager.Terminate();
// Terminate Duality
DualityApp.Terminate();
// Remove the global in-memory log
if (memoryLogOutput != null)
{
Logs.RemoveGlobalOutput(memoryLogOutput);
memoryLogOutput = null;
}
return true;
}
public static IEnumerable<Assembly> GetDualityEditorAssemblies()
{
return pluginManager.GetAssemblies();
}
public static IEnumerable<TypeInfo> GetAvailDualityEditorTypes(Type baseType)
{
return pluginManager.GetTypes(baseType);
}
/// <summary>
/// Enumerates editor user actions that can be applied to objects of the specified type.
/// A typical usage example for this are context menus that are populated dynamically
/// based on the selected object and the available editor plugin capabilities.
/// </summary>
/// <param name="subjectType">The type ob the object the action operates on.</param>
/// <param name="objects">
/// The set of objects the action will be applied on, which is used to
/// determine whether or not a given action can operate on the specific set of objects. If this is null,
/// no such check is performed and all editor actions that match the other criteria are returned.
/// </param>
/// <param name="context">The context in which this action is performed.</param>
public static IEnumerable<IEditorAction> GetEditorActions(Type subjectType, IEnumerable<object> objects, string context = ActionContextMenu)
{
if (objects != null)
{
return editorActions.Where(a =>
a.SubjectType.IsAssignableFrom(subjectType) &&
a.MatchesContext(context) &&
a.CanPerformOn(objects));
}
else
{
return editorActions.Where(a =>
a.SubjectType.IsAssignableFrom(subjectType) &&
a.MatchesContext(context));
}
}
public static void SaveUserData()
{
Logs.Editor.Write("Saving user data...");
Logs.Editor.PushIndent();
using (FileStream str = File.Create(UserDataFile))
{
Encoding encoding = Encoding.Default;
using (StreamWriter writer = new StreamWriter(str.NonClosing()))
{
encoding = writer.Encoding;
XDocument xmlDoc = new XDocument();
XElement rootElement = new XElement("UserData");
{
XElement editorAppElement = new XElement("EditorApp");
{
editorAppElement.SetElementValue("Backups", backupsEnabled);
editorAppElement.SetElementValue("Autosaves", autosaveFrequency);
editorAppElement.SetElementValue("LauncherPath", launcherApp);
editorAppElement.SetElementValue("FirstSession", false);
editorAppElement.SetElementValue("ActiveDocumentIndex", mainForm.ActiveDocumentIndex);
editorAppElement.SetElementValue("LastOpenScene", lastOpenScene.Path);
editorAppElement.SetElementValue("StartWithLastScene", startWithLastScene);
}
if (!editorAppElement.IsEmpty)
rootElement.Add(editorAppElement);
XElement pluginsElement = new XElement("Plugins");
pluginManager.SaveUserData(pluginsElement);
if (!pluginsElement.IsEmpty)
rootElement.Add(pluginsElement);
}
xmlDoc.Add(rootElement);
xmlDoc.Save(writer.BaseStream);
writer.WriteLine();
writer.WriteLine(UserDataDockSeparator);
writer.Flush();
}
mainForm.MainDockPanel.SaveAsXml(str, encoding);
}
Logs.Editor.PopIndent();
}
private static void LoadUserData()
{
if (!File.Exists(UserDataFile))
{
File.WriteAllText(UserDataFile, Properties.GeneralRes.DefaultEditorUserData);
if (!File.Exists(UserDataFile)) return;
}
Logs.Editor.Write("Loading user data...");
Logs.Editor.PushIndent();
Encoding encoding = Encoding.Default;
StringBuilder editorData = new StringBuilder();
StringBuilder dockPanelData = new StringBuilder();
using (StreamReader reader = new StreamReader(UserDataFile))
{
encoding = reader.CurrentEncoding;
string line;
// Retrieve pre-DockPanel section
while ((line = reader.ReadLine()) != null && line.Trim() != UserDataDockSeparator)
editorData.AppendLine(line);
// Retrieve DockPanel section
while ((line = reader.ReadLine()) != null)
dockPanelData.AppendLine(line);
}
// Load DockPanel Data
{
Logs.Editor.Write("Loading DockPanel data...");
Logs.Editor.PushIndent();
MemoryStream dockPanelDataStream = new MemoryStream(encoding.GetBytes(dockPanelData.ToString()));
try
{
mainForm.MainDockPanel.LoadFromXml(dockPanelDataStream, DeserializeDockContent);
}
catch (Exception e)
{
Logs.Editor.WriteError("Cannot load DockPanel data due to malformed or non-existent Xml: {0}", LogFormat.Exception(e));
}
Logs.Editor.PopIndent();
}
// Load editor userdata
{
Logs.Editor.Write("Loading editor user data...");
Logs.Editor.PushIndent();
try
{
int activeDocumentIndex = 0;
// Load main editor data
XDocument xmlDoc = XDocument.Parse(editorData.ToString());
XElement rootElement = xmlDoc.Root;
XElement editorAppElement = rootElement.Elements("EditorApp").FirstOrDefault();
if (editorAppElement != null)
{
editorAppElement.TryGetElementValue("Backups", ref backupsEnabled);
editorAppElement.TryGetElementValue("Autosaves", ref autosaveFrequency);
editorAppElement.TryGetElementValue("LauncherPath", ref launcherApp);
editorAppElement.TryGetElementValue("FirstSession", ref firstEditorSession);
editorAppElement.TryGetElementValue("ActiveDocumentIndex", ref activeDocumentIndex);
string scenePath;
editorAppElement.GetElementValue("LastOpenScene", out scenePath);
if (scenePath != null) lastOpenScene = new ContentRef<Scene>(null, scenePath);
editorAppElement.TryGetElementValue("StartWithLastScene", ref startWithLastScene);
}
// Load plugin editor data
XElement pluginsElement = rootElement.Elements("Plugins").FirstOrDefault();
if (pluginsElement != null)
pluginManager.LoadUserData(pluginsElement);
// Set the active document as loaded from user data
mainForm.ActiveDocumentIndex = activeDocumentIndex;
}
catch (Exception e)
{
Logs.Editor.WriteError("Error loading editor user data: {0}", LogFormat.Exception(e));
}
Logs.Editor.PopIndent();
}
Logs.Editor.PopIndent();
return;
}
private static IDockContent DeserializeDockContent(string persistName)
{
Logs.Editor.Write("Deserializing layout: '" + persistName + "'");
return pluginManager.DeserializeDockContent(persistName);
}
private static void InitMainGraphicsContext()
{
if (mainGraphicsContext != null) return;
if (graphicsBack == null)
DualityApp.InitBackend(out graphicsBack, GetAvailDualityEditorTypes);
Logs.Editor.Write("Creating editor graphics context...");
Logs.Editor.PushIndent();
try
{
// Currently bound to game-specific settings. Should be decoupled
// from them at some point, so the editor can use independent settings.
mainGraphicsContext = graphicsBack.CreateContext(
DualityApp.AppData.MultisampleBackBuffer ?
DualityApp.UserData.AntialiasingQuality :
AAQuality.Off);
}
catch (Exception e)
{
mainGraphicsContext = null;
Logs.Editor.WriteError("Can't create editor graphics context, because an error occurred: {0}", LogFormat.Exception(e));
}
Logs.Editor.PopIndent();
}
public static void PerformBufferSwap()
{
if (mainGraphicsContext == null) return;
mainGraphicsContext.PerformBufferSwap();
}
public static INativeRenderableSite CreateRenderableSite()
{
if (mainGraphicsContext == null) return null;
return mainGraphicsContext.CreateRenderableSite();
}
public static void UpdateGameObject(GameObject obj)
{
updateObjects.Add(obj);
}
/// <summary>
/// Triggers a highlight event in the editor, to which the appropriate modules will
/// be able to react. This usually means flashing a certain tree view entry or similar.
/// </summary>
/// <param name="sender"></param>
/// <param name="obj"></param>
/// <param name="mode"></param>
public static void Highlight(object sender, ObjectSelection obj, HighlightMode mode = HighlightMode.Conceptual)
{
OnHightlightObject(sender, obj, mode);
}
public static void Select(object sender, ObjectSelection sel, SelectMode mode = SelectMode.Set)
{
selectionPrevious = selectionCurrent;
if (mode == SelectMode.Set)
selectionCurrent = selectionCurrent.Transform(sel);
else if (mode == SelectMode.Append)
selectionCurrent = selectionCurrent.Append(sel);
else if (mode == SelectMode.Toggle)
selectionCurrent = selectionCurrent.Toggle(sel);
OnSelectionChanged(sender, sel.Categories, SelectionChangeReason.Unknown);
}
public static void Deselect(object sender, ObjectSelection sel)
{
Deselect(sender, sel, SelectionChangeReason.Unknown);
}
public static void Deselect(object sender, ObjectSelection.Category category)
{
selectionPrevious = selectionCurrent;
selectionCurrent = selectionCurrent.Clear(category);
OnSelectionChanged(sender, ObjectSelection.Category.None, SelectionChangeReason.Unknown);
}
public static void Deselect(object sender, Predicate<object> predicate)
{
selectionPrevious = selectionCurrent;
selectionCurrent = selectionCurrent.Clear(predicate);
OnSelectionChanged(sender, ObjectSelection.Category.None, SelectionChangeReason.Unknown);
}
private static void Deselect(object sender, ObjectSelection sel, SelectionChangeReason reason)
{
selectionPrevious = selectionCurrent;
selectionCurrent = selectionCurrent.Remove(sel);
OnSelectionChanged(sender, ObjectSelection.Category.None, reason);
}
public static string SaveCurrentScene(bool skipYetUnsaved = true)
{
if (!Scene.Current.IsRuntimeResource)
{
if (IsResourceUnsaved(Scene.Current))
{
Scene.Current.Save();
DualityApp.AppData.Version++;
}
}
else if (!skipYetUnsaved)
{
string basePath = Path.Combine(DualityApp.DataDirectory, "Scene");
string path = PathHelper.GetFreePath(basePath, Resource.GetFileExtByType<Scene>());
Scene.Current.Save(path);
DualityApp.AppData.Version++;
// If there is no start scene defined, use this one.
if (DualityApp.AppData.StartScene == null)
{
DualityApp.AppData.StartScene = Scene.Current;
DualityApp.SaveAppData();
}
}
return Scene.Current.Path;
}
public static void SaveResources()
{
bool anySaved = false;
Resource[] resToSave = UnsavedResources.ToArray(); // The Property does some safety checks
foreach (Resource res in resToSave)
{
res.Save();
anySaved = true;
}
unsavedResources.Clear();
if (anySaved) DualityApp.AppData.Version++;
}
public static void FlagResourceUnsaved(IEnumerable<Resource> res)
{
foreach (Resource r in res)
FlagResourceUnsaved(r);
}
public static void FlagResourceUnsaved(Resource res)
{
if (unsavedResources.Contains(res)) return;
unsavedResources.Add(res);
}
public static void FlagResourceSaved(IEnumerable<Resource> res)
{
foreach (Resource r in res)
FlagResourceSaved(r);
}
public static void FlagResourceSaved(Resource res)
{
unsavedResources.Remove(res);
}
public static bool IsResourceUnsaved(Resource res)
{
return UnsavedResources.Contains(res);
}
public static bool IsResourceUnsaved(IContentRef res)
{
if (res.IsDefaultContent) return false;
return res.ResWeak != null ? IsResourceUnsaved(res.ResWeak) : IsResourceUnsaved(res.Path);
}
public static bool IsResourceUnsaved(string resPath)
{
return UnsavedResources.Any(r => Path.GetFullPath(r.Path) == Path.GetFullPath(resPath));
}
public static void SaveAllProjectData()
{
if (!IsResourceUnsaved(Scene.Current) && !Sandbox.IsActive) SaveCurrentScene();
SaveResources();
if (SaveAllTriggered != null)
SaveAllTriggered(null, EventArgs.Empty);
autosaveLast = DateTime.Now;
}
public static void BackupResource(string path)
{
if (Resource.IsDefaultContentPath(path)) return;
if (!File.Exists(path)) return;
if (!PathOp.IsPathLocatedIn(path, DualityApp.DataDirectory)) return;
// We don't want to screw anything up by trying to backup stuff, so just catch and log everything.
try
{
string fileName = Path.GetFileName(path);
string resourceName = Resource.GetNameFromPath(path);
string pathCompleteExt = fileName.Remove(0, resourceName.Length);
string fileBackupDir = Path.Combine(EditorHelper.BackupDirectory, PathHelper.MakeFilePathRelative(path, DualityApp.DataDirectory));
string fileBackupName = DateTime.Now.ToString("yyyy-MM-dd T HH-mm", System.Globalization.CultureInfo.InvariantCulture) + pathCompleteExt;
// Copy the file to the backup directory
if (!Directory.Exists(fileBackupDir)) Directory.CreateDirectory(fileBackupDir);
File.Copy(path, Path.Combine(fileBackupDir, fileBackupName), true);
}
catch (Exception e)
{
Logs.Editor.WriteError("Backup of file '{0}' failed: {1}", path, LogFormat.Exception(e));
}
}
public static void NotifyObjPrefabApplied(object sender, ObjectSelection obj)
{
if (obj == null) return;
if (obj.Empty) return;
// For now, applying Prefabs will kill UndoRedo support since OnCopyTo is likely to detach objects
// and thus invalidate old UndoRedoActions. This will only affect a small subset of operations, but
// as for UndoRedo, it is better to fully support a small feature than poorly support a large feature.
// The editor should always act reliable.
UndoRedoManager.Clear();
OnObjectPropertyChanged(sender, new PrefabAppliedEventArgs(obj));
}
/// <summary>
/// Notify other elements of the editor that one or more objects have had properties changed.
/// If the specified objects can be saved, they will be marked as unsaved.
/// See <seealso cref="ObjectPropertyChanged"/>.
/// </summary>
/// <param name="sender"></param>
/// <param name="obj">The selection of obejcts that have been modified</param>
/// <param name="info">The optional set of <see cref="PropertyInfo"/>s specifying which properties have changed on the objects</param>
public static void NotifyObjPropChanged(object sender, ObjectSelection obj, params PropertyInfo[] info)
{
if (obj == null) return;
if (obj.Empty) return;
OnObjectPropertyChanged(sender, new ObjectPropertyChangedEventArgs(obj, info));
}
/// <summary>
/// Notify other elements of the editor that one or more objects have had properties changed.
/// See <seealso cref="ObjectPropertyChanged"/>.
/// </summary>
/// <param name="sender"></param>
/// <param name="obj">The selection of obejcts that have been modified</param>
/// <param name="persistenceCritical">Determines whether or not the objects should be marked as unsaved</param>
/// <param name="info">The optional set of <see cref="PropertyInfo"/>s specifying which properties have changed on the objects</param>
public static void NotifyObjPropChanged(object sender, ObjectSelection obj, bool persistenceCritical, params PropertyInfo[] info)
{
if (obj == null) return;
if (obj.Empty) return;
OnObjectPropertyChanged(sender, new ObjectPropertyChangedEventArgs(obj, info, persistenceCritical));
}
public static T GetPlugin<T>() where T : EditorPlugin
{
return pluginManager.LoadedPlugins.OfType<T>().FirstOrDefault();
}
public static void AnalyzeCorePlugin(CorePlugin plugin)
{
Logs.Editor.Write("Analyzing Core Plugin: {0}", plugin.AssemblyName);
Logs.Editor.PushIndent();
// Query references to other Assemblies
var asmRefQuery = from AssemblyName a in plugin.PluginAssembly.GetReferencedAssemblies()
select a.GetShortAssemblyName();
string thisAsmName = typeof(DualityEditorApp).Assembly.GetShortAssemblyName();
foreach (string asmName in asmRefQuery)
{
bool illegalRef = false;
// Scan for illegally referenced Assemblies
if (asmName == thisAsmName)
illegalRef = true;
else if (pluginManager.LoadedPlugins.Any(p => p.PluginAssembly.GetShortAssemblyName() == asmName))
illegalRef = true;
// Warn about them
if (illegalRef)
{
Logs.Editor.WriteWarning(
"Found illegally referenced Assembly '{0}'. " +
"CorePlugins should never reference or use DualityEditor or any of its EditorPlugins. Consider moving the critical code to an EditorPlugin.",
asmName);
}
}
// Try to retrieve all Types from the current Assembly
Type[] exportedTypes;
try
{
exportedTypes = plugin.PluginAssembly.GetExportedTypes();
}
catch (Exception e)
{
Logs.Editor.WriteError(
"Unable to analyze exported types because an error occured: {0}",
LogFormat.Exception(e));
exportedTypes = null;
}
// Analyze exported types
if (exportedTypes != null)
{
// Query Component types
var cmpTypeQuery = from Type t in exportedTypes
where typeof(Component).IsAssignableFrom(t)
select t;
foreach (var cmpType in cmpTypeQuery)
{
// Scan for public Fields
FieldInfo[] fields = cmpType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
if (fields.Length > 0)
{
Logs.Editor.WriteWarning(
"Found public fields in Component class '{0}': {1}. " +
"The usage of public fields is strongly discouraged in Component classes. Consider using properties instead.",
cmpType.GetTypeCSCodeName(true),
fields.ToString(f => LogFormat.FieldInfo(f, false), ", "));
}
}
}
Logs.Editor.PopIndent();
}
public static bool DisplayConfirmDeleteObjects(ObjectSelection obj = null)
{
if (Sandbox.State == SandboxState.Playing) return true;
DialogResult result = MessageBox.Show(
Properties.GeneralRes.Msg_ConfirmDeleteSelectedObjects_Text,
Properties.GeneralRes.Msg_ConfirmDeleteSelectedObjects_Caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
return result == DialogResult.Yes;
}
public static bool DisplayConfirmBreakPrefabLinkStructure(ObjectSelection obj = null)
{
if (obj == null) obj = DualityEditorApp.Selection;
var linkQueryObj =
from o in obj.GameObjects
where (o.PrefabLink == null && o.AffectedByPrefabLink != null && o.AffectedByPrefabLink.AffectsObject(o)) || (o.PrefabLink != null && o.PrefabLink.ParentLink != null && o.PrefabLink.ParentLink.AffectsObject(o))
select o.PrefabLink == null ? o.AffectedByPrefabLink : o.PrefabLink.ParentLink;
var linkQueryCmp =
from c in obj.Components
where c.GameObj.AffectedByPrefabLink != null && c.GameObj.AffectedByPrefabLink.AffectsObject(c)
select c.GameObj.AffectedByPrefabLink;
var linkList = new List<PrefabLink>(linkQueryObj.Concat(linkQueryCmp).Distinct());
if (linkList.Count == 0) return true;
if (!DisplayConfirmBreakPrefabLink()) return false;
UndoRedoManager.Do(new BreakPrefabLinkAction(linkList.Select(l => l.Obj)));
return true;
}
public static bool DisplayConfirmBreakPrefabLink()
{
DialogResult result = MessageBox.Show(
Properties.GeneralRes.Msg_ConfirmBreakPrefabLink_Desc,
Properties.GeneralRes.Msg_ConfirmBreakPrefabLink_Caption,
MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
return result == DialogResult.Yes;
}
private static void OnEventLoopIdling()
{
if (EventLoopIdling != null)
EventLoopIdling(null, EventArgs.Empty);
}
private static void OnEditorIdling()
{
if (EditorIdling != null)
EditorIdling(null, EventArgs.Empty);
}
private static void OnUpdatingEngine()
{
if (UpdatingEngine != null)
UpdatingEngine(null, EventArgs.Empty);
}
private static void OnHightlightObject(object sender, ObjectSelection target, HighlightMode mode)
{
if (HighlightObject != null)
HighlightObject(sender, new HighlightObjectEventArgs(target, mode));
}
private static void OnSelectionChanged(object sender, ObjectSelection.Category changedCategoryFallback, SelectionChangeReason changeReson)
{
if (DualityApp.ExecContext == DualityApp.ExecutionContext.Terminated) return;
//if (selectionCurrent == selectionPrevious) return;
selectionChanging = true;
selectionActiveCat = changedCategoryFallback;
if (SelectionChanged != null)
{
SelectionChanged(sender, new SelectionChangedEventArgs(
selectionCurrent,
selectionPrevious,
changedCategoryFallback,
changeReson));
}
selectionChanging = false;
}
private static void OnObjectPropertyChanged(object sender, ObjectPropertyChangedEventArgs args)
{
if (DualityApp.ExecContext == DualityApp.ExecutionContext.Terminated) return;
//Logs.Editor.Write("OnObjectPropertyChanged: {0}{2}\t{1}", args.PropNames.ToString(", "), args.Objects.Objects.ToString(", "), Environment.NewLine);
if (args.PersistenceCritical)
{
// If a linked GameObject was modified, update its prefab link changelist
if (!(args is PrefabAppliedEventArgs) && (args.Objects.GameObjects.Any() || args.Objects.Components.Any()))
{
HashSet<PrefabLink> changedLinks = new HashSet<PrefabLink>();
foreach (object o in args.Objects)
{
Component cmp = o as Component;
GameObject obj = o as GameObject;
if (cmp == null && obj == null) continue;
PrefabLink link = null;
if (obj != null) link = obj.AffectedByPrefabLink;
else if (cmp != null && cmp.GameObj != null) link = cmp.GameObj.AffectedByPrefabLink;
if (link == null) continue;
if (cmp != null && !link.AffectsObject(cmp)) continue;
if (obj != null && !link.AffectsObject(obj)) continue;
// Handle property changes regarding affected prefab links change lists
foreach (PropertyInfo info in args.PropInfos)
{
if (PushPrefabLinkPropertyChange(link, o, info))
changedLinks.Add(link);
}
}
foreach (PrefabLink link in changedLinks)
{
NotifyObjPropChanged(null, new ObjectSelection(new[] { link.Obj }), ReflectionInfo.Property_GameObject_PrefabLink);
}
}
// When modifying prefabs, apply changes to all linked objects
if (args.Objects.Resources.OfType<Prefab>().Any())
{
foreach (Prefab prefab in args.Objects.Resources.OfType<Prefab>())
{
HashSet<PrefabLink> appliedLinks = PrefabLink.ApplyAllLinks(Scene.Current.AllObjects, p => p.Prefab == prefab);
List<GameObject> changedObjects = new List<GameObject>(appliedLinks.Select(p => p.Obj));
NotifyObjPrefabApplied(null, new ObjectSelection(changedObjects));
}
}
// If a Resource's Properties are modified, mark Resource for saving
if (args.Objects.ResourceCount > 0)
{
foreach (Resource res in args.Objects.Resources)
{
if (Sandbox.IsActive && res is Scene && (res as Scene).IsCurrent) continue;
FlagResourceUnsaved(res);
}