2
0

EditorApplication.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Runtime.CompilerServices;
  6. using System.IO;
  7. using BansheeEngine;
  8. namespace BansheeEditor
  9. {
  10. /** @addtogroup General
  11. * @{
  12. */
  13. /// <summary>
  14. /// Available tools in the scene view.
  15. /// </summary>
  16. public enum SceneViewTool
  17. {
  18. View,
  19. Move,
  20. Rotate,
  21. Scale
  22. }
  23. /// <summary>
  24. /// Pivot mode used by the scene view tools.
  25. /// </summary>
  26. public enum HandlePivotMode
  27. {
  28. Center,
  29. Pivot
  30. }
  31. /// <summary>
  32. /// Coordinate mode used by the scene view tools.
  33. /// </summary>
  34. public enum HandleCoordinateMode
  35. {
  36. Local,
  37. World
  38. }
  39. /// <summary>
  40. /// Manages various generic and global settings relating to the editor.
  41. /// </summary>
  42. public class EditorApplication
  43. {
  44. internal const string CutBinding = "Cut";
  45. internal const string CopyBinding = "Copy";
  46. internal const string RenameBinding = "Rename";
  47. internal const string DuplicateBinding = "Duplicate";
  48. internal const string DeleteBinding = "Delete";
  49. internal const string PasteBinding = "Paste";
  50. /// <summary>
  51. /// Determines the active tool shown in the scene view.
  52. /// </summary>
  53. public static SceneViewTool ActiveSceneTool
  54. {
  55. get { return EditorSettings.ActiveSceneTool; }
  56. set { EditorSettings.ActiveSceneTool = value; }
  57. }
  58. /// <summary>
  59. /// Determines the coordinate mode used by the tools in the scene view.
  60. /// </summary>
  61. public static HandleCoordinateMode ActiveCoordinateMode
  62. {
  63. get { return EditorSettings.ActiveCoordinateMode; }
  64. set { EditorSettings.ActiveCoordinateMode = value; }
  65. }
  66. /// <summary>
  67. /// Determines the pivot mode used by the tools in the scene view.
  68. /// </summary>
  69. public static HandlePivotMode ActivePivotMode
  70. {
  71. get { return EditorSettings.ActivePivotMode; }
  72. set { EditorSettings.ActivePivotMode = value; }
  73. }
  74. /// <summary>
  75. /// Camera used for rendering the scene view.
  76. /// </summary>
  77. public static Camera SceneViewCamera
  78. {
  79. get { return EditorWindow.GetWindow<SceneWindow>().Camera; }
  80. }
  81. /// <summary>
  82. /// Absolute path to the folder containing the currently open project.
  83. /// </summary>
  84. public static string ProjectPath { get { return Internal_GetProjectPath(); } }
  85. /// <summary>
  86. /// Name of the currently open project.
  87. /// </summary>
  88. public static string ProjectName { get { return Internal_GetProjectName(); } }
  89. /// <summary>
  90. /// Checks is any project currently loaded.
  91. /// </summary>
  92. public static bool IsProjectLoaded { get { return Internal_GetProjectLoaded(); } }
  93. /// <summary>
  94. /// Determines is the game currently running in the editor, or is it stopped or paused. Setting this value to false
  95. /// will stop the game, but if you just want to pause it use <see cref="IsPaused"/> property.
  96. /// </summary>
  97. public static bool IsPlaying
  98. {
  99. get { return Internal_GetIsPlaying(); }
  100. set
  101. {
  102. ToggleToolbarItem("Play", value);
  103. ToggleToolbarItem("Pause", false);
  104. if (!value)
  105. Selection.SceneObject = null;
  106. else
  107. {
  108. if (EditorSettings.GetBool(LogWindow.CLEAR_ON_PLAY_KEY, true))
  109. {
  110. Debug.Clear();
  111. LogWindow log = EditorWindow.GetWindow<LogWindow>();
  112. if (log != null)
  113. log.Refresh();
  114. }
  115. }
  116. Internal_SetIsPlaying(value);
  117. }
  118. }
  119. /// <summary>
  120. /// Determines if the game is currently running in the editor, but paused. If the game is stopped and not running
  121. /// this will return false. If the game is not running and this is enabled, the game will start running but be
  122. /// immediately paused.
  123. /// </summary>
  124. public static bool IsPaused
  125. {
  126. get { return Internal_GetIsPaused(); }
  127. set
  128. {
  129. ToggleToolbarItem("Play", !value);
  130. ToggleToolbarItem("Pause", value);
  131. Internal_SetIsPaused(value);
  132. }
  133. }
  134. /// <summary>
  135. /// Returns true if the game is currently neither running nor paused. Use <see cref="IsPlaying"/> or
  136. /// <see cref="IsPaused"/> to actually change these states.
  137. /// </summary>
  138. public static bool IsStopped
  139. {
  140. get { return !IsPlaying && !IsPaused; }
  141. }
  142. /// <summary>
  143. /// Checks whether the editor currently has focus.
  144. /// </summary>
  145. public static bool HasFocus
  146. {
  147. get { return Internal_HasFocus(); }
  148. }
  149. /// <summary>
  150. /// Render target that the main camera in the scene (if any) will render its view to. This generally means the main
  151. /// game window when running standalone, or the Game viewport when running in editor.
  152. /// </summary>
  153. internal static RenderTarget MainRenderTarget
  154. {
  155. set
  156. {
  157. IntPtr rtPtr = IntPtr.Zero;
  158. if (value != null)
  159. rtPtr = value.GetCachedPtr();
  160. Internal_SetMainRenderTarget(rtPtr);
  161. }
  162. }
  163. /// <summary>
  164. /// Returns the path where the script compiler is located at.
  165. /// </summary>
  166. internal static string CompilerPath { get { return Internal_GetCompilerPath(); } }
  167. /// <summary>
  168. /// Returns the path to the folder where the custom script assemblies are located at.
  169. /// </summary>
  170. internal static string ScriptAssemblyPath { get { return Internal_GetScriptAssemblyPath(); } }
  171. /// <summary>
  172. /// Returns the path to the folder where the .NET framework assemblies are located at.
  173. /// </summary>
  174. internal static string FrameworkAssemblyPath { get { return Internal_GetFrameworkAssemblyPath(); } }
  175. /// <summary>
  176. /// Name of the builtin assembly containing engine specific types.
  177. /// </summary>
  178. internal static string EngineAssemblyName { get { return Internal_GetEngineAssemblyName(); } }
  179. /// <summary>
  180. /// Name of the builtin assembly containing editor specific types.
  181. /// </summary>
  182. internal static string EditorAssemblyName { get { return Internal_GetEditorAssemblyName(); } }
  183. /// <summary>
  184. /// Name of the custom assembly compiled from non-editor scripts within the project.
  185. /// </summary>
  186. internal static string ScriptGameAssemblyName { get { return Internal_GetScriptGameAssemblyName(); } }
  187. /// <summary>
  188. /// Name of the custom assembly compiled from editor scripts within the project.
  189. /// </summary>
  190. internal static string ScriptEditorAssemblyName { get { return Internal_GetScriptEditorAssemblyName(); } }
  191. /// <summary>
  192. /// Returns the path to the folder where the builtin release script assemblies are located at.
  193. /// </summary>
  194. internal static string BuiltinReleaseAssemblyPath { get { return Internal_GetBuiltinReleaseAssemblyPath(); } }
  195. /// <summary>
  196. /// Returns the path to the folder where the builtin debug script assemblies are located at.
  197. /// </summary>
  198. internal static string BuiltinDebugAssemblyPath { get { return Internal_GetBuiltinDebugAssemblyPath(); } }
  199. internal static VirtualButton CutKey = new VirtualButton(CutBinding);
  200. internal static VirtualButton CopyKey = new VirtualButton(CopyBinding);
  201. internal static VirtualButton PasteKey = new VirtualButton(PasteBinding);
  202. internal static VirtualButton RenameKey = new VirtualButton(RenameBinding);
  203. internal static VirtualButton DuplicateKey = new VirtualButton(DuplicateBinding);
  204. internal static VirtualButton DeleteKey = new VirtualButton(DeleteBinding);
  205. private static EditorApplication instance;
  206. private static FolderMonitor monitor;
  207. private static ScriptCodeManager codeManager;
  208. private static bool sceneDirty;
  209. private static bool unitTestsExecuted;
  210. private static EditorPersistentData persistentData;
  211. /// <summary>
  212. /// Constructs a new editor application. Called at editor start-up by the runtime, and any time assembly refresh
  213. /// occurrs.
  214. /// </summary>
  215. internal EditorApplication()
  216. {
  217. instance = this;
  218. codeManager = new ScriptCodeManager();
  219. const string soName = "EditorPersistentData";
  220. SceneObject so = Scene.Root.FindChild(soName);
  221. if (so == null)
  222. so = new SceneObject(soName, true);
  223. persistentData = so.GetComponent<EditorPersistentData>();
  224. if (persistentData == null)
  225. persistentData = so.AddComponent<EditorPersistentData>();
  226. // Register controls
  227. InputConfiguration inputConfig = VirtualInput.KeyConfig;
  228. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.W);
  229. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.S);
  230. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.A);
  231. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.D);
  232. inputConfig.RegisterButton(SceneCamera.MoveUpBinding, ButtonCode.E);
  233. inputConfig.RegisterButton(SceneCamera.MoveDownBinding, ButtonCode.Q);
  234. inputConfig.RegisterButton(SceneCamera.MoveForwardBinding, ButtonCode.Up);
  235. inputConfig.RegisterButton(SceneCamera.MoveBackBinding, ButtonCode.Down);
  236. inputConfig.RegisterButton(SceneCamera.MoveLeftBinding, ButtonCode.Left);
  237. inputConfig.RegisterButton(SceneCamera.MoveRightBinding, ButtonCode.Right);
  238. inputConfig.RegisterButton(SceneCamera.FastMoveBinding, ButtonCode.LeftShift);
  239. inputConfig.RegisterButton(SceneCamera.RotateBinding, ButtonCode.MouseRight);
  240. inputConfig.RegisterButton(SceneCamera.PanBinding, ButtonCode.MouseMiddle);
  241. inputConfig.RegisterAxis(SceneCamera.HorizontalAxisBinding, InputAxis.MouseX);
  242. inputConfig.RegisterAxis(SceneCamera.VerticalAxisBinding, InputAxis.MouseY);
  243. inputConfig.RegisterAxis(SceneCamera.ScrollAxisBinding, InputAxis.MouseZ);
  244. inputConfig.RegisterButton(SceneWindow.ToggleProfilerOverlayBinding, ButtonCode.P, ButtonModifier.CtrlAlt);
  245. inputConfig.RegisterButton(SceneWindow.ViewToolBinding, ButtonCode.Q);
  246. inputConfig.RegisterButton(SceneWindow.FrameBinding, ButtonCode.F);
  247. inputConfig.RegisterButton(SceneWindow.MoveToolBinding, ButtonCode.W);
  248. inputConfig.RegisterButton(SceneWindow.RotateToolBinding, ButtonCode.E);
  249. inputConfig.RegisterButton(SceneWindow.ScaleToolBinding, ButtonCode.R);
  250. inputConfig.RegisterButton(CutBinding, ButtonCode.X, ButtonModifier.Ctrl);
  251. inputConfig.RegisterButton(CopyBinding, ButtonCode.C, ButtonModifier.Ctrl);
  252. inputConfig.RegisterButton(PasteBinding, ButtonCode.V, ButtonModifier.Ctrl);
  253. inputConfig.RegisterButton(DuplicateBinding, ButtonCode.D, ButtonModifier.Ctrl);
  254. inputConfig.RegisterButton(DeleteBinding, ButtonCode.Delete);
  255. inputConfig.RegisterButton(RenameBinding, ButtonCode.F2);
  256. if (IsProjectLoaded)
  257. {
  258. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  259. monitor.OnAdded += OnAssetModified;
  260. monitor.OnRemoved += OnAssetModified;
  261. monitor.OnModified += OnAssetModified;
  262. }
  263. }
  264. /// <summary>
  265. /// Triggered when the folder monitor detects an asset in the monitored folder was modified.
  266. /// </summary>
  267. /// <param name="path">Path to the modified file or folder.</param>
  268. private static void OnAssetModified(string path)
  269. {
  270. ProjectLibrary.Refresh(path);
  271. }
  272. /// <summary>
  273. /// Called every frame by the runtime.
  274. /// </summary>
  275. internal void OnEditorUpdate()
  276. {
  277. // Update managers
  278. ProjectLibrary.Update();
  279. codeManager.Update();
  280. }
  281. /// <summary>
  282. /// Manually triggers a global shortcut.
  283. /// </summary>
  284. /// <param name="btn">Button for the shortcut. If this doesn't correspond to any shortcut, it is ignored.</param>
  285. internal static void TriggerGlobalShortcut(VirtualButton btn)
  286. {
  287. IGlobalShortcuts window = null;
  288. if (btn != PasteKey)
  289. {
  290. // The system ensures elsewhere that only either a resource or a scene object is selected, but not both
  291. if (Selection.ResourcePaths.Length > 0)
  292. {
  293. window = EditorWindow.GetWindow<LibraryWindow>();
  294. }
  295. else if (Selection.SceneObjects.Length > 0)
  296. {
  297. window = EditorWindow.GetWindow<HierarchyWindow>();
  298. if (window == null)
  299. window = EditorWindow.GetWindow<SceneWindow>();
  300. }
  301. if (window != null)
  302. {
  303. if (btn == CopyKey)
  304. window.OnCopyPressed();
  305. else if (btn == CutKey)
  306. window.OnCutPressed();
  307. else if (btn == PasteKey)
  308. window.OnPastePressed();
  309. else if (btn == DuplicateKey)
  310. window.OnDuplicatePressed();
  311. else if (btn == RenameKey)
  312. window.OnRenamePressed();
  313. else if (btn == DeleteKey)
  314. window.OnDeletePressed();
  315. }
  316. }
  317. else
  318. {
  319. HierarchyWindow hierarchy = EditorWindow.GetWindow<HierarchyWindow>();
  320. if (hierarchy != null && hierarchy.HasFocus)
  321. window = hierarchy;
  322. else
  323. {
  324. LibraryWindow library = EditorWindow.GetWindow<LibraryWindow>();
  325. if (library != null && library.HasFocus)
  326. window = library;
  327. }
  328. if (window != null)
  329. window.OnPastePressed();
  330. }
  331. }
  332. /// <summary>
  333. /// Creates a new empty scene.
  334. /// </summary>
  335. [MenuItem("File/New Scene", 10051, true)]
  336. private static void NewScene()
  337. {
  338. LoadScene(null);
  339. }
  340. /// <summary>
  341. /// Opens a dialog that allows the user to select a new prefab to load as the current scene. If current scene
  342. /// is modified the user is offered a chance to save it.
  343. /// </summary>
  344. [MenuItem("File/Open Scene", ButtonModifier.Ctrl, ButtonCode.L, 10050)]
  345. private static void LoadScene()
  346. {
  347. string[] scenePaths;
  348. if (BrowseDialog.OpenFile(ProjectLibrary.ResourceFolder, "", false, out scenePaths))
  349. {
  350. if (scenePaths.Length > 0)
  351. LoadScene(scenePaths[0]);
  352. }
  353. }
  354. /// <summary>
  355. /// Opens a dialog to allows the user to select a location where to save the current scene. If scene was previously
  356. /// saved it is instead automatically saved at the last location.
  357. /// </summary>
  358. public static void SaveScene(Action onSuccess = null, Action onFailure = null)
  359. {
  360. if (!string.IsNullOrEmpty(Scene.ActiveSceneUUID))
  361. {
  362. string scenePath = ProjectLibrary.GetPath(Scene.ActiveSceneUUID);
  363. if (!string.IsNullOrEmpty(scenePath))
  364. {
  365. if (Scene.IsGenericPrefab)
  366. {
  367. SaveGenericPrefab(onSuccess, onFailure);
  368. }
  369. else
  370. {
  371. SaveScene(scenePath);
  372. if (onSuccess != null)
  373. onSuccess();
  374. }
  375. }
  376. else
  377. SaveSceneAs(onSuccess, onFailure);
  378. }
  379. else
  380. SaveSceneAs(onSuccess, onFailure);
  381. }
  382. /// <summary>
  383. /// Opens a dialog to allows the user to select a location where to save the current scene.
  384. /// </summary>
  385. public static void SaveSceneAs(Action onSuccess = null, Action onFailure = null)
  386. {
  387. string scenePath = "";
  388. if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.prefab", out scenePath))
  389. {
  390. if (!PathEx.IsPartOf(scenePath, ProjectLibrary.ResourceFolder))
  391. {
  392. DialogBox.Open("Error", "The location must be inside the Resources folder of the project.",
  393. DialogBox.Type.OK,
  394. x =>
  395. {
  396. if (onFailure != null)
  397. onFailure();
  398. });
  399. }
  400. else
  401. {
  402. // TODO - If path points to an existing non-scene asset or folder I should delete it otherwise
  403. // Internal_SaveScene will silently fail.
  404. scenePath = Path.ChangeExtension(scenePath, ".prefab");
  405. SaveScene(scenePath);
  406. }
  407. }
  408. else
  409. {
  410. // User canceled, so technically a success
  411. if (onSuccess != null)
  412. onSuccess();
  413. }
  414. }
  415. /// <summary>
  416. /// Loads a prefab as the current scene at the specified path. If current scene is modified the user is offered a
  417. /// chance to save it.
  418. /// </summary>
  419. /// <param name="path">Path to a valid prefab relative to the resource folder. If path is empty a brand new
  420. /// scene will be loaded.</param>
  421. public static void LoadScene(string path)
  422. {
  423. Action<string> continueLoad =
  424. (scenePath) =>
  425. {
  426. if (string.IsNullOrEmpty(path))
  427. Scene.Clear();
  428. else
  429. Scene.Load(path);
  430. SetSceneDirty(false);
  431. ProjectSettings.LastOpenScene = scenePath;
  432. ProjectSettings.Save();
  433. };
  434. Action<DialogBox.ResultType> dialogCallback =
  435. (result) =>
  436. {
  437. if (result == DialogBox.ResultType.Yes)
  438. {
  439. SaveScene();
  440. continueLoad(path);
  441. }
  442. else if (result == DialogBox.ResultType.No)
  443. continueLoad(path);
  444. };
  445. if (IsSceneModified())
  446. {
  447. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  448. DialogBox.Type.YesNoCancel, dialogCallback);
  449. }
  450. else
  451. continueLoad(path);
  452. }
  453. /// <summary>
  454. /// Saves the currently loaded scene to the specified path.
  455. /// </summary>
  456. /// <param name="path">Path relative to the resource folder. This can be the path to the existing scene
  457. /// prefab if it just needs updating. </param>
  458. internal static void SaveScene(string path)
  459. {
  460. Prefab scene = Internal_SaveScene(path);
  461. Scene.SetActive(scene);
  462. ProjectLibrary.Refresh(true);
  463. SetSceneDirty(false);
  464. }
  465. /// <summary>
  466. /// Attempts to save the current scene by applying the changes to a prefab, instead of saving it as a brand new
  467. /// scene. This is necessary for generic prefabs that have don't have a scene root included in the prefab. If the
  468. /// object added any other objects to the root, or has moved or deleted the original generic prefab the user
  469. /// will be asked to save the scene normally, creating a brand new prefab.
  470. /// </summary>
  471. private static void SaveGenericPrefab(Action onSuccess = null, Action onFailure = null)
  472. {
  473. // Find prefab root
  474. SceneObject root = null;
  475. int numChildren = Scene.Root.GetNumChildren();
  476. int numNormalChildren = 0;
  477. for (int i = 0; i < numChildren; i++)
  478. {
  479. SceneObject child = Scene.Root.GetChild(i);
  480. if (EditorUtility.IsInternal(child))
  481. continue;
  482. string prefabUUID = PrefabUtility.GetPrefabUUID(child);
  483. if (prefabUUID == Scene.ActiveSceneUUID)
  484. root = child;
  485. // If user added any other prefabs other than the initial one, the scene no longer represents a generic
  486. // prefab (as we can now longer save it by applying changes only to that prefab)
  487. numNormalChildren++;
  488. if (numNormalChildren > 1)
  489. {
  490. root = null;
  491. break;
  492. }
  493. }
  494. if (root != null)
  495. {
  496. PrefabUtility.ApplyPrefab(root, false);
  497. ProjectLibrary.Refresh(true);
  498. SetSceneDirty(false);
  499. if (onSuccess != null)
  500. onSuccess();
  501. }
  502. else
  503. {
  504. SaveSceneAs(onSuccess, onFailure);
  505. }
  506. }
  507. /// <summary>
  508. /// Checks does the folder at the provieded path contain a valid project.
  509. /// </summary>
  510. /// <param name="path">Absolute path to the root project folder.</param>
  511. /// <returns>True if the folder contains a valid project.</returns>
  512. public static bool IsValidProject(string path)
  513. {
  514. return Internal_IsValidProject(path);
  515. }
  516. /// <summary>
  517. /// Contains a new project in the provided folder.
  518. /// </summary>
  519. /// <param name="path">Absolute path to the folder to create the project in. Name of this folder will be used as the
  520. /// project's name.</param>
  521. public static void CreateProject(string path)
  522. {
  523. Internal_CreateProject(path);
  524. }
  525. /// <summary>
  526. /// Wrapper for menu items for <see cref="SaveScene(Action, Action)"/> method
  527. /// </summary>
  528. [MenuItem("File/Save Scene", ButtonModifier.Ctrl, ButtonCode.S, 10049)]
  529. [ToolbarItem("Save Scene", ToolbarIcon.SaveScene, "Save scene (Ctrl + S)", 1998)]
  530. private static void SaveSceneMenu()
  531. {
  532. SaveScene();
  533. }
  534. /// <summary>
  535. /// Wrapper for menu items for <see cref="SaveSceneAs(Action, Action)"/> method
  536. /// </summary>
  537. [MenuItem("File/Save Scene As", 10048)]
  538. private static void SaveSceneAsMenu()
  539. {
  540. SaveSceneAs();
  541. }
  542. /// <summary>
  543. /// Opens a Project Window allowing you to browse for or create a project.
  544. /// </summary>
  545. [MenuItem("File/Open Project", 10100)]
  546. [ToolbarItem("Open Project", ToolbarIcon.OpenProject, "Project manager", 2000)]
  547. public static void BrowseForProject()
  548. {
  549. ProjectWindow.Open();
  550. }
  551. /// <summary>
  552. /// Saves all data in the currently open project.
  553. /// </summary>
  554. [MenuItem("File/Save Project", 10099)]
  555. [ToolbarItem("Save Project", ToolbarIcon.SaveProject, "Save project", 1999)]
  556. public static void SaveProject()
  557. {
  558. foreach (var KVP in persistentData.dirtyResources)
  559. {
  560. string resourceUUID = KVP.Key;
  561. string path = ProjectLibrary.GetPath(resourceUUID);
  562. if (!IsNative(path))
  563. continue; // Native resources can't be changed
  564. Resource resource = ProjectLibrary.Load<Resource>(path);
  565. if(resource != null)
  566. ProjectLibrary.Save(resource);
  567. }
  568. persistentData.dirtyResources.Clear();
  569. SetStatusProject(false);
  570. Internal_SaveProject();
  571. }
  572. /// <summary>
  573. /// Loads the project at the specified path. This method executes asynchronously.
  574. /// </summary>
  575. /// <param name="path">Absolute path to the project's root folder.</param>
  576. public static void LoadProject(string path)
  577. {
  578. if (IsProjectLoaded && path == ProjectPath)
  579. return;
  580. if (!Internal_IsValidProject(path))
  581. {
  582. Debug.LogWarning("Provided path: \"" + path + "\" is not a valid project.");
  583. return;
  584. }
  585. if (IsProjectLoaded)
  586. UnloadProject();
  587. Internal_LoadProject(path); // Triggers Internal_OnProjectLoaded when done
  588. }
  589. /// <summary>
  590. /// Closes the editor.
  591. /// </summary>
  592. public static void Quit()
  593. {
  594. Internal_Quit();
  595. }
  596. /// <summary>
  597. /// Toggles an existing toolbar button into an on or off state which changes the visuals of the button.
  598. /// </summary>
  599. /// <param name="name">Name of the existing button to toggle</param>
  600. /// <param name="on">True to toggle on, false to toggle off (default)</param>
  601. public static void ToggleToolbarItem(string name, bool on)
  602. {
  603. Internal_ToggleToolbarItem(name, on);
  604. }
  605. /// <summary>
  606. /// Opens a file or a folder in the default external application.
  607. /// </summary>
  608. /// <param name="path">Absolute path to the file or folder to open.</param>
  609. public static void OpenExternally(string path)
  610. {
  611. Internal_OpenExternally(path);
  612. }
  613. /// <summary>
  614. /// Marks a resource as dirty so that it may be saved the next time the project is saved. Optionally you may also
  615. /// call <see cref="ProjectLibrary.Save"/> to save it immediately.
  616. /// </summary>
  617. /// <param name="resource">Resource to mark as dirty</param>
  618. public static void SetDirty(Resource resource)
  619. {
  620. if (resource == null)
  621. return;
  622. SetStatusProject(true);
  623. persistentData.dirtyResources[resource.UUID] = true;
  624. }
  625. /// <summary>
  626. /// Marks the current scene as dirty.
  627. /// </summary>
  628. public static void SetSceneDirty()
  629. {
  630. SetSceneDirty(true);
  631. }
  632. /// <summary>
  633. /// Marks the current scene as clean or dirty.
  634. /// </summary>
  635. /// <param name="dirty">Should the scene be marked as clean or dirty.</param>
  636. internal static void SetSceneDirty(bool dirty)
  637. {
  638. sceneDirty = dirty;
  639. SetStatusScene(Scene.ActiveSceneName, dirty);
  640. if (!dirty && Scene.ActiveSceneUUID != null)
  641. persistentData.dirtyResources.Remove(Scene.ActiveSceneUUID);
  642. }
  643. /// <summary>
  644. /// Checks is the specific resource dirty and needs saving.
  645. /// </summary>
  646. /// <param name="resource">Resource to check.</param>
  647. /// <returns>True if the resource requires saving, false otherwise.</returns>
  648. public static bool IsDirty(Resource resource)
  649. {
  650. return persistentData.dirtyResources.ContainsKey(resource.UUID);
  651. }
  652. /// <summary>
  653. /// Checks does the path represent a native resource.
  654. /// </summary>
  655. /// <param name="path">Filename or path to check.</param>
  656. /// <returns>True if the path represents a native resource.</returns>
  657. public static bool IsNative(string path)
  658. {
  659. string extension = Path.GetExtension(path);
  660. return extension == ".asset" || extension == ".prefab";
  661. }
  662. /// <summary>
  663. /// Unloads the currently loaded project. Offers the user a chance to save the current scene if it is modified.
  664. /// Automatically saves all project data before unloading.
  665. /// </summary>
  666. private static void UnloadProject()
  667. {
  668. Action continueUnload =
  669. () =>
  670. {
  671. Scene.Clear();
  672. if (monitor != null)
  673. {
  674. monitor.Destroy();
  675. monitor = null;
  676. }
  677. LibraryWindow window = EditorWindow.GetWindow<LibraryWindow>();
  678. if(window != null)
  679. window.Reset();
  680. SetSceneDirty(false);
  681. Internal_UnloadProject();
  682. SetStatusProject(false);
  683. };
  684. Action<DialogBox.ResultType> dialogCallback =
  685. (result) =>
  686. {
  687. if (result == DialogBox.ResultType.Yes)
  688. SaveScene();
  689. continueUnload();
  690. };
  691. if (IsSceneModified())
  692. {
  693. DialogBox.Open("Warning", "You current scene has modifications. Do you wish to save them first?",
  694. DialogBox.Type.YesNoCancel, dialogCallback);
  695. }
  696. else
  697. continueUnload();
  698. }
  699. /// <summary>
  700. /// Reloads all script assemblies in case they were modified. This action is delayed and will be executed
  701. /// at the beginning of the next frame.
  702. /// </summary>
  703. public static void ReloadAssemblies()
  704. {
  705. Internal_ReloadAssemblies();
  706. }
  707. /// <summary>
  708. /// Changes the scene displayed on the status bar.
  709. /// </summary>
  710. /// <param name="name">Name of the scene.</param>
  711. /// <param name="modified">Whether to display the scene as modified or not.</param>
  712. private static void SetStatusScene(string name, bool modified)
  713. {
  714. Internal_SetStatusScene(name, modified);
  715. }
  716. /// <summary>
  717. /// Changes the project state displayed on the status bar.
  718. /// </summary>
  719. /// <param name="modified">Whether to display the project as modified or not.</param>
  720. private static void SetStatusProject(bool modified)
  721. {
  722. Internal_SetStatusProject(modified);
  723. }
  724. /// <summary>
  725. /// Displays or hides the "compilation in progress" visual on the status bar.
  726. /// </summary>
  727. /// <param name="compiling">True to display the visual, false otherwise.</param>
  728. internal static void SetStatusCompiling(bool compiling)
  729. {
  730. Internal_SetStatusCompiling(compiling);
  731. }
  732. /// <summary>
  733. /// Checks did we make any modifications to the scene since it was last saved.
  734. /// </summary>
  735. /// <returns>True if the scene was never saved, or was modified after last save.</returns>
  736. public static bool IsSceneModified()
  737. {
  738. return sceneDirty;
  739. }
  740. /// <summary>
  741. /// Runs a single frame of the game and pauses it. If the game is not currently running it will be started.
  742. /// </summary>
  743. public static void FrameStep()
  744. {
  745. if (IsStopped)
  746. {
  747. if (EditorSettings.GetBool(LogWindow.CLEAR_ON_PLAY_KEY, true))
  748. {
  749. Debug.Clear();
  750. LogWindow log = EditorWindow.GetWindow<LogWindow>();
  751. if (log != null)
  752. log.Refresh();
  753. }
  754. }
  755. ToggleToolbarItem("Play", false);
  756. ToggleToolbarItem("Pause", true);
  757. Internal_FrameStep();
  758. }
  759. /// <summary>
  760. /// Executes any editor-specific unit tests. This should be called after a project is loaded if possible.
  761. /// </summary>
  762. private static void RunUnitTests()
  763. {
  764. #if DEBUG
  765. Internal_RunUnitTests();
  766. #endif
  767. }
  768. /// <summary>
  769. /// Triggered by the runtime when <see cref="LoadProject"/> method completes.
  770. /// </summary>
  771. private static void Internal_OnProjectLoaded()
  772. {
  773. SetStatusProject(false);
  774. if (!unitTestsExecuted)
  775. {
  776. RunUnitTests();
  777. unitTestsExecuted = true;
  778. }
  779. if (!IsProjectLoaded)
  780. {
  781. ProjectWindow.Open();
  782. return;
  783. }
  784. string projectPath = ProjectPath;
  785. RecentProject[] recentProjects = EditorSettings.RecentProjects;
  786. bool foundPath = false;
  787. for (int i = 0; i < recentProjects.Length; i++)
  788. {
  789. if (PathEx.Compare(recentProjects[i].path, projectPath))
  790. {
  791. recentProjects[i].accessTimestamp = (ulong)DateTime.Now.Ticks;
  792. EditorSettings.RecentProjects = recentProjects;
  793. foundPath = true;
  794. break;
  795. }
  796. }
  797. if (!foundPath)
  798. {
  799. List<RecentProject> extendedRecentProjects = new List<RecentProject>();
  800. extendedRecentProjects.AddRange(recentProjects);
  801. RecentProject newProject = new RecentProject();
  802. newProject.path = projectPath;
  803. newProject.accessTimestamp = (ulong)DateTime.Now.Ticks;
  804. extendedRecentProjects.Add(newProject);
  805. EditorSettings.RecentProjects = extendedRecentProjects.ToArray();
  806. }
  807. EditorSettings.LastOpenProject = projectPath;
  808. EditorSettings.Save();
  809. ProjectLibrary.Refresh();
  810. monitor = new FolderMonitor(ProjectLibrary.ResourceFolder);
  811. monitor.OnAdded += OnAssetModified;
  812. monitor.OnRemoved += OnAssetModified;
  813. monitor.OnModified += OnAssetModified;
  814. if (!string.IsNullOrWhiteSpace(ProjectSettings.LastOpenScene))
  815. {
  816. Scene.Load(ProjectSettings.LastOpenScene);
  817. SetSceneDirty(false);
  818. }
  819. }
  820. /// <summary>
  821. /// Triggered by the runtime when the user clicks on the status bar.
  822. /// </summary>
  823. private static void Internal_OnStatusBarClicked()
  824. {
  825. EditorWindow.OpenWindow<LogWindow>();
  826. }
  827. [MethodImpl(MethodImplOptions.InternalCall)]
  828. private static extern void Internal_SetStatusScene(string name, bool modified);
  829. [MethodImpl(MethodImplOptions.InternalCall)]
  830. private static extern void Internal_SetStatusProject(bool modified);
  831. [MethodImpl(MethodImplOptions.InternalCall)]
  832. private static extern void Internal_SetStatusCompiling(bool compiling);
  833. [MethodImpl(MethodImplOptions.InternalCall)]
  834. private static extern string Internal_GetProjectPath();
  835. [MethodImpl(MethodImplOptions.InternalCall)]
  836. private static extern string Internal_GetProjectName();
  837. [MethodImpl(MethodImplOptions.InternalCall)]
  838. private static extern bool Internal_GetProjectLoaded();
  839. [MethodImpl(MethodImplOptions.InternalCall)]
  840. private static extern string Internal_GetCompilerPath();
  841. [MethodImpl(MethodImplOptions.InternalCall)]
  842. private static extern string Internal_GetBuiltinReleaseAssemblyPath();
  843. [MethodImpl(MethodImplOptions.InternalCall)]
  844. private static extern string Internal_GetBuiltinDebugAssemblyPath();
  845. [MethodImpl(MethodImplOptions.InternalCall)]
  846. private static extern string Internal_GetScriptAssemblyPath();
  847. [MethodImpl(MethodImplOptions.InternalCall)]
  848. private static extern string Internal_GetFrameworkAssemblyPath();
  849. [MethodImpl(MethodImplOptions.InternalCall)]
  850. private static extern string Internal_GetEngineAssemblyName();
  851. [MethodImpl(MethodImplOptions.InternalCall)]
  852. private static extern string Internal_GetEditorAssemblyName();
  853. [MethodImpl(MethodImplOptions.InternalCall)]
  854. private static extern string Internal_GetScriptGameAssemblyName();
  855. [MethodImpl(MethodImplOptions.InternalCall)]
  856. private static extern string Internal_GetScriptEditorAssemblyName();
  857. [MethodImpl(MethodImplOptions.InternalCall)]
  858. private static extern Prefab Internal_SaveScene(string path);
  859. [MethodImpl(MethodImplOptions.InternalCall)]
  860. private static extern bool Internal_IsValidProject(string path);
  861. [MethodImpl(MethodImplOptions.InternalCall)]
  862. private static extern void Internal_SaveProject();
  863. [MethodImpl(MethodImplOptions.InternalCall)]
  864. private static extern void Internal_LoadProject(string path);
  865. [MethodImpl(MethodImplOptions.InternalCall)]
  866. private static extern void Internal_UnloadProject();
  867. [MethodImpl(MethodImplOptions.InternalCall)]
  868. private static extern void Internal_CreateProject(string path);
  869. [MethodImpl(MethodImplOptions.InternalCall)]
  870. private static extern void Internal_ReloadAssemblies();
  871. [MethodImpl(MethodImplOptions.InternalCall)]
  872. private static extern void Internal_OpenExternally(string path);
  873. [MethodImpl(MethodImplOptions.InternalCall)]
  874. private static extern void Internal_RunUnitTests();
  875. [MethodImpl(MethodImplOptions.InternalCall)]
  876. private static extern void Internal_Quit();
  877. [MethodImpl(MethodImplOptions.InternalCall)]
  878. private static extern void Internal_ToggleToolbarItem(string name, bool on);
  879. [MethodImpl(MethodImplOptions.InternalCall)]
  880. private static extern bool Internal_GetIsPlaying();
  881. [MethodImpl(MethodImplOptions.InternalCall)]
  882. private static extern void Internal_SetIsPlaying(bool value);
  883. [MethodImpl(MethodImplOptions.InternalCall)]
  884. private static extern bool Internal_GetIsPaused();
  885. [MethodImpl(MethodImplOptions.InternalCall)]
  886. private static extern void Internal_SetIsPaused(bool value);
  887. [MethodImpl(MethodImplOptions.InternalCall)]
  888. private static extern void Internal_FrameStep();
  889. [MethodImpl(MethodImplOptions.InternalCall)]
  890. private static extern void Internal_SetMainRenderTarget(IntPtr rendertarget);
  891. [MethodImpl(MethodImplOptions.InternalCall)]
  892. private static extern bool Internal_HasFocus();
  893. }
  894. /** @} */
  895. }