InspectableObject.cs 15 KB

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