EditorHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System.Collections.Generic;
  4. //-----------------------------------------------------------------------------
  5. // Copyright 2015-2021 RenderHeads Ltd. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. namespace RenderHeads.Media.AVProVideo.Editor
  8. {
  9. /// <summary>
  10. /// Helper methods for editor components
  11. /// </summary>
  12. public static class EditorHelper
  13. {
  14. /// <summary>
  15. /// Loads from EditorPrefs, converts a CSV string to List<string> and returns it
  16. /// </summary>
  17. internal static List<string> GetEditorPrefsToStringList(string key, char separator = ';')
  18. {
  19. string items = EditorPrefs.GetString(key, string.Empty);
  20. return new List<string>(items.Split(new char[] { separator }, System.StringSplitOptions.RemoveEmptyEntries));
  21. }
  22. /// <summary>
  23. /// Converts a List<string> into a CSV string and saves it in EditorPrefs
  24. /// </summary>
  25. internal static void SetEditorPrefsFromStringList(string key, List<string> items, char separator = ';')
  26. {
  27. string value = string.Empty;
  28. if (items != null && items.Count > 0)
  29. {
  30. value = string.Join(separator.ToString(), items.ToArray());
  31. }
  32. EditorPrefs.SetString(key, value);
  33. }
  34. public static SerializedProperty CheckFindProperty(this UnityEditor.Editor editor, string propertyName)
  35. {
  36. SerializedProperty result = editor.serializedObject.FindProperty(propertyName);
  37. Debug.Assert(result != null, "Missing property: " + propertyName);
  38. return result;
  39. }
  40. /// <summary>
  41. /// Only lets the property if the proposed path doesn't contain invalid characters
  42. /// Also changes all backslash characters to forwardslash for better cross-platform compatability
  43. /// </summary>
  44. internal static bool SafeSetPathProperty(string path, SerializedProperty property)
  45. {
  46. bool result = false;
  47. if (path == null)
  48. {
  49. path = string.Empty;
  50. }
  51. else if (path.IndexOfAny(System.IO.Path.GetInvalidPathChars()) < 0)
  52. {
  53. path = path.Replace("\\", "/");
  54. }
  55. if (path.StartsWith("//"))
  56. {
  57. path = path.Substring(2);
  58. }
  59. if (path != property.stringValue)
  60. {
  61. property.stringValue = path;
  62. result = true;
  63. }
  64. return result;
  65. }
  66. /// <summary>
  67. /// Returns whether a define exists for a specific platform
  68. /// </summary>
  69. internal static bool HasScriptDefine(string define, BuildTargetGroup buildTarget = BuildTargetGroup.Unknown)
  70. {
  71. if (buildTarget == BuildTargetGroup.Unknown) { buildTarget = EditorUserBuildSettings.selectedBuildTargetGroup; }
  72. string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTarget);
  73. return defines.Contains(define);
  74. }
  75. /// <summary>
  76. /// Adds a define if it doesn't already exist for a specific platform
  77. /// </summary>
  78. internal static void AddScriptDefine(string define, BuildTargetGroup buildTarget = BuildTargetGroup.Unknown)
  79. {
  80. if (buildTarget == BuildTargetGroup.Unknown) { buildTarget = EditorUserBuildSettings.selectedBuildTargetGroup; }
  81. string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTarget);
  82. if (!defines.Contains(define))
  83. {
  84. defines += ";" + define + ";";
  85. PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTarget, defines);
  86. }
  87. }
  88. /// <summary>
  89. /// Removes a define if it exists for a specific platform
  90. /// </summary>
  91. internal static void RemoveScriptDefine(string define, BuildTargetGroup buildTarget = BuildTargetGroup.Unknown)
  92. {
  93. if (buildTarget == BuildTargetGroup.Unknown) { buildTarget = EditorUserBuildSettings.selectedBuildTargetGroup; }
  94. string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTarget);
  95. if (defines.Contains(define))
  96. {
  97. defines = defines.Replace(define, "");
  98. PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTarget, defines);
  99. }
  100. }
  101. /// <summary>
  102. /// Given a partial file path and MediaLocation, return a directory path suitable for a file browse dialog to start in
  103. /// </summary>
  104. internal static string GetBrowsableFolder(string path, MediaPathType fileLocation)
  105. {
  106. // Try to resolve based on file path + file location
  107. string result = Helper.GetFilePath(path, fileLocation);
  108. if (!string.IsNullOrEmpty(result))
  109. {
  110. if (System.IO.File.Exists(result))
  111. {
  112. result = System.IO.Path.GetDirectoryName(result);
  113. }
  114. }
  115. if (!System.IO.Directory.Exists(result))
  116. {
  117. // Just resolve on file location
  118. result = Helper.GetPath(fileLocation);
  119. }
  120. if (string.IsNullOrEmpty(result))
  121. {
  122. // Fallback
  123. result = Application.streamingAssetsPath;
  124. }
  125. return result;
  126. }
  127. internal static bool OpenMediaFileDialog(string startPath, ref MediaPath mediaPath, ref string fullPath, string extensions)
  128. {
  129. bool result = false;
  130. string path = UnityEditor.EditorUtility.OpenFilePanel("Browse Media File", startPath, extensions);
  131. if (!string.IsNullOrEmpty(path) && !path.EndsWith(".meta"))
  132. {
  133. mediaPath = GetMediaPathFromFullPath(path);
  134. result = true;
  135. }
  136. return result;
  137. }
  138. /*private static bool IsPathWithin(string fullPath, string targetPath)
  139. {
  140. return fullPath.StartsWith(targetPath);
  141. }*/
  142. private static string GetPathRelativeTo(string root, string fullPath)
  143. {
  144. string result = fullPath.Remove(0, root.Length);
  145. if (result.StartsWith(System.IO.Path.DirectorySeparatorChar.ToString()) || result.StartsWith(System.IO.Path.AltDirectorySeparatorChar.ToString()))
  146. {
  147. result = result.Remove(0, 1);
  148. }
  149. return result;
  150. }
  151. internal static MediaPath GetMediaPathFromFullPath(string fullPath)
  152. {
  153. MediaPath result = null;
  154. string projectRoot = System.IO.Path.GetFullPath(System.IO.Path.Combine(Application.dataPath, ".."));
  155. projectRoot = projectRoot.Replace('\\', '/');
  156. if (fullPath.StartsWith(projectRoot))
  157. {
  158. if (fullPath.StartsWith(Application.streamingAssetsPath))
  159. {
  160. // Must be StreamingAssets relative path
  161. result = new MediaPath(GetPathRelativeTo(Application.streamingAssetsPath, fullPath), MediaPathType.RelativeToStreamingAssetsFolder);
  162. }
  163. else if (fullPath.StartsWith(Application.dataPath))
  164. {
  165. // Must be Assets relative path
  166. result = new MediaPath(GetPathRelativeTo(Application.dataPath, fullPath), MediaPathType.RelativeToDataFolder);
  167. }
  168. else
  169. {
  170. // Must be project relative path
  171. result = new MediaPath(GetPathRelativeTo(projectRoot, fullPath), MediaPathType.RelativeToProjectFolder);
  172. }
  173. }
  174. else
  175. {
  176. // Must be persistant data
  177. if (fullPath.StartsWith(Application.persistentDataPath))
  178. {
  179. result = new MediaPath(GetPathRelativeTo(Application.persistentDataPath, fullPath), MediaPathType.RelativeToPersistentDataFolder);
  180. }
  181. // Must be absolute path
  182. result = new MediaPath(fullPath, MediaPathType.AbsolutePathOrURL);
  183. }
  184. return result;
  185. }
  186. internal class IMGUI
  187. {
  188. private static GUIStyle _copyableStyle = null;
  189. private static GUIStyle _wordWrappedTextAreaStyle = null;
  190. private static GUIStyle _rightAlignedLabelStyle = null;
  191. private static GUIStyle _centerAlignedLabelStyle = null;
  192. /// <summary>
  193. /// Displays an IMGUI warning text box inline
  194. /// </summary>
  195. internal static void WarningTextBox(string title, string body, Color bgColor, Color titleColor, Color bodyColor)
  196. {
  197. BeginWarningTextBox(title, body, bgColor, titleColor, bodyColor);
  198. EndWarningTextBox();
  199. }
  200. /// <summary>
  201. /// Displays an IMGUI warning text box inline
  202. /// </summary>
  203. internal static void BeginWarningTextBox(string title, string body, Color bgColor, Color titleColor, Color bodyColor)
  204. {
  205. GUI.backgroundColor = bgColor;
  206. EditorGUILayout.BeginVertical(GUI.skin.box);
  207. if (!string.IsNullOrEmpty(title))
  208. {
  209. GUI.color = titleColor;
  210. GUILayout.Label(title, EditorStyles.boldLabel);
  211. }
  212. if (!string.IsNullOrEmpty(body))
  213. {
  214. GUI.color = bodyColor;
  215. GUILayout.Label(body, EditorStyles.wordWrappedLabel);
  216. }
  217. }
  218. internal static void EndWarningTextBox()
  219. {
  220. EditorGUILayout.EndVertical();
  221. GUI.backgroundColor = Color.white;
  222. GUI.color = Color.white;
  223. }
  224. /// <summary>
  225. /// Displays an IMGUI box containing a copyable string that wraps
  226. /// Usedful for very long strings eg file paths/urls
  227. /// </summary>
  228. internal static void CopyableFilename(string path)
  229. {
  230. // The box disappars unless it has some content
  231. if (string.IsNullOrEmpty(path))
  232. {
  233. path = " ";
  234. }
  235. // Display the file name so it's easy to read and copy to the clipboard
  236. if (!string.IsNullOrEmpty(path) && 0 > path.IndexOfAny(System.IO.Path.GetInvalidPathChars()))
  237. {
  238. // Some GUI hacks here because SelectableLabel wants to be double height and it doesn't want to be centered because it's an EditorGUILayout function...
  239. string text = System.IO.Path.GetFileName(path);
  240. if (_copyableStyle == null)
  241. {
  242. _copyableStyle = new GUIStyle(EditorStyles.wordWrappedLabel);
  243. _copyableStyle.fontStyle = FontStyle.Bold;
  244. _copyableStyle.stretchWidth = true;
  245. _copyableStyle.stretchHeight = true;
  246. _copyableStyle.alignment = TextAnchor.MiddleCenter;
  247. _copyableStyle.margin.top = 8;
  248. _copyableStyle.margin.bottom = 16;
  249. }
  250. float height = _copyableStyle.CalcHeight(new GUIContent(text), Screen.width)*1.5f;
  251. EditorGUILayout.SelectableLabel(text, _copyableStyle, GUILayout.Height(height), GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(true));
  252. }
  253. }
  254. /// <summary>
  255. /// </summary>
  256. internal static GUIStyle GetWordWrappedTextAreaStyle()
  257. {
  258. if (_wordWrappedTextAreaStyle == null)
  259. {
  260. _wordWrappedTextAreaStyle = new GUIStyle(EditorStyles.textArea);
  261. _wordWrappedTextAreaStyle.wordWrap = true;
  262. }
  263. return _wordWrappedTextAreaStyle;
  264. }
  265. internal static GUIStyle GetRightAlignedLabelStyle()
  266. {
  267. if (_rightAlignedLabelStyle == null)
  268. {
  269. _rightAlignedLabelStyle = new GUIStyle(GUI.skin.label);
  270. _rightAlignedLabelStyle.alignment = TextAnchor.UpperRight;
  271. }
  272. return _rightAlignedLabelStyle;
  273. }
  274. internal static GUIStyle GetCenterAlignedLabelStyle()
  275. {
  276. if (_centerAlignedLabelStyle == null)
  277. {
  278. _centerAlignedLabelStyle = new GUIStyle(GUI.skin.label);
  279. _centerAlignedLabelStyle.alignment = TextAnchor.MiddleCenter;
  280. }
  281. return _centerAlignedLabelStyle;
  282. }
  283. /// <summary>
  284. /// Displays IMGUI box in red/yellow for errors/warnings
  285. /// </summary>
  286. internal static void NoticeBox(MessageType messageType, string message)
  287. {
  288. //GUI.backgroundColor = Color.yellow;
  289. //EditorGUILayout.HelpBox(message, messageType);
  290. switch (messageType)
  291. {
  292. case MessageType.Error:
  293. GUI.color = Color.red;
  294. message = "Error: " + message;
  295. break;
  296. case MessageType.Warning:
  297. GUI.color = Color.yellow;
  298. message = "Warning: " + message;
  299. break;
  300. }
  301. //GUI.color = Color.yellow;
  302. GUILayout.TextArea(message);
  303. GUI.color = Color.white;
  304. }
  305. /// <summary>
  306. /// Displays IMGUI text centered horizontally
  307. /// </summary>
  308. internal static void CentreLabel(string text, GUIStyle style = null)
  309. {
  310. GUILayout.BeginHorizontal();
  311. GUILayout.FlexibleSpace();
  312. if (style == null)
  313. {
  314. GUILayout.Label(text);
  315. }
  316. else
  317. {
  318. GUILayout.Label(text, style);
  319. }
  320. GUILayout.FlexibleSpace();
  321. GUILayout.EndHorizontal();
  322. }
  323. internal static bool ToggleScriptDefine(string label, string define)
  324. {
  325. EditorGUI.BeginChangeCheck();
  326. bool isEnabled = EditorGUILayout.Toggle(label, EditorHelper.HasScriptDefine(define));
  327. if (EditorGUI.EndChangeCheck())
  328. {
  329. if (isEnabled)
  330. {
  331. EditorHelper.AddScriptDefine(define);
  332. }
  333. else
  334. {
  335. EditorHelper.RemoveScriptDefine(define);
  336. }
  337. }
  338. return isEnabled;
  339. }
  340. }
  341. }
  342. internal class HorizontalFlowScope : GUI.Scope
  343. {
  344. private float _windowWidth;
  345. private float _width;
  346. public HorizontalFlowScope(int windowWidth)
  347. {
  348. _windowWidth = windowWidth;
  349. _width = _windowWidth;
  350. GUILayout.BeginHorizontal();
  351. }
  352. protected override void CloseScope()
  353. {
  354. GUILayout.EndHorizontal();
  355. }
  356. public void AddItem(GUIContent content, GUIStyle style)
  357. {
  358. _width -= style.CalcSize(content).x + style.padding.horizontal;
  359. if (_width <= 0f)
  360. {
  361. _width += Screen.width;
  362. GUILayout.EndHorizontal();
  363. GUILayout.BeginHorizontal();
  364. }
  365. }
  366. }
  367. }