SpriteEditorWindow.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. using System;
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using UnityTexture2D = UnityEngine.Texture2D;
  5. using System.Linq;
  6. using System.Reflection;
  7. using UnityEngine.UIElements;
  8. namespace UnityEditor.U2D.Sprites
  9. {
  10. /// <summary>
  11. /// Interface for providing a ISpriteEditorDataProvider instance.
  12. /// </summary>
  13. /// <typeparam name="T">The object type the implemented interface is interested in.</typeparam>
  14. public interface ISpriteDataProviderFactory<T>
  15. {
  16. /// <summary>
  17. /// Implement the method to provide an instance of ISpriteEditorDataProvider for a given object.
  18. /// </summary>
  19. /// <param name="obj">The object that requires an instance of ISpriteEditorDataProvider.</param>
  20. /// <returns>An instance of ISpriteEditorDataProvider or null if not supported by the interface.</returns>
  21. ISpriteEditorDataProvider CreateDataProvider(T obj);
  22. }
  23. [AttributeUsage(AttributeTargets.Method)]
  24. internal class SpriteEditorAssetPathProviderAttribute : Attribute
  25. {
  26. [RequiredSignature]
  27. private static string GetAssetPath(UnityEngine.Object obj)
  28. {
  29. return null;
  30. }
  31. }
  32. [AttributeUsage(AttributeTargets.Method)]
  33. internal class SpriteObjectProviderAttribute : Attribute
  34. {
  35. [RequiredSignature]
  36. private static Sprite GetSpriteObject(UnityEngine.Object obj)
  37. {
  38. return null;
  39. }
  40. }
  41. /// <summary>
  42. /// Utility class that collects methods with SpriteDataProviderFactoryAttribute and SpriteDataProviderAssetPathProviderAttribute.
  43. /// </summary>
  44. public class SpriteDataProviderFactories
  45. {
  46. struct SpriteDataProviderFactory
  47. {
  48. public object instance;
  49. public MethodInfo method;
  50. public Type methodType;
  51. }
  52. static SpriteDataProviderFactory[] s_Factories;
  53. static TypeCache.MethodCollection s_AssetPathProvider;
  54. static TypeCache.MethodCollection s_SpriteObjectProvider;
  55. static SpriteDataProviderFactory[] GetFactories()
  56. {
  57. CacheDataProviders();
  58. return s_Factories;
  59. }
  60. static TypeCache.MethodCollection GetAssetPathProvider()
  61. {
  62. CacheDataProviders();
  63. return s_AssetPathProvider;
  64. }
  65. static TypeCache.MethodCollection GetSpriteObjectProvider()
  66. {
  67. CacheDataProviders();
  68. return s_SpriteObjectProvider;
  69. }
  70. static void CacheDataProviders()
  71. {
  72. if (s_Factories != null)
  73. return;
  74. var factories = TypeCache.GetTypesDerivedFrom(typeof(ISpriteDataProviderFactory<>));
  75. var factoryList = new List<SpriteDataProviderFactory>();
  76. foreach (var factory in factories)
  77. {
  78. try
  79. {
  80. var ins = Activator.CreateInstance(factory);
  81. foreach (var i in factory.GetInterfaces())
  82. {
  83. var genericArguments = i.GetGenericArguments();
  84. if (genericArguments.Length == 1)
  85. {
  86. var s = new SpriteDataProviderFactory();
  87. s.instance = ins;
  88. var method = i.GetMethod("CreateDataProvider");
  89. s.method = method;
  90. s.methodType = genericArguments[0];
  91. factoryList.Add(s);
  92. }
  93. }
  94. }
  95. catch (Exception ex)
  96. {
  97. Debug.LogAssertion(ex);
  98. }
  99. }
  100. s_Factories = factoryList.ToArray();
  101. s_AssetPathProvider = TypeCache.GetMethodsWithAttribute<SpriteEditorAssetPathProviderAttribute>();
  102. s_SpriteObjectProvider = TypeCache.GetMethodsWithAttribute<SpriteObjectProviderAttribute>();
  103. }
  104. /// <summary>
  105. /// Initialized and collect methods with SpriteDataProviderFactoryAttribute and SpriteDataProviderAssetPathProviderAttribute.
  106. /// </summary>
  107. public void Init()
  108. {
  109. CacheDataProviders();
  110. }
  111. /// <summary>
  112. /// Given a UnityEngine.Object, determine the ISpriteEditorDataProvider associate with the object by going
  113. /// going through the methods with SpriteDataProviderFactoryAttribute.
  114. /// </summary>
  115. /// <remarks>When none of the methods is able to provide ISpriteEditorDataProvider for the object, the method will
  116. /// try to cast the AssetImporter of the object to ISpriteEditorDataProvider.</remarks>
  117. /// <param name="obj">The UnityEngine.Object to query.</param>
  118. /// <returns>The ISpriteEditorDataProvider associated with the object.</returns>
  119. public ISpriteEditorDataProvider GetSpriteEditorDataProviderFromObject(UnityEngine.Object obj)
  120. {
  121. if (obj != null)
  122. {
  123. var objType = obj.GetType();
  124. foreach (var factory in GetFactories())
  125. {
  126. try
  127. {
  128. if (factory.methodType == objType)
  129. {
  130. var dataProvider = factory.method.Invoke(factory.instance, new[] { obj }) as ISpriteEditorDataProvider;
  131. if (dataProvider != null && !dataProvider.Equals(null))
  132. return dataProvider;
  133. }
  134. }
  135. catch (Exception ex)
  136. {
  137. Debug.LogAssertion(ex);
  138. }
  139. }
  140. if (obj is ISpriteEditorDataProvider)
  141. return (ISpriteEditorDataProvider)obj;
  142. // now we try the importer
  143. var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(obj));
  144. return importer as ISpriteEditorDataProvider;
  145. }
  146. return null;
  147. }
  148. /// <summary>
  149. /// Given a UnityEngine.Object, determine the asset path associate with the object by going
  150. /// going through the methods with SpriteDataProviderAssetPathProviderAttribute.
  151. /// </summary>
  152. /// <remarks>When none of the methods is able to provide the asset path for the object, the method will return null</remarks>
  153. /// <param name="obj">The UnityEngine.Object to query</param>
  154. /// <returns>The asset path for the object</returns>
  155. internal string GetAssetPath(UnityEngine.Object obj)
  156. {
  157. foreach (var assetPathProvider in GetAssetPathProvider())
  158. {
  159. try
  160. {
  161. var path = assetPathProvider.Invoke(null, new object[] { obj }) as string;
  162. if (!string.IsNullOrEmpty(path))
  163. return path;
  164. }
  165. catch (Exception ex)
  166. {
  167. Debug.LogException(ex);
  168. }
  169. }
  170. return null;
  171. }
  172. /// <summary>
  173. /// Given a UnityEngine.Object, determine the Sprite object associate with the object by going
  174. /// going through the methods with SpriteObjectProviderAttribute.
  175. /// </summary>
  176. /// <remarks>When none of the methods is able to provide a Sprite object, the method will return null</remarks>
  177. /// <param name="obj">The UnityEngine.Object to query</param>
  178. /// <returns>The Sprite object</returns>
  179. internal Sprite GetSpriteObject(UnityEngine.Object obj)
  180. {
  181. foreach (var spriteObjectProvider in GetSpriteObjectProvider())
  182. {
  183. try
  184. {
  185. var sprite = spriteObjectProvider.Invoke(null, new object[] { obj }) as Sprite;
  186. if (sprite != null && !sprite.Equals(null))
  187. return sprite;
  188. }
  189. catch (Exception ex)
  190. {
  191. Debug.LogException(ex);
  192. }
  193. }
  194. return null;
  195. }
  196. }
  197. [InitializeOnLoad]
  198. internal class SpriteEditorWindow : SpriteUtilityWindow, ISpriteEditor
  199. {
  200. static SpriteEditorWindow()
  201. {
  202. UnityEditor.SpriteUtilityWindow.SetShowSpriteEditorWindowWithObject((x) =>
  203. {
  204. SpriteEditorWindow.GetWindow(x);
  205. return true;
  206. });
  207. }
  208. private class SpriteEditorWindowStyles
  209. {
  210. public static readonly GUIContent editingDisableMessageBecausePlaymodeLabel = EditorGUIUtility.TrTextContent("Editing is disabled during play mode");
  211. public static readonly GUIContent editingDisableMessageBecauseNonEditableLabel = EditorGUIUtility.TrTextContent("Editing is disabled because the asset is not editable.");
  212. public static readonly GUIContent revertButtonLabel = EditorGUIUtility.TrTextContent("Revert");
  213. public static readonly GUIContent applyButtonLabel = EditorGUIUtility.TrTextContent("Apply");
  214. public static readonly GUIContent spriteEditorWindowTitle = EditorGUIUtility.TrTextContent("Sprite Editor");
  215. public static readonly GUIContent pendingChangesDialogContent = EditorGUIUtility.TrTextContent("The asset was modified outside of Sprite Editor Window.\nDo you want to apply pending changes?");
  216. public static readonly GUIContent applyRevertDialogTitle = EditorGUIUtility.TrTextContent("Unapplied import settings");
  217. public static readonly GUIContent applyRevertDialogContent = EditorGUIUtility.TrTextContent("Unapplied import settings for '{0}'");
  218. public static readonly GUIContent noSelectionWarning = EditorGUIUtility.TrTextContent("No texture or sprite selected");
  219. public static readonly GUIContent noModuleWarning = EditorGUIUtility.TrTextContent("No Sprite Editor module available");
  220. public static readonly GUIContent applyRevertModuleDialogTitle = EditorGUIUtility.TrTextContent("Unapplied module changes");
  221. public static readonly GUIContent applyRevertModuleDialogContent = EditorGUIUtility.TrTextContent("You have unapplied changes from the current module");
  222. public static readonly GUIContent loadProgressTitle = EditorGUIUtility.TrTextContent("Loading");
  223. public static readonly GUIContent loadContentText = EditorGUIUtility.TrTextContent("Loading Sprites {0}/{1}");
  224. public static readonly string styleSheetPath = "Packages/com.unity.2d.sprite/Editor/UI/SpriteEditor/SpriteEditor.uss";
  225. }
  226. class CurrentResetContext
  227. {
  228. public string assetPath;
  229. }
  230. private const float k_MarginForFraming = 0.05f;
  231. private const float k_WarningMessageWidth = 250f;
  232. private const float k_WarningMessageHeight = 40f;
  233. private const float k_ModuleListWidth = 90f;
  234. private const string k_RefreshOnNextRepaintCommandEvent = "RefreshOnNextRepaintCommand";
  235. bool m_ResetOnNextRepaint;
  236. bool m_ResetCommandSent;
  237. private List<SpriteRect> m_RectsCache;
  238. ISpriteEditorDataProvider m_SpriteDataProvider;
  239. private bool m_RequestRepaint = false;
  240. public static bool s_OneClickDragStarted = false;
  241. string m_SelectedAssetPath;
  242. bool m_AssetNotEditable;
  243. private IEventSystem m_EventSystem;
  244. private IUndoSystem m_UndoSystem;
  245. private IAssetDatabase m_AssetDatabase;
  246. private IGUIUtility m_GUIUtility;
  247. private UnityTexture2D m_OutlineTexture;
  248. private UnityTexture2D m_ReadableTexture;
  249. private Dictionary<Type, RequireSpriteDataProviderAttribute> m_ModuleRequireSpriteDataProvider = new Dictionary<Type, RequireSpriteDataProviderAttribute>();
  250. private IMGUIContainer m_ToolbarIMGUIElement;
  251. private IMGUIContainer m_MainViewIMGUIElement;
  252. private VisualElement m_ModuleViewElement;
  253. private VisualElement m_MainViewElement;
  254. SpriteDataProviderFactories m_SpriteDataProviderFactories;
  255. [SerializeField]
  256. private UnityEngine.Object m_SelectedObject;
  257. [SerializeField]
  258. private string m_SelectedSpriteRectGUID;
  259. internal Func<string, string, bool> onHandleApplyRevertDialog = ShowHandleApplyRevertDialog;
  260. private CurrentResetContext m_CurrentResetContext = null;
  261. public static void GetWindow(UnityEngine.Object obj)
  262. {
  263. var window = EditorWindow.GetWindow<SpriteEditorWindow>();
  264. window.selectedObject = obj;
  265. }
  266. public SpriteEditorWindow()
  267. {
  268. m_EventSystem = new EventSystem();
  269. m_UndoSystem = new UndoSystem();
  270. m_AssetDatabase = new AssetDatabaseSystem();
  271. m_GUIUtility = new GUIUtilitySystem();
  272. }
  273. void ModifierKeysChanged()
  274. {
  275. if (EditorWindow.focusedWindow == this)
  276. {
  277. Repaint();
  278. }
  279. }
  280. private void OnFocus()
  281. {
  282. if (selectedObject != Selection.activeObject)
  283. OnSelectionChange();
  284. if (selectedProviderChanged)
  285. RefreshSpriteEditorWindow();
  286. }
  287. internal UnityEngine.Object selectedObject
  288. {
  289. get { return m_SelectedObject; }
  290. set
  291. {
  292. m_SelectedObject = value;
  293. RefreshSpriteEditorWindow();
  294. }
  295. }
  296. string selectedAssetPath
  297. {
  298. get => m_SelectedAssetPath;
  299. set
  300. {
  301. m_SelectedAssetPath = value;
  302. m_AssetNotEditable = !AssetDatabase.IsOpenForEdit(m_SelectedAssetPath);
  303. }
  304. }
  305. public void RefreshPropertiesCache()
  306. {
  307. var obj = AssetDatabase.LoadMainAssetAtPath(selectedAssetPath);
  308. m_SpriteDataProvider = spriteDataProviderFactories.GetSpriteEditorDataProviderFromObject(obj);
  309. if (!IsSpriteDataProviderValid())
  310. {
  311. selectedAssetPath = "";
  312. return;
  313. }
  314. m_SpriteDataProvider.InitSpriteEditorDataProvider();
  315. var textureProvider = m_SpriteDataProvider.GetDataProvider<ITextureDataProvider>();
  316. if (textureProvider != null)
  317. {
  318. int width = 0, height = 0;
  319. textureProvider.GetTextureActualWidthAndHeight(out width, out height);
  320. m_Texture = textureProvider.previewTexture == null ? null : new PreviewTexture2D(textureProvider.previewTexture, width, height);
  321. }
  322. }
  323. internal string GetSelectionAssetPath()
  324. {
  325. var path = spriteDataProviderFactories.GetAssetPath(selectedObject);
  326. if (string.IsNullOrEmpty(path))
  327. path = m_AssetDatabase.GetAssetPath(selectedObject);
  328. return path;
  329. }
  330. public void InvalidatePropertiesCache()
  331. {
  332. m_RectsCache = null;
  333. m_SpriteDataProvider = null;
  334. }
  335. private Rect warningMessageRect
  336. {
  337. get
  338. {
  339. return new Rect(
  340. position.width - k_WarningMessageWidth - k_InspectorWindowMargin - k_ScrollbarMargin,
  341. k_InspectorWindowMargin + k_ScrollbarMargin,
  342. k_WarningMessageWidth,
  343. k_WarningMessageHeight);
  344. }
  345. }
  346. public SpriteImportMode spriteImportMode
  347. {
  348. get { return !IsSpriteDataProviderValid() ? SpriteImportMode.None : m_SpriteDataProvider.spriteImportMode; }
  349. }
  350. bool activeDataProviderSelected
  351. {
  352. get { return m_SpriteDataProvider != null; }
  353. }
  354. public bool textureIsDirty
  355. {
  356. get
  357. {
  358. return hasUnsavedChanges;
  359. }
  360. set
  361. {
  362. hasUnsavedChanges = value;
  363. }
  364. }
  365. public bool selectedProviderChanged
  366. {
  367. get
  368. {
  369. var assetPath = GetSelectionAssetPath();
  370. var dataProvider = spriteDataProviderFactories.GetSpriteEditorDataProviderFromObject(selectedObject);
  371. return dataProvider != null && selectedAssetPath != assetPath;
  372. }
  373. }
  374. void OnSelectionChange()
  375. {
  376. selectedObject = Selection.activeObject;
  377. RefreshSpriteEditorWindow();
  378. }
  379. void RefreshSpriteEditorWindow()
  380. {
  381. // In case of changed of texture/sprite or selected on non texture object
  382. bool updateModules = false;
  383. if (selectedProviderChanged)
  384. {
  385. HandleApplyRevertDialog(SpriteEditorWindowStyles.applyRevertDialogTitle.text,
  386. String.Format(SpriteEditorWindowStyles.applyRevertDialogContent.text, selectedAssetPath));
  387. selectedAssetPath = GetSelectionAssetPath();
  388. ResetWindow();
  389. ResetZoomAndScroll();
  390. RefreshPropertiesCache();
  391. RefreshRects();
  392. updateModules = true;
  393. }
  394. if (m_RectsCache != null)
  395. {
  396. UpdateSelectedSpriteRectFromSelection();
  397. }
  398. // We only update modules when data provider changed
  399. if (updateModules)
  400. UpdateAvailableModules();
  401. Repaint();
  402. }
  403. private void UpdateSelectedSpriteRectFromSelection()
  404. {
  405. if (Selection.activeObject is UnityEngine.Sprite)
  406. {
  407. UpdateSelectedSpriteRect(Selection.activeObject as UnityEngine.Sprite);
  408. }
  409. else
  410. {
  411. var sprite = spriteDataProviderFactories.GetSpriteObject(Selection.activeObject);
  412. UpdateSelectedSpriteRect(sprite);
  413. }
  414. }
  415. public void ResetWindow()
  416. {
  417. InvalidatePropertiesCache();
  418. textureIsDirty = false;
  419. saveChangesMessage = SpriteEditorWindowStyles.applyRevertModuleDialogContent.text;
  420. }
  421. public void ResetZoomAndScroll()
  422. {
  423. m_Zoom = -1;
  424. m_ScrollPosition = Vector2.zero;
  425. }
  426. SpriteDataProviderFactories spriteDataProviderFactories
  427. {
  428. get
  429. {
  430. if (m_SpriteDataProviderFactories == null)
  431. {
  432. m_SpriteDataProviderFactories = new SpriteDataProviderFactories();
  433. m_SpriteDataProviderFactories.Init();
  434. }
  435. return m_SpriteDataProviderFactories;
  436. }
  437. }
  438. void OnEnable()
  439. {
  440. this.name = "SpriteEditorWindow";
  441. selectedObject = Selection.activeObject;
  442. minSize = new Vector2(360, 200);
  443. titleContent = SpriteEditorWindowStyles.spriteEditorWindowTitle;
  444. m_UndoSystem.RegisterUndoCallback(UndoRedoPerformed);
  445. EditorApplication.modifierKeysChanged += ModifierKeysChanged;
  446. EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
  447. EditorApplication.quitting += OnEditorApplicationQuit;
  448. if (selectedProviderChanged)
  449. selectedAssetPath = GetSelectionAssetPath();
  450. ResetWindow();
  451. RefreshPropertiesCache();
  452. bool noSelectedSprite = string.IsNullOrEmpty(m_SelectedSpriteRectGUID);
  453. RefreshRects();
  454. if (noSelectedSprite)
  455. UpdateSelectedSpriteRectFromSelection();
  456. UnityEditor.SpriteUtilityWindow.SetApplySpriteEditorWindow(RebuildCache);
  457. if (SetupVisualElements())
  458. InitModules();
  459. }
  460. void CreateGUI()
  461. {
  462. if (m_MainViewElement == null)
  463. {
  464. if (SetupVisualElements())
  465. InitModules();
  466. }
  467. }
  468. private bool SetupVisualElements()
  469. {
  470. var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(SpriteEditorWindowStyles.styleSheetPath);
  471. if (styleSheet != null)
  472. {
  473. m_ToolbarIMGUIElement = new IMGUIContainer(DoToolbarGUI)
  474. {
  475. name = "spriteEditorWindowToolbar",
  476. };
  477. m_MainViewIMGUIElement = new IMGUIContainer(DoTextureAndModulesGUI)
  478. {
  479. name = "mainViewIMGUIElement"
  480. };
  481. m_MainViewElement = new VisualElement()
  482. {
  483. name = "spriteEditorWindowMainView",
  484. };
  485. m_ModuleViewElement = new VisualElement()
  486. {
  487. name = "moduleViewElement",
  488. pickingMode = PickingMode.Ignore
  489. };
  490. m_MainViewElement.Add(m_MainViewIMGUIElement);
  491. m_MainViewElement.Add(m_ModuleViewElement);
  492. var root = rootVisualElement;
  493. root.styleSheetList.Add(styleSheet);
  494. root.Add(m_ToolbarIMGUIElement);
  495. root.Add(m_MainViewElement);
  496. return true;
  497. }
  498. return false;
  499. }
  500. private void UndoRedoPerformed()
  501. {
  502. // Was selected texture changed by undo?
  503. if (selectedProviderChanged)
  504. RefreshSpriteEditorWindow();
  505. InitSelectedSpriteRect();
  506. Repaint();
  507. }
  508. private void InitSelectedSpriteRect()
  509. {
  510. SpriteRect newSpriteRect = null;
  511. if (m_RectsCache != null && m_RectsCache.Count > 0)
  512. {
  513. if (selectedSpriteRect != null)
  514. newSpriteRect = m_RectsCache.FirstOrDefault(x => x.spriteID == selectedSpriteRect.spriteID) != null ? selectedSpriteRect : m_RectsCache[0];
  515. else
  516. newSpriteRect = m_RectsCache[0];
  517. }
  518. selectedSpriteRect = newSpriteRect;
  519. }
  520. void OnGUI()
  521. {
  522. CreateGUI();
  523. }
  524. public override void SaveChanges()
  525. {
  526. var oldDelegate = onHandleApplyRevertDialog;
  527. onHandleApplyRevertDialog = (x, y) => true;
  528. HandleApplyRevertDialog(SpriteEditorWindowStyles.applyRevertDialogTitle.text,
  529. String.Format(SpriteEditorWindowStyles.applyRevertDialogContent.text, selectedAssetPath));
  530. onHandleApplyRevertDialog = oldDelegate;
  531. base.SaveChanges();
  532. }
  533. private void OnDisable()
  534. {
  535. Undo.undoRedoPerformed -= UndoRedoPerformed;
  536. InvalidatePropertiesCache();
  537. EditorApplication.modifierKeysChanged -= ModifierKeysChanged;
  538. EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
  539. EditorApplication.quitting -= OnEditorApplicationQuit;
  540. if (m_OutlineTexture != null)
  541. {
  542. DestroyImmediate(m_OutlineTexture);
  543. m_OutlineTexture = null;
  544. }
  545. if (m_ReadableTexture)
  546. {
  547. DestroyImmediate(m_ReadableTexture);
  548. m_ReadableTexture = null;
  549. }
  550. if (m_CurrentModule != null)
  551. m_CurrentModule.OnModuleDeactivate();
  552. UnityEditor.SpriteUtilityWindow.SetApplySpriteEditorWindow(null);
  553. if (m_MainViewElement != null)
  554. {
  555. rootVisualElement.Remove(m_MainViewElement);
  556. m_MainViewElement = null;
  557. }
  558. }
  559. void OnPlayModeStateChanged(PlayModeStateChange playModeState)
  560. {
  561. if (PlayModeStateChange.EnteredPlayMode == playModeState || PlayModeStateChange.EnteredEditMode == playModeState)
  562. {
  563. RebuildCache();
  564. }
  565. }
  566. void OnEditorApplicationQuit()
  567. {
  568. HandleApplyRevertDialog(SpriteEditorWindowStyles.applyRevertDialogTitle.text,
  569. String.Format(SpriteEditorWindowStyles.applyRevertDialogContent.text, selectedAssetPath));
  570. }
  571. static bool ShowHandleApplyRevertDialog(string dialogTitle, string dialogContent)
  572. {
  573. return EditorUtility.DisplayDialog(dialogTitle, dialogContent,
  574. SpriteEditorWindowStyles.applyButtonLabel.text, SpriteEditorWindowStyles.revertButtonLabel.text);
  575. }
  576. void HandleApplyRevertDialog(string dialogTitle, string dialogContent)
  577. {
  578. if (textureIsDirty && IsSpriteDataProviderValid())
  579. {
  580. if (onHandleApplyRevertDialog(dialogTitle, dialogContent))
  581. DoApply();
  582. else
  583. DoRevert();
  584. SetupModule(m_CurrentModuleIndex);
  585. }
  586. }
  587. bool IsSpriteDataProviderValid()
  588. {
  589. return m_SpriteDataProvider != null && !m_SpriteDataProvider.Equals(null);
  590. }
  591. void RefreshRects()
  592. {
  593. m_RectsCache = null;
  594. if (IsSpriteDataProviderValid())
  595. {
  596. m_RectsCache = m_SpriteDataProvider.GetSpriteRects().ToList();
  597. }
  598. InitSelectedSpriteRect();
  599. }
  600. private void UpdateAssetSelectionChange()
  601. {
  602. if (selectedProviderChanged)
  603. {
  604. ResetOnNextRepaint();
  605. }
  606. if (m_ResetCommandSent || (UnityEngine.Event.current.type == EventType.ExecuteCommand && UnityEngine.Event.current.commandName == k_RefreshOnNextRepaintCommandEvent))
  607. {
  608. m_ResetCommandSent = false;
  609. if (selectedProviderChanged || !IsSpriteDataProviderValid())
  610. selectedAssetPath = GetSelectionAssetPath();
  611. RebuildCache();
  612. }
  613. }
  614. internal void ResetOnNextRepaint()
  615. {
  616. //Because we can't show dialog in a repaint/layout event, we need to send event to IMGUI to trigger this.
  617. //The event is now sent through the Update loop.
  618. m_ResetOnNextRepaint = true;
  619. if (textureIsDirty)
  620. {
  621. // We can't depend on the existing data provider to set data because a reimport might cause
  622. // the data provider to be invalid. We store up the current asset path so that in DoApply()
  623. // the modified data can be set correctly to correct asset.
  624. if (m_CurrentResetContext != null)
  625. Debug.LogError("Existing reset not completed for " + m_CurrentResetContext.assetPath);
  626. m_CurrentResetContext = new CurrentResetContext()
  627. {
  628. assetPath = selectedAssetPath
  629. };
  630. }
  631. }
  632. void Update()
  633. {
  634. if (m_ResetOnNextRepaint)
  635. {
  636. m_ResetOnNextRepaint = false;
  637. m_ResetCommandSent = true;
  638. var e = EditorGUIUtility.CommandEvent(k_RefreshOnNextRepaintCommandEvent);
  639. this.SendEvent(e);
  640. }
  641. }
  642. private void RebuildCache()
  643. {
  644. HandleApplyRevertDialog(SpriteEditorWindowStyles.applyRevertDialogTitle.text, SpriteEditorWindowStyles.pendingChangesDialogContent.text);
  645. ResetWindow();
  646. RefreshPropertiesCache();
  647. RefreshRects();
  648. UpdateAvailableModules();
  649. }
  650. private void DoTextureAndModulesGUI()
  651. {
  652. // Don't do anything until reset event is sent
  653. if (m_ResetOnNextRepaint)
  654. return;
  655. InitStyles();
  656. UpdateAssetSelectionChange();
  657. if (m_ResetCommandSent)
  658. return;
  659. if (!activeDataProviderSelected)
  660. {
  661. using (new EditorGUI.DisabledScope(true))
  662. {
  663. GUILayout.Label(SpriteEditorWindowStyles.noSelectionWarning);
  664. }
  665. return;
  666. }
  667. if (m_CurrentModule == null)
  668. {
  669. using (new EditorGUI.DisabledScope(true))
  670. {
  671. GUILayout.Label(SpriteEditorWindowStyles.noModuleWarning);
  672. }
  673. return;
  674. }
  675. textureViewRect = new Rect(0f, 0f, m_MainViewIMGUIElement.layout.width - k_ScrollbarMargin, m_MainViewIMGUIElement.layout.height - k_ScrollbarMargin);
  676. Matrix4x4 oldHandlesMatrix = Handles.matrix;
  677. DoTextureGUI();
  678. // Warning message if applicable
  679. DoEditingDisabledMessage();
  680. m_CurrentModule.DoPostGUI();
  681. Handles.matrix = oldHandlesMatrix;
  682. if (m_RequestRepaint)
  683. {
  684. Repaint();
  685. m_RequestRepaint = false;
  686. }
  687. }
  688. protected override void DoTextureGUIExtras()
  689. {
  690. HandleFrameSelected();
  691. if (m_EventSystem.current.type == EventType.Repaint)
  692. {
  693. SpriteEditorUtility.BeginLines(new Color(1f, 1f, 1f, 0.5f));
  694. var selectedRect = selectedSpriteRect != null ? selectedSpriteRect.spriteID : new GUID();
  695. for (int i = 0; i < m_RectsCache.Count; i++)
  696. {
  697. if (m_RectsCache[i].spriteID != selectedRect)
  698. SpriteEditorUtility.DrawBox(m_RectsCache[i].rect);
  699. }
  700. SpriteEditorUtility.EndLines();
  701. }
  702. m_CurrentModule.DoMainGUI();
  703. }
  704. private void DoToolbarGUI()
  705. {
  706. InitStyles();
  707. GUIStyle toolBarStyle = EditorStyles.toolbar;
  708. Rect toolbarRect = new Rect(0, 0, position.width, k_ToolbarHeight);
  709. if (m_EventSystem.current.type == EventType.Repaint)
  710. {
  711. toolBarStyle.Draw(toolbarRect, false, false, false, false);
  712. }
  713. if (!activeDataProviderSelected || m_CurrentModule == null)
  714. return;
  715. // Top menu bar
  716. // only show popup if there is more than 1 module.
  717. if (m_RegisteredModules.Count > 1)
  718. {
  719. float moduleWidthPercentage = k_ModuleListWidth / minSize.x;
  720. float moduleListWidth = position.width > minSize.x ? position.width * moduleWidthPercentage : k_ModuleListWidth;
  721. moduleListWidth = Mathf.Min(moduleListWidth, EditorStyles.toolbarPopup.CalcSize(m_RegisteredModuleNames[m_CurrentModuleIndex]).x);
  722. int module = EditorGUI.Popup(new Rect(0, 0, moduleListWidth, k_ToolbarHeight), m_CurrentModuleIndex, m_RegisteredModuleNames, EditorStyles.toolbarPopup);
  723. if (module != m_CurrentModuleIndex)
  724. {
  725. if (textureIsDirty)
  726. {
  727. // Have pending module edit changes. Ask user if they want to apply or revert
  728. if (EditorUtility.DisplayDialog(SpriteEditorWindowStyles.applyRevertModuleDialogTitle.text,
  729. SpriteEditorWindowStyles.applyRevertModuleDialogContent.text,
  730. SpriteEditorWindowStyles.applyButtonLabel.text, SpriteEditorWindowStyles.revertButtonLabel.text))
  731. DoApply();
  732. else
  733. DoRevert();
  734. }
  735. m_LastUsedModuleTypeName = m_RegisteredModules[module].GetType().FullName;
  736. SetupModule(module);
  737. }
  738. toolbarRect.x = moduleListWidth;
  739. }
  740. toolbarRect = DoAlphaZoomToolbarGUI(toolbarRect);
  741. Rect applyRevertDrawArea = toolbarRect;
  742. applyRevertDrawArea.x = applyRevertDrawArea.width;
  743. using (new EditorGUI.DisabledScope(!textureIsDirty))
  744. {
  745. applyRevertDrawArea.width = EditorStyles.toolbarButton.CalcSize(SpriteEditorWindowStyles.applyButtonLabel).x;
  746. applyRevertDrawArea.x -= applyRevertDrawArea.width;
  747. if (GUI.Button(applyRevertDrawArea, SpriteEditorWindowStyles.applyButtonLabel, EditorStyles.toolbarButton))
  748. {
  749. DoApply();
  750. SetupModule(m_CurrentModuleIndex);
  751. }
  752. applyRevertDrawArea.width = EditorStyles.toolbarButton.CalcSize(SpriteEditorWindowStyles.revertButtonLabel).x;
  753. applyRevertDrawArea.x -= applyRevertDrawArea.width;
  754. if (GUI.Button(applyRevertDrawArea, SpriteEditorWindowStyles.revertButtonLabel, EditorStyles.toolbarButton))
  755. {
  756. DoRevert();
  757. SetupModule(m_CurrentModuleIndex);
  758. }
  759. }
  760. toolbarRect.width = applyRevertDrawArea.x - toolbarRect.x;
  761. m_CurrentModule.DoToolbarGUI(toolbarRect);
  762. }
  763. private void DoEditingDisabledMessage()
  764. {
  765. if (editingDisabled)
  766. {
  767. GUILayout.BeginArea(warningMessageRect);
  768. var disableMessage = m_AssetNotEditable ? SpriteEditorWindowStyles.editingDisableMessageBecauseNonEditableLabel.text : SpriteEditorWindowStyles.editingDisableMessageBecausePlaymodeLabel.text;
  769. EditorGUILayout.HelpBox(disableMessage, MessageType.Warning);
  770. GUILayout.EndArea();
  771. }
  772. }
  773. private void DoApply()
  774. {
  775. textureIsDirty = false;
  776. bool reimport = true;
  777. var dataProvider = m_SpriteDataProvider;
  778. if (m_CurrentResetContext != null)
  779. {
  780. m_SpriteDataProvider =
  781. m_SpriteDataProviderFactories.GetSpriteEditorDataProviderFromObject(
  782. AssetDatabase.LoadMainAssetAtPath(m_CurrentResetContext.assetPath));
  783. m_SpriteDataProvider.InitSpriteEditorDataProvider();
  784. m_CurrentResetContext = null;
  785. }
  786. if (m_SpriteDataProvider != null)
  787. {
  788. if (m_CurrentModule != null)
  789. reimport = m_CurrentModule.ApplyRevert(true);
  790. m_SpriteDataProvider.Apply();
  791. }
  792. m_SpriteDataProvider = dataProvider;
  793. // Do this so that asset change save dialog will not show
  794. var originalValue = EditorPrefs.GetBool("VerifySavingAssets", false);
  795. EditorPrefs.SetBool("VerifySavingAssets", false);
  796. AssetDatabase.ForceReserializeAssets(new[] {selectedAssetPath}, ForceReserializeAssetsOptions.ReserializeMetadata);
  797. EditorPrefs.SetBool("VerifySavingAssets", originalValue);
  798. if (reimport)
  799. DoTextureReimport(selectedAssetPath);
  800. Repaint();
  801. RefreshRects();
  802. }
  803. private void DoRevert()
  804. {
  805. textureIsDirty = false;
  806. RefreshRects();
  807. GUI.FocusControl("");
  808. if (m_CurrentModule != null)
  809. m_CurrentModule.ApplyRevert(false);
  810. }
  811. public bool HandleSpriteSelection()
  812. {
  813. bool changed = false;
  814. if (m_EventSystem.current.type == EventType.MouseDown && m_EventSystem.current.button == 0 && GUIUtility.hotControl == 0 && !m_EventSystem.current.alt)
  815. {
  816. var oldSelected = selectedSpriteRect;
  817. var triedRect = TrySelect(m_EventSystem.current.mousePosition);
  818. if (triedRect != oldSelected)
  819. {
  820. Undo.RegisterCompleteObjectUndo(this, "Sprite Selection");
  821. selectedSpriteRect = triedRect;
  822. changed = true;
  823. }
  824. if (selectedSpriteRect != null)
  825. s_OneClickDragStarted = true;
  826. else
  827. RequestRepaint();
  828. if (changed && selectedSpriteRect != null)
  829. {
  830. m_EventSystem.current.Use();
  831. }
  832. }
  833. return changed;
  834. }
  835. private void HandleFrameSelected()
  836. {
  837. var evt = m_EventSystem.current;
  838. if ((evt.type == EventType.ValidateCommand || evt.type == EventType.ExecuteCommand)
  839. && evt.commandName == EventCommandNames.FrameSelected)
  840. {
  841. if (evt.type == EventType.ExecuteCommand)
  842. {
  843. // Do not do frame if there is none selected
  844. if (selectedSpriteRect == null)
  845. return;
  846. Rect rect = selectedSpriteRect.rect;
  847. // Calculate the require pixel to display the frame, then get the zoom needed.
  848. float targetZoom = m_Zoom;
  849. if (rect.width < rect.height)
  850. targetZoom = textureViewRect.height / (rect.height + textureViewRect.height * k_MarginForFraming);
  851. else
  852. targetZoom = textureViewRect.width / (rect.width + textureViewRect.width * k_MarginForFraming);
  853. // Apply the zoom
  854. zoomLevel = targetZoom;
  855. // Calculate the scroll values to center the frame
  856. m_ScrollPosition.x = (rect.center.x - (m_Texture.width * 0.5f)) * m_Zoom;
  857. m_ScrollPosition.y = (rect.center.y - (m_Texture.height * 0.5f)) * m_Zoom * -1.0f;
  858. Repaint();
  859. }
  860. evt.Use();
  861. }
  862. }
  863. void UpdateSelectedSpriteRect(UnityEngine.Sprite sprite)
  864. {
  865. if (m_RectsCache == null || sprite == null || sprite.Equals(null))
  866. return;
  867. var spriteGUID = sprite.GetSpriteID();
  868. for (int i = 0; i < m_RectsCache.Count; i++)
  869. {
  870. if (spriteGUID == m_RectsCache[i].spriteID)
  871. {
  872. selectedSpriteRect = m_RectsCache[i];
  873. return;
  874. }
  875. }
  876. selectedSpriteRect = null;
  877. }
  878. private SpriteRect TrySelect(Vector2 mousePosition)
  879. {
  880. float selectedSize = float.MaxValue;
  881. SpriteRect currentRect = null;
  882. mousePosition = Handles.inverseMatrix.MultiplyPoint(mousePosition);
  883. for (int i = 0; i < m_RectsCache.Count; i++)
  884. {
  885. var sr = m_RectsCache[i];
  886. if (sr.rect.Contains(mousePosition))
  887. {
  888. // If we clicked inside an already selected spriterect, always persist that selection
  889. if (sr == selectedSpriteRect)
  890. return sr;
  891. float width = sr.rect.width;
  892. float height = sr.rect.height;
  893. float newSize = width * height;
  894. if (width > 0f && height > 0f && newSize < selectedSize)
  895. {
  896. currentRect = sr;
  897. selectedSize = newSize;
  898. }
  899. }
  900. }
  901. return currentRect;
  902. }
  903. public void DoTextureReimport(string path)
  904. {
  905. if (m_SpriteDataProvider != null)
  906. {
  907. try
  908. {
  909. AssetDatabase.StartAssetEditing();
  910. AssetDatabase.ImportAsset(path);
  911. }
  912. finally
  913. {
  914. AssetDatabase.StopAssetEditing();
  915. }
  916. }
  917. }
  918. GUIContent[] m_RegisteredModuleNames;
  919. List<SpriteEditorModuleBase> m_AllRegisteredModules;
  920. List<SpriteEditorModuleBase> m_RegisteredModules;
  921. SpriteEditorModuleBase m_CurrentModule = null;
  922. int m_CurrentModuleIndex = 0;
  923. [SerializeField]
  924. string m_LastUsedModuleTypeName;
  925. internal void SetupModule(int newModuleIndex)
  926. {
  927. m_ModuleViewElement.Clear();
  928. if (m_RegisteredModules.Count > newModuleIndex)
  929. {
  930. m_CurrentModuleIndex = newModuleIndex;
  931. if (m_CurrentModule != null)
  932. m_CurrentModule.OnModuleDeactivate();
  933. m_CurrentModule = null;
  934. m_CurrentModule = m_RegisteredModules[newModuleIndex];
  935. m_CurrentModule.OnModuleActivate();
  936. }
  937. if (m_MainViewElement != null)
  938. m_MainViewElement.MarkDirtyRepaint();
  939. if (m_ModuleViewElement != null)
  940. m_ModuleViewElement.MarkDirtyRepaint();
  941. }
  942. void UpdateAvailableModules()
  943. {
  944. if (m_AllRegisteredModules == null)
  945. return;
  946. m_RegisteredModules = new List<SpriteEditorModuleBase>();
  947. foreach (var module in m_AllRegisteredModules)
  948. {
  949. if (module.CanBeActivated())
  950. {
  951. RequireSpriteDataProviderAttribute attribute = null;
  952. m_ModuleRequireSpriteDataProvider.TryGetValue(module.GetType(), out attribute);
  953. if (attribute == null || attribute.ContainsAllType(m_SpriteDataProvider))
  954. m_RegisteredModules.Add(module);
  955. }
  956. }
  957. m_RegisteredModuleNames = new GUIContent[m_RegisteredModules.Count];
  958. int lastUsedModuleIndex = 0;
  959. for (int i = 0; i < m_RegisteredModules.Count; i++)
  960. {
  961. m_RegisteredModuleNames[i] = new GUIContent(m_RegisteredModules[i].moduleName);
  962. if (m_RegisteredModules[i].GetType().FullName.Equals(m_LastUsedModuleTypeName))
  963. {
  964. lastUsedModuleIndex = i;
  965. }
  966. }
  967. SetupModule(lastUsedModuleIndex);
  968. }
  969. void InitModules()
  970. {
  971. m_AllRegisteredModules = new List<SpriteEditorModuleBase>();
  972. m_ModuleRequireSpriteDataProvider.Clear();
  973. if (m_OutlineTexture == null)
  974. {
  975. m_OutlineTexture = new UnityTexture2D(1, 16, TextureFormat.RGBA32, false);
  976. m_OutlineTexture.SetPixels(new Color[]
  977. {
  978. new Color(0.5f, 0.5f, 0.5f, 0.5f), new Color(0.5f, 0.5f, 0.5f, 0.5f), new Color(0.8f, 0.8f, 0.8f, 0.8f), new Color(0.8f, 0.8f, 0.8f, 0.8f),
  979. Color.white, Color.white, Color.white, Color.white,
  980. new Color(.8f, .8f, .8f, 1f), new Color(.5f, .5f, .5f, .8f), new Color(0.3f, 0.3f, 0.3f, 0.5f), new Color(0.3f, .3f, 0.3f, 0.5f),
  981. new Color(0.3f, .3f, 0.3f, 0.3f), new Color(0.3f, .3f, 0.3f, 0.3f), new Color(0.1f, 0.1f, 0.1f, 0.1f), new Color(0.1f, .1f, 0.1f, 0.1f)
  982. });
  983. m_OutlineTexture.Apply();
  984. m_OutlineTexture.hideFlags = HideFlags.HideAndDontSave;
  985. }
  986. var outlineTexture = new Texture2DWrapper(m_OutlineTexture);
  987. // Add your modules here
  988. RegisterModule(new SpriteFrameModule(this, m_EventSystem, m_UndoSystem, m_AssetDatabase));
  989. RegisterModule(new SpritePolygonModeModule(this, m_EventSystem, m_UndoSystem, m_AssetDatabase));
  990. RegisterModule(new SpriteOutlineModule(this, m_EventSystem, m_UndoSystem, m_AssetDatabase, m_GUIUtility, new ShapeEditorFactory(), outlineTexture));
  991. RegisterModule(new SpritePhysicsShapeModule(this, m_EventSystem, m_UndoSystem, m_AssetDatabase, m_GUIUtility, new ShapeEditorFactory(), outlineTexture));
  992. RegisterCustomModules();
  993. UpdateAvailableModules();
  994. }
  995. void RegisterModule(SpriteEditorModuleBase module)
  996. {
  997. var type = module.GetType();
  998. var attributes = type.GetCustomAttributes(typeof(RequireSpriteDataProviderAttribute), false);
  999. if (attributes.Length == 1)
  1000. m_ModuleRequireSpriteDataProvider.Add(type, (RequireSpriteDataProviderAttribute)attributes[0]);
  1001. m_AllRegisteredModules.Add(module);
  1002. }
  1003. void RegisterCustomModules()
  1004. {
  1005. foreach (var moduleClassType in TypeCache.GetTypesDerivedFrom<SpriteEditorModuleBase>())
  1006. {
  1007. if (!moduleClassType.IsAbstract)
  1008. {
  1009. bool moduleFound = false;
  1010. foreach (var module in m_AllRegisteredModules)
  1011. {
  1012. if (module.GetType() == moduleClassType)
  1013. {
  1014. moduleFound = true;
  1015. break;
  1016. }
  1017. }
  1018. if (!moduleFound)
  1019. {
  1020. var constructorType = new Type[0];
  1021. // Get the public instance constructor that takes ISpriteEditorModule parameter.
  1022. var constructorInfoObj = moduleClassType.GetConstructor(
  1023. BindingFlags.Instance | BindingFlags.Public, null,
  1024. CallingConventions.HasThis, constructorType, null);
  1025. if (constructorInfoObj != null)
  1026. {
  1027. try
  1028. {
  1029. var newInstance = constructorInfoObj.Invoke(new object[0]) as SpriteEditorModuleBase;
  1030. if (newInstance != null)
  1031. {
  1032. newInstance.spriteEditor = this;
  1033. RegisterModule(newInstance);
  1034. }
  1035. }
  1036. catch (Exception ex)
  1037. {
  1038. Debug.LogWarning("Unable to instantiate custom module " + moduleClassType.FullName + ". Exception:" + ex);
  1039. }
  1040. }
  1041. else
  1042. Debug.LogWarning(moduleClassType.FullName + " does not have a parameterless constructor");
  1043. }
  1044. }
  1045. }
  1046. }
  1047. internal List<SpriteEditorModuleBase> activatedModules
  1048. {
  1049. get { return m_RegisteredModules; }
  1050. }
  1051. public List<SpriteRect> spriteRects
  1052. {
  1053. set { m_RectsCache = value; }
  1054. }
  1055. public SpriteRect selectedSpriteRect
  1056. {
  1057. get
  1058. {
  1059. // Always return null if editing is disabled to prevent all possible action to selected frame.
  1060. if (editingDisabled || m_RectsCache == null || string.IsNullOrEmpty(m_SelectedSpriteRectGUID))
  1061. return null;
  1062. var guid = new GUID(m_SelectedSpriteRectGUID);
  1063. return m_RectsCache.FirstOrDefault(x => x.spriteID == guid);
  1064. }
  1065. set
  1066. {
  1067. if (editingDisabled)
  1068. return;
  1069. var oldSelected = m_SelectedSpriteRectGUID;
  1070. m_SelectedSpriteRectGUID = value != null ? value.spriteID.ToString() : new GUID().ToString();
  1071. if (oldSelected != m_SelectedSpriteRectGUID)
  1072. {
  1073. if (m_MainViewIMGUIElement != null)
  1074. m_MainViewIMGUIElement.MarkDirtyRepaint();
  1075. if (m_MainViewElement != null)
  1076. {
  1077. m_MainViewElement.MarkDirtyRepaint();
  1078. using (var e = SpriteSelectionChangeEvent.GetPooled())
  1079. {
  1080. e.target = m_ModuleViewElement;
  1081. m_MainViewElement.SendEvent(e);
  1082. }
  1083. }
  1084. }
  1085. }
  1086. }
  1087. public ISpriteEditorDataProvider spriteEditorDataProvider
  1088. {
  1089. get { return m_SpriteDataProvider; }
  1090. }
  1091. public bool enableMouseMoveEvent
  1092. {
  1093. set { wantsMouseMove = value; }
  1094. }
  1095. public void RequestRepaint()
  1096. {
  1097. if (focusedWindow != this)
  1098. Repaint();
  1099. else
  1100. m_RequestRepaint = true;
  1101. }
  1102. public void SetDataModified()
  1103. {
  1104. textureIsDirty = true;
  1105. }
  1106. public Rect windowDimension
  1107. {
  1108. get { return textureViewRect; }
  1109. }
  1110. public ITexture2D previewTexture
  1111. {
  1112. get { return m_Texture; }
  1113. }
  1114. public bool editingDisabled => EditorApplication.isPlayingOrWillChangePlaymode || m_AssetNotEditable;
  1115. public void SetPreviewTexture(UnityTexture2D texture, int width, int height)
  1116. {
  1117. m_Texture = new PreviewTexture2D(texture, width, height);
  1118. }
  1119. public void ApplyOrRevertModification(bool apply)
  1120. {
  1121. if (apply)
  1122. DoApply();
  1123. else
  1124. DoRevert();
  1125. }
  1126. internal class PreviewTexture2D : Texture2DWrapper
  1127. {
  1128. private int m_ActualWidth = 0;
  1129. private int m_ActualHeight = 0;
  1130. public PreviewTexture2D(UnityTexture2D t, int width, int height)
  1131. : base(t)
  1132. {
  1133. m_ActualWidth = width;
  1134. m_ActualHeight = height;
  1135. }
  1136. public override int width
  1137. {
  1138. get { return m_ActualWidth; }
  1139. }
  1140. public override int height
  1141. {
  1142. get { return m_ActualHeight; }
  1143. }
  1144. }
  1145. public T GetDataProvider<T>() where T : class
  1146. {
  1147. return m_SpriteDataProvider != null ? m_SpriteDataProvider.GetDataProvider<T>() : null;
  1148. }
  1149. public VisualElement GetMainVisualContainer()
  1150. {
  1151. return m_ModuleViewElement;
  1152. }
  1153. static internal void OnTextureReimport(SpriteEditorWindow win, string path)
  1154. {
  1155. if (win.selectedAssetPath == path)
  1156. {
  1157. win.ResetOnNextRepaint();
  1158. }
  1159. }
  1160. [MenuItem("Window/2D/Sprite Editor", false, 0)]
  1161. static private void OpenSpriteEditorWindow()
  1162. {
  1163. SpriteEditorWindow.GetWindow(Selection.activeObject);
  1164. }
  1165. }
  1166. internal class SpriteEditorTexturePostprocessor : AssetPostprocessor
  1167. {
  1168. public override int GetPostprocessOrder()
  1169. {
  1170. return 1;
  1171. }
  1172. static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
  1173. {
  1174. UnityEngine.Object[] wins = Resources.FindObjectsOfTypeAll(typeof(SpriteEditorWindow));
  1175. SpriteEditorWindow win = wins.Length > 0 ? (EditorWindow)(wins[0]) as SpriteEditorWindow : null;
  1176. if (win != null)
  1177. {
  1178. foreach (var deletedAsset in deletedAssets)
  1179. SpriteEditorWindow.OnTextureReimport(win, deletedAsset);
  1180. foreach (var importedAsset in importedAssets)
  1181. SpriteEditorWindow.OnTextureReimport(win, importedAsset);
  1182. }
  1183. }
  1184. }
  1185. internal class SpriteSelectionChangeEvent : EventBase<SpriteSelectionChangeEvent>
  1186. {
  1187. }
  1188. }