InspectableObject.cs 15 KB

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