EditorHelper.cs 12 KB

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