InspectableObject.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System.Collections.Generic;
  4. using System;
  5. using System.Reflection;
  6. using BansheeEngine;
  7. namespace BansheeEditor
  8. {
  9. /** @addtogroup Inspector
  10. * @{
  11. */
  12. /// <summary>
  13. /// Displays GUI for a serializable property containing a generic object. Inspectable object fields are displayed
  14. /// in separate rows.
  15. /// </summary>
  16. public class InspectableObject : InspectableField
  17. {
  18. private const int IndentAmount = 5;
  19. private object propertyValue;
  20. private List<InspectableField> children = new List<InspectableField>();
  21. private InspectableFieldStyleInfo style;
  22. private GUILayoutY guiLayout;
  23. private GUILayoutX guiChildLayout;
  24. private GUILayoutX guiTitleLayout;
  25. private GUILayoutX guiInternalTitleLayout;
  26. private GUIButton guiCreateBtn;
  27. private ContextMenu createContextMenu;
  28. private bool isExpanded;
  29. private bool forceUpdate = true;
  30. private State state;
  31. private Type[] instantiableTypes;
  32. /// <summary>
  33. /// Creates a new inspectable array GUI for the specified property.
  34. /// </summary>
  35. /// <param name="parent">Parent Inspector this field belongs to.</param>
  36. /// <param name="title">Name of the property, or some other value to set as the title.</param>
  37. /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param>
  38. /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may
  39. /// contain other fields, in which case you should increase this value by one.</param>
  40. /// <param name="layout">Parent layout that all the field elements will be added to.</param>
  41. /// <param name="property">Serializable property referencing the object whose contents to display.</param>
  42. /// <param name="style">Information that can be used for customizing field rendering and behaviour.</param>
  43. public InspectableObject(Inspector parent, string title, string path, int depth, InspectableFieldLayout layout,
  44. SerializableProperty property, InspectableFieldStyleInfo style)
  45. : base(parent, title, path, SerializableProperty.FieldType.Object, depth, layout, property)
  46. {
  47. this.style = style;
  48. isExpanded = parent.Persistent.GetBool(path + "_Expanded");
  49. // Builds a context menu that lets the user create objects to assign to this field.
  50. instantiableTypes = GetInstantiableTypes(property.InternalType);
  51. if (instantiableTypes.Length > 1)
  52. {
  53. createContextMenu = new ContextMenu();
  54. Array.Sort(instantiableTypes, (x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));
  55. bool showNamespace = false;
  56. string ns = instantiableTypes[0].Namespace;
  57. for (int i = 1; i < instantiableTypes.Length; i++)
  58. {
  59. if (instantiableTypes[i].Namespace != ns)
  60. {
  61. showNamespace = true;
  62. break;
  63. }
  64. }
  65. foreach (var type in instantiableTypes)
  66. {
  67. string prefix = "";
  68. if (showNamespace)
  69. prefix = type.Namespace + ".";
  70. createContextMenu.AddItem(prefix + type.Name, () => property.SetValue(Activator.CreateInstance(type)));
  71. }
  72. }
  73. }
  74. /// <inheritdoc/>
  75. public override GUILayoutX GetTitleLayout()
  76. {
  77. return guiTitleLayout;
  78. }
  79. /// <inheritdoc/>
  80. public override InspectableState Refresh(int layoutIndex)
  81. {
  82. // Check if modified internally and rebuild if needed
  83. object newPropertyValue = property.GetValue<object>();
  84. if (forceUpdate)
  85. {
  86. propertyValue = newPropertyValue;
  87. BuildGUI(layoutIndex);
  88. forceUpdate = false;
  89. }
  90. else if (propertyValue == null && newPropertyValue != null)
  91. {
  92. propertyValue = newPropertyValue;
  93. BuildGUI(layoutIndex);
  94. }
  95. else if (newPropertyValue == null && propertyValue != null)
  96. {
  97. propertyValue = null;
  98. BuildGUI(layoutIndex);
  99. }
  100. InspectableState state = InspectableState.NotModified;
  101. int currentIndex = 0;
  102. for (int i = 0; i < children.Count; i++)
  103. {
  104. state |= children[i].Refresh(currentIndex);
  105. currentIndex += children[i].GetNumLayoutElements();
  106. }
  107. return state;
  108. }
  109. /// <summary>
  110. /// Rebuilds the GUI object header if needed.
  111. /// </summary>
  112. /// <param name="layoutIndex">Index at which to insert the GUI elements.</param>
  113. protected void BuildGUI(int layoutIndex)
  114. {
  115. Action BuildEmptyGUI = () =>
  116. {
  117. guiInternalTitleLayout = guiTitleLayout.InsertLayoutX(0);
  118. guiInternalTitleLayout.AddElement(new GUILabel(title));
  119. guiInternalTitleLayout.AddElement(new GUILabel("Empty", GUIOption.FixedWidth(100)));
  120. if (!property.IsValueType)
  121. {
  122. GUIContent createIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Create),
  123. new LocEdString("Create"));
  124. guiCreateBtn = new GUIButton(createIcon, GUIOption.FixedWidth(30));
  125. guiCreateBtn.OnClick += OnCreateButtonClicked;
  126. guiInternalTitleLayout.AddElement(guiCreateBtn);
  127. }
  128. };
  129. Action BuildFilledGUI = () =>
  130. {
  131. guiInternalTitleLayout = guiTitleLayout.InsertLayoutX(0);
  132. GUIToggle guiFoldout = new GUIToggle(title, EditorStyles.Foldout);
  133. guiFoldout.Value = isExpanded;
  134. guiFoldout.AcceptsKeyFocus = false;
  135. guiFoldout.OnToggled += OnFoldoutToggled;
  136. guiInternalTitleLayout.AddElement(guiFoldout);
  137. if (!style.StyleFlags.HasFlag(InspectableFieldStyleFlags.NotNull))
  138. {
  139. GUIContent clearIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Clear),
  140. new LocEdString("Clear"));
  141. GUIButton clearBtn = new GUIButton(clearIcon, GUIOption.FixedWidth(20));
  142. clearBtn.OnClick += OnClearButtonClicked;
  143. guiInternalTitleLayout.AddElement(clearBtn);
  144. }
  145. if (isExpanded)
  146. {
  147. SerializableObject serializableObject = property.GetObject();
  148. SerializableField[] fields = serializableObject.Fields;
  149. if (fields.Length > 0)
  150. {
  151. guiChildLayout = guiLayout.AddLayoutX();
  152. guiChildLayout.AddSpace(IndentAmount);
  153. GUIPanel guiContentPanel = guiChildLayout.AddPanel();
  154. GUILayoutX guiIndentLayoutX = guiContentPanel.AddLayoutX();
  155. guiIndentLayoutX.AddSpace(IndentAmount);
  156. GUILayoutY guiIndentLayoutY = guiIndentLayoutX.AddLayoutY();
  157. guiIndentLayoutY.AddSpace(IndentAmount);
  158. GUILayoutY guiContentLayout = guiIndentLayoutY.AddLayoutY();
  159. guiIndentLayoutY.AddSpace(IndentAmount);
  160. guiIndentLayoutX.AddSpace(IndentAmount);
  161. guiChildLayout.AddSpace(IndentAmount);
  162. short backgroundDepth = (short) (Inspector.START_BACKGROUND_DEPTH - depth - 1);
  163. string bgPanelStyle = depth%2 == 0
  164. ? EditorStylesInternal.InspectorContentBgAlternate
  165. : EditorStylesInternal.InspectorContentBg;
  166. GUIPanel backgroundPanel = guiContentPanel.AddPanel(backgroundDepth);
  167. GUITexture inspectorContentBg = new GUITexture(null, bgPanelStyle);
  168. backgroundPanel.AddElement(inspectorContentBg);
  169. int currentIndex = 0;
  170. foreach (var field in fields)
  171. {
  172. if (!field.Flags.HasFlag(SerializableFieldAttributes.Inspectable))
  173. continue;
  174. string childPath = path + "/" + field.Name;
  175. InspectableField inspectable = CreateInspectable(parent, field.Name, childPath,
  176. currentIndex, depth + 1, new InspectableFieldLayout(guiContentLayout), field.GetProperty(), InspectableFieldStyle.Create(field));
  177. children.Add(inspectable);
  178. currentIndex += inspectable.GetNumLayoutElements();
  179. }
  180. }
  181. }
  182. else
  183. guiChildLayout = null;
  184. };
  185. if (state == State.None)
  186. {
  187. if (propertyValue != null)
  188. {
  189. BuildFilledGUI();
  190. state = State.Filled;
  191. }
  192. else
  193. {
  194. BuildEmptyGUI();
  195. state = State.Empty;
  196. }
  197. }
  198. else if (state == State.Empty)
  199. {
  200. if (propertyValue != null)
  201. {
  202. guiInternalTitleLayout.Destroy();
  203. guiCreateBtn = null;
  204. BuildFilledGUI();
  205. state = State.Filled;
  206. }
  207. }
  208. else if (state == State.Filled)
  209. {
  210. foreach (var child in children)
  211. child.Destroy();
  212. children.Clear();
  213. guiInternalTitleLayout.Destroy();
  214. guiCreateBtn = null;
  215. if (guiChildLayout != null)
  216. {
  217. guiChildLayout.Destroy();
  218. guiChildLayout = null;
  219. }
  220. if (propertyValue == null)
  221. {
  222. BuildEmptyGUI();
  223. state = State.Empty;
  224. }
  225. else
  226. {
  227. BuildFilledGUI();
  228. }
  229. }
  230. }
  231. /// <inheritdoc/>
  232. protected internal override void Initialize(int index)
  233. {
  234. guiLayout = layout.AddLayoutY(index);
  235. guiTitleLayout = guiLayout.AddLayoutX();
  236. propertyValue = property.GetValue<object>();
  237. BuildGUI(index);
  238. }
  239. /// <summary>
  240. /// Triggered when the user clicks on the expand/collapse toggle in the title bar.
  241. /// </summary>
  242. /// <param name="expanded">Determines whether the contents were expanded or collapsed.</param>
  243. private void OnFoldoutToggled(bool expanded)
  244. {
  245. parent.Persistent.SetBool(path + "_Expanded", expanded);
  246. isExpanded = expanded;
  247. forceUpdate = true;
  248. }
  249. /// <summary>
  250. /// Triggered when the user clicks on the create button on the title bar. Creates a brand new object with default
  251. /// values in the place of the current array.
  252. /// </summary>
  253. private void OnCreateButtonClicked()
  254. {
  255. if (createContextMenu == null)
  256. {
  257. if (instantiableTypes.Length > 0)
  258. property.SetValue(Activator.CreateInstance(instantiableTypes[0]));
  259. }
  260. else
  261. {
  262. Rect2I bounds = GUIUtility.CalculateBounds(guiCreateBtn, guiInternalTitleLayout);
  263. Vector2I position = new Vector2I(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
  264. createContextMenu.Open(position, guiInternalTitleLayout);
  265. }
  266. }
  267. /// <summary>
  268. /// Triggered when the user clicks on the clear button on the title bar. Deletes the current object and sets
  269. /// the reference to the object in the parent object to null. This is only relevant for objects of reference types.
  270. /// </summary>
  271. private void OnClearButtonClicked()
  272. {
  273. property.SetValue<object>(null);
  274. }
  275. /// <summary>
  276. /// Possible states object GUI can be in.
  277. /// </summary>
  278. private enum State
  279. {
  280. None,
  281. Empty,
  282. Filled
  283. }
  284. /// <summary>
  285. /// Returns a list of all types that can be created using the parameterless constructor and assigned to an object of
  286. /// type <paramref name="type"/>.
  287. /// </summary>
  288. /// <param name="type">Type to which the instantiable types need to be assignable to.</param>
  289. /// <returns>List of types that can be instantiated and assigned type <paramref name="type"/></returns>
  290. private static Type[] GetInstantiableTypes(Type type)
  291. {
  292. // Note: This could be cached
  293. List<Type> output = new List<Type>();
  294. Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
  295. foreach (var assembly in assemblies)
  296. {
  297. Type[] assemblyTypes = assembly.GetExportedTypes();
  298. foreach (var assemblyType in assemblyTypes)
  299. {
  300. if (assemblyType.IsAbstract)
  301. continue;
  302. if (!type.IsAssignableFrom(assemblyType))
  303. continue;
  304. var ctor = assemblyType.GetConstructor(Type.EmptyTypes);
  305. if (ctor == null)
  306. continue;
  307. output.Add(assemblyType);
  308. }
  309. }
  310. return output.ToArray();
  311. }
  312. }
  313. /** @} */
  314. }