InspectableObject.cs 15 KB

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