InspectableObject.cs 15 KB

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