RenameSpritesTool.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. #if UNITY_EDITOR
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using UnityEditor;
  7. using UnityEditorInternal;
  8. using UnityEngine;
  9. namespace Animancer.Editor.Tools
  10. {
  11. /// <summary>[Editor-Only] [Pro-Only] A <see cref="SpriteModifierTool"/> for bulk-renaming <see cref="Sprite"/>s.</summary>
  12. /// <remarks>
  13. /// <strong>Documentation:</strong>
  14. /// <see href="https://kybernetik.com.au/animancer/docs/manual/tools/rename-sprites">
  15. /// Rename Sprites</see>
  16. /// </remarks>
  17. /// https://kybernetik.com.au/animancer/api/Animancer.Editor.Tools/RenameSpritesTool
  18. ///
  19. [Serializable]
  20. public class RenameSpritesTool : SpriteModifierTool
  21. {
  22. /************************************************************************************************************************/
  23. [NonSerialized] private List<string> _GeneratedNames;
  24. [NonSerialized] private bool _NamesAreDirty;
  25. [NonSerialized] private ReorderableList _SpritesDisplay;
  26. [SerializeField] private List<string> _ManualNames;
  27. [SerializeField] private int _FirstIndex = 1;
  28. [SerializeField] private int _MinimumDigits = 1;
  29. /************************************************************************************************************************/
  30. /// <inheritdoc/>
  31. public override int DisplayOrder => 2;
  32. /// <inheritdoc/>
  33. public override string Name => "Rename Sprites";
  34. /// <inheritdoc/>
  35. public override string HelpURL => Strings.DocsURLs.RenameSprites;
  36. /// <inheritdoc/>
  37. public override string Instructions
  38. {
  39. get
  40. {
  41. if (Sprites.Count == 0)
  42. return "Select the Sprites you want to rename.";
  43. return "Enter the new name(s) you want to give the Sprites then click Apply." +
  44. "\n\nEach Sprite below the name you enter will be given the same name" +
  45. " until the next name which will restart the counter.";
  46. }
  47. }
  48. /************************************************************************************************************************/
  49. /// <inheritdoc/>
  50. public override void OnEnable(int index)
  51. {
  52. base.OnEnable(index);
  53. _ManualNames ??= new();
  54. _GeneratedNames ??= new();
  55. _SpritesDisplay = AnimancerToolsWindow.CreateReorderableObjectList(Sprites, "Sprites to Rename");
  56. _SpritesDisplay.onChangedCallback += list => DirtyNames();
  57. _SpritesDisplay.drawElementCallback = DrawItem;
  58. _SpritesDisplay.elementHeight = AnimancerGUI.LineHeight * 3 + AnimancerGUI.StandardSpacing * 2;
  59. }
  60. /************************************************************************************************************************/
  61. /// <inheritdoc/>
  62. public override void OnSelectionChanged()
  63. {
  64. base.OnSelectionChanged();
  65. DirtyNames();
  66. }
  67. /************************************************************************************************************************/
  68. /// <summary>Refreshes the <see cref="_GeneratedNames"/>.</summary>
  69. private void UpdateNames()
  70. {
  71. if (!_NamesAreDirty)
  72. return;
  73. _NamesAreDirty = false;
  74. var sprites = Sprites;
  75. AnimancerEditorUtilities.SetCount(_ManualNames, sprites.Count);
  76. AnimancerEditorUtilities.SetCount(_GeneratedNames, sprites.Count);
  77. string name = null;
  78. string digitFormat = null;
  79. int index = 0;
  80. for (int i = 0; i < sprites.Count; i++)
  81. {
  82. var newName = _ManualNames[i];
  83. if (!string.IsNullOrWhiteSpace(newName))
  84. {
  85. name = newName;
  86. index = 0;
  87. var nextNameIndex = IndexOfNextManualName(i);
  88. var digits = Mathf.FloorToInt(Mathf.Log10(nextNameIndex - i)) + 1;
  89. if (digits < _MinimumDigits)
  90. digits = _MinimumDigits;
  91. var formatCharacters = new char[digits];
  92. for (int iDigit = 0; iDigit < digits; iDigit++)
  93. formatCharacters[iDigit] = '0';
  94. digitFormat = new string(formatCharacters);
  95. }
  96. _GeneratedNames[i] = string.IsNullOrWhiteSpace(name)
  97. ? sprites[i].name
  98. : name + (index + _FirstIndex).ToString(digitFormat);
  99. index++;
  100. }
  101. }
  102. /************************************************************************************************************************/
  103. private int IndexOfNextManualName(int startIndex)
  104. {
  105. for (int i = startIndex + 1; i < _ManualNames.Count; i++)
  106. if (!string.IsNullOrWhiteSpace(_ManualNames[i]))
  107. return i;
  108. return _ManualNames.Count;
  109. }
  110. /************************************************************************************************************************/
  111. /// <inheritdoc/>
  112. public override void DoBodyGUI()
  113. {
  114. base.DoBodyGUI();
  115. #if ! UNITY_2D_SPRITE
  116. EditorGUILayout.HelpBox(
  117. "Without the 2D Sprite Package," +
  118. " any references to the renamed sprites will be lost (including animations).",
  119. MessageType.Warning);
  120. #endif
  121. AnimancerToolsWindow.BeginChangeCheck();
  122. var firstIndex = EditorGUILayout.IntField("First Index", _FirstIndex);
  123. if (AnimancerToolsWindow.EndChangeCheck(ref _FirstIndex, Mathf.Max(firstIndex, 0)))
  124. DirtyNames();
  125. AnimancerToolsWindow.BeginChangeCheck();
  126. var digits = EditorGUILayout.IntField("Minimum Digits", _MinimumDigits);
  127. if (AnimancerToolsWindow.EndChangeCheck(ref _MinimumDigits, Mathf.Max(digits, 1)))
  128. DirtyNames();
  129. UpdateNames();
  130. _SpritesDisplay.DoLayoutList();
  131. GUILayout.BeginHorizontal();
  132. {
  133. GUILayout.FlexibleSpace();
  134. GUI.enabled = HasAnyNames();
  135. if (GUILayout.Button("Clear"))
  136. {
  137. AnimancerGUI.Deselect();
  138. AnimancerToolsWindow.RecordUndo();
  139. _ManualNames.Clear();
  140. DirtyNames();
  141. }
  142. GUI.enabled = HasAnyDifferentNames();
  143. if (GUILayout.Button("Apply"))
  144. {
  145. AnimancerGUI.Deselect();
  146. AskAndApply();
  147. }
  148. }
  149. GUILayout.EndHorizontal();
  150. }
  151. /************************************************************************************************************************/
  152. private void DrawItem(Rect area, int index, bool isActive, bool isFocused)
  153. {
  154. var sprites = Sprites;
  155. var sprite = sprites[index];
  156. var thumbnailWidth = Math.Min(area.height, area.width * 0.5f);
  157. var thumbnailArea = AnimancerGUI.StealFromLeft(ref area, thumbnailWidth, AnimancerGUI.StandardSpacing);
  158. AnimancerGUI.DrawSprite(thumbnailArea, sprite);
  159. area.y += (AnimancerGUI.LineHeight + AnimancerGUI.StandardSpacing) * 0.5f;
  160. area.height = AnimancerGUI.LineHeight;
  161. sprites[index] = DrawSpriteField(area, sprite);
  162. AnimancerGUI.NextVerticalArea(ref area);
  163. DrawName(area, index);
  164. }
  165. /************************************************************************************************************************/
  166. private Sprite DrawSpriteField(Rect area, Sprite sprite)
  167. => AnimancerGUI.DoObjectFieldGUI(area, "", sprite, false);
  168. /************************************************************************************************************************/
  169. private static GUIStyle _TextFieldStyle;
  170. private void DrawName(Rect area, int index)
  171. {
  172. area.y += 1;
  173. area.height = AnimancerGUI.LineHeight;
  174. var manualName = _ManualNames[index];
  175. var generatedName = _GeneratedNames[index];
  176. if (Event.current.type == EventType.Repaint)
  177. {
  178. _TextFieldStyle ??= new(EditorStyles.textField);
  179. _TextFieldStyle.fontStyle = string.IsNullOrWhiteSpace(manualName)
  180. ? FontStyle.Italic
  181. : FontStyle.Bold;
  182. GUI.TextField(area, generatedName, _TextFieldStyle);
  183. }
  184. else
  185. {
  186. EditorGUI.BeginChangeCheck();
  187. _ManualNames[index] = GUI.TextField(area, manualName);
  188. if (EditorGUI.EndChangeCheck())
  189. DirtyNames();
  190. }
  191. }
  192. /************************************************************************************************************************/
  193. private bool HasAnyNames()
  194. {
  195. var sprites = Sprites;
  196. for (int i = 0; i < sprites.Count; i++)
  197. if (!string.IsNullOrWhiteSpace(_ManualNames[i]))
  198. return true;
  199. return false;
  200. }
  201. private bool HasAnyDifferentNames()
  202. {
  203. var sprites = Sprites;
  204. for (int i = 0; i < sprites.Count; i++)
  205. if (sprites[i].name != _GeneratedNames[i])
  206. return true;
  207. return false;
  208. }
  209. /************************************************************************************************************************/
  210. private void DirtyNames()
  211. => _NamesAreDirty = true;
  212. /************************************************************************************************************************/
  213. /// <inheritdoc/>
  214. protected override string AreYouSure =>
  215. "Are you sure you want to rename these Sprites?"
  216. #if UNITY_2D_SPRITE
  217. ;
  218. #else
  219. + "\n\nAny references to the renamed Sprites will be lost (including animations that use them)."
  220. + " This can be avoided by importing Unity's 2D Sprite Package before using this tool.";
  221. #endif
  222. /************************************************************************************************************************/
  223. private static Dictionary<Sprite, string> _SpriteToName;
  224. /// <inheritdoc/>
  225. protected override void BeforeApply()
  226. {
  227. if (_SpriteToName == null)
  228. _SpriteToName = new();
  229. else
  230. _SpriteToName.Clear();
  231. var sprites = Sprites;
  232. for (int i = 0; i < sprites.Count; i++)
  233. {
  234. _SpriteToName.Add(sprites[i], _GeneratedNames[i]);
  235. }
  236. // Renaming selected Sprites will lose the selection without triggering OnSelectionChanged.
  237. EditorApplication.delayCall += OnSelectionChanged;
  238. }
  239. /************************************************************************************************************************/
  240. /// <inheritdoc/>
  241. protected override void Modify(SpriteDataEditor data, int index, Sprite sprite)
  242. {
  243. data.SetName(index, _SpriteToName[sprite]);
  244. }
  245. /************************************************************************************************************************/
  246. /// <inheritdoc/>
  247. protected override void Modify(TextureImporter importer, List<Sprite> sprites)
  248. {
  249. if (sprites.Count == 1 && importer.spriteImportMode != SpriteImportMode.Multiple)
  250. {
  251. var sprite = sprites[0];
  252. var fileName = Path.GetFileNameWithoutExtension(importer.assetPath);
  253. if (fileName == sprite.name)
  254. {
  255. AssetDatabase.RenameAsset(importer.assetPath, _SpriteToName[sprite]);
  256. sprites.Clear();
  257. }
  258. }
  259. base.Modify(importer, sprites);
  260. }
  261. /************************************************************************************************************************/
  262. /// <inheritdoc/>
  263. protected override void AfterApply()
  264. {
  265. base.AfterApply();
  266. AnimancerToolsWindow.RecordUndo();
  267. _ManualNames.Clear();
  268. }
  269. /************************************************************************************************************************/
  270. }
  271. }
  272. #endif