TMP_EditorUtility.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System.Text;
  4. using System.IO;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. namespace TMPro.EditorUtilities
  8. {
  9. public static class TMP_EditorUtility
  10. {
  11. /// <summary>
  12. /// Returns the relative path of the package.
  13. /// </summary>
  14. public static string packageRelativePath
  15. {
  16. get
  17. {
  18. if (string.IsNullOrEmpty(m_PackagePath))
  19. m_PackagePath = GetPackageRelativePath();
  20. return m_PackagePath;
  21. }
  22. }
  23. [SerializeField]
  24. private static string m_PackagePath;
  25. /// <summary>
  26. /// Returns the fully qualified path of the package.
  27. /// </summary>
  28. public static string packageFullPath
  29. {
  30. get
  31. {
  32. if (string.IsNullOrEmpty(m_PackageFullPath))
  33. m_PackageFullPath = GetPackageFullPath();
  34. return m_PackageFullPath;
  35. }
  36. }
  37. [SerializeField]
  38. private static string m_PackageFullPath;
  39. // Static Fields Related to locating the TextMesh Pro Asset
  40. private static string folderPath = "Not Found";
  41. private static EditorWindow Gameview;
  42. private static bool isInitialized = false;
  43. private static void GetGameview()
  44. {
  45. System.Reflection.Assembly assembly = typeof(UnityEditor.EditorWindow).Assembly;
  46. System.Type type = assembly.GetType("UnityEditor.GameView");
  47. Gameview = EditorWindow.GetWindow(type);
  48. }
  49. public static void RepaintAll()
  50. {
  51. if (isInitialized == false)
  52. {
  53. GetGameview();
  54. isInitialized = true;
  55. }
  56. SceneView.RepaintAll();
  57. Gameview.Repaint();
  58. }
  59. /// <summary>
  60. /// Create and return a new asset in a smart location based on the current selection and then select it.
  61. /// </summary>
  62. /// <param name="name">
  63. /// Name of the new asset. Do not include the .asset extension.
  64. /// </param>
  65. /// <returns>
  66. /// The new asset.
  67. /// </returns>
  68. public static T CreateAsset<T>(string name) where T : ScriptableObject
  69. {
  70. string path = AssetDatabase.GetAssetPath(Selection.activeObject);
  71. if (path.Length == 0)
  72. {
  73. // no asset selected, place in asset root
  74. path = "Assets/" + name + ".asset";
  75. }
  76. else if (Directory.Exists(path))
  77. {
  78. // place in currently selected directory
  79. path += "/" + name + ".asset";
  80. }
  81. else {
  82. // place in current selection's containing directory
  83. path = Path.GetDirectoryName(path) + "/" + name + ".asset";
  84. }
  85. T asset = ScriptableObject.CreateInstance<T>();
  86. AssetDatabase.CreateAsset(asset, AssetDatabase.GenerateUniqueAssetPath(path));
  87. EditorUtility.FocusProjectWindow();
  88. Selection.activeObject = asset;
  89. return asset;
  90. }
  91. // Function used to find all materials which reference a font atlas so we can update all their references.
  92. public static Material[] FindMaterialReferences(TMP_FontAsset fontAsset)
  93. {
  94. List<Material> refs = new List<Material>();
  95. Material mat = fontAsset.material;
  96. refs.Add(mat);
  97. // Get materials matching the search pattern.
  98. string searchPattern = "t:Material" + " " + fontAsset.name.Split(new char[] { ' ' })[0];
  99. string[] materialAssetGUIDs = AssetDatabase.FindAssets(searchPattern);
  100. for (int i = 0; i < materialAssetGUIDs.Length; i++)
  101. {
  102. string materialPath = AssetDatabase.GUIDToAssetPath(materialAssetGUIDs[i]);
  103. Material targetMaterial = AssetDatabase.LoadAssetAtPath<Material>(materialPath);
  104. if (targetMaterial.HasProperty(ShaderUtilities.ID_MainTex) && targetMaterial.GetTexture(ShaderUtilities.ID_MainTex) != null && mat.GetTexture(ShaderUtilities.ID_MainTex) != null && targetMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() == mat.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
  105. {
  106. if (!refs.Contains(targetMaterial))
  107. refs.Add(targetMaterial);
  108. }
  109. else
  110. {
  111. // TODO: Find a more efficient method to unload resources.
  112. //Resources.UnloadAsset(targetMaterial.GetTexture(ShaderUtilities.ID_MainTex));
  113. }
  114. }
  115. return refs.ToArray();
  116. }
  117. // Function used to find the Font Asset which matches the given Material Preset and Font Atlas Texture.
  118. public static TMP_FontAsset FindMatchingFontAsset(Material mat)
  119. {
  120. if (mat.GetTexture(ShaderUtilities.ID_MainTex) == null) return null;
  121. // Find the dependent assets of this material.
  122. string[] dependentAssets = AssetDatabase.GetDependencies(AssetDatabase.GetAssetPath(mat), false);
  123. for (int i = 0; i < dependentAssets.Length; i++)
  124. {
  125. TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath<TMP_FontAsset>(dependentAssets[i]);
  126. if (fontAsset != null)
  127. return fontAsset;
  128. }
  129. return null;
  130. }
  131. private static string GetPackageRelativePath()
  132. {
  133. // Check for potential UPM package
  134. string packagePath = Path.GetFullPath("Packages/com.unity.textmeshpro");
  135. if (Directory.Exists(packagePath))
  136. {
  137. return "Packages/com.unity.textmeshpro";
  138. }
  139. packagePath = Path.GetFullPath("Assets/..");
  140. if (Directory.Exists(packagePath))
  141. {
  142. // Search default location for development package
  143. if (Directory.Exists(packagePath + "/Assets/Packages/com.unity.TextMeshPro/Editor Resources"))
  144. {
  145. return "Assets/Packages/com.unity.TextMeshPro";
  146. }
  147. // Search for default location of normal TextMesh Pro AssetStore package
  148. if (Directory.Exists(packagePath + "/Assets/TextMesh Pro/Editor Resources"))
  149. {
  150. return "Assets/TextMesh Pro";
  151. }
  152. // Search for potential alternative locations in the user project
  153. string[] matchingPaths = Directory.GetDirectories(packagePath, "TextMesh Pro", SearchOption.AllDirectories);
  154. packagePath = ValidateLocation(matchingPaths, packagePath);
  155. if (packagePath != null) return packagePath;
  156. }
  157. return null;
  158. }
  159. private static string GetPackageFullPath()
  160. {
  161. // Check for potential UPM package
  162. string packagePath = Path.GetFullPath("Packages/com.unity.textmeshpro");
  163. if (Directory.Exists(packagePath))
  164. {
  165. return packagePath;
  166. }
  167. packagePath = Path.GetFullPath("Assets/..");
  168. if (Directory.Exists(packagePath))
  169. {
  170. // Search default location for development package
  171. if (Directory.Exists(packagePath + "/Assets/Packages/com.unity.TextMeshPro/Editor Resources"))
  172. {
  173. return packagePath + "/Assets/Packages/com.unity.TextMeshPro";
  174. }
  175. // Search for default location of normal TextMesh Pro AssetStore package
  176. if (Directory.Exists(packagePath + "/Assets/TextMesh Pro/Editor Resources"))
  177. {
  178. return packagePath + "/Assets/TextMesh Pro";
  179. }
  180. // Search for potential alternative locations in the user project
  181. string[] matchingPaths = Directory.GetDirectories(packagePath, "TextMesh Pro", SearchOption.AllDirectories);
  182. string path = ValidateLocation(matchingPaths, packagePath);
  183. if (path != null) return packagePath + path;
  184. }
  185. return null;
  186. }
  187. /// <summary>
  188. /// Method to validate the location of the asset folder by making sure the GUISkins folder exists.
  189. /// </summary>
  190. /// <param name="paths"></param>
  191. /// <returns></returns>
  192. private static string ValidateLocation(string[] paths, string projectPath)
  193. {
  194. for (int i = 0; i < paths.Length; i++)
  195. {
  196. // Check if any of the matching directories contain a GUISkins directory.
  197. if (Directory.Exists(paths[i] + "/Editor Resources"))
  198. {
  199. folderPath = paths[i].Replace(projectPath, "");
  200. folderPath = folderPath.TrimStart('\\', '/');
  201. return folderPath;
  202. }
  203. }
  204. return null;
  205. }
  206. /// <summary>
  207. /// Function which returns a string containing a sequence of Decimal character ranges.
  208. /// </summary>
  209. /// <param name="characterSet"></param>
  210. /// <returns></returns>
  211. public static string GetDecimalCharacterSequence(int[] characterSet)
  212. {
  213. if (characterSet == null || characterSet.Length == 0)
  214. return string.Empty;
  215. string characterSequence = string.Empty;
  216. int count = characterSet.Length;
  217. int first = characterSet[0];
  218. int last = first;
  219. for (int i = 1; i < count; i++)
  220. {
  221. if (characterSet[i - 1] + 1 == characterSet[i])
  222. {
  223. last = characterSet[i];
  224. }
  225. else
  226. {
  227. if (first == last)
  228. characterSequence += first + ",";
  229. else
  230. characterSequence += first + "-" + last + ",";
  231. first = last = characterSet[i];
  232. }
  233. }
  234. // handle the final group
  235. if (first == last)
  236. characterSequence += first;
  237. else
  238. characterSequence += first + "-" + last;
  239. return characterSequence;
  240. }
  241. /// <summary>
  242. /// Function which returns a string containing a sequence of Unicode (Hex) character ranges.
  243. /// </summary>
  244. /// <param name="characterSet"></param>
  245. /// <returns></returns>
  246. public static string GetUnicodeCharacterSequence(int[] characterSet)
  247. {
  248. if (characterSet == null || characterSet.Length == 0)
  249. return string.Empty;
  250. string characterSequence = string.Empty;
  251. int count = characterSet.Length;
  252. int first = characterSet[0];
  253. int last = first;
  254. for (int i = 1; i < count; i++)
  255. {
  256. if (characterSet[i - 1] + 1 == characterSet[i])
  257. {
  258. last = characterSet[i];
  259. }
  260. else
  261. {
  262. if (first == last)
  263. characterSequence += first.ToString("X2") + ",";
  264. else
  265. characterSequence += first.ToString("X2") + "-" + last.ToString("X2") + ",";
  266. first = last = characterSet[i];
  267. }
  268. }
  269. // handle the final group
  270. if (first == last)
  271. characterSequence += first.ToString("X2");
  272. else
  273. characterSequence += first.ToString("X2") + "-" + last.ToString("X2");
  274. return characterSequence;
  275. }
  276. /// <summary>
  277. ///
  278. /// </summary>
  279. /// <param name="rect"></param>
  280. /// <param name="thickness"></param>
  281. /// <param name="color"></param>
  282. public static void DrawBox(Rect rect, float thickness, Color color)
  283. {
  284. EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + thickness, rect.width + thickness * 2, thickness), color);
  285. EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + thickness, thickness, rect.height - thickness * 2), color);
  286. EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + rect.height - thickness * 2, rect.width + thickness * 2, thickness), color);
  287. EditorGUI.DrawRect(new Rect(rect.x + rect.width, rect.y + thickness, thickness, rect.height - thickness * 2), color);
  288. }
  289. /// <summary>
  290. /// Function to return the horizontal alignment grid value.
  291. /// </summary>
  292. /// <param name="value"></param>
  293. /// <returns></returns>
  294. public static int GetHorizontalAlignmentGridValue(int value)
  295. {
  296. if ((value & 0x1) == 0x1)
  297. return 0;
  298. else if ((value & 0x2) == 0x2)
  299. return 1;
  300. else if ((value & 0x4) == 0x4)
  301. return 2;
  302. else if ((value & 0x8) == 0x8)
  303. return 3;
  304. else if ((value & 0x10) == 0x10)
  305. return 4;
  306. else if ((value & 0x20) == 0x20)
  307. return 5;
  308. return 0;
  309. }
  310. /// <summary>
  311. /// Function to return the vertical alignment grid value.
  312. /// </summary>
  313. /// <param name="value"></param>
  314. /// <returns></returns>
  315. public static int GetVerticalAlignmentGridValue(int value)
  316. {
  317. if ((value & 0x100) == 0x100)
  318. return 0;
  319. if ((value & 0x200) == 0x200)
  320. return 1;
  321. if ((value & 0x400) == 0x400)
  322. return 2;
  323. if ((value & 0x800) == 0x800)
  324. return 3;
  325. if ((value & 0x1000) == 0x1000)
  326. return 4;
  327. if ((value & 0x2000) == 0x2000)
  328. return 5;
  329. return 0;
  330. }
  331. public static void DrawColorProperty(Rect rect, SerializedProperty property)
  332. {
  333. int oldIndent = EditorGUI.indentLevel;
  334. EditorGUI.indentLevel = 0;
  335. if (EditorGUIUtility.wideMode)
  336. {
  337. EditorGUI.PropertyField(new Rect(rect.x, rect.y, 50f, rect.height), property, GUIContent.none);
  338. rect.x += 50f;
  339. rect.width = Mathf.Min(100f, rect.width - 55f);
  340. }
  341. else
  342. {
  343. rect.height /= 2f;
  344. rect.width = Mathf.Min(100f, rect.width - 5f);
  345. EditorGUI.PropertyField(rect, property, GUIContent.none);
  346. rect.y += rect.height;
  347. }
  348. EditorGUI.BeginChangeCheck();
  349. string colorString = EditorGUI.TextField(rect, string.Format("#{0}", ColorUtility.ToHtmlStringRGBA(property.colorValue)));
  350. if (EditorGUI.EndChangeCheck())
  351. {
  352. if (ColorUtility.TryParseHtmlString(colorString, out Color color))
  353. {
  354. property.colorValue = color;
  355. }
  356. }
  357. EditorGUI.indentLevel = oldIndent;
  358. }
  359. public static bool EditorToggle(Rect position, bool value, GUIContent content, GUIStyle style)
  360. {
  361. var id = GUIUtility.GetControlID(content, FocusType.Keyboard, position);
  362. var evt = Event.current;
  363. // Toggle selected toggle on space or return key
  364. if (GUIUtility.keyboardControl == id && evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Space || evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter))
  365. {
  366. value = !value;
  367. evt.Use();
  368. GUI.changed = true;
  369. }
  370. if (evt.type == EventType.MouseDown && position.Contains(Event.current.mousePosition))
  371. {
  372. GUIUtility.keyboardControl = id;
  373. EditorGUIUtility.editingTextField = false;
  374. HandleUtility.Repaint();
  375. }
  376. return GUI.Toggle(position, id, value, content, style);
  377. }
  378. }
  379. }