InspectableObject.cs 13 KB

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